responses.inc (44319B)
1 @cindex response 2 3 @noindent 4 Response handling by MHD is asynchronous with respect to the 5 application execution flow. Instances of type @code{struct MHD_Response} 6 are not tightly associated with a request or a daemon; 7 they are managed with reference counting. 8 9 @deftp {C Struct} MHD_Response 10 Handle for a response to be returned to an HTTP client. 11 A response includes the HTTP status code, HTTP headers, 12 a body and possibly HTTP footers. 13 @end deftp 14 15 @cindex action 16 17 In the simplest case we allocate a new @code{struct MHD_Response} 18 for each request, use it to create an action and it is (automatically) 19 destroyed: 20 21 @example 22 @verbatiminclude examples/simple_reply_fragment.c 23 @end example 24 25 The above code will cause MHD to @code{close()} a connection in 26 case the memory allocation failed (and log nothing), but unless 27 an application really needs to handle even such an error more 28 gracefully, the above code is already fine even in terms of 29 error handling and leaks no memory (assuming the action is 30 returned to MHD). 31 32 However, MHD also allows responses to be reused and the same response 33 structure to be used multiple times. This is explained in more detail 34 under @ref{MHD_R_OPTION_REUSABLE} in the section on 35 @ref{libmicrohttpd-response-performance,,Response options for 36 performance optimization}. 37 38 @menu 39 * libmicrohttpd-response enqueue:: Returning a response. 40 * libmicrohttpd-response create:: Creating responses. 41 * libmicrohttpd-response headers:: Adding headers to a response. 42 * libmicrohttpd2-response options:: Setting response options. 43 * libmicrohttpd-upgrade:: Creating a response for protocol upgrades. 44 @end menu 45 46 @c ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 47 48 @c ------------------------------------------------------------ 49 @node libmicrohttpd-response enqueue 50 @section Enqueuing a response 51 52 As we have discussed in the previous chapters and shown in the example 53 above, handling a request requires applications to return a 54 @code{struct MHD_Action} that tells MHD how to continue. The most 55 common way to create an action is from a @code{struct MHD_Response} 56 via @code{MHD_action_from_response}. 57 58 @anchor{MHD_action_from_response} 59 @deftypefun {struct MHD_Action *} MHD_action_from_response (struct MHD_Request *request, struct MHD_Response *response) 60 61 This instructs MHD to transmit the given @var{response} to 62 the client. The @var{request} must match the request handle 63 given to the call that is returning the action. 64 65 @table @var 66 @item request 67 the request to create an action for; 68 69 @item response 70 the response to convert. If this argument is NULL then this 71 function will behave equivalent to @code{MHD_action_abort_connection()}. 72 @end table 73 74 Returns an action on success. The action returned must be returned to 75 MHD, otherwise there @emph{may} be a memory leak. This function 76 checks that no other action was already created for the given 77 @var{request} and returns @code{NULL} on API usage errors or possibly 78 in out-of-memory situations. The application @emph{may} try to create 79 a different action in this case, but most likely should just give MHD 80 the @code{NULL} value for the action to close the connection. 81 82 @end deftypefun 83 84 Note that calling @code{MHD_action_from_response()} will typically 85 consume a response and cause its resources to be released 86 by MHD once the response has been sent. Thus, after converting 87 a response to an action applications do not have to call 88 @code{MHD_response_destroy()} @emph{unless} they used 89 @ref{MHD_R_OPTION_REUSABLE} as explained below. 90 91 92 @node libmicrohttpd-response create 93 @section Creating responses 94 95 @cindex lifetime 96 @subsection Destroying responses 97 98 There are various ways for applications to create a @code{struct 99 MHD_Response}. Almost all of these functions will have to allocate 100 memory and may fail, returning @code{NULL} to indicate that the 101 response generation failed. To avoid leaking memory, any response that 102 was successfull created must @emph{either} be converted into an action 103 via @code{MHD_action_from_response()} or explicitly destroyed via 104 @code{MHD_response_destroy()}. 105 106 @anchor{MHD_response_destroy} 107 @deftypefun void MHD_response_destroy (struct MHD_Response *response) 108 Destroys a response and associated resources (decrement the 109 reference counter). Note that MHD may keep some of the resources 110 around if the response is still in the queue for some clients, so the 111 memory may not necessarily be freed immediately. 112 113 @table @var 114 @item response 115 the response to destroy. 116 @end table 117 @end deftypefun 118 119 @subsection HTTP status codes 120 @cindex status code 121 122 When creating a response, applications must always specify the HTTP 123 status code that should be returned with the response. MHD provides 124 @code{enum MHD_HTTP_StatusCode} with all supported HTTP status 125 codes. Using other numeric values is possible but not advised: in such 126 cases MHD will be unable to provide the human-readable status code 127 description and clients are likely to be unhappy about the use of 128 non-standard codes. 129 130 @anchor{MHD_HTTP_StatusCode} 131 @deftp {Enumeration} MHD_HTTP_StatusCode 132 133 Represents canonical HTTP status codes. 134 135 @table @code 136 @include manual/http-status-texi.gen 137 @end table 138 @end deftp 139 140 141 @subsection Responses from memory buffers 142 143 You can use any of the following functions (or convenience macros) 144 to create responses from static data in memory: 145 146 @anchor{MHD_response_from_buffer} 147 @deftypefun {struct MHD_Response *} MHD_response_from_buffer (enum MHD_HTTP_StatusCode sc, size_t buffer_size, const char *buffer, MHD_FreeCallback free_cb, void *free_cb_cls) 148 149 Create a response object with a callback that can be used to free resources after the response has been sent to the client. 150 151 @table @var 152 @item sc 153 HTTP status code for the response; 154 155 @item buffer_size 156 size of the data portion of the response, must be zero if @var{buffer} 157 is @code{NULL}; 158 159 @item buffer 160 the body to return, must contain at least @var{buffer_size} bytes of data, 161 can be @code{NULL} if @var{buffer_size} is zero; 162 the application must ensure that data in @var{buffer} remains valid 163 at least until the response was sent; 164 165 @item free_cb 166 function to call to release application data associated with 167 the response (usually @var{buffer}) after transmitting the 168 response is complete. For example, if @var{buffer} is the 169 result of @code{mmap()} the callback may invoke 170 @code{munmap()}. Similarly, if @var{buffer} was part of an 171 allocation on the heap, the callback may simply call 172 @code{free()}. You may pass @code{NULL} to indicate that 173 no cleanup function is needed; however, in that case it 174 might be simpler to use @code{MHD_response_from_buffer_static()}. 175 176 @item free_cb_cls 177 additional argument to pass to the @var{free_cb}. 178 A common value to pass is @var{buffer}. 179 @end table 180 181 Return @code{NULL} on error (i.e. invalid arguments, out of memory). 182 @end deftypefun 183 184 @anchor{MHD_FreeCallback} 185 @deftypefn {Function Pointer} void (*MHD_FreeCallback) (void *cls) 186 187 Functions of this type are invoked by MHD whenever it wants to give 188 the application a chance to free resources. 189 190 @table @var 191 @item cls 192 custom value provided by the application together with the 193 actual function pointer; should identify the resources to be released 194 @end table 195 @end deftypefn 196 197 When releasing resources is unnecessary, applications can instead 198 use the simplified @code{MHD_response_from_buffer_static()} API 199 that simply omits the @var{free_cb} and @var{free_cb_cls} arguments. 200 201 @anchor{MHD_response_from_buffer_static} 202 @deftypefun {struct MHD_Response *} MHD_response_from_buffer_static (enum MHD_HTTP_StatusCode sc, size_t buffer_size, const char *buffer) 203 Create a response object without the need to free resources after the response has been sent to the client. 204 205 @table @var 206 @item sc 207 HTTP status code for the response. 208 209 @item size 210 size of the data portion of the response; 211 212 @item buffer 213 the body to return, must contain at least @var{size} bytes of data; 214 the application must ensure that data in @var{buffer} remains valid 215 at least until the response was sent; can be NULL if @var{size} is zero, 216 but in this case it might be simpler to use @code{MHD_response_from_empty()}. 217 @end table 218 219 Return @code{NULL} on error (i.e. invalid arguments, out of memory). 220 @end deftypefun 221 222 @anchor{MHD_response_from_buffer_copy} 223 @deftypefun {struct MHD_Response *} MHD_response_from_buffer_copy (enum MHD_HTTP_StatusCode sc, size_t buffer_size, const char *buffer) 224 225 Create a response object from an ephemeral @var{buffer}. The data 226 in the @var{buffer} will be copied into internal storage of MHD. 227 228 @table @var 229 @item sc 230 HTTP status code for the response. 231 232 @item buffer_size 233 size of the data portion of the response; must be zero if @var{buffer} 234 is @code{NULL}; 235 236 @item buffer 237 the body to return, must contain at least @var{buffer_size} bytes of data; 238 can be @code{NULL} if @var{buffer_size} is zero; 239 the @var{buffer} can become invalid immediately after the 240 call to @code{MHD_response_from_buffer_copy()} returns as MHD 241 will make a copy of the data contained in it. 242 @end table 243 244 Return @code{NULL} on error (i.e. invalid arguments, out of memory). 245 @end deftypefun 246 247 @anchor{MHD_response_from_empty} 248 @deftypefun {struct MHD_Response *} MHD_response_from_empty (enum MHD_HTTP_StatusCode sc) 249 Create an response with an empty body. 250 251 @table @var 252 @item sc 253 HTTP status code for the response. A common value would be @code{MHD_HTTP_NO_CONTENT}. 254 @end table 255 256 Return @code{NULL} on error (i.e. invalid arguments, out of memory). 257 @end deftypefun 258 259 Finally, in rare cases, the response data may not be available in a 260 continuous block in memory and it might be more efficient to not copy 261 the data into a continous area just for the network transfer (or 262 encryption). In this case, applications can initialize an array of 263 @code{struct MHD_IoVec} data structures and use 264 @code{MHD_response_from_iovec()} to point MHD to the various fragments 265 of the body and enable (if supported) the kernel (or NIC) to assemble 266 the final response dynamcially from the fragments in 267 memory.@footnote{See the @code{writev()} POSIX call for an example of 268 the type of scatter input operationg system interface that MHD might 269 use to implement this.} 270 271 @cindex iovec 272 @cindex scatter write 273 @cindex writev 274 @anchor{MHD_response_from_iovec} 275 @deftypefun {struct MHD_Response *} MHD_response_from_iovec (enum MHD_HTTP_StatusCode sc, unsigned int iov_count, const struct MHD_IoVec *iov, MHD_FreeCallback free_cb, void *free_cb_cls) 276 277 Create a response object from an array of memory buffers. 278 @table @var 279 @item sc 280 HTTP status code for the response. 281 282 @item iov_count 283 the number of elements in @var{iov}; must be zero if @var{iov} 284 is @code{NULL}; 285 286 @item iov 287 the array for response data buffers of length @var{iov_count}; can be 288 @code{NULL} if @var{iov_count} is zero; an internal copy of the @var{iov} 289 will be made; however, note that the data pointed to by the @var{iov} is 290 @strong{not} copied and must be preserved unchanged at the given locations 291 until the response is no longer in use and the @var{free_cb} is called; 292 293 @item free_cb 294 the callback to call to free resources associated with @var{iov}; 295 You may pass @code{NULL} to indicate that no cleanup function is needed. 296 297 @item free_cb_cls 298 additional argument to pass to the @var{free_cb}. 299 @end table 300 301 Return @code{NULL} on error (i.e. invalid arguments, out of memory). 302 @end deftypefun 303 304 @anchor{MHD_IoVec} 305 @deftp {C Struct} MHD_IoVec 306 Input/output vector type. Informations MHD about a fragment of 307 data in memory for assembly as part of an HTTP response body. 308 @table @var 309 @item @code{const void *} iov_base 310 Pointer to the memory region for I/O. 311 @item @code{size_t} iov_len 312 The size (in bytes) of the memory region pointed to by @var{iov_base}. 313 @end table 314 @end deftp 315 316 317 @subsection Responses from file descriptors 318 @cindex sendfile 319 320 @anchor{MHD_response_from_fd} 321 @deftypefun {struct MHD_Response *} MHD_response_from_fd (enum MHD_HTTP_StatusCode sc, int fd, uint_fast64_t offset, uint_fast64_t size) 322 Create a response object based on a file descriptor @var{fd} from 323 which the body is supposed to be read. 324 325 @table @var 326 @item sc 327 HTTP status code for the response. 328 329 @item fd 330 file descriptor referring to a file on disk with the 331 data; MHD will @code{close()} the file descriptor when 332 the response is destroyed; @var{fd} should be in @emph{blocking} mode; 333 @var{fd} must be an actual file descriptor (not a pipe or socket) 334 since MHD might use @code{sendfile()} or @code{seek()} on it; 335 336 @item offset 337 offset to start reading from in the file; 338 readings file beyond 2 GiB may be not supported by some 339 operationg systems or MHD builds. 340 @xref{MHD_LIB_INFO_FIXED_HAS_LARGE_FILE}. 341 342 @item size 343 size size of the data portion of the response; 344 sizes larger than 2 GiB may be not supported by 345 some operating systems or MHD builds. 346 @xref{MHD_LIB_INFO_FIXED_HAS_LARGE_FILE}. 347 @end table 348 349 Returns @code{NULL} on error (i.e. invalid arguments, out of memory). 350 The @var{fd} is closed on error. 351 @end deftypefun 352 353 @cindex splice 354 @anchor{MHD_response_from_pipe} 355 @deftypefun {struct MHD_Response *} MHD_response_from_pipe (enum MHD_HTTP_StatusCode sc, int fd) 356 357 Create a response object where the response body is created by reading from 358 the provided pipe. 359 @c FIXME: will it also work for sockets? Is this using splice()? Clarify! 360 361 @table @var 362 @item sc 363 HTTP status code for the response. 364 365 @item fd 366 file descriptor of the read-end of a pipe; will be 367 closed when response is destroyed. 368 The descriptor should be in blocking-IO mode. 369 @end table 370 371 Returns @code{NULL} on error (i.e. out of memory). 372 @c FIXME: closes fd on error? 373 @end deftypefun 374 375 376 @subsection Responses from dynamic generators 377 378 This API is useful for applications that dynamically create the 379 response body, possibly even with significant delays between 380 chunks. 381 382 @c FIXME: this comment seems wrong, see above for from_pipe()! 383 @c This is also the only API that applications can use to 384 @c return responses for which they do not know the length up-front. 385 386 @cindex dynamic responses 387 @cindex generation 388 389 @anchor{MHD_response_from_callback} 390 @deftypefun {struct MHD_Response *} MHD_response_from_callback (enum MHD_HTTP_StatusCode sc, uint_fast64_t size, MHD_DynamicContentCreator dyn_cont, void *dyn_cont_cls, MHD_FreeCallback dyn_cont_fc) 391 392 Create a response object with a body that will be yielded over 393 time by the @code{dyn_cont} callback. 394 395 @table @var 396 @item sc 397 HTTP status code for the response. 398 399 @item size 400 size of the body of the response, applications should pass 401 @code{MHD_SIZE_UNKNOWN} if the size of the body is not yet known; 402 403 @item dyn_cont 404 callback that MHD will use to obtain the response body 405 406 @item dyn_cont_cls 407 extra argument that MHD will pass to @var{dyn_cont} and 408 @var{dyn_cont_fc} 409 410 @item dyn_cont_fc 411 callback that MHD will call to allow the application to 412 free resources associated with @var{dyn_cont_cls}. 413 @end table 414 415 Return @code{NULL} on error (i.e. invalid arguments, out of memory). 416 @end deftypefun 417 418 The interesting work for dynamic response generation happens in the 419 dynamic content creation callback, which must be a function of 420 type @code{MHD_DynamicContentCreator}. 421 422 @anchor{MHD_DynamicContentCreator} 423 @deftypefn {Function Pointer} {struct MHD_DynamicContentCreatorAction *} (*MHD_DynamicContentCreator) (void *dyn_cont_cls, struct MHD_DynamicContentCreatorContext *ctx, uint_fast64_t pos, void *buf, size_t max) 424 425 @table @var 426 @item dyn_cont_cls 427 closure argument that was associated with the callback 428 429 @item ctx 430 the context to produce the action to return; 431 the pointer is only valid until the callback returns; 432 equivalent to the @var{request} argument given to 433 functions of type @code{MHD_RequestCallback}; 434 435 @item pos 436 position in the datastream to access; 437 note that if a @code{struct MHD_Response} is re-used, 438 it is possible for the same dynamic content creator to 439 be queried multiple times for the same data; 440 however, if a @code{struct MHD_Response} is not re-used, 441 libmicrohttpd guarantees that @var{pos} will be 442 the sum of all data sizes previously yielded by this callback 443 444 @item buf 445 buffer where the application may write data that should be 446 included in the body at offset @var{pos}; @var{buf} has 447 @var{max} bytes available; 448 449 @item max 450 maximum number of bytes the application may copy to @var{buf}; 451 if the size of the content of the response is known then the 452 size of the buffer is never larger than amount of data left 453 @end table 454 455 Most importantly, the callback must also return a 456 @code{struct MHD_DynamicContentCreatorAction} which determines 457 the next step in creating the body. Applications may 458 return @code{NULL} in which case response generation will 459 be aborted and MHD will @code{close()} the connection. 460 @end deftypefn 461 462 @cindex dynamic content creator action 463 464 @anchor{MHD_DynamicContentCreatorAction} 465 @deftp {C Struct} MHD_DynamicContentCreatorAction 466 Special type of action that must be returned by a 467 @code{MHD_DynamicContentCreator}. 468 @end deftp 469 470 Various possibilities exist for applications to create 471 an @code{struct MHD_DynamicContentCreatorAction} (DCC action). Note 472 that at most one @code{struct MHD_DynamicContentCreatorAction} 473 can be created per @var{ctx}. 474 475 We begin with DCC actions that end the process of 476 dynamic response generation: 477 478 @anchor{MHD_DCC_action_abort} 479 @deftypefun {struct MHD_DynamicContentCreatorAction *} MHD_DCC_action_abort (struct MHD_DynamicContentCreatorContext *ctx) 480 481 Aborts handling the request by closing the connection. This 482 is actually simply a macro that is equivalent to just @code{NULL}, 483 except that it also suggests to the compiler that it it should 484 not emit a warning for not using @var{ctx}. 485 486 @end deftypefun 487 488 @anchor{MHD_DCC_action_finish} 489 @deftypefun {struct MHD_DynamicContentCreatorAction *} MHD_DCC_action_finish (struct MHD_DynamicContentCreatorContext *ctx) 490 491 Create a "finished" action that signals MHD that the dynamic content creation 492 is finished. Note that this will cause MHD to @code{close()} the connection 493 if the amount of data yielded by the content creation logic is less than 494 the @var{size} promised to @code{MHD_response_from_callback()}. 495 496 @table @var 497 @item ctx 498 context that was given to the @code{MHD_DynamicContentCreator} for 499 which a @code{struct MHD_DynamicContentCreatorAction} should be generated. 500 @end table 501 502 @code{NULL} is returned in case of any error. 503 @end deftypefun 504 505 506 HTTP has not only headers, but also the lesser-known concept of 507 @emph{footers}. Applications can specify footers (for example, 508 to append a checksum after dynamic content creation) using 509 @code{MHD_DCC_action_finish_with_footer()}. 510 511 @anchor{MHD_DCC_action_finish_with_footer} 512 @deftypefun {struct MHD_DynamicContentCreatorAction *} MHD_DCC_action_finish_with_footer (struct MHD_DynamicContentCreatorContext *ctx, size_t num_footers, const struct MHD_NameValueCStr *footers) 513 514 Create a "finished" action that signals MHD that the dynamic content creation 515 is finished. Note that this will cause MHD to @code{close()} the connection 516 if the amount of data yielded by the content creation logic is less than 517 the @var{size} promised to @code{MHD_response_from_callback()}. 518 519 @table @var 520 @item ctx 521 context that was given to the @code{MHD_DynamicContentCreator} for 522 which a @code{struct MHD_DynamicContentCreatorAction} should be generated; 523 524 @item num_footers 525 length of the @var{footers} array; 526 527 @item footers 528 array of @var{num_footers} HTTP footers to return. 529 @end table 530 531 @code{NULL} is returned in case of any error. 532 @end deftypefun 533 534 The @var{footers} are provided as key-value pairs of 0-terminated C strings 535 in a @code{struct MHD_NameValueCStr}. In this context, both members must 536 not be @code{NULL}. 537 538 @anchor{MHD_NameValueCStr} 539 @deftp {C Struct} MHD_NameValueCStr name value 540 Name with value pair as C strings. 541 @table @var 542 @item @code{const char *} name 543 The name or key of the field. Must never be @code{NULL}. 544 @item @code{const char *} value 545 The value to be returned under the name or key. 546 In some cases, @var{value} is allowed to be absent, 547 which is indicated by a @code{NULL} pointer. 548 @end table 549 @end deftp 550 551 @cindex long-polling 552 553 Applications may not want to finish generating a response, but also 554 may not (yet) have more data to return to the client. In this case, 555 applications must @emph{suspend} response generation. This is done 556 using @code{MHD_DCC_action_suspend()}. 557 558 @anchor{MHD_DCC_action_suspend} 559 @deftypefun {struct MHD_DynamicContentCreatorAction *} MHD_DCC_action_suspend (struct MHD_DynamicContentCreatorContext *ctx) 560 561 Creates a DCC action that suspends response generation. The connection 562 is not closed! MHD merely waits for the application to resume response 563 generation via a call to @code{MHD_request_resume()}. This is 564 especially useful for long-polling where response generation is not 565 computationally bound. This is common in cases where client and server 566 need to wait (possibly for an extended period of time) on some 567 external event to happen before the server can generate a response. 568 569 @table @var 570 @item ctx 571 context that was given to the @code{MHD_DynamicContentCreator} for 572 which a @code{struct MHD_DynamicContentCreatorAction} should be generated; 573 @end table 574 575 @code{NULL} is returned in case of any error. 576 @end deftypefun 577 578 After dynamic content creation was suspended with 579 @code{MHD_DCC_action_suspend()}, applications @strong{must} 580 (eventually) call @code{MHD_request_resume()} to continue 581 processing the client's request. 582 583 Finally, we consider DCC actions that can be used to signal MHD data to be 584 returned in the MHD body. 585 586 @anchor{MHD_DCC_action_continue} 587 @deftypefun {struct MHD_DynamicContentCreatorAction *} MHD_DCC_action_continue (struct MHD_DynamicContentCreatorContext *ctx, size_t data_size) 588 589 Creates an action that indicates that a chunk of @var{data_size} bytes 590 was provided in the @var{buf} that MHD provided to the 591 @code{MHD_DynamicContentCreator} callback 592 and that MHD should continue to call the content generator for more 593 (as soon as MHD has more buffer space available). 594 595 @table @var 596 @item ctx 597 context that was given to the @code{MHD_DynamicContentCreator} for 598 which a @code{struct MHD_DynamicContentCreatorAction} should be generated; 599 600 @item data_size 601 number of bytes that were written by the application into @var{buf}; 602 must be non-zero; 603 @end table 604 605 @code{NULL} is returned in case of any error. 606 @end deftypefun 607 608 A small variation of the above API can be used to associate 609 a chunk-extension (see RFC 9112, 7.1) with the chunk: 610 611 @deftypefun {struct MHD_DynamicContentCreatorAction *} MHD_DCC_action_continue_ce (struct MHD_DynamicContentCreatorContext *ctx, size_t data_size, const char *chunk_ext) 612 613 Creates an action that indicates that a chunk of @var{data_size} bytes 614 was provided in the @var{buf} that MHD provided to the 615 @code{MHD_DynamicContentCreator} callback 616 and that MHD should continue to call the content generator for more 617 (as soon as MHD has more buffer space available). 618 Furthermore, the chunk of data that was returned is optionally 619 associated with a chunk-extension (@var{ce}) that MHD should 620 include in the transmission if possible. 621 622 @table @var 623 @item ctx 624 context that was given to the @code{MHD_DynamicContentCreator} for 625 which a @code{struct MHD_DynamicContentCreatorAction} should be generated; 626 627 @item data_size 628 number of bytes that were written by the application into @var{buf}; 629 must be non-zero; 630 631 @item chunk_ext 632 optional pointer to a chunk extension string; 633 can be @code{NULL} to not use chunk extension, 634 ignored if chunked encoding is not used by MHD 635 (say because the client is using HTTP/1.0 and 636 the connection is only used for a single request). 637 @end table 638 639 @code{NULL} is returned in case of any error. 640 @end deftypefun 641 642 While writing new data that an application may dynamically generate 643 directly into MHD's @var{buf} is usually ideal, copying existing 644 data over into the buffer provided by MHD may not be ideal. 645 Applications can also instruct MHD to include data from 646 locations in the application's memory, and in fact it is 647 possible to @emph{mix} both strategies using 648 @code{MHD_DCC_action_continue_zc()}: 649 650 @anchor{MHD_DCC_action_continue_zc} 651 @deftypefun {struct MHD_DynamicContentCreatorAction *} MHD_DCC_action_continue_zc (struct MHD_DynamicContentCreatorContext *ctx, size_t data_size, const struct MHD_DynContentZCIoVec *iov_data, const char *chunk_ext) 652 653 Yields a chunk of body data to MHD with (optional) chunk-extension. 654 The data is provided in the MHD buffer and/or in the zero-copy @var{iov_data}. 655 656 If data is provided both in the MHD buffer and @var{ivo_data} then 657 data in the MHD buffer is sent first, followed by the @var{iov_data}. 658 The total size of the data in the buffer and in @var{iov_data} @strong{must} 659 be non-zero. 660 661 @table @var 662 @item ctx 663 context that was given to the @code{MHD_DynamicContentCreator} for 664 which a @code{struct MHD_DynamicContentCreatorAction} should be generated; 665 666 @item data_size 667 the amount of the data placed to the provided MHD buffer (@var{buf}), 668 cannot be larger than provided buffer size, 669 must be non-zero if @var{iov_data} is @code{NULL} or has no data; 670 671 @item iov_data 672 optional pointer to a vector of data fragments to send, 673 must not be NULL and have non-zero bytes of data if @var{data_size} 674 is zero; 675 676 @item chunk_ext 677 optional pointer to a chunk extension string; 678 can be @code{NULL} to not use chunk extension, 679 ignored if chunked encoding is not used by MHD 680 (say because the client is using HTTP/1.0 and 681 the connection is only used for a single request). 682 @end table 683 684 It is an error if the total response body size is known and the 685 amount of data yielded in total by the dynamic content creation logic 686 exceeds that amount. In this case, this function will fail and 687 return @code{NULL}. 688 689 @end deftypefun 690 691 The @code{struct MHD_DynContentZCIoVec} adds an application 692 cleanup callback to an array of @code{struct MHD_IoVec}s: 693 694 @cindex iovec 695 @cindex writev 696 @cindex scatter write 697 698 @anchor{MHD_DynContentZCIoVec} 699 @deftp {C Struct} MHD_DynContentZCIoVec 700 Structure to pass various memory buffers to MHD together with 701 a callback for cleaning up after MHD is done using the data. 702 @table @var 703 @item @code{size_t} iov_count 704 The length of the @var{iov} array; 705 706 @item @code{const struct MHD_ioVec *} iov 707 Pointer to an array of length @var{iov_count} identifying data chunks 708 to return as part of the body; 709 710 @item @code{MHD_FreeCallback} iov_fcb 711 Function to call to free resources associated with @var{iov}. 712 Can be @code{NULL} if releasing these resources is not necessary 713 after finishing the response generation; 714 715 @item @code{void *} iov_fcb_cls 716 Parameter to pass to @var{iov_fcb}. 717 @end table 718 719 @end deftp 720 721 722 @node libmicrohttpd-response headers 723 @section Adding headers to a response 724 @cindex header 725 @cindex Connection 726 @cindex Date 727 @cindex Content-Length 728 @cindex Transfer-Encoding 729 730 After creating a response, but @emph{before} using it to create an 731 @code{struct MHD_Action}, applications may add custom HTTP headers 732 to a response. Note that MHD will automatically set some common 733 HTTP headers, in particular ``Content-Length'', ``Transfer-Encoding'', 734 ``Date`` and ``Connection''. 735 736 @code{MHD_response_add_header()} prevents applications from setting a 737 ``Transfer-Encoding'' header to values other than ``identity'' or 738 ``chunked'' as other transfer encodings are not supported by MHD. Note 739 that usually MHD will pick the correct transfer encoding 740 automatically; however, applications can use the header to force a 741 particular behavior. 742 743 @code{MHD_response_add_header()} prevents applications from setting a 744 ``Connection'' header to values other than ``close'' or 745 ``keep-alive''. Note that usually MHD will pick a sane value 746 automatically; however, applications can use the header to force a 747 particular behavior. 748 749 @code{MHD_response_add_header()} also prevents applications from setting a 750 ``Content-Length'' header unless special options are set for the 751 response (see @ref{libmicrohttpd2-response options,,response options}) as 752 MHD will automatically set a correct ``Content-Length'' header if it 753 is possible and allowed by the HTTP protocol. 754 755 @anchor{MHD_response_add_header} 756 @deftypefun {enum MHD_StatusCode} MHD_response_add_header (struct MHD_Response *response, const char *name, const char *value) 757 758 Add a header line to the response. 759 760 @table @var 761 @item response 762 which response to add a header for, @code{NULL} is tolerated; 763 764 @item name 765 the name of the header to add; 766 an internal copy of the string will be made; 767 must not contain newlines, carriage returns or 768 tabulator characters; 769 770 @item value 771 the value of the header to add; 772 an internal copy of the string will be made; 773 must not contain newlines, carriage returns or 774 tabulator characters. 775 @end table 776 777 On success @code{MHD_SC_OK} is returned. 778 @end deftypefun 779 780 @cindex HTTP2 781 @cindex predefined HTTP header 782 @cindex header 783 784 HTTP2 introduced @emph{predefined} (standard) HTTP headers. For such 785 headers, it is (slightly) more efficient to set the headers using 786 values from the @code{enum MHD_PredefinedHeader} instead of specifying 787 the name as a string.@footnote{The main reason being that HTTP2 can 788 encode these headers using a number instead of a string, and by having 789 the application directly provide the numeric value MHD does not have 790 to map the string to the number.} 791 792 @deftypefun {enum MHD_StatusCode} MHD_response_add_predef_header (struct MHD_Response *response, enum MHD_PredefinedHeader stk, const char *content) 793 Adds a header line to the response. 794 795 @table @var 796 @item response 797 which response to add a header for, @code{NULL} is tolerated; 798 799 @item stk 800 code of the predefined header; 801 802 @item content 803 the value of the header to add 804 an internal copy of the string will be made. 805 @end table 806 807 Notice that the content must not contain newlines, carriage returns or 808 tabulator characters. On success @code{MHD_SC_OK} is returned. 809 @end deftypefun 810 811 @anchor{MHD_PredefinedHeader} 812 @deftp {Enumeration} MHD_PredefinedHeader 813 814 Predefined list of canonical HTTP headers, useful for HTTP2 815 header packing (HPACK). 816 817 @c FIXME: the table seems rather incomplete (also in libmicrohttpd2.h), 818 @c and we should probably generate it via GANA (like HTTP status codes) 819 @table @code 820 @item MHD_PREDEF_ACCEPT_CHARSET 821 15: ``Accept-Charset`` 822 @item MHD_PREDEF_ACCEPT_LANGUAGE 823 17: ``Accept-Language`` 824 @end table 825 @end deftp 826 827 @node libmicrohttpd2-response options 828 @section Setting response options 829 @cindex option 830 831 This section is about setting response options. In principle, setting 832 response options works like setting other options in 833 MHD. @xref{libmicrohttpd2-doptions,,Configuring your HTTP daemon}. 834 835 MHD response options are represented using a @code{struct 836 MHD_ResponseOptionAndValue}. However, applications should never be 837 concerned with the internals of this data structure, and only use the 838 provided API functions and macros explained in this chapter to 839 construct these options. 840 841 MHD offers three main ways to set options for a @code{struct MHD_Response}: 842 843 @itemize 844 @item @code{MHD_response_set_options()} sets an array of options, 845 @item @code{MHD_response_set_option()} sets an individual option, and 846 @item @code{MHD_RESPONSE_SET_OPTIONS()} sets a list of options. 847 @end itemize 848 849 All three approaches can be combined for the same response 850 to set various options. We will now look at each of them. 851 852 @code{MHD_response_set_options()} is useful if the application needs 853 complex code to first initialize a set of options, or if it has a 854 static data buffer with all of the options (say in ROM). It is also 855 the function use to implement the other styles. 856 857 @deftypefun {struct MHD_StatusCode} MHD_response_set_options (struct MHD_Response *response, const struct MHD_ResponseOptionAndValue *options, size_t options_max_num) 858 859 @table @var 860 @item response 861 the response to configure 862 863 @item options 864 array of options to set, either @code{MHD_D_OPTION_TERIMINATE()}-terminated or 865 limited by @var{options_max_num} (whatever comes first). 866 867 @item options_max_num 868 maximum number of options to process from the @var{options} array, 869 or @code{MHD_OPTIONS_ARRAY_MAX_SIZE} to process all options from 870 @var{options} until the @code{MHD_D_OPTION_TERMINATE()}-terminator. 871 872 @end table 873 874 Returns @code{MHD_SC_OK} on success, otherwise the error code of 875 the first option that could not be set. 876 @end deftypefun 877 878 To set only a single option, MHD defines a simple convenience API with 879 @code{MHD_response_set_option()}. This is useful if there is only one 880 option to be set, or if error handling for that specific option is 881 somehow special (like not failing when setting this particular option 882 failed). 883 884 @deftypefun {struct MHD_StatusCode} MHD_response_set_option (struct MHD_Response *response, const struct MHD_ResponseOptionAndValue *option) 885 886 @table @var 887 @item response 888 the response to configure 889 890 @item option 891 the option to set 892 893 @end table 894 895 Returns @code{MHD_SC_OK} on success, otherwise the error code from 896 trying to set the @var{option}. 897 @end deftypefun 898 899 900 An easy way to set a bunch of options without having to worry 901 about explicitly allocating an array or checking each return 902 value is to use @code{MHD_RESPONSE_SET_OPTIONS()}. 903 904 @anchor{MHD_RESPONSE_SET_OPTIONS} 905 @deftypefun {struct MHD_StatusCode} MHD_RESPONSE_SET_OPTIONS (struct MHD_Response *response, ...) 906 907 @table @var 908 @item response 909 the response to configure 910 911 @item ... 912 variable-length list of @code{MHD_ResponseOptionAndValue} options 913 to set; does @emph{not} need to be terminated via 914 @code{MHD_D_OPTION_TERMINATE()} as such a terminator is added 915 automatically. 916 917 @end table 918 919 Returns @code{MHD_SC_OK} on success, otherwise the error code of 920 the first option that could not be set. 921 @end deftypefun 922 923 The remaining sections of this section discuss the various 924 response options available to applications today. 925 926 @include manual/response_options.inc 927 928 929 @node libmicrohttpd-upgrade 930 @section Creating a response for protocol upgrades 931 @cindex WebSockets 932 @cindex HTTP Upgrade 933 @cindex HTTP2 934 @cindex RFC2817 935 936 With RFC 2817 a mechanism to switch protocols within HTTP was 937 introduced. Here, a client sends a request with a ``Connection: 938 Upgrade'' header. The server responds with a ``101 Switching 939 Protocols'' response header, after which the two parties begin to 940 speak a different (non-HTTP) protocol over the TCP connection. 941 942 This mechanism is used for upgrading HTTP 1.1 connections to HTTP2 or 943 HTTPS, as well as for implementing WebSockets. Which protocol 944 upgrade is performed is negotiated between server and client in 945 additional headers, in particular the ``Upgrade'' header. 946 947 MHD supports switching protocols using this mechanism 948 by returning a special @code{MHD_action_upgrade()} action 949 from the @ref{MHD_RequestCallback,,@code{MHD_RequestCallback}}. 950 951 Note that support for upgrading connections is an @emph{optional} 952 feature that could be left out especially in embedded builds. Use 953 @ref{MHD_LIB_INFO_FIXED_HAS_UPGRADE,,@code{MHD_LIB_INFO_FIXED_HAS_UPGRADE}} 954 to check if the library supports it. Furthermore, connection upgrades 955 can be disabled for a daemon using 956 @code{MHD_D_OPTION_DISALLOW_UPGRADE()} for some potential minor 957 performance benefit. Thus, you may want to make sure the feature is 958 actually properly enabled. 959 960 @anchor{MHD_action_upgrade} 961 @deftypefun {const struct MHD_Action *} MHD_action_upgrade (struct MHD_Request *request, const char *upgrade_hdr_value, MHD_UpgradeHandler upgrade_handler, void *upgrade_handler_cls, size_t num_headers, const struct MHD_NameValueCStr *headers) 962 963 Create a action object that can be used for 101 Upgrade 964 responses, for example to implement WebSockets. After sending the 965 response, control over the data stream is given to the callback (which 966 can then, for example, start some bi-directional communication). 967 The callback will @emph{only} be called after the response header 968 was successfully passed to the OS; if there are communication errors 969 before, the usual MHD connection error handling code will be performed. 970 971 When creating this type of response, the "Connection: Upgrade" 972 header will be set automatically for you. 973 974 975 @table @var 976 @item request 977 the request to create action for; 978 979 @item upgrade_hdr_value 980 the value of the (mandatory) "Upgrade:" header, must not be @code{NULL}; 981 982 @item upgrade_handler 983 function to call with the "upgraded" socket; 984 985 @item upgrade_handler_cls 986 closure for @var{upgrade_handler}; 987 988 @item num_headers 989 number of elements in the @var{headers} array, 990 must be zero if @var{headers} is @code{NULL}; 991 992 @item headers 993 optional pointer to an array of additional HTTP headers to return in 994 the response (the strings will be copied and do not need to be 995 preserved by the application after this function returns); 996 can be @code{NULL} if @var{num_headers} is zero; 997 998 @end table 999 1000 @code{NULL} is returned on error (i.e. invalid arguments, out of memory). 1001 @end deftypefun 1002 1003 The @var{upgrade_handler} argument has the following type: 1004 1005 @anchor{MHD_UpgradeHandler} 1006 @deftypefn {Function Pointer} void (*MHD_UpgradeHandler) (void *cls, struct MHD_Request *request, struct MHD_UpgradeHandle *urh) 1007 1008 Applications must implement functions of this type which be called 1009 once MHD has transmitted the header of the response to the connection 1010 that is being upgraded. At this point, the application is expected to 1011 take over the connection represented by @var{urh} and use @var{urh} to speak 1012 the non-HTTP protocol to which the connection was upgraded with the client. 1013 1014 The application must call @code{MHD_upgraded_send()}, 1015 @code{MHD_upgraded_recv()} and eventually @code{MHD_upgraded_close()} 1016 to interact with the client. @code{MHD_upgraded_close()} must be 1017 called before destroying the daemon. 1018 1019 "Upgraded" connection will not time out, but are still counted for daemon 1020 global connections limit and for per-IP limit (if set). 1021 1022 Except when in "thread-per-connection" mode, implementations of this 1023 function should never block (as it will be called from within the main 1024 event loop). 1025 1026 @table @var 1027 @item cls 1028 matches the @code{upgrade_handler_cls} that was given to @code{MHD_action_upgrade()}; 1029 1030 @item request 1031 identifies the request of the connection that is being upgraded; 1032 1033 @item urh 1034 handle to interact with the client. 1035 @c FIXME: C comment talks about MHD_upgrade_operation(), seems outdated! 1036 @end table 1037 1038 @end deftypefn 1039 1040 @c FIXME: Evgeny: this is correct, right? 1041 When upgrading a connection, applications using an external event loop may 1042 use the connection @ref{libmicrohttpd-request-status-info,,request 1043 introspection API} to obtain the socket underlying the HTTP request 1044 and then add that socket to their own event loop to decide when to 1045 call @code{MHD_upgraded_recv()} and @code{MHD_upgraded_send()}. 1046 1047 @anchor{MHD_upgraded_recv} 1048 @deftypefun {enum MHD_StatusCode} MHD_upgraded_recv (struct MHD_UpgradeHandle *urh, size_t recv_buf_size, void *recv_buf, size_t *received_size, uint_fast64_t max_wait_millisec) 1049 1050 Receive data on the HTTP-Upgraded connection. 1051 1052 The function will return if one of the following happens: 1053 @itemize 1054 @item Any amount of data has been received, 1055 @item The specified timeout was reached, or 1056 @item a network error occured. 1057 @end itemize 1058 1059 If @var{recv_buf_size} is zero, no data is received. 1060 For a valid @var{urh}, the function returns @code{MHD_SC_OK} immediately 1061 and stores zero in the variable pointed to by @var{received_size}. 1062 1063 @table @var 1064 @item urh 1065 identifies the HTTP-upgraded connection handle 1066 1067 @item recv_buf_size 1068 size of the @var{recv_buf}, must be zero if @var{recv_buf} is @code{NULL} 1069 1070 @item recv_buf 1071 application buffer where MHD should place received data, can be @code{NULL} 1072 if @var{recv_buf_size} is zero 1073 1074 @item received_size 1075 pointer where to return the number of bytes received 1076 @c FIXME: header lacks [out], English not so good 1077 1078 @item max_wait_millisec 1079 the maximum wait time for the data, non-blocking operation if set to zero, 1080 wait indefinitely if set larger or equal to @code{MHD_WAIT_INDEFINITELY}; 1081 the function may return earlier if waiting is interrupted for some reason. 1082 @end table 1083 Returns: 1084 @table @code 1085 @item MHD_SC_OK 1086 if any data was received (check the @var{received_size}), 1087 remote shut down send side (indicated by @var{received_size} 1088 set to zero while @var{recv_buf_size} is not zero) or 1089 @var{recv_buf_size} is zero; 1090 1091 @item MHD_SC_UPGRADED_NET_TIMEOUT 1092 if no data was received but and timeout was reached; 1093 1094 @item MHD_SC_UPGRADED_NET_CONN_CLOSED 1095 if the network connection has been closed, 1096 @c FIXME: should the application still call MHD_upgraded_close()? If so, we should say so explicitly! 1097 1098 @item MHD_SC_UPGRADED_NET_CONN_BROKEN 1099 if a broken network connection has been detected, 1100 1101 @item MHD_SC_UPGRADED_TLS_ERROR 1102 if a TLS error occured (only possible with TLS connections), 1103 1104 @item MHD_SC_UPGRADED_NET_HARD_ERROR 1105 if any other network or sockets unrecoverable error occured, 1106 1107 @item MHD_SC_UPGRADED_HANDLE_INVALID 1108 if @var{urh} is invalid, 1109 1110 @item MHD_SC_UPGRADED_WAITING_NOT_SUPPORTED 1111 if timed wait is not supported by this MHD build or platform 1112 @end table 1113 @end deftypefun 1114 1115 @cindex upgraded handle 1116 1117 After the upgrade, the application must use the 1118 @code{struct MHD_UpgradedHandle} to continue the 1119 interaction with the client. 1120 1121 @anchor{MHD_UpgradedHandle} 1122 @deftp {C Struct} MHD_UpgradedHandle 1123 Handle for response that has been "upgraded" (say to a WebSocket). 1124 @end deftp 1125 1126 Using the handle, the application primarily has 1127 three ways to interact with the client: 1128 @itemize 1129 @item send data, 1130 @item receive data, or 1131 @item close the connection. 1132 @end itemize 1133 1134 @anchor{MHD_upgraded_send} 1135 @deftypefun {enum MHD_StatusCode} MHD_upgraded_send (struct MHD_UpgradeHandle *urh, size_t send_buf_size, const void *send_buf, size_t *sent_size, uint_fast64_t max_wait_millisec, enum MHD_Bool more_data_to_come) 1136 1137 Sends data on an HTTP-Upgraded connection. 1138 1139 The function will return if one of the following happens: 1140 @itemize 1141 @item All provided data has been sent, 1142 @c FIXME: Truly *all*? So always blocking? Not ideal! Discuss! 1143 @item The timeout was reached, or 1144 @item a network error occurs 1145 @end itemize 1146 1147 If @var{send_buf_size} is zero, no data is sent or pushed to the network. 1148 For a valid @var{urh}, the function returns @code{MHD_SC_OK} immediately 1149 and stores zero in the variable pointed to by @var{sent_size}. 1150 1151 1152 @table @var 1153 @item urh 1154 identifies the upgraded connection to transmit data on 1155 1156 @item send_buf_size 1157 the number of bytes of data in the @var{send_buf}, must be zero if 1158 @var{send_buf} is @code{NULL} 1159 1160 @item send_buf 1161 the buffer with the data to send, can be @code{NULL} if 1162 @var{send_buf_size} is zero 1163 1164 @item sent_size 1165 the pointer where MHD will return the number of bytes of data actually sent 1166 1167 @item max_wait_millisec 1168 the maximum wait time for the data, non-blocking operation if set to zero, 1169 wait indefinitely if larger or equal to @code{MHD_WAIT_INDEFINITELY} 1170 1171 @item more_data_to_come 1172 should be set to @code{MHD_YES} if the provided data in the 1173 @var{send_buf} is part of a larger data package, like an incomplete 1174 message or part of a data stream (and not the final part), and thus 1175 more data is expected to be sent soon over the same connection; set to 1176 @code{MHD_NO} if the data in the @var{send_buf} is the complete 1177 message or the final part of the message (or file) and it should be 1178 pushed to the network (and to the client) as soon as possible; 1179 basically controls network buffering (see Nagle's algorithm and 1180 TCP PUSH). 1181 @end table 1182 1183 Returns: 1184 @table @code 1185 @item MHD_SC_OK 1186 if any data was sent or @var{send_buf_size} is zero 1187 (check the @var{sent_size}); 1188 1189 @item MHD_SC_UPGRADED_NET_TIMEOUT 1190 if no data was sent and the timeout was reached; 1191 1192 @item MHD_SC_UPGRADED_NET_CONN_CLOSED 1193 if the network connection has been closed, 1194 @c FIXME: should the application still call MHD_upgraded_close()? If so, we should say so explicitly! 1195 1196 @item MHD_SC_UPGRADED_NET_CONN_BROKEN 1197 if a broken network connection has been detected, 1198 1199 @item MHD_SC_UPGRADED_TLS_ERROR 1200 if a TLS error occured (only possible with TLS connections), 1201 1202 @item MHD_SC_UPGRADED_NET_HARD_ERROR 1203 if any other network or sockets unrecoverable error occured, 1204 1205 @item MHD_SC_UPGRADED_HANDLE_INVALID 1206 if @var{urh} is invalid, 1207 1208 @item MHD_SC_UPGRADED_WAITING_NOT_SUPPORTED 1209 if timed wait is not supported by this MHD build or platform 1210 @end table 1211 1212 @end deftypefun 1213 1214 1215 @anchor{MHD_upgraded_close} 1216 @deftypefun {enum MHD_StatusCode} MHD_upgraded_close (struct MHD_UpgradeHandle *urh) 1217 Close HTTP-Upgraded connection handle. 1218 1219 The handle cannot be used after successful return from this function. 1220 1221 The function cannot fail if called correctly (the daemon is not destroyed 1222 and the upgraded connection has not been closed previously). 1223 1224 @table @var 1225 @item urh 1226 identifies the upgraded connection to close 1227 @end table 1228 Returns @code{MHD_SC_OK} on success, otherwise an error code. 1229 @end deftypefun