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