libmicrohttpd

HTTP/1.x server C library (MHD 1.x, stable)
Log | Files | Refs | Submodules | README | LICENSE

responseheaders.inc (7242B)


      1 Now that we are able to inspect the incoming request in great detail,
      2 this chapter discusses the means to enrich the outgoing responses likewise.
      3 
      4 As you have learned in the @emph{Hello, Browser} chapter, some obligatory
      5 header fields are added and set automatically for simple responses by the library
      6 itself but if more advanced features are desired, additional fields have to be created.
      7 One of the possible fields is the content type field and an example will be developed around it.
      8 This will lead to an application capable of correctly serving different types of files.
      9 
     10 
     11 When we responded with HTML page packed in the static string previously, the client had no choice
     12 but guessing about how to handle the response, because the server had not told him.
     13 What if we had sent a picture or a sound file?  Would the message have been understood
     14 or merely been displayed as an endless stream of random characters in the browser?
     15 This is what the mime content types are for. The header of the response is extended
     16 by certain information about how the data is to be interpreted.
     17 
     18 To introduce the concept, a picture of the format @emph{PNG} will be sent to the client
     19 and labeled accordingly with @code{image/png}.
     20 Once again, we can base the new example on the @code{hellobrowser} program.
     21 
     22 @verbatim
     23 #define FILENAME "picture.png"
     24 #define MIMETYPE "image/png"
     25 
     26 static enum MHD_Result
     27 answer_to_connection (void *cls, struct MHD_Connection *connection,
     28 		      const char *url,
     29                       const char *method, const char *version,
     30 		      const char *upload_data,
     31               	      size_t *upload_data_size, void **req_cls)
     32 {
     33   struct MHD_Response *response;
     34 @end verbatim
     35 @noindent
     36 
     37 We want the program to open the file for reading and determine its size:
     38 @verbatim
     39   int fd;
     40   enum MHD_Result ret;
     41   struct stat sbuf;
     42 
     43   if (0 != strcmp (method, "GET"))
     44     return MHD_NO;
     45   if ( (-1 == (fd = open (FILENAME, O_RDONLY))) ||
     46        (0 != fstat (fd, &sbuf)) )
     47     {
     48      /* error accessing file */
     49       /* ... (see below) */
     50     }
     51  /* ... (see below) */
     52 @end verbatim
     53 @noindent
     54 
     55 When dealing with files, there is a lot that could go wrong on the
     56 server side and if so, the client should be informed with @code{MHD_HTTP_INTERNAL_SERVER_ERROR}.
     57 
     58 @verbatim
     59       /* error accessing file */
     60       if (fd != -1) close (fd);
     61       const char *errorstr =
     62         "<html><body>An internal server error has occurred!\
     63                               </body></html>";
     64       response =
     65 	MHD_create_response_from_buffer_static (strlen (errorstr),
     66 				                errorstr);
     67       if (NULL != response)
     68         {
     69           ret =
     70             MHD_queue_response (connection, MHD_HTTP_INTERNAL_SERVER_ERROR,
     71                                 response);
     72           MHD_destroy_response (response);
     73 
     74           return ret;
     75         }
     76       else
     77         return MHD_NO;
     78 @end verbatim
     79 @noindent
     80 
     81 Note that we nevertheless have to create a response object even for sending a simple error code.
     82 Otherwise, the connection would just be closed without comment, leaving the client curious about
     83 what has happened.
     84 
     85 But in the case of success a response will be constructed directly from the file descriptor:
     86 
     87 @verbatim
     88      /* error accessing file */
     89      /* ... (see above) */
     90     }
     91 
     92   response =
     93     MHD_create_response_from_fd_at_offset64 ((uint64_t) sbuf.st_size, fd, 0);
     94   MHD_add_response_header (response, "Content-Type", MIMETYPE);
     95 @end verbatim
     96 @noindent
     97 
     98 Note that the response object will take care of closing the file descriptor for us.
     99 
    100 Up to this point, there was little new. The actual novelty is that we enhance the header with the
    101 meta data about the content. Aware of the field's name we want to add, it is as easy as that:
    102 @verbatim
    103 MHD_add_response_header(response, "Content-Type", MIMETYPE);
    104 @end verbatim
    105 @noindent
    106 We do not have to append a colon expected by the protocol behind the first
    107 field---@emph{GNU libmicrohttpd} will take care of this.
    108 
    109 The function finishes with the well-known lines
    110 @verbatim
    111   ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
    112   MHD_destroy_response (response);
    113   return ret;
    114 }
    115 @end verbatim
    116 @noindent
    117 
    118 The complete program @code{responseheaders.c} is in the @code{examples} section as usual.
    119 Find a @emph{PNG} file you like and save it to the directory the example is run from under the name
    120 @code{picture.png}. You should find the image displayed on your browser if everything worked well.
    121 
    122 @heading Remarks
    123 The include file of the @emph{MHD} library comes with the header types mentioned in @emph{RFC 9110}
    124 already defined as macros. Thus, we could have written @code{MHD_HTTP_HEADER_CONTENT_TYPE} instead
    125 of @code{"Content-Type"} as well. However, one is not limited to these standard headers and could
    126 add custom response headers without violating the protocol. Whether, and how, the client would react
    127 to these custom header is up to the receiver. Likewise, the client is allowed to send custom request
    128 headers to the server as well, opening up yet more possibilities how client and server could
    129 communicate with each other.
    130 
    131 The method of creating the response from a file on disk only works for static content.
    132 Serving dynamically created responses will be a topic of a future chapter.
    133 
    134 @heading Exercises
    135 @itemize @bullet
    136 
    137 @item
    138 Remember that the original program was written under a few assumptions---a static response
    139 using a local file being one of them. In order to simulate a very large or hard to reach file that cannot be provided
    140 instantly, postpone the queuing in the callback with the @code{sleep} function for 30 seconds
    141 @emph{if} the file @code{/big.png} is requested (but deliver the same as above). A request for
    142 @code{/picture.png} should provide just the same but without any artificial delays.
    143 
    144 Now start two instances of your browser (or even use two machines) and see how the second client
    145 is put on hold while the first waits for his request on the slow file to be fulfilled.
    146 
    147 Finally, change the sourcecode to add @code{MHD_USE_THREAD_PER_CONNECTION} to the daemon's flags
    148 (this flag must be combined with @code{MHD_USE_INTERNAL_POLLING_THREAD}) and try again.
    149 
    150 
    151 @item
    152 Did you succeed in implementing the clock exercise yet? This time, let the server save the
    153 program's start time @code{t} and implement a response simulating a countdown that reaches 0 at
    154 @code{t+60}. Returning a message saying on which point the countdown is, the response should
    155 ultimately be to reply "Done" if the program has been running long enough,
    156 
    157 An unofficial, but widely understood, response header line is @code{Refresh: DELAY; url=URL} with
    158 the uppercase words substituted to tell the client it should request the given resource after
    159 the given delay again. Improve your program in that the browser (any modern browser should work)
    160 automatically reconnects and asks for the status again every 5 seconds or so. The URL would have
    161 to be composed so that it begins with "http://", followed by the @emph{URI} the server is reachable
    162 from the client's point of view.
    163 
    164 Maybe you want also to visualize the countdown as a status bar by creating a
    165 @code{<table>} consisting of one row and @code{n} columns whose fields contain small images of either
    166 a red or a green light.
    167 
    168 @end itemize