mongoose.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  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. // Parsed Authorization header
  30. struct mg_auth_header {
  31. const char *user, *uri, *cnonce, *response, *qop, *nc, *nonce; // Fields of the Authorization header
  32. // The following members can be set by MG_AUTHENTICATE callback
  33. // if non-NULL, will be freed by mongoose
  34. char *ha1; // ha1 = md5(username:domain:password), used to compute expected_response
  35. char *expected_response; // Compared against response
  36. };
  37. // This structure contains information about the HTTP request.
  38. struct mg_request_info {
  39. void *user_data; // User-defined pointer passed to mg_start()
  40. char *request_method; // "GET", "POST", etc
  41. char *uri; // URL-decoded URI
  42. char *http_version; // E.g. "1.0", "1.1"
  43. char *query_string; // URL part after '?' (not including '?') or NULL
  44. char *remote_user; // Authenticated user, or NULL if no auth used
  45. char *log_message; // Mongoose error log message, MG_EVENT_LOG only
  46. long remote_ip; // Client's IP address
  47. int remote_port; // Client's port
  48. int status_code; // HTTP reply status code, e.g. 200
  49. int is_ssl; // 1 if SSL-ed, 0 if not
  50. int num_headers; // Number of headers
  51. struct mg_header {
  52. char *name; // HTTP header name
  53. char *value; // HTTP header value
  54. } http_headers[64]; // Maximum 64 headers
  55. struct mg_auth_header *ah; // Parsed Authorization header, if present
  56. };
  57. // Various events on which user-defined function is called by Mongoose.
  58. enum mg_event {
  59. MG_NEW_MASTER_PLUGIN, // New master plugin thread created user can add plugin to it
  60. // that will survive the whole server life
  61. MG_FREE_MASTER_PLUGIN, // Master plgugin thread is exiting free user added plugin
  62. MG_NEW_PLUGIN, // New worker thread created user can add plugin to it
  63. // that will survive the whole thread life
  64. MG_FREE_PLUGIN, // Worker thread is exiting free user added plugin
  65. MG_NEW_CONNECTION,// New TCP connection request has arrived from the client
  66. MG_NEW_REQUEST, // New HTTP request has arrived from the client
  67. MG_REQUEST_COMPLETE, // Mongoose has finished handling the request
  68. MG_HTTP_ERROR, // HTTP error must be returned to the client
  69. MG_EVENT_LOG, // Mongoose logs an event, request_info.log_message
  70. MG_INIT_SSL, // Mongoose initializes SSL. Instead of mg_connection *,
  71. // SSL context is passed to the callback function.
  72. MG_WEBSOCKET_CONNECT, // 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. MG_WEBSOCKET_READY, // Handshake has been successfully completed.
  76. MG_WEBSOCKET_MESSAGE, // Incoming message from the client
  77. MG_WEBSOCKET_CLOSE, // Client has closed the connection
  78. MG_AUTHENTICATE, // Authenticate a new HTTP request. request_info->ah
  79. // is set, if available. Callback should fill in request_info->ha1.
  80. };
  81. // Prototype for the user-defined function. Mongoose calls this function
  82. // on every MG_* event.
  83. //
  84. // Parameters:
  85. // event: which event has been triggered.
  86. // conn: opaque connection handler. Could be used to read, write data to the
  87. // client, etc. See functions below that have "mg_connection *" arg.
  88. // request_info: Information about HTTP request.
  89. //
  90. // Return:
  91. // If handler returns non-NULL, that means that handler has processed the
  92. // request by sending appropriate HTTP reply to the client. Mongoose treats
  93. // the request as served.
  94. // If handler returns NULL, that means that handler has not processed
  95. // the request. Handler must not send any data to the client in this case.
  96. // Mongoose proceeds with request handling as if nothing happened.
  97. typedef void * (*mg_callback_t)(enum mg_event event,
  98. struct mg_connection *conn,
  99. const struct mg_request_info *request_info);
  100. void *mg_get_plugin(struct mg_connection *conn);
  101. void *mg_lock_master_plugin(struct mg_connection *conn);
  102. void mg_unlock_master_plugin(struct mg_connection *conn);
  103. void *mg_get_user_data(struct mg_connection *conn);
  104. // Start web server.
  105. //
  106. // Parameters:
  107. // callback: user defined event handling function or NULL.
  108. // options: NULL terminated list of option_name, option_value pairs that
  109. // specify Mongoose configuration parameters.
  110. //
  111. // Side-effects: on UNIX, ignores SIGCHLD and SIGPIPE signals. If custom
  112. // processing is required for these, signal handlers must be set up
  113. // after calling mg_start().
  114. //
  115. //
  116. // Example:
  117. // const char *options[] = {
  118. // "document_root", "/var/www",
  119. // "listening_ports", "80,443s",
  120. // NULL
  121. // };
  122. // struct mg_context *ctx = mg_start(&my_func, NULL, options);
  123. //
  124. // Please refer to http://code.google.com/p/mongoose/wiki/MongooseManual
  125. // for the list of valid option and their possible values.
  126. //
  127. // Return:
  128. // web server context, or NULL on error.
  129. struct mg_context *mg_start(mg_callback_t callback, void *user_data,
  130. const char **options);
  131. void mg_handle_cgi_request(struct mg_connection *conn, const char *prog);
  132. int mg_strncasecmp(const char *s1, const char *s2, size_t len);
  133. int mg_strcasecmp(const char *s1, const char *s2);
  134. char * mg_strdup(const char *str);
  135. char * mg_strndup(const char *ptr, size_t len);
  136. // Stop the web server.
  137. //
  138. // Must be called last, when an application wants to stop the web server and
  139. // release all associated resources. This function blocks until all Mongoose
  140. // threads are stopped. Context pointer becomes invalid.
  141. void mg_stop(struct mg_context *);
  142. // Get the value of particular configuration parameter.
  143. // The value returned is read-only. Mongoose does not allow changing
  144. // configuration at run time.
  145. // If given parameter name is not valid, NULL is returned. For valid
  146. // names, return value is guaranteed to be non-NULL. If parameter is not
  147. // set, zero-length string is returned.
  148. const char *mg_get_option(const struct mg_context *ctx, const char *name);
  149. // Return array of strings that represent valid configuration options.
  150. // For each option, a short name, long name, and default value is returned.
  151. // Array is NULL terminated.
  152. const char **mg_get_valid_option_names(void);
  153. // Add, edit or delete the entry in the passwords file.
  154. //
  155. // This function allows an application to manipulate .htpasswd files on the
  156. // fly by adding, deleting and changing user records. This is one of the
  157. // several ways of implementing authentication on the server side. For another,
  158. // cookie-based way please refer to the examples/chat.c in the source tree.
  159. //
  160. // If password is not NULL, entry is added (or modified if already exists).
  161. // If password is NULL, entry is deleted.
  162. //
  163. // Return:
  164. // 1 on success, 0 on error.
  165. int mg_modify_passwords_file(const char *passwords_file_name,
  166. const char *domain,
  167. const char *user,
  168. const char *password);
  169. // Return information associated with the request.
  170. // These functions always succeed.
  171. const struct mg_request_info *mg_get_request_info(const struct mg_connection *);
  172. void *mg_get_user_data(struct mg_connection *);
  173. const char *mg_get_log_message(const struct mg_connection *);
  174. int mg_get_reply_status_code(const struct mg_connection *);
  175. void *mg_get_ssl_context(const struct mg_connection *);
  176. // Send data to the client.
  177. // Return:
  178. // 0 when the connection has been closed
  179. // -1 on error
  180. // number of bytes written on success
  181. int mg_write(struct mg_connection *, const void *buf, size_t len);
  182. // Send data to the browser using printf() semantics.
  183. //
  184. // Works exactly like mg_write(), but allows to do message formatting.
  185. // Below are the macros for enabling compiler-specific checks for
  186. // printf-like arguments.
  187. #undef PRINTF_FORMAT_STRING
  188. #if _MSC_VER >= 1400
  189. #include <sal.h>
  190. #if _MSC_VER > 1400
  191. #define PRINTF_FORMAT_STRING(s) _Printf_format_string_ s
  192. #else
  193. #define PRINTF_FORMAT_STRING(s) __format_string s
  194. #endif
  195. #else
  196. #define PRINTF_FORMAT_STRING(s) s
  197. #endif
  198. #ifdef __GNUC__
  199. #define PRINTF_ARGS(x, y) __attribute__((format(printf, x, y)))
  200. #else
  201. #define PRINTF_ARGS(x, y)
  202. #endif
  203. int mg_printf(struct mg_connection *,
  204. PRINTF_FORMAT_STRING(const char *fmt), ...) PRINTF_ARGS(2, 3);
  205. // Send contents of the entire file together with HTTP headers.
  206. void mg_send_file(struct mg_connection *conn, const char *path);
  207. // Read data from the remote end, return number of bytes read.
  208. int mg_read(struct mg_connection *, void *buf, size_t len);
  209. // Send a 401 Unauthorized response to the browser.
  210. //
  211. // This triggers a username/password entry in the browser. The realm
  212. // in the request is set to the AUTHENTICATION_DOMAIN option.
  213. // If nonce is non-NULL, it is sent as the nonce of the authentication
  214. // request, else a nonce is generated.
  215. void mg_send_authorization_request(struct mg_connection *conn, const char *nonce);
  216. // Get the value of particular HTTP header.
  217. //
  218. // This is a helper function. It traverses request_info->http_headers array,
  219. // and if the header is present in the array, returns its value. If it is
  220. // not present, NULL is returned.
  221. const char *mg_get_header(const struct mg_connection *, const char *name);
  222. //int mg_get_connection_count(const struct mg_connection *conn);
  223. // Get a value of particular form variable.
  224. //
  225. // Parameters:
  226. // data: pointer to form-uri-encoded buffer. This could be either POST data,
  227. // or request_info.query_string.
  228. // data_len: length of the encoded data.
  229. // var_name: variable name to decode from the buffer
  230. // buf: destination buffer for the decoded variable
  231. // buf_len: length of the destination buffer
  232. //
  233. // Return:
  234. // On success, length of the decoded variable.
  235. // On error:
  236. // -1 (variable not found, or destination buffer is too small).
  237. // -2 (destination buffer is NULL or zero length).
  238. //
  239. // Destination buffer is guaranteed to be '\0' - terminated. In case of
  240. // failure, dst[0] == '\0'.
  241. int mg_find_var(const char *buf, size_t buf_len, const char *name,
  242. const char **start);
  243. int mg_get_var(const char *data, size_t data_len,
  244. const char *var_name, char *buf, size_t buf_len);
  245. // Fetch value of certain cookie variable into the destination buffer.
  246. //
  247. // Destination buffer is guaranteed to be '\0' - terminated. In case of
  248. // failure, dst[0] == '\0'. Note that RFC allows many occurrences of the same
  249. // parameter. This function returns only first occurrence.
  250. //
  251. // Return:
  252. // On success, value length.
  253. // On error, -1 (either "Cookie:" header is not present at all, or the
  254. // requested parameter is not found, or destination buffer is too small
  255. // to hold the value).
  256. int mg_get_cookie(const struct mg_connection *,
  257. const char *cookie_name, char *buf, size_t buf_len);
  258. int mg_find_cookie(const struct mg_connection *,
  259. const char *cookie_name, const char **start);
  260. const char *mg_get_document_root(const struct mg_connection *);
  261. // Connect to the remote web server.
  262. // Return:
  263. // On success, valid pointer to the new connection
  264. // On error, NULL
  265. struct mg_connection *mg_connect(struct mg_context *ctx,
  266. const char *host, int port, int use_ssl);
  267. // Close the connection opened by mg_connect().
  268. void mg_close_connection(struct mg_connection *conn);
  269. // Download given URL to a given file.
  270. // url: URL to download
  271. // path: file name where to save the data
  272. // request_info: pointer to a structure that will hold parsed reply headers
  273. // buf, bul_len: a buffer for the reply headers
  274. // Return:
  275. // On error, NULL
  276. // On success, opened file stream to the downloaded contents. The stream
  277. // is positioned to the end of the file. It is the user's responsibility
  278. // to fclose() the opened file stream.
  279. FILE *mg_fetch(struct mg_context *ctx, const char *url, const char *path,
  280. char *buf, size_t buf_len, struct mg_request_info *request_info);
  281. // Convenience function -- create detached thread.
  282. // Return: 0 on success, non-0 on error.
  283. typedef void * (*mg_thread_func_t)(void *);
  284. int mg_start_thread(mg_thread_func_t f, void *p);
  285. // Return builtin mime type for the given file name.
  286. // For unrecognized extensions, "text/plain" is returned.
  287. const char *mg_get_builtin_mime_type(const char *file_name);
  288. // Return Mongoose version.
  289. const char *mg_version(void);
  290. // MD5 hash given strings.
  291. // Buffer 'buf' must be 33 bytes long. Varargs is a NULL terminated list of
  292. // ASCIIz strings. When function returns, buf will contain human-readable
  293. // MD5 hash. Example:
  294. // char buf[33];
  295. // mg_md5(buf, "aa", "bb", NULL);
  296. #define MD5_BUF_SIZE 33
  297. typedef char md5_buf_t[MD5_BUF_SIZE];
  298. void mg_md5(md5_buf_t buf, ...);
  299. // Stringify binary data. Output buffer must be twice as big as input,
  300. // because each byte takes 2 bytes in string representation
  301. void mg_bin2str(char *to, const unsigned char *p, size_t len);
  302. #ifdef USE_MG_MD5
  303. #include <stdint.h>
  304. typedef struct MD5Context {
  305. uint32_t buf[4];
  306. uint32_t bits[2];
  307. unsigned char in[64];
  308. } MD5_CTX;
  309. void MD5Init(MD5_CTX *ctx);
  310. void MD5Transform(uint32_t buf[4], uint32_t const in[16]);
  311. void MD5Update(MD5_CTX *ctx, unsigned char const *buf, unsigned len);
  312. void MD5Final(unsigned char digest[16], MD5_CTX *ctx);
  313. #endif //HAVE_MD5
  314. // URL-decode input buffer into destination buffer.
  315. // 0-terminate the destination buffer. Return the length of decoded data.
  316. // form-url-encoded data differs from URI encoding in a way that it
  317. // uses '+' as character for space, see RFC 1866 section 8.2.1
  318. // http://ftp.ics.uci.edu/pub/ietf/html/rfc1866.txt
  319. size_t mg_url_decode(const char *src, size_t src_len, char *dst,
  320. size_t dst_len, int is_form_url_encoded);
  321. const char * mg_url_encode_to(const char *src, char *dst, size_t dst_len);
  322. char * mg_url_encode(const char *src);
  323. #if defined(_WIN32) || defined(_WIN32_WCE)
  324. #include <windows.h>
  325. typedef HANDLE mg_thread_mutex_t;
  326. typedef struct {HANDLE signal, broadcast;} mg_thread_cond_t;
  327. typedef DWORD mg_thread_t;
  328. typedef void mg_thread_mutexattr_t;
  329. typedef void mg_thread_condattr_t;
  330. #else
  331. #include <pthread.h>
  332. typedef pthread_mutex_t mg_thread_mutex_t;
  333. typedef pthread_cond_t mg_thread_cond_t;
  334. typedef pthread_t mg_thread_t;
  335. typedef pthread_mutexattr_t mg_thread_mutexattr_t;
  336. typedef pthread_condattr_t mg_thread_condattr_t;
  337. #endif
  338. #define HAS_MG_THREAD_FUNC_DEFINED
  339. //typedef void * (*mg_thread_func_t)(void *);
  340. mg_thread_t mg_thread_self(void);
  341. int mg_thread_mutex_init(mg_thread_mutex_t *mutex, const mg_thread_mutexattr_t *attr);
  342. int mg_thread_mutex_destroy(mg_thread_mutex_t *mutex);
  343. int mg_thread_mutex_lock(mg_thread_mutex_t *mutex);
  344. int mg_thread_mutex_unlock(mg_thread_mutex_t *mutex);
  345. int mg_thread_cond_init(mg_thread_cond_t *cv, const mg_thread_condattr_t *attr);
  346. int mg_thread_cond_wait(mg_thread_cond_t *cv, mg_thread_mutex_t *mutex);
  347. int mg_thread_cond_signal(mg_thread_cond_t *cv);
  348. int mg_thread_cond_broadcast(mg_thread_cond_t *cv);
  349. int mg_thread_cond_destroy(mg_thread_cond_t *cv);
  350. int mg_start_thread(mg_thread_func_t func, void *param);
  351. #ifdef __cplusplus
  352. }
  353. #endif // __cplusplus
  354. #endif // MONGOOSE_HEADER_INCLUDED