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