Statistics
| Branch: | Tag: | Revision:

mongoose / mongoose.h @ 6b923bdf

History | View | Annotate | Download (167 KB)

1
#ifdef MG_MODULE_LINES
2
#line 1 "mongoose/src/common.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
#ifndef CS_MONGOOSE_SRC_COMMON_H_
24
#define CS_MONGOOSE_SRC_COMMON_H_
25

    
26
#define MG_VERSION "6.7"
27

    
28
/* Local tweaks, applied before any of Mongoose's own headers. */
29
#ifdef MG_LOCALS
30
#include <mg_locals.h>
31
#endif
32

    
33
#endif /* CS_MONGOOSE_SRC_COMMON_H_ */
34
#ifdef MG_MODULE_LINES
35
#line 1 "common/platform.h"
36
#endif
37
#ifndef CS_COMMON_PLATFORM_H_
38
#define CS_COMMON_PLATFORM_H_
39

    
40
/*
41
 * For the "custom" platform, includes and dependencies can be
42
 * provided through mg_locals.h.
43
 */
44
#define CS_P_CUSTOM 0
45
#define CS_P_UNIX 1
46
#define CS_P_WINDOWS 2
47
#define CS_P_ESP32 15
48
#define CS_P_ESP8266 3
49
#define CS_P_CC3200 4
50
#define CS_P_MSP432 5
51
#define CS_P_CC3100 6
52
#define CS_P_TM4C129 14
53
#define CS_P_MBED 7
54
#define CS_P_WINCE 8
55
#define CS_P_NXP_LPC 13
56
#define CS_P_NXP_KINETIS 9
57
#define CS_P_NRF51 12
58
#define CS_P_NRF52 10
59
#define CS_P_PIC32 11
60
#define CS_P_STM32 16
61
/* Next id: 17 */
62

    
63
/* If not specified explicitly, we guess platform by defines. */
64
#ifndef CS_PLATFORM
65

    
66
#if defined(TARGET_IS_MSP432P4XX) || defined(__MSP432P401R__)
67
#define CS_PLATFORM CS_P_MSP432
68
#elif defined(cc3200)
69
#define CS_PLATFORM CS_P_CC3200
70
#elif defined(__unix__) || defined(__APPLE__)
71
#define CS_PLATFORM CS_P_UNIX
72
#elif defined(WINCE)
73
#define CS_PLATFORM CS_P_WINCE
74
#elif defined(_WIN32)
75
#define CS_PLATFORM CS_P_WINDOWS
76
#elif defined(__MBED__)
77
#define CS_PLATFORM CS_P_MBED
78
#elif defined(__USE_LPCOPEN)
79
#define CS_PLATFORM CS_P_NXP_LPC
80
#elif defined(FRDM_K64F) || defined(FREEDOM)
81
#define CS_PLATFORM CS_P_NXP_KINETIS
82
#elif defined(PIC32)
83
#define CS_PLATFORM CS_P_PIC32
84
#elif defined(ESP_PLATFORM)
85
#define CS_PLATFORM CS_P_ESP32
86
#elif defined(ICACHE_FLASH)
87
#define CS_PLATFORM CS_P_ESP8266
88
#elif defined(TARGET_IS_TM4C129_RA0) || defined(TARGET_IS_TM4C129_RA1) || \
89
    defined(TARGET_IS_TM4C129_RA2)
90
#define CS_PLATFORM CS_P_TM4C129
91
#elif defined(STM32)
92
#define CS_PLATFORM CS_P_STM32
93
#endif
94

    
95
#ifndef CS_PLATFORM
96
#error "CS_PLATFORM is not specified and we couldn't guess it."
97
#endif
98

    
99
#endif /* !defined(CS_PLATFORM) */
100

    
101
#define MG_NET_IF_SOCKET 1
102
#define MG_NET_IF_SIMPLELINK 2
103
#define MG_NET_IF_LWIP_LOW_LEVEL 3
104
#define MG_NET_IF_PIC32 4
105

    
106
#define MG_SSL_IF_OPENSSL 1
107
#define MG_SSL_IF_MBEDTLS 2
108
#define MG_SSL_IF_SIMPLELINK 3
109

    
110
/* Amalgamated: #include "common/platforms/platform_unix.h" */
111
/* Amalgamated: #include "common/platforms/platform_windows.h" */
112
/* Amalgamated: #include "common/platforms/platform_esp32.h" */
113
/* Amalgamated: #include "common/platforms/platform_esp8266.h" */
114
/* Amalgamated: #include "common/platforms/platform_cc3200.h" */
115
/* Amalgamated: #include "common/platforms/platform_cc3100.h" */
116
/* Amalgamated: #include "common/platforms/platform_mbed.h" */
117
/* Amalgamated: #include "common/platforms/platform_nrf51.h" */
118
/* Amalgamated: #include "common/platforms/platform_nrf52.h" */
119
/* Amalgamated: #include "common/platforms/platform_wince.h" */
120
/* Amalgamated: #include "common/platforms/platform_nxp_lpc.h" */
121
/* Amalgamated: #include "common/platforms/platform_nxp_kinetis.h" */
122
/* Amalgamated: #include "common/platforms/platform_pic32.h" */
123
/* Amalgamated: #include "common/platforms/platform_stm32.h" */
124

    
125
/* Common stuff */
126

    
127
#if !defined(WEAK)
128
#if (defined(__GNUC__) || defined(__TI_COMPILER_VERSION__)) && !defined(_WIN32)
129
#define WEAK __attribute__((weak))
130
#else
131
#define WEAK
132
#endif
133
#endif
134

    
135
#ifdef __GNUC__
136
#define NORETURN __attribute__((noreturn))
137
#define NOINLINE __attribute__((noinline))
138
#define WARN_UNUSED_RESULT __attribute__((warn_unused_result))
139
#define NOINSTR __attribute__((no_instrument_function))
140
#define DO_NOT_WARN_UNUSED __attribute__((unused))
141
#else
142
#define NORETURN
143
#define NOINLINE
144
#define WARN_UNUSED_RESULT
145
#define NOINSTR
146
#define DO_NOT_WARN_UNUSED
147
#endif /* __GNUC__ */
148

    
149
#ifndef ARRAY_SIZE
150
#define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
151
#endif
152

    
153
#endif /* CS_COMMON_PLATFORM_H_ */
154
#ifdef MG_MODULE_LINES
155
#line 1 "common/platforms/platform_windows.h"
156
#endif
157
#ifndef CS_COMMON_PLATFORMS_PLATFORM_WINDOWS_H_
158
#define CS_COMMON_PLATFORMS_PLATFORM_WINDOWS_H_
159
#if CS_PLATFORM == CS_P_WINDOWS
160

    
161
/*
162
 * MSVC++ 14.0 _MSC_VER == 1900 (Visual Studio 2015)
163
 * MSVC++ 12.0 _MSC_VER == 1800 (Visual Studio 2013)
164
 * MSVC++ 11.0 _MSC_VER == 1700 (Visual Studio 2012)
165
 * MSVC++ 10.0 _MSC_VER == 1600 (Visual Studio 2010)
166
 * MSVC++ 9.0  _MSC_VER == 1500 (Visual Studio 2008)
167
 * MSVC++ 8.0  _MSC_VER == 1400 (Visual Studio 2005)
168
 * MSVC++ 7.1  _MSC_VER == 1310 (Visual Studio 2003)
169
 * MSVC++ 7.0  _MSC_VER == 1300
170
 * MSVC++ 6.0  _MSC_VER == 1200
171
 * MSVC++ 5.0  _MSC_VER == 1100
172
 */
173
#ifdef _MSC_VER
174
#pragma warning(disable : 4127) /* FD_SET() emits warning, disable it */
175
#pragma warning(disable : 4204) /* missing c99 support */
176
#endif
177

    
178
#ifndef _WINSOCK_DEPRECATED_NO_WARNINGS
179
#define _WINSOCK_DEPRECATED_NO_WARNINGS 1
180
#endif
181

    
182
#ifndef _CRT_SECURE_NO_WARNINGS
183
#define _CRT_SECURE_NO_WARNINGS
184
#endif
185

    
186
#include <assert.h>
187
#include <direct.h>
188
#include <errno.h>
189
#include <fcntl.h>
190
#include <io.h>
191
#include <limits.h>
192
#include <signal.h>
193
#include <stddef.h>
194
#include <stdio.h>
195
#include <stdlib.h>
196
#include <sys/stat.h>
197
#include <time.h>
198

    
199
#ifdef _MSC_VER
200
#pragma comment(lib, "ws2_32.lib") /* Linking with winsock library */
201
#endif
202

    
203
#include <winsock2.h>
204
#include <ws2tcpip.h>
205
#include <windows.h>
206
#include <process.h>
207

    
208
#if defined(_MSC_VER) && _MSC_VER >= 1800
209
#define strdup _strdup
210
#endif
211

    
212
#ifndef EINPROGRESS
213
#define EINPROGRESS WSAEINPROGRESS
214
#endif
215
#ifndef EWOULDBLOCK
216
#define EWOULDBLOCK WSAEWOULDBLOCK
217
#endif
218
#ifndef __func__
219
#define STRX(x) #x
220
#define STR(x) STRX(x)
221
#define __func__ __FILE__ ":" STR(__LINE__)
222
#endif
223
#define snprintf _snprintf
224
#define fileno _fileno
225
#define vsnprintf _vsnprintf
226
#define sleep(x) Sleep((x) *1000)
227
#define to64(x) _atoi64(x)
228
#if !defined(__MINGW32__) && !defined(__MINGW64__)
229
#define popen(x, y) _popen((x), (y))
230
#define pclose(x) _pclose(x)
231
#endif
232
#define rmdir _rmdir
233
#if defined(_MSC_VER) && _MSC_VER >= 1400
234
#define fseeko(x, y, z) _fseeki64((x), (y), (z))
235
#else
236
#define fseeko(x, y, z) fseek((x), (y), (z))
237
#endif
238
#if defined(_MSC_VER) && _MSC_VER <= 1200
239
typedef unsigned long uintptr_t;
240
typedef long intptr_t;
241
#endif
242
typedef int socklen_t;
243
#if _MSC_VER >= 1700
244
#include <stdint.h>
245
#else
246
typedef signed char int8_t;
247
typedef unsigned char uint8_t;
248
typedef int int32_t;
249
typedef unsigned int uint32_t;
250
typedef short int16_t;
251
typedef unsigned short uint16_t;
252
typedef __int64 int64_t;
253
typedef unsigned __int64 uint64_t;
254
#endif
255
typedef SOCKET sock_t;
256
typedef uint32_t in_addr_t;
257
#ifndef UINT16_MAX
258
#define UINT16_MAX 65535
259
#endif
260
#ifndef UINT32_MAX
261
#define UINT32_MAX 4294967295
262
#endif
263
#ifndef pid_t
264
#define pid_t HANDLE
265
#endif
266
#define INT64_FMT "I64d"
267
#define INT64_X_FMT "I64x"
268
#define SIZE_T_FMT "Iu"
269
typedef struct _stati64 cs_stat_t;
270
#ifndef S_ISDIR
271
#define S_ISDIR(x) (((x) &_S_IFMT) == _S_IFDIR)
272
#endif
273
#ifndef S_ISREG
274
#define S_ISREG(x) (((x) &_S_IFMT) == _S_IFREG)
275
#endif
276
#define DIRSEP '\\'
277
#define CS_DEFINE_DIRENT
278

    
279
#ifndef va_copy
280
#ifdef __va_copy
281
#define va_copy __va_copy
282
#else
283
#define va_copy(x, y) (x) = (y)
284
#endif
285
#endif
286

    
287
#ifndef MG_MAX_HTTP_REQUEST_SIZE
288
#define MG_MAX_HTTP_REQUEST_SIZE 8192
289
#endif
290

    
291
#ifndef MG_MAX_HTTP_SEND_MBUF
292
#define MG_MAX_HTTP_SEND_MBUF 4096
293
#endif
294

    
295
#ifndef MG_MAX_HTTP_HEADERS
296
#define MG_MAX_HTTP_HEADERS 40
297
#endif
298

    
299
#ifndef CS_ENABLE_STDIO
300
#define CS_ENABLE_STDIO 1
301
#endif
302

    
303
#ifndef MG_ENABLE_BROADCAST
304
#define MG_ENABLE_BROADCAST 1
305
#endif
306

    
307
#ifndef MG_ENABLE_DIRECTORY_LISTING
308
#define MG_ENABLE_DIRECTORY_LISTING 1
309
#endif
310

    
311
#ifndef MG_ENABLE_FILESYSTEM
312
#define MG_ENABLE_FILESYSTEM 1
313
#endif
314

    
315
#ifndef MG_ENABLE_HTTP_CGI
316
#define MG_ENABLE_HTTP_CGI MG_ENABLE_FILESYSTEM
317
#endif
318

    
319
#ifndef MG_NET_IF
320
#define MG_NET_IF MG_NET_IF_SOCKET
321
#endif
322

    
323
#endif /* CS_PLATFORM == CS_P_WINDOWS */
324
#endif /* CS_COMMON_PLATFORMS_PLATFORM_WINDOWS_H_ */
325
#ifdef MG_MODULE_LINES
326
#line 1 "common/platforms/platform_unix.h"
327
#endif
328
#ifndef CS_COMMON_PLATFORMS_PLATFORM_UNIX_H_
329
#define CS_COMMON_PLATFORMS_PLATFORM_UNIX_H_
330
#if CS_PLATFORM == CS_P_UNIX
331

    
332
#ifndef _XOPEN_SOURCE
333
#define _XOPEN_SOURCE 600
334
#endif
335

    
336
/* <inttypes.h> wants this for C++ */
337
#ifndef __STDC_FORMAT_MACROS
338
#define __STDC_FORMAT_MACROS
339
#endif
340

    
341
/* C++ wants that for INT64_MAX */
342
#ifndef __STDC_LIMIT_MACROS
343
#define __STDC_LIMIT_MACROS
344
#endif
345

    
346
/* Enable fseeko() and ftello() functions */
347
#ifndef _LARGEFILE_SOURCE
348
#define _LARGEFILE_SOURCE
349
#endif
350

    
351
/* Enable 64-bit file offsets */
352
#ifndef _FILE_OFFSET_BITS
353
#define _FILE_OFFSET_BITS 64
354
#endif
355

    
356
#include <arpa/inet.h>
357
#include <assert.h>
358
#include <ctype.h>
359
#include <dirent.h>
360
#include <errno.h>
361
#include <fcntl.h>
362
#include <inttypes.h>
363
#include <stdint.h>
364
#include <limits.h>
365
#include <math.h>
366
#include <netdb.h>
367
#include <netinet/in.h>
368
#include <pthread.h>
369
#include <signal.h>
370
#include <stdarg.h>
371
#include <stdio.h>
372
#include <stdlib.h>
373
#include <string.h>
374
#include <sys/param.h>
375
#include <sys/socket.h>
376
#include <sys/select.h>
377
#include <sys/stat.h>
378
#include <sys/time.h>
379
#include <sys/types.h>
380
#include <unistd.h>
381

    
382
#ifdef __APPLE__
383
#include <machine/endian.h>
384
#ifndef BYTE_ORDER
385
#define LITTLE_ENDIAN __DARWIN_LITTLE_ENDIAN
386
#define BIG_ENDIAN __DARWIN_BIG_ENDIAN
387
#define PDP_ENDIAN __DARWIN_PDP_ENDIAN
388
#define BYTE_ORDER __DARWIN_BYTE_ORDER
389
#endif
390
#endif
391

    
392
/*
393
 * osx correctly avoids defining strtoll when compiling in strict ansi mode.
394
 * c++ 11 standard defines strtoll as well.
395
 * We require strtoll, and if your embedded pre-c99 compiler lacks one, please
396
 * implement a shim.
397
 */
398
#if !(defined(__cplusplus) && __cplusplus >= 201103L) && \
399
    !(defined(__DARWIN_C_LEVEL) && __DARWIN_C_LEVEL >= 200809L)
400
long long strtoll(const char *, char **, int);
401
#endif
402

    
403
typedef int sock_t;
404
#define INVALID_SOCKET (-1)
405
#define SIZE_T_FMT "zu"
406
typedef struct stat cs_stat_t;
407
#define DIRSEP '/'
408
#define to64(x) strtoll(x, NULL, 10)
409
#define INT64_FMT PRId64
410
#define INT64_X_FMT PRIx64
411

    
412
#ifndef __cdecl
413
#define __cdecl
414
#endif
415

    
416
#ifndef va_copy
417
#ifdef __va_copy
418
#define va_copy __va_copy
419
#else
420
#define va_copy(x, y) (x) = (y)
421
#endif
422
#endif
423

    
424
#define closesocket(x) close(x)
425

    
426
#ifndef MG_MAX_HTTP_REQUEST_SIZE
427
#define MG_MAX_HTTP_REQUEST_SIZE 8192
428
#endif
429

    
430
#ifndef MG_MAX_HTTP_SEND_MBUF
431
#define MG_MAX_HTTP_SEND_MBUF 4096
432
#endif
433

    
434
#ifndef MG_MAX_HTTP_HEADERS
435
#define MG_MAX_HTTP_HEADERS 40
436
#endif
437

    
438
#ifndef CS_ENABLE_STDIO
439
#define CS_ENABLE_STDIO 1
440
#endif
441

    
442
#ifndef MG_ENABLE_BROADCAST
443
#define MG_ENABLE_BROADCAST 1
444
#endif
445

    
446
#ifndef MG_ENABLE_DIRECTORY_LISTING
447
#define MG_ENABLE_DIRECTORY_LISTING 1
448
#endif
449

    
450
#ifndef MG_ENABLE_FILESYSTEM
451
#define MG_ENABLE_FILESYSTEM 1
452
#endif
453

    
454
#ifndef MG_ENABLE_HTTP_CGI
455
#define MG_ENABLE_HTTP_CGI MG_ENABLE_FILESYSTEM
456
#endif
457

    
458
#ifndef MG_NET_IF
459
#define MG_NET_IF MG_NET_IF_SOCKET
460
#endif
461

    
462
#endif /* CS_PLATFORM == CS_P_UNIX */
463
#endif /* CS_COMMON_PLATFORMS_PLATFORM_UNIX_H_ */
464
#ifdef MG_MODULE_LINES
465
#line 1 "common/platforms/platform_esp32.h"
466
#endif
467
/*
468
 * Copyright (c) 2014-2016 Cesanta Software Limited
469
 * All rights reserved
470
 */
471

    
472
#ifndef CS_COMMON_PLATFORMS_PLATFORM_ESP32_H_
473
#define CS_COMMON_PLATFORMS_PLATFORM_ESP32_H_
474
#if CS_PLATFORM == CS_P_ESP32
475

    
476
#include <assert.h>
477
#include <ctype.h>
478
#include <dirent.h>
479
#include <fcntl.h>
480
#include <inttypes.h>
481
#include <machine/endian.h>
482
#include <stdint.h>
483
#include <string.h>
484
#include <sys/stat.h>
485
#include <sys/time.h>
486

    
487
#define SIZE_T_FMT "u"
488
typedef struct stat cs_stat_t;
489
#define DIRSEP '/'
490
#define to64(x) strtoll(x, NULL, 10)
491
#define INT64_FMT PRId64
492
#define INT64_X_FMT PRIx64
493
#define __cdecl
494
#define _FILE_OFFSET_BITS 32
495

    
496
#define MG_LWIP 1
497

    
498
#ifndef MG_NET_IF
499
#define MG_NET_IF MG_NET_IF_SOCKET
500
#endif
501

    
502
#ifndef CS_ENABLE_STDIO
503
#define CS_ENABLE_STDIO 1
504
#endif
505

    
506
#endif /* CS_PLATFORM == CS_P_ESP32 */
507
#endif /* CS_COMMON_PLATFORMS_PLATFORM_ESP32_H_ */
508
#ifdef MG_MODULE_LINES
509
#line 1 "common/platforms/platform_esp8266.h"
510
#endif
511
/*
512
 * Copyright (c) 2014-2016 Cesanta Software Limited
513
 * All rights reserved
514
 */
515

    
516
#ifndef CS_COMMON_PLATFORMS_PLATFORM_ESP8266_H_
517
#define CS_COMMON_PLATFORMS_PLATFORM_ESP8266_H_
518
#if CS_PLATFORM == CS_P_ESP8266
519

    
520
#include <assert.h>
521
#include <ctype.h>
522
#include <fcntl.h>
523
#include <inttypes.h>
524
#include <machine/endian.h>
525
#include <string.h>
526
#include <sys/stat.h>
527
#include <sys/time.h>
528

    
529
#define SIZE_T_FMT "u"
530
typedef struct stat cs_stat_t;
531
#define DIRSEP '/'
532
#define CS_DEFINE_DIRENT
533

    
534
#define to64(x) strtoll(x, NULL, 10)
535
#define INT64_FMT PRId64
536
#define INT64_X_FMT PRIx64
537
#define __cdecl
538
#define _FILE_OFFSET_BITS 32
539

    
540
#ifndef RTOS_SDK
541
#define fileno(x) -1
542
#endif
543

    
544
#define MG_LWIP 1
545

    
546
/* struct timeval is defined in sys/time.h. */
547
#define LWIP_TIMEVAL_PRIVATE 0
548

    
549
#ifndef MG_NET_IF
550
#include <lwip/opt.h>
551
#if LWIP_SOCKET /* RTOS SDK has LWIP sockets */
552
#  define MG_NET_IF MG_NET_IF_SOCKET
553
#else
554
#  define MG_NET_IF MG_NET_IF_LWIP_LOW_LEVEL
555
#endif
556
#endif
557

    
558
#ifndef CS_ENABLE_STDIO
559
#define CS_ENABLE_STDIO 1
560
#endif
561

    
562
#endif /* CS_PLATFORM == CS_P_ESP8266 */
563
#endif /* CS_COMMON_PLATFORMS_PLATFORM_ESP8266_H_ */
564
#ifdef MG_MODULE_LINES
565
#line 1 "common/platforms/platform_cc3100.h"
566
#endif
567
/*
568
 * Copyright (c) 2014-2016 Cesanta Software Limited
569
 * All rights reserved
570
 */
571

    
572
#ifndef CS_COMMON_PLATFORMS_PLATFORM_CC3100_H_
573
#define CS_COMMON_PLATFORMS_PLATFORM_CC3100_H_
574
#if CS_PLATFORM == CS_P_CC3100
575

    
576
#include <assert.h>
577
#include <ctype.h>
578
#include <errno.h>
579
#include <inttypes.h>
580
#include <stdint.h>
581
#include <string.h>
582
#include <time.h>
583

    
584
#define MG_NET_IF MG_NET_IF_SIMPLELINK
585
#define MG_SSL_IF MG_SSL_IF_SIMPLELINK
586

    
587
/*
588
 * CC3100 SDK and STM32 SDK include headers w/out path, just like
589
 * #include "simplelink.h". As result, we have to add all required directories
590
 * into Makefile IPATH and do the same thing (include w/out path)
591
 */
592

    
593
#include <simplelink.h>
594
#include <netapp.h>
595
#undef timeval 
596

    
597
typedef int sock_t;
598
#define INVALID_SOCKET (-1)
599

    
600
#define to64(x) strtoll(x, NULL, 10)
601
#define INT64_FMT PRId64
602
#define INT64_X_FMT PRIx64
603
#define SIZE_T_FMT "u"
604

    
605
#define SOMAXCONN 8
606

    
607
const char *inet_ntop(int af, const void *src, char *dst, socklen_t size);
608
char *inet_ntoa(struct in_addr in);
609
int inet_pton(int af, const char *src, void *dst);
610

    
611
#endif /* CS_PLATFORM == CS_P_CC3100 */
612
#endif /* CS_COMMON_PLATFORMS_PLATFORM_CC3100_H_ */
613
#ifdef MG_MODULE_LINES
614
#line 1 "common/platforms/platform_cc3200.h"
615
#endif
616
/*
617
 * Copyright (c) 2014-2016 Cesanta Software Limited
618
 * All rights reserved
619
 */
620

    
621
#ifndef CS_COMMON_PLATFORMS_PLATFORM_CC3200_H_
622
#define CS_COMMON_PLATFORMS_PLATFORM_CC3200_H_
623
#if CS_PLATFORM == CS_P_CC3200
624

    
625
#include <assert.h>
626
#include <ctype.h>
627
#include <errno.h>
628
#include <inttypes.h>
629
#include <stdint.h>
630
#include <string.h>
631
#include <time.h>
632

    
633
#ifndef __TI_COMPILER_VERSION__
634
#include <fcntl.h>
635
#include <sys/time.h>
636
#endif
637

    
638
#define MG_NET_IF MG_NET_IF_SIMPLELINK
639
#define MG_SSL_IF MG_SSL_IF_SIMPLELINK
640

    
641
/* Only SPIFFS supports directories, SLFS does not. */
642
#if defined(CC3200_FS_SPIFFS) && !defined(MG_ENABLE_DIRECTORY_LISTING)
643
#define MG_ENABLE_DIRECTORY_LISTING 1
644
#endif
645

    
646
/* Amalgamated: #include "common/platforms/simplelink/cs_simplelink.h" */
647

    
648
typedef int sock_t;
649
#define INVALID_SOCKET (-1)
650
#define SIZE_T_FMT "u"
651
typedef struct stat cs_stat_t;
652
#define DIRSEP '/'
653
#define to64(x) strtoll(x, NULL, 10)
654
#define INT64_FMT PRId64
655
#define INT64_X_FMT PRIx64
656
#define __cdecl
657

    
658
#define fileno(x) -1
659

    
660
/* Some functions we implement for Mongoose. */
661

    
662
#ifdef __cplusplus
663
extern "C" {
664
#endif
665

    
666
#ifdef __TI_COMPILER_VERSION__
667
struct SlTimeval_t;
668
#define timeval SlTimeval_t
669
int gettimeofday(struct timeval *t, void *tz);
670

    
671
int asprintf(char **strp, const char *fmt, ...);
672

    
673
#endif
674

    
675
/* TI's libc does not have stat & friends, add them. */
676
#ifdef __TI_COMPILER_VERSION__
677

    
678
#include <file.h>
679

    
680
typedef unsigned int mode_t;
681
typedef size_t _off_t;
682
typedef long ssize_t;
683

    
684
struct stat {
685
  int st_ino;
686
  mode_t st_mode;
687
  int st_nlink;
688
  time_t st_mtime;
689
  off_t st_size;
690
};
691

    
692
int _stat(const char *pathname, struct stat *st);
693
#define stat(a, b) _stat(a, b)
694

    
695
#define __S_IFMT 0170000
696

    
697
#define __S_IFDIR 0040000
698
#define __S_IFCHR 0020000
699
#define __S_IFREG 0100000
700

    
701
#define __S_ISTYPE(mode, mask) (((mode) &__S_IFMT) == (mask))
702

    
703
#define S_IFDIR __S_IFDIR
704
#define S_IFCHR __S_IFCHR
705
#define S_IFREG __S_IFREG
706
#define S_ISDIR(mode) __S_ISTYPE((mode), __S_IFDIR)
707
#define S_ISREG(mode) __S_ISTYPE((mode), __S_IFREG)
708

    
709
/* As of 5.2.7, TI compiler does not support va_copy() yet. */
710
#define va_copy(apc, ap) ((apc) = (ap))
711

    
712
#endif /* __TI_COMPILER_VERSION__ */
713

    
714
#ifdef CC3200_FS_SLFS
715
#define MG_FS_SLFS
716
#endif
717

    
718
#if (defined(CC3200_FS_SPIFFS) || defined(CC3200_FS_SLFS)) && \
719
    !defined(MG_ENABLE_FILESYSTEM)
720
#define MG_ENABLE_FILESYSTEM 1
721
#define CS_DEFINE_DIRENT
722
#endif
723

    
724
#ifndef CS_ENABLE_STDIO
725
#define CS_ENABLE_STDIO 1
726
#endif
727

    
728
#ifdef __cplusplus
729
}
730
#endif
731

    
732
#endif /* CS_PLATFORM == CS_P_CC3200 */
733
#endif /* CS_COMMON_PLATFORMS_PLATFORM_CC3200_H_ */
734
#ifdef MG_MODULE_LINES
735
#line 1 "common/platforms/platform_msp432.h"
736
#endif
737
/*
738
 * Copyright (c) 2014-2016 Cesanta Software Limited
739
 * All rights reserved
740
 */
741

    
742
#ifndef CS_COMMON_PLATFORMS_PLATFORM_MSP432_H_
743
#define CS_COMMON_PLATFORMS_PLATFORM_MSP432_H_
744
#if CS_PLATFORM == CS_P_MSP432
745

    
746
#include <assert.h>
747
#include <ctype.h>
748
#include <errno.h>
749
#include <inttypes.h>
750
#include <stdint.h>
751
#include <string.h>
752
#include <time.h>
753

    
754
#ifndef __TI_COMPILER_VERSION__
755
#include <fcntl.h>
756
#include <sys/time.h>
757
#endif
758

    
759
#define MG_NET_IF MG_NET_IF_SIMPLELINK
760
#define MG_SSL_IF MG_SSL_IF_SIMPLELINK
761

    
762
/* Amalgamated: #include "common/platforms/simplelink/cs_simplelink.h" */
763

    
764
typedef int sock_t;
765
#define INVALID_SOCKET (-1)
766
#define SIZE_T_FMT "u"
767
typedef struct stat cs_stat_t;
768
#define DIRSEP '/'
769
#define to64(x) strtoll(x, NULL, 10)
770
#define INT64_FMT PRId64
771
#define INT64_X_FMT PRIx64
772
#define __cdecl
773

    
774
#define fileno(x) -1
775

    
776
/* Some functions we implement for Mongoose. */
777

    
778
#ifdef __cplusplus
779
extern "C" {
780
#endif
781

    
782
#ifdef __TI_COMPILER_VERSION__
783
struct SlTimeval_t;
784
#define timeval SlTimeval_t
785
int gettimeofday(struct timeval *t, void *tz);
786
#endif
787

    
788
/* TI's libc does not have stat & friends, add them. */
789
#ifdef __TI_COMPILER_VERSION__
790

    
791
#include <file.h>
792

    
793
typedef unsigned int mode_t;
794
typedef size_t _off_t;
795
typedef long ssize_t;
796

    
797
struct stat {
798
  int st_ino;
799
  mode_t st_mode;
800
  int st_nlink;
801
  time_t st_mtime;
802
  off_t st_size;
803
};
804

    
805
int _stat(const char *pathname, struct stat *st);
806
#define stat(a, b) _stat(a, b)
807

    
808
#define __S_IFMT 0170000
809

    
810
#define __S_IFDIR 0040000
811
#define __S_IFCHR 0020000
812
#define __S_IFREG 0100000
813

    
814
#define __S_ISTYPE(mode, mask) (((mode) &__S_IFMT) == (mask))
815

    
816
#define S_IFDIR __S_IFDIR
817
#define S_IFCHR __S_IFCHR
818
#define S_IFREG __S_IFREG
819
#define S_ISDIR(mode) __S_ISTYPE((mode), __S_IFDIR)
820
#define S_ISREG(mode) __S_ISTYPE((mode), __S_IFREG)
821

    
822
/* As of 5.2.7, TI compiler does not support va_copy() yet. */
823
#define va_copy(apc, ap) ((apc) = (ap))
824

    
825
#endif /* __TI_COMPILER_VERSION__ */
826

    
827
#ifndef CS_ENABLE_STDIO
828
#define CS_ENABLE_STDIO 1
829
#endif
830

    
831
#if (defined(CC3200_FS_SPIFFS) || defined(CC3200_FS_SLFS)) && !defined(MG_ENABLE_FILESYSTEM)
832
#define MG_ENABLE_FILESYSTEM 1
833
#endif
834

    
835
#ifdef __cplusplus
836
}
837
#endif
838

    
839
#endif /* CS_PLATFORM == CS_P_MSP432 */
840
#endif /* CS_COMMON_PLATFORMS_PLATFORM_MSP432_H_ */
841
#ifdef MG_MODULE_LINES
842
#line 1 "common/platforms/platform_tm4c129.h"
843
#endif
844
/*
845
 * Copyright (c) 2014-2016 Cesanta Software Limited
846
 * All rights reserved
847
 */
848

    
849
#ifndef CS_COMMON_PLATFORMS_PLATFORM_TM4C129_H_
850
#define CS_COMMON_PLATFORMS_PLATFORM_TM4C129_H_
851
#if CS_PLATFORM == CS_P_TM4C129
852

    
853
#include <assert.h>
854
#include <ctype.h>
855
#include <errno.h>
856
#include <inttypes.h>
857
#include <stdint.h>
858
#include <string.h>
859
#include <time.h>
860

    
861
#ifndef __TI_COMPILER_VERSION__
862
#include <fcntl.h>
863
#include <sys/time.h>
864
#endif
865

    
866
#define SIZE_T_FMT "u"
867
typedef struct stat cs_stat_t;
868
#define DIRSEP '/'
869
#define to64(x) strtoll(x, NULL, 10)
870
#define INT64_FMT PRId64
871
#define INT64_X_FMT PRIx64
872
#define __cdecl
873

    
874
#ifndef MG_NET_IF
875
#  include <lwip/opt.h>
876
#  if LWIP_SOCKET
877
#    define MG_NET_IF MG_NET_IF_SOCKET
878
#  else
879
#    define MG_NET_IF MG_NET_IF_LWIP_LOW_LEVEL
880
#  endif
881
#  define MG_LWIP 1
882
#elif MG_NET_IF == MG_NET_IF_SIMPLELINK
883
#  include "common/platforms/simplelink/cs_simplelink.h"
884
#endif
885

    
886
#ifndef CS_ENABLE_STDIO
887
#define CS_ENABLE_STDIO 1
888
#endif
889

    
890
#ifdef __TI_COMPILER_VERSION__
891
/* As of 5.2.8, TI compiler does not support va_copy() yet. */
892
#define va_copy(apc, ap) ((apc) = (ap))
893
#endif /* __TI_COMPILER_VERSION__ */
894

    
895
#ifdef __cplusplus
896
}
897
#endif
898

    
899
#endif /* CS_PLATFORM == CS_P_TM4C129 */
900
#endif /* CS_COMMON_PLATFORMS_PLATFORM_TM4C129_H_ */
901
#ifdef MG_MODULE_LINES
902
#line 1 "common/platforms/platform_mbed.h"
903
#endif
904
/*
905
 * Copyright (c) 2014-2016 Cesanta Software Limited
906
 * All rights reserved
907
 */
908

    
909
#ifndef CS_COMMON_PLATFORMS_PLATFORM_MBED_H_
910
#define CS_COMMON_PLATFORMS_PLATFORM_MBED_H_
911
#if CS_PLATFORM == CS_P_MBED
912

    
913
/*
914
 * mbed.h contains C++ code (e.g. templates), thus, it should be processed
915
 * only if included directly to startup file (ex: main.cpp)
916
 */
917
#ifdef __cplusplus
918
/* Amalgamated: #include "mbed.h" */
919
#endif /* __cplusplus */
920

    
921
#include <assert.h>
922
#include <ctype.h>
923
#include <errno.h>
924
#include <inttypes.h>
925
#include <stdint.h>
926
#include <string.h>
927
#include <time.h>
928
#include <sys/stat.h>
929
#include <sys/types.h>
930
#include <fcntl.h>
931
#include <stdio.h>
932

    
933
typedef struct stat cs_stat_t;
934
#define DIRSEP '/'
935

    
936
#ifndef CS_ENABLE_STDIO
937
#define CS_ENABLE_STDIO 1
938
#endif
939

    
940
/*
941
 * mbed can be compiled with the ARM compiler which
942
 * just doesn't come with a gettimeofday shim
943
 * because it's a BSD API and ARM targets embedded
944
 * non-unix platforms.
945
 */
946
#if defined(__ARMCC_VERSION) || defined(__ICCARM__)
947
#define _TIMEVAL_DEFINED
948
#define gettimeofday _gettimeofday
949

    
950
/* copied from GCC on ARM; for some reason useconds are signed */
951
typedef long suseconds_t; /* microseconds (signed) */
952
struct timeval {
953
  time_t tv_sec;       /* seconds */
954
  suseconds_t tv_usec; /* and microseconds */
955
};
956

    
957
#endif
958

    
959
#if MG_NET_IF == MG_NET_IF_SIMPLELINK
960

    
961
#define MG_SIMPLELINK_NO_OSI 1
962

    
963
#include <simplelink.h>
964

    
965
typedef int sock_t;
966
#define INVALID_SOCKET (-1)
967

    
968
#define to64(x) strtoll(x, NULL, 10)
969
#define INT64_FMT PRId64
970
#define INT64_X_FMT PRIx64
971
#define SIZE_T_FMT "u"
972

    
973
#define SOMAXCONN 8
974

    
975
const char *inet_ntop(int af, const void *src, char *dst, socklen_t size);
976
char *inet_ntoa(struct in_addr in);
977
int inet_pton(int af, const char *src, void *dst);
978
int inet_aton(const char *cp, struct in_addr *inp);
979
in_addr_t inet_addr(const char *cp);
980

    
981
#endif /* MG_NET_IF == MG_NET_IF_SIMPLELINK */
982

    
983
#endif /* CS_PLATFORM == CS_P_MBED */
984
#endif /* CS_COMMON_PLATFORMS_PLATFORM_MBED_H_ */
985
#ifdef MG_MODULE_LINES
986
#line 1 "common/platforms/platform_nrf51.h"
987
#endif
988
/*
989
 * Copyright (c) 2014-2016 Cesanta Software Limited
990
 * All rights reserved
991
 */
992
#ifndef CS_COMMON_PLATFORMS_PLATFORM_NRF51_H_
993
#define CS_COMMON_PLATFORMS_PLATFORM_NRF51_H_
994
#if CS_PLATFORM == CS_P_NRF51
995

    
996
#include <assert.h>
997
#include <ctype.h>
998
#include <inttypes.h>
999
#include <stdint.h>
1000
#include <string.h>
1001
#include <time.h>
1002

    
1003
#define to64(x) strtoll(x, NULL, 10)
1004

    
1005
#define MG_NET_IF             MG_NET_IF_LWIP_LOW_LEVEL
1006
#define MG_LWIP               1
1007
#define MG_ENABLE_IPV6        1
1008

    
1009
/*
1010
 * For ARM C Compiler, make lwip to export `struct timeval`; for other
1011
 * compilers, suppress it.
1012
 */
1013
#if !defined(__ARMCC_VERSION)
1014
# define LWIP_TIMEVAL_PRIVATE  0
1015
#else
1016
struct timeval;
1017
int gettimeofday(struct timeval *tp, void *tzp);
1018
#endif
1019

    
1020
#define INT64_FMT PRId64
1021
#define SIZE_T_FMT "u"
1022

    
1023
/*
1024
 * ARM C Compiler doesn't have strdup, so we provide it
1025
 */
1026
#define CS_ENABLE_STRDUP defined(__ARMCC_VERSION)
1027

    
1028
#endif /* CS_PLATFORM == CS_P_NRF51 */
1029
#endif /* CS_COMMON_PLATFORMS_PLATFORM_NRF51_H_ */
1030
#ifdef MG_MODULE_LINES
1031
#line 1 "common/platforms/platform_nrf52.h"
1032
#endif
1033
/*
1034
 * Copyright (c) 2014-2016 Cesanta Software Limited
1035
 * All rights reserved
1036
 */
1037
#ifndef CS_COMMON_PLATFORMS_PLATFORM_NRF52_H_
1038
#define CS_COMMON_PLATFORMS_PLATFORM_NRF52_H_
1039
#if CS_PLATFORM == CS_P_NRF52
1040

    
1041
#include <assert.h>
1042
#include <ctype.h>
1043
#include <errno.h>
1044
#include <inttypes.h>
1045
#include <stdint.h>
1046
#include <string.h>
1047
#include <time.h>
1048

    
1049
#define to64(x) strtoll(x, NULL, 10)
1050

    
1051
#define MG_NET_IF             MG_NET_IF_LWIP_LOW_LEVEL
1052
#define MG_LWIP               1
1053
#define MG_ENABLE_IPV6        1
1054

    
1055
#if !defined(ENOSPC)
1056
# define ENOSPC 28  /* No space left on device */
1057
#endif
1058

    
1059
/*
1060
 * For ARM C Compiler, make lwip to export `struct timeval`; for other
1061
 * compilers, suppress it.
1062
 */
1063
#if !defined(__ARMCC_VERSION)
1064
# define LWIP_TIMEVAL_PRIVATE  0
1065
#endif
1066

    
1067
#define INT64_FMT PRId64
1068
#define SIZE_T_FMT "u"
1069

    
1070
/*
1071
 * ARM C Compiler doesn't have strdup, so we provide it
1072
 */
1073
#define CS_ENABLE_STRDUP defined(__ARMCC_VERSION)
1074

    
1075
#endif /* CS_PLATFORM == CS_P_NRF52 */
1076
#endif /* CS_COMMON_PLATFORMS_PLATFORM_NRF52_H_ */
1077
#ifdef MG_MODULE_LINES
1078
#line 1 "common/platforms/simplelink/cs_simplelink.h"
1079
#endif
1080
/*
1081
 * Copyright (c) 2014-2016 Cesanta Software Limited
1082
 * All rights reserved
1083
 */
1084

    
1085
#ifndef CS_COMMON_PLATFORMS_SIMPLELINK_CS_SIMPLELINK_H_
1086
#define CS_COMMON_PLATFORMS_SIMPLELINK_CS_SIMPLELINK_H_
1087

    
1088
/* If simplelink.h is already included, all bets are off. */
1089
#if defined(MG_NET_IF) && MG_NET_IF == MG_NET_IF_SIMPLELINK && \
1090
    !defined(__SIMPLELINK_H__)
1091

    
1092
#include <stdbool.h>
1093

    
1094
#ifndef __TI_COMPILER_VERSION__
1095
#undef __CONCAT
1096
#undef FD_CLR
1097
#undef FD_ISSET
1098
#undef FD_SET
1099
#undef FD_SETSIZE
1100
#undef FD_ZERO
1101
#undef fd_set
1102
#endif
1103

    
1104
/* We want to disable SL_INC_STD_BSD_API_NAMING, so we include user.h ourselves
1105
 * and undef it. */
1106
#define PROVISIONING_API_H_
1107
#include <simplelink/user.h>
1108
#undef PROVISIONING_API_H_
1109
#undef SL_INC_STD_BSD_API_NAMING
1110

    
1111
#include <simplelink/include/simplelink.h>
1112
#include <simplelink/include/netapp.h>
1113

    
1114
/* Now define only the subset of the BSD API that we use.
1115
 * Notably, close(), read() and write() are not defined. */
1116
#define AF_INET SL_AF_INET
1117

    
1118
#define socklen_t SlSocklen_t
1119
#define sockaddr SlSockAddr_t
1120
#define sockaddr_in SlSockAddrIn_t
1121
#define in_addr SlInAddr_t
1122

    
1123
#define SOCK_STREAM SL_SOCK_STREAM
1124
#define SOCK_DGRAM SL_SOCK_DGRAM
1125

    
1126
#define htonl sl_Htonl
1127
#define ntohl sl_Ntohl
1128
#define htons sl_Htons
1129
#define ntohs sl_Ntohs
1130

    
1131
#ifndef EACCES
1132
#define EACCES SL_EACCES
1133
#endif
1134
#ifndef EAFNOSUPPORT
1135
#define EAFNOSUPPORT SL_EAFNOSUPPORT
1136
#endif
1137
#ifndef EAGAIN
1138
#define EAGAIN SL_EAGAIN
1139
#endif
1140
#ifndef EBADF
1141
#define EBADF SL_EBADF
1142
#endif
1143
#ifndef EINVAL
1144
#define EINVAL SL_EINVAL
1145
#endif
1146
#ifndef ENOMEM
1147
#define ENOMEM SL_ENOMEM
1148
#endif
1149
#ifndef EWOULDBLOCK
1150
#define EWOULDBLOCK SL_EWOULDBLOCK
1151
#endif
1152

    
1153
#define SOMAXCONN 8
1154

    
1155
#ifdef __cplusplus
1156
extern "C" {
1157
#endif
1158

    
1159
const char *inet_ntop(int af, const void *src, char *dst, socklen_t size);
1160
char *inet_ntoa(struct in_addr in);
1161
int inet_pton(int af, const char *src, void *dst);
1162

    
1163
struct mg_mgr;
1164
struct mg_connection;
1165

    
1166
typedef void (*mg_init_cb)(struct mg_mgr *mgr);
1167
bool mg_start_task(int priority, int stack_size, mg_init_cb mg_init);
1168

    
1169
void mg_run_in_task(void (*cb)(struct mg_mgr *mgr, void *arg), void *cb_arg);
1170

    
1171
int sl_fs_init(void);
1172

    
1173
void sl_restart_cb(struct mg_mgr *mgr);
1174

    
1175
int sl_set_ssl_opts(struct mg_connection *nc);
1176

    
1177
#ifdef __cplusplus
1178
}
1179
#endif
1180

    
1181
#endif /* MG_NET_IF == MG_NET_IF_SIMPLELINK && !defined(__SIMPLELINK_H__) */
1182

    
1183
#endif /* CS_COMMON_PLATFORMS_SIMPLELINK_CS_SIMPLELINK_H_ */
1184
#ifdef MG_MODULE_LINES
1185
#line 1 "common/platforms/platform_wince.h"
1186
#endif
1187
#ifndef CS_COMMON_PLATFORMS_PLATFORM_WINCE_H_
1188
#define CS_COMMON_PLATFORMS_PLATFORM_WINCE_H_
1189

    
1190
#if CS_PLATFORM == CS_P_WINCE
1191

    
1192
/*
1193
 * MSVC++ 14.0 _MSC_VER == 1900 (Visual Studio 2015)
1194
 * MSVC++ 12.0 _MSC_VER == 1800 (Visual Studio 2013)
1195
 * MSVC++ 11.0 _MSC_VER == 1700 (Visual Studio 2012)
1196
 * MSVC++ 10.0 _MSC_VER == 1600 (Visual Studio 2010)
1197
 * MSVC++ 9.0  _MSC_VER == 1500 (Visual Studio 2008)
1198
 * MSVC++ 8.0  _MSC_VER == 1400 (Visual Studio 2005)
1199
 * MSVC++ 7.1  _MSC_VER == 1310 (Visual Studio 2003)
1200
 * MSVC++ 7.0  _MSC_VER == 1300
1201
 * MSVC++ 6.0  _MSC_VER == 1200
1202
 * MSVC++ 5.0  _MSC_VER == 1100
1203
 */
1204
#pragma warning(disable : 4127) /* FD_SET() emits warning, disable it */
1205
#pragma warning(disable : 4204) /* missing c99 support */
1206

    
1207
#ifndef _WINSOCK_DEPRECATED_NO_WARNINGS
1208
#define _WINSOCK_DEPRECATED_NO_WARNINGS 1
1209
#endif
1210

    
1211
#ifndef _CRT_SECURE_NO_WARNINGS
1212
#define _CRT_SECURE_NO_WARNINGS
1213
#endif
1214

    
1215
#include <assert.h>
1216
#include <limits.h>
1217
#include <stddef.h>
1218
#include <stdio.h>
1219
#include <stdlib.h>
1220
#include <time.h>
1221

    
1222
#pragma comment(lib, "ws2.lib") /* Linking with WinCE winsock library */
1223

    
1224
#include <winsock2.h>
1225
#include <ws2tcpip.h>
1226
#include <windows.h>
1227

    
1228
#define strdup _strdup
1229

    
1230
#ifndef EINPROGRESS
1231
#define EINPROGRESS WSAEINPROGRESS
1232
#endif
1233

    
1234
#ifndef EWOULDBLOCK
1235
#define EWOULDBLOCK WSAEWOULDBLOCK
1236
#endif
1237

    
1238
#ifndef __func__
1239
#define STRX(x) #x
1240
#define STR(x) STRX(x)
1241
#define __func__ __FILE__ ":" STR(__LINE__)
1242
#endif
1243

    
1244
#define snprintf _snprintf
1245
#define fileno _fileno
1246
#define vsnprintf _vsnprintf
1247
#define sleep(x) Sleep((x) *1000)
1248
#define to64(x) _atoi64(x)
1249
#define rmdir _rmdir
1250

    
1251
#if defined(_MSC_VER) && _MSC_VER >= 1400
1252
#define fseeko(x, y, z) _fseeki64((x), (y), (z))
1253
#else
1254
#define fseeko(x, y, z) fseek((x), (y), (z))
1255
#endif
1256

    
1257
typedef int socklen_t;
1258

    
1259
#if _MSC_VER >= 1700
1260
#include <stdint.h>
1261
#else
1262
typedef signed char int8_t;
1263
typedef unsigned char uint8_t;
1264
typedef int int32_t;
1265
typedef unsigned int uint32_t;
1266
typedef short int16_t;
1267
typedef unsigned short uint16_t;
1268
typedef __int64 int64_t;
1269
typedef unsigned __int64 uint64_t;
1270
#endif
1271

    
1272
typedef SOCKET sock_t;
1273
typedef uint32_t in_addr_t;
1274

    
1275
#ifndef UINT16_MAX
1276
#define UINT16_MAX 65535
1277
#endif
1278

    
1279
#ifndef UINT32_MAX
1280
#define UINT32_MAX 4294967295
1281
#endif
1282

    
1283
#ifndef pid_t
1284
#define pid_t HANDLE
1285
#endif
1286

    
1287
#define INT64_FMT "I64d"
1288
#define INT64_X_FMT "I64x"
1289
/* TODO(alashkin): check if this is correct */
1290
#define SIZE_T_FMT "u"
1291

    
1292
#define DIRSEP '\\'
1293
#define CS_DEFINE_DIRENT
1294

    
1295
#ifndef va_copy
1296
#ifdef __va_copy
1297
#define va_copy __va_copy
1298
#else
1299
#define va_copy(x, y) (x) = (y)
1300
#endif
1301
#endif
1302

    
1303
#ifndef MG_MAX_HTTP_REQUEST_SIZE
1304
#define MG_MAX_HTTP_REQUEST_SIZE 8192
1305
#endif
1306

    
1307
#ifndef MG_MAX_HTTP_SEND_MBUF
1308
#define MG_MAX_HTTP_SEND_MBUF 4096
1309
#endif
1310

    
1311
#ifndef MG_MAX_HTTP_HEADERS
1312
#define MG_MAX_HTTP_HEADERS 40
1313
#endif
1314

    
1315
#ifndef CS_ENABLE_STDIO
1316
#define CS_ENABLE_STDIO 1
1317
#endif
1318

    
1319
#define abort() DebugBreak();
1320

    
1321
#ifndef BUFSIZ
1322
#define BUFSIZ 4096
1323
#endif
1324
/*
1325
 * Explicitly disabling MG_ENABLE_THREADS for WinCE
1326
 * because they are enabled for _WIN32 by default
1327
 */
1328
#ifndef MG_ENABLE_THREADS
1329
#define MG_ENABLE_THREADS 0
1330
#endif
1331

    
1332
#ifndef MG_ENABLE_FILESYSTEM
1333
#define MG_ENABLE_FILESYSTEM 1
1334
#endif
1335

    
1336
#ifndef MG_NET_IF
1337
#define MG_NET_IF MG_NET_IF_SOCKET
1338
#endif
1339

    
1340
typedef struct _stati64 {
1341
  uint32_t st_mtime;
1342
  uint32_t st_size;
1343
  uint32_t st_mode;
1344
} cs_stat_t;
1345

    
1346
/*
1347
 * WinCE 6.0 has a lot of useful definitions in ATL (not windows.h) headers
1348
 * use #ifdefs to avoid conflicts
1349
 */
1350

    
1351
#ifndef ENOENT
1352
#define ENOENT ERROR_PATH_NOT_FOUND
1353
#endif
1354

    
1355
#ifndef EACCES
1356
#define EACCES ERROR_ACCESS_DENIED
1357
#endif
1358

    
1359
#ifndef ENOMEM
1360
#define ENOMEM ERROR_NOT_ENOUGH_MEMORY
1361
#endif
1362

    
1363
#ifndef _UINTPTR_T_DEFINED
1364
typedef unsigned int* uintptr_t;
1365
#endif
1366

    
1367
#define _S_IFREG 2
1368
#define _S_IFDIR 4
1369

    
1370
#ifndef S_ISDIR
1371
#define S_ISDIR(x) (((x) & _S_IFDIR) != 0)
1372
#endif
1373

    
1374
#ifndef S_ISREG
1375
#define S_ISREG(x) (((x) & _S_IFREG) != 0)
1376
#endif
1377

    
1378
int open(const char *filename, int oflag, int pmode);
1379
int _wstati64(const wchar_t *path, cs_stat_t *st);
1380
const char *strerror();
1381

    
1382
#endif /* CS_PLATFORM == CS_P_WINCE */
1383
#endif /* CS_COMMON_PLATFORMS_PLATFORM_WINCE_H_ */
1384
#ifdef MG_MODULE_LINES
1385
#line 1 "common/platforms/platform_nxp_lpc.h"
1386
#endif
1387
/*
1388
 * Copyright (c) 2014-2016 Cesanta Software Limited
1389
 * All rights reserved
1390
 */
1391

    
1392
#ifndef CS_COMMON_PLATFORMS_PLATFORM_NXP_LPC_H_
1393
#define CS_COMMON_PLATFORMS_PLATFORM_NXP_LPC_H_
1394

    
1395
#if CS_PLATFORM == CS_P_NXP_LPC
1396

    
1397
#include <ctype.h>
1398
#include <stdint.h>
1399
#include <string.h>
1400

    
1401
#define SIZE_T_FMT "u"
1402
typedef struct stat cs_stat_t;
1403
#define INT64_FMT "lld"
1404
#define INT64_X_FMT "llx"
1405
#define __cdecl
1406

    
1407
#define MG_LWIP 1
1408

    
1409
#define MG_NET_IF MG_NET_IF_LWIP_LOW_LEVEL
1410

    
1411
/*
1412
 * LPCXpress comes with 3 C library implementations: Newlib, NewlibNano and Redlib.
1413
 * See https://community.nxp.com/message/630860 for more details.
1414
 *
1415
 * Redlib is the default and lacks certain things, so we provide them.
1416
 */
1417
#ifdef __REDLIB_INTERFACE_VERSION__
1418

    
1419
/* Let LWIP define timeval for us. */
1420
#define LWIP_TIMEVAL_PRIVATE 1
1421

    
1422
#define va_copy(d, s) __builtin_va_copy(d, s)
1423

    
1424
#define CS_ENABLE_TO64 1
1425
#define to64(x) cs_to64(x)
1426

    
1427
#define CS_ENABLE_STRDUP 1
1428

    
1429
#else
1430

    
1431
#include <sys/time.h>
1432
#define LWIP_TIMEVAL_PRIVATE 0
1433
#define to64(x) strtoll(x, NULL, 10)
1434

    
1435
#endif
1436

    
1437
#endif /* CS_PLATFORM == CS_P_NXP_LPC */
1438
#endif /* CS_COMMON_PLATFORMS_PLATFORM_NXP_LPC_H_ */
1439
#ifdef MG_MODULE_LINES
1440
#line 1 "common/platforms/platform_nxp_kinetis.h"
1441
#endif
1442
/*
1443
 * Copyright (c) 2014-2016 Cesanta Software Limited
1444
 * All rights reserved
1445
 */
1446

    
1447
#ifndef CS_COMMON_PLATFORMS_PLATFORM_NXP_KINETIS_H_
1448
#define CS_COMMON_PLATFORMS_PLATFORM_NXP_KINETIS_H_
1449

    
1450
#if CS_PLATFORM == CS_P_NXP_KINETIS
1451

    
1452
#include <ctype.h>
1453
#include <inttypes.h>
1454
#include <string.h>
1455
#include <sys/time.h>
1456

    
1457
#define SIZE_T_FMT "u"
1458
typedef struct stat cs_stat_t;
1459
#define to64(x) strtoll(x, NULL, 10)
1460
#define INT64_FMT "lld"
1461
#define INT64_X_FMT "llx"
1462
#define __cdecl
1463

    
1464
#define MG_LWIP 1
1465

    
1466
#define MG_NET_IF MG_NET_IF_LWIP_LOW_LEVEL
1467

    
1468
/* struct timeval is defined in sys/time.h. */
1469
#define LWIP_TIMEVAL_PRIVATE 0
1470

    
1471
#endif /* CS_PLATFORM == CS_P_NXP_KINETIS */
1472
#endif /* CS_COMMON_PLATFORMS_PLATFORM_NXP_KINETIS_H_ */
1473
#ifdef MG_MODULE_LINES
1474
#line 1 "common/platforms/platform_pic32.h"
1475
#endif
1476
/*
1477
 * Copyright (c) 2014-2016 Cesanta Software Limited
1478
 * All rights reserved
1479
 */
1480

    
1481
#ifndef CS_COMMON_PLATFORMS_PLATFORM_PIC32_H_
1482
#define CS_COMMON_PLATFORMS_PLATFORM_PIC32_H_
1483

    
1484
#if CS_PLATFORM == CS_P_PIC32
1485

    
1486
#define MG_NET_IF MG_NET_IF_PIC32
1487

    
1488
#include <stdint.h>
1489
#include <time.h>
1490
#include <ctype.h>
1491
#include <stdlib.h>
1492

    
1493
#include <system_config.h>
1494
#include <system_definitions.h>
1495

    
1496
#include <sys/types.h>
1497

    
1498
typedef TCP_SOCKET sock_t;
1499
#define to64(x) strtoll(x, NULL, 10)
1500

    
1501
#define SIZE_T_FMT "lu"
1502
#define INT64_FMT "lld"
1503

    
1504
#ifndef CS_ENABLE_STDIO
1505
#define CS_ENABLE_STDIO 1
1506
#endif
1507

    
1508
char* inet_ntoa(struct in_addr in);
1509

    
1510
#endif /* CS_PLATFORM == CS_P_PIC32 */
1511

    
1512
#endif /* CS_COMMON_PLATFORMS_PLATFORM_PIC32_H_ */
1513
#ifdef MG_MODULE_LINES
1514
#line 1 "common/platforms/platform_stm32.h"
1515
#endif
1516
/*
1517
 * Copyright (c) 2014-2016 Cesanta Software Limited
1518
 * All rights reserved
1519
 */
1520

    
1521
#ifndef CS_COMMON_PLATFORMS_PLATFORM_STM32_H_
1522
#define CS_COMMON_PLATFORMS_PLATFORM_STM32_H_
1523
#if CS_PLATFORM == CS_P_STM32
1524

    
1525
#include <sys/types.h>
1526
#include <sys/stat.h>
1527
#include <stdint.h>
1528
#include <inttypes.h>
1529
#include <stdio.h>
1530
#include <ctype.h>
1531
#include <errno.h>
1532
#include <memory.h>
1533
#include <fcntl.h>
1534
#include <stm32_sdk_hal.h>
1535

    
1536
#define to64(x) strtoll(x, NULL, 10)
1537
#define INT64_FMT PRId64
1538
#define SIZE_T_FMT "u"
1539
typedef struct stat cs_stat_t;
1540
#define DIRSEP '/'
1541

    
1542
#ifndef CS_ENABLE_STDIO
1543
#define CS_ENABLE_STDIO 1
1544
#endif
1545

    
1546
#ifndef MG_ENABLE_FILESYSTEM
1547
#define MG_ENABLE_FILESYSTEM 1
1548
#endif
1549

    
1550
#define CS_DEFINE_DIRENT
1551

    
1552
#endif /* CS_PLATFORM == CS_P_STM32 */
1553
#endif /* CS_COMMON_PLATFORMS_PLATFORM_STM32_H_ */
1554
#ifdef MG_MODULE_LINES
1555
#line 1 "common/platforms/lwip/mg_lwip.h"
1556
#endif
1557
/*
1558
 * Copyright (c) 2014-2016 Cesanta Software Limited
1559
 * All rights reserved
1560
 */
1561

    
1562
#ifndef CS_COMMON_PLATFORMS_LWIP_MG_LWIP_H_
1563
#define CS_COMMON_PLATFORMS_LWIP_MG_LWIP_H_
1564

    
1565
#ifndef MG_LWIP
1566
#define MG_LWIP 0
1567
#endif
1568

    
1569
#if MG_LWIP
1570

    
1571
/*
1572
 * When compiling for nRF5x chips with arm-none-eabi-gcc, it has BYTE_ORDER
1573
 * already defined, so in order to avoid warnings in lwip, we have to undefine
1574
 * it.
1575
 *
1576
 * TODO: Check if in the future versions of nRF5 SDK that changes.
1577
 *       Current version of nRF51 SDK: 0.8.0
1578
 *                          nRF5 SDK:  0.9.0
1579
 */
1580
#if CS_PLATFORM == CS_P_NRF51 || CS_PLATFORM == CS_P_NRF52
1581
#undef BYTE_ORDER
1582
#endif
1583

    
1584
#include <lwip/opt.h>
1585
#include <lwip/err.h>
1586
#include <lwip/ip_addr.h>
1587
#include <lwip/inet.h>
1588
#include <lwip/netdb.h>
1589
#include <lwip/dns.h>
1590

    
1591
#ifndef LWIP_PROVIDE_ERRNO
1592
#include <errno.h>
1593
#endif
1594

    
1595
#if LWIP_SOCKET
1596
#include <lwip/sockets.h>
1597
#else
1598
/* We really need the definitions from sockets.h. */
1599
#undef LWIP_SOCKET
1600
#define LWIP_SOCKET 1
1601
#include <lwip/sockets.h>
1602
#undef LWIP_SOCKET
1603
#define LWIP_SOCKET 0
1604
#endif
1605

    
1606
#define INVALID_SOCKET (-1)
1607
#define SOMAXCONN 10
1608
typedef int sock_t;
1609

    
1610
#if MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL
1611
struct mg_mgr;
1612
struct mg_connection;
1613
uint32_t mg_lwip_get_poll_delay_ms(struct mg_mgr *mgr);
1614
void mg_lwip_set_keepalive_params(struct mg_connection *nc, int idle,
1615
                                  int interval, int count);
1616
#endif
1617

    
1618
#endif /* MG_LWIP */
1619

    
1620
#endif /* CS_COMMON_PLATFORMS_LWIP_MG_LWIP_H_ */
1621
#ifdef MG_MODULE_LINES
1622
#line 1 "common/cs_time.h"
1623
#endif
1624
/*
1625
 * Copyright (c) 2014-2016 Cesanta Software Limited
1626
 * All rights reserved
1627
 */
1628

    
1629
#ifndef CS_COMMON_CS_TIME_H_
1630
#define CS_COMMON_CS_TIME_H_
1631

    
1632
/* Amalgamated: #include "common/platform.h" */
1633

    
1634
#ifdef __cplusplus
1635
extern "C" {
1636
#endif /* __cplusplus */
1637

    
1638
/* Sub-second granularity time(). */
1639
double cs_time(void);
1640

    
1641
#ifdef __cplusplus
1642
}
1643
#endif /* __cplusplus */
1644

    
1645
#endif /* CS_COMMON_CS_TIME_H_ */
1646
#ifdef MG_MODULE_LINES
1647
#line 1 "common/mg_str.h"
1648
#endif
1649
/*
1650
 * Copyright (c) 2014-2016 Cesanta Software Limited
1651
 * All rights reserved
1652
 */
1653

    
1654
#ifndef CS_COMMON_MG_STR_H_
1655
#define CS_COMMON_MG_STR_H_
1656

    
1657
#include <stddef.h>
1658

    
1659
/* Amalgamated: #include "common/platform.h" */
1660

    
1661
#ifdef __cplusplus
1662
extern "C" {
1663
#endif /* __cplusplus */
1664

    
1665
/* Describes chunk of memory */
1666
struct mg_str {
1667
  const char *p; /* Memory chunk pointer */
1668
  size_t len;    /* Memory chunk length */
1669
};
1670

    
1671
/*
1672
 * Helper functions for creating mg_str struct from plain C string.
1673
 * `NULL` is allowed and becomes `{NULL, 0}`.
1674
 */
1675
struct mg_str mg_mk_str(const char *s);
1676
struct mg_str mg_mk_str_n(const char *s, size_t len);
1677

    
1678
/* Macro for initializing mg_str. */
1679
#define MG_MK_STR(str_literal) \
1680
  { str_literal, sizeof(str_literal) - 1 }
1681

    
1682
/*
1683
 * Cross-platform version of `strcmp()` where where first string is
1684
 * specified by `struct mg_str`.
1685
 */
1686
int mg_vcmp(const struct mg_str *str2, const char *str1);
1687

    
1688
/*
1689
 * Cross-platform version of `strncasecmp()` where first string is
1690
 * specified by `struct mg_str`.
1691
 */
1692
int mg_vcasecmp(const struct mg_str *str2, const char *str1);
1693

    
1694
struct mg_str mg_strdup(const struct mg_str s);
1695
int mg_strcmp(const struct mg_str str1, const struct mg_str str2);
1696
int mg_strncmp(const struct mg_str str1, const struct mg_str str2, size_t n);
1697

    
1698
#ifdef __cplusplus
1699
}
1700
#endif /* __cplusplus */
1701

    
1702
#endif /* CS_COMMON_MG_STR_H_ */
1703
#ifdef MG_MODULE_LINES
1704
#line 1 "common/mbuf.h"
1705
#endif
1706
/*
1707
 * Copyright (c) 2015 Cesanta Software Limited
1708
 * All rights reserved
1709
 */
1710

    
1711
/*
1712
 * === Memory Buffers
1713
 *
1714
 * Mbufs are mutable/growing memory buffers, like C++ strings.
1715
 * Mbuf can append data to the end of a buffer or insert data into arbitrary
1716
 * position in the middle of a buffer. The buffer grows automatically when
1717
 * needed.
1718
 */
1719

    
1720
#ifndef CS_COMMON_MBUF_H_
1721
#define CS_COMMON_MBUF_H_
1722

    
1723
#include <stdlib.h>
1724
/* Amalgamated: #include "common/platform.h" */
1725

    
1726
#if defined(__cplusplus)
1727
extern "C" {
1728
#endif
1729

    
1730
#ifndef MBUF_SIZE_MULTIPLIER
1731
#define MBUF_SIZE_MULTIPLIER 1.5
1732
#endif
1733

    
1734
/* Memory buffer descriptor */
1735
struct mbuf {
1736
  char *buf;   /* Buffer pointer */
1737
  size_t len;  /* Data length. Data is located between offset 0 and len. */
1738
  size_t size; /* Buffer size allocated by realloc(1). Must be >= len */
1739
};
1740

    
1741
/*
1742
 * Initialises an Mbuf.
1743
 * `initial_capacity` specifies the initial capacity of the mbuf.
1744
 */
1745
void mbuf_init(struct mbuf *, size_t initial_capacity);
1746

    
1747
/* Frees the space allocated for the mbuffer and resets the mbuf structure. */
1748
void mbuf_free(struct mbuf *);
1749

    
1750
/*
1751
 * Appends data to the Mbuf.
1752
 *
1753
 * Returns the number of bytes appended or 0 if out of memory.
1754
 */
1755
size_t mbuf_append(struct mbuf *, const void *data, size_t data_size);
1756

    
1757
/*
1758
 * Inserts data at a specified offset in the Mbuf.
1759
 *
1760
 * Existing data will be shifted forwards and the buffer will
1761
 * be grown if necessary.
1762
 * Returns the number of bytes inserted.
1763
 */
1764
size_t mbuf_insert(struct mbuf *, size_t, const void *, size_t);
1765

    
1766
/* Removes `data_size` bytes from the beginning of the buffer. */
1767
void mbuf_remove(struct mbuf *, size_t data_size);
1768

    
1769
/*
1770
 * Resizes an Mbuf.
1771
 *
1772
 * If `new_size` is smaller than buffer's `len`, the
1773
 * resize is not performed.
1774
 */
1775
void mbuf_resize(struct mbuf *, size_t new_size);
1776

    
1777
/* Shrinks an Mbuf by resizing its `size` to `len`. */
1778
void mbuf_trim(struct mbuf *);
1779

    
1780
#if defined(__cplusplus)
1781
}
1782
#endif /* __cplusplus */
1783

    
1784
#endif /* CS_COMMON_MBUF_H_ */
1785
#ifdef MG_MODULE_LINES
1786
#line 1 "common/sha1.h"
1787
#endif
1788
/*
1789
 * Copyright (c) 2014 Cesanta Software Limited
1790
 * All rights reserved
1791
 */
1792

    
1793
#ifndef CS_COMMON_SHA1_H_
1794
#define CS_COMMON_SHA1_H_
1795

    
1796
#ifndef DISABLE_SHA1
1797
#define DISABLE_SHA1 0
1798
#endif
1799

    
1800
#if !DISABLE_SHA1
1801

    
1802
/* Amalgamated: #include "common/platform.h" */
1803

    
1804
#ifdef __cplusplus
1805
extern "C" {
1806
#endif /* __cplusplus */
1807

    
1808
typedef struct {
1809
  uint32_t state[5];
1810
  uint32_t count[2];
1811
  unsigned char buffer[64];
1812
} cs_sha1_ctx;
1813

    
1814
void cs_sha1_init(cs_sha1_ctx *);
1815
void cs_sha1_update(cs_sha1_ctx *, const unsigned char *data, uint32_t len);
1816
void cs_sha1_final(unsigned char digest[20], cs_sha1_ctx *);
1817
void cs_hmac_sha1(const unsigned char *key, size_t key_len,
1818
                  const unsigned char *text, size_t text_len,
1819
                  unsigned char out[20]);
1820
#ifdef __cplusplus
1821
}
1822
#endif /* __cplusplus */
1823

    
1824
#endif /* DISABLE_SHA1 */
1825

    
1826
#endif /* CS_COMMON_SHA1_H_ */
1827
#ifdef MG_MODULE_LINES
1828
#line 1 "common/md5.h"
1829
#endif
1830
/*
1831
 * Copyright (c) 2014 Cesanta Software Limited
1832
 * All rights reserved
1833
 */
1834

    
1835
#ifndef CS_COMMON_MD5_H_
1836
#define CS_COMMON_MD5_H_
1837

    
1838
/* Amalgamated: #include "common/platform.h" */
1839

    
1840
#ifndef DISABLE_MD5
1841
#define DISABLE_MD5 0
1842
#endif
1843

    
1844
#ifdef __cplusplus
1845
extern "C" {
1846
#endif /* __cplusplus */
1847

    
1848
typedef struct MD5Context {
1849
  uint32_t buf[4];
1850
  uint32_t bits[2];
1851
  unsigned char in[64];
1852
} MD5_CTX;
1853

    
1854
void MD5_Init(MD5_CTX *c);
1855
void MD5_Update(MD5_CTX *c, const unsigned char *data, size_t len);
1856
void MD5_Final(unsigned char *md, MD5_CTX *c);
1857

    
1858
/*
1859
 * Return stringified MD5 hash for NULL terminated list of pointer/length pairs.
1860
 * A length should be specified as size_t variable.
1861
 * Example:
1862
 *
1863
 *    char buf[33];
1864
 *    cs_md5(buf, "foo", (size_t) 3, "bar", (size_t) 3, NULL);
1865
 */
1866
char *cs_md5(char buf[33], ...);
1867

    
1868
#ifdef __cplusplus
1869
}
1870
#endif /* __cplusplus */
1871

    
1872
#endif /* CS_COMMON_MD5_H_ */
1873
#ifdef MG_MODULE_LINES
1874
#line 1 "common/base64.h"
1875
#endif
1876
/*
1877
 * Copyright (c) 2014 Cesanta Software Limited
1878
 * All rights reserved
1879
 */
1880

    
1881
#ifndef CS_COMMON_BASE64_H_
1882
#define CS_COMMON_BASE64_H_
1883

    
1884
#ifndef DISABLE_BASE64
1885
#define DISABLE_BASE64 0
1886
#endif
1887

    
1888
#if !DISABLE_BASE64
1889

    
1890
#include <stdio.h>
1891

    
1892
#ifdef __cplusplus
1893
extern "C" {
1894
#endif
1895

    
1896
typedef void (*cs_base64_putc_t)(char, void *);
1897

    
1898
struct cs_base64_ctx {
1899
  /* cannot call it putc because it's a macro on some environments */
1900
  cs_base64_putc_t b64_putc;
1901
  unsigned char chunk[3];
1902
  int chunk_size;
1903
  void *user_data;
1904
};
1905

    
1906
void cs_base64_init(struct cs_base64_ctx *ctx, cs_base64_putc_t putc,
1907
                    void *user_data);
1908
void cs_base64_update(struct cs_base64_ctx *ctx, const char *str, size_t len);
1909
void cs_base64_finish(struct cs_base64_ctx *ctx);
1910

    
1911
void cs_base64_encode(const unsigned char *src, int src_len, char *dst);
1912
void cs_fprint_base64(FILE *f, const unsigned char *src, int src_len);
1913
int cs_base64_decode(const unsigned char *s, int len, char *dst, int *dec_len);
1914

    
1915
#ifdef __cplusplus
1916
}
1917
#endif
1918

    
1919
#endif /* DISABLE_BASE64 */
1920

    
1921
#endif /* CS_COMMON_BASE64_H_ */
1922
#ifdef MG_MODULE_LINES
1923
#line 1 "common/str_util.h"
1924
#endif
1925
/*
1926
 * Copyright (c) 2015 Cesanta Software Limited
1927
 * All rights reserved
1928
 */
1929

    
1930
#ifndef CS_COMMON_STR_UTIL_H_
1931
#define CS_COMMON_STR_UTIL_H_
1932

    
1933
#include <stdarg.h>
1934
#include <stdlib.h>
1935

    
1936
/* Amalgamated: #include "common/platform.h" */
1937

    
1938
#ifndef CS_ENABLE_STRDUP
1939
#define CS_ENABLE_STRDUP 0
1940
#endif
1941

    
1942
#ifndef CS_ENABLE_TO64
1943
#define CS_ENABLE_TO64 0
1944
#endif
1945

    
1946
/*
1947
 * Expands to a string representation of its argument: e.g.
1948
 * `CS_STRINGIFY_LIT(5) expands to "5"`
1949
 */
1950
#define CS_STRINGIFY_LIT(x) #x
1951

    
1952
/*
1953
 * Expands to a string representation of its argument, which is allowed
1954
 * to be a macro: e.g.
1955
 *
1956
 * #define FOO 123
1957
 * CS_STRINGIFY_MACRO(FOO)
1958
 *
1959
 * expands to 123.
1960
 */
1961
#define CS_STRINGIFY_MACRO(x) CS_STRINGIFY_LIT(x)
1962

    
1963
#ifdef __cplusplus
1964
extern "C" {
1965
#endif
1966

    
1967
size_t c_strnlen(const char *s, size_t maxlen);
1968
int c_snprintf(char *buf, size_t buf_size, const char *format, ...);
1969
int c_vsnprintf(char *buf, size_t buf_size, const char *format, va_list ap);
1970
/*
1971
 * Find the first occurrence of find in s, where the search is limited to the
1972
 * first slen characters of s.
1973
 */
1974
const char *c_strnstr(const char *s, const char *find, size_t slen);
1975

    
1976
/*
1977
 * Stringify binary data. Output buffer size must be 2 * size_of_input + 1
1978
 * because each byte of input takes 2 bytes in string representation
1979
 * plus 1 byte for the terminating \0 character.
1980
 */
1981
void cs_to_hex(char *to, const unsigned char *p, size_t len);
1982

    
1983
/*
1984
 * Convert stringified binary data back to binary.
1985
 * Does the reverse of `cs_to_hex()`.
1986
 */
1987
void cs_from_hex(char *to, const char *p, size_t len);
1988

    
1989
#if CS_ENABLE_STRDUP
1990
char *strdup(const char *src);
1991
#endif
1992

    
1993
#if CS_ENABLE_TO64
1994
#include <stdint.h>
1995
/*
1996
 * Simple string -> int64 conversion routine.
1997
 */
1998
int64_t cs_to64(const char *s);
1999
#endif
2000

    
2001
/*
2002
 * Cross-platform version of `strncasecmp()`.
2003
 */
2004
int mg_ncasecmp(const char *s1, const char *s2, size_t len);
2005

    
2006
/*
2007
 * Cross-platform version of `strcasecmp()`.
2008
 */
2009
int mg_casecmp(const char *s1, const char *s2);
2010

    
2011
/*
2012
 * Prints message to the buffer. If the buffer is large enough to hold the
2013
 * message, it returns buffer. If buffer is to small, it allocates a large
2014
 * enough buffer on heap and returns allocated buffer.
2015
 * This is a supposed use case:
2016
 *
2017
 *    char buf[5], *p = buf;
2018
 *    mg_avprintf(&p, sizeof(buf), "%s", "hi there");
2019
 *    use_p_somehow(p);
2020
 *    if (p != buf) {
2021
 *      free(p);
2022
 *    }
2023
 *
2024
 * The purpose of this is to avoid malloc-ing if generated strings are small.
2025
 */
2026
int mg_asprintf(char **buf, size_t size, const char *fmt, ...);
2027

    
2028
/* Same as mg_asprintf, but takes varargs list. */
2029
int mg_avprintf(char **buf, size_t size, const char *fmt, va_list ap);
2030

    
2031
#ifdef __cplusplus
2032
}
2033
#endif
2034

    
2035
#endif /* CS_COMMON_STR_UTIL_H_ */
2036
#ifdef MG_MODULE_LINES
2037
#line 1 "common/queue.h"
2038
#endif
2039
/* clang-format off */
2040
/*-
2041
 * Copyright (c) 1991, 1993
2042
 *        The Regents of the University of California.  All rights reserved.
2043
 *
2044
 * Redistribution and use in source and binary forms, with or without
2045
 * modification, are permitted provided that the following conditions
2046
 * are met:
2047
 * 1. Redistributions of source code must retain the above copyright
2048
 *    notice, this list of conditions and the following disclaimer.
2049
 * 2. Redistributions in binary form must reproduce the above copyright
2050
 *    notice, this list of conditions and the following disclaimer in the
2051
 *    documentation and/or other materials provided with the distribution.
2052
 * 4. Neither the name of the University nor the names of its contributors
2053
 *    may be used to endorse or promote products derived from this software
2054
 *    without specific prior written permission.
2055
 *
2056
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
2057
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
2058
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
2059
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
2060
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2061
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
2062
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
2063
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
2064
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
2065
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
2066
 * SUCH DAMAGE.
2067
 *
2068
 *        @(#)queue.h        8.5 (Berkeley) 8/20/94
2069
 * $FreeBSD$
2070
 */
2071

    
2072
#ifndef _SYS_QUEUE_H_
2073
#define        _SYS_QUEUE_H_
2074

    
2075
/*
2076
 * This file defines four types of data structures: singly-linked lists,
2077
 * singly-linked tail queues, lists and tail queues.
2078
 *
2079
 * A singly-linked list is headed by a single forward pointer. The elements
2080
 * are singly linked for minimum space and pointer manipulation overhead at
2081
 * the expense of O(n) removal for arbitrary elements. New elements can be
2082
 * added to the list after an existing element or at the head of the list.
2083
 * Elements being removed from the head of the list should use the explicit
2084
 * macro for this purpose for optimum efficiency. A singly-linked list may
2085
 * only be traversed in the forward direction.  Singly-linked lists are ideal
2086
 * for applications with large datasets and few or no removals or for
2087
 * implementing a LIFO queue.
2088
 *
2089
 * A singly-linked tail queue is headed by a pair of pointers, one to the
2090
 * head of the list and the other to the tail of the list. The elements are
2091
 * singly linked for minimum space and pointer manipulation overhead at the
2092
 * expense of O(n) removal for arbitrary elements. New elements can be added
2093
 * to the list after an existing element, at the head of the list, or at the
2094
 * end of the list. Elements being removed from the head of the tail queue
2095
 * should use the explicit macro for this purpose for optimum efficiency.
2096
 * A singly-linked tail queue may only be traversed in the forward direction.
2097
 * Singly-linked tail queues are ideal for applications with large datasets
2098
 * and few or no removals or for implementing a FIFO queue.
2099
 *
2100
 * A list is headed by a single forward pointer (or an array of forward
2101
 * pointers for a hash table header). The elements are doubly linked
2102
 * so that an arbitrary element can be removed without a need to
2103
 * traverse the list. New elements can be added to the list before
2104
 * or after an existing element or at the head of the list. A list
2105
 * may be traversed in either direction.
2106
 *
2107
 * A tail queue is headed by a pair of pointers, one to the head of the
2108
 * list and the other to the tail of the list. The elements are doubly
2109
 * linked so that an arbitrary element can be removed without a need to
2110
 * traverse the list. New elements can be added to the list before or
2111
 * after an existing element, at the head of the list, or at the end of
2112
 * the list. A tail queue may be traversed in either direction.
2113
 *
2114
 * For details on the use of these macros, see the queue(3) manual page.
2115
 *
2116
 *
2117
 *                                SLIST        LIST        STAILQ        TAILQ
2118
 * _HEAD                        +        +        +        +
2119
 * _CLASS_HEAD                        +        +        +        +
2120
 * _HEAD_INITIALIZER                +        +        +        +
2121
 * _ENTRY                        +        +        +        +
2122
 * _CLASS_ENTRY                        +        +        +        +
2123
 * _INIT                        +        +        +        +
2124
 * _EMPTY                        +        +        +        +
2125
 * _FIRST                        +        +        +        +
2126
 * _NEXT                        +        +        +        +
2127
 * _PREV                        -        +        -        +
2128
 * _LAST                        -        -        +        +
2129
 * _FOREACH                        +        +        +        +
2130
 * _FOREACH_FROM                +        +        +        +
2131
 * _FOREACH_SAFE                +        +        +        +
2132
 * _FOREACH_FROM_SAFE                +        +        +        +
2133
 * _FOREACH_REVERSE                -        -        -        +
2134
 * _FOREACH_REVERSE_FROM        -        -        -        +
2135
 * _FOREACH_REVERSE_SAFE        -        -        -        +
2136
 * _FOREACH_REVERSE_FROM_SAFE        -        -        -        +
2137
 * _INSERT_HEAD                        +        +        +        +
2138
 * _INSERT_BEFORE                -        +        -        +
2139
 * _INSERT_AFTER                +        +        +        +
2140
 * _INSERT_TAIL                        -        -        +        +
2141
 * _CONCAT                        -        -        +        +
2142
 * _REMOVE_AFTER                +        -        +        -
2143
 * _REMOVE_HEAD                        +        -        +        -
2144
 * _REMOVE                        +        +        +        +
2145
 * _SWAP                        +        +        +        +
2146
 *
2147
 */
2148
#ifdef QUEUE_MACRO_DEBUG
2149
/* Store the last 2 places the queue element or head was altered */
2150
struct qm_trace {
2151
        unsigned long         lastline;
2152
        unsigned long         prevline;
2153
        const char        *lastfile;
2154
        const char        *prevfile;
2155
};
2156

    
2157
#define        TRACEBUF        struct qm_trace trace;
2158
#define        TRACEBUF_INITIALIZER        { __LINE__, 0, __FILE__, NULL } ,
2159
#define        TRASHIT(x)        do {(x) = (void *)-1;} while (0)
2160
#define        QMD_SAVELINK(name, link)        void **name = (void *)&(link)
2161

    
2162
#define        QMD_TRACE_HEAD(head) do {                                        \
2163
        (head)->trace.prevline = (head)->trace.lastline;                \
2164
        (head)->trace.prevfile = (head)->trace.lastfile;                \
2165
        (head)->trace.lastline = __LINE__;                                \
2166
        (head)->trace.lastfile = __FILE__;                                \
2167
} while (0)
2168

    
2169
#define        QMD_TRACE_ELEM(elem) do {                                        \
2170
        (elem)->trace.prevline = (elem)->trace.lastline;                \
2171
        (elem)->trace.prevfile = (elem)->trace.lastfile;                \
2172
        (elem)->trace.lastline = __LINE__;                                \
2173
        (elem)->trace.lastfile = __FILE__;                                \
2174
} while (0)
2175

    
2176
#else
2177
#define        QMD_TRACE_ELEM(elem)
2178
#define        QMD_TRACE_HEAD(head)
2179
#define        QMD_SAVELINK(name, link)
2180
#define        TRACEBUF
2181
#define        TRACEBUF_INITIALIZER
2182
#define        TRASHIT(x)
2183
#endif        /* QUEUE_MACRO_DEBUG */
2184

    
2185
#ifdef __cplusplus
2186
/*
2187
 * In C++ there can be structure lists and class lists:
2188
 */
2189
#define        QUEUE_TYPEOF(type) type
2190
#else
2191
#define        QUEUE_TYPEOF(type) struct type
2192
#endif
2193

    
2194
/*
2195
 * Singly-linked List declarations.
2196
 */
2197
#define        SLIST_HEAD(name, type)                                                \
2198
struct name {                                                                \
2199
        struct type *slh_first;        /* first element */                        \
2200
}
2201

    
2202
#define        SLIST_CLASS_HEAD(name, type)                                        \
2203
struct name {                                                                \
2204
        class type *slh_first;        /* first element */                        \
2205
}
2206

    
2207
#define        SLIST_HEAD_INITIALIZER(head)                                        \
2208
        { NULL }
2209

    
2210
#define        SLIST_ENTRY(type)                                                \
2211
struct {                                                                \
2212
        struct type *sle_next;        /* next element */                        \
2213
}
2214

    
2215
#define        SLIST_CLASS_ENTRY(type)                                                \
2216
struct {                                                                \
2217
        class type *sle_next;                /* next element */                \
2218
}
2219

    
2220
/*
2221
 * Singly-linked List functions.
2222
 */
2223
#define        SLIST_EMPTY(head)        ((head)->slh_first == NULL)
2224

    
2225
#define        SLIST_FIRST(head)        ((head)->slh_first)
2226

    
2227
#define        SLIST_FOREACH(var, head, field)                                        \
2228
        for ((var) = SLIST_FIRST((head));                                \
2229
            (var);                                                        \
2230
            (var) = SLIST_NEXT((var), field))
2231

    
2232
#define        SLIST_FOREACH_FROM(var, head, field)                                \
2233
        for ((var) = ((var) ? (var) : SLIST_FIRST((head)));                \
2234
            (var);                                                        \
2235
            (var) = SLIST_NEXT((var), field))
2236

    
2237
#define        SLIST_FOREACH_SAFE(var, head, field, tvar)                        \
2238
        for ((var) = SLIST_FIRST((head));                                \
2239
            (var) && ((tvar) = SLIST_NEXT((var), field), 1);                \
2240
            (var) = (tvar))
2241

    
2242
#define        SLIST_FOREACH_FROM_SAFE(var, head, field, tvar)                        \
2243
        for ((var) = ((var) ? (var) : SLIST_FIRST((head)));                \
2244
            (var) && ((tvar) = SLIST_NEXT((var), field), 1);                \
2245
            (var) = (tvar))
2246

    
2247
#define        SLIST_FOREACH_PREVPTR(var, varp, head, field)                        \
2248
        for ((varp) = &SLIST_FIRST((head));                                \
2249
            ((var) = *(varp)) != NULL;                                        \
2250
            (varp) = &SLIST_NEXT((var), field))
2251

    
2252
#define        SLIST_INIT(head) do {                                                \
2253
        SLIST_FIRST((head)) = NULL;                                        \
2254
} while (0)
2255

    
2256
#define        SLIST_INSERT_AFTER(slistelm, elm, field) do {                        \
2257
        SLIST_NEXT((elm), field) = SLIST_NEXT((slistelm), field);        \
2258
        SLIST_NEXT((slistelm), field) = (elm);                                \
2259
} while (0)
2260

    
2261
#define        SLIST_INSERT_HEAD(head, elm, field) do {                        \
2262
        SLIST_NEXT((elm), field) = SLIST_FIRST((head));                        \
2263
        SLIST_FIRST((head)) = (elm);                                        \
2264
} while (0)
2265

    
2266
#define        SLIST_NEXT(elm, field)        ((elm)->field.sle_next)
2267

    
2268
#define        SLIST_REMOVE(head, elm, type, field) do {                        \
2269
        QMD_SAVELINK(oldnext, (elm)->field.sle_next);                        \
2270
        if (SLIST_FIRST((head)) == (elm)) {                                \
2271
                SLIST_REMOVE_HEAD((head), field);                        \
2272
        }                                                                \
2273
        else {                                                                \
2274
                QUEUE_TYPEOF(type) *curelm = SLIST_FIRST(head);                \
2275
                while (SLIST_NEXT(curelm, field) != (elm))                \
2276
                        curelm = SLIST_NEXT(curelm, field);                \
2277
                SLIST_REMOVE_AFTER(curelm, field);                        \
2278
        }                                                                \
2279
        TRASHIT(*oldnext);                                                \
2280
} while (0)
2281

    
2282
#define SLIST_REMOVE_AFTER(elm, field) do {                                \
2283
        SLIST_NEXT(elm, field) =                                        \
2284
            SLIST_NEXT(SLIST_NEXT(elm, field), field);                        \
2285
} while (0)
2286

    
2287
#define        SLIST_REMOVE_HEAD(head, field) do {                                \
2288
        SLIST_FIRST((head)) = SLIST_NEXT(SLIST_FIRST((head)), field);        \
2289
} while (0)
2290

    
2291
#define SLIST_SWAP(head1, head2, type) do {                                \
2292
        QUEUE_TYPEOF(type) *swap_first = SLIST_FIRST(head1);                \
2293
        SLIST_FIRST(head1) = SLIST_FIRST(head2);                        \
2294
        SLIST_FIRST(head2) = swap_first;                                \
2295
} while (0)
2296

    
2297
/*
2298
 * Singly-linked Tail queue declarations.
2299
 */
2300
#define        STAILQ_HEAD(name, type)                                                \
2301
struct name {                                                                \
2302
        struct type *stqh_first;/* first element */                        \
2303
        struct type **stqh_last;/* addr of last next element */                \
2304
}
2305

    
2306
#define        STAILQ_CLASS_HEAD(name, type)                                        \
2307
struct name {                                                                \
2308
        class type *stqh_first;        /* first element */                        \
2309
        class type **stqh_last;        /* addr of last next element */                \
2310
}
2311

    
2312
#define        STAILQ_HEAD_INITIALIZER(head)                                        \
2313
        { NULL, &(head).stqh_first }
2314

    
2315
#define        STAILQ_ENTRY(type)                                                \
2316
struct {                                                                \
2317
        struct type *stqe_next;        /* next element */                        \
2318
}
2319

    
2320
#define        STAILQ_CLASS_ENTRY(type)                                        \
2321
struct {                                                                \
2322
        class type *stqe_next;        /* next element */                        \
2323
}
2324

    
2325
/*
2326
 * Singly-linked Tail queue functions.
2327
 */
2328
#define        STAILQ_CONCAT(head1, head2) do {                                \
2329
        if (!STAILQ_EMPTY((head2))) {                                        \
2330
                *(head1)->stqh_last = (head2)->stqh_first;                \
2331
                (head1)->stqh_last = (head2)->stqh_last;                \
2332
                STAILQ_INIT((head2));                                        \
2333
        }                                                                \
2334
} while (0)
2335

    
2336
#define        STAILQ_EMPTY(head)        ((head)->stqh_first == NULL)
2337

    
2338
#define        STAILQ_FIRST(head)        ((head)->stqh_first)
2339

    
2340
#define        STAILQ_FOREACH(var, head, field)                                \
2341
        for((var) = STAILQ_FIRST((head));                                \
2342
           (var);                                                        \
2343
           (var) = STAILQ_NEXT((var), field))
2344

    
2345
#define        STAILQ_FOREACH_FROM(var, head, field)                                \
2346
        for ((var) = ((var) ? (var) : STAILQ_FIRST((head)));                \
2347
           (var);                                                        \
2348
           (var) = STAILQ_NEXT((var), field))
2349

    
2350
#define        STAILQ_FOREACH_SAFE(var, head, field, tvar)                        \
2351
        for ((var) = STAILQ_FIRST((head));                                \
2352
            (var) && ((tvar) = STAILQ_NEXT((var), field), 1);                \
2353
            (var) = (tvar))
2354

    
2355
#define        STAILQ_FOREACH_FROM_SAFE(var, head, field, tvar)                \
2356
        for ((var) = ((var) ? (var) : STAILQ_FIRST((head)));                \
2357
            (var) && ((tvar) = STAILQ_NEXT((var), field), 1);                \
2358
            (var) = (tvar))
2359

    
2360
#define        STAILQ_INIT(head) do {                                                \
2361
        STAILQ_FIRST((head)) = NULL;                                        \
2362
        (head)->stqh_last = &STAILQ_FIRST((head));                        \
2363
} while (0)
2364

    
2365
#define        STAILQ_INSERT_AFTER(head, tqelm, elm, field) do {                \
2366
        if ((STAILQ_NEXT((elm), field) = STAILQ_NEXT((tqelm), field)) == NULL)\
2367
                (head)->stqh_last = &STAILQ_NEXT((elm), field);                \
2368
        STAILQ_NEXT((tqelm), field) = (elm);                                \
2369
} while (0)
2370

    
2371
#define        STAILQ_INSERT_HEAD(head, elm, field) do {                        \
2372
        if ((STAILQ_NEXT((elm), field) = STAILQ_FIRST((head))) == NULL)        \
2373
                (head)->stqh_last = &STAILQ_NEXT((elm), field);                \
2374
        STAILQ_FIRST((head)) = (elm);                                        \
2375
} while (0)
2376

    
2377
#define        STAILQ_INSERT_TAIL(head, elm, field) do {                        \
2378
        STAILQ_NEXT((elm), field) = NULL;                                \
2379
        *(head)->stqh_last = (elm);                                        \
2380
        (head)->stqh_last = &STAILQ_NEXT((elm), field);                        \
2381
} while (0)
2382

    
2383
#define        STAILQ_LAST(head, type, field)                                \
2384
        (STAILQ_EMPTY((head)) ? NULL :                                \
2385
            __containerof((head)->stqh_last,                        \
2386
            QUEUE_TYPEOF(type), field.stqe_next))
2387

    
2388
#define        STAILQ_NEXT(elm, field)        ((elm)->field.stqe_next)
2389

    
2390
#define        STAILQ_REMOVE(head, elm, type, field) do {                        \
2391
        QMD_SAVELINK(oldnext, (elm)->field.stqe_next);                        \
2392
        if (STAILQ_FIRST((head)) == (elm)) {                                \
2393
                STAILQ_REMOVE_HEAD((head), field);                        \
2394
        }                                                                \
2395
        else {                                                                \
2396
                QUEUE_TYPEOF(type) *curelm = STAILQ_FIRST(head);        \
2397
                while (STAILQ_NEXT(curelm, field) != (elm))                \
2398
                        curelm = STAILQ_NEXT(curelm, field);                \
2399
                STAILQ_REMOVE_AFTER(head, curelm, field);                \
2400
        }                                                                \
2401
        TRASHIT(*oldnext);                                                \
2402
} while (0)
2403

    
2404
#define STAILQ_REMOVE_AFTER(head, elm, field) do {                        \
2405
        if ((STAILQ_NEXT(elm, field) =                                        \
2406
             STAILQ_NEXT(STAILQ_NEXT(elm, field), field)) == NULL)        \
2407
                (head)->stqh_last = &STAILQ_NEXT((elm), field);                \
2408
} while (0)
2409

    
2410
#define        STAILQ_REMOVE_HEAD(head, field) do {                                \
2411
        if ((STAILQ_FIRST((head)) =                                        \
2412
             STAILQ_NEXT(STAILQ_FIRST((head)), field)) == NULL)                \
2413
                (head)->stqh_last = &STAILQ_FIRST((head));                \
2414
} while (0)
2415

    
2416
#define STAILQ_SWAP(head1, head2, type) do {                                \
2417
        QUEUE_TYPEOF(type) *swap_first = STAILQ_FIRST(head1);                \
2418
        QUEUE_TYPEOF(type) **swap_last = (head1)->stqh_last;                \
2419
        STAILQ_FIRST(head1) = STAILQ_FIRST(head2);                        \
2420
        (head1)->stqh_last = (head2)->stqh_last;                        \
2421
        STAILQ_FIRST(head2) = swap_first;                                \
2422
        (head2)->stqh_last = swap_last;                                        \
2423
        if (STAILQ_EMPTY(head1))                                        \
2424
                (head1)->stqh_last = &STAILQ_FIRST(head1);                \
2425
        if (STAILQ_EMPTY(head2))                                        \
2426
                (head2)->stqh_last = &STAILQ_FIRST(head2);                \
2427
} while (0)
2428

    
2429

    
2430
/*
2431
 * List declarations.
2432
 */
2433
#define        LIST_HEAD(name, type)                                                \
2434
struct name {                                                                \
2435
        struct type *lh_first;        /* first element */                        \
2436
}
2437

    
2438
#define        LIST_CLASS_HEAD(name, type)                                        \
2439
struct name {                                                                \
2440
        class type *lh_first;        /* first element */                        \
2441
}
2442

    
2443
#define        LIST_HEAD_INITIALIZER(head)                                        \
2444
        { NULL }
2445

    
2446
#define        LIST_ENTRY(type)                                                \
2447
struct {                                                                \
2448
        struct type *le_next;        /* next element */                        \
2449
        struct type **le_prev;        /* address of previous next element */        \
2450
}
2451

    
2452
#define        LIST_CLASS_ENTRY(type)                                                \
2453
struct {                                                                \
2454
        class type *le_next;        /* next element */                        \
2455
        class type **le_prev;        /* address of previous next element */        \
2456
}
2457

    
2458
/*
2459
 * List functions.
2460
 */
2461

    
2462
#if (defined(_KERNEL) && defined(INVARIANTS))
2463
#define        QMD_LIST_CHECK_HEAD(head, field) do {                                \
2464
        if (LIST_FIRST((head)) != NULL &&                                \
2465
            LIST_FIRST((head))->field.le_prev !=                        \
2466
             &LIST_FIRST((head)))                                        \
2467
                panic("Bad list head %p first->prev != head", (head));        \
2468
} while (0)
2469

    
2470
#define        QMD_LIST_CHECK_NEXT(elm, field) do {                                \
2471
        if (LIST_NEXT((elm), field) != NULL &&                                \
2472
            LIST_NEXT((elm), field)->field.le_prev !=                        \
2473
             &((elm)->field.le_next))                                        \
2474
                     panic("Bad link elm %p next->prev != elm", (elm));        \
2475
} while (0)
2476

    
2477
#define        QMD_LIST_CHECK_PREV(elm, field) do {                                \
2478
        if (*(elm)->field.le_prev != (elm))                                \
2479
                panic("Bad link elm %p prev->next != elm", (elm));        \
2480
} while (0)
2481
#else
2482
#define        QMD_LIST_CHECK_HEAD(head, field)
2483
#define        QMD_LIST_CHECK_NEXT(elm, field)
2484
#define        QMD_LIST_CHECK_PREV(elm, field)
2485
#endif /* (_KERNEL && INVARIANTS) */
2486

    
2487
#define        LIST_EMPTY(head)        ((head)->lh_first == NULL)
2488

    
2489
#define        LIST_FIRST(head)        ((head)->lh_first)
2490

    
2491
#define        LIST_FOREACH(var, head, field)                                        \
2492
        for ((var) = LIST_FIRST((head));                                \
2493
            (var);                                                        \
2494
            (var) = LIST_NEXT((var), field))
2495

    
2496
#define        LIST_FOREACH_FROM(var, head, field)                                \
2497
        for ((var) = ((var) ? (var) : LIST_FIRST((head)));                \
2498
            (var);                                                        \
2499
            (var) = LIST_NEXT((var), field))
2500

    
2501
#define        LIST_FOREACH_SAFE(var, head, field, tvar)                        \
2502
        for ((var) = LIST_FIRST((head));                                \
2503
            (var) && ((tvar) = LIST_NEXT((var), field), 1);                \
2504
            (var) = (tvar))
2505

    
2506
#define        LIST_FOREACH_FROM_SAFE(var, head, field, tvar)                        \
2507
        for ((var) = ((var) ? (var) : LIST_FIRST((head)));                \
2508
            (var) && ((tvar) = LIST_NEXT((var), field), 1);                \
2509
            (var) = (tvar))
2510

    
2511
#define        LIST_INIT(head) do {                                                \
2512
        LIST_FIRST((head)) = NULL;                                        \
2513
} while (0)
2514

    
2515
#define        LIST_INSERT_AFTER(listelm, elm, field) do {                        \
2516
        QMD_LIST_CHECK_NEXT(listelm, field);                                \
2517
        if ((LIST_NEXT((elm), field) = LIST_NEXT((listelm), field)) != NULL)\
2518
                LIST_NEXT((listelm), field)->field.le_prev =                \
2519
                    &LIST_NEXT((elm), field);                                \
2520
        LIST_NEXT((listelm), field) = (elm);                                \
2521
        (elm)->field.le_prev = &LIST_NEXT((listelm), field);                \
2522
} while (0)
2523

    
2524
#define        LIST_INSERT_BEFORE(listelm, elm, field) do {                        \
2525
        QMD_LIST_CHECK_PREV(listelm, field);                                \
2526
        (elm)->field.le_prev = (listelm)->field.le_prev;                \
2527
        LIST_NEXT((elm), field) = (listelm);                                \
2528
        *(listelm)->field.le_prev = (elm);                                \
2529
        (listelm)->field.le_prev = &LIST_NEXT((elm), field);                \
2530
} while (0)
2531

    
2532
#define        LIST_INSERT_HEAD(head, elm, field) do {                                \
2533
        QMD_LIST_CHECK_HEAD((head), field);                                \
2534
        if ((LIST_NEXT((elm), field) = LIST_FIRST((head))) != NULL)        \
2535
                LIST_FIRST((head))->field.le_prev = &LIST_NEXT((elm), field);\
2536
        LIST_FIRST((head)) = (elm);                                        \
2537
        (elm)->field.le_prev = &LIST_FIRST((head));                        \
2538
} while (0)
2539

    
2540
#define        LIST_NEXT(elm, field)        ((elm)->field.le_next)
2541

    
2542
#define        LIST_PREV(elm, head, type, field)                        \
2543
        ((elm)->field.le_prev == &LIST_FIRST((head)) ? NULL :        \
2544
            __containerof((elm)->field.le_prev,                        \
2545
            QUEUE_TYPEOF(type), field.le_next))
2546

    
2547
#define        LIST_REMOVE(elm, field) do {                                        \
2548
        QMD_SAVELINK(oldnext, (elm)->field.le_next);                        \
2549
        QMD_SAVELINK(oldprev, (elm)->field.le_prev);                        \
2550
        QMD_LIST_CHECK_NEXT(elm, field);                                \
2551
        QMD_LIST_CHECK_PREV(elm, field);                                \
2552
        if (LIST_NEXT((elm), field) != NULL)                                \
2553
                LIST_NEXT((elm), field)->field.le_prev =                 \
2554
                    (elm)->field.le_prev;                                \
2555
        *(elm)->field.le_prev = LIST_NEXT((elm), field);                \
2556
        TRASHIT(*oldnext);                                                \
2557
        TRASHIT(*oldprev);                                                \
2558
} while (0)
2559

    
2560
#define LIST_SWAP(head1, head2, type, field) do {                        \
2561
        QUEUE_TYPEOF(type) *swap_tmp = LIST_FIRST(head1);                \
2562
        LIST_FIRST((head1)) = LIST_FIRST((head2));                        \
2563
        LIST_FIRST((head2)) = swap_tmp;                                        \
2564
        if ((swap_tmp = LIST_FIRST((head1))) != NULL)                        \
2565
                swap_tmp->field.le_prev = &LIST_FIRST((head1));                \
2566
        if ((swap_tmp = LIST_FIRST((head2))) != NULL)                        \
2567
                swap_tmp->field.le_prev = &LIST_FIRST((head2));                \
2568
} while (0)
2569

    
2570
/*
2571
 * Tail queue declarations.
2572
 */
2573
#define        TAILQ_HEAD(name, type)                                                \
2574
struct name {                                                                \
2575
        struct type *tqh_first;        /* first element */                        \
2576
        struct type **tqh_last;        /* addr of last next element */                \
2577
        TRACEBUF                                                        \
2578
}
2579

    
2580
#define        TAILQ_CLASS_HEAD(name, type)                                        \
2581
struct name {                                                                \
2582
        class type *tqh_first;        /* first element */                        \
2583
        class type **tqh_last;        /* addr of last next element */                \
2584
        TRACEBUF                                                        \
2585
}
2586

    
2587
#define        TAILQ_HEAD_INITIALIZER(head)                                        \
2588
        { NULL, &(head).tqh_first, TRACEBUF_INITIALIZER }
2589

    
2590
#define        TAILQ_ENTRY(type)                                                \
2591
struct {                                                                \
2592
        struct type *tqe_next;        /* next element */                        \
2593
        struct type **tqe_prev;        /* address of previous next element */        \
2594
        TRACEBUF                                                        \
2595
}
2596

    
2597
#define        TAILQ_CLASS_ENTRY(type)                                                \
2598
struct {                                                                \
2599
        class type *tqe_next;        /* next element */                        \
2600
        class type **tqe_prev;        /* address of previous next element */        \
2601
        TRACEBUF                                                        \
2602
}
2603

    
2604
/*
2605
 * Tail queue functions.
2606
 */
2607
#if (defined(_KERNEL) && defined(INVARIANTS))
2608
#define        QMD_TAILQ_CHECK_HEAD(head, field) do {                                \
2609
        if (!TAILQ_EMPTY(head) &&                                        \
2610
            TAILQ_FIRST((head))->field.tqe_prev !=                        \
2611
             &TAILQ_FIRST((head)))                                        \
2612
                panic("Bad tailq head %p first->prev != head", (head));        \
2613
} while (0)
2614

    
2615
#define        QMD_TAILQ_CHECK_TAIL(head, field) do {                                \
2616
        if (*(head)->tqh_last != NULL)                                        \
2617
                    panic("Bad tailq NEXT(%p->tqh_last) != NULL", (head));         \
2618
} while (0)
2619

    
2620
#define        QMD_TAILQ_CHECK_NEXT(elm, field) do {                                \
2621
        if (TAILQ_NEXT((elm), field) != NULL &&                                \
2622
            TAILQ_NEXT((elm), field)->field.tqe_prev !=                        \
2623
             &((elm)->field.tqe_next))                                        \
2624
                panic("Bad link elm %p next->prev != elm", (elm));        \
2625
} while (0)
2626

    
2627
#define        QMD_TAILQ_CHECK_PREV(elm, field) do {                                \
2628
        if (*(elm)->field.tqe_prev != (elm))                                \
2629
                panic("Bad link elm %p prev->next != elm", (elm));        \
2630
} while (0)
2631
#else
2632
#define        QMD_TAILQ_CHECK_HEAD(head, field)
2633
#define        QMD_TAILQ_CHECK_TAIL(head, headname)
2634
#define        QMD_TAILQ_CHECK_NEXT(elm, field)
2635
#define        QMD_TAILQ_CHECK_PREV(elm, field)
2636
#endif /* (_KERNEL && INVARIANTS) */
2637

    
2638
#define        TAILQ_CONCAT(head1, head2, field) do {                                \
2639
        if (!TAILQ_EMPTY(head2)) {                                        \
2640
                *(head1)->tqh_last = (head2)->tqh_first;                \
2641
                (head2)->tqh_first->field.tqe_prev = (head1)->tqh_last;        \
2642
                (head1)->tqh_last = (head2)->tqh_last;                        \
2643
                TAILQ_INIT((head2));                                        \
2644
                QMD_TRACE_HEAD(head1);                                        \
2645
                QMD_TRACE_HEAD(head2);                                        \
2646
        }                                                                \
2647
} while (0)
2648

    
2649
#define        TAILQ_EMPTY(head)        ((head)->tqh_first == NULL)
2650

    
2651
#define        TAILQ_FIRST(head)        ((head)->tqh_first)
2652

    
2653
#define        TAILQ_FOREACH(var, head, field)                                        \
2654
        for ((var) = TAILQ_FIRST((head));                                \
2655
            (var);                                                        \
2656
            (var) = TAILQ_NEXT((var), field))
2657

    
2658
#define        TAILQ_FOREACH_FROM(var, head, field)                                \
2659
        for ((var) = ((var) ? (var) : TAILQ_FIRST((head)));                \
2660
            (var);                                                        \
2661
            (var) = TAILQ_NEXT((var), field))
2662

    
2663
#define        TAILQ_FOREACH_SAFE(var, head, field, tvar)                        \
2664
        for ((var) = TAILQ_FIRST((head));                                \
2665
            (var) && ((tvar) = TAILQ_NEXT((var), field), 1);                \
2666
            (var) = (tvar))
2667

    
2668
#define        TAILQ_FOREACH_FROM_SAFE(var, head, field, tvar)                        \
2669
        for ((var) = ((var) ? (var) : TAILQ_FIRST((head)));                \
2670
            (var) && ((tvar) = TAILQ_NEXT((var), field), 1);                \
2671
            (var) = (tvar))
2672

    
2673
#define        TAILQ_FOREACH_REVERSE(var, head, headname, field)                \
2674
        for ((var) = TAILQ_LAST((head), headname);                        \
2675
            (var);                                                        \
2676
            (var) = TAILQ_PREV((var), headname, field))
2677

    
2678
#define        TAILQ_FOREACH_REVERSE_FROM(var, head, headname, field)                \
2679
        for ((var) = ((var) ? (var) : TAILQ_LAST((head), headname));        \
2680
            (var);                                                        \
2681
            (var) = TAILQ_PREV((var), headname, field))
2682

    
2683
#define        TAILQ_FOREACH_REVERSE_SAFE(var, head, headname, field, tvar)        \
2684
        for ((var) = TAILQ_LAST((head), headname);                        \
2685
            (var) && ((tvar) = TAILQ_PREV((var), headname, field), 1);        \
2686
            (var) = (tvar))
2687

    
2688
#define        TAILQ_FOREACH_REVERSE_FROM_SAFE(var, head, headname, field, tvar) \
2689
        for ((var) = ((var) ? (var) : TAILQ_LAST((head), headname));        \
2690
            (var) && ((tvar) = TAILQ_PREV((var), headname, field), 1);        \
2691
            (var) = (tvar))
2692

    
2693
#define        TAILQ_INIT(head) do {                                                \
2694
        TAILQ_FIRST((head)) = NULL;                                        \
2695
        (head)->tqh_last = &TAILQ_FIRST((head));                        \
2696
        QMD_TRACE_HEAD(head);                                                \
2697
} while (0)
2698

    
2699
#define        TAILQ_INSERT_AFTER(head, listelm, elm, field) do {                \
2700
        QMD_TAILQ_CHECK_NEXT(listelm, field);                                \
2701
        if ((TAILQ_NEXT((elm), field) = TAILQ_NEXT((listelm), field)) != NULL)\
2702
                TAILQ_NEXT((elm), field)->field.tqe_prev =                 \
2703
                    &TAILQ_NEXT((elm), field);                                \
2704
        else {                                                                \
2705
                (head)->tqh_last = &TAILQ_NEXT((elm), field);                \
2706
                QMD_TRACE_HEAD(head);                                        \
2707
        }                                                                \
2708
        TAILQ_NEXT((listelm), field) = (elm);                                \
2709
        (elm)->field.tqe_prev = &TAILQ_NEXT((listelm), field);                \
2710
        QMD_TRACE_ELEM(&(elm)->field);                                        \
2711
        QMD_TRACE_ELEM(&(listelm)->field);                                \
2712
} while (0)
2713

    
2714
#define        TAILQ_INSERT_BEFORE(listelm, elm, field) do {                        \
2715
        QMD_TAILQ_CHECK_PREV(listelm, field);                                \
2716
        (elm)->field.tqe_prev = (listelm)->field.tqe_prev;                \
2717
        TAILQ_NEXT((elm), field) = (listelm);                                \
2718
        *(listelm)->field.tqe_prev = (elm);                                \
2719
        (listelm)->field.tqe_prev = &TAILQ_NEXT((elm), field);                \
2720
        QMD_TRACE_ELEM(&(elm)->field);                                        \
2721
        QMD_TRACE_ELEM(&(listelm)->field);                                \
2722
} while (0)
2723

    
2724
#define        TAILQ_INSERT_HEAD(head, elm, field) do {                        \
2725
        QMD_TAILQ_CHECK_HEAD(head, field);                                \
2726
        if ((TAILQ_NEXT((elm), field) = TAILQ_FIRST((head))) != NULL)        \
2727
                TAILQ_FIRST((head))->field.tqe_prev =                        \
2728
                    &TAILQ_NEXT((elm), field);                                \
2729
        else                                                                \
2730
                (head)->tqh_last = &TAILQ_NEXT((elm), field);                \
2731
        TAILQ_FIRST((head)) = (elm);                                        \
2732
        (elm)->field.tqe_prev = &TAILQ_FIRST((head));                        \
2733
        QMD_TRACE_HEAD(head);                                                \
2734
        QMD_TRACE_ELEM(&(elm)->field);                                        \
2735
} while (0)
2736

    
2737
#define        TAILQ_INSERT_TAIL(head, elm, field) do {                        \
2738
        QMD_TAILQ_CHECK_TAIL(head, field);                                \
2739
        TAILQ_NEXT((elm), field) = NULL;                                \
2740
        (elm)->field.tqe_prev = (head)->tqh_last;                        \
2741
        *(head)->tqh_last = (elm);                                        \
2742
        (head)->tqh_last = &TAILQ_NEXT((elm), field);                        \
2743
        QMD_TRACE_HEAD(head);                                                \
2744
        QMD_TRACE_ELEM(&(elm)->field);                                        \
2745
} while (0)
2746

    
2747
#define        TAILQ_LAST(head, headname)                                        \
2748
        (*(((struct headname *)((head)->tqh_last))->tqh_last))
2749

    
2750
#define        TAILQ_NEXT(elm, field) ((elm)->field.tqe_next)
2751

    
2752
#define        TAILQ_PREV(elm, headname, field)                                \
2753
        (*(((struct headname *)((elm)->field.tqe_prev))->tqh_last))
2754

    
2755
#define        TAILQ_REMOVE(head, elm, field) do {                                \
2756
        QMD_SAVELINK(oldnext, (elm)->field.tqe_next);                        \
2757
        QMD_SAVELINK(oldprev, (elm)->field.tqe_prev);                        \
2758
        QMD_TAILQ_CHECK_NEXT(elm, field);                                \
2759
        QMD_TAILQ_CHECK_PREV(elm, field);                                \
2760
        if ((TAILQ_NEXT((elm), field)) != NULL)                                \
2761
                TAILQ_NEXT((elm), field)->field.tqe_prev =                 \
2762
                    (elm)->field.tqe_prev;                                \
2763
        else {                                                                \
2764
                (head)->tqh_last = (elm)->field.tqe_prev;                \
2765
                QMD_TRACE_HEAD(head);                                        \
2766
        }                                                                \
2767
        *(elm)->field.tqe_prev = TAILQ_NEXT((elm), field);                \
2768
        TRASHIT(*oldnext);                                                \
2769
        TRASHIT(*oldprev);                                                \
2770
        QMD_TRACE_ELEM(&(elm)->field);                                        \
2771
} while (0)
2772

    
2773
#define TAILQ_SWAP(head1, head2, type, field) do {                        \
2774
        QUEUE_TYPEOF(type) *swap_first = (head1)->tqh_first;                \
2775
        QUEUE_TYPEOF(type) **swap_last = (head1)->tqh_last;                \
2776
        (head1)->tqh_first = (head2)->tqh_first;                        \
2777
        (head1)->tqh_last = (head2)->tqh_last;                                \
2778
        (head2)->tqh_first = swap_first;                                \
2779
        (head2)->tqh_last = swap_last;                                        \
2780
        if ((swap_first = (head1)->tqh_first) != NULL)                        \
2781
                swap_first->field.tqe_prev = &(head1)->tqh_first;        \
2782
        else                                                                \
2783
                (head1)->tqh_last = &(head1)->tqh_first;                \
2784
        if ((swap_first = (head2)->tqh_first) != NULL)                        \
2785
                swap_first->field.tqe_prev = &(head2)->tqh_first;        \
2786
        else                                                                \
2787
                (head2)->tqh_last = &(head2)->tqh_first;                \
2788
} while (0)
2789

    
2790
#endif /* !_SYS_QUEUE_H_ */
2791
#ifdef MG_MODULE_LINES
2792
#line 1 "mongoose/src/features.h"
2793
#endif
2794
/*
2795
 * Copyright (c) 2014-2016 Cesanta Software Limited
2796
 * All rights reserved
2797
 */
2798

    
2799
#ifndef CS_MONGOOSE_SRC_FEATURES_H_
2800
#define CS_MONGOOSE_SRC_FEATURES_H_
2801

    
2802
#ifndef MG_DISABLE_HTTP_DIGEST_AUTH
2803
#define MG_DISABLE_HTTP_DIGEST_AUTH 0
2804
#endif
2805

    
2806
#ifndef MG_DISABLE_HTTP_KEEP_ALIVE
2807
#define MG_DISABLE_HTTP_KEEP_ALIVE 0
2808
#endif
2809

    
2810
#ifndef MG_DISABLE_PFS
2811
#define MG_DISABLE_PFS 0
2812
#endif
2813

    
2814
#ifndef MG_DISABLE_WS_RANDOM_MASK
2815
#define MG_DISABLE_WS_RANDOM_MASK 0
2816
#endif
2817

    
2818
#ifndef MG_ENABLE_ASYNC_RESOLVER
2819
#define MG_ENABLE_ASYNC_RESOLVER 1
2820
#endif
2821

    
2822
#ifndef MG_ENABLE_BROADCAST
2823
#define MG_ENABLE_BROADCAST 0
2824
#endif
2825

    
2826
#ifndef MG_ENABLE_COAP
2827
#define MG_ENABLE_COAP 0
2828
#endif
2829

    
2830
#ifndef MG_ENABLE_DEBUG
2831
#define MG_ENABLE_DEBUG 0
2832
#endif
2833

    
2834
#ifndef MG_ENABLE_DIRECTORY_LISTING
2835
#define MG_ENABLE_DIRECTORY_LISTING 0
2836
#endif
2837

    
2838
#ifndef MG_ENABLE_DNS
2839
#define MG_ENABLE_DNS 1
2840
#endif
2841

    
2842
#ifndef MG_ENABLE_DNS_SERVER
2843
#define MG_ENABLE_DNS_SERVER 0
2844
#endif
2845

    
2846
#ifndef MG_ENABLE_FAKE_DAVLOCK
2847
#define MG_ENABLE_FAKE_DAVLOCK 0
2848
#endif
2849

    
2850
#ifndef MG_ENABLE_FILESYSTEM
2851
#define MG_ENABLE_FILESYSTEM 0
2852
#endif
2853

    
2854
#ifndef MG_ENABLE_GETADDRINFO
2855
#define MG_ENABLE_GETADDRINFO 0
2856
#endif
2857

    
2858
#ifndef MG_ENABLE_HEXDUMP
2859
#define MG_ENABLE_HEXDUMP CS_ENABLE_STDIO
2860
#endif
2861

    
2862
#ifndef MG_ENABLE_HTTP
2863
#define MG_ENABLE_HTTP 1
2864
#endif
2865

    
2866
#ifndef MG_ENABLE_HTTP_CGI
2867
#define MG_ENABLE_HTTP_CGI 0
2868
#endif
2869

    
2870
#ifndef MG_ENABLE_HTTP_SSI
2871
#define MG_ENABLE_HTTP_SSI MG_ENABLE_FILESYSTEM
2872
#endif
2873

    
2874
#ifndef MG_ENABLE_HTTP_SSI_EXEC
2875
#define MG_ENABLE_HTTP_SSI_EXEC 0
2876
#endif
2877

    
2878
#ifndef MG_ENABLE_HTTP_STREAMING_MULTIPART
2879
#define MG_ENABLE_HTTP_STREAMING_MULTIPART 0
2880
#endif
2881

    
2882
#ifndef MG_ENABLE_HTTP_WEBDAV
2883
#define MG_ENABLE_HTTP_WEBDAV 0
2884
#endif
2885

    
2886
#ifndef MG_ENABLE_HTTP_WEBSOCKET
2887
#define MG_ENABLE_HTTP_WEBSOCKET MG_ENABLE_HTTP
2888
#endif
2889

    
2890
#ifndef MG_ENABLE_IPV6
2891
#define MG_ENABLE_IPV6 0
2892
#endif
2893

    
2894
#ifndef MG_ENABLE_JAVASCRIPT
2895
#define MG_ENABLE_JAVASCRIPT 0
2896
#endif
2897

    
2898
#ifndef MG_ENABLE_MQTT
2899
#define MG_ENABLE_MQTT 1
2900
#endif
2901

    
2902
#ifndef MG_ENABLE_MQTT_BROKER
2903
#define MG_ENABLE_MQTT_BROKER 0
2904
#endif
2905

    
2906
#ifndef MG_ENABLE_SSL
2907
#define MG_ENABLE_SSL 0
2908
#endif
2909

    
2910
#ifndef MG_ENABLE_SYNC_RESOLVER
2911
#define MG_ENABLE_SYNC_RESOLVER 0
2912
#endif
2913

    
2914
#ifndef MG_ENABLE_STDIO
2915
#define MG_ENABLE_STDIO CS_ENABLE_STDIO
2916
#endif
2917

    
2918
#ifndef MG_NET_IF
2919
#define MG_NET_IF MG_NET_IF_SOCKET
2920
#endif
2921

    
2922
#ifndef MG_SSL_IF
2923
#define MG_SSL_IF MG_SSL_IF_OPENSSL
2924
#endif
2925

    
2926
#ifndef MG_ENABLE_THREADS /* ifdef-ok */
2927
#ifdef _WIN32
2928
#define MG_ENABLE_THREADS 1
2929
#else
2930
#define MG_ENABLE_THREADS 0
2931
#endif
2932
#endif
2933

    
2934
#if MG_ENABLE_DEBUG && !defined(CS_ENABLE_DEBUG)
2935
#define CS_ENABLE_DEBUG 1
2936
#endif
2937

    
2938
/* MQTT broker requires MQTT */
2939
#if MG_ENABLE_MQTT_BROKER && !MG_ENABLE_MQTT
2940
#undef MG_ENABLE_MQTT
2941
#define MG_ENABLE_MQTT 1
2942
#endif
2943

    
2944
#ifndef MG_ENABLE_HTTP_URL_REWRITES
2945
#define MG_ENABLE_HTTP_URL_REWRITES \
2946
  (CS_PLATFORM == CS_P_WINDOWS || CS_PLATFORM == CS_P_UNIX)
2947
#endif
2948

    
2949
#ifndef MG_ENABLE_TUN
2950
#define MG_ENABLE_TUN MG_ENABLE_HTTP_WEBSOCKET
2951
#endif
2952

    
2953
#ifndef MG_ENABLE_SNTP
2954
#define MG_ENABLE_SNTP 0
2955
#endif
2956

    
2957
#ifndef MG_ENABLE_EXTRA_ERRORS_DESC
2958
#define MG_ENABLE_EXTRA_ERRORS_DESC 0
2959
#endif
2960

    
2961
#endif /* CS_MONGOOSE_SRC_FEATURES_H_ */
2962
#ifdef MG_MODULE_LINES
2963
#line 1 "mongoose/src/net_if.h"
2964
#endif
2965
/*
2966
 * Copyright (c) 2014-2016 Cesanta Software Limited
2967
 * All rights reserved
2968
 */
2969

    
2970
#ifndef CS_MONGOOSE_SRC_NET_IF_H_
2971
#define CS_MONGOOSE_SRC_NET_IF_H_
2972

    
2973
/* Amalgamated: #include "common/platform.h" */
2974

    
2975
/*
2976
 * Internal async networking core interface.
2977
 * Consists of calls made by the core, which should not block,
2978
 * and callbacks back into the core ("..._cb").
2979
 * Callbacks may (will) cause methods to be invoked from within,
2980
 * but methods are not allowed to invoke callbacks inline.
2981
 *
2982
 * Implementation must ensure that only one callback is invoked at any time.
2983
 */
2984

    
2985
#ifdef __cplusplus
2986
extern "C" {
2987
#endif /* __cplusplus */
2988

    
2989
#define MG_MAIN_IFACE 0
2990

    
2991
struct mg_mgr;
2992
struct mg_connection;
2993
union socket_address;
2994

    
2995
struct mg_iface_vtable;
2996

    
2997
struct mg_iface {
2998
  struct mg_mgr *mgr;
2999
  void *data; /* Implementation-specific data */
3000
  struct mg_iface_vtable *vtable;
3001
};
3002

    
3003
struct mg_iface_vtable {
3004
  void (*init)(struct mg_iface *iface);
3005
  void (*free)(struct mg_iface *iface);
3006
  void (*add_conn)(struct mg_connection *nc);
3007
  void (*remove_conn)(struct mg_connection *nc);
3008
  time_t (*poll)(struct mg_iface *iface, int timeout_ms);
3009

    
3010
  /* Set up a listening TCP socket on a given address. rv = 0 -> ok. */
3011
  int (*listen_tcp)(struct mg_connection *nc, union socket_address *sa);
3012
  /* Request that a "listening" UDP socket be created. */
3013
  int (*listen_udp)(struct mg_connection *nc, union socket_address *sa);
3014

    
3015
  /* Request that a TCP connection is made to the specified address. */
3016
  void (*connect_tcp)(struct mg_connection *nc, const union socket_address *sa);
3017
  /* Open a UDP socket. Doesn't actually connect anything. */
3018
  void (*connect_udp)(struct mg_connection *nc);
3019

    
3020
  /* Send functions for TCP and UDP. Sent data is copied before return. */
3021
  void (*tcp_send)(struct mg_connection *nc, const void *buf, size_t len);
3022
  void (*udp_send)(struct mg_connection *nc, const void *buf, size_t len);
3023

    
3024
  void (*recved)(struct mg_connection *nc, size_t len);
3025

    
3026
  /* Perform interface-related connection initialization. Return 1 on ok. */
3027
  int (*create_conn)(struct mg_connection *nc);
3028
  /* Perform interface-related cleanup on connection before destruction. */
3029
  void (*destroy_conn)(struct mg_connection *nc);
3030

    
3031
  /* Associate a socket to a connection. */
3032
  void (*sock_set)(struct mg_connection *nc, sock_t sock);
3033

    
3034
  /* Put connection's address into *sa, local (remote = 0) or remote. */
3035
  void (*get_conn_addr)(struct mg_connection *nc, int remote,
3036
                        union socket_address *sa);
3037
};
3038

    
3039
extern struct mg_iface_vtable *mg_ifaces[];
3040
extern int mg_num_ifaces;
3041

    
3042
/* Creates a new interface instance. */
3043
struct mg_iface *mg_if_create_iface(struct mg_iface_vtable *vtable,
3044
                                    struct mg_mgr *mgr);
3045

    
3046
/*
3047
 * Find an interface with a given implementation. The search is started from
3048
 * interface `from`, exclusive. Returns NULL if none is found.
3049
 */
3050
struct mg_iface *mg_find_iface(struct mg_mgr *mgr,
3051
                               struct mg_iface_vtable *vtable,
3052
                               struct mg_iface *from);
3053
/*
3054
 * Deliver a new TCP connection. Returns NULL in case on error (unable to
3055
 * create connection, in which case interface state should be discarded.
3056
 * This is phase 1 of the two-phase process - MG_EV_ACCEPT will be delivered
3057
 * when mg_if_accept_tcp_cb is invoked.
3058
 */
3059
struct mg_connection *mg_if_accept_new_conn(struct mg_connection *lc);
3060
void mg_if_accept_tcp_cb(struct mg_connection *nc, union socket_address *sa,
3061
                         size_t sa_len);
3062

    
3063
/* Callback invoked by connect methods. err = 0 -> ok, != 0 -> error. */
3064
void mg_if_connect_cb(struct mg_connection *nc, int err);
3065
/* Callback that reports that data has been put on the wire. */
3066
void mg_if_sent_cb(struct mg_connection *nc, int num_sent);
3067
/*
3068
 * Receive callback.
3069
 * if `own` is true, buf must be heap-allocated and ownership is transferred
3070
 * to the core.
3071
 * Core will acknowledge consumption by calling iface::recved.
3072
 */
3073
void mg_if_recv_tcp_cb(struct mg_connection *nc, void *buf, int len, int own);
3074
/*
3075
 * Receive callback.
3076
 * buf must be heap-allocated and ownership is transferred to the core.
3077
 * Core will acknowledge consumption by calling iface::recved.
3078
 */
3079
void mg_if_recv_udp_cb(struct mg_connection *nc, void *buf, int len,
3080
                       union socket_address *sa, size_t sa_len);
3081

    
3082
/* void mg_if_close_conn(struct mg_connection *nc); */
3083

    
3084
/* Deliver a POLL event to the connection. */
3085
void mg_if_poll(struct mg_connection *nc, time_t now);
3086

    
3087
/* Deliver a TIMER event to the connection. */
3088
void mg_if_timer(struct mg_connection *c, double now);
3089

    
3090
#ifdef __cplusplus
3091
}
3092
#endif /* __cplusplus */
3093

    
3094
#endif /* CS_MONGOOSE_SRC_NET_IF_H_ */
3095
#ifdef MG_MODULE_LINES
3096
#line 1 "mongoose/src/ssl_if.h"
3097
#endif
3098
/*
3099
 * Copyright (c) 2014-2016 Cesanta Software Limited
3100
 * All rights reserved
3101
 */
3102

    
3103
#ifndef CS_MONGOOSE_SRC_SSL_IF_H_
3104
#define CS_MONGOOSE_SRC_SSL_IF_H_
3105

    
3106
#if MG_ENABLE_SSL
3107

    
3108
#ifdef __cplusplus
3109
extern "C" {
3110
#endif /* __cplusplus */
3111

    
3112
struct mg_ssl_if_ctx;
3113
struct mg_connection;
3114

    
3115
void mg_ssl_if_init();
3116

    
3117
enum mg_ssl_if_result {
3118
  MG_SSL_OK = 0,
3119
  MG_SSL_WANT_READ = -1,
3120
  MG_SSL_WANT_WRITE = -2,
3121
  MG_SSL_ERROR = -3,
3122
};
3123

    
3124
struct mg_ssl_if_conn_params {
3125
  const char *cert;
3126
  const char *key;
3127
  const char *ca_cert;
3128
  const char *server_name;
3129
  const char *cipher_suites;
3130
};
3131

    
3132
enum mg_ssl_if_result mg_ssl_if_conn_init(
3133
    struct mg_connection *nc, const struct mg_ssl_if_conn_params *params,
3134
    const char **err_msg);
3135
enum mg_ssl_if_result mg_ssl_if_conn_accept(struct mg_connection *nc,
3136
                                            struct mg_connection *lc);
3137
void mg_ssl_if_conn_free(struct mg_connection *nc);
3138

    
3139
enum mg_ssl_if_result mg_ssl_if_handshake(struct mg_connection *nc);
3140
int mg_ssl_if_read(struct mg_connection *nc, void *buf, size_t buf_size);
3141
int mg_ssl_if_write(struct mg_connection *nc, const void *data, size_t len);
3142

    
3143
#ifdef __cplusplus
3144
}
3145
#endif /* __cplusplus */
3146

    
3147
#endif /* MG_ENABLE_SSL */
3148

    
3149
#endif /* CS_MONGOOSE_SRC_SSL_IF_H_ */
3150
#ifdef MG_MODULE_LINES
3151
#line 1 "mongoose/src/net.h"
3152
#endif
3153
/*
3154
 * Copyright (c) 2014 Cesanta Software Limited
3155
 * All rights reserved
3156
 * This software is dual-licensed: you can redistribute it and/or modify
3157
 * it under the terms of the GNU General Public License version 2 as
3158
 * published by the Free Software Foundation. For the terms of this
3159
 * license, see <http://www.gnu.org/licenses/>.
3160
 *
3161
 * You are free to use this software under the terms of the GNU General
3162
 * Public License, but WITHOUT ANY WARRANTY; without even the implied
3163
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
3164
 * See the GNU General Public License for more details.
3165
 *
3166
 * Alternatively, you can license this software under a commercial
3167
 * license, as set out in <https://www.cesanta.com/license>.
3168
 */
3169

    
3170
/*
3171
 * === Core API: TCP/UDP/SSL
3172
 *
3173
 * NOTE: Mongoose manager is single threaded. It does not protect
3174
 * its data structures by mutexes, therefore all functions that are dealing
3175
 * with a particular event manager should be called from the same thread,
3176
 * with exception of the `mg_broadcast()` function. It is fine to have different
3177
 * event managers handled by different threads.
3178
 */
3179

    
3180
#ifndef CS_MONGOOSE_SRC_NET_H_
3181
#define CS_MONGOOSE_SRC_NET_H_
3182

    
3183
#if MG_ENABLE_JAVASCRIPT
3184
#define EXCLUDE_COMMON
3185
#include <v7.h>
3186
#endif
3187

    
3188
/* Amalgamated: #include "mongoose/src/common.h" */
3189
/* Amalgamated: #include "mongoose/src/net_if.h" */
3190
/* Amalgamated: #include "common/mbuf.h" */
3191

    
3192
#ifndef MG_VPRINTF_BUFFER_SIZE
3193
#define MG_VPRINTF_BUFFER_SIZE 100
3194
#endif
3195

    
3196
#ifdef MG_USE_READ_WRITE
3197
#define MG_RECV_FUNC(s, b, l, f) read(s, b, l)
3198
#define MG_SEND_FUNC(s, b, l, f) write(s, b, l)
3199
#else
3200
#define MG_RECV_FUNC(s, b, l, f) recv(s, b, l, f)
3201
#define MG_SEND_FUNC(s, b, l, f) send(s, b, l, f)
3202
#endif
3203

    
3204
#ifdef __cplusplus
3205
extern "C" {
3206
#endif /* __cplusplus */
3207

    
3208
union socket_address {
3209
  struct sockaddr sa;
3210
  struct sockaddr_in sin;
3211
#if MG_ENABLE_IPV6
3212
  struct sockaddr_in6 sin6;
3213
#else
3214
  struct sockaddr sin6;
3215
#endif
3216
};
3217

    
3218
struct mg_connection;
3219

    
3220
/*
3221
 * Callback function (event handler) prototype. Must be defined by the user.
3222
 * Mongoose calls the event handler, passing the events defined below.
3223
 */
3224
typedef void (*mg_event_handler_t)(struct mg_connection *nc, int ev,
3225
                                   void *ev_data);
3226

    
3227
/* Events. Meaning of event parameter (evp) is given in the comment. */
3228
#define MG_EV_POLL 0    /* Sent to each connection on each mg_mgr_poll() call */
3229
#define MG_EV_ACCEPT 1  /* New connection accepted. union socket_address * */
3230
#define MG_EV_CONNECT 2 /* connect() succeeded or failed. int *  */
3231
#define MG_EV_RECV 3    /* Data has benn received. int *num_bytes */
3232
#define MG_EV_SEND 4    /* Data has been written to a socket. int *num_bytes */
3233
#define MG_EV_CLOSE 5   /* Connection is closed. NULL */
3234
#define MG_EV_TIMER 6   /* now >= conn->ev_timer_time. double * */
3235

    
3236
/*
3237
 * Mongoose event manager.
3238
 */
3239
struct mg_mgr {
3240
  struct mg_connection *active_connections;
3241
#if MG_ENABLE_HEXDUMP
3242
  const char *hexdump_file; /* Debug hexdump file path */
3243
#endif
3244
#if MG_ENABLE_BROADCAST
3245
  sock_t ctl[2]; /* Socketpair for mg_broadcast() */
3246
#endif
3247
  void *user_data; /* User data */
3248
  int num_ifaces;
3249
  struct mg_iface **ifaces; /* network interfaces */
3250
#if MG_ENABLE_JAVASCRIPT
3251
  struct v7 *v7;
3252
#endif
3253
};
3254

    
3255
/*
3256
 * Mongoose connection.
3257
 */
3258
struct mg_connection {
3259
  struct mg_connection *next, *prev; /* mg_mgr::active_connections linkage */
3260
  struct mg_connection *listener;    /* Set only for accept()-ed connections */
3261
  struct mg_mgr *mgr;                /* Pointer to containing manager */
3262

    
3263
  sock_t sock; /* Socket to the remote peer */
3264
  int err;
3265
  union socket_address sa; /* Remote peer address */
3266
  size_t recv_mbuf_limit;  /* Max size of recv buffer */
3267
  struct mbuf recv_mbuf;   /* Received data */
3268
  struct mbuf send_mbuf;   /* Data scheduled for sending */
3269
  time_t last_io_time;     /* Timestamp of the last socket IO */
3270
  double ev_timer_time;    /* Timestamp of the future MG_EV_TIMER */
3271
#if MG_ENABLE_SSL
3272
  void *ssl_if_data; /* SSL library data. */
3273
#endif
3274
  mg_event_handler_t proto_handler; /* Protocol-specific event handler */
3275
  void *proto_data;                 /* Protocol-specific data */
3276
  void (*proto_data_destructor)(void *proto_data);
3277
  mg_event_handler_t handler; /* Event handler function */
3278
  void *user_data;            /* User-specific data */
3279
  union {
3280
    void *v;
3281
    /*
3282
     * the C standard is fussy about fitting function pointers into
3283
     * void pointers, since some archs might have fat pointers for functions.
3284
     */
3285
    mg_event_handler_t f;
3286
  } priv_1;
3287
  void *priv_2;
3288
  void *mgr_data; /* Implementation-specific event manager's data. */
3289
  struct mg_iface *iface;
3290
  unsigned long flags;
3291
/* Flags set by Mongoose */
3292
#define MG_F_LISTENING (1 << 0)          /* This connection is listening */
3293
#define MG_F_UDP (1 << 1)                /* This connection is UDP */
3294
#define MG_F_RESOLVING (1 << 2)          /* Waiting for async resolver */
3295
#define MG_F_CONNECTING (1 << 3)         /* connect() call in progress */
3296
#define MG_F_SSL (1 << 4)                /* SSL is enabled on the connection */
3297
#define MG_F_SSL_HANDSHAKE_DONE (1 << 5) /* SSL hanshake has completed */
3298
#define MG_F_WANT_READ (1 << 6)          /* SSL specific */
3299
#define MG_F_WANT_WRITE (1 << 7)         /* SSL specific */
3300
#define MG_F_IS_WEBSOCKET (1 << 8)       /* Websocket specific */
3301

    
3302
/* Flags that are settable by user */
3303
#define MG_F_SEND_AND_CLOSE (1 << 10)       /* Push remaining data and close  */
3304
#define MG_F_CLOSE_IMMEDIATELY (1 << 11)    /* Disconnect */
3305
#define MG_F_WEBSOCKET_NO_DEFRAG (1 << 12)  /* Websocket specific */
3306
#define MG_F_DELETE_CHUNK (1 << 13)         /* HTTP specific */
3307
#define MG_F_ENABLE_BROADCAST (1 << 14)     /* Allow broadcast address usage */
3308
#define MG_F_TUN_DO_NOT_RECONNECT (1 << 15) /* Don't reconnect tunnel */
3309

    
3310
#define MG_F_USER_1 (1 << 20) /* Flags left for application */
3311
#define MG_F_USER_2 (1 << 21)
3312
#define MG_F_USER_3 (1 << 22)
3313
#define MG_F_USER_4 (1 << 23)
3314
#define MG_F_USER_5 (1 << 24)
3315
#define MG_F_USER_6 (1 << 25)
3316
};
3317

    
3318
/*
3319
 * Initialise Mongoose manager. Side effect: ignores SIGPIPE signal.
3320
 * `mgr->user_data` field will be initialised with a `user_data` parameter.
3321
 * That is an arbitrary pointer, where the user code can associate some data
3322
 * with the particular Mongoose manager. For example, a C++ wrapper class
3323
 * could be written in which case `user_data` can hold a pointer to the
3324
 * class instance.
3325
 */
3326
void mg_mgr_init(struct mg_mgr *mgr, void *user_data);
3327

    
3328
/*
3329
 * Optional parameters to `mg_mgr_init_opt()`.
3330
 *
3331
 * If `main_iface` is not NULL, it will be used as the main interface in the
3332
 * default interface set. The pointer will be free'd by `mg_mgr_free`.
3333
 * Otherwise, the main interface will be autodetected based on the current
3334
 * platform.
3335
 *
3336
 * If `num_ifaces` is 0 and `ifaces` is NULL, the default interface set will be
3337
 * used.
3338
 * This is an advanced option, as it requires you to construct a full interface
3339
 * set, including special networking interfaces required by some optional
3340
 * features such as TCP tunneling. Memory backing `ifaces` and each of the
3341
 * `num_ifaces` pointers it contains will be reclaimed by `mg_mgr_free`.
3342
 */
3343
struct mg_mgr_init_opts {
3344
  struct mg_iface_vtable *main_iface;
3345
  int num_ifaces;
3346
  struct mg_iface_vtable **ifaces;
3347
};
3348

    
3349
/*
3350
 * Like `mg_mgr_init` but with more options.
3351
 *
3352
 * Notably, this allows you to create a manger and choose
3353
 * dynamically which networking interface implementation to use.
3354
 */
3355
void mg_mgr_init_opt(struct mg_mgr *mgr, void *user_data,
3356
                     struct mg_mgr_init_opts opts);
3357

    
3358
/*
3359
 * De-initialises Mongoose manager.
3360
 *
3361
 * Closes and deallocates all active connections.
3362
 */
3363
void mg_mgr_free(struct mg_mgr *);
3364

    
3365
/*
3366
 * This function performs the actual IO and must be called in a loop
3367
 * (an event loop). It returns the current timestamp.
3368
 * `milli` is the maximum number of milliseconds to sleep.
3369
 * `mg_mgr_poll()` checks all connections for IO readiness. If at least one
3370
 * of the connections is IO-ready, `mg_mgr_poll()` triggers the respective
3371
 * event handlers and returns.
3372
 */
3373
time_t mg_mgr_poll(struct mg_mgr *, int milli);
3374

    
3375
#if MG_ENABLE_BROADCAST
3376
/*
3377
 * Passes a message of a given length to all connections.
3378
 *
3379
 * Must be called from a thread that does NOT call `mg_mgr_poll()`.
3380
 * Note that `mg_broadcast()` is the only function
3381
 * that can be, and must be, called from a different (non-IO) thread.
3382
 *
3383
 * `func` callback function will be called by the IO thread for each
3384
 * connection. When called, the event will be `MG_EV_POLL`, and a message will
3385
 * be passed as the `ev_data` pointer. Maximum message size is capped
3386
 * by `MG_CTL_MSG_MESSAGE_SIZE` which is set to 8192 bytes.
3387
 */
3388
void mg_broadcast(struct mg_mgr *, mg_event_handler_t func, void *, size_t);
3389
#endif
3390

    
3391
/*
3392
 * Iterates over all active connections.
3393
 *
3394
 * Returns the next connection from the list
3395
 * of active connections or `NULL` if there are no more connections. Below
3396
 * is the iteration idiom:
3397
 *
3398
 * ```c
3399
 * for (c = mg_next(srv, NULL); c != NULL; c = mg_next(srv, c)) {
3400
 *   // Do something with connection `c`
3401
 * }
3402
 * ```
3403
 */
3404
struct mg_connection *mg_next(struct mg_mgr *, struct mg_connection *);
3405

    
3406
/*
3407
 * Optional parameters to `mg_add_sock_opt()`.
3408
 *
3409
 * `flags` is an initial `struct mg_connection::flags` bitmask to set,
3410
 * see `MG_F_*` flags definitions.
3411
 */
3412
struct mg_add_sock_opts {
3413
  void *user_data;           /* Initial value for connection's user_data */
3414
  unsigned int flags;        /* Initial connection flags */
3415
  const char **error_string; /* Placeholder for the error string */
3416
  struct mg_iface *iface;    /* Interface instance */
3417
};
3418

    
3419
/*
3420
 * Creates a connection, associates it with the given socket and event handler
3421
 * and adds it to the manager.
3422
 *
3423
 * For more options see the `mg_add_sock_opt` variant.
3424
 */
3425
struct mg_connection *mg_add_sock(struct mg_mgr *, sock_t, mg_event_handler_t);
3426

    
3427
/*
3428
 * Creates a connection, associates it with the given socket and event handler
3429
 * and adds to the manager.
3430
 *
3431
 * See the `mg_add_sock_opts` structure for a description of the options.
3432
 */
3433
struct mg_connection *mg_add_sock_opt(struct mg_mgr *, sock_t,
3434
                                      mg_event_handler_t,
3435
                                      struct mg_add_sock_opts);
3436

    
3437
/*
3438
 * Optional parameters to `mg_bind_opt()`.
3439
 *
3440
 * `flags` is an initial `struct mg_connection::flags` bitmask to set,
3441
 * see `MG_F_*` flags definitions.
3442
 */
3443
struct mg_bind_opts {
3444
  void *user_data;           /* Initial value for connection's user_data */
3445
  unsigned int flags;        /* Extra connection flags */
3446
  const char **error_string; /* Placeholder for the error string */
3447
  struct mg_iface *iface;    /* Interface instance */
3448
#if MG_ENABLE_SSL
3449
  /*
3450
   * SSL settings.
3451
   *
3452
   * Server certificate to present to clients or client certificate to
3453
   * present to tunnel dispatcher (for tunneled connections).
3454
   */
3455
  const char *ssl_cert;
3456
  /* Private key corresponding to the certificate. If ssl_cert is set but
3457
   * ssl_key is not, ssl_cert is used. */
3458
  const char *ssl_key;
3459
  /* CA bundle used to verify client certificates or tunnel dispatchers. */
3460
  const char *ssl_ca_cert;
3461
  /* Colon-delimited list of acceptable cipher suites.
3462
   * Names depend on the library used, for example:
3463
   *
3464
   * ECDH-ECDSA-AES128-GCM-SHA256:DHE-RSA-AES128-SHA256 (OpenSSL)
3465
   * TLS-ECDH-ECDSA-WITH-AES-128-GCM-SHA256:TLS-DHE-RSA-WITH-AES-128-GCM-SHA256
3466
   *   (mbedTLS)
3467
   *
3468
   * For OpenSSL the list can be obtained by running "openssl ciphers".
3469
   * For mbedTLS, names can be found in library/ssl_ciphersuites.c
3470
   * If NULL, a reasonable default is used.
3471
   */
3472
  const char *ssl_cipher_suites;
3473
#endif
3474
};
3475

    
3476
/*
3477
 * Creates a listening connection.
3478
 *
3479
 * See `mg_bind_opt` for full documentation.
3480
 */
3481
struct mg_connection *mg_bind(struct mg_mgr *, const char *,
3482
                              mg_event_handler_t);
3483
/*
3484
 * Creates a listening connection.
3485
 *
3486
 * The `address` parameter specifies which address to bind to. It's format is
3487
 * the same as for the `mg_connect()` call, where `HOST` part is optional.
3488
 * `address` can be just a port number, e.g. `:8000`. To bind to a specific
3489
 * interface, an IP address can be specified, e.g. `1.2.3.4:8000`. By default,
3490
 * a TCP connection is created. To create UDP connection, prepend `udp://`
3491
 * prefix, e.g. `udp://:8000`. To summarize, `address` paramer has following
3492
 * format: `[PROTO://][IP_ADDRESS]:PORT`, where `PROTO` could be `tcp` or
3493
 * `udp`.
3494
 *
3495
 * See the `mg_bind_opts` structure for a description of the optional
3496
 * parameters.
3497
 *
3498
 * Returns a new listening connection or `NULL` on error.
3499
 * NOTE: The connection remains owned by the manager, do not free().
3500
 */
3501
struct mg_connection *mg_bind_opt(struct mg_mgr *mgr, const char *address,
3502
                                  mg_event_handler_t handler,
3503
                                  struct mg_bind_opts opts);
3504

    
3505
/* Optional parameters to `mg_connect_opt()` */
3506
struct mg_connect_opts {
3507
  void *user_data;           /* Initial value for connection's user_data */
3508
  unsigned int flags;        /* Extra connection flags */
3509
  const char **error_string; /* Placeholder for the error string */
3510
  struct mg_iface *iface;    /* Interface instance */
3511
#if MG_ENABLE_SSL
3512
  /*
3513
   * SSL settings.
3514
   * Client certificate to present to the server.
3515
   */
3516
  const char *ssl_cert;
3517
  /*
3518
   * Private key corresponding to the certificate.
3519
   * If ssl_cert is set but ssl_key is not, ssl_cert is used.
3520
   */
3521
  const char *ssl_key;
3522
  /*
3523
   * Verify server certificate using this CA bundle. If set to "*", then SSL
3524
   * is enabled but no cert verification is performed.
3525
   */
3526
  const char *ssl_ca_cert;
3527
  /* Colon-delimited list of acceptable cipher suites.
3528
   * Names depend on the library used, for example:
3529
   *
3530
   * ECDH-ECDSA-AES128-GCM-SHA256:DHE-RSA-AES128-SHA256 (OpenSSL)
3531
   * TLS-ECDH-ECDSA-WITH-AES-128-GCM-SHA256:TLS-DHE-RSA-WITH-AES-128-GCM-SHA256
3532
   *   (mbedTLS)
3533
   *
3534
   * For OpenSSL the list can be obtained by running "openssl ciphers".
3535
   * For mbedTLS, names can be found in library/ssl_ciphersuites.c
3536
   * If NULL, a reasonable default is used.
3537
   */
3538
  const char *ssl_cipher_suites;
3539
  /*
3540
   * Server name verification. If ssl_ca_cert is set and the certificate has
3541
   * passed verification, its subject will be verified against this string.
3542
   * By default (if ssl_server_name is NULL) hostname part of the address will
3543
   * be used. Wildcard matching is supported. A special value of "*" disables
3544
   * name verification.
3545
   */
3546
  const char *ssl_server_name;
3547
#endif
3548
};
3549

    
3550
/*
3551
 * Connects to a remote host.
3552
 *
3553
 * See `mg_connect_opt()` for full documentation.
3554
 */
3555
struct mg_connection *mg_connect(struct mg_mgr *mgr, const char *address,
3556
                                 mg_event_handler_t handler);
3557

    
3558
/*
3559
 * Connects to a remote host.
3560
 *
3561
 * The `address` format is `[PROTO://]HOST:PORT`. `PROTO` could be `tcp` or
3562
 * `udp`. `HOST` could be an IP address,
3563
 * IPv6 address (if Mongoose is compiled with `-DMG_ENABLE_IPV6`) or a host
3564
 * name. If `HOST` is a name, Mongoose will resolve it asynchronously. Examples
3565
 * of valid addresses: `google.com:80`, `udp://1.2.3.4:53`, `10.0.0.1:443`,
3566
 * `[::1]:80`
3567
 *
3568
 * See the `mg_connect_opts` structure for a description of the optional
3569
 * parameters.
3570
 *
3571
 * Returns a new outbound connection or `NULL` on error.
3572
 *
3573
 * NOTE: The connection remains owned by the manager, do not free().
3574
 *
3575
 * NOTE: To enable IPv6 addresses `-DMG_ENABLE_IPV6` should be specified
3576
 * in the compilation flags.
3577
 *
3578
 * NOTE: The new connection will receive `MG_EV_CONNECT` as its first event
3579
 * which will report the connect success status.
3580
 * If the asynchronous resolution fails or the `connect()` syscall fails for
3581
 * whatever reason (e.g. with `ECONNREFUSED` or `ENETUNREACH`), then
3582
 * `MG_EV_CONNECT` event will report failure. Code example below:
3583
 *
3584
 * ```c
3585
 * static void ev_handler(struct mg_connection *nc, int ev, void *ev_data) {
3586
 *   int connect_status;
3587
 *
3588
 *   switch (ev) {
3589
 *     case MG_EV_CONNECT:
3590
 *       connect_status = * (int *) ev_data;
3591
 *       if (connect_status == 0) {
3592
 *         // Success
3593
 *       } else  {
3594
 *         // Error
3595
 *         printf("connect() error: %s\n", strerror(connect_status));
3596
 *       }
3597
 *       break;
3598
 *     ...
3599
 *   }
3600
 * }
3601
 *
3602
 *   ...
3603
 *   mg_connect(mgr, "my_site.com:80", ev_handler);
3604
 * ```
3605
 */
3606
struct mg_connection *mg_connect_opt(struct mg_mgr *mgr, const char *address,
3607
                                     mg_event_handler_t handler,
3608
                                     struct mg_connect_opts opts);
3609

    
3610
#if MG_ENABLE_SSL && MG_NET_IF != MG_NET_IF_SIMPLELINK
3611
/*
3612
 * Note: This function is deprecated. Please, use SSL options in
3613
 * mg_connect_opt.
3614
 *
3615
 * Enables SSL for a given connection.
3616
 * `cert` is a server certificate file name for a listening connection
3617
 * or a client certificate file name for an outgoing connection.
3618
 * The certificate files must be in PEM format. The server certificate file
3619
 * must contain a certificate, concatenated with a private key, optionally
3620
 * concatenated with DH parameters.
3621
 * `ca_cert` is a CA certificate or NULL if peer verification is not
3622
 * required.
3623
 * Return: NULL on success or error message on error.
3624
 */
3625
const char *mg_set_ssl(struct mg_connection *nc, const char *cert,
3626
                       const char *ca_cert);
3627
#endif
3628

    
3629
/*
3630
 * Sends data to the connection.
3631
 *
3632
 * Note that sending functions do not actually push data to the socket.
3633
 * They just append data to the output buffer. MG_EV_SEND will be delivered when
3634
 * the data has actually been pushed out.
3635
 */
3636
void mg_send(struct mg_connection *, const void *buf, int len);
3637

    
3638
/* Enables format string warnings for mg_printf */
3639
#if defined(__GNUC__)
3640
__attribute__((format(printf, 2, 3)))
3641
#endif
3642
/* don't separate from mg_printf declaration */
3643

    
3644
/*
3645
 * Sends `printf`-style formatted data to the connection.
3646
 *
3647
 * See `mg_send` for more details on send semantics.
3648
 */
3649
int mg_printf(struct mg_connection *, const char *fmt, ...);
3650

    
3651
/* Same as `mg_printf()`, but takes `va_list ap` as an argument. */
3652
int mg_vprintf(struct mg_connection *, const char *fmt, va_list ap);
3653

    
3654
/*
3655
 * Creates a socket pair.
3656
 * `sock_type` can be either `SOCK_STREAM` or `SOCK_DGRAM`.
3657
 * Returns 0 on failure and 1 on success.
3658
 */
3659
int mg_socketpair(sock_t[2], int sock_type);
3660

    
3661
#if MG_ENABLE_SYNC_RESOLVER
3662
/*
3663
 * Convert domain name into IP address.
3664
 *
3665
 * This is a utility function. If compilation flags have
3666
 * `-DMG_ENABLE_GETADDRINFO`, then `getaddrinfo()` call is used for name
3667
 * resolution. Otherwise, `gethostbyname()` is used.
3668
 *
3669
 * CAUTION: this function can block.
3670
 * Return 1 on success, 0 on failure.
3671
 */
3672
int mg_resolve(const char *domain_name, char *ip_addr_buf, size_t buf_len);
3673
#endif
3674

    
3675
/*
3676
 * Verify given IP address against the ACL.
3677
 *
3678
 * `remote_ip` - an IPv4 address to check, in host byte order
3679
 * `acl` - a comma separated list of IP subnets: `x.x.x.x/x` or `x.x.x.x`.
3680
 * Each subnet is
3681
 * prepended by either a - or a + sign. A plus sign means allow, where a
3682
 * minus sign means deny. If a subnet mask is omitted, such as `-1.2.3.4`,
3683
 * it means that only that single IP address is denied.
3684
 * Subnet masks may vary from 0 to 32, inclusive. The default setting
3685
 * is to allow all access. On each request the full list is traversed,
3686
 * and the last match wins. Example:
3687
 *
3688
 * `-0.0.0.0/0,+192.168/16` - deny all acccesses, only allow 192.168/16 subnet
3689
 *
3690
 * To learn more about subnet masks, see this
3691
 * link:https://en.wikipedia.org/wiki/Subnetwork[Wikipedia page on Subnetwork].
3692
 *
3693
 * Returns -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
3694
 */
3695
int mg_check_ip_acl(const char *acl, uint32_t remote_ip);
3696

    
3697
#if MG_ENABLE_JAVASCRIPT
3698
/*
3699
 * Enables server-side JavaScript scripting.
3700
 * Requires a `-DMG_ENABLE_JAVASCRIPT` compilation flag and V7 engine sources.
3701
 * V7 instance must not be destroyed during manager's lifetime.
3702
 * Returns a V7 error.
3703
 */
3704
enum v7_err mg_enable_javascript(struct mg_mgr *m, struct v7 *v7,
3705
                                 const char *init_js_file_name);
3706
#endif
3707

    
3708
/*
3709
 * Schedules an MG_EV_TIMER event to be delivered at `timestamp` time.
3710
 * `timestamp` is UNIX time (the number of seconds since Epoch). It is
3711
 * `double` instead of `time_t` to allow for sub-second precision.
3712
 * Returns the old timer value.
3713
 *
3714
 * Example: set the connect timeout to 1.5 seconds:
3715
 *
3716
 * ```
3717
 *  c = mg_connect(&mgr, "cesanta.com", ev_handler);
3718
 *  mg_set_timer(c, mg_time() + 1.5);
3719
 *  ...
3720
 *
3721
 *  void ev_handler(struct mg_connection *c, int ev, void *ev_data) {
3722
 *  switch (ev) {
3723
 *    case MG_EV_CONNECT:
3724
 *      mg_set_timer(c, 0);  // Clear connect timer
3725
 *      break;
3726
 *    case MG_EV_TIMER:
3727
 *      log("Connect timeout");
3728
 *      c->flags |= MG_F_CLOSE_IMMEDIATELY;
3729
 *      break;
3730
 * ```
3731
 */
3732
double mg_set_timer(struct mg_connection *c, double timestamp);
3733

    
3734
/*
3735
 * A sub-second precision version of time().
3736
 */
3737
double mg_time(void);
3738

    
3739
#ifdef __cplusplus
3740
}
3741
#endif /* __cplusplus */
3742

    
3743
#endif /* CS_MONGOOSE_SRC_NET_H_ */
3744
#ifdef MG_MODULE_LINES
3745
#line 1 "mongoose/src/uri.h"
3746
#endif
3747
/*
3748
 * Copyright (c) 2014 Cesanta Software Limited
3749
 * All rights reserved
3750
 */
3751

    
3752
/*
3753
 * === URI
3754
 */
3755

    
3756
#ifndef CS_MONGOOSE_SRC_URI_H_
3757
#define CS_MONGOOSE_SRC_URI_H_
3758

    
3759
/* Amalgamated: #include "mongoose/src/net.h" */
3760

    
3761
#ifdef __cplusplus
3762
extern "C" {
3763
#endif /* __cplusplus */
3764

    
3765
/*
3766
 * Parses an URI and fills string chunks with locations of the respective
3767
 * uri components within the input uri string. NULL pointers will be
3768
 * ignored.
3769
 *
3770
 * General syntax:
3771
 *
3772
 *     [scheme://[user_info@]]host[:port][/path][?query][#fragment]
3773
 *
3774
 * Example:
3775
 *
3776
 *     foo.com:80
3777
 *     tcp://foo.com:1234
3778
 *     http://foo.com:80/bar?baz=1
3779
 *     https://user:pw@foo.com:443/blah
3780
 *
3781
 * `path` will include the leading slash. `query` won't include the leading `?`.
3782
 * `host` can contain embedded colons if surrounded by square brackets in order
3783
 * to support IPv6 literal addresses.
3784
 *
3785
 *
3786
 * Returns 0 on success, -1 on error.
3787
 */
3788
int mg_parse_uri(struct mg_str uri, struct mg_str *scheme,
3789
                 struct mg_str *user_info, struct mg_str *host,
3790
                 unsigned int *port, struct mg_str *path, struct mg_str *query,
3791
                 struct mg_str *fragment);
3792

    
3793
int mg_normalize_uri_path(const struct mg_str *in, struct mg_str *out);
3794

    
3795
#ifdef __cplusplus
3796
}
3797
#endif /* __cplusplus */
3798
#endif /* CS_MONGOOSE_SRC_URI_H_ */
3799
#ifdef MG_MODULE_LINES
3800
#line 1 "mongoose/src/util.h"
3801
#endif
3802
/*
3803
 * Copyright (c) 2014 Cesanta Software Limited
3804
 * All rights reserved
3805
 */
3806

    
3807
/*
3808
 * === Utility API
3809
 */
3810

    
3811
#ifndef CS_MONGOOSE_SRC_UTIL_H_
3812
#define CS_MONGOOSE_SRC_UTIL_H_
3813

    
3814
#include <stdio.h>
3815

    
3816
/* Amalgamated: #include "mongoose/src/common.h" */
3817
/* Amalgamated: #include "mongoose/src/net_if.h" */
3818

    
3819
#ifdef __cplusplus
3820
extern "C" {
3821
#endif /* __cplusplus */
3822

    
3823
#ifndef MAX_PATH_SIZE
3824
#define MAX_PATH_SIZE 500
3825
#endif
3826

    
3827
/*
3828
 * Fetches substring from input string `s`, `end` into `v`.
3829
 * Skips initial delimiter characters. Records first non-delimiter character
3830
 * at the beginning of substring `v`. Then scans the rest of the string
3831
 * until a delimiter character or end-of-string is found.
3832
 * `delimiters` is a 0-terminated string containing delimiter characters.
3833
 * Either one of `delimiters` or `end_string` terminates the search.
3834
 * Returns an `s` pointer, advanced forward where parsing has stopped.
3835
 */
3836
const char *mg_skip(const char *s, const char *end_string,
3837
                    const char *delimiters, struct mg_str *v);
3838

    
3839
/*
3840
 * Decodes base64-encoded string `s`, `len` into the destination `dst`.
3841
 * The destination has to have enough space to hold the decoded buffer.
3842
 * Decoding stops either when all strings have been decoded or invalid an
3843
 * character appeared.
3844
 * Destination is '\0'-terminated.
3845
 * Returns the number of decoded characters. On success, that should be equal
3846
 * to `len`. On error (invalid character) the return value is smaller then
3847
 * `len`.
3848
 */
3849
int mg_base64_decode(const unsigned char *s, int len, char *dst);
3850

    
3851
/*
3852
 * Base64-encode chunk of memory `src`, `src_len` into the destination `dst`.
3853
 * Destination has to have enough space to hold encoded buffer.
3854
 * Destination is '\0'-terminated.
3855
 */
3856
void mg_base64_encode(const unsigned char *src, int src_len, char *dst);
3857

    
3858
#if MG_ENABLE_FILESYSTEM
3859
/*
3860
 * Performs a 64-bit `stat()` call against a given file.
3861
 *
3862
 * `path` should be UTF8 encoded.
3863
 *
3864
 * Return value is the same as for `stat()` syscall.
3865
 */
3866
int mg_stat(const char *path, cs_stat_t *st);
3867

    
3868
/*
3869
 * Opens the given file and returns a file stream.
3870
 *
3871
 * `path` and `mode` should be UTF8 encoded.
3872
 *
3873
 * Return value is the same as for the `fopen()` call.
3874
 */
3875
FILE *mg_fopen(const char *path, const char *mode);
3876

    
3877
/*
3878
 * Opens the given file and returns a file stream.
3879
 *
3880
 * `path` should be UTF8 encoded.
3881
 *
3882
 * Return value is the same as for the `open()` syscall.
3883
 */
3884
int mg_open(const char *path, int flag, int mode);
3885
#endif /* MG_ENABLE_FILESYSTEM */
3886

    
3887
#if MG_ENABLE_THREADS
3888
/*
3889
 * Starts a new detached thread.
3890
 * Arguments and semantics are the same as pthead's `pthread_create()`.
3891
 * `thread_func` is a thread function, `thread_func_param` is a parameter
3892
 * that is passed to the thread function.
3893
 */
3894
void *mg_start_thread(void *(*thread_func)(void *), void *thread_func_param);
3895
#endif
3896

    
3897
void mg_set_close_on_exec(sock_t);
3898

    
3899
#define MG_SOCK_STRINGIFY_IP 1
3900
#define MG_SOCK_STRINGIFY_PORT 2
3901
#define MG_SOCK_STRINGIFY_REMOTE 4
3902
/*
3903
 * Converts a connection's local or remote address into string.
3904
 *
3905
 * The `flags` parameter is a bit mask that controls the behaviour,
3906
 * see `MG_SOCK_STRINGIFY_*` definitions.
3907
 *
3908
 * - MG_SOCK_STRINGIFY_IP - print IP address
3909
 * - MG_SOCK_STRINGIFY_PORT - print port number
3910
 * - MG_SOCK_STRINGIFY_REMOTE - print remote peer's IP/port, not local address
3911
 *
3912
 * If both port number and IP address are printed, they are separated by `:`.
3913
 * If compiled with `-DMG_ENABLE_IPV6`, IPv6 addresses are supported.
3914
 */
3915
void mg_conn_addr_to_str(struct mg_connection *nc, char *buf, size_t len,
3916
                         int flags);
3917
#if MG_NET_IF == MG_NET_IF_SOCKET
3918
/* Legacy interface. */
3919
void mg_sock_to_str(sock_t sock, char *buf, size_t len, int flags);
3920
#endif
3921

    
3922
/*
3923
 * Convert the socket's address into string.
3924
 *
3925
 * `flags` is MG_SOCK_STRINGIFY_IP and/or MG_SOCK_STRINGIFY_PORT.
3926
 */
3927
void mg_sock_addr_to_str(const union socket_address *sa, char *buf, size_t len,
3928
                         int flags);
3929

    
3930
#if MG_ENABLE_HEXDUMP
3931
/*
3932
 * Generates a human-readable hexdump of memory chunk.
3933
 *
3934
 * Takes a memory buffer `buf` of length `len` and creates a hex dump of that
3935
 * buffer in `dst`. The generated output is a-la hexdump(1).
3936
 * Returns the length of generated string, excluding terminating `\0`. If
3937
 * returned length is bigger than `dst_len`, the overflow bytes are discarded.
3938
 */
3939
int mg_hexdump(const void *buf, int len, char *dst, int dst_len);
3940

    
3941
/*
3942
 * Generates human-readable hexdump of the data sent or received by the
3943
 * connection. `path` is a file name where hexdump should be written.
3944
 * `num_bytes` is a number of bytes sent/received. `ev` is one of the `MG_*`
3945
 * events sent to an event handler. This function is supposed to be called from
3946
 * the event handler.
3947
 */
3948
void mg_hexdump_connection(struct mg_connection *nc, const char *path,
3949
                           const void *buf, int num_bytes, int ev);
3950
#endif
3951

    
3952
/*
3953
 * Returns true if target platform is big endian.
3954
 */
3955
int mg_is_big_endian(void);
3956

    
3957
/*
3958
 * A helper function for traversing a comma separated list of values.
3959
 * It returns a list pointer shifted to the next value or NULL if the end
3960
 * of the list found.
3961
 * The value is stored in a val vector. If the value has a form "x=y", then
3962
 * eq_val vector is initialised to point to the "y" part, and val vector length
3963
 * is adjusted to point only to "x".
3964
 * If the list is just a comma separated list of entries, like "aa,bb,cc" then
3965
 * `eq_val` will contain zero-length string.
3966
 *
3967
 * The purpose of this function is to parse comma separated string without
3968
 * any copying/memory allocation.
3969
 */
3970
const char *mg_next_comma_list_entry(const char *list, struct mg_str *val,
3971
                                     struct mg_str *eq_val);
3972

    
3973
/*
3974
 * Matches 0-terminated string (mg_match_prefix) or string with given length
3975
 * mg_match_prefix_n against a glob pattern.
3976
 *
3977
 * Match is case-insensitive. Returns number of bytes matched, or -1 if no
3978
 * match.
3979
 */
3980
int mg_match_prefix(const char *pattern, int pattern_len, const char *str);
3981
int mg_match_prefix_n(const struct mg_str pattern, const struct mg_str str);
3982

    
3983
/*
3984
 * Use with cs_base64_init/update/finish in order to write out base64 in chunks.
3985
 */
3986
void mg_mbuf_append_base64_putc(char ch, void *user_data);
3987

    
3988
/*
3989
 * Encode `len` bytes starting at `data` as base64 and append them to an mbuf.
3990
 */
3991
void mg_mbuf_append_base64(struct mbuf *mbuf, const void *data, size_t len);
3992

    
3993
/*
3994
 * Generate a Basic Auth header and appends it to buf.
3995
 * If pass is NULL, then user is expected to contain the credentials pair
3996
 * already encoded as `user:pass`.
3997
 */
3998
void mg_basic_auth_header(const char *user, const char *pass, struct mbuf *buf);
3999

    
4000
#ifdef __cplusplus
4001
}
4002
#endif /* __cplusplus */
4003
#endif /* CS_MONGOOSE_SRC_UTIL_H_ */
4004
#ifdef MG_MODULE_LINES
4005
#line 1 "mongoose/src/http.h"
4006
#endif
4007
/*
4008
 * Copyright (c) 2014 Cesanta Software Limited
4009
 * All rights reserved
4010
 */
4011

    
4012
/*
4013
 * === Common API reference
4014
 */
4015

    
4016
#ifndef CS_MONGOOSE_SRC_HTTP_H_
4017
#define CS_MONGOOSE_SRC_HTTP_H_
4018

    
4019
#if MG_ENABLE_HTTP
4020

    
4021
/* Amalgamated: #include "mongoose/src/net.h" */
4022
/* Amalgamated: #include "common/mg_str.h" */
4023

    
4024
#ifdef __cplusplus
4025
extern "C" {
4026
#endif /* __cplusplus */
4027

    
4028
#ifndef MG_MAX_HTTP_HEADERS
4029
#define MG_MAX_HTTP_HEADERS 20
4030
#endif
4031

    
4032
#ifndef MG_MAX_HTTP_REQUEST_SIZE
4033
#define MG_MAX_HTTP_REQUEST_SIZE 1024
4034
#endif
4035

    
4036
#ifndef MG_MAX_PATH
4037
#ifdef PATH_MAX
4038
#define MG_MAX_PATH PATH_MAX
4039
#else
4040
#define MG_MAX_PATH 256
4041
#endif
4042
#endif
4043

    
4044
#ifndef MG_MAX_HTTP_SEND_MBUF
4045
#define MG_MAX_HTTP_SEND_MBUF 1024
4046
#endif
4047

    
4048
#ifndef MG_CGI_ENVIRONMENT_SIZE
4049
#define MG_CGI_ENVIRONMENT_SIZE 8192
4050
#endif
4051

    
4052
/* HTTP message */
4053
struct http_message {
4054
  struct mg_str message; /* Whole message: request line + headers + body */
4055

    
4056
  /* HTTP Request line (or HTTP response line) */
4057
  struct mg_str method; /* "GET" */
4058
  struct mg_str uri;    /* "/my_file.html" */
4059
  struct mg_str proto;  /* "HTTP/1.1" -- for both request and response */
4060

    
4061
  /* For responses, code and response status message are set */
4062
  int resp_code;
4063
  struct mg_str resp_status_msg;
4064

    
4065
  /*
4066
   * Query-string part of the URI. For example, for HTTP request
4067
   *    GET /foo/bar?param1=val1&param2=val2
4068
   *    |    uri    |     query_string     |
4069
   *
4070
   * Note that question mark character doesn't belong neither to the uri,
4071
   * nor to the query_string
4072
   */
4073
  struct mg_str query_string;
4074

    
4075
  /* Headers */
4076
  struct mg_str header_names[MG_MAX_HTTP_HEADERS];
4077
  struct mg_str header_values[MG_MAX_HTTP_HEADERS];
4078

    
4079
  /* Message body */
4080
  struct mg_str body; /* Zero-length for requests with no body */
4081
};
4082

    
4083
#if MG_ENABLE_HTTP_WEBSOCKET
4084
/* WebSocket message */
4085
struct websocket_message {
4086
  unsigned char *data;
4087
  size_t size;
4088
  unsigned char flags;
4089
};
4090
#endif
4091

    
4092
/* HTTP multipart part */
4093
struct mg_http_multipart_part {
4094
  const char *file_name;
4095
  const char *var_name;
4096
  struct mg_str data;
4097
  int status; /* <0 on error */
4098
  void *user_data;
4099
};
4100

    
4101
/* SSI call context */
4102
struct mg_ssi_call_ctx {
4103
  struct http_message *req; /* The request being processed. */
4104
  struct mg_str file;       /* Filesystem path of the file being processed. */
4105
  struct mg_str arg; /* The argument passed to the tag: <!-- call arg -->. */
4106
};
4107

    
4108
/* HTTP and websocket events. void *ev_data is described in a comment. */
4109
#define MG_EV_HTTP_REQUEST 100 /* struct http_message * */
4110
#define MG_EV_HTTP_REPLY 101   /* struct http_message * */
4111
#define MG_EV_HTTP_CHUNK 102   /* struct http_message * */
4112
#define MG_EV_SSI_CALL 105     /* char * */
4113
#define MG_EV_SSI_CALL_CTX 106 /* struct mg_ssi_call_ctx * */
4114

    
4115
#if MG_ENABLE_HTTP_WEBSOCKET
4116
#define MG_EV_WEBSOCKET_HANDSHAKE_REQUEST 111 /* struct http_message * */
4117
#define MG_EV_WEBSOCKET_HANDSHAKE_DONE 112    /* NULL */
4118
#define MG_EV_WEBSOCKET_FRAME 113             /* struct websocket_message * */
4119
#define MG_EV_WEBSOCKET_CONTROL_FRAME 114     /* struct websocket_message * */
4120
#endif
4121

    
4122
#if MG_ENABLE_HTTP_STREAMING_MULTIPART
4123
#define MG_EV_HTTP_MULTIPART_REQUEST 121 /* struct http_message */
4124
#define MG_EV_HTTP_PART_BEGIN 122        /* struct mg_http_multipart_part */
4125
#define MG_EV_HTTP_PART_DATA 123         /* struct mg_http_multipart_part */
4126
#define MG_EV_HTTP_PART_END 124          /* struct mg_http_multipart_part */
4127
/* struct mg_http_multipart_part */
4128
#define MG_EV_HTTP_MULTIPART_REQUEST_END 125
4129
#endif
4130

    
4131
/*
4132
 * Attaches a built-in HTTP event handler to the given connection.
4133
 * The user-defined event handler will receive following extra events:
4134
 *
4135
 * - MG_EV_HTTP_REQUEST: HTTP request has arrived. Parsed HTTP request
4136
 *  is passed as
4137
 *   `struct http_message` through the handler's `void *ev_data` pointer.
4138
 * - MG_EV_HTTP_REPLY: The HTTP reply has arrived. The parsed HTTP reply is
4139
 *   passed as `struct http_message` through the handler's `void *ev_data`
4140
 *   pointer.
4141
 * - MG_EV_HTTP_CHUNK: The HTTP chunked-encoding chunk has arrived.
4142
 *   The parsed HTTP reply is passed as `struct http_message` through the
4143
 *   handler's `void *ev_data` pointer. `http_message::body` would contain
4144
 *   incomplete, reassembled HTTP body.
4145
 *   It will grow with every new chunk that arrives, and it can
4146
 *   potentially consume a lot of memory. An event handler may process
4147
 *   the body as chunks are coming, and signal Mongoose to delete processed
4148
 *   body by setting `MG_F_DELETE_CHUNK` in `mg_connection::flags`. When
4149
 *   the last zero chunk is received,
4150
 *   Mongoose sends `MG_EV_HTTP_REPLY` event with
4151
 *   full reassembled body (if handler did not signal to delete chunks) or
4152
 *   with empty body (if handler did signal to delete chunks).
4153
 * - MG_EV_WEBSOCKET_HANDSHAKE_REQUEST: server has received the WebSocket
4154
 *   handshake request. `ev_data` contains parsed HTTP request.
4155
 * - MG_EV_WEBSOCKET_HANDSHAKE_DONE: server has completed the WebSocket
4156
 *   handshake. `ev_data` is `NULL`.
4157
 * - MG_EV_WEBSOCKET_FRAME: new WebSocket frame has arrived. `ev_data` is
4158
 *   `struct websocket_message *`
4159
 *
4160
 * When compiled with MG_ENABLE_HTTP_STREAMING_MULTIPART, Mongoose parses
4161
 * multipart requests and splits them into separate events:
4162
 * - MG_EV_HTTP_MULTIPART_REQUEST: Start of the request.
4163
 *   This event is sent before body is parsed. After this, the user
4164
 *   should expect a sequence of PART_BEGIN/DATA/END requests.
4165
 *   This is also the last time when headers and other request fields are
4166
 *   accessible.
4167
 * - MG_EV_HTTP_PART_BEGIN: Start of a part of a multipart message.
4168
 *   Argument: mg_http_multipart_part with var_name and file_name set
4169
 *   (if present). No data is passed in this message.
4170
 * - MG_EV_HTTP_PART_DATA: new portion of data from the multipart message.
4171
 *   Argument: mg_http_multipart_part. var_name and file_name are preserved,
4172
 *   data is available in mg_http_multipart_part.data.
4173
 * - MG_EV_HTTP_PART_END: End of the current part. var_name, file_name are
4174
 *   the same, no data in the message. If status is 0, then the part is
4175
 *   properly terminated with a boundary, status < 0 means that connection
4176
 *   was terminated.
4177
 * - MG_EV_HTTP_MULTIPART_REQUEST_END: End of the multipart request.
4178
 *   Argument: mg_http_multipart_part, var_name and file_name are NULL,
4179
 *   status = 0 means request was properly closed, < 0 means connection
4180
 *   was terminated (note: in this case both PART_END and REQUEST_END are
4181
 *   delivered).
4182
 */
4183
void mg_set_protocol_http_websocket(struct mg_connection *nc);
4184

    
4185
#if MG_ENABLE_HTTP_WEBSOCKET
4186
/*
4187
 * Send websocket handshake to the server.
4188
 *
4189
 * `nc` must be a valid connection, connected to a server. `uri` is an URI
4190
 * to fetch, extra_headers` is extra HTTP headers to send or `NULL`.
4191
 *
4192
 * This function is intended to be used by websocket client.
4193
 *
4194
 * Note that the Host header is mandatory in HTTP/1.1 and must be
4195
 * included in `extra_headers`. `mg_send_websocket_handshake2` offers
4196
 * a better API for that.
4197
 *
4198
 * Deprecated in favour of `mg_send_websocket_handshake2`
4199
 */
4200
void mg_send_websocket_handshake(struct mg_connection *nc, const char *uri,
4201
                                 const char *extra_headers);
4202

    
4203
/*
4204
 * Send websocket handshake to the server.
4205
 *
4206
 * `nc` must be a valid connection, connected to a server. `uri` is an URI
4207
 * to fetch, `host` goes into the `Host` header, `protocol` goes into the
4208
 * `Sec-WebSocket-Proto` header (NULL to omit), extra_headers` is extra HTTP
4209
 * headers to send or `NULL`.
4210
 *
4211
 * This function is intended to be used by websocket client.
4212
 */
4213
void mg_send_websocket_handshake2(struct mg_connection *nc, const char *path,
4214
                                  const char *host, const char *protocol,
4215
                                  const char *extra_headers);
4216

    
4217
/* Like mg_send_websocket_handshake2 but also passes basic auth header */
4218
void mg_send_websocket_handshake3(struct mg_connection *nc, const char *path,
4219
                                  const char *host, const char *protocol,
4220
                                  const char *extra_headers, const char *user,
4221
                                  const char *pass);
4222
/*
4223
 * Helper function that creates an outbound WebSocket connection.
4224
 *
4225
 * `url` is a URL to connect to. It must be properly URL-encoded, e.g. have
4226
 * no spaces, etc. By default, `mg_connect_ws()` sends Connection and
4227
 * Host headers. `extra_headers` is an extra HTTP header to send, e.g.
4228
 * `"User-Agent: my-app\r\n"`.
4229
 * If `protocol` is not NULL, then a `Sec-WebSocket-Protocol` header is sent.
4230
 *
4231
 * Examples:
4232
 *
4233
 * ```c
4234
 *   nc1 = mg_connect_ws(mgr, ev_handler_1, "ws://echo.websocket.org", NULL,
4235
 *                       NULL);
4236
 *   nc2 = mg_connect_ws(mgr, ev_handler_1, "wss://echo.websocket.org", NULL,
4237
 *                       NULL);
4238
 *   nc3 = mg_connect_ws(mgr, ev_handler_1, "ws://api.cesanta.com",
4239
 *                       "clubby.cesanta.com", NULL);
4240
 * ```
4241
 */
4242
struct mg_connection *mg_connect_ws(struct mg_mgr *mgr,
4243
                                    mg_event_handler_t event_handler,
4244
                                    const char *url, const char *protocol,
4245
                                    const char *extra_headers);
4246

    
4247
/*
4248
 * Helper function that creates an outbound WebSocket connection
4249
 *
4250
 * Mostly identical to `mg_connect_ws`, but allows to provide extra parameters
4251
 * (for example, SSL parameters)
4252
 */
4253
struct mg_connection *mg_connect_ws_opt(struct mg_mgr *mgr,
4254
                                        mg_event_handler_t ev_handler,
4255
                                        struct mg_connect_opts opts,
4256
                                        const char *url, const char *protocol,
4257
                                        const char *extra_headers);
4258

    
4259
/*
4260
 * Send WebSocket frame to the remote end.
4261
 *
4262
 * `op_and_flags` specifies the frame's type. It's one of:
4263
 *
4264
 * - WEBSOCKET_OP_CONTINUE
4265
 * - WEBSOCKET_OP_TEXT
4266
 * - WEBSOCKET_OP_BINARY
4267
 * - WEBSOCKET_OP_CLOSE
4268
 * - WEBSOCKET_OP_PING
4269
 * - WEBSOCKET_OP_PONG
4270
 *
4271
 * Orred with one of the flags:
4272
 *
4273
 * - WEBSOCKET_DONT_FIN: Don't set the FIN flag on the frame to be sent.
4274
 *
4275
 * `data` and `data_len` contain frame data.
4276
 */
4277
void mg_send_websocket_frame(struct mg_connection *nc, int op_and_flags,
4278
                             const void *data, size_t data_len);
4279

    
4280
/*
4281
 * Sends multiple websocket frames.
4282
 *
4283
 * Like `mg_send_websocket_frame()`, but composes a frame from multiple buffers.
4284
 */
4285
void mg_send_websocket_framev(struct mg_connection *nc, int op_and_flags,
4286
                              const struct mg_str *strings, int num_strings);
4287

    
4288
/*
4289
 * Sends WebSocket frame to the remote end.
4290
 *
4291
 * Like `mg_send_websocket_frame()`, but allows to create formatted messages
4292
 * with `printf()`-like semantics.
4293
 */
4294
void mg_printf_websocket_frame(struct mg_connection *nc, int op_and_flags,
4295
                               const char *fmt, ...);
4296

    
4297
/* Websocket opcodes, from http://tools.ietf.org/html/rfc6455 */
4298
#define WEBSOCKET_OP_CONTINUE 0
4299
#define WEBSOCKET_OP_TEXT 1
4300
#define WEBSOCKET_OP_BINARY 2
4301
#define WEBSOCKET_OP_CLOSE 8
4302
#define WEBSOCKET_OP_PING 9
4303
#define WEBSOCKET_OP_PONG 10
4304

    
4305
/*
4306
 * If set causes the FIN flag to not be set on outbound
4307
 * frames. This enables sending multiple fragments of a single
4308
 * logical message.
4309
 *
4310
 * The WebSocket protocol mandates that if the FIN flag of a data
4311
 * frame is not set, the next frame must be a WEBSOCKET_OP_CONTINUE.
4312
 * The last frame must have the FIN bit set.
4313
 *
4314
 * Note that mongoose will automatically defragment incoming messages,
4315
 * so this flag is used only on outbound messages.
4316
 */
4317
#define WEBSOCKET_DONT_FIN 0x100
4318

    
4319
#endif /* MG_ENABLE_HTTP_WEBSOCKET */
4320

    
4321
/*
4322
 * Decodes a URL-encoded string.
4323
 *
4324
 * Source string is specified by (`src`, `src_len`), and destination is
4325
 * (`dst`, `dst_len`). If `is_form_url_encoded` is non-zero, then
4326
 * `+` character is decoded as a blank space character. This function
4327
 * guarantees to NUL-terminate the destination. If destination is too small,
4328
 * then the source string is partially decoded and `-1` is returned. Otherwise,
4329
 * a length of the decoded string is returned, not counting final NUL.
4330
 */
4331
int mg_url_decode(const char *src, int src_len, char *dst, int dst_len,
4332
                  int is_form_url_encoded);
4333

    
4334
#ifdef __cplusplus
4335
}
4336
#endif /* __cplusplus */
4337

    
4338
#endif /* MG_ENABLE_HTTP */
4339

    
4340
#endif /* CS_MONGOOSE_SRC_HTTP_H_ */
4341
#ifdef MG_MODULE_LINES
4342
#line 1 "mongoose/src/http_server.h"
4343
#endif
4344
/*
4345
 * === Server API reference
4346
 */
4347

    
4348
#ifndef CS_MONGOOSE_SRC_HTTP_SERVER_H_
4349
#define CS_MONGOOSE_SRC_HTTP_SERVER_H_
4350

    
4351
#if MG_ENABLE_HTTP
4352

    
4353
#ifdef __cplusplus
4354
extern "C" {
4355
#endif /* __cplusplus */
4356

    
4357
/*
4358
 * Parses a HTTP message.
4359
 *
4360
 * `is_req` should be set to 1 if parsing a request, 0 if reply.
4361
 *
4362
 * Returns the number of bytes parsed. If HTTP message is
4363
 * incomplete `0` is returned. On parse error, a negative number is returned.
4364
 */
4365
int mg_parse_http(const char *s, int n, struct http_message *hm, int is_req);
4366

    
4367
/*
4368
 * Searches and returns the header `name` in parsed HTTP message `hm`.
4369
 * If header is not found, NULL is returned. Example:
4370
 *
4371
 *     struct mg_str *host_hdr = mg_get_http_header(hm, "Host");
4372
 */
4373
struct mg_str *mg_get_http_header(struct http_message *hm, const char *name);
4374

    
4375
/*
4376
 * Parses the HTTP header `hdr`. Finds variable `var_name` and stores its value
4377
 * in the buffer `buf`, `buf_size`. Returns 0 if variable not found, non-zero
4378
 * otherwise.
4379
 *
4380
 * This function is supposed to parse cookies, authentication headers, etc.
4381
 * Example (error handling omitted):
4382
 *
4383
 *     char user[20];
4384
 *     struct mg_str *hdr = mg_get_http_header(hm, "Authorization");
4385
 *     mg_http_parse_header(hdr, "username", user, sizeof(user));
4386
 *
4387
 * Returns the length of the variable's value. If buffer is not large enough,
4388
 * or variable not found, 0 is returned.
4389
 */
4390
int mg_http_parse_header(struct mg_str *hdr, const char *var_name, char *buf,
4391
                         size_t buf_size);
4392

    
4393
/*
4394
 * Gets and parses the Authorization: Basic header
4395
 * Returns -1 if no Authorization header is found, or if
4396
 * mg_parse_http_basic_auth
4397
 * fails parsing the resulting header.
4398
 */
4399
int mg_get_http_basic_auth(struct http_message *hm, char *user, size_t user_len,
4400
                           char *pass, size_t pass_len);
4401

    
4402
/*
4403
 * Parses the Authorization: Basic header
4404
 * Returns -1 iif the authorization type is not "Basic" or any other error such
4405
 * as incorrectly encoded base64 user password pair.
4406
 */
4407
int mg_parse_http_basic_auth(struct mg_str *hdr, char *user, size_t user_len,
4408
                             char *pass, size_t pass_len);
4409

    
4410
/*
4411
 * Parses the buffer `buf`, `buf_len` that contains multipart form data chunks.
4412
 * Stores the chunk name in a `var_name`, `var_name_len` buffer.
4413
 * If a chunk is an uploaded file, then `file_name`, `file_name_len` is
4414
 * filled with an uploaded file name. `chunk`, `chunk_len`
4415
 * points to the chunk data.
4416
 *
4417
 * Return: number of bytes to skip to the next chunk or 0 if there are
4418
 *         no more chunks.
4419
 *
4420
 * Usage example:
4421
 *
4422
 * ```c
4423
 *    static void ev_handler(struct mg_connection *nc, int ev, void *ev_data) {
4424
 *      switch(ev) {
4425
 *        case MG_EV_HTTP_REQUEST: {
4426
 *          struct http_message *hm = (struct http_message *) ev_data;
4427
 *          char var_name[100], file_name[100];
4428
 *          const char *chunk;
4429
 *          size_t chunk_len, n1, n2;
4430
 *
4431
 *          n1 = n2 = 0;
4432
 *          while ((n2 = mg_parse_multipart(hm->body.p + n1,
4433
 *                                          hm->body.len - n1,
4434
 *                                          var_name, sizeof(var_name),
4435
 *                                          file_name, sizeof(file_name),
4436
 *                                          &chunk, &chunk_len)) > 0) {
4437
 *            printf("var: %s, file_name: %s, size: %d, chunk: [%.*s]\n",
4438
 *                   var_name, file_name, (int) chunk_len,
4439
 *                   (int) chunk_len, chunk);
4440
 *            n1 += n2;
4441
 *          }
4442
 *        }
4443
 *        break;
4444
 * ```
4445
 */
4446
size_t mg_parse_multipart(const char *buf, size_t buf_len, char *var_name,
4447
                          size_t var_name_len, char *file_name,
4448
                          size_t file_name_len, const char **chunk,
4449
                          size_t *chunk_len);
4450

    
4451
/*
4452
 * Fetches a HTTP form variable.
4453
 *
4454
 * Fetches a variable `name` from a `buf` into a buffer specified by `dst`,
4455
 * `dst_len`. The destination is always zero-terminated. Returns the length of
4456
 * a fetched variable. If not found, 0 is returned. `buf` must be valid
4457
 * url-encoded buffer. If destination is too small, `-1` is returned.
4458
 */
4459
int mg_get_http_var(const struct mg_str *buf, const char *name, char *dst,
4460
                    size_t dst_len);
4461

    
4462
#if MG_ENABLE_FILESYSTEM
4463
/*
4464
 * This structure defines how `mg_serve_http()` works.
4465
 * Best practice is to set only required settings, and leave the rest as NULL.
4466
 */
4467
struct mg_serve_http_opts {
4468
  /* Path to web root directory */
4469
  const char *document_root;
4470

    
4471
  /* List of index files. Default is "" */
4472
  const char *index_files;
4473

    
4474
  /*
4475
   * Leave as NULL to disable authentication.
4476
   * To enable directory protection with authentication, set this to ".htpasswd"
4477
   * Then, creating ".htpasswd" file in any directory automatically protects
4478
   * it with digest authentication.
4479
   * Use `mongoose` web server binary, or `htdigest` Apache utility to
4480
   * create/manipulate passwords file.
4481
   * Make sure `auth_domain` is set to a valid domain name.
4482
   */
4483
  const char *per_directory_auth_file;
4484

    
4485
  /* Authorization domain (domain name of this web server) */
4486
  const char *auth_domain;
4487

    
4488
  /*
4489
   * Leave as NULL to disable authentication.
4490
   * Normally, only selected directories in the document root are protected.
4491
   * If absolutely every access to the web server needs to be authenticated,
4492
   * regardless of the URI, set this option to the path to the passwords file.
4493
   * Format of that file is the same as ".htpasswd" file. Make sure that file
4494
   * is located outside document root to prevent people fetching it.
4495
   */
4496
  const char *global_auth_file;
4497

    
4498
  /* Set to "no" to disable directory listing. Enabled by default. */
4499
  const char *enable_directory_listing;
4500

    
4501
  /*
4502
   * SSI files pattern. If not set, "**.shtml$|**.shtm$" is used.
4503
   *
4504
   * All files that match ssi_pattern are treated as SSI.
4505
   *
4506
   * Server Side Includes (SSI) is a simple interpreted server-side scripting
4507
   * language which is most commonly used to include the contents of a file
4508
   * into a web page. It can be useful when it is desirable to include a common
4509
   * piece of code throughout a website, for example, headers and footers.
4510
   *
4511
   * In order for a webpage to recognize an SSI-enabled HTML file, the
4512
   * filename should end with a special extension, by default the extension
4513
   * should be either .shtml or .shtm
4514
   *
4515
   * Unknown SSI directives are silently ignored by Mongoose. Currently,
4516
   * the following SSI directives are supported:
4517
   *    &lt;!--#include FILE_TO_INCLUDE --&gt;
4518
   *    &lt;!--#exec "COMMAND_TO_EXECUTE" --&gt;
4519
   *    &lt;!--#call COMMAND --&gt;
4520
   *
4521
   * Note that &lt;!--#include ...> directive supports three path
4522
   *specifications:
4523
   *
4524
   * &lt;!--#include virtual="path" --&gt;  Path is relative to web server root
4525
   * &lt;!--#include abspath="path" --&gt;  Path is absolute or relative to the
4526
   *                                  web server working dir
4527
   * &lt;!--#include file="path" --&gt;,    Path is relative to current document
4528
   * &lt;!--#include "path" --&gt;
4529
   *
4530
   * The include directive may be used to include the contents of a file or
4531
   * the result of running a CGI script.
4532
   *
4533
   * The exec directive is used to execute
4534
   * a command on a server, and show command's output. Example:
4535
   *
4536
   * &lt;!--#exec "ls -l" --&gt;
4537
   *
4538
   * The call directive is a way to invoke a C handler from the HTML page.
4539
   * On each occurence of &lt;!--#call COMMAND OPTIONAL_PARAMS> directive,
4540
   * Mongoose calls a registered event handler with MG_EV_SSI_CALL event,
4541
   * and event parameter will point to the COMMAND OPTIONAL_PARAMS string.
4542
   * An event handler can output any text, for example by calling
4543
   * `mg_printf()`. This is a flexible way of generating a web page on
4544
   * server side by calling a C event handler. Example:
4545
   *
4546
   * &lt;!--#call foo --&gt; ... &lt;!--#call bar --&gt;
4547
   *
4548
   * In the event handler:
4549
   *    case MG_EV_SSI_CALL: {
4550
   *      const char *param = (const char *) ev_data;
4551
   *      if (strcmp(param, "foo") == 0) {
4552
   *        mg_printf(c, "hello from foo");
4553
   *      } else if (strcmp(param, "bar") == 0) {
4554
   *        mg_printf(c, "hello from bar");
4555
   *      }
4556
   *      break;
4557
   *    }
4558
   */
4559
  const char *ssi_pattern;
4560

    
4561
  /* IP ACL. By default, NULL, meaning all IPs are allowed to connect */
4562
  const char *ip_acl;
4563

    
4564
#if MG_ENABLE_HTTP_URL_REWRITES
4565
  /* URL rewrites.
4566
   *
4567
   * Comma-separated list of `uri_pattern=url_file_or_directory_path` rewrites.
4568
   * When HTTP request is received, Mongoose constructs a file name from the
4569
   * requested URI by combining `document_root` and the URI. However, if the
4570
   * rewrite option is used and `uri_pattern` matches requested URI, then
4571
   * `document_root` is ignored. Instead, `url_file_or_directory_path` is used,
4572
   * which should be a full path name or a path relative to the web server's
4573
   * current working directory. It can also be an URI (http:// or https://)
4574
   * in which case mongoose will behave as a reverse proxy for that destination.
4575
   *
4576
   * Note that `uri_pattern`, as all Mongoose patterns, is a prefix pattern.
4577
   *
4578
   * If uri_pattern starts with `@` symbol, then Mongoose compares it with the
4579
   * HOST header of the request. If they are equal, Mongoose sets document root
4580
   * to `file_or_directory_path`, implementing virtual hosts support.
4581
   * Example: `@foo.com=/document/root/for/foo.com`
4582
   *
4583
   * If `uri_pattern` starts with `%` symbol, then Mongoose compares it with
4584
   * the listening port. If they match, then Mongoose issues a 301 redirect.
4585
   * For example, to redirect all HTTP requests to the
4586
   * HTTPS port, do `%80=https://my.site.com`. Note that the request URI is
4587
   * automatically appended to the redirect location.
4588
   */
4589
  const char *url_rewrites;
4590
#endif
4591

    
4592
  /* DAV document root. If NULL, DAV requests are going to fail. */
4593
  const char *dav_document_root;
4594

    
4595
  /*
4596
   * DAV passwords file. If NULL, DAV requests are going to fail.
4597
   * If passwords file is set to "-", then DAV auth is disabled.
4598
   */
4599
  const char *dav_auth_file;
4600

    
4601
  /* Glob pattern for the files to hide. */
4602
  const char *hidden_file_pattern;
4603

    
4604
  /* Set to non-NULL to enable CGI, e.g. **.cgi$|**.php$" */
4605
  const char *cgi_file_pattern;
4606

    
4607
  /* If not NULL, ignore CGI script hashbang and use this interpreter */
4608
  const char *cgi_interpreter;
4609

    
4610
  /*
4611
   * Comma-separated list of Content-Type overrides for path suffixes, e.g.
4612
   * ".txt=text/plain; charset=utf-8,.c=text/plain"
4613
   */
4614
  const char *custom_mime_types;
4615

    
4616
  /*
4617
   * Extra HTTP headers to add to each server response.
4618
   * Example: to enable CORS, set this to "Access-Control-Allow-Origin: *".
4619
   */
4620
  const char *extra_headers;
4621
};
4622

    
4623
/*
4624
 * Serves given HTTP request according to the `options`.
4625
 *
4626
 * Example code snippet:
4627
 *
4628
 * ```c
4629
 * static void ev_handler(struct mg_connection *nc, int ev, void *ev_data) {
4630
 *   struct http_message *hm = (struct http_message *) ev_data;
4631
 *   struct mg_serve_http_opts opts = { .document_root = "/var/www" };  // C99
4632
 *
4633
 *   switch (ev) {
4634
 *     case MG_EV_HTTP_REQUEST:
4635
 *       mg_serve_http(nc, hm, opts);
4636
 *       break;
4637
 *     default:
4638
 *       break;
4639
 *   }
4640
 * }
4641
 * ```
4642
 */
4643
void mg_serve_http(struct mg_connection *nc, struct http_message *hm,
4644
                   struct mg_serve_http_opts opts);
4645

    
4646
/*
4647
 * Serves a specific file with a given MIME type and optional extra headers.
4648
 *
4649
 * Example code snippet:
4650
 *
4651
 * ```c
4652
 * static void ev_handler(struct mg_connection *nc, int ev, void *ev_data) {
4653
 *   switch (ev) {
4654
 *     case MG_EV_HTTP_REQUEST: {
4655
 *       struct http_message *hm = (struct http_message *) ev_data;
4656
 *       mg_http_serve_file(nc, hm, "file.txt",
4657
 *                          mg_mk_str("text/plain"), mg_mk_str(""));
4658
 *       break;
4659
 *     }
4660
 *     ...
4661
 *   }
4662
 * }
4663
 * ```
4664
 */
4665
void mg_http_serve_file(struct mg_connection *nc, struct http_message *hm,
4666
                        const char *path, const struct mg_str mime_type,
4667
                        const struct mg_str extra_headers);
4668

    
4669
#if MG_ENABLE_HTTP_STREAMING_MULTIPART
4670

    
4671
/* Callback prototype for `mg_file_upload_handler()`. */
4672
typedef struct mg_str (*mg_fu_fname_fn)(struct mg_connection *nc,
4673
                                        struct mg_str fname);
4674

    
4675
/*
4676
 * File upload handler.
4677
 * This handler can be used to implement file uploads with minimum code.
4678
 * This handler will process MG_EV_HTTP_PART_* events and store file data into
4679
 * a local file.
4680
 * `local_name_fn` will be invoked with whatever name was provided by the client
4681
 * and will expect the name of the local file to open. A return value of NULL
4682
 * will abort file upload (client will get a "403 Forbidden" response). If
4683
 * non-null, the returned string must be heap-allocated and will be freed by
4684
 * the caller.
4685
 * Exception: it is ok to return the same string verbatim.
4686
 *
4687
 * Example:
4688
 *
4689
 * ```c
4690
 * struct mg_str upload_fname(struct mg_connection *nc, struct mg_str fname) {
4691
 *   // Just return the same filename. Do not actually do this except in test!
4692
 *   // fname is user-controlled and needs to be sanitized.
4693
 *   return fname;
4694
 * }
4695
 * void ev_handler(struct mg_connection *nc, int ev, void *ev_data) {
4696
 *   switch (ev) {
4697
 *     ...
4698
 *     case MG_EV_HTTP_PART_BEGIN:
4699
 *     case MG_EV_HTTP_PART_DATA:
4700
 *     case MG_EV_HTTP_PART_END:
4701
 *       mg_file_upload_handler(nc, ev, ev_data, upload_fname);
4702
 *       break;
4703
 *   }
4704
 * }
4705
 * ```
4706
 */
4707
void mg_file_upload_handler(struct mg_connection *nc, int ev, void *ev_data,
4708
                            mg_fu_fname_fn local_name_fn);
4709
#endif /* MG_ENABLE_HTTP_STREAMING_MULTIPART */
4710
#endif /* MG_ENABLE_FILESYSTEM */
4711

    
4712
/*
4713
 * Registers a callback for a specified http endpoint
4714
 * Note: if callback is registered it is called instead of the
4715
 * callback provided in mg_bind
4716
 *
4717
 * Example code snippet:
4718
 *
4719
 * ```c
4720
 * static void handle_hello1(struct mg_connection *nc, int ev, void *ev_data) {
4721
 *   (void) ev; (void) ev_data;
4722
 *   mg_printf(nc, "HTTP/1.0 200 OK\r\n\r\n[I am Hello1]");
4723
 *  nc->flags |= MG_F_SEND_AND_CLOSE;
4724
 * }
4725
 *
4726
 * static void handle_hello1(struct mg_connection *nc, int ev, void *ev_data) {
4727
 *  (void) ev; (void) ev_data;
4728
 *   mg_printf(nc, "HTTP/1.0 200 OK\r\n\r\n[I am Hello2]");
4729
 *  nc->flags |= MG_F_SEND_AND_CLOSE;
4730
 * }
4731
 *
4732
 * void init() {
4733
 *   nc = mg_bind(&mgr, local_addr, cb1);
4734
 *   mg_register_http_endpoint(nc, "/hello1", handle_hello1);
4735
 *   mg_register_http_endpoint(nc, "/hello1/hello2", handle_hello2);
4736
 * }
4737
 * ```
4738
 */
4739
void mg_register_http_endpoint(struct mg_connection *nc, const char *uri_path,
4740
                               mg_event_handler_t handler);
4741

    
4742
/*
4743
 * Authenticates a HTTP request against an opened password file.
4744
 * Returns 1 if authenticated, 0 otherwise.
4745
 */
4746
int mg_http_check_digest_auth(struct http_message *hm, const char *auth_domain,
4747
                              FILE *fp);
4748

    
4749
/*
4750
 * Sends buffer `buf` of size `len` to the client using chunked HTTP encoding.
4751
 * This function sends the buffer size as hex number + newline first, then
4752
 * the buffer itself, then the newline. For example,
4753
 * `mg_send_http_chunk(nc, "foo", 3)` whill append the `3\r\nfoo\r\n` string
4754
 * to the `nc->send_mbuf` output IO buffer.
4755
 *
4756
 * NOTE: The HTTP header "Transfer-Encoding: chunked" should be sent prior to
4757
 * using this function.
4758
 *
4759
 * NOTE: do not forget to send an empty chunk at the end of the response,
4760
 * to tell the client that everything was sent. Example:
4761
 *
4762
 * ```
4763
 *   mg_printf_http_chunk(nc, "%s", "my response!");
4764
 *   mg_send_http_chunk(nc, "", 0); // Tell the client we're finished
4765
 * ```
4766
 */
4767
void mg_send_http_chunk(struct mg_connection *nc, const char *buf, size_t len);
4768

    
4769
/*
4770
 * Sends a printf-formatted HTTP chunk.
4771
 * Functionality is similar to `mg_send_http_chunk()`.
4772
 */
4773
void mg_printf_http_chunk(struct mg_connection *nc, const char *fmt, ...);
4774

    
4775
/*
4776
 * Sends the response status line.
4777
 * If `extra_headers` is not NULL, then `extra_headers` are also sent
4778
 * after the reponse line. `extra_headers` must NOT end end with new line.
4779
 * Example:
4780
 *
4781
 *      mg_send_response_line(nc, 200, "Access-Control-Allow-Origin: *");
4782
 *
4783
 * Will result in:
4784
 *
4785
 *      HTTP/1.1 200 OK\r\n
4786
 *      Access-Control-Allow-Origin: *\r\n
4787
 */
4788
void mg_send_response_line(struct mg_connection *nc, int status_code,
4789