civetweb.h 65 KB

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