civetweb.h 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024
  1. /* Copyright (c) 2013-2016 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.9"
  25. #ifndef CIVETWEB_API
  26. #if defined(_WIN32)
  27. #if defined(CIVETWEB_DLL_EXPORTS)
  28. #define CIVETWEB_API __declspec(dllexport)
  29. #elif defined(CIVETWEB_DLL_IMPORTS)
  30. #define CIVETWEB_API __declspec(dllimport)
  31. #else
  32. #define CIVETWEB_API
  33. #endif
  34. #elif __GNUC__ >= 4
  35. #define CIVETWEB_API __attribute__((visibility("default")))
  36. #else
  37. #define CIVETWEB_API
  38. #endif
  39. #endif
  40. #include <stdio.h>
  41. #include <stddef.h>
  42. #ifdef __cplusplus
  43. extern "C" {
  44. #endif /* __cplusplus */
  45. struct mg_context; /* Handle for the HTTP service itself */
  46. struct mg_connection; /* Handle for the individual connection */
  47. /* This structure contains information about the HTTP request. */
  48. struct mg_request_info {
  49. const char *request_method; /* "GET", "POST", etc */
  50. const char *request_uri; /* URL-decoded URI (absolute or relative,
  51. * as in the request) */
  52. const char *local_uri; /* URL-decoded URI (relative). Can be NULL
  53. * if the request_uri does not address a
  54. * resource at the server host. */
  55. const char *uri; /* Deprecated: use local_uri instead */
  56. const char *http_version; /* E.g. "1.0", "1.1" */
  57. const char *query_string; /* URL part after '?', not including '?', or
  58. NULL */
  59. const char *remote_user; /* Authenticated user, or NULL if no auth
  60. used */
  61. char remote_addr[48]; /* Client's IP address as a string. */
  62. #if defined(MG_LEGACY_INTERFACE)
  63. long remote_ip; /* Client's IP address. Deprecated: use remote_addr instead
  64. */
  65. #endif
  66. long long content_length; /* Length (in bytes) of the request body,
  67. can be -1 if no length was given. */
  68. int remote_port; /* Client's port */
  69. int is_ssl; /* 1 if SSL-ed, 0 if not */
  70. void *user_data; /* User data pointer passed to mg_start() */
  71. void *conn_data; /* Connection-specific user data */
  72. int num_headers; /* Number of HTTP headers */
  73. struct mg_header {
  74. const char *name; /* HTTP header name */
  75. const char *value; /* HTTP header value */
  76. } http_headers[64]; /* Maximum 64 headers */
  77. };
  78. /* This structure needs to be passed to mg_start(), to let civetweb know
  79. which callbacks to invoke. For a detailed description, see
  80. https://github.com/civetweb/civetweb/blob/master/docs/UserManual.md */
  81. struct mg_callbacks {
  82. /* Called when civetweb has received new HTTP request.
  83. If the callback returns one, it must process the request
  84. by sending valid HTTP headers and a body. Civetweb will not do
  85. any further processing. Otherwise it must return zero.
  86. Note that since V1.7 the "begin_request" function is called
  87. before an authorization check. If an authorization check is
  88. required, use a request_handler instead.
  89. Return value:
  90. 0: civetweb will process the request itself. In this case,
  91. the callback must not send any data to the client.
  92. 1-999: callback already processed the request. Civetweb will
  93. not send any data after the callback returned. The
  94. return code is stored as a HTTP status code for the
  95. access log. */
  96. int (*begin_request)(struct mg_connection *);
  97. /* Called when civetweb has finished processing request. */
  98. void (*end_request)(const struct mg_connection *, int reply_status_code);
  99. /* Called when civetweb is about to log a message. If callback returns
  100. non-zero, civetweb does not log anything. */
  101. int (*log_message)(const struct mg_connection *, const char *message);
  102. /* Called when civetweb is about to log access. If callback returns
  103. non-zero, civetweb does not log anything. */
  104. int (*log_access)(const struct mg_connection *, const char *message);
  105. /* Called when civetweb initializes SSL library.
  106. Parameters:
  107. user_data: parameter user_data passed when starting the server.
  108. Return value:
  109. 0: civetweb will set up the SSL certificate.
  110. 1: civetweb assumes the callback already set up the certificate.
  111. -1: initializing ssl fails. */
  112. int (*init_ssl)(void *ssl_context, void *user_data);
  113. #if defined(MG_LEGACY_INTERFACE)
  114. /* Called when websocket request is received, before websocket handshake.
  115. Return value:
  116. 0: civetweb proceeds with websocket handshake.
  117. 1: connection is closed immediately.
  118. This callback is deprecated: Use mg_set_websocket_handler instead. */
  119. int (*websocket_connect)(const struct mg_connection *);
  120. /* Called when websocket handshake is successfully completed, and
  121. connection is ready for data exchange.
  122. This callback is deprecated: Use mg_set_websocket_handler instead. */
  123. void (*websocket_ready)(struct mg_connection *);
  124. /* Called when data frame has been received from the client.
  125. Parameters:
  126. bits: first byte of the websocket frame, see websocket RFC at
  127. http://tools.ietf.org/html/rfc6455, section 5.2
  128. data, data_len: payload, with mask (if any) already applied.
  129. Return value:
  130. 1: keep this websocket connection open.
  131. 0: close this websocket connection.
  132. This callback is deprecated: Use mg_set_websocket_handler instead. */
  133. int (*websocket_data)(struct mg_connection *,
  134. int bits,
  135. char *data,
  136. size_t data_len);
  137. #endif /* MG_LEGACY_INTERFACE */
  138. /* Called when civetweb is closing a connection. The per-context mutex is
  139. locked when this is invoked. This is primarily useful for noting when
  140. a websocket is closing and removing it from any application-maintained
  141. list of clients.
  142. Using this callback for websocket connections is deprecated: Use
  143. mg_set_websocket_handler instead. */
  144. void (*connection_close)(const struct mg_connection *);
  145. /* Called when civetweb tries to open a file. Used to intercept file open
  146. calls, and serve file data from memory instead.
  147. Parameters:
  148. path: Full path to the file to open.
  149. data_len: Placeholder for the file size, if file is served from
  150. memory.
  151. Return value:
  152. NULL: do not serve file from memory, proceed with normal file open.
  153. non-NULL: pointer to the file contents in memory. data_len must be
  154. initialized with the size of the memory block. */
  155. const char *(*open_file)(const struct mg_connection *,
  156. const char *path,
  157. size_t *data_len);
  158. /* Called when civetweb is about to serve Lua server page, if
  159. Lua support is enabled.
  160. Parameters:
  161. lua_context: "lua_State *" pointer. */
  162. void (*init_lua)(const struct mg_connection *, void *lua_context);
  163. #if defined(MG_LEGACY_INTERFACE)
  164. /* Called when civetweb has uploaded a file to a temporary directory as a
  165. result of mg_upload() call.
  166. Note that mg_upload is deprecated. Use mg_handle_form_request instead.
  167. Parameters:
  168. file_name: full path name to the uploaded file. */
  169. void (*upload)(struct mg_connection *, const char *file_name);
  170. #endif
  171. /* Called when civetweb is about to send HTTP error to the client.
  172. Implementing this callback allows to create custom error pages.
  173. Parameters:
  174. status: HTTP error status code.
  175. Return value:
  176. 1: run civetweb error handler.
  177. 0: callback already handled the error. */
  178. int (*http_error)(struct mg_connection *, int status);
  179. /* Called after civetweb context has been created, before requests
  180. are processed.
  181. Parameters:
  182. ctx: context handle */
  183. void (*init_context)(const struct mg_context *ctx);
  184. /* Called when a new worker thread is initialized.
  185. Parameters:
  186. ctx: context handle
  187. thread_type:
  188. 0 indicates the master thread
  189. 1 indicates a worker thread handling client connections
  190. 2 indicates an internal helper thread (timer thread)
  191. */
  192. void (*init_thread)(const struct mg_context *ctx, int thread_type);
  193. /* Called when civetweb context is deleted.
  194. Parameters:
  195. ctx: context handle */
  196. void (*exit_context)(const struct mg_context *ctx);
  197. };
  198. /* Start web server.
  199. Parameters:
  200. callbacks: mg_callbacks structure with user-defined callbacks.
  201. options: NULL terminated list of option_name, option_value pairs that
  202. specify Civetweb configuration parameters.
  203. Side-effects: on UNIX, ignores SIGCHLD and SIGPIPE signals. If custom
  204. processing is required for these, signal handlers must be set up
  205. after calling mg_start().
  206. Example:
  207. const char *options[] = {
  208. "document_root", "/var/www",
  209. "listening_ports", "80,443s",
  210. NULL
  211. };
  212. struct mg_context *ctx = mg_start(&my_func, NULL, options);
  213. Refer to https://github.com/civetweb/civetweb/blob/master/docs/UserManual.md
  214. for the list of valid option and their possible values.
  215. Return:
  216. web server context, or NULL on error. */
  217. CIVETWEB_API struct mg_context *mg_start(const struct mg_callbacks *callbacks,
  218. void *user_data,
  219. const char **configuration_options);
  220. /* Stop the web server.
  221. Must be called last, when an application wants to stop the web server and
  222. release all associated resources. This function blocks until all Civetweb
  223. threads are stopped. Context pointer becomes invalid. */
  224. CIVETWEB_API void mg_stop(struct mg_context *);
  225. /* mg_request_handler
  226. Called when a new request comes in. This callback is URI based
  227. and configured with mg_set_request_handler().
  228. Parameters:
  229. conn: current connection information.
  230. cbdata: the callback data configured with mg_set_request_handler().
  231. Returns:
  232. 0: the handler could not handle the request, so fall through.
  233. 1 - 999: the handler processed the request. The return code is
  234. stored as a HTTP status code for the access log. */
  235. typedef int (*mg_request_handler)(struct mg_connection *conn, void *cbdata);
  236. /* mg_set_request_handler
  237. Sets or removes a URI mapping for a request handler.
  238. This function uses mg_lock_context internally.
  239. URI's are ordered and prefixed URI's are supported. For example,
  240. consider two URIs: /a/b and /a
  241. /a matches /a
  242. /a/b matches /a/b
  243. /a/c matches /a
  244. Parameters:
  245. ctx: server context
  246. uri: the URI (exact or pattern) for the handler
  247. handler: the callback handler to use when the URI is requested.
  248. If NULL, an already registered handler for this URI will be
  249. removed.
  250. The URI used to remove a handler must match exactly the one used
  251. to
  252. register it (not only a pattern match).
  253. cbdata: the callback data to give to the handler when it is called. */
  254. CIVETWEB_API void mg_set_request_handler(struct mg_context *ctx,
  255. const char *uri,
  256. mg_request_handler handler,
  257. void *cbdata);
  258. /* Callback types for websocket handlers in C/C++.
  259. mg_websocket_connect_handler
  260. Is called when the client intends to establish a websocket connection,
  261. before websocket handshake.
  262. Return value:
  263. 0: civetweb proceeds with websocket handshake.
  264. 1: connection is closed immediately.
  265. mg_websocket_ready_handler
  266. Is called when websocket handshake is successfully completed, and
  267. connection is ready for data exchange.
  268. mg_websocket_data_handler
  269. Is called when a data frame has been received from the client.
  270. Parameters:
  271. bits: first byte of the websocket frame, see websocket RFC at
  272. http://tools.ietf.org/html/rfc6455, section 5.2
  273. data, data_len: payload, with mask (if any) already applied.
  274. Return value:
  275. 1: keep this websocket connection open.
  276. 0: close this websocket connection.
  277. mg_connection_close_handler
  278. Is called, when the connection is closed.*/
  279. typedef int (*mg_websocket_connect_handler)(const struct mg_connection *,
  280. void *);
  281. typedef void (*mg_websocket_ready_handler)(struct mg_connection *, void *);
  282. typedef int (*mg_websocket_data_handler)(struct mg_connection *,
  283. int,
  284. char *,
  285. size_t,
  286. void *);
  287. typedef void (*mg_websocket_close_handler)(const struct mg_connection *,
  288. void *);
  289. /* mg_set_websocket_handler
  290. Set or remove handler functions for websocket connections.
  291. This function works similar to mg_set_request_handler - see there. */
  292. CIVETWEB_API void
  293. mg_set_websocket_handler(struct mg_context *ctx,
  294. const char *uri,
  295. mg_websocket_connect_handler connect_handler,
  296. mg_websocket_ready_handler ready_handler,
  297. mg_websocket_data_handler data_handler,
  298. mg_websocket_close_handler close_handler,
  299. void *cbdata);
  300. /* mg_authorization_handler
  301. Some description here
  302. Parameters:
  303. conn: current connection information.
  304. cbdata: the callback data configured with mg_set_request_handler().
  305. Returns:
  306. 0: access denied
  307. 1: access granted
  308. */
  309. typedef int (*mg_authorization_handler)(struct mg_connection *conn,
  310. void *cbdata);
  311. /* mg_set_auth_handler
  312. Sets or removes a URI mapping for an authorization handler.
  313. This function works similar to mg_set_request_handler - see there. */
  314. CIVETWEB_API void mg_set_auth_handler(struct mg_context *ctx,
  315. const char *uri,
  316. mg_authorization_handler handler,
  317. void *cbdata);
  318. /* Get the value of particular configuration parameter.
  319. The value returned is read-only. Civetweb does not allow changing
  320. configuration at run time.
  321. If given parameter name is not valid, NULL is returned. For valid
  322. names, return value is guaranteed to be non-NULL. If parameter is not
  323. set, zero-length string is returned. */
  324. CIVETWEB_API const char *mg_get_option(const struct mg_context *ctx,
  325. const char *name);
  326. /* Get context from connection. */
  327. CIVETWEB_API struct mg_context *
  328. mg_get_context(const struct mg_connection *conn);
  329. /* Get user data passed to mg_start from context. */
  330. CIVETWEB_API void *mg_get_user_data(const struct mg_context *ctx);
  331. /* Set user data for the current connection. */
  332. CIVETWEB_API void mg_set_user_connection_data(struct mg_connection *conn,
  333. void *data);
  334. /* Get user data set for the current connection. */
  335. CIVETWEB_API void *
  336. mg_get_user_connection_data(const struct mg_connection *conn);
  337. #if defined(MG_LEGACY_INTERFACE)
  338. /* Return array of strings that represent valid configuration options.
  339. For each option, option name and default value is returned, i.e. the
  340. number of entries in the array equals to number_of_options x 2.
  341. Array is NULL terminated. */
  342. /* Deprecated: Use mg_get_valid_options instead. */
  343. CIVETWEB_API const char **mg_get_valid_option_names(void);
  344. #endif
  345. struct mg_option {
  346. const char *name;
  347. int type;
  348. const char *default_value;
  349. };
  350. enum {
  351. CONFIG_TYPE_UNKNOWN = 0x0,
  352. CONFIG_TYPE_NUMBER = 0x1,
  353. CONFIG_TYPE_STRING = 0x2,
  354. CONFIG_TYPE_FILE = 0x3,
  355. CONFIG_TYPE_DIRECTORY = 0x4,
  356. CONFIG_TYPE_BOOLEAN = 0x5,
  357. CONFIG_TYPE_EXT_PATTERN = 0x6
  358. };
  359. /* Return array of struct mg_option, representing all valid configuration
  360. options of civetweb.c.
  361. The array is terminated by a NULL name option. */
  362. CIVETWEB_API const struct mg_option *mg_get_valid_options(void);
  363. struct mg_server_ports {
  364. int protocol; /* 1 = IPv4, 2 = IPv6, 3 = both */
  365. int port; /* port number */
  366. int is_ssl; /* https port: 0 = no, 1 = yes */
  367. int is_redirect; /* redirect all requests: 0 = no, 1 = yes */
  368. int _reserved1;
  369. int _reserved2;
  370. int _reserved3;
  371. int _reserved4;
  372. };
  373. /* Get the list of ports that civetweb is listening on.
  374. The parameter size is the size of the ports array in elements.
  375. The caller is responsibility to allocate the required memory.
  376. This function returns the number of struct mg_server_ports elements
  377. filled in, or <0 in case of an error. */
  378. CIVETWEB_API int mg_get_server_ports(const struct mg_context *ctx,
  379. int size,
  380. struct mg_server_ports *ports);
  381. /* Deprecated: Use mg_get_server_ports instead. */
  382. CIVETWEB_API size_t
  383. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl);
  384. /* Add, edit or delete the entry in the passwords file.
  385. This function allows an application to manipulate .htpasswd files on the
  386. fly by adding, deleting and changing user records. This is one of the
  387. several ways of implementing authentication on the server side. For another,
  388. cookie-based way please refer to the examples/chat in the source tree.
  389. If password is not NULL, entry is added (or modified if already exists).
  390. If password is NULL, entry is deleted.
  391. Return:
  392. 1 on success, 0 on error. */
  393. CIVETWEB_API int mg_modify_passwords_file(const char *passwords_file_name,
  394. const char *domain,
  395. const char *user,
  396. const char *password);
  397. /* Return information associated with the request. */
  398. CIVETWEB_API const struct mg_request_info *
  399. mg_get_request_info(const struct mg_connection *);
  400. /* Send data to the client.
  401. Return:
  402. 0 when the connection has been closed
  403. -1 on error
  404. >0 number of bytes written on success */
  405. CIVETWEB_API int mg_write(struct mg_connection *, const void *buf, size_t len);
  406. /* Send data to a websocket client wrapped in a websocket frame. Uses
  407. mg_lock_connection to ensure that the transmission is not interrupted,
  408. i.e., when the application is proactively communicating and responding to
  409. a request simultaneously.
  410. Send data to a websocket client wrapped in a websocket frame.
  411. This function is available when civetweb is compiled with -DUSE_WEBSOCKET
  412. Return:
  413. 0 when the connection has been closed
  414. -1 on error
  415. >0 number of bytes written on success */
  416. CIVETWEB_API int mg_websocket_write(struct mg_connection *conn,
  417. int opcode,
  418. const char *data,
  419. size_t data_len);
  420. /* Send data to a websocket server wrapped in a masked websocket frame. Uses
  421. mg_lock_connection to ensure that the transmission is not interrupted,
  422. i.e., when the application is proactively communicating and responding to
  423. a request simultaneously.
  424. Send data to a websocket server wrapped in a masked websocket frame.
  425. This function is available when civetweb is compiled with -DUSE_WEBSOCKET
  426. Return:
  427. 0 when the connection has been closed
  428. -1 on error
  429. >0 number of bytes written on success */
  430. CIVETWEB_API int mg_websocket_client_write(struct mg_connection *conn,
  431. int opcode,
  432. const char *data,
  433. size_t data_len);
  434. /* Blocks until unique access is obtained to this connection. Intended for use
  435. with websockets only.
  436. Invoke this before mg_write or mg_printf when communicating with a
  437. websocket if your code has server-initiated communication as well as
  438. communication in direct response to a message. */
  439. CIVETWEB_API void mg_lock_connection(struct mg_connection *conn);
  440. CIVETWEB_API void mg_unlock_connection(struct mg_connection *conn);
  441. #if defined(MG_LEGACY_INTERFACE)
  442. #define mg_lock mg_lock_connection
  443. #define mg_unlock mg_unlock_connection
  444. #endif
  445. /* Lock server context. This lock may be used to protect resources
  446. that are shared between different connection/worker threads. */
  447. CIVETWEB_API void mg_lock_context(struct mg_context *ctx);
  448. CIVETWEB_API void mg_unlock_context(struct mg_context *ctx);
  449. /* Opcodes, from http://tools.ietf.org/html/rfc6455 */
  450. enum {
  451. WEBSOCKET_OPCODE_CONTINUATION = 0x0,
  452. WEBSOCKET_OPCODE_TEXT = 0x1,
  453. WEBSOCKET_OPCODE_BINARY = 0x2,
  454. WEBSOCKET_OPCODE_CONNECTION_CLOSE = 0x8,
  455. WEBSOCKET_OPCODE_PING = 0x9,
  456. WEBSOCKET_OPCODE_PONG = 0xa
  457. };
  458. /* Macros for enabling compiler-specific checks for printf-like arguments. */
  459. #undef PRINTF_FORMAT_STRING
  460. #if defined(_MSC_VER) && _MSC_VER >= 1400
  461. #include <sal.h>
  462. #if defined(_MSC_VER) && _MSC_VER > 1400
  463. #define PRINTF_FORMAT_STRING(s) _Printf_format_string_ s
  464. #else
  465. #define PRINTF_FORMAT_STRING(s) __format_string s
  466. #endif
  467. #else
  468. #define PRINTF_FORMAT_STRING(s) s
  469. #endif
  470. #ifdef __GNUC__
  471. #define PRINTF_ARGS(x, y) __attribute__((format(printf, x, y)))
  472. #else
  473. #define PRINTF_ARGS(x, y)
  474. #endif
  475. /* Send data to the client using printf() semantics.
  476. Works exactly like mg_write(), but allows to do message formatting. */
  477. CIVETWEB_API int mg_printf(struct mg_connection *,
  478. PRINTF_FORMAT_STRING(const char *fmt),
  479. ...) PRINTF_ARGS(2, 3);
  480. /* Send contents of the entire file together with HTTP headers. */
  481. CIVETWEB_API void mg_send_file(struct mg_connection *conn, const char *path);
  482. /* Send contents of the entire file together with HTTP headers.
  483. Parameters:
  484. conn: Current connection information.
  485. path: Full path to the file to send.
  486. mime_type: Content-Type for file. NULL will cause the type to be
  487. looked up by the file extension.
  488. */
  489. CIVETWEB_API void mg_send_mime_file(struct mg_connection *conn,
  490. const char *path,
  491. const char *mime_type);
  492. /* Store body data into a file. */
  493. CIVETWEB_API long long mg_store_body(struct mg_connection *conn,
  494. const char *path);
  495. /* Read entire request body and store it in a file "path".
  496. Return:
  497. < 0 Error
  498. >= 0 Number of bytes stored in file "path".
  499. */
  500. /* Read data from the remote end, return number of bytes read.
  501. Return:
  502. 0 connection has been closed by peer. No more data could be read.
  503. < 0 read error. No more data could be read from the connection.
  504. > 0 number of bytes read into the buffer. */
  505. CIVETWEB_API int mg_read(struct mg_connection *, void *buf, size_t len);
  506. /* Get the value of particular HTTP header.
  507. This is a helper function. It traverses request_info->http_headers array,
  508. and if the header is present in the array, returns its value. If it is
  509. not present, NULL is returned. */
  510. CIVETWEB_API const char *mg_get_header(const struct mg_connection *,
  511. const char *name);
  512. /* Get a value of particular form variable.
  513. Parameters:
  514. data: pointer to form-uri-encoded buffer. This could be either POST data,
  515. or request_info.query_string.
  516. data_len: length of the encoded data.
  517. var_name: variable name to decode from the buffer
  518. dst: destination buffer for the decoded variable
  519. dst_len: length of the destination buffer
  520. Return:
  521. On success, length of the decoded variable.
  522. On error:
  523. -1 (variable not found).
  524. -2 (destination buffer is NULL, zero length or too small to hold the
  525. decoded variable).
  526. Destination buffer is guaranteed to be '\0' - terminated if it is not
  527. NULL or zero length. */
  528. CIVETWEB_API int mg_get_var(const char *data,
  529. size_t data_len,
  530. const char *var_name,
  531. char *dst,
  532. size_t dst_len);
  533. /* Get a value of particular form variable.
  534. Parameters:
  535. data: pointer to form-uri-encoded buffer. This could be either POST data,
  536. or request_info.query_string.
  537. data_len: length of the encoded data.
  538. var_name: variable name to decode from the buffer
  539. dst: destination buffer for the decoded variable
  540. dst_len: length of the destination buffer
  541. occurrence: which occurrence of the variable, 0 is the first, 1 the
  542. second...
  543. this makes it possible to parse a query like
  544. b=x&a=y&a=z which will have occurrence values b:0, a:0 and a:1
  545. Return:
  546. On success, length of the decoded variable.
  547. On error:
  548. -1 (variable not found).
  549. -2 (destination buffer is NULL, zero length or too small to hold the
  550. decoded variable).
  551. Destination buffer is guaranteed to be '\0' - terminated if it is not
  552. NULL or zero length. */
  553. CIVETWEB_API int mg_get_var2(const char *data,
  554. size_t data_len,
  555. const char *var_name,
  556. char *dst,
  557. size_t dst_len,
  558. size_t occurrence);
  559. /* Fetch value of certain cookie variable into the destination buffer.
  560. Destination buffer is guaranteed to be '\0' - terminated. In case of
  561. failure, dst[0] == '\0'. Note that RFC allows many occurrences of the same
  562. parameter. This function returns only first occurrence.
  563. Return:
  564. On success, value length.
  565. On error:
  566. -1 (either "Cookie:" header is not present at all or the requested
  567. parameter is not found).
  568. -2 (destination buffer is NULL, zero length or too small to hold the
  569. value). */
  570. CIVETWEB_API int mg_get_cookie(const char *cookie,
  571. const char *var_name,
  572. char *buf,
  573. size_t buf_len);
  574. /* Download data from the remote web server.
  575. host: host name to connect to, e.g. "foo.com", or "10.12.40.1".
  576. port: port number, e.g. 80.
  577. use_ssl: wether to use SSL connection.
  578. error_buffer, error_buffer_size: error message placeholder.
  579. request_fmt,...: HTTP request.
  580. Return:
  581. On success, valid pointer to the new connection, suitable for mg_read().
  582. On error, NULL. error_buffer contains error message.
  583. Example:
  584. char ebuf[100];
  585. struct mg_connection *conn;
  586. conn = mg_download("google.com", 80, 0, ebuf, sizeof(ebuf),
  587. "%s", "GET / HTTP/1.0\r\nHost: google.com\r\n\r\n");
  588. */
  589. CIVETWEB_API struct mg_connection *
  590. mg_download(const char *host,
  591. int port,
  592. int use_ssl,
  593. char *error_buffer,
  594. size_t error_buffer_size,
  595. PRINTF_FORMAT_STRING(const char *request_fmt),
  596. ...) PRINTF_ARGS(6, 7);
  597. /* Close the connection opened by mg_download(). */
  598. CIVETWEB_API void mg_close_connection(struct mg_connection *conn);
  599. #if defined(MG_LEGACY_INTERFACE)
  600. /* File upload functionality. Each uploaded file gets saved into a temporary
  601. file and MG_UPLOAD event is sent.
  602. Return number of uploaded files.
  603. Deprecated: Use mg_handle_form_request instead. */
  604. CIVETWEB_API int mg_upload(struct mg_connection *conn,
  605. const char *destination_dir);
  606. #endif
  607. /* This structure contains callback functions for handling form fields.
  608. It is used as an argument to mg_handle_form_request. */
  609. struct mg_form_data_handler {
  610. /* This callback function is called, if a new field has been found.
  611. * The return value of this callback is used to define how the field
  612. * should be processed.
  613. *
  614. * Parameters:
  615. * key: Name of the field ("name" property of the HTML input field).
  616. * filename: Name of a file to upload, at the client computer.
  617. * Only set for input fields of type "file", otherwise NULL.
  618. * path: Output parameter: File name (incl. path) to store the file
  619. * at the server computer. Only used if FORM_FIELD_STORAGE_STORE
  620. * is returned by this callback. Existing files will be
  621. * overwritten.
  622. * pathlen: Length of the buffer for path.
  623. * user_data: Value of the member user_data of mg_form_data_handler
  624. *
  625. * Return value:
  626. * The callback must return the intended storage for this field
  627. * (See FORM_FIELD_STORAGE_*).
  628. */
  629. int (*field_found)(const char *key,
  630. const char *filename,
  631. char *path,
  632. size_t pathlen,
  633. void *user_data);
  634. /* If the "field_found" callback returned FORM_FIELD_STORAGE_GET,
  635. * this callback will receive the field data.
  636. *
  637. * Parameters:
  638. * key: Name of the field ("name" property of the HTML input field).
  639. * value: Value of the input field.
  640. * user_data: Value of the member user_data of mg_form_data_handler
  641. *
  642. * Return value:
  643. * TODO: Needs to be defined.
  644. */
  645. int (*field_get)(const char *key,
  646. const char *value,
  647. size_t valuelen,
  648. void *user_data);
  649. /* If the "field_found" callback returned FORM_FIELD_STORAGE_STORE,
  650. * the data will be stored into a file. If the file has been written
  651. * successfully, this callback will be called. This callback will
  652. * not be called for only partially uploaded files. The
  653. * mg_handle_form_request function will either store the file completely
  654. * and call this callback, or it will remove any partial content and
  655. * not call this callback function.
  656. *
  657. * Parameters:
  658. * path: Path of the file stored at the server.
  659. * file_size: Size of the stored file in bytes.
  660. * user_data: Value of the member user_data of mg_form_data_handler
  661. *
  662. * Return value:
  663. * TODO: Needs to be defined.
  664. */
  665. int (*field_store)(const char *path, long long file_size, void *user_data);
  666. /* User supplied argument, passed to all callback functions. */
  667. void *user_data;
  668. };
  669. /* Return values definition for the "field_found" callback in
  670. * mg_form_data_handler. */
  671. enum {
  672. /* Skip this field (neither get nor store it). Continue with the
  673. * next field. */
  674. FORM_FIELD_STORAGE_SKIP = 0x0,
  675. /* Get the field value. */
  676. FORM_FIELD_STORAGE_GET = 0x1,
  677. /* Store the field value into a file. */
  678. FORM_FIELD_STORAGE_STORE = 0x2,
  679. /* Stop parsing this request. Skip the remaining fields. */
  680. FORM_FIELD_STORAGE_ABORT = 0x10
  681. };
  682. /* Process form data.
  683. * Returns the number of fields handled, or < 0 in case of an error.
  684. * Note: It is possible that several fields are already handled successfully
  685. * (e.g., stored into files), before the request handling is stopped with an
  686. * error. In this case a number < 0 is returned as well.
  687. * In any case, it is the duty of the caller to remove files once they are
  688. * no longer required. */
  689. CIVETWEB_API int mg_handle_form_request(struct mg_connection *conn,
  690. struct mg_form_data_handler *fdh);
  691. /* Convenience function -- create detached thread.
  692. Return: 0 on success, non-0 on error. */
  693. typedef void *(*mg_thread_func_t)(void *);
  694. CIVETWEB_API int mg_start_thread(mg_thread_func_t f, void *p);
  695. /* Return builtin mime type for the given file name.
  696. For unrecognized extensions, "text/plain" is returned. */
  697. CIVETWEB_API const char *mg_get_builtin_mime_type(const char *file_name);
  698. /* Get text representation of HTTP status code. */
  699. CIVETWEB_API const char *mg_get_response_code_text(struct mg_connection *conn,
  700. int response_code);
  701. /* Return CivetWeb version. */
  702. CIVETWEB_API const char *mg_version(void);
  703. /* URL-decode input buffer into destination buffer.
  704. 0-terminate the destination buffer.
  705. form-url-encoded data differs from URI encoding in a way that it
  706. uses '+' as character for space, see RFC 1866 section 8.2.1
  707. http://ftp.ics.uci.edu/pub/ietf/html/rfc1866.txt
  708. Return: length of the decoded data, or -1 if dst buffer is too small. */
  709. CIVETWEB_API int mg_url_decode(const char *src,
  710. int src_len,
  711. char *dst,
  712. int dst_len,
  713. int is_form_url_encoded);
  714. /* URL-encode input buffer into destination buffer.
  715. returns the length of the resulting buffer or -1
  716. is the buffer is too small. */
  717. CIVETWEB_API int mg_url_encode(const char *src, char *dst, size_t dst_len);
  718. /* MD5 hash given strings.
  719. Buffer 'buf' must be 33 bytes long. Varargs is a NULL terminated list of
  720. ASCIIz strings. When function returns, buf will contain human-readable
  721. MD5 hash. Example:
  722. char buf[33];
  723. mg_md5(buf, "aa", "bb", NULL); */
  724. CIVETWEB_API char *mg_md5(char buf[33], ...);
  725. /* Print error message to the opened error log stream.
  726. This utilizes the provided logging configuration.
  727. conn: connection
  728. fmt: format string without the line return
  729. ...: variable argument list
  730. Example:
  731. mg_cry(conn,"i like %s", "logging"); */
  732. CIVETWEB_API void mg_cry(const struct mg_connection *conn,
  733. PRINTF_FORMAT_STRING(const char *fmt),
  734. ...) PRINTF_ARGS(2, 3);
  735. /* utility methods to compare two buffers, case insensitive. */
  736. CIVETWEB_API int mg_strcasecmp(const char *s1, const char *s2);
  737. CIVETWEB_API int mg_strncasecmp(const char *s1, const char *s2, size_t len);
  738. /* Connect to a websocket as a client
  739. Parameters:
  740. host: host to connect to, i.e. "echo.websocket.org" or "192.168.1.1" or
  741. "localhost"
  742. port: server port
  743. use_ssl: make a secure connection to server
  744. error_buffer, error_buffer_size: buffer for an error message
  745. path: server path you are trying to connect to, i.e. if connection to
  746. localhost/app, path should be "/app"
  747. origin: value of the Origin HTTP header
  748. data_func: callback that should be used when data is received from the
  749. server
  750. user_data: user supplied argument
  751. Return:
  752. On success, valid mg_connection object.
  753. On error, NULL. Se error_buffer for details.
  754. */
  755. CIVETWEB_API struct mg_connection *
  756. mg_connect_websocket_client(const char *host,
  757. int port,
  758. int use_ssl,
  759. char *error_buffer,
  760. size_t error_buffer_size,
  761. const char *path,
  762. const char *origin,
  763. mg_websocket_data_handler data_func,
  764. mg_websocket_close_handler close_func,
  765. void *user_data);
  766. /* Connect to a TCP server as a client (can be used to connect to a HTTP server)
  767. Parameters:
  768. host: host to connect to, i.e. "www.wikipedia.org" or "192.168.1.1" or
  769. "localhost"
  770. port: server port
  771. use_ssl: make a secure connection to server
  772. error_buffer, error_buffer_size: buffer for an error message
  773. Return:
  774. On success, valid mg_connection object.
  775. On error, NULL. Se error_buffer for details.
  776. */
  777. CIVETWEB_API struct mg_connection *mg_connect_client(const char *host,
  778. int port,
  779. int use_ssl,
  780. char *error_buffer,
  781. size_t error_buffer_size);
  782. struct mg_client_options {
  783. const char *host;
  784. int port;
  785. const char *client_cert;
  786. const char *server_cert;
  787. /* TODO: add more data */
  788. };
  789. CIVETWEB_API struct mg_connection *
  790. mg_connect_client_secure(const struct mg_client_options *client_options,
  791. char *error_buffer,
  792. size_t error_buffer_size);
  793. enum { TIMEOUT_INFINITE = -1 };
  794. /* Wait for a response from the server
  795. Parameters:
  796. conn: connection
  797. ebuf, ebuf_len: error message placeholder.
  798. timeout: time to wait for a response in milliseconds (if < 0 then wait
  799. forever)
  800. Return:
  801. On success, >= 0
  802. On error/timeout, < 0
  803. */
  804. CIVETWEB_API int mg_get_response(struct mg_connection *conn,
  805. char *ebuf,
  806. size_t ebuf_len,
  807. int timeout);
  808. /* Check which features where set when civetweb has been compiled.
  809. Parameters:
  810. feature: specifies which feature should be checked
  811. 1 serve files (NO_FILES not set)
  812. 2 support HTTPS (NO_SSL not set)
  813. 4 support CGI (NO_CGI not set)
  814. 8 support IPv6 (USE_IPV6 set)
  815. 16 support WebSocket (USE_WEBSOCKET set)
  816. 32 support Lua scripts and Lua server pages (USE_LUA is set)
  817. 64 support server side JavaScript (USE_DUKTAPE is set)
  818. 128 support caching (NO_CACHING not set)
  819. The result is undefined for all other feature values.
  820. Return:
  821. If feature is available > 0
  822. If feature is not available = 0
  823. */
  824. CIVETWEB_API unsigned mg_check_feature(unsigned feature);
  825. #ifdef __cplusplus
  826. }
  827. #endif /* __cplusplus */
  828. #endif /* CIVETWEB_HEADER_INCLUDED */