libmicrohttpd

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

callbackresponse.inc (18734B)


      1 All responses we have built so far were complete before they were
      2 queued.  @code{MHD_create_response_from_buffer()} needs the whole
      3 answer to be sitting in memory already, and
      4 @code{MHD_create_response_from_fd()} needs it to be a file that the
      5 operating system can read for us.  Neither fits an answer that is
      6 computed while it is being sent: the output of a long-running report,
      7 a log file that is filtered on the fly, the result of a database
      8 cursor, or simply a document that is far too large to be worth
      9 assembling in a buffer first.
     10 
     11 For those cases @emph{libmicrohttpd} lets the application hand over a
     12 callback instead of the data.  Whenever @emph{MHD} has room on the
     13 socket, it calls that function and asks for the next few bytes.  The
     14 application only ever needs one modest buffer, and the client starts
     15 receiving the answer long before the last byte has been produced.
     16 
     17 
     18 @heading Creating the response
     19 
     20 The response object is created with
     21 
     22 @verbatim
     23 struct MHD_Response *
     24 MHD_create_response_from_callback (uint64_t size,
     25                                    size_t block_size,
     26                                    MHD_ContentReaderCallback crc,
     27                                    void *crc_cls,
     28                                    MHD_ContentReaderFreeCallback crfc);
     29 @end verbatim
     30 @noindent
     31 
     32 The five arguments are:
     33 
     34 @table @code
     35 @item size
     36 The total length of the body in bytes, or the constant
     37 @code{MHD_SIZE_UNKNOWN} if the application does not know it in
     38 advance.  If a concrete number is given, @emph{MHD} announces it as
     39 @code{Content-Length} and expects the callback to deliver exactly that
     40 many bytes.
     41 
     42 @item block_size
     43 The buffer size @emph{MHD} should use when it queries the callback.
     44 The value must not be zero---@code{MHD_create_response_from_callback()}
     45 returns @code{NULL} otherwise.  @emph{MHD} allocates a buffer of that
     46 size together with the response object.  Note that this buffer is only
     47 used for responses of known size; when chunked transfer encoding is in
     48 use (see below) the data is collected in the connection's own memory
     49 pool instead, and @code{block_size} has no influence on how much
     50 @emph{MHD} asks for.  In either case the value is advisory: the
     51 callback must always look at the @code{max} argument it is passed and
     52 never write more than that.
     53 
     54 @item crc
     55 The content reader callback itself, described in the next section.
     56 
     57 @item crc_cls
     58 An arbitrary pointer that is passed back to @code{crc} on every
     59 invocation.  This is where the per-request state goes.
     60 
     61 @item crfc
     62 A callback that is invoked once, when the response object is
     63 destroyed, so that @code{crc_cls} can be released.  May be
     64 @code{NULL} if there is nothing to clean up.
     65 @end table
     66 
     67 
     68 @heading The content reader callback
     69 
     70 The callback has the following signature:
     71 
     72 @verbatim
     73 typedef ssize_t
     74 (*MHD_ContentReaderCallback) (void *cls,
     75                               uint64_t pos,
     76                               char *buf,
     77                               size_t max);
     78 @end verbatim
     79 @noindent
     80 
     81 @code{cls} is the @code{crc_cls} pointer given at creation time.
     82 @code{buf} points to the memory @emph{MHD} wants filled and
     83 @code{max} is the number of bytes that may be written there.
     84 
     85 The @code{pos} argument deserves a closer look, because its meaning
     86 depends on how the response is used.  For a response created from a
     87 file descriptor, @emph{MHD} uses it as a file offset and reads with
     88 @code{pread()}; that is what makes such a response object reusable for
     89 many connections.  For a response that is created fresh for each
     90 request---which is what we do here---@emph{MHD} guarantees that
     91 @code{pos} is simply the sum of all non-negative values the callback
     92 has returned so far.  In other words: for a stream, @code{pos} is a
     93 monotonically increasing count of the bytes already produced, and the
     94 callback will never be asked to go back.  A generator that has no use
     95 for random access can ignore @code{pos} completely.  Do note that the
     96 guarantee only holds as long as the response object is used for one
     97 request; if the same object is queued for several connections, the
     98 same content reader may be asked for the same data more than once, and
     99 sharing one mutable buffer between them would be wrong.
    100 
    101 The return value tells @emph{MHD} what happened:
    102 
    103 @table @asis
    104 @item a positive number
    105 That many bytes were written to @code{buf}.  Returning more than
    106 @code{max} is a fatal application error and makes @emph{MHD} close the
    107 connection.
    108 
    109 @item @code{MHD_CONTENT_READER_END_OF_STREAM}
    110 The body is complete.  With chunked encoding @emph{MHD} terminates the
    111 chunk sequence properly and appends any footers; without chunked
    112 encoding and an unknown size it simply closes the connection.  If a
    113 concrete @code{size} was announced, ending the stream early is not
    114 legal, and @emph{MHD} treats it essentially like an error---the client
    115 receives fewer bytes than the @code{Content-Length} promised.
    116 
    117 @item @code{MHD_CONTENT_READER_END_WITH_ERROR}
    118 Something went wrong while generating the data; see below.
    119 
    120 @item @code{0}
    121 No data is available @emph{right now}, but the stream is not over.
    122 @end table
    123 
    124 @noindent
    125 That last case is the dangerous one.  The header file states that
    126 returning zero is legal only when @emph{MHD} is @emph{not} using an
    127 internal sockets polling mode, and this is not a formality:
    128 @emph{MHD} does not diagnose the situation, it simply arranges for the
    129 next poll to time out immediately and calls the callback again.  A
    130 callback that returns zero while a request is stalled for a third of a
    131 second is called several million times in that period and pins a CPU
    132 core at 100%.  In external polling mode the effect is milder---the
    133 callback is retried whenever the application calls one of the
    134 @code{MHD_run*()} functions---but it is still a spin.  The proper
    135 answer for "no data yet" is to suspend the connection, which is
    136 covered further down.
    137 
    138 
    139 @heading Keeping state per request
    140 
    141 Because the callback is a plain C function, everything it needs to
    142 know has to travel through @code{crc_cls}.  The natural shape of a
    143 streaming handler is therefore: allocate a context on the heap,
    144 allocate its data buffer, create the response with that context as
    145 @code{crc_cls}, and let the free callback dispose of both.
    146 
    147 @verbatim
    148 struct ResponseContext
    149 {
    150   char *buf;            /* heap buffer, refilled again and again */
    151   size_t fill;          /* number of valid bytes in buf */
    152   size_t off;           /* number of bytes of buf given to MHD */
    153   unsigned int block;   /* number of blocks produced so far */
    154 };
    155 @end verbatim
    156 @noindent
    157 
    158 The two offsets are what make the buffer independent of @emph{MHD}'s
    159 appetite.  A block is generated once and may then be handed out over
    160 several invocations, because @code{max} can be smaller than what we
    161 have ready:
    162 
    163 @verbatim
    164 static ssize_t
    165 content_reader (void *cls, uint64_t pos, char *buf, size_t max)
    166 {
    167   struct ResponseContext *ctx = cls;
    168   size_t ready;
    169 
    170   (void) pos;
    171 
    172   if (ctx->off == ctx->fill)
    173     {
    174       /* Everything we had was passed on, produce the next block. */
    175       if (BLOCK_COUNT == ctx->block)
    176         return MHD_CONTENT_READER_END_OF_STREAM;
    177       generate_block (ctx);
    178     }
    179   ready = ctx->fill - ctx->off;
    180   if (ready > max)
    181     ready = max;
    182   memcpy (buf, &ctx->buf[ctx->off], ready);
    183   ctx->off += ready;
    184   return (ssize_t) ready;
    185 }
    186 @end verbatim
    187 @noindent
    188 
    189 @code{generate_block()} is the place where a real application would
    190 run its expensive computation, query, or network fetch.  The important
    191 property is that the same buffer is reused every time, so the memory
    192 the server needs does not grow with the size of the document.
    193 
    194 The handler assembles all of this and, from that moment on, hands
    195 ownership of the context to the response object:
    196 
    197 @verbatim
    198   ctx = malloc (sizeof (struct ResponseContext));
    199   if (NULL == ctx)
    200     return MHD_NO;
    201   ctx->buf = malloc (BUFFER_SIZE);
    202   if (NULL == ctx->buf)
    203     {
    204       free (ctx);
    205       return MHD_NO;
    206     }
    207   ctx->fill = 0;
    208   ctx->off = 0;
    209   ctx->block = 0;
    210 
    211   response = MHD_create_response_from_callback (MHD_SIZE_UNKNOWN,
    212                                                 IO_BLOCK_SIZE,
    213                                                 &content_reader,
    214                                                 ctx,
    215                                                 &free_context);
    216   if (NULL == response)
    217     {
    218       /* No response object exists, so nobody will call the free
    219          callback for us. */
    220       free_context (ctx);
    221       return MHD_NO;
    222     }
    223   ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
    224   MHD_destroy_response (response);
    225 @end verbatim
    226 @noindent
    227 
    228 Note the error path: as long as
    229 @code{MHD_create_response_from_callback()} has not returned a response,
    230 the free callback will never run and the application must clean up
    231 itself.
    232 
    233 
    234 @heading Releasing the state
    235 
    236 The free callback is trivial:
    237 
    238 @verbatim
    239 static void
    240 free_context (void *cls)
    241 {
    242   struct ResponseContext *ctx = cls;
    243 
    244   free (ctx->buf);
    245   free (ctx);
    246 }
    247 @end verbatim
    248 @noindent
    249 
    250 @emph{MHD} invokes it when the last reference to the response object
    251 goes away.  The call to @code{MHD_destroy_response()} in the handler
    252 does not trigger it, because queuing the response took a reference;
    253 the callback runs when the connection is finished with the response.
    254 That happens after a completed body, but equally after a client that
    255 closed the socket in the middle of the download, after a timeout, and
    256 when the daemon is stopped.  This is precisely what makes the free
    257 callback the right place for the cleanup: there is no other hook that
    258 covers all of these cases.
    259 
    260 
    261 @heading Unknown size and chunked encoding
    262 
    263 Passing @code{MHD_SIZE_UNKNOWN} as the size leaves @emph{MHD} with the
    264 problem of telling the client where the body ends.  For an HTTP/1.1
    265 client it solves it by switching to chunked transfer encoding: it adds
    266 a @code{Transfer-Encoding: chunked} header and frames every piece the
    267 callback returns as one chunk, terminating the body with a zero-length
    268 chunk when the callback reports the end of the stream.  Nothing has to
    269 be done for this; it is a consequence of the unknown size.
    270 
    271 @verbatim
    272 < HTTP/1.1 200 OK
    273 < Content-Type: text/plain
    274 < Transfer-Encoding: chunked
    275 @end verbatim
    276 @noindent
    277 
    278 An HTTP/1.0 client cannot be sent chunks.  In that case @emph{MHD}
    279 falls back to the only other framing the protocol offers and marks the
    280 connection as one that must be closed: the body is sent raw, without
    281 @code{Content-Length}, and its end is the end of the connection.  The
    282 data arrives intact, but the client has no way to distinguish a
    283 complete answer from one that was cut short.
    284 
    285 If the size @emph{is} known---and in the example program the URL
    286 @code{/sized} shows this variant---it should be announced, simply by
    287 passing the number instead of @code{MHD_SIZE_UNKNOWN}.  @emph{MHD}
    288 then emits a normal @code{Content-Length} header, no chunk framing is
    289 added, and the callback is queried with @code{max} limited by both
    290 @code{block_size} and the number of bytes still outstanding.  The
    291 callback must produce exactly the announced number of bytes.
    292 
    293 
    294 @heading Aborting a response
    295 
    296 Generating data can fail halfway through---the database connection
    297 drops, a file disappears, an allocation fails.  Since the response
    298 headers, and probably a good part of the body, have already been sent,
    299 there is no way to turn the answer into an error page any more.
    300 Returning @code{MHD_CONTENT_READER_END_WITH_ERROR} is the way to give
    301 up: @emph{MHD} logs the condition and closes the connection
    302 immediately, without writing the terminating chunk.
    303 
    304 What the client sees depends on the framing.  With chunked encoding it
    305 is an abnormally terminated chunk stream, and a well-behaved client
    306 reports it as such---@code{curl} for instance fails with "transfer
    307 closed with outstanding read data remaining" and a non-zero exit
    308 status.  With an announced @code{Content-Length} the client notices
    309 that the body is shorter than promised.  Only in the HTTP/1.0 case
    310 discussed above, where the end of the body is the end of the
    311 connection, is the failure indistinguishable from a normal ending;
    312 that is a property of the protocol and not something @emph{MHD} can
    313 repair.  The URL @code{/error} of the example program aborts the
    314 stream after a few blocks so that this can be observed.
    315 
    316 
    317 @heading When the data is not ready yet
    318 
    319 So far the generator could always produce the next block on the spot.
    320 If it cannot---because the data is coming from another thread, another
    321 process, or the network---then, as explained above, returning
    322 @code{0} in an internal polling mode turns the daemon into a busy
    323 loop.  The supported answer is to take the connection out of the event
    324 loop until the data has arrived, with the pair
    325 
    326 @verbatim
    327 void MHD_suspend_connection (struct MHD_Connection *connection);
    328 void MHD_resume_connection (struct MHD_Connection *connection);
    329 @end verbatim
    330 @noindent
    331 
    332 The daemon has to be started with the @code{MHD_ALLOW_SUSPEND_RESUME}
    333 flag; both functions call @code{MHD_PANIC()} and abort the process
    334 otherwise.  The flag implies @code{MHD_USE_ITC}, so that a resumed
    335 connection wakes the polling thread up instead of waiting for the next
    336 timeout.  Suspending is not available for daemons running with
    337 @code{MHD_USE_THREAD_PER_CONNECTION}, and the daemon must not be
    338 stopped while connections are still suspended.
    339 
    340 @code{MHD_suspend_connection()} may only be called from the access
    341 handler or from the content reader callback, which means the
    342 connection handle has to be stored in the context struct so that the
    343 callback can reach it.  The pattern is then:
    344 
    345 @verbatim
    346   if (! ctx->data_available)
    347     {
    348       MHD_suspend_connection (ctx->connection);
    349       return 0;
    350     }
    351 @end verbatim
    352 @noindent
    353 
    354 @code{MHD_resume_connection()}, in contrast, may be called from any
    355 thread and at any time.  In particular it is explicitly allowed to
    356 call it before the suspension has taken effect: the producer may
    357 already be done by the time the callback gets around to suspending.
    358 @emph{MHD} handles this by remembering the resume request and, when the
    359 suspension is finally processed, cancelling it instead of parking the
    360 connection, so the wakeup can never be lost.  This is what makes the
    361 "check, suspend, return 0" sequence above safe without a lock of its
    362 own.
    363 
    364 The difference is dramatic in practice.  A callback that stalls for
    365 three hundred milliseconds and returns @code{0} is entered several
    366 million times and burns a full core; the same callback suspending the
    367 connection is entered exactly once more and the daemon uses no
    368 measurable CPU time at all.
    369 
    370 Suspending brings requirements of its own---on who may call what from
    371 which thread, on how a worker thread wakes up a blocked event loop, and
    372 on who releases the shared state when a client disappears halfway
    373 through.  @ref{Answering from another thread} works all of that out on
    374 a complete program.
    375 
    376 
    377 @heading Trailers
    378 
    379 Chunked responses may carry trailers, that is header fields that are
    380 transmitted after the body.  They are added with
    381 
    382 @verbatim
    383 MHD_add_response_footer (response, "X-Checksum", "deadbeef");
    384 @end verbatim
    385 @noindent
    386 
    387 @emph{MHD} writes them out after the terminating zero-length chunk:
    388 
    389 @verbatim
    390 0
    391 X-Checksum: deadbeef
    392 
    393 @end verbatim
    394 @noindent
    395 
    396 Footers may still be added while the body is being generated---even
    397 from inside the content reader callback, immediately before returning
    398 @code{MHD_CONTENT_READER_END_OF_STREAM}---which is what makes them
    399 useful in the first place: a checksum or a row count over data that
    400 has only just been produced cannot be put into the headers, because
    401 those are long gone.  This is safe as long as the response object
    402 belongs to a single request, as it does in the pattern used here.
    403 @emph{MHD} does not generate a @code{Trailer} response header by
    404 itself; if the client should be told in advance which fields to
    405 expect, add it with @code{MHD_add_response_header()}.  Be aware that
    406 many clients discard trailers silently.
    407 
    408 
    409 @heading Example code
    410 
    411 The complete program is available as @code{callbackresponse.c}.  It
    412 serves a document of sixty-four blocks that are produced one at a time
    413 into a single heap buffer.  @code{GET /} streams it with
    414 @code{MHD_SIZE_UNKNOWN} and thus with chunked encoding,
    415 @code{GET /sized} streams the same bytes with a @code{Content-Length}
    416 announced up front, and @code{GET /error} aborts in the middle.
    417 
    418 
    419 @heading Remarks
    420 
    421 Calls into the content reader of one response object are serialized by
    422 @emph{MHD}, so a per-request context needs no locking of its own as
    423 long as no other thread touches it.  As soon as a producer thread is
    424 involved---the suspend/resume case---the shared fields do need
    425 protection.
    426 
    427 The chunk boundaries are not under the application's control and carry
    428 no meaning: a client may receive the bytes of one callback invocation
    429 spread over several chunks or, in other configurations, several
    430 invocations combined.  Chunked encoding is a transport detail, and any
    431 record structure the application needs must be part of the body
    432 itself.
    433 
    434 Finally, returning very small amounts of data per invocation is
    435 correct but wasteful, since every invocation may become its own chunk
    436 with its own framing overhead.  If the producer has more data ready, it
    437 should fill as much of @code{buf} as @code{max} permits.
    438 
    439 
    440 @heading Exercises
    441 
    442 @itemize @bullet
    443 
    444 @item
    445 Add a URL that reports how far the transfer has progressed by writing
    446 the value of @code{pos} into every line, and confirm with a slow
    447 client (@code{curl --limit-rate}) that it really is the number of
    448 bytes already sent, and not a block counter.
    449 
    450 @item
    451 Register a request completion callback with
    452 @code{MHD_OPTION_NOTIFY_COMPLETED} and print the termination code.
    453 Then download the document, interrupt the client in the middle, and
    454 watch in which order the completion callback and the content reader's
    455 free callback are invoked, and that the free callback runs in both
    456 cases.
    457 
    458 @item
    459 Turn the generator into an asynchronous one.  Start a thread that
    460 appends a line to a shared buffer once per second, keep the connection
    461 handle in the context struct, and suspend the connection whenever the
    462 buffer is empty.  Do not forget @code{MHD_ALLOW_SUSPEND_RESUME} when
    463 starting the daemon.  Then remove the call to
    464 @code{MHD_suspend_connection()}, leaving only the @code{return 0}, and
    465 compare the CPU usage of the server process.  A complete solution,
    466 together with the ownership rules that a shared buffer between a
    467 worker and the event loop needs, is the subject of
    468 @ref{Answering from another thread}.
    469 
    470 @item
    471 Compute a checksum over the generated document while it is being sent
    472 and append it as a trailer.  Watch it on the wire---most command line
    473 clients will not show it to you, so a raw @code{nc} or a small script
    474 speaking HTTP by hand is the easier tool here.
    475 
    476 @end itemize