Path: blob/trunk/third_party/cpp/civetweb/civetweb.h
2868 views
/* Copyright (c) 2013-2017 the Civetweb developers1* Copyright (c) 2004-2013 Sergey Lyubka2*3* Permission is hereby granted, free of charge, to any person obtaining a copy4* of this software and associated documentation files (the "Software"), to deal5* in the Software without restriction, including without limitation the rights6* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell7* copies of the Software, and to permit persons to whom the Software is8* furnished to do so, subject to the following conditions:9*10* The above copyright notice and this permission notice shall be included in11* all copies or substantial portions of the Software.12*13* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR14* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,15* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE16* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER17* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,18* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN19* THE SOFTWARE.20*/2122#ifndef CIVETWEB_HEADER_INCLUDED23#define CIVETWEB_HEADER_INCLUDED2425#define CIVETWEB_VERSION "1.11"26#define CIVETWEB_VERSION_MAJOR (1)27#define CIVETWEB_VERSION_MINOR (11)28#define CIVETWEB_VERSION_PATCH (0)2930#ifndef CIVETWEB_API31#if defined(_WIN32)32#if defined(CIVETWEB_DLL_EXPORTS)33#define CIVETWEB_API __declspec(dllexport)34#elif defined(CIVETWEB_DLL_IMPORTS)35#define CIVETWEB_API __declspec(dllimport)36#else37#define CIVETWEB_API38#endif39#elif __GNUC__ >= 440#define CIVETWEB_API __attribute__((visibility("default")))41#else42#define CIVETWEB_API43#endif44#endif4546#include <stddef.h>47#include <stdio.h>4849#ifdef __cplusplus50extern "C" {51#endif /* __cplusplus */525354/* Init Features */55enum {56MG_FEATURES_DEFAULT = 0x0u,5758/* Support files from local directories */59/* Will only work, if NO_FILES is not set. */60MG_FEATURES_FILES = 0x1u,6162/* Support transport layer security (TLS). */63/* SSL is still often used synonymously for TLS. */64/* Will only work, if NO_SSL is not set. */65MG_FEATURES_TLS = 0x2u,66MG_FEATURES_SSL = 0x2u,6768/* Support common gateway interface (CGI). */69/* Will only work, if NO_CGI is not set. */70MG_FEATURES_CGI = 0x4u,7172/* Support IPv6. */73/* Will only work, if USE_IPV6 is set. */74MG_FEATURES_IPV6 = 0x8u,7576/* Support WebSocket protocol. */77/* Will only work, if USE_WEBSOCKET is set. */78MG_FEATURES_WEBSOCKET = 0x10u,7980/* Support server side Lua scripting. */81/* Will only work, if USE_LUA is set. */82MG_FEATURES_LUA = 0x20u,8384/* Support server side JavaScript scripting. */85/* Will only work, if USE_DUKTAPE is set. */86MG_FEATURES_SSJS = 0x40u,8788/* Provide data required for caching files. */89/* Will only work, if NO_CACHING is not set. */90MG_FEATURES_CACHE = 0x80u,9192/* Collect server status information. */93/* Will only work, if USE_SERVER_STATS is set. */94MG_FEATURES_STATS = 0x100u,9596/* Support on-the-fly compression. */97/* Will only work, if USE_ZLIB is set. */98MG_FEATURES_COMPRESSION = 0x200u,99100/* Collect server status information. */101/* Will only work, if USE_SERVER_STATS is set. */102MG_FEATURES_ALL = 0xFFFFu103};104105106/* Initialize this library. This should be called once before any other107* function from this library. This function is not guaranteed to be108* thread safe.109* Parameters:110* features: bit mask for features to be initialized.111* Note: The TLS libraries (like OpenSSL) is initialized112* only if the MG_FEATURES_TLS bit is set.113* Currently the other bits do not influence114* initialization, but this may change in future115* versions.116* Return value:117* initialized features118* 0: error119*/120CIVETWEB_API unsigned mg_init_library(unsigned features);121122123/* Un-initialize this library.124* Return value:125* 0: error126*/127CIVETWEB_API unsigned mg_exit_library(void);128129130struct mg_context; /* Handle for the HTTP service itself */131struct mg_connection; /* Handle for the individual connection */132133134/* Maximum number of headers */135#define MG_MAX_HEADERS (64)136137struct mg_header {138const char *name; /* HTTP header name */139const char *value; /* HTTP header value */140};141142143/* This structure contains information about the HTTP request. */144struct mg_request_info {145const char *request_method; /* "GET", "POST", etc */146const char *request_uri; /* URL-decoded URI (absolute or relative,147* as in the request) */148const char *local_uri; /* URL-decoded URI (relative). Can be NULL149* if the request_uri does not address a150* resource at the server host. */151#if defined(MG_LEGACY_INTERFACE) /* 2017-02-04, deprecated 2014-09-14 */152const char *uri; /* Deprecated: use local_uri instead */153#endif154const char *http_version; /* E.g. "1.0", "1.1" */155const char *query_string; /* URL part after '?', not including '?', or156NULL */157const char *remote_user; /* Authenticated user, or NULL if no auth158used */159char remote_addr[48]; /* Client's IP address as a string. */160161long long content_length; /* Length (in bytes) of the request body,162can be -1 if no length was given. */163int remote_port; /* Client's port */164int is_ssl; /* 1 if SSL-ed, 0 if not */165void *user_data; /* User data pointer passed to mg_start() */166void *conn_data; /* Connection-specific user data */167168int num_headers; /* Number of HTTP headers */169struct mg_header170http_headers[MG_MAX_HEADERS]; /* Allocate maximum headers */171172struct mg_client_cert *client_cert; /* Client certificate information */173174const char *acceptedWebSocketSubprotocol; /* websocket subprotocol,175* accepted during handshake */176};177178179/* This structure contains information about the HTTP request. */180/* This structure may be extended in future versions. */181struct mg_response_info {182int status_code; /* E.g. 200 */183const char *status_text; /* E.g. "OK" */184const char *http_version; /* E.g. "1.0", "1.1" */185186long long content_length; /* Length (in bytes) of the request body,187can be -1 if no length was given. */188189int num_headers; /* Number of HTTP headers */190struct mg_header191http_headers[MG_MAX_HEADERS]; /* Allocate maximum headers */192};193194195/* Client certificate information (part of mg_request_info) */196/* New nomenclature. */197struct mg_client_cert {198void *peer_cert;199const char *subject;200const char *issuer;201const char *serial;202const char *finger;203};204205#if defined(MG_LEGACY_INTERFACE) /* 2017-10-05 */206/* Old nomenclature. */207struct client_cert {208const char *subject;209const char *issuer;210const char *serial;211const char *finger;212};213#endif214215216/* This structure needs to be passed to mg_start(), to let civetweb know217which callbacks to invoke. For a detailed description, see218https://github.com/civetweb/civetweb/blob/master/docs/UserManual.md */219struct mg_callbacks {220/* Called when civetweb has received new HTTP request.221If the callback returns one, it must process the request222by sending valid HTTP headers and a body. Civetweb will not do223any further processing. Otherwise it must return zero.224Note that since V1.7 the "begin_request" function is called225before an authorization check. If an authorization check is226required, use a request_handler instead.227Return value:2280: civetweb will process the request itself. In this case,229the callback must not send any data to the client.2301-999: callback already processed the request. Civetweb will231not send any data after the callback returned. The232return code is stored as a HTTP status code for the233access log. */234int (*begin_request)(struct mg_connection *);235236/* Called when civetweb has finished processing request. */237void (*end_request)(const struct mg_connection *, int reply_status_code);238239/* Called when civetweb is about to log a message. If callback returns240non-zero, civetweb does not log anything. */241int (*log_message)(const struct mg_connection *, const char *message);242243/* Called when civetweb is about to log access. If callback returns244non-zero, civetweb does not log anything. */245int (*log_access)(const struct mg_connection *, const char *message);246247/* Called when civetweb initializes SSL library.248Parameters:249user_data: parameter user_data passed when starting the server.250Return value:2510: civetweb will set up the SSL certificate.2521: civetweb assumes the callback already set up the certificate.253-1: initializing ssl fails. */254int (*init_ssl)(void *ssl_context, void *user_data);255256/* Called when civetweb is about to create or free a SSL_CTX.257Parameters:258ssl_ctx: SSL_CTX pointer. NULL at creation time, Not NULL when mg_context259will be freed260user_data: parameter user_data passed when starting the server.261Return value:2620: civetweb will continue to create the context, just as if the263callback would not be present.264The value in *ssl_ctx when the function returns is ignored.2651: civetweb will copy the value from *ssl_ctx to the civetweb context266and doesn't create its own.267-1: initializing ssl fails.*/268int (*external_ssl_ctx)(void **ssl_ctx, void *user_data);269270#if defined(MG_LEGACY_INTERFACE) /* 2015-08-19 */271/* Called when websocket request is received, before websocket handshake.272Return value:2730: civetweb proceeds with websocket handshake.2741: connection is closed immediately.275This callback is deprecated: Use mg_set_websocket_handler instead. */276int (*websocket_connect)(const struct mg_connection *);277278/* Called when websocket handshake is successfully completed, and279connection is ready for data exchange.280This callback is deprecated: Use mg_set_websocket_handler instead. */281void (*websocket_ready)(struct mg_connection *);282283/* Called when data frame has been received from the client.284Parameters:285bits: first byte of the websocket frame, see websocket RFC at286http://tools.ietf.org/html/rfc6455, section 5.2287data, data_len: payload, with mask (if any) already applied.288Return value:2891: keep this websocket connection open.2900: close this websocket connection.291This callback is deprecated: Use mg_set_websocket_handler instead. */292int (*websocket_data)(struct mg_connection *,293int bits,294char *data,295size_t data_len);296#endif /* MG_LEGACY_INTERFACE */297298/* Called when civetweb is closing a connection. The per-context mutex is299locked when this is invoked.300301Websockets:302Before mg_set_websocket_handler has been added, it was primarily useful303for noting when a websocket is closing, and used to remove it from any304application-maintained list of clients.305Using this callback for websocket connections is deprecated: Use306mg_set_websocket_handler instead.307308Connection specific data:309If memory has been allocated for the connection specific user data310(mg_request_info->conn_data, mg_get_user_connection_data),311this is the last chance to free it.312*/313void (*connection_close)(const struct mg_connection *);314315/* Called when civetweb is about to serve Lua server page, if316Lua support is enabled.317Parameters:318conn: current connection.319lua_context: "lua_State *" pointer. */320void (*init_lua)(const struct mg_connection *conn, void *lua_context);321322#if defined(MG_LEGACY_INTERFACE) /* 2016-05-14 */323/* Called when civetweb has uploaded a file to a temporary directory as a324result of mg_upload() call.325Note that mg_upload is deprecated. Use mg_handle_form_request instead.326Parameters:327file_name: full path name to the uploaded file. */328void (*upload)(struct mg_connection *, const char *file_name);329#endif330331/* Called when civetweb is about to send HTTP error to the client.332Implementing this callback allows to create custom error pages.333Parameters:334conn: current connection.335status: HTTP error status code.336errmsg: error message text.337Return value:3381: run civetweb error handler.3390: callback already handled the error. */340int (*http_error)(struct mg_connection *conn,341int status,342const char *errmsg);343344/* Called after civetweb context has been created, before requests345are processed.346Parameters:347ctx: context handle */348void (*init_context)(const struct mg_context *ctx);349350/* Called when a new worker thread is initialized.351Parameters:352ctx: context handle353thread_type:3540 indicates the master thread3551 indicates a worker thread handling client connections3562 indicates an internal helper thread (timer thread)357*/358void (*init_thread)(const struct mg_context *ctx, int thread_type);359360/* Called when civetweb context is deleted.361Parameters:362ctx: context handle */363void (*exit_context)(const struct mg_context *ctx);364365/* Called when initializing a new connection object.366* Can be used to initialize the connection specific user data367* (mg_request_info->conn_data, mg_get_user_connection_data).368* When the callback is called, it is not yet known if a369* valid HTTP(S) request will be made.370* Parameters:371* conn: not yet fully initialized connection object372* conn_data: output parameter, set to initialize the373* connection specific user data374* Return value:375* must be 0376* Otherwise, the result is undefined377*/378int (*init_connection)(const struct mg_connection *conn, void **conn_data);379};380381382/* Start web server.383384Parameters:385callbacks: mg_callbacks structure with user-defined callbacks.386options: NULL terminated list of option_name, option_value pairs that387specify Civetweb configuration parameters.388389Side-effects: on UNIX, ignores SIGCHLD and SIGPIPE signals. If custom390processing is required for these, signal handlers must be set up391after calling mg_start().392393394Example:395const char *options[] = {396"document_root", "/var/www",397"listening_ports", "80,443s",398NULL399};400struct mg_context *ctx = mg_start(&my_func, NULL, options);401402Refer to https://github.com/civetweb/civetweb/blob/master/docs/UserManual.md403for the list of valid option and their possible values.404405Return:406web server context, or NULL on error. */407CIVETWEB_API struct mg_context *mg_start(const struct mg_callbacks *callbacks,408void *user_data,409const char **configuration_options);410411412/* Stop the web server.413414Must be called last, when an application wants to stop the web server and415release all associated resources. This function blocks until all Civetweb416threads are stopped. Context pointer becomes invalid. */417CIVETWEB_API void mg_stop(struct mg_context *);418419420#if defined(MG_EXPERIMENTAL_INTERFACES)421/* Add an additional domain to an already running web server.422*423* Parameters:424* ctx: Context handle of a server started by mg_start.425* options: NULL terminated list of option_name, option_value pairs that426* specify CivetWeb configuration parameters.427*428* Return:429* < 0 in case of an error430* -1 for a parameter error431* -2 invalid options432* -3 initializing SSL failed433* -4 mandatory domain option missing434* -5 duplicate domain435* -6 out of memory436* > 0 index / handle of a new domain437*/438CIVETWEB_API int mg_start_domain(struct mg_context *ctx,439const char **configuration_options);440#endif441442443/* mg_request_handler444445Called when a new request comes in. This callback is URI based446and configured with mg_set_request_handler().447448Parameters:449conn: current connection information.450cbdata: the callback data configured with mg_set_request_handler().451Returns:4520: the handler could not handle the request, so fall through.4531 - 999: the handler processed the request. The return code is454stored as a HTTP status code for the access log. */455typedef int (*mg_request_handler)(struct mg_connection *conn, void *cbdata);456457458/* mg_set_request_handler459460Sets or removes a URI mapping for a request handler.461This function uses mg_lock_context internally.462463URI's are ordered and prefixed URI's are supported. For example,464consider two URIs: /a/b and /a465/a matches /a466/a/b matches /a/b467/a/c matches /a468469Parameters:470ctx: server context471uri: the URI (exact or pattern) for the handler472handler: the callback handler to use when the URI is requested.473If NULL, an already registered handler for this URI will474be removed.475The URI used to remove a handler must match exactly the476one used to register it (not only a pattern match).477cbdata: the callback data to give to the handler when it is called. */478CIVETWEB_API void mg_set_request_handler(struct mg_context *ctx,479const char *uri,480mg_request_handler handler,481void *cbdata);482483484/* Callback types for websocket handlers in C/C++.485486mg_websocket_connect_handler487Is called when the client intends to establish a websocket connection,488before websocket handshake.489Return value:4900: civetweb proceeds with websocket handshake.4911: connection is closed immediately.492493mg_websocket_ready_handler494Is called when websocket handshake is successfully completed, and495connection is ready for data exchange.496497mg_websocket_data_handler498Is called when a data frame has been received from the client.499Parameters:500bits: first byte of the websocket frame, see websocket RFC at501http://tools.ietf.org/html/rfc6455, section 5.2502data, data_len: payload, with mask (if any) already applied.503Return value:5041: keep this websocket connection open.5050: close this websocket connection.506507mg_connection_close_handler508Is called, when the connection is closed.*/509typedef int (*mg_websocket_connect_handler)(const struct mg_connection *,510void *);511typedef void (*mg_websocket_ready_handler)(struct mg_connection *, void *);512typedef int (*mg_websocket_data_handler)(struct mg_connection *,513int,514char *,515size_t,516void *);517typedef void (*mg_websocket_close_handler)(const struct mg_connection *,518void *);519520/* struct mg_websocket_subprotocols521*522* List of accepted subprotocols523*/524struct mg_websocket_subprotocols {525int nb_subprotocols;526char **subprotocols;527};528529/* mg_set_websocket_handler530531Set or remove handler functions for websocket connections.532This function works similar to mg_set_request_handler - see there. */533CIVETWEB_API void534mg_set_websocket_handler(struct mg_context *ctx,535const char *uri,536mg_websocket_connect_handler connect_handler,537mg_websocket_ready_handler ready_handler,538mg_websocket_data_handler data_handler,539mg_websocket_close_handler close_handler,540void *cbdata);541542/* mg_set_websocket_handler543544Set or remove handler functions for websocket connections.545This function works similar to mg_set_request_handler - see there. */546CIVETWEB_API void mg_set_websocket_handler_with_subprotocols(547struct mg_context *ctx,548const char *uri,549struct mg_websocket_subprotocols *subprotocols,550mg_websocket_connect_handler connect_handler,551mg_websocket_ready_handler ready_handler,552mg_websocket_data_handler data_handler,553mg_websocket_close_handler close_handler,554void *cbdata);555556557/* mg_authorization_handler558559Callback function definition for mg_set_auth_handler560561Parameters:562conn: current connection information.563cbdata: the callback data configured with mg_set_request_handler().564Returns:5650: access denied5661: access granted567*/568typedef int (*mg_authorization_handler)(struct mg_connection *conn,569void *cbdata);570571572/* mg_set_auth_handler573574Sets or removes a URI mapping for an authorization handler.575This function works similar to mg_set_request_handler - see there. */576CIVETWEB_API void mg_set_auth_handler(struct mg_context *ctx,577const char *uri,578mg_authorization_handler handler,579void *cbdata);580581582/* Get the value of particular configuration parameter.583The value returned is read-only. Civetweb does not allow changing584configuration at run time.585If given parameter name is not valid, NULL is returned. For valid586names, return value is guaranteed to be non-NULL. If parameter is not587set, zero-length string is returned. */588CIVETWEB_API const char *mg_get_option(const struct mg_context *ctx,589const char *name);590591592/* Get context from connection. */593CIVETWEB_API struct mg_context *594mg_get_context(const struct mg_connection *conn);595596597/* Get user data passed to mg_start from context. */598CIVETWEB_API void *mg_get_user_data(const struct mg_context *ctx);599600601/* Set user data for the current connection. */602/* Note: This function is deprecated. Use the init_connection callback603instead to initialize the user connection data pointer. It is604reccomended to supply a pointer to some user defined data structure605as conn_data initializer in init_connection. In case it is required606to change some data after the init_connection call, store another607data pointer in the user defined data structure and modify that608pointer. In either case, after the init_connection callback, only609calls to mg_get_user_connection_data should be required. */610CIVETWEB_API void mg_set_user_connection_data(struct mg_connection *conn,611void *data);612613614/* Get user data set for the current connection. */615CIVETWEB_API void *616mg_get_user_connection_data(const struct mg_connection *conn);617618619/* Get a formatted link corresponding to the current request620621Parameters:622conn: current connection information.623buf: string buffer (out)624buflen: length of the string buffer625Returns:626<0: error627>=0: ok */628CIVETWEB_API int629mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen);630631632#if defined(MG_LEGACY_INTERFACE) /* 2014-02-21 */633/* Return array of strings that represent valid configuration options.634For each option, option name and default value is returned, i.e. the635number of entries in the array equals to number_of_options x 2.636Array is NULL terminated. */637/* Deprecated: Use mg_get_valid_options instead. */638CIVETWEB_API const char **mg_get_valid_option_names(void);639#endif640641642struct mg_option {643const char *name;644int type;645const char *default_value;646};647648/* Old nomenclature */649#if defined(MG_LEGACY_INTERFACE) /* 2017-10-05 */650enum {651CONFIG_TYPE_UNKNOWN = 0x0,652CONFIG_TYPE_NUMBER = 0x1,653CONFIG_TYPE_STRING = 0x2,654CONFIG_TYPE_FILE = 0x3,655CONFIG_TYPE_DIRECTORY = 0x4,656CONFIG_TYPE_BOOLEAN = 0x5,657CONFIG_TYPE_EXT_PATTERN = 0x6,658CONFIG_TYPE_STRING_LIST = 0x7,659CONFIG_TYPE_STRING_MULTILINE = 0x8660};661#endif662663/* New nomenclature */664enum {665MG_CONFIG_TYPE_UNKNOWN = 0x0,666MG_CONFIG_TYPE_NUMBER = 0x1,667MG_CONFIG_TYPE_STRING = 0x2,668MG_CONFIG_TYPE_FILE = 0x3,669MG_CONFIG_TYPE_DIRECTORY = 0x4,670MG_CONFIG_TYPE_BOOLEAN = 0x5,671MG_CONFIG_TYPE_EXT_PATTERN = 0x6,672MG_CONFIG_TYPE_STRING_LIST = 0x7,673MG_CONFIG_TYPE_STRING_MULTILINE = 0x8,674MG_CONFIG_TYPE_YES_NO_OPTIONAL = 0x9675};676677/* Return array of struct mg_option, representing all valid configuration678options of civetweb.c.679The array is terminated by a NULL name option. */680CIVETWEB_API const struct mg_option *mg_get_valid_options(void);681682683struct mg_server_ports {684int protocol; /* 1 = IPv4, 2 = IPv6, 3 = both */685int port; /* port number */686int is_ssl; /* https port: 0 = no, 1 = yes */687int is_redirect; /* redirect all requests: 0 = no, 1 = yes */688int _reserved1;689int _reserved2;690int _reserved3;691int _reserved4;692};693694695/* Get the list of ports that civetweb is listening on.696The parameter size is the size of the ports array in elements.697The caller is responsibility to allocate the required memory.698This function returns the number of struct mg_server_ports elements699filled in, or <0 in case of an error. */700CIVETWEB_API int mg_get_server_ports(const struct mg_context *ctx,701int size,702struct mg_server_ports *ports);703704705#if defined(MG_LEGACY_INTERFACE) /* 2017-04-02 */706/* Deprecated: Use mg_get_server_ports instead. */707CIVETWEB_API size_t mg_get_ports(const struct mg_context *ctx,708size_t size,709int *ports,710int *ssl);711#endif712713714/* Add, edit or delete the entry in the passwords file.715*716* This function allows an application to manipulate .htpasswd files on the717* fly by adding, deleting and changing user records. This is one of the718* several ways of implementing authentication on the server side. For another,719* cookie-based way please refer to the examples/chat in the source tree.720*721* Parameter:722* passwords_file_name: Path and name of a file storing multiple passwords723* realm: HTTP authentication realm (authentication domain) name724* user: User name725* password:726* If password is not NULL, entry modified or added.727* If password is NULL, entry is deleted.728*729* Return:730* 1 on success, 0 on error.731*/732CIVETWEB_API int mg_modify_passwords_file(const char *passwords_file_name,733const char *realm,734const char *user,735const char *password);736737738/* Return information associated with the request.739* Use this function to implement a server and get data about a request740* from a HTTP/HTTPS client.741* Note: Before CivetWeb 1.10, this function could be used to read742* a response from a server, when implementing a client, although the743* values were never returned in appropriate mg_request_info elements.744* It is strongly advised to use mg_get_response_info for clients.745*/746CIVETWEB_API const struct mg_request_info *747mg_get_request_info(const struct mg_connection *);748749750/* Return information associated with a HTTP/HTTPS response.751* Use this function in a client, to check the response from752* the server. */753CIVETWEB_API const struct mg_response_info *754mg_get_response_info(const struct mg_connection *);755756757/* Send data to the client.758Return:7590 when the connection has been closed760-1 on error761>0 number of bytes written on success */762CIVETWEB_API int mg_write(struct mg_connection *, const void *buf, size_t len);763764765/* Send data to a websocket client wrapped in a websocket frame. Uses766mg_lock_connection to ensure that the transmission is not interrupted,767i.e., when the application is proactively communicating and responding to768a request simultaneously.769770Send data to a websocket client wrapped in a websocket frame.771This function is available when civetweb is compiled with -DUSE_WEBSOCKET772773Return:7740 when the connection has been closed775-1 on error776>0 number of bytes written on success */777CIVETWEB_API int mg_websocket_write(struct mg_connection *conn,778int opcode,779const char *data,780size_t data_len);781782783/* Send data to a websocket server wrapped in a masked websocket frame. Uses784mg_lock_connection to ensure that the transmission is not interrupted,785i.e., when the application is proactively communicating and responding to786a request simultaneously.787788Send data to a websocket server wrapped in a masked websocket frame.789This function is available when civetweb is compiled with -DUSE_WEBSOCKET790791Return:7920 when the connection has been closed793-1 on error794>0 number of bytes written on success */795CIVETWEB_API int mg_websocket_client_write(struct mg_connection *conn,796int opcode,797const char *data,798size_t data_len);799800801/* Blocks until unique access is obtained to this connection. Intended for use802with websockets only.803Invoke this before mg_write or mg_printf when communicating with a804websocket if your code has server-initiated communication as well as805communication in direct response to a message. */806CIVETWEB_API void mg_lock_connection(struct mg_connection *conn);807CIVETWEB_API void mg_unlock_connection(struct mg_connection *conn);808809810#if defined(MG_LEGACY_INTERFACE) /* 2014-06-21 */811#define mg_lock mg_lock_connection812#define mg_unlock mg_unlock_connection813#endif814815816/* Lock server context. This lock may be used to protect resources817that are shared between different connection/worker threads. */818CIVETWEB_API void mg_lock_context(struct mg_context *ctx);819CIVETWEB_API void mg_unlock_context(struct mg_context *ctx);820821822/* Opcodes, from http://tools.ietf.org/html/rfc6455 */823#if defined(MG_LEGACY_INTERFACE) /* 2017-10-05 */824enum {825WEBSOCKET_OPCODE_CONTINUATION = 0x0,826WEBSOCKET_OPCODE_TEXT = 0x1,827WEBSOCKET_OPCODE_BINARY = 0x2,828WEBSOCKET_OPCODE_CONNECTION_CLOSE = 0x8,829WEBSOCKET_OPCODE_PING = 0x9,830WEBSOCKET_OPCODE_PONG = 0xa831};832#endif833834/* New nomenclature */835enum {836MG_WEBSOCKET_OPCODE_CONTINUATION = 0x0,837MG_WEBSOCKET_OPCODE_TEXT = 0x1,838MG_WEBSOCKET_OPCODE_BINARY = 0x2,839MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE = 0x8,840MG_WEBSOCKET_OPCODE_PING = 0x9,841MG_WEBSOCKET_OPCODE_PONG = 0xa842};843844/* Macros for enabling compiler-specific checks for printf-like arguments. */845#undef PRINTF_FORMAT_STRING846#if defined(_MSC_VER) && _MSC_VER >= 1400847#include <sal.h>848#if defined(_MSC_VER) && _MSC_VER > 1400849#define PRINTF_FORMAT_STRING(s) _Printf_format_string_ s850#else851#define PRINTF_FORMAT_STRING(s) __format_string s852#endif853#else854#define PRINTF_FORMAT_STRING(s) s855#endif856857#ifdef __GNUC__858#define PRINTF_ARGS(x, y) __attribute__((format(printf, x, y)))859#else860#define PRINTF_ARGS(x, y)861#endif862863864/* Send data to the client using printf() semantics.865Works exactly like mg_write(), but allows to do message formatting. */866CIVETWEB_API int mg_printf(struct mg_connection *,867PRINTF_FORMAT_STRING(const char *fmt),868...) PRINTF_ARGS(2, 3);869870871/* Send a part of the message body, if chunked transfer encoding is set.872* Only use this function after sending a complete HTTP request or response873* header with "Transfer-Encoding: chunked" set. */874CIVETWEB_API int mg_send_chunk(struct mg_connection *conn,875const char *chunk,876unsigned int chunk_len);877878879/* Send contents of the entire file together with HTTP headers.880* Parameters:881* conn: Current connection information.882* path: Full path to the file to send.883* This function has been superseded by mg_send_mime_file884*/885CIVETWEB_API void mg_send_file(struct mg_connection *conn, const char *path);886887888/* Send contents of the file without HTTP headers.889* The code must send a valid HTTP response header before using this function.890*891* Parameters:892* conn: Current connection information.893* path: Full path to the file to send.894*895* Return:896* < 0 Error897*/898CIVETWEB_API int mg_send_file_body(struct mg_connection *conn,899const char *path);900901902/* Send HTTP error reply. */903CIVETWEB_API int mg_send_http_error(struct mg_connection *conn,904int status_code,905PRINTF_FORMAT_STRING(const char *fmt),906...) PRINTF_ARGS(3, 4);907908909/* Send "HTTP 200 OK" response header.910* After calling this function, use mg_write or mg_send_chunk to send the911* response body.912* Parameters:913* conn: Current connection handle.914* mime_type: Set Content-Type for the following content.915* content_length: Size of the following content, if content_length >= 0.916* Will set transfer-encoding to chunked, if set to -1.917* Return:918* < 0 Error919*/920CIVETWEB_API int mg_send_http_ok(struct mg_connection *conn,921const char *mime_type,922long long content_length);923924925/* Send "HTTP 30x" redirect response.926* The response has content-size zero: do not send any body data after calling927* this function.928* Parameters:929* conn: Current connection handle.930* target_url: New location.931* redirect_code: HTTP redirect type. Could be 301, 302, 303, 307, 308.932* Return:933* < 0 Error (-1 send error, -2 parameter error)934*/935CIVETWEB_API int mg_send_http_redirect(struct mg_connection *conn,936const char *target_url,937int redirect_code);938939940/* Send HTTP digest access authentication request.941* Browsers will send a user name and password in their next request, showing942* an authentication dialog if the password is not stored.943* Parameters:944* conn: Current connection handle.945* realm: Authentication realm. If NULL is supplied, the sever domain946* set in the authentication_domain configuration is used.947* Return:948* < 0 Error949*/950CIVETWEB_API int951mg_send_digest_access_authentication_request(struct mg_connection *conn,952const char *realm);953954955/* Check if the current request has a valid authentication token set.956* A file is used to provide a list of valid user names, realms and957* password hashes. The file can be created and modified using the958* mg_modify_passwords_file API function.959* Parameters:960* conn: Current connection handle.961* realm: Authentication realm. If NULL is supplied, the sever domain962* set in the authentication_domain configuration is used.963* filename: Path and name of a file storing multiple password hashes.964* Return:965* > 0 Valid authentication966* 0 Invalid authentication967* < 0 Error (all values < 0 should be considered as invalid968* authentication, future error codes will have negative969* numbers)970* -1 Parameter error971* -2 File not found972*/973CIVETWEB_API int974mg_check_digest_access_authentication(struct mg_connection *conn,975const char *realm,976const char *filename);977978979/* Send contents of the entire file together with HTTP headers.980* Parameters:981* conn: Current connection handle.982* path: Full path to the file to send.983* mime_type: Content-Type for file. NULL will cause the type to be984* looked up by the file extension.985*/986CIVETWEB_API void mg_send_mime_file(struct mg_connection *conn,987const char *path,988const char *mime_type);989990991/* Send contents of the entire file together with HTTP headers.992Parameters:993conn: Current connection information.994path: Full path to the file to send.995mime_type: Content-Type for file. NULL will cause the type to be996looked up by the file extension.997additional_headers: Additional custom header fields appended to the header.998Each header should start with an X-, to ensure it is999not included twice.1000NULL does not append anything.1001*/1002CIVETWEB_API void mg_send_mime_file2(struct mg_connection *conn,1003const char *path,1004const char *mime_type,1005const char *additional_headers);100610071008/* Store body data into a file. */1009CIVETWEB_API long long mg_store_body(struct mg_connection *conn,1010const char *path);1011/* Read entire request body and store it in a file "path".1012Return:1013< 0 Error1014>= 0 Number of bytes stored in file "path".1015*/101610171018/* Read data from the remote end, return number of bytes read.1019Return:10200 connection has been closed by peer. No more data could be read.1021< 0 read error. No more data could be read from the connection.1022> 0 number of bytes read into the buffer. */1023CIVETWEB_API int mg_read(struct mg_connection *, void *buf, size_t len);102410251026/* Get the value of particular HTTP header.10271028This is a helper function. It traverses request_info->http_headers array,1029and if the header is present in the array, returns its value. If it is1030not present, NULL is returned. */1031CIVETWEB_API const char *mg_get_header(const struct mg_connection *,1032const char *name);103310341035/* Get a value of particular form variable.10361037Parameters:1038data: pointer to form-uri-encoded buffer. This could be either POST data,1039or request_info.query_string.1040data_len: length of the encoded data.1041var_name: variable name to decode from the buffer1042dst: destination buffer for the decoded variable1043dst_len: length of the destination buffer10441045Return:1046On success, length of the decoded variable.1047On error:1048-1 (variable not found).1049-2 (destination buffer is NULL, zero length or too small to hold the1050decoded variable).10511052Destination buffer is guaranteed to be '\0' - terminated if it is not1053NULL or zero length. */1054CIVETWEB_API int mg_get_var(const char *data,1055size_t data_len,1056const char *var_name,1057char *dst,1058size_t dst_len);105910601061/* Get a value of particular form variable.10621063Parameters:1064data: pointer to form-uri-encoded buffer. This could be either POST data,1065or request_info.query_string.1066data_len: length of the encoded data.1067var_name: variable name to decode from the buffer1068dst: destination buffer for the decoded variable1069dst_len: length of the destination buffer1070occurrence: which occurrence of the variable, 0 is the first, 1 the1071second...1072this makes it possible to parse a query like1073b=x&a=y&a=z which will have occurrence values b:0, a:0 and a:110741075Return:1076On success, length of the decoded variable.1077On error:1078-1 (variable not found).1079-2 (destination buffer is NULL, zero length or too small to hold the1080decoded variable).10811082Destination buffer is guaranteed to be '\0' - terminated if it is not1083NULL or zero length. */1084CIVETWEB_API int mg_get_var2(const char *data,1085size_t data_len,1086const char *var_name,1087char *dst,1088size_t dst_len,1089size_t occurrence);109010911092/* Fetch value of certain cookie variable into the destination buffer.10931094Destination buffer is guaranteed to be '\0' - terminated. In case of1095failure, dst[0] == '\0'. Note that RFC allows many occurrences of the same1096parameter. This function returns only first occurrence.10971098Return:1099On success, value length.1100On error:1101-1 (either "Cookie:" header is not present at all or the requested1102parameter is not found).1103-2 (destination buffer is NULL, zero length or too small to hold the1104value). */1105CIVETWEB_API int mg_get_cookie(const char *cookie,1106const char *var_name,1107char *buf,1108size_t buf_len);110911101111/* Download data from the remote web server.1112host: host name to connect to, e.g. "foo.com", or "10.12.40.1".1113port: port number, e.g. 80.1114use_ssl: whether to use SSL connection.1115error_buffer, error_buffer_size: error message placeholder.1116request_fmt,...: HTTP request.1117Return:1118On success, valid pointer to the new connection, suitable for mg_read().1119On error, NULL. error_buffer contains error message.1120Example:1121char ebuf[100];1122struct mg_connection *conn;1123conn = mg_download("google.com", 80, 0, ebuf, sizeof(ebuf),1124"%s", "GET / HTTP/1.0\r\nHost: google.com\r\n\r\n");1125*/1126CIVETWEB_API struct mg_connection *1127mg_download(const char *host,1128int port,1129int use_ssl,1130char *error_buffer,1131size_t error_buffer_size,1132PRINTF_FORMAT_STRING(const char *request_fmt),1133...) PRINTF_ARGS(6, 7);113411351136/* Close the connection opened by mg_download(). */1137CIVETWEB_API void mg_close_connection(struct mg_connection *conn);113811391140#if defined(MG_LEGACY_INTERFACE) /* 2016-05-14 */1141/* File upload functionality. Each uploaded file gets saved into a temporary1142file and MG_UPLOAD event is sent.1143Return number of uploaded files.1144Deprecated: Use mg_handle_form_request instead. */1145CIVETWEB_API int mg_upload(struct mg_connection *conn,1146const char *destination_dir);1147#endif114811491150/* This structure contains callback functions for handling form fields.1151It is used as an argument to mg_handle_form_request. */1152struct mg_form_data_handler {1153/* This callback function is called, if a new field has been found.1154* The return value of this callback is used to define how the field1155* should be processed.1156*1157* Parameters:1158* key: Name of the field ("name" property of the HTML input field).1159* filename: Name of a file to upload, at the client computer.1160* Only set for input fields of type "file", otherwise NULL.1161* path: Output parameter: File name (incl. path) to store the file1162* at the server computer. Only used if FORM_FIELD_STORAGE_STORE1163* is returned by this callback. Existing files will be1164* overwritten.1165* pathlen: Length of the buffer for path.1166* user_data: Value of the member user_data of mg_form_data_handler1167*1168* Return value:1169* The callback must return the intended storage for this field1170* (See FORM_FIELD_STORAGE_*).1171*/1172int (*field_found)(const char *key,1173const char *filename,1174char *path,1175size_t pathlen,1176void *user_data);11771178/* If the "field_found" callback returned FORM_FIELD_STORAGE_GET,1179* this callback will receive the field data.1180*1181* Parameters:1182* key: Name of the field ("name" property of the HTML input field).1183* value: Value of the input field.1184* user_data: Value of the member user_data of mg_form_data_handler1185*1186* Return value:1187* The return code determines how the server should continue processing1188* the current request (See MG_FORM_FIELD_HANDLE_*).1189*/1190int (*field_get)(const char *key,1191const char *value,1192size_t valuelen,1193void *user_data);11941195/* If the "field_found" callback returned FORM_FIELD_STORAGE_STORE,1196* the data will be stored into a file. If the file has been written1197* successfully, this callback will be called. This callback will1198* not be called for only partially uploaded files. The1199* mg_handle_form_request function will either store the file completely1200* and call this callback, or it will remove any partial content and1201* not call this callback function.1202*1203* Parameters:1204* path: Path of the file stored at the server.1205* file_size: Size of the stored file in bytes.1206* user_data: Value of the member user_data of mg_form_data_handler1207*1208* Return value:1209* The return code determines how the server should continue processing1210* the current request (See MG_FORM_FIELD_HANDLE_*).1211*/1212int (*field_store)(const char *path, long long file_size, void *user_data);12131214/* User supplied argument, passed to all callback functions. */1215void *user_data;1216};121712181219/* Return values definition for the "field_found" callback in1220* mg_form_data_handler. */1221#if defined(MG_LEGACY_INTERFACE) /* 2017-10-05 */1222enum {1223/* Skip this field (neither get nor store it). Continue with the1224* next field. */1225FORM_FIELD_STORAGE_SKIP = 0x0,1226/* Get the field value. */1227FORM_FIELD_STORAGE_GET = 0x1,1228/* Store the field value into a file. */1229FORM_FIELD_STORAGE_STORE = 0x2,1230/* Stop parsing this request. Skip the remaining fields. */1231FORM_FIELD_STORAGE_ABORT = 0x101232};1233#endif1234/* New nomenclature */1235enum {1236/* Skip this field (neither get nor store it). Continue with the1237* next field. */1238MG_FORM_FIELD_STORAGE_SKIP = 0x0,1239/* Get the field value. */1240MG_FORM_FIELD_STORAGE_GET = 0x1,1241/* Store the field value into a file. */1242MG_FORM_FIELD_STORAGE_STORE = 0x2,1243/* Stop parsing this request. Skip the remaining fields. */1244MG_FORM_FIELD_STORAGE_ABORT = 0x101245};12461247/* Return values for "field_get" and "field_store" */1248enum {1249/* Only "field_get": If there is more data in this field, get the next1250* chunk. Otherwise: handle the next field. */1251MG_FORM_FIELD_HANDLE_GET = 0x1,1252/* Handle the next field */1253MG_FORM_FIELD_HANDLE_NEXT = 0x8,1254/* Stop parsing this request */1255MG_FORM_FIELD_HANDLE_ABORT = 0x101256};125712581259/* Process form data.1260* Returns the number of fields handled, or < 0 in case of an error.1261* Note: It is possible that several fields are already handled successfully1262* (e.g., stored into files), before the request handling is stopped with an1263* error. In this case a number < 0 is returned as well.1264* In any case, it is the duty of the caller to remove files once they are1265* no longer required. */1266CIVETWEB_API int mg_handle_form_request(struct mg_connection *conn,1267struct mg_form_data_handler *fdh);126812691270/* Convenience function -- create detached thread.1271Return: 0 on success, non-0 on error. */1272typedef void *(*mg_thread_func_t)(void *);1273CIVETWEB_API int mg_start_thread(mg_thread_func_t f, void *p);127412751276/* Return builtin mime type for the given file name.1277For unrecognized extensions, "text/plain" is returned. */1278CIVETWEB_API const char *mg_get_builtin_mime_type(const char *file_name);127912801281/* Get text representation of HTTP status code. */1282CIVETWEB_API const char *1283mg_get_response_code_text(const struct mg_connection *conn, int response_code);128412851286/* Return CivetWeb version. */1287CIVETWEB_API const char *mg_version(void);128812891290/* URL-decode input buffer into destination buffer.12910-terminate the destination buffer.1292form-url-encoded data differs from URI encoding in a way that it1293uses '+' as character for space, see RFC 1866 section 8.2.11294http://ftp.ics.uci.edu/pub/ietf/html/rfc1866.txt1295Return: length of the decoded data, or -1 if dst buffer is too small. */1296CIVETWEB_API int mg_url_decode(const char *src,1297int src_len,1298char *dst,1299int dst_len,1300int is_form_url_encoded);130113021303/* URL-encode input buffer into destination buffer.1304returns the length of the resulting buffer or -11305is the buffer is too small. */1306CIVETWEB_API int mg_url_encode(const char *src, char *dst, size_t dst_len);130713081309/* MD5 hash given strings.1310Buffer 'buf' must be 33 bytes long. Varargs is a NULL terminated list of1311ASCIIz strings. When function returns, buf will contain human-readable1312MD5 hash. Example:1313char buf[33];1314mg_md5(buf, "aa", "bb", NULL); */1315CIVETWEB_API char *mg_md5(char buf[33], ...);131613171318/* Print error message to the opened error log stream.1319This utilizes the provided logging configuration.1320conn: connection (not used for sending data, but to get perameters)1321fmt: format string without the line return1322...: variable argument list1323Example:1324mg_cry(conn,"i like %s", "logging"); */1325CIVETWEB_API void mg_cry(const struct mg_connection *conn,1326PRINTF_FORMAT_STRING(const char *fmt),1327...) PRINTF_ARGS(2, 3);132813291330/* utility methods to compare two buffers, case insensitive. */1331CIVETWEB_API int mg_strcasecmp(const char *s1, const char *s2);1332CIVETWEB_API int mg_strncasecmp(const char *s1, const char *s2, size_t len);133313341335/* Connect to a websocket as a client1336Parameters:1337host: host to connect to, i.e. "echo.websocket.org" or "192.168.1.1" or1338"localhost"1339port: server port1340use_ssl: make a secure connection to server1341error_buffer, error_buffer_size: buffer for an error message1342path: server path you are trying to connect to, i.e. if connection to1343localhost/app, path should be "/app"1344origin: value of the Origin HTTP header1345data_func: callback that should be used when data is received from the1346server1347user_data: user supplied argument13481349Return:1350On success, valid mg_connection object.1351On error, NULL. Se error_buffer for details.1352*/1353CIVETWEB_API struct mg_connection *1354mg_connect_websocket_client(const char *host,1355int port,1356int use_ssl,1357char *error_buffer,1358size_t error_buffer_size,1359const char *path,1360const char *origin,1361mg_websocket_data_handler data_func,1362mg_websocket_close_handler close_func,1363void *user_data);136413651366/* Connect to a TCP server as a client (can be used to connect to a HTTP server)1367Parameters:1368host: host to connect to, i.e. "www.wikipedia.org" or "192.168.1.1" or1369"localhost"1370port: server port1371use_ssl: make a secure connection to server1372error_buffer, error_buffer_size: buffer for an error message13731374Return:1375On success, valid mg_connection object.1376On error, NULL. Se error_buffer for details.1377*/1378CIVETWEB_API struct mg_connection *mg_connect_client(const char *host,1379int port,1380int use_ssl,1381char *error_buffer,1382size_t error_buffer_size);138313841385struct mg_client_options {1386const char *host;1387int port;1388const char *client_cert;1389const char *server_cert;1390/* TODO: add more data */1391};139213931394CIVETWEB_API struct mg_connection *1395mg_connect_client_secure(const struct mg_client_options *client_options,1396char *error_buffer,1397size_t error_buffer_size);139813991400enum { TIMEOUT_INFINITE = -1 };1401enum { MG_TIMEOUT_INFINITE = -1 };14021403/* Wait for a response from the server1404Parameters:1405conn: connection1406ebuf, ebuf_len: error message placeholder.1407timeout: time to wait for a response in milliseconds (if < 0 then wait1408forever)14091410Return:1411On success, >= 01412On error/timeout, < 01413*/1414CIVETWEB_API int mg_get_response(struct mg_connection *conn,1415char *ebuf,1416size_t ebuf_len,1417int timeout);141814191420/* Check which features where set when the civetweb library has been compiled.1421The function explicitly addresses compile time defines used when building1422the library - it does not mean, the feature has been initialized using a1423mg_init_library call.1424mg_check_feature can be called anytime, even before mg_init_library has1425been called.14261427Parameters:1428feature: specifies which feature should be checked1429The value is a bit mask. The individual bits are defined as:14301 serve files (NO_FILES not set)14312 support HTTPS (NO_SSL not set)14324 support CGI (NO_CGI not set)14338 support IPv6 (USE_IPV6 set)143416 support WebSocket (USE_WEBSOCKET set)143532 support Lua scripts and Lua server pages (USE_LUA is set)143664 support server side JavaScript (USE_DUKTAPE is set)1437128 support caching (NO_CACHING not set)1438256 support server statistics (USE_SERVER_STATS is set)1439The result is undefined, if bits are set that do not represent a1440defined feature (currently: feature >= 512).1441The result is undefined, if no bit is set (feature == 0).14421443Return:1444If feature is available, the corresponding bit is set1445If feature is not available, the bit is 01446*/1447CIVETWEB_API unsigned mg_check_feature(unsigned feature);144814491450/* Get information on the system. Useful for support requests.1451Parameters:1452buffer: Store system information as string here.1453buflen: Length of buffer (including a byte required for a terminating 0).1454Return:1455Available size of system information, exluding a terminating 0.1456The information is complete, if the return value is smaller than buflen.1457The result is a JSON formatted string, the exact content may vary.1458Note:1459It is possible to determine the required buflen, by first calling this1460function with buffer = NULL and buflen = NULL. The required buflen is1461one byte more than the returned value.1462*/1463CIVETWEB_API int mg_get_system_info(char *buffer, int buflen);146414651466/* Get context information. Useful for server diagnosis.1467Parameters:1468ctx: Context handle1469buffer: Store context information here.1470buflen: Length of buffer (including a byte required for a terminating 0).1471Return:1472Available size of system information, exluding a terminating 0.1473The information is complete, if the return value is smaller than buflen.1474The result is a JSON formatted string, the exact content may vary.1475Note:1476It is possible to determine the required buflen, by first calling this1477function with buffer = NULL and buflen = NULL. The required buflen is1478one byte more than the returned value. However, since the available1479context information changes, you should allocate a few bytes more.1480*/1481CIVETWEB_API int1482mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen);148314841485#ifdef MG_EXPERIMENTAL_INTERFACES1486/* Get connection information. Useful for server diagnosis.1487Parameters:1488ctx: Context handle1489idx: Connection index1490buffer: Store context information here.1491buflen: Length of buffer (including a byte required for a terminating 0).1492Return:1493Available size of system information, exluding a terminating 0.1494The information is complete, if the return value is smaller than buflen.1495The result is a JSON formatted string, the exact content may vary.1496Note:1497It is possible to determine the required buflen, by first calling this1498function with buffer = NULL and buflen = NULL. The required buflen is1499one byte more than the returned value. However, since the available1500context information changes, you should allocate a few bytes more.1501*/1502CIVETWEB_API int mg_get_connection_info(const struct mg_context *ctx,1503int idx,1504char *buffer,1505int buflen);1506#endif150715081509#ifdef __cplusplus1510}1511#endif /* __cplusplus */15121513#endif /* CIVETWEB_HEADER_INCLUDED */151415151516