1 /* Copyright (c) 2013-2018 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.12"
27 #define CIVETWEB_VERSION_MAJOR (1)
28 #define CIVETWEB_VERSION_MINOR (12)
29 #define CIVETWEB_VERSION_PATCH (0)
30 
31 #ifndef CIVETWEB_API
32 #if defined(_WIN32)
33 #if defined(CIVETWEB_DLL_EXPORTS)
34 #define CIVETWEB_API __declspec(dllexport)
35 #elif defined(CIVETWEB_DLL_IMPORTS)
36 #define CIVETWEB_API __declspec(dllimport)
37 #else
38 #define CIVETWEB_API
39 #endif
40 #elif __GNUC__ >= 4
41 #define CIVETWEB_API __attribute__((visibility("default")))
42 #else
43 #define CIVETWEB_API
44 #endif
45 #endif
46 
47 #include <stddef.h>
48 #include <stdio.h>
49 
50 #ifdef __cplusplus
51 extern "C" {
52 #endif /* __cplusplus */
53 
54 
55 /* Init Features */
56 enum {
57 	MG_FEATURES_DEFAULT = 0x0u,
58 
59 	/* Support files from local directories */
60 	/* Will only work, if NO_FILES is not set. */
61 	MG_FEATURES_FILES = 0x1u,
62 
63 	/* Support transport layer security (TLS). */
64 	/* SSL is still often used synonymously for TLS. */
65 	/* Will only work, if NO_SSL is not set. */
66 	MG_FEATURES_TLS = 0x2u,
67 	MG_FEATURES_SSL = 0x2u,
68 
69 	/* Support common gateway interface (CGI). */
70 	/* Will only work, if NO_CGI is not set. */
71 	MG_FEATURES_CGI = 0x4u,
72 
73 	/* Support IPv6. */
74 	/* Will only work, if USE_IPV6 is set. */
75 	MG_FEATURES_IPV6 = 0x8u,
76 
77 	/* Support WebSocket protocol. */
78 	/* Will only work, if USE_WEBSOCKET is set. */
79 	MG_FEATURES_WEBSOCKET = 0x10u,
80 
81 	/* Support server side Lua scripting. */
82 	/* Will only work, if USE_LUA is set. */
83 	MG_FEATURES_LUA = 0x20u,
84 
85 	/* Support server side JavaScript scripting. */
86 	/* Will only work, if USE_DUKTAPE is set. */
87 	MG_FEATURES_SSJS = 0x40u,
88 
89 	/* Provide data required for caching files. */
90 	/* Will only work, if NO_CACHING is not set. */
91 	MG_FEATURES_CACHE = 0x80u,
92 
93 	/* Collect server status information. */
94 	/* Will only work, if USE_SERVER_STATS is set. */
95 	MG_FEATURES_STATS = 0x100u,
96 
97 	/* Support on-the-fly compression. */
98 	/* Will only work, if USE_ZLIB is set. */
99 	MG_FEATURES_COMPRESSION = 0x200u,
100 
101 	/* Collect server status information. */
102 	/* Will only work, if USE_SERVER_STATS is set. */
103 	MG_FEATURES_ALL = 0xFFFFu
104 };
105 
106 
107 /* Initialize this library. This should be called once before any other
108  * function from this library. This function is not guaranteed to be
109  * thread safe.
110  * Parameters:
111  *   features: bit mask for features to be initialized.
112  *             Note: The TLS libraries (like OpenSSL) is initialized
113  *                   only if the MG_FEATURES_TLS bit is set.
114  *                   Currently the other bits do not influence
115  *                   initialization, but this may change in future
116  *                   versions.
117  * Return value:
118  *   initialized features
119  *   0: error
120  */
121 CIVETWEB_API unsigned mg_init_library(unsigned features);
122 
123 
124 /* Un-initialize this library.
125  * Return value:
126  *   0: error
127  */
128 CIVETWEB_API unsigned mg_exit_library(void);
129 
130 
131 struct mg_context;    /* Handle for the HTTP service itself */
132 struct mg_connection; /* Handle for the individual connection */
133 
134 
135 /* Maximum number of headers */
136 #define MG_MAX_HEADERS (64)
137 
138 struct mg_header {
139 	const char *name;  /* HTTP header name */
140 	const char *value; /* HTTP header value */
141 };
142 
143 
144 /* This structure contains information about the HTTP request. */
145 struct mg_request_info {
146 	const char *request_method;  /* "GET", "POST", etc */
147 	const char *request_uri;     /* URL-decoded URI (absolute or relative,
148 	                              * as in the request) */
149 	const char *local_uri;       /* URL-decoded URI (relative). Can be NULL
150 	                              * if the request_uri does not address a
151 	                              * resource at the server host. */
152 #if defined(MG_LEGACY_INTERFACE) /* 2017-02-04, deprecated 2014-09-14 */
153 	const char *uri;             /* Deprecated: use local_uri instead */
154 #endif
155 	const char *http_version; /* E.g. "1.0", "1.1" */
156 	const char *query_string; /* URL part after '?', not including '?', or
157 	                             NULL */
158 	const char *remote_user;  /* Authenticated user, or NULL if no auth
159 	                             used */
160 	char remote_addr[48];     /* Client's IP address as a string. */
161 
162 	long long content_length; /* Length (in bytes) of the request body,
163 	                             can be -1 if no length was given. */
164 	int remote_port;          /* Client's port */
165 	int is_ssl;               /* 1 if SSL-ed, 0 if not */
166 	void *user_data;          /* User data pointer passed to mg_start() */
167 	void *conn_data;          /* Connection-specific user data */
168 
169 	int num_headers; /* Number of HTTP headers */
170 	struct mg_header
171 	    http_headers[MG_MAX_HEADERS]; /* Allocate maximum headers */
172 
173 	struct mg_client_cert *client_cert; /* Client certificate information */
174 
175 	const char *acceptedWebSocketSubprotocol; /* websocket subprotocol,
176 	                                           * accepted during handshake */
177 };
178 
179 
180 /* This structure contains information about the HTTP request. */
181 /* This structure may be extended in future versions. */
182 struct mg_response_info {
183 	int status_code;          /* E.g. 200 */
184 	const char *status_text;  /* E.g. "OK" */
185 	const char *http_version; /* E.g. "1.0", "1.1" */
186 
187 	long long content_length; /* Length (in bytes) of the request body,
188 	                             can be -1 if no length was given. */
189 
190 	int num_headers; /* Number of HTTP headers */
191 	struct mg_header
192 	    http_headers[MG_MAX_HEADERS]; /* Allocate maximum headers */
193 };
194 
195 
196 /* Client certificate information (part of mg_request_info) */
197 /* New nomenclature. */
198 struct mg_client_cert {
199 	void *peer_cert;
200 	const char *subject;
201 	const char *issuer;
202 	const char *serial;
203 	const char *finger;
204 };
205 
206 #if defined(MG_LEGACY_INTERFACE) /* 2017-10-05 */
207 /* Old nomenclature. */
208 struct client_cert {
209 	const char *subject;
210 	const char *issuer;
211 	const char *serial;
212 	const char *finger;
213 };
214 #endif
215 
216 
217 /* This structure needs to be passed to mg_start(), to let civetweb know
218    which callbacks to invoke. For a detailed description, see
219    https://github.com/civetweb/civetweb/blob/master/docs/UserManual.md */
220 struct mg_callbacks {
221 	/* Called when civetweb has received new HTTP request.
222 	   If the callback returns one, it must process the request
223 	   by sending valid HTTP headers and a body. Civetweb will not do
224 	   any further processing. Otherwise it must return zero.
225 	   Note that since V1.7 the "begin_request" function is called
226 	   before an authorization check. If an authorization check is
227 	   required, use a request_handler instead.
228 	   Return value:
229 	     0: civetweb will process the request itself. In this case,
230 	        the callback must not send any data to the client.
231 	     1-999: callback already processed the request. Civetweb will
232 	            not send any data after the callback returned. The
233 	            return code is stored as a HTTP status code for the
234 	            access log. */
235 	int (*begin_request)(struct mg_connection *);
236 
237 	/* Called when civetweb has finished processing request. */
238 	void (*end_request)(const struct mg_connection *, int reply_status_code);
239 
240 	/* Called when civetweb is about to log a message. If callback returns
241 	   non-zero, civetweb does not log anything. */
242 	int (*log_message)(const struct mg_connection *, const char *message);
243 
244 	/* Called when civetweb is about to log access. If callback returns
245 	   non-zero, civetweb does not log anything. */
246 	int (*log_access)(const struct mg_connection *, const char *message);
247 
248 	/* Called when civetweb initializes SSL library.
249 	   Parameters:
250 	     user_data: parameter user_data passed when starting the server.
251 	   Return value:
252 	     0: civetweb will set up the SSL certificate.
253 	     1: civetweb assumes the callback already set up the certificate.
254 	    -1: initializing ssl fails. */
255 	int (*init_ssl)(void *ssl_context, void *user_data);
256 
257 	/* Called when civetweb is about to create or free a SSL_CTX.
258 	Parameters:
259 	   ssl_ctx: SSL_CTX pointer. NULL at creation time, Not NULL when mg_context
260 	            will be freed
261 	     user_data: parameter user_data passed when starting the server.
262 	   Return value:
263 	     0: civetweb will continue to create the context, just as if the
264 	        callback would not be present.
265 	        The value in *ssl_ctx when the function returns is ignored.
266 	     1: civetweb will copy the value from *ssl_ctx to the civetweb context
267 	        and doesn't create its own.
268 	    -1: initializing ssl fails.*/
269 	int (*external_ssl_ctx)(void **ssl_ctx, void *user_data);
270 
271 #if defined(MG_LEGACY_INTERFACE) /* 2015-08-19 */
272 	/* Called when websocket request is received, before websocket handshake.
273 	   Return value:
274 	     0: civetweb proceeds with websocket handshake.
275 	     1: connection is closed immediately.
276 	   This callback is deprecated: Use mg_set_websocket_handler instead. */
277 	int (*websocket_connect)(const struct mg_connection *);
278 
279 	/* Called when websocket handshake is successfully completed, and
280 	   connection is ready for data exchange.
281 	   This callback is deprecated: Use mg_set_websocket_handler instead. */
282 	void (*websocket_ready)(struct mg_connection *);
283 
284 	/* Called when data frame has been received from the client.
285 	   Parameters:
286 	     bits: first byte of the websocket frame, see websocket RFC at
287 	           http://tools.ietf.org/html/rfc6455, section 5.2
288 	     data, data_len: payload, with mask (if any) already applied.
289 	   Return value:
290 	     1: keep this websocket connection open.
291 	     0: close this websocket connection.
292 	   This callback is deprecated: Use mg_set_websocket_handler instead. */
293 	int (*websocket_data)(struct mg_connection *,
294 	                      int bits,
295 	                      char *data,
296 	                      size_t data_len);
297 #endif /* MG_LEGACY_INTERFACE */
298 
299 	/* Called when civetweb is closing a connection.  The per-context mutex is
300 	   locked when this is invoked.
301 
302 	   Websockets:
303 	   Before mg_set_websocket_handler has been added, it was primarily useful
304 	   for noting when a websocket is closing, and used to remove it from any
305 	   application-maintained list of clients.
306 	   Using this callback for websocket connections is deprecated: Use
307 	   mg_set_websocket_handler instead.
308 
309 	   Connection specific data:
310 	   If memory has been allocated for the connection specific user data
311 	   (mg_request_info->conn_data, mg_get_user_connection_data),
312 	   this is the last chance to free it.
313 	*/
314 	void (*connection_close)(const struct mg_connection *);
315 
316 	/* Called when civetweb is about to serve Lua server page, if
317 	   Lua support is enabled.
318 	   Parameters:
319 	     conn: current connection.
320 	     lua_context: "lua_State *" pointer. */
321 	void (*init_lua)(const struct mg_connection *conn, void *lua_context);
322 
323 #if defined(MG_LEGACY_INTERFACE) /* 2016-05-14 */
324 	/* Called when civetweb has uploaded a file to a temporary directory as a
325 	   result of mg_upload() call.
326 	   Note that mg_upload is deprecated. Use mg_handle_form_request instead.
327 	   Parameters:
328 	     file_name: full path name to the uploaded file. */
329 	void (*upload)(struct mg_connection *, const char *file_name);
330 #endif
331 
332 	/* Called when civetweb is about to send HTTP error to the client.
333 	   Implementing this callback allows to create custom error pages.
334 	   Parameters:
335 	     conn: current connection.
336 	     status: HTTP error status code.
337 	     errmsg: error message text.
338 	   Return value:
339 	     1: run civetweb error handler.
340 	     0: callback already handled the error. */
341 	int (*http_error)(struct mg_connection *conn,
342 	                  int status,
343 	                  const char *errmsg);
344 
345 	/* Called after civetweb context has been created, before requests
346 	   are processed.
347 	   Parameters:
348 	     ctx: context handle */
349 	void (*init_context)(const struct mg_context *ctx);
350 
351 	/* Called when civetweb context is deleted.
352 	Parameters:
353 	ctx: context handle */
354 	void (*exit_context)(const struct mg_context *ctx);
355 
356 	/* Called when a new worker thread is initialized.
357 	 * Parameters:
358 	 *   ctx: context handle
359 	 *   thread_type:
360 	 *     0 indicates the master thread
361 	 *     1 indicates a worker thread handling client connections
362 	 *     2 indicates an internal helper thread (timer thread)
363 	 * Return value:
364 	 *   This function returns a user supplied pointer. The pointer is assigned
365 	 *   to the thread and can be obtained from the mg_connection object using
366 	 *   mg_get_thread_pointer in all server callbacks. Note: A connection and
367 	 *   a thread are not directly related. Threads will serve several different
368 	 *   connections, and data from a single connection may call different
369 	 *   callbacks using different threads. The thread pointer can be obtained
370 	 *   in a callback handler, but should not be stored beyond the scope of
371 	 *   one call to one callback.
372 	 */
373 	void *(*init_thread)(const struct mg_context *ctx, int thread_type);
374 
375 	/* Called when a worker exits.
376 	 * The parameters "ctx" and "thread_type" correspond to the "init_thread"
377 	 * call. The  "thread_pointer" parameter is the value returned by
378 	 * "init_thread".
379 	 */
380 	void (*exit_thread)(const struct mg_context *ctx,
381 	                    int thread_type,
382 	                    void *thread_pointer);
383 
384 
385 	/* Called when initializing a new connection object.
386 	 * Can be used to initialize the connection specific user data
387 	 * (mg_request_info->conn_data, mg_get_user_connection_data).
388 	 * When the callback is called, it is not yet known if a
389 	 * valid HTTP(S) request will be made.
390 	 * Parameters:
391 	 *   conn: not yet fully initialized connection object
392 	 *   conn_data: output parameter, set to initialize the
393 	 *              connection specific user data
394 	 * Return value:
395 	 *   must be 0
396 	 *   Otherwise, the result is undefined
397 	 */
398 	int (*init_connection)(const struct mg_connection *conn, void **conn_data);
399 };
400 
401 
402 /* Start web server.
403 
404    Parameters:
405      callbacks: mg_callbacks structure with user-defined callbacks.
406      options: NULL terminated list of option_name, option_value pairs that
407               specify Civetweb configuration parameters.
408 
409    Side-effects: on UNIX, ignores SIGCHLD and SIGPIPE signals. If custom
410       processing is required for these, signal handlers must be set up
411       after calling mg_start().
412 
413 
414    Example:
415      const char *options[] = {
416        "document_root", "/var/www",
417        "listening_ports", "80,443s",
418        NULL
419      };
420      struct mg_context *ctx = mg_start(&my_func, NULL, options);
421 
422    Refer to https://github.com/civetweb/civetweb/blob/master/docs/UserManual.md
423    for the list of valid option and their possible values.
424 
425    Return:
426      web server context, or NULL on error. */
427 CIVETWEB_API struct mg_context *mg_start(const struct mg_callbacks *callbacks,
428                                          void *user_data,
429                                          const char **configuration_options);
430 
431 
432 /* Stop the web server.
433 
434    Must be called last, when an application wants to stop the web server and
435    release all associated resources. This function blocks until all Civetweb
436    threads are stopped. Context pointer becomes invalid. */
437 CIVETWEB_API void mg_stop(struct mg_context *);
438 
439 
440 #if defined(MG_EXPERIMENTAL_INTERFACES)
441 /* Add an additional domain to an already running web server.
442  *
443  * Parameters:
444  *   ctx: Context handle of a server started by mg_start.
445  *   options: NULL terminated list of option_name, option_value pairs that
446  *            specify CivetWeb configuration parameters.
447  *
448  * Return:
449  *   < 0 in case of an error
450  *    -1 for a parameter error
451  *    -2 invalid options
452  *    -3 initializing SSL failed
453  *    -4 mandatory domain option missing
454  *    -5 duplicate domain
455  *    -6 out of memory
456  *   > 0 index / handle of a new domain
457  */
458 CIVETWEB_API int mg_start_domain(struct mg_context *ctx,
459                                  const char **configuration_options);
460 #endif
461 
462 
463 /* mg_request_handler
464 
465    Called when a new request comes in.  This callback is URI based
466    and configured with mg_set_request_handler().
467 
468    Parameters:
469       conn: current connection information.
470       cbdata: the callback data configured with mg_set_request_handler().
471    Returns:
472       0: the handler could not handle the request, so fall through.
473       1 - 999: the handler processed the request. The return code is
474                stored as a HTTP status code for the access log. */
475 typedef int (*mg_request_handler)(struct mg_connection *conn, void *cbdata);
476 
477 
478 /* mg_set_request_handler
479 
480    Sets or removes a URI mapping for a request handler.
481    This function uses mg_lock_context internally.
482 
483    URI's are ordered and prefixed URI's are supported. For example,
484    consider two URIs: /a/b and /a
485            /a   matches /a
486            /a/b matches /a/b
487            /a/c matches /a
488 
489    Parameters:
490       ctx: server context
491       uri: the URI (exact or pattern) for the handler
492       handler: the callback handler to use when the URI is requested.
493                If NULL, an already registered handler for this URI will
494                be removed.
495                The URI used to remove a handler must match exactly the
496                one used to register it (not only a pattern match).
497       cbdata: the callback data to give to the handler when it is called. */
498 CIVETWEB_API void mg_set_request_handler(struct mg_context *ctx,
499                                          const char *uri,
500                                          mg_request_handler handler,
501                                          void *cbdata);
502 
503 
504 /* Callback types for websocket handlers in C/C++.
505 
506    mg_websocket_connect_handler
507        Is called when the client intends to establish a websocket connection,
508        before websocket handshake.
509        Return value:
510          0: civetweb proceeds with websocket handshake.
511          1: connection is closed immediately.
512 
513    mg_websocket_ready_handler
514        Is called when websocket handshake is successfully completed, and
515        connection is ready for data exchange.
516 
517    mg_websocket_data_handler
518        Is called when a data frame has been received from the client.
519        Parameters:
520          bits: first byte of the websocket frame, see websocket RFC at
521                http://tools.ietf.org/html/rfc6455, section 5.2
522          data, data_len: payload, with mask (if any) already applied.
523        Return value:
524          1: keep this websocket connection open.
525          0: close this websocket connection.
526 
527    mg_connection_close_handler
528        Is called, when the connection is closed.*/
529 typedef int (*mg_websocket_connect_handler)(const struct mg_connection *,
530                                             void *);
531 typedef void (*mg_websocket_ready_handler)(struct mg_connection *, void *);
532 typedef int (*mg_websocket_data_handler)(struct mg_connection *,
533                                          int,
534                                          char *,
535                                          size_t,
536                                          void *);
537 typedef void (*mg_websocket_close_handler)(const struct mg_connection *,
538                                            void *);
539 
540 /* struct mg_websocket_subprotocols
541  *
542  * List of accepted subprotocols
543  */
544 struct mg_websocket_subprotocols {
545 	int nb_subprotocols;
546 	char **subprotocols;
547 };
548 
549 /* mg_set_websocket_handler
550 
551    Set or remove handler functions for websocket connections.
552    This function works similar to mg_set_request_handler - see there. */
553 CIVETWEB_API void
554 mg_set_websocket_handler(struct mg_context *ctx,
555                          const char *uri,
556                          mg_websocket_connect_handler connect_handler,
557                          mg_websocket_ready_handler ready_handler,
558                          mg_websocket_data_handler data_handler,
559                          mg_websocket_close_handler close_handler,
560                          void *cbdata);
561 
562 /* mg_set_websocket_handler
563 
564    Set or remove handler functions for websocket connections.
565    This function works similar to mg_set_request_handler - see there. */
566 CIVETWEB_API void mg_set_websocket_handler_with_subprotocols(
567     struct mg_context *ctx,
568     const char *uri,
569     struct mg_websocket_subprotocols *subprotocols,
570     mg_websocket_connect_handler connect_handler,
571     mg_websocket_ready_handler ready_handler,
572     mg_websocket_data_handler data_handler,
573     mg_websocket_close_handler close_handler,
574     void *cbdata);
575 
576 
577 /* mg_authorization_handler
578 
579    Callback function definition for mg_set_auth_handler
580 
581    Parameters:
582       conn: current connection information.
583       cbdata: the callback data configured with mg_set_request_handler().
584    Returns:
585       0: access denied
586       1: access granted
587  */
588 typedef int (*mg_authorization_handler)(struct mg_connection *conn,
589                                         void *cbdata);
590 
591 
592 /* mg_set_auth_handler
593 
594    Sets or removes a URI mapping for an authorization handler.
595    This function works similar to mg_set_request_handler - see there. */
596 CIVETWEB_API void mg_set_auth_handler(struct mg_context *ctx,
597                                       const char *uri,
598                                       mg_authorization_handler handler,
599                                       void *cbdata);
600 
601 
602 /* Get the value of particular configuration parameter.
603    The value returned is read-only. Civetweb does not allow changing
604    configuration at run time.
605    If given parameter name is not valid, NULL is returned. For valid
606    names, return value is guaranteed to be non-NULL. If parameter is not
607    set, zero-length string is returned. */
608 CIVETWEB_API const char *mg_get_option(const struct mg_context *ctx,
609                                        const char *name);
610 
611 
612 /* Get context from connection. */
613 CIVETWEB_API struct mg_context *
614 mg_get_context(const struct mg_connection *conn);
615 
616 
617 /* Get user data passed to mg_start from context. */
618 CIVETWEB_API void *mg_get_user_data(const struct mg_context *ctx);
619 
620 
621 /* Get user defined thread pointer for server threads (see init_thread). */
622 CIVETWEB_API void *mg_get_thread_pointer(const struct mg_connection *conn);
623 
624 
625 /* Set user data for the current connection. */
626 /* Note: This function is deprecated. Use the init_connection callback
627    instead to initialize the user connection data pointer. It is
628    reccomended to supply a pointer to some user defined data structure
629    as conn_data initializer in init_connection. In case it is required
630    to change some data after the init_connection call, store another
631    data pointer in the user defined data structure and modify that
632    pointer. In either case, after the init_connection callback, only
633    calls to mg_get_user_connection_data should be required. */
634 CIVETWEB_API void mg_set_user_connection_data(struct mg_connection *conn,
635                                               void *data);
636 
637 
638 /* Get user data set for the current connection. */
639 CIVETWEB_API void *
640 mg_get_user_connection_data(const struct mg_connection *conn);
641 
642 
643 /* Get a formatted link corresponding to the current request
644 
645    Parameters:
646       conn: current connection information.
647       buf: string buffer (out)
648       buflen: length of the string buffer
649    Returns:
650       <0: error
651       >=0: ok */
652 CIVETWEB_API int
653 mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen);
654 
655 
656 #if defined(MG_LEGACY_INTERFACE) /* 2014-02-21 */
657 /* Return array of strings that represent valid configuration options.
658    For each option, option name and default value is returned, i.e. the
659    number of entries in the array equals to number_of_options x 2.
660    Array is NULL terminated. */
661 /* Deprecated: Use mg_get_valid_options instead. */
662 CIVETWEB_API const char **mg_get_valid_option_names(void);
663 #endif
664 
665 
666 struct mg_option {
667 	const char *name;
668 	int type;
669 	const char *default_value;
670 };
671 
672 /* Old nomenclature */
673 #if defined(MG_LEGACY_INTERFACE) /* 2017-10-05 */
674 enum {
675 	CONFIG_TYPE_UNKNOWN = 0x0,
676 	CONFIG_TYPE_NUMBER = 0x1,
677 	CONFIG_TYPE_STRING = 0x2,
678 	CONFIG_TYPE_FILE = 0x3,
679 	CONFIG_TYPE_DIRECTORY = 0x4,
680 	CONFIG_TYPE_BOOLEAN = 0x5,
681 	CONFIG_TYPE_EXT_PATTERN = 0x6,
682 	CONFIG_TYPE_STRING_LIST = 0x7,
683 	CONFIG_TYPE_STRING_MULTILINE = 0x8
684 };
685 #endif
686 
687 /* New nomenclature */
688 enum {
689 	MG_CONFIG_TYPE_UNKNOWN = 0x0,
690 	MG_CONFIG_TYPE_NUMBER = 0x1,
691 	MG_CONFIG_TYPE_STRING = 0x2,
692 	MG_CONFIG_TYPE_FILE = 0x3,
693 	MG_CONFIG_TYPE_DIRECTORY = 0x4,
694 	MG_CONFIG_TYPE_BOOLEAN = 0x5,
695 	MG_CONFIG_TYPE_EXT_PATTERN = 0x6,
696 	MG_CONFIG_TYPE_STRING_LIST = 0x7,
697 	MG_CONFIG_TYPE_STRING_MULTILINE = 0x8,
698 	MG_CONFIG_TYPE_YES_NO_OPTIONAL = 0x9
699 };
700 
701 /* Return array of struct mg_option, representing all valid configuration
702    options of civetweb.c.
703    The array is terminated by a NULL name option. */
704 CIVETWEB_API const struct mg_option *mg_get_valid_options(void);
705 
706 
707 struct mg_server_port {
708 	int protocol;    /* 1 = IPv4, 2 = IPv6, 3 = both */
709 	int port;        /* port number */
710 	int is_ssl;      /* https port: 0 = no, 1 = yes */
711 	int is_redirect; /* redirect all requests: 0 = no, 1 = yes */
712 	int _reserved1;
713 	int _reserved2;
714 	int _reserved3;
715 	int _reserved4;
716 };
717 
718 /* Legacy name */
719 #define mg_server_ports mg_server_port
720 
721 
722 /* Get the list of ports that civetweb is listening on.
723    The parameter size is the size of the ports array in elements.
724    The caller is responsibility to allocate the required memory.
725    This function returns the number of struct mg_server_port elements
726    filled in, or <0 in case of an error. */
727 CIVETWEB_API int mg_get_server_ports(const struct mg_context *ctx,
728                                      int size,
729                                      struct mg_server_port *ports);
730 
731 
732 #if defined(MG_LEGACY_INTERFACE) /* 2017-04-02 */
733 /* Deprecated: Use mg_get_server_ports instead. */
734 CIVETWEB_API size_t mg_get_ports(const struct mg_context *ctx,
735                                  size_t size,
736                                  int *ports,
737                                  int *ssl);
738 #endif
739 
740 
741 /* Add, edit or delete the entry in the passwords file.
742  *
743  * This function allows an application to manipulate .htpasswd files on the
744  * fly by adding, deleting and changing user records. This is one of the
745  * several ways of implementing authentication on the server side. For another,
746  * cookie-based way please refer to the examples/chat in the source tree.
747  *
748  * Parameter:
749  *   passwords_file_name: Path and name of a file storing multiple passwords
750  *   realm: HTTP authentication realm (authentication domain) name
751  *   user: User name
752  *   password:
753  *     If password is not NULL, entry modified or added.
754  *     If password is NULL, entry is deleted.
755  *
756  *  Return:
757  *    1 on success, 0 on error.
758  */
759 CIVETWEB_API int mg_modify_passwords_file(const char *passwords_file_name,
760                                           const char *realm,
761                                           const char *user,
762                                           const char *password);
763 
764 
765 /* Return information associated with the request.
766  * Use this function to implement a server and get data about a request
767  * from a HTTP/HTTPS client.
768  * Note: Before CivetWeb 1.10, this function could be used to read
769  * a response from a server, when implementing a client, although the
770  * values were never returned in appropriate mg_request_info elements.
771  * It is strongly advised to use mg_get_response_info for clients.
772  */
773 CIVETWEB_API const struct mg_request_info *
774 mg_get_request_info(const struct mg_connection *);
775 
776 
777 /* Return information associated with a HTTP/HTTPS response.
778  * Use this function in a client, to check the response from
779  * the server. */
780 CIVETWEB_API const struct mg_response_info *
781 mg_get_response_info(const struct mg_connection *);
782 
783 
784 /* Send data to the client.
785    Return:
786     0   when the connection has been closed
787     -1  on error
788     >0  number of bytes written on success */
789 CIVETWEB_API int mg_write(struct mg_connection *, const void *buf, size_t len);
790 
791 
792 /* Send data to a websocket client wrapped in a websocket frame.  Uses
793    mg_lock_connection to ensure that the transmission is not interrupted,
794    i.e., when the application is proactively communicating and responding to
795    a request simultaneously.
796 
797    Send data to a websocket client wrapped in a websocket frame.
798    This function is available when civetweb is compiled with -DUSE_WEBSOCKET
799 
800    Return:
801     0   when the connection has been closed
802     -1  on error
803     >0  number of bytes written on success */
804 CIVETWEB_API int mg_websocket_write(struct mg_connection *conn,
805                                     int opcode,
806                                     const char *data,
807                                     size_t data_len);
808 
809 
810 /* Send data to a websocket server wrapped in a masked websocket frame.  Uses
811    mg_lock_connection to ensure that the transmission is not interrupted,
812    i.e., when the application is proactively communicating and responding to
813    a request simultaneously.
814 
815    Send data to a websocket server wrapped in a masked websocket frame.
816    This function is available when civetweb is compiled with -DUSE_WEBSOCKET
817 
818    Return:
819     0   when the connection has been closed
820     -1  on error
821     >0  number of bytes written on success */
822 CIVETWEB_API int mg_websocket_client_write(struct mg_connection *conn,
823                                            int opcode,
824                                            const char *data,
825                                            size_t data_len);
826 
827 
828 /* Blocks until unique access is obtained to this connection. Intended for use
829    with websockets only.
830    Invoke this before mg_write or mg_printf when communicating with a
831    websocket if your code has server-initiated communication as well as
832    communication in direct response to a message. */
833 CIVETWEB_API void mg_lock_connection(struct mg_connection *conn);
834 CIVETWEB_API void mg_unlock_connection(struct mg_connection *conn);
835 
836 
837 #if defined(MG_LEGACY_INTERFACE) /* 2014-06-21 */
838 #define mg_lock mg_lock_connection
839 #define mg_unlock mg_unlock_connection
840 #endif
841 
842 
843 /* Lock server context.  This lock may be used to protect resources
844    that are shared between different connection/worker threads. */
845 CIVETWEB_API void mg_lock_context(struct mg_context *ctx);
846 CIVETWEB_API void mg_unlock_context(struct mg_context *ctx);
847 
848 
849 /* Opcodes, from http://tools.ietf.org/html/rfc6455 */
850 #if defined(MG_LEGACY_INTERFACE) /* 2017-10-05 */
851 enum {
852 	WEBSOCKET_OPCODE_CONTINUATION = 0x0,
853 	WEBSOCKET_OPCODE_TEXT = 0x1,
854 	WEBSOCKET_OPCODE_BINARY = 0x2,
855 	WEBSOCKET_OPCODE_CONNECTION_CLOSE = 0x8,
856 	WEBSOCKET_OPCODE_PING = 0x9,
857 	WEBSOCKET_OPCODE_PONG = 0xa
858 };
859 #endif
860 
861 /* New nomenclature */
862 enum {
863 	MG_WEBSOCKET_OPCODE_CONTINUATION = 0x0,
864 	MG_WEBSOCKET_OPCODE_TEXT = 0x1,
865 	MG_WEBSOCKET_OPCODE_BINARY = 0x2,
866 	MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE = 0x8,
867 	MG_WEBSOCKET_OPCODE_PING = 0x9,
868 	MG_WEBSOCKET_OPCODE_PONG = 0xa
869 };
870 
871 /* Macros for enabling compiler-specific checks for printf-like arguments. */
872 #undef PRINTF_FORMAT_STRING
873 #if defined(_MSC_VER) && _MSC_VER >= 1400
874 #include <sal.h>
875 #if defined(_MSC_VER) && _MSC_VER > 1400
876 #define PRINTF_FORMAT_STRING(s) _Printf_format_string_ s
877 #else
878 #define PRINTF_FORMAT_STRING(s) __format_string s
879 #endif
880 #else
881 #define PRINTF_FORMAT_STRING(s) s
882 #endif
883 
884 #ifdef __GNUC__
885 #define PRINTF_ARGS(x, y) __attribute__((format(printf, x, y)))
886 #else
887 #define PRINTF_ARGS(x, y)
888 #endif
889 
890 
891 /* Send data to the client using printf() semantics.
892    Works exactly like mg_write(), but allows to do message formatting. */
893 CIVETWEB_API int mg_printf(struct mg_connection *,
894                            PRINTF_FORMAT_STRING(const char *fmt),
895                            ...) PRINTF_ARGS(2, 3);
896 
897 
898 /* Send a part of the message body, if chunked transfer encoding is set.
899  * Only use this function after sending a complete HTTP request or response
900  * header with "Transfer-Encoding: chunked" set. */
901 CIVETWEB_API int mg_send_chunk(struct mg_connection *conn,
902                                const char *chunk,
903                                unsigned int chunk_len);
904 
905 
906 /* Send contents of the entire file together with HTTP headers.
907  * Parameters:
908  *   conn: Current connection information.
909  *   path: Full path to the file to send.
910  * This function has been superseded by mg_send_mime_file
911  */
912 CIVETWEB_API void mg_send_file(struct mg_connection *conn, const char *path);
913 
914 
915 /* Send contents of the file without HTTP headers.
916  * The code must send a valid HTTP response header before using this function.
917  *
918  * Parameters:
919  *   conn: Current connection information.
920  *   path: Full path to the file to send.
921  *
922  * Return:
923  *   < 0   Error
924  */
925 CIVETWEB_API int mg_send_file_body(struct mg_connection *conn,
926                                    const char *path);
927 
928 
929 /* Send HTTP error reply. */
930 CIVETWEB_API int mg_send_http_error(struct mg_connection *conn,
931                                     int status_code,
932                                     PRINTF_FORMAT_STRING(const char *fmt),
933                                     ...) PRINTF_ARGS(3, 4);
934 
935 
936 /* Send "HTTP 200 OK" response header.
937  * After calling this function, use mg_write or mg_send_chunk to send the
938  * response body.
939  * Parameters:
940  *   conn: Current connection handle.
941  *   mime_type: Set Content-Type for the following content.
942  *   content_length: Size of the following content, if content_length >= 0.
943  *                   Will set transfer-encoding to chunked, if set to -1.
944  * Return:
945  *   < 0   Error
946  */
947 CIVETWEB_API int mg_send_http_ok(struct mg_connection *conn,
948                                  const char *mime_type,
949                                  long long content_length);
950 
951 
952 /* Send "HTTP 30x" redirect response.
953  * The response has content-size zero: do not send any body data after calling
954  * this function.
955  * Parameters:
956  *   conn: Current connection handle.
957  *   target_url: New location.
958  *   redirect_code: HTTP redirect type. Could be 301, 302, 303, 307, 308.
959  * Return:
960  *   < 0   Error (-1 send error, -2 parameter error)
961  */
962 CIVETWEB_API int mg_send_http_redirect(struct mg_connection *conn,
963                                        const char *target_url,
964                                        int redirect_code);
965 
966 
967 /* Send HTTP digest access authentication request.
968  * Browsers will send a user name and password in their next request, showing
969  * an authentication dialog if the password is not stored.
970  * Parameters:
971  *   conn: Current connection handle.
972  *   realm: Authentication realm. If NULL is supplied, the sever domain
973  *          set in the authentication_domain configuration is used.
974  * Return:
975  *   < 0   Error
976  */
977 CIVETWEB_API int
978 mg_send_digest_access_authentication_request(struct mg_connection *conn,
979                                              const char *realm);
980 
981 
982 /* Check if the current request has a valid authentication token set.
983  * A file is used to provide a list of valid user names, realms and
984  * password hashes. The file can be created and modified using the
985  * mg_modify_passwords_file API function.
986  * Parameters:
987  *   conn: Current connection handle.
988  *   realm: Authentication realm. If NULL is supplied, the sever domain
989  *          set in the authentication_domain configuration is used.
990  *   filename: Path and name of a file storing multiple password hashes.
991  * Return:
992  *   > 0   Valid authentication
993  *   0     Invalid authentication
994  *   < 0   Error (all values < 0 should be considered as invalid
995  *         authentication, future error codes will have negative
996  *         numbers)
997  *   -1    Parameter error
998  *   -2    File not found
999  */
1000 CIVETWEB_API int
1001 mg_check_digest_access_authentication(struct mg_connection *conn,
1002                                       const char *realm,
1003                                       const char *filename);
1004 
1005 
1006 /* Send contents of the entire file together with HTTP headers.
1007  * Parameters:
1008  *   conn: Current connection handle.
1009  *   path: Full path to the file to send.
1010  *   mime_type: Content-Type for file.  NULL will cause the type to be
1011  *              looked up by the file extension.
1012  */
1013 CIVETWEB_API void mg_send_mime_file(struct mg_connection *conn,
1014                                     const char *path,
1015                                     const char *mime_type);
1016 
1017 
1018 /* Send contents of the entire file together with HTTP headers.
1019    Parameters:
1020      conn: Current connection information.
1021      path: Full path to the file to send.
1022      mime_type: Content-Type for file.  NULL will cause the type to be
1023                 looked up by the file extension.
1024      additional_headers: Additional custom header fields appended to the header.
1025                          Each header should start with an X-, to ensure it is
1026                          not included twice.
1027                          NULL does not append anything.
1028 */
1029 CIVETWEB_API void mg_send_mime_file2(struct mg_connection *conn,
1030                                      const char *path,
1031                                      const char *mime_type,
1032                                      const char *additional_headers);
1033 
1034 
1035 /* Store body data into a file. */
1036 CIVETWEB_API long long mg_store_body(struct mg_connection *conn,
1037                                      const char *path);
1038 /* Read entire request body and store it in a file "path".
1039    Return:
1040      < 0   Error
1041      >= 0  Number of bytes stored in file "path".
1042 */
1043 
1044 
1045 /* Read data from the remote end, return number of bytes read.
1046    Return:
1047      0     connection has been closed by peer. No more data could be read.
1048      < 0   read error. No more data could be read from the connection.
1049      > 0   number of bytes read into the buffer. */
1050 CIVETWEB_API int mg_read(struct mg_connection *, void *buf, size_t len);
1051 
1052 
1053 /* Get the value of particular HTTP header.
1054 
1055    This is a helper function. It traverses request_info->http_headers array,
1056    and if the header is present in the array, returns its value. If it is
1057    not present, NULL is returned. */
1058 CIVETWEB_API const char *mg_get_header(const struct mg_connection *,
1059                                        const char *name);
1060 
1061 
1062 /* Get a value of particular form variable.
1063 
1064    Parameters:
1065      data: pointer to form-uri-encoded buffer. This could be either POST data,
1066            or request_info.query_string.
1067      data_len: length of the encoded data.
1068      var_name: variable name to decode from the buffer
1069      dst: destination buffer for the decoded variable
1070      dst_len: length of the destination buffer
1071 
1072    Return:
1073      On success, length of the decoded variable.
1074      On error:
1075         -1 (variable not found).
1076         -2 (destination buffer is NULL, zero length or too small to hold the
1077             decoded variable).
1078 
1079    Destination buffer is guaranteed to be '\0' - terminated if it is not
1080    NULL or zero length. */
1081 CIVETWEB_API int mg_get_var(const char *data,
1082                             size_t data_len,
1083                             const char *var_name,
1084                             char *dst,
1085                             size_t dst_len);
1086 
1087 
1088 /* Get a value of particular form variable.
1089 
1090    Parameters:
1091      data: pointer to form-uri-encoded buffer. This could be either POST data,
1092            or request_info.query_string.
1093      data_len: length of the encoded data.
1094      var_name: variable name to decode from the buffer
1095      dst: destination buffer for the decoded variable
1096      dst_len: length of the destination buffer
1097      occurrence: which occurrence of the variable, 0 is the first, 1 the
1098                  second...
1099                 this makes it possible to parse a query like
1100                 b=x&a=y&a=z which will have occurrence values b:0, a:0 and a:1
1101 
1102    Return:
1103      On success, length of the decoded variable.
1104      On error:
1105         -1 (variable not found).
1106         -2 (destination buffer is NULL, zero length or too small to hold the
1107             decoded variable).
1108 
1109    Destination buffer is guaranteed to be '\0' - terminated if it is not
1110    NULL or zero length. */
1111 CIVETWEB_API int mg_get_var2(const char *data,
1112                              size_t data_len,
1113                              const char *var_name,
1114                              char *dst,
1115                              size_t dst_len,
1116                              size_t occurrence);
1117 
1118 
1119 /* Fetch value of certain cookie variable into the destination buffer.
1120 
1121    Destination buffer is guaranteed to be '\0' - terminated. In case of
1122    failure, dst[0] == '\0'. Note that RFC allows many occurrences of the same
1123    parameter. This function returns only first occurrence.
1124 
1125    Return:
1126      On success, value length.
1127      On error:
1128         -1 (either "Cookie:" header is not present at all or the requested
1129             parameter is not found).
1130         -2 (destination buffer is NULL, zero length or too small to hold the
1131             value). */
1132 CIVETWEB_API int mg_get_cookie(const char *cookie,
1133                                const char *var_name,
1134                                char *buf,
1135                                size_t buf_len);
1136 
1137 
1138 /* Download data from the remote web server.
1139      host: host name to connect to, e.g. "foo.com", or "10.12.40.1".
1140      port: port number, e.g. 80.
1141      use_ssl: whether to use SSL connection.
1142      error_buffer, error_buffer_size: error message placeholder.
1143      request_fmt,...: HTTP request.
1144    Return:
1145      On success, valid pointer to the new connection, suitable for mg_read().
1146      On error, NULL. error_buffer contains error message.
1147    Example:
1148      char ebuf[100];
1149      struct mg_connection *conn;
1150      conn = mg_download("google.com", 80, 0, ebuf, sizeof(ebuf),
1151                         "%s", "GET / HTTP/1.0\r\nHost: google.com\r\n\r\n");
1152  */
1153 CIVETWEB_API struct mg_connection *
1154 mg_download(const char *host,
1155             int port,
1156             int use_ssl,
1157             char *error_buffer,
1158             size_t error_buffer_size,
1159             PRINTF_FORMAT_STRING(const char *request_fmt),
1160             ...) PRINTF_ARGS(6, 7);
1161 
1162 
1163 /* Close the connection opened by mg_download(). */
1164 CIVETWEB_API void mg_close_connection(struct mg_connection *conn);
1165 
1166 
1167 #if defined(MG_LEGACY_INTERFACE) /* 2016-05-14 */
1168 /* File upload functionality. Each uploaded file gets saved into a temporary
1169    file and MG_UPLOAD event is sent.
1170    Return number of uploaded files.
1171    Deprecated: Use mg_handle_form_request instead. */
1172 CIVETWEB_API int mg_upload(struct mg_connection *conn,
1173                            const char *destination_dir);
1174 #endif
1175 
1176 
1177 /* This structure contains callback functions for handling form fields.
1178    It is used as an argument to mg_handle_form_request. */
1179 struct mg_form_data_handler {
1180 	/* This callback function is called, if a new field has been found.
1181 	 * The return value of this callback is used to define how the field
1182 	 * should be processed.
1183 	 *
1184 	 * Parameters:
1185 	 *   key: Name of the field ("name" property of the HTML input field).
1186 	 *   filename: Name of a file to upload, at the client computer.
1187 	 *             Only set for input fields of type "file", otherwise NULL.
1188 	 *   path: Output parameter: File name (incl. path) to store the file
1189 	 *         at the server computer. Only used if FORM_FIELD_STORAGE_STORE
1190 	 *         is returned by this callback. Existing files will be
1191 	 *         overwritten.
1192 	 *   pathlen: Length of the buffer for path.
1193 	 *   user_data: Value of the member user_data of mg_form_data_handler
1194 	 *
1195 	 * Return value:
1196 	 *   The callback must return the intended storage for this field
1197 	 *   (See FORM_FIELD_STORAGE_*).
1198 	 */
1199 	int (*field_found)(const char *key,
1200 	                   const char *filename,
1201 	                   char *path,
1202 	                   size_t pathlen,
1203 	                   void *user_data);
1204 
1205 	/* If the "field_found" callback returned FORM_FIELD_STORAGE_GET,
1206 	 * this callback will receive the field data.
1207 	 *
1208 	 * Parameters:
1209 	 *   key: Name of the field ("name" property of the HTML input field).
1210 	 *   value: Value of the input field.
1211 	 *   user_data: Value of the member user_data of mg_form_data_handler
1212 	 *
1213 	 * Return value:
1214 	 *   The return code determines how the server should continue processing
1215 	 *   the current request (See MG_FORM_FIELD_HANDLE_*).
1216 	 */
1217 	int (*field_get)(const char *key,
1218 	                 const char *value,
1219 	                 size_t valuelen,
1220 	                 void *user_data);
1221 
1222 	/* If the "field_found" callback returned FORM_FIELD_STORAGE_STORE,
1223 	 * the data will be stored into a file. If the file has been written
1224 	 * successfully, this callback will be called. This callback will
1225 	 * not be called for only partially uploaded files. The
1226 	 * mg_handle_form_request function will either store the file completely
1227 	 * and call this callback, or it will remove any partial content and
1228 	 * not call this callback function.
1229 	 *
1230 	 * Parameters:
1231 	 *   path: Path of the file stored at the server.
1232 	 *   file_size: Size of the stored file in bytes.
1233 	 *   user_data: Value of the member user_data of mg_form_data_handler
1234 	 *
1235 	 * Return value:
1236 	 *   The return code determines how the server should continue processing
1237 	 *   the current request (See MG_FORM_FIELD_HANDLE_*).
1238 	 */
1239 	int (*field_store)(const char *path, long long file_size, void *user_data);
1240 
1241 	/* User supplied argument, passed to all callback functions. */
1242 	void *user_data;
1243 };
1244 
1245 
1246 /* Return values definition for the "field_found" callback in
1247  * mg_form_data_handler. */
1248 #if defined(MG_LEGACY_INTERFACE) /* 2017-10-05 */
1249 enum {
1250 	/* Skip this field (neither get nor store it). Continue with the
1251 	 * next field. */
1252 	FORM_FIELD_STORAGE_SKIP = 0x0,
1253 	/* Get the field value. */
1254 	FORM_FIELD_STORAGE_GET = 0x1,
1255 	/* Store the field value into a file. */
1256 	FORM_FIELD_STORAGE_STORE = 0x2,
1257 	/* Stop parsing this request. Skip the remaining fields. */
1258 	FORM_FIELD_STORAGE_ABORT = 0x10
1259 };
1260 #endif
1261 /* New nomenclature */
1262 enum {
1263 	/* Skip this field (neither get nor store it). Continue with the
1264 	 * next field. */
1265 	MG_FORM_FIELD_STORAGE_SKIP = 0x0,
1266 	/* Get the field value. */
1267 	MG_FORM_FIELD_STORAGE_GET = 0x1,
1268 	/* Store the field value into a file. */
1269 	MG_FORM_FIELD_STORAGE_STORE = 0x2,
1270 	/* Stop parsing this request. Skip the remaining fields. */
1271 	MG_FORM_FIELD_STORAGE_ABORT = 0x10
1272 };
1273 
1274 /* Return values for "field_get" and "field_store" */
1275 enum {
1276 	/* Only "field_get": If there is more data in this field, get the next
1277 	 * chunk. Otherwise: handle the next field. */
1278 	MG_FORM_FIELD_HANDLE_GET = 0x1,
1279 	/* Handle the next field */
1280 	MG_FORM_FIELD_HANDLE_NEXT = 0x8,
1281 	/* Stop parsing this request */
1282 	MG_FORM_FIELD_HANDLE_ABORT = 0x10
1283 };
1284 
1285 
1286 /* Process form data.
1287  * Returns the number of fields handled, or < 0 in case of an error.
1288  * Note: It is possible that several fields are already handled successfully
1289  * (e.g., stored into files), before the request handling is stopped with an
1290  * error. In this case a number < 0 is returned as well.
1291  * In any case, it is the duty of the caller to remove files once they are
1292  * no longer required. */
1293 CIVETWEB_API int mg_handle_form_request(struct mg_connection *conn,
1294                                         struct mg_form_data_handler *fdh);
1295 
1296 
1297 /* Convenience function -- create detached thread.
1298    Return: 0 on success, non-0 on error. */
1299 typedef void *(*mg_thread_func_t)(void *);
1300 CIVETWEB_API int mg_start_thread(mg_thread_func_t f, void *p);
1301 
1302 
1303 /* Return builtin mime type for the given file name.
1304    For unrecognized extensions, "text/plain" is returned. */
1305 CIVETWEB_API const char *mg_get_builtin_mime_type(const char *file_name);
1306 
1307 
1308 /* Get text representation of HTTP status code. */
1309 CIVETWEB_API const char *
1310 mg_get_response_code_text(const struct mg_connection *conn, int response_code);
1311 
1312 
1313 /* Return CivetWeb version. */
1314 CIVETWEB_API const char *mg_version(void);
1315 
1316 
1317 /* URL-decode input buffer into destination buffer.
1318    0-terminate the destination buffer.
1319    form-url-encoded data differs from URI encoding in a way that it
1320    uses '+' as character for space, see RFC 1866 section 8.2.1
1321    http://ftp.ics.uci.edu/pub/ietf/html/rfc1866.txt
1322    Return: length of the decoded data, or -1 if dst buffer is too small. */
1323 CIVETWEB_API int mg_url_decode(const char *src,
1324                                int src_len,
1325                                char *dst,
1326                                int dst_len,
1327                                int is_form_url_encoded);
1328 
1329 
1330 /* URL-encode input buffer into destination buffer.
1331    returns the length of the resulting buffer or -1
1332    is the buffer is too small. */
1333 CIVETWEB_API int mg_url_encode(const char *src, char *dst, size_t dst_len);
1334 
1335 
1336 /* MD5 hash given strings.
1337    Buffer 'buf' must be 33 bytes long. Varargs is a NULL terminated list of
1338    ASCIIz strings. When function returns, buf will contain human-readable
1339    MD5 hash. Example:
1340      char buf[33];
1341      mg_md5(buf, "aa", "bb", NULL); */
1342 CIVETWEB_API char *mg_md5(char buf[33], ...);
1343 
1344 
1345 /* Print error message to the opened error log stream.
1346    This utilizes the provided logging configuration.
1347      conn: connection (not used for sending data, but to get perameters)
1348      fmt: format string without the line return
1349      ...: variable argument list
1350    Example:
1351      mg_cry(conn,"i like %s", "logging"); */
1352 CIVETWEB_API void mg_cry(const struct mg_connection *conn,
1353                          PRINTF_FORMAT_STRING(const char *fmt),
1354                          ...) PRINTF_ARGS(2, 3);
1355 
1356 
1357 /* utility methods to compare two buffers, case insensitive. */
1358 CIVETWEB_API int mg_strcasecmp(const char *s1, const char *s2);
1359 CIVETWEB_API int mg_strncasecmp(const char *s1, const char *s2, size_t len);
1360 
1361 
1362 /* Connect to a websocket as a client
1363    Parameters:
1364      host: host to connect to, i.e. "echo.websocket.org" or "192.168.1.1" or
1365    "localhost"
1366      port: server port
1367      use_ssl: make a secure connection to server
1368      error_buffer, error_buffer_size: buffer for an error message
1369      path: server path you are trying to connect to, i.e. if connection to
1370    localhost/app, path should be "/app"
1371      origin: value of the Origin HTTP header
1372      data_func: callback that should be used when data is received from the
1373    server
1374      user_data: user supplied argument
1375 
1376    Return:
1377      On success, valid mg_connection object.
1378      On error, NULL. Se error_buffer for details.
1379 */
1380 CIVETWEB_API struct mg_connection *
1381 mg_connect_websocket_client(const char *host,
1382                             int port,
1383                             int use_ssl,
1384                             char *error_buffer,
1385                             size_t error_buffer_size,
1386                             const char *path,
1387                             const char *origin,
1388                             mg_websocket_data_handler data_func,
1389                             mg_websocket_close_handler close_func,
1390                             void *user_data);
1391 
1392 
1393 /* Connect to a TCP server as a client (can be used to connect to a HTTP server)
1394    Parameters:
1395      host: host to connect to, i.e. "www.wikipedia.org" or "192.168.1.1" or
1396    "localhost"
1397      port: server port
1398      use_ssl: make a secure connection to server
1399      error_buffer, error_buffer_size: buffer for an error message
1400 
1401    Return:
1402      On success, valid mg_connection object.
1403      On error, NULL. Se error_buffer for details.
1404 */
1405 CIVETWEB_API struct mg_connection *mg_connect_client(const char *host,
1406                                                      int port,
1407                                                      int use_ssl,
1408                                                      char *error_buffer,
1409                                                      size_t error_buffer_size);
1410 
1411 
1412 struct mg_client_options {
1413 	const char *host;
1414 	int port;
1415 	const char *client_cert;
1416 	const char *server_cert;
1417 	const char *host_name;
1418 	/* TODO: add more data */
1419 };
1420 
1421 
1422 CIVETWEB_API struct mg_connection *
1423 mg_connect_client_secure(const struct mg_client_options *client_options,
1424                          char *error_buffer,
1425                          size_t error_buffer_size);
1426 
1427 
1428 enum { TIMEOUT_INFINITE = -1 };
1429 enum { MG_TIMEOUT_INFINITE = -1 };
1430 
1431 /* Wait for a response from the server
1432    Parameters:
1433      conn: connection
1434      ebuf, ebuf_len: error message placeholder.
1435      timeout: time to wait for a response in milliseconds (if < 0 then wait
1436    forever)
1437 
1438    Return:
1439      On success, >= 0
1440      On error/timeout, < 0
1441 */
1442 CIVETWEB_API int mg_get_response(struct mg_connection *conn,
1443                                  char *ebuf,
1444                                  size_t ebuf_len,
1445                                  int timeout);
1446 
1447 
1448 /* Check which features where set when the civetweb library has been compiled.
1449    The function explicitly addresses compile time defines used when building
1450    the library - it does not mean, the feature has been initialized using a
1451    mg_init_library call.
1452    mg_check_feature can be called anytime, even before mg_init_library has
1453    been called.
1454 
1455    Parameters:
1456      feature: specifies which feature should be checked
1457        The value is a bit mask. The individual bits are defined as:
1458          1  serve files (NO_FILES not set)
1459          2  support HTTPS (NO_SSL not set)
1460          4  support CGI (NO_CGI not set)
1461          8  support IPv6 (USE_IPV6 set)
1462         16  support WebSocket (USE_WEBSOCKET set)
1463         32  support Lua scripts and Lua server pages (USE_LUA is set)
1464         64  support server side JavaScript (USE_DUKTAPE is set)
1465        128  support caching (NO_CACHING not set)
1466        256  support server statistics (USE_SERVER_STATS is set)
1467        The result is undefined, if bits are set that do not represent a
1468        defined feature (currently: feature >= 512).
1469        The result is undefined, if no bit is set (feature == 0).
1470 
1471    Return:
1472      If feature is available, the corresponding bit is set
1473      If feature is not available, the bit is 0
1474 */
1475 CIVETWEB_API unsigned mg_check_feature(unsigned feature);
1476 
1477 
1478 /* Get information on the system. Useful for support requests.
1479    Parameters:
1480      buffer: Store system information as string here.
1481      buflen: Length of buffer (including a byte required for a terminating 0).
1482    Return:
1483      Available size of system information, exluding a terminating 0.
1484      The information is complete, if the return value is smaller than buflen.
1485      The result is a JSON formatted string, the exact content may vary.
1486    Note:
1487      It is possible to determine the required buflen, by first calling this
1488      function with buffer = NULL and buflen = NULL. The required buflen is
1489      one byte more than the returned value.
1490 */
1491 CIVETWEB_API int mg_get_system_info(char *buffer, int buflen);
1492 
1493 
1494 /* Get context information. Useful for server diagnosis.
1495    Parameters:
1496      ctx: Context handle
1497      buffer: Store context information here.
1498      buflen: Length of buffer (including a byte required for a terminating 0).
1499    Return:
1500      Available size of system information, exluding a terminating 0.
1501      The information is complete, if the return value is smaller than buflen.
1502      The result is a JSON formatted string, the exact content may vary.
1503      Note:
1504      It is possible to determine the required buflen, by first calling this
1505      function with buffer = NULL and buflen = NULL. The required buflen is
1506      one byte more than the returned value. However, since the available
1507      context information changes, you should allocate a few bytes more.
1508 */
1509 CIVETWEB_API int
1510 mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen);
1511 
1512 
1513 #ifdef MG_EXPERIMENTAL_INTERFACES
1514 /* Get connection information. Useful for server diagnosis.
1515    Parameters:
1516      ctx: Context handle
1517      idx: Connection index
1518      buffer: Store context information here.
1519      buflen: Length of buffer (including a byte required for a terminating 0).
1520    Return:
1521      Available size of system information, exluding a terminating 0.
1522      The information is complete, if the return value is smaller than buflen.
1523      The result is a JSON formatted string, the exact content may vary.
1524    Note:
1525      It is possible to determine the required buflen, by first calling this
1526      function with buffer = NULL and buflen = NULL. The required buflen is
1527      one byte more than the returned value. However, since the available
1528      context information changes, you should allocate a few bytes more.
1529 */
1530 CIVETWEB_API int mg_get_connection_info(const struct mg_context *ctx,
1531                                         int idx,
1532                                         char *buffer,
1533                                         int buflen);
1534 #endif
1535 
1536 
1537 #ifdef __cplusplus
1538 }
1539 #endif /* __cplusplus */
1540 
1541 #endif /* CIVETWEB_HEADER_INCLUDED */
1542