mongoose.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  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. // Mongoose has uploaded file to a temporary directory.
  113. // Callback's return value is ignored.
  114. // ev_data contains NUL-terminated file name.
  115. MG_UPLOAD,
  116. };
  117. // Prototype for the user-defined function. Mongoose calls this function
  118. // on every MG_* event.
  119. //
  120. // Parameters:
  121. // event: which event has been triggered.
  122. // conn: opaque connection handler. Could be used to read, write data to the
  123. // client, etc. See functions below that have "mg_connection *" arg.
  124. //
  125. // Return:
  126. // If handler returns non-NULL, that means that handler has processed the
  127. // request by sending appropriate HTTP reply to the client. Mongoose treats
  128. // the request as served.
  129. // If handler returns NULL, that means that handler has not processed
  130. // the request. Handler must not send any data to the client in this case.
  131. // Mongoose proceeds with request handling as if nothing happened.
  132. typedef void *(*mg_callback_t)(enum mg_event event, struct mg_connection *conn);
  133. // Start web server.
  134. //
  135. // Parameters:
  136. // callback: user defined event handling function or NULL.
  137. // options: NULL terminated list of option_name, option_value pairs that
  138. // specify Mongoose configuration parameters.
  139. //
  140. // Side-effects: on UNIX, ignores SIGCHLD and SIGPIPE signals. If custom
  141. // processing is required for these, signal handlers must be set up
  142. // after calling mg_start().
  143. //
  144. //
  145. // Example:
  146. // const char *options[] = {
  147. // "document_root", "/var/www",
  148. // "listening_ports", "80,443s",
  149. // NULL
  150. // };
  151. // struct mg_context *ctx = mg_start(&my_func, NULL, options);
  152. //
  153. // Please refer to http://code.google.com/p/mongoose/wiki/MongooseManual
  154. // for the list of valid option and their possible values.
  155. //
  156. // Return:
  157. // web server context, or NULL on error.
  158. struct mg_context *mg_start(mg_callback_t callback, void *user_data,
  159. const char **options);
  160. // Stop the web server.
  161. //
  162. // Must be called last, when an application wants to stop the web server and
  163. // release all associated resources. This function blocks until all Mongoose
  164. // threads are stopped. Context pointer becomes invalid.
  165. void mg_stop(struct mg_context *);
  166. // Get the value of particular configuration parameter.
  167. // The value returned is read-only. Mongoose does not allow changing
  168. // configuration at run time.
  169. // If given parameter name is not valid, NULL is returned. For valid
  170. // names, return value is guaranteed to be non-NULL. If parameter is not
  171. // set, zero-length string is returned.
  172. const char *mg_get_option(const struct mg_context *ctx, const char *name);
  173. // Return array of strings that represent valid configuration options.
  174. // For each option, a short name, long name, and default value is returned.
  175. // Array is NULL terminated.
  176. const char **mg_get_valid_option_names(void);
  177. // Add, edit or delete the entry in the passwords file.
  178. //
  179. // This function allows an application to manipulate .htpasswd files on the
  180. // fly by adding, deleting and changing user records. This is one of the
  181. // several ways of implementing authentication on the server side. For another,
  182. // cookie-based way please refer to the examples/chat.c in the source tree.
  183. //
  184. // If password is not NULL, entry is added (or modified if already exists).
  185. // If password is NULL, entry is deleted.
  186. //
  187. // Return:
  188. // 1 on success, 0 on error.
  189. int mg_modify_passwords_file(const char *passwords_file_name,
  190. const char *domain,
  191. const char *user,
  192. const char *password);
  193. // Return information associated with the request.
  194. struct mg_request_info *mg_get_request_info(struct mg_connection *);
  195. // Send data to the client.
  196. // Return:
  197. // 0 when the connection has been closed
  198. // -1 on error
  199. // number of bytes written on success
  200. int mg_write(struct mg_connection *, const void *buf, size_t len);
  201. // Send data to the browser using printf() semantics.
  202. //
  203. // Works exactly like mg_write(), but allows to do message formatting.
  204. // Below are the macros for enabling compiler-specific checks for
  205. // printf-like arguments.
  206. #undef PRINTF_FORMAT_STRING
  207. #if _MSC_VER >= 1400
  208. #include <sal.h>
  209. #if _MSC_VER > 1400
  210. #define PRINTF_FORMAT_STRING(s) _Printf_format_string_ s
  211. #else
  212. #define PRINTF_FORMAT_STRING(s) __format_string s
  213. #endif
  214. #else
  215. #define PRINTF_FORMAT_STRING(s) s
  216. #endif
  217. #ifdef __GNUC__
  218. #define PRINTF_ARGS(x, y) __attribute__((format(printf, x, y)))
  219. #else
  220. #define PRINTF_ARGS(x, y)
  221. #endif
  222. int mg_printf(struct mg_connection *,
  223. PRINTF_FORMAT_STRING(const char *fmt), ...) PRINTF_ARGS(2, 3);
  224. // Send contents of the entire file together with HTTP headers.
  225. void mg_send_file(struct mg_connection *conn, const char *path);
  226. // Read data from the remote end, return number of bytes read.
  227. int mg_read(struct mg_connection *, void *buf, size_t len);
  228. // Get the value of particular HTTP header.
  229. //
  230. // This is a helper function. It traverses request_info->http_headers array,
  231. // and if the header is present in the array, returns its value. If it is
  232. // not present, NULL is returned.
  233. const char *mg_get_header(const struct mg_connection *, const char *name);
  234. // Get a value of particular form variable.
  235. //
  236. // Parameters:
  237. // data: pointer to form-uri-encoded buffer. This could be either POST data,
  238. // or request_info.query_string.
  239. // data_len: length of the encoded data.
  240. // var_name: variable name to decode from the buffer
  241. // dst: destination buffer for the decoded variable
  242. // dst_len: length of the destination buffer
  243. //
  244. // Return:
  245. // On success, length of the decoded variable.
  246. // On error:
  247. // -1 (variable not found).
  248. // -2 (destination buffer is NULL, zero length or too small to hold the decoded variable).
  249. //
  250. // Destination buffer is guaranteed to be '\0' - terminated if it is not
  251. // NULL or zero length.
  252. int mg_get_var(const char *data, size_t data_len,
  253. const char *var_name, char *dst, size_t dst_len);
  254. // Fetch value of certain cookie variable into the destination buffer.
  255. //
  256. // Destination buffer is guaranteed to be '\0' - terminated. In case of
  257. // failure, dst[0] == '\0'. Note that RFC allows many occurrences of the same
  258. // parameter. This function returns only first occurrence.
  259. //
  260. // Return:
  261. // On success, value length.
  262. // On error, -1 (either "Cookie:" header is not present at all, or the
  263. // requested parameter is not found, or destination buffer is too small
  264. // to hold the value).
  265. int mg_get_cookie(const struct mg_connection *,
  266. const char *cookie_name, char *buf, size_t buf_len);
  267. // Connect to the remote web server.
  268. // Return:
  269. // On success, valid pointer to the new connection
  270. // On error, NULL
  271. struct mg_connection *mg_connect(struct mg_context *ctx,
  272. const char *host, int port, int use_ssl);
  273. // Close the connection opened by mg_connect().
  274. void mg_close_connection(struct mg_connection *conn);
  275. // Download given URL to a given file.
  276. // url: URL to download
  277. // path: file name where to save the data
  278. // request_info: pointer to a structure that will hold parsed reply headers
  279. // buf, bul_len: a buffer for the reply headers
  280. // Return:
  281. // On error, NULL
  282. // On success, opened file stream to the downloaded contents. The stream
  283. // is positioned to the end of the file. It is the user's responsibility
  284. // to fclose() the opened file stream.
  285. FILE *mg_fetch(struct mg_context *ctx, const char *url, const char *path,
  286. char *buf, size_t buf_len, struct mg_request_info *request_info);
  287. // File upload functionality. Each uploaded file gets saved into a temporary
  288. // file and MG_UPLOAD event is sent.
  289. // Return number of uploaded files.
  290. int mg_upload(struct mg_connection *conn, const char *destination_dir);
  291. // Convenience function -- create detached thread.
  292. // Return: 0 on success, non-0 on error.
  293. typedef void * (*mg_thread_func_t)(void *);
  294. int mg_start_thread(mg_thread_func_t f, void *p);
  295. // Return builtin mime type for the given file name.
  296. // For unrecognized extensions, "text/plain" is returned.
  297. const char *mg_get_builtin_mime_type(const char *file_name);
  298. // Return Mongoose version.
  299. const char *mg_version(void);
  300. // MD5 hash given strings.
  301. // Buffer 'buf' must be 33 bytes long. Varargs is a NULL terminated list of
  302. // ASCIIz strings. When function returns, buf will contain human-readable
  303. // MD5 hash. Example:
  304. // char buf[33];
  305. // mg_md5(buf, "aa", "bb", NULL);
  306. void mg_md5(char buf[33], ...);
  307. #ifdef __cplusplus
  308. }
  309. #endif // __cplusplus
  310. #endif // MONGOOSE_HEADER_INCLUDED