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