Statistics
| Branch: | Tag: | Revision:

mongoose / mongoose.h @ b8c37404

History | View | Annotate | Download (168 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
#endif /* CS_PLATFORM == CS_P_STM32 */
1551
#endif /* CS_COMMON_PLATFORMS_PLATFORM_STM32_H_ */
1552
#ifdef MG_MODULE_LINES
1553
#line 1 "common/platforms/lwip/mg_lwip.h"
1554
#endif
1555
/*
1556
 * Copyright (c) 2014-2016 Cesanta Software Limited
1557
 * All rights reserved
1558
 */
1559

    
1560
#ifndef CS_COMMON_PLATFORMS_LWIP_MG_LWIP_H_
1561
#define CS_COMMON_PLATFORMS_LWIP_MG_LWIP_H_
1562

    
1563
#ifndef MG_LWIP
1564
#define MG_LWIP 0
1565
#endif
1566

    
1567
#if MG_LWIP
1568

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

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

    
1589
#ifndef LWIP_PROVIDE_ERRNO
1590
#include <errno.h>
1591
#endif
1592

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

    
1604
#define INVALID_SOCKET (-1)
1605
#define SOMAXCONN 10
1606
typedef int sock_t;
1607

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

    
1616
#endif /* MG_LWIP */
1617

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

    
1627
#ifndef CS_COMMON_CS_TIME_H_
1628
#define CS_COMMON_CS_TIME_H_
1629

    
1630
/* Amalgamated: #include "common/platform.h" */
1631

    
1632
#ifdef __cplusplus
1633
extern "C" {
1634
#endif /* __cplusplus */
1635

    
1636
/* Sub-second granularity time(). */
1637
double cs_time(void);
1638

    
1639
#ifdef __cplusplus
1640
}
1641
#endif /* __cplusplus */
1642

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

    
1652
#ifndef CS_COMMON_MG_STR_H_
1653
#define CS_COMMON_MG_STR_H_
1654

    
1655
#include <stddef.h>
1656

    
1657
/* Amalgamated: #include "common/platform.h" */
1658

    
1659
#ifdef __cplusplus
1660
extern "C" {
1661
#endif /* __cplusplus */
1662

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

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

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

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

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

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

    
1696
#ifdef __cplusplus
1697
}
1698
#endif /* __cplusplus */
1699

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

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

    
1718
#ifndef CS_COMMON_MBUF_H_
1719
#define CS_COMMON_MBUF_H_
1720

    
1721
#include <stdlib.h>
1722
/* Amalgamated: #include "common/platform.h" */
1723

    
1724
#if defined(__cplusplus)
1725
extern "C" {
1726
#endif
1727

    
1728
#ifndef MBUF_SIZE_MULTIPLIER
1729
#define MBUF_SIZE_MULTIPLIER 1.5
1730
#endif
1731

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

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

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

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

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

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

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

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

    
1778
#if defined(__cplusplus)
1779
}
1780
#endif /* __cplusplus */
1781

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

    
1791
#ifndef CS_COMMON_SHA1_H_
1792
#define CS_COMMON_SHA1_H_
1793

    
1794
#ifndef DISABLE_SHA1
1795
#define DISABLE_SHA1 0
1796
#endif
1797

    
1798
#if !DISABLE_SHA1
1799

    
1800
/* Amalgamated: #include "common/platform.h" */
1801

    
1802
#ifdef __cplusplus
1803
extern "C" {
1804
#endif /* __cplusplus */
1805

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

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

    
1822
#endif /* DISABLE_SHA1 */
1823

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

    
1833
#ifndef CS_COMMON_MD5_H_
1834
#define CS_COMMON_MD5_H_
1835

    
1836
/* Amalgamated: #include "common/platform.h" */
1837

    
1838
#ifndef DISABLE_MD5
1839
#define DISABLE_MD5 0
1840
#endif
1841

    
1842
#ifdef __cplusplus
1843
extern "C" {
1844
#endif /* __cplusplus */
1845

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

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

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

    
1866
#ifdef __cplusplus
1867
}
1868
#endif /* __cplusplus */
1869

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

    
1879
#ifndef CS_COMMON_BASE64_H_
1880
#define CS_COMMON_BASE64_H_
1881

    
1882
#ifndef DISABLE_BASE64
1883
#define DISABLE_BASE64 0
1884
#endif
1885

    
1886
#if !DISABLE_BASE64
1887

    
1888
#include <stdio.h>
1889

    
1890
#ifdef __cplusplus
1891
extern "C" {
1892
#endif
1893

    
1894
typedef void (*cs_base64_putc_t)(char, void *);
1895

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

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

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

    
1913
#ifdef __cplusplus
1914
}
1915
#endif
1916

    
1917
#endif /* DISABLE_BASE64 */
1918

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

    
1928
#ifndef CS_COMMON_STR_UTIL_H_
1929
#define CS_COMMON_STR_UTIL_H_
1930

    
1931
#include <stdarg.h>
1932
#include <stdlib.h>
1933

    
1934
/* Amalgamated: #include "common/platform.h" */
1935

    
1936
#ifndef CS_ENABLE_STRDUP
1937
#define CS_ENABLE_STRDUP 0
1938
#endif
1939

    
1940
#ifndef CS_ENABLE_TO64
1941
#define CS_ENABLE_TO64 0
1942
#endif
1943

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

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

    
1961
#ifdef __cplusplus
1962
extern "C" {
1963
#endif
1964

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

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

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

    
1987
#if CS_ENABLE_STRDUP
1988
char *strdup(const char *src);
1989
#endif
1990

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

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

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

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

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

    
2029
#ifdef __cplusplus
2030
}
2031
#endif
2032

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

    
2070
#ifndef _SYS_QUEUE_H_
2071
#define        _SYS_QUEUE_H_
2072

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

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

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

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

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

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

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

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

    
2205
#define        SLIST_HEAD_INITIALIZER(head)                                        \
2206
        { NULL }
2207

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

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

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

    
2223
#define        SLIST_FIRST(head)        ((head)->slh_first)
2224

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

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

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

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

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

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

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

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

    
2264
#define        SLIST_NEXT(elm, field)        ((elm)->field.sle_next)
2265

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

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

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

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

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

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

    
2310
#define        STAILQ_HEAD_INITIALIZER(head)                                        \
2311
        { NULL, &(head).stqh_first }
2312

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

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

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

    
2334
#define        STAILQ_EMPTY(head)        ((head)->stqh_first == NULL)
2335

    
2336
#define        STAILQ_FIRST(head)        ((head)->stqh_first)
2337

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

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

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

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

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

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

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

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

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

    
2386
#define        STAILQ_NEXT(elm, field)        ((elm)->field.stqe_next)
2387

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

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

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

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

    
2427

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

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

    
2441
#define        LIST_HEAD_INITIALIZER(head)                                        \
2442
        { NULL }
2443

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

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

    
2456
/*
2457
 * List functions.
2458
 */
2459

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

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

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

    
2485
#define        LIST_EMPTY(head)        ((head)->lh_first == NULL)
2486

    
2487
#define        LIST_FIRST(head)        ((head)->lh_first)
2488

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

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

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

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

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

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

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

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

    
2538
#define        LIST_NEXT(elm, field)        ((elm)->field.le_next)
2539

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2647
#define        TAILQ_EMPTY(head)        ((head)->tqh_first == NULL)
2648

    
2649
#define        TAILQ_FIRST(head)        ((head)->tqh_first)
2650

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2745
#define        TAILQ_LAST(head, headname)                                        \
2746
        (*(((struct headname *)((head)->tqh_last))->tqh_last))
2747

    
2748
#define        TAILQ_NEXT(elm, field) ((elm)->field.tqe_next)
2749

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

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

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

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

    
2797
#ifndef CS_MONGOOSE_SRC_FEATURES_H_
2798
#define CS_MONGOOSE_SRC_FEATURES_H_
2799

    
2800
#ifndef MG_DISABLE_HTTP_DIGEST_AUTH
2801
#define MG_DISABLE_HTTP_DIGEST_AUTH 0
2802
#endif
2803

    
2804
#ifndef MG_DISABLE_HTTP_KEEP_ALIVE
2805
#define MG_DISABLE_HTTP_KEEP_ALIVE 0
2806
#endif
2807

    
2808
#ifndef MG_DISABLE_PFS
2809
#define MG_DISABLE_PFS 0
2810
#endif
2811

    
2812
#ifndef MG_DISABLE_WS_RANDOM_MASK
2813
#define MG_DISABLE_WS_RANDOM_MASK 0
2814
#endif
2815

    
2816
#ifndef MG_ENABLE_ASYNC_RESOLVER
2817
#define MG_ENABLE_ASYNC_RESOLVER 1
2818
#endif
2819

    
2820
#ifndef MG_ENABLE_BROADCAST
2821
#define MG_ENABLE_BROADCAST 0
2822
#endif
2823

    
2824
#ifndef MG_ENABLE_COAP
2825
#define MG_ENABLE_COAP 0
2826
#endif
2827

    
2828
#ifndef MG_ENABLE_DEBUG
2829
#define MG_ENABLE_DEBUG 0
2830
#endif
2831

    
2832
#ifndef MG_ENABLE_DIRECTORY_LISTING
2833
#define MG_ENABLE_DIRECTORY_LISTING 0
2834
#endif
2835

    
2836
#ifndef MG_ENABLE_DNS
2837
#define MG_ENABLE_DNS 1
2838
#endif
2839

    
2840
#ifndef MG_ENABLE_DNS_SERVER
2841
#define MG_ENABLE_DNS_SERVER 0
2842
#endif
2843

    
2844
#ifndef MG_ENABLE_FAKE_DAVLOCK
2845
#define MG_ENABLE_FAKE_DAVLOCK 0
2846
#endif
2847

    
2848
#ifndef MG_ENABLE_FILESYSTEM
2849
#define MG_ENABLE_FILESYSTEM 0
2850
#endif
2851

    
2852
#ifndef MG_ENABLE_GETADDRINFO
2853
#define MG_ENABLE_GETADDRINFO 0
2854
#endif
2855

    
2856
#ifndef MG_ENABLE_HEXDUMP
2857
#define MG_ENABLE_HEXDUMP CS_ENABLE_STDIO
2858
#endif
2859

    
2860
#ifndef MG_ENABLE_HTTP
2861
#define MG_ENABLE_HTTP 1
2862
#endif
2863

    
2864
#ifndef MG_ENABLE_HTTP_CGI
2865
#define MG_ENABLE_HTTP_CGI 0
2866
#endif
2867

    
2868
#ifndef MG_ENABLE_HTTP_SSI
2869
#define MG_ENABLE_HTTP_SSI MG_ENABLE_FILESYSTEM
2870
#endif
2871

    
2872
#ifndef MG_ENABLE_HTTP_SSI_EXEC
2873
#define MG_ENABLE_HTTP_SSI_EXEC 0
2874
#endif
2875

    
2876
#ifndef MG_ENABLE_HTTP_STREAMING_MULTIPART
2877
#define MG_ENABLE_HTTP_STREAMING_MULTIPART 0
2878
#endif
2879

    
2880
#ifndef MG_ENABLE_HTTP_WEBDAV
2881
#define MG_ENABLE_HTTP_WEBDAV 0
2882
#endif
2883

    
2884
#ifndef MG_ENABLE_HTTP_WEBSOCKET
2885
#define MG_ENABLE_HTTP_WEBSOCKET MG_ENABLE_HTTP
2886
#endif
2887

    
2888
#ifndef MG_ENABLE_IPV6
2889
#define MG_ENABLE_IPV6 0
2890
#endif
2891

    
2892
#ifndef MG_ENABLE_JAVASCRIPT
2893
#define MG_ENABLE_JAVASCRIPT 0
2894
#endif
2895

    
2896
#ifndef MG_ENABLE_MQTT
2897
#define MG_ENABLE_MQTT 1
2898
#endif
2899

    
2900
#ifndef MG_ENABLE_MQTT_BROKER
2901
#define MG_ENABLE_MQTT_BROKER 0
2902
#endif
2903

    
2904
#ifndef MG_ENABLE_SSL
2905
#define MG_ENABLE_SSL 0
2906
#endif
2907

    
2908
#ifndef MG_ENABLE_SYNC_RESOLVER
2909
#define MG_ENABLE_SYNC_RESOLVER 0
2910
#endif
2911

    
2912
#ifndef MG_ENABLE_STDIO
2913
#define MG_ENABLE_STDIO CS_ENABLE_STDIO
2914
#endif
2915

    
2916
#ifndef MG_NET_IF
2917
#define MG_NET_IF MG_NET_IF_SOCKET
2918
#endif
2919

    
2920
#ifndef MG_SSL_IF
2921
#define MG_SSL_IF MG_SSL_IF_OPENSSL
2922
#endif
2923

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

    
2932
#if MG_ENABLE_DEBUG && !defined(CS_ENABLE_DEBUG)
2933
#define CS_ENABLE_DEBUG 1
2934
#endif
2935

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

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

    
2947
#ifndef MG_ENABLE_TUN
2948
#define MG_ENABLE_TUN MG_ENABLE_HTTP_WEBSOCKET
2949
#endif
2950

    
2951
#ifndef MG_ENABLE_SNTP
2952
#define MG_ENABLE_SNTP 0
2953
#endif
2954

    
2955
#ifndef MG_ENABLE_EXTRA_ERRORS_DESC
2956
#define MG_ENABLE_EXTRA_ERRORS_DESC 0
2957
#endif
2958

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

    
2968
#ifndef CS_MONGOOSE_SRC_NET_IF_H_
2969
#define CS_MONGOOSE_SRC_NET_IF_H_
2970

    
2971
/* Amalgamated: #include "common/platform.h" */
2972

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

    
2983
#ifdef __cplusplus
2984
extern "C" {
2985
#endif /* __cplusplus */
2986

    
2987
#define MG_MAIN_IFACE 0
2988

    
2989
struct mg_mgr;
2990
struct mg_connection;
2991
union socket_address;
2992

    
2993
struct mg_iface_vtable;
2994

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

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

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

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

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

    
3022
  void (*recved)(struct mg_connection *nc, size_t len);
3023

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

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

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

    
3037
extern struct mg_iface_vtable *mg_ifaces[];
3038
extern int mg_num_ifaces;
3039

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

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

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

    
3080
/* void mg_if_close_conn(struct mg_connection *nc); */
3081

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

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

    
3088
#ifdef __cplusplus
3089
}
3090
#endif /* __cplusplus */
3091

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

    
3101
#ifndef CS_MONGOOSE_SRC_SSL_IF_H_
3102
#define CS_MONGOOSE_SRC_SSL_IF_H_
3103

    
3104
#if MG_ENABLE_SSL
3105

    
3106
#ifdef __cplusplus
3107
extern "C" {
3108
#endif /* __cplusplus */
3109

    
3110
struct mg_ssl_if_ctx;
3111
struct mg_connection;
3112

    
3113
void mg_ssl_if_init();
3114

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

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

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

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

    
3141
#ifdef __cplusplus
3142
}
3143
#endif /* __cplusplus */
3144

    
3145
#endif /* MG_ENABLE_SSL */
3146

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

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

    
3178
#ifndef CS_MONGOOSE_SRC_NET_H_
3179
#define CS_MONGOOSE_SRC_NET_H_
3180

    
3181
#if MG_ENABLE_JAVASCRIPT
3182
#define EXCLUDE_COMMON
3183
#include <v7.h>
3184
#endif
3185

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

    
3190
#ifndef MG_VPRINTF_BUFFER_SIZE
3191
#define MG_VPRINTF_BUFFER_SIZE 100
3192
#endif
3193

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

    
3202
#ifdef __cplusplus
3203
extern "C" {
3204
#endif /* __cplusplus */
3205

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

    
3216
struct mg_connection;
3217

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
3695
/*
3696
 * Optional parameters for mg_enable_multithreading_opt()
3697
 */
3698
struct mg_multithreading_opts {
3699
  int poll_timeout; /* Polling interval */
3700
};
3701

    
3702
/*
3703
 * Enables multi-threaded handling for the given listening connection `nc`.
3704
 * For each accepted connection, Mongoose will create a separate thread
3705
 * and run an event handler in that thread. Thus, if an event handler is doing
3706
 * a blocking call or some long computation, it will not slow down
3707
 * other connections.
3708
 */
3709
void mg_enable_multithreading(struct mg_connection *nc);
3710
void mg_enable_multithreading_opt(struct mg_connection *nc,
3711
                                  struct mg_multithreading_opts opts);
3712

    
3713
#if MG_ENABLE_JAVASCRIPT
3714
/*
3715
 * Enables server-side JavaScript scripting.
3716
 * Requires a `-DMG_ENABLE_JAVASCRIPT` compilation flag and V7 engine sources.
3717
 * V7 instance must not be destroyed during manager's lifetime.
3718
 * Returns a V7 error.
3719
 */
3720
enum v7_err mg_enable_javascript(struct mg_mgr *m, struct v7 *v7,
3721
                                 const char *init_js_file_name);
3722
#endif
3723

    
3724
/*
3725
 * Schedules an MG_EV_TIMER event to be delivered at `timestamp` time.
3726
 * `timestamp` is UNIX time (the number of seconds since Epoch). It is
3727
 * `double` instead of `time_t` to allow for sub-second precision.
3728
 * Returns the old timer value.
3729
 *
3730
 * Example: set the connect timeout to 1.5 seconds:
3731
 *
3732
 * ```
3733
 *  c = mg_connect(&mgr, "cesanta.com", ev_handler);
3734
 *  mg_set_timer(c, mg_time() + 1.5);
3735
 *  ...
3736
 *
3737
 *  void ev_handler(struct mg_connection *c, int ev, void *ev_data) {
3738
 *  switch (ev) {
3739
 *    case MG_EV_CONNECT:
3740
 *      mg_set_timer(c, 0);  // Clear connect timer
3741
 *      break;
3742
 *    case MG_EV_TIMER:
3743
 *      log("Connect timeout");
3744
 *      c->flags |= MG_F_CLOSE_IMMEDIATELY;
3745
 *      break;
3746
 * ```
3747
 */
3748
double mg_set_timer(struct mg_connection *c, double timestamp);
3749

    
3750
/*
3751
 * A sub-second precision version of time().
3752
 */
3753
double mg_time(void);
3754

    
3755
#ifdef __cplusplus
3756
}
3757
#endif /* __cplusplus */
3758

    
3759
#endif /* CS_MONGOOSE_SRC_NET_H_ */
3760
#ifdef MG_MODULE_LINES
3761
#line 1 "mongoose/src/uri.h"
3762
#endif
3763
/*
3764
 * Copyright (c) 2014 Cesanta Software Limited
3765
 * All rights reserved
3766
 */
3767

    
3768
/*
3769
 * === URI
3770
 */
3771

    
3772
#ifndef CS_MONGOOSE_SRC_URI_H_
3773
#define CS_MONGOOSE_SRC_URI_H_
3774

    
3775
/* Amalgamated: #include "mongoose/src/net.h" */
3776

    
3777
#ifdef __cplusplus
3778
extern "C" {
3779
#endif /* __cplusplus */
3780

    
3781
/*
3782
 * Parses an URI and fills string chunks with locations of the respective
3783
 * uri components within the input uri string. NULL pointers will be
3784
 * ignored.
3785
 *
3786
 * General syntax:
3787
 *
3788
 *     [scheme://[user_info@]]host[:port][/path][?query][#fragment]
3789
 *
3790
 * Example:
3791
 *
3792
 *     foo.com:80
3793
 *     tcp://foo.com:1234
3794
 *     http://foo.com:80/bar?baz=1
3795
 *     https://user:pw@foo.com:443/blah
3796
 *
3797
 * `path` will include the leading slash. `query` won't include the leading `?`.
3798
 * `host` can contain embedded colons if surrounded by square brackets in order
3799
 * to support IPv6 literal addresses.
3800
 *
3801
 *
3802
 * Returns 0 on success, -1 on error.
3803
 */
3804
int mg_parse_uri(struct mg_str uri, struct mg_str *scheme,
3805
                 struct mg_str *user_info, struct mg_str *host,
3806
                 unsigned int *port, struct mg_str *path, struct mg_str *query,
3807
                 struct mg_str *fragment);
3808

    
3809
int mg_normalize_uri_path(const struct mg_str *in, struct mg_str *out);
3810

    
3811
#ifdef __cplusplus
3812
}
3813
#endif /* __cplusplus */
3814
#endif /* CS_MONGOOSE_SRC_URI_H_ */
3815
#ifdef MG_MODULE_LINES
3816
#line 1 "mongoose/src/util.h"
3817
#endif
3818
/*
3819
 * Copyright (c) 2014 Cesanta Software Limited
3820
 * All rights reserved
3821
 */
3822

    
3823
/*
3824
 * === Utility API
3825
 */
3826

    
3827
#ifndef CS_MONGOOSE_SRC_UTIL_H_
3828
#define CS_MONGOOSE_SRC_UTIL_H_
3829

    
3830
#include <stdio.h>
3831

    
3832
/* Amalgamated: #include "mongoose/src/common.h" */
3833
/* Amalgamated: #include "mongoose/src/net_if.h" */
3834

    
3835
#ifdef __cplusplus
3836
extern "C" {
3837
#endif /* __cplusplus */
3838

    
3839
#ifndef MAX_PATH_SIZE
3840
#define MAX_PATH_SIZE 500
3841
#endif
3842

    
3843
/*
3844
 * Fetches substring from input string `s`, `end` into `v`.
3845
 * Skips initial delimiter characters. Records first non-delimiter character
3846
 * at the beginning of substring `v`. Then scans the rest of the string
3847
 * until a delimiter character or end-of-string is found.
3848
 * `delimiters` is a 0-terminated string containing delimiter characters.
3849
 * Either one of `delimiters` or `end_string` terminates the search.
3850
 * Returns an `s` pointer, advanced forward where parsing has stopped.
3851
 */
3852
const char *mg_skip(const char *s, const char *end_string,
3853
                    const char *delimiters, struct mg_str *v);
3854

    
3855
/*
3856
 * Decodes base64-encoded string `s`, `len` into the destination `dst`.
3857
 * The destination has to have enough space to hold the decoded buffer.
3858
 * Decoding stops either when all strings have been decoded or invalid an
3859
 * character appeared.
3860
 * Destination is '\0'-terminated.
3861
 * Returns the number of decoded characters. On success, that should be equal
3862
 * to `len`. On error (invalid character) the return value is smaller then
3863
 * `len`.
3864
 */
3865
int mg_base64_decode(const unsigned char *s, int len, char *dst);
3866

    
3867
/*
3868
 * Base64-encode chunk of memory `src`, `src_len` into the destination `dst`.
3869
 * Destination has to have enough space to hold encoded buffer.
3870
 * Destination is '\0'-terminated.
3871
 */
3872
void mg_base64_encode(const unsigned char *src, int src_len, char *dst);
3873

    
3874
#if MG_ENABLE_FILESYSTEM
3875
/*
3876
 * Performs a 64-bit `stat()` call against a given file.
3877
 *
3878
 * `path` should be UTF8 encoded.
3879
 *
3880
 * Return value is the same as for `stat()` syscall.
3881
 */
3882
int mg_stat(const char *path, cs_stat_t *st);
3883

    
3884
/*
3885
 * Opens the given file and returns a file stream.
3886
 *
3887
 * `path` and `mode` should be UTF8 encoded.
3888
 *
3889
 * Return value is the same as for the `fopen()` call.
3890
 */
3891
FILE *mg_fopen(const char *path, const char *mode);
3892

    
3893
/*
3894
 * Opens the given file and returns a file stream.
3895
 *
3896
 * `path` should be UTF8 encoded.
3897
 *
3898
 * Return value is the same as for the `open()` syscall.
3899
 */
3900
int mg_open(const char *path, int flag, int mode);
3901
#endif /* MG_ENABLE_FILESYSTEM */
3902

    
3903
#if MG_ENABLE_THREADS
3904
/*
3905
 * Starts a new detached thread.
3906
 * Arguments and semantics are the same as pthead's `pthread_create()`.
3907
 * `thread_func` is a thread function, `thread_func_param` is a parameter
3908
 * that is passed to the thread function.
3909
 */
3910
void *mg_start_thread(void *(*thread_func)(void *), void *thread_func_param);
3911
#endif
3912

    
3913
void mg_set_close_on_exec(sock_t);
3914

    
3915
#define MG_SOCK_STRINGIFY_IP 1
3916
#define MG_SOCK_STRINGIFY_PORT 2
3917
#define MG_SOCK_STRINGIFY_REMOTE 4
3918
/*
3919
 * Converts a connection's local or remote address into string.
3920
 *
3921
 * The `flags` parameter is a bit mask that controls the behaviour,
3922
 * see `MG_SOCK_STRINGIFY_*` definitions.
3923
 *
3924
 * - MG_SOCK_STRINGIFY_IP - print IP address
3925
 * - MG_SOCK_STRINGIFY_PORT - print port number
3926
 * - MG_SOCK_STRINGIFY_REMOTE - print remote peer's IP/port, not local address
3927
 *
3928
 * If both port number and IP address are printed, they are separated by `:`.
3929
 * If compiled with `-DMG_ENABLE_IPV6`, IPv6 addresses are supported.
3930
 */
3931
void mg_conn_addr_to_str(struct mg_connection *nc, char *buf, size_t len,
3932
                         int flags);
3933
#if MG_NET_IF == MG_NET_IF_SOCKET
3934
/* Legacy interface. */
3935
void mg_sock_to_str(sock_t sock, char *buf, size_t len, int flags);
3936
#endif
3937

    
3938
/*
3939
 * Convert the socket's address into string.
3940
 *
3941
 * `flags` is MG_SOCK_STRINGIFY_IP and/or MG_SOCK_STRINGIFY_PORT.
3942
 */
3943
void mg_sock_addr_to_str(const union socket_address *sa, char *buf, size_t len,
3944
                         int flags);
3945

    
3946
#if MG_ENABLE_HEXDUMP
3947
/*
3948
 * Generates a human-readable hexdump of memory chunk.
3949
 *
3950
 * Takes a memory buffer `buf` of length `len` and creates a hex dump of that
3951
 * buffer in `dst`. The generated output is a-la hexdump(1).
3952
 * Returns the length of generated string, excluding terminating `\0`. If
3953
 * returned length is bigger than `dst_len`, the overflow bytes are discarded.
3954
 */
3955
int mg_hexdump(const void *buf, int len, char *dst, int dst_len);
3956

    
3957
/*
3958
 * Generates human-readable hexdump of the data sent or received by the
3959
 * connection. `path` is a file name where hexdump should be written.
3960
 * `num_bytes` is a number of bytes sent/received. `ev` is one of the `MG_*`
3961
 * events sent to an event handler. This function is supposed to be called from
3962
 * the event handler.
3963
 */
3964
void mg_hexdump_connection(struct mg_connection *nc, const char *path,
3965
                           const void *buf, int num_bytes, int ev);
3966
#endif
3967

    
3968
/*
3969
 * Returns true if target platform is big endian.
3970
 */
3971
int mg_is_big_endian(void);
3972

    
3973
/*
3974
 * A helper function for traversing a comma separated list of values.
3975
 * It returns a list pointer shifted to the next value or NULL if the end
3976
 * of the list found.
3977
 * The value is stored in a val vector. If the value has a form "x=y", then
3978
 * eq_val vector is initialised to point to the "y" part, and val vector length
3979
 * is adjusted to point only to "x".
3980
 * If the list is just a comma separated list of entries, like "aa,bb,cc" then
3981
 * `eq_val` will contain zero-length string.
3982
 *
3983
 * The purpose of this function is to parse comma separated string without
3984
 * any copying/memory allocation.
3985
 */
3986
const char *mg_next_comma_list_entry(const char *list, struct mg_str *val,
3987
                                     struct mg_str *eq_val);
3988

    
3989
/*
3990
 * Matches 0-terminated string (mg_match_prefix) or string with given length
3991
 * mg_match_prefix_n against a glob pattern.
3992
 *
3993
 * Match is case-insensitive. Returns number of bytes matched, or -1 if no
3994
 * match.
3995
 */
3996
int mg_match_prefix(const char *pattern, int pattern_len, const char *str);
3997
int mg_match_prefix_n(const struct mg_str pattern, const struct mg_str str);
3998

    
3999
/*
4000
 * Use with cs_base64_init/update/finish in order to write out base64 in chunks.
4001
 */
4002
void mg_mbuf_append_base64_putc(char ch, void *user_data);
4003

    
4004
/*
4005
 * Encode `len` bytes starting at `data` as base64 and append them to an mbuf.
4006
 */
4007
void mg_mbuf_append_base64(struct mbuf *mbuf, const void *data, size_t len);
4008

    
4009
/*
4010
 * Generate a Basic Auth header and appends it to buf.
4011
 * If pass is NULL, then user is expected to contain the credentials pair
4012
 * already encoded as `user:pass`.
4013
 */
4014
void mg_basic_auth_header(const char *user, const char *pass, struct mbuf *buf);
4015

    
4016
#ifdef __cplusplus
4017
}
4018
#endif /* __cplusplus */
4019
#endif /* CS_MONGOOSE_SRC_UTIL_H_ */
4020
#ifdef MG_MODULE_LINES
4021
#line 1 "mongoose/src/http.h"
4022
#endif
4023
/*
4024
 * Copyright (c) 2014 Cesanta Software Limited
4025
 * All rights reserved
4026
 */
4027

    
4028
/*
4029
 * === Common API reference
4030
 */
4031

    
4032
#ifndef CS_MONGOOSE_SRC_HTTP_H_
4033
#define CS_MONGOOSE_SRC_HTTP_H_
4034

    
4035
#if MG_ENABLE_HTTP
4036

    
4037
/* Amalgamated: #include "mongoose/src/net.h" */
4038
/* Amalgamated: #include "common/mg_str.h" */
4039

    
4040
#ifdef __cplusplus
4041
extern "C" {
4042
#endif /* __cplusplus */
4043

    
4044
#ifndef MG_MAX_HTTP_HEADERS
4045
#define MG_MAX_HTTP_HEADERS 20
4046
#endif
4047

    
4048
#ifndef MG_MAX_HTTP_REQUEST_SIZE
4049
#define MG_MAX_HTTP_REQUEST_SIZE 1024
4050
#endif
4051

    
4052
#ifndef MG_MAX_PATH
4053
#ifdef PATH_MAX
4054
#define MG_MAX_PATH PATH_MAX
4055
#else
4056
#define MG_MAX_PATH 256
4057
#endif
4058
#endif
4059

    
4060
#ifndef MG_MAX_HTTP_SEND_MBUF
4061
#define MG_MAX_HTTP_SEND_MBUF 1024
4062
#endif
4063

    
4064
#ifndef MG_CGI_ENVIRONMENT_SIZE
4065
#define MG_CGI_ENVIRONMENT_SIZE 8192
4066
#endif
4067

    
4068
/* HTTP message */
4069
struct http_message {
4070
  struct mg_str message; /* Whole message: request line + headers + body */
4071

    
4072
  /* HTTP Request line (or HTTP response line) */
4073
  struct mg_str method; /* "GET" */
4074
  struct mg_str uri;    /* "/my_file.html" */
4075
  struct mg_str proto;  /* "HTTP/1.1" -- for both request and response */
4076

    
4077
  /* For responses, code and response status message are set */
4078
  int resp_code;
4079
  struct mg_str resp_status_msg;
4080

    
4081
  /*
4082
   * Query-string part of the URI. For example, for HTTP request
4083
   *    GET /foo/bar?param1=val1&param2=val2
4084
   *    |    uri    |     query_string     |
4085
   *
4086
   * Note that question mark character doesn't belong neither to the uri,
4087
   * nor to the query_string
4088
   */
4089
  struct mg_str query_string;
4090

    
4091
  /* Headers */
4092
  struct mg_str header_names[MG_MAX_HTTP_HEADERS];
4093
  struct mg_str header_values[MG_MAX_HTTP_HEADERS];
4094

    
4095
  /* Message body */
4096
  struct mg_str body; /* Zero-length for requests with no body */
4097
};
4098

    
4099
#if MG_ENABLE_HTTP_WEBSOCKET
4100
/* WebSocket message */
4101
struct websocket_message {
4102
  unsigned char *data;
4103
  size_t size;
4104
  unsigned char flags;
4105
};
4106
#endif
4107

    
4108
/* HTTP multipart part */
4109
struct mg_http_multipart_part {
4110
  const char *file_name;
4111
  const char *var_name;
4112
  struct mg_str data;
4113
  int status; /* <0 on error */
4114
  void *user_data;
4115
};
4116

    
4117
/* SSI call context */
4118
struct mg_ssi_call_ctx {
4119
  struct http_message *req; /* The request being processed. */
4120
  struct mg_str file;       /* Filesystem path of the file being processed. */
4121
  struct mg_str arg; /* The argument passed to the tag: <!-- call arg -->. */
4122
};
4123

    
4124
/* HTTP and websocket events. void *ev_data is described in a comment. */
4125
#define MG_EV_HTTP_REQUEST 100 /* struct http_message * */
4126
#define MG_EV_HTTP_REPLY 101   /* struct http_message * */
4127
#define MG_EV_HTTP_CHUNK 102   /* struct http_message * */
4128
#define MG_EV_SSI_CALL 105     /* char * */
4129
#define MG_EV_SSI_CALL_CTX 106 /* struct mg_ssi_call_ctx * */
4130

    
4131
#if MG_ENABLE_HTTP_WEBSOCKET
4132
#define MG_EV_WEBSOCKET_HANDSHAKE_REQUEST 111 /* struct http_message * */
4133
#define MG_EV_WEBSOCKET_HANDSHAKE_DONE 112    /* NULL */
4134
#define MG_EV_WEBSOCKET_FRAME 113             /* struct websocket_message * */
4135
#define MG_EV_WEBSOCKET_CONTROL_FRAME 114     /* struct websocket_message * */
4136
#endif
4137

    
4138
#if MG_ENABLE_HTTP_STREAMING_MULTIPART
4139
#define MG_EV_HTTP_MULTIPART_REQUEST 121 /* struct http_message */
4140
#define MG_EV_HTTP_PART_BEGIN 122        /* struct mg_http_multipart_part */
4141
#define MG_EV_HTTP_PART_DATA 123         /* struct mg_http_multipart_part */
4142
#define MG_EV_HTTP_PART_END 124          /* struct mg_http_multipart_part */
4143
/* struct mg_http_multipart_part */
4144
#define MG_EV_HTTP_MULTIPART_REQUEST_END 125
4145
#endif
4146

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

    
4201
#if MG_ENABLE_HTTP_WEBSOCKET
4202
/*
4203
 * Send websocket handshake to the server.
4204
 *
4205
 * `nc` must be a valid connection, connected to a server. `uri` is an URI
4206
 * to fetch, extra_headers` is extra HTTP headers to send or `NULL`.
4207
 *
4208
 * This function is intended to be used by websocket client.
4209
 *
4210
 * Note that the Host header is mandatory in HTTP/1.1 and must be
4211
 * included in `extra_headers`. `mg_send_websocket_handshake2` offers
4212
 * a better API for that.
4213
 *
4214
 * Deprecated in favour of `mg_send_websocket_handshake2`
4215
 */
4216
void mg_send_websocket_handshake(struct mg_connection *nc, const char *uri,
4217
                                 const char *extra_headers);
4218

    
4219
/*
4220
 * Send websocket handshake to the server.
4221
 *
4222
 * `nc` must be a valid connection, connected to a server. `uri` is an URI
4223
 * to fetch, `host` goes into the `Host` header, `protocol` goes into the
4224
 * `Sec-WebSocket-Proto` header (NULL to omit), extra_headers` is extra HTTP
4225
 * headers to send or `NULL`.
4226
 *
4227
 * This function is intended to be used by websocket client.
4228
 */
4229
void mg_send_websocket_handshake2(struct mg_connection *nc, const char *path,
4230
                                  const char *host, const char *protocol,
4231
                                  const char *extra_headers);
4232

    
4233
/* Like mg_send_websocket_handshake2 but also passes basic auth header */
4234
void mg_send_websocket_handshake3(struct mg_connection *nc, const char *path,
4235
                                  const char *host, const char *protocol,
4236
                                  const char *extra_headers, const char *user,
4237
                                  const char *pass);
4238
/*
4239
 * Helper function that creates an outbound WebSocket connection.
4240
 *
4241
 * `url` is a URL to connect to. It must be properly URL-encoded, e.g. have
4242
 * no spaces, etc. By default, `mg_connect_ws()` sends Connection and
4243
 * Host headers. `extra_headers` is an extra HTTP header to send, e.g.
4244
 * `"User-Agent: my-app\r\n"`.
4245
 * If `protocol` is not NULL, then a `Sec-WebSocket-Protocol` header is sent.
4246
 *
4247
 * Examples:
4248
 *
4249
 * ```c
4250
 *   nc1 = mg_connect_ws(mgr, ev_handler_1, "ws://echo.websocket.org", NULL,
4251
 *                       NULL);
4252
 *   nc2 = mg_connect_ws(mgr, ev_handler_1, "wss://echo.websocket.org", NULL,
4253
 *                       NULL);
4254
 *   nc3 = mg_connect_ws(mgr, ev_handler_1, "ws://api.cesanta.com",
4255
 *                       "clubby.cesanta.com", NULL);
4256
 * ```
4257
 */
4258
struct mg_connection *mg_connect_ws(struct mg_mgr *mgr,
4259
                                    mg_event_handler_t event_handler,
4260
                                    const char *url, const char *protocol,
4261
                                    const char *extra_headers);
4262

    
4263
/*
4264
 * Helper function that creates an outbound WebSocket connection
4265
 *
4266
 * Mostly identical to `mg_connect_ws`, but allows to provide extra parameters
4267
 * (for example, SSL parameters)
4268
 */
4269
struct mg_connection *mg_connect_ws_opt(struct mg_mgr *mgr,
4270
                                        mg_event_handler_t ev_handler,
4271
                                        struct mg_connect_opts opts,
4272
                                        const char *url, const char *protocol,
4273
                                        const char *extra_headers);
4274

    
4275
/*
4276
 * Send WebSocket frame to the remote end.
4277
 *
4278
 * `op_and_flags` specifies the frame's type. It's one of:
4279
 *
4280
 * - WEBSOCKET_OP_CONTINUE
4281
 * - WEBSOCKET_OP_TEXT
4282
 * - WEBSOCKET_OP_BINARY
4283
 * - WEBSOCKET_OP_CLOSE
4284
 * - WEBSOCKET_OP_PING
4285
 * - WEBSOCKET_OP_PONG
4286
 *
4287
 * Orred with one of the flags:
4288
 *
4289
 * - WEBSOCKET_DONT_FIN: Don't set the FIN flag on the frame to be sent.
4290
 *
4291
 * `data` and `data_len` contain frame data.
4292
 */
4293
void mg_send_websocket_frame(struct mg_connection *nc, int op_and_flags,
4294
                             const void *data, size_t data_len);
4295

    
4296
/*
4297
 * Sends multiple websocket frames.
4298
 *
4299
 * Like `mg_send_websocket_frame()`, but composes a frame from multiple buffers.
4300
 */
4301
void mg_send_websocket_framev(struct mg_connection *nc, int op_and_flags,
4302
                              const struct mg_str *strings, int num_strings);
4303

    
4304
/*
4305
 * Sends WebSocket frame to the remote end.
4306
 *
4307
 * Like `mg_send_websocket_frame()`, but allows to create formatted messages
4308
 * with `printf()`-like semantics.
4309
 */
4310
void mg_printf_websocket_frame(struct mg_connection *nc, int op_and_flags,
4311
                               const char *fmt, ...);
4312

    
4313
/* Websocket opcodes, from http://tools.ietf.org/html/rfc6455 */
4314
#define WEBSOCKET_OP_CONTINUE 0
4315
#define WEBSOCKET_OP_TEXT 1
4316
#define WEBSOCKET_OP_BINARY 2
4317
#define WEBSOCKET_OP_CLOSE 8
4318
#define WEBSOCKET_OP_PING 9
4319
#define WEBSOCKET_OP_PONG 10
4320

    
4321
/*
4322
 * If set causes the FIN flag to not be set on outbound
4323
 * frames. This enables sending multiple fragments of a single
4324
 * logical message.
4325
 *
4326
 * The WebSocket protocol mandates that if the FIN flag of a data
4327
 * frame is not set, the next frame must be a WEBSOCKET_OP_CONTINUE.
4328
 * The last frame must have the FIN bit set.
4329
 *
4330
 * Note that mongoose will automatically defragment incoming messages,
4331
 * so this flag is used only on outbound messages.
4332
 */
4333
#define WEBSOCKET_DONT_FIN 0x100
4334

    
4335
#endif /* MG_ENABLE_HTTP_WEBSOCKET */
4336

    
4337
/*
4338
 * Decodes a URL-encoded string.
4339
 *
4340
 * Source string is specified by (`src`, `src_len`), and destination is
4341
 * (`dst`, `dst_len`). If `is_form_url_encoded` is non-zero, then
4342
 * `+` character is decoded as a blank space character. This function
4343
 * guarantees to NUL-terminate the destination. If destination is too small,
4344
 * then the source string is partially decoded and `-1` is returned. Otherwise,
4345
 * a length of the decoded string is returned, not counting final NUL.
4346
 */
4347
int mg_url_decode(const char *src, int src_len, char *dst, int dst_len,
4348
                  int is_form_url_encoded);
4349

    
4350
#ifdef __cplusplus
4351
}
4352
#endif /* __cplusplus */
4353

    
4354
#endif /* MG_ENABLE_HTTP */
4355

    
4356
#endif /* CS_MONGOOSE_SRC_HTTP_H_ */
4357
#ifdef MG_MODULE_LINES
4358
#line 1 "mongoose/src/http_server.h"
4359
#endif
4360
/*
4361
 * === Server API reference
4362
 */
4363

    
4364
#ifndef CS_MONGOOSE_SRC_HTTP_SERVER_H_
4365
#define CS_MONGOOSE_SRC_HTTP_SERVER_H_
4366

    
4367
#if MG_ENABLE_HTTP
4368

    
4369
#ifdef __cplusplus
4370
extern "C" {
4371
#endif /* __cplusplus */
4372

    
4373
/*
4374
 * Parses a HTTP message.
4375
 *
4376
 * `is_req` should be set to 1 if parsing a request, 0 if reply.
4377
 *
4378
 * Returns the number of bytes parsed. If HTTP message is
4379
 * incomplete `0` is returned. On parse error, a negative number is returned.
4380
 */
4381
int mg_parse_http(const char *s, int n, struct http_message *hm, int is_req);
4382

    
4383
/*
4384
 * Searches and returns the header `name` in parsed HTTP message `hm`.
4385
 * If header is not found, NULL is returned. Example:
4386
 *
4387
 *     struct mg_str *host_hdr = mg_get_http_header(hm, "Host");
4388
 */
4389
struct mg_str *mg_get_http_header(struct http_message *hm, const char *name);
4390

    
4391
/*
4392
 * Parses the HTTP header `hdr`. Finds variable `var_name` and stores its value
4393
 * in the buffer `buf`, `buf_size`. Returns 0 if variable not found, non-zero
4394
 * otherwise.
4395
 *
4396
 * This function is supposed to parse cookies, authentication headers, etc.
4397
 * Example (error handling omitted):
4398
 *
4399
 *     char user[20];
4400
 *     struct mg_str *hdr = mg_get_http_header(hm, "Authorization");
4401
 *     mg_http_parse_header(hdr, "username", user, sizeof(user));
4402
 *
4403
 * Returns the length of the variable's value. If buffer is not large enough,
4404
 * or variable not found, 0 is returned.
4405
 */
4406
int mg_http_parse_header(struct mg_str *hdr, const char *var_name, char *buf,
4407
                         size_t buf_size);
4408

    
4409
/*
4410
 * Gets and parses the Authorization: Basic header
4411
 * Returns -1 if no Authorization header is found, or if
4412
 * mg_parse_http_basic_auth
4413
 * fails parsing the resulting header.
4414
 */
4415
int mg_get_http_basic_auth(struct http_message *hm, char *user, size_t user_len,
4416
                           char *pass, size_t pass_len);
4417

    
4418
/*
4419
 * Parses the Authorization: Basic header
4420
 * Returns -1 iif the authorization type is not "Basic" or any other error such
4421
 * as incorrectly encoded base64 user password pair.
4422
 */
4423
int mg_parse_http_basic_auth(struct mg_str *hdr, char *user, size_t user_len,
4424
                             char *pass, size_t pass_len);
4425

    
4426
/*
4427
 * Parses the buffer `buf`, `buf_len` that contains multipart form data chunks.
4428
 * Stores the chunk name in a `var_name`, `var_name_len` buffer.
4429
 * If a chunk is an uploaded file, then `file_name`, `file_name_len` is
4430
 * filled with an uploaded file name. `chunk`, `chunk_len`
4431
 * points to the chunk data.
4432
 *
4433
 * Return: number of bytes to skip to the next chunk or 0 if there are
4434
 *         no more chunks.
4435
 *
4436
 * Usage example:
4437
 *
4438
 * ```c
4439
 *    static void ev_handler(struct mg_connection *nc, int ev, void *ev_data) {
4440
 *      switch(ev) {
4441
 *        case MG_EV_HTTP_REQUEST: {
4442
 *          struct http_message *hm = (struct http_message *) ev_data;
4443
 *          char var_name[100], file_name[100];
4444
 *          const char *chunk;
4445
 *          size_t chunk_len, n1, n2;
4446
 *
4447
 *          n1 = n2 = 0;
4448
 *          while ((n2 = mg_parse_multipart(hm->body.p + n1,
4449
 *                                          hm->body.len - n1,
4450
 *                                          var_name, sizeof(var_name),
4451
 *                                          file_name, sizeof(file_name),
4452
 *                                          &chunk, &chunk_len)) > 0) {
4453
 *            printf("var: %s, file_name: %s, size: %d, chunk: [%.*s]\n",
4454
 *                   var_name, file_name, (int) chunk_len,
4455
 *                   (int) chunk_len, chunk);
4456
 *            n1 += n2;
4457
 *          }
4458
 *        }
4459
 *        break;
4460
 * ```
4461
 */
4462
size_t mg_parse_multipart(const char *buf, size_t buf_len, char *var_name,
4463
                          size_t var_name_len, char *file_name,
4464
                          size_t file_name_len, const char **chunk,
4465
                          size_t *chunk_len);
4466

    
4467
/*
4468
 * Fetches a HTTP form variable.
4469
 *
4470
 * Fetches a variable `name` from a `buf` into a buffer specified by `dst`,
4471
 * `dst_len`. The destination is always zero-terminated. Returns the length of
4472
 * a fetched variable. If not found, 0 is returned. `buf` must be valid
4473
 * url-encoded buffer. If destination is too small, `-1` is returned.
4474
 */
4475
int mg_get_http_var(const struct mg_str *buf, const char *name, char *dst,
4476
                    size_t dst_len);
4477

    
4478
#if MG_ENABLE_FILESYSTEM
4479
/*
4480
 * This structure defines how `mg_serve_http()` works.
4481
 * Best practice is to set only required settings, and leave the rest as NULL.
4482
 */
4483
struct mg_serve_http_opts {
4484
  /* Path to web root directory */
4485
  const char *document_root;
4486

    
4487
  /* List of index files. Default is "" */
4488
  const char *index_files;
4489

    
4490
  /*
4491
   * Leave as NULL to disable authentication.
4492
   * To enable directory protection with authentication, set this to ".htpasswd"
4493
   * Then, creating ".htpasswd" file in any directory automatically protects
4494
   * it with digest authentication.
4495
   * Use `mongoose` web server binary, or `htdigest` Apache utility to
4496
   * create/manipulate passwords file.
4497
   * Make sure `auth_domain` is set to a valid domain name.
4498
   */
4499
  const char *per_directory_auth_file;
4500

    
4501
  /* Authorization domain (domain name of this web server) */
4502
  const char *auth_domain;
4503

    
4504
  /*
4505
   * Leave as NULL to disable authentication.
4506
   * Normally, only selected directories in the document root are protected.
4507
   * If absolutely every access to the web server needs to be authenticated,
4508
   * regardless of the URI, set this option to the path to the passwords file.
4509
   * Format of that file is the same as ".htpasswd" file. Make sure that file
4510
   * is located outside document root to prevent people fetching it.
4511
   */
4512
  const char *global_auth_file;
4513

    
4514
  /* Set to "no" to disable directory listing. Enabled by default. */
4515
  const char *enable_directory_listing;
4516

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

    
4577
  /* IP ACL. By default, NULL, meaning all IPs are allowed to connect */
4578
  const char *ip_acl;
4579

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

    
4608
  /* DAV document root. If NULL, DAV requests are going to fail. */
4609
  const char *dav_document_root;
4610

    
4611
  /*
4612
   * DAV passwords file. If NULL, DAV requests are going to fail.
4613
   * If passwords file is set to "-", then DAV auth is disabled.
4614
   */
4615
  const char *dav_auth_file;
4616

    
4617
  /* Glob pattern for the files to hide. */
4618
  const char *hidden_file_pattern;
4619

    
4620
  /* Set to non-NULL to enable CGI, e.g. **.cgi$|**.php$" */
4621
  const char *cgi_file_pattern;
4622

    
4623
  /* If not NULL, ignore CGI script hashbang and use this interpreter */
4624
  const char *cgi_interpreter;
4625

    
4626
  /*
4627
   * Comma-separated list of Content-Type overrides for path suffixes, e.g.
4628
   * ".txt=text/plain; charset=utf-8,.c=text/plain"
4629
   */
4630
  const char *custom_mime_types;
4631

    
4632
  /*
4633
   * Extra HTTP headers to add to each server response.
4634
   * Example: to enable CORS, set this to "Access-Control-Allow-Origin: *".
4635
   */
4636
  const char *extra_headers;
4637
};
4638

    
4639
/*
4640
 * Serves given HTTP request according to the `options`.
4641
 *
4642
 * Example code snippet:
4643
 *
4644
 * ```c
4645
 * static void ev_handler(struct mg_connection *nc, int ev, void *ev_data) {
4646
 *   struct http_message *hm = (struct http_message *) ev_data;
4647
 *   struct mg_serve_http_opts opts = { .document_root = "/var/www" };  // C99
4648
 *
4649
 *   switch (ev) {
4650
 *     case MG_EV_HTTP_REQUEST:
4651
 *       mg_serve_http(nc, hm, opts);
4652
 *       break;
4653
 *     default:
4654
 *       break;
4655
 *   }
4656
 * }
4657
 * ```
4658
 */
4659
void mg_serve_http(struct mg_connection *nc, struct http_message *hm,
4660
                   struct mg_serve_http_opts opts);
4661

    
4662
/*
4663
 * Serves a specific file with a given MIME type and optional extra headers.
4664
 *
4665
 * Example code snippet:
4666
 *
4667
 * ```c
4668
 * static void ev_handler(struct mg_connection *nc, int ev, void *ev_data) {
4669
 *   switch (ev) {
4670
 *     case MG_EV_HTTP_REQUEST: {
4671
 *       struct http_message *hm = (struct http_message *) ev_data;
4672
 *       mg_http_serve_file(nc, hm, "file.txt",
4673
 *                          mg_mk_str("text/plain"), mg_mk_str(""));
4674
 *       break;
4675
 *     }
4676
 *     ...
4677
 *   }
4678
 * }
4679
 * ```
4680
 */
4681
void mg_http_serve_file(struct mg_connection *nc, struct http_message *hm,
4682
                        const char *path, const struct mg_str mime_type,
4683
                        const struct mg_str extra_headers);
4684

    
4685
#if MG_ENABLE_HTTP_STREAMING_MULTIPART
4686

    
4687
/* Callback prototype for `mg_file_upload_handler()`. */
4688
typedef struct mg_str (*mg_fu_fname_fn)(struct mg_connection *nc,
4689
                                        struct mg_str fname);
4690

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

    
4728
/*
4729
 * Registers a callback for a specified http endpoint
4730
 * Note: if callback is registered it is called instead of the
4731
 * callback provided in mg_bind
4732
 *
4733
 * Example code snippet:
4734
 *
4735
 * ```c
4736
 * static void handle_hello1(struct mg_connection *nc, int ev, void *ev_data) {
4737
 *   (void) ev; (void) ev_data;
4738
 *   mg_printf(nc, "HTTP/1.0 200 OK\r\n\r\n[I am Hello1]");
4739
 *  nc->flags |= MG_F_SEND_AND_CLOSE;
4740
 * }
4741
 *
4742
 * static void handle_hello1(struct mg_connection *nc, int ev, void *ev_data) {
4743
 *  (void) ev; (void) ev_data;
4744
 *   mg_printf(nc, "HTTP/1.0 200 OK\r\n\r\n[I am Hello2]");
4745
 *  nc->flags |= MG_F_SEND_AND_CLOSE;
4746
 * }
4747
 *
4748
 * void init() {
4749
 *   nc = mg_bind(&mgr, local_addr, cb1);
4750
 *   mg_register_http_endpoint(nc, "/hello1", handle_hello1);
4751
 *   mg_register_http_endpoint(nc, "/hello1/hello2", handle_hello2);
4752
 * }
4753
 * ```
4754
 */
4755
void mg_register_http_endpoint(struct mg_connection *nc, const char *uri_path,
4756
                               mg_event_handler_t handler);
4757

    
4758
/*
4759
 * Authenticates a HTTP request against an opened password file.
4760
 * Returns 1 if authenticated, 0 otherwise.
4761
 */
4762
int mg_http_check_digest_auth(struct http_message *hm, const char *auth_domain,
4763
                              FILE *fp);
4764

    
4765
/*
4766
 * Sends buffer `buf` of size `len` to the client using chunked HTTP encoding.
4767
 * This function sends the buffer size as hex number + newline first, then
4768
 * the buffer itself, then the newline. For example,
4769
 * `mg_send_http_chunk(nc, "foo", 3)` whill append the `3\r\nfoo\r\n` string
4770
 * to the `nc->send_mbuf` output IO buffer.
4771
 *
4772
 * NOTE: The HTTP header "Transfer-Encoding: chunked" should be sent prior to
4773
 * using this function.
4774
 *
4775
 * NOTE: do not forget to send an empty chunk at the end of the response,
4776
 * to tell the client that everything was sent. Example:
4777
 *
4778
 * ```
4779
 *   mg_printf_http_chunk(nc, "%s", "my response!");
4780
 *   mg_send_http_chunk(nc, "", 0); // Tell the client we're finished
4781
 * ```
4782
 */
4783
void mg_send_http_chunk(struct mg_connection *nc, const char *buf, size_t len);
4784

    
4785
/*
4786
 * Sends a printf-formatted HTTP chunk.
4787
 * Functionality is similar to `mg_send_http_chunk()`.
4788
 */