libmicrohttpd2

HTTP server C library (MHD 2.x, alpha)
Log | Files | Refs | README | LICENSE

init.inc (13269B)


      1 This chapter explains the key functions of MHD to create, start,
      2 quiesce and destroy an HTTP server, as well as how to configure
      3 global logging to receive more detailed messages when something
      4 goes really wrong inside of MHD.
      5 
      6 @node libmicrohttpd-init-panic
      7 @section Setting up a panic handler
      8 @cindex logging
      9 
     10 @code{MHD_PanicCallback} is the type of a function that MHD
     11 calls when it encounters an error that it cannot handle. This
     12 should always be indicative of a serious bug, be it a hardware
     13 failure (such as a bit-flip in RAM or a broken CPU) or a bug
     14 in the application (for example, memory corruption or a
     15 failed assertion). MHD will not cause a panic in case of
     16 normal operation or when there would be a safe way to continue
     17 the execution.
     18 
     19 @anchor{MHD_PanicCallback}
     20 @deftypefn {Function Pointer} {enum MHD_Result} (*MHD_PanicCallback) (void *cls, const char *file, const char *func, unsigned int line, const char *message)
     21 
     22 Invoked in the context of a serious error condition. The callback should not return. Some parameters could be empty strings (with zero-termination at zero position),
     23 especially if MHD is built without support for log messages.
     24 @table @var
     25 @item cls
     26 custom value provided by the application at callback registration time;
     27 
     28 @item file
     29 name of the source file where the error occured;
     30 
     31 @item func
     32 function in the source where the error occured;
     33 
     34 @item line
     35 line in the source file where the error occured;
     36 
     37 @item message
     38 message describing the error;
     39 @end table
     40 @end deftypefn
     41 
     42 MHD comes with a default panic action, which is to print an error
     43 message and call @code{abort()} to terminate the process.
     44 Applications can use @code{MHD_lib_set_panic_func()} to change this
     45 behavior. However, applications must always terminate the process
     46 inside of the panic callback (but they could use @code{exit()} or
     47 @code{_exit()} or some other way to terminate the process instead
     48 of calling @code{abort()}). Note that
     49 the panic function is @emph{expected} to be called in a situation
     50 where the process is in an @emph{unsafe} state, thus even the default
     51 behavior of calling @code{fprintf()} could be dangerous as it may
     52 enable an attacker to further exploit whatever bug caused the panic in
     53 the first place.
     54 
     55 @deftypefun {void} MHD_lib_set_panic_func (MHD_PanicCallback cb, void *cb_cls)
     56 Set a handler for fatal errors.
     57 
     58 @table @var
     59 @item cb
     60 function to call if MHD encounters a fatal internal error.  If no handler was set explicitly, MHD will log an error and call @code{abort()}.
     61 
     62 @item cb_cls
     63 closure argument for @var{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})
     64 @end table
     65 @end deftypefun
     66 
     67 @node libmicrohttpd-init-create
     68 @section Creating an HTTP daemon
     69 
     70 @cindex daemon
     71 
     72 @anchor{MHD_Daemon}
     73 @deftp {C Struct} MHD_Daemon
     74 
     75 Handle for an HTTP daemon. A daemon contains the MHD configuration
     76 and state to listening on a socket for HTTP clients and handle
     77 their requests.
     78 @end deftp
     79 
     80 An application can in principle create multiple daemons, for example
     81 to listen on both port 80 and port 443. Each daemon handles requests
     82 from at most one @code{listen()} socket.
     83 The @code{MHD_daemon_create()} function is used by applications to
     84 create a @code{struct MHD_Daemon}.
     85 
     86 @anchor{MHD_daemon_create}
     87 @deftypefun {struct MHD_Daemon *} MHD_daemon_create (MHD_RequestCallback req_cb, void *req_cb_cls)
     88 Create a new HTTP daemon object. Does not actually start
     89 the HTTP daemon.
     90 @table @var
     91 @item req_cb
     92 Function to call to handle each HTTP request;
     93 
     94 @item req_cb_cls
     95 closure to pass to the @var{req_cb};
     96 @end table
     97 
     98 Returns @code{NULL} on error (usually out-of-memory),
     99 handle to daemon on success.
    100 @end deftypefun
    101 
    102 When creating an HTTP daemon the application must pass the address of
    103 a function of type @code{MHD_RequestCallback} which MHD will call for
    104 each HTTP request that daemon receives from the network.
    105 
    106 @cindex anchor
    107 @anchor{MHD_RequestCallback}
    108 @deftypefn {Function Pointer} {struct MHD_Action *} (*MHD_RequestCallback) (void *cls, struct MHD_Request *request, const struct MHD_String *path, enum MHD_HTTP_Method method, uint_fast64_t upload_size)
    109 
    110 Functions of this type are invoked by MHD whenever it received an HTTP
    111 request and needs to handle it.
    112 
    113 @table @var
    114 @item cls
    115 custom value provided by the application to @code{MHD_daemon_create()};
    116 
    117 @item path
    118 the PATH component of the HTTP URL requested by the client. Empty
    119 if the request was just for ``http://domain``, otherwise
    120 starting with ``/``;
    121 
    122 @item method
    123 the HTTP method used by the client;
    124 
    125 @item upload_size
    126 number of bytes of data that the client intends to upload
    127 in the request body; a special value of @code{MHD_SIZE_UNKNOWN}
    128 is provided if the client indicated the use of chunked encoding
    129 and the final upload size is not yet known;
    130 @end table
    131 
    132 The returned @code{struct MHD_Action} determines how MHD will continue
    133 handling the request. Implementations must call MHD
    134 functions to create a @code{struct MHD_Action}, which then determines
    135 the next steps.
    136 
    137 @ref{libmicrohttpd2-actions,,Using actions} explains in more detail how to create
    138 various possible actions. It is also possible to return @code{NULL},
    139 in which case MHD will close the HTTP connection without returning
    140 anything (not even an error message).  This can be used if the socket
    141 must be closed due to a serious error while handling the request (such
    142 as being out-of-memory).
    143 @end deftypefn
    144 
    145 The HTTP @var{method} is not provided as a string as comparing
    146 strings is generally inefficient for the application. Furthermore,
    147 by providing an enumeration value applications often can avoid
    148 implementing case-insensitive ASCII string comparissons. However,
    149 the enumeration only works for HTTP methods specified in RFC 9110.
    150 
    151 @cindex method
    152 @anchor{MHD_HTTP_Method}
    153 @deftp {Enumeration} MHD_HTTP_Method
    154 
    155 Represents canonical HTTP methods as per RFC 9110.
    156 
    157 @table @code
    158 @item MHD_HTTP_METHOD_GET
    159  "GET". Safe. Idempotent.  RFC9110, Section 9.3.1.
    160 
    161 @item MHD_HTTP_METHOD_HEAD
    162 "HEAD". Safe. Idempotent.  RFC9110, Section 9.3.2.
    163 
    164 @item MHD_HTTP_METHOD_POST
    165 "POST". Not safe. Not idempotent. RFC9110, Section 9.3.3.
    166 
    167 @item MHD_HTTP_METHOD_PUT
    168 "PUT". Not safe. Idempotent. RFC9110, Section 9.3.4.
    169 
    170 @item MHD_HTTP_METHOD_DELETE
    171 "DELETE". Not safe. Idempotent. RFC9110, Section 9.3.5.
    172 
    173 @item MHD_HTTP_METHOD_CONNECT
    174 "CONNECT". Not safe. Not idempotent. RFC9110, Section 9.3.6.
    175 
    176 @item MHD_HTTP_METHOD_OPTIONS
    177 "OPTIONS". Safe. Idempotent. RFC9110, Section 9.3.7.
    178 
    179 @item MHD_HTTP_METHOD_TRACE
    180 "TRACE". Safe.  Idempotent. RFC9110, Section 9.3.8.
    181 
    182 @item MHD_HTTP_METHOD_ASTERISK
    183  "*". Not safe. Not idempotent. RFC9110, Section 18.2.
    184 
    185 @item MHD_HTTP_METHOD_OTHER
    186 Non-canonical HTTP method. If an application wants to
    187 support non-canonical HTTP methods, the application
    188 must request the method's value by passing
    189 @code{MHD_REQUEST_INFO_DYNAMIC_HTTP_METHOD_STR}
    190 to @code{MHD_request_get_info_dynamic()}.
    191 @xref{libmicrohttpd2-info request,,request introspection}.
    192 
    193 @end table
    194 @end deftp
    195 
    196 The convenience function @code{MHD_http_method_to_string()}
    197 can be used to convert members of this enumeration to
    198 a string value.
    199 
    200 @anchor{MHD_http_method_to_string}
    201 @deftypefun {const struct MHD_String *} MHD_http_method_to_string (enum MHD_HTTP_Method method)
    202 Get text version of the method name.
    203 
    204 Returns a pointer (!) to the HTTP method as a string.
    205 @code{NULL} is returned if @var{method} is @code{MHD_HTTP_METHOD_OTHER}.
    206 
    207 @table @var
    208 @item method
    209 the method to get the text version for
    210 
    211 @end table
    212 @end deftypefun
    213 
    214 Various additional string constants for HTTP methods are defined in
    215 the @code{microhttpd2.h} header for HTTP methods from a wide range of
    216 RFCs. Check the header for constants with the prefix
    217 @code{MHD_HTTP_METHOD_STR_}.
    218 
    219 @node libmicrohttpd-init-start
    220 @section Starting an HTTP daemon
    221 
    222 After creating an MHD daemon, applications will typically configure
    223 various optional features, such as support for TLS.
    224 @ref{libmicrohttpd2-doptions,,Daemon options} explains how to set the various options.
    225 Once the daemon is correctly configured, applications can start
    226 processing client requests using @code{MHD_daemon_start()}.
    227 
    228 @anchor{MHD_daemon_start}
    229 @deftypefun {enum MHD_StatusCode} MHD_daemon_start (struct MHD_Daemon *daemon)
    230 
    231 Starts an HTTP daemon. Checks that options are consistent, initializes
    232 the TLS library (if enabled), creates the listen socket (if not
    233 disabled) and launches the internal threads (if configured to do so).
    234 
    235 @table @var
    236 @item daemon
    237 Handle to the HTTP daemon to start. Must be configured
    238 but not have been started previously.
    239 @end table
    240 
    241 Returns @code{MHD_SC_OK} on success, otherwise an error code indicative of the problem.
    242 @end deftypefun
    243 
    244 Note that if you configured the daemon to use an
    245 @emph{external} event loop, calling @code{MHD_daemon_start()}
    246 is not sufficient to actually start processing client requests.
    247 In this case, you must also integrate MHD into your event loop.
    248 @xref{libmicrohttpd2-external,,Using external event loops}.
    249 
    250 @node libmicrohttpd-status-codes
    251 @section Interpreting status codes
    252 @cindex status code
    253 
    254 MHD uses the @code{enum MHD_StatusCode} to inform the application
    255 about errors.
    256 
    257 @anchor{MHD_StatusCode}
    258 @deftp {Enumeration} MHD_StatusCode
    259 Status codes are returned to indicate to the
    260 application the success or failure of an
    261 operation.  The value ranges have a meaning:
    262 
    263 @itemize
    264 @item from 0 and 10000
    265   must be handled explicitly by the app.
    266 @item from 10000-19999
    267   are informational.
    268 @item from 20000-29999
    269   indicate successful operations.
    270 @item from 30000-39999
    271  indicate unsuccessful (normal) operations.
    272 @item from 40000-49999
    273  indicate client errors.
    274 @item from 50000-59999
    275  indicate MHD server errors.
    276 @item from 60000-65535
    277  indicate application errors.
    278 @end itemize
    279 
    280 The most common value is @code{MHD_SC_OK} (0)
    281 which indicates a successful operation.
    282 @end deftp
    283 
    284 To obtain a human-readable message explaining the status code,
    285 applications can use @code{MHD_status_code_to_string()}.
    286 
    287 @anchor{MHD_status_code_to_string}
    288 @deftypefun {const struct MHD_String *} MHD_status_code_to_string (struct MHD_StatusCode code)
    289 
    290 Get text description for the MHD status code.
    291 This function works for MHD status codes, not for HTTP status codes!
    292 
    293 @table @var
    294 @item code
    295 the MHD code to get a description for
    296 @end table
    297 
    298 The function returns a pointer to the text description for the
    299 status code, or @code{NULL} if @var{code} is not known.
    300 
    301 @end deftypefun
    302 
    303 The convenience macro @code{MHD_status_code_to_string_lazy()} converts
    304 an @code{enum MHD_StatusCode} directly to a @code{const char *}. It
    305 also ensures that the result is never @code{NULL} by returning
    306 @code{"[No code]"} instead of @code{NULL}.
    307 
    308 
    309 @node libmicrohttpd-init-quiesce
    310 @section Quiescing an HTTP daemon
    311 @cindex quiesce
    312 
    313 Quiescing an HTTP daemon prevents it from further accepting new
    314 connections, but allows it to finish handling existing clients.  This
    315 is useful to minimize the disruptions when gracefully shutting down,
    316 restarting or reloading an HTTP service.
    317 
    318 @anchor{MHD_daemon_quiesce}
    319 @deftypefun MHD_Socket MHD_daemon_quiesce (struct MHD_Daemon *daemon)
    320 Stop accepting connections from the listening socket.  Allows clients
    321 to continue processing, but stops accepting new connections.
    322 
    323 @table @var
    324 @item daemon
    325 Handle to the HTTP daemon to quiesce. The daemon should have been
    326 started before.
    327 @end table
    328 
    329 The returned socket is the listen socket of the daemon.  This value
    330 can be useful in the special case that a listen socket is to be
    331 migrated to another process (i.e. a newer version of the HTTP server).
    332 The caller is made responsible for ultimately closing the returned
    333 socket; however, if MHD is run using threads (anything but external
    334 select mode), it @strong{must not} be closed until @emph{after}
    335 @code{MHD_daemon_destroy()} has been called (as it is theoretically
    336 possible that an existing thread is still using it).
    337 
    338 A value of @code{-1} is returned if either the daemon was not
    339 started or was not listening on a socket.
    340 @end deftypefun
    341 
    342 @cindex socket
    343 @anchor{MHD_Socket}
    344 @deftp {Typedef} MHD_Socket
    345 
    346 The type @code{MHD_Socket} is platform-dependent:
    347 @code{MHD_Socket} is simply an @code{int} on UNIX systems, while on
    348 W32 it is a @code{SOCKET}.
    349 @end deftp
    350 
    351 
    352 @node libmicrohttpd-init-destroy
    353 @section Destroying an HTTP daemon
    354 
    355 Destroying an HTTP daemon using @code{MHD_daemon_destroy()}
    356 immediately stops all MHD processing of associated requests and frees
    357 all associated resources. Applications do @emph{not} have to call
    358 @code{MHD_daemon_quiesce()} before destroying a daemon: if the daemon
    359 was not quiesced first, the listen socket will still be closed and all
    360 ongoing requests will simply be terminated hard by closing the
    361 connections.
    362 
    363 @anchor{MHD_daemon_destroy}
    364 @deftypefun void MHD_daemon_destroy (struct MHD_Daemon *daemon)
    365 
    366 Shutdown and destroy an HTTP daemon. Frees all
    367 resources still associated with the daemon.
    368 
    369 @table @var
    370 @item daemon
    371 Handle to the HTTP daemon to destroy.
    372 @end table
    373 @end deftypefun
    374 
    375 
    376 @node libmicrohttpd-init-example
    377 @section Example: Starting with GNU libmicrohttpd
    378 
    379 The following is a minimal starting point for implementing
    380 an application that uses MHD to add an HTTP server:
    381 
    382 @example c
    383 @verbatiminclude examples/init-example.c
    384 @end example