libmicrohttpd.texi (133273B)
1 \input texinfo 2 @setfilename libmicrohttpd.info 3 @documentencoding UTF-8 4 @include version.texi 5 @settitle The GNU libmicrohttpd Reference Manual 6 @c Unify all the indices into concept index. 7 @syncodeindex vr cp 8 @syncodeindex ky cp 9 @syncodeindex pg cp 10 @copying 11 This manual is for GNU libmicrohttpd 12 (version @value{VERSION}, @value{UPDATED}), a library for embedding 13 an HTTP(S) server into C applications. 14 15 Copyright @copyright{} 2007--2019 Christian Grothoff 16 17 @quotation 18 Permission is granted to copy, distribute and/or modify this document 19 under the terms of the GNU Free Documentation License, Version 1.3 20 or any later version published by the Free Software Foundation; 21 with no Invariant Sections, no Front-Cover Texts, and no Back-Cover 22 Texts. A copy of the license is included in the section entitled "GNU 23 Free Documentation License". 24 @end quotation 25 @end copying 26 27 @dircategory Software libraries 28 @direntry 29 * libmicrohttpd: (libmicrohttpd). Embedded HTTP server library. 30 @end direntry 31 32 @c 33 @c Titlepage 34 @c 35 @titlepage 36 @title The GNU libmicrohttpd Reference Manual 37 @subtitle Version @value{VERSION} 38 @subtitle @value{UPDATED} 39 @author Marco Maggi (@email{marco.maggi-ipsu@@poste.it}) 40 @author Christian Grothoff (@email{christian@@grothoff.org}) 41 @page 42 @vskip 0pt plus 1filll 43 @insertcopying 44 @end titlepage 45 46 @summarycontents 47 @contents 48 49 @c ------------------------------------------------------------ 50 @ifnottex 51 @node Top 52 @top The GNU libmicrohttpd Library 53 @insertcopying 54 @end ifnottex 55 56 @menu 57 * microhttpd-intro:: Introduction. 58 * microhttpd-const:: Constants. 59 * microhttpd-struct:: Structures type definition. 60 * microhttpd-cb:: Callback functions definition. 61 * microhttpd-init:: Starting and stopping the server. 62 * microhttpd-inspect:: Implementing external @code{select}. 63 * microhttpd-requests:: Handling requests. 64 * microhttpd-responses:: Building responses to requests. 65 * microhttpd-flow:: Flow control. 66 * microhttpd-dauth:: Utilizing Authentication. 67 * microhttpd-post:: Adding a @code{POST} processor. 68 * microhttpd-info:: Obtaining and modifying status information. 69 * microhttpd-util:: Utilities. 70 71 Appendices 72 73 * GNU-LGPL:: The GNU Lesser General Public License says how you 74 can copy and share almost all of `libmicrohttpd'. 75 * eCos License:: The eCos License says how you can copy and share some parts of `libmicrohttpd'. 76 * GNU-GPL:: The GNU General Public License (with eCos extension) says how you can copy and share some parts of `libmicrohttpd'. 77 * GNU-FDL:: The GNU Free Documentation License says how you 78 can copy and share the documentation of `libmicrohttpd'. 79 80 Indices 81 82 * Concept Index:: Index of concepts and programs. 83 * Function and Data Index:: Index of functions, variables and data types. 84 * Type Index:: Index of data types. 85 @end menu 86 87 @c ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 88 89 @c ------------------------------------------------------------ 90 @node microhttpd-intro 91 @chapter Introduction 92 93 94 @noindent 95 All symbols defined in the public API start with @code{MHD_}. MHD 96 is a small HTTP daemon library. As such, it does not have any API 97 for logging errors (you can only enable or disable logging to stderr). 98 Also, it may not support all of the HTTP features directly, where 99 applicable, portions of HTTP may have to be handled by clients of the 100 library. 101 102 The library is supposed to handle everything that it must handle 103 (because the API would not allow clients to do this), such as basic 104 connection management. However, detailed interpretations of headers, 105 such as range requests, are left to the main application. In 106 particular, if an application developer wants to support range 107 requests, he needs to explicitly indicate support in responses and 108 also explicitly parse the range header and generate a response (for 109 example, using the @code{MHD_create_response_from_fd_at_offset} call 110 to serve ranges from a file). MHD does understands headers that 111 control connection management (specifically, @code{Connection: close} 112 and @code{Expect: 100 continue} are understood and handled 113 automatically). @code{Connection: upgrade} is supported by passing 114 control over the socket (or something that behaves like the real 115 socket in the case of TLS) to the application (after sending the 116 desired HTTP response header). 117 118 MHD largely ignores the semantics of the different HTTP methods, 119 so clients are left to handle those. One exception is that MHD does 120 understand @code{HEAD} and will only send the headers of the response 121 and not the body, even if the client supplied a body. (In fact, 122 clients do need to construct a response with the correct length, even 123 for @code{HEAD} request.) 124 125 MHD understands @code{POST} data and is able to decode certain 126 formats (at the moment only @code{application/x-www-form-urlencoded} 127 and @code{multipart/form-data}) using the post processor API. The 128 data stream of a POST is also provided directly to the main 129 application, so unsupported encodings could still be processed, just 130 not conveniently by MHD. 131 132 The header file defines various constants used by the HTTP protocol. 133 This does not mean that MHD actually interprets all of these values. 134 The provided constants are exported as a convenience for users of the 135 library. MHD does not verify that transmitted HTTP headers are 136 part of the standard specification; users of the library are free to 137 define their own extensions of the HTTP standard and use those with 138 MHD. 139 140 All functions are guaranteed to be completely reentrant and 141 thread-safe. MHD checks for allocation failures and tries to 142 recover gracefully (for example, by closing the connection). 143 Additionally, clients can specify resource limits on the overall 144 number of connections, number of connections per IP address and memory 145 used per connection to avoid resource exhaustion. 146 147 @section Scope 148 149 MHD is currently used in a wide range of implementations. 150 Examples based on reports we've received from developers include: 151 @itemize 152 @item Embedded HTTP server on a cortex M3 (128 KB code space) 153 @item Large-scale multimedia server (reportedly serving at the 154 simulator limit of 7.5 GB/s) 155 @item Administrative console (via HTTP/HTTPS) for network appliances 156 @c If you have other interesting examples, please let us know 157 @end itemize 158 159 @section Thread modes and event loops 160 @cindex poll 161 @cindex epoll 162 @cindex select 163 164 MHD supports four basic thread modes and up to three event loop 165 styles. 166 167 The four basic thread modes are external sockets polling (MHD creates 168 no threads, event loop is fully managed by the application), internal 169 polling (MHD creates one thread for all connections), polling in 170 thread pool (MHD creates a thread pool which is used to process all 171 connections) and thread-per-connection (MHD creates one thread for 172 listen sockets and then one thread per accepted connection). 173 174 These thread modes are then combined with the evet loop styles 175 (polling function type). MHD support select, poll and epoll. select 176 is available on all platforms, epoll and poll may not be available on 177 some platforms. Note that it is possible to combine MHD using epoll 178 with an external select-based event loop. 179 180 The default (if no other option is passed) is ``external select''. 181 The highest performance can typically be obtained with a thread pool 182 using @code{epoll}. Apache Benchmark (ab) was used to compare the 183 performance of @code{select} and @code{epoll} when using a thread pool 184 and a large number of connections. @ref{fig:performance} shows the 185 resulting plot from the @code{benchmark.c} example, which measures the 186 latency between an incoming request and the completion of the 187 transmission of the response. In this setting, the @code{epoll} 188 thread pool with four threads was able to handle more than 45,000 189 connections per second on loopback (with Apache Benchmark running 190 three processes on the same machine). 191 @cindex performance 192 193 194 @float Figure,fig:performance 195 @image{libmicrohttpd_performance_data,400pt,300pt,Data,.png} 196 @caption{Performance measurements for select vs. epoll (with thread-pool).} 197 @end float 198 199 200 Not all combinations of thread modes and event loop styles are 201 supported. This is partially to keep the API simple, and partially 202 because some combinations simply make no sense as others are strictly 203 superior. Note that the choice of style depends first of all on the 204 application logic, and then on the performance requirements. 205 Applications that perform a blocking operation while handling a 206 request within the callbacks from MHD must use a thread per 207 connection. This is typically rather costly. Applications that do 208 not support threads or that must run on embedded devices without 209 thread-support must use the external mode. Using @code{epoll} is only 210 supported on some platform, thus portable applications must at least 211 have a fallback option available. @ref{tbl:supported} lists the sane 212 combinations. 213 214 @float Table,tbl:supported 215 @multitable {@b{thread-per-connection}} {@b{select}} {@b{poll}} {@b{epoll}} 216 @item @tab @b{select} @tab @b{poll} @tab @b{epoll} 217 @item @b{external} @tab yes @tab no @tab yes 218 @item @b{internal} @tab yes @tab yes @tab yes 219 @item @b{thread pool} @tab yes @tab yes @tab yes 220 @item @b{thread-per-connection} @tab yes @tab yes @tab no 221 @end multitable 222 @caption{Supported combinations of event styles and thread modes.} 223 @end float 224 225 226 @section Compiling GNU libmicrohttpd 227 @cindex compilation 228 @cindex embedded systems 229 @cindex portability 230 231 MHD uses the standard GNU system where the usual build process 232 involves running 233 @verbatim 234 $ ./configure 235 $ make 236 $ make install 237 @end verbatim 238 239 MHD supports various options to be given to configure to tailor the 240 binary to a specific situation. Note that some of these options will 241 remove portions of the MHD code that are required for 242 binary-compatibility. They should only be used on embedded systems 243 with tight resource constraints and no concerns about library 244 versioning. Standard distributions including MHD are expected to 245 always ship with all features enabled, otherwise unexpected 246 incompatibilities can arise! 247 248 Here is a list of MHD-specific options that can be given to configure 249 (canonical configure options such as ``--prefix'' are also supported, for a 250 full list of options run ``./configure --help''): 251 252 @table @code 253 @item ``--disable-curl'' 254 disable running testcases using libcurl 255 256 @item ``--disable-largefile'' 257 disable support for 64-bit files 258 259 @item ``--disable-messages'' 260 disable logging of error messages (smaller binary size, not so much fun for debugging) 261 262 @item ``--disable-https'' 263 disable HTTPS support, even if GNUtls is found; this option must be used if eCOS license is desired as an option (in all cases the resulting binary falls under a GNU LGPL-only license) 264 265 @item ``--disable-postprocessor'' 266 do not include the post processor API (results in binary incompatibility) 267 268 @item ``--disable-dauth'' 269 do not include the authentication APIs (results in binary incompatibility) 270 271 @item ``--disable-httpupgrade'' 272 do not build code for HTTP ``Upgrade'' (smaller binary size, binary incompatible library) 273 274 @item ``--disable-epoll'' 275 do not include epoll support, even if it supported (minimally smaller binary size, good for portability testing) 276 277 @item ``--enable-coverage'' 278 set flags for analysis of code-coverage with gcc/gcov (results in slow, large binaries) 279 280 @item ``--with-threads=posix,w32,none,auto'' 281 sets threading library to use. With use ``none'' to not support threads. In this case, MHD will only support the ``external'' threading modes and not perform any locking of data structures! Use @code{MHD_is_feature_supported(MHD_FEATURE_THREADS)} to test if threads are available. Default is ``auto''. 282 283 @item ``--with-gcrypt=PATH'' 284 specifies path to libgcrypt installation 285 286 @item ``--with-gnutls=PATH'' 287 specifies path to libgnutls installation 288 289 @end table 290 291 To cross-compile MHD for Android, install the Android NDK and use: 292 @verbatim 293 ./configure --target=arm-linux-androideabi --host=arm-linux-androideabi --disable-doc --disable-examples 294 make 295 @end verbatim 296 297 Similar build commands should work for cross-compilation to other platforms. 298 Note that you may have to first cross-compile GnuTLS to get MHD with TLS support. 299 300 301 @section Validity of pointers 302 303 MHD will give applications access to its internal data structures 304 via pointers via arguments and return values from its API. This 305 creates the question as to how long those pointers are assured to 306 stay valid. 307 308 Most MHD data structures are associated with the connection of an 309 HTTP client. Thus, pointers associated with a connection are 310 typically valid until the connection is finished, at which point 311 MHD will call the @code{MHD_RequestCompletedCallback} if one is 312 registered. Applications that have such a callback registered 313 may assume that keys and values from the 314 @code{MHD_KeyValueIterator}, return values from 315 @code{MHD_lookup_connection_value} and the @code{url}, 316 @code{method} and @code{version} arguments to the 317 @code{MHD_AccessHandlerCallback} will remain valid until the 318 respective @code{MHD_RequestCompletedCallback} is invoked. 319 320 In contrast, the @code{upload_data} argument of 321 @code{MHD_RequestCompletedCallback} as well as all pointers 322 from the @code{MHD_PostDataIterator} are only valid for the 323 duration of the callback. 324 325 Pointers returned from @code{MHD_get_response_header} are 326 valid as long as the response itself is valid. 327 328 329 @section Including the microhttpd.h header 330 @cindex portability 331 @cindex microhttpd.h 332 333 Ideally, before including "microhttpd.h" you should add the necessary 334 includes to define the @code{va_list}, @code{size_t}, @code{ssize_t}, 335 @code{intptr_t}, @code{off_t}, @code{uint8_t}, @code{uint16_t}, 336 @code{int32_t}, @code{uint32_t}, @code{int64_t}, @code{uint64_t}, 337 @code{fd_set}, @code{socklen_t} and @code{struct sockaddr} data types. 338 Which specific headers are needed may depend on your platform and your 339 build system might include some tests to provide you with the 340 necessary conditional operations. For possible suggestions consult 341 @code{platform.h} and @code{configure.ac} in the MHD distribution. 342 343 Once you have ensured that you manually (!) included the right headers 344 for your platform before "microhttpd.h", you should also add a line 345 with @code{#define MHD_PLATFORM_H} which will prevent the 346 "microhttpd.h" header from trying (and, depending on your platform, 347 failing) to include the right headers. 348 349 If you do not define MHD_PLATFORM_H, the "microhttpd.h" header will 350 automatically include headers needed on GNU/Linux systems (possibly 351 causing problems when porting to other platforms). 352 353 @section SIGPIPE 354 @cindex signals 355 MHD does not install a signal handler for SIGPIPE. On platforms where 356 this is possible (such as GNU/Linux), it disables SIGPIPE for its I/O 357 operations (by passing MSG_NOSIGNAL or similar). On other platforms, 358 SIGPIPE signals may be generated from network operations by MHD and 359 will cause the process to die unless the developer explicitly installs 360 a signal handler for SIGPIPE. 361 362 Hence portable code using MHD must install a SIGPIPE handler or 363 explicitly block the SIGPIPE signal. MHD does not do so in order to 364 avoid messing with other parts of the application that may need to 365 handle SIGPIPE in a particular way. You can make your application 366 handle SIGPIPE by calling the following function in @code{main}: 367 368 @verbatim 369 static void 370 catcher (int sig) 371 { 372 } 373 374 static void 375 ignore_sigpipe () 376 { 377 struct sigaction oldsig; 378 struct sigaction sig; 379 380 sig.sa_handler = &catcher; 381 sigemptyset (&sig.sa_mask); 382 #ifdef SA_INTERRUPT 383 sig.sa_flags = SA_INTERRUPT; /* SunOS */ 384 #else 385 sig.sa_flags = SA_RESTART; 386 #endif 387 if (0 != sigaction (SIGPIPE, &sig, &oldsig)) 388 fprintf (stderr, 389 "Failed to install SIGPIPE handler: %s\n", strerror (errno)); 390 } 391 @end verbatim 392 393 @section MHD_UNSIGNED_LONG_LONG 394 @cindex long long 395 @cindex MHD_LONG_LONG 396 @cindex IAR 397 @cindex ARM 398 @cindex cortex m3 399 @cindex embedded systems 400 401 Some platforms do not support @code{long long}. Hence MHD defines a 402 macro @code{MHD_UNSIGNED LONG_LONG} which will default to 403 @code{unsigned long long}. For standard desktop operating systems, 404 this is all you need to know. 405 406 However, if your platform does not support @code{unsigned long long}, 407 you should change "platform.h" to define @code{MHD_LONG_LONG} and 408 @code{MHD_UNSIGNED_LONG_LONG} to an appropriate alternative type and 409 also define @code{MHD_LONG_LONG_PRINTF} and 410 @code{MHD_UNSIGNED_LONG_LONG_PRINTF} to the corresponding format 411 string for printing such a data type. Note that the ``signed'' 412 versions are deprecated. Also, for historical reasons, 413 @code{MHD_LONG_LONG_PRINTF} is without the percent sign, whereas 414 @code{MHD_UNSIGNED_LONG_LONG_PRINTF} is with the percent sign. Newly 415 written code should only use the unsigned versions. However, you need 416 to define both in "platform.h" if you need to change the definition 417 for the specific platform. 418 419 420 @section Portability to W32 421 422 libmicrohttpd in general ported well to W32. Most libmicrohttpd features 423 are supported. W32 do not support some functions, like epoll and 424 corresponding MHD features are not available on W32. 425 426 427 @section Portability to z/OS 428 429 To compile MHD on z/OS, extract the archive and run 430 431 @verbatim 432 iconv -f UTF-8 -t IBM-1047 contrib/ascebc > /tmp/ascebc.sh 433 chmod +x /tmp/ascebc.sh 434 for n in `find * -type f` 435 do 436 /tmp/ascebc.sh $n 437 done 438 @end verbatim 439 to convert all source files to EBCDIC. Note that you must run 440 @code{configure} from the directory where the configure script is 441 located. Otherwise, configure will fail to find the 442 @code{contrib/xcc} script (which is a wrapper around the z/OS c89 443 compiler). 444 445 446 447 @c ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 448 449 @c ------------------------------------------------------------ 450 @node microhttpd-const 451 @chapter Constants 452 453 454 @deftp {Enumeration} MHD_FLAG 455 Options for the MHD daemon. 456 457 Note that MHD will run automatically in background thread(s) only if 458 @code{MHD_USE_INTERNAL_POLLING_THREAD} is used. Otherwise caller 459 (application) must use @code{MHD_run} or @code{MHD_run_from_select} to 460 have MHD processed network connections and data. 461 462 Starting the daemon may also fail if a particular option is not 463 implemented or not supported on the target platform (i.e. no support 464 for @acronym{TLS}, threads or IPv6). TLS support generally depends on 465 options given during MHD compilation. 466 467 @table @code 468 @item MHD_NO_FLAG 469 No options selected. 470 471 @item MHD_USE_ERROR_LOG 472 If this flag is used, the library should print error messages and 473 warnings to stderr (or to custom error printer if it's specified by 474 options). Note that for this run-time option to have any effect, MHD 475 needs to be compiled with messages enabled. This is done by default 476 except you ran configure with the @code{--disable-messages} flag set. 477 478 @item MHD_USE_DEBUG 479 @cindex debugging 480 Currently the same as @code{MHD_USE_ERROR_LOG}. 481 482 @item MHD_USE_TLS 483 @cindex TLS 484 @cindex SSL 485 Run in HTTPS-mode. If you specify @code{MHD_USE_TLS} and MHD was 486 compiled without SSL support, @code{MHD_start_daemon} will return 487 NULL. 488 489 @item MHD_USE_THREAD_PER_CONNECTION 490 Run using one thread per connection. 491 492 @item MHD_USE_INTERNAL_POLLING_THREAD 493 Run using an internal thread doing @code{SELECT}. 494 495 @item MHD_USE_IPv6 496 @cindex IPv6 497 Run using the IPv6 protocol (otherwise, MHD will just support IPv4). 498 If you specify @code{MHD_USE_IPV6} and the local platform does not 499 support it, @code{MHD_start_daemon} will return NULL. 500 501 If you want MHD to support IPv4 and IPv6 using a single socket, pass 502 MHD_USE_DUAL_STACK, otherwise, if you only pass this option, MHD will 503 try to bind to IPv6-only (resulting in no IPv4 support). 504 505 @item MHD_USE_DUAL_STACK 506 @cindex IPv6 507 Use a single socket for IPv4 and IPv6. Note that this will mean 508 that IPv4 addresses are returned by MHD in the IPv6-mapped format 509 (the 'struct sockaddr_in6' format will be used for IPv4 and IPv6). 510 511 @item MHD_USE_PEDANTIC_CHECKS 512 @cindex deprecated 513 Deprecated (use @code{MHD_OPTION_STRICT_FOR_CLIENT}). 514 Be pedantic about the protocol. 515 Specifically, at the moment, this flag causes MHD to reject HTTP 516 1.1 connections without a @code{Host} header. This is required by the 517 standard, but of course in violation of the ``be as liberal as possible 518 in what you accept'' norm. It is recommended to turn this @strong{ON} 519 if you are testing clients against MHD, and @strong{OFF} in 520 production. 521 522 @item MHD_USE_POLL 523 @cindex FD_SETSIZE 524 @cindex poll 525 @cindex select 526 Use @code{poll()} instead of @code{select()}. This allows sockets with 527 descriptors @code{>= FD_SETSIZE}. This option currently only works in 528 conjunction with @code{MHD_USE_INTERNAL_POLLING_THREAD} (at this point). 529 If you specify @code{MHD_USE_POLL} and the local platform does not 530 support it, @code{MHD_start_daemon} will return NULL. 531 532 @item MHD_USE_EPOLL 533 @cindex FD_SETSIZE 534 @cindex epoll 535 @cindex select 536 Use @code{epoll()} instead of @code{poll()} or @code{select()}. This 537 allows sockets with descriptors @code{>= FD_SETSIZE}. This option is 538 only available on some systems and does not work in conjunction with 539 @code{MHD_USE_THREAD_PER_CONNECTION} (at this point). If you specify 540 @code{MHD_USE_EPOLL} and the local platform does not support it, 541 @code{MHD_start_daemon} will return NULL. Using @code{epoll()} 542 instead of @code{select()} or @code{poll()} can in some situations 543 result in significantly higher performance as the system call has 544 fundamentally lower complexity (O(1) for @code{epoll()} vs. O(n) for 545 @code{select()}/@code{poll()} where n is the number of open 546 connections). 547 548 @item MHD_USE_TURBO 549 @cindex performance 550 Enable optimizations to aggressively improve performance. 551 552 Currently, the optimizations this option enables are based on 553 opportunistic reads and writes. Basically, MHD will simply try to 554 read or write or accept on a socket before checking that the socket is 555 ready for IO using the event loop mechanism. As the sockets are 556 non-blocking, this may fail (at a loss of performance), but generally 557 MHD does this in situations where the operation is likely to succeed, 558 in which case performance is improved. Setting the flag should generally 559 be safe (even though the code is slightly more experimental). You may 560 want to benchmark your application to see if this makes any difference 561 for you. 562 563 564 @item MHD_USE_SUPPRESS_DATE_NO_CLOCK 565 @cindex date 566 @cindex clock 567 @cindex embedded systems 568 Suppress (automatically) adding the 'Date:' header to HTTP responses. 569 This option should ONLY be used on systems that do not have a clock 570 and that DO provide other mechanisms for cache control. See also 571 RFC 2616, section 14.18 (exception 3). 572 573 574 @item MHD_USE_NO_LISTEN_SOCKET 575 @cindex listen 576 @cindex proxy 577 @cindex embedded systems 578 Run the HTTP server without any listen socket. This option only makes 579 sense if @code{MHD_add_connection} is going to be used exclusively to 580 connect HTTP clients to the HTTP server. This option is incompatible 581 with using a thread pool; if it is used, 582 @code{MHD_OPTION_THREAD_POOL_SIZE} is ignored. 583 584 585 @item MHD_USE_ITC 586 @cindex quiesce 587 Force MHD to use a signal inter-thread communication channel to notify 588 the event loop (of threads) of our shutdown and other events. This is 589 required if an application uses @code{MHD_USE_INTERNAL_POLLING_THREAD} 590 and then performs @code{MHD_quiesce_daemon} (which eliminates our 591 ability to signal termination via the listen socket). In these modes, 592 @code{MHD_quiesce_daemon} will fail if this option was not set. Also, 593 use of this option is automatic (as in, you do not even have to 594 specify it), if @code{MHD_USE_NO_LISTEN_SOCKET} is specified. In 595 "external" select mode, this option is always simply ignored. 596 597 Using this option also guarantees that MHD will not call 598 @code{shutdown()} on the listen socket, which means a parent 599 process can continue to use the socket. 600 601 @item MHD_ALLOW_SUSPEND_RESUME 602 Enables using @code{MHD_suspend_connection} and 603 @code{MHD_resume_connection}, as performing these calls requires some 604 additional inter-thred communication channels to be created, and code 605 not using these calls should not pay the cost. 606 607 @item MHD_USE_TCP_FASTOPEN 608 @cindex listen 609 Enable TCP_FASTOPEN on the listen socket. TCP_FASTOPEN is currently 610 supported on Linux >= 3.6. On other systems using this option with 611 cause @code{MHD_start_daemon} to fail. 612 613 614 @item MHD_ALLOW_UPGRADE 615 @cindex upgrade 616 This option must be set if you want to upgrade connections 617 (via ``101 Switching Protocols'' responses). This requires MHD to 618 allocate additional resources, and hence we require this 619 special flag so we only use the resources that are really needed. 620 621 622 @item MHD_USE_AUTO 623 Automatically select best event loop style (polling function) 624 depending on requested mode by other MHD flags and functions available 625 on platform. If application doesn't have requirements for any 626 specific polling function, it's recommended to use this flag. This 627 flag is very convenient for multiplatform applications. 628 629 @item MHD_USE_POST_HANDSHAKE_AUTH_SUPPORT 630 Tell the TLS library to support post handshake client authentication. 631 Only useful in combination with @code{MHD_USE_TLS}. 632 633 This option will only work if the underlying TLS library 634 supports it (i.e. GnuTLS after 3.6.3). If the TLS library 635 does not support it, MHD may ignore the option and proceed 636 without supporting this features. 637 638 @item MHD_USE_INSECURE_TLS_EARLY_DATA 639 Tell the TLS library to support TLS v1.3 early data (0-RTT) with the 640 resulting security drawbacks. Only enable this if you really know what 641 you are doing. MHD currently does NOT enforce that this only affects 642 GET requests! You have been warned. 643 644 This option will only work if the underlying TLS library 645 supports it (i.e. GnuTLS after 3.6.3). If the TLS library 646 does not support it, MHD may ignore the option and proceed 647 without supporting this features. 648 649 @end table 650 @end deftp 651 652 653 @deftp {Enumeration} MHD_OPTION 654 MHD options. Passed in the varargs portion of 655 @code{MHD_start_daemon()}. 656 657 @table @code 658 @item MHD_OPTION_END 659 No more options / last option. This is used to terminate the VARARGs 660 list. 661 662 @item MHD_OPTION_CONNECTION_MEMORY_LIMIT 663 @cindex memory, limiting memory utilization 664 Maximum memory size per connection (followed by a @code{size_t}). The 665 default is 32 kB (32*1024 bytes) as defined by the internal constant 666 @code{MHD_POOL_SIZE_DEFAULT}. Values above 128k are unlikely to 667 result in much benefit, as half of the memory will be typically used 668 for IO, and TCP buffers are unlikely to support window sizes above 64k 669 on most systems. 670 671 @item MHD_OPTION_CONNECTION_MEMORY_INCREMENT 672 @cindex memory 673 Increment to use for growing the read buffer (followed by a 674 @code{size_t}). The default is 1024 (bytes). Increasing this value 675 will make MHD use memory for reading more aggressively, which can 676 reduce the number of @code{recvfrom} calls but may increase the number 677 of @code{sendto} calls. The given value must fit within 678 MHD_OPTION_CONNECTION_MEMORY_LIMIT. 679 680 @item MHD_OPTION_CONNECTION_LIMIT 681 @cindex connection, limiting number of connections 682 Maximum number of concurrent connections to accept (followed by an 683 @code{unsigned int}). The default is @code{FD_SETSIZE - 4} (the 684 maximum number of file descriptors supported by @code{select} minus 685 four for @code{stdin}, @code{stdout}, @code{stderr} and the server 686 socket). In other words, the default is as large as possible. 687 688 If the connection limit is reached, MHD's behavior depends a bit on 689 other options. If @code{MHD_USE_ITC} was given, MHD 690 will stop accepting connections on the listen socket. This will cause 691 the operating system to queue connections (up to the @code{listen()} 692 limit) above the connection limit. Those connections will be held 693 until MHD is done processing at least one of the active connections. 694 If @code{MHD_USE_ITC} is not set, then MHD will continue 695 to @code{accept()} and immediately @code{close()} these connections. 696 697 Note that if you set a low connection limit, you can easily get into 698 trouble with browsers doing request pipelining. For example, if your 699 connection limit is ``1'', a browser may open a first connection to 700 access your ``index.html'' file, keep it open but use a second 701 connection to retrieve CSS files, images and the like. In fact, modern 702 browsers are typically by default configured for up to 15 parallel 703 connections to a single server. If this happens, MHD will refuse to 704 even accept the second connection until the first connection is 705 closed --- which does not happen until timeout. As a result, the 706 browser will fail to render the page and seem to hang. If you expect 707 your server to operate close to the connection limit, you should 708 first consider using a lower timeout value and also possibly add 709 a ``Connection: close'' header to your response to ensure that 710 request pipelining is not used and connections are closed immediately 711 after the request has completed: 712 @example 713 MHD_add_response_header (response, 714 MHD_HTTP_HEADER_CONNECTION, 715 "close"); 716 @end example 717 718 @item MHD_OPTION_CONNECTION_TIMEOUT 719 @cindex timeout 720 After how many seconds of inactivity should a connection automatically 721 be timed out? (followed by an @code{unsigned int}; use zero for no 722 timeout). The default is zero (no timeout). 723 724 @item MHD_OPTION_NOTIFY_COMPLETED 725 Register a function that should be called whenever a request has been 726 completed (this can be used for application-specific clean up). 727 Requests that have never been presented to the application (via 728 @code{MHD_AccessHandlerCallback()}) will not result in 729 notifications. 730 731 This option should be followed by @strong{TWO} pointers. First a 732 pointer to a function of type @code{MHD_RequestCompletedCallback()} 733 and second a pointer to a closure to pass to the request completed 734 callback. The second pointer maybe @code{NULL}. 735 736 @item MHD_OPTION_NOTIFY_CONNECTION 737 Register a function that should be called when the TCP connection to a 738 client is opened or closed. The registered callback is called twice per 739 TCP connection, with @code{MHD_CONNECTION_NOTIFY_STARTED} and 740 @code{MHD_CONNECTION_NOTIFY_CLOSED} respectively. An additional 741 argument can be used to store TCP connection specific information, 742 which can be retrieved using @code{MHD_CONNECTION_INFO_SOCKET_CONTEXT} 743 during the lifetime of the TCP connection. 744 Note @code{MHD_OPTION_NOTIFY_COMPLETED} and the @code{req_cls} argument 745 to the @code{MHD_AccessHandlerCallback} are per HTTP request (and there 746 can be multiple HTTP requests per TCP connection). 747 748 This option should be followed by @strong{TWO} pointers. First a 749 pointer to a function of type @code{MHD_NotifyConnectionCallback()} 750 and second a pointer to a closure to pass to the request completed 751 callback. The second pointer maybe @code{NULL}. 752 753 @item MHD_OPTION_PER_IP_CONNECTION_LIMIT 754 Limit on the number of (concurrent) connections made to the 755 server from the same IP address. Can be used to prevent one 756 IP from taking over all of the allowed connections. If the 757 same IP tries to establish more than the specified number of 758 connections, they will be immediately rejected. The option 759 should be followed by an @code{unsigned int}. The default is 760 zero, which means no limit on the number of connections 761 from the same IP address. 762 763 @item MHD_OPTION_LISTEN_BACKLOG_SIZE 764 Set the size of the @code{listen()} back log queue of the TCP socket. 765 Takes an @code{unsigned int} as the argument. Default is the 766 platform-specific value of @code{SOMAXCONN}. 767 768 @item MHD_OPTION_STRICT_FOR_CLIENT 769 Specify how strict we should enforce the HTTP protocol. 770 Takes an @code{int} as the argument. Default is zero. 771 772 If set to 1, MHD will be strict about the protocol. Specifically, at 773 the moment, this flag uses MHD to reject HTTP 1.1 connections without 774 a "Host" header. This is required by the standard, but of course in 775 violation of the "be as liberal as possible in what you accept" norm. 776 It is recommended to set this to 1 if you are testing clients against 777 MHD, and 0 in production. 778 779 If set to -1 MHD will be permissive about the protocol, allowing 780 slight deviations that are technically not allowed by the 781 RFC. Specifically, at the moment, this flag causes MHD to allow spaces 782 in header field names. This is disallowed by the standard. 783 784 It is not recommended to set it to -1 on publicly available servers as 785 it may potentially lower level of protection. 786 787 @item MHD_OPTION_SERVER_INSANITY 788 @cindex testing 789 Allows the application to disable certain sanity precautions in MHD. With 790 these, the client can break the HTTP protocol, so this should never be used in 791 production. The options are, however, useful for testing HTTP clients against 792 "broken" server implementations. This argument must be followed by an 793 @code{unsigned int}, corresponding to an @code{enum MHD_DisableSanityCheck}. 794 795 Right now, no sanity checks can be disabled. 796 797 @item MHD_OPTION_SOCK_ADDR 798 @cindex bind, restricting bind 799 Bind daemon to the supplied socket address. This option should be followed by a 800 @code{struct sockaddr *}. If @code{MHD_USE_IPv6} is specified, 801 the @code{struct sockaddr*} should point to a @code{struct sockaddr_in6}, 802 otherwise to a @code{struct sockaddr_in}. If this option is not specified, 803 the daemon will listen to incoming connections from anywhere. If you use this 804 option, the 'port' argument from @code{MHD_start_daemon} is ignored and the port 805 from the given @code{struct sockaddr *} will be used instead. 806 807 @item MHD_OPTION_URI_LOG_CALLBACK 808 @cindex debugging 809 @cindex logging 810 @cindex query string 811 Specify a function that should be called before parsing the URI from 812 the client. The specified callback function can be used for processing 813 the URI (including the options) before it is parsed. The URI after 814 parsing will no longer contain the options, which maybe inconvenient for 815 logging. This option should be followed by two arguments, the first 816 one must be of the form 817 @example 818 void * my_logger(void * cls, const char * uri, struct MHD_Connection *con) 819 @end example 820 where the return value will be passed as 821 @code{*req_cls} in calls to the @code{MHD_AccessHandlerCallback} 822 when this request is processed later; returning a 823 value of @code{NULL} has no special significance; (however, 824 note that if you return non-@code{NULL}, you can no longer 825 rely on the first call to the access handler having 826 @code{NULL == *req_cls} on entry) 827 @code{cls} will be set to the second argument following 828 MHD_OPTION_URI_LOG_CALLBACK. Finally, @code{uri} will 829 be the 0-terminated URI of the request. 830 831 Note that during the time of this call, most of the connection's state 832 is not initialized (as we have not yet parsed he headers). However, 833 information about the connecting client (IP, socket) is available. 834 835 @item MHD_OPTION_HTTPS_MEM_KEY 836 @cindex SSL 837 @cindex TLS 838 Memory pointer to the private key to be used by the 839 HTTPS daemon. This option should be followed by an 840 "const char*" argument. 841 This should be used in conjunction with 'MHD_OPTION_HTTPS_MEM_CERT'. 842 843 @item MHD_OPTION_HTTPS_KEY_PASSWORD 844 @cindex SSL 845 @cindex TLS 846 Memory pointer to the password that decrypts the 847 private key to be used by the HTTPS daemon. 848 This option should be followed by an 849 "const char*" argument. 850 This should be used in conjunction with 'MHD_OPTION_HTTPS_MEM_KEY'. 851 852 The password (or passphrase) is only used immediately during 853 @code{MHD_start_daemon()}. Thus, the application may want to 854 erase it from memory afterwards for additional security. 855 856 @item MHD_OPTION_HTTPS_MEM_CERT 857 @cindex SSL 858 @cindex TLS 859 Memory pointer to the certificate to be used by the 860 HTTPS daemon. This option should be followed by an 861 "const char*" argument. 862 This should be used in conjunction with 'MHD_OPTION_HTTPS_MEM_KEY'. 863 864 @item MHD_OPTION_HTTPS_MEM_TRUST 865 @cindex SSL 866 @cindex TLS 867 Memory pointer to the CA certificate to be used by the 868 HTTPS daemon to authenticate and trust clients certificates. 869 This option should be followed by an "const char*" argument. 870 The presence of this option activates the request of certificate 871 to the client. The request to the client is marked optional, and 872 it is the responsibility of the server to check the presence 873 of the certificate if needed. 874 Note that most browsers will only present a client certificate 875 only if they have one matching the specified CA, not sending 876 any certificate otherwise. 877 878 @item MHD_OPTION_HTTPS_CRED_TYPE 879 @cindex SSL 880 @cindex TLS 881 Daemon credentials type. Either certificate or anonymous, 882 this option should be followed by one of the values listed in 883 "enum gnutls_credentials_type_t". 884 885 @item MHD_OPTION_HTTPS_PRIORITIES 886 @cindex SSL 887 @cindex TLS 888 @cindex cipher 889 SSL/TLS protocol version and ciphers. 890 This option must be followed by an "const char *" argument 891 specifying the SSL/TLS protocol versions and ciphers that 892 are acceptable for the application. The string is passed 893 unchanged to gnutls_priority_init. If this option is not 894 specified, ``NORMAL'' is used. 895 896 @item MHD_OPTION_HTTPS_CERT_CALLBACK 897 @cindex SSL 898 @cindex TLS 899 @cindex SNI 900 Use a callback to determine which X.509 certificate should be used for 901 a given HTTPS connection. This option should be followed by a 902 argument of type "gnutls_certificate_retrieve_function2 *". This 903 option provides an alternative to MHD_OPTION_HTTPS_MEM_KEY and 904 MHD_OPTION_HTTPS_MEM_CERT. You must use this version if multiple 905 domains are to be hosted at the same IP address using TLS's Server 906 Name Indication (SNI) extension. In this case, the callback is 907 expected to select the correct certificate based on the SNI 908 information provided. The callback is expected to access the SNI data 909 using gnutls_server_name_get(). Using this option requires GnuTLS 3.0 910 or higher. 911 912 @item MHD_OPTION_HTTPS_CERT_CALLBACK2 913 @cindex SSL 914 @cindex TLS 915 @cindex SNI 916 @cindex OCSP 917 Use a callback to determine which X.509 certificate should be 918 used for a given HTTPS connection. This option should be 919 followed by a argument of type `gnutls_certificate_retrieve_function3 *`. 920 This option provides an 921 alternative/extension to #MHD_OPTION_HTTPS_CERT_CALLBACK. 922 You must use this version if you want to use OCSP stapling. 923 Using this option requires GnuTLS 3.6.3 or higher. 924 925 @item MHD_OPTION_GNUTLS_PSK_CRED_HANDLER 926 @cindex SSL 927 @cindex TLS 928 @cindex PSK 929 Use pre-shared key for TLS credentials. 930 Pass a pointer to callback of type 931 @code{MHD_PskServerCredentialsCallback} and a closure. 932 The function will be called to 933 retrieve the shared key for a given username. 934 The key must be at least 16 bytes long, as required by RFC 4279 935 section 7.1; MHD fails the authentication for a shorter one. 936 937 @item MHD_OPTION_DIGEST_AUTH_RANDOM 938 @cindex digest auth 939 @cindex random 940 Digest Authentication nonce's seed. 941 942 This option should be followed by two arguments. First an integer of 943 type "size_t" which specifies the size of the buffer pointed to by the 944 second argument in bytes. Note that the application must ensure that 945 the buffer of the second argument remains allocated and unmodified 946 while the daemon is running. For security, you SHOULD provide a fresh 947 random nonce when using MHD with Digest Authentication. 948 949 @item MHD_OPTION_NONCE_NC_SIZE 950 @cindex digest auth 951 @cindex replay attack 952 953 Size of an array of nonce and nonce counter map. This option must be 954 followed by an "unsigned int" argument that have the size (number of 955 elements) of a map of a nonce and a nonce-counter. If this option 956 is not specified, a default value of 4 will be used (which might be 957 too small for servers handling many requests). If you do not use 958 digest authentication at all, you can specify a value of zero to 959 save some memory. 960 961 You should calculate the value of NC_SIZE based on the number of 962 connections per second multiplied by your expected session duration 963 plus a factor of about two for hash table collisions. For example, if 964 you expect 100 digest-authenticated connections per second and the 965 average user to stay on your site for 5 minutes, then you likely need 966 a value of about 60000. On the other hand, if you can only expect 967 only 10 digest-authenticated connections per second, tolerate browsers 968 getting a fresh nonce for each request and expect a HTTP request 969 latency of 250 ms, then a value of about 5 should be fine. 970 971 972 @item MHD_OPTION_LISTEN_SOCKET 973 @cindex systemd 974 Listen socket to use. Pass a listen socket for MHD to use 975 (systemd-style). If this option is used, MHD will not open its own 976 listen socket(s). The argument passed must be of type "int" and refer 977 to an existing socket that has been bound to a port and is listening. 978 979 @item MHD_OPTION_EXTERNAL_LOGGER 980 @cindex logging 981 Use the given function for logging error messages. 982 This option must be followed by two arguments; the 983 first must be a pointer to a function 984 of type 'void fun(void * arg, const char * fmt, va_list ap)' 985 and the second a pointer of type 'void*' which will 986 be passed as the "arg" argument to "fun". 987 988 Note that MHD will not generate any log messages without 989 the MHD_USE_ERROR_LOG flag set and if MHD was compiled 990 with the "--disable-messages" flag. 991 992 @item MHD_OPTION_THREAD_POOL_SIZE 993 @cindex performance 994 Number (unsigned int) of threads in thread pool. Enable 995 thread pooling by setting this value to to something 996 greater than 1. Currently, thread mode must be 997 MHD_USE_INTERNAL_POLLING_THREAD if thread pooling is enabled 998 (@code{MHD_start_daemon} returns @code{NULL} for an unsupported thread 999 mode). 1000 1001 @item MHD_OPTION_ARRAY 1002 @cindex options 1003 @cindex foreign-function interface 1004 This option can be used for initializing MHD using options from an 1005 array. A common use for this is writing an FFI for MHD. The actual 1006 options given are in an array of 'struct MHD_OptionItem', so this 1007 option requires a single argument of type 'struct MHD_OptionItem'. 1008 The array must be terminated with an entry @code{MHD_OPTION_END}. 1009 1010 An example for code using MHD_OPTION_ARRAY is: 1011 @example 1012 struct MHD_OptionItem ops[] = @{ 1013 @{ MHD_OPTION_CONNECTION_LIMIT, 100, NULL @}, 1014 @{ MHD_OPTION_CONNECTION_TIMEOUT, 10, NULL @}, 1015 @{ MHD_OPTION_END, 0, NULL @} 1016 @}; 1017 d = MHD_start_daemon(0, 8080, NULL, NULL, dh, NULL, 1018 MHD_OPTION_ARRAY, ops, 1019 MHD_OPTION_END); 1020 @end example 1021 For options that expect a single pointer argument, the 1022 second member of the @code{struct MHD_OptionItem} is ignored. 1023 For options that expect two pointer arguments, the first 1024 argument must be cast to @code{intptr_t}. 1025 1026 @item MHD_OPTION_UNESCAPE_CALLBACK 1027 @cindex internationalization 1028 @cindex escaping 1029 1030 Specify a function that should be called for unescaping escape 1031 sequences in URIs and URI arguments. Note that this function will NOT 1032 be used by the MHD_PostProcessor. If this option is not specified, 1033 the default method will be used which decodes escape sequences of the 1034 form "%HH". This option should be followed by two arguments, the 1035 first one must be of the form 1036 1037 @example 1038 size_t my_unescaper(void * cls, struct MHD_Connection *c, char *s) 1039 @end example 1040 1041 where the return value must be @code{strlen(s)} and @code{s} should be 1042 updated. Note that the unescape function must not lengthen @code{s} 1043 (the result must be shorter than the input and still be 0-terminated). 1044 @code{cls} will be set to the second argument following 1045 MHD_OPTION_UNESCAPE_CALLBACK. 1046 1047 1048 @item MHD_OPTION_THREAD_STACK_SIZE 1049 @cindex stack 1050 @cindex thread 1051 @cindex pthread 1052 @cindex embedded systems 1053 Maximum stack size for threads created by MHD. This option must be 1054 followed by a @code{size_t}). Not specifying this option or using 1055 a value of zero means using the system default (which is likely to 1056 differ based on your platform). 1057 1058 @item MHD_OPTION_TCP_FASTQUEUE_QUEUE_SIZE 1059 @cindex listen 1060 When the flag @code{MHD_USE_TCP_FASTOPEN} is used, this option sets the 1061 connection handshake queue size for the TCP FASTOPEN connections. Note 1062 that a TCP FASTOPEN connection handshake occupies more resources than a 1063 TCP handshake as the SYN packets also contain DATA which is kept in the 1064 associate state until handshake is completed. If this option is not 1065 given the queue size is set to a default value of 10. This option must 1066 be followed by a @code{unsigned int}. 1067 1068 @item MHD_OPTION_HTTPS_MEM_DHPARAMS 1069 @cindex TLS 1070 @cindex SSL 1071 @cindex DH 1072 Memory pointer for the Diffie-Hellman parameters (dh.pem) to be used 1073 by the HTTPS daemon for key exchange. This option must be followed by 1074 a @code{const char *} argument. The argument would be a zero-terminated 1075 string with a PEM encoded PKCS3 DH parameters structure suitable 1076 for passing to @code{gnutls_dh_parms_import_pkcs3}. 1077 1078 @item MHD_OPTION_LISTENING_ADDRESS_REUSE 1079 @cindex bind, restricting bind 1080 @cindex reusing listening address 1081 This option must be followed by a @code{unsigned int} argument. 1082 If this option is present and true (nonzero) parameter is given, allow reusing 1083 the address:port of the listening socket (using @code{SO_REUSEPORT} on most 1084 platforms, and @code{SO_REUSEADDR} on Windows). If a false (zero) parameter is 1085 given, disallow reusing the the address:port of the listening socket (this 1086 usually requires no special action, but @code{SO_EXCLUSIVEADDRUSE} is needed on 1087 Windows). If this option is not present @code{SO_REUSEADDR} is used on all 1088 platforms except Windows so reusing of address:port is disallowed. 1089 1090 @end table 1091 @end deftp 1092 1093 1094 @deftp {C Struct} MHD_OptionItem 1095 Entry in an MHD_OPTION_ARRAY. See the @code{MHD_OPTION_ARRAY} option 1096 argument for its use. 1097 1098 The @code{option} member is used to specify which option is specified 1099 in the array. The other members specify the respective argument. 1100 1101 Note that for options taking only a single pointer, the 1102 @code{ptr_value} member should be set. For options taking two pointer 1103 arguments, the first pointer must be cast to @code{intptr_t} and both 1104 the @code{value} and the @code{ptr_value} members should be used to 1105 pass the two pointers. 1106 @end deftp 1107 1108 1109 @deftp {Enumeration} MHD_ValueKind 1110 The @code{MHD_ValueKind} specifies the source of the key-value pairs in 1111 the HTTP protocol. 1112 1113 @table @code 1114 @item MHD_HEADER_KIND 1115 HTTP header. 1116 1117 @item MHD_COOKIE_KIND 1118 @cindex cookie 1119 Cookies. Note that the original HTTP header containing the cookie(s) 1120 will still be available and intact. 1121 1122 @item MHD_POSTDATA_KIND 1123 @cindex POST method 1124 @code{POST} data. This is available only if a content encoding 1125 supported by MHD is used (currently only @acronym{URL} encoding), and 1126 only if the posted content fits within the available memory pool. Note 1127 that in that case, the upload data given to the 1128 @code{MHD_AccessHandlerCallback()} will be empty (since it has 1129 already been processed). 1130 1131 @item MHD_GET_ARGUMENT_KIND 1132 @code{GET} (URI) arguments. 1133 1134 @item MHD_FOOTER_KIND 1135 HTTP footer (only for http 1.1 chunked encodings). 1136 1137 @end table 1138 @end deftp 1139 1140 1141 @deftp {Enumeration} MHD_RequestTerminationCode 1142 The @code{MHD_RequestTerminationCode} specifies reasons why a request 1143 has been terminated (or completed). 1144 1145 @table @code 1146 @item MHD_REQUEST_TERMINATED_COMPLETED_OK 1147 We finished sending the response. 1148 1149 @item MHD_REQUEST_TERMINATED_WITH_ERROR 1150 Error handling the connection (resources exhausted, other side closed 1151 connection, application error accepting request, etc.) 1152 1153 @item MHD_REQUEST_TERMINATED_TIMEOUT_REACHED 1154 No activity on the connection for the number of seconds specified using 1155 @code{MHD_OPTION_CONNECTION_TIMEOUT}. 1156 1157 @item MHD_REQUEST_TERMINATED_DAEMON_SHUTDOWN 1158 We had to close the session since MHD was being shut down. 1159 @end table 1160 @end deftp 1161 1162 1163 @deftp {Enumeration} MHD_ResponseMemoryMode 1164 The @code{MHD_ResponeMemoryMode} specifies how MHD should treat 1165 the memory buffer given for the response in 1166 @code{MHD_create_response_from_buffer}. 1167 1168 @table @code 1169 @item MHD_RESPMEM_PERSISTENT 1170 Buffer is a persistent (static/global) buffer that won't change 1171 for at least the lifetime of the response, MHD should just use 1172 it, not free it, not copy it, just keep an alias to it. 1173 1174 @item MHD_RESPMEM_MUST_FREE 1175 Buffer is heap-allocated with @code{malloc} (or equivalent) and 1176 should be freed by MHD after processing the response has 1177 concluded (response reference counter reaches zero). 1178 1179 @item MHD_RESPMEM_MUST_COPY 1180 Buffer is in transient memory, but not on the heap (for example, 1181 on the stack or non-malloc allocated) and only valid during the 1182 call to @code{MHD_create_response_from_buffer}. MHD must make its 1183 own private copy of the data for processing. 1184 1185 @end table 1186 @end deftp 1187 1188 1189 @deftp {Enumeration} MHD_ResponseFlags 1190 Response-specific flags. Passed as an argument to 1191 @code{MHD_set_response_options()}. 1192 1193 @table @code 1194 @item MHD_RF_NONE 1195 No special handling. 1196 1197 @item MHD_RF_HTTP_VERSION_1_0_ONLY 1198 Only respond in conservative HTTP 1.0-mode. In particular, 1199 do not (automatically) sent "Connection" headers and always 1200 close the connection after generating the response. 1201 1202 By default, MHD will respond using the same HTTP version which 1203 was set in the request. You can also set the 1204 @code{MHD_RF_HTTP_VERSION_1_0_RESPONSE} flag to force version 1.0 1205 in the response. 1206 1207 @item MHD_RF_HTTP_VERSION_1_0_RESPONSE 1208 Only respond in HTTP 1.0-mode. Contrary to the 1209 @code{MHD_RF_HTTP_VERSION_1_0_ONLY} flag, the response's HTTP version will 1210 always be set to 1.0 and ``Connection'' headers are still supported. 1211 1212 You can even combine this option with MHD_RF_HTTP_VERSION_1_0_ONLY to 1213 change the response's HTTP version while maintaining strict compliance 1214 with HTTP 1.0 regarding connection management. 1215 1216 This solution is not perfect as this flag is set on the response which 1217 is created after header processing. So MHD will behave as a HTTP 1.1 1218 server until the response is queued. It means that an invalid HTTP 1.1 1219 request will fail even if the response is sent with HTTP 1.0 and the 1220 request would be valid if interpreted with this version. For example, 1221 this request will fail in strict mode: 1222 1223 @verbatim 1224 GET / HTTP/1.1 1225 @end verbatim 1226 1227 as the ``Host'' header is missing and is mandatory in HTTP 1.1, but it 1228 should succeed when interpreted with HTTP 1.0. 1229 1230 @item MHD_RF_INSANITY_HEADER_CONTENT_LENGTH 1231 Disable sanity check preventing clients from manually 1232 setting the HTTP content length option. 1233 1234 @end table 1235 @end deftp 1236 1237 1238 @deftp {Enumeration} MHD_ResponseOptions 1239 Response-specific options. Passed in the varargs portion of 1240 @code{MHD_set_response_options()}. 1241 1242 @table @code 1243 @item MHD_RO_END 1244 No more options / last option. This is used to terminate the VARARGs 1245 list. 1246 @end table 1247 @end deftp 1248 1249 1250 @c ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1251 1252 @c ------------------------------------------------------------ 1253 @node microhttpd-struct 1254 @chapter Structures type definition 1255 1256 1257 @deftp {C Struct} MHD_Daemon 1258 Handle for the daemon (listening on a socket for HTTP traffic). 1259 @end deftp 1260 1261 1262 @deftp {C Struct} MHD_Connection 1263 Handle for a connection / HTTP request. With HTTP/1.1, multiple 1264 requests can be run over the same connection. However, MHD will only 1265 show one request per TCP connection to the client at any given time. 1266 @end deftp 1267 1268 1269 @deftp {C Struct} MHD_Response 1270 Handle for a response. 1271 @end deftp 1272 1273 1274 @deftp {C Struct} MHD_IoVec 1275 An element of an array of memory buffers. 1276 @end deftp 1277 1278 1279 @deftp {C Struct} MHD_PostProcessor 1280 @cindex POST method 1281 Handle for @code{POST} processing. 1282 @end deftp 1283 1284 1285 @deftp {C Union} MHD_ConnectionInfo 1286 Information about a connection. 1287 @end deftp 1288 1289 1290 @deftp {C Union} MHD_DaemonInfo 1291 Information about an MHD daemon. 1292 @end deftp 1293 1294 1295 1296 @c ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1297 1298 @c ------------------------------------------------------------ 1299 @node microhttpd-cb 1300 @chapter Callback functions definition 1301 1302 1303 @deftypefn {Function Pointer} enum MHD_Result {*MHD_AcceptPolicyCallback} (void *cls, const struct sockaddr * addr, socklen_t addrlen) 1304 Invoked in the context of a connection to allow or deny a client to 1305 connect. This callback return @code{MHD_YES} if connection is allowed, 1306 @code{MHD_NO} if not. 1307 1308 @table @var 1309 @item cls 1310 custom value selected at callback registration time; 1311 @item addr 1312 address information from the client; 1313 @item addrlen 1314 length of the address information. 1315 @end table 1316 @end deftypefn 1317 1318 1319 @deftypefn {Function Pointer} enum MHD_Result {*MHD_AccessHandlerCallback} (void *cls, struct MHD_Connection * connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) 1320 Invoked in the context of a connection to answer a request from the 1321 client. This callback must call MHD functions (example: the 1322 @code{MHD_Response} ones) to provide content to give back to the client 1323 and return an HTTP status code (i.e. @code{200} for OK, @code{404}, 1324 etc.). 1325 1326 @ref{microhttpd-post}, for details on how to code this callback. 1327 1328 Must return @code{MHD_YES} if the connection was handled successfully, 1329 @code{MHD_NO} if the socket must be closed due to a serious error while 1330 handling the request 1331 1332 @table @var 1333 @item cls 1334 custom value selected at callback registration time; 1335 1336 @item url 1337 the URL requested by the client; 1338 1339 @item method 1340 the HTTP method used by the client (@code{GET}, @code{PUT}, 1341 @code{DELETE}, @code{POST}, etc.); 1342 1343 @item version 1344 the HTTP version string (i.e. @code{HTTP/1.1}); 1345 1346 @item upload_data 1347 the data being uploaded (excluding headers): 1348 @cindex POST method 1349 @cindex PUT method 1350 1351 @code{POST} data @strong{will} be made available 1352 incrementally in @var{upload_data}; even if @code{POST} 1353 data is available, the first time the callback is 1354 invoked there won't be upload data, as this is done 1355 just after MHD parses the headers. If supported by 1356 the client and the HTTP version, the application can 1357 at this point queue an error response to possibly 1358 avoid the upload entirely. If no response is generated, 1359 MHD will (if required) automatically send a 100 CONTINUE 1360 reply to the client. 1361 1362 Afterwards, POST data will be passed to the callback 1363 to be processed incrementally by the application. The 1364 application may return @code{MHD_NO} to forcefully 1365 terminate the TCP connection without generating a 1366 proper HTTP response. Once all of the upload data has 1367 been provided to the application, the application 1368 will be called again with 0 bytes of upload data. 1369 At this point, a response should be queued to complete 1370 the handling of the request. 1371 1372 @item upload_data_size 1373 set initially to the size of the @var{upload_data} provided; this 1374 callback must update this value to the number of bytes @strong{NOT} 1375 processed; unless external select is used, the callback maybe 1376 required to process at least some data. If the callback fails to 1377 process data in multi-threaded or internal-select mode and if the 1378 read-buffer is already at the maximum size that MHD is willing to 1379 use for reading (about half of the maximum amount of memory allowed 1380 for the connection), then MHD will abort handling the connection 1381 and return an internal server error to the client. In order to 1382 avoid this, clients must be able to process upload data incrementally 1383 and reduce the value of @code{upload_data_size}. 1384 1385 @item req_cls 1386 reference to a pointer, initially set to @code{NULL}, that this callback can 1387 set to some address and that will be preserved by MHD for future 1388 calls for this request; 1389 1390 since the access handler may be called many times (i.e., for a 1391 @code{PUT}/@code{POST} operation with plenty of upload data) this allows 1392 the application to easily associate some request-specific state; 1393 1394 if necessary, this state can be cleaned up in the global 1395 @code{MHD_RequestCompletedCallback} (which can be set with the 1396 @code{MHD_OPTION_NOTIFY_COMPLETED}). 1397 @end table 1398 @end deftypefn 1399 1400 1401 @deftypefn {Function Pointer} void {*MHD_RequestCompletedCallback} (void *cls, struct MHD_Connectionconnection, void **req_cls, enum MHD_RequestTerminationCode toe) 1402 Signature of the callback used by MHD to notify the application about 1403 completed requests. 1404 1405 @table @var 1406 @item cls 1407 custom value selected at callback registration time; 1408 1409 @item connection 1410 connection handle; 1411 1412 @item req_cls 1413 value as set by the last call to the 1414 @code{MHD_AccessHandlerCallback}; 1415 1416 @item toe 1417 reason for request termination see @code{MHD_OPTION_NOTIFY_COMPLETED}. 1418 @end table 1419 @end deftypefn 1420 1421 1422 @deftypefn {Function Pointer} enum MHD_Result {*MHD_KeyValueIterator} (void *cls, enum MHD_ValueKind kind, const char *key, const char *value, size_t value_size) 1423 Iterator over key-value pairs. This iterator can be used to iterate 1424 over all of the cookies, headers, or @code{POST}-data fields of a 1425 request, and also to iterate over the headers that have been added to a 1426 response. 1427 1428 @table @var 1429 @item cls 1430 custom value specified when iteration was triggered; 1431 1432 @item kind 1433 kind of the header we are looking at 1434 1435 @item key 1436 key for the value, can be an empty string 1437 1438 @item value 1439 value corresponding value, can be NULL 1440 1441 @item value_size 1442 number of bytes in @code{value}. This argument was introduced in 1443 @code{MHD_VERSION} 0x00096301 to allow applications to use binary 1444 zeros in values. Applications using this argument must ensure that 1445 they are using a sufficiently recent version of MHD, i.e. by testing 1446 @code{MHD_get_version()} for values above or equal to 0.9.64. 1447 Applications that do not need zeros in values and that want to compile 1448 without warnings against newer versions of MHD should not declare this 1449 argument and cast the function pointer argument to 1450 @code{MHD_KeyValueIterator}. 1451 1452 @end table 1453 1454 Return @code{MHD_YES} to continue iterating, @code{MHD_NO} to abort the 1455 iteration. 1456 @end deftypefn 1457 1458 1459 @deftypefn {Function Pointer} ssize_t {*MHD_ContentReaderCallback} (void *cls, uint64_t pos, char *buf, size_t max) 1460 Callback used by MHD in order to obtain content. The callback has to 1461 copy at most @var{max} bytes of content into @var{buf}. The total 1462 number of bytes that has been placed into @var{buf} should be returned. 1463 1464 Note that returning zero will cause MHD to try again. 1465 Thus, returning zero should only be used in conjunction 1466 with @code{MHD_suspend_connection()} to avoid busy waiting. 1467 1468 While usually the callback simply returns the number of bytes written 1469 into @var{buf}, there are two special return value: 1470 1471 @code{MHD_CONTENT_READER_END_OF_STREAM} (-1) should be returned 1472 for the regular end of transmission (with chunked encoding, MHD will then 1473 terminate the chunk and send any HTTP footers that might be 1474 present; without chunked encoding and given an unknown 1475 response size, MHD will simply close the connection; note 1476 that while returning @code{MHD_CONTENT_READER_END_OF_STREAM} is not technically 1477 legal if a response size was specified, MHD accepts this 1478 and treats it just as @code{MHD_CONTENT_READER_END_WITH_ERROR}. 1479 1480 @code{MHD_CONTENT_READER_END_WITH_ERROR} (-2) is used to indicate a server 1481 error generating the response; this will cause MHD to simply 1482 close the connection immediately. If a response size was 1483 given or if chunked encoding is in use, this will indicate 1484 an error to the client. Note, however, that if the client 1485 does not know a response size and chunked encoding is not in 1486 use, then clients will not be able to tell the difference between 1487 @code{MHD_CONTENT_READER_END_WITH_ERROR} and 1488 @code{MHD_CONTENT_READER_END_OF_STREAM}. 1489 This is not a limitation of MHD but rather of the HTTP protocol. 1490 1491 @table @var 1492 @item cls 1493 custom value selected at callback registration time; 1494 1495 @item pos 1496 position in the datastream to access; note that if an 1497 @code{MHD_Response} object is re-used, it is possible for the same 1498 content reader to be queried multiple times for the same data; however, 1499 if an @code{MHD_Response} is not re-used, MHD guarantees that 1500 @var{pos} will be the sum of all non-negative return values obtained 1501 from the content reader so far. 1502 @end table 1503 1504 Return @code{-1} on error (MHD will no longer try to read content and 1505 instead close the connection with the client). 1506 @end deftypefn 1507 1508 1509 @deftypefn {Function Pointer} void {*MHD_ContentReaderFreeCallback} (void *cls) 1510 This method is called by MHD if we are done with a content reader. 1511 It should be used to free resources associated with the content reader. 1512 @end deftypefn 1513 1514 1515 @deftypefn {Function Pointer} enum MHD_Result {*MHD_PostDataIterator} (void *cls, enum MHD_ValueKind kind, const char *key, const char *filename, const char *content_type, const char *transfer_encoding, const char *data, uint64_t off, size_t size) 1516 Iterator over key-value pairs where the value maybe made available in 1517 increments and/or may not be zero-terminated. Used for processing 1518 @code{POST} data. 1519 1520 @table @var 1521 @item cls 1522 custom value selected at callback registration time; 1523 1524 @item kind 1525 type of the value; 1526 1527 @item key 1528 zero-terminated key for the value; 1529 1530 @item filename 1531 name of the uploaded file, @code{NULL} if not known; 1532 1533 @item content_type 1534 mime-type of the data, @code{NULL} if not known; 1535 1536 @item transfer_encoding 1537 encoding of the data, @code{NULL} if not known; 1538 1539 @item data 1540 pointer to size bytes of data at the specified offset; 1541 1542 @item off 1543 offset of data in the overall value; 1544 1545 @item size 1546 number of bytes in data available. 1547 @end table 1548 1549 Return @code{MHD_YES} to continue iterating, @code{MHD_NO} to abort the 1550 iteration. 1551 @end deftypefn 1552 1553 1554 @c ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1555 1556 @c ------------------------------------------------------------ 1557 @node microhttpd-init 1558 @chapter Starting and stopping the server 1559 1560 @deftypefun {void} MHD_set_panic_func (MHD_PanicCallback cb, void *cls) 1561 Set a handler for fatal errors. 1562 1563 @table @var 1564 @item cb 1565 function to call if MHD encounters a fatal internal error. If no handler was set explicitly, MHD will call @code{abort}. 1566 1567 @item cls 1568 closure argument for cb; the other arguments are the name of the source file, line number and a string describing the nature of the fatal error (which can be @code{NULL}) 1569 @end table 1570 @end deftypefun 1571 1572 @deftypefun {struct MHD_Daemon *} MHD_start_daemon (unsigned int flags, unsigned short port, MHD_AcceptPolicyCallback apc, void *apc_cls, MHD_AccessHandlerCallback dh, void *dh_cls, ...) 1573 Start a webserver on the given port. 1574 1575 @table @var 1576 @item flags 1577 OR-ed combination of @code{MHD_FLAG} values; 1578 1579 @item port 1580 port to bind to; 1581 1582 @item apc 1583 callback to call to check which clients will be allowed to connect; you 1584 can pass @code{NULL} in which case connections from any @acronym{IP} will be 1585 accepted; 1586 1587 @item apc_cls 1588 extra argument to @var{apc}; 1589 1590 @item dh 1591 default handler for all URIs; 1592 1593 @item dh_cls 1594 extra argument to @var{dh}. 1595 @end table 1596 1597 Additional arguments are a list of options (type-value pairs, 1598 terminated with @code{MHD_OPTION_END}). It is mandatory to use 1599 @code{MHD_OPTION_END} as last argument, even when there are no 1600 additional arguments. 1601 1602 Return @code{NULL} on error, handle to daemon on success. 1603 @end deftypefun 1604 1605 1606 @deftypefun MHD_socket MHD_quiesce_daemon (struct MHD_Daemon *daemon) 1607 @cindex quiesce 1608 Stop accepting connections from the listening socket. Allows clients 1609 to continue processing, but stops accepting new connections. Note 1610 that the caller is responsible for closing the returned socket; 1611 however, if MHD is run using threads (anything but external select 1612 mode), it must not be closed until AFTER @code{MHD_stop_daemon} has 1613 been called (as it is theoretically possible that an existing thread 1614 is still using it). 1615 1616 This function is useful in the special case that a listen socket 1617 is to be migrated to another process (i.e. a newer version of the 1618 HTTP server) while existing connections should continue to be 1619 processed until they are finished. 1620 1621 Return @code{-1} on error (daemon not listening), the handle to the 1622 listen socket otherwise. 1623 1624 @end deftypefun 1625 1626 1627 @deftypefun void MHD_stop_daemon (struct MHD_Daemon *daemon) 1628 Shutdown an HTTP daemon. 1629 @end deftypefun 1630 1631 1632 @deftypefun enum MHD_Result MHD_run (struct MHD_Daemon *daemon) 1633 Run webserver operations (without blocking unless in client callbacks). 1634 This method should be called by clients in combination with 1635 @code{MHD_get_fdset()} if the client-controlled @code{select}-method is used. 1636 @cindex select 1637 @cindex poll 1638 1639 This function will work for external @code{poll} and @code{select} mode. 1640 However, if using external @code{select} mode, you may want to 1641 instead use @code{MHD_run_from_select}, as it is more efficient. 1642 1643 @table @var 1644 @item daemon 1645 daemon to process connections of 1646 @end table 1647 1648 Return @code{MHD_YES} on success, @code{MHD_NO} if this daemon was not 1649 started with the right options for this call. 1650 @end deftypefun 1651 1652 1653 @deftypefun enum MHD_Result MHD_run_from_select (struct MHD_Daemon *daemon, const fd_set *read_fd_set, const fd_set *write_fd_set, const fd_set *except_fd_set) 1654 Run webserver operations given sets of ready socket handles. 1655 @cindex select 1656 1657 This method should be called by clients in combination with 1658 @code{MHD_get_fdset} if the client-controlled (external) 1659 select method is used. 1660 1661 You can use this function instead of @code{MHD_run} if you called 1662 @code{select} on the result from @code{MHD_get_fdset}. File descriptors in 1663 the sets that are not controlled by MHD will be ignored. Calling 1664 this function instead of @code{MHD_run} is more efficient as MHD will 1665 not have to call @code{select} again to determine which operations are 1666 ready. 1667 1668 @table @var 1669 @item daemon 1670 daemon to process connections of 1671 @item read_fd_set 1672 set of descriptors that must be ready for reading without blocking 1673 @item write_fd_set 1674 set of descriptors that must be ready for writing without blocking 1675 @item except_fd_set 1676 ignored, can be NULL 1677 @end table 1678 1679 Return @code{MHD_YES} on success, @code{MHD_NO} on serious internal 1680 errors. 1681 1682 @end deftypefun 1683 1684 1685 1686 @deftypefun void MHD_add_connection (struct MHD_Daemon *daemon, int client_socket, const struct sockaddr *addr, socklen_t addrlen) 1687 Add another client connection to the set of connections 1688 managed by MHD. This API is usually not needed (since 1689 MHD will accept inbound connections on the server socket). 1690 Use this API in special cases, for example if your HTTP 1691 server is behind NAT and needs to connect out to the 1692 HTTP client, or if you are building a proxy. 1693 1694 If you use this API in conjunction with a internal select or a thread 1695 pool, you must set the option @code{MHD_USE_ITC} to 1696 ensure that the freshly added connection is immediately processed by 1697 MHD. 1698 1699 The given client socket will be managed (and closed!) by MHD after 1700 this call and must no longer be used directly by the application 1701 afterwards. 1702 1703 @table @var 1704 @item daemon 1705 daemon that manages the connection 1706 @item client_socket 1707 socket to manage (MHD will expect to receive an HTTP request from this socket next). 1708 @item addr 1709 IP address of the client 1710 @item addrlen 1711 number of bytes in addr 1712 @end table 1713 1714 This function will return @code{MHD_YES} on success, 1715 @code{MHD_NO} if this daemon could 1716 not handle the connection (i.e. malloc failed, etc). 1717 The socket will be closed in any case; 'errno' is set 1718 to indicate further details about the error. 1719 @end deftypefun 1720 1721 1722 @c ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1723 1724 @c ----------------------------------------------------------- 1725 @node microhttpd-inspect 1726 @chapter Implementing external @code{select} 1727 1728 1729 @deftypefun enum MHD_Result MHD_get_fdset (struct MHD_Daemon *daemon, fd_set * read_fd_set, fd_set * write_fd_set, fd_set * except_fd_set, int *max_fd) 1730 Obtain the @code{select()} sets for this daemon. The daemon's socket 1731 is added to @var{read_fd_set}. The list of currently existent 1732 connections is scanned and their file descriptors added to the correct 1733 set. 1734 1735 When calling this function, FD_SETSIZE is assumed to be platform's 1736 default. If you changed FD_SETSIZE for your application, 1737 you should use @code{MHD_get_fdset2()} instead. 1738 1739 This function should only be called in when MHD is configured to use 1740 external select with @code{select()} or with @code{epoll()}. In 1741 the latter case, it will only add the single @code{epoll()} file 1742 descriptor used by MHD to the sets. 1743 1744 After the call completed successfully: the variable referenced by 1745 @var{max_fd} references the file descriptor with highest integer 1746 identifier. The variable must be set to zero before invoking this 1747 function. 1748 1749 Return @code{MHD_YES} on success, @code{MHD_NO} if: the arguments are 1750 invalid (example: @code{NULL} pointers); this daemon was not started with 1751 the right options for this call. 1752 @end deftypefun 1753 1754 1755 @deftypefun enum MHD_Result MHD_get_fdset2 (struct MHD_Daemon *daemon, fd_set * read_fd_set, fd_set * write_fd_set, fd_set * except_fd_set, int *max_fd, unsigned int fd_setsize) 1756 Like @code{MHD_get_fdset()}, except that you can manually specify the value of FD_SETSIZE used by your application. 1757 @end deftypefun 1758 1759 1760 @deftypefun enum MHD_Result MHD_get_timeout (struct MHD_Daemon *daemon, unsigned long long *timeout) 1761 @cindex timeout 1762 Obtain timeout value for select for this daemon (only needed if 1763 connection timeout is used). The returned value is how many 1764 milliseconds @code{select} should at most block, not the timeout value 1765 set for connections. This function must not be called if the 1766 @code{MHD_USE_THREAD_PER_CONNECTION} mode is in use (since then it is 1767 not meaningful to ask for a timeout, after all, there is concurrenct 1768 activity). The function must also not be called by user-code if 1769 @code{MHD_USE_INTERNAL_POLLING_THREAD} is in use. In the latter case, the 1770 behavior is undefined. 1771 1772 @table @var 1773 @item daemon 1774 which daemon to obtain the timeout from. 1775 @item timeout 1776 will be set to the timeout (in milliseconds). 1777 @end table 1778 1779 Return @code{MHD_YES} on success, @code{MHD_NO} if timeouts are not used 1780 (or no connections exist that would necessitate the use of a timeout 1781 right now). 1782 @end deftypefun 1783 1784 1785 @c ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1786 1787 @c ----------------------------------------------------------- 1788 @node microhttpd-requests 1789 @chapter Handling requests 1790 1791 1792 @deftypefun int MHD_get_connection_values (struct MHD_Connection *connection, enum MHD_ValueKind kind, MHD_KeyValueIterator iterator, void *iterator_cls) 1793 Get all the headers matching @var{kind} from the request. The @var{kind} 1794 argument can be a bitmask, ORing the various header kinds that are 1795 requested. 1796 1797 The @var{iterator} callback is invoked once for each header, with 1798 @var{iterator_cls} as first argument. After version 0.9.19, the 1799 headers are iterated in the same order as they were received from 1800 the network; previous versions iterated over the headers in reverse 1801 order. 1802 1803 @code{MHD_get_connection_values} returns the number of entries 1804 iterated over; this can be less than the number of headers if, while 1805 iterating, @var{iterator} returns @code{MHD_NO}. 1806 1807 @var{iterator} can be @code{NULL}: in this case this function just counts 1808 and returns the number of headers. 1809 1810 In the case of @code{MHD_GET_ARGUMENT_KIND}, the @var{value} argument 1811 will be @code{NULL} if the URL contained a key without an equals operator. 1812 For example, for a HTTP request to the URL ``http://foo/bar?key'', the 1813 @var{value} argument is @code{NULL}; in contrast, a HTTP request to the URL 1814 ``http://foo/bar?key='', the @var{value} argument is the empty string. 1815 The normal case is that the URL contains ``http://foo/bar?key=value'' 1816 in which case @var{value} would be the string ``value'' and @var{key} 1817 would contain the string ``key''. 1818 @end deftypefun 1819 1820 1821 @deftypefun enum MHD_Result MHD_set_connection_value (struct MHD_Connection *connection, enum MHD_ValueKind kind, const char *key, const char *value) 1822 This function can be used to append an entry to 1823 the list of HTTP headers of a connection (so that the 1824 @code{MHD_get_connection_values function} will return 1825 them -- and the MHD PostProcessor will also 1826 see them). This maybe required in certain 1827 situations (see Mantis #1399) where (broken) 1828 HTTP implementations fail to supply values needed 1829 by the post processor (or other parts of the 1830 application). 1831 1832 This function MUST only be called from within 1833 the MHD_AccessHandlerCallback (otherwise, access 1834 maybe improperly synchronized). Furthermore, 1835 the client must guarantee that the key and 1836 value arguments are 0-terminated strings that 1837 are NOT freed until the connection is closed. 1838 (The easiest way to do this is by passing only 1839 arguments to permanently allocated strings.). 1840 1841 @var{connection} is the connection for which 1842 the entry for @var{key} of the given @var{kind} 1843 should be set to the given @var{value}. 1844 1845 The function returns @code{MHD_NO} if the operation 1846 could not be performed due to insufficient memory 1847 and @code{MHD_YES} on success. 1848 @end deftypefun 1849 1850 1851 @deftypefun {const char *} MHD_lookup_connection_value (struct MHD_Connection *connection, enum MHD_ValueKind kind, const char *key) 1852 Get a particular header value. If multiple values match the 1853 @var{kind}, return one of them (the ``first'', whatever that means). 1854 @var{key} must reference a zero-terminated ASCII-coded string 1855 representing the header to look for: it is compared against the 1856 headers using (basically) @code{strcasecmp()}, so case is ignored. 1857 @end deftypefun 1858 1859 @deftypefun {const char *} MHD_lookup_connection_value_n (struct MHD_Connection *connection, enum MHD_ValueKind kind, const char *key, size_t key_size, const char **value_ptr, size_t *value_size_ptr) 1860 Get a particular header value. If multiple values match the 1861 @var{kind}, return one of them (the ``first'', whatever that means). 1862 @var{key} must reference an ASCII-coded string 1863 representing the header to look for: it is compared against the 1864 headers using (basically) @code{strncasecmp()}, so case is ignored. 1865 The @var{value_ptr} is set to the address of the value found, 1866 and @var{value_size_ptr} is set to the number of bytes in the 1867 value. 1868 @end deftypefun 1869 1870 1871 @c ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1872 1873 @c ------------------------------------------------------------ 1874 @node microhttpd-responses 1875 @chapter Building responses to requests 1876 1877 1878 @noindent 1879 Response objects handling by MHD is asynchronous with respect to the 1880 application execution flow. Instances of the @code{MHD_Response} 1881 structure are not associated to a daemon and neither to a client 1882 connection: they are managed with reference counting. 1883 1884 In the simplest case: we allocate a new @code{MHD_Response} structure 1885 for each response, we use it once and finally we destroy it. 1886 1887 MHD allows more efficient resources usages. 1888 1889 Example: we allocate a new @code{MHD_Response} structure for each 1890 response @strong{kind}, we use it every time we have to give that 1891 response and we finally destroy it only when the daemon shuts down. 1892 1893 @menu 1894 * microhttpd-response enqueue:: Enqueuing a response. 1895 * microhttpd-response create:: Creating a response object. 1896 * microhttpd-response headers:: Adding headers to a response. 1897 * microhttpd-response options:: Setting response options. 1898 * microhttpd-response inspect:: Inspecting a response object. 1899 * microhttpd-response upgrade:: Creating a response for protocol upgrades. 1900 @end menu 1901 1902 @c ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1903 1904 @c ------------------------------------------------------------ 1905 @node microhttpd-response enqueue 1906 @section Enqueuing a response 1907 1908 1909 @deftypefun enum MHD_Result MHD_queue_response (struct MHD_Connection *connection, unsigned int status_code, struct MHD_Response *response) 1910 Queue a response to be transmitted to the client as soon as possible 1911 but only after MHD_AccessHandlerCallback returns. This function 1912 checks that it is legal to queue a response at this time for the 1913 given connection. It also increments the internal reference 1914 counter for the response object (the counter will be decremented 1915 automatically once the response has been transmitted). 1916 1917 @table @var 1918 @item connection 1919 the connection identifying the client; 1920 1921 @item status_code 1922 HTTP status code (i.e. @code{200} for OK); 1923 1924 @item response 1925 response to transmit. 1926 @end table 1927 1928 Return @code{MHD_YES} on success or if message has been queued. Return 1929 @code{MHD_NO}: if arguments are invalid (example: @code{NULL} pointer); on 1930 error (i.e. reply already sent). 1931 @end deftypefun 1932 1933 1934 @deftypefun void MHD_destroy_response (struct MHD_Response *response) 1935 Destroy a response object and associated resources (decrement the 1936 reference counter). Note that MHD may keep some of the resources 1937 around if the response is still in the queue for some clients, so the 1938 memory may not necessarily be freed immediately. 1939 @end deftypefun 1940 1941 1942 An explanation of reference counting@footnote{Note to readers acquainted 1943 to the Tcl API: reference counting on @code{MHD_Connection} 1944 structures is handled in the same way as Tcl handles @code{Tcl_Obj} 1945 structures through @code{Tcl_IncrRefCount()} and 1946 @code{Tcl_DecrRefCount()}.}: 1947 1948 @enumerate 1949 @item 1950 a @code{MHD_Response} object is allocated: 1951 1952 @example 1953 struct MHD_Response * response = MHD_create_response_from_buffer(...); 1954 /* here: reference counter = 1 */ 1955 @end example 1956 1957 @item 1958 the @code{MHD_Response} object is enqueued in a @code{MHD_Connection}: 1959 1960 @example 1961 MHD_queue_response(connection, , response); 1962 /* here: reference counter = 2 */ 1963 @end example 1964 1965 @item 1966 the creator of the response object discharges responsibility for it: 1967 1968 @example 1969 MHD_destroy_response(response); 1970 /* here: reference counter = 1 */ 1971 @end example 1972 1973 @item 1974 the daemon handles the connection sending the response's data to the 1975 client then decrements the reference counter by calling 1976 @code{MHD_destroy_response()}: the counter's value drops to zero and 1977 the @code{MHD_Response} object is released. 1978 @end enumerate 1979 1980 1981 @c ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1982 1983 @c ------------------------------------------------------------ 1984 @node microhttpd-response create 1985 @section Creating a response object 1986 1987 1988 @deftypefun {struct MHD_Response *} MHD_create_response_from_callback (uint64_t size, size_t block_size, MHD_ContentReaderCallback crc, void *crc_cls, MHD_ContentReaderFreeCallback crfc) 1989 Create a response object. The response object can be extended with 1990 header information and then it can be used any number of times. 1991 1992 @table @var 1993 @item size 1994 size of the data portion of the response, @code{-1} for unknown; 1995 1996 @item block_size 1997 preferred block size for querying @var{crc} (advisory only, MHD may 1998 still call @var{crc} using smaller chunks); this is essentially the 1999 buffer size used for @acronym{IO}, clients should pick a value that is 2000 appropriate for @acronym{IO} and memory performance requirements; 2001 2002 @item crc 2003 callback to use to obtain response data; 2004 2005 @item crc_cls 2006 extra argument to @var{crc}; 2007 2008 @item crfc 2009 callback to call to free @var{crc_cls} resources. 2010 @end table 2011 2012 Return @code{NULL} on error (i.e. invalid arguments, out of memory). 2013 @end deftypefun 2014 2015 2016 2017 @deftypefun {struct MHD_Response *} MHD_create_response_from_fd (uint64_t size, int fd) 2018 Create a response object. The response object can be extended with 2019 header information and then it can be used any number of times. 2020 2021 @table @var 2022 @item size 2023 size of the data portion of the response (should be smaller or equal to the 2024 size of the file) 2025 2026 @item fd 2027 file descriptor referring to a file on disk with the data; will be 2028 closed when response is destroyed; note that 'fd' must be an actual 2029 file descriptor (not a pipe or socket) since MHD might use 'sendfile' 2030 or 'seek' on it. The descriptor should be in blocking-IO mode. 2031 @end table 2032 2033 Return @code{NULL} on error (i.e. invalid arguments, out of memory). 2034 @end deftypefun 2035 2036 2037 @deftypefun {struct MHD_Response *} MHD_create_response_from_pipe (int fd) 2038 Create a response object. The response object can be extended with 2039 header information and then it can be used ONLY ONCE. 2040 2041 @table @var 2042 @item fd 2043 file descriptor of the read-end of the pipe; will be 2044 closed when response is destroyed. 2045 The descriptor should be in blocking-IO mode. 2046 @end table 2047 2048 Return @code{NULL} on error (i.e. out of memory). 2049 @end deftypefun 2050 2051 2052 @deftypefun {struct MHD_Response *} MHD_create_response_from_fd_at_offset (size_t size, int fd, off_t offset) 2053 Create a response object. The response object can be extended with 2054 header information and then it can be used any number of times. 2055 Note that you need to be a bit careful about @code{off_t} when 2056 writing this code. Depending on your platform, MHD is likely 2057 to have been compiled with support for 64-bit files. When you 2058 compile your own application, you must make sure that @code{off_t} 2059 is also a 64-bit value. If not, your compiler may pass a 32-bit 2060 value as @code{off_t}, which will result in 32-bits of garbage. 2061 2062 If you use the autotools, use the @code{AC_SYS_LARGEFILE} autoconf 2063 macro and make sure to include the generated @file{config.h} file 2064 before @file{microhttpd.h} to avoid problems. If you do not have a 2065 build system and only want to run on a GNU/Linux system, you could 2066 also use 2067 @verbatim 2068 #define _FILE_OFFSET_BITS 64 2069 #include <sys/types.h> 2070 #include <sys/stat.h> 2071 #include <fcntl.h> 2072 #include <microhttpd.h> 2073 @end verbatim 2074 to ensure 64-bit @code{off_t}. Note that if your operating system 2075 does not support 64-bit files, MHD will be compiled with a 32-bit 2076 @code{off_t} (in which case the above would be wrong). 2077 2078 @table @var 2079 @item size 2080 size of the data portion of the response (number of bytes to transmit from the 2081 file starting at offset). 2082 2083 @item fd 2084 file descriptor referring to a file on disk with the data; will be 2085 closed when response is destroyed; note that 'fd' must be an actual 2086 file descriptor (not a pipe or socket) since MHD might use 'sendfile' 2087 or 'seek' on it. The descriptor should be in blocking-IO mode. 2088 2089 @item offset 2090 offset to start reading from in the file 2091 @end table 2092 2093 Return @code{NULL} on error (i.e. invalid arguments, out of memory). 2094 @end deftypefun 2095 2096 2097 @deftypefun {struct MHD_Response *} MHD_create_response_from_buffer (size_t size, void *data, enum MHD_ResponseMemoryMode mode) 2098 Create a response object. The response object can be extended with 2099 header information and then it can be used any number of times. 2100 2101 @table @var 2102 @item size 2103 size of the data portion of the response; 2104 2105 @item buffer 2106 the data itself; 2107 2108 @item mode 2109 memory management options for buffer; use 2110 MHD_RESPMEM_PERSISTENT if the buffer is static/global memory, 2111 use MHD_RESPMEM_MUST_FREE if the buffer is heap-allocated and 2112 should be freed by MHD and MHD_RESPMEM_MUST_COPY if the 2113 buffer is in transient memory (i.e. on the stack) and must 2114 be copied by MHD; 2115 @end table 2116 2117 Return @code{NULL} on error (i.e. invalid arguments, out of memory). 2118 @end deftypefun 2119 2120 2121 @deftypefun {struct MHD_Response *} MHD_create_response_from_buffer_with_free_callback (size_t size, void *data, MHD_ContentReaderFreeCallback crfc) 2122 Create a response object. The buffer at the end must be free'd 2123 by calling the @var{crfc} function. 2124 2125 @table @var 2126 @item size 2127 size of the data portion of the response; 2128 2129 @item buffer 2130 the data itself; 2131 2132 @item crfc 2133 function to call at the end to free memory allocated at @var{buffer}. 2134 @end table 2135 2136 Return @code{NULL} on error (i.e. invalid arguments, out of memory). 2137 @end deftypefun 2138 2139 @deftypefun {struct MHD_Response *} MHD_create_response_from_data (size_t size, void *data, int must_free, int must_copy) 2140 Create a response object. The response object can be extended with 2141 header information and then it can be used any number of times. 2142 This function is deprecated, use @code{MHD_create_response_from_buffer} instead. 2143 2144 @table @var 2145 @item size 2146 size of the data portion of the response; 2147 2148 @item data 2149 the data itself; 2150 2151 @item must_free 2152 if true: MHD should free data when done; 2153 2154 @item must_copy 2155 if true: MHD allocates a block of memory and use it to make a copy of 2156 @var{data} embedded in the returned @code{MHD_Response} structure; 2157 handling of the embedded memory is responsibility of MHD; @var{data} 2158 can be released anytime after this call returns. 2159 @end table 2160 2161 Return @code{NULL} on error (i.e. invalid arguments, out of memory). 2162 @end deftypefun 2163 2164 2165 Example: create a response from a statically allocated string: 2166 2167 @example 2168 const char * data = "<html><body><p>Error!</p></body></html>"; 2169 2170 struct MHD_Connection * connection = ...; 2171 struct MHD_Response * response; 2172 2173 response = MHD_create_response_from_buffer (strlen(data), data, 2174 MHD_RESPMEM_PERSISTENT); 2175 MHD_queue_response(connection, 404, response); 2176 MHD_destroy_response(response); 2177 @end example 2178 2179 2180 @deftypefun {struct MHD_Response *} MHD_create_response_from_iovec (const struct MHD_IoVec *iov, int iovcnt, MHD_ContentReaderFreeCallback crfc, void *cls) 2181 Create a response object from an array of memory buffers. 2182 The response object can be extended with header information and then be used 2183 any number of times. 2184 @table @var 2185 @item iov 2186 the array for response data buffers, an internal copy of this will be made; however, note that the data pointed to by the @var{iov} is not copied and must be preserved unchanged at the given locations until the response is no longer in use and the @var{crfc} is called; 2187 2188 @item iovcnt 2189 the number of elements in @var{iov}; 2190 2191 @item crfc 2192 the callback to call to free resources associated with @var{iov}; 2193 2194 @item cls 2195 the argument to @var{crfc}; 2196 @end table 2197 2198 Return @code{NULL} on error (i.e. invalid arguments, out of memory). 2199 @end deftypefun 2200 2201 2202 2203 @c ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2204 2205 @c ------------------------------------------------------------ 2206 @node microhttpd-response headers 2207 @section Adding headers to a response 2208 2209 2210 @deftypefun enum MHD_Result MHD_add_response_header (struct MHD_Response *response, const char *header, const char *content) 2211 Add a header line to the response. The strings referenced by 2212 @var{header} and @var{content} must be zero-terminated and they are 2213 duplicated into memory blocks embedded in @var{response}. 2214 2215 Notice that the strings must not hold newlines, carriage returns or tab 2216 chars. 2217 2218 MHD_add_response_header() prevents applications from setting a 2219 ``Transfer-Encoding'' header to values other than ``identity'' or 2220 ``chunked'' as other transfer encodings are not supported by MHD. Note 2221 that usually MHD will pick the transfer encoding correctly 2222 automatically, but applications can use the header to force a 2223 particular behavior. 2224 2225 MHD_add_response_header() also prevents applications from setting a 2226 ``Content-Length'' header. MHD will automatically set a correct 2227 ``Content-Length'' header if it is possible and allowed. 2228 2229 Return @code{MHD_NO} on error (i.e. invalid header or content format or 2230 memory allocation error). 2231 @end deftypefun 2232 2233 2234 @deftypefun enum MHD_Result MHD_add_response_footer (struct MHD_Response *response, const char *footer, const char *content) 2235 Add a footer line to the response. The strings referenced by 2236 @var{footer} and @var{content} must be zero-terminated and they are 2237 duplicated into memory blocks embedded in @var{response}. 2238 2239 Notice that the strings must not hold newlines, carriage returns or tab 2240 chars. You can add response footers at any time before signalling the 2241 end of the response to MHD (not just before calling 'MHD_queue_response'). 2242 Footers are useful for adding cryptographic checksums to the reply or to 2243 signal errors encountered during data generation. This call was introduced 2244 in MHD 0.9.3. 2245 2246 Return @code{MHD_NO} on error (i.e. invalid header or content format or 2247 memory allocation error). 2248 @end deftypefun 2249 2250 2251 2252 @deftypefun enum MHD_Result MHD_del_response_header (struct MHD_Response *response, const char *header, const char *content) 2253 Delete a header (or footer) line from the response. Return @code{MHD_NO} on error 2254 (arguments are invalid or no such header known). 2255 @end deftypefun 2256 2257 2258 @c ------------------------------------------------------------ 2259 @node microhttpd-response options 2260 @section Setting response options 2261 2262 2263 @deftypefun enum MHD_Result MHD_set_response_options (struct MHD_Response *response, enum MHD_ResponseFlags flags, ...) 2264 Set special flags and options for a response. 2265 2266 Calling this functions sets the given flags and options for the response. 2267 2268 @table @var 2269 @item response 2270 which response should be modified; 2271 2272 @item flags 2273 flags to set for the response; 2274 2275 @end table 2276 2277 Additional arguments are a list of options (type-value pairs, 2278 terminated with @code{MHD_RO_END}). It is mandatory to use 2279 @code{MHD_RO_END} as last argument, even when there are no 2280 additional arguments. 2281 2282 Return @code{MHD_NO} on error, @code{MHD_YES} on success. 2283 @end deftypefun 2284 2285 2286 @c ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2287 2288 @c ------------------------------------------------------------ 2289 @node microhttpd-response inspect 2290 @section Inspecting a response object 2291 2292 2293 @deftypefun int MHD_get_response_headers (struct MHD_Response *response, MHD_KeyValueIterator iterator, void *iterator_cls) 2294 Get all of the headers added to a response. 2295 2296 Invoke the @var{iterator} callback for each header in the response, 2297 using @var{iterator_cls} as first argument. Return number of entries 2298 iterated over. @var{iterator} can be @code{NULL}: in this case the function 2299 just counts headers. 2300 2301 @var{iterator} should not modify the its key and value arguments, unless 2302 we know what we are doing. 2303 @end deftypefun 2304 2305 2306 @deftypefun {const char *} MHD_get_response_header (struct MHD_Response *response, const char *key) 2307 Find and return a pointer to the value of a particular header from the 2308 response. @var{key} must reference a zero-terminated string 2309 representing the header to look for. The search is case sensitive. 2310 Return @code{NULL} if header does not exist or @var{key} is @code{NULL}. 2311 2312 We should not modify the value, unless we know what we are doing. 2313 @end deftypefun 2314 2315 2316 @c ------------------------------------------------------------ 2317 @node microhttpd-response upgrade 2318 @section Creating a response for protocol upgrades 2319 @cindex WebSockets 2320 @cindex Upgrade 2321 @cindex HTTP2 2322 @cindex RFC2817 2323 2324 With RFC 2817 a mechanism to switch protocols within HTTP was 2325 introduced. Here, a client sends a request with a ``Connection: 2326 Upgrade'' header. The server responds with a ``101 Switching 2327 Protocols'' response header, after which the two parties begin to 2328 speak a different (non-HTTP) protocol over the TCP connection. 2329 2330 This mechanism is used for upgrading HTTP 1.1 connections to HTTP2 or 2331 HTTPS, as well as for implementing WebSockets. Which protocol 2332 upgrade is performed is negotiated between server and client in 2333 additional headers, in particular the ``Upgrade'' header. 2334 2335 MHD supports switching protocols using this mechanism only if the 2336 @code{MHD_ALLOW_SUSPEND_RESUME} flag has been set when starting 2337 the daemon. If this flag has been set, applications can upgrade 2338 a connection by queueing a response (using the 2339 @code{MHD_HTTP_SWITCHING_PROTOCOLS} status code) which must 2340 have been created with the following function: 2341 2342 2343 @deftypefun enum MHD_Result MHD_create_response_for_upgrade (MHD_UpgradeHandler upgrade_handler, void *upgrade_handler_cls) 2344 Create a response suitable for switching protocols. Returns @code{MHD_YES} on success. @code{upgrade_handler} must not be @code{NULL}. 2345 2346 When creating this type of response, the ``Connection: Upgrade'' 2347 header will be set automatically for you. MHD requires that you 2348 additionally set an ``Upgrade:'' header. The ``Upgrade'' header 2349 must simply exist, the specific value is completely up to the 2350 application. 2351 2352 @end deftypefun 2353 2354 The @code{upgrade_handler} argument to the above has the following type: 2355 2356 2357 @deftypefn {Function Pointer} void {*MHD_UpgradeHandler} (void *cls, struct MHD_Connection *connection, const char *extra_in, size_t extra_in_size, MHD_socket sock, struct MHD_UpgradeResponseHandle *urh) 2358 This function will be called once MHD has transmitted the header of the response to the connection that is being upgraded. At this point, the application is expected to take over the socket @code{sock} and speak the non-HTTP protocol to which the connection was upgraded. MHD will no longer use the socket; this includes handling timeouts. The application must call @code{MHD_upgrade_action} with an upgrade action of @code{MHD_UPGRADE_ACTION_CLOSE} when it is done processing the connection to close the socket. The application must not call @code{MHD_stop_daemon} on the respective daemon as long as it is still handling the connection. The arguments given to the @code{upgrade_handler} have the following meaning: 2359 2360 @table @var 2361 @item cls 2362 matches the @code{upgrade_handler_cls} that was given to @code{MHD_create_response_for_upgrade} 2363 @item connection 2364 identifies the connection that is being upgraded; 2365 2366 @item req_cls 2367 last value left in `*req_cls` in the `MHD_AccessHandlerCallback` 2368 2369 @item extra_in 2370 buffer of bytes MHD read ``by accident'' from the socket already. This can happen if the client eagerly transmits more than just the HTTP request. The application should treat these as if it had read them from the socket. 2371 2372 @item extra_in_size 2373 number of bytes in @code{extra_in} 2374 2375 @item sock 2376 the socket which the application can now use directly for some bi-directional communication with the client. The application can henceforth use @code{recv()} and @code{send()} or @code{read()} and @code{write()} system calls on the socket. However, @code{ioctl()} and @code{setsockopt()} functions will not work as expected when using HTTPS. Such operations may be supported in the future via @code{MHD_upgrade_action}. Most importantly, the application must never call @code{close()} on this socket. Closing the socket must be done using @code{MHD_upgrade_action}. However, while close is forbidden, the application may call @code{shutdown()} on the socket. 2377 2378 @item urh 2379 argument for calls to @code{MHD_upgrade_action}. Applications must eventually use this function to perform the @code{close()} action on the socket. 2380 @end table 2381 2382 @end deftypefn 2383 2384 @deftypefun enum MHD_Result MHD_upgrade_action (struct MHD_UpgradeResponseHandle *urh, enum MHD_UpgradeAction action, ...) 2385 Perform special operations related to upgraded connections. 2386 2387 @table @var 2388 @item urh 2389 identifies the upgraded connection to perform an action on 2390 2391 @item action 2392 specifies the action to perform; further arguments to the function depend on the specifics of the action. 2393 @end table 2394 2395 @end deftypefun 2396 2397 2398 @deftp {Enumeration} MHD_UpgradeAction 2399 Set of actions to be performed on upgraded connections. Passed as an argument to 2400 @code{MHD_upgrade_action()}. 2401 2402 @table @code 2403 @item MHD_UPGRADE_ACTION_CLOSE 2404 Closes the connection. Must be called once the application is done with the client. Takes no additional arguments. 2405 @item MHD_UPGRADE_ACTION_CORK_ON 2406 Enable corking on the underlying socket. 2407 @item MHD_UPGRADE_ACTION_CORK_OFF 2408 Disable corking on the underlying socket. 2409 2410 @end table 2411 @end deftp 2412 2413 2414 @c ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2415 2416 @c ------------------------------------------------------------ 2417 @node microhttpd-flow 2418 @chapter Flow control. 2419 2420 @noindent 2421 Sometimes it may be possible that clients upload data faster 2422 than an application can process it, or that an application 2423 needs an extended period of time to generate a response. 2424 If @code{MHD_USE_THREAD_PER_CONNECTION} is used, applications 2425 can simply deal with this by performing their logic within the 2426 thread and thus effectively blocking connection processing 2427 by MHD. In all other modes, blocking logic must not be 2428 placed within the callbacks invoked by MHD as this would also 2429 block processing of other requests, as a single thread may be 2430 responsible for tens of thousands of connections. 2431 2432 Instead, applications using thread modes other than 2433 @code{MHD_USE_THREAD_PER_CONNECTION} should use the 2434 following functions to perform flow control. 2435 2436 @deftypefun enum MHD_Result MHD_suspend_connection (struct MHD_Connection *connection) 2437 Suspend handling of network data for a given connection. This can 2438 be used to dequeue a connection from MHD's event loop (external 2439 select, internal select or thread pool; not applicable to 2440 thread-per-connection!) for a while. 2441 2442 If you use this API in conjunction with a internal select or a 2443 thread pool, you must set the option @code{MHD_ALLOW_SUSPEND_RESUME} to 2444 ensure that a resumed connection is immediately processed by MHD. 2445 2446 Suspended connections continue to count against the total number of 2447 connections allowed (per daemon, as well as per IP, if such limits 2448 are set). Suspended connections will NOT time out; timeouts will 2449 restart when the connection handling is resumed. While a 2450 connection is suspended, MHD will not detect disconnects by the 2451 client. 2452 2453 The only safe time to suspend a connection is from the 2454 @code{MHD_AccessHandlerCallback} or from the respective 2455 @code{MHD_ContentReaderCallback} (but in this case the 2456 response object must not be shared among multiple 2457 connections). 2458 2459 When suspending from the @code{MHD_AccessHandlerCallback} 2460 you MUST afterwards return @code{MHD_YES} from the access handler 2461 callback (as MHD_NO would imply to both close and suspend 2462 the connection, which is not allowed). 2463 2464 Finally, it is an API violation to call @code{MHD_stop_daemon} while 2465 having suspended connections (this will at least create memory and 2466 socket leaks or lead to undefined behavior). You must explicitly 2467 resume all connections before stopping the daemon. 2468 2469 @table @var 2470 @item connection 2471 the connection to suspend 2472 @end table 2473 @end deftypefun 2474 2475 @deftypefun enum MHD_Result MHD_resume_connection (struct MHD_Connection *connection) 2476 Resume handling of network data for suspended connection. It is safe 2477 to resume a suspended connection at any time. Calling this function 2478 on a connection that was not previously suspended will result in 2479 undefined behavior. 2480 2481 If you are using this function in ``external'' select mode, you must 2482 make sure to run @code{MHD_run} afterwards (before again calling 2483 @code{MHD_get_fdset}), as otherwise the change may not be reflected in 2484 the set returned by @code{MHD_get_fdset} and you may end up with a 2485 connection that is stuck until the next network activity. 2486 2487 This function may be called from any thread, which is what makes it 2488 usable to hand work to threads of your own. In ``external'' select 2489 mode it writes to the inter-thread communication channel that 2490 @code{MHD_ALLOW_SUSPEND_RESUME} sets up, and since 2491 @code{MHD_get_fdset} adds the reading end of that channel to the read 2492 set, a call from another thread interrupts a @code{select} that your 2493 application is blocked in. That matters because 2494 @code{MHD_get_timeout} reports no timeout at all while every 2495 connection is suspended, so your application would otherwise block 2496 indefinitely. The channel is level triggered, so a resume issued 2497 between @code{MHD_get_fdset} and @code{select} cannot be lost. 2498 2499 You can check whether a connection is currently suspended using 2500 @code{MHD_get_connection_info} by querying for 2501 @code{MHD_CONNECTION_INFO_CONNECTION_SUSPENDED}. 2502 2503 A worked example of suspending connections while worker threads 2504 produce the answers, driven by an external @code{select} loop, is 2505 given in the chapter ``Answering from another thread'' of the MHD 2506 tutorial. 2507 2508 @table @var 2509 @item connection 2510 the connection to resume 2511 @end table 2512 @end deftypefun 2513 2514 2515 @c ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2516 2517 @c ------------------------------------------------------------ 2518 @node microhttpd-dauth 2519 @chapter Utilizing Authentication 2520 2521 @noindent 2522 MHD support three types of client authentication. 2523 2524 Basic authentication uses a simple authentication method based 2525 on BASE64 algorithm. Username and password are exchanged in clear 2526 between the client and the server, so this method must only be used 2527 for non-sensitive content or when the session is protected with https. 2528 When using basic authentication MHD will have access to the clear 2529 password, possibly allowing to create a chained authentication 2530 toward an external authentication server. 2531 2532 Digest authentication uses a one-way authentication method based 2533 on MD5 hash algorithm. Only the hash will transit over the network, 2534 hence protecting the user password. The nonce will prevent replay 2535 attacks. This method is appropriate for general use, especially 2536 when https is not used to encrypt the session. 2537 2538 Client certificate authentication uses a X.509 certificate from 2539 the client. This is the strongest authentication mechanism but it 2540 requires the use of HTTPS. Client certificate authentication can 2541 be used simultaneously with Basic or Digest Authentication in order 2542 to provide a two levels authentication (like for instance separate 2543 machine and user authentication). A code example for using 2544 client certificates is presented in the MHD tutorial. 2545 2546 @menu 2547 * microhttpd-dauth basic:: Using Basic Authentication. 2548 * microhttpd-dauth digest:: Using Digest Authentication. 2549 @end menu 2550 2551 @c ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2552 2553 @c ------------------------------------------------------------ 2554 @node microhttpd-dauth basic 2555 @section Using Basic Authentication 2556 2557 @deftypefun {void} MHD_free (void *ptr) 2558 Free the memory given at @code{ptr}. Used to free data structures allocated by MHD. Calls @code{free(ptr)}. 2559 @end deftypefun 2560 2561 @deftypefun {char *} MHD_basic_auth_get_username_password3 (struct MHD_Connection *connection) 2562 Get the username and password from the basic authorization header sent by the client. 2563 Return @code{NULL} if no Basic Authorization header set by the client or if Base64 2564 encoding is invalid; a pointer to the structure with username and password 2565 if found values set by the client. 2566 If returned value is not @code{NULL}, the value must be @code{MHD_free()}'ed. 2567 @end deftypefun 2568 2569 @deftypefun {enum MHD_Result} MHD_queue_basic_auth_fail_response3 (struct MHD_Connection *connection, const char *realm, int prefer_utf8, struct MHD_Response *response) 2570 Queues a response to request basic authentication from the client. 2571 Return @code{MHD_YES} if successful, otherwise @code{MHD_NO}. 2572 2573 @var{realm} must reference to a zero-terminated string representing the realm. 2574 2575 @var{prefer_utf8} if set to @code{MHD_YES} then parameter @code{charset} with value 2576 @code{UTF-8} will be added to the response authentication header which indicates 2577 that UTF-8 encoding is preferred for username and password. 2578 2579 @var{response} a response structure to specify what shall be presented to the 2580 client with a 401 HTTP status. 2581 @end deftypefun 2582 2583 @c ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2584 2585 @c ------------------------------------------------------------ 2586 @node microhttpd-dauth digest 2587 @section Using Digest Authentication 2588 2589 MHD supports MD5 (deprecated by IETF) and SHA-256 hash algorithms 2590 for digest authentication. The @code{MHD_DigestAuthAlgorithm} enumeration 2591 is used to specify which algorithm should be used. 2592 2593 @deftp {Enumeration} MHD_DigestAuthAlgorithm 2594 Which digest algorithm should be used. Must be used consistently. 2595 2596 @table @code 2597 @item MHD_DIGEST_ALG_AUTO 2598 Have MHD pick an algorithm currently considered secure. For now defaults to SHA-256. 2599 2600 @item MHD_DIGEST_ALG_MD5 2601 Force use of (deprecated, ancient, insecure) MD5. 2602 2603 @item MHD_DIGEST_ALG_SHA256 2604 Force use of SHA-256. 2605 2606 @end table 2607 @end deftp 2608 2609 @deftp {Enumeration} MHD_DigestAuthResult 2610 The result of digest authentication of the client. 2611 2612 @table @code 2613 @item MHD_DAUTH_OK 2614 Authentication OK. 2615 2616 @item MHD_DAUTH_ERROR 2617 General error, like ``out of memory''. 2618 2619 @item MHD_DAUTH_WRONG_HEADER 2620 No ``Authorization'' header or wrong format of the header. 2621 2622 @item MHD_DAUTH_WRONG_USERNAME 2623 Wrong ``username''. 2624 2625 @item MHD_DAUTH_WRONG_REALM 2626 Wrong ``realm''. 2627 2628 @item MHD_DAUTH_WRONG_URI 2629 Wrong ``URI'' (or URI parameters). 2630 2631 @item MHD_DAUTH_NONCE_STALE 2632 The ``nonce'' is too old. Suggest the client to retry with the same username and 2633 password to get the fresh ``nonce''. 2634 The validity of the ``nonce'' may not be checked. 2635 2636 @item MHD_DAUTH_NONCE_WRONG 2637 The ``nonce'' is wrong. May indicate an attack attempt. 2638 2639 @item MHD_DAUTH_RESPONSE_WRONG 2640 The ``response'' is wrong. May indicate an attack attempt. 2641 2642 @end table 2643 @end deftp 2644 2645 2646 @deftypefun {char *} MHD_digest_auth_get_username (struct MHD_Connection *connection) 2647 Find and return a pointer to the username value from the request header. 2648 Return @code{NULL} if the value is not found or header does not exist. 2649 If returned value is not @code{NULL}, the value must be @code{MHD_free()}'ed. 2650 @end deftypefun 2651 2652 @deftypefun enum MHD_DigestAuthResult MHD_digest_auth_check3 (struct MHD_Connection *connection, const char *realm, const char *username, const char *password, unsigned int nonce_timeout, enum MHD_DigestAuthAlgorithm algo) 2653 Checks if the provided values in the WWW-Authenticate header are valid 2654 and sound according to RFC7616. If valid return @code{MHD_DAUTH_OK}, otherwise return the error code. 2655 2656 @var{realm} must reference to a zero-terminated string representing the realm. 2657 2658 @var{username} must reference to a zero-terminated string representing the username, 2659 it is usually the returned value from MHD_digest_auth_get_username. 2660 2661 @var{password} must reference to a zero-terminated string representing the password, 2662 most probably it will be the result of a lookup of the username against a local database. 2663 2664 @var{nonce_timeout} the nonce validity duration in seconds. 2665 Most of the time it is sound to specify 300 seconds as its values. 2666 2667 @var{algo} which digest algorithm should we use. 2668 @end deftypefun 2669 2670 @deftypefun int MHD_digest_auth_check2 (struct MHD_Connection *connection, const char *realm, const char *username, const char *password, unsigned int nonce_timeout, enum MHD_DigestAuthAlgorithm algo) 2671 Checks if the provided values in the WWW-Authenticate header are valid 2672 and sound according to RFC2716. If valid return @code{MHD_YES}, otherwise return @code{MHD_NO}. 2673 2674 @var{realm} must reference to a zero-terminated string representing the realm. 2675 2676 @var{username} must reference to a zero-terminated string representing the username, 2677 it is usually the returned value from MHD_digest_auth_get_username. 2678 2679 @var{password} must reference to a zero-terminated string representing the password, 2680 most probably it will be the result of a lookup of the username against a local database. 2681 2682 @var{nonce_timeout} is the amount of time in seconds for a nonce to be invalid. 2683 Most of the time it is sound to specify 300 seconds as its values. 2684 2685 @var{algo} which digest algorithm should we use. 2686 @end deftypefun 2687 2688 2689 @deftypefun int MHD_digest_auth_check (struct MHD_Connection *connection, const char *realm, const char *username, const char *password, unsigned int nonce_timeout) 2690 Checks if the provided values in the WWW-Authenticate header are valid 2691 and sound according to RFC2716. If valid return @code{MHD_YES}, otherwise return @code{MHD_NO}. 2692 Deprecated, use @code{MHD_digest_auth_check2} instead. 2693 2694 2695 @var{realm} must reference to a zero-terminated string representing the realm. 2696 2697 @var{username} must reference to a zero-terminated string representing the username, 2698 it is usually the returned value from MHD_digest_auth_get_username. 2699 2700 @var{password} must reference to a zero-terminated string representing the password, 2701 most probably it will be the result of a lookup of the username against a local database. 2702 2703 @var{nonce_timeout} is the amount of time in seconds for a nonce to be invalid. 2704 Most of the time it is sound to specify 300 seconds as its values. 2705 @end deftypefun 2706 2707 2708 2709 @deftypefun enum MHD_DigestAuthResult MHD_digest_auth_check_digest3 (struct MHD_Connection *connection, const char *realm, const char *username, const uint8_t *digest, unsigned int nonce_timeout, enum MHD_DigestAuthAlgorithm algo) 2710 Checks if the provided values in the WWW-Authenticate header are valid 2711 and sound according to RFC7616. If valid return @code{MHD_DAUTH_OK}, otherwise return the error code. 2712 2713 @var{realm} must reference to a zero-terminated string representing the realm. 2714 2715 @var{username} must reference to a zero-terminated string representing the username, 2716 it is usually the returned value from MHD_digest_auth_get_username. 2717 2718 @var{digest} the pointer to the binary digest for the precalculated hash value ``username:realm:password'' with specified @var{algo}. 2719 2720 @var{digest_size} the number of bytes in @var{digest} (the size must match @var{algo}!) 2721 2722 @var{nonce_timeout} the nonce validity duration in seconds. 2723 Most of the time it is sound to specify 300 seconds as its values. 2724 2725 @var{algo} digest authentication algorithm to use. 2726 @end deftypefun 2727 2728 @deftypefun int MHD_digest_auth_check_digest2 (struct MHD_Connection *connection, const char *realm, const char *username, const uint8_t *digest, unsigned int nonce_timeout, enum MHD_DigestAuthAlgorithm algo) 2729 Checks if the provided values in the WWW-Authenticate header are valid 2730 and sound according to RFC2716. If valid return @code{MHD_YES}, otherwise return @code{MHD_NO}. 2731 2732 @var{realm} must reference to a zero-terminated string representing the realm. 2733 2734 @var{username} must reference to a zero-terminated string representing the username, 2735 it is usually the returned value from MHD_digest_auth_get_username. 2736 2737 @var{digest} pointer to the binary MD5 sum for the precalculated hash value ``userame:realm:password''. The size must match the selected @var{algo}! 2738 2739 @var{nonce_timeout} is the amount of time in seconds for a nonce to be invalid. 2740 Most of the time it is sound to specify 300 seconds as its values. 2741 2742 @var{algo} digest authentication algorithm to use. 2743 @end deftypefun 2744 2745 @deftypefun int MHD_digest_auth_check_digest (struct MHD_Connection *connection, const char *realm, const char *username, const unsigned char digest[MHD_MD5_DIGEST_SIZE], unsigned int nonce_timeout) 2746 Checks if the provided values in the WWW-Authenticate header are valid 2747 and sound according to RFC2716. If valid return @code{MHD_YES}, otherwise return @code{MHD_NO}. 2748 Deprecated, use @code{MHD_digest_auth_check_digest2} instead. 2749 2750 @var{realm} must reference to a zero-terminated string representing the realm. 2751 2752 @var{username} must reference to a zero-terminated string representing the username, 2753 it is usually the returned value from MHD_digest_auth_get_username. 2754 2755 @var{digest} pointer to the binary MD5 sum for the precalculated hash value ``userame:realm:password'' of @code{MHD_MD5_DIGEST_SIZE} bytes. 2756 2757 @var{nonce_timeout} is the amount of time in seconds for a nonce to be invalid. 2758 Most of the time it is sound to specify 300 seconds as its values. 2759 @end deftypefun 2760 2761 2762 @deftypefun enum MHD_Result MHD_queue_auth_fail_response2 (struct MHD_Connection *connection, const char *realm, const char *opaque, struct MHD_Response *response, int signal_stale, enum MHD_DigestAuthAlgorithm algo) 2763 Queues a response to request authentication from the client, 2764 return @code{MHD_YES} if successful, otherwise @code{MHD_NO}. 2765 2766 @var{realm} must reference to a zero-terminated string representing the realm. 2767 2768 @var{opaque} must reference to a zero-terminated string representing a value 2769 that gets passed to the client and expected to be passed again to the server 2770 as-is. This value can be a hexadecimal or base64 string. 2771 2772 @var{response} a response structure to specify what shall be presented to the 2773 client with a 401 HTTP status. 2774 2775 @var{signal_stale} a value that signals "stale=true" in the response header to 2776 indicate the invalidity of the nonce and no need to ask for authentication 2777 parameters and only a new nonce gets generated. @code{MHD_YES} to generate a new 2778 nonce, @code{MHD_NO} to ask for authentication parameters. 2779 2780 @var{algo} which digest algorithm should we use. The same algorithm 2781 must then be selected when checking digests received from clients! 2782 2783 @end deftypefun 2784 2785 2786 @deftypefun enum MHD_Result MHD_queue_auth_fail_response (struct MHD_Connection *connection, const char *realm, const char *opaque, struct MHD_Response *response, int signal_stale) 2787 Queues a response to request authentication from the client, 2788 return @code{MHD_YES} if successful, otherwise @code{MHD_NO}. 2789 2790 @var{realm} must reference to a zero-terminated string representing the realm. 2791 2792 @var{opaque} must reference to a zero-terminated string representing a value 2793 that gets passed to the client and expected to be passed again to the server 2794 as-is. This value can be a hexadecimal or base64 string. 2795 2796 @var{response} a response structure to specify what shall be presented to the 2797 client with a 401 HTTP status. 2798 2799 @var{signal_stale} a value that signals "stale=true" in the response header to 2800 indicate the invalidity of the nonce and no need to ask for authentication 2801 parameters and only a new nonce gets generated. @code{MHD_YES} to generate a new 2802 nonce, @code{MHD_NO} to ask for authentication parameters. 2803 @end deftypefun 2804 2805 Example: handling digest authentication requests and responses. 2806 2807 @example 2808 #define PAGE "<html><head><title>libmicrohttpd demo</title></head><body>Access granted</body></html>" 2809 #define DENIED "<html><head><title>libmicrohttpd demo</title></head><body>Access denied</body></html>" 2810 #define OPAQUE "11733b200778ce33060f31c9af70a870ba96ddd4" 2811 2812 static int 2813 ahc_echo (void *cls, 2814 struct MHD_Connection *connection, 2815 const char *url, 2816 const char *method, 2817 const char *version, 2818 const char *upload_data, size_t *upload_data_size, void **ptr) 2819 @{ 2820 struct MHD_Response *response; 2821 char *username; 2822 const char *password = "testpass"; 2823 const char *realm = "test@@example.com"; 2824 int ret; 2825 static int already_called_marker; 2826 2827 if (&already_called_marker != *req_cls) 2828 @{ /* Called for the first time, request not fully read yet */ 2829 *req_cls = &already_called_marker; 2830 /* Wait for complete request */ 2831 return MHD_YES; 2832 @} 2833 2834 username = MHD_digest_auth_get_username (connection); 2835 if (username == NULL) 2836 @{ 2837 response = MHD_create_response_from_buffer(strlen (DENIED), 2838 DENIED, 2839 MHD_RESPMEM_PERSISTENT); 2840 ret = MHD_queue_auth_fail_response2 (connection, 2841 realm, 2842 OPAQUE, 2843 response, 2844 MHD_NO, 2845 MHD_DIGEST_ALG_SHA256); 2846 MHD_destroy_response(response); 2847 return ret; 2848 @} 2849 ret = MHD_digest_auth_check2 (connection, 2850 realm, 2851 username, 2852 password, 2853 300, 2854 MHD_DIGEST_ALG_SHA256); 2855 MHD_free(username); 2856 if ( (ret == MHD_INVALID_NONCE) || 2857 (ret == MHD_NO) ) 2858 @{ 2859 response = MHD_create_response_from_buffer(strlen (DENIED), 2860 DENIED, 2861 MHD_RESPMEM_PERSISTENT); 2862 if (NULL == response) 2863 return MHD_NO; 2864 ret = MHD_queue_auth_fail_response2 (connection, 2865 realm, 2866 OPAQUE, 2867 response, 2868 (ret == MHD_INVALID_NONCE) ? MHD_YES : MHD_NO, 2869 MHD_DIGEST_ALG_SHA256); 2870 MHD_destroy_response(response); 2871 return ret; 2872 @} 2873 response = MHD_create_response_from_buffer (strlen(PAGE), 2874 PAGE, 2875 MHD_RESPMEM_PERSISTENT); 2876 ret = MHD_queue_response (connection, 2877 MHD_HTTP_OK, 2878 response); 2879 MHD_destroy_response(response); 2880 return ret; 2881 @} 2882 @end example 2883 2884 @c ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2885 2886 @c ------------------------------------------------------------ 2887 @node microhttpd-post 2888 @chapter Adding a @code{POST} processor 2889 @cindex POST method 2890 2891 @menu 2892 * microhttpd-post api:: Programming interface for the 2893 @code{POST} processor. 2894 @end menu 2895 2896 2897 @noindent 2898 MHD provides the post processor API to make it easier for applications to 2899 parse the data of a client's @code{POST} request: the 2900 @code{MHD_AccessHandlerCallback} will be invoked multiple times to 2901 process data as it arrives; at each invocation a new chunk of data must 2902 be processed. The arguments @var{upload_data} and @var{upload_data_size} 2903 are used to reference the chunk of data. 2904 2905 When @code{MHD_AccessHandlerCallback} is invoked for a new request: 2906 its @code{*@var{req_cls}} argument is set to @code{NULL}. When @code{POST} 2907 data comes in the upload buffer it is @strong{mandatory} to use the 2908 @var{req_cls} to store a reference to per-request data. The fact 2909 that the pointer was initially @code{NULL} can be used to detect that 2910 this is a new request. 2911 2912 One method to detect that a new request was started is 2913 to set @code{*req_cls} to an unused integer: 2914 2915 @example 2916 int 2917 access_handler (void *cls, 2918 struct MHD_Connection * connection, 2919 const char *url, 2920 const char *method, const char *version, 2921 const char *upload_data, size_t *upload_data_size, 2922 void **req_cls) 2923 @{ 2924 static int old_connection_marker; 2925 int new_connection = (NULL == *req_cls); 2926 2927 if (new_connection) 2928 @{ 2929 /* new connection with POST */ 2930 *req_cls = &old_connection_marker; 2931 @} 2932 2933 ... 2934 @} 2935 @end example 2936 2937 @noindent 2938 In contrast to the previous example, for @code{POST} requests in particular, 2939 it is more common to use the value of @code{*req_cls} to keep track of 2940 actual state used during processing, such as the post processor (or a 2941 struct containing a post processor): 2942 2943 @example 2944 int 2945 access_handler (void *cls, 2946 struct MHD_Connection * connection, 2947 const char *url, 2948 const char *method, const char *version, 2949 const char *upload_data, size_t *upload_data_size, 2950 void **req_cls) 2951 @{ 2952 struct MHD_PostProcessor * pp = *req_cls; 2953 2954 if (pp == NULL) 2955 @{ 2956 pp = MHD_create_post_processor(connection, ...); 2957 *req_cls = pp; 2958 return MHD_YES; 2959 @} 2960 if (*upload_data_size) 2961 @{ 2962 MHD_post_process(pp, upload_data, *upload_data_size); 2963 *upload_data_size = 0; 2964 return MHD_YES; 2965 @} 2966 else 2967 @{ 2968 MHD_destroy_post_processor(pp); 2969 return MHD_queue_response(...); 2970 @} 2971 @} 2972 @end example 2973 2974 Note that the callback from @code{MHD_OPTION_NOTIFY_COMPLETED} 2975 should be used to destroy the post processor. This cannot be 2976 done inside of the access handler since the connection may not 2977 always terminate normally. 2978 2979 2980 @c ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2981 2982 @c ------------------------------------------------------------ 2983 @node microhttpd-post api 2984 @section Programming interface for the @code{POST} processor 2985 @cindex POST method 2986 2987 @deftypefun {struct MHD_PostProcessor *} MHD_create_post_processor (struct MHD_Connection *connection, size_t buffer_size, MHD_PostDataIterator iterator, void *iterator_cls) 2988 Create a PostProcessor. A PostProcessor can be used to (incrementally) 2989 parse the data portion of a @code{POST} request. 2990 2991 @table @var 2992 @item connection 2993 the connection on which the @code{POST} is happening (used to determine 2994 the @code{POST} format); 2995 2996 @item buffer_size 2997 maximum number of bytes to use for internal buffering (used only for the 2998 parsing, specifically the parsing of the keys). A tiny value (256-1024) 2999 should be sufficient; do @strong{NOT} use a value smaller than 256; 3000 for good performance, use 32k or 64k (i.e. 65536). 3001 3002 @item iterator 3003 iterator to be called with the parsed data; must @strong{NOT} be 3004 @code{NULL}; 3005 3006 @item iterator_cls 3007 custom value to be used as first argument to @var{iterator}. 3008 @end table 3009 3010 Return @code{NULL} on error (out of memory, unsupported encoding), otherwise 3011 a PP handle. 3012 @end deftypefun 3013 3014 3015 @deftypefun enum MHD_Result MHD_post_process (struct MHD_PostProcessor *pp, const char *post_data, size_t post_data_len) 3016 Parse and process @code{POST} data. Call this function when @code{POST} 3017 data is available (usually during an @code{MHD_AccessHandlerCallback}) 3018 with the @var{upload_data} and @var{upload_data_size}. Whenever 3019 possible, this will then cause calls to the 3020 @code{MHD_IncrementalKeyValueIterator}. 3021 3022 @table @var 3023 @item pp 3024 the post processor; 3025 3026 @item post_data 3027 @var{post_data_len} bytes of @code{POST} data; 3028 3029 @item post_data_len 3030 length of @var{post_data}. 3031 @end table 3032 3033 Return @code{MHD_YES} on success, @code{MHD_NO} on error 3034 (out-of-memory, iterator aborted, parse error). 3035 @end deftypefun 3036 3037 3038 @deftypefun enum MHD_Result MHD_destroy_post_processor (struct MHD_PostProcessor *pp) 3039 Release PostProcessor resources. After this function is being called, 3040 the PostProcessor is guaranteed to no longer call its iterator. There 3041 is no special call to the iterator to indicate the end of the post processing 3042 stream. After destroying the PostProcessor, the programmer should 3043 perform any necessary work to complete the processing of the iterator. 3044 3045 Return @code{MHD_YES} if processing completed nicely, @code{MHD_NO} 3046 if there were spurious characters or formatting problems with 3047 the post request. It is common to ignore the return value 3048 of this function. 3049 3050 3051 @end deftypefun 3052 3053 3054 3055 @c ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 3056 3057 @c ------------------------------------------------------------ 3058 @node microhttpd-info 3059 @chapter Obtaining and modifying status information. 3060 3061 3062 @menu 3063 * microhttpd-info daemon:: State information about an MHD daemon 3064 * microhttpd-info conn:: State information about a connection 3065 * microhttpd-option conn:: Modify per-connection options 3066 @end menu 3067 3068 3069 @c ------------------------------------------------------------ 3070 @node microhttpd-info daemon 3071 @section Obtaining state information about an MHD daemon 3072 3073 @deftypefun {const union MHD_DaemonInfo *} MHD_get_daemon_info (struct MHD_Daemon *daemon, enum MHD_DaemonInfoType infoType, ...) 3074 Obtain information about the given daemon. This function 3075 is currently not fully implemented. 3076 3077 @table @var 3078 @item daemon 3079 the daemon about which information is desired; 3080 3081 @item infoType 3082 type of information that is desired 3083 3084 @item ... 3085 additional arguments about the desired information (depending on 3086 infoType) 3087 @end table 3088 3089 Returns a union with the respective member (depending on 3090 infoType) set to the desired information), or @code{NULL} 3091 in case the desired information is not available or 3092 applicable. 3093 @end deftypefun 3094 3095 3096 @deftp {Enumeration} MHD_DaemonInfoType 3097 Values of this enum are used to specify what 3098 information about a daemon is desired. 3099 @table @code 3100 @item MHD_DAEMON_INFO_KEY_SIZE 3101 Request information about the key size for a particular cipher 3102 algorithm. The cipher algorithm should be passed as an extra argument 3103 (of type 'enum MHD_GNUTLS_CipherAlgorithm'). No longer supported, 3104 using this value will cause @code{MHD_get_daemon_info} to return NULL. 3105 3106 @item MHD_DAEMON_INFO_MAC_KEY_SIZE 3107 Request information about the key size for a particular cipher 3108 algorithm. The cipher algorithm should be passed as an extra argument 3109 (of type 'enum MHD_GNUTLS_HashAlgorithm'). No longer supported, 3110 using this value will cause @code{MHD_get_daemon_info} to return NULL. 3111 3112 @item MHD_DAEMON_INFO_LISTEN_FD 3113 @cindex listen 3114 Request the file-descriptor number that MHD is using to listen to the 3115 server socket. This can be useful if no port 3116 was specified and a client needs to learn what port 3117 is actually being used by MHD. 3118 No extra arguments should be passed. 3119 3120 @item MHD_DAEMON_INFO_EPOLL_FD 3121 @cindex epoll 3122 Request the file-descriptor number that MHD is using for epoll. If 3123 the build is not supporting epoll, NULL is returned; if we are using a 3124 thread pool or this daemon was not started with 3125 @code{MHD_USE_EPOLL}, (a pointer to) -1 is returned. If we are 3126 using @code{MHD_USE_INTERNAL_POLLING_THREAD} or are in 'external' select mode, the 3127 internal epoll FD is returned. This function must be used in external 3128 select mode with epoll to obtain the FD to call epoll on. No extra 3129 arguments should be passed. 3130 3131 @item MHD_DAEMON_INFO_CURRENT_CONNECTIONS 3132 @cindex connection, limiting number of connections 3133 Request the number of current connections handled by the daemon. No 3134 extra arguments should be passed and a pointer to a @code{union 3135 MHD_DaemonInfo} value is returned, with the @code{num_connections} 3136 member of type @code{unsigned int} set to the number of active 3137 connections. 3138 3139 Note that in multi-threaded or internal-select mode, the real number of current 3140 connections may already be different when @code{MHD_get_daemon_info} returns. 3141 The number of current connections can be used (even in multi-threaded and 3142 internal-select mode) after @code{MHD_quiesce_daemon} to detect whether all 3143 connections have been handled. 3144 3145 @end table 3146 @end deftp 3147 3148 3149 3150 @c ------------------------------------------------------------ 3151 @node microhttpd-info conn 3152 @section Obtaining state information about a connection 3153 3154 3155 @deftypefun {const union MHD_ConnectionInfo *} MHD_get_connection_info (struct MHD_Connection *connection, enum MHD_ConnectionInfoType infoType, ...) 3156 Obtain information about the given connection. 3157 3158 @table @var 3159 @item connection 3160 the connection about which information is desired; 3161 3162 @item infoType 3163 type of information that is desired 3164 3165 @item ... 3166 additional arguments about the desired information (depending on 3167 infoType) 3168 @end table 3169 3170 Returns a union with the respective member (depending on 3171 infoType) set to the desired information), or @code{NULL} 3172 in case the desired information is not available or 3173 applicable. 3174 @end deftypefun 3175 3176 @deftp {Enumeration} MHD_ConnectionInfoType 3177 Values of this enum are used to specify what information about a 3178 connection is desired. 3179 3180 @table @code 3181 3182 @item MHD_CONNECTION_INFO_CIPHER_ALGO 3183 What cipher algorithm is being used (HTTPS connections only). 3184 @code{NULL} is returned for non-HTTPS connections. 3185 3186 Takes no extra arguments. 3187 3188 @item MHD_CONNECTION_INFO_PROTOCOL, 3189 Allows finding out the TLS/SSL protocol used 3190 (HTTPS connections only). 3191 @code{NULL} is returned for non-HTTPS connections. 3192 3193 Takes no extra arguments. 3194 3195 @item MHD_CONNECTION_INFO_CLIENT_ADDRESS 3196 Returns information about the address of the client. Returns 3197 essentially a @code{struct sockaddr **} (since the API returns 3198 a @code{union MHD_ConnectionInfo *} and that union contains 3199 a @code{struct sockaddr *}). 3200 3201 Takes no extra arguments. 3202 3203 @item MHD_CONNECTION_INFO_GNUTLS_SESSION, 3204 Takes no extra arguments. Allows access to the underlying GNUtls session, 3205 including access to the underlying GNUtls client certificate 3206 (HTTPS connections only). Takes no extra arguments. 3207 @code{NULL} is returned for non-HTTPS connections. 3208 3209 Takes no extra arguments. 3210 3211 @item MHD_CONNECTION_INFO_GNUTLS_CLIENT_CERT, 3212 Dysfunctional (never implemented, deprecated). Use 3213 MHD_CONNECTION_INFO_GNUTLS_SESSION to get the @code{gnutls_session_t} 3214 and then call @code{gnutls_certificate_get_peers()}. 3215 3216 @item MHD_CONNECTION_INFO_DAEMON 3217 Returns information about @code{struct MHD_Daemon} which manages 3218 this connection. 3219 3220 Takes no extra arguments. 3221 3222 @item MHD_CONNECTION_INFO_CONNECTION_FD 3223 Returns the file descriptor (usually a TCP socket) associated with 3224 this connection (in the ``connect-fd'' member of the returned struct). 3225 Note that manipulating the descriptor directly can have problematic 3226 consequences (as in, break HTTP). Applications might use this access 3227 to manipulate TCP options, for example to set the ``TCP-NODELAY'' 3228 option for COMET-like applications. Note that MHD will set TCP-CORK 3229 after sending the HTTP header and clear it after finishing the footers 3230 automatically (if the platform supports it). As the connection 3231 callbacks are invoked in between, those might be used to set different 3232 values for TCP-CORK and TCP-NODELAY in the meantime. 3233 3234 Takes no extra arguments. 3235 3236 @item MHD_CONNECTION_INFO_CONNECTION_SUSPENDED 3237 Returns pointer to an integer that is @code{MHD_YES} if the connection 3238 is currently suspended (and thus can be safely resumed) and 3239 @code{MHD_NO} otherwise. 3240 3241 Takes no extra arguments. 3242 3243 @item MHD_CONNECTION_INFO_SOCKET_CONTEXT 3244 Returns the client-specific pointer to a @code{void *} that was 3245 (possibly) set during a @code{MHD_NotifyConnectionCallback} when the 3246 socket was first accepted. Note that this is NOT the same as the 3247 @code{req_cls} argument of the @code{MHD_AccessHandlerCallback}. The 3248 @code{req_cls} is fresh for each HTTP request, while the 3249 @code{socket_context} is fresh for each socket. 3250 3251 Takes no extra arguments. 3252 3253 @item MHD_CONNECTION_INFO_CONNECTION_TIMEOUT 3254 Returns pointer to an @code{unsigned int} that is the current timeout 3255 used for the connection (in seconds, 0 for no timeout). Note that 3256 while suspended connections will not timeout, the timeout value 3257 returned for suspended connections will be the timeout that the 3258 connection will use after it is resumed, and thus might not be zero. 3259 3260 Takes no extra arguments. 3261 3262 @item MHD_CONNECTION_INFO_REQUEST_HEADER_SIZE 3263 @cindex performance 3264 Returns pointer to an @code{size_t} that represents the size of the 3265 HTTP header received from the client. Only valid after the first callback 3266 to the access handler. 3267 3268 Takes no extra arguments. 3269 3270 @item MHD_CONNECTION_INFO_HTTP_STATUS 3271 Returns the HTTP status code of the response that was 3272 queued. Returns NULL if no response was queued yet. 3273 3274 Takes no extra arguments. 3275 3276 @end table 3277 @end deftp 3278 3279 3280 3281 @c ------------------------------------------------------------ 3282 @node microhttpd-option conn 3283 @section Setting custom options for an individual connection 3284 @cindex timeout 3285 3286 3287 3288 @deftypefun {int} MHD_set_connection_option (struct MHD_Connection *daemon, enum MHD_CONNECTION_OPTION option, ...) 3289 Set a custom option for the given connection. 3290 3291 @table @var 3292 @item connection 3293 the connection for which an option should be set or modified; 3294 3295 @item option 3296 option to set 3297 3298 @item ... 3299 additional arguments for the option (depending on option) 3300 @end table 3301 3302 Returns @code{MHD_YES} on success, @code{MHD_NO} for errors 3303 (i.e. option argument invalid or option unknown). 3304 @end deftypefun 3305 3306 3307 @deftp {Enumeration} MHD_CONNECTION_OPTION 3308 Values of this enum are used to specify which option for a 3309 connection should be changed. 3310 3311 @table @code 3312 3313 @item MHD_CONNECTION_OPTION_TIMEOUT 3314 Set a custom timeout for the given connection. Specified 3315 as the number of seconds, given as an @code{unsigned int}. Use 3316 zero for no timeout. 3317 3318 @end table 3319 @end deftp 3320 3321 3322 3323 @c ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 3324 3325 @c ------------------------------------------------------------ 3326 @node microhttpd-util 3327 @chapter Utility functions. 3328 3329 3330 @menu 3331 * microhttpd-util feature:: Test supported MHD features 3332 * microhttpd-util unescape:: Unescape strings 3333 @end menu 3334 3335 3336 @c ------------------------------------------------------------ 3337 @node microhttpd-util feature 3338 @section Testing for supported MHD features 3339 3340 3341 @deftp {Enumeration} MHD_FEATURE 3342 Values of this enum are used to specify what 3343 information about a daemon is desired. 3344 @table @code 3345 @item MHD_FEATURE_MESSAGES 3346 Get whether messages are supported. If supported then in debug 3347 mode messages can be printed to stderr or to external logger. 3348 3349 @item MHD_FEATURE_SSL 3350 Get whether HTTPS is supported. If supported then flag 3351 MHD_USE_SSL and options MHD_OPTION_HTTPS_MEM_KEY, 3352 MHD_OPTION_HTTPS_MEM_CERT, MHD_OPTION_HTTPS_MEM_TRUST, 3353 MHD_OPTION_HTTPS_MEM_DHPARAMS, MHD_OPTION_HTTPS_CRED_TYPE, 3354 MHD_OPTION_HTTPS_PRIORITIES can be used. 3355 3356 @item MHD_FEATURE_HTTPS_CERT_CALLBACK 3357 Get whether option #MHD_OPTION_HTTPS_CERT_CALLBACK is 3358 supported. 3359 3360 @item MHD_FEATURE_IPv6 3361 Get whether IPv6 is supported. If supported then flag 3362 MHD_USE_IPv6 can be used. 3363 3364 @item MHD_FEATURE_IPv6_ONLY 3365 Get whether IPv6 without IPv4 is supported. If not supported 3366 then IPv4 is always enabled in IPv6 sockets and 3367 flag MHD_USE_DUAL_STACK if always used when MHD_USE_IPv6 is 3368 specified. 3369 3370 @item MHD_FEATURE_POLL 3371 Get whether @code{poll()} is supported. If supported then flag 3372 MHD_USE_POLL can be used. 3373 3374 @item MHD_FEATURE_EPOLL 3375 Get whether @code{epoll()} is supported. If supported then Flags 3376 MHD_USE_EPOLL and 3377 MHD_USE_EPOLL_INTERNAL_THREAD can be used. 3378 3379 @item MHD_FEATURE_SHUTDOWN_LISTEN_SOCKET 3380 Get whether shutdown on listen socket to signal other 3381 threads is supported. If not supported flag 3382 MHD_USE_ITC is automatically forced. 3383 3384 @item MHD_FEATURE_SOCKETPAIR 3385 Get whether a @code{socketpair()} is used internally instead of 3386 a @code{pipe()} to signal other threads. 3387 3388 @item MHD_FEATURE_TCP_FASTOPEN 3389 Get whether TCP Fast Open is supported. If supported then 3390 flag MHD_USE_TCP_FASTOPEN and option 3391 MHD_OPTION_TCP_FASTOPEN_QUEUE_SIZE can be used. 3392 3393 @item MHD_FEATURE_BASIC_AUTH 3394 Get whether HTTP Basic authorization is supported. If supported 3395 then functions @code{MHD_basic_auth_get_username_password()} and 3396 @code{MHD_queue_basic_auth_fail_response()} can be used. 3397 3398 @item MHD_FEATURE_DIGEST_AUTH 3399 Get whether HTTP Digest authorization is supported. If 3400 supported then options MHD_OPTION_DIGEST_AUTH_RANDOM, 3401 MHD_OPTION_NONCE_NC_SIZE and functions @code{MHD_digest_auth_check()}, 3402 can be used. 3403 3404 @item MHD_FEATURE_POSTPROCESSOR 3405 Get whether postprocessor is supported. If supported then 3406 functions @code{MHD_create_post_processor()}, 3407 @code{MHD_post_process()}, @code{MHD_destroy_post_processor()} 3408 can be used. 3409 3410 @item MHD_FEATURE_SENDFILE 3411 Get whether @code{sendfile()} is supported. 3412 3413 @end table 3414 @end deftp 3415 3416 3417 3418 @deftypefun {int} MHD_is_feature_supported (enum MHD_FEATURE feature) 3419 Get information about supported MHD features. Indicate that MHD was 3420 compiled with or without support for particular feature. Some features 3421 require additional support by the kernel. However, kernel support is not 3422 checked by this function. 3423 3424 @table @var 3425 @item feature 3426 type of requested information 3427 @end table 3428 3429 Returns @code{MHD_YES} if the feature is supported, 3430 and @code{MHD_NO} if not. 3431 @end deftypefun 3432 3433 3434 @c ------------------------------------------------------------ 3435 @node microhttpd-util unescape 3436 @section Unescape strings 3437 3438 @deftypefun {size_t} MHD_http_unescape (char *val) 3439 Process escape sequences ('%HH') Updates val in place; the result 3440 should be UTF-8 encoded and cannot be larger than the input. The 3441 result must also still be 0-terminated. 3442 3443 @table @var 3444 @item val 3445 value to unescape (modified in the process), must be 3446 a 0-terminated UTF-8 string. 3447 @end table 3448 3449 Returns length of the resulting val (@code{strlen(val)} may be 3450 shorter afterwards due to elimination of escape sequences). 3451 3452 @end deftypefun 3453 3454 3455 3456 3457 3458 @c ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 3459 3460 3461 @c ********************************************************** 3462 @c ******************* Appendices ************************* 3463 @c ********************************************************** 3464 3465 @node GNU-LGPL 3466 @unnumbered GNU-LGPL 3467 @cindex license 3468 @include lgpl.texi 3469 3470 @node eCos License 3471 @unnumbered eCos License 3472 @cindex license 3473 @include ecos.texi 3474 3475 @node GNU-GPL 3476 @unnumbered GNU General Public License 3477 @cindex license 3478 @include gpl-2.0.texi 3479 3480 @node GNU-FDL 3481 @unnumbered GNU-FDL 3482 @cindex license 3483 @include fdl-1.3.texi 3484 3485 @node Concept Index 3486 @unnumbered Concept Index 3487 3488 @printindex cp 3489 3490 @node Function and Data Index 3491 @unnumbered Function and Data Index 3492 3493 @printindex fn 3494 3495 @node Type Index 3496 @unnumbered Type Index 3497 3498 @printindex tp 3499 3500 @bye