civetweb.h 42 KB

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