mongoose.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. // Copyright (c) 2004-2012 Sergey Lyubka
  2. //
  3. // Permission is hereby granted, free of charge, to any person obtaining a copy
  4. // of this software and associated documentation files (the "Software"), to deal
  5. // in the Software without restriction, including without limitation the rights
  6. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7. // copies of the Software, and to permit persons to whom the Software is
  8. // furnished to do so, subject to the following conditions:
  9. //
  10. // The above copyright notice and this permission notice shall be included in
  11. // all copies or substantial portions of the Software.
  12. //
  13. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19. // THE SOFTWARE.
  20. #ifndef MONGOOSE_HEADER_INCLUDED
  21. #define MONGOOSE_HEADER_INCLUDED
  22. #include <stdio.h>
  23. #include <stddef.h>
  24. #ifdef __cplusplus
  25. extern "C" {
  26. #endif // __cplusplus
  27. struct mg_context; // Handle for the HTTP service itself
  28. struct mg_connection; // Handle for the individual connection
  29. // This structure contains information about the HTTP request.
  30. struct mg_request_info {
  31. const char *request_method; // "GET", "POST", etc
  32. const char *uri; // URL-decoded URI
  33. const char *http_version; // E.g. "1.0", "1.1"
  34. const char *query_string; // URL part after '?', not including '?', or NULL
  35. const char *remote_user; // Authenticated user, or NULL if no auth used
  36. long remote_ip; // Client's IP address
  37. int remote_port; // Client's port
  38. int is_ssl; // 1 if SSL-ed, 0 if not
  39. int num_headers; // Number of headers
  40. struct mg_header {
  41. const char *name; // HTTP header name
  42. const char *value; // HTTP header value
  43. } http_headers[64]; // Maximum 64 headers
  44. void *user_data; // User data pointer passed to mg_start()
  45. void *ev_data; // Event-specific data pointer
  46. };
  47. // This structure needs to be passed to mg_start(), to let mongoose know
  48. // which callbacks to invoke. For detailed description, see
  49. // https://github.com/valenok/mongoose/blob/master/UserManual.md
  50. struct mg_callbacks {
  51. int (*request_start)(struct mg_connection *);
  52. void (*request_done)(struct mg_connection *, int reply_status_code);
  53. int (*log_message)(struct mg_connection *, const char *message);
  54. int (*init_ssl)(void *ssl_context);
  55. void (*websocket_connect)(struct mg_connection *);
  56. void (*websocket_ready)(struct mg_connection *);
  57. int (*websocket_data)(struct mg_connection *);
  58. void (*websocket_close)(struct mg_connection *);
  59. void (*open_file)(struct mg_connection *, char **data, size_t *data_len);
  60. void (*init_lua)(struct mg_connection *, void *lua_context);
  61. void (*upload)(struct mg_connection *, const char *file_name);
  62. };
  63. // Various events on which user-defined callback function is called by Mongoose.
  64. enum mg_event {
  65. // New HTTP request has arrived from the client.
  66. // If callback returns non-NULL, Mongoose stops handling current request.
  67. // ev_data contains NULL.
  68. MG_NEW_REQUEST,
  69. // Mongoose has finished handling the request.
  70. // Callback return value is ignored.
  71. // ev_data contains integer HTTP status code:
  72. // int http_reply_status_code = (long) request_info->ev_data;
  73. MG_REQUEST_COMPLETE,
  74. // HTTP error must be returned to the client.
  75. // If callback returns non-NULL, Mongoose stops handling error.
  76. // ev_data contains HTTP error code:
  77. // int http_reply_status_code = (long) request_info->ev_data;
  78. MG_HTTP_ERROR,
  79. // Mongoose logs a message.
  80. // If callback returns non-NULL, Mongoose stops handling that event.
  81. // ev_data contains a message to be logged:
  82. // const char *log_message = request_info->ev_data;
  83. MG_EVENT_LOG,
  84. // SSL initialization, sent before certificate setup.
  85. // If callback returns non-NULL, Mongoose does not set up certificates.
  86. // ev_data contains server's OpenSSL context:
  87. // SSL_CTX *ssl_context = request_info->ev_data;
  88. MG_INIT_SSL,
  89. // Sent on HTTP connect, before websocket handshake.
  90. // If user callback returns NULL, then mongoose proceeds
  91. // with handshake, otherwise it closes the connection.
  92. // ev_data contains NULL.
  93. MG_WEBSOCKET_CONNECT,
  94. // Handshake has been successfully completed.
  95. // Callback's return value is ignored.
  96. // ev_data contains NULL.
  97. MG_WEBSOCKET_READY,
  98. // Incoming message from the client, data could be read with mg_read().
  99. // If user callback returns non-NULL, mongoose closes the websocket.
  100. // ev_data contains NULL.
  101. MG_WEBSOCKET_MESSAGE,
  102. // Client has closed the connection.
  103. // Callback's return value is ignored.
  104. // ev_data contains NULL.
  105. MG_WEBSOCKET_CLOSE,
  106. // Mongoose tries to open file.
  107. // If callback returns non-NULL, Mongoose will not try to open it, but
  108. // will use the returned value as a pointer to the file data. This allows
  109. // for example to serve files from memory.
  110. // ev_data contains file path, including document root path.
  111. // Upon return, ev_data should return file size, which should be a long int.
  112. //
  113. // const char *file_name = request_info->ev_data;
  114. // if (strcmp(file_name, "foo.txt") == 0) {
  115. // request_info->ev_data = (void *) (long) 4;
  116. // return "data";
  117. // }
  118. // return NULL;
  119. //
  120. // Note that this even is sent multiple times during one request. Each
  121. // time mongoose tries to open or stat the file, this event is sent, e.g.
  122. // for opening .htpasswd file, stat-ting requested file, opening requested
  123. // file, etc.
  124. MG_OPEN_FILE,
  125. // Mongoose initializes Lua server page. Sent only if Lua support is enabled.
  126. // Callback's return value is ignored.
  127. // ev_data contains lua_State pointer.
  128. MG_INIT_LUA,
  129. // Mongoose has uploaded file to a temporary directory.
  130. // Callback's return value is ignored.
  131. // ev_data contains NUL-terminated file name.
  132. MG_UPLOAD,
  133. };
  134. // Prototype for the user-defined function. Mongoose calls this function
  135. // on every MG_* event.
  136. //
  137. // Parameters:
  138. // event: which event has been triggered.
  139. // conn: opaque connection handler. Could be used to read, write data to the
  140. // client, etc. See functions below that have "mg_connection *" arg.
  141. //
  142. // Return:
  143. // If handler returns non-NULL, that means that handler has processed the
  144. // request by sending appropriate HTTP reply to the client. Mongoose treats
  145. // the request as served.
  146. // If handler returns NULL, that means that handler has not processed
  147. // the request. Handler must not send any data to the client in this case.
  148. // Mongoose proceeds with request handling as if nothing happened.
  149. typedef void *(*mg_callback_t)(enum mg_event event, struct mg_connection *conn);
  150. // Start web server.
  151. //
  152. // Parameters:
  153. // callback: user defined event handling function or NULL.
  154. // options: NULL terminated list of option_name, option_value pairs that
  155. // specify Mongoose configuration parameters.
  156. //
  157. // Side-effects: on UNIX, ignores SIGCHLD and SIGPIPE signals. If custom
  158. // processing is required for these, signal handlers must be set up
  159. // after calling mg_start().
  160. //
  161. //
  162. // Example:
  163. // const char *options[] = {
  164. // "document_root", "/var/www",
  165. // "listening_ports", "80,443s",
  166. // NULL
  167. // };
  168. // struct mg_context *ctx = mg_start(&my_func, NULL, options);
  169. //
  170. // Please refer to http://code.google.com/p/mongoose/wiki/MongooseManual
  171. // for the list of valid option and their possible values.
  172. //
  173. // Return:
  174. // web server context, or NULL on error.
  175. struct mg_context *mg_start(mg_callback_t callback, void *user_data,
  176. const char **options);
  177. // Stop the web server.
  178. //
  179. // Must be called last, when an application wants to stop the web server and
  180. // release all associated resources. This function blocks until all Mongoose
  181. // threads are stopped. Context pointer becomes invalid.
  182. void mg_stop(struct mg_context *);
  183. // Get the value of particular configuration parameter.
  184. // The value returned is read-only. Mongoose does not allow changing
  185. // configuration at run time.
  186. // If given parameter name is not valid, NULL is returned. For valid
  187. // names, return value is guaranteed to be non-NULL. If parameter is not
  188. // set, zero-length string is returned.
  189. const char *mg_get_option(const struct mg_context *ctx, const char *name);
  190. // Return array of strings that represent valid configuration options.
  191. // For each option, a short name, long name, and default value is returned.
  192. // Array is NULL terminated.
  193. const char **mg_get_valid_option_names(void);
  194. // Add, edit or delete the entry in the passwords file.
  195. //
  196. // This function allows an application to manipulate .htpasswd files on the
  197. // fly by adding, deleting and changing user records. This is one of the
  198. // several ways of implementing authentication on the server side. For another,
  199. // cookie-based way please refer to the examples/chat.c in the source tree.
  200. //
  201. // If password is not NULL, entry is added (or modified if already exists).
  202. // If password is NULL, entry is deleted.
  203. //
  204. // Return:
  205. // 1 on success, 0 on error.
  206. int mg_modify_passwords_file(const char *passwords_file_name,
  207. const char *domain,
  208. const char *user,
  209. const char *password);
  210. // Return information associated with the request.
  211. struct mg_request_info *mg_get_request_info(struct mg_connection *);
  212. // Send data to the client.
  213. // Return:
  214. // 0 when the connection has been closed
  215. // -1 on error
  216. // number of bytes written on success
  217. int mg_write(struct mg_connection *, const void *buf, size_t len);
  218. #undef PRINTF_FORMAT_STRING
  219. #if _MSC_VER >= 1400
  220. #include <sal.h>
  221. #if _MSC_VER > 1400
  222. #define PRINTF_FORMAT_STRING(s) _Printf_format_string_ s
  223. #else
  224. #define PRINTF_FORMAT_STRING(s) __format_string s
  225. #endif
  226. #else
  227. #define PRINTF_FORMAT_STRING(s) s
  228. #endif
  229. #ifdef __GNUC__
  230. #define PRINTF_ARGS(x, y) __attribute__((format(printf, x, y)))
  231. #else
  232. #define PRINTF_ARGS(x, y)
  233. #endif
  234. // Send data to the browser using printf() semantics.
  235. //
  236. // Works exactly like mg_write(), but allows to do message formatting.
  237. // Below are the macros for enabling compiler-specific checks for
  238. // printf-like arguments.
  239. int mg_printf(struct mg_connection *,
  240. PRINTF_FORMAT_STRING(const char *fmt), ...) PRINTF_ARGS(2, 3);
  241. // Send contents of the entire file together with HTTP headers.
  242. void mg_send_file(struct mg_connection *conn, const char *path);
  243. // Read data from the remote end, return number of bytes read.
  244. int mg_read(struct mg_connection *, void *buf, size_t len);
  245. // Get the value of particular HTTP header.
  246. //
  247. // This is a helper function. It traverses request_info->http_headers array,
  248. // and if the header is present in the array, returns its value. If it is
  249. // not present, NULL is returned.
  250. const char *mg_get_header(const struct mg_connection *, const char *name);
  251. // Get a value of particular form variable.
  252. //
  253. // Parameters:
  254. // data: pointer to form-uri-encoded buffer. This could be either POST data,
  255. // or request_info.query_string.
  256. // data_len: length of the encoded data.
  257. // var_name: variable name to decode from the buffer
  258. // dst: destination buffer for the decoded variable
  259. // dst_len: length of the destination buffer
  260. //
  261. // Return:
  262. // On success, length of the decoded variable.
  263. // On error:
  264. // -1 (variable not found).
  265. // -2 (destination buffer is NULL, zero length or too small to hold the decoded variable).
  266. //
  267. // Destination buffer is guaranteed to be '\0' - terminated if it is not
  268. // NULL or zero length.
  269. int mg_get_var(const char *data, size_t data_len,
  270. const char *var_name, char *dst, size_t dst_len);
  271. // Fetch value of certain cookie variable into the destination buffer.
  272. //
  273. // Destination buffer is guaranteed to be '\0' - terminated. In case of
  274. // failure, dst[0] == '\0'. Note that RFC allows many occurrences of the same
  275. // parameter. This function returns only first occurrence.
  276. //
  277. // Return:
  278. // On success, value length.
  279. // On error:
  280. // -1 (either "Cookie:" header is not present at all or the requested parameter is not found).
  281. // -2 (destination buffer is NULL, zero length or too small to hold the value).
  282. int mg_get_cookie(const struct mg_connection *,
  283. const char *cookie_name, char *buf, size_t buf_len);
  284. // Download data from the remote web server.
  285. // host: host name to connect to, e.g. "foo.com", or "10.12.40.1".
  286. // port: port number, e.g. 80.
  287. // use_ssl: wether to use SSL connection.
  288. // error_buffer, error_buffer_size: error message placeholder.
  289. // request_fmt,...: HTTP request.
  290. // Return:
  291. // On success, valid pointer to the new connection, suitable for mg_read().
  292. // On error, NULL. error_buffer contains error message.
  293. // Example:
  294. // char ebuf[100];
  295. // struct mg_connection *conn;
  296. // conn = mg_download("google.com", 80, 0, ebuf, sizeof(ebuf),
  297. // "%s", "GET / HTTP/1.0\r\nHost: google.com\r\n\r\n");
  298. struct mg_connection *mg_download(const char *host, int port, int use_ssl,
  299. char *error_buffer, size_t error_buffer_size,
  300. PRINTF_FORMAT_STRING(const char *request_fmt),
  301. ...) PRINTF_ARGS(6, 7);
  302. // Close the connection opened by mg_download().
  303. void mg_close_connection(struct mg_connection *conn);
  304. // File upload functionality. Each uploaded file gets saved into a temporary
  305. // file and MG_UPLOAD event is sent.
  306. // Return number of uploaded files.
  307. int mg_upload(struct mg_connection *conn, const char *destination_dir);
  308. // Convenience function -- create detached thread.
  309. // Return: 0 on success, non-0 on error.
  310. typedef void * (*mg_thread_func_t)(void *);
  311. int mg_start_thread(mg_thread_func_t f, void *p);
  312. // Return builtin mime type for the given file name.
  313. // For unrecognized extensions, "text/plain" is returned.
  314. const char *mg_get_builtin_mime_type(const char *file_name);
  315. // Return Mongoose version.
  316. const char *mg_version(void);
  317. // MD5 hash given strings.
  318. // Buffer 'buf' must be 33 bytes long. Varargs is a NULL terminated list of
  319. // ASCIIz strings. When function returns, buf will contain human-readable
  320. // MD5 hash. Example:
  321. // char buf[33];
  322. // mg_md5(buf, "aa", "bb", NULL);
  323. void mg_md5(char buf[33], ...);
  324. #ifdef __cplusplus
  325. }
  326. #endif // __cplusplus
  327. #endif // MONGOOSE_HEADER_INCLUDED