Teonet library  0.4.7
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
mongoose.h
Go to the documentation of this file.
1 #ifdef __AVR__
2 #include "avrsupport.h"
3 #endif
4 /*
5  * Copyright (c) 2004-2013 Sergey Lyubka
6  * Copyright (c) 2013-2015 Cesanta Software Limited
7  * All rights reserved
8  *
9  * This software is dual-licensed: you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License version 2 as
11  * published by the Free Software Foundation. For the terms of this
12  * license, see <http://www.gnu.org/licenses/>.
13  *
14  * You are free to use this software under the terms of the GNU General
15  * Public License, but WITHOUT ANY WARRANTY; without even the implied
16  * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
17  * See the GNU General Public License for more details.
18  *
19  * Alternatively, you can license this software under a commercial
20  * license, as set out in <https://www.cesanta.com/license>.
21  */
22 
23 #define MG_VERSION "6.0"
24 
25 /* Local tweaks, applied before any of Mongoose's own headers. */
26 #ifdef MG_LOCALS
27 #include <mg_locals.h>
28 #endif
29 
30 #if defined(MG_ENABLE_DEBUG) && !defined(CS_ENABLE_DEBUG)
31 #define CS_ENABLE_DEBUG
32 #endif
33 /*
34  * Copyright (c) 2015 Cesanta Software Limited
35  * All rights reserved
36  */
37 
38 #ifndef OSDEP_HEADER_INCLUDED
39 #define OSDEP_HEADER_INCLUDED
40 
41 #if !defined(MG_DISABLE_FILESYSTEM) && defined(AVR_NOFS)
42 #define MG_DISABLE_FILESYSTEM
43 #endif
44 
45 #undef UNICODE /* Use ANSI WinAPI functions */
46 #undef _UNICODE /* Use multibyte encoding on Windows */
47 #define _MBCS /* Use multibyte encoding on Windows */
48 #define _INTEGRAL_MAX_BITS 64 /* Enable _stati64() on Windows */
49 #ifndef _CRT_SECURE_NO_WARNINGS
50 #define _CRT_SECURE_NO_WARNINGS /* Disable deprecation warning in VS2005+ */
51 #endif
52 #undef WIN32_LEAN_AND_MEAN /* Let windows.h always include winsock2.h */
53 #undef _XOPEN_SOURCE
54 #define _XOPEN_SOURCE 600 /* For flockfile() on Linux */
55 #define __STDC_FORMAT_MACROS /* <inttypes.h> wants this for C++ */
56 #define __STDC_LIMIT_MACROS /* C++ wants that for INT64_MAX */
57 #ifndef _LARGEFILE_SOURCE
58 #define _LARGEFILE_SOURCE /* Enable fseeko() and ftello() functions */
59 #endif
60 #define _FILE_OFFSET_BITS 64 /* Enable 64-bit file offsets */
61 
62 #if !(defined(AVR_LIBC) || defined(PICOTCP))
63 #include <sys/types.h>
64 #include <sys/stat.h>
65 #include <fcntl.h>
66 #include <time.h>
67 #include <signal.h>
68 #endif
69 
70 #ifndef BYTE_ORDER
71 #define LITTLE_ENDIAN 0x41424344
72 #define BIG_ENDIAN 0x44434241
73 #define PDP_ENDIAN 0x42414443
74 /* TODO(lsm): fix for big-endian machines. 'ABCD' is not portable */
75 /*#define BYTE_ORDER 'ABCD'*/
76 #define BYTE_ORDER LITTLE_ENDIAN
77 #endif
78 
79 /*
80  * MSVC++ 14.0 _MSC_VER == 1900 (Visual Studio 2015)
81  * MSVC++ 12.0 _MSC_VER == 1800 (Visual Studio 2013)
82  * MSVC++ 11.0 _MSC_VER == 1700 (Visual Studio 2012)
83  * MSVC++ 10.0 _MSC_VER == 1600 (Visual Studio 2010)
84  * MSVC++ 9.0 _MSC_VER == 1500 (Visual Studio 2008)
85  * MSVC++ 8.0 _MSC_VER == 1400 (Visual Studio 2005)
86  * MSVC++ 7.1 _MSC_VER == 1310 (Visual Studio 2003)
87  * MSVC++ 7.0 _MSC_VER == 1300
88  * MSVC++ 6.0 _MSC_VER == 1200
89  * MSVC++ 5.0 _MSC_VER == 1100
90  */
91 #ifdef _MSC_VER
92 #pragma warning(disable : 4127) /* FD_SET() emits warning, disable it */
93 #pragma warning(disable : 4204) /* missing c99 support */
94 #endif
95 
96 #ifdef PICOTCP
97 #define time(x) PICO_TIME()
98 #ifndef SOMAXCONN
99 #define SOMAXCONN (16)
100 #endif
101 #ifdef _POSIX_VERSION
102 #define signal(...)
103 #endif
104 #endif
105 
106 #include <assert.h>
107 #include <ctype.h>
108 #include <limits.h>
109 #include <stdarg.h>
110 #include <stddef.h>
111 #include <stdio.h>
112 #include <stdlib.h>
113 #include <string.h>
114 
115 #ifndef va_copy
116 #ifdef __va_copy
117 #define va_copy __va_copy
118 #else
119 #define va_copy(x, y) (x) = (y)
120 #endif
121 #endif
122 
123 #ifdef _WIN32
124 #define random() rand()
125 #ifdef _MSC_VER
126 #pragma comment(lib, "ws2_32.lib") /* Linking with winsock library */
127 #endif
128 #include <windows.h>
129 #include <process.h>
130 #ifndef EINPROGRESS
131 #define EINPROGRESS WSAEINPROGRESS
132 #endif
133 #ifndef EWOULDBLOCK
134 #define EWOULDBLOCK WSAEWOULDBLOCK
135 #endif
136 #ifndef __func__
137 #define STRX(x) #x
138 #define STR(x) STRX(x)
139 #define __func__ __FILE__ ":" STR(__LINE__)
140 #endif
141 #define snprintf _snprintf
142 #define fileno _fileno
143 #define vsnprintf _vsnprintf
144 #define sleep(x) Sleep((x) *1000)
145 #define to64(x) _atoi64(x)
146 #define popen(x, y) _popen((x), (y))
147 #define pclose(x) _pclose(x)
148 #if defined(_MSC_VER) && _MSC_VER >= 1400
149 #define fseeko(x, y, z) _fseeki64((x), (y), (z))
150 #else
151 #define fseeko(x, y, z) fseek((x), (y), (z))
152 #endif
153 #define random() rand()
154 typedef int socklen_t;
155 typedef signed char int8_t;
156 typedef unsigned char uint8_t;
157 typedef int int32_t;
158 typedef unsigned int uint32_t;
159 typedef short int16_t;
160 typedef unsigned short uint16_t;
161 typedef __int64 int64_t;
162 typedef unsigned __int64 uint64_t;
163 typedef SOCKET sock_t;
164 typedef uint32_t in_addr_t;
165 #ifndef UINT16_MAX
166 #define UINT16_MAX 65535
167 #endif
168 #ifndef UINT32_MAX
169 #define UINT32_MAX 4294967295
170 #endif
171 #ifndef pid_t
172 #define pid_t HANDLE
173 #endif
174 #define INT64_FMT "I64d"
175 #define SIZE_T_FMT "Iu"
176 #ifdef __MINGW32__
177 typedef struct stat cs_stat_t;
178 #else
179 typedef struct _stati64 cs_stat_t;
180 #endif
181 #ifndef S_ISDIR
182 #define S_ISDIR(x) ((x) &_S_IFDIR)
183 #endif
184 #define DIRSEP '\\'
185 
186 /* POSIX opendir/closedir/readdir API for Windows. */
187 struct dirent {
188  char d_name[MAX_PATH];
189 };
190 
191 typedef struct DIR {
192  HANDLE handle;
193  WIN32_FIND_DATAW info;
194  struct dirent result;
195 } DIR;
196 
197 DIR *opendir(const char *name);
198 int closedir(DIR *dir);
199 struct dirent *readdir(DIR *dir);
200 
201 #elif /* not _WIN32 */ defined(MG_CC3200)
202 
203 #include <fcntl.h>
204 #include <unistd.h>
205 #include <cc3200_libc.h>
206 #include <cc3200_socket.h>
207 
208 #elif /* not CC3200 */ defined(MG_LWIP)
209 
210 #include <lwip/sockets.h>
211 #include <lwip/netdb.h>
212 #include <lwip/dns.h>
213 
214 #if defined(MG_ESP8266) && defined(RTOS_SDK)
215 #include <esp_libc.h>
216 #define random() os_random()
217 #endif
218 
219 /* TODO(alashkin): check if zero is OK */
220 #define SOMAXCONN 0
221 #include <stdlib.h>
222 
223 #elif /* not ESP8266 RTOS */ !defined(NO_LIBC) && !defined(NO_BSD_SOCKETS)
224 
225 #include <dirent.h>
226 #include <fcntl.h>
227 #include <netdb.h>
228 #include <pthread.h>
229 #include <unistd.h>
230 #include <arpa/inet.h> /* For inet_pton() when MG_ENABLE_IPV6 is defined */
231 #include <netinet/in.h>
232 #include <sys/socket.h>
233 #include <sys/select.h>
234 #endif
235 
236 #ifndef LWIP_PROVIDE_ERRNO
237 #include <errno.h>
238 #endif
239 
240 #ifndef _WIN32
241 #include <inttypes.h>
242 #include <stdarg.h>
243 
244 #ifndef AVR_LIBC
245 #ifndef MG_ESP8266
246 #define closesocket(x) close(x)
247 #endif
248 #ifndef __cdecl
249 #define __cdecl
250 #endif
251 
252 #define INVALID_SOCKET (-1)
253 #define INT64_FMT PRId64
254 #if defined(ESP8266) || defined(MG_ESP8266) || defined(MG_CC3200)
255 #define SIZE_T_FMT "u"
256 #else
257 #define SIZE_T_FMT "zu"
258 #endif
259 #define to64(x) strtoll(x, NULL, 10)
260 typedef int sock_t;
261 typedef struct stat cs_stat_t;
262 #define DIRSEP '/'
263 #endif /* !AVR_LIBC */
264 
265 #ifdef __APPLE__
266 int64_t strtoll(const char *str, char **endptr, int base);
267 #endif
268 #endif /* !_WIN32 */
269 
270 #ifndef ARRAY_SIZE
271 #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
272 #endif
273 
274 #endif /* OSDEP_HEADER_INCLUDED */
275 #ifndef _CS_DBG_H_
276 #define _CS_DBG_H_
277 
279  LL_NONE = -1,
280  LL_ERROR = 0,
281  LL_WARN = 1,
282  LL_INFO = 2,
283  LL_DEBUG = 3,
284 
285  _LL_MIN = -2,
286  _LL_MAX = 4,
287 };
288 
289 #ifndef CS_NDEBUG
290 
291 extern enum cs_log_level s_cs_log_level;
292 void cs_log_set_level(enum cs_log_level level);
293 
294 void cs_log_printf(const char *fmt, ...);
295 
296 #define LOG(l, x) \
297  if (s_cs_log_level >= l) { \
298  fprintf(stderr, "%-20s ", __func__); \
299  cs_log_printf x; \
300  }
301 
302 #define DBG(x) \
303  if (s_cs_log_level >= LL_DEBUG) { \
304  fprintf(stderr, "%-20s ", __func__); \
305  cs_log_printf x; \
306  }
307 
308 #else /* NDEBUG */
309 
310 #define cs_log_set_level(l)
311 
312 #define LOG(l, x)
313 #define DBG(x)
314 
315 #endif
316 
317 #endif /* _CS_DBG_H_ */
318 /*
319  * Copyright (c) 2015 Cesanta Software Limited
320  * All rights reserved
321  */
322 
323 /*
324  * === Memory Buffers
325  *
326  * Mbufs are mutable/growing memory buffers, like C++ strings.
327  * Mbuf can append data to the end of a buffer, or insert data into arbitrary
328  * position in the middle of a buffer. The buffer grows automatically when
329  * needed.
330  */
331 
332 #ifndef MBUF_H_INCLUDED
333 #define MBUF_H_INCLUDED
334 
335 #if defined(__cplusplus)
336 extern "C" {
337 #endif
338 
339 #include <stdlib.h>
340 
341 #ifndef MBUF_SIZE_MULTIPLIER
342 #define MBUF_SIZE_MULTIPLIER 1.5
343 #endif
344 
345 /* Memory buffer descriptor */
346 struct mbuf {
347  char *buf; /* Buffer pointer */
348  size_t len; /* Data length. Data is located between offset 0 and len. */
349  size_t size; /* Buffer size allocated by realloc(1). Must be >= len */
350 };
351 
352 /*
353  * Initialize an Mbuf.
354  * `initial_capacity` specifies the initial capacity of the mbuf.
355  */
356 void mbuf_init(struct mbuf *, size_t initial_capacity);
357 
358 /* Free the space allocated for the mbuffer and resets the mbuf structure. */
359 void mbuf_free(struct mbuf *);
360 
361 /*
362  * Appends data to the Mbuf.
363  *
364  * Return the number of bytes appended, or 0 if out of memory.
365  */
366 size_t mbuf_append(struct mbuf *, const void *data, size_t data_size);
367 
368 /*
369  * Insert data at a specified offset in the Mbuf.
370  *
371  * Existing data will be shifted forwards and the buffer will
372  * be grown if necessary.
373  * Return the number of bytes inserted.
374  */
375 size_t mbuf_insert(struct mbuf *, size_t, const void *, size_t);
376 
377 /* Remove `data_size` bytes from the beginning of the buffer. */
378 void mbuf_remove(struct mbuf *, size_t data_size);
379 
380 /*
381  * Resize an Mbuf.
382  *
383  * If `new_size` is smaller than buffer's `len`, the
384  * resize is not performed.
385  */
386 void mbuf_resize(struct mbuf *, size_t new_size);
387 
388 /* Shrink an Mbuf by resizing its `size` to `len`. */
389 void mbuf_trim(struct mbuf *);
390 
391 #if defined(__cplusplus)
392 }
393 #endif /* __cplusplus */
394 
395 #endif /* MBUF_H_INCLUDED */
396 /*
397  * Copyright (c) 2014 Cesanta Software Limited
398  * All rights reserved
399  */
400 
401 #if !defined(MG_SHA1_HEADER_INCLUDED) && !defined(DISABLE_SHA1)
402 #define MG_SHA1_HEADER_INCLUDED
403 
404 
405 #ifdef __cplusplus
406 extern "C" {
407 #endif /* __cplusplus */
408 
409 typedef struct {
410  uint32_t state[5];
411  uint32_t count[2];
412  unsigned char buffer[64];
413 } cs_sha1_ctx;
414 
415 void cs_sha1_init(cs_sha1_ctx *);
416 void cs_sha1_update(cs_sha1_ctx *, const unsigned char *data, uint32_t len);
417 void cs_sha1_final(unsigned char digest[20], cs_sha1_ctx *);
418 void cs_hmac_sha1(const unsigned char *key, size_t key_len,
419  const unsigned char *text, size_t text_len,
420  unsigned char out[20]);
421 #ifdef __cplusplus
422 }
423 #endif /* __cplusplus */
424 #endif /* MG_SHA1_HEADER_INCLUDED */
425 /*
426  * Copyright (c) 2014 Cesanta Software Limited
427  * All rights reserved
428  */
429 
430 #ifndef MD5_HEADER_DEFINED
431 #define MD5_HEADER_DEFINED
432 
433 
434 #ifdef __cplusplus
435 extern "C" {
436 #endif /* __cplusplus */
437 
438 typedef struct MD5Context {
439  uint32_t buf[4];
440  uint32_t bits[2];
441  unsigned char in[64];
442 } MD5_CTX;
443 
444 void MD5_Init(MD5_CTX *c);
445 void MD5_Update(MD5_CTX *c, const unsigned char *data, size_t len);
446 void MD5_Final(unsigned char *md, MD5_CTX *c);
447 
448 /*
449  * Return stringified MD5 hash for NULL terminated list of strings.
450  * Example:
451  *
452  * char buf[33];
453  * cs_md5(buf, "foo", "bar", NULL);
454  */
455 char *cs_md5(char buf[33], ...);
456 
457 /*
458  * Stringify binary data. Output buffer size must be 2 * size_of_input + 1
459  * because each byte of input takes 2 bytes in string representation
460  * plus 1 byte for the terminating \0 character.
461  */
462 void cs_to_hex(char *to, const unsigned char *p, size_t len);
463 
464 #ifdef __cplusplus
465 }
466 #endif /* __cplusplus */
467 
468 #endif
469 /*
470  * Copyright (c) 2014 Cesanta Software Limited
471  * All rights reserved
472  */
473 
474 #if !defined(BASE64_H_INCLUDED) && !defined(DISABLE_BASE64)
475 #define BASE64_H_INCLUDED
476 
477 #include <stdio.h>
478 
479 #ifdef __cplusplus
480 extern "C" {
481 #endif
482 
483 typedef void (*cs_base64_putc_t)(char, void *);
484 
486  /* cannot call it putc because it's a macro on some environments */
488  unsigned char chunk[3];
490  void *user_data;
491 };
492 
493 void cs_base64_init(struct cs_base64_ctx *ctx, cs_base64_putc_t putc,
494  void *user_data);
495 void cs_base64_update(struct cs_base64_ctx *ctx, const char *str, size_t len);
496 void cs_base64_finish(struct cs_base64_ctx *ctx);
497 
498 void cs_base64_encode(const unsigned char *src, int src_len, char *dst);
499 void cs_fprint_base64(FILE *f, const unsigned char *src, int src_len);
500 int cs_base64_decode(const unsigned char *s, int len, char *dst);
501 
502 #ifdef __cplusplus
503 }
504 #endif
505 #endif
506 /*
507  * Copyright (c) 2015 Cesanta Software Limited
508  * All rights reserved
509  */
510 
511 #ifndef STR_UTIL_H
512 #define STR_UTIL_H
513 
514 #include <stdarg.h>
515 #include <stdlib.h>
516 
517 #ifdef __cplusplus
518 extern "C" {
519 #endif
520 
521 int c_snprintf(char *buf, size_t buf_size, const char *format, ...);
522 int c_vsnprintf(char *buf, size_t buf_size, const char *format, va_list ap);
523 
524 #if (!(defined(_XOPEN_SOURCE) && _XOPEN_SOURCE >= 700) && \
525  !(defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200809L) && \
526  !(defined(__DARWIN_C_LEVEL) && __DARWIN_C_LEVEL >= 200809L) && \
527  !defined(RTOS_SDK)) || \
528  defined(_WIN32)
529 #define _MG_PROVIDE_STRNLEN
530 size_t strnlen(const char *s, size_t maxlen);
531 #endif
532 
533 #ifdef __cplusplus
534 }
535 #endif
536 #endif
537 /*
538  * Copyright (c) 2004-2013 Sergey Lyubka <valenok@gmail.com>
539  * Copyright (c) 2013 Cesanta Software Limited
540  * All rights reserved
541  *
542  * This library is dual-licensed: you can redistribute it and/or modify
543  * it under the terms of the GNU General Public License version 2 as
544  * published by the Free Software Foundation. For the terms of this
545  * license, see <http: *www.gnu.org/licenses/>.
546  *
547  * You are free to use this library under the terms of the GNU General
548  * Public License, but WITHOUT ANY WARRANTY; without even the implied
549  * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
550  * See the GNU General Public License for more details.
551  *
552  * Alternatively, you can license this library under a commercial
553  * license, as set out in <https://www.cesanta.com/license>.
554  */
555 
556 #ifndef FROZEN_HEADER_INCLUDED
557 #define FROZEN_HEADER_INCLUDED
558 
559 #ifdef __cplusplus
560 extern "C" {
561 #endif /* __cplusplus */
562 
563 #include <stdarg.h>
564 
565 enum json_type {
566  JSON_TYPE_EOF = 0, /* End of parsed tokens marker */
574 };
575 
576 struct json_token {
577  const char *ptr; /* Points to the beginning of the token */
578  int len; /* Token length */
579  int num_desc; /* For arrays and object, total number of descendants */
580  enum json_type type; /* Type of the token, possible values above */
581 };
582 
583 /* Error codes */
584 #define JSON_STRING_INVALID -1
585 #define JSON_STRING_INCOMPLETE -2
586 #define JSON_TOKEN_ARRAY_TOO_SMALL -3
587 
588 int parse_json(const char *json_string, int json_string_length,
589  struct json_token *tokens_array, int size_of_tokens_array);
590 struct json_token *parse_json2(const char *json_string, int string_length);
591 struct json_token *find_json_token(struct json_token *toks, const char *path);
592 
593 int json_emit_long(char *buf, int buf_len, long value);
594 int json_emit_double(char *buf, int buf_len, double value);
595 int json_emit_quoted_str(char *buf, int buf_len, const char *str, int len);
596 int json_emit_unquoted_str(char *buf, int buf_len, const char *str, int len);
597 int json_emit(char *buf, int buf_len, const char *fmt, ...);
598 int json_emit_va(char *buf, int buf_len, const char *fmt, va_list);
599 
600 #ifdef __cplusplus
601 }
602 #endif /* __cplusplus */
603 
604 #endif /* FROZEN_HEADER_INCLUDED */
605 /*
606  * Copyright (c) 2014 Cesanta Software Limited
607  * All rights reserved
608  * This software is dual-licensed: you can redistribute it and/or modify
609  * it under the terms of the GNU General Public License version 2 as
610  * published by the Free Software Foundation. For the terms of this
611  * license, see <http://www.gnu.org/licenses/>.
612  *
613  * You are free to use this software under the terms of the GNU General
614  * Public License, but WITHOUT ANY WARRANTY; without even the implied
615  * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
616  * See the GNU General Public License for more details.
617  *
618  * Alternatively, you can license this software under a commercial
619  * license, as set out in <https://www.cesanta.com/license>.
620  */
621 
622 /*
623  * === Core: TCP/UDP/SSL
624  *
625  * NOTE: Mongoose manager is single threaded. It does not protect
626  * its data structures by mutexes, therefore all functions that are dealing
627  * with particular event manager should be called from the same thread,
628  * with exception of `mg_broadcast()` function. It is fine to have different
629  * event managers handled by different threads.
630  */
631 
632 #ifndef MG_NET_HEADER_INCLUDED
633 #define MG_NET_HEADER_INCLUDED
634 
635 #ifdef MG_ENABLE_JAVASCRIPT
636 #define EXCLUDE_COMMON
637 #include <v7.h>
638 #endif
639 
640 
641 #ifdef MG_ENABLE_SSL
642 #ifdef __APPLE__
643 #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
644 #endif
645 #include <openssl/ssl.h>
646 #else
647 typedef void *SSL;
648 typedef void *SSL_CTX;
649 #endif
650 
651 #ifdef MG_USE_READ_WRITE
652 #define MG_RECV_FUNC(s, b, l, f) read(s, b, l)
653 #define MG_SEND_FUNC(s, b, l, f) write(s, b, l)
654 #else
655 #define MG_RECV_FUNC(s, b, l, f) recv(s, b, l, f)
656 #define MG_SEND_FUNC(s, b, l, f) send(s, b, l, f)
657 #endif
658 
659 #ifdef __cplusplus
660 extern "C" {
661 #endif /* __cplusplus */
662 
664  struct sockaddr sa;
665  struct sockaddr_in sin;
666 #ifdef MG_ENABLE_IPV6
667  struct sockaddr_in6 sin6;
668 #else
669  struct sockaddr sin6;
670 #endif
671 };
672 
673 /* Describes chunk of memory */
674 struct mg_str {
675  const char *p; /* Memory chunk pointer */
676  size_t len; /* Memory chunk length */
677 };
678 
679 #define MG_STR(str_literal) \
680  { str_literal, sizeof(str_literal) - 1 }
681 
682 /*
683  * Callback function (event handler) prototype, must be defined by user.
684  * Mongoose calls event handler, passing events defined below.
685  */
686 struct mg_connection;
687 typedef void (*mg_event_handler_t)(struct mg_connection *, int ev, void *);
688 
689 /* Events. Meaning of event parameter (evp) is given in the comment. */
690 #define MG_EV_POLL 0 /* Sent to each connection on each mg_mgr_poll() call */
691 #define MG_EV_ACCEPT 1 /* New connection accepted. union socket_address * */
692 #define MG_EV_CONNECT 2 /* connect() succeeded or failed. int * */
693 #define MG_EV_RECV 3 /* Data has benn received. int *num_bytes */
694 #define MG_EV_SEND 4 /* Data has been written to a socket. int *num_bytes */
695 #define MG_EV_CLOSE 5 /* Connection is closed. NULL */
696 
697 /*
698  * Mongoose event manager.
699  */
700 struct mg_mgr {
702  const char *hexdump_file; /* Debug hexdump file path */
703  sock_t ctl[2]; /* Socketpair for mg_wakeup() */
704  void *user_data; /* User data */
705  void *mgr_data; /* Implementation-specific event manager's data. */
706 #ifdef MG_ENABLE_JAVASCRIPT
707  struct v7 *v7;
708 #endif
709 };
710 
711 /*
712  * Mongoose connection.
713  */
715  struct mg_connection *next, *prev; /* mg_mgr::active_connections linkage */
716  struct mg_connection *listener; /* Set only for accept()-ed connections */
717  struct mg_mgr *mgr; /* Pointer to containing manager */
718 
719  sock_t sock; /* Socket to the remote peer */
720  int err;
721  union socket_address sa; /* Remote peer address */
722  size_t recv_mbuf_limit; /* Max size of recv buffer */
723  struct mbuf recv_mbuf; /* Received data */
724  struct mbuf send_mbuf; /* Data scheduled for sending */
727  time_t last_io_time; /* Timestamp of the last socket IO */
728  mg_event_handler_t proto_handler; /* Protocol-specific event handler */
729  void *proto_data; /* Protocol-specific data */
730  mg_event_handler_t handler; /* Event handler function */
731  void *user_data; /* User-specific data */
732  void *priv_1; /* Used by mg_enable_multithreading() */
733  void *priv_2; /* Used by mg_enable_multithreading() */
734  void *mgr_data; /* Implementation-specific event manager's data. */
735 
736  unsigned long flags;
737 /* Flags set by Mongoose */
738 #define MG_F_LISTENING (1 << 0) /* This connection is listening */
739 #define MG_F_UDP (1 << 1) /* This connection is UDP */
740 #define MG_F_RESOLVING (1 << 2) /* Waiting for async resolver */
741 #define MG_F_CONNECTING (1 << 3) /* connect() call in progress */
742 #define MG_F_SSL_HANDSHAKE_DONE (1 << 4) /* SSL specific */
743 #define MG_F_WANT_READ (1 << 5) /* SSL specific */
744 #define MG_F_WANT_WRITE (1 << 6) /* SSL specific */
745 #define MG_F_IS_WEBSOCKET (1 << 7) /* Websocket specific */
746 
747 /* Flags that are settable by user */
748 #define MG_F_SEND_AND_CLOSE (1 << 10) /* Push remaining data and close */
749 #define MG_F_CLOSE_IMMEDIATELY (1 << 11) /* Disconnect */
750 #define MG_F_WEBSOCKET_NO_DEFRAG (1 << 12) /* Websocket specific */
751 #define MG_F_DELETE_CHUNK (1 << 13) /* HTTP specific */
752 
753 #define MG_F_USER_1 (1 << 20) /* Flags left for application */
754 #define MG_F_USER_2 (1 << 21)
755 #define MG_F_USER_3 (1 << 22)
756 #define MG_F_USER_4 (1 << 23)
757 #define MG_F_USER_5 (1 << 24)
758 #define MG_F_USER_6 (1 << 25)
759 };
760 
761 /*
762  * Initialize Mongoose manager. Side effect: ignores SIGPIPE signal.
763  * `mgr->user_data` field will be initialized with `user_data` parameter.
764  * That is an arbitrary pointer, where user code can associate some data
765  * with the particular Mongoose manager. For example, a C++ wrapper class
766  * could be written, in which case `user_data` can hold a pointer to the
767  * class instance.
768  */
769 void mg_mgr_init(struct mg_mgr *mgr, void *user_data);
770 
771 /*
772  * De-initializes Mongoose manager.
773  *
774  * Close and deallocate all active connections.
775  */
776 void mg_mgr_free(struct mg_mgr *);
777 
778 /*
779  * This function performs the actual IO, and must be called in a loop
780  * (an event loop). Returns the current timestamp.
781  * `milli` is the maximum number of milliseconds to sleep.
782  * `mg_mgr_poll()` checks all connection for IO readiness. If at least one
783  * of the connections is IO-ready, `mg_mgr_poll()` triggers respective
784  * event handlers and returns.
785  */
786 time_t mg_mgr_poll(struct mg_mgr *, int milli);
787 
788 #ifndef MG_DISABLE_SOCKETPAIR
789 /*
790  * Pass a message of a given length to all connections.
791  *
792  * Must be called from a thread that does NOT call `mg_mgr_poll()`.
793  * Note that `mg_broadcast()` is the only function
794  * that can be, and must be, called from a different (non-IO) thread.
795  *
796  * `func` callback function will be called by the IO thread for each
797  * connection. When called, event would be `MG_EV_POLL`, and message will
798  * be passed as `ev_data` pointer. Maximum message size is capped
799  * by `MG_CTL_MSG_MESSAGE_SIZE` which is set to 8192 bytes.
800  */
801 void mg_broadcast(struct mg_mgr *, mg_event_handler_t func, void *, size_t);
802 #endif
803 
804 /*
805  * Iterate over all active connections.
806  *
807  * Returns next connection from the list
808  * of active connections, or `NULL` if there is no more connections. Below
809  * is the iteration idiom:
810  *
811  * [source,c]
812  * ----
813  * for (c = mg_next(srv, NULL); c != NULL; c = mg_next(srv, c)) {
814  * // Do something with connection `c`
815  * }
816  * ----
817  */
818 struct mg_connection *mg_next(struct mg_mgr *, struct mg_connection *);
819 
820 /*
821  * Optional parameters to mg_add_sock_opt()
822  * `flags` is an initial `struct mg_connection::flags` bitmask to set,
823  * see `MG_F_*` flags definitions.
824  */
826  void *user_data; /* Initial value for connection's user_data */
827  unsigned int flags; /* Initial connection flags */
828  const char **error_string; /* Placeholder for the error string */
829 };
830 
831 /*
832  * Create a connection, associate it with the given socket and event handler,
833  * and add it to the manager.
834  *
835  * For more options see the `mg_add_sock_opt` variant.
836  */
838 
839 /*
840  * Create a connection, associate it with the given socket and event handler,
841  * and add to the manager.
842  *
843  * See the `mg_add_sock_opts` structure for a description of the options.
844  */
845 struct mg_connection *mg_add_sock_opt(struct mg_mgr *, sock_t,
847  struct mg_add_sock_opts);
848 
849 /*
850  * Optional parameters to mg_bind_opt()
851  * `flags` is an initial `struct mg_connection::flags` bitmask to set,
852  * see `MG_F_*` flags definitions.
853  */
854 struct mg_bind_opts {
855  void *user_data; /* Initial value for connection's user_data */
856  unsigned int flags; /* Extra connection flags */
857  const char **error_string; /* Placeholder for the error string */
858 };
859 
860 /*
861  * Create listening connection.
862  *
863  * See `mg_bind_opt` for full documentation.
864  */
865 struct mg_connection *mg_bind(struct mg_mgr *, const char *,
867 /*
868  * Create listening connection.
869  *
870  * `address` parameter tells which address to bind to. It's format is the same
871  * as for the `mg_connect()` call, where `HOST` part is optional. `address`
872  * can be just a port number, e.g. `:8000`. To bind to a specific interface,
873  * an IP address can be specified, e.g. `1.2.3.4:8000`. By default, a TCP
874  * connection is created. To create UDP connection, prepend `udp://` prefix,
875  * e.g. `udp://:8000`. To summarize, `address` paramer has following format:
876  * `[PROTO://][IP_ADDRESS]:PORT`, where `PROTO` could be `tcp` or `udp`.
877  *
878  * See the `mg_bind_opts` structure for a description of the optional
879  * parameters.
880  *
881  * Return a new listening connection, or `NULL` on error.
882  * NOTE: Connection remains owned by the manager, do not free().
883  */
884 struct mg_connection *mg_bind_opt(struct mg_mgr *, const char *,
886 
887 /* Optional parameters to mg_connect_opt() */
889  void *user_data; /* Initial value for connection's user_data */
890  unsigned int flags; /* Extra connection flags */
891  const char **error_string; /* Placeholder for the error string */
892 };
893 
894 /*
895  * Connect to a remote host.
896  *
897  * See `mg_connect_opt()` for full documentation.
898  */
899 struct mg_connection *mg_connect(struct mg_mgr *, const char *,
901 
902 /*
903  * Connect to a remote host.
904  *
905  * `address` format is `[PROTO://]HOST:PORT`. `PROTO` could be `tcp` or `udp`.
906  * `HOST` could be an IP address,
907  * IPv6 address (if Mongoose is compiled with `-DMG_ENABLE_IPV6`), or a host
908  * name. If `HOST` is a name, Mongoose will resolve it asynchronously. Examples
909  * of valid addresses: `google.com:80`, `udp://1.2.3.4:53`, `10.0.0.1:443`,
910  * `[::1]:80`
911  *
912  * See the `mg_connect_opts` structure for a description of the optional
913  * parameters.
914  *
915  * Returns a new outbound connection, or `NULL` on error.
916  *
917  * NOTE: Connection remains owned by the manager, do not free().
918  *
919  * NOTE: To enable IPv6 addresses, `-DMG_ENABLE_IPV6` should be specified
920  * in the compilation flags.
921  *
922  * NOTE: New connection will receive `MG_EV_CONNECT` as it's first event
923  * which will report connect success status.
924  * If asynchronous resolution fail, or `connect()` syscall fail for whatever
925  * reason (e.g. with `ECONNREFUSED` or `ENETUNREACH`), then `MG_EV_CONNECT`
926  * event report failure. Code example below:
927  *
928  * [source,c]
929  * ----
930  * static void ev_handler(struct mg_connection *nc, int ev, void *ev_data) {
931  * int connect_status;
932  *
933  * switch (ev) {
934  * case MG_EV_CONNECT:
935  * connect_status = * (int *) ev_data;
936  * if (connect_status == 0) {
937  * // Success
938  * } else {
939  * // Error
940  * printf("connect() error: %s\n", strerror(connect_status));
941  * }
942  * break;
943  * ...
944  * }
945  * }
946  *
947  * ...
948  * mg_connect(mgr, "my_site.com:80", ev_handler);
949  * ----
950  */
951 struct mg_connection *mg_connect_opt(struct mg_mgr *, const char *,
953  struct mg_connect_opts);
954 
955 /*
956  * Enable SSL for a given connection.
957  * `cert` is a server certificate file name for a listening connection,
958  * or a client certificate file name for an outgoing connection.
959  * Certificate files must be in PEM format. Server certificate file
960  * must contain a certificate, concatenated with a private key, optionally
961  * concatenated with parameters.
962  * `ca_cert` is a CA certificate, or NULL if peer verification is not
963  * required.
964  * Return: NULL on success, or error message on error.
965  */
966 const char *mg_set_ssl(struct mg_connection *nc, const char *cert,
967  const char *ca_cert);
968 
969 /*
970  * Send data to the connection.
971  *
972  * Note that sending functions do not actually push data to the socket.
973  * They just append data to the output buffer. MG_EV_SEND will be delivered when
974  * the data has actually been pushed out.
975  */
976 void mg_send(struct mg_connection *, const void *buf, int len);
977 
978 /* Enables format string warnings for mg_printf */
979 #if defined(__GNUC__)
980 __attribute__((format(printf, 2, 3)))
981 #endif
982 /* don't separate from mg_printf declaration */
983 
984 /*
985  * Send `printf`-style formatted data to the connection.
986  *
987  * See `mg_send` for more details on send semantics.
988  */
989 int mg_printf(struct mg_connection *, const char *fmt, ...);
990 
991 /* Same as `mg_printf()`, but takes `va_list ap` as an argument. */
992 int mg_vprintf(struct mg_connection *, const char *fmt, va_list ap);
993 
994 /*
995  * Create a socket pair.
996  * `sock_type` can be either `SOCK_STREAM` or `SOCK_DGRAM`.
997  * Return 0 on failure, 1 on success.
998  */
999 int mg_socketpair(sock_t[2], int sock_type);
1000 
1001 /*
1002  * Convert domain name into IP address.
1003  *
1004  * This is a utility function. If compilation flags have
1005  * `-DMG_ENABLE_GETADDRINFO`, then `getaddrinfo()` call is used for name
1006  * resolution. Otherwise, `gethostbyname()` is used.
1007  *
1008  * CAUTION: this function can block.
1009  * Return 1 on success, 0 on failure.
1010  */
1011 #ifndef MG_DISABLE_SYNC_RESOLVER
1012 int mg_resolve(const char *domain_name, char *ip_addr_buf, size_t buf_len);
1013 #endif
1014 
1015 /*
1016  * Verify given IP address against the ACL.
1017  *
1018  * `remote_ip` - an IPv4 address to check, in host byte order
1019  * `acl` - a comma separated list of IP subnets: `x.x.x.x/x` or `x.x.x.x`.
1020  * Each subnet is
1021  * prepended by either a - or a + sign. A plus sign means allow, where a
1022  * minus sign means deny. If a subnet mask is omitted, such as `-1.2.3.4`,
1023  * this means to deny only that single IP address.
1024  * Subnet masks may vary from 0 to 32, inclusive. The default setting
1025  * is to allow all accesses. On each request the full list is traversed,
1026  * and the last match wins. Example:
1027  *
1028  * `-0.0.0.0/0,+192.168/16` - deny all acccesses, only allow 192.168/16 subnet
1029  *
1030  * To learn more about subnet masks, see the
1031  * link:https://en.wikipedia.org/wiki/Subnetwork[Wikipedia page on Subnetwork]
1032  *
1033  * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
1034  */
1035 int mg_check_ip_acl(const char *acl, uint32_t remote_ip);
1036 
1037 /*
1038  * Enable multi-threaded handling for the given listening connection `nc`.
1039  * For each accepted connection, Mongoose will create a separate thread
1040  * and run event handler in that thread. Thus, if an event hanler is doing
1041  * a blocking call or some long computation, that will not slow down
1042  * other connections.
1043  */
1045 
1046 #ifdef MG_ENABLE_JAVASCRIPT
1047 /*
1048  * Enable server-side JavaScript scripting.
1049  * Requires `-DMG_ENABLE_JAVASCRIPT` compilation flag, and V7 engine sources.
1050  * v7 instance must not be destroyed during manager's lifetime.
1051  * Return V7 error.
1052  */
1053 enum v7_err mg_enable_javascript(struct mg_mgr *m, struct v7 *v7,
1054  const char *init_js_file_name);
1055 #endif
1056 
1057 #ifdef __cplusplus
1058 }
1059 #endif /* __cplusplus */
1060 
1061 #endif /* MG_NET_HEADER_INCLUDED */
1062 #ifndef MG_NET_IF_HEADER_INCLUDED
1063 #define MG_NET_IF_HEADER_INCLUDED
1064 
1065 /*
1066  * Internal async networking core interface.
1067  * Consists of calls made by the core, which should not block,
1068  * and callbacks back into the core ("..._cb").
1069  * Callbacks may (will) cause methods to be invoked from within,
1070  * but methods are not allowed to invoke callbacks inline.
1071  *
1072  * Implementation must ensure that only one callback is invoked at any time.
1073  */
1074 
1075 /* Request that a TCP connection is made to the specified address. */
1076 void mg_if_connect_tcp(struct mg_connection *nc,
1077  const union socket_address *sa);
1078 /* Open a UDP socket. Doesn't actually connect anything. */
1079 void mg_if_connect_udp(struct mg_connection *nc);
1080 /* Callback invoked by connect methods. err = 0 -> ok, != 0 -> error. */
1081 void mg_if_connect_cb(struct mg_connection *nc, int err);
1082 
1083 /* Set up a listening TCP socket on a given address. rv = 0 -> ok. */
1084 int mg_if_listen_tcp(struct mg_connection *nc, union socket_address *sa);
1085 /* Deliver a new TCP connection. Returns NULL in case on error (unable to
1086  * create connection, in which case interface state should be discarded. */
1088  union socket_address *sa,
1089  size_t sa_len);
1090 
1091 /* Request that a "listening" UDP socket be created. */
1092 int mg_if_listen_udp(struct mg_connection *nc, union socket_address *sa);
1093 
1094 /* Send functions for TCP and UDP. Sent data is copied before return. */
1095 void mg_if_tcp_send(struct mg_connection *nc, const void *buf, size_t len);
1096 void mg_if_udp_send(struct mg_connection *nc, const void *buf, size_t len);
1097 /* Callback that reports that data has been put on the wire. */
1098 void mg_if_sent_cb(struct mg_connection *nc, int num_sent);
1099 
1100 /*
1101  * Receive callback.
1102  * buf must be heap-allocated and ownership is transferred to the core.
1103  * Core will acknowledge consumption by calling mg_if_recved.
1104  * No more than one chunk of data can be unacknowledged at any time.
1105  */
1106 void mg_if_recv_tcp_cb(struct mg_connection *nc, void *buf, int len);
1107 void mg_if_recv_udp_cb(struct mg_connection *nc, void *buf, int len,
1108  union socket_address *sa, size_t sa_len);
1109 void mg_if_recved(struct mg_connection *nc, size_t len);
1110 
1111 /* Deliver a POLL event to the connection. */
1112 void mg_if_poll(struct mg_connection *nc, time_t now);
1113 
1114 /* Perform interface-related cleanup on connection before destruction. */
1115 void mg_if_destroy_conn(struct mg_connection *nc);
1116 
1117 void mg_close_conn(struct mg_connection *nc);
1118 
1119 #endif /* MG_NET_IF_HEADER_INCLUDED */
1120 /*
1121  * Copyright (c) 2014 Cesanta Software Limited
1122  * All rights reserved
1123  */
1124 
1125 /*
1126  * === Utilities
1127  */
1128 
1129 #ifndef MG_UTIL_HEADER_DEFINED
1130 #define MG_UTIL_HEADER_DEFINED
1131 
1132 #include <stdio.h>
1133 
1134 
1135 #ifdef __cplusplus
1136 extern "C" {
1137 #endif /* __cplusplus */
1138 
1139 #ifndef MAX_PATH_SIZE
1140 #define MAX_PATH_SIZE 500
1141 #endif
1142 
1143 /*
1144  * Fetch substring from input string `s`, `end` into `v`.
1145  * Skips initial delimiter characters. Records first non-delimiter character
1146  * as the beginning of substring `v`. Then scans the rest of the string
1147  * until a delimiter character or end-of-string is found.
1148  * `delimiters` is a 0-terminated string containing delimiter characters.
1149  * Either one of `delimiters` or `end_string` terminates the search.
1150  * Return an `s` pointer, advanced forward where parsing stopped.
1151  */
1152 const char *mg_skip(const char *s, const char *end_string,
1153  const char *delimiters, struct mg_str *v);
1154 
1155 /*
1156  * Cross-platform version of `strncasecmp()`.
1157  */
1158 int mg_ncasecmp(const char *s1, const char *s2, size_t len);
1159 
1160 /*
1161  * Cross-platform version of `strcasecmp()`.
1162  */
1163 int mg_casecmp(const char *s1, const char *s2);
1164 
1165 /*
1166  * Cross-platform version of `strcmp()` where where first string is
1167  * specified by `struct mg_str`.
1168  */
1169 int mg_vcmp(const struct mg_str *str2, const char *str1);
1170 
1171 /*
1172  * Cross-platform version of `strncasecmp()` where first string is
1173  * specified by `struct mg_str`.
1174  */
1175 int mg_vcasecmp(const struct mg_str *str2, const char *str1);
1176 
1177 /*
1178  * Decode base64-encoded string `s`, `len` into the destination `dst`.
1179  * Destination has to have enough space to hold decoded buffer.
1180  * Decoding stops either when all string has been decoded, or invalid
1181  * character appeared.
1182  * Destination is '\0'-terminated.
1183  * Return number of decoded characters. On success, that should be equal to
1184  * `len`. On error (invalid character) the return value is smaller then `len`.
1185  */
1186 int mg_base64_decode(const unsigned char *s, int len, char *dst);
1187 
1188 /*
1189  * Base64-encode chunk of memory `src`, `src_len` into the destination `dst`.
1190  * Destination has to have enough space to hold encoded buffer.
1191  * Destination is '\0'-terminated.
1192  */
1193 void mg_base64_encode(const unsigned char *src, int src_len, char *dst);
1194 
1195 #ifndef MG_DISABLE_FILESYSTEM
1196 /*
1197  * Perform a 64-bit `stat()` call against given file.
1198  *
1199  * `path` should be UTF8 encoded.
1200  *
1201  * Return value is the same as for `stat()` syscall.
1202  */
1203 int mg_stat(const char *path, cs_stat_t *st);
1204 
1205 /*
1206  * Open the given file and return a file stream.
1207  *
1208  * `path` and `mode` should be UTF8 encoded.
1209  *
1210  * Return value is the same as for the `fopen()` call.
1211  */
1212 FILE *mg_fopen(const char *path, const char *mode);
1213 
1214 /*
1215  * Open the given file and return a file stream.
1216  *
1217  * `path` should be UTF8 encoded.
1218  *
1219  * Return value is the same as for the `open()` syscall.
1220  */
1221 int mg_open(const char *path, int flag, int mode);
1222 #endif /* MG_DISABLE_FILESYSTEM */
1223 
1224 #ifdef _WIN32
1225 #define MG_ENABLE_THREADS
1226 #endif
1227 
1228 #ifdef MG_ENABLE_THREADS
1229 /*
1230  * Start a new detached thread.
1231  * Arguments and semantic is the same as pthead's `pthread_create()`.
1232  * `thread_func` is a thread function, `thread_func_param` is a parameter
1233  * that is passed to the thread function.
1234  */
1235 void *mg_start_thread(void *(*thread_func)(void *), void *thread_func_param);
1236 #endif
1237 
1239 
1240 #define MG_SOCK_STRINGIFY_IP 1
1241 #define MG_SOCK_STRINGIFY_PORT 2
1242 #define MG_SOCK_STRINGIFY_REMOTE 4
1243 /*
1244  * Convert socket's local or remote address into string.
1245  *
1246  * The `flags` parameter is a bit mask that controls the behavior,
1247  * see `MG_SOCK_STRINGIFY_*` definitions.
1248  *
1249  * - MG_SOCK_STRINGIFY_IP - print IP address
1250  * - MG_SOCK_STRINGIFY_PORT - print port number
1251  * - MG_SOCK_STRINGIFY_REMOTE - print remote peer's IP/port, not local address
1252  *
1253  * If both port number and IP address are printed, they are separated by `:`.
1254  * If compiled with `-DMG_ENABLE_IPV6`, IPv6 addresses are supported.
1255  */
1256 void mg_sock_to_str(sock_t sock, char *buf, size_t len, int flags);
1257 
1258 /*
1259  * Convert socket's address into string.
1260  *
1261  * `flags` is MG_SOCK_STRINGIFY_IP and/or MG_SOCK_STRINGIFY_PORT.
1262  */
1263 void mg_sock_addr_to_str(const union socket_address *sa, char *buf, size_t len,
1264  int flags);
1265 
1266 /*
1267  * Generates human-readable hexdump of memory chunk.
1268  *
1269  * Takes a memory buffer `buf` of length `len` and creates a hex dump of that
1270  * buffer in `dst`. Generated output is a-la hexdump(1).
1271  * Return length of generated string, excluding terminating `\0`. If returned
1272  * length is bigger than `dst_len`, overflow bytes are discarded.
1273  */
1274 int mg_hexdump(const void *buf, int len, char *dst, int dst_len);
1275 
1276 /*
1277  * Generates human-readable hexdump of the data sent or received by connection.
1278  * `path` is a file name where hexdump should be written. `num_bytes` is
1279  * a number of bytes sent/received. `ev` is one of the `MG_*` events sent to
1280  * an event handler. This function is supposed to be called from the
1281  * event handler.
1282  */
1283 void mg_hexdump_connection(struct mg_connection *nc, const char *path,
1284  int num_bytes, int ev);
1285 /*
1286  * Print message to buffer. If buffer is large enough to hold the message,
1287  * return buffer. If buffer is to small, allocate large enough buffer on heap,
1288  * and return allocated buffer.
1289  * This is a supposed use case:
1290  *
1291  * char buf[5], *p = buf;
1292  * p = mg_avprintf(&p, sizeof(buf), "%s", "hi there");
1293  * use_p_somehow(p);
1294  * if (p != buf) {
1295  * free(p);
1296  * }
1297  *
1298  * The purpose of this is to avoid malloc-ing if generated strings are small.
1299  */
1300 int mg_avprintf(char **buf, size_t size, const char *fmt, va_list ap);
1301 
1302 /*
1303  * Return true if target platform is big endian.
1304  */
1305 int mg_is_big_endian(void);
1306 
1307 /*
1308  * A helper function for traversing a comma separated list of values.
1309  * It returns a list pointer shifted to the next value, or NULL if the end
1310  * of the list found.
1311  * Value is stored in val vector. If value has form "x=y", then eq_val
1312  * vector is initialized to point to the "y" part, and val vector length
1313  * is adjusted to point only to "x".
1314  * If list is just a comma separated list of entries, like "aa,bb,cc" then
1315  * `eq_val` will contain zero-length string.
1316  *
1317  * The purpose of this function is to parse comma separated string without
1318  * any copying/memory allocation.
1319  */
1320 const char *mg_next_comma_list_entry(const char *list, struct mg_str *val,
1321  struct mg_str *eq_val);
1322 
1323 /*
1324  * Match 0-terminated string against a glob pattern.
1325  * Match is case-insensitive. Return number of bytes matched, or -1 if no match.
1326  */
1327 int mg_match_prefix(const char *pattern, int pattern_len, const char *str);
1328 
1329 #ifdef __cplusplus
1330 }
1331 #endif /* __cplusplus */
1332 #endif /* MG_UTIL_HEADER_DEFINED */
1333 /*
1334  * Copyright (c) 2014 Cesanta Software Limited
1335  * All rights reserved
1336  */
1337 
1338 /*
1339  * === HTTP + Websocket
1340  */
1341 
1342 #ifndef MG_HTTP_HEADER_DEFINED
1343 #define MG_HTTP_HEADER_DEFINED
1344 
1345 
1346 #ifdef __cplusplus
1347 extern "C" {
1348 #endif /* __cplusplus */
1349 
1350 #ifndef MG_MAX_HTTP_HEADERS
1351 #define MG_MAX_HTTP_HEADERS 40
1352 #endif
1353 
1354 #ifndef MG_MAX_HTTP_REQUEST_SIZE
1355 #define MG_MAX_HTTP_REQUEST_SIZE 8192
1356 #endif
1357 
1358 #ifndef MG_MAX_PATH
1359 #ifdef PATH_MAX
1360 #define MG_MAX_PATH PATH_MAX
1361 #else
1362 #define MG_MAX_PATH 1024
1363 #endif
1364 #endif
1365 
1366 #ifndef MG_MAX_HTTP_SEND_IOBUF
1367 #define MG_MAX_HTTP_SEND_IOBUF 4096
1368 #endif
1369 
1370 #ifndef MG_WEBSOCKET_PING_INTERVAL_SECONDS
1371 #define MG_WEBSOCKET_PING_INTERVAL_SECONDS 5
1372 #endif
1373 
1374 #ifndef MG_CGI_ENVIRONMENT_SIZE
1375 #define MG_CGI_ENVIRONMENT_SIZE 8192
1376 #endif
1377 
1378 #ifndef MG_MAX_CGI_ENVIR_VARS
1379 #define MG_MAX_CGI_ENVIR_VARS 64
1380 #endif
1381 
1382 #ifndef MG_ENV_EXPORT_TO_CGI
1383 #define MG_ENV_EXPORT_TO_CGI "MONGOOSE_CGI"
1384 #endif
1385 
1386 /* HTTP message */
1388  struct mg_str message; /* Whole message: request line + headers + body */
1389 
1390  /* HTTP Request line (or HTTP response line) */
1391  struct mg_str method; /* "GET" */
1392  struct mg_str uri; /* "/my_file.html" */
1393  struct mg_str proto; /* "HTTP/1.1" -- for both request and response */
1394 
1395  /* For responses, code and response status message are set */
1398 
1399  /*
1400  * Query-string part of the URI. For example, for HTTP request
1401  * GET /foo/bar?param1=val1&param2=val2
1402  * | uri | query_string |
1403  *
1404  * Note that question mark character doesn't belong neither to the uri,
1405  * nor to the query_string
1406  */
1408 
1409  /* Headers */
1412 
1413  /* Message body */
1414  struct mg_str body; /* Zero-length for requests with no body */
1415 };
1416 
1418  unsigned char *data;
1419  size_t size;
1420  unsigned char flags;
1421 };
1422 
1423 /* HTTP and websocket events. void *ev_data is described in a comment. */
1424 #define MG_EV_HTTP_REQUEST 100 /* struct http_message * */
1425 #define MG_EV_HTTP_REPLY 101 /* struct http_message * */
1426 #define MG_EV_HTTP_CHUNK 102 /* struct http_message * */
1427 #define MG_EV_SSI_CALL 105 /* char * */
1428 
1429 #define MG_EV_WEBSOCKET_HANDSHAKE_REQUEST 111 /* NULL */
1430 #define MG_EV_WEBSOCKET_HANDSHAKE_DONE 112 /* NULL */
1431 #define MG_EV_WEBSOCKET_FRAME 113 /* struct websocket_message * */
1432 #define MG_EV_WEBSOCKET_CONTROL_FRAME 114 /* struct websocket_message * */
1433 
1434 /*
1435  * Attach built-in HTTP event handler to the given connection.
1436  * User-defined event handler will receive following extra events:
1437  *
1438  * - MG_EV_HTTP_REQUEST: HTTP request has arrived. Parsed HTTP request is passed
1439  *as
1440  * `struct http_message` through the handler's `void *ev_data` pointer.
1441  * - MG_EV_HTTP_REPLY: HTTP reply has arrived. Parsed HTTP reply is passed as
1442  * `struct http_message` through the handler's `void *ev_data` pointer.
1443  * - MG_EV_HTTP_CHUNK: HTTP chunked-encoding chunk has arrived.
1444  * Parsed HTTP reply is passed as `struct http_message` through the
1445  * handler's `void *ev_data` pointer. `http_message::body` would contain
1446  * incomplete, reassembled HTTP body.
1447  * It will grow with every new chunk arrived, and
1448  * potentially can consume a lot of memory. An event handler may process
1449  * the body as chunks are coming, and signal Mongoose to delete processed
1450  * body by setting `MG_F_DELETE_CHUNK` in `mg_connection::flags`. When
1451  * the last zero chunk is received,
1452  * Mongoose sends `MG_EV_HTTP_REPLY` event with
1453  * full reassembled body (if handler did not signal to delete chunks) or
1454  * with empty body (if handler did signal to delete chunks).
1455  * - MG_EV_WEBSOCKET_HANDSHAKE_REQUEST: server has received websocket handshake
1456  * request. `ev_data` contains parsed HTTP request.
1457  * - MG_EV_WEBSOCKET_HANDSHAKE_DONE: server has completed Websocket handshake.
1458  * `ev_data` is `NULL`.
1459  * - MG_EV_WEBSOCKET_FRAME: new websocket frame has arrived. `ev_data` is
1460  * `struct websocket_message *`
1461  */
1463 
1464 /*
1465  * Send websocket handshake to the server.
1466  *
1467  * `nc` must be a valid connection, connected to a server. `uri` is an URI
1468  * to fetch, extra_headers` is extra HTTP headers to send or `NULL`.
1469  *
1470  * This function is intended to be used by websocket client.
1471  */
1472 void mg_send_websocket_handshake(struct mg_connection *nc, const char *uri,
1473  const char *extra_headers);
1474 
1475 /*
1476  * Send websocket frame to the remote end.
1477  *
1478  * `op_and_flags` specifies frame's type, one of:
1479  *
1480  * - WEBSOCKET_OP_CONTINUE
1481  * - WEBSOCKET_OP_TEXT
1482  * - WEBSOCKET_OP_BINARY
1483  * - WEBSOCKET_OP_CLOSE
1484  * - WEBSOCKET_OP_PING
1485  * - WEBSOCKET_OP_PONG
1486  *
1487  * Orred with one of the flags:
1488  *
1489  * - WEBSOCKET_DONT_FIN: Don't set the FIN flag on the frame to be sent.
1490  *
1491  * `data` and `data_len` contain frame data.
1492  */
1493 void mg_send_websocket_frame(struct mg_connection *nc, int op_and_flags,
1494  const void *data, size_t data_len);
1495 
1496 /*
1497  * Send multiple websocket frames.
1498  *
1499  * Like `mg_send_websocket_frame()`, but composes a frame from multiple buffers.
1500  */
1501 void mg_send_websocket_framev(struct mg_connection *nc, int op_and_flags,
1502  const struct mg_str *strings, int num_strings);
1503 
1504 /*
1505  * Send websocket frame to the remote end.
1506  *
1507  * Like `mg_send_websocket_frame()`, but allows to create formatted message
1508  * with `printf()`-like semantics.
1509  */
1510 void mg_printf_websocket_frame(struct mg_connection *nc, int op_and_flags,
1511  const char *fmt, ...);
1512 
1513 /*
1514  * Send buffer `buf` of size `len` to the client using chunked HTTP encoding.
1515  * This function first sends buffer size as hex number + newline, then
1516  * buffer itself, then newline. For example,
1517  * `mg_send_http_chunk(nc, "foo", 3)` whill append `3\r\nfoo\r\n` string to
1518  * the `nc->send_mbuf` output IO buffer.
1519  *
1520  * NOTE: HTTP header "Transfer-Encoding: chunked" should be sent prior to
1521  * using this function.
1522  *
1523  * NOTE: do not forget to send empty chunk at the end of the response,
1524  * to tell the client that everything was sent. Example:
1525  *
1526  * ```
1527  * mg_printf_http_chunk(nc, "%s", "my response!");
1528  * mg_send_http_chunk(nc, "", 0); // Tell the client we're finished
1529  * ```
1530  */
1531 void mg_send_http_chunk(struct mg_connection *nc, const char *buf, size_t len);
1532 
1533 /*
1534  * Send printf-formatted HTTP chunk.
1535  * Functionality is similar to `mg_send_http_chunk()`.
1536  */
1537 void mg_printf_http_chunk(struct mg_connection *, const char *, ...);
1538 
1539 /*
1540  * Send response status line.
1541  * If `extra_headers` is not NULL, then `extra_headers` are also sent
1542  * after the reponse line. `extra_headers` must NOT end end with new line.
1543  * Example:
1544  *
1545  * mg_send_response_line(nc, 200, "Access-Control-Allow-Origin: *");
1546  *
1547  * Will result in:
1548  *
1549  * HTTP/1.1 200 OK\r\n
1550  * Access-Control-Allow-Origin: *\r\n
1551  */
1552 void mg_send_response_line(struct mg_connection *c, int status_code,
1553  const char *extra_headers);
1554 
1555 /*
1556  * Send response line and headers.
1557  * This function sends response line with the `status_code`, and automatically
1558  * sends one header: either "Content-Length", or "Transfer-Encoding".
1559  * If `content_length` is negative, then "Transfer-Encoding: chunked" header
1560  * is sent, otherwise, "Content-Length" header is sent.
1561  *
1562  * NOTE: If `Transfer-Encoding` is `chunked`, then message body must be sent
1563  * using `mg_send_http_chunk()` or `mg_printf_http_chunk()` functions.
1564  * Otherwise, `mg_send()` or `mg_printf()` must be used.
1565  * Extra headers could be set through `extra_headers` - and note `extra_headers`
1566  * must NOT be terminated by a new line.
1567  */
1568 void mg_send_head(struct mg_connection *n, int status_code,
1569  int64_t content_length, const char *extra_headers);
1570 
1571 /*
1572  * Send printf-formatted HTTP chunk, escaping HTML tags.
1573  */
1574 void mg_printf_html_escape(struct mg_connection *, const char *, ...);
1575 
1576 /* Websocket opcodes, from http://tools.ietf.org/html/rfc6455 */
1577 #define WEBSOCKET_OP_CONTINUE 0
1578 #define WEBSOCKET_OP_TEXT 1
1579 #define WEBSOCKET_OP_BINARY 2
1580 #define WEBSOCKET_OP_CLOSE 8
1581 #define WEBSOCKET_OP_PING 9
1582 #define WEBSOCKET_OP_PONG 10
1583 
1584 /*
1585  * If set causes the FIN flag to not be set on outbound
1586  * frames. This enables sending multiple fragments of a single
1587  * logical message.
1588  *
1589  * The WebSocket protocol mandates that if the FIN flag of a data
1590  * frame is not set, the next frame must be a WEBSOCKET_OP_CONTINUE.
1591  * The last frame must have the FIN bit set.
1592  *
1593  * Note that mongoose will automatically defragment incoming messages,
1594  * so this flag is used only on outbound messages.
1595  */
1596 #define WEBSOCKET_DONT_FIN 0x100
1597 
1598 /*
1599  * Parse a HTTP message.
1600  *
1601  * `is_req` should be set to 1 if parsing request, 0 if reply.
1602  *
1603  * Return number of bytes parsed. If HTTP message is
1604  * incomplete, `0` is returned. On parse error, negative number is returned.
1605  */
1606 int mg_parse_http(const char *s, int n, struct http_message *hm, int is_req);
1607 
1608 /*
1609  * Search and return header `name` in parsed HTTP message `hm`.
1610  * If header is not found, NULL is returned. Example:
1611  *
1612  * struct mg_str *host_hdr = mg_get_http_header(hm, "Host");
1613  */
1614 struct mg_str *mg_get_http_header(struct http_message *hm, const char *name);
1615 
1616 /*
1617  * Parse HTTP header `hdr`. Find variable `var_name` and store it's value
1618  * in the buffer `buf`, `buf_size`. Return 0 if variable not found, non-zero
1619  * otherwise.
1620  *
1621  * This function is supposed to parse
1622  * cookies, authentication headers, etcetera. Example (error handling omitted):
1623  *
1624  * char user[20];
1625  * struct mg_str *hdr = mg_get_http_header(hm, "Authorization");
1626  * mg_http_parse_header(hdr, "username", user, sizeof(user));
1627  *
1628  * Return length of the variable's value. If buffer is not large enough,
1629  * or variable not found, 0 is returned.
1630  */
1631 int mg_http_parse_header(struct mg_str *hdr, const char *var_name, char *buf,
1632  size_t buf_size);
1633 
1634 /*
1635  * Parse buffer `buf`, `buf_len` that contains multipart form data chunks.
1636  * Store chunk name in a `var_name`, `var_name_len` buffer.
1637  * If a chunk is an uploaded file, then `file_name`, `file_name_len` is
1638  * filled with an uploaded file name. `chunk`, `chunk_len`
1639  * points to the chunk data.
1640  *
1641  * Return: number of bytes to skip to the next chunk, or 0 if there are
1642  * no more chunks.
1643  *
1644  * Usage example:
1645  *
1646  * static void ev_handler(struct mg_connection *nc, int ev, void *ev_data) {
1647  * switch(ev) {
1648  * case MG_EV_HTTP_REQUEST: {
1649  * struct http_message *hm = (struct http_message *) ev_data;
1650  * char var_name[100], file_name[100];
1651  * const char *chunk;
1652  * size_t chunk_len, n1, n2;
1653  *
1654  * n1 = n2 = 0;
1655  * while ((n2 = mg_parse_multipart(hm->body.p + n1,
1656  * hm->body.len - n1,
1657  * var_name, sizeof(var_name),
1658  * file_name, sizeof(file_name),
1659  * &chunk, &chunk_len)) > 0) {
1660  * printf("var: %s, file_name: %s, size: %d, chunk: [%.*s]\n",
1661  * var_name, file_name, (int) chunk_len,
1662  * (int) chunk_len, chunk);
1663  * n1 += n2;
1664  * }
1665  * }
1666  * break;
1667  *
1668  */
1669 size_t mg_parse_multipart(const char *buf, size_t buf_len, char *var_name,
1670  size_t var_name_len, char *file_name,
1671  size_t file_name_len, const char **chunk,
1672  size_t *chunk_len);
1673 
1674 /*
1675  * Fetch an HTTP form variable.
1676  *
1677  * Fetch a variable `name` from a `buf` into a buffer specified by
1678  * `dst`, `dst_len`. Destination is always zero-terminated. Return length
1679  * of a fetched variable. If not found, 0 is returned. `buf` must be
1680  * valid url-encoded buffer. If destination is too small, `-1` is returned.
1681  */
1682 int mg_get_http_var(const struct mg_str *, const char *, char *dst, size_t);
1683 
1684 /* Create Digest authentication header for client request. */
1685 int mg_http_create_digest_auth_header(char *buf, size_t buf_len,
1686  const char *method, const char *uri,
1687  const char *auth_domain, const char *user,
1688  const char *passwd);
1689 /*
1690  * Helper function that creates outbound HTTP connection.
1691  *
1692  * `url` is a URL to fetch. It must be properly URL-encoded, e.g. have
1693  * no spaces, etc. By default, `mg_connect_http()` sends Connection and
1694  * Host headers. `extra_headers` is an extra HTTP headers to send, e.g.
1695  * `"User-Agent: my-app\r\n"`.
1696  * If `post_data` is NULL, then GET request is created. Otherwise, POST request
1697  * is created with the specified POST data. Examples:
1698  *
1699  * [source,c]
1700  * ----
1701  * nc1 = mg_connect_http(mgr, ev_handler_1, "http://www.google.com", NULL,
1702  * NULL);
1703  * nc2 = mg_connect_http(mgr, ev_handler_1, "https://github.com", NULL, NULL);
1704  * nc3 = mg_connect_http(mgr, ev_handler_1, "my_server:8000/form_submit/",
1705  * NULL, "var_1=value_1&var_2=value_2");
1706  * ----
1707  */
1708 struct mg_connection *mg_connect_http(struct mg_mgr *,
1709  mg_event_handler_t event_handler,
1710  const char *url,
1711  const char *extra_headers,
1712  const char *post_data);
1713 
1714 /*
1715  * This structure defines how `mg_serve_http()` works.
1716  * Best practice is to set only required settings, and leave the rest as NULL.
1717  */
1719  /* Path to web root directory */
1720  const char *document_root;
1721 
1722  /* List of index files. Default is "" */
1723  const char *index_files;
1724 
1725  /* Path to a HTTP requests log file. Leave as NULL to disable access log. */
1726  const char *access_log_file;
1727 
1728  /*
1729  * Leave as NULL to disable authentication.
1730  * To enable directory protection with authentication, set this to ".htpasswd"
1731  * Then, creating ".htpasswd" file in any directory automatically protects
1732  * it with digest authentication.
1733  * Use `mongoose` web server binary, or `htdigest` Apache utility to
1734  * create/manipulate passwords file.
1735  * Make sure `auth_domain` is set to a valid domain name.
1736  */
1738 
1739  /* Authorization domain (domain name of this web server) */
1740  const char *auth_domain;
1741 
1742  /*
1743  * Leave as NULL to disable authentication.
1744  * Normally, only selected directories in the document root are protected.
1745  * If absolutely every access to the web server needs to be authenticated,
1746  * regardless of the URI, set this option to the path to the passwords file.
1747  * Format of that file is the same as ".htpasswd" file. Make sure that file
1748  * is located outside document root to prevent people fetching it.
1749  */
1750  const char *global_auth_file;
1751 
1752  /* Set to "no" to disable directory listing. Enabled by default. */
1754 
1755  /* SSI files pattern. If not set, "**.shtml$|**.shtm$" is used. */
1756  const char *ssi_pattern;
1757 
1758  /* IP ACL. By default, NULL, meaning all IPs are allowed to connect */
1759  const char *ip_acl;
1760 
1761  /* URL rewrites.
1762  *
1763  * Comma-separated list of `uri_pattern=file_or_directory_path` rewrites.
1764  * When HTTP request is received, Mongoose constructs a file name from the
1765  * requested URI by combining `document_root` and the URI. However, if the
1766  * rewrite option is used and `uri_pattern` matches requested URI, then
1767  * `document_root` is ignored. Instead, `file_or_directory_path` is used,
1768  * which should be a full path name or a path relative to the web server's
1769  * current working directory. Note that `uri_pattern`, as all Mongoose
1770  * patterns, is a prefix pattern.
1771  *
1772  * If uri_pattern starts with `@` symbol, then Mongoose compares it with the
1773  * HOST header of the request. If they are equal, Mongoose sets document root
1774  * to `file_or_directory_path`, implementing virtual hosts support.
1775  */
1776  const char *url_rewrites;
1777 
1778  /* DAV document root. If NULL, DAV requests are going to fail. */
1779  const char *dav_document_root;
1780 
1781  /* DAV passwords file. If NULL, DAV requests are going to fail. */
1782  const char *dav_auth_file;
1783 
1784  /* Glob pattern for the files to hide. */
1785  const char *hidden_file_pattern;
1786 
1787  /* Set to non-NULL to enable CGI, e.g. **.cgi$|**.php$" */
1788  const char *cgi_file_pattern;
1789 
1790  /* If not NULL, ignore CGI script hashbang and use this interpreter */
1791  const char *cgi_interpreter;
1792 
1793  /*
1794  * Comma-separated list of Content-Type overrides for path suffixes, e.g.
1795  * ".txt=text/plain; charset=utf-8,.c=text/plain"
1796  */
1797  const char *custom_mime_types;
1798 
1799  /*
1800  * Extra HTTP headers to add to each server response.
1801  * Example: to enable CORS, set this to "Access-Control-Allow-Origin: *".
1802  */
1803  const char *extra_headers;
1804 };
1805 
1806 /*
1807  * Serve given HTTP request according to the `options`.
1808  *
1809  * Example code snippet:
1810  *
1811  * [source,c]
1812  * .web_server.c
1813  * ----
1814  * static void ev_handler(struct mg_connection *nc, int ev, void *ev_data) {
1815  * struct http_message *hm = (struct http_message *) ev_data;
1816  * struct mg_serve_http_opts opts = { .document_root = "/var/www" }; // C99
1817  *
1818  * switch (ev) {
1819  * case MG_EV_HTTP_REQUEST:
1820  * mg_serve_http(nc, hm, opts);
1821  * break;
1822  * default:
1823  * break;
1824  * }
1825  * }
1826  * ----
1827  */
1828 void mg_serve_http(struct mg_connection *, struct http_message *,
1829  struct mg_serve_http_opts);
1830 
1831 #ifdef __cplusplus
1832 }
1833 #endif /* __cplusplus */
1834 #endif /* MG_HTTP_HEADER_DEFINED */
1835 /*
1836  * Copyright (c) 2014 Cesanta Software Limited
1837  * All rights reserved
1838  */
1839 
1840 /*
1841  * === JSON-RPC
1842  */
1843 
1844 #ifndef MG_JSON_RPC_HEADER_DEFINED
1845 #define MG_JSON_RPC_HEADER_DEFINED
1846 
1847 #ifdef __cplusplus
1848 extern "C" {
1849 #endif /* __cplusplus */
1850 
1851 /* JSON-RPC request */
1853  struct json_token *message; /* Whole RPC message */
1854  struct json_token *id; /* Message ID */
1855  struct json_token *method; /* Method name */
1856  struct json_token *params; /* Method params */
1857 };
1858 
1859 /* JSON-RPC response */
1861  struct json_token *message; /* Whole RPC message */
1862  struct json_token *id; /* Message ID */
1863  struct json_token *result; /* Remote call result */
1864 };
1865 
1866 /* JSON-RPC error */
1868  struct json_token *message; /* Whole RPC message */
1869  struct json_token *id; /* Message ID */
1870  struct json_token *error_code; /* error.code */
1871  struct json_token *error_message; /* error.message */
1872  struct json_token *error_data; /* error.data, can be NULL */
1873 };
1874 
1875 /*
1876  * Parse JSON-RPC reply contained in `buf`, `len` into JSON tokens array
1877  * `toks`, `max_toks`. If buffer contains valid reply, `reply` structure is
1878  * populated. The result of RPC call is located in `reply.result`. On error,
1879  * `error` structure is populated. Returns: the result of calling
1880  * `parse_json(buf, len, toks, max_toks)`:
1881  *
1882  * On success, an offset inside `json_string` is returned
1883  * where parsing has finished. On failure, a negative number is
1884  * returned, one of:
1885  *
1886  * - #define JSON_STRING_INVALID -1
1887  * - #define JSON_STRING_INCOMPLETE -2
1888  * - #define JSON_TOKEN_ARRAY_TOO_SMALL -3
1889  */
1890 int mg_rpc_parse_reply(const char *buf, int len, struct json_token *toks,
1891  int max_toks, struct mg_rpc_reply *,
1892  struct mg_rpc_error *);
1893 
1894 /*
1895  * Create JSON-RPC request in a given buffer.
1896  *
1897  * Return length of the request, which
1898  * can be larger then `len` that indicates an overflow.
1899  * `params_fmt` format string should conform to `json_emit()` API,
1900  * see https://github.com/cesanta/frozen
1901  */
1902 int mg_rpc_create_request(char *buf, int len, const char *method,
1903  const char *id, const char *params_fmt, ...);
1904 
1905 /*
1906  * Create JSON-RPC reply in a given buffer.
1907  *
1908  * Return length of the reply, which
1909  * can be larger then `len` that indicates an overflow.
1910  * `result_fmt` format string should conform to `json_emit()` API,
1911  * see https://github.com/cesanta/frozen
1912  */
1913 int mg_rpc_create_reply(char *buf, int len, const struct mg_rpc_request *req,
1914  const char *result_fmt, ...);
1915 
1916 /*
1917  * Create JSON-RPC error reply in a given buffer.
1918  *
1919  * Return length of the error, which
1920  * can be larger then `len` that indicates an overflow.
1921  * `fmt` format string should conform to `json_emit()` API,
1922  * see https://github.com/cesanta/frozen
1923  */
1924 int mg_rpc_create_error(char *buf, int len, struct mg_rpc_request *req,
1925  int code, const char *message, const char *fmt, ...);
1926 
1927 /* JSON-RPC standard error codes */
1928 #define JSON_RPC_PARSE_ERROR (-32700)
1929 #define JSON_RPC_INVALID_REQUEST_ERROR (-32600)
1930 #define JSON_RPC_METHOD_NOT_FOUND_ERROR (-32601)
1931 #define JSON_RPC_INVALID_PARAMS_ERROR (-32602)
1932 #define JSON_RPC_INTERNAL_ERROR (-32603)
1933 #define JSON_RPC_SERVER_ERROR (-32000)
1934 
1935 /*
1936  * Create JSON-RPC error in a given buffer.
1937  *
1938  * Return length of the error, which
1939  * can be larger then `len` that indicates an overflow. See
1940  * JSON_RPC_*_ERROR definitions for standard error values:
1941  *
1942  * - #define JSON_RPC_PARSE_ERROR (-32700)
1943  * - #define JSON_RPC_INVALID_REQUEST_ERROR (-32600)
1944  * - #define JSON_RPC_METHOD_NOT_FOUND_ERROR (-32601)
1945  * - #define JSON_RPC_INVALID_PARAMS_ERROR (-32602)
1946  * - #define JSON_RPC_INTERNAL_ERROR (-32603)
1947  * - #define JSON_RPC_SERVER_ERROR (-32000)
1948  */
1949 int mg_rpc_create_std_error(char *, int, struct mg_rpc_request *, int code);
1950 
1951 typedef int (*mg_rpc_handler_t)(char *buf, int len, struct mg_rpc_request *);
1952 
1953 /*
1954  * Dispatches a JSON-RPC request.
1955  *
1956  * Parses JSON-RPC request contained in `buf`, `len`.
1957  * Then, dispatches the request to the correct handler method.
1958  * Valid method names should be specified in NULL
1959  * terminated array `methods`, and corresponding handlers in `handlers`.
1960  * Result is put in `dst`, `dst_len`. Return: length of the result, which
1961  * can be larger then `dst_len` that indicates an overflow.
1962  * Overflown bytes are not written to the buffer.
1963  * If method is not found, an error is automatically generated.
1964  */
1965 int mg_rpc_dispatch(const char *buf, int, char *dst, int dst_len,
1966  const char **methods, mg_rpc_handler_t *handlers);
1967 
1968 #ifdef __cplusplus
1969 }
1970 #endif /* __cplusplus */
1971 #endif /* MG_JSON_RPC_HEADER_DEFINED */
1972 /*
1973  * Copyright (c) 2014 Cesanta Software Limited
1974  * All rights reserved
1975  * This software is dual-licensed: you can redistribute it and/or modify
1976  * it under the terms of the GNU General Public License version 2 as
1977  * published by the Free Software Foundation. For the terms of this
1978  * license, see <http://www.gnu.org/licenses/>.
1979  *
1980  * You are free to use this software under the terms of the GNU General
1981  * Public License, but WITHOUT ANY WARRANTY; without even the implied
1982  * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
1983  * See the GNU General Public License for more details.
1984  *
1985  * Alternatively, you can license this software under a commercial
1986  * license, as set out in <https://www.cesanta.com/license>.
1987  */
1988 
1989 /*
1990  * === MQTT
1991  */
1992 
1993 #ifndef MG_MQTT_HEADER_INCLUDED
1994 #define MG_MQTT_HEADER_INCLUDED
1995 
1996 
1998  int cmd;
1999  struct mg_str payload;
2000  int qos;
2001  uint8_t connack_ret_code; /* connack */
2002  uint16_t message_id; /* puback */
2003  char *topic;
2004 };
2005 
2007  const char *topic;
2008  uint8_t qos;
2009 };
2010 
2012  unsigned char flags; /* connection flags */
2013  uint16_t keep_alive;
2014  const char *will_topic;
2015  const char *will_message;
2016  const char *user_name;
2017  const char *password;
2018 };
2019 
2020 /* Message types */
2021 #define MG_MQTT_CMD_CONNECT 1
2022 #define MG_MQTT_CMD_CONNACK 2
2023 #define MG_MQTT_CMD_PUBLISH 3
2024 #define MG_MQTT_CMD_PUBACK 4
2025 #define MG_MQTT_CMD_PUBREC 5
2026 #define MG_MQTT_CMD_PUBREL 6
2027 #define MG_MQTT_CMD_PUBCOMP 7
2028 #define MG_MQTT_CMD_SUBSCRIBE 8
2029 #define MG_MQTT_CMD_SUBACK 9
2030 #define MG_MQTT_CMD_UNSUBSCRIBE 10
2031 #define MG_MQTT_CMD_UNSUBACK 11
2032 #define MG_MQTT_CMD_PINGREQ 12
2033 #define MG_MQTT_CMD_PINGRESP 13
2034 #define MG_MQTT_CMD_DISCONNECT 14
2035 
2036 /* MQTT event types */
2037 #define MG_MQTT_EVENT_BASE 200
2038 #define MG_EV_MQTT_CONNECT (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_CONNECT)
2039 #define MG_EV_MQTT_CONNACK (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_CONNACK)
2040 #define MG_EV_MQTT_PUBLISH (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_PUBLISH)
2041 #define MG_EV_MQTT_PUBACK (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_PUBACK)
2042 #define MG_EV_MQTT_PUBREC (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_PUBREC)
2043 #define MG_EV_MQTT_PUBREL (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_PUBREL)
2044 #define MG_EV_MQTT_PUBCOMP (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_PUBCOMP)
2045 #define MG_EV_MQTT_SUBSCRIBE (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_SUBSCRIBE)
2046 #define MG_EV_MQTT_SUBACK (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_SUBACK)
2047 #define MG_EV_MQTT_UNSUBSCRIBE (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_UNSUBSCRIBE)
2048 #define MG_EV_MQTT_UNSUBACK (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_UNSUBACK)
2049 #define MG_EV_MQTT_PINGREQ (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_PINGREQ)
2050 #define MG_EV_MQTT_PINGRESP (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_PINGRESP)
2051 #define MG_EV_MQTT_DISCONNECT (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_DISCONNECT)
2052 
2053 /* Message flags */
2054 #define MG_MQTT_RETAIN 0x1
2055 #define MG_MQTT_DUP 0x4
2056 #define MG_MQTT_QOS(qos) ((qos) << 1)
2057 #define MG_MQTT_GET_QOS(flags) (((flags) &0x6) >> 1)
2058 #define MG_MQTT_SET_QOS(flags, qos) (flags) = ((flags) & ~0x6) | ((qos) << 1)
2059 
2060 /* Connection flags */
2061 #define MG_MQTT_CLEAN_SESSION 0x02
2062 #define MG_MQTT_HAS_WILL 0x04
2063 #define MG_MQTT_WILL_RETAIN 0x20
2064 #define MG_MQTT_HAS_PASSWORD 0x40
2065 #define MG_MQTT_HAS_USER_NAME 0x80
2066 #define MG_MQTT_GET_WILL_QOS(flags) (((flags) &0x18) >> 3)
2067 #define MG_MQTT_SET_WILL_QOS(flags, qos) \
2068  (flags) = ((flags) & ~0x18) | ((qos) << 3)
2069 
2070 /* CONNACK return codes */
2071 #define MG_EV_MQTT_CONNACK_ACCEPTED 0
2072 #define MG_EV_MQTT_CONNACK_UNACCEPTABLE_VERSION 1
2073 #define MG_EV_MQTT_CONNACK_IDENTIFIER_REJECTED 2
2074 #define MG_EV_MQTT_CONNACK_SERVER_UNAVAILABLE 3
2075 #define MG_EV_MQTT_CONNACK_BAD_AUTH 4
2076 #define MG_EV_MQTT_CONNACK_NOT_AUTHORIZED 5
2077 
2078 #ifdef __cplusplus
2079 extern "C" {
2080 #endif /* __cplusplus */
2081 
2082 /*
2083  * Attach built-in MQTT event handler to the given connection.
2084  *
2085  * The user-defined event handler will receive following extra events:
2086  *
2087  * - MG_EV_MQTT_CONNACK
2088  * - MG_EV_MQTT_PUBLISH
2089  * - MG_EV_MQTT_PUBACK
2090  * - MG_EV_MQTT_PUBREC
2091  * - MG_EV_MQTT_PUBREL
2092  * - MG_EV_MQTT_PUBCOMP
2093  * - MG_EV_MQTT_SUBACK
2094  */
2095 void mg_set_protocol_mqtt(struct mg_connection *);
2096 
2097 /* Send MQTT handshake. */
2098 void mg_send_mqtt_handshake(struct mg_connection *nc, const char *client_id);
2099 
2100 /* Send MQTT handshake with optional parameters. */
2101 void mg_send_mqtt_handshake_opt(struct mg_connection *, const char *client_id,
2103 
2104 /* Publish a message to a given topic. */
2105 void mg_mqtt_publish(struct mg_connection *nc, const char *topic,
2106  uint16_t message_id, int flags, const void *data,
2107  size_t len);
2108 
2109 /* Subscribe to a bunch of topics. */
2110 void mg_mqtt_subscribe(struct mg_connection *nc,
2111  const struct mg_mqtt_topic_expression *topics,
2112  size_t topics_len, uint16_t message_id);
2113 
2114 /* Unsubscribe from a bunch of topics. */
2115 void mg_mqtt_unsubscribe(struct mg_connection *nc, char **topics,
2116  size_t topics_len, uint16_t message_id);
2117 
2118 /* Send a DISCONNECT command. */
2119 void mg_mqtt_disconnect(struct mg_connection *nc);
2120 
2121 /* Send a CONNACK command with a given `return_code`. */
2122 void mg_mqtt_connack(struct mg_connection *, uint8_t);
2123 
2124 /* Send a PUBACK command with a given `message_id`. */
2125 void mg_mqtt_puback(struct mg_connection *, uint16_t);
2126 
2127 /* Send a PUBREC command with a given `message_id`. */
2128 void mg_mqtt_pubrec(struct mg_connection *, uint16_t);
2129 
2130 /* Send a PUBREL command with a given `message_id`. */
2131 void mg_mqtt_pubrel(struct mg_connection *, uint16_t);
2132 
2133 /* Send a PUBCOMP command with a given `message_id`. */
2134 void mg_mqtt_pubcomp(struct mg_connection *, uint16_t);
2135 
2136 /*
2137  * Send a SUBACK command with a given `message_id`
2138  * and a sequence of granted QoSs.
2139  */
2140 void mg_mqtt_suback(struct mg_connection *, uint8_t *, size_t, uint16_t);
2141 
2142 /* Send a UNSUBACK command with a given `message_id`. */
2143 void mg_mqtt_unsuback(struct mg_connection *, uint16_t);
2144 
2145 /* Send a PINGREQ command. */
2146 void mg_mqtt_ping(struct mg_connection *);
2147 
2148 /* Send a PINGRESP command. */
2149 void mg_mqtt_pong(struct mg_connection *);
2150 
2151 /*
2152  * Extract the next topic expression from a SUBSCRIBE command payload.
2153  *
2154  * Topic expression name will point to a string in the payload buffer.
2155  * Return the pos of the next topic expression or -1 when the list
2156  * of topics is exhausted.
2157  */
2158 int mg_mqtt_next_subscribe_topic(struct mg_mqtt_message *, struct mg_str *,
2159  uint8_t *, int);
2160 
2161 #ifdef __cplusplus
2162 }
2163 #endif /* __cplusplus */
2164 
2165 #endif /* MG_MQTT_HEADER_INCLUDED */
2166 /*
2167  * Copyright (c) 2014 Cesanta Software Limited
2168  * All rights reserved
2169  * This software is dual-licensed: you can redistribute it and/or modify
2170  * it under the terms of the GNU General Public License version 2 as
2171  * published by the Free Software Foundation. For the terms of this
2172  * license, see <http://www.gnu.org/licenses/>.
2173  *
2174  * You are free to use this software under the terms of the GNU General
2175  * Public License, but WITHOUT ANY WARRANTY; without even the implied
2176  * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
2177  * See the GNU General Public License for more details.
2178  *
2179  * Alternatively, you can license this software under a commercial
2180  * license, as set out in <https://www.cesanta.com/license>.
2181  */
2182 
2183 /*
2184  * === MQTT Broker
2185  */
2186 
2187 #ifndef MG_MQTT_BROKER_HEADER_INCLUDED
2188 #define MG_MQTT_BROKER_HEADER_INCLUDED
2189 
2190 #ifdef MG_ENABLE_MQTT_BROKER
2191 
2192 
2193 #ifdef __cplusplus
2194 extern "C" {
2195 #endif /* __cplusplus */
2196 
2197 #define MG_MQTT_MAX_SESSION_SUBSCRIPTIONS 512;
2198 
2199 struct mg_mqtt_broker;
2200 
2201 /* MQTT session (Broker side). */
2202 struct mg_mqtt_session {
2203  struct mg_mqtt_broker *brk; /* Broker */
2204  struct mg_mqtt_session *next, *prev; /* mg_mqtt_broker::sessions linkage */
2205  struct mg_connection *nc; /* Connection with the client */
2206  size_t num_subscriptions; /* Size of `subscriptions` array */
2207  struct mg_mqtt_topic_expression *subscriptions;
2208  void *user_data; /* User data */
2209 };
2210 
2211 /* MQTT broker. */
2212 struct mg_mqtt_broker {
2213  struct mg_mqtt_session *sessions; /* Session list */
2214  void *user_data; /* User data */
2215 };
2216 
2217 /* Initialize a MQTT broker. */
2218 void mg_mqtt_broker_init(struct mg_mqtt_broker *, void *);
2219 
2220 /*
2221  * Process a MQTT broker message.
2222  *
2223  * Listening connection expects a pointer to an initialized `mg_mqtt_broker`
2224  * structure in the `user_data` field.
2225  *
2226  * Basic usage:
2227  *
2228  * [source,c]
2229  * -----
2230  * mg_mqtt_broker_init(&brk, NULL);
2231  *
2232  * if ((nc = mg_bind(&mgr, address, mg_mqtt_broker)) == NULL) {
2233  * // fail;
2234  * }
2235  * nc->user_data = &brk;
2236  * -----
2237  *
2238  * New incoming connections will receive a `mg_mqtt_session` structure
2239  * in the connection `user_data`. The original `user_data` will be stored
2240  * in the `user_data` field of the session structure. This allows the user
2241  * handler to store user data before `mg_mqtt_broker` creates the session.
2242  *
2243  * Since only the MG_EV_ACCEPT message is processed by the listening socket,
2244  * for most events the `user_data` will thus point to a `mg_mqtt_session`.
2245  */
2246 void mg_mqtt_broker(struct mg_connection *, int, void *);
2247 
2248 /*
2249  * Iterate over all mqtt sessions connections. Example:
2250  *
2251  * struct mg_mqtt_session *s;
2252  * for (s = mg_mqtt_next(brk, NULL); s != NULL; s = mg_mqtt_next(brk, s)) {
2253  * // Do something
2254  * }
2255  */
2256 struct mg_mqtt_session *mg_mqtt_next(struct mg_mqtt_broker *,
2257  struct mg_mqtt_session *);
2258 
2259 #ifdef __cplusplus
2260 }
2261 #endif /* __cplusplus */
2262 
2263 #endif /* MG_ENABLE_MQTT_BROKER */
2264 #endif /* MG_MQTT_HEADER_INCLUDED */
2265 /*
2266  * Copyright (c) 2014 Cesanta Software Limited
2267  * All rights reserved
2268  */
2269 
2270 /*
2271  * === DNS
2272  */
2273 
2274 #ifndef MG_DNS_HEADER_DEFINED
2275 #define MG_DNS_HEADER_DEFINED
2276 
2277 
2278 #ifdef __cplusplus
2279 extern "C" {
2280 #endif /* __cplusplus */
2281 
2282 #define MG_DNS_A_RECORD 0x01 /* Lookup IP address */
2283 #define MG_DNS_CNAME_RECORD 0x05 /* Lookup CNAME */
2284 #define MG_DNS_AAAA_RECORD 0x1c /* Lookup IPv6 address */
2285 #define MG_DNS_MX_RECORD 0x0f /* Lookup mail server for domain */
2286 
2287 #define MG_MAX_DNS_QUESTIONS 32
2288 #define MG_MAX_DNS_ANSWERS 32
2289 
2290 #define MG_DNS_MESSAGE 100 /* High-level DNS message event */
2291 
2296 };
2297 
2298 /* DNS resource record. */
2300  struct mg_str name; /* buffer with compressed name */
2301  int rtype;
2302  int rclass;
2303  int ttl;
2305  struct mg_str rdata; /* protocol data (can be a compressed name) */
2306 };
2307 
2308 /* DNS message (request and response). */
2310  struct mg_str pkt; /* packet body */
2311  uint16_t flags;
2312  uint16_t transaction_id;
2317 };
2318 
2320  struct mg_dns_message *, int, struct mg_dns_resource_record *);
2321 
2322 /*
2323  * Parse the record data from a DNS resource record.
2324  *
2325  * - A: struct in_addr *ina
2326  * - AAAA: struct in6_addr *ina
2327  * - CNAME: char buffer
2328  *
2329  * Returns -1 on error.
2330  *
2331  * TODO(mkm): MX
2332  */
2334  struct mg_dns_resource_record *, void *, size_t);
2335 
2336 /*
2337  * Send a DNS query to the remote end.
2338  */
2339 void mg_send_dns_query(struct mg_connection *, const char *, int);
2340 
2341 /*
2342  * Insert a DNS header to an IO buffer.
2343  *
2344  * Return number of bytes inserted.
2345  */
2346 int mg_dns_insert_header(struct mbuf *, size_t, struct mg_dns_message *);
2347 
2348 /*
2349  * Append already encoded body from an existing message.
2350  *
2351  * This is useful when generating a DNS reply message which includes
2352  * all question records.
2353  *
2354  * Return number of appened bytes.
2355  */
2356 int mg_dns_copy_body(struct mbuf *, struct mg_dns_message *);
2357 
2358 /*
2359  * Encode and append a DNS resource record to an IO buffer.
2360  *
2361  * The record metadata is taken from the `rr` parameter, while the name and data
2362  * are taken from the parameters, encoded in the appropriate format depending on
2363  * record type, and stored in the IO buffer. The encoded values might contain
2364  * offsets within the IO buffer. It's thus important that the IO buffer doesn't
2365  * get trimmed while a sequence of records are encoded while preparing a DNS
2366  *reply.
2367  *
2368  * This function doesn't update the `name` and `rdata` pointers in the `rr`
2369  *struct
2370  * because they might be invalidated as soon as the IO buffer grows again.
2371  *
2372  * Return the number of bytes appened or -1 in case of error.
2373  */
2374 int mg_dns_encode_record(struct mbuf *, struct mg_dns_resource_record *,
2375  const char *, size_t, const void *, size_t);
2376 
2377 /* Low-level: parses a DNS response. */
2378 int mg_parse_dns(const char *, int, struct mg_dns_message *);
2379 
2380 /*
2381  * Uncompress a DNS compressed name.
2382  *
2383  * The containing dns message is required because the compressed encoding
2384  * and reference suffixes present elsewhere in the packet.
2385  *
2386  * If name is less than `dst_len` characters long, the remainder
2387  * of `dst` is terminated with `\0' characters. Otherwise, `dst` is not
2388  *terminated.
2389  *
2390  * If `dst_len` is 0 `dst` can be NULL.
2391  * Return the uncompressed name length.
2392  */
2393 size_t mg_dns_uncompress_name(struct mg_dns_message *, struct mg_str *, char *,
2394  int);
2395 
2396 /*
2397  * Attach built-in DNS event handler to the given listening connection.
2398  *
2399  * DNS event handler parses incoming UDP packets, treating them as DNS
2400  * requests. If incoming packet gets successfully parsed by the DNS event
2401  * handler, a user event handler will receive `MG_DNS_REQUEST` event, with
2402  * `ev_data` pointing to the parsed `struct mg_dns_message`.
2403  *
2404  * See
2405  * https://github.com/cesanta/mongoose/tree/master/examples/captive_dns_server[captive_dns_server]
2406  * example on how to handle DNS request and send DNS reply.
2407  */
2408 void mg_set_protocol_dns(struct mg_connection *);
2409 
2410 #ifdef __cplusplus
2411 }
2412 #endif /* __cplusplus */
2413 #endif /* MG_HTTP_HEADER_DEFINED */
2414 /*
2415  * Copyright (c) 2014 Cesanta Software Limited
2416  * All rights reserved
2417  */
2418 
2419 /*
2420  * === DNS server
2421  *
2422  * Disabled by default; enable with `-DMG_ENABLE_DNS_SERVER`.
2423  */
2424 
2425 #ifndef MG_DNS_SERVER_HEADER_DEFINED
2426 #define MG_DNS_SERVER_HEADER_DEFINED
2427 
2428 #ifdef MG_ENABLE_DNS_SERVER
2429 
2430 
2431 #ifdef __cplusplus
2432 extern "C" {
2433 #endif /* __cplusplus */
2434 
2435 #define MG_DNS_SERVER_DEFAULT_TTL 3600
2436 
2437 struct mg_dns_reply {
2438  struct mg_dns_message *msg;
2439  struct mbuf *io;
2440  size_t start;
2441 };
2442 
2443 /*
2444  * Create a DNS reply.
2445  *
2446  * The reply will be based on an existing query message `msg`.
2447  * The query body will be appended to the output buffer.
2448  * "reply + recursion allowed" will be added to the message flags and
2449  * message's num_answers will be set to 0.
2450  *
2451  * Answer records can be appended with `mg_dns_send_reply` or by lower
2452  * level function defined in the DNS API.
2453  *
2454  * In order to send the reply use `mg_dns_send_reply`.
2455  * It's possible to use a connection's send buffer as reply buffers,
2456  * and it will work for both UDP and TCP connections.
2457  *
2458  * Example:
2459  *
2460  * [source,c]
2461  * -----
2462  * reply = mg_dns_create_reply(&nc->send_mbuf, msg);
2463  * for (i = 0; i < msg->num_questions; i++) {
2464  * rr = &msg->questions[i];
2465  * if (rr->rtype == MG_DNS_A_RECORD) {
2466  * mg_dns_reply_record(&reply, rr, 3600, &dummy_ip_addr, 4);
2467  * }
2468  * }
2469  * mg_dns_send_reply(nc, &reply);
2470  * -----
2471  */
2472 struct mg_dns_reply mg_dns_create_reply(struct mbuf *, struct mg_dns_message *);
2473 
2474 /*
2475  * Append a DNS reply record to the IO buffer and to the DNS message.
2476  *
2477  * The message num_answers field will be incremented. It's caller's duty
2478  * to ensure num_answers is propertly initialized.
2479  *
2480  * Returns -1 on error.
2481  */
2482 int mg_dns_reply_record(struct mg_dns_reply *, struct mg_dns_resource_record *,
2483  const char *, int, int, const void *, size_t);
2484 
2485 /*
2486  * Send a DNS reply through a connection.
2487  *
2488  * The DNS data is stored in an IO buffer pointed by reply structure in `r`.
2489  * This function mutates the content of that buffer in order to ensure that
2490  * the DNS header reflects size and flags of the mssage, that might have been
2491  * updated either with `mg_dns_reply_record` or by direct manipulation of
2492  * `r->message`.
2493  *
2494  * Once sent, the IO buffer will be trimmed unless the reply IO buffer
2495  * is the connection's send buffer and the connection is not in UDP mode.
2496  */
2497 void mg_dns_send_reply(struct mg_connection *, struct mg_dns_reply *);
2498 
2499 #ifdef __cplusplus
2500 }
2501 #endif /* __cplusplus */
2502 
2503 #endif /* MG_ENABLE_DNS_SERVER */
2504 #endif /* MG_HTTP_HEADER_DEFINED */
2505 /*
2506  * Copyright (c) 2014 Cesanta Software Limited
2507  * All rights reserved
2508  */
2509 
2510 /*
2511  * === Asynchronouns DNS resolver
2512  */
2513 
2514 #ifndef MG_RESOLV_HEADER_DEFINED
2515 #define MG_RESOLV_HEADER_DEFINED
2516 
2517 
2518 #ifdef __cplusplus
2519 extern "C" {
2520 #endif /* __cplusplus */
2521 
2522 typedef void (*mg_resolve_callback_t)(struct mg_dns_message *, void *);
2523 
2524 /* Options for `mg_resolve_async_opt`. */
2526  const char *nameserver_url;
2527  int max_retries; /* defaults to 2 if zero */
2528  int timeout; /* in seconds; defaults to 5 if zero */
2529  int accept_literal; /* pseudo-resolve literal ipv4 and ipv6 addrs */
2530  int only_literal; /* only resolves literal addrs; sync cb invocation */
2531 };
2532 
2533 /* See `mg_resolve_async_opt()` */
2534 int mg_resolve_async(struct mg_mgr *, const char *, int, mg_resolve_callback_t,
2535  void *data);
2536 
2537 /*
2538  * Resolved a DNS name asynchronously.
2539  *
2540  * Upon successful resolution, the user callback will be invoked
2541  * with the full DNS response message and a pointer to the user's
2542  * context `data`.
2543  *
2544  * In case of timeout while performing the resolution the callback
2545  * will receive a NULL `msg`.
2546  *
2547  * The DNS answers can be extracted with `mg_next_record` and
2548  * `mg_dns_parse_record_data`:
2549  *
2550  * [source,c]
2551  * ----
2552  * struct in_addr ina;
2553  * struct mg_dns_resource_record *rr = mg_next_record(msg, MG_DNS_A_RECORD,
2554  * NULL);
2555  * mg_dns_parse_record_data(msg, rr, &ina, sizeof(ina));
2556  * ----
2557  */
2558 int mg_resolve_async_opt(struct mg_mgr *, const char *, int,
2559  mg_resolve_callback_t, void *data,
2560  struct mg_resolve_async_opts opts);
2561 
2562 /*
2563  * Resolve a name from `/etc/hosts`.
2564  *
2565  * Returns 0 on success, -1 on failure.
2566  */
2567 int mg_resolve_from_hosts_file(const char *host, union socket_address *usa);
2568 
2569 #ifdef __cplusplus
2570 }
2571 #endif /* __cplusplus */
2572 #endif /* MG_RESOLV_HEADER_DEFINED */
2573 /*
2574  * Copyright (c) 2015 Cesanta Software Limited
2575  * All rights reserved
2576  * This software is dual-licensed: you can redistribute it and/or modify
2577  * it under the terms of the GNU General Public License version 2 as
2578  * published by the Free Software Foundation. For the terms of this
2579  * license, see <http://www.gnu.org/licenses/>.
2580  *
2581  * You are free to use this software under the terms of the GNU General
2582  * Public License, but WITHOUT ANY WARRANTY; without even the implied
2583  * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
2584  * See the GNU General Public License for more details.
2585  *
2586  * Alternatively, you can license this software under a commercial
2587  * license, as set out in <https://www.cesanta.com/license>.
2588  */
2589 
2590 /*
2591  * === CoAP
2592  *
2593  * CoAP message format:
2594  *
2595  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
2596  * |Ver| T | TKL | Code | Message ID | Token (if any, TKL bytes) ...
2597  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
2598  * | Options (if any) ... |1 1 1 1 1 1 1 1| Payload (if any) ...
2599  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
2600  */
2601 
2602 #ifndef MG_COAP_HEADER_INCLUDED
2603 #define MG_COAP_HEADER_INCLUDED
2604 
2605 #ifdef MG_ENABLE_COAP
2606 
2607 #define MG_COAP_MSG_TYPE_FIELD 0x2
2608 #define MG_COAP_CODE_CLASS_FIELD 0x4
2609 #define MG_COAP_CODE_DETAIL_FIELD 0x8
2610 #define MG_COAP_MSG_ID_FIELD 0x10
2611 #define MG_COAP_TOKEN_FIELD 0x20
2612 #define MG_COAP_OPTIOMG_FIELD 0x40
2613 #define MG_COAP_PAYLOAD_FIELD 0x80
2614 
2615 #define MG_COAP_ERROR 0x10000
2616 #define MG_COAP_FORMAT_ERROR (MG_COAP_ERROR | 0x20000)
2617 #define MG_COAP_IGNORE (MG_COAP_ERROR | 0x40000)
2618 #define MG_COAP_NOT_ENOUGH_DATA (MG_COAP_ERROR | 0x80000)
2619 #define MG_COAP_NETWORK_ERROR (MG_COAP_ERROR | 0x100000)
2620 
2621 #define MG_COAP_MSG_CON 0
2622 #define MG_COAP_MSG_NOC 1
2623 #define MG_COAP_MSG_ACK 2
2624 #define MG_COAP_MSG_RST 3
2625 #define MG_COAP_MSG_MAX 3
2626 
2627 #define MG_COAP_CODECLASS_REQUEST 0
2628 #define MG_COAP_CODECLASS_RESP_OK 2
2629 #define MG_COAP_CODECLASS_CLIENT_ERR 4
2630 #define MG_COAP_CODECLASS_SRV_ERR 5
2631 
2632 #define MG_COAP_EVENT_BASE 300
2633 #define MG_EV_COAP_CON (MG_COAP_EVENT_BASE + MG_COAP_MSG_CON)
2634 #define MG_EV_COAP_NOC (MG_COAP_EVENT_BASE + MG_COAP_MSG_NOC)
2635 #define MG_EV_COAP_ACK (MG_COAP_EVENT_BASE + MG_COAP_MSG_ACK)
2636 #define MG_EV_COAP_RST (MG_COAP_EVENT_BASE + MG_COAP_MSG_RST)
2637 
2638 /*
2639  * CoAP options.
2640  * Use mg_coap_add_option and mg_coap_free_options
2641  * for creation and destruction.
2642  */
2643 struct mg_coap_option {
2644  struct mg_coap_option *next;
2645  uint32_t number;
2646  struct mg_str value;
2647 };
2648 
2649 /* CoAP message. See RFC 7252 for details. */
2650 struct mg_coap_message {
2651  uint32_t flags;
2652  uint8_t msg_type;
2653  uint8_t code_class;
2654  uint8_t code_detail;
2655  uint16_t msg_id;
2656  struct mg_str token;
2657  struct mg_coap_option *options;
2658  struct mg_str payload;
2659  struct mg_coap_option *optiomg_tail;
2660 };
2661 
2662 #ifdef __cplusplus
2663 extern "C" {
2664 #endif /* __cplusplus */
2665 
2666 /* Set CoAP protocol handler - trigger CoAP specific events */
2667 int mg_set_protocol_coap(struct mg_connection *nc);
2668 
2669 /*
2670  * Add new option to mg_coap_message structure.
2671  * Returns pointer to the newly created option.
2672  */
2673 struct mg_coap_option *mg_coap_add_option(struct mg_coap_message *cm,
2674  uint32_t number, char *value,
2675  size_t len);
2676 
2677 /*
2678  * Free the memory allocated for options,
2679  * if cm paramater doesn't contain any option does nothing.
2680  */
2681 void mg_coap_free_options(struct mg_coap_message *cm);
2682 
2683 /*
2684  * Compose CoAP message from `mg_coap_message`
2685  * and send it into `nc` connection.
2686  * Return 0 on success. On error, it is a bitmask:
2687  *
2688  * - #define MG_COAP_ERROR 0x10000
2689  * - #define MG_COAP_FORMAT_ERROR (MG_COAP_ERROR | 0x20000)
2690  * - #define MG_COAP_IGNORE (MG_COAP_ERROR | 0x40000)
2691  * - #define MG_COAP_NOT_ENOUGH_DATA (MG_COAP_ERROR | 0x80000)
2692  * - #define MG_COAP_NETWORK_ERROR (MG_COAP_ERROR | 0x100000)
2693  */
2694 uint32_t mg_coap_send_message(struct mg_connection *nc,
2695  struct mg_coap_message *cm);
2696 
2697 /*
2698  * Compose CoAP acknowledgement from `mg_coap_message`
2699  * and send it into `nc` connection.
2700  * Return value: see `mg_coap_send_message()`
2701  */
2702 uint32_t mg_coap_send_ack(struct mg_connection *nc, uint16_t msg_id);
2703 
2704 /*
2705  * Parse COAP message and fills mg_coap_message and returns cm->flags.
2706  * This is a helper function.
2707  *
2708  * NOTE: usually CoAP work over UDP, so lack of data means format error,
2709  * but in theory it is possible to use CoAP over TCP (according to RFC)
2710  *
2711  * The caller have to check results and treat COAP_NOT_ENOUGH_DATA according to
2712  * underlying protocol:
2713  *
2714  * - in case of UDP COAP_NOT_ENOUGH_DATA means COAP_FORMAT_ERROR,
2715  * - in case of TCP client can try to receive more data
2716  *
2717  * Return value: see `mg_coap_send_message()`
2718  */
2719 uint32_t mg_coap_parse(struct mbuf *io, struct mg_coap_message *cm);
2720 
2721 /*
2722  * Composes CoAP message from mg_coap_message structure.
2723  * This is a helper function.
2724  * Return value: see `mg_coap_send_message()`
2725  */
2726 uint32_t mg_coap_compose(struct mg_coap_message *cm, struct mbuf *io);
2727 
2728 #ifdef __cplusplus
2729 }
2730 #endif /* __cplusplus */
2731 
2732 #endif /* MG_ENABLE_COAP */
2733 
2734 #endif /* MG_COAP_HEADER_INCLUDED */
int mg_resolve(const char *domain_name, char *ip_addr_buf, size_t buf_len)
Definition: mongoose.c:2043
struct mg_str header_values[MG_MAX_HTTP_HEADERS]
Definition: mongoose.h:1411
void mg_mqtt_pubcomp(struct mg_connection *, uint16_t)
Definition: mongoose.c:7060
int mg_parse_dns(const char *, int, struct mg_dns_message *)
Definition: mongoose.c:7511
Definition: mongoose.h:2309
const char * cgi_file_pattern
Definition: mongoose.h:1788
Definition: mongoose.h:2299
struct json_token * message
Definition: mongoose.h:1868
Definition: mongoose.h:1852
Definition: mongoose.h:1417
struct json_token * result
Definition: mongoose.h:1863
void mg_set_protocol_http_websocket(struct mg_connection *nc)
Definition: mongoose.c:4458
int accept_literal
Definition: mongoose.h:2529
unsigned char in[64]
Definition: mongoose.h:441
int mg_vprintf(struct mg_connection *, const char *fmt, va_list ap)
Definition: mongoose.c:1988
void mg_send_dns_query(struct mg_connection *, const char *, int)
Definition: mongoose.c:7424
void mg_if_connect_cb(struct mg_connection *nc, int err)
Definition: mongoose.c:2497
union socket_address sa
Definition: mongoose.h:721
mg_event_handler_t handler
Definition: mongoose.h:730
const char * custom_mime_types
Definition: mongoose.h:1797
struct json_token * parse_json2(const char *json_string, int string_length)
Definition: mongoose.c:759
void mg_if_poll(struct mg_connection *nc, time_t now)
Definition: mongoose.c:1891
void cs_sha1_init(cs_sha1_ctx *)
Definition: mongoose.c:1451
int json_emit_quoted_str(char *buf, int buf_len, const char *str, int len)
Definition: mongoose.c:830
void mg_send_websocket_handshake(struct mg_connection *nc, const char *uri, const char *extra_headers)
Definition: mongoose.c:4464
void mbuf_free(struct mbuf *)
Definition: mongoose.c:1216
void mg_broadcast(struct mg_mgr *, mg_event_handler_t func, void *, size_t)
Definition: mongoose.c:2659
mg_event_handler_t proto_handler
Definition: mongoose.h:728
int sock_t
Definition: mongoose.h:260
unsigned char flags
Definition: mongoose.h:2012
Definition: mongoose.h:281
Definition: mongoose.h:2011
#define MG_MAX_DNS_QUESTIONS
Definition: mongoose.h:2287
void mg_if_udp_send(struct mg_connection *nc, const void *buf, size_t len)
Definition: mongoose.c:2820
const char * topic
Definition: mongoose.h:2007
Definition: mongoose.h:1860
json_type
Definition: mongoose.h:565
void cs_base64_finish(struct cs_base64_ctx *ctx)
Definition: mongoose.c:188
Definition: mongoose.h:2295
size_t mbuf_insert(struct mbuf *, size_t, const void *, size_t)
Definition: mongoose.c:1241
struct mg_connection * mg_bind_opt(struct mg_mgr *, const char *, mg_event_handler_t, struct mg_bind_opts)
Definition: mongoose.c:2614
Definition: mongoose.h:1718
struct json_token * error_data
Definition: mongoose.h:1872
void mg_mqtt_unsubscribe(struct mg_connection *nc, char **topics, size_t topics_len, uint16_t message_id)
Definition: mongoose.c:7011
struct json_token * method
Definition: mongoose.h:1855
void mg_enable_multithreading(struct mg_connection *nc)
int only_literal
Definition: mongoose.h:2530
void MD5_Init(MD5_CTX *c)
Definition: mongoose.c:992
void mbuf_init(struct mbuf *, size_t initial_capacity)
Definition: mongoose.c:1210
void cs_base64_update(struct cs_base64_ctx *ctx, const char *str, size_t len)
Definition: mongoose.c:176
int mg_mqtt_next_subscribe_topic(struct mg_mqtt_message *, struct mg_str *, uint8_t *, int)
Definition: mongoose.c:6998
struct mbuf send_mbuf
Definition: mongoose.h:724
void * priv_1
Definition: mongoose.h:732
const char data[]
Make it with: gcc -o post-callback post-callback.c -lcurl.
Definition: post-callback.c:23
void mg_send_mqtt_handshake_opt(struct mg_connection *, const char *client_id, struct mg_send_mqtt_handshake_opts)
Definition: mongoose.c:6906
struct MD5Context MD5_CTX
int mg_hexdump(const void *buf, int len, char *dst, int dst_len)
Definition: mongoose.c:6460
int c_snprintf(char *buf, size_t buf_size, const char *format,...)
Definition: mongoose.c:1740
struct mg_str message
Definition: mongoose.h:1388
char * topic
Definition: mongoose.h:2003
struct mg_str query_string
Definition: mongoose.h:1407
void mg_if_recv_udp_cb(struct mg_connection *nc, void *buf, int len, union socket_address *sa, size_t sa_len)
Definition: mongoose.c:2433
struct sockaddr sa
Definition: mongoose.h:664
int mg_rpc_parse_reply(const char *buf, int len, struct json_token *toks, int max_toks, struct mg_rpc_reply *, struct mg_rpc_error *)
Definition: mongoose.c:6767
Definition: mongoose.h:485
void * SSL
Definition: mongoose.h:647
Definition: mongoose.h:825
const char * password
Definition: mongoose.h:2017
struct mg_str name
Definition: mongoose.h:2300
const char * ip_acl
Definition: mongoose.h:1759
void(* mg_event_handler_t)(struct mg_connection *, int ev, void *)
Definition: mongoose.h:687
const char ** error_string
Definition: mongoose.h:828
SSL_CTX * ssl_ctx
Definition: mongoose.h:726
const char * per_directory_auth_file
Definition: mongoose.h:1737
const char * document_root
Definition: mongoose.h:1720
struct json_token * id
Definition: mongoose.h:1854
const char * hexdump_file
Definition: mongoose.h:702
void MD5_Final(unsigned char *md, MD5_CTX *c)
void * user_data
Definition: mongoose.h:490
int mg_if_listen_tcp(struct mg_connection *nc, union socket_address *sa)
Definition: mongoose.c:2802
uint8_t connack_ret_code
Definition: mongoose.h:2001
void mg_mqtt_ping(struct mg_connection *)
Definition: mongoose.c:7079
void mg_serve_http(struct mg_connection *, struct http_message *, struct mg_serve_http_opts)
Definition: mongoose.c:6130
enum mg_dns_resource_record_kind kind
Definition: mongoose.h:2304
struct mg_connection * prev
Definition: mongoose.h:715
struct json_token * error_message
Definition: mongoose.h:1871
int rclass
Definition: mongoose.h:2302
int mg_match_prefix(const char *pattern, int pattern_len, const char *str)
Definition: mongoose.c:6594
void mg_send_head(struct mg_connection *n, int status_code, int64_t content_length, const char *extra_headers)
Definition: mongoose.c:4504
void mg_if_destroy_conn(struct mg_connection *nc)
Definition: mongoose.c:2830
Definition: mongoose.h:854
void mg_close_conn(struct mg_connection *nc)
Definition: mongoose.c:1902
Definition: mongoose.h:568
void mg_mqtt_pong(struct mg_connection *)
Definition: mongoose.c:7083
int num_answers
Definition: mongoose.h:2314
void mg_send_mqtt_handshake(struct mg_connection *nc, const char *client_id)
Definition: mongoose.c:6901
void(* cs_base64_putc_t)(char, void *)
Definition: mongoose.h:483
int mg_avprintf(char **buf, size_t size, const char *fmt, va_list ap)
Definition: mongoose.c:6482
Definition: mongoose.h:409
Definition: mongoose.h:280
Definition: mongoose.h:571
uint32_t buf[4]
Definition: mongoose.h:439
void mg_if_tcp_send(struct mg_connection *nc, const void *buf, size_t len)
Definition: mongoose.c:2816
Definition: mongoose.h:674
struct mg_dns_resource_record answers[MG_MAX_DNS_ANSWERS]
Definition: mongoose.h:2316
struct mg_connection * mg_add_sock_opt(struct mg_mgr *, sock_t, mg_event_handler_t, struct mg_add_sock_opts)
Definition: mongoose.c:3140
void * priv_2
Definition: mongoose.h:733
int mg_parse_http(const char *s, int n, struct http_message *hm, int is_req)
Definition: mongoose.c:3788
Definition: mongoose.h:1867
struct mg_connection * mg_connect_opt(struct mg_mgr *, const char *, mg_event_handler_t, struct mg_connect_opts)
Definition: mongoose.c:2560
size_t len
Definition: mongoose.h:348
const char * access_log_file
Definition: mongoose.h:1726
enum json_type type
Definition: mongoose.h:580
int c_vsnprintf(char *buf, size_t buf_size, const char *format, va_list ap)
Definition: mongoose.c:1617
void * user_data
Definition: mongoose.h:889
int json_emit_unquoted_str(char *buf, int buf_len, const char *str, int len)
Definition: mongoose.c:858
const char * enable_directory_listing
Definition: mongoose.h:1753
Definition: mongoose.h:283
struct mg_connection * next
Definition: mongoose.h:715
int mg_http_parse_header(struct mg_str *hdr, const char *var_name, char *buf, size_t buf_size)
Definition: mongoose.c:4958
int(* mg_rpc_handler_t)(char *buf, int len, struct mg_rpc_request *)
Definition: mongoose.h:1951
struct mg_connection * mg_if_accept_tcp_cb(struct mg_connection *lc, union socket_address *sa, size_t sa_len)
Definition: mongoose.c:2316
int mg_stat(const char *path, cs_stat_t *st)
Definition: mongoose.c:6341
void mg_mqtt_suback(struct mg_connection *, uint8_t *, size_t, uint16_t)
Definition: mongoose.c:7064
int mg_socketpair(sock_t[2], int sock_type)
Definition: mongoose.c:3424
struct json_token * message
Definition: mongoose.h:1861
int cs_base64_decode(const unsigned char *s, int len, char *dst)
Definition: mongoose.c:296
const char * user_name
Definition: mongoose.h:2016
const char * p
Definition: mongoose.h:675
Definition: mongoose.h:2293
void mg_printf_websocket_frame(struct mg_connection *nc, int op_and_flags, const char *fmt,...)
Definition: mongoose.c:4080
size_t mg_dns_uncompress_name(struct mg_dns_message *, struct mg_str *, char *, int)
Definition: mongoose.c:7540
sock_t ctl[2]
Definition: mongoose.h:703
void * user_data
Definition: mongoose.h:855
struct sockaddr_in sin
Definition: mongoose.h:665
int num_desc
Definition: mongoose.h:579
struct mg_connection * mg_bind(struct mg_mgr *, const char *, mg_event_handler_t)
Definition: mongoose.c:2607
size_t mg_parse_multipart(const char *buf, size_t buf_len, char *var_name, size_t var_name_len, char *file_name, size_t file_name_len, const char **chunk, size_t *chunk_len)
Definition: mongoose.c:6245
Definition: mongoose.h:285
void cs_base64_encode(const unsigned char *src, int src_len, char *dst)
Definition: mongoose.c:234
struct mg_connection * mg_add_sock(struct mg_mgr *, sock_t, mg_event_handler_t)
Definition: mongoose.c:3133
struct json_token * params
Definition: mongoose.h:1856
int err
Definition: test38.c:26
const char * dav_auth_file
Definition: mongoose.h:1782
struct mg_str rdata
Definition: mongoose.h:2305
void mg_send_response_line(struct mg_connection *c, int status_code, const char *extra_headers)
Definition: mongoose.c:4484
void * proto_data
Definition: mongoose.h:729
time_t last_io_time
Definition: mongoose.h:727
void mg_mqtt_connack(struct mg_connection *, uint8_t)
Definition: mongoose.c:7029
int json_emit_va(char *buf, int buf_len, const char *fmt, va_list)
Definition: mongoose.c:869
Definition: mongoose.h:282
void mbuf_trim(struct mbuf *)
Definition: mongoose.c:1237
void cs_hmac_sha1(const unsigned char *key, size_t key_len, const unsigned char *text, size_t text_len, unsigned char out[20])
Definition: mongoose.c:1504
int num_questions
Definition: mongoose.h:2313
unsigned long flags
Definition: mongoose.h:736
struct json_token * message
Definition: mongoose.h:1853
struct mg_str payload
Definition: mongoose.h:1999
unsigned char chunk[3]
Definition: mongoose.h:488
struct mg_str proto
Definition: mongoose.h:1393
struct mg_connection * mg_connect(struct mg_mgr *, const char *, mg_event_handler_t)
Definition: mongoose.c:2553
mg_dns_resource_record_kind
Definition: mongoose.h:2292
void mg_set_protocol_dns(struct mg_connection *)
Definition: mongoose.c:7620
void MD5_Update(MD5_CTX *c, const unsigned char *data, size_t len)
Definition: mongoose.c:1084
struct mg_str method
Definition: mongoose.h:1391
Definition: mongoose.h:663
struct mg_connection * listener
Definition: mongoose.h:716
Definition: mongoose.h:700
size_t mbuf_append(struct mbuf *, const void *data, size_t data_size)
Definition: mongoose.c:1273
void * user_data
Definition: mongoose.h:731
int rtype
Definition: mongoose.h:2301
void mg_printf_html_escape(struct mg_connection *, const char *,...)
Definition: mongoose.c:4931
int ttl
Definition: mongoose.h:2303
void mg_if_sent_cb(struct mg_connection *nc, int num_sent)
Definition: mongoose.c:2395
int json_emit(char *buf, int buf_len, const char *fmt,...)
Definition: mongoose.c:929
int mg_casecmp(const char *s1, const char *s2)
Definition: mongoose.c:6318
int cmd
Definition: mongoose.h:1998
int mg_dns_encode_record(struct mbuf *, struct mg_dns_resource_record *, const char *, size_t, const void *, size_t)
Definition: mongoose.c:7379
unsigned int flags
Definition: mongoose.h:856
const char * cgi_interpreter
Definition: mongoose.h:1791
int mg_resolve_from_hosts_file(const char *host, union socket_address *usa)
Definition: mongoose.c:7807
void * SSL_CTX
Definition: mongoose.h:648
uint16_t transaction_id
Definition: mongoose.h:2312
struct mg_str uri
Definition: mongoose.h:1392
Definition: mongoose.h:1387
void mg_base64_encode(const unsigned char *src, int src_len, char *dst)
Definition: mongoose.c:6374
unsigned int flags
Definition: mongoose.h:890
Definition: mongoose.h:888
int mg_ncasecmp(const char *s1, const char *s2, size_t len)
Definition: mongoose.c:6308
int result
Definition: grammar-filter.c:79
time_t mg_mgr_poll(struct mg_mgr *, int milli)
Definition: mongoose.c:3338
struct mg_dns_resource_record * mg_dns_next_record(struct mg_dns_message *, int, struct mg_dns_resource_record *)
Definition: mongoose.c:7289
char * cs_md5(char buf[33],...)
Definition: mongoose.c:1165
Definition: mongoose.h:569
void cs_log_set_level(enum cs_log_level level)
Definition: mongoose.c:341
unsigned char flags
Definition: mongoose.h:1420
struct stat cs_stat_t
Definition: mongoose.h:261
void mg_mqtt_pubrel(struct mg_connection *, uint16_t)
Definition: mongoose.c:7056
void cs_sha1_final(unsigned char digest[20], cs_sha1_ctx *)
Definition: mongoose.c:1480
void mg_mqtt_subscribe(struct mg_connection *nc, const struct mg_mqtt_topic_expression *topics, size_t topics_len, uint16_t message_id)
Definition: mongoose.c:6978
size_t strnlen(const char *s, size_t maxlen)
Definition: mongoose.c:1555
int mg_if_listen_udp(struct mg_connection *nc, union socket_address *sa)
Definition: mongoose.c:2809
int max_retries
Definition: mongoose.h:2527
int parse_json(const char *json_string, int json_string_length, struct json_token *tokens_array, int size_of_tokens_array)
Definition: mongoose.c:745
struct mg_dns_resource_record questions[MG_MAX_DNS_QUESTIONS]
Definition: mongoose.h:2315
int mg_base64_decode(const unsigned char *s, int len, char *dst)
Definition: mongoose.c:6378
void mg_mqtt_pubrec(struct mg_connection *, uint16_t)
Definition: mongoose.c:7052
int mg_rpc_create_request(char *buf, int len, const char *method, const char *id, const char *params_fmt,...)
Definition: mongoose.c:6666
void mg_send_websocket_frame(struct mg_connection *nc, int op_and_flags, const void *data, size_t data_len)
Definition: mongoose.c:4045
#define MG_MAX_DNS_ANSWERS
Definition: mongoose.h:2288
void mg_mqtt_unsuback(struct mg_connection *, uint16_t)
Definition: mongoose.c:7075
void mg_mqtt_puback(struct mg_connection *, uint16_t)
Definition: mongoose.c:7048
Definition: mongoose.h:346
void mg_send(struct mg_connection *, const void *buf, int len)
Definition: mongoose.c:2381
void cs_base64_init(struct cs_base64_ctx *ctx, cs_base64_putc_t putc, void *user_data)
Definition: mongoose.c:169
int qos
Definition: mongoose.h:2000
int mg_is_big_endian(void)
Definition: mongoose.c:6555
struct json_token * id
Definition: mongoose.h:1862
Definition: mongoose.h:279
void cs_to_hex(char *to, const unsigned char *p, size_t len)
Definition: mongoose.c:1155
size_t size
Definition: mongoose.h:1419
Definition: mongoose.h:572
struct mg_str resp_status_msg
Definition: mongoose.h:1397
enum cs_log_level s_cs_log_level
Definition: mongoose.c:325
int mg_check_ip_acl(const char *acl, uint32_t remote_ip)
Definition: mongoose.c:2704
int timeout
Definition: mongoose.h:2528
Definition: mongoose.h:576
void * user_data
Definition: mongoose.h:826
Definition: mongoose.h:566
void cs_sha1_update(cs_sha1_ctx *, const unsigned char *data, uint32_t len)
Definition: mongoose.c:1460
const char * extra_headers
Definition: mongoose.h:1803
void cs_log_printf(const char *fmt,...)
Definition: mongoose.c:332
void mg_set_close_on_exec(sock_t)
Definition: mongoose.c:6406
cs_base64_putc_t b64_putc
Definition: mongoose.h:487
uint16_t flags
Definition: mongoose.h:2311
struct mg_str * mg_get_http_header(struct http_message *hm, const char *name)
Definition: mongoose.c:3852
cs_log_level
Definition: mongoose.h:278
int mg_rpc_create_std_error(char *, int, struct mg_rpc_request *, int code)
Definition: mongoose.c:6700
void mg_hexdump_connection(struct mg_connection *nc, const char *path, int num_bytes, int ev)
Definition: mongoose.c:6519
struct json_token * find_json_token(struct json_token *toks, const char *path)
Definition: mongoose.c:780
enum @1 state
Application states.
int chunk_size
Definition: mongoose.h:489
uint32_t bits[2]
Definition: mongoose.h:440
void mbuf_resize(struct mbuf *, size_t new_size)
Definition: mongoose.c:1223
Definition: mongoose.h:1997
struct mg_str header_names[MG_MAX_HTTP_HEADERS]
Definition: mongoose.h:1410
Definition: mongoose.h:438
struct mg_str pkt
Definition: mongoose.h:2310
Definition: mongoose.h:567
int mg_vcmp(const struct mg_str *str2, const char *str1)
Definition: mongoose.c:6331
const char * nameserver_url
Definition: mongoose.h:2526
size_t size
Definition: mongoose.h:349
Definition: mongoose.h:570
int json_emit_long(char *buf, int buf_len, long value)
const char * will_message
Definition: mongoose.h:2015
Definition: mongoose.h:714
struct mg_connection * mg_connect_http(struct mg_mgr *, mg_event_handler_t event_handler, const char *url, const char *extra_headers, const char *post_data)
Definition: mongoose.c:6169
int json_emit_double(char *buf, int buf_len, double value)
Definition: mongoose.c:823
int mg_get_http_var(const struct mg_str *, const char *, char *dst, size_t)
Definition: mongoose.c:4864
sock_t sock
Definition: mongoose.h:719
int mg_dns_parse_record_data(struct mg_dns_message *, struct mg_dns_resource_record *, void *, size_t)
Definition: mongoose.c:7303
int mg_rpc_dispatch(const char *buf, int, char *dst, int dst_len, const char **methods, mg_rpc_handler_t *handlers)
Definition: mongoose.c:6728
const char ** error_string
Definition: mongoose.h:857
int mg_http_create_digest_auth_header(char *buf, size_t buf_len, const char *method, const char *uri, const char *auth_domain, const char *user, const char *passwd)
Definition: mongoose.c:5021
int mg_resolve_async(struct mg_mgr *, const char *, int, mg_resolve_callback_t, void *data)
Definition: mongoose.c:7895
void mg_mgr_init(struct mg_mgr *mgr, void *user_data)
Definition: mongoose.c:1911
void mg_sock_addr_to_str(const union socket_address *sa, char *buf, size_t len, int flags)
Definition: mongoose.c:6414
void mg_set_protocol_mqtt(struct mg_connection *)
Definition: mongoose.c:6897
struct mg_connection * active_connections
Definition: mongoose.h:701
void mg_send_http_chunk(struct mg_connection *nc, const char *buf, size_t len)
Definition: mongoose.c:4901
void mg_if_recved(struct mg_connection *nc, size_t len)
Definition: mongoose.c:2825
void mg_if_connect_tcp(struct mg_connection *nc, const union socket_address *sa)
Definition: mongoose.c:2775
void mg_mqtt_publish(struct mg_connection *nc, const char *topic, uint16_t message_id, int flags, const void *data, size_t len)
Definition: mongoose.c:6959
#define nc
Pointer to mg_connection structure.
Definition: teo_ws.c:36
uint16_t message_id
Definition: mongoose.h:2002
Definition: mongoose.h:2525
struct json_token * id
Definition: mongoose.h:1869
const char * global_auth_file
Definition: mongoose.h:1750
const char * url_rewrites
Definition: mongoose.h:1776
void(* mg_resolve_callback_t)(struct mg_dns_message *, void *)
Definition: mongoose.h:2522
const char * mg_next_comma_list_entry(const char *list, struct mg_str *val, struct mg_str *eq_val)
Definition: mongoose.c:6561
uint16_t keep_alive
Definition: mongoose.h:2013
int resp_code
Definition: mongoose.h:1396
int mg_dns_copy_body(struct mbuf *, struct mg_dns_message *)
Definition: mongoose.c:7345
int mg_rpc_create_reply(char *buf, int len, const struct mg_rpc_request *req, const char *result_fmt,...)
Definition: mongoose.c:6642
unsigned char * data
Definition: mongoose.h:1418
void mg_if_connect_udp(struct mg_connection *nc)
Definition: mongoose.c:2792
Definition: mongoose.h:2006
const char * hidden_file_pattern
Definition: mongoose.h:1785
uint8_t qos
Definition: mongoose.h:2008
void mg_sock_to_str(sock_t sock, char *buf, size_t len, int flags)
Definition: mongoose.c:3467
struct sockaddr sin6
Definition: mongoose.h:669
Definition: mongoose.h:573
const char * dav_document_root
Definition: mongoose.h:1779
struct mbuf recv_mbuf
Definition: mongoose.h:723
char * buf
Definition: mongoose.h:347
const char * ssi_pattern
Definition: mongoose.h:1756
int info
Definition: test38.c:26
const char * mg_set_ssl(struct mg_connection *nc, const char *cert, const char *ca_cert)
const char * auth_domain
Definition: mongoose.h:1740
int mg_rpc_create_error(char *buf, int len, struct mg_rpc_request *req, int code, const char *message, const char *fmt,...)
Definition: mongoose.c:6682
SSL * ssl
Definition: mongoose.h:725
int len
Definition: mongoose.h:578
unsigned int flags
Definition: mongoose.h:827
int mg_open(const char *path, int flag, int mode)
Definition: mongoose.c:6363
const char * will_topic
Definition: mongoose.h:2014
void mg_send_websocket_framev(struct mg_connection *nc, int op_and_flags, const struct mg_str *strings, int num_strings)
Definition: mongoose.c:4058
FILE * mg_fopen(const char *path, const char *mode)
Definition: mongoose.c:6352
const char * mg_skip(const char *s, const char *end_string, const char *delimiters, struct mg_str *v)
Definition: mongoose.c:6295
const char * index_files
Definition: mongoose.h:1723
void * user_data
Definition: mongoose.h:704
Definition: mongoose.h:286
int err
Definition: mongoose.h:720
const char * ptr
Definition: mongoose.h:577
int mg_vcasecmp(const struct mg_str *str2, const char *str1)
Definition: mongoose.c:6322
void mbuf_remove(struct mbuf *, size_t data_size)
Definition: mongoose.c:1277
void mg_printf_http_chunk(struct mg_connection *, const char *,...)
Definition: mongoose.c:4911
int mg_printf(struct mg_connection *, const char *fmt,...)
Definition: mongoose.c:2002
#define MG_MAX_HTTP_HEADERS
Definition: mongoose.h:1351
int mg_resolve_async_opt(struct mg_mgr *, const char *, int, mg_resolve_callback_t, void *data, struct mg_resolve_async_opts opts)
Definition: mongoose.c:7902
int mg_dns_insert_header(struct mbuf *, size_t, struct mg_dns_message *)
Definition: mongoose.c:7332
size_t recv_mbuf_limit
Definition: mongoose.h:722
void * mgr_data
Definition: mongoose.h:734
void mg_mqtt_disconnect(struct mg_connection *nc)
Definition: mongoose.c:7087
Definition: mongoose.h:2294
const char ** error_string
Definition: mongoose.h:891
void mg_if_recv_tcp_cb(struct mg_connection *nc, void *buf, int len)
Definition: mongoose.c:2428
void * mgr_data
Definition: mongoose.h:705
void cs_fprint_base64(FILE *f, const unsigned char *src, int src_len)
Definition: mongoose.c:249
struct mg_mgr * mgr
Definition: mongoose.h:717
struct json_token * error_code
Definition: mongoose.h:1870
struct mg_str body
Definition: mongoose.h:1414
size_t len
Definition: mongoose.h:676
struct mg_connection * mg_next(struct mg_mgr *, struct mg_connection *)
Definition: mongoose.c:2654
void mg_mgr_free(struct mg_mgr *)
Definition: mongoose.c:1966