mongoose.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  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 the mg_start()
  45. void *ev_data; // Event-specific data pointer
  46. };
  47. // Various events on which user-defined callback function is called by Mongoose.
  48. enum mg_event {
  49. // New HTTP request has arrived from the client.
  50. // If callback returns non-NULL, Mongoose stops handling current request.
  51. // ev_data contains NULL.
  52. MG_NEW_REQUEST,
  53. // Mongoose has finished handling the request.
  54. // Callback return value is ignored.
  55. // ev_data contains NULL.
  56. MG_REQUEST_COMPLETE,
  57. // HTTP error must be returned to the client.
  58. // If callback returns non-NULL, Mongoose stops handling error.
  59. // ev_data contains HTTP error code:
  60. // int http_reply_status_code = (long) request_info->ev_data;
  61. MG_HTTP_ERROR,
  62. // Mongoose logs a message.
  63. // If callback returns non-NULL, Mongoose stops handling that event.
  64. // ev_data contains a message to be logged:
  65. // const char *log_message = request_info->ev_data;
  66. MG_EVENT_LOG,
  67. // SSL initialization, sent before certificate setup.
  68. // If callback returns non-NULL, Mongoose does not set up certificates.
  69. // ev_data contains server's OpenSSL context:
  70. // SSL_CTX *ssl_context = request_info->ev_data;
  71. MG_INIT_SSL,
  72. // Sent on HTTP connect, before websocket handshake.
  73. // If user callback returns NULL, then mongoose proceeds
  74. // with handshake, otherwise it closes the connection.
  75. // ev_data contains NULL.
  76. MG_WEBSOCKET_CONNECT,
  77. // Handshake has been successfully completed.
  78. // Callback's return value is ignored.
  79. // ev_data contains NULL.
  80. MG_WEBSOCKET_READY,
  81. // Incoming message from the client, data could be read with mg_read().
  82. // If user callback returns non-NULL, mongoose closes the websocket.
  83. // ev_data contains NULL.
  84. MG_WEBSOCKET_MESSAGE,
  85. // Client has closed the connection.
  86. // Callback's return value is ignored.
  87. // ev_data contains NULL.
  88. MG_WEBSOCKET_CLOSE,
  89. // Mongoose tries to open file.
  90. // If callback returns non-NULL, Mongoose will not try to open it, but
  91. // will use the returned value as a pointer to the file data. This allows
  92. // for example to serve files from memory.
  93. // ev_data contains file path, including document root path.
  94. // Upon return, ev_data should return file size, which should be a long int.
  95. //
  96. // const char *file_name = request_info->ev_data;
  97. // if (strcmp(file_name, "foo.txt") == 0) {
  98. // request_info->ev_data = (void *) (long) 4;
  99. // return "data";
  100. // }
  101. // return NULL;
  102. //
  103. // Note that this even is sent multiple times during one request. Each
  104. // time mongoose tries to open or stat the file, this event is sent, e.g.
  105. // for opening .htpasswd file, stat-ting requested file, opening requested
  106. // file, etc.
  107. MG_OPEN_FILE,
  108. // Mongoose initializes Lua server page. Sent only if Lua support is enabled.
  109. // Callback's return value is ignored.
  110. // ev_data contains lua_State pointer.
  111. MG_INIT_LUA,
  112. };
  113. // Prototype for the user-defined function. Mongoose calls this function
  114. // on every MG_* event.
  115. //
  116. // Parameters:
  117. // event: which event has been triggered.
  118. // conn: opaque connection handler. Could be used to read, write data to the
  119. // client, etc. See functions below that have "mg_connection *" arg.
  120. //
  121. // Return:
  122. // If handler returns non-NULL, that means that handler has processed the
  123. // request by sending appropriate HTTP reply to the client. Mongoose treats
  124. // the request as served.
  125. // If handler returns NULL, that means that handler has not processed
  126. // the request. Handler must not send any data to the client in this case.
  127. // Mongoose proceeds with request handling as if nothing happened.
  128. typedef void *(*mg_callback_t)(enum mg_event event, struct mg_connection *conn);
  129. // Start web server.
  130. //
  131. // Parameters:
  132. // callback: user defined event handling function or NULL.
  133. // options: NULL terminated list of option_name, option_value pairs that
  134. // specify Mongoose configuration parameters.
  135. //
  136. // Side-effects: on UNIX, ignores SIGCHLD and SIGPIPE signals. If custom
  137. // processing is required for these, signal handlers must be set up
  138. // after calling mg_start().
  139. //
  140. //
  141. // Example:
  142. // const char *options[] = {
  143. // "document_root", "/var/www",
  144. // "listening_ports", "80,443s",
  145. // NULL
  146. // };
  147. // struct mg_context *ctx = mg_start(&my_func, NULL, options);
  148. //
  149. // Please refer to http://code.google.com/p/mongoose/wiki/MongooseManual
  150. // for the list of valid option and their possible values.
  151. //
  152. // Return:
  153. // web server context, or NULL on error.
  154. struct mg_context *mg_start(mg_callback_t callback, void *user_data,
  155. const char **options);
  156. // Stop the web server.
  157. //
  158. // Must be called last, when an application wants to stop the web server and
  159. // release all associated resources. This function blocks until all Mongoose
  160. // threads are stopped. Context pointer becomes invalid.
  161. void mg_stop(struct mg_context *);
  162. // Get the value of particular configuration parameter.
  163. // The value returned is read-only. Mongoose does not allow changing
  164. // configuration at run time.
  165. // If given parameter name is not valid, NULL is returned. For valid
  166. // names, return value is guaranteed to be non-NULL. If parameter is not
  167. // set, zero-length string is returned.
  168. const char *mg_get_option(const struct mg_context *ctx, const char *name);
  169. // Return array of strings that represent valid configuration options.
  170. // For each option, a short name, long name, and default value is returned.
  171. // Array is NULL terminated.
  172. const char **mg_get_valid_option_names(void);
  173. // Add, edit or delete the entry in the passwords file.
  174. //
  175. // This function allows an application to manipulate .htpasswd files on the
  176. // fly by adding, deleting and changing user records. This is one of the
  177. // several ways of implementing authentication on the server side. For another,
  178. // cookie-based way please refer to the examples/chat.c in the source tree.
  179. //
  180. // If password is not NULL, entry is added (or modified if already exists).
  181. // If password is NULL, entry is deleted.
  182. //
  183. // Return:
  184. // 1 on success, 0 on error.
  185. int mg_modify_passwords_file(const char *passwords_file_name,
  186. const char *domain,
  187. const char *user,
  188. const char *password);
  189. // Return information associated with the request.
  190. struct mg_request_info *mg_get_request_info(struct mg_connection *);
  191. // Send data to the client.
  192. // Return:
  193. // 0 when the connection has been closed
  194. // -1 on error
  195. // number of bytes written on success
  196. int mg_write(struct mg_connection *, const void *buf, size_t len);
  197. // Send data to the browser using printf() semantics.
  198. //
  199. // Works exactly like mg_write(), but allows to do message formatting.
  200. // Below are the macros for enabling compiler-specific checks for
  201. // printf-like arguments.
  202. #undef PRINTF_FORMAT_STRING
  203. #if _MSC_VER >= 1400
  204. #include <sal.h>
  205. #if _MSC_VER > 1400
  206. #define PRINTF_FORMAT_STRING(s) _Printf_format_string_ s
  207. #else
  208. #define PRINTF_FORMAT_STRING(s) __format_string s
  209. #endif
  210. #else
  211. #define PRINTF_FORMAT_STRING(s) s
  212. #endif
  213. #ifdef __GNUC__
  214. #define PRINTF_ARGS(x, y) __attribute__((format(printf, x, y)))
  215. #else
  216. #define PRINTF_ARGS(x, y)
  217. #endif
  218. int mg_printf(struct mg_connection *,
  219. PRINTF_FORMAT_STRING(const char *fmt), ...) PRINTF_ARGS(2, 3);
  220. // Send contents of the entire file together with HTTP headers.
  221. void mg_send_file(struct mg_connection *conn, const char *path);
  222. // Read data from the remote end, return number of bytes read.
  223. int mg_read(struct mg_connection *, void *buf, size_t len);
  224. // Get the value of particular HTTP header.
  225. //
  226. // This is a helper function. It traverses request_info->http_headers array,
  227. // and if the header is present in the array, returns its value. If it is
  228. // not present, NULL is returned.
  229. const char *mg_get_header(const struct mg_connection *, const char *name);
  230. // Get a value of particular form variable.
  231. //
  232. // Parameters:
  233. // data: pointer to form-uri-encoded buffer. This could be either POST data,
  234. // or request_info.query_string.
  235. // data_len: length of the encoded data.
  236. // var_name: variable name to decode from the buffer
  237. // buf: destination buffer for the decoded variable
  238. // buf_len: length of the destination buffer
  239. //
  240. // Return:
  241. // On success, length of the decoded variable.
  242. // On error:
  243. // -1 (variable not found, or destination buffer is too small).
  244. // -2 (destination buffer is NULL or zero length).
  245. //
  246. // Destination buffer is guaranteed to be '\0' - terminated if it is not
  247. // NULL or zero length. In case of failure, dst[0] == '\0'.
  248. int mg_get_var(const char *data, size_t data_len,
  249. const char *var_name, char *buf, size_t buf_len);
  250. // Fetch value of certain cookie variable into the destination buffer.
  251. //
  252. // Destination buffer is guaranteed to be '\0' - terminated. In case of
  253. // failure, dst[0] == '\0'. Note that RFC allows many occurrences of the same
  254. // parameter. This function returns only first occurrence.
  255. //
  256. // Return:
  257. // On success, value length.
  258. // On error, -1 (either "Cookie:" header is not present at all, or the
  259. // requested parameter is not found, or destination buffer is too small
  260. // to hold the value).
  261. int mg_get_cookie(const struct mg_connection *,
  262. const char *cookie_name, char *buf, size_t buf_len);
  263. // Connect to the remote web server.
  264. // Return:
  265. // On success, valid pointer to the new connection
  266. // On error, NULL
  267. struct mg_connection *mg_connect(struct mg_context *ctx,
  268. const char *host, int port, int use_ssl);
  269. // Close the connection opened by mg_connect().
  270. void mg_close_connection(struct mg_connection *conn);
  271. // Download given URL to a given file.
  272. // url: URL to download
  273. // path: file name where to save the data
  274. // request_info: pointer to a structure that will hold parsed reply headers
  275. // buf, bul_len: a buffer for the reply headers
  276. // Return:
  277. // On error, NULL
  278. // On success, opened file stream to the downloaded contents. The stream
  279. // is positioned to the end of the file. It is the user's responsibility
  280. // to fclose() the opened file stream.
  281. FILE *mg_fetch(struct mg_context *ctx, const char *url, const char *path,
  282. char *buf, size_t buf_len, struct mg_request_info *request_info);
  283. // Convenience function -- create detached thread.
  284. // Return: 0 on success, non-0 on error.
  285. typedef void * (*mg_thread_func_t)(void *);
  286. int mg_start_thread(mg_thread_func_t f, void *p);
  287. // Return builtin mime type for the given file name.
  288. // For unrecognized extensions, "text/plain" is returned.
  289. const char *mg_get_builtin_mime_type(const char *file_name);
  290. // Return Mongoose version.
  291. const char *mg_version(void);
  292. // MD5 hash given strings.
  293. // Buffer 'buf' must be 33 bytes long. Varargs is a NULL terminated list of
  294. // ASCIIz strings. When function returns, buf will contain human-readable
  295. // MD5 hash. Example:
  296. // char buf[33];
  297. // mg_md5(buf, "aa", "bb", NULL);
  298. void mg_md5(char buf[33], ...);
  299. #ifdef __cplusplus
  300. }
  301. #endif // __cplusplus
  302. #endif // MONGOOSE_HEADER_INCLUDED