Back to home page

EIC code displayed by LXR

 
 

    


Warning, file /include/civetweb.h was not indexed or was modified since last indexation (in which case cross-reference links may be missing, inaccurate or erroneous).

0001 /* Copyright (c) 2013-2024 the Civetweb developers
0002  * Copyright (c) 2004-2013 Sergey Lyubka
0003  *
0004  * Permission is hereby granted, free of charge, to any person obtaining a copy
0005  * of this software and associated documentation files (the "Software"), to deal
0006  * in the Software without restriction, including without limitation the rights
0007  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
0008  * copies of the Software, and to permit persons to whom the Software is
0009  * furnished to do so, subject to the following conditions:
0010  *
0011  * The above copyright notice and this permission notice shall be included in
0012  * all copies or substantial portions of the Software.
0013  *
0014  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
0015  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
0016  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
0017  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
0018  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
0019  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
0020  * THE SOFTWARE.
0021  */
0022 
0023 #ifndef CIVETWEB_HEADER_INCLUDED
0024 #define CIVETWEB_HEADER_INCLUDED
0025 
0026 #define CIVETWEB_VERSION "1.17"
0027 #define CIVETWEB_VERSION_MAJOR (1)
0028 #define CIVETWEB_VERSION_MINOR (17)
0029 #define CIVETWEB_VERSION_PATCH (0)
0030 
0031 #ifndef CIVETWEB_API
0032 #if defined(_WIN32)
0033 #if defined(CIVETWEB_DLL_EXPORTS)
0034 #define CIVETWEB_API __declspec(dllexport)
0035 #elif defined(CIVETWEB_DLL_IMPORTS)
0036 #define CIVETWEB_API __declspec(dllimport)
0037 #else
0038 #define CIVETWEB_API
0039 #endif
0040 #elif __GNUC__ >= 4
0041 #define CIVETWEB_API __attribute__((visibility("default")))
0042 #else
0043 #define CIVETWEB_API
0044 #endif
0045 #endif
0046 
0047 #include <stddef.h>
0048 #include <stdio.h>
0049 
0050 #ifdef __cplusplus
0051 extern "C" {
0052 #endif /* __cplusplus */
0053 
0054 
0055 /* Init Features */
0056 enum {
0057     MG_FEATURES_DEFAULT = 0x0u,
0058 
0059     /* Support files from local directories */
0060     /* Will only work, if NO_FILES is not set. */
0061     MG_FEATURES_FILES = 0x1u,
0062 
0063     /* Support transport layer security (TLS). */
0064     /* SSL is still often used synonymously for TLS. */
0065     /* Will only work, if NO_SSL is not set. */
0066     MG_FEATURES_TLS = 0x2u,
0067     MG_FEATURES_SSL = 0x2u,
0068 
0069     /* Support common gateway interface (CGI). */
0070     /* Will only work, if NO_CGI is not set. */
0071     MG_FEATURES_CGI = 0x4u,
0072 
0073     /* Support IPv6. */
0074     /* Will only work, if USE_IPV6 is set. */
0075     MG_FEATURES_IPV6 = 0x8u,
0076 
0077     /* Support WebSocket protocol. */
0078     /* Will only work, if USE_WEBSOCKET is set. */
0079     MG_FEATURES_WEBSOCKET = 0x10u,
0080 
0081     /* Support server side Lua scripting. */
0082     /* Will only work, if USE_LUA is set. */
0083     MG_FEATURES_LUA = 0x20u,
0084 
0085     /* Support server side JavaScript scripting. */
0086     /* Will only work, if USE_DUKTAPE is set. */
0087     MG_FEATURES_SSJS = 0x40u,
0088 
0089     /* Provide data required for caching files. */
0090     /* Will only work, if NO_CACHING is not set. */
0091     MG_FEATURES_CACHE = 0x80u,
0092 
0093     /* Collect server status information. */
0094     /* Will only work, if USE_SERVER_STATS is set. */
0095     MG_FEATURES_STATS = 0x100u,
0096 
0097     /* Support on-the-fly compression. */
0098     /* Will only work, if USE_ZLIB is set. */
0099     MG_FEATURES_COMPRESSION = 0x200u,
0100 
0101     /* HTTP/2 support enabled. */
0102     MG_FEATURES_HTTP2 = 0x400u,
0103 
0104     /* Support unix domain sockets. */
0105     MG_FEATURES_X_DOMAIN_SOCKET = 0x800u,
0106 
0107     /* Bit mask for all feature defines. */
0108     MG_FEATURES_ALL = 0xFFFFu
0109 };
0110 
0111 
0112 /* Initialize this library. This should be called once before any other
0113  * function from this library. This function is not guaranteed to be
0114  * thread safe.
0115  * Parameters:
0116  *   features: bit mask for features to be initialized.
0117  *             Note: The TLS libraries (like OpenSSL) is initialized
0118  *                   only if the MG_FEATURES_TLS bit is set.
0119  *                   Currently the other bits do not influence
0120  *                   initialization, but this may change in future
0121  *                   versions.
0122  * Return value:
0123  *   initialized features
0124  *   0: error
0125  */
0126 CIVETWEB_API unsigned mg_init_library(unsigned features);
0127 
0128 
0129 /* Un-initialize this library.
0130  * Return value:
0131  *   0: error
0132  */
0133 CIVETWEB_API unsigned mg_exit_library(void);
0134 
0135 
0136 struct mg_context;    /* Handle for the HTTP service itself */
0137 struct mg_connection; /* Handle for the individual connection */
0138 
0139 
0140 /* Maximum number of headers */
0141 #define MG_MAX_HEADERS (64)
0142 
0143 struct mg_header {
0144     const char *name;  /* HTTP header name */
0145     const char *value; /* HTTP header value */
0146 };
0147 
0148 
0149 /* This structure contains information about the HTTP request. */
0150 struct mg_request_info {
0151     const char *request_method; /* "GET", "POST", etc */
0152     const char *request_uri;    /* URL-decoded URI (absolute or relative,
0153                                  * as in the request) */
0154     const char *local_uri_raw;  /* URL-decoded URI (relative). Can be NULL
0155                                  * if the request_uri does not address a
0156                                  * resource at the server host. */
0157     const char *local_uri;      /* Same as local_uri_raw, however, cleaned
0158                                  * so a path like
0159                                  *   allowed_dir/../forbidden_file
0160                                  * is not possible. */
0161     const char *http_version;   /* E.g. "1.0", "1.1" */
0162     const char *query_string;   /* URL part after '?', not including '?', or
0163                                    NULL */
0164     const char *remote_user;    /* Authenticated user, or NULL if no auth
0165                                    used */
0166     char remote_addr[48];       /* Client's IP address as a string. */
0167 
0168     long long content_length; /* Length (in bytes) of the request body,
0169                                  can be -1 if no length was given. */
0170     int remote_port;          /* Port at client side */
0171     int server_port;          /* Port at server side (one of the listening
0172                                  ports) */
0173     int is_ssl;               /* 1 if HTTPS or WS is used (SSL/TLS used),
0174                                  0 if not */
0175     void *user_data;          /* User data pointer passed to mg_start() */
0176     void *conn_data;          /* Connection-specific user data */
0177 
0178     int num_headers; /* Number of HTTP headers */
0179     struct mg_header
0180         http_headers[MG_MAX_HEADERS]; /* Allocate maximum headers */
0181 
0182     struct mg_client_cert *client_cert; /* Client certificate information */
0183 
0184     const char *acceptedWebSocketSubprotocol; /* websocket subprotocol,
0185                                                * accepted during handshake */
0186 };
0187 
0188 
0189 /* This structure contains information about the HTTP request. */
0190 /* This structure may be extended in future versions. */
0191 struct mg_response_info {
0192     int status_code;          /* E.g. 200 */
0193     const char *status_text;  /* E.g. "OK" */
0194     const char *http_version; /* E.g. "1.0", "1.1" */
0195 
0196     long long content_length; /* Length (in bytes) of the request body,
0197                                  can be -1 if no length was given. */
0198 
0199     int num_headers; /* Number of HTTP headers */
0200     struct mg_header
0201         http_headers[MG_MAX_HEADERS]; /* Allocate maximum headers */
0202 };
0203 
0204 
0205 /* Client certificate information (part of mg_request_info) */
0206 struct mg_client_cert {
0207     void *peer_cert;
0208     const char *subject;
0209     const char *issuer;
0210     const char *serial;
0211     const char *finger;
0212 };
0213 
0214 
0215 /* This structure needs to be passed to mg_start(), to let civetweb know
0216    which callbacks to invoke. For a detailed description, see
0217    https://github.com/civetweb/civetweb/blob/master/docs/UserManual.md */
0218 struct mg_callbacks {
0219     /* Called when civetweb has received new HTTP request.
0220        If the callback returns one, it must process the request
0221        by sending valid HTTP headers and a body. Civetweb will not do
0222        any further processing. Otherwise it must return zero.
0223        Note that since V1.7 the "begin_request" function is called
0224        before an authorization check. If an authorization check is
0225        required, use a request_handler instead.
0226        Return value:
0227          0: civetweb will process the request itself. In this case,
0228             the callback must not send any data to the client.
0229          1-999: callback already processed the request. Civetweb will
0230                 not send any data after the callback returned. The
0231                 return code is stored as a HTTP status code for the
0232                 access log. */
0233     int (*begin_request)(struct mg_connection *);
0234 
0235     /* Called when civetweb has finished processing request. */
0236     void (*end_request)(const struct mg_connection *, int reply_status_code);
0237 
0238     /* Called when civetweb is about to log a message. If callback returns
0239        non-zero, civetweb does not log anything. */
0240     int (*log_message)(const struct mg_connection *, const char *message);
0241 
0242     /* Called when civetweb is about to log access. If callback returns
0243        non-zero, civetweb does not log anything. */
0244     int (*log_access)(const struct mg_connection *, const char *message);
0245 
0246     /* Called when civetweb initializes SSL library.
0247        Parameters:
0248          ssl_ctx: SSL_CTX pointer.
0249          user_data: parameter user_data passed when starting the server.
0250        Return value:
0251          0: civetweb will set up the SSL certificate.
0252          1: civetweb assumes the callback already set up the certificate.
0253         -1: initializing ssl fails. */
0254     int (*init_ssl)(void *ssl_ctx, void *user_data);
0255 
0256     /* Called when civetweb initializes SSL library for a domain.
0257        Parameters:
0258          server_domain: authentication_domain from the domain config.
0259          ssl_ctx: SSL_CTX pointer.
0260          user_data: parameter user_data passed when starting the server.
0261        Return value:
0262          0: civetweb will set up the SSL certificate.
0263          1: civetweb assumes the callback already set up the certificate.
0264         -1: initializing ssl fails. */
0265     int (*init_ssl_domain)(const char *server_domain,
0266                            void *ssl_ctx,
0267                            void *user_data);
0268 
0269     /* Called when civetweb is about to create or free a SSL_CTX.
0270     Parameters:
0271          ssl_ctx: SSL_CTX pointer. NULL at creation time, Not NULL when
0272     mg_context will be freed user_data: parameter user_data passed when starting
0273     the server. Return value: 0: civetweb will continue to create the context,
0274     just as if the callback would not be present. The value in *ssl_ctx when the
0275     function returns is ignored. 1: civetweb will copy the value from *ssl_ctx
0276     to the civetweb context and doesn't create its own. -1: initializing ssl
0277     fails.*/
0278     int (*external_ssl_ctx)(void **ssl_ctx, void *user_data);
0279 
0280     /* Called when civetweb is about to create or free a SSL_CTX for a domain.
0281     Parameters:
0282          server_domain: authentication_domain from the domain config.
0283          ssl_ctx: SSL_CTX pointer. NULL at creation time, Not NULL when
0284     mg_context will be freed user_data: parameter user_data passed when starting
0285     the server. Return value: 0: civetweb will continue to create the context,
0286     just as if the callback would not be present. The value in *ssl_ctx when the
0287     function returns is ignored. 1: civetweb will copy the value from *ssl_ctx
0288     to the civetweb context and doesn't create its own. -1: initializing ssl
0289     fails.*/
0290     int (*external_ssl_ctx_domain)(const char *server_domain,
0291                                    void **ssl_ctx,
0292                                    void *user_data);
0293 
0294 #if defined(MG_EXPERIMENTAL_INTERFACES) /* 2019-11-03 */
0295     /* Called when data frame has been received from the peer.
0296        Parameters:
0297          bits: first byte of the websocket frame, see websocket RFC at
0298                http://tools.ietf.org/html/rfc6455, section 5.2
0299          data, data_len: payload, with mask (if any) already applied.
0300        Return value:
0301          1: keep this websocket connection open.
0302          0: close this websocket connection.
0303        This callback is deprecated: Use mg_set_websocket_handler instead. */
0304     int (*websocket_data)(struct mg_connection *,
0305                           int bits,
0306                           char *data,
0307                           size_t data_len);
0308 #endif /* MG_LEGACY_INTERFACE */
0309 
0310     /* Called when civetweb is closing a connection.  The per-context mutex is
0311        locked when this is invoked.
0312 
0313        Websockets:
0314        Before mg_set_websocket_handler has been added, it was primarily useful
0315        for noting when a websocket is closing, and used to remove it from any
0316        application-maintained list of clients.
0317        Using this callback for websocket connections is deprecated: Use
0318        mg_set_websocket_handler instead.
0319     */
0320     void (*connection_close)(const struct mg_connection *);
0321 
0322     /* Called after civetweb has closed a connection.  The per-context mutex is
0323        locked when this is invoked.
0324 
0325     Connection specific data:
0326     If memory has been allocated for the connection specific user data
0327     (mg_request_info->conn_data, mg_get_user_connection_data),
0328     this is the last chance to free it.
0329  */
0330     void (*connection_closed)(const struct mg_connection *);
0331 
0332 
0333     /* init_lua is called when civetweb is about to serve Lua server page.
0334        exit_lua is called when the Lua processing is complete.
0335        Both will work only if Lua support is enabled.
0336        Parameters:
0337          conn: current connection.
0338          lua_context: "lua_State *" pointer.
0339          context_flags: context type information as bitmask:
0340            context_flags & 0x0F: (0-15) Lua environment type
0341     */
0342     void (*init_lua)(const struct mg_connection *conn,
0343                      void *lua_context,
0344                      unsigned context_flags);
0345     void (*exit_lua)(const struct mg_connection *conn,
0346                      void *lua_context,
0347                      unsigned context_flags);
0348 
0349 
0350     /* Called when civetweb is about to send HTTP error to the client.
0351        Implementing this callback allows to create custom error pages.
0352        Parameters:
0353          conn: current connection.
0354          status: HTTP error status code.
0355          errmsg: error message text.
0356        Return value:
0357          1: run civetweb error handler.
0358          0: callback already handled the error. */
0359     int (*http_error)(struct mg_connection *conn,
0360                       int status,
0361                       const char *errmsg);
0362 
0363     /* Called after civetweb context has been created, before requests
0364        are processed.
0365        Parameters:
0366          ctx: context handle */
0367     void (*init_context)(const struct mg_context *ctx);
0368 
0369     /* Called when civetweb context is deleted.
0370     Parameters:
0371     ctx: context handle */
0372     void (*exit_context)(const struct mg_context *ctx);
0373 
0374     /* Called when a new worker thread is initialized.
0375      * It is always called from the newly created thread and can be used to
0376      * initialize thread local storage data.
0377      * Parameters:
0378      *   ctx: context handle
0379      *   thread_type:
0380      *     0 indicates the master thread
0381      *     1 indicates a worker thread handling client connections
0382      *     2 indicates an internal helper thread (timer thread)
0383      * Return value:
0384      *   This function returns a user supplied pointer. The pointer is assigned
0385      *   to the thread and can be obtained from the mg_connection object using
0386      *   mg_get_thread_pointer in all server callbacks. Note: A connection and
0387      *   a thread are not directly related. Threads will serve several different
0388      *   connections, and data from a single connection may call different
0389      *   callbacks using different threads. The thread pointer can be obtained
0390      *   in a callback handler, but should not be stored beyond the scope of
0391      *   one call to one callback.
0392      */
0393     void *(*init_thread)(const struct mg_context *ctx, int thread_type);
0394 
0395     /* Called when a worker exits.
0396      * The parameters "ctx" and "thread_type" correspond to the "init_thread"
0397      * call. The  "thread_pointer" parameter is the value returned by
0398      * "init_thread".
0399      */
0400     void (*exit_thread)(const struct mg_context *ctx,
0401                         int thread_type,
0402                         void *thread_pointer);
0403 
0404     /* Called when initializing a new connection object.
0405      * Can be used to initialize the connection specific user data
0406      * (mg_request_info->conn_data, mg_get_user_connection_data).
0407      * When the callback is called, it is not yet known if a
0408      * valid HTTP(S) request will be made.
0409      * Parameters:
0410      *   conn: not yet fully initialized connection object
0411      *   conn_data: output parameter, set to initialize the
0412      *              connection specific user data
0413      * Return value:
0414      *   must be 0
0415      *   Otherwise, the result is undefined
0416      */
0417     int (*init_connection)(const struct mg_connection *conn, void **conn_data);
0418 };
0419 
0420 
0421 /* Start web server.
0422 
0423    Parameters:
0424      callbacks: mg_callbacks structure with user-defined callbacks.
0425      options: NULL terminated list of option_name, option_value pairs that
0426               specify Civetweb configuration parameters.
0427 
0428    Side-effects: on UNIX, ignores SIGCHLD and SIGPIPE signals. If custom
0429       processing is required for these, signal handlers must be set up
0430       after calling mg_start().
0431 
0432 
0433    Example:
0434      const char *options[] = {
0435        "document_root", "/var/www",
0436        "listening_ports", "80,443s",
0437        NULL
0438      };
0439      struct mg_context *ctx = mg_start(&my_func, NULL, options);
0440 
0441    Refer to https://github.com/civetweb/civetweb/blob/master/docs/UserManual.md
0442    for the list of valid option and their possible values.
0443 
0444    Return:
0445      web server context, or NULL on error. */
0446 CIVETWEB_API struct mg_context *mg_start(const struct mg_callbacks *callbacks,
0447                                          void *user_data,
0448                                          const char **configuration_options);
0449 
0450 
0451 /* Stop the web server.
0452 
0453    Must be called last, when an application wants to stop the web server and
0454    release all associated resources. This function blocks until all Civetweb
0455    threads are stopped. Context pointer becomes invalid. */
0456 CIVETWEB_API void mg_stop(struct mg_context *);
0457 
0458 
0459 /* Add an additional domain to an already running web server.
0460  *
0461  * Parameters:
0462  *   ctx: Context handle of a server started by mg_start.
0463  *   options: NULL terminated list of option_name, option_value pairs that
0464  *            specify CivetWeb configuration parameters.
0465  *
0466  * Return:
0467  *   < 0 in case of an error
0468  *    -1 for a parameter error
0469  *    -2 invalid options
0470  *    -3 initializing SSL failed
0471  *    -4 mandatory domain option missing
0472  *    -5 duplicate domain
0473  *    -6 out of memory
0474  *   > 0 index / handle of a new domain
0475  */
0476 CIVETWEB_API int mg_start_domain(struct mg_context *ctx,
0477                                  const char **configuration_options);
0478 
0479 
0480 /* mg_request_handler
0481 
0482    Called when a new request comes in.  This callback is URI based
0483    and configured with mg_set_request_handler().
0484 
0485    Parameters:
0486       conn: current connection information.
0487       cbdata: the callback data configured with mg_set_request_handler().
0488    Returns:
0489       0: the handler could not handle the request, so fall through.
0490       1 - 999: the handler processed the request. The return code is
0491                stored as a HTTP status code for the access log. */
0492 typedef int (*mg_request_handler)(struct mg_connection *conn, void *cbdata);
0493 
0494 
0495 /* mg_set_request_handler
0496 
0497    Sets or removes a URI mapping for a request handler.
0498    This function waits until a removing/updating handler becomes unused, so
0499    do not call from the handler itself.
0500 
0501    URI's are ordered and prefixed URI's are supported. For example,
0502    consider two URIs: /a/b and /a
0503            /a   matches /a
0504            /a/b matches /a/b
0505            /a/c matches /a
0506 
0507    Parameters:
0508       ctx: server context
0509       uri: the URI (exact or pattern) for the handler
0510       handler: the callback handler to use when the URI is requested.
0511                If NULL, an already registered handler for this URI will
0512                be removed.
0513                The URI used to remove a handler must match exactly the
0514                one used to register it (not only a pattern match).
0515       cbdata: the callback data to give to the handler when it is called. */
0516 CIVETWEB_API void mg_set_request_handler(struct mg_context *ctx,
0517                                          const char *uri,
0518                                          mg_request_handler handler,
0519                                          void *cbdata);
0520 
0521 
0522 /* Callback types for websocket handlers in C/C++.
0523 
0524    mg_websocket_connect_handler
0525        Is called when the client intends to establish a websocket connection,
0526        before websocket handshake.
0527        Return value:
0528          0: civetweb proceeds with websocket handshake.
0529          1: connection is closed immediately.
0530 
0531    mg_websocket_ready_handler
0532        Is called when websocket handshake is successfully completed, and
0533        connection is ready for data exchange.
0534 
0535    mg_websocket_data_handler
0536        Is called when a data frame has been received from the client.
0537        Parameters:
0538          bits: first byte of the websocket frame, see websocket RFC at
0539                http://tools.ietf.org/html/rfc6455, section 5.2
0540          data, data_len: payload, with mask (if any) already applied.
0541        Return value:
0542          1: keep this websocket connection open.
0543          0: close this websocket connection.
0544 
0545    mg_connection_close_handler
0546        Is called, when the connection is closed.*/
0547 typedef int (*mg_websocket_connect_handler)(const struct mg_connection *,
0548                                             void *);
0549 typedef void (*mg_websocket_ready_handler)(struct mg_connection *, void *);
0550 typedef int (*mg_websocket_data_handler)(struct mg_connection *,
0551                                          int,
0552                                          char *,
0553                                          size_t,
0554                                          void *);
0555 typedef void (*mg_websocket_close_handler)(const struct mg_connection *,
0556                                            void *);
0557 
0558 /* struct mg_websocket_subprotocols
0559  *
0560  * List of accepted subprotocols
0561  */
0562 struct mg_websocket_subprotocols {
0563     int nb_subprotocols;
0564     const char **subprotocols;
0565 };
0566 
0567 /* mg_set_websocket_handler
0568 
0569    Set or remove handler functions for websocket connections.
0570    This function works similar to mg_set_request_handler - see there. */
0571 CIVETWEB_API void
0572 mg_set_websocket_handler(struct mg_context *ctx,
0573                          const char *uri,
0574                          mg_websocket_connect_handler connect_handler,
0575                          mg_websocket_ready_handler ready_handler,
0576                          mg_websocket_data_handler data_handler,
0577                          mg_websocket_close_handler close_handler,
0578                          void *cbdata);
0579 
0580 /* mg_set_websocket_handler
0581 
0582    Set or remove handler functions for websocket connections.
0583    This function works similar to mg_set_request_handler - see there. */
0584 CIVETWEB_API void mg_set_websocket_handler_with_subprotocols(
0585     struct mg_context *ctx,
0586     const char *uri,
0587     struct mg_websocket_subprotocols *subprotocols,
0588     mg_websocket_connect_handler connect_handler,
0589     mg_websocket_ready_handler ready_handler,
0590     mg_websocket_data_handler data_handler,
0591     mg_websocket_close_handler close_handler,
0592     void *cbdata);
0593 
0594 
0595 /* mg_authorization_handler
0596 
0597    Callback function definition for mg_set_auth_handler
0598 
0599    Parameters:
0600       conn: current connection information.
0601       cbdata: the callback data configured with mg_set_request_handler().
0602    Returns:
0603       0: access denied
0604       1: access granted
0605  */
0606 typedef int (*mg_authorization_handler)(struct mg_connection *conn,
0607                                         void *cbdata);
0608 
0609 
0610 /* mg_set_auth_handler
0611 
0612    Sets or removes a URI mapping for an authorization handler.
0613    This function works similar to mg_set_request_handler - see there. */
0614 CIVETWEB_API void mg_set_auth_handler(struct mg_context *ctx,
0615                                       const char *uri,
0616                                       mg_authorization_handler handler,
0617                                       void *cbdata);
0618 
0619 
0620 /* Get the value of particular configuration parameter.
0621    The value returned is read-only. Civetweb does not allow changing
0622    configuration at run time.
0623    If given parameter name is not valid, NULL is returned. For valid
0624    names, return value is guaranteed to be non-NULL. If parameter is not
0625    set, zero-length string is returned. */
0626 CIVETWEB_API const char *mg_get_option(const struct mg_context *ctx,
0627                                        const char *name);
0628 
0629 
0630 /* Get context from connection. */
0631 CIVETWEB_API struct mg_context *
0632 mg_get_context(const struct mg_connection *conn);
0633 
0634 
0635 /* Get user data passed to mg_start from context. */
0636 CIVETWEB_API void *mg_get_user_data(const struct mg_context *ctx);
0637 
0638 
0639 /* Get user data passed to mg_start from connection. */
0640 CIVETWEB_API void *mg_get_user_context_data(const struct mg_connection *conn);
0641 
0642 
0643 /* Get user defined thread pointer for server threads (see init_thread). */
0644 CIVETWEB_API void *mg_get_thread_pointer(const struct mg_connection *conn);
0645 
0646 
0647 /* Set user data for the current connection. */
0648 /* Note: CivetWeb callbacks use "struct mg_connection *conn" as input
0649    when mg_read/mg_write callbacks are allowed in the callback,
0650    while "const struct mg_connection *conn" is used as input in case
0651    calling mg_read/mg_write is not allowed.
0652    Setting the user connection data will modify the connection
0653    object represented by mg_connection *, but it will not read from
0654    or write to the connection. */
0655 /* Note: An alternative is to use the init_connection callback
0656    instead to initialize the user connection data pointer. It is
0657    recommended to supply a pointer to some user defined data structure
0658    as conn_data initializer in init_connection. In case it is required
0659    to change some data after the init_connection call, store another
0660    data pointer in the user defined data structure and modify that
0661    pointer. In either case, after the init_connection callback, only
0662    calls to mg_get_user_connection_data should be required. */
0663 CIVETWEB_API void mg_set_user_connection_data(const struct mg_connection *conn,
0664                                               void *data);
0665 
0666 
0667 /* Get user data set for the current connection. */
0668 CIVETWEB_API void *
0669 mg_get_user_connection_data(const struct mg_connection *conn);
0670 
0671 
0672 /* Get a formatted link corresponding to the current request
0673 
0674    Parameters:
0675       conn: current connection information.
0676       buf: string buffer (out)
0677       buflen: length of the string buffer
0678    Returns:
0679       <0: error
0680       >=0: ok */
0681 CIVETWEB_API int
0682 mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen);
0683 
0684 
0685 struct mg_option {
0686     const char *name;
0687     int type;
0688     const char *default_value;
0689 };
0690 
0691 
0692 /* Configuration types */
0693 enum {
0694     MG_CONFIG_TYPE_UNKNOWN = 0x0,
0695     MG_CONFIG_TYPE_NUMBER = 0x1,
0696     MG_CONFIG_TYPE_STRING = 0x2,
0697     MG_CONFIG_TYPE_FILE = 0x3,
0698     MG_CONFIG_TYPE_DIRECTORY = 0x4,
0699     MG_CONFIG_TYPE_BOOLEAN = 0x5,
0700     MG_CONFIG_TYPE_EXT_PATTERN = 0x6,
0701     MG_CONFIG_TYPE_STRING_LIST = 0x7,
0702     MG_CONFIG_TYPE_STRING_MULTILINE = 0x8,
0703     MG_CONFIG_TYPE_YES_NO_OPTIONAL = 0x9
0704 };
0705 
0706 /* Return array of struct mg_option, representing all valid configuration
0707    options of civetweb.c.
0708    The array is terminated by a NULL name option. */
0709 CIVETWEB_API const struct mg_option *mg_get_valid_options(void);
0710 
0711 
0712 struct mg_server_port {
0713     int protocol;    /* 1 = IPv4, 2 = IPv6, 3 = both */
0714     int port;        /* port number */
0715     int is_ssl;      /* https port: 0 = no, 1 = yes */
0716     int is_redirect; /* redirect all requests: 0 = no, 1 = yes */
0717     int is_optional; /* optional: 0 = no, 1 = yes */
0718     int is_bound;    /* bound: 0 = no, 1 = yes, relevant for optional ports */
0719     int _reserved3;
0720     int _reserved4;
0721 };
0722 
0723 /* Legacy name */
0724 #define mg_server_ports mg_server_port
0725 
0726 
0727 /* Get the list of ports that civetweb is listening on.
0728    The parameter size is the size of the ports array in elements.
0729    The caller is responsibility to allocate the required memory.
0730    This function returns the number of struct mg_server_port elements
0731    filled in, or <0 in case of an error. */
0732 CIVETWEB_API int mg_get_server_ports(const struct mg_context *ctx,
0733                                      int size,
0734                                      struct mg_server_port *ports);
0735 
0736 
0737 /* Add, edit or delete the entry in the passwords file.
0738  *
0739  * This function allows an application to manipulate .htpasswd files on the
0740  * fly by adding, deleting and changing user records. This is one of the
0741  * several ways of implementing authentication on the server side. For another,
0742  * cookie-based way please refer to the examples/chat in the source tree.
0743  *
0744  * Parameter:
0745  *   passwords_file_name: Path and name of a file storing multiple passwords
0746  *   realm: HTTP authentication realm (authentication domain) name
0747  *   user: User name
0748  *   password:
0749  *     If password is not NULL, entry modified or added.
0750  *     If password is NULL, entry is deleted.
0751  *
0752  *  Return:
0753  *    1 on success, 0 on error.
0754  */
0755 CIVETWEB_API int mg_modify_passwords_file(const char *passwords_file_name,
0756                                           const char *realm,
0757                                           const char *user,
0758                                           const char *password);
0759 
0760 
0761 /* Same as mg_modify_passwords_file, but instead of the plain-text
0762  * password, the HA1 hash is specified. The plain-text password is
0763  * not made known to civetweb.
0764  *
0765  * The HA1 hash is the MD5 checksum of a "user:realm:password" string
0766  * in lower-case hex format. For example, if the user name is "myuser",
0767  * the realm is "myrealm", and the password is "secret", then the HA1 is
0768  * e67fd3248b58975c3e89ff18ecb75e2f.
0769  */
0770 CIVETWEB_API int mg_modify_passwords_file_ha1(const char *passwords_file_name,
0771                                               const char *realm,
0772                                               const char *user,
0773                                               const char *ha1);
0774 
0775 
0776 /* Return information associated with the request.
0777  * Use this function to implement a server and get data about a request
0778  * from a HTTP/HTTPS client.
0779  * Note: Before CivetWeb 1.10, this function could be used to read
0780  * a response from a server, when implementing a client, although the
0781  * values were never returned in appropriate mg_request_info elements.
0782  * It is strongly advised to use mg_get_response_info for clients.
0783  */
0784 CIVETWEB_API const struct mg_request_info *
0785 mg_get_request_info(const struct mg_connection *);
0786 
0787 
0788 /* Return information associated with a HTTP/HTTPS response.
0789  * Use this function in a client, to check the response from
0790  * the server. */
0791 CIVETWEB_API const struct mg_response_info *
0792 mg_get_response_info(const struct mg_connection *);
0793 
0794 
0795 /* Send data to the client.
0796    Return:
0797     0   when the connection has been closed
0798     -1  on error
0799     >0  number of bytes written on success */
0800 CIVETWEB_API int mg_write(struct mg_connection *, const void *buf, size_t len);
0801 
0802 
0803 /* Send data to a websocket client wrapped in a websocket frame.  Uses
0804    mg_lock_connection to ensure that the transmission is not interrupted,
0805    i.e., when the application is proactively communicating and responding to
0806    a request simultaneously.
0807 
0808    Send data to a websocket client wrapped in a websocket frame.
0809    This function is available when civetweb is compiled with -DUSE_WEBSOCKET
0810 
0811    Return:
0812     0   when the connection has been closed
0813     -1  on error
0814     >0  number of bytes written on success */
0815 CIVETWEB_API int mg_websocket_write(struct mg_connection *conn,
0816                                     int opcode,
0817                                     const char *data,
0818                                     size_t data_len);
0819 
0820 
0821 /* Send data to a websocket server wrapped in a masked websocket frame.  Uses
0822    mg_lock_connection to ensure that the transmission is not interrupted,
0823    i.e., when the application is proactively communicating and responding to
0824    a request simultaneously.
0825 
0826    Send data to a websocket server wrapped in a masked websocket frame.
0827    This function is available when civetweb is compiled with -DUSE_WEBSOCKET
0828 
0829    Return:
0830     0   when the connection has been closed
0831     -1  on error
0832     >0  number of bytes written on success */
0833 CIVETWEB_API int mg_websocket_client_write(struct mg_connection *conn,
0834                                            int opcode,
0835                                            const char *data,
0836                                            size_t data_len);
0837 
0838 
0839 /* Blocks until unique access is obtained to this connection. Intended for use
0840    with websockets only.
0841    Invoke this before mg_write or mg_printf when communicating with a
0842    websocket if your code has server-initiated communication as well as
0843    communication in direct response to a message.
0844    Do not acquire this lock while holding mg_lock_context(). */
0845 CIVETWEB_API void mg_lock_connection(struct mg_connection *conn);
0846 CIVETWEB_API void mg_unlock_connection(struct mg_connection *conn);
0847 
0848 
0849 /* Lock server context.  This lock may be used to protect resources
0850    that are shared between different connection/worker threads.
0851    If the given context is not server, these functions do nothing. */
0852 CIVETWEB_API void mg_lock_context(struct mg_context *ctx);
0853 CIVETWEB_API void mg_unlock_context(struct mg_context *ctx);
0854 
0855 
0856 /* WebSocket OpcCodes, from http://tools.ietf.org/html/rfc6455 */
0857 enum {
0858     MG_WEBSOCKET_OPCODE_CONTINUATION = 0x0,
0859     MG_WEBSOCKET_OPCODE_TEXT = 0x1,
0860     MG_WEBSOCKET_OPCODE_BINARY = 0x2,
0861     MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE = 0x8,
0862     MG_WEBSOCKET_OPCODE_PING = 0x9,
0863     MG_WEBSOCKET_OPCODE_PONG = 0xa
0864 };
0865 
0866 
0867 /* Macros for enabling compiler-specific checks for printf-like arguments. */
0868 #undef PRINTF_FORMAT_STRING
0869 #if defined(_MSC_VER) && _MSC_VER >= 1400
0870 #include <sal.h>
0871 #if defined(_MSC_VER) && _MSC_VER > 1400
0872 #define PRINTF_FORMAT_STRING(s) _Printf_format_string_ s
0873 #else
0874 #define PRINTF_FORMAT_STRING(s) __format_string s
0875 #endif
0876 #else
0877 #define PRINTF_FORMAT_STRING(s) s
0878 #endif
0879 
0880 #ifdef __GNUC__
0881 #define PRINTF_ARGS(x, y) __attribute__((format(printf, x, y)))
0882 #else
0883 #define PRINTF_ARGS(x, y)
0884 #endif
0885 
0886 
0887 /* Send data to the client using printf() semantics.
0888    Works exactly like mg_write(), but allows to do message formatting. */
0889 CIVETWEB_API int mg_printf(struct mg_connection *,
0890                            PRINTF_FORMAT_STRING(const char *fmt),
0891                            ...) PRINTF_ARGS(2, 3);
0892 
0893 
0894 /* Send a part of the message body, if chunked transfer encoding is set.
0895  * Only use this function after sending a complete HTTP request or response
0896  * header with "Transfer-Encoding: chunked" set. */
0897 CIVETWEB_API int mg_send_chunk(struct mg_connection *conn,
0898                                const char *chunk,
0899                                unsigned int chunk_len);
0900 
0901 
0902 /* Send contents of the entire file together with HTTP headers.
0903  * Parameters:
0904  *   conn: Current connection information.
0905  *   path: Full path to the file to send.
0906  * This function has been superseded by mg_send_mime_file
0907  */
0908 CIVETWEB_API void mg_send_file(struct mg_connection *conn, const char *path);
0909 
0910 
0911 /* Send contents of the file without HTTP headers.
0912  * The code must send a valid HTTP response header before using this function.
0913  *
0914  * Parameters:
0915  *   conn: Current connection information.
0916  *   path: Full path to the file to send.
0917  *
0918  * Return:
0919  *   < 0   Error
0920  */
0921 CIVETWEB_API int mg_send_file_body(struct mg_connection *conn,
0922                                    const char *path);
0923 
0924 
0925 /* Send HTTP error reply. */
0926 CIVETWEB_API int mg_send_http_error(struct mg_connection *conn,
0927                                     int status_code,
0928                                     PRINTF_FORMAT_STRING(const char *fmt),
0929                                     ...) PRINTF_ARGS(3, 4);
0930 
0931 
0932 /* Send "HTTP 200 OK" response header.
0933  * After calling this function, use mg_write or mg_send_chunk to send the
0934  * response body.
0935  * Parameters:
0936  *   conn: Current connection handle.
0937  *   mime_type: Set Content-Type for the following content.
0938  *   content_length: Size of the following content, if content_length >= 0.
0939  *                   Will set transfer-encoding to chunked, if set to -1.
0940  * Return:
0941  *   < 0   Error
0942  */
0943 CIVETWEB_API int mg_send_http_ok(struct mg_connection *conn,
0944                                  const char *mime_type,
0945                                  long long content_length);
0946 
0947 
0948 /* Send "HTTP 30x" redirect response.
0949  * The response has content-size zero: do not send any body data after calling
0950  * this function.
0951  * Parameters:
0952  *   conn: Current connection handle.
0953  *   target_url: New location.
0954  *   redirect_code: HTTP redirect type. Could be 301, 302, 303, 307, 308.
0955  * Return:
0956  *   < 0   Error (-1 send error, -2 parameter error)
0957  */
0958 CIVETWEB_API int mg_send_http_redirect(struct mg_connection *conn,
0959                                        const char *target_url,
0960                                        int redirect_code);
0961 
0962 
0963 /* Send HTTP digest access authentication request.
0964  * Browsers will send a user name and password in their next request, showing
0965  * an authentication dialog if the password is not stored.
0966  * Parameters:
0967  *   conn: Current connection handle.
0968  *   realm: Authentication realm. If NULL is supplied, the sever domain
0969  *          set in the authentication_domain configuration is used.
0970  * Return:
0971  *   < 0   Error
0972  */
0973 CIVETWEB_API int
0974 mg_send_digest_access_authentication_request(struct mg_connection *conn,
0975                                              const char *realm);
0976 
0977 
0978 /* Check if the current request has a valid authentication token set.
0979  * A file is used to provide a list of valid user names, realms and
0980  * password hashes. The file can be created and modified using the
0981  * mg_modify_passwords_file API function.
0982  * Parameters:
0983  *   conn: Current connection handle.
0984  *   realm: Authentication realm. If NULL is supplied, the sever domain
0985  *          set in the authentication_domain configuration is used.
0986  *   filename: Path and name of a file storing multiple password hashes.
0987  * Return:
0988  *   > 0   Valid authentication
0989  *   0     Invalid authentication
0990  *   < 0   Error (all values < 0 should be considered as invalid
0991  *         authentication, future error codes will have negative
0992  *         numbers)
0993  *   -1    Parameter error
0994  *   -2    File not found
0995  */
0996 CIVETWEB_API int
0997 mg_check_digest_access_authentication(struct mg_connection *conn,
0998                                       const char *realm,
0999                                       const char *filename);
1000 
1001 
1002 /* Send contents of the entire file together with HTTP headers.
1003  * Parameters:
1004  *   conn: Current connection handle.
1005  *   path: Full path to the file to send.
1006  *   mime_type: Content-Type for file.  NULL will cause the type to be
1007  *              looked up by the file extension.
1008  */
1009 CIVETWEB_API void mg_send_mime_file(struct mg_connection *conn,
1010                                     const char *path,
1011                                     const char *mime_type);
1012 
1013 
1014 /* Send contents of the entire file together with HTTP headers.
1015    Parameters:
1016      conn: Current connection information.
1017      path: Full path to the file to send.
1018      mime_type: Content-Type for file.  NULL will cause the type to be
1019                 looked up by the file extension.
1020      additional_headers: Additional custom header fields appended to the header.
1021                          Each header should start with an X-, to ensure it is
1022                          not included twice.
1023                          NULL does not append anything.
1024 */
1025 CIVETWEB_API void mg_send_mime_file2(struct mg_connection *conn,
1026                                      const char *path,
1027                                      const char *mime_type,
1028                                      const char *additional_headers);
1029 
1030 
1031 /* Store body data into a file. */
1032 CIVETWEB_API long long mg_store_body(struct mg_connection *conn,
1033                                      const char *path);
1034 /* Read entire request body and store it in a file "path".
1035    Return:
1036      < 0   Error
1037      >= 0  Number of bytes stored in file "path".
1038 */
1039 
1040 
1041 /* Read data from the remote end, return number of bytes read.
1042    Return:
1043      0     connection has been closed by peer. No more data could be read.
1044      < 0   read error. No more data could be read from the connection.
1045      > 0   number of bytes read into the buffer. */
1046 CIVETWEB_API int mg_read(struct mg_connection *, void *buf, size_t len);
1047 
1048 
1049 /* Get the value of particular HTTP header.
1050 
1051    This is a helper function. It traverses request_info->http_headers array,
1052    and if the header is present in the array, returns its value. If it is
1053    not present, NULL is returned. */
1054 CIVETWEB_API const char *mg_get_header(const struct mg_connection *,
1055                                        const char *name);
1056 
1057 
1058 /* Get a value of particular form variable.
1059 
1060    Parameters:
1061      data: pointer to form-uri-encoded buffer. This could be either POST data,
1062            or request_info.query_string.
1063      data_len: length of the encoded data.
1064      var_name: variable name to decode from the buffer
1065      dst: destination buffer for the decoded variable
1066      dst_len: length of the destination buffer
1067 
1068    Return:
1069      On success, length of the decoded variable.
1070      On error:
1071         -1 (variable not found).
1072         -2 (destination buffer is NULL, zero length or too small to hold the
1073             decoded variable).
1074 
1075    Destination buffer is guaranteed to be '\0' - terminated if it is not
1076    NULL or zero length. */
1077 CIVETWEB_API int mg_get_var(const char *data,
1078                             size_t data_len,
1079                             const char *var_name,
1080                             char *dst,
1081                             size_t dst_len);
1082 
1083 
1084 /* Get a value of particular form variable.
1085 
1086    Parameters:
1087      data: pointer to form-uri-encoded buffer. This could be either POST data,
1088            or request_info.query_string.
1089      data_len: length of the encoded data.
1090      var_name: variable name to decode from the buffer
1091      dst: destination buffer for the decoded variable
1092      dst_len: length of the destination buffer
1093      occurrence: which occurrence of the variable, 0 is the 1st, 1 the 2nd, ...
1094                  this makes it possible to parse a query like
1095                  b=x&a=y&a=z which will have occurrence values b:0, a:0 and a:1
1096 
1097    Return:
1098      On success, length of the decoded variable.
1099      On error:
1100         -1 (variable not found).
1101         -2 (destination buffer is NULL, zero length or too small to hold the
1102             decoded variable).
1103 
1104    Destination buffer is guaranteed to be '\0' - terminated if it is not
1105    NULL or zero length. */
1106 CIVETWEB_API int mg_get_var2(const char *data,
1107                              size_t data_len,
1108                              const char *var_name,
1109                              char *dst,
1110                              size_t dst_len,
1111                              size_t occurrence);
1112 
1113 
1114 /* Split form encoded data into a list of key value pairs.
1115    A form encoded input might be a query string, the body of a
1116    x-www-form-urlencoded POST request or any other data with this
1117    structure: "keyName1=value1&keyName2=value2&keyName3=value3".
1118    Values might be percent-encoded - this function will transform
1119    them to the unencoded characters.
1120    The input string is modified by this function: To split the
1121    "query_string" member of struct request_info, create a copy first
1122    (e.g., using strdup).
1123    The function itself does not allocate memory. Thus, it is not
1124    required to free any pointer returned from this function.
1125    The output list of is limited to MG_MAX_FORM_FIELDS name-value-
1126    pairs. The default value is reasonably oversized for typical
1127    applications, however, for special purpose systems it might be
1128    required to increase this value at compile time.
1129 
1130    Parameters:
1131      data: form encoded input string. Will be modified by this function.
1132      form_fields: output list of name/value-pairs. A buffer with a size
1133                   specified by num_form_fields must be provided by the
1134                   caller.
1135      num_form_fields: Size of provided form_fields buffer in number of
1136                       "struct mg_header" elements.
1137 
1138    Return:
1139      On success: number of form_fields filled
1140      On error:
1141         -1 (parameter error). */
1142 CIVETWEB_API int mg_split_form_urlencoded(char *data,
1143                                           struct mg_header *form_fields,
1144                                           unsigned num_form_fields);
1145 
1146 
1147 /* Fetch value of certain cookie variable into the destination buffer.
1148 
1149    Destination buffer is guaranteed to be '\0' - terminated. In case of
1150    failure, dst[0] == '\0'. Note that RFC allows many occurrences of the same
1151    parameter. This function returns only first occurrence.
1152 
1153    Return:
1154      On success, value length.
1155      On error:
1156         -1 (either "Cookie:" header is not present at all or the requested
1157             parameter is not found).
1158         -2 (destination buffer is NULL, zero length or too small to hold the
1159             value). */
1160 CIVETWEB_API int mg_get_cookie(const char *cookie,
1161                                const char *var_name,
1162                                char *buf,
1163                                size_t buf_len);
1164 
1165 
1166 /* Download data from the remote web server.
1167      host: host name to connect to, e.g. "foo.com", or "10.12.40.1".
1168      port: port number, e.g. 80.
1169      use_ssl: whether to use SSL connection.
1170      error_buffer, error_buffer_size: error message placeholder.
1171      request_fmt,...: HTTP request.
1172    Return:
1173      On success, valid pointer to the new connection, suitable for mg_read().
1174      On error, NULL. error_buffer contains error message.
1175    Example:
1176      char ebuf[100];
1177      struct mg_connection *conn;
1178      conn = mg_download("google.com", 80, 0, ebuf, sizeof(ebuf),
1179                         "%s", "GET / HTTP/1.0\r\nHost: google.com\r\n\r\n");
1180 
1181    mg_download is equivalent to calling mg_connect_client followed by
1182    mg_printf and mg_get_response. Using these three functions directly may
1183    allow more control as compared to using mg_download.
1184  */
1185 CIVETWEB_API struct mg_connection *
1186 mg_download(const char *host,
1187             int port,
1188             int use_ssl,
1189             char *error_buffer,
1190             size_t error_buffer_size,
1191             PRINTF_FORMAT_STRING(const char *request_fmt),
1192             ...) PRINTF_ARGS(6, 7);
1193 
1194 
1195 /* Close the connection opened by mg_download(). */
1196 CIVETWEB_API void mg_close_connection(struct mg_connection *conn);
1197 
1198 
1199 /* This structure contains callback functions for handling form fields.
1200    It is used as an argument to mg_handle_form_request. */
1201 struct mg_form_data_handler {
1202     /* This callback function is called, if a new field has been found.
1203      * The return value of this callback is used to define how the field
1204      * should be processed.
1205      *
1206      * Parameters:
1207      *   key: Name of the field ("name" property of the HTML input field).
1208      *   filename: Name of a file to upload, at the client computer.
1209      *             Only set for input fields of type "file", otherwise NULL.
1210      *   path: Output parameter: File name (incl. path) to store the file
1211      *         at the server computer. Only used if MG_FORM_FIELD_STORAGE_STORE
1212      *         is returned by this callback. Existing files will be
1213      *         overwritten.
1214      *   pathlen: Length of the buffer for path.
1215      *   user_data: Value of the member user_data of mg_form_data_handler
1216      *
1217      * Return value:
1218      *   The callback must return the intended storage for this field
1219      *   (See MG_FORM_FIELD_STORAGE_*).
1220      */
1221     int (*field_found)(const char *key,
1222                        const char *filename,
1223                        char *path,
1224                        size_t pathlen,
1225                        void *user_data);
1226 
1227     /* If the "field_found" callback returned MG_FORM_FIELD_STORAGE_GET,
1228      * this callback will receive the field data.
1229      *
1230      * Parameters:
1231      *   key: Name of the field ("name" property of the HTML input field).
1232      *   value: Value of the input field.
1233      *   user_data: Value of the member user_data of mg_form_data_handler
1234      *
1235      * Return value:
1236      *   The return code determines how the server should continue processing
1237      *   the current request (See MG_FORM_FIELD_HANDLE_*).
1238      */
1239     int (*field_get)(const char *key,
1240                      const char *value,
1241                      size_t valuelen,
1242                      void *user_data);
1243 
1244     /* If the "field_found" callback returned MG_FORM_FIELD_STORAGE_STORE,
1245      * the data will be stored into a file. If the file has been written
1246      * successfully, this callback will be called. This callback will
1247      * not be called for only partially uploaded files. The
1248      * mg_handle_form_request function will either store the file completely
1249      * and call this callback, or it will remove any partial content and
1250      * not call this callback function.
1251      *
1252      * Parameters:
1253      *   path: Path of the file stored at the server.
1254      *   file_size: Size of the stored file in bytes.
1255      *   user_data: Value of the member user_data of mg_form_data_handler
1256      *
1257      * Return value:
1258      *   The return code determines how the server should continue processing
1259      *   the current request (See MG_FORM_FIELD_HANDLE_*).
1260      */
1261     int (*field_store)(const char *path, long long file_size, void *user_data);
1262 
1263     /* User supplied argument, passed to all callback functions. */
1264     void *user_data;
1265 };
1266 
1267 
1268 /* Return values definition for the "field_found" callback in
1269  * mg_form_data_handler. */
1270 enum {
1271     /* Skip this field (neither get nor store it). Continue with the
1272      * next field. */
1273     MG_FORM_FIELD_STORAGE_SKIP = 0x0,
1274     /* Get the field value. */
1275     MG_FORM_FIELD_STORAGE_GET = 0x1,
1276     /* Store the field value into a file. */
1277     MG_FORM_FIELD_STORAGE_STORE = 0x2,
1278     /* Stop parsing this request. Skip the remaining fields. */
1279     MG_FORM_FIELD_STORAGE_ABORT = 0x10
1280 };
1281 
1282 /* Return values for "field_get" and "field_store" */
1283 enum {
1284     /* Only "field_get": If there is more data in this field, get the next
1285      * chunk. Otherwise: handle the next field. */
1286     MG_FORM_FIELD_HANDLE_GET = 0x1,
1287     /* Handle the next field */
1288     MG_FORM_FIELD_HANDLE_NEXT = 0x8,
1289     /* Stop parsing this request */
1290     MG_FORM_FIELD_HANDLE_ABORT = 0x10
1291 };
1292 
1293 
1294 /* Process form data.
1295  * Returns the number of fields handled, or < 0 in case of an error.
1296  * Note: It is possible that several fields are already handled successfully
1297  * (e.g., stored into files), before the request handling is stopped with an
1298  * error. In this case a number < 0 is returned as well.
1299  * In any case, it is the duty of the caller to remove files once they are
1300  * no longer required. */
1301 CIVETWEB_API int mg_handle_form_request(struct mg_connection *conn,
1302                                         struct mg_form_data_handler *fdh);
1303 
1304 
1305 /* Convenience function -- create detached thread.
1306    Return: 0 on success, non-0 on error. */
1307 typedef void *(*mg_thread_func_t)(void *);
1308 CIVETWEB_API int mg_start_thread(mg_thread_func_t f, void *p);
1309 
1310 
1311 /* Return builtin mime type for the given file name.
1312    For unrecognized extensions, "text/plain" is returned. */
1313 CIVETWEB_API const char *mg_get_builtin_mime_type(const char *file_name);
1314 
1315 
1316 /* Get text representation of HTTP status code. */
1317 CIVETWEB_API const char *
1318 mg_get_response_code_text(const struct mg_connection *conn, int response_code);
1319 
1320 
1321 /* Return CivetWeb version. */
1322 CIVETWEB_API const char *mg_version(void);
1323 
1324 
1325 /* URL-decode input buffer into destination buffer.
1326    0-terminate the destination buffer.
1327    form-url-encoded data differs from URI encoding in a way that it
1328    uses '+' as character for space, see RFC 1866 section 8.2.1
1329    http://ftp.ics.uci.edu/pub/ietf/html/rfc1866.txt
1330    Return: length of the decoded data, or -1 if dst buffer is too small. */
1331 CIVETWEB_API int mg_url_decode(const char *src,
1332                                int src_len,
1333                                char *dst,
1334                                int dst_len,
1335                                int is_form_url_encoded);
1336 
1337 
1338 /* URL-encode input buffer into destination buffer.
1339    returns the length of the resulting buffer or -1
1340    is the buffer is too small. */
1341 CIVETWEB_API int mg_url_encode(const char *src, char *dst, size_t dst_len);
1342 
1343 
1344 /* BASE64-encode input buffer into destination buffer.
1345    returns -1 on OK. */
1346 CIVETWEB_API int mg_base64_encode(const unsigned char *src,
1347                                   size_t src_len,
1348                                   char *dst,
1349                                   size_t *dst_len);
1350 
1351 
1352 /* BASE64-decode input buffer into destination buffer.
1353    returns -1 on OK. */
1354 CIVETWEB_API int mg_base64_decode(const char *src,
1355                                   size_t src_len,
1356                                   unsigned char *dst,
1357                                   size_t *dst_len);
1358 
1359 
1360 /* MD5 hash given strings.
1361    Buffer 'buf' must be 33 bytes long. Varargs is a NULL terminated list of
1362    ASCIIz strings. When function returns, buf will contain human-readable
1363    MD5 hash. Example:
1364      char buf[33];
1365      mg_md5(buf, "aa", "bb", NULL); */
1366 CIVETWEB_API char *mg_md5(char buf[33], ...);
1367 
1368 
1369 #if !defined(MG_MATCH_CONTEXT_MAX_MATCHES)
1370 #define MG_MATCH_CONTEXT_MAX_MATCHES (32)
1371 #endif
1372 
1373 struct mg_match_element {
1374     const char *str; /* First character matching wildcard */
1375     size_t len;      /* Number of character matching wildcard */
1376 };
1377 
1378 struct mg_match_context {
1379     int case_sensitive; /* Input: 1 (case sensitive) or 0 (insensitive) */
1380     size_t num_matches; /* Output: Number of wildcard matches returned. */
1381     struct mg_match_element match[MG_MATCH_CONTEXT_MAX_MATCHES]; /* Output */
1382 };
1383 
1384 
1385 #if defined(MG_EXPERIMENTAL_INTERFACES)
1386 /* Pattern matching and extraction function.
1387    Parameters:
1388      pat: Pattern string (see UserManual.md)
1389      str: String to search for match patterns.
1390      mcx: Match context (optional, can be NULL).
1391 
1392    Return:
1393      Number of characters matched.
1394      -1 if no valid match was found.
1395      Note: 0 characters might be a valid match for some patterns.
1396 */
1397 CIVETWEB_API ptrdiff_t mg_match(const char *pat,
1398                                 const char *str,
1399                                 struct mg_match_context *mcx);
1400 #endif
1401 
1402 
1403 /* Print error message to the opened error log stream.
1404    This utilizes the provided logging configuration.
1405      conn: connection (not used for sending data, but to get perameters)
1406      fmt: format string without the line return
1407      ...: variable argument list
1408    Example:
1409      mg_cry(conn,"i like %s", "logging"); */
1410 CIVETWEB_API void mg_cry(const struct mg_connection *conn,
1411                          PRINTF_FORMAT_STRING(const char *fmt),
1412                          ...) PRINTF_ARGS(2, 3);
1413 
1414 
1415 /* utility methods to compare two buffers, case insensitive. */
1416 CIVETWEB_API int mg_strcasecmp(const char *s1, const char *s2);
1417 CIVETWEB_API int mg_strncasecmp(const char *s1, const char *s2, size_t len);
1418 
1419 
1420 /* Connect to a websocket as a client
1421    Parameters:
1422      host: host to connect to, i.e. "echo.websocket.org" or "192.168.1.1" or
1423    "localhost"
1424      port: server port
1425      use_ssl: make a secure connection to server
1426      error_buffer, error_buffer_size: buffer for an error message
1427      path: server path you are trying to connect to, i.e. if connection to
1428    localhost/app, path should be "/app"
1429      origin: value of the Origin HTTP header
1430      data_func: callback that should be used when data is received from the
1431    server
1432      user_data: user supplied argument
1433 
1434    Return:
1435      On success, valid mg_connection object.
1436      On error, NULL. Se error_buffer for details.
1437 */
1438 CIVETWEB_API struct mg_connection *
1439 mg_connect_websocket_client(const char *host,
1440                             int port,
1441                             int use_ssl,
1442                             char *error_buffer,
1443                             size_t error_buffer_size,
1444                             const char *path,
1445                             const char *origin,
1446                             mg_websocket_data_handler data_func,
1447                             mg_websocket_close_handler close_func,
1448                             void *user_data);
1449 
1450 CIVETWEB_API struct mg_connection *
1451 mg_connect_websocket_client_extensions(const char *host,
1452                                        int port,
1453                                        int use_ssl,
1454                                        char *error_buffer,
1455                                        size_t error_buffer_size,
1456                                        const char *path,
1457                                        const char *origin,
1458                                        const char *extensions,
1459                                        mg_websocket_data_handler data_func,
1460                                        mg_websocket_close_handler close_func,
1461                                        void *user_data);
1462 
1463 
1464 /* Connect to a TCP server as a client (can be used to connect to a HTTP server)
1465    Parameters:
1466      host: host to connect to, i.e. "www.wikipedia.org" or "192.168.1.1" or
1467    "localhost"
1468      port: server port
1469      use_ssl: make a secure connection to server
1470      error_buffer, error_buffer_size: buffer for an error message
1471 
1472    Return:
1473      On success, valid mg_connection object.
1474      On error, NULL. Se error_buffer for details.
1475 */
1476 CIVETWEB_API struct mg_connection *mg_connect_client(const char *host,
1477                                                      int port,
1478                                                      int use_ssl,
1479                                                      char *error_buffer,
1480                                                      size_t error_buffer_size);
1481 
1482 
1483 struct mg_client_options {
1484     const char *host;
1485     int port;
1486     const char *client_cert;
1487     const char *server_cert;
1488     const char *host_name;
1489     /* TODO: add more data */
1490 };
1491 
1492 
1493 CIVETWEB_API struct mg_connection *
1494 mg_connect_client_secure(const struct mg_client_options *client_options,
1495                          char *error_buffer,
1496                          size_t error_buffer_size);
1497 
1498 
1499 CIVETWEB_API struct mg_connection *mg_connect_websocket_client_secure(
1500     const struct mg_client_options *client_options,
1501     char *error_buffer,
1502     size_t error_buffer_size,
1503     const char *path,
1504     const char *origin,
1505     mg_websocket_data_handler data_func,
1506     mg_websocket_close_handler close_func,
1507     void *user_data);
1508 
1509 CIVETWEB_API struct mg_connection *
1510 mg_connect_websocket_client_secure_extensions(
1511     const struct mg_client_options *client_options,
1512     char *error_buffer,
1513     size_t error_buffer_size,
1514     const char *path,
1515     const char *origin,
1516     const char *extensions,
1517     mg_websocket_data_handler data_func,
1518     mg_websocket_close_handler close_func,
1519     void *user_data);
1520 
1521 #if defined(MG_LEGACY_INTERFACE) /* 2019-11-02 */
1522 enum { TIMEOUT_INFINITE = -1 };
1523 #endif
1524 enum { MG_TIMEOUT_INFINITE = -1 };
1525 
1526 
1527 /* Wait for a response from the server
1528    Parameters:
1529      conn: connection
1530      ebuf, ebuf_len: error message placeholder.
1531      timeout: time to wait for a response in milliseconds (if < 0 then wait
1532    forever)
1533 
1534    Return:
1535      On success, >= 0
1536      On error/timeout, < 0
1537 */
1538 CIVETWEB_API int mg_get_response(struct mg_connection *conn,
1539                                  char *ebuf,
1540                                  size_t ebuf_len,
1541                                  int timeout);
1542 
1543 
1544 /* mg_response_header_* functions can be used from server callbacks
1545  * to prepare HTTP server response headers. Using this function will
1546  * allow a callback to work with HTTP/1.x and HTTP/2.
1547  */
1548 
1549 /* Initialize a new HTTP response
1550  * Parameters:
1551  *   conn: Current connection handle.
1552  *   status: HTTP status code (e.g., 200 for "OK").
1553  * Return:
1554  *   0:    ok
1555  *  -1:    parameter error
1556  *  -2:    invalid connection type
1557  *  -3:    invalid connection status
1558  *  -4:    network error (only if built with NO_RESPONSE_BUFFERING)
1559  */
1560 CIVETWEB_API int mg_response_header_start(struct mg_connection *conn,
1561                                           int status);
1562 
1563 
1564 /* Add a new HTTP response header line
1565  * Parameters:
1566  *   conn: Current connection handle.
1567  *   header: Header name.
1568  *   value: Header value.
1569  *   value_len: Length of header value, excluding the terminating zero.
1570  *              Use -1 for "strlen(value)".
1571  * Return:
1572  *   0:    ok
1573  *  -1:    parameter error
1574  *  -2:    invalid connection type
1575  *  -3:    invalid connection status
1576  *  -4:    too many headers
1577  *  -5:    out of memory
1578  */
1579 CIVETWEB_API int mg_response_header_add(struct mg_connection *conn,
1580                                         const char *header,
1581                                         const char *value,
1582                                         int value_len);
1583 
1584 
1585 /* Add a complete header string (key + value).
1586  * This function is less efficient as compared to mg_response_header_add,
1587  * and should only be used to convert complete HTTP/1.x header lines.
1588  * Parameters:
1589  *   conn: Current connection handle.
1590  *   http1_headers: Header line(s) in the form "name: value\r\n".
1591  * Return:
1592  *  >=0:   no error, number of header lines added
1593  *  -1:    parameter error
1594  *  -2:    invalid connection type
1595  *  -3:    invalid connection status
1596  *  -4:    too many headers
1597  *  -5:    out of memory
1598  */
1599 CIVETWEB_API int mg_response_header_add_lines(struct mg_connection *conn,
1600                                               const char *http1_headers);
1601 
1602 
1603 /* Send http response
1604  * Parameters:
1605  *   conn: Current connection handle.
1606  * Return:
1607  *   0:    ok
1608  *  -1:    parameter error
1609  *  -2:    invalid connection type
1610  *  -3:    invalid connection status
1611  *  -4:    sending failed (network error)
1612  */
1613 CIVETWEB_API int mg_response_header_send(struct mg_connection *conn);
1614 
1615 
1616 /* Check which features where set when the civetweb library has been compiled.
1617    The function explicitly addresses compile time defines used when building
1618    the library - it does not mean, the feature has been initialized using a
1619    mg_init_library call.
1620    mg_check_feature can be called anytime, even before mg_init_library has
1621    been called.
1622 
1623    Parameters:
1624      feature: specifies which feature should be checked
1625        The value is a bit mask. The individual bits are defined as:
1626          1  serve files (NO_FILES not set)
1627          2  support HTTPS (NO_SSL not set)
1628          4  support CGI (NO_CGI not set)
1629          8  support IPv6 (USE_IPV6 set)
1630         16  support WebSocket (USE_WEBSOCKET set)
1631         32  support Lua scripts and Lua server pages (USE_LUA is set)
1632         64  support server side JavaScript (USE_DUKTAPE is set)
1633        128  support caching (NO_CACHING not set)
1634        256  support server statistics (USE_SERVER_STATS is set)
1635        512  support for on the fly compression (USE_ZLIB is set)
1636 
1637        These values are defined as MG_FEATURES_*
1638 
1639        The result is undefined, if bits are set that do not represent a
1640        defined feature (currently: feature >= 1024).
1641        The result is undefined, if no bit is set (feature == 0).
1642 
1643    Return:
1644      If a feature is available, the corresponding bit is set
1645      If a feature is not available, the bit is 0
1646 */
1647 CIVETWEB_API unsigned mg_check_feature(unsigned feature);
1648 
1649 
1650 /* Get information on the system. Useful for support requests.
1651    Parameters:
1652      buffer: Store system information as string here.
1653      buflen: Length of buffer (including a byte required for a terminating 0).
1654    Return:
1655      Available size of system information, excluding a terminating 0.
1656      The information is complete, if the return value is smaller than buflen.
1657      The result is a JSON formatted string, the exact content may vary.
1658    Note:
1659      It is possible to determine the required buflen, by first calling this
1660      function with buffer = NULL and buflen = NULL. The required buflen is
1661      one byte more than the returned value.
1662 */
1663 CIVETWEB_API int mg_get_system_info(char *buffer, int buflen);
1664 
1665 
1666 /* Get context information. Useful for server diagnosis.
1667    Parameters:
1668      ctx: Context handle
1669      buffer: Store context information here.
1670      buflen: Length of buffer (including a byte required for a terminating 0).
1671    Return:
1672      Available size of system information, excluding a terminating 0.
1673      The information is complete, if the return value is smaller than buflen.
1674      The result is a JSON formatted string, the exact content may vary.
1675      Note:
1676      It is possible to determine the required buflen, by first calling this
1677      function with buffer = NULL and buflen = NULL. The required buflen is
1678      one byte more than the returned value. However, since the available
1679      context information changes, you should allocate a few bytes more.
1680 */
1681 CIVETWEB_API int
1682 mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen);
1683 
1684 
1685 /* Disable HTTP keep-alive on a per-connection basis.
1686    Reference: https://github.com/civetweb/civetweb/issues/727
1687    Parameters:
1688      conn: Current connection handle.
1689 */
1690 CIVETWEB_API void mg_disable_connection_keep_alive(struct mg_connection *conn);
1691 
1692 
1693 #if defined(MG_EXPERIMENTAL_INTERFACES)
1694 /* Get connection information. Useful for server diagnosis.
1695    Parameters:
1696      ctx: Context handle
1697      idx: Connection index
1698      buffer: Store context information here.
1699      buflen: Length of buffer (including a byte required for a terminating 0).
1700    Return:
1701      Available size of system information, excluding a terminating 0.
1702      The information is complete, if the return value is smaller than buflen.
1703      The result is a JSON formatted string, the exact content may vary.
1704    Note:
1705      It is possible to determine the required buflen, by first calling this
1706      function with buffer = NULL and buflen = NULL. The required buflen is
1707      one byte more than the returned value. However, since the available
1708      context information changes, you should allocate a few bytes more.
1709 */
1710 CIVETWEB_API int mg_get_connection_info(const struct mg_context *ctx,
1711                                         int idx,
1712                                         char *buffer,
1713                                         int buflen);
1714 #endif
1715 
1716 
1717 /* New APIs for enhanced option and error handling.
1718    These mg_*2 API functions have the same purpose as their original versions,
1719    but provide additional options and/or provide improved error diagnostics.
1720 
1721    Note: Experimental interfaces may change
1722 */
1723 struct mg_error_data {
1724     unsigned code;           /* error code (number) */
1725     unsigned code_sub;       /* error sub code (number) */
1726     char *text;              /* buffer for error text */
1727     size_t text_buffer_size; /* size of buffer of "text" */
1728 };
1729 
1730 
1731 /* Values for error "code" in mg_error_data */
1732 enum {
1733     /* No error */
1734     MG_ERROR_DATA_CODE_OK = 0u,
1735 
1736     /* Caller provided invalid parameter */
1737     MG_ERROR_DATA_CODE_INVALID_PARAM = 1u,
1738 
1739     /* "configuration_option" contains invalid element */
1740     MG_ERROR_DATA_CODE_INVALID_OPTION = 2u,
1741 
1742     /* Initializen TLS / SSL library failed */
1743     MG_ERROR_DATA_CODE_INIT_TLS_FAILED = 3u,
1744 
1745     /* Mandatory "configuration_option" missing */
1746     MG_ERROR_DATA_CODE_MISSING_OPTION = 4u,
1747 
1748     /* Duplicate "authentication_domain" option */
1749     MG_ERROR_DATA_CODE_DUPLICATE_DOMAIN = 5u,
1750 
1751     /* Not enough memory */
1752     MG_ERROR_DATA_CODE_OUT_OF_MEMORY = 6u,
1753 
1754     /* Server already stopped */
1755     MG_ERROR_DATA_CODE_SERVER_STOPPED = 7u,
1756 
1757     /* mg_init_library must be called first */
1758     MG_ERROR_DATA_CODE_INIT_LIBRARY_FAILED = 8u,
1759 
1760     /* Operating system function failed */
1761     MG_ERROR_DATA_CODE_OS_ERROR = 9u,
1762 
1763     /* Failed to bind to server ports */
1764     MG_ERROR_DATA_CODE_INIT_PORTS_FAILED = 10u,
1765 
1766     /* Failed to switch user (option "run_as_user") */
1767     MG_ERROR_DATA_CODE_INIT_USER_FAILED = 11u,
1768 
1769     /* Access Control List error */
1770     MG_ERROR_DATA_CODE_INIT_ACL_FAILED = 12u,
1771 
1772     /* Global password file error */
1773     MG_ERROR_DATA_CODE_INVALID_PASS_FILE = 13u,
1774 
1775     /* Lua background script init error */
1776     MG_ERROR_DATA_CODE_SCRIPT_ERROR = 14u,
1777 
1778     /* Client: Host not found, invalid IP to connect */
1779     MG_ERROR_DATA_CODE_HOST_NOT_FOUND = 15u,
1780 
1781     /* Client: TCP connect timeout */
1782     MG_ERROR_DATA_CODE_CONNECT_TIMEOUT = 16u,
1783 
1784     /* Client: TCP connect failed */
1785     MG_ERROR_DATA_CODE_CONNECT_FAILED = 17u,
1786 
1787     /* Error using TLS client certificate */
1788     MG_ERROR_DATA_CODE_TLS_CLIENT_CERT_ERROR = 18u,
1789 
1790     /* Error setting trusted TLS server certificate for client connection */
1791     MG_ERROR_DATA_CODE_TLS_SERVER_CERT_ERROR = 19u,
1792 
1793     /* Error establishing TLS connection to HTTPS server */
1794     MG_ERROR_DATA_CODE_TLS_CONNECT_ERROR = 20u
1795 };
1796 
1797 
1798 struct mg_init_data {
1799     const struct mg_callbacks *callbacks; /* callback function pointer */
1800     void *user_data;                      /* data */
1801     const char **configuration_options;
1802 };
1803 
1804 
1805 #if defined(MG_EXPERIMENTAL_INTERFACES)
1806 
1807 CIVETWEB_API struct mg_connection *
1808 mg_connect_client2(const char *host,
1809                    const char *protocol,
1810                    int port,
1811                    const char *path,
1812                    struct mg_init_data *init,
1813                    struct mg_error_data *error);
1814 
1815 CIVETWEB_API int mg_get_response2(struct mg_connection *conn,
1816                                   struct mg_error_data *error,
1817                                   int timeout);
1818 #endif
1819 
1820 
1821 CIVETWEB_API struct mg_context *mg_start2(struct mg_init_data *init,
1822                                           struct mg_error_data *error);
1823 
1824 CIVETWEB_API int mg_start_domain2(struct mg_context *ctx,
1825                                   const char **configuration_options,
1826                                   struct mg_error_data *error);
1827 
1828 
1829 #ifdef __cplusplus
1830 }
1831 #endif /* __cplusplus */
1832 
1833 #endif /* CIVETWEB_HEADER_INCLUDED */