civetweb.h 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623
  1. /* Copyright (c) 2013-2019 the Civetweb developers
  2. * Copyright (c) 2004-2013 Sergey Lyubka
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to deal
  6. * in the Software without restriction, including without limitation the rights
  7. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. * copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. * THE SOFTWARE.
  21. */
  22. #ifndef CIVETWEB_HEADER_INCLUDED
  23. #define CIVETWEB_HEADER_INCLUDED
  24. #define CIVETWEB_VERSION "1.12"
  25. #define CIVETWEB_VERSION_MAJOR (1)
  26. #define CIVETWEB_VERSION_MINOR (12)
  27. #define CIVETWEB_VERSION_PATCH (0)
  28. #ifndef CIVETWEB_API
  29. #if defined(_WIN32)
  30. #if defined(CIVETWEB_DLL_EXPORTS)
  31. #define CIVETWEB_API __declspec(dllexport)
  32. #elif defined(CIVETWEB_DLL_IMPORTS)
  33. #define CIVETWEB_API __declspec(dllimport)
  34. #else
  35. #define CIVETWEB_API
  36. #endif
  37. #elif __GNUC__ >= 4
  38. #define CIVETWEB_API __attribute__((visibility("default")))
  39. #else
  40. #define CIVETWEB_API
  41. #endif
  42. #endif
  43. #include <stddef.h>
  44. #include <stdio.h>
  45. #ifdef __cplusplus
  46. extern "C" {
  47. #endif /* __cplusplus */
  48. /* Init Features */
  49. enum {
  50. MG_FEATURES_DEFAULT = 0x0u,
  51. /* Support files from local directories */
  52. /* Will only work, if NO_FILES is not set. */
  53. MG_FEATURES_FILES = 0x1u,
  54. /* Support transport layer security (TLS). */
  55. /* SSL is still often used synonymously for TLS. */
  56. /* Will only work, if NO_SSL is not set. */
  57. MG_FEATURES_TLS = 0x2u,
  58. MG_FEATURES_SSL = 0x2u,
  59. /* Support common gateway interface (CGI). */
  60. /* Will only work, if NO_CGI is not set. */
  61. MG_FEATURES_CGI = 0x4u,
  62. /* Support IPv6. */
  63. /* Will only work, if USE_IPV6 is set. */
  64. MG_FEATURES_IPV6 = 0x8u,
  65. /* Support WebSocket protocol. */
  66. /* Will only work, if USE_WEBSOCKET is set. */
  67. MG_FEATURES_WEBSOCKET = 0x10u,
  68. /* Support server side Lua scripting. */
  69. /* Will only work, if USE_LUA is set. */
  70. MG_FEATURES_LUA = 0x20u,
  71. /* Support server side JavaScript scripting. */
  72. /* Will only work, if USE_DUKTAPE is set. */
  73. MG_FEATURES_SSJS = 0x40u,
  74. /* Provide data required for caching files. */
  75. /* Will only work, if NO_CACHING is not set. */
  76. MG_FEATURES_CACHE = 0x80u,
  77. /* Collect server status information. */
  78. /* Will only work, if USE_SERVER_STATS is set. */
  79. MG_FEATURES_STATS = 0x100u,
  80. /* Support on-the-fly compression. */
  81. /* Will only work, if USE_ZLIB is set. */
  82. MG_FEATURES_COMPRESSION = 0x200u,
  83. /* Collect server status information. */
  84. /* Will only work, if USE_SERVER_STATS is set. */
  85. MG_FEATURES_ALL = 0xFFFFu
  86. };
  87. /* Initialize this library. This should be called once before any other
  88. * function from this library. This function is not guaranteed to be
  89. * thread safe.
  90. * Parameters:
  91. * features: bit mask for features to be initialized.
  92. * Note: The TLS libraries (like OpenSSL) is initialized
  93. * only if the MG_FEATURES_TLS bit is set.
  94. * Currently the other bits do not influence
  95. * initialization, but this may change in future
  96. * versions.
  97. * Return value:
  98. * initialized features
  99. * 0: error
  100. */
  101. CIVETWEB_API unsigned mg_init_library(unsigned features);
  102. /* Un-initialize this library.
  103. * Return value:
  104. * 0: error
  105. */
  106. CIVETWEB_API unsigned mg_exit_library(void);
  107. struct mg_context; /* Handle for the HTTP service itself */
  108. struct mg_connection; /* Handle for the individual connection */
  109. /* Maximum number of headers */
  110. #define MG_MAX_HEADERS (64)
  111. struct mg_header {
  112. const char *name; /* HTTP header name */
  113. const char *value; /* HTTP header value */
  114. };
  115. /* This structure contains information about the HTTP request. */
  116. struct mg_request_info {
  117. const char *request_method; /* "GET", "POST", etc */
  118. const char *request_uri; /* URL-decoded URI (absolute or relative,
  119. * as in the request) */
  120. const char *local_uri; /* URL-decoded URI (relative). Can be NULL
  121. * if the request_uri does not address a
  122. * resource at the server host. */
  123. #if defined(MG_LEGACY_INTERFACE) /* 2017-02-04, deprecated 2014-09-14 */
  124. const char *uri; /* Deprecated: use local_uri instead */
  125. #endif
  126. const char *http_version; /* E.g. "1.0", "1.1" */
  127. const char *query_string; /* URL part after '?', not including '?', or
  128. NULL */
  129. const char *remote_user; /* Authenticated user, or NULL if no auth
  130. used */
  131. char remote_addr[48]; /* Client's IP address as a string. */
  132. long long content_length; /* Length (in bytes) of the request body,
  133. can be -1 if no length was given. */
  134. int remote_port; /* Client's port */
  135. int is_ssl; /* 1 if SSL-ed, 0 if not */
  136. void *user_data; /* User data pointer passed to mg_start() */
  137. void *conn_data; /* Connection-specific user data */
  138. int num_headers; /* Number of HTTP headers */
  139. struct mg_header
  140. http_headers[MG_MAX_HEADERS]; /* Allocate maximum headers */
  141. struct mg_client_cert *client_cert; /* Client certificate information */
  142. const char *acceptedWebSocketSubprotocol; /* websocket subprotocol,
  143. * accepted during handshake */
  144. };
  145. /* This structure contains information about the HTTP request. */
  146. /* This structure may be extended in future versions. */
  147. struct mg_response_info {
  148. int status_code; /* E.g. 200 */
  149. const char *status_text; /* E.g. "OK" */
  150. const char *http_version; /* E.g. "1.0", "1.1" */
  151. long long content_length; /* Length (in bytes) of the request body,
  152. can be -1 if no length was given. */
  153. int num_headers; /* Number of HTTP headers */
  154. struct mg_header
  155. http_headers[MG_MAX_HEADERS]; /* Allocate maximum headers */
  156. };
  157. /* Client certificate information (part of mg_request_info) */
  158. /* New nomenclature. */
  159. struct mg_client_cert {
  160. void *peer_cert;
  161. const char *subject;
  162. const char *issuer;
  163. const char *serial;
  164. const char *finger;
  165. };
  166. #if defined(MG_LEGACY_INTERFACE) /* 2017-10-05 */
  167. /* Old nomenclature. */
  168. struct client_cert {
  169. const char *subject;
  170. const char *issuer;
  171. const char *serial;
  172. const char *finger;
  173. };
  174. #endif
  175. /* This structure needs to be passed to mg_start(), to let civetweb know
  176. which callbacks to invoke. For a detailed description, see
  177. https://github.com/civetweb/civetweb/blob/master/docs/UserManual.md */
  178. struct mg_callbacks {
  179. /* Called when civetweb has received new HTTP request.
  180. If the callback returns one, it must process the request
  181. by sending valid HTTP headers and a body. Civetweb will not do
  182. any further processing. Otherwise it must return zero.
  183. Note that since V1.7 the "begin_request" function is called
  184. before an authorization check. If an authorization check is
  185. required, use a request_handler instead.
  186. Return value:
  187. 0: civetweb will process the request itself. In this case,
  188. the callback must not send any data to the client.
  189. 1-999: callback already processed the request. Civetweb will
  190. not send any data after the callback returned. The
  191. return code is stored as a HTTP status code for the
  192. access log. */
  193. int (*begin_request)(struct mg_connection *);
  194. /* Called when civetweb has finished processing request. */
  195. void (*end_request)(const struct mg_connection *, int reply_status_code);
  196. /* Called when civetweb is about to log a message. If callback returns
  197. non-zero, civetweb does not log anything. */
  198. int (*log_message)(const struct mg_connection *, const char *message);
  199. /* Called when civetweb is about to log access. If callback returns
  200. non-zero, civetweb does not log anything. */
  201. int (*log_access)(const struct mg_connection *, const char *message);
  202. /* Called when civetweb initializes SSL library.
  203. Parameters:
  204. ssl_ctx: SSL_CTX pointer.
  205. user_data: parameter user_data passed when starting the server.
  206. Return value:
  207. 0: civetweb will set up the SSL certificate.
  208. 1: civetweb assumes the callback already set up the certificate.
  209. -1: initializing ssl fails. */
  210. int (*init_ssl)(void *ssl_ctx, void *user_data);
  211. /* Called when civetweb initializes SSL library for a domain.
  212. Parameters:
  213. server_domain: authentication_domain from the domain config.
  214. ssl_ctx: SSL_CTX pointer.
  215. user_data: parameter user_data passed when starting the server.
  216. Return value:
  217. 0: civetweb will set up the SSL certificate.
  218. 1: civetweb assumes the callback already set up the certificate.
  219. -1: initializing ssl fails. */
  220. int (*init_ssl_domain)(const char *server_domain, void *ssl_ctx, void *user_data);
  221. /* Called when civetweb is about to create or free a SSL_CTX.
  222. Parameters:
  223. ssl_ctx: SSL_CTX pointer. NULL at creation time, Not NULL when mg_context
  224. will be freed
  225. user_data: parameter user_data passed when starting the server.
  226. Return value:
  227. 0: civetweb will continue to create the context, just as if the
  228. callback would not be present.
  229. The value in *ssl_ctx when the function returns is ignored.
  230. 1: civetweb will copy the value from *ssl_ctx to the civetweb context
  231. and doesn't create its own.
  232. -1: initializing ssl fails.*/
  233. int (*external_ssl_ctx)(void **ssl_ctx, void *user_data);
  234. /* Called when civetweb is about to create or free a SSL_CTX for a domain.
  235. Parameters:
  236. server_domain: authentication_domain from the domain config.
  237. ssl_ctx: SSL_CTX pointer. NULL at creation time, Not NULL when mg_context
  238. will be freed
  239. user_data: parameter user_data passed when starting the server.
  240. Return value:
  241. 0: civetweb will continue to create the context, just as if the
  242. callback would not be present.
  243. The value in *ssl_ctx when the function returns is ignored.
  244. 1: civetweb will copy the value from *ssl_ctx to the civetweb context
  245. and doesn't create its own.
  246. -1: initializing ssl fails.*/
  247. int (*external_ssl_ctx_domain)(const char *server_domain, void **ssl_ctx, void *user_data);
  248. #if defined(MG_LEGACY_INTERFACE) /* 2015-08-19 */ \
  249. || defined(MG_EXPERIMENTAL_INTERFACES) /* 2019-11-03 */
  250. /* Called when websocket request is received, before websocket handshake.
  251. Return value:
  252. 0: civetweb proceeds with websocket handshake.
  253. 1: connection is closed immediately.
  254. This callback is deprecated: Use mg_set_websocket_handler instead. */
  255. int (*websocket_connect)(const struct mg_connection *);
  256. /* Called when websocket handshake is successfully completed, and
  257. connection is ready for data exchange.
  258. This callback is deprecated: Use mg_set_websocket_handler instead. */
  259. void (*websocket_ready)(struct mg_connection *);
  260. /* Called when data frame has been received from the client.
  261. Parameters:
  262. bits: first byte of the websocket frame, see websocket RFC at
  263. http://tools.ietf.org/html/rfc6455, section 5.2
  264. data, data_len: payload, with mask (if any) already applied.
  265. Return value:
  266. 1: keep this websocket connection open.
  267. 0: close this websocket connection.
  268. This callback is deprecated: Use mg_set_websocket_handler instead. */
  269. int (*websocket_data)(struct mg_connection *,
  270. int bits,
  271. char *data,
  272. size_t data_len);
  273. #endif /* MG_LEGACY_INTERFACE */
  274. /* Called when civetweb is closing a connection. The per-context mutex is
  275. locked when this is invoked.
  276. Websockets:
  277. Before mg_set_websocket_handler has been added, it was primarily useful
  278. for noting when a websocket is closing, and used to remove it from any
  279. application-maintained list of clients.
  280. Using this callback for websocket connections is deprecated: Use
  281. mg_set_websocket_handler instead.
  282. Connection specific data:
  283. If memory has been allocated for the connection specific user data
  284. (mg_request_info->conn_data, mg_get_user_connection_data),
  285. this is the last chance to free it.
  286. */
  287. void (*connection_close)(const struct mg_connection *);
  288. /* Called when civetweb is about to serve Lua server page, if
  289. Lua support is enabled.
  290. Parameters:
  291. conn: current connection.
  292. lua_context: "lua_State *" pointer. */
  293. void (*init_lua)(const struct mg_connection *conn, void *lua_context);
  294. #if defined(MG_LEGACY_INTERFACE) /* 2016-05-14 */
  295. /* Called when civetweb has uploaded a file to a temporary directory as a
  296. result of mg_upload() call.
  297. Note that mg_upload is deprecated. Use mg_handle_form_request instead.
  298. Parameters:
  299. file_name: full path name to the uploaded file. */
  300. void (*upload)(struct mg_connection *, const char *file_name);
  301. #endif
  302. /* Called when civetweb is about to send HTTP error to the client.
  303. Implementing this callback allows to create custom error pages.
  304. Parameters:
  305. conn: current connection.
  306. status: HTTP error status code.
  307. errmsg: error message text.
  308. Return value:
  309. 1: run civetweb error handler.
  310. 0: callback already handled the error. */
  311. int (*http_error)(struct mg_connection *conn,
  312. int status,
  313. const char *errmsg);
  314. /* Called after civetweb context has been created, before requests
  315. are processed.
  316. Parameters:
  317. ctx: context handle */
  318. void (*init_context)(const struct mg_context *ctx);
  319. /* Called when civetweb context is deleted.
  320. Parameters:
  321. ctx: context handle */
  322. void (*exit_context)(const struct mg_context *ctx);
  323. /* Called when a new worker thread is initialized.
  324. * Parameters:
  325. * ctx: context handle
  326. * thread_type:
  327. * 0 indicates the master thread
  328. * 1 indicates a worker thread handling client connections
  329. * 2 indicates an internal helper thread (timer thread)
  330. * Return value:
  331. * This function returns a user supplied pointer. The pointer is assigned
  332. * to the thread and can be obtained from the mg_connection object using
  333. * mg_get_thread_pointer in all server callbacks. Note: A connection and
  334. * a thread are not directly related. Threads will serve several different
  335. * connections, and data from a single connection may call different
  336. * callbacks using different threads. The thread pointer can be obtained
  337. * in a callback handler, but should not be stored beyond the scope of
  338. * one call to one callback.
  339. */
  340. void *(*init_thread)(const struct mg_context *ctx, int thread_type);
  341. /* Called when a worker exits.
  342. * The parameters "ctx" and "thread_type" correspond to the "init_thread"
  343. * call. The "thread_pointer" parameter is the value returned by
  344. * "init_thread".
  345. */
  346. void (*exit_thread)(const struct mg_context *ctx,
  347. int thread_type,
  348. void *thread_pointer);
  349. /* Called when initializing a new connection object.
  350. * Can be used to initialize the connection specific user data
  351. * (mg_request_info->conn_data, mg_get_user_connection_data).
  352. * When the callback is called, it is not yet known if a
  353. * valid HTTP(S) request will be made.
  354. * Parameters:
  355. * conn: not yet fully initialized connection object
  356. * conn_data: output parameter, set to initialize the
  357. * connection specific user data
  358. * Return value:
  359. * must be 0
  360. * Otherwise, the result is undefined
  361. */
  362. int (*init_connection)(const struct mg_connection *conn, void **conn_data);
  363. };
  364. /* Start web server.
  365. Parameters:
  366. callbacks: mg_callbacks structure with user-defined callbacks.
  367. options: NULL terminated list of option_name, option_value pairs that
  368. specify Civetweb configuration parameters.
  369. Side-effects: on UNIX, ignores SIGCHLD and SIGPIPE signals. If custom
  370. processing is required for these, signal handlers must be set up
  371. after calling mg_start().
  372. Example:
  373. const char *options[] = {
  374. "document_root", "/var/www",
  375. "listening_ports", "80,443s",
  376. NULL
  377. };
  378. struct mg_context *ctx = mg_start(&my_func, NULL, options);
  379. Refer to https://github.com/civetweb/civetweb/blob/master/docs/UserManual.md
  380. for the list of valid option and their possible values.
  381. Return:
  382. web server context, or NULL on error. */
  383. CIVETWEB_API struct mg_context *mg_start(const struct mg_callbacks *callbacks,
  384. void *user_data,
  385. const char **configuration_options);
  386. /* Stop the web server.
  387. Must be called last, when an application wants to stop the web server and
  388. release all associated resources. This function blocks until all Civetweb
  389. threads are stopped. Context pointer becomes invalid. */
  390. CIVETWEB_API void mg_stop(struct mg_context *);
  391. #if defined(MG_EXPERIMENTAL_INTERFACES)
  392. /* Add an additional domain to an already running web server.
  393. *
  394. * Parameters:
  395. * ctx: Context handle of a server started by mg_start.
  396. * options: NULL terminated list of option_name, option_value pairs that
  397. * specify CivetWeb configuration parameters.
  398. *
  399. * Return:
  400. * < 0 in case of an error
  401. * -1 for a parameter error
  402. * -2 invalid options
  403. * -3 initializing SSL failed
  404. * -4 mandatory domain option missing
  405. * -5 duplicate domain
  406. * -6 out of memory
  407. * > 0 index / handle of a new domain
  408. */
  409. CIVETWEB_API int mg_start_domain(struct mg_context *ctx,
  410. const char **configuration_options);
  411. #endif
  412. /* mg_request_handler
  413. Called when a new request comes in. This callback is URI based
  414. and configured with mg_set_request_handler().
  415. Parameters:
  416. conn: current connection information.
  417. cbdata: the callback data configured with mg_set_request_handler().
  418. Returns:
  419. 0: the handler could not handle the request, so fall through.
  420. 1 - 999: the handler processed the request. The return code is
  421. stored as a HTTP status code for the access log. */
  422. typedef int (*mg_request_handler)(struct mg_connection *conn, void *cbdata);
  423. /* mg_set_request_handler
  424. Sets or removes a URI mapping for a request handler.
  425. This function uses mg_lock_context internally.
  426. URI's are ordered and prefixed URI's are supported. For example,
  427. consider two URIs: /a/b and /a
  428. /a matches /a
  429. /a/b matches /a/b
  430. /a/c matches /a
  431. Parameters:
  432. ctx: server context
  433. uri: the URI (exact or pattern) for the handler
  434. handler: the callback handler to use when the URI is requested.
  435. If NULL, an already registered handler for this URI will
  436. be removed.
  437. The URI used to remove a handler must match exactly the
  438. one used to register it (not only a pattern match).
  439. cbdata: the callback data to give to the handler when it is called. */
  440. CIVETWEB_API void mg_set_request_handler(struct mg_context *ctx,
  441. const char *uri,
  442. mg_request_handler handler,
  443. void *cbdata);
  444. /* Callback types for websocket handlers in C/C++.
  445. mg_websocket_connect_handler
  446. Is called when the client intends to establish a websocket connection,
  447. before websocket handshake.
  448. Return value:
  449. 0: civetweb proceeds with websocket handshake.
  450. 1: connection is closed immediately.
  451. mg_websocket_ready_handler
  452. Is called when websocket handshake is successfully completed, and
  453. connection is ready for data exchange.
  454. mg_websocket_data_handler
  455. Is called when a data frame has been received from the client.
  456. Parameters:
  457. bits: first byte of the websocket frame, see websocket RFC at
  458. http://tools.ietf.org/html/rfc6455, section 5.2
  459. data, data_len: payload, with mask (if any) already applied.
  460. Return value:
  461. 1: keep this websocket connection open.
  462. 0: close this websocket connection.
  463. mg_connection_close_handler
  464. Is called, when the connection is closed.*/
  465. typedef int (*mg_websocket_connect_handler)(const struct mg_connection *,
  466. void *);
  467. typedef void (*mg_websocket_ready_handler)(struct mg_connection *, void *);
  468. typedef int (*mg_websocket_data_handler)(struct mg_connection *,
  469. int,
  470. char *,
  471. size_t,
  472. void *);
  473. typedef void (*mg_websocket_close_handler)(const struct mg_connection *,
  474. void *);
  475. /* struct mg_websocket_subprotocols
  476. *
  477. * List of accepted subprotocols
  478. */
  479. struct mg_websocket_subprotocols {
  480. int nb_subprotocols;
  481. char **subprotocols;
  482. };
  483. /* mg_set_websocket_handler
  484. Set or remove handler functions for websocket connections.
  485. This function works similar to mg_set_request_handler - see there. */
  486. CIVETWEB_API void
  487. mg_set_websocket_handler(struct mg_context *ctx,
  488. const char *uri,
  489. mg_websocket_connect_handler connect_handler,
  490. mg_websocket_ready_handler ready_handler,
  491. mg_websocket_data_handler data_handler,
  492. mg_websocket_close_handler close_handler,
  493. void *cbdata);
  494. /* mg_set_websocket_handler
  495. Set or remove handler functions for websocket connections.
  496. This function works similar to mg_set_request_handler - see there. */
  497. CIVETWEB_API void mg_set_websocket_handler_with_subprotocols(
  498. struct mg_context *ctx,
  499. const char *uri,
  500. struct mg_websocket_subprotocols *subprotocols,
  501. mg_websocket_connect_handler connect_handler,
  502. mg_websocket_ready_handler ready_handler,
  503. mg_websocket_data_handler data_handler,
  504. mg_websocket_close_handler close_handler,
  505. void *cbdata);
  506. /* mg_authorization_handler
  507. Callback function definition for mg_set_auth_handler
  508. Parameters:
  509. conn: current connection information.
  510. cbdata: the callback data configured with mg_set_request_handler().
  511. Returns:
  512. 0: access denied
  513. 1: access granted
  514. */
  515. typedef int (*mg_authorization_handler)(struct mg_connection *conn,
  516. void *cbdata);
  517. /* mg_set_auth_handler
  518. Sets or removes a URI mapping for an authorization handler.
  519. This function works similar to mg_set_request_handler - see there. */
  520. CIVETWEB_API void mg_set_auth_handler(struct mg_context *ctx,
  521. const char *uri,
  522. mg_authorization_handler handler,
  523. void *cbdata);
  524. /* Get the value of particular configuration parameter.
  525. The value returned is read-only. Civetweb does not allow changing
  526. configuration at run time.
  527. If given parameter name is not valid, NULL is returned. For valid
  528. names, return value is guaranteed to be non-NULL. If parameter is not
  529. set, zero-length string is returned. */
  530. CIVETWEB_API const char *mg_get_option(const struct mg_context *ctx,
  531. const char *name);
  532. /* Get context from connection. */
  533. CIVETWEB_API struct mg_context *
  534. mg_get_context(const struct mg_connection *conn);
  535. /* Get user data passed to mg_start from context. */
  536. CIVETWEB_API void *mg_get_user_data(const struct mg_context *ctx);
  537. /* Get user data passed to mg_start from connection. */
  538. CIVETWEB_API void *mg_get_user_context_data(const struct mg_connection *conn);
  539. /* Get user defined thread pointer for server threads (see init_thread). */
  540. CIVETWEB_API void *mg_get_thread_pointer(const struct mg_connection *conn);
  541. /* Set user data for the current connection. */
  542. /* Note: This function is deprecated. Use the init_connection callback
  543. instead to initialize the user connection data pointer. It is
  544. reccomended to supply a pointer to some user defined data structure
  545. as conn_data initializer in init_connection. In case it is required
  546. to change some data after the init_connection call, store another
  547. data pointer in the user defined data structure and modify that
  548. pointer. In either case, after the init_connection callback, only
  549. calls to mg_get_user_connection_data should be required. */
  550. CIVETWEB_API void mg_set_user_connection_data(struct mg_connection *conn,
  551. void *data);
  552. /* Get user data set for the current connection. */
  553. CIVETWEB_API void *
  554. mg_get_user_connection_data(const struct mg_connection *conn);
  555. /* Get a formatted link corresponding to the current request
  556. Parameters:
  557. conn: current connection information.
  558. buf: string buffer (out)
  559. buflen: length of the string buffer
  560. Returns:
  561. <0: error
  562. >=0: ok */
  563. CIVETWEB_API int
  564. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen);
  565. #if defined(MG_LEGACY_INTERFACE) /* 2014-02-21 */
  566. /* Return array of strings that represent valid configuration options.
  567. For each option, option name and default value is returned, i.e. the
  568. number of entries in the array equals to number_of_options x 2.
  569. Array is NULL terminated. */
  570. /* Deprecated: Use mg_get_valid_options instead. */
  571. CIVETWEB_API const char **mg_get_valid_option_names(void);
  572. #endif
  573. struct mg_option {
  574. const char *name;
  575. int type;
  576. const char *default_value;
  577. };
  578. /* Old nomenclature */
  579. #if defined(MG_LEGACY_INTERFACE) /* 2017-10-05 */
  580. enum {
  581. CONFIG_TYPE_UNKNOWN = 0x0,
  582. CONFIG_TYPE_NUMBER = 0x1,
  583. CONFIG_TYPE_STRING = 0x2,
  584. CONFIG_TYPE_FILE = 0x3,
  585. CONFIG_TYPE_DIRECTORY = 0x4,
  586. CONFIG_TYPE_BOOLEAN = 0x5,
  587. CONFIG_TYPE_EXT_PATTERN = 0x6,
  588. CONFIG_TYPE_STRING_LIST = 0x7,
  589. CONFIG_TYPE_STRING_MULTILINE = 0x8
  590. };
  591. #endif
  592. /* New nomenclature */
  593. enum {
  594. MG_CONFIG_TYPE_UNKNOWN = 0x0,
  595. MG_CONFIG_TYPE_NUMBER = 0x1,
  596. MG_CONFIG_TYPE_STRING = 0x2,
  597. MG_CONFIG_TYPE_FILE = 0x3,
  598. MG_CONFIG_TYPE_DIRECTORY = 0x4,
  599. MG_CONFIG_TYPE_BOOLEAN = 0x5,
  600. MG_CONFIG_TYPE_EXT_PATTERN = 0x6,
  601. MG_CONFIG_TYPE_STRING_LIST = 0x7,
  602. MG_CONFIG_TYPE_STRING_MULTILINE = 0x8,
  603. MG_CONFIG_TYPE_YES_NO_OPTIONAL = 0x9
  604. };
  605. /* Return array of struct mg_option, representing all valid configuration
  606. options of civetweb.c.
  607. The array is terminated by a NULL name option. */
  608. CIVETWEB_API const struct mg_option *mg_get_valid_options(void);
  609. struct mg_server_port {
  610. int protocol; /* 1 = IPv4, 2 = IPv6, 3 = both */
  611. int port; /* port number */
  612. int is_ssl; /* https port: 0 = no, 1 = yes */
  613. int is_redirect; /* redirect all requests: 0 = no, 1 = yes */
  614. int _reserved1;
  615. int _reserved2;
  616. int _reserved3;
  617. int _reserved4;
  618. };
  619. /* Legacy name */
  620. #define mg_server_ports mg_server_port
  621. /* Get the list of ports that civetweb is listening on.
  622. The parameter size is the size of the ports array in elements.
  623. The caller is responsibility to allocate the required memory.
  624. This function returns the number of struct mg_server_port elements
  625. filled in, or <0 in case of an error. */
  626. CIVETWEB_API int mg_get_server_ports(const struct mg_context *ctx,
  627. int size,
  628. struct mg_server_port *ports);
  629. #if defined(MG_LEGACY_INTERFACE) /* 2017-04-02 */
  630. /* Deprecated: Use mg_get_server_ports instead. */
  631. CIVETWEB_API size_t mg_get_ports(const struct mg_context *ctx,
  632. size_t size,
  633. int *ports,
  634. int *ssl);
  635. #endif
  636. /* Add, edit or delete the entry in the passwords file.
  637. *
  638. * This function allows an application to manipulate .htpasswd files on the
  639. * fly by adding, deleting and changing user records. This is one of the
  640. * several ways of implementing authentication on the server side. For another,
  641. * cookie-based way please refer to the examples/chat in the source tree.
  642. *
  643. * Parameter:
  644. * passwords_file_name: Path and name of a file storing multiple passwords
  645. * realm: HTTP authentication realm (authentication domain) name
  646. * user: User name
  647. * password:
  648. * If password is not NULL, entry modified or added.
  649. * If password is NULL, entry is deleted.
  650. *
  651. * Return:
  652. * 1 on success, 0 on error.
  653. */
  654. CIVETWEB_API int mg_modify_passwords_file(const char *passwords_file_name,
  655. const char *realm,
  656. const char *user,
  657. const char *password);
  658. /* Return information associated with the request.
  659. * Use this function to implement a server and get data about a request
  660. * from a HTTP/HTTPS client.
  661. * Note: Before CivetWeb 1.10, this function could be used to read
  662. * a response from a server, when implementing a client, although the
  663. * values were never returned in appropriate mg_request_info elements.
  664. * It is strongly advised to use mg_get_response_info for clients.
  665. */
  666. CIVETWEB_API const struct mg_request_info *
  667. mg_get_request_info(const struct mg_connection *);
  668. /* Return information associated with a HTTP/HTTPS response.
  669. * Use this function in a client, to check the response from
  670. * the server. */
  671. CIVETWEB_API const struct mg_response_info *
  672. mg_get_response_info(const struct mg_connection *);
  673. /* Send data to the client.
  674. Return:
  675. 0 when the connection has been closed
  676. -1 on error
  677. >0 number of bytes written on success */
  678. CIVETWEB_API int mg_write(struct mg_connection *, const void *buf, size_t len);
  679. /* Send data to a websocket client wrapped in a websocket frame. Uses
  680. mg_lock_connection to ensure that the transmission is not interrupted,
  681. i.e., when the application is proactively communicating and responding to
  682. a request simultaneously.
  683. Send data to a websocket client wrapped in a websocket frame.
  684. This function is available when civetweb is compiled with -DUSE_WEBSOCKET
  685. Return:
  686. 0 when the connection has been closed
  687. -1 on error
  688. >0 number of bytes written on success */
  689. CIVETWEB_API int mg_websocket_write(struct mg_connection *conn,
  690. int opcode,
  691. const char *data,
  692. size_t data_len);
  693. /* Send data to a websocket server wrapped in a masked websocket frame. Uses
  694. mg_lock_connection to ensure that the transmission is not interrupted,
  695. i.e., when the application is proactively communicating and responding to
  696. a request simultaneously.
  697. Send data to a websocket server wrapped in a masked websocket frame.
  698. This function is available when civetweb is compiled with -DUSE_WEBSOCKET
  699. Return:
  700. 0 when the connection has been closed
  701. -1 on error
  702. >0 number of bytes written on success */
  703. CIVETWEB_API int mg_websocket_client_write(struct mg_connection *conn,
  704. int opcode,
  705. const char *data,
  706. size_t data_len);
  707. /* Blocks until unique access is obtained to this connection. Intended for use
  708. with websockets only.
  709. Invoke this before mg_write or mg_printf when communicating with a
  710. websocket if your code has server-initiated communication as well as
  711. communication in direct response to a message. */
  712. CIVETWEB_API void mg_lock_connection(struct mg_connection *conn);
  713. CIVETWEB_API void mg_unlock_connection(struct mg_connection *conn);
  714. #if defined(MG_LEGACY_INTERFACE) /* 2014-06-21 */
  715. #define mg_lock mg_lock_connection
  716. #define mg_unlock mg_unlock_connection
  717. #endif
  718. /* Lock server context. This lock may be used to protect resources
  719. that are shared between different connection/worker threads. */
  720. CIVETWEB_API void mg_lock_context(struct mg_context *ctx);
  721. CIVETWEB_API void mg_unlock_context(struct mg_context *ctx);
  722. /* Opcodes, from http://tools.ietf.org/html/rfc6455 */
  723. #if defined(MG_LEGACY_INTERFACE) /* 2017-10-05 */
  724. enum {
  725. WEBSOCKET_OPCODE_CONTINUATION = 0x0,
  726. WEBSOCKET_OPCODE_TEXT = 0x1,
  727. WEBSOCKET_OPCODE_BINARY = 0x2,
  728. WEBSOCKET_OPCODE_CONNECTION_CLOSE = 0x8,
  729. WEBSOCKET_OPCODE_PING = 0x9,
  730. WEBSOCKET_OPCODE_PONG = 0xa
  731. };
  732. #endif
  733. /* New nomenclature */
  734. enum {
  735. MG_WEBSOCKET_OPCODE_CONTINUATION = 0x0,
  736. MG_WEBSOCKET_OPCODE_TEXT = 0x1,
  737. MG_WEBSOCKET_OPCODE_BINARY = 0x2,
  738. MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE = 0x8,
  739. MG_WEBSOCKET_OPCODE_PING = 0x9,
  740. MG_WEBSOCKET_OPCODE_PONG = 0xa
  741. };
  742. /* Macros for enabling compiler-specific checks for printf-like arguments. */
  743. #undef PRINTF_FORMAT_STRING
  744. #if defined(_MSC_VER) && _MSC_VER >= 1400
  745. #include <sal.h>
  746. #if defined(_MSC_VER) && _MSC_VER > 1400
  747. #define PRINTF_FORMAT_STRING(s) _Printf_format_string_ s
  748. #else
  749. #define PRINTF_FORMAT_STRING(s) __format_string s
  750. #endif
  751. #else
  752. #define PRINTF_FORMAT_STRING(s) s
  753. #endif
  754. #ifdef __GNUC__
  755. #define PRINTF_ARGS(x, y) __attribute__((format(printf, x, y)))
  756. #else
  757. #define PRINTF_ARGS(x, y)
  758. #endif
  759. /* Send data to the client using printf() semantics.
  760. Works exactly like mg_write(), but allows to do message formatting. */
  761. CIVETWEB_API int mg_printf(struct mg_connection *,
  762. PRINTF_FORMAT_STRING(const char *fmt),
  763. ...) PRINTF_ARGS(2, 3);
  764. /* Send a part of the message body, if chunked transfer encoding is set.
  765. * Only use this function after sending a complete HTTP request or response
  766. * header with "Transfer-Encoding: chunked" set. */
  767. CIVETWEB_API int mg_send_chunk(struct mg_connection *conn,
  768. const char *chunk,
  769. unsigned int chunk_len);
  770. /* Send contents of the entire file together with HTTP headers.
  771. * Parameters:
  772. * conn: Current connection information.
  773. * path: Full path to the file to send.
  774. * This function has been superseded by mg_send_mime_file
  775. */
  776. CIVETWEB_API void mg_send_file(struct mg_connection *conn, const char *path);
  777. /* Send contents of the file without HTTP headers.
  778. * The code must send a valid HTTP response header before using this function.
  779. *
  780. * Parameters:
  781. * conn: Current connection information.
  782. * path: Full path to the file to send.
  783. *
  784. * Return:
  785. * < 0 Error
  786. */
  787. CIVETWEB_API int mg_send_file_body(struct mg_connection *conn,
  788. const char *path);
  789. /* Send HTTP error reply. */
  790. CIVETWEB_API int mg_send_http_error(struct mg_connection *conn,
  791. int status_code,
  792. PRINTF_FORMAT_STRING(const char *fmt),
  793. ...) PRINTF_ARGS(3, 4);
  794. /* Send "HTTP 200 OK" response header.
  795. * After calling this function, use mg_write or mg_send_chunk to send the
  796. * response body.
  797. * Parameters:
  798. * conn: Current connection handle.
  799. * mime_type: Set Content-Type for the following content.
  800. * content_length: Size of the following content, if content_length >= 0.
  801. * Will set transfer-encoding to chunked, if set to -1.
  802. * Return:
  803. * < 0 Error
  804. */
  805. CIVETWEB_API int mg_send_http_ok(struct mg_connection *conn,
  806. const char *mime_type,
  807. long long content_length);
  808. /* Send "HTTP 30x" redirect response.
  809. * The response has content-size zero: do not send any body data after calling
  810. * this function.
  811. * Parameters:
  812. * conn: Current connection handle.
  813. * target_url: New location.
  814. * redirect_code: HTTP redirect type. Could be 301, 302, 303, 307, 308.
  815. * Return:
  816. * < 0 Error (-1 send error, -2 parameter error)
  817. */
  818. CIVETWEB_API int mg_send_http_redirect(struct mg_connection *conn,
  819. const char *target_url,
  820. int redirect_code);
  821. /* Send HTTP digest access authentication request.
  822. * Browsers will send a user name and password in their next request, showing
  823. * an authentication dialog if the password is not stored.
  824. * Parameters:
  825. * conn: Current connection handle.
  826. * realm: Authentication realm. If NULL is supplied, the sever domain
  827. * set in the authentication_domain configuration is used.
  828. * Return:
  829. * < 0 Error
  830. */
  831. CIVETWEB_API int
  832. mg_send_digest_access_authentication_request(struct mg_connection *conn,
  833. const char *realm);
  834. /* Check if the current request has a valid authentication token set.
  835. * A file is used to provide a list of valid user names, realms and
  836. * password hashes. The file can be created and modified using the
  837. * mg_modify_passwords_file API function.
  838. * Parameters:
  839. * conn: Current connection handle.
  840. * realm: Authentication realm. If NULL is supplied, the sever domain
  841. * set in the authentication_domain configuration is used.
  842. * filename: Path and name of a file storing multiple password hashes.
  843. * Return:
  844. * > 0 Valid authentication
  845. * 0 Invalid authentication
  846. * < 0 Error (all values < 0 should be considered as invalid
  847. * authentication, future error codes will have negative
  848. * numbers)
  849. * -1 Parameter error
  850. * -2 File not found
  851. */
  852. CIVETWEB_API int
  853. mg_check_digest_access_authentication(struct mg_connection *conn,
  854. const char *realm,
  855. const char *filename);
  856. /* Send contents of the entire file together with HTTP headers.
  857. * Parameters:
  858. * conn: Current connection handle.
  859. * path: Full path to the file to send.
  860. * mime_type: Content-Type for file. NULL will cause the type to be
  861. * looked up by the file extension.
  862. */
  863. CIVETWEB_API void mg_send_mime_file(struct mg_connection *conn,
  864. const char *path,
  865. const char *mime_type);
  866. /* Send contents of the entire file together with HTTP headers.
  867. Parameters:
  868. conn: Current connection information.
  869. path: Full path to the file to send.
  870. mime_type: Content-Type for file. NULL will cause the type to be
  871. looked up by the file extension.
  872. additional_headers: Additional custom header fields appended to the header.
  873. Each header should start with an X-, to ensure it is
  874. not included twice.
  875. NULL does not append anything.
  876. */
  877. CIVETWEB_API void mg_send_mime_file2(struct mg_connection *conn,
  878. const char *path,
  879. const char *mime_type,
  880. const char *additional_headers);
  881. /* Store body data into a file. */
  882. CIVETWEB_API long long mg_store_body(struct mg_connection *conn,
  883. const char *path);
  884. /* Read entire request body and store it in a file "path".
  885. Return:
  886. < 0 Error
  887. >= 0 Number of bytes stored in file "path".
  888. */
  889. /* Read data from the remote end, return number of bytes read.
  890. Return:
  891. 0 connection has been closed by peer. No more data could be read.
  892. < 0 read error. No more data could be read from the connection.
  893. > 0 number of bytes read into the buffer. */
  894. CIVETWEB_API int mg_read(struct mg_connection *, void *buf, size_t len);
  895. /* Get the value of particular HTTP header.
  896. This is a helper function. It traverses request_info->http_headers array,
  897. and if the header is present in the array, returns its value. If it is
  898. not present, NULL is returned. */
  899. CIVETWEB_API const char *mg_get_header(const struct mg_connection *,
  900. const char *name);
  901. /* Get a value of particular form variable.
  902. Parameters:
  903. data: pointer to form-uri-encoded buffer. This could be either POST data,
  904. or request_info.query_string.
  905. data_len: length of the encoded data.
  906. var_name: variable name to decode from the buffer
  907. dst: destination buffer for the decoded variable
  908. dst_len: length of the destination buffer
  909. Return:
  910. On success, length of the decoded variable.
  911. On error:
  912. -1 (variable not found).
  913. -2 (destination buffer is NULL, zero length or too small to hold the
  914. decoded variable).
  915. Destination buffer is guaranteed to be '\0' - terminated if it is not
  916. NULL or zero length. */
  917. CIVETWEB_API int mg_get_var(const char *data,
  918. size_t data_len,
  919. const char *var_name,
  920. char *dst,
  921. size_t dst_len);
  922. /* Get a value of particular form variable.
  923. Parameters:
  924. data: pointer to form-uri-encoded buffer. This could be either POST data,
  925. or request_info.query_string.
  926. data_len: length of the encoded data.
  927. var_name: variable name to decode from the buffer
  928. dst: destination buffer for the decoded variable
  929. dst_len: length of the destination buffer
  930. occurrence: which occurrence of the variable, 0 is the first, 1 the
  931. second...
  932. this makes it possible to parse a query like
  933. b=x&a=y&a=z which will have occurrence values b:0, a:0 and a:1
  934. Return:
  935. On success, length of the decoded variable.
  936. On error:
  937. -1 (variable not found).
  938. -2 (destination buffer is NULL, zero length or too small to hold the
  939. decoded variable).
  940. Destination buffer is guaranteed to be '\0' - terminated if it is not
  941. NULL or zero length. */
  942. CIVETWEB_API int mg_get_var2(const char *data,
  943. size_t data_len,
  944. const char *var_name,
  945. char *dst,
  946. size_t dst_len,
  947. size_t occurrence);
  948. /* Fetch value of certain cookie variable into the destination buffer.
  949. Destination buffer is guaranteed to be '\0' - terminated. In case of
  950. failure, dst[0] == '\0'. Note that RFC allows many occurrences of the same
  951. parameter. This function returns only first occurrence.
  952. Return:
  953. On success, value length.
  954. On error:
  955. -1 (either "Cookie:" header is not present at all or the requested
  956. parameter is not found).
  957. -2 (destination buffer is NULL, zero length or too small to hold the
  958. value). */
  959. CIVETWEB_API int mg_get_cookie(const char *cookie,
  960. const char *var_name,
  961. char *buf,
  962. size_t buf_len);
  963. /* Download data from the remote web server.
  964. host: host name to connect to, e.g. "foo.com", or "10.12.40.1".
  965. port: port number, e.g. 80.
  966. use_ssl: whether to use SSL connection.
  967. error_buffer, error_buffer_size: error message placeholder.
  968. request_fmt,...: HTTP request.
  969. Return:
  970. On success, valid pointer to the new connection, suitable for mg_read().
  971. On error, NULL. error_buffer contains error message.
  972. Example:
  973. char ebuf[100];
  974. struct mg_connection *conn;
  975. conn = mg_download("google.com", 80, 0, ebuf, sizeof(ebuf),
  976. "%s", "GET / HTTP/1.0\r\nHost: google.com\r\n\r\n");
  977. mg_download is equivalent to calling mg_connect_client followed by
  978. mg_printf and mg_get_response. Using these three functions directly may
  979. allow more control as compared to using mg_download.
  980. */
  981. CIVETWEB_API struct mg_connection *
  982. mg_download(const char *host,
  983. int port,
  984. int use_ssl,
  985. char *error_buffer,
  986. size_t error_buffer_size,
  987. PRINTF_FORMAT_STRING(const char *request_fmt),
  988. ...) PRINTF_ARGS(6, 7);
  989. /* Close the connection opened by mg_download(). */
  990. CIVETWEB_API void mg_close_connection(struct mg_connection *conn);
  991. #if defined(MG_LEGACY_INTERFACE) /* 2016-05-14 */
  992. /* File upload functionality. Each uploaded file gets saved into a temporary
  993. file and MG_UPLOAD event is sent.
  994. Return number of uploaded files.
  995. Deprecated: Use mg_handle_form_request instead. */
  996. CIVETWEB_API int mg_upload(struct mg_connection *conn,
  997. const char *destination_dir);
  998. #endif
  999. /* This structure contains callback functions for handling form fields.
  1000. It is used as an argument to mg_handle_form_request. */
  1001. struct mg_form_data_handler {
  1002. /* This callback function is called, if a new field has been found.
  1003. * The return value of this callback is used to define how the field
  1004. * should be processed.
  1005. *
  1006. * Parameters:
  1007. * key: Name of the field ("name" property of the HTML input field).
  1008. * filename: Name of a file to upload, at the client computer.
  1009. * Only set for input fields of type "file", otherwise NULL.
  1010. * path: Output parameter: File name (incl. path) to store the file
  1011. * at the server computer. Only used if FORM_FIELD_STORAGE_STORE
  1012. * is returned by this callback. Existing files will be
  1013. * overwritten.
  1014. * pathlen: Length of the buffer for path.
  1015. * user_data: Value of the member user_data of mg_form_data_handler
  1016. *
  1017. * Return value:
  1018. * The callback must return the intended storage for this field
  1019. * (See FORM_FIELD_STORAGE_*).
  1020. */
  1021. int (*field_found)(const char *key,
  1022. const char *filename,
  1023. char *path,
  1024. size_t pathlen,
  1025. void *user_data);
  1026. /* If the "field_found" callback returned FORM_FIELD_STORAGE_GET,
  1027. * this callback will receive the field data.
  1028. *
  1029. * Parameters:
  1030. * key: Name of the field ("name" property of the HTML input field).
  1031. * value: Value of the input field.
  1032. * user_data: Value of the member user_data of mg_form_data_handler
  1033. *
  1034. * Return value:
  1035. * The return code determines how the server should continue processing
  1036. * the current request (See MG_FORM_FIELD_HANDLE_*).
  1037. */
  1038. int (*field_get)(const char *key,
  1039. const char *value,
  1040. size_t valuelen,
  1041. void *user_data);
  1042. /* If the "field_found" callback returned FORM_FIELD_STORAGE_STORE,
  1043. * the data will be stored into a file. If the file has been written
  1044. * successfully, this callback will be called. This callback will
  1045. * not be called for only partially uploaded files. The
  1046. * mg_handle_form_request function will either store the file completely
  1047. * and call this callback, or it will remove any partial content and
  1048. * not call this callback function.
  1049. *
  1050. * Parameters:
  1051. * path: Path of the file stored at the server.
  1052. * file_size: Size of the stored file in bytes.
  1053. * user_data: Value of the member user_data of mg_form_data_handler
  1054. *
  1055. * Return value:
  1056. * The return code determines how the server should continue processing
  1057. * the current request (See MG_FORM_FIELD_HANDLE_*).
  1058. */
  1059. int (*field_store)(const char *path, long long file_size, void *user_data);
  1060. /* User supplied argument, passed to all callback functions. */
  1061. void *user_data;
  1062. };
  1063. /* Return values definition for the "field_found" callback in
  1064. * mg_form_data_handler. */
  1065. #if defined(MG_LEGACY_INTERFACE) /* 2017-10-05 */
  1066. enum {
  1067. /* Skip this field (neither get nor store it). Continue with the
  1068. * next field. */
  1069. FORM_FIELD_STORAGE_SKIP = 0x0,
  1070. /* Get the field value. */
  1071. FORM_FIELD_STORAGE_GET = 0x1,
  1072. /* Store the field value into a file. */
  1073. FORM_FIELD_STORAGE_STORE = 0x2,
  1074. /* Stop parsing this request. Skip the remaining fields. */
  1075. FORM_FIELD_STORAGE_ABORT = 0x10
  1076. };
  1077. #endif
  1078. /* New nomenclature */
  1079. enum {
  1080. /* Skip this field (neither get nor store it). Continue with the
  1081. * next field. */
  1082. MG_FORM_FIELD_STORAGE_SKIP = 0x0,
  1083. /* Get the field value. */
  1084. MG_FORM_FIELD_STORAGE_GET = 0x1,
  1085. /* Store the field value into a file. */
  1086. MG_FORM_FIELD_STORAGE_STORE = 0x2,
  1087. /* Stop parsing this request. Skip the remaining fields. */
  1088. MG_FORM_FIELD_STORAGE_ABORT = 0x10
  1089. };
  1090. /* Return values for "field_get" and "field_store" */
  1091. enum {
  1092. /* Only "field_get": If there is more data in this field, get the next
  1093. * chunk. Otherwise: handle the next field. */
  1094. MG_FORM_FIELD_HANDLE_GET = 0x1,
  1095. /* Handle the next field */
  1096. MG_FORM_FIELD_HANDLE_NEXT = 0x8,
  1097. /* Stop parsing this request */
  1098. MG_FORM_FIELD_HANDLE_ABORT = 0x10
  1099. };
  1100. /* Process form data.
  1101. * Returns the number of fields handled, or < 0 in case of an error.
  1102. * Note: It is possible that several fields are already handled successfully
  1103. * (e.g., stored into files), before the request handling is stopped with an
  1104. * error. In this case a number < 0 is returned as well.
  1105. * In any case, it is the duty of the caller to remove files once they are
  1106. * no longer required. */
  1107. CIVETWEB_API int mg_handle_form_request(struct mg_connection *conn,
  1108. struct mg_form_data_handler *fdh);
  1109. /* Convenience function -- create detached thread.
  1110. Return: 0 on success, non-0 on error. */
  1111. typedef void *(*mg_thread_func_t)(void *);
  1112. CIVETWEB_API int mg_start_thread(mg_thread_func_t f, void *p);
  1113. /* Return builtin mime type for the given file name.
  1114. For unrecognized extensions, "text/plain" is returned. */
  1115. CIVETWEB_API const char *mg_get_builtin_mime_type(const char *file_name);
  1116. /* Get text representation of HTTP status code. */
  1117. CIVETWEB_API const char *
  1118. mg_get_response_code_text(const struct mg_connection *conn, int response_code);
  1119. /* Return CivetWeb version. */
  1120. CIVETWEB_API const char *mg_version(void);
  1121. /* URL-decode input buffer into destination buffer.
  1122. 0-terminate the destination buffer.
  1123. form-url-encoded data differs from URI encoding in a way that it
  1124. uses '+' as character for space, see RFC 1866 section 8.2.1
  1125. http://ftp.ics.uci.edu/pub/ietf/html/rfc1866.txt
  1126. Return: length of the decoded data, or -1 if dst buffer is too small. */
  1127. CIVETWEB_API int mg_url_decode(const char *src,
  1128. int src_len,
  1129. char *dst,
  1130. int dst_len,
  1131. int is_form_url_encoded);
  1132. /* URL-encode input buffer into destination buffer.
  1133. returns the length of the resulting buffer or -1
  1134. is the buffer is too small. */
  1135. CIVETWEB_API int mg_url_encode(const char *src, char *dst, size_t dst_len);
  1136. /* MD5 hash given strings.
  1137. Buffer 'buf' must be 33 bytes long. Varargs is a NULL terminated list of
  1138. ASCIIz strings. When function returns, buf will contain human-readable
  1139. MD5 hash. Example:
  1140. char buf[33];
  1141. mg_md5(buf, "aa", "bb", NULL); */
  1142. CIVETWEB_API char *mg_md5(char buf[33], ...);
  1143. /* Print error message to the opened error log stream.
  1144. This utilizes the provided logging configuration.
  1145. conn: connection (not used for sending data, but to get perameters)
  1146. fmt: format string without the line return
  1147. ...: variable argument list
  1148. Example:
  1149. mg_cry(conn,"i like %s", "logging"); */
  1150. CIVETWEB_API void mg_cry(const struct mg_connection *conn,
  1151. PRINTF_FORMAT_STRING(const char *fmt),
  1152. ...) PRINTF_ARGS(2, 3);
  1153. /* utility methods to compare two buffers, case insensitive. */
  1154. CIVETWEB_API int mg_strcasecmp(const char *s1, const char *s2);
  1155. CIVETWEB_API int mg_strncasecmp(const char *s1, const char *s2, size_t len);
  1156. /* Connect to a websocket as a client
  1157. Parameters:
  1158. host: host to connect to, i.e. "echo.websocket.org" or "192.168.1.1" or
  1159. "localhost"
  1160. port: server port
  1161. use_ssl: make a secure connection to server
  1162. error_buffer, error_buffer_size: buffer for an error message
  1163. path: server path you are trying to connect to, i.e. if connection to
  1164. localhost/app, path should be "/app"
  1165. origin: value of the Origin HTTP header
  1166. data_func: callback that should be used when data is received from the
  1167. server
  1168. user_data: user supplied argument
  1169. Return:
  1170. On success, valid mg_connection object.
  1171. On error, NULL. Se error_buffer for details.
  1172. */
  1173. CIVETWEB_API struct mg_connection *
  1174. mg_connect_websocket_client(const char *host,
  1175. int port,
  1176. int use_ssl,
  1177. char *error_buffer,
  1178. size_t error_buffer_size,
  1179. const char *path,
  1180. const char *origin,
  1181. mg_websocket_data_handler data_func,
  1182. mg_websocket_close_handler close_func,
  1183. void *user_data);
  1184. /* Connect to a TCP server as a client (can be used to connect to a HTTP server)
  1185. Parameters:
  1186. host: host to connect to, i.e. "www.wikipedia.org" or "192.168.1.1" or
  1187. "localhost"
  1188. port: server port
  1189. use_ssl: make a secure connection to server
  1190. error_buffer, error_buffer_size: buffer for an error message
  1191. Return:
  1192. On success, valid mg_connection object.
  1193. On error, NULL. Se error_buffer for details.
  1194. */
  1195. CIVETWEB_API struct mg_connection *mg_connect_client(const char *host,
  1196. int port,
  1197. int use_ssl,
  1198. char *error_buffer,
  1199. size_t error_buffer_size);
  1200. struct mg_client_options {
  1201. const char *host;
  1202. int port;
  1203. const char *client_cert;
  1204. const char *server_cert;
  1205. const char *host_name;
  1206. /* TODO: add more data */
  1207. };
  1208. CIVETWEB_API struct mg_connection *
  1209. mg_connect_client_secure(const struct mg_client_options *client_options,
  1210. char *error_buffer,
  1211. size_t error_buffer_size);
  1212. #if defined(MG_LEGACY_INTERFACE) /* 2019-11-02 */
  1213. enum { TIMEOUT_INFINITE = -1 };
  1214. #endif
  1215. enum { MG_TIMEOUT_INFINITE = -1 };
  1216. /* Wait for a response from the server
  1217. Parameters:
  1218. conn: connection
  1219. ebuf, ebuf_len: error message placeholder.
  1220. timeout: time to wait for a response in milliseconds (if < 0 then wait
  1221. forever)
  1222. Return:
  1223. On success, >= 0
  1224. On error/timeout, < 0
  1225. */
  1226. CIVETWEB_API int mg_get_response(struct mg_connection *conn,
  1227. char *ebuf,
  1228. size_t ebuf_len,
  1229. int timeout);
  1230. /* Check which features where set when the civetweb library has been compiled.
  1231. The function explicitly addresses compile time defines used when building
  1232. the library - it does not mean, the feature has been initialized using a
  1233. mg_init_library call.
  1234. mg_check_feature can be called anytime, even before mg_init_library has
  1235. been called.
  1236. Parameters:
  1237. feature: specifies which feature should be checked
  1238. The value is a bit mask. The individual bits are defined as:
  1239. 1 serve files (NO_FILES not set)
  1240. 2 support HTTPS (NO_SSL not set)
  1241. 4 support CGI (NO_CGI not set)
  1242. 8 support IPv6 (USE_IPV6 set)
  1243. 16 support WebSocket (USE_WEBSOCKET set)
  1244. 32 support Lua scripts and Lua server pages (USE_LUA is set)
  1245. 64 support server side JavaScript (USE_DUKTAPE is set)
  1246. 128 support caching (NO_CACHING not set)
  1247. 256 support server statistics (USE_SERVER_STATS is set)
  1248. 512 support for on the fly compression (USE_ZLIB is set)
  1249. These values are defined as MG_FEATURES_*
  1250. The result is undefined, if bits are set that do not represent a
  1251. defined feature (currently: feature >= 1024).
  1252. The result is undefined, if no bit is set (feature == 0).
  1253. Return:
  1254. If a feature is available, the corresponding bit is set
  1255. If a feature is not available, the bit is 0
  1256. */
  1257. CIVETWEB_API unsigned mg_check_feature(unsigned feature);
  1258. /* Get information on the system. Useful for support requests.
  1259. Parameters:
  1260. buffer: Store system information as string here.
  1261. buflen: Length of buffer (including a byte required for a terminating 0).
  1262. Return:
  1263. Available size of system information, exluding a terminating 0.
  1264. The information is complete, if the return value is smaller than buflen.
  1265. The result is a JSON formatted string, the exact content may vary.
  1266. Note:
  1267. It is possible to determine the required buflen, by first calling this
  1268. function with buffer = NULL and buflen = NULL. The required buflen is
  1269. one byte more than the returned value.
  1270. */
  1271. CIVETWEB_API int mg_get_system_info(char *buffer, int buflen);
  1272. /* Get context information. Useful for server diagnosis.
  1273. Parameters:
  1274. ctx: Context handle
  1275. buffer: Store context information here.
  1276. buflen: Length of buffer (including a byte required for a terminating 0).
  1277. Return:
  1278. Available size of system information, exluding a terminating 0.
  1279. The information is complete, if the return value is smaller than buflen.
  1280. The result is a JSON formatted string, the exact content may vary.
  1281. Note:
  1282. It is possible to determine the required buflen, by first calling this
  1283. function with buffer = NULL and buflen = NULL. The required buflen is
  1284. one byte more than the returned value. However, since the available
  1285. context information changes, you should allocate a few bytes more.
  1286. */
  1287. CIVETWEB_API int
  1288. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen);
  1289. #if defined(MG_EXPERIMENTAL_INTERFACES)
  1290. /* Get connection information. Useful for server diagnosis.
  1291. Parameters:
  1292. ctx: Context handle
  1293. idx: Connection index
  1294. buffer: Store context information here.
  1295. buflen: Length of buffer (including a byte required for a terminating 0).
  1296. Return:
  1297. Available size of system information, exluding a terminating 0.
  1298. The information is complete, if the return value is smaller than buflen.
  1299. The result is a JSON formatted string, the exact content may vary.
  1300. Note:
  1301. It is possible to determine the required buflen, by first calling this
  1302. function with buffer = NULL and buflen = NULL. The required buflen is
  1303. one byte more than the returned value. However, since the available
  1304. context information changes, you should allocate a few bytes more.
  1305. */
  1306. CIVETWEB_API int mg_get_connection_info(const struct mg_context *ctx,
  1307. int idx,
  1308. char *buffer,
  1309. int buflen);
  1310. #endif
  1311. /* New APIs for enhanced option and error handling.
  1312. These mg_*2 API functions have the same purpose as their original versions,
  1313. but provide additional options and/or provide improved error diagnostics.
  1314. Note: Experimental interfaces may change
  1315. */
  1316. struct mg_error_data {
  1317. unsigned *code; /* error code (number) */
  1318. char *text; /* buffer for error text */
  1319. size_t text_buffer_size; /* size of buffer of "text" */
  1320. };
  1321. struct mg_init_data {
  1322. const struct mg_callbacks *callbacks; /* callback function pointer */
  1323. void *user_data; /* data */
  1324. const char **configuration_options;
  1325. };
  1326. #if defined(MG_EXPERIMENTAL_INTERFACES)
  1327. CIVETWEB_API struct mg_connection *
  1328. mg_connect_client2(const char *host,
  1329. const char *protocol,
  1330. int port,
  1331. const char *path,
  1332. struct mg_init_data *init,
  1333. struct mg_error_data *error);
  1334. CIVETWEB_API int mg_get_response2(struct mg_connection *conn,
  1335. struct mg_error_data *error,
  1336. int timeout);
  1337. CIVETWEB_API struct mg_context *mg_start2(struct mg_init_data *init,
  1338. struct mg_error_data *error);
  1339. CIVETWEB_API int mg_start_domain2(struct mg_context *ctx,
  1340. const char **configuration_options,
  1341. struct mg_error_data *error);
  1342. #endif
  1343. #ifdef __cplusplus
  1344. }
  1345. #endif /* __cplusplus */
  1346. #endif /* CIVETWEB_HEADER_INCLUDED */