Project

General

Profile

Feature #2758 » mongoose.h

yan hong, 06/19/2023 03:34 PM

 
1
#ifdef MG_MODULE_LINES
2
#line 1 "mongoose/src/mg_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.11"
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_CC3100 6
50
#define CS_P_CC3200 4
51
#define CS_P_CC3220 17
52
#define CS_P_MSP432 5
53
#define CS_P_TM4C129 14
54
#define CS_P_MBED 7
55
#define CS_P_WINCE 8
56
#define CS_P_NXP_LPC 13
57
#define CS_P_NXP_KINETIS 9
58
#define CS_P_NRF51 12
59
#define CS_P_NRF52 10
60
#define CS_P_PIC32 11
61
#define CS_P_STM32 16
62
/* Next id: 18 */
63

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

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

    
98
#ifndef CS_PLATFORM
99
#error "CS_PLATFORM is not specified and we couldn't guess it."
100
#endif
101

    
102
#endif /* !defined(CS_PLATFORM) */
103

    
104
#define MG_NET_IF_SOCKET 1
105
#define MG_NET_IF_SIMPLELINK 2
106
#define MG_NET_IF_LWIP_LOW_LEVEL 3
107
#define MG_NET_IF_PIC32 4
108

    
109
#define MG_SSL_IF_OPENSSL 1
110
#define MG_SSL_IF_MBEDTLS 2
111
#define MG_SSL_IF_SIMPLELINK 3
112

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

    
129
/* Common stuff */
130

    
131
#if !defined(WEAK)
132
#if (defined(__GNUC__) || defined(__TI_COMPILER_VERSION__)) && !defined(_WIN32)
133
#define WEAK __attribute__((weak))
134
#else
135
#define WEAK
136
#endif
137
#endif
138

    
139
#ifdef __GNUC__
140
#define NORETURN __attribute__((noreturn))
141
#define NOINLINE __attribute__((noinline))
142
#define WARN_UNUSED_RESULT __attribute__((warn_unused_result))
143
#define NOINSTR __attribute__((no_instrument_function))
144
#define DO_NOT_WARN_UNUSED __attribute__((unused))
145
#else
146
#define NORETURN
147
#define NOINLINE
148
#define WARN_UNUSED_RESULT
149
#define NOINSTR
150
#define DO_NOT_WARN_UNUSED
151
#endif /* __GNUC__ */
152

    
153
#ifndef ARRAY_SIZE
154
#define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
155
#endif
156

    
157
#endif /* CS_COMMON_PLATFORM_H_ */
158
#ifdef MG_MODULE_LINES
159
#line 1 "common/platforms/platform_windows.h"
160
#endif
161
#ifndef CS_COMMON_PLATFORMS_PLATFORM_WINDOWS_H_
162
#define CS_COMMON_PLATFORMS_PLATFORM_WINDOWS_H_
163
#if CS_PLATFORM == CS_P_WINDOWS
164

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

    
182
#ifndef _WINSOCK_DEPRECATED_NO_WARNINGS
183
#define _WINSOCK_DEPRECATED_NO_WARNINGS 1
184
#endif
185

    
186
#ifndef _CRT_SECURE_NO_WARNINGS
187
#define _CRT_SECURE_NO_WARNINGS
188
#endif
189

    
190
#include <assert.h>
191
#include <direct.h>
192
#include <errno.h>
193
#include <fcntl.h>
194
#include <io.h>
195
#include <limits.h>
196
#include <signal.h>
197
#include <stddef.h>
198
#include <stdio.h>
199
#include <stdlib.h>
200
#include <sys/stat.h>
201
#include <time.h>
202
#include <ctype.h>
203

    
204
#ifdef _MSC_VER
205
#pragma comment(lib, "ws2_32.lib") /* Linking with winsock library */
206
#endif
207

    
208
#include <winsock2.h>
209
#include <ws2tcpip.h>
210
#include <windows.h>
211
#include <process.h>
212

    
213
#if _MSC_VER < 1700
214
typedef int bool;
215
#else
216
#include <stdbool.h>
217
#endif
218

    
219
#if defined(_MSC_VER) && _MSC_VER >= 1800
220
#define strdup _strdup
221
#endif
222

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

    
288
#ifndef va_copy
289
#ifdef __va_copy
290
#define va_copy __va_copy
291
#else
292
#define va_copy(x, y) (x) = (y)
293
#endif
294
#endif
295

    
296
#ifndef MG_MAX_HTTP_REQUEST_SIZE
297
#define MG_MAX_HTTP_REQUEST_SIZE 8192
298
#endif
299

    
300
#ifndef MG_MAX_HTTP_SEND_MBUF
301
#define MG_MAX_HTTP_SEND_MBUF 4096
302
#endif
303

    
304
#ifndef MG_MAX_HTTP_HEADERS
305
#define MG_MAX_HTTP_HEADERS 40
306
#endif
307

    
308
#ifndef CS_ENABLE_STDIO
309
#define CS_ENABLE_STDIO 1
310
#endif
311

    
312
#ifndef MG_ENABLE_BROADCAST
313
#define MG_ENABLE_BROADCAST 1
314
#endif
315

    
316
#ifndef MG_ENABLE_DIRECTORY_LISTING
317
#define MG_ENABLE_DIRECTORY_LISTING 1
318
#endif
319

    
320
#ifndef MG_ENABLE_FILESYSTEM
321
#define MG_ENABLE_FILESYSTEM 1
322
#endif
323

    
324
#ifndef MG_ENABLE_HTTP_CGI
325
#define MG_ENABLE_HTTP_CGI MG_ENABLE_FILESYSTEM
326
#endif
327

    
328
#ifndef MG_NET_IF
329
#define MG_NET_IF MG_NET_IF_SOCKET
330
#endif
331

    
332
unsigned int sleep(unsigned int seconds);
333

    
334
/* https://stackoverflow.com/questions/16647819/timegm-cross-platform */
335
#define timegm _mkgmtime
336

    
337
#define gmtime_r(a, b) \
338
  do {                 \
339
    *(b) = *gmtime(a); \
340
  } while (0)
341

    
342
#endif /* CS_PLATFORM == CS_P_WINDOWS */
343
#endif /* CS_COMMON_PLATFORMS_PLATFORM_WINDOWS_H_ */
344
#ifdef MG_MODULE_LINES
345
#line 1 "common/platforms/platform_unix.h"
346
#endif
347
#ifndef CS_COMMON_PLATFORMS_PLATFORM_UNIX_H_
348
#define CS_COMMON_PLATFORMS_PLATFORM_UNIX_H_
349
#if CS_PLATFORM == CS_P_UNIX
350

    
351
#ifndef _XOPEN_SOURCE
352
#define _XOPEN_SOURCE 600
353
#endif
354

    
355
/* <inttypes.h> wants this for C++ */
356
#ifndef __STDC_FORMAT_MACROS
357
#define __STDC_FORMAT_MACROS
358
#endif
359

    
360
/* C++ wants that for INT64_MAX */
361
#ifndef __STDC_LIMIT_MACROS
362
#define __STDC_LIMIT_MACROS
363
#endif
364

    
365
/* Enable fseeko() and ftello() functions */
366
#ifndef _LARGEFILE_SOURCE
367
#define _LARGEFILE_SOURCE
368
#endif
369

    
370
/* Enable 64-bit file offsets */
371
#ifndef _FILE_OFFSET_BITS
372
#define _FILE_OFFSET_BITS 64
373
#endif
374

    
375
#include <arpa/inet.h>
376
#include <assert.h>
377
#include <ctype.h>
378
#include <dirent.h>
379
#include <errno.h>
380
#include <fcntl.h>
381
#include <inttypes.h>
382
#include <stdint.h>
383
#include <limits.h>
384
#include <math.h>
385
#include <netdb.h>
386
#include <netinet/in.h>
387
#include <pthread.h>
388
#include <signal.h>
389
#include <stdarg.h>
390
#include <stdbool.h>
391
#include <stdio.h>
392
#include <stdlib.h>
393
#include <string.h>
394
#include <sys/param.h>
395
#include <sys/socket.h>
396
#include <sys/select.h>
397
#include <sys/stat.h>
398
#include <sys/time.h>
399
#include <sys/types.h>
400
#include <unistd.h>
401

    
402
#ifdef __APPLE__
403
#include <machine/endian.h>
404
#ifndef BYTE_ORDER
405
#define LITTLE_ENDIAN __DARWIN_LITTLE_ENDIAN
406
#define BIG_ENDIAN __DARWIN_BIG_ENDIAN
407
#define PDP_ENDIAN __DARWIN_PDP_ENDIAN
408
#define BYTE_ORDER __DARWIN_BYTE_ORDER
409
#endif
410
#endif
411

    
412
/*
413
 * osx correctly avoids defining strtoll when compiling in strict ansi mode.
414
 * c++ 11 standard defines strtoll as well.
415
 * We require strtoll, and if your embedded pre-c99 compiler lacks one, please
416
 * implement a shim.
417
 */
418
#if !(defined(__cplusplus) && __cplusplus >= 201103L) && \
419
    !(defined(__DARWIN_C_LEVEL) && __DARWIN_C_LEVEL >= 200809L)
420
long long strtoll(const char *, char **, int);
421
#endif
422

    
423
typedef int sock_t;
424
#define INVALID_SOCKET (-1)
425
#define SIZE_T_FMT "zu"
426
typedef struct stat cs_stat_t;
427
#define DIRSEP '/'
428
#define to64(x) strtoll(x, NULL, 10)
429
#define INT64_FMT PRId64
430
#define INT64_X_FMT PRIx64
431

    
432
#ifndef __cdecl
433
#define __cdecl
434
#endif
435

    
436
#ifndef va_copy
437
#ifdef __va_copy
438
#define va_copy __va_copy
439
#else
440
#define va_copy(x, y) (x) = (y)
441
#endif
442
#endif
443

    
444
#define closesocket(x) close(x)
445

    
446
#ifndef MG_MAX_HTTP_REQUEST_SIZE
447
#define MG_MAX_HTTP_REQUEST_SIZE 8192
448
#endif
449

    
450
#ifndef MG_MAX_HTTP_SEND_MBUF
451
#define MG_MAX_HTTP_SEND_MBUF 4096
452
#endif
453

    
454
#ifndef MG_MAX_HTTP_HEADERS
455
#define MG_MAX_HTTP_HEADERS 40
456
#endif
457

    
458
#ifndef CS_ENABLE_STDIO
459
#define CS_ENABLE_STDIO 1
460
#endif
461

    
462
#ifndef MG_ENABLE_BROADCAST
463
#define MG_ENABLE_BROADCAST 1
464
#endif
465

    
466
#ifndef MG_ENABLE_DIRECTORY_LISTING
467
#define MG_ENABLE_DIRECTORY_LISTING 1
468
#endif
469

    
470
#ifndef MG_ENABLE_FILESYSTEM
471
#define MG_ENABLE_FILESYSTEM 1
472
#endif
473

    
474
#ifndef MG_ENABLE_HTTP_CGI
475
#define MG_ENABLE_HTTP_CGI MG_ENABLE_FILESYSTEM
476
#endif
477

    
478
#ifndef MG_NET_IF
479
#define MG_NET_IF MG_NET_IF_SOCKET
480
#endif
481

    
482
#ifndef MG_HOSTS_FILE_NAME
483
#define MG_HOSTS_FILE_NAME "/etc/hosts"
484
#endif
485

    
486
#ifndef MG_RESOLV_CONF_FILE_NAME
487
#define MG_RESOLV_CONF_FILE_NAME "/etc/resolv.conf"
488
#endif
489

    
490
#endif /* CS_PLATFORM == CS_P_UNIX */
491
#endif /* CS_COMMON_PLATFORMS_PLATFORM_UNIX_H_ */
492
#ifdef MG_MODULE_LINES
493
#line 1 "common/platforms/platform_esp32.h"
494
#endif
495
/*
496
 * Copyright (c) 2014-2016 Cesanta Software Limited
497
 * All rights reserved
498
 */
499

    
500
#ifndef CS_COMMON_PLATFORMS_PLATFORM_ESP32_H_
501
#define CS_COMMON_PLATFORMS_PLATFORM_ESP32_H_
502
#if CS_PLATFORM == CS_P_ESP32
503

    
504
#include <assert.h>
505
#include <ctype.h>
506
#include <dirent.h>
507
#include <fcntl.h>
508
#include <inttypes.h>
509
#include <machine/endian.h>
510
#include <stdbool.h>
511
#include <stdint.h>
512
#include <string.h>
513
#include <sys/stat.h>
514
#include <sys/time.h>
515

    
516
#define SIZE_T_FMT "u"
517
typedef struct stat cs_stat_t;
518
#define DIRSEP '/'
519
#define to64(x) strtoll(x, NULL, 10)
520
#define INT64_FMT PRId64
521
#define INT64_X_FMT PRIx64
522
#define __cdecl
523
#define _FILE_OFFSET_BITS 32
524

    
525
#define MG_LWIP 1
526

    
527
#ifndef MG_NET_IF
528
#define MG_NET_IF MG_NET_IF_SOCKET
529
#endif
530

    
531
#ifndef CS_ENABLE_STDIO
532
#define CS_ENABLE_STDIO 1
533
#endif
534

    
535
#endif /* CS_PLATFORM == CS_P_ESP32 */
536
#endif /* CS_COMMON_PLATFORMS_PLATFORM_ESP32_H_ */
537
#ifdef MG_MODULE_LINES
538
#line 1 "common/platforms/platform_esp8266.h"
539
#endif
540
/*
541
 * Copyright (c) 2014-2016 Cesanta Software Limited
542
 * All rights reserved
543
 */
544

    
545
#ifndef CS_COMMON_PLATFORMS_PLATFORM_ESP8266_H_
546
#define CS_COMMON_PLATFORMS_PLATFORM_ESP8266_H_
547
#if CS_PLATFORM == CS_P_ESP8266
548

    
549
#include <assert.h>
550
#include <ctype.h>
551
#include <fcntl.h>
552
#include <inttypes.h>
553
#include <machine/endian.h>
554
#include <stdbool.h>
555
#include <string.h>
556
#include <sys/stat.h>
557
#include <sys/time.h>
558

    
559
#define SIZE_T_FMT "u"
560
typedef struct stat cs_stat_t;
561
#define DIRSEP '/'
562
#if !defined(MGOS_VFS_DEFINE_DIRENT)
563
#define CS_DEFINE_DIRENT
564
#endif
565

    
566
#define to64(x) strtoll(x, NULL, 10)
567
#define INT64_FMT PRId64
568
#define INT64_X_FMT PRIx64
569
#define __cdecl
570
#define _FILE_OFFSET_BITS 32
571

    
572
#if !defined(RTOS_SDK) && !defined(__cplusplus)
573
#define fileno(x) -1
574
#endif
575

    
576
#define MG_LWIP 1
577

    
578
/* struct timeval is defined in sys/time.h. */
579
#define LWIP_TIMEVAL_PRIVATE 0
580

    
581
#ifndef MG_NET_IF
582
#include <lwip/opt.h>
583
#if LWIP_SOCKET /* RTOS SDK has LWIP sockets */
584
#define MG_NET_IF MG_NET_IF_SOCKET
585
#else
586
#define MG_NET_IF MG_NET_IF_LWIP_LOW_LEVEL
587
#endif
588
#endif
589

    
590
#ifndef CS_ENABLE_STDIO
591
#define CS_ENABLE_STDIO 1
592
#endif
593

    
594
#define inet_ntop(af, src, dst, size)                                          \
595
  (((af) == AF_INET) ? ipaddr_ntoa_r((const ip_addr_t *) (src), (dst), (size)) \
596
                     : NULL)
597
#define inet_pton(af, src, dst) \
598
  (((af) == AF_INET) ? ipaddr_aton((src), (ip_addr_t *) (dst)) : 0)
599

    
600
#endif /* CS_PLATFORM == CS_P_ESP8266 */
601
#endif /* CS_COMMON_PLATFORMS_PLATFORM_ESP8266_H_ */
602
#ifdef MG_MODULE_LINES
603
#line 1 "common/platforms/platform_cc3100.h"
604
#endif
605
/*
606
 * Copyright (c) 2014-2016 Cesanta Software Limited
607
 * All rights reserved
608
 */
609

    
610
#ifndef CS_COMMON_PLATFORMS_PLATFORM_CC3100_H_
611
#define CS_COMMON_PLATFORMS_PLATFORM_CC3100_H_
612
#if CS_PLATFORM == CS_P_CC3100
613

    
614
#include <assert.h>
615
#include <ctype.h>
616
#include <errno.h>
617
#include <inttypes.h>
618
#include <stdint.h>
619
#include <string.h>
620
#include <time.h>
621

    
622
#define MG_NET_IF MG_NET_IF_SIMPLELINK
623
#define MG_SSL_IF MG_SSL_IF_SIMPLELINK
624

    
625
/*
626
 * CC3100 SDK and STM32 SDK include headers w/out path, just like
627
 * #include "simplelink.h". As result, we have to add all required directories
628
 * into Makefile IPATH and do the same thing (include w/out path)
629
 */
630

    
631
#include <simplelink.h>
632
#include <netapp.h>
633
#undef timeval
634

    
635
typedef int sock_t;
636
#define INVALID_SOCKET (-1)
637

    
638
#define to64(x) strtoll(x, NULL, 10)
639
#define INT64_FMT PRId64
640
#define INT64_X_FMT PRIx64
641
#define SIZE_T_FMT "u"
642

    
643
#define SOMAXCONN 8
644

    
645
const char *inet_ntop(int af, const void *src, char *dst, socklen_t size);
646
char *inet_ntoa(struct in_addr in);
647
int inet_pton(int af, const char *src, void *dst);
648

    
649
#endif /* CS_PLATFORM == CS_P_CC3100 */
650
#endif /* CS_COMMON_PLATFORMS_PLATFORM_CC3100_H_ */
651
#ifdef MG_MODULE_LINES
652
#line 1 "common/platforms/platform_cc3200.h"
653
#endif
654
/*
655
 * Copyright (c) 2014-2016 Cesanta Software Limited
656
 * All rights reserved
657
 */
658

    
659
#ifndef CS_COMMON_PLATFORMS_PLATFORM_CC3200_H_
660
#define CS_COMMON_PLATFORMS_PLATFORM_CC3200_H_
661
#if CS_PLATFORM == CS_P_CC3200
662

    
663
#include <assert.h>
664
#include <ctype.h>
665
#include <errno.h>
666
#include <inttypes.h>
667
#include <stdbool.h>
668
#include <stdint.h>
669
#include <string.h>
670
#include <time.h>
671

    
672
#ifndef __TI_COMPILER_VERSION__
673
#include <fcntl.h>
674
#include <sys/time.h>
675
#endif
676

    
677
#define MG_NET_IF MG_NET_IF_SIMPLELINK
678
#define MG_SSL_IF MG_SSL_IF_SIMPLELINK
679

    
680
/* Only SPIFFS supports directories, SLFS does not. */
681
#if defined(CC3200_FS_SPIFFS) && !defined(MG_ENABLE_DIRECTORY_LISTING)
682
#define MG_ENABLE_DIRECTORY_LISTING 1
683
#endif
684

    
685
/* Amalgamated: #include "common/platforms/simplelink/cs_simplelink.h" */
686

    
687
typedef int sock_t;
688
#define INVALID_SOCKET (-1)
689
#define SIZE_T_FMT "u"
690
typedef struct stat cs_stat_t;
691
#define DIRSEP '/'
692
#define to64(x) strtoll(x, NULL, 10)
693
#define INT64_FMT PRId64
694
#define INT64_X_FMT PRIx64
695
#define __cdecl
696

    
697
#define fileno(x) -1
698

    
699
/* Some functions we implement for Mongoose. */
700

    
701
#ifdef __cplusplus
702
extern "C" {
703
#endif
704

    
705
#ifdef __TI_COMPILER_VERSION__
706
struct SlTimeval_t;
707
#define timeval SlTimeval_t
708
int gettimeofday(struct timeval *t, void *tz);
709
int settimeofday(const struct timeval *tv, const void *tz);
710

    
711
int asprintf(char **strp, const char *fmt, ...);
712

    
713
#endif
714

    
715
/* TI's libc does not have stat & friends, add them. */
716
#ifdef __TI_COMPILER_VERSION__
717

    
718
#include <file.h>
719

    
720
typedef unsigned int mode_t;
721
typedef size_t _off_t;
722
typedef long ssize_t;
723

    
724
struct stat {
725
  int st_ino;
726
  mode_t st_mode;
727
  int st_nlink;
728
  time_t st_mtime;
729
  off_t st_size;
730
};
731

    
732
int _stat(const char *pathname, struct stat *st);
733
int stat(const char *pathname, struct stat *st);
734

    
735
#define __S_IFMT 0170000
736

    
737
#define __S_IFDIR 0040000
738
#define __S_IFCHR 0020000
739
#define __S_IFREG 0100000
740

    
741
#define __S_ISTYPE(mode, mask) (((mode) &__S_IFMT) == (mask))
742

    
743
#define S_IFDIR __S_IFDIR
744
#define S_IFCHR __S_IFCHR
745
#define S_IFREG __S_IFREG
746
#define S_ISDIR(mode) __S_ISTYPE((mode), __S_IFDIR)
747
#define S_ISREG(mode) __S_ISTYPE((mode), __S_IFREG)
748

    
749
/* 5.x series compilers don't have va_copy, 16.x do. */
750
#if __TI_COMPILER_VERSION__ < 16000000
751
#define va_copy(apc, ap) ((apc) = (ap))
752
#endif
753

    
754
#endif /* __TI_COMPILER_VERSION__ */
755

    
756
#ifdef CC3200_FS_SLFS
757
#define MG_FS_SLFS
758
#endif
759

    
760
#if (defined(CC3200_FS_SPIFFS) || defined(CC3200_FS_SLFS)) && \
761
    !defined(MG_ENABLE_FILESYSTEM)
762
#define MG_ENABLE_FILESYSTEM 1
763
#define CS_DEFINE_DIRENT
764
#endif
765

    
766
#ifndef CS_ENABLE_STDIO
767
#define CS_ENABLE_STDIO 1
768
#endif
769

    
770
#ifdef __cplusplus
771
}
772
#endif
773

    
774
#endif /* CS_PLATFORM == CS_P_CC3200 */
775
#endif /* CS_COMMON_PLATFORMS_PLATFORM_CC3200_H_ */
776
#ifdef MG_MODULE_LINES
777
#line 1 "common/platforms/platform_msp432.h"
778
#endif
779
/*
780
 * Copyright (c) 2014-2016 Cesanta Software Limited
781
 * All rights reserved
782
 */
783

    
784
#ifndef CS_COMMON_PLATFORMS_PLATFORM_MSP432_H_
785
#define CS_COMMON_PLATFORMS_PLATFORM_MSP432_H_
786
#if CS_PLATFORM == CS_P_MSP432
787

    
788
#include <assert.h>
789
#include <ctype.h>
790
#include <errno.h>
791
#include <inttypes.h>
792
#include <stdint.h>
793
#include <string.h>
794
#include <time.h>
795

    
796
#ifndef __TI_COMPILER_VERSION__
797
#include <fcntl.h>
798
#include <sys/time.h>
799
#endif
800

    
801
#define MG_NET_IF MG_NET_IF_SIMPLELINK
802
#define MG_SSL_IF MG_SSL_IF_SIMPLELINK
803

    
804
/* Amalgamated: #include "common/platforms/simplelink/cs_simplelink.h" */
805

    
806
typedef int sock_t;
807
#define INVALID_SOCKET (-1)
808
#define SIZE_T_FMT "u"
809
typedef struct stat cs_stat_t;
810
#define DIRSEP '/'
811
#define to64(x) strtoll(x, NULL, 10)
812
#define INT64_FMT PRId64
813
#define INT64_X_FMT PRIx64
814
#define __cdecl
815

    
816
#define fileno(x) -1
817

    
818
/* Some functions we implement for Mongoose. */
819

    
820
#ifdef __cplusplus
821
extern "C" {
822
#endif
823

    
824
#ifdef __TI_COMPILER_VERSION__
825
struct SlTimeval_t;
826
#define timeval SlTimeval_t
827
int gettimeofday(struct timeval *t, void *tz);
828
#endif
829

    
830
/* TI's libc does not have stat & friends, add them. */
831
#ifdef __TI_COMPILER_VERSION__
832

    
833
#include <file.h>
834

    
835
typedef unsigned int mode_t;
836
typedef size_t _off_t;
837
typedef long ssize_t;
838

    
839
struct stat {
840
  int st_ino;
841
  mode_t st_mode;
842
  int st_nlink;
843
  time_t st_mtime;
844
  off_t st_size;
845
};
846

    
847
int _stat(const char *pathname, struct stat *st);
848
#define stat(a, b) _stat(a, b)
849

    
850
#define __S_IFMT 0170000
851

    
852
#define __S_IFDIR 0040000
853
#define __S_IFCHR 0020000
854
#define __S_IFREG 0100000
855

    
856
#define __S_ISTYPE(mode, mask) (((mode) &__S_IFMT) == (mask))
857

    
858
#define S_IFDIR __S_IFDIR
859
#define S_IFCHR __S_IFCHR
860
#define S_IFREG __S_IFREG
861
#define S_ISDIR(mode) __S_ISTYPE((mode), __S_IFDIR)
862
#define S_ISREG(mode) __S_ISTYPE((mode), __S_IFREG)
863

    
864
/* As of 5.2.7, TI compiler does not support va_copy() yet. */
865
#define va_copy(apc, ap) ((apc) = (ap))
866

    
867
#endif /* __TI_COMPILER_VERSION__ */
868

    
869
#ifndef CS_ENABLE_STDIO
870
#define CS_ENABLE_STDIO 1
871
#endif
872

    
873
#if (defined(CC3200_FS_SPIFFS) || defined(CC3200_FS_SLFS)) && \
874
    !defined(MG_ENABLE_FILESYSTEM)
875
#define MG_ENABLE_FILESYSTEM 1
876
#endif
877

    
878
#ifdef __cplusplus
879
}
880
#endif
881

    
882
#endif /* CS_PLATFORM == CS_P_MSP432 */
883
#endif /* CS_COMMON_PLATFORMS_PLATFORM_MSP432_H_ */
884
#ifdef MG_MODULE_LINES
885
#line 1 "common/platforms/platform_tm4c129.h"
886
#endif
887
/*
888
 * Copyright (c) 2014-2016 Cesanta Software Limited
889
 * All rights reserved
890
 */
891

    
892
#ifndef CS_COMMON_PLATFORMS_PLATFORM_TM4C129_H_
893
#define CS_COMMON_PLATFORMS_PLATFORM_TM4C129_H_
894
#if CS_PLATFORM == CS_P_TM4C129
895

    
896
#include <assert.h>
897
#include <ctype.h>
898
#include <errno.h>
899
#include <inttypes.h>
900
#include <stdint.h>
901
#include <string.h>
902
#include <time.h>
903

    
904
#ifndef __TI_COMPILER_VERSION__
905
#include <fcntl.h>
906
#include <sys/time.h>
907
#endif
908

    
909
#define SIZE_T_FMT "u"
910
typedef struct stat cs_stat_t;
911
#define DIRSEP '/'
912
#define to64(x) strtoll(x, NULL, 10)
913
#define INT64_FMT PRId64
914
#define INT64_X_FMT PRIx64
915
#define __cdecl
916

    
917
#ifndef MG_NET_IF
918
#include <lwip/opt.h>
919
#if LWIP_SOCKET
920
#define MG_NET_IF MG_NET_IF_SOCKET
921
#else
922
#define MG_NET_IF MG_NET_IF_LWIP_LOW_LEVEL
923
#endif
924
#define MG_LWIP 1
925
#elif MG_NET_IF == MG_NET_IF_SIMPLELINK
926
/* Amalgamated: #include "common/platforms/simplelink/cs_simplelink.h" */
927
#endif
928

    
929
#ifndef CS_ENABLE_STDIO
930
#define CS_ENABLE_STDIO 1
931
#endif
932

    
933
#ifdef __TI_COMPILER_VERSION__
934
/* As of 5.2.8, TI compiler does not support va_copy() yet. */
935
#define va_copy(apc, ap) ((apc) = (ap))
936
#endif /* __TI_COMPILER_VERSION__ */
937

    
938
#ifdef __cplusplus
939
}
940
#endif
941

    
942
#endif /* CS_PLATFORM == CS_P_TM4C129 */
943
#endif /* CS_COMMON_PLATFORMS_PLATFORM_TM4C129_H_ */
944
#ifdef MG_MODULE_LINES
945
#line 1 "common/platforms/platform_mbed.h"
946
#endif
947
/*
948
 * Copyright (c) 2014-2016 Cesanta Software Limited
949
 * All rights reserved
950
 */
951

    
952
#ifndef CS_COMMON_PLATFORMS_PLATFORM_MBED_H_
953
#define CS_COMMON_PLATFORMS_PLATFORM_MBED_H_
954
#if CS_PLATFORM == CS_P_MBED
955

    
956
/*
957
 * mbed.h contains C++ code (e.g. templates), thus, it should be processed
958
 * only if included directly to startup file (ex: main.cpp)
959
 */
960
#ifdef __cplusplus
961
/* Amalgamated: #include "mbed.h" */
962
#endif /* __cplusplus */
963

    
964
#include <assert.h>
965
#include <ctype.h>
966
#include <errno.h>
967
#include <inttypes.h>
968
#include <stdint.h>
969
#include <string.h>
970
#include <time.h>
971
#include <sys/stat.h>
972
#include <sys/types.h>
973
#include <fcntl.h>
974
#include <stdio.h>
975

    
976
typedef struct stat cs_stat_t;
977
#define DIRSEP '/'
978

    
979
#ifndef CS_ENABLE_STDIO
980
#define CS_ENABLE_STDIO 1
981
#endif
982

    
983
/*
984
 * mbed can be compiled with the ARM compiler which
985
 * just doesn't come with a gettimeofday shim
986
 * because it's a BSD API and ARM targets embedded
987
 * non-unix platforms.
988
 */
989
#if defined(__ARMCC_VERSION) || defined(__ICCARM__)
990
#define _TIMEVAL_DEFINED
991
#define gettimeofday _gettimeofday
992

    
993
/* copied from GCC on ARM; for some reason useconds are signed */
994
typedef long suseconds_t; /* microseconds (signed) */
995
struct timeval {
996
  time_t tv_sec;       /* seconds */
997
  suseconds_t tv_usec; /* and microseconds */
998
};
999

    
1000
#endif
1001

    
1002
#if MG_NET_IF == MG_NET_IF_SIMPLELINK
1003

    
1004
#define MG_SIMPLELINK_NO_OSI 1
1005

    
1006
#include <simplelink.h>
1007

    
1008
typedef int sock_t;
1009
#define INVALID_SOCKET (-1)
1010

    
1011
#define to64(x) strtoll(x, NULL, 10)
1012
#define INT64_FMT PRId64
1013
#define INT64_X_FMT PRIx64
1014
#define SIZE_T_FMT "u"
1015

    
1016
#define SOMAXCONN 8
1017

    
1018
const char *inet_ntop(int af, const void *src, char *dst, socklen_t size);
1019
char *inet_ntoa(struct in_addr in);
1020
int inet_pton(int af, const char *src, void *dst);
1021
int inet_aton(const char *cp, struct in_addr *inp);
1022
in_addr_t inet_addr(const char *cp);
1023

    
1024
#endif /* MG_NET_IF == MG_NET_IF_SIMPLELINK */
1025

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

    
1039
#include <assert.h>
1040
#include <ctype.h>
1041
#include <inttypes.h>
1042
#include <stdint.h>
1043
#include <string.h>
1044
#include <time.h>
1045

    
1046
#define to64(x) strtoll(x, NULL, 10)
1047

    
1048
#define MG_NET_IF MG_NET_IF_LWIP_LOW_LEVEL
1049
#define MG_LWIP 1
1050
#define MG_ENABLE_IPV6 1
1051

    
1052
/*
1053
 * For ARM C Compiler, make lwip to export `struct timeval`; for other
1054
 * compilers, suppress it.
1055
 */
1056
#if !defined(__ARMCC_VERSION)
1057
#define LWIP_TIMEVAL_PRIVATE 0
1058
#else
1059
struct timeval;
1060
int gettimeofday(struct timeval *tp, void *tzp);
1061
#endif
1062

    
1063
#define INT64_FMT PRId64
1064
#define SIZE_T_FMT "u"
1065

    
1066
/*
1067
 * ARM C Compiler doesn't have strdup, so we provide it
1068
 */
1069
#define CS_ENABLE_STRDUP defined(__ARMCC_VERSION)
1070

    
1071
#endif /* CS_PLATFORM == CS_P_NRF51 */
1072
#endif /* CS_COMMON_PLATFORMS_PLATFORM_NRF51_H_ */
1073
#ifdef MG_MODULE_LINES
1074
#line 1 "common/platforms/platform_nrf52.h"
1075
#endif
1076
/*
1077
 * Copyright (c) 2014-2016 Cesanta Software Limited
1078
 * All rights reserved
1079
 */
1080
#ifndef CS_COMMON_PLATFORMS_PLATFORM_NRF52_H_
1081
#define CS_COMMON_PLATFORMS_PLATFORM_NRF52_H_
1082
#if CS_PLATFORM == CS_P_NRF52
1083

    
1084
#include <assert.h>
1085
#include <ctype.h>
1086
#include <errno.h>
1087
#include <inttypes.h>
1088
#include <stdbool.h>
1089
#include <stdint.h>
1090
#include <string.h>
1091
#include <time.h>
1092

    
1093
#define to64(x) strtoll(x, NULL, 10)
1094

    
1095
#define MG_NET_IF MG_NET_IF_LWIP_LOW_LEVEL
1096
#define MG_LWIP 1
1097
#define MG_ENABLE_IPV6 1
1098

    
1099
#if !defined(ENOSPC)
1100
#define ENOSPC 28 /* No space left on device */
1101
#endif
1102

    
1103
/*
1104
 * For ARM C Compiler, make lwip to export `struct timeval`; for other
1105
 * compilers, suppress it.
1106
 */
1107
#if !defined(__ARMCC_VERSION)
1108
#define LWIP_TIMEVAL_PRIVATE 0
1109
#endif
1110

    
1111
#define INT64_FMT PRId64
1112
#define SIZE_T_FMT "u"
1113

    
1114
/*
1115
 * ARM C Compiler doesn't have strdup, so we provide it
1116
 */
1117
#define CS_ENABLE_STRDUP defined(__ARMCC_VERSION)
1118

    
1119
#endif /* CS_PLATFORM == CS_P_NRF52 */
1120
#endif /* CS_COMMON_PLATFORMS_PLATFORM_NRF52_H_ */
1121
#ifdef MG_MODULE_LINES
1122
#line 1 "common/platforms/simplelink/cs_simplelink.h"
1123
#endif
1124
/*
1125
 * Copyright (c) 2014-2016 Cesanta Software Limited
1126
 * All rights reserved
1127
 */
1128

    
1129
#ifndef CS_COMMON_PLATFORMS_SIMPLELINK_CS_SIMPLELINK_H_
1130
#define CS_COMMON_PLATFORMS_SIMPLELINK_CS_SIMPLELINK_H_
1131

    
1132
#if defined(MG_NET_IF) && MG_NET_IF == MG_NET_IF_SIMPLELINK
1133

    
1134
/* If simplelink.h is already included, all bets are off. */
1135
#if !defined(__SIMPLELINK_H__)
1136

    
1137
#include <stdbool.h>
1138

    
1139
#ifndef __TI_COMPILER_VERSION__
1140
#undef __CONCAT
1141
#undef FD_CLR
1142
#undef FD_ISSET
1143
#undef FD_SET
1144
#undef FD_SETSIZE
1145
#undef FD_ZERO
1146
#undef fd_set
1147
#endif
1148

    
1149
#if CS_PLATFORM == CS_P_CC3220
1150
#include <ti/drivers/net/wifi/porting/user.h>
1151
#include <ti/drivers/net/wifi/simplelink.h>
1152
#include <ti/drivers/net/wifi/sl_socket.h>
1153
#include <ti/drivers/net/wifi/netapp.h>
1154
#else
1155
/* We want to disable SL_INC_STD_BSD_API_NAMING, so we include user.h ourselves
1156
 * and undef it. */
1157
#define PROVISIONING_API_H_
1158
#include <simplelink/user.h>
1159
#undef PROVISIONING_API_H_
1160
#undef SL_INC_STD_BSD_API_NAMING
1161

    
1162
#include <simplelink/include/simplelink.h>
1163
#include <simplelink/include/netapp.h>
1164
#endif /* CS_PLATFORM == CS_P_CC3220 */
1165

    
1166
/* Now define only the subset of the BSD API that we use.
1167
 * Notably, close(), read() and write() are not defined. */
1168
#define AF_INET SL_AF_INET
1169

    
1170
#define socklen_t SlSocklen_t
1171
#define sockaddr SlSockAddr_t
1172
#define sockaddr_in SlSockAddrIn_t
1173
#define in_addr SlInAddr_t
1174

    
1175
#define SOCK_STREAM SL_SOCK_STREAM
1176
#define SOCK_DGRAM SL_SOCK_DGRAM
1177

    
1178
#define htonl sl_Htonl
1179
#define ntohl sl_Ntohl
1180
#define htons sl_Htons
1181
#define ntohs sl_Ntohs
1182

    
1183
#ifndef EACCES
1184
#define EACCES SL_EACCES
1185
#endif
1186
#ifndef EAFNOSUPPORT
1187
#define EAFNOSUPPORT SL_EAFNOSUPPORT
1188
#endif
1189
#ifndef EAGAIN
1190
#define EAGAIN SL_EAGAIN
1191
#endif
1192
#ifndef EBADF
1193
#define EBADF SL_EBADF
1194
#endif
1195
#ifndef EINVAL
1196
#define EINVAL SL_EINVAL
1197
#endif
1198
#ifndef ENOMEM
1199
#define ENOMEM SL_ENOMEM
1200
#endif
1201
#ifndef EWOULDBLOCK
1202
#define EWOULDBLOCK SL_EWOULDBLOCK
1203
#endif
1204

    
1205
#define SOMAXCONN 8
1206

    
1207
#ifdef __cplusplus
1208
extern "C" {
1209
#endif
1210

    
1211
const char *inet_ntop(int af, const void *src, char *dst, socklen_t size);
1212
char *inet_ntoa(struct in_addr in);
1213
int inet_pton(int af, const char *src, void *dst);
1214

    
1215
struct mg_mgr;
1216
struct mg_connection;
1217

    
1218
typedef void (*mg_init_cb)(struct mg_mgr *mgr);
1219
bool mg_start_task(int priority, int stack_size, mg_init_cb mg_init);
1220

    
1221
void mg_run_in_task(void (*cb)(struct mg_mgr *mgr, void *arg), void *cb_arg);
1222

    
1223
int sl_fs_init(void);
1224

    
1225
void sl_restart_cb(struct mg_mgr *mgr);
1226

    
1227
int sl_set_ssl_opts(int sock, struct mg_connection *nc);
1228

    
1229
#ifdef __cplusplus
1230
}
1231
#endif
1232

    
1233
#endif /* !defined(__SIMPLELINK_H__) */
1234

    
1235
/* Compatibility with older versions of SimpleLink */
1236
#if SL_MAJOR_VERSION_NUM < 2
1237

    
1238
#define SL_ERROR_BSD_EAGAIN SL_EAGAIN
1239
#define SL_ERROR_BSD_EALREADY SL_EALREADY
1240
#define SL_ERROR_BSD_ENOPROTOOPT SL_ENOPROTOOPT
1241
#define SL_ERROR_BSD_ESECDATEERROR SL_ESECDATEERROR
1242
#define SL_ERROR_BSD_ESECSNOVERIFY SL_ESECSNOVERIFY
1243
#define SL_ERROR_FS_FAILED_TO_ALLOCATE_MEM SL_FS_ERR_FAILED_TO_ALLOCATE_MEM
1244
#define SL_ERROR_FS_FILE_HAS_NOT_BEEN_CLOSE_CORRECTLY \
1245
  SL_FS_FILE_HAS_NOT_BEEN_CLOSE_CORRECTLY
1246
#define SL_ERROR_FS_FILE_NAME_EXIST SL_FS_FILE_NAME_EXIST
1247
#define SL_ERROR_FS_FILE_NOT_EXISTS SL_FS_ERR_FILE_NOT_EXISTS
1248
#define SL_ERROR_FS_NO_AVAILABLE_NV_INDEX SL_FS_ERR_NO_AVAILABLE_NV_INDEX
1249
#define SL_ERROR_FS_NOT_ENOUGH_STORAGE_SPACE SL_FS_ERR_NO_AVAILABLE_BLOCKS
1250
#define SL_ERROR_FS_NOT_SUPPORTED SL_FS_ERR_NOT_SUPPORTED
1251
#define SL_ERROR_FS_WRONG_FILE_NAME SL_FS_WRONG_FILE_NAME
1252
#define SL_ERROR_FS_INVALID_HANDLE SL_FS_ERR_INVALID_HANDLE
1253
#define SL_NETCFG_MAC_ADDRESS_GET SL_MAC_ADDRESS_GET
1254
#define SL_SOCKET_FD_ZERO SL_FD_ZERO
1255
#define SL_SOCKET_FD_SET SL_FD_SET
1256
#define SL_SOCKET_FD_ISSET SL_FD_ISSET
1257
#define SL_SO_SECURE_DOMAIN_NAME_VERIFICATION SO_SECURE_DOMAIN_NAME_VERIFICATION
1258

    
1259
#define SL_FS_READ FS_MODE_OPEN_READ
1260
#define SL_FS_WRITE FS_MODE_OPEN_WRITE
1261

    
1262
#define SL_FI_FILE_SIZE(fi) ((fi).FileLen)
1263
#define SL_FI_FILE_MAX_SIZE(fi) ((fi).AllocatedLen)
1264

    
1265
#define SlDeviceVersion_t SlVersionFull
1266
#define sl_DeviceGet sl_DevGet
1267
#define SL_DEVICE_GENERAL SL_DEVICE_GENERAL_CONFIGURATION
1268
#define SL_LEN_TYPE _u8
1269
#define SL_OPT_TYPE _u8
1270

    
1271
#else /* SL_MAJOR_VERSION_NUM >= 2 */
1272

    
1273
#define FS_MODE_OPEN_CREATE(max_size, flag) \
1274
  (SL_FS_CREATE | SL_FS_CREATE_MAX_SIZE(max_size))
1275
#define SL_FI_FILE_SIZE(fi) ((fi).Len)
1276
#define SL_FI_FILE_MAX_SIZE(fi) ((fi).MaxSize)
1277

    
1278
#define SL_LEN_TYPE _u16
1279
#define SL_OPT_TYPE _u16
1280

    
1281
#endif /* SL_MAJOR_VERSION_NUM < 2 */
1282

    
1283
int slfs_open(const unsigned char *fname, uint32_t flags);
1284

    
1285
#endif /* MG_NET_IF == MG_NET_IF_SIMPLELINK */
1286

    
1287
#endif /* CS_COMMON_PLATFORMS_SIMPLELINK_CS_SIMPLELINK_H_ */
1288
#ifdef MG_MODULE_LINES
1289
#line 1 "common/platforms/platform_wince.h"
1290
#endif
1291
#ifndef CS_COMMON_PLATFORMS_PLATFORM_WINCE_H_
1292
#define CS_COMMON_PLATFORMS_PLATFORM_WINCE_H_
1293

    
1294
#if CS_PLATFORM == CS_P_WINCE
1295

    
1296
/*
1297
 * MSVC++ 14.0 _MSC_VER == 1900 (Visual Studio 2015)
1298
 * MSVC++ 12.0 _MSC_VER == 1800 (Visual Studio 2013)
1299
 * MSVC++ 11.0 _MSC_VER == 1700 (Visual Studio 2012)
1300
 * MSVC++ 10.0 _MSC_VER == 1600 (Visual Studio 2010)
1301
 * MSVC++ 9.0  _MSC_VER == 1500 (Visual Studio 2008)
1302
 * MSVC++ 8.0  _MSC_VER == 1400 (Visual Studio 2005)
1303
 * MSVC++ 7.1  _MSC_VER == 1310 (Visual Studio 2003)
1304
 * MSVC++ 7.0  _MSC_VER == 1300
1305
 * MSVC++ 6.0  _MSC_VER == 1200
1306
 * MSVC++ 5.0  _MSC_VER == 1100
1307
 */
1308
#pragma warning(disable : 4127) /* FD_SET() emits warning, disable it */
1309
#pragma warning(disable : 4204) /* missing c99 support */
1310

    
1311
#ifndef _WINSOCK_DEPRECATED_NO_WARNINGS
1312
#define _WINSOCK_DEPRECATED_NO_WARNINGS 1
1313
#endif
1314

    
1315
#ifndef _CRT_SECURE_NO_WARNINGS
1316
#define _CRT_SECURE_NO_WARNINGS
1317
#endif
1318

    
1319
#include <assert.h>
1320
#include <limits.h>
1321
#include <stddef.h>
1322
#include <stdio.h>
1323
#include <stdlib.h>
1324
#include <time.h>
1325

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

    
1328
#include <winsock2.h>
1329
#include <ws2tcpip.h>
1330
#include <windows.h>
1331

    
1332
#define strdup _strdup
1333

    
1334
#ifndef EINPROGRESS
1335
#define EINPROGRESS WSAEINPROGRESS
1336
#endif
1337

    
1338
#ifndef EWOULDBLOCK
1339
#define EWOULDBLOCK WSAEWOULDBLOCK
1340
#endif
1341

    
1342
#ifndef EAGAIN
1343
#define EAGAIN EWOULDBLOCK
1344
#endif
1345

    
1346
#ifndef __func__
1347
#define STRX(x) #x
1348
#define STR(x) STRX(x)
1349
#define __func__ __FILE__ ":" STR(__LINE__)
1350
#endif
1351

    
1352
#define snprintf _snprintf
1353
#define fileno _fileno
1354
#define vsnprintf _vsnprintf
1355
#define sleep(x) Sleep((x) *1000)
1356
#define to64(x) _atoi64(x)
1357
#define rmdir _rmdir
1358

    
1359
#if defined(_MSC_VER) && _MSC_VER >= 1400
1360
#define fseeko(x, y, z) _fseeki64((x), (y), (z))
1361
#else
1362
#define fseeko(x, y, z) fseek((x), (y), (z))
1363
#endif
1364

    
1365
typedef int socklen_t;
1366

    
1367
#if _MSC_VER >= 1700
1368
#include <stdint.h>
1369
#else
1370
typedef signed char int8_t;
1371
typedef unsigned char uint8_t;
1372
typedef int int32_t;
1373
typedef unsigned int uint32_t;
1374
typedef short int16_t;
1375
typedef unsigned short uint16_t;
1376
typedef __int64 int64_t;
1377
typedef unsigned __int64 uint64_t;
1378
#endif
1379

    
1380
typedef SOCKET sock_t;
1381
typedef uint32_t in_addr_t;
1382

    
1383
#ifndef UINT16_MAX
1384
#define UINT16_MAX 65535
1385
#endif
1386

    
1387
#ifndef UINT32_MAX
1388
#define UINT32_MAX 4294967295
1389
#endif
1390

    
1391
#ifndef pid_t
1392
#define pid_t HANDLE
1393
#endif
1394

    
1395
#define INT64_FMT "I64d"
1396
#define INT64_X_FMT "I64x"
1397
/* TODO(alashkin): check if this is correct */
1398
#define SIZE_T_FMT "u"
1399

    
1400
#define DIRSEP '\\'
1401
#define CS_DEFINE_DIRENT
1402

    
1403
#ifndef va_copy
1404
#ifdef __va_copy
1405
#define va_copy __va_copy
1406
#else
1407
#define va_copy(x, y) (x) = (y)
1408
#endif
1409
#endif
1410

    
1411
#ifndef MG_MAX_HTTP_REQUEST_SIZE
1412
#define MG_MAX_HTTP_REQUEST_SIZE 8192
1413
#endif
1414

    
1415
#ifndef MG_MAX_HTTP_SEND_MBUF
1416
#define MG_MAX_HTTP_SEND_MBUF 4096
1417
#endif
1418

    
1419
#ifndef MG_MAX_HTTP_HEADERS
1420
#define MG_MAX_HTTP_HEADERS 40
1421
#endif
1422

    
1423
#ifndef CS_ENABLE_STDIO
1424
#define CS_ENABLE_STDIO 1
1425
#endif
1426

    
1427
#define abort() DebugBreak();
1428

    
1429
#ifndef BUFSIZ
1430
#define BUFSIZ 4096
1431
#endif
1432
/*
1433
 * Explicitly disabling MG_ENABLE_THREADS for WinCE
1434
 * because they are enabled for _WIN32 by default
1435
 */
1436
#ifndef MG_ENABLE_THREADS
1437
#define MG_ENABLE_THREADS 0
1438
#endif
1439

    
1440
#ifndef MG_ENABLE_FILESYSTEM
1441
#define MG_ENABLE_FILESYSTEM 1
1442
#endif
1443

    
1444
#ifndef MG_NET_IF
1445
#define MG_NET_IF MG_NET_IF_SOCKET
1446
#endif
1447

    
1448
typedef struct _stati64 {
1449
  uint32_t st_mtime;
1450
  uint32_t st_size;
1451
  uint32_t st_mode;
1452
} cs_stat_t;
1453

    
1454
/*
1455
 * WinCE 6.0 has a lot of useful definitions in ATL (not windows.h) headers
1456
 * use #ifdefs to avoid conflicts
1457
 */
1458

    
1459
#ifndef ENOENT
1460
#define ENOENT ERROR_PATH_NOT_FOUND
1461
#endif
1462

    
1463
#ifndef EACCES
1464
#define EACCES ERROR_ACCESS_DENIED
1465
#endif
1466

    
1467
#ifndef ENOMEM
1468
#define ENOMEM ERROR_NOT_ENOUGH_MEMORY
1469
#endif
1470

    
1471
#ifndef _UINTPTR_T_DEFINED
1472
typedef unsigned int *uintptr_t;
1473
#endif
1474

    
1475
#define _S_IFREG 2
1476
#define _S_IFDIR 4
1477

    
1478
#ifndef S_ISDIR
1479
#define S_ISDIR(x) (((x) &_S_IFDIR) != 0)
1480
#endif
1481

    
1482
#ifndef S_ISREG
1483
#define S_ISREG(x) (((x) &_S_IFREG) != 0)
1484
#endif
1485

    
1486
int open(const char *filename, int oflag, int pmode);
1487
int _wstati64(const wchar_t *path, cs_stat_t *st);
1488
const char *strerror();
1489

    
1490
#endif /* CS_PLATFORM == CS_P_WINCE */
1491
#endif /* CS_COMMON_PLATFORMS_PLATFORM_WINCE_H_ */
1492
#ifdef MG_MODULE_LINES
1493
#line 1 "common/platforms/platform_nxp_lpc.h"
1494
#endif
1495
/*
1496
 * Copyright (c) 2014-2016 Cesanta Software Limited
1497
 * All rights reserved
1498
 */
1499

    
1500
#ifndef CS_COMMON_PLATFORMS_PLATFORM_NXP_LPC_H_
1501
#define CS_COMMON_PLATFORMS_PLATFORM_NXP_LPC_H_
1502

    
1503
#if CS_PLATFORM == CS_P_NXP_LPC
1504

    
1505
#include <ctype.h>
1506
#include <stdint.h>
1507
#include <string.h>
1508

    
1509
#define SIZE_T_FMT "u"
1510
typedef struct stat cs_stat_t;
1511
#define INT64_FMT "lld"
1512
#define INT64_X_FMT "llx"
1513
#define __cdecl
1514

    
1515
#define MG_LWIP 1
1516

    
1517
#define MG_NET_IF MG_NET_IF_LWIP_LOW_LEVEL
1518

    
1519
/*
1520
 * LPCXpress comes with 3 C library implementations: Newlib, NewlibNano and
1521
 *Redlib.
1522
 * See https://community.nxp.com/message/630860 for more details.
1523
 *
1524
 * Redlib is the default and lacks certain things, so we provide them.
1525
 */
1526
#ifdef __REDLIB_INTERFACE_VERSION__
1527

    
1528
/* Let LWIP define timeval for us. */
1529
#define LWIP_TIMEVAL_PRIVATE 1
1530

    
1531
#define va_copy(d, s) __builtin_va_copy(d, s)
1532

    
1533
#define CS_ENABLE_TO64 1
1534
#define to64(x) cs_to64(x)
1535

    
1536
#define CS_ENABLE_STRDUP 1
1537

    
1538
#else
1539

    
1540
#include <sys/time.h>
1541
#define LWIP_TIMEVAL_PRIVATE 0
1542
#define to64(x) strtoll(x, NULL, 10)
1543

    
1544
#endif
1545

    
1546
#endif /* CS_PLATFORM == CS_P_NXP_LPC */
1547
#endif /* CS_COMMON_PLATFORMS_PLATFORM_NXP_LPC_H_ */
1548
#ifdef MG_MODULE_LINES
1549
#line 1 "common/platforms/platform_nxp_kinetis.h"
1550
#endif
1551
/*
1552
 * Copyright (c) 2014-2016 Cesanta Software Limited
1553
 * All rights reserved
1554
 */
1555

    
1556
#ifndef CS_COMMON_PLATFORMS_PLATFORM_NXP_KINETIS_H_
1557
#define CS_COMMON_PLATFORMS_PLATFORM_NXP_KINETIS_H_
1558

    
1559
#if CS_PLATFORM == CS_P_NXP_KINETIS
1560

    
1561
#include <ctype.h>
1562
#include <inttypes.h>
1563
#include <string.h>
1564
#include <sys/time.h>
1565

    
1566
#define SIZE_T_FMT "u"
1567
typedef struct stat cs_stat_t;
1568
#define to64(x) strtoll(x, NULL, 10)
1569
#define INT64_FMT "lld"
1570
#define INT64_X_FMT "llx"
1571
#define __cdecl
1572

    
1573
#define MG_LWIP 1
1574

    
1575
#define MG_NET_IF MG_NET_IF_LWIP_LOW_LEVEL
1576

    
1577
/* struct timeval is defined in sys/time.h. */
1578
#define LWIP_TIMEVAL_PRIVATE 0
1579

    
1580
#endif /* CS_PLATFORM == CS_P_NXP_KINETIS */
1581
#endif /* CS_COMMON_PLATFORMS_PLATFORM_NXP_KINETIS_H_ */
1582
#ifdef MG_MODULE_LINES
1583
#line 1 "common/platforms/platform_pic32.h"
1584
#endif
1585
/*
1586
 * Copyright (c) 2014-2016 Cesanta Software Limited
1587
 * All rights reserved
1588
 */
1589

    
1590
#ifndef CS_COMMON_PLATFORMS_PLATFORM_PIC32_H_
1591
#define CS_COMMON_PLATFORMS_PLATFORM_PIC32_H_
1592

    
1593
#if CS_PLATFORM == CS_P_PIC32
1594

    
1595
#define MG_NET_IF MG_NET_IF_PIC32
1596

    
1597
#include <stdint.h>
1598
#include <time.h>
1599
#include <ctype.h>
1600
#include <stdlib.h>
1601

    
1602
#include <system_config.h>
1603
#include <system_definitions.h>
1604

    
1605
#include <sys/types.h>
1606

    
1607
typedef TCP_SOCKET sock_t;
1608
#define to64(x) strtoll(x, NULL, 10)
1609

    
1610
#define SIZE_T_FMT "lu"
1611
#define INT64_FMT "lld"
1612

    
1613
#ifndef CS_ENABLE_STDIO
1614
#define CS_ENABLE_STDIO 1
1615
#endif
1616

    
1617
char *inet_ntoa(struct in_addr in);
1618

    
1619
#endif /* CS_PLATFORM == CS_P_PIC32 */
1620

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

    
1630
#ifndef CS_COMMON_PLATFORMS_PLATFORM_STM32_H_
1631
#define CS_COMMON_PLATFORMS_PLATFORM_STM32_H_
1632
#if CS_PLATFORM == CS_P_STM32
1633

    
1634
#include <ctype.h>
1635
#include <errno.h>
1636
#include <fcntl.h>
1637
#include <stdint.h>
1638
#include <stdio.h>
1639
#include <string.h>
1640
#include <sys/stat.h>
1641
#include <sys/time.h>
1642
#include <sys/types.h>
1643
#include <unistd.h>
1644
#include <dirent.h>
1645

    
1646
#include <stm32_sdk_hal.h>
1647

    
1648
#define to64(x) strtoll(x, NULL, 10)
1649
#define INT64_FMT PRId64
1650
#define SIZE_T_FMT "u"
1651
typedef struct stat cs_stat_t;
1652
#define DIRSEP '/'
1653

    
1654
#ifndef CS_ENABLE_STDIO
1655
#define CS_ENABLE_STDIO 1
1656
#endif
1657

    
1658
#ifndef MG_ENABLE_FILESYSTEM
1659
#define MG_ENABLE_FILESYSTEM 1
1660
#endif
1661

    
1662
#endif /* CS_PLATFORM == CS_P_STM32 */
1663
#endif /* CS_COMMON_PLATFORMS_PLATFORM_STM32_H_ */
1664
#ifdef MG_MODULE_LINES
1665
#line 1 "common/platforms/lwip/mg_lwip.h"
1666
#endif
1667
/*
1668
 * Copyright (c) 2014-2016 Cesanta Software Limited
1669
 * All rights reserved
1670
 */
1671

    
1672
#ifndef CS_COMMON_PLATFORMS_LWIP_MG_LWIP_H_
1673
#define CS_COMMON_PLATFORMS_LWIP_MG_LWIP_H_
1674

    
1675
#ifndef MG_LWIP
1676
#define MG_LWIP 0
1677
#endif
1678

    
1679
#if MG_LWIP
1680

    
1681
/*
1682
 * When compiling for nRF5x chips with arm-none-eabi-gcc, it has BYTE_ORDER
1683
 * already defined, so in order to avoid warnings in lwip, we have to undefine
1684
 * it.
1685
 *
1686
 * TODO: Check if in the future versions of nRF5 SDK that changes.
1687
 *       Current version of nRF51 SDK: 0.8.0
1688
 *                          nRF5 SDK:  0.9.0
1689
 */
1690
#if CS_PLATFORM == CS_P_NRF51 || CS_PLATFORM == CS_P_NRF52
1691
#undef BYTE_ORDER
1692
#endif
1693

    
1694
#include <lwip/opt.h>
1695
#include <lwip/err.h>
1696
#include <lwip/ip_addr.h>
1697
#include <lwip/inet.h>
1698
#include <lwip/netdb.h>
1699
#include <lwip/dns.h>
1700

    
1701
#ifndef LWIP_PROVIDE_ERRNO
1702
#include <errno.h>
1703
#endif
1704

    
1705
#if LWIP_SOCKET
1706
#include <lwip/sockets.h>
1707
#else
1708
/* We really need the definitions from sockets.h. */
1709
#undef LWIP_SOCKET
1710
#define LWIP_SOCKET 1
1711
#include <lwip/sockets.h>
1712
#undef LWIP_SOCKET
1713
#define LWIP_SOCKET 0
1714
#endif
1715

    
1716
#define INVALID_SOCKET (-1)
1717
#define SOMAXCONN 10
1718
typedef int sock_t;
1719

    
1720
#if MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL
1721
struct mg_mgr;
1722
struct mg_connection;
1723
uint32_t mg_lwip_get_poll_delay_ms(struct mg_mgr *mgr);
1724
void mg_lwip_set_keepalive_params(struct mg_connection *nc, int idle,
1725
                                  int interval, int count);
1726
#endif
1727

    
1728
/* For older version of LWIP */
1729
#ifndef ipX_2_ip
1730
#define ipX_2_ip(x) (x)
1731
#endif
1732

    
1733
#endif /* MG_LWIP */
1734

    
1735
#endif /* CS_COMMON_PLATFORMS_LWIP_MG_LWIP_H_ */
1736
#ifdef MG_MODULE_LINES
1737
#line 1 "common/cs_md5.h"
1738
#endif
1739
/*
1740
 * Copyright (c) 2014 Cesanta Software Limited
1741
 * All rights reserved
1742
 */
1743

    
1744
#ifndef CS_COMMON_MD5_H_
1745
#define CS_COMMON_MD5_H_
1746

    
1747
/* Amalgamated: #include "common/platform.h" */
1748

    
1749
#ifndef CS_DISABLE_MD5
1750
#define CS_DISABLE_MD5 0
1751
#endif
1752

    
1753
#ifdef __cplusplus
1754
extern "C" {
1755
#endif /* __cplusplus */
1756

    
1757
typedef struct {
1758
  uint32_t buf[4];
1759
  uint32_t bits[2];
1760
  unsigned char in[64];
1761
} cs_md5_ctx;
1762

    
1763
void cs_md5_init(cs_md5_ctx *c);
1764
void cs_md5_update(cs_md5_ctx *c, const unsigned char *data, size_t len);
1765
void cs_md5_final(unsigned char *md, cs_md5_ctx *c);
1766

    
1767
#ifdef __cplusplus
1768
}
1769
#endif /* __cplusplus */
1770

    
1771
#endif /* CS_COMMON_MD5_H_ */
1772
#ifdef MG_MODULE_LINES
1773
#line 1 "common/cs_sha1.h"
1774
#endif
1775
/*
1776
 * Copyright (c) 2014 Cesanta Software Limited
1777
 * All rights reserved
1778
 */
1779

    
1780
#ifndef CS_COMMON_SHA1_H_
1781
#define CS_COMMON_SHA1_H_
1782

    
1783
#ifndef CS_DISABLE_SHA1
1784
#define CS_DISABLE_SHA1 0
1785
#endif
1786

    
1787
#if !CS_DISABLE_SHA1
1788

    
1789
/* Amalgamated: #include "common/platform.h" */
1790

    
1791
#ifdef __cplusplus
1792
extern "C" {
1793
#endif /* __cplusplus */
1794

    
1795
typedef struct {
1796
  uint32_t state[5];
1797
  uint32_t count[2];
1798
  unsigned char buffer[64];
1799
} cs_sha1_ctx;
1800

    
1801
void cs_sha1_init(cs_sha1_ctx *);
1802
void cs_sha1_update(cs_sha1_ctx *, const unsigned char *data, uint32_t len);
1803
void cs_sha1_final(unsigned char digest[20], cs_sha1_ctx *);
1804
void cs_hmac_sha1(const unsigned char *key, size_t key_len,
1805
                  const unsigned char *text, size_t text_len,
1806
                  unsigned char out[20]);
1807
#ifdef __cplusplus
1808
}
1809
#endif /* __cplusplus */
1810

    
1811
#endif /* CS_DISABLE_SHA1 */
1812

    
1813
#endif /* CS_COMMON_SHA1_H_ */
1814
#ifdef MG_MODULE_LINES
1815
#line 1 "common/cs_time.h"
1816
#endif
1817
/*
1818
 * Copyright (c) 2014-2016 Cesanta Software Limited
1819
 * All rights reserved
1820
 */
1821

    
1822
#ifndef CS_COMMON_CS_TIME_H_
1823
#define CS_COMMON_CS_TIME_H_
1824

    
1825
#include <time.h>
1826

    
1827
/* Amalgamated: #include "common/platform.h" */
1828

    
1829
#ifdef __cplusplus
1830
extern "C" {
1831
#endif /* __cplusplus */
1832

    
1833
/* Sub-second granularity time(). */
1834
double cs_time(void);
1835

    
1836
/*
1837
 * Similar to (non-standard) timegm, converts broken-down time into the number
1838
 * of seconds since Unix Epoch.
1839
 */
1840
double cs_timegm(const struct tm *tm);
1841

    
1842
#ifdef __cplusplus
1843
}
1844
#endif /* __cplusplus */
1845

    
1846
#endif /* CS_COMMON_CS_TIME_H_ */
1847
#ifdef MG_MODULE_LINES
1848
#line 1 "common/mg_str.h"
1849
#endif
1850
/*
1851
 * Copyright (c) 2014-2016 Cesanta Software Limited
1852
 * All rights reserved
1853
 */
1854

    
1855
#ifndef CS_COMMON_MG_STR_H_
1856
#define CS_COMMON_MG_STR_H_
1857

    
1858
#include <stddef.h>
1859

    
1860
/* Amalgamated: #include "common/platform.h" */
1861

    
1862
#ifdef __cplusplus
1863
extern "C" {
1864
#endif
1865

    
1866
/* Describes chunk of memory */
1867
struct mg_str {
1868
  const char *p; /* Memory chunk pointer */
1869
  size_t len;    /* Memory chunk length */
1870
};
1871

    
1872
/*
1873
 * Helper function for creating mg_str struct from plain C string.
1874
 * `NULL` is allowed and becomes `{NULL, 0}`.
1875
 */
1876
struct mg_str mg_mk_str(const char *s);
1877

    
1878
/*
1879
 * Like `mg_mk_str`, but takes string length explicitly.
1880
 */
1881
struct mg_str mg_mk_str_n(const char *s, size_t len);
1882

    
1883
/* Macro for initializing mg_str. */
1884
#define MG_MK_STR(str_literal) \
1885
  { str_literal, sizeof(str_literal) - 1 }
1886
#define MG_NULL_STR \
1887
  { NULL, 0 }
1888

    
1889
/*
1890
 * Cross-platform version of `strcmp()` where where first string is
1891
 * specified by `struct mg_str`.
1892
 */
1893
int mg_vcmp(const struct mg_str *str2, const char *str1);
1894

    
1895
/*
1896
 * Cross-platform version of `strncasecmp()` where first string is
1897
 * specified by `struct mg_str`.
1898
 */
1899
int mg_vcasecmp(const struct mg_str *str2, const char *str1);
1900

    
1901
/* Creates a copy of s (heap-allocated). */
1902
struct mg_str mg_strdup(const struct mg_str s);
1903

    
1904
/*
1905
 * Creates a copy of s (heap-allocated).
1906
 * Resulting string is NUL-terminated (but NUL is not included in len).
1907
 */
1908
struct mg_str mg_strdup_nul(const struct mg_str s);
1909

    
1910
/*
1911
 * Locates character in a string.
1912
 */
1913
const char *mg_strchr(const struct mg_str s, int c);
1914

    
1915
/*
1916
 * Compare two `mg_str`s; return value is the same as `strcmp`.
1917
 */
1918
int mg_strcmp(const struct mg_str str1, const struct mg_str str2);
1919

    
1920
/*
1921
 * Like `mg_strcmp`, but compares at most `n` characters.
1922
 */
1923
int mg_strncmp(const struct mg_str str1, const struct mg_str str2, size_t n);
1924

    
1925
/*
1926
 * Finds the first occurrence of a substring `needle` in the `haystack`.
1927
 */
1928
const char *mg_strstr(const struct mg_str haystack, const struct mg_str needle);
1929

    
1930
#ifdef __cplusplus
1931
}
1932
#endif
1933

    
1934
#endif /* CS_COMMON_MG_STR_H_ */
1935
#ifdef MG_MODULE_LINES
1936
#line 1 "common/mbuf.h"
1937
#endif
1938
/*
1939
 * Copyright (c) 2015 Cesanta Software Limited
1940
 * All rights reserved
1941
 */
1942

    
1943
/*
1944
 * === Memory Buffers
1945
 *
1946
 * Mbufs are mutable/growing memory buffers, like C++ strings.
1947
 * Mbuf can append data to the end of a buffer or insert data into arbitrary
1948
 * position in the middle of a buffer. The buffer grows automatically when
1949
 * needed.
1950
 */
1951

    
1952
#ifndef CS_COMMON_MBUF_H_
1953
#define CS_COMMON_MBUF_H_
1954

    
1955
#include <stdlib.h>
1956
/* Amalgamated: #include "common/platform.h" */
1957

    
1958
#if defined(__cplusplus)
1959
extern "C" {
1960
#endif
1961

    
1962
#ifndef MBUF_SIZE_MULTIPLIER
1963
#define MBUF_SIZE_MULTIPLIER 1.5
1964
#endif
1965

    
1966
/* Memory buffer descriptor */
1967
struct mbuf {
1968
  char *buf;   /* Buffer pointer */
1969
  size_t len;  /* Data length. Data is located between offset 0 and len. */
1970
  size_t size; /* Buffer size allocated by realloc(1). Must be >= len */
1971
};
1972

    
1973
/*
1974
 * Initialises an Mbuf.
1975
 * `initial_capacity` specifies the initial capacity of the mbuf.
1976
 */
1977
void mbuf_init(struct mbuf *, size_t initial_capacity);
1978

    
1979
/* Frees the space allocated for the mbuffer and resets the mbuf structure. */
1980
void mbuf_free(struct mbuf *);
1981

    
1982
/*
1983
 * Appends data to the Mbuf.
1984
 *
1985
 * Returns the number of bytes appended or 0 if out of memory.
1986
 */
1987
size_t mbuf_append(struct mbuf *, const void *data, size_t data_size);
1988

    
1989
/*
1990
 * Inserts data at a specified offset in the Mbuf.
1991
 *
1992
 * Existing data will be shifted forwards and the buffer will
1993
 * be grown if necessary.
1994
 * Returns the number of bytes inserted.
1995
 */
1996
size_t mbuf_insert(struct mbuf *, size_t, const void *, size_t);
1997

    
1998
/* Removes `data_size` bytes from the beginning of the buffer. */
1999
void mbuf_remove(struct mbuf *, size_t data_size);
2000

    
2001
/*
2002
 * Resizes an Mbuf.
2003
 *
2004
 * If `new_size` is smaller than buffer's `len`, the
2005
 * resize is not performed.
2006
 */
2007
void mbuf_resize(struct mbuf *, size_t new_size);
2008

    
2009
/* Shrinks an Mbuf by resizing its `size` to `len`. */
2010
void mbuf_trim(struct mbuf *);
2011

    
2012
#if defined(__cplusplus)
2013
}
2014
#endif /* __cplusplus */
2015

    
2016
#endif /* CS_COMMON_MBUF_H_ */
2017
#ifdef MG_MODULE_LINES
2018
#line 1 "common/cs_base64.h"
2019
#endif
2020
/*
2021
 * Copyright (c) 2014 Cesanta Software Limited
2022
 * All rights reserved
2023
 */
2024

    
2025
#ifndef CS_COMMON_CS_BASE64_H_
2026
#define CS_COMMON_CS_BASE64_H_
2027

    
2028
#ifndef DISABLE_BASE64
2029
#define DISABLE_BASE64 0
2030
#endif
2031

    
2032
#if !DISABLE_BASE64
2033

    
2034
#include <stdio.h>
2035

    
2036
#ifdef __cplusplus
2037
extern "C" {
2038
#endif
2039

    
2040
typedef void (*cs_base64_putc_t)(char, void *);
2041

    
2042
struct cs_base64_ctx {
2043
  /* cannot call it putc because it's a macro on some environments */
2044
  cs_base64_putc_t b64_putc;
2045
  unsigned char chunk[3];
2046
  int chunk_size;
2047
  void *user_data;
2048
};
2049

    
2050
void cs_base64_init(struct cs_base64_ctx *ctx, cs_base64_putc_t putc,
2051
                    void *user_data);
2052
void cs_base64_update(struct cs_base64_ctx *ctx, const char *str, size_t len);
2053
void cs_base64_finish(struct cs_base64_ctx *ctx);
2054

    
2055
void cs_base64_encode(const unsigned char *src, int src_len, char *dst);
2056
void cs_fprint_base64(FILE *f, const unsigned char *src, int src_len);
2057
int cs_base64_decode(const unsigned char *s, int len, char *dst, int *dec_len);
2058

    
2059
#ifdef __cplusplus
2060
}
2061
#endif
2062

    
2063
#endif /* DISABLE_BASE64 */
2064

    
2065
#endif /* CS_COMMON_CS_BASE64_H_ */
2066
#ifdef MG_MODULE_LINES
2067
#line 1 "common/str_util.h"
2068
#endif
2069
/*
2070
 * Copyright (c) 2015 Cesanta Software Limited
2071
 * All rights reserved
2072
 */
2073

    
2074
#ifndef CS_COMMON_STR_UTIL_H_
2075
#define CS_COMMON_STR_UTIL_H_
2076

    
2077
#include <stdarg.h>
2078
#include <stdlib.h>
2079

    
2080
/* Amalgamated: #include "common/mg_str.h" */
2081
/* Amalgamated: #include "common/platform.h" */
2082

    
2083
#ifndef CS_ENABLE_STRDUP
2084
#define CS_ENABLE_STRDUP 0
2085
#endif
2086

    
2087
#ifndef CS_ENABLE_TO64
2088
#define CS_ENABLE_TO64 0
2089
#endif
2090

    
2091
/*
2092
 * Expands to a string representation of its argument: e.g.
2093
 * `CS_STRINGIFY_LIT(5) expands to "5"`
2094
 */
2095
#define CS_STRINGIFY_LIT(x) #x
2096

    
2097
/*
2098
 * Expands to a string representation of its argument, which is allowed
2099
 * to be a macro: e.g.
2100
 *
2101
 * #define FOO 123
2102
 * CS_STRINGIFY_MACRO(FOO)
2103
 *
2104
 * expands to 123.
2105
 */
2106
#define CS_STRINGIFY_MACRO(x) CS_STRINGIFY_LIT(x)
2107

    
2108
#ifdef __cplusplus
2109
extern "C" {
2110
#endif
2111

    
2112
/*
2113
 * Equivalent of standard `strnlen()`.
2114
 */
2115
size_t c_strnlen(const char *s, size_t maxlen);
2116

    
2117
/*
2118
 * Equivalent of standard `snprintf()`.
2119
 */
2120
int c_snprintf(char *buf, size_t buf_size, const char *format, ...);
2121

    
2122
/*
2123
 * Equivalent of standard `vsnprintf()`.
2124
 */
2125
int c_vsnprintf(char *buf, size_t buf_size, const char *format, va_list ap);
2126

    
2127
/*
2128
 * Find the first occurrence of find in s, where the search is limited to the
2129
 * first slen characters of s.
2130
 */
2131
const char *c_strnstr(const char *s, const char *find, size_t slen);
2132

    
2133
/*
2134
 * Stringify binary data. Output buffer size must be 2 * size_of_input + 1
2135
 * because each byte of input takes 2 bytes in string representation
2136
 * plus 1 byte for the terminating \0 character.
2137
 */
2138
void cs_to_hex(char *to, const unsigned char *p, size_t len);
2139

    
2140
/*
2141
 * Convert stringified binary data back to binary.
2142
 * Does the reverse of `cs_to_hex()`.
2143
 */
2144
void cs_from_hex(char *to, const char *p, size_t len);
2145

    
2146
#if CS_ENABLE_STRDUP
2147
/*
2148
 * Equivalent of standard `strdup()`, defined if only `CS_ENABLE_STRDUP` is 1.
2149
 */
2150
char *strdup(const char *src);
2151
#endif
2152

    
2153
#if CS_ENABLE_TO64
2154
#include <stdint.h>
2155
/*
2156
 * Simple string -> int64 conversion routine.
2157
 */
2158
int64_t cs_to64(const char *s);
2159
#endif
2160

    
2161
/*
2162
 * Cross-platform version of `strncasecmp()`.
2163
 */
2164
int mg_ncasecmp(const char *s1, const char *s2, size_t len);
2165

    
2166
/*
2167
 * Cross-platform version of `strcasecmp()`.
2168
 */
2169
int mg_casecmp(const char *s1, const char *s2);
2170

    
2171
/*
2172
 * Prints message to the buffer. If the buffer is large enough to hold the
2173
 * message, it returns buffer. If buffer is to small, it allocates a large
2174
 * enough buffer on heap and returns allocated buffer.
2175
 * This is a supposed use case:
2176
 *
2177
 * ```c
2178
 *    char buf[5], *p = buf;
2179
 *    mg_avprintf(&p, sizeof(buf), "%s", "hi there");
2180
 *    use_p_somehow(p);
2181
 *    if (p != buf) {
2182
 *      free(p);
2183
 *    }
2184
 * ```
2185
 *
2186
 * The purpose of this is to avoid malloc-ing if generated strings are small.
2187
 */
2188
int mg_asprintf(char **buf, size_t size, const char *fmt, ...);
2189

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

    
2193
/*
2194
 * A helper function for traversing a comma separated list of values.
2195
 * It returns a list pointer shifted to the next value or NULL if the end
2196
 * of the list found.
2197
 * The value is stored in a val vector. If the value has a form "x=y", then
2198
 * eq_val vector is initialised to point to the "y" part, and val vector length
2199
 * is adjusted to point only to "x".
2200
 * If the list is just a comma separated list of entries, like "aa,bb,cc" then
2201
 * `eq_val` will contain zero-length string.
2202
 *
2203
 * The purpose of this function is to parse comma separated string without
2204
 * any copying/memory allocation.
2205
 */
2206
const char *mg_next_comma_list_entry(const char *list, struct mg_str *val,
2207
                                     struct mg_str *eq_val);
2208

    
2209
/*
2210
 * Like `mg_next_comma_list_entry()`, but takes `list` as `struct mg_str`.
2211
 */
2212
struct mg_str mg_next_comma_list_entry_n(struct mg_str list, struct mg_str *val,
2213
                                         struct mg_str *eq_val);
2214

    
2215
/*
2216
 * Matches 0-terminated string (mg_match_prefix) or string with given length
2217
 * mg_match_prefix_n against a glob pattern. Glob syntax:
2218
 * ```
2219
 * - * matches zero or more characters until a slash character /
2220
 * - ** matches zero or more characters
2221
 * - ? Matches exactly one character which is not a slash /
2222
 * - | or ,  divides alternative patterns
2223
 * - any other character matches itself
2224
 * ```
2225
 * Match is case-insensitive. Return number of bytes matched.
2226
 * Examples:
2227
 * ```
2228
 * mg_match_prefix("a*f", len, "abcdefgh") == 6
2229
 * mg_match_prefix("a*f", len, "abcdexgh") == 0
2230
 * mg_match_prefix("a*f|de*,xy", len, "defgh") == 5
2231
 * mg_match_prefix("?*", len, "abc") == 3
2232
 * mg_match_prefix("?*", len, "") == 0
2233
 * ```
2234
 */
2235
size_t mg_match_prefix(const char *pattern, int pattern_len, const char *str);
2236

    
2237
/*
2238
 * Like `mg_match_prefix()`, but takes `pattern` and `str` as `struct mg_str`.
2239
 */
2240
size_t mg_match_prefix_n(const struct mg_str pattern, const struct mg_str str);
2241

    
2242
#ifdef __cplusplus
2243
}
2244
#endif
2245

    
2246
#endif /* CS_COMMON_STR_UTIL_H_ */
2247
#ifdef MG_MODULE_LINES
2248
#line 1 "common/queue.h"
2249
#endif
2250
/* clang-format off */
2251
/*-
2252
 * Copyright (c) 1991, 1993
2253
 *	The Regents of the University of California.  All rights reserved.
2254
 *
2255
 * Redistribution and use in source and binary forms, with or without
2256
 * modification, are permitted provided that the following conditions
2257
 * are met:
2258
 * 1. Redistributions of source code must retain the above copyright
2259
 *    notice, this list of conditions and the following disclaimer.
2260
 * 2. Redistributions in binary form must reproduce the above copyright
2261
 *    notice, this list of conditions and the following disclaimer in the
2262
 *    documentation and/or other materials provided with the distribution.
2263
 * 4. Neither the name of the University nor the names of its contributors
2264
 *    may be used to endorse or promote products derived from this software
2265
 *    without specific prior written permission.
2266
 *
2267
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
2268
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
2269
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
2270
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
2271
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2272
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
2273
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
2274
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
2275
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
2276
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
2277
 * SUCH DAMAGE.
2278
 *
2279
 *	@(#)queue.h	8.5 (Berkeley) 8/20/94
2280
 * $FreeBSD$
2281
 */
2282

    
2283
#ifndef _SYS_QUEUE_H_
2284
#define	_SYS_QUEUE_H_
2285

    
2286
/*
2287
 * This file defines four types of data structures: singly-linked lists,
2288
 * singly-linked tail queues, lists and tail queues.
2289
 *
2290
 * A singly-linked list is headed by a single forward pointer. The elements
2291
 * are singly linked for minimum space and pointer manipulation overhead at
2292
 * the expense of O(n) removal for arbitrary elements. New elements can be
2293
 * added to the list after an existing element or at the head of the list.
2294
 * Elements being removed from the head of the list should use the explicit
2295
 * macro for this purpose for optimum efficiency. A singly-linked list may
2296
 * only be traversed in the forward direction.  Singly-linked lists are ideal
2297
 * for applications with large datasets and few or no removals or for
2298
 * implementing a LIFO queue.
2299
 *
2300
 * A singly-linked tail queue is headed by a pair of pointers, one to the
2301
 * head of the list and the other to the tail of the list. The elements are
2302
 * singly linked for minimum space and pointer manipulation overhead at the
2303
 * expense of O(n) removal for arbitrary elements. New elements can be added
2304
 * to the list after an existing element, at the head of the list, or at the
2305
 * end of the list. Elements being removed from the head of the tail queue
2306
 * should use the explicit macro for this purpose for optimum efficiency.
2307
 * A singly-linked tail queue may only be traversed in the forward direction.
2308
 * Singly-linked tail queues are ideal for applications with large datasets
2309
 * and few or no removals or for implementing a FIFO queue.
2310
 *
2311
 * A list is headed by a single forward pointer (or an array of forward
2312
 * pointers for a hash table header). The elements are doubly linked
2313
 * so that an arbitrary element can be removed without a need to
2314
 * traverse the list. New elements can be added to the list before
2315
 * or after an existing element or at the head of the list. A list
2316
 * may be traversed in either direction.
2317
 *
2318
 * A tail queue is headed by a pair of pointers, one to the head of the
2319
 * list and the other to the tail of the list. The elements are doubly
2320
 * linked so that an arbitrary element can be removed without a need to
2321
 * traverse the list. New elements can be added to the list before or
2322
 * after an existing element, at the head of the list, or at the end of
2323
 * the list. A tail queue may be traversed in either direction.
2324
 *
2325
 * For details on the use of these macros, see the queue(3) manual page.
2326
 *
2327
 *
2328
 *				SLIST	LIST	STAILQ	TAILQ
2329
 * _HEAD			+	+	+	+
2330
 * _CLASS_HEAD			+	+	+	+
2331
 * _HEAD_INITIALIZER		+	+	+	+
2332
 * _ENTRY			+	+	+	+
2333
 * _CLASS_ENTRY			+	+	+	+
2334
 * _INIT			+	+	+	+
2335
 * _EMPTY			+	+	+	+
2336
 * _FIRST			+	+	+	+
2337
 * _NEXT			+	+	+	+
2338
 * _PREV			-	+	-	+
2339
 * _LAST			-	-	+	+
2340
 * _FOREACH			+	+	+	+
2341
 * _FOREACH_FROM		+	+	+	+
2342
 * _FOREACH_SAFE		+	+	+	+
2343
 * _FOREACH_FROM_SAFE		+	+	+	+
2344
 * _FOREACH_REVERSE		-	-	-	+
2345
 * _FOREACH_REVERSE_FROM	-	-	-	+
2346
 * _FOREACH_REVERSE_SAFE	-	-	-	+
2347
 * _FOREACH_REVERSE_FROM_SAFE	-	-	-	+
2348
 * _INSERT_HEAD			+	+	+	+
2349
 * _INSERT_BEFORE		-	+	-	+
2350
 * _INSERT_AFTER		+	+	+	+
2351
 * _INSERT_TAIL			-	-	+	+
2352
 * _CONCAT			-	-	+	+
2353
 * _REMOVE_AFTER		+	-	+	-
2354
 * _REMOVE_HEAD			+	-	+	-
2355
 * _REMOVE			+	+	+	+
2356
 * _SWAP			+	+	+	+
2357
 *
2358
 */
2359
#ifdef QUEUE_MACRO_DEBUG
2360
/* Store the last 2 places the queue element or head was altered */
2361
struct qm_trace {
2362
	unsigned long	 lastline;
2363
	unsigned long	 prevline;
2364
	const char	*lastfile;
2365
	const char	*prevfile;
2366
};
2367

    
2368
#define	TRACEBUF	struct qm_trace trace;
2369
#define	TRACEBUF_INITIALIZER	{ __LINE__, 0, __FILE__, NULL } ,
2370
#define	TRASHIT(x)	do {(x) = (void *)-1;} while (0)
2371
#define	QMD_SAVELINK(name, link)	void **name = (void *)&(link)
2372

    
2373
#define	QMD_TRACE_HEAD(head) do {					\
2374
	(head)->trace.prevline = (head)->trace.lastline;		\
2375
	(head)->trace.prevfile = (head)->trace.lastfile;		\
2376
	(head)->trace.lastline = __LINE__;				\
2377
	(head)->trace.lastfile = __FILE__;				\
2378
} while (0)
2379

    
2380
#define	QMD_TRACE_ELEM(elem) do {					\
2381
	(elem)->trace.prevline = (elem)->trace.lastline;		\
2382
	(elem)->trace.prevfile = (elem)->trace.lastfile;		\
2383
	(elem)->trace.lastline = __LINE__;				\
2384
	(elem)->trace.lastfile = __FILE__;				\
2385
} while (0)
2386

    
2387
#else
2388
#define	QMD_TRACE_ELEM(elem)
2389
#define	QMD_TRACE_HEAD(head)
2390
#define	QMD_SAVELINK(name, link)
2391
#define	TRACEBUF
2392
#define	TRACEBUF_INITIALIZER
2393
#define	TRASHIT(x)
2394
#endif	/* QUEUE_MACRO_DEBUG */
2395

    
2396
#ifdef __cplusplus
2397
/*
2398
 * In C++ there can be structure lists and class lists:
2399
 */
2400
#define	QUEUE_TYPEOF(type) type
2401
#else
2402
#define	QUEUE_TYPEOF(type) struct type
2403
#endif
2404

    
2405
/*
2406
 * Singly-linked List declarations.
2407
 */
2408
#define	SLIST_HEAD(name, type)						\
2409
struct name {								\
2410
	struct type *slh_first;	/* first element */			\
2411
}
2412

    
2413
#define	SLIST_CLASS_HEAD(name, type)					\
2414
struct name {								\
2415
	class type *slh_first;	/* first element */			\
2416
}
2417

    
2418
#define	SLIST_HEAD_INITIALIZER(head)					\
2419
	{ NULL }
2420

    
2421
#define	SLIST_ENTRY(type)						\
2422
struct {								\
2423
	struct type *sle_next;	/* next element */			\
2424
}
2425

    
2426
#define	SLIST_CLASS_ENTRY(type)						\
2427
struct {								\
2428
	class type *sle_next;		/* next element */		\
2429
}
2430

    
2431
/*
2432
 * Singly-linked List functions.
2433
 */
2434
#define	SLIST_EMPTY(head)	((head)->slh_first == NULL)
2435

    
2436
#define	SLIST_FIRST(head)	((head)->slh_first)
2437

    
2438
#define	SLIST_FOREACH(var, head, field)					\
2439
	for ((var) = SLIST_FIRST((head));				\
2440
	    (var);							\
2441
	    (var) = SLIST_NEXT((var), field))
2442

    
2443
#define	SLIST_FOREACH_FROM(var, head, field)				\
2444
	for ((var) = ((var) ? (var) : SLIST_FIRST((head)));		\
2445
	    (var);							\
2446
	    (var) = SLIST_NEXT((var), field))
2447

    
2448
#define	SLIST_FOREACH_SAFE(var, head, field, tvar)			\
2449
	for ((var) = SLIST_FIRST((head));				\
2450
	    (var) && ((tvar) = SLIST_NEXT((var), field), 1);		\
2451
	    (var) = (tvar))
2452

    
2453
#define	SLIST_FOREACH_FROM_SAFE(var, head, field, tvar)			\
2454
	for ((var) = ((var) ? (var) : SLIST_FIRST((head)));		\
2455
	    (var) && ((tvar) = SLIST_NEXT((var), field), 1);		\
2456
	    (var) = (tvar))
2457

    
2458
#define	SLIST_FOREACH_PREVPTR(var, varp, head, field)			\
2459
	for ((varp) = &SLIST_FIRST((head));				\
2460
	    ((var) = *(varp)) != NULL;					\
2461
	    (varp) = &SLIST_NEXT((var), field))
2462

    
2463
#define	SLIST_INIT(head) do {						\
2464
	SLIST_FIRST((head)) = NULL;					\
2465
} while (0)
2466

    
2467
#define	SLIST_INSERT_AFTER(slistelm, elm, field) do {			\
2468
	SLIST_NEXT((elm), field) = SLIST_NEXT((slistelm), field);	\
2469
	SLIST_NEXT((slistelm), field) = (elm);				\
2470
} while (0)
2471

    
2472
#define	SLIST_INSERT_HEAD(head, elm, field) do {			\
2473
	SLIST_NEXT((elm), field) = SLIST_FIRST((head));			\
2474
	SLIST_FIRST((head)) = (elm);					\
2475
} while (0)
2476

    
2477
#define	SLIST_NEXT(elm, field)	((elm)->field.sle_next)
2478

    
2479
#define	SLIST_REMOVE(head, elm, type, field) do {			\
2480
	QMD_SAVELINK(oldnext, (elm)->field.sle_next);			\
2481
	if (SLIST_FIRST((head)) == (elm)) {				\
2482
		SLIST_REMOVE_HEAD((head), field);			\
2483
	}								\
2484
	else {								\
2485
		QUEUE_TYPEOF(type) *curelm = SLIST_FIRST(head);		\
2486
		while (SLIST_NEXT(curelm, field) != (elm))		\
2487
			curelm = SLIST_NEXT(curelm, field);		\
2488
		SLIST_REMOVE_AFTER(curelm, field);			\
2489
	}								\
2490
	TRASHIT(*oldnext);						\
2491
} while (0)
2492

    
2493
#define SLIST_REMOVE_AFTER(elm, field) do {				\
2494
	SLIST_NEXT(elm, field) =					\
2495
	    SLIST_NEXT(SLIST_NEXT(elm, field), field);			\
2496
} while (0)
2497

    
2498
#define	SLIST_REMOVE_HEAD(head, field) do {				\
2499
	SLIST_FIRST((head)) = SLIST_NEXT(SLIST_FIRST((head)), field);	\
2500
} while (0)
2501

    
2502
#define SLIST_SWAP(head1, head2, type) do {				\
2503
	QUEUE_TYPEOF(type) *swap_first = SLIST_FIRST(head1);		\
2504
	SLIST_FIRST(head1) = SLIST_FIRST(head2);			\
2505
	SLIST_FIRST(head2) = swap_first;				\
2506
} while (0)
2507

    
2508
/*
2509
 * Singly-linked Tail queue declarations.
2510
 */
2511
#define	STAILQ_HEAD(name, type)						\
2512
struct name {								\
2513
	struct type *stqh_first;/* first element */			\
2514
	struct type **stqh_last;/* addr of last next element */		\
2515
}
2516

    
2517
#define	STAILQ_CLASS_HEAD(name, type)					\
2518
struct name {								\
2519
	class type *stqh_first;	/* first element */			\
2520
	class type **stqh_last;	/* addr of last next element */		\
2521
}
2522

    
2523
#define	STAILQ_HEAD_INITIALIZER(head)					\
2524
	{ NULL, &(head).stqh_first }
2525

    
2526
#define	STAILQ_ENTRY(type)						\
2527
struct {								\
2528
	struct type *stqe_next;	/* next element */			\
2529
}
2530

    
2531
#define	STAILQ_CLASS_ENTRY(type)					\
2532
struct {								\
2533
	class type *stqe_next;	/* next element */			\
2534
}
2535

    
2536
/*
2537
 * Singly-linked Tail queue functions.
2538
 */
2539
#define	STAILQ_CONCAT(head1, head2) do {				\
2540
	if (!STAILQ_EMPTY((head2))) {					\
2541
		*(head1)->stqh_last = (head2)->stqh_first;		\
2542
		(head1)->stqh_last = (head2)->stqh_last;		\
2543
		STAILQ_INIT((head2));					\
2544
	}								\
2545
} while (0)
2546

    
2547
#define	STAILQ_EMPTY(head)	((head)->stqh_first == NULL)
2548

    
2549
#define	STAILQ_FIRST(head)	((head)->stqh_first)
2550

    
2551
#define	STAILQ_FOREACH(var, head, field)				\
2552
	for((var) = STAILQ_FIRST((head));				\
2553
	   (var);							\
2554
	   (var) = STAILQ_NEXT((var), field))
2555

    
2556
#define	STAILQ_FOREACH_FROM(var, head, field)				\
2557
	for ((var) = ((var) ? (var) : STAILQ_FIRST((head)));		\
2558
	   (var);							\
2559
	   (var) = STAILQ_NEXT((var), field))
2560

    
2561
#define	STAILQ_FOREACH_SAFE(var, head, field, tvar)			\
2562
	for ((var) = STAILQ_FIRST((head));				\
2563
	    (var) && ((tvar) = STAILQ_NEXT((var), field), 1);		\
2564
	    (var) = (tvar))
2565

    
2566
#define	STAILQ_FOREACH_FROM_SAFE(var, head, field, tvar)		\
2567
	for ((var) = ((var) ? (var) : STAILQ_FIRST((head)));		\
2568
	    (var) && ((tvar) = STAILQ_NEXT((var), field), 1);		\
2569
	    (var) = (tvar))
2570

    
2571
#define	STAILQ_INIT(head) do {						\
2572
	STAILQ_FIRST((head)) = NULL;					\
2573
	(head)->stqh_last = &STAILQ_FIRST((head));			\
2574
} while (0)
2575

    
2576
#define	STAILQ_INSERT_AFTER(head, tqelm, elm, field) do {		\
2577
	if ((STAILQ_NEXT((elm), field) = STAILQ_NEXT((tqelm), field)) == NULL)\
2578
		(head)->stqh_last = &STAILQ_NEXT((elm), field);		\
2579
	STAILQ_NEXT((tqelm), field) = (elm);				\
2580
} while (0)
2581

    
2582
#define	STAILQ_INSERT_HEAD(head, elm, field) do {			\
2583
	if ((STAILQ_NEXT((elm), field) = STAILQ_FIRST((head))) == NULL)	\
2584
		(head)->stqh_last = &STAILQ_NEXT((elm), field);		\
2585
	STAILQ_FIRST((head)) = (elm);					\
2586
} while (0)
2587

    
2588
#define	STAILQ_INSERT_TAIL(head, elm, field) do {			\
2589
	STAILQ_NEXT((elm), field) = NULL;				\
2590
	*(head)->stqh_last = (elm);					\
2591
	(head)->stqh_last = &STAILQ_NEXT((elm), field);			\
2592
} while (0)
2593

    
2594
#define	STAILQ_LAST(head, type, field)				\
2595
	(STAILQ_EMPTY((head)) ? NULL :				\
2596
	    __containerof((head)->stqh_last,			\
2597
	    QUEUE_TYPEOF(type), field.stqe_next))
2598

    
2599
#define	STAILQ_NEXT(elm, field)	((elm)->field.stqe_next)
2600

    
2601
#define	STAILQ_REMOVE(head, elm, type, field) do {			\
2602
	QMD_SAVELINK(oldnext, (elm)->field.stqe_next);			\
2603
	if (STAILQ_FIRST((head)) == (elm)) {				\
2604
		STAILQ_REMOVE_HEAD((head), field);			\
2605
	}								\
2606
	else {								\
2607
		QUEUE_TYPEOF(type) *curelm = STAILQ_FIRST(head);	\
2608
		while (STAILQ_NEXT(curelm, field) != (elm))		\
2609
			curelm = STAILQ_NEXT(curelm, field);		\
2610
		STAILQ_REMOVE_AFTER(head, curelm, field);		\
2611
	}								\
2612
	TRASHIT(*oldnext);						\
2613
} while (0)
2614

    
2615
#define STAILQ_REMOVE_AFTER(head, elm, field) do {			\
2616
	if ((STAILQ_NEXT(elm, field) =					\
2617
	     STAILQ_NEXT(STAILQ_NEXT(elm, field), field)) == NULL)	\
2618
		(head)->stqh_last = &STAILQ_NEXT((elm), field);		\
2619
} while (0)
2620

    
2621
#define	STAILQ_REMOVE_HEAD(head, field) do {				\
2622
	if ((STAILQ_FIRST((head)) =					\
2623
	     STAILQ_NEXT(STAILQ_FIRST((head)), field)) == NULL)		\
2624
		(head)->stqh_last = &STAILQ_FIRST((head));		\
2625
} while (0)
2626

    
2627
#define STAILQ_SWAP(head1, head2, type) do {				\
2628
	QUEUE_TYPEOF(type) *swap_first = STAILQ_FIRST(head1);		\
2629
	QUEUE_TYPEOF(type) **swap_last = (head1)->stqh_last;		\
2630
	STAILQ_FIRST(head1) = STAILQ_FIRST(head2);			\
2631
	(head1)->stqh_last = (head2)->stqh_last;			\
2632
	STAILQ_FIRST(head2) = swap_first;				\
2633
	(head2)->stqh_last = swap_last;					\
2634
	if (STAILQ_EMPTY(head1))					\
2635
		(head1)->stqh_last = &STAILQ_FIRST(head1);		\
2636
	if (STAILQ_EMPTY(head2))					\
2637
		(head2)->stqh_last = &STAILQ_FIRST(head2);		\
2638
} while (0)
2639

    
2640

    
2641
/*
2642
 * List declarations.
2643
 */
2644
#define	LIST_HEAD(name, type)						\
2645
struct name {								\
2646
	struct type *lh_first;	/* first element */			\
2647
}
2648

    
2649
#define	LIST_CLASS_HEAD(name, type)					\
2650
struct name {								\
2651
	class type *lh_first;	/* first element */			\
2652
}
2653

    
2654
#define	LIST_HEAD_INITIALIZER(head)					\
2655
	{ NULL }
2656

    
2657
#define	LIST_ENTRY(type)						\
2658
struct {								\
2659
	struct type *le_next;	/* next element */			\
2660
	struct type **le_prev;	/* address of previous next element */	\
2661
}
2662

    
2663
#define	LIST_CLASS_ENTRY(type)						\
2664
struct {								\
2665
	class type *le_next;	/* next element */			\
2666
	class type **le_prev;	/* address of previous next element */	\
2667
}
2668

    
2669
/*
2670
 * List functions.
2671
 */
2672

    
2673
#if (defined(_KERNEL) && defined(INVARIANTS))
2674
#define	QMD_LIST_CHECK_HEAD(head, field) do {				\
2675
	if (LIST_FIRST((head)) != NULL &&				\
2676
	    LIST_FIRST((head))->field.le_prev !=			\
2677
	     &LIST_FIRST((head)))					\
2678
		panic("Bad list head %p first->prev != head", (head));	\
2679
} while (0)
2680

    
2681
#define	QMD_LIST_CHECK_NEXT(elm, field) do {				\
2682
	if (LIST_NEXT((elm), field) != NULL &&				\
2683
	    LIST_NEXT((elm), field)->field.le_prev !=			\
2684
	     &((elm)->field.le_next))					\
2685
	     	panic("Bad link elm %p next->prev != elm", (elm));	\
2686
} while (0)
2687

    
2688
#define	QMD_LIST_CHECK_PREV(elm, field) do {				\
2689
	if (*(elm)->field.le_prev != (elm))				\
2690
		panic("Bad link elm %p prev->next != elm", (elm));	\
2691
} while (0)
2692
#else
2693
#define	QMD_LIST_CHECK_HEAD(head, field)
2694
#define	QMD_LIST_CHECK_NEXT(elm, field)
2695
#define	QMD_LIST_CHECK_PREV(elm, field)
2696
#endif /* (_KERNEL && INVARIANTS) */
2697

    
2698
#define	LIST_EMPTY(head)	((head)->lh_first == NULL)
2699

    
2700
#define	LIST_FIRST(head)	((head)->lh_first)
2701

    
2702
#define	LIST_FOREACH(var, head, field)					\
2703
	for ((var) = LIST_FIRST((head));				\
2704
	    (var);							\
2705
	    (var) = LIST_NEXT((var), field))
2706

    
2707
#define	LIST_FOREACH_FROM(var, head, field)				\
2708
	for ((var) = ((var) ? (var) : LIST_FIRST((head)));		\
2709
	    (var);							\
2710
	    (var) = LIST_NEXT((var), field))
2711

    
2712
#define	LIST_FOREACH_SAFE(var, head, field, tvar)			\
2713
	for ((var) = LIST_FIRST((head));				\
2714
	    (var) && ((tvar) = LIST_NEXT((var), field), 1);		\
2715
	    (var) = (tvar))
2716

    
2717
#define	LIST_FOREACH_FROM_SAFE(var, head, field, tvar)			\
2718
	for ((var) = ((var) ? (var) : LIST_FIRST((head)));		\
2719
	    (var) && ((tvar) = LIST_NEXT((var), field), 1);		\
2720
	    (var) = (tvar))
2721

    
2722
#define	LIST_INIT(head) do {						\
2723
	LIST_FIRST((head)) = NULL;					\
2724
} while (0)
2725

    
2726
#define	LIST_INSERT_AFTER(listelm, elm, field) do {			\
2727
	QMD_LIST_CHECK_NEXT(listelm, field);				\
2728
	if ((LIST_NEXT((elm), field) = LIST_NEXT((listelm), field)) != NULL)\
2729
		LIST_NEXT((listelm), field)->field.le_prev =		\
2730
		    &LIST_NEXT((elm), field);				\
2731
	LIST_NEXT((listelm), field) = (elm);				\
2732
	(elm)->field.le_prev = &LIST_NEXT((listelm), field);		\
2733
} while (0)
2734

    
2735
#define	LIST_INSERT_BEFORE(listelm, elm, field) do {			\
2736
	QMD_LIST_CHECK_PREV(listelm, field);				\
2737
	(elm)->field.le_prev = (listelm)->field.le_prev;		\
2738
	LIST_NEXT((elm), field) = (listelm);				\
2739
	*(listelm)->field.le_prev = (elm);				\
2740
	(listelm)->field.le_prev = &LIST_NEXT((elm), field);		\
2741
} while (0)
2742

    
2743
#define	LIST_INSERT_HEAD(head, elm, field) do {				\
2744
	QMD_LIST_CHECK_HEAD((head), field);				\
2745
	if ((LIST_NEXT((elm), field) = LIST_FIRST((head))) != NULL)	\
2746
		LIST_FIRST((head))->field.le_prev = &LIST_NEXT((elm), field);\
2747
	LIST_FIRST((head)) = (elm);					\
2748
	(elm)->field.le_prev = &LIST_FIRST((head));			\
2749
} while (0)
2750

    
2751
#define	LIST_NEXT(elm, field)	((elm)->field.le_next)
2752

    
2753
#define	LIST_PREV(elm, head, type, field)			\
2754
	((elm)->field.le_prev == &LIST_FIRST((head)) ? NULL :	\
2755
	    __containerof((elm)->field.le_prev,			\
2756
	    QUEUE_TYPEOF(type), field.le_next))
2757

    
2758
#define	LIST_REMOVE(elm, field) do {					\
2759
	QMD_SAVELINK(oldnext, (elm)->field.le_next);			\
2760
	QMD_SAVELINK(oldprev, (elm)->field.le_prev);			\
2761
	QMD_LIST_CHECK_NEXT(elm, field);				\
2762
	QMD_LIST_CHECK_PREV(elm, field);				\
2763
	if (LIST_NEXT((elm), field) != NULL)				\
2764
		LIST_NEXT((elm), field)->field.le_prev = 		\
2765
		    (elm)->field.le_prev;				\
2766
	*(elm)->field.le_prev = LIST_NEXT((elm), field);		\
2767
	TRASHIT(*oldnext);						\
2768
	TRASHIT(*oldprev);						\
2769
} while (0)
2770

    
2771
#define LIST_SWAP(head1, head2, type, field) do {			\
2772
	QUEUE_TYPEOF(type) *swap_tmp = LIST_FIRST(head1);		\
2773
	LIST_FIRST((head1)) = LIST_FIRST((head2));			\
2774
	LIST_FIRST((head2)) = swap_tmp;					\
2775
	if ((swap_tmp = LIST_FIRST((head1))) != NULL)			\
2776
		swap_tmp->field.le_prev = &LIST_FIRST((head1));		\
2777
	if ((swap_tmp = LIST_FIRST((head2))) != NULL)			\
2778
		swap_tmp->field.le_prev = &LIST_FIRST((head2));		\
2779
} while (0)
2780

    
2781
/*
2782
 * Tail queue declarations.
2783
 */
2784
#define	TAILQ_HEAD(name, type)						\
2785
struct name {								\
2786
	struct type *tqh_first;	/* first element */			\
2787
	struct type **tqh_last;	/* addr of last next element */		\
2788
	TRACEBUF							\
2789
}
2790

    
2791
#define	TAILQ_CLASS_HEAD(name, type)					\
2792
struct name {								\
2793
	class type *tqh_first;	/* first element */			\
2794
	class type **tqh_last;	/* addr of last next element */		\
2795
	TRACEBUF							\
2796
}
2797

    
2798
#define	TAILQ_HEAD_INITIALIZER(head)					\
2799
	{ NULL, &(head).tqh_first, TRACEBUF_INITIALIZER }
2800

    
2801
#define	TAILQ_ENTRY(type)						\
2802
struct {								\
2803
	struct type *tqe_next;	/* next element */			\
2804
	struct type **tqe_prev;	/* address of previous next element */	\
2805
	TRACEBUF							\
2806
}
2807

    
2808
#define	TAILQ_CLASS_ENTRY(type)						\
2809
struct {								\
2810
	class type *tqe_next;	/* next element */			\
2811
	class type **tqe_prev;	/* address of previous next element */	\
2812
	TRACEBUF							\
2813
}
2814

    
2815
/*
2816
 * Tail queue functions.
2817
 */
2818
#if (defined(_KERNEL) && defined(INVARIANTS))
2819
#define	QMD_TAILQ_CHECK_HEAD(head, field) do {				\
2820
	if (!TAILQ_EMPTY(head) &&					\
2821
	    TAILQ_FIRST((head))->field.tqe_prev !=			\
2822
	     &TAILQ_FIRST((head)))					\
2823
		panic("Bad tailq head %p first->prev != head", (head));	\
2824
} while (0)
2825

    
2826
#define	QMD_TAILQ_CHECK_TAIL(head, field) do {				\
2827
	if (*(head)->tqh_last != NULL)					\
2828
	    	panic("Bad tailq NEXT(%p->tqh_last) != NULL", (head)); 	\
2829
} while (0)
2830

    
2831
#define	QMD_TAILQ_CHECK_NEXT(elm, field) do {				\
2832
	if (TAILQ_NEXT((elm), field) != NULL &&				\
2833
	    TAILQ_NEXT((elm), field)->field.tqe_prev !=			\
2834
	     &((elm)->field.tqe_next))					\
2835
		panic("Bad link elm %p next->prev != elm", (elm));	\
2836
} while (0)
2837

    
2838
#define	QMD_TAILQ_CHECK_PREV(elm, field) do {				\
2839
	if (*(elm)->field.tqe_prev != (elm))				\
2840
		panic("Bad link elm %p prev->next != elm", (elm));	\
2841
} while (0)
2842
#else
2843
#define	QMD_TAILQ_CHECK_HEAD(head, field)
2844
#define	QMD_TAILQ_CHECK_TAIL(head, headname)
2845
#define	QMD_TAILQ_CHECK_NEXT(elm, field)
2846
#define	QMD_TAILQ_CHECK_PREV(elm, field)
2847
#endif /* (_KERNEL && INVARIANTS) */
2848

    
2849
#define	TAILQ_CONCAT(head1, head2, field) do {				\
2850
	if (!TAILQ_EMPTY(head2)) {					\
2851
		*(head1)->tqh_last = (head2)->tqh_first;		\
2852
		(head2)->tqh_first->field.tqe_prev = (head1)->tqh_last;	\
2853
		(head1)->tqh_last = (head2)->tqh_last;			\
2854
		TAILQ_INIT((head2));					\
2855
		QMD_TRACE_HEAD(head1);					\
2856
		QMD_TRACE_HEAD(head2);					\
2857
	}								\
2858
} while (0)
2859

    
2860
#define	TAILQ_EMPTY(head)	((head)->tqh_first == NULL)
2861

    
2862
#define	TAILQ_FIRST(head)	((head)->tqh_first)
2863

    
2864
#define	TAILQ_FOREACH(var, head, field)					\
2865
	for ((var) = TAILQ_FIRST((head));				\
2866
	    (var);							\
2867
	    (var) = TAILQ_NEXT((var), field))
2868

    
2869
#define	TAILQ_FOREACH_FROM(var, head, field)				\
2870
	for ((var) = ((var) ? (var) : TAILQ_FIRST((head)));		\
2871
	    (var);							\
2872
	    (var) = TAILQ_NEXT((var), field))
2873

    
2874
#define	TAILQ_FOREACH_SAFE(var, head, field, tvar)			\
2875
	for ((var) = TAILQ_FIRST((head));				\
2876
	    (var) && ((tvar) = TAILQ_NEXT((var), field), 1);		\
2877
	    (var) = (tvar))
2878

    
2879
#define	TAILQ_FOREACH_FROM_SAFE(var, head, field, tvar)			\
2880
	for ((var) = ((var) ? (var) : TAILQ_FIRST((head)));		\
2881
	    (var) && ((tvar) = TAILQ_NEXT((var), field), 1);		\
2882
	    (var) = (tvar))
2883

    
2884
#define	TAILQ_FOREACH_REVERSE(var, head, headname, field)		\
2885
	for ((var) = TAILQ_LAST((head), headname);			\
2886
	    (var);							\
2887
	    (var) = TAILQ_PREV((var), headname, field))
2888

    
2889
#define	TAILQ_FOREACH_REVERSE_FROM(var, head, headname, field)		\
2890
	for ((var) = ((var) ? (var) : TAILQ_LAST((head), headname));	\
2891
	    (var);							\
2892
	    (var) = TAILQ_PREV((var), headname, field))
2893

    
2894
#define	TAILQ_FOREACH_REVERSE_SAFE(var, head, headname, field, tvar)	\
2895
	for ((var) = TAILQ_LAST((head), headname);			\
2896
	    (var) && ((tvar) = TAILQ_PREV((var), headname, field), 1);	\
2897
	    (var) = (tvar))
2898

    
2899
#define	TAILQ_FOREACH_REVERSE_FROM_SAFE(var, head, headname, field, tvar) \
2900
	for ((var) = ((var) ? (var) : TAILQ_LAST((head), headname));	\
2901
	    (var) && ((tvar) = TAILQ_PREV((var), headname, field), 1);	\
2902
	    (var) = (tvar))
2903

    
2904
#define	TAILQ_INIT(head) do {						\
2905
	TAILQ_FIRST((head)) = NULL;					\
2906
	(head)->tqh_last = &TAILQ_FIRST((head));			\
2907
	QMD_TRACE_HEAD(head);						\
2908
} while (0)
2909

    
2910
#define	TAILQ_INSERT_AFTER(head, listelm, elm, field) do {		\
2911
	QMD_TAILQ_CHECK_NEXT(listelm, field);				\
2912
	if ((TAILQ_NEXT((elm), field) = TAILQ_NEXT((listelm), field)) != NULL)\
2913
		TAILQ_NEXT((elm), field)->field.tqe_prev = 		\
2914
		    &TAILQ_NEXT((elm), field);				\
2915
	else {								\
2916
		(head)->tqh_last = &TAILQ_NEXT((elm), field);		\
2917
		QMD_TRACE_HEAD(head);					\
2918
	}								\
2919
	TAILQ_NEXT((listelm), field) = (elm);				\
2920
	(elm)->field.tqe_prev = &TAILQ_NEXT((listelm), field);		\
2921
	QMD_TRACE_ELEM(&(elm)->field);					\
2922
	QMD_TRACE_ELEM(&(listelm)->field);				\
2923
} while (0)
2924

    
2925
#define	TAILQ_INSERT_BEFORE(listelm, elm, field) do {			\
2926
	QMD_TAILQ_CHECK_PREV(listelm, field);				\
2927
	(elm)->field.tqe_prev = (listelm)->field.tqe_prev;		\
2928
	TAILQ_NEXT((elm), field) = (listelm);				\
2929
	*(listelm)->field.tqe_prev = (elm);				\
2930
	(listelm)->field.tqe_prev = &TAILQ_NEXT((elm), field);		\
2931
	QMD_TRACE_ELEM(&(elm)->field);					\
2932
	QMD_TRACE_ELEM(&(listelm)->field);				\
2933
} while (0)
2934

    
2935
#define	TAILQ_INSERT_HEAD(head, elm, field) do {			\
2936
	QMD_TAILQ_CHECK_HEAD(head, field);				\
2937
	if ((TAILQ_NEXT((elm), field) = TAILQ_FIRST((head))) != NULL)	\
2938
		TAILQ_FIRST((head))->field.tqe_prev =			\
2939
		    &TAILQ_NEXT((elm), field);				\
2940
	else								\
2941
		(head)->tqh_last = &TAILQ_NEXT((elm), field);		\
2942
	TAILQ_FIRST((head)) = (elm);					\
2943
	(elm)->field.tqe_prev = &TAILQ_FIRST((head));			\
2944
	QMD_TRACE_HEAD(head);						\
2945
	QMD_TRACE_ELEM(&(elm)->field);					\
2946
} while (0)
2947

    
2948
#define	TAILQ_INSERT_TAIL(head, elm, field) do {			\
2949
	QMD_TAILQ_CHECK_TAIL(head, field);				\
2950
	TAILQ_NEXT((elm), field) = NULL;				\
2951
	(elm)->field.tqe_prev = (head)->tqh_last;			\
2952
	*(head)->tqh_last = (elm);					\
2953
	(head)->tqh_last = &TAILQ_NEXT((elm), field);			\
2954
	QMD_TRACE_HEAD(head);						\
2955
	QMD_TRACE_ELEM(&(elm)->field);					\
2956
} while (0)
2957

    
2958
#define	TAILQ_LAST(head, headname)					\
2959
	(*(((struct headname *)((head)->tqh_last))->tqh_last))
2960

    
2961
#define	TAILQ_NEXT(elm, field) ((elm)->field.tqe_next)
2962

    
2963
#define	TAILQ_PREV(elm, headname, field)				\
2964
	(*(((struct headname *)((elm)->field.tqe_prev))->tqh_last))
2965

    
2966
#define	TAILQ_REMOVE(head, elm, field) do {				\
2967
	QMD_SAVELINK(oldnext, (elm)->field.tqe_next);			\
2968
	QMD_SAVELINK(oldprev, (elm)->field.tqe_prev);			\
2969
	QMD_TAILQ_CHECK_NEXT(elm, field);				\
2970
	QMD_TAILQ_CHECK_PREV(elm, field);				\
2971
	if ((TAILQ_NEXT((elm), field)) != NULL)				\
2972
		TAILQ_NEXT((elm), field)->field.tqe_prev = 		\
2973
		    (elm)->field.tqe_prev;				\
2974
	else {								\
2975
		(head)->tqh_last = (elm)->field.tqe_prev;		\
2976
		QMD_TRACE_HEAD(head);					\
2977
	}								\
2978
	*(elm)->field.tqe_prev = TAILQ_NEXT((elm), field);		\
2979
	TRASHIT(*oldnext);						\
2980
	TRASHIT(*oldprev);						\
2981
	QMD_TRACE_ELEM(&(elm)->field);					\
2982
} while (0)
2983

    
2984
#define TAILQ_SWAP(head1, head2, type, field) do {			\
2985
	QUEUE_TYPEOF(type) *swap_first = (head1)->tqh_first;		\
2986
	QUEUE_TYPEOF(type) **swap_last = (head1)->tqh_last;		\
2987
	(head1)->tqh_first = (head2)->tqh_first;			\
2988
	(head1)->tqh_last = (head2)->tqh_last;				\
2989
	(head2)->tqh_first = swap_first;				\
2990
	(head2)->tqh_last = swap_last;					\
2991
	if ((swap_first = (head1)->tqh_first) != NULL)			\
2992
		swap_first->field.tqe_prev = &(head1)->tqh_first;	\
2993
	else								\
2994
		(head1)->tqh_last = &(head1)->tqh_first;		\
2995
	if ((swap_first = (head2)->tqh_first) != NULL)			\
2996
		swap_first->field.tqe_prev = &(head2)->tqh_first;	\
2997
	else								\
2998
		(head2)->tqh_last = &(head2)->tqh_first;		\
2999
} while (0)
3000

    
3001
#endif /* !_SYS_QUEUE_H_ */
3002
#ifdef MG_MODULE_LINES
3003
#line 1 "mongoose/src/mg_features.h"
3004
#endif
3005
/*
3006
 * Copyright (c) 2014-2016 Cesanta Software Limited
3007
 * All rights reserved
3008
 */
3009

    
3010
#ifndef CS_MONGOOSE_SRC_FEATURES_H_
3011
#define CS_MONGOOSE_SRC_FEATURES_H_
3012

    
3013
#ifndef MG_DISABLE_HTTP_DIGEST_AUTH
3014
#define MG_DISABLE_HTTP_DIGEST_AUTH 0
3015
#endif
3016

    
3017
#ifndef MG_DISABLE_HTTP_KEEP_ALIVE
3018
#define MG_DISABLE_HTTP_KEEP_ALIVE 0
3019
#endif
3020

    
3021
#ifndef MG_DISABLE_PFS
3022
#define MG_DISABLE_PFS 0
3023
#endif
3024

    
3025
#ifndef MG_DISABLE_WS_RANDOM_MASK
3026
#define MG_DISABLE_WS_RANDOM_MASK 0
3027
#endif
3028

    
3029
#ifndef MG_ENABLE_ASYNC_RESOLVER
3030
#define MG_ENABLE_ASYNC_RESOLVER 1
3031
#endif
3032

    
3033
#ifndef MG_ENABLE_BROADCAST
3034
#define MG_ENABLE_BROADCAST 0
3035
#endif
3036

    
3037
#ifndef MG_ENABLE_COAP
3038
#define MG_ENABLE_COAP 0
3039
#endif
3040

    
3041
#ifndef MG_ENABLE_DEBUG
3042
#define MG_ENABLE_DEBUG 0
3043
#endif
3044

    
3045
#ifndef MG_ENABLE_DIRECTORY_LISTING
3046
#define MG_ENABLE_DIRECTORY_LISTING 0
3047
#endif
3048

    
3049
#ifndef MG_ENABLE_DNS
3050
#define MG_ENABLE_DNS 1
3051
#endif
3052

    
3053
#ifndef MG_ENABLE_DNS_SERVER
3054
#define MG_ENABLE_DNS_SERVER 0
3055
#endif
3056

    
3057
#ifndef MG_ENABLE_FAKE_DAVLOCK
3058
#define MG_ENABLE_FAKE_DAVLOCK 0
3059
#endif
3060

    
3061
#ifndef MG_ENABLE_FILESYSTEM
3062
#define MG_ENABLE_FILESYSTEM 0
3063
#endif
3064

    
3065
#ifndef MG_ENABLE_GETADDRINFO
3066
#define MG_ENABLE_GETADDRINFO 0
3067
#endif
3068

    
3069
#ifndef MG_ENABLE_HEXDUMP
3070
#define MG_ENABLE_HEXDUMP CS_ENABLE_STDIO
3071
#endif
3072

    
3073
#ifndef MG_ENABLE_HTTP
3074
#define MG_ENABLE_HTTP 1
3075
#endif
3076

    
3077
#ifndef MG_ENABLE_HTTP_CGI
3078
#define MG_ENABLE_HTTP_CGI 0
3079
#endif
3080

    
3081
#ifndef MG_ENABLE_HTTP_SSI
3082
#define MG_ENABLE_HTTP_SSI MG_ENABLE_FILESYSTEM
3083
#endif
3084

    
3085
#ifndef MG_ENABLE_HTTP_SSI_EXEC
3086
#define MG_ENABLE_HTTP_SSI_EXEC 0
3087
#endif
3088

    
3089
#ifndef MG_ENABLE_HTTP_STREAMING_MULTIPART
3090
#define MG_ENABLE_HTTP_STREAMING_MULTIPART 0
3091
#endif
3092

    
3093
#ifndef MG_ENABLE_HTTP_WEBDAV
3094
#define MG_ENABLE_HTTP_WEBDAV 0
3095
#endif
3096

    
3097
#ifndef MG_ENABLE_HTTP_WEBSOCKET
3098
#define MG_ENABLE_HTTP_WEBSOCKET MG_ENABLE_HTTP
3099
#endif
3100

    
3101
#ifndef MG_ENABLE_IPV6
3102
#define MG_ENABLE_IPV6 0
3103
#endif
3104

    
3105
#ifndef MG_ENABLE_MQTT
3106
#define MG_ENABLE_MQTT 1
3107
#endif
3108

    
3109
#ifndef MG_ENABLE_SOCKS
3110
#define MG_ENABLE_SOCKS 0
3111
#endif
3112

    
3113
#ifndef MG_ENABLE_MQTT_BROKER
3114
#define MG_ENABLE_MQTT_BROKER 0
3115
#endif
3116

    
3117
#ifndef MG_ENABLE_SSL
3118
#define MG_ENABLE_SSL 0
3119
#endif
3120

    
3121
#ifndef MG_ENABLE_SYNC_RESOLVER
3122
#define MG_ENABLE_SYNC_RESOLVER 0
3123
#endif
3124

    
3125
#ifndef MG_ENABLE_STDIO
3126
#define MG_ENABLE_STDIO CS_ENABLE_STDIO
3127
#endif
3128

    
3129
#ifndef MG_NET_IF
3130
#define MG_NET_IF MG_NET_IF_SOCKET
3131
#endif
3132

    
3133
#ifndef MG_SSL_IF
3134
#define MG_SSL_IF MG_SSL_IF_OPENSSL
3135
#endif
3136

    
3137
#ifndef MG_ENABLE_THREADS /* ifdef-ok */
3138
#ifdef _WIN32
3139
#define MG_ENABLE_THREADS 1
3140
#else
3141
#define MG_ENABLE_THREADS 0
3142
#endif
3143
#endif
3144

    
3145
#if MG_ENABLE_DEBUG && !defined(CS_ENABLE_DEBUG)
3146
#define CS_ENABLE_DEBUG 1
3147
#endif
3148

    
3149
/* MQTT broker requires MQTT */
3150
#if MG_ENABLE_MQTT_BROKER && !MG_ENABLE_MQTT
3151
#undef MG_ENABLE_MQTT
3152
#define MG_ENABLE_MQTT 1
3153
#endif
3154

    
3155
#ifndef MG_ENABLE_HTTP_URL_REWRITES
3156
#define MG_ENABLE_HTTP_URL_REWRITES \
3157
  (CS_PLATFORM == CS_P_WINDOWS || CS_PLATFORM == CS_P_UNIX)
3158
#endif
3159

    
3160
#ifndef MG_ENABLE_SNTP
3161
#define MG_ENABLE_SNTP 0
3162
#endif
3163

    
3164
#ifndef MG_ENABLE_EXTRA_ERRORS_DESC
3165
#define MG_ENABLE_EXTRA_ERRORS_DESC 0
3166
#endif
3167

    
3168
#ifndef MG_ENABLE_CALLBACK_USERDATA
3169
#define MG_ENABLE_CALLBACK_USERDATA 0
3170
#endif
3171

    
3172
#if MG_ENABLE_CALLBACK_USERDATA
3173
#define MG_UD_ARG(ud) , ud
3174
#define MG_CB(cb, ud) cb, ud
3175
#else
3176
#define MG_UD_ARG(ud)
3177
#define MG_CB(cb, ud) cb
3178
#endif
3179

    
3180
#endif /* CS_MONGOOSE_SRC_FEATURES_H_ */
3181
#ifdef MG_MODULE_LINES
3182
#line 1 "mongoose/src/mg_net_if.h"
3183
#endif
3184
/*
3185
 * Copyright (c) 2014-2016 Cesanta Software Limited
3186
 * All rights reserved
3187
 */
3188

    
3189
#ifndef CS_MONGOOSE_SRC_NET_IF_H_
3190
#define CS_MONGOOSE_SRC_NET_IF_H_
3191

    
3192
/* Amalgamated: #include "common/platform.h" */
3193

    
3194
/*
3195
 * Internal async networking core interface.
3196
 * Consists of calls made by the core, which should not block,
3197
 * and callbacks back into the core ("..._cb").
3198
 * Callbacks may (will) cause methods to be invoked from within,
3199
 * but methods are not allowed to invoke callbacks inline.
3200
 *
3201
 * Implementation must ensure that only one callback is invoked at any time.
3202
 */
3203

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

    
3208
#define MG_MAIN_IFACE 0
3209

    
3210
struct mg_mgr;
3211
struct mg_connection;
3212
union socket_address;
3213

    
3214
struct mg_iface_vtable;
3215

    
3216
struct mg_iface {
3217
  struct mg_mgr *mgr;
3218
  void *data; /* Implementation-specific data */
3219
  const struct mg_iface_vtable *vtable;
3220
};
3221

    
3222
struct mg_iface_vtable {
3223
  void (*init)(struct mg_iface *iface);
3224
  void (*free)(struct mg_iface *iface);
3225
  void (*add_conn)(struct mg_connection *nc);
3226
  void (*remove_conn)(struct mg_connection *nc);
3227
  time_t (*poll)(struct mg_iface *iface, int timeout_ms);
3228

    
3229
  /* Set up a listening TCP socket on a given address. rv = 0 -> ok. */
3230
  int (*listen_tcp)(struct mg_connection *nc, union socket_address *sa);
3231
  /* Request that a "listening" UDP socket be created. */
3232
  int (*listen_udp)(struct mg_connection *nc, union socket_address *sa);
3233

    
3234
  /* Request that a TCP connection is made to the specified address. */
3235
  void (*connect_tcp)(struct mg_connection *nc, const union socket_address *sa);
3236
  /* Open a UDP socket. Doesn't actually connect anything. */
3237
  void (*connect_udp)(struct mg_connection *nc);
3238

    
3239
  /* Send functions for TCP and UDP. Sent data is copied before return. */
3240
  void (*tcp_send)(struct mg_connection *nc, const void *buf, size_t len);
3241
  void (*udp_send)(struct mg_connection *nc, const void *buf, size_t len);
3242

    
3243
  void (*recved)(struct mg_connection *nc, size_t len);
3244

    
3245
  /* Perform interface-related connection initialization. Return 1 on ok. */
3246
  int (*create_conn)(struct mg_connection *nc);
3247
  /* Perform interface-related cleanup on connection before destruction. */
3248
  void (*destroy_conn)(struct mg_connection *nc);
3249

    
3250
  /* Associate a socket to a connection. */
3251
  void (*sock_set)(struct mg_connection *nc, sock_t sock);
3252

    
3253
  /* Put connection's address into *sa, local (remote = 0) or remote. */
3254
  void (*get_conn_addr)(struct mg_connection *nc, int remote,
3255
                        union socket_address *sa);
3256
};
3257

    
3258
extern const struct mg_iface_vtable *mg_ifaces[];
3259
extern int mg_num_ifaces;
3260

    
3261
/* Creates a new interface instance. */
3262
struct mg_iface *mg_if_create_iface(const struct mg_iface_vtable *vtable,
3263
                                    struct mg_mgr *mgr);
3264

    
3265
/*
3266
 * Find an interface with a given implementation. The search is started from
3267
 * interface `from`, exclusive. Returns NULL if none is found.
3268
 */
3269
struct mg_iface *mg_find_iface(struct mg_mgr *mgr,
3270
                               const struct mg_iface_vtable *vtable,
3271
                               struct mg_iface *from);
3272
/*
3273
 * Deliver a new TCP connection. Returns NULL in case on error (unable to
3274
 * create connection, in which case interface state should be discarded.
3275
 * This is phase 1 of the two-phase process - MG_EV_ACCEPT will be delivered
3276
 * when mg_if_accept_tcp_cb is invoked.
3277
 */
3278
struct mg_connection *mg_if_accept_new_conn(struct mg_connection *lc);
3279
void mg_if_accept_tcp_cb(struct mg_connection *nc, union socket_address *sa,
3280
                         size_t sa_len);
3281

    
3282
/* Callback invoked by connect methods. err = 0 -> ok, != 0 -> error. */
3283
void mg_if_connect_cb(struct mg_connection *nc, int err);
3284
/* Callback that reports that data has been put on the wire. */
3285
void mg_if_sent_cb(struct mg_connection *nc, int num_sent);
3286
/*
3287
 * Receive callback.
3288
 * if `own` is true, buf must be heap-allocated and ownership is transferred
3289
 * to the core.
3290
 * Core will acknowledge consumption by calling iface::recved.
3291
 */
3292
void mg_if_recv_tcp_cb(struct mg_connection *nc, void *buf, int len, int own);
3293
/*
3294
 * Receive callback.
3295
 * buf must be heap-allocated and ownership is transferred to the core.
3296
 * Core will acknowledge consumption by calling iface::recved.
3297
 */
3298
void mg_if_recv_udp_cb(struct mg_connection *nc, void *buf, int len,
3299
                       union socket_address *sa, size_t sa_len);
3300

    
3301
/* void mg_if_close_conn(struct mg_connection *nc); */
3302

    
3303
/* Deliver a POLL event to the connection. */
3304
void mg_if_poll(struct mg_connection *nc, time_t now);
3305

    
3306
/* Deliver a TIMER event to the connection. */
3307
void mg_if_timer(struct mg_connection *c, double now);
3308

    
3309
#ifdef __cplusplus
3310
}
3311
#endif /* __cplusplus */
3312

    
3313
#endif /* CS_MONGOOSE_SRC_NET_IF_H_ */
3314
#ifdef MG_MODULE_LINES
3315
#line 1 "mongoose/src/mg_ssl_if.h"
3316
#endif
3317
/*
3318
 * Copyright (c) 2014-2016 Cesanta Software Limited
3319
 * All rights reserved
3320
 */
3321

    
3322
#ifndef CS_MONGOOSE_SRC_SSL_IF_H_
3323
#define CS_MONGOOSE_SRC_SSL_IF_H_
3324

    
3325
#if MG_ENABLE_SSL
3326

    
3327
#ifdef __cplusplus
3328
extern "C" {
3329
#endif /* __cplusplus */
3330

    
3331
struct mg_ssl_if_ctx;
3332
struct mg_connection;
3333

    
3334
void mg_ssl_if_init();
3335

    
3336
enum mg_ssl_if_result {
3337
  MG_SSL_OK = 0,
3338
  MG_SSL_WANT_READ = -1,
3339
  MG_SSL_WANT_WRITE = -2,
3340
  MG_SSL_ERROR = -3,
3341
};
3342

    
3343
struct mg_ssl_if_conn_params {
3344
  const char *cert;
3345
  const char *key;
3346
  const char *ca_cert;
3347
  const char *server_name;
3348
  const char *cipher_suites;
3349
  const char *psk_identity;
3350
  const char *psk_key;
3351
};
3352

    
3353
enum mg_ssl_if_result mg_ssl_if_conn_init(
3354
    struct mg_connection *nc, const struct mg_ssl_if_conn_params *params,
3355
    const char **err_msg);
3356
enum mg_ssl_if_result mg_ssl_if_conn_accept(struct mg_connection *nc,
3357
                                            struct mg_connection *lc);
3358
void mg_ssl_if_conn_close_notify(struct mg_connection *nc);
3359
void mg_ssl_if_conn_free(struct mg_connection *nc);
3360

    
3361
enum mg_ssl_if_result mg_ssl_if_handshake(struct mg_connection *nc);
3362
int mg_ssl_if_read(struct mg_connection *nc, void *buf, size_t buf_size);
3363
int mg_ssl_if_write(struct mg_connection *nc, const void *data, size_t len);
3364

    
3365
#ifdef __cplusplus
3366
}
3367
#endif /* __cplusplus */
3368

    
3369
#endif /* MG_ENABLE_SSL */
3370

    
3371
#endif /* CS_MONGOOSE_SRC_SSL_IF_H_ */
3372
#ifdef MG_MODULE_LINES
3373
#line 1 "mongoose/src/mg_net.h"
3374
#endif
3375
/*
3376
 * Copyright (c) 2014 Cesanta Software Limited
3377
 * All rights reserved
3378
 * This software is dual-licensed: you can redistribute it and/or modify
3379
 * it under the terms of the GNU General Public License version 2 as
3380
 * published by the Free Software Foundation. For the terms of this
3381
 * license, see <http://www.gnu.org/licenses/>.
3382
 *
3383
 * You are free to use this software under the terms of the GNU General
3384
 * Public License, but WITHOUT ANY WARRANTY; without even the implied
3385
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
3386
 * See the GNU General Public License for more details.
3387
 *
3388
 * Alternatively, you can license this software under a commercial
3389
 * license, as set out in <https://www.cesanta.com/license>.
3390
 */
3391

    
3392
/*
3393
 * === Core API: TCP/UDP/SSL
3394
 *
3395
 * NOTE: Mongoose manager is single threaded. It does not protect
3396
 * its data structures by mutexes, therefore all functions that are dealing
3397
 * with a particular event manager should be called from the same thread,
3398
 * with exception of the `mg_broadcast()` function. It is fine to have different
3399
 * event managers handled by different threads.
3400
 */
3401

    
3402
#ifndef CS_MONGOOSE_SRC_NET_H_
3403
#define CS_MONGOOSE_SRC_NET_H_
3404

    
3405
/* Amalgamated: #include "mg_common.h" */
3406
/* Amalgamated: #include "mg_net_if.h" */
3407
/* Amalgamated: #include "common/mbuf.h" */
3408

    
3409
#ifndef MG_VPRINTF_BUFFER_SIZE
3410
#define MG_VPRINTF_BUFFER_SIZE 100
3411
#endif
3412

    
3413
#ifdef MG_USE_READ_WRITE
3414
#define MG_RECV_FUNC(s, b, l, f) read(s, b, l)
3415
#define MG_SEND_FUNC(s, b, l, f) write(s, b, l)
3416
#else
3417
#define MG_RECV_FUNC(s, b, l, f) recv(s, b, l, f)
3418
#define MG_SEND_FUNC(s, b, l, f) send(s, b, l, f)
3419
#endif
3420

    
3421
#ifdef __cplusplus
3422
extern "C" {
3423
#endif /* __cplusplus */
3424

    
3425
union socket_address {
3426
  struct sockaddr sa;
3427
  struct sockaddr_in sin;
3428
#if MG_ENABLE_IPV6
3429
  struct sockaddr_in6 sin6;
3430
#else
3431
  struct sockaddr sin6;
3432
#endif
3433
};
3434

    
3435
struct mg_connection;
3436

    
3437
/*
3438
 * Callback function (event handler) prototype. Must be defined by the user.
3439
 * Mongoose calls the event handler, passing the events defined below.
3440
 */
3441
typedef void (*mg_event_handler_t)(struct mg_connection *nc, int ev,
3442
                                   void *ev_data MG_UD_ARG(void *user_data));
3443

    
3444
/* Events. Meaning of event parameter (evp) is given in the comment. */
3445
#define MG_EV_POLL 0    /* Sent to each connection on each mg_mgr_poll() call */
3446
#define MG_EV_ACCEPT 1  /* New connection accepted. union socket_address * */
3447
#define MG_EV_CONNECT 2 /* connect() succeeded or failed. int *  */
3448
#define MG_EV_RECV 3    /* Data has been received. int *num_bytes */
3449
#define MG_EV_SEND 4    /* Data has been written to a socket. int *num_bytes */
3450
#define MG_EV_CLOSE 5   /* Connection is closed. NULL */
3451
#define MG_EV_TIMER 6   /* now >= conn->ev_timer_time. double * */
3452

    
3453
/*
3454
 * Mongoose event manager.
3455
 */
3456
struct mg_mgr {
3457
  struct mg_connection *active_connections;
3458
#if MG_ENABLE_HEXDUMP
3459
  const char *hexdump_file; /* Debug hexdump file path */
3460
#endif
3461
#if MG_ENABLE_BROADCAST
3462
  sock_t ctl[2]; /* Socketpair for mg_broadcast() */
3463
#endif
3464
  void *user_data; /* User data */
3465
  int num_ifaces;
3466
  struct mg_iface **ifaces; /* network interfaces */
3467
  const char *nameserver;   /* DNS server to use */
3468
};
3469

    
3470
/*
3471
 * Mongoose connection.
3472
 */
3473
struct mg_connection {
3474
  struct mg_connection *next, *prev; /* mg_mgr::active_connections linkage */
3475
  struct mg_connection *listener;    /* Set only for accept()-ed connections */
3476
  struct mg_mgr *mgr;                /* Pointer to containing manager */
3477

    
3478
  sock_t sock; /* Socket to the remote peer */
3479
  int err;
3480
  union socket_address sa; /* Remote peer address */
3481
  size_t recv_mbuf_limit;  /* Max size of recv buffer */
3482
  struct mbuf recv_mbuf;   /* Received data */
3483
  struct mbuf send_mbuf;   /* Data scheduled for sending */
3484
  time_t last_io_time;     /* Timestamp of the last socket IO */
3485
  double ev_timer_time;    /* Timestamp of the future MG_EV_TIMER */
3486
#if MG_ENABLE_SSL
3487
  void *ssl_if_data; /* SSL library data. */
3488
#endif
3489
  mg_event_handler_t proto_handler; /* Protocol-specific event handler */
3490
  void *proto_data;                 /* Protocol-specific data */
3491
  void (*proto_data_destructor)(void *proto_data);
3492
  mg_event_handler_t handler; /* Event handler function */
3493
  void *user_data;            /* User-specific data */
3494
  union {
3495
    void *v;
3496
    /*
3497
     * the C standard is fussy about fitting function pointers into
3498
     * void pointers, since some archs might have fat pointers for functions.
3499
     */
3500
    mg_event_handler_t f;
3501
  } priv_1;
3502
  void *priv_2;
3503
  void *mgr_data; /* Implementation-specific event manager's data. */
3504
  struct mg_iface *iface;
3505
  unsigned long flags;
3506
/* Flags set by Mongoose */
3507
#define MG_F_LISTENING (1 << 0)          /* This connection is listening */
3508
#define MG_F_UDP (1 << 1)                /* This connection is UDP */
3509
#define MG_F_RESOLVING (1 << 2)          /* Waiting for async resolver */
3510
#define MG_F_CONNECTING (1 << 3)         /* connect() call in progress */
3511
#define MG_F_SSL (1 << 4)                /* SSL is enabled on the connection */
3512
#define MG_F_SSL_HANDSHAKE_DONE (1 << 5) /* SSL hanshake has completed */
3513
#define MG_F_WANT_READ (1 << 6)          /* SSL specific */
3514
#define MG_F_WANT_WRITE (1 << 7)         /* SSL specific */
3515
#define MG_F_IS_WEBSOCKET (1 << 8)       /* Websocket specific */
3516

    
3517
/* Flags that are settable by user */
3518
#define MG_F_SEND_AND_CLOSE (1 << 10)      /* Push remaining data and close  */
3519
#define MG_F_CLOSE_IMMEDIATELY (1 << 11)   /* Disconnect */
3520
#define MG_F_WEBSOCKET_NO_DEFRAG (1 << 12) /* Websocket specific */
3521
#define MG_F_DELETE_CHUNK (1 << 13)        /* HTTP specific */
3522
#define MG_F_ENABLE_BROADCAST (1 << 14)    /* Allow broadcast address usage */
3523

    
3524
#define MG_F_USER_1 (1 << 20) /* Flags left for application */
3525
#define MG_F_USER_2 (1 << 21)
3526
#define MG_F_USER_3 (1 << 22)
3527
#define MG_F_USER_4 (1 << 23)
3528
#define MG_F_USER_5 (1 << 24)
3529
#define MG_F_USER_6 (1 << 25)
3530
};
3531

    
3532
/*
3533
 * Initialise Mongoose manager. Side effect: ignores SIGPIPE signal.
3534
 * `mgr->user_data` field will be initialised with a `user_data` parameter.
3535
 * That is an arbitrary pointer, where the user code can associate some data
3536
 * with the particular Mongoose manager. For example, a C++ wrapper class
3537
 * could be written in which case `user_data` can hold a pointer to the
3538
 * class instance.
3539
 */
3540
void mg_mgr_init(struct mg_mgr *mgr, void *user_data);
3541

    
3542
/*
3543
 * Optional parameters to `mg_mgr_init_opt()`.
3544
 *
3545
 * If `main_iface` is not NULL, it will be used as the main interface in the
3546
 * default interface set. The pointer will be free'd by `mg_mgr_free`.
3547
 * Otherwise, the main interface will be autodetected based on the current
3548
 * platform.
3549
 *
3550
 * If `num_ifaces` is 0 and `ifaces` is NULL, the default interface set will be
3551
 * used.
3552
 * This is an advanced option, as it requires you to construct a full interface
3553
 * set, including special networking interfaces required by some optional
3554
 * features such as TCP tunneling. Memory backing `ifaces` and each of the
3555
 * `num_ifaces` pointers it contains will be reclaimed by `mg_mgr_free`.
3556
 */
3557
struct mg_mgr_init_opts {
3558
  const struct mg_iface_vtable *main_iface;
3559
  int num_ifaces;
3560
  const struct mg_iface_vtable **ifaces;
3561
  const char *nameserver;
3562
};
3563

    
3564
/*
3565
 * Like `mg_mgr_init` but with more options.
3566
 *
3567
 * Notably, this allows you to create a manger and choose
3568
 * dynamically which networking interface implementation to use.
3569
 */
3570
void mg_mgr_init_opt(struct mg_mgr *mgr, void *user_data,
3571
                     struct mg_mgr_init_opts opts);
3572

    
3573
/*
3574
 * De-initialises Mongoose manager.
3575
 *
3576
 * Closes and deallocates all active connections.
3577
 */
3578
void mg_mgr_free(struct mg_mgr *);
3579

    
3580
/*
3581
 * This function performs the actual IO and must be called in a loop
3582
 * (an event loop). It returns the current timestamp.
3583
 * `milli` is the maximum number of milliseconds to sleep.
3584
 * `mg_mgr_poll()` checks all connections for IO readiness. If at least one
3585
 * of the connections is IO-ready, `mg_mgr_poll()` triggers the respective
3586
 * event handlers and returns.
3587
 */
3588
time_t mg_mgr_poll(struct mg_mgr *, int milli);
3589

    
3590
#if MG_ENABLE_BROADCAST
3591
/*
3592
 * Passes a message of a given length to all connections.
3593
 *
3594
 * Must be called from a thread that does NOT call `mg_mgr_poll()`.
3595
 * Note that `mg_broadcast()` is the only function
3596
 * that can be, and must be, called from a different (non-IO) thread.
3597
 *
3598
 * `func` callback function will be called by the IO thread for each
3599
 * connection. When called, the event will be `MG_EV_POLL`, and a message will
3600
 * be passed as the `ev_data` pointer. Maximum message size is capped
3601
 * by `MG_CTL_MSG_MESSAGE_SIZE` which is set to 8192 bytes.
3602
 */
3603
void mg_broadcast(struct mg_mgr *mgr, mg_event_handler_t cb, void *data,
3604
                  size_t len);
3605
#endif
3606

    
3607
/*
3608
 * Iterates over all active connections.
3609
 *
3610
 * Returns the next connection from the list
3611
 * of active connections or `NULL` if there are no more connections. Below
3612
 * is the iteration idiom:
3613
 *
3614
 * ```c
3615
 * for (c = mg_next(srv, NULL); c != NULL; c = mg_next(srv, c)) {
3616
 *   // Do something with connection `c`
3617
 * }
3618
 * ```
3619
 */
3620
struct mg_connection *mg_next(struct mg_mgr *mgr, struct mg_connection *c);
3621

    
3622
/*
3623
 * Optional parameters to `mg_add_sock_opt()`.
3624
 *
3625
 * `flags` is an initial `struct mg_connection::flags` bitmask to set,
3626
 * see `MG_F_*` flags definitions.
3627
 */
3628
struct mg_add_sock_opts {
3629
  void *user_data;           /* Initial value for connection's user_data */
3630
  unsigned int flags;        /* Initial connection flags */
3631
  const char **error_string; /* Placeholder for the error string */
3632
  struct mg_iface *iface;    /* Interface instance */
3633
};
3634

    
3635
/*
3636
 * Creates a connection, associates it with the given socket and event handler
3637
 * and adds it to the manager.
3638
 *
3639
 * For more options see the `mg_add_sock_opt` variant.
3640
 */
3641
struct mg_connection *mg_add_sock(struct mg_mgr *mgr, sock_t sock,
3642
                                  MG_CB(mg_event_handler_t handler,
3643
                                        void *user_data));
3644

    
3645
/*
3646
 * Creates a connection, associates it with the given socket and event handler
3647
 * and adds to the manager.
3648
 *
3649
 * See the `mg_add_sock_opts` structure for a description of the options.
3650
 */
3651
struct mg_connection *mg_add_sock_opt(struct mg_mgr *mgr, sock_t sock,
3652
                                      MG_CB(mg_event_handler_t handler,
3653
                                            void *user_data),
3654
                                      struct mg_add_sock_opts opts);
3655

    
3656
/*
3657
 * Optional parameters to `mg_bind_opt()`.
3658
 *
3659
 * `flags` is an initial `struct mg_connection::flags` bitmask to set,
3660
 * see `MG_F_*` flags definitions.
3661
 */
3662
struct mg_bind_opts {
3663
  void *user_data;           /* Initial value for connection's user_data */
3664
  unsigned int flags;        /* Extra connection flags */
3665
  const char **error_string; /* Placeholder for the error string */
3666
  struct mg_iface *iface;    /* Interface instance */
3667
#if MG_ENABLE_SSL
3668
  /*
3669
   * SSL settings.
3670
   *
3671
   * Server certificate to present to clients or client certificate to
3672
   * present to tunnel dispatcher (for tunneled connections).
3673
   */
3674
  const char *ssl_cert;
3675
  /* Private key corresponding to the certificate. If ssl_cert is set but
3676
   * ssl_key is not, ssl_cert is used. */
3677
  const char *ssl_key;
3678
  /* CA bundle used to verify client certificates or tunnel dispatchers. */
3679
  const char *ssl_ca_cert;
3680
  /* Colon-delimited list of acceptable cipher suites.
3681
   * Names depend on the library used, for example:
3682
   *
3683
   * ECDH-ECDSA-AES128-GCM-SHA256:DHE-RSA-AES128-SHA256 (OpenSSL)
3684
   * TLS-ECDH-ECDSA-WITH-AES-128-GCM-SHA256:TLS-DHE-RSA-WITH-AES-128-GCM-SHA256
3685
   *   (mbedTLS)
3686
   *
3687
   * For OpenSSL the list can be obtained by running "openssl ciphers".
3688
   * For mbedTLS, names can be found in library/ssl_ciphersuites.c
3689
   * If NULL, a reasonable default is used.
3690
   */
3691
  const char *ssl_cipher_suites;
3692
#endif
3693
};
3694

    
3695
/*
3696
 * Creates a listening connection.
3697
 *
3698
 * See `mg_bind_opt` for full documentation.
3699
 */
3700
struct mg_connection *mg_bind(struct mg_mgr *mgr, const char *address,
3701
                              MG_CB(mg_event_handler_t handler,
3702
                                    void *user_data));
3703
/*
3704
 * Creates a listening connection.
3705
 *
3706
 * The `address` parameter specifies which address to bind to. It's format is
3707
 * the same as for the `mg_connect()` call, where `HOST` part is optional.
3708
 * `address` can be just a port number, e.g. `:8000`. To bind to a specific
3709
 * interface, an IP address can be specified, e.g. `1.2.3.4:8000`. By default,
3710
 * a TCP connection is created. To create UDP connection, prepend `udp://`
3711
 * prefix, e.g. `udp://:8000`. To summarize, `address` parameter has following
3712
 * format: `[PROTO://][IP_ADDRESS]:PORT`, where `PROTO` could be `tcp` or
3713
 * `udp`.
3714
 *
3715
 * See the `mg_bind_opts` structure for a description of the optional
3716
 * parameters.
3717
 *
3718
 * Returns a new listening connection or `NULL` on error.
3719
 * NOTE: The connection remains owned by the manager, do not free().
3720
 */
3721
struct mg_connection *mg_bind_opt(struct mg_mgr *mgr, const char *address,
3722
                                  MG_CB(mg_event_handler_t handler,
3723
                                        void *user_data),
3724
                                  struct mg_bind_opts opts);
3725

    
3726
/* Optional parameters to `mg_connect_opt()` */
3727
struct mg_connect_opts {
3728
  void *user_data;           /* Initial value for connection's user_data */
3729
  unsigned int flags;        /* Extra connection flags */
3730
  const char **error_string; /* Placeholder for the error string */
3731
  struct mg_iface *iface;    /* Interface instance */
3732
  const char *nameserver;    /* DNS server to use, NULL for default */
3733
#if MG_ENABLE_SSL
3734
  /*
3735
   * SSL settings.
3736
   * Client certificate to present to the server.
3737
   */
3738
  const char *ssl_cert;
3739
  /*
3740
   * Private key corresponding to the certificate.
3741
   * If ssl_cert is set but ssl_key is not, ssl_cert is used.
3742
   */
3743
  const char *ssl_key;
3744
  /*
3745
   * Verify server certificate using this CA bundle. If set to "*", then SSL
3746
   * is enabled but no cert verification is performed.
3747
   */
3748
  const char *ssl_ca_cert;
3749
  /* Colon-delimited list of acceptable cipher suites.
3750
   * Names depend on the library used, for example:
3751
   *
3752
   * ECDH-ECDSA-AES128-GCM-SHA256:DHE-RSA-AES128-SHA256 (OpenSSL)
3753
   * TLS-ECDH-ECDSA-WITH-AES-128-GCM-SHA256:TLS-DHE-RSA-WITH-AES-128-GCM-SHA256
3754
   *   (mbedTLS)
3755
   *
3756
   * For OpenSSL the list can be obtained by running "openssl ciphers".
3757
   * For mbedTLS, names can be found in library/ssl_ciphersuites.c
3758
   * If NULL, a reasonable default is used.
3759
   */
3760
  const char *ssl_cipher_suites;
3761
  /*
3762
   * Server name verification. If ssl_ca_cert is set and the certificate has
3763
   * passed verification, its subject will be verified against this string.
3764
   * By default (if ssl_server_name is NULL) hostname part of the address will
3765
   * be used. Wildcard matching is supported. A special value of "*" disables
3766
   * name verification.
3767
   */
3768
  const char *ssl_server_name;
3769
  /*
3770
   * PSK identity and key. Identity is a NUL-terminated string and key is a hex
3771
   * string. Key must be either 16 or 32 bytes (32 or 64 hex digits) for AES-128
3772
   * or AES-256 respectively.
3773
   * Note: Default list of cipher suites does not include PSK suites, if you
3774
   * want to use PSK you will need to set ssl_cipher_suites as well.
3775
   */
3776
  const char *ssl_psk_identity;
3777
  const char *ssl_psk_key;
3778
#endif
3779
};
3780

    
3781
/*
3782
 * Connects to a remote host.
3783
 *
3784
 * See `mg_connect_opt()` for full documentation.
3785
 */
3786
struct mg_connection *mg_connect(struct mg_mgr *mgr, const char *address,
3787
                                 MG_CB(mg_event_handler_t handler,
3788
                                       void *user_data));
3789

    
3790
/*
3791
 * Connects to a remote host.
3792
 *
3793
 * The `address` format is `[PROTO://]HOST:PORT`. `PROTO` could be `tcp` or
3794
 * `udp`. `HOST` could be an IP address,
3795
 * IPv6 address (if Mongoose is compiled with `-DMG_ENABLE_IPV6`) or a host
3796
 * name. If `HOST` is a name, Mongoose will resolve it asynchronously. Examples
3797
 * of valid addresses: `google.com:80`, `udp://1.2.3.4:53`, `10.0.0.1:443`,
3798
 * `[::1]:80`
3799
 *
3800
 * See the `mg_connect_opts` structure for a description of the optional
3801
 * parameters.
3802
 *
3803
 * Returns a new outbound connection or `NULL` on error.
3804
 *
3805
 * NOTE: The connection remains owned by the manager, do not free().
3806
 *
3807
 * NOTE: To enable IPv6 addresses `-DMG_ENABLE_IPV6` should be specified
3808
 * in the compilation flags.
3809
 *
3810
 * NOTE: The new connection will receive `MG_EV_CONNECT` as its first event
3811
 * which will report the connect success status.
3812
 * If the asynchronous resolution fails or the `connect()` syscall fails for
3813
 * whatever reason (e.g. with `ECONNREFUSED` or `ENETUNREACH`), then
3814
 * `MG_EV_CONNECT` event will report failure. Code example below:
3815
 *
3816
 * ```c
3817
 * static void ev_handler(struct mg_connection *nc, int ev, void *ev_data) {
3818
 *   int connect_status;
3819
 *
3820
 *   switch (ev) {
3821
 *     case MG_EV_CONNECT:
3822
 *       connect_status = * (int *) ev_data;
3823
 *       if (connect_status == 0) {
3824
 *         // Success
3825
 *       } else  {
3826
 *         // Error
3827
 *         printf("connect() error: %s\n", strerror(connect_status));
3828
 *       }
3829
 *       break;
3830
 *     ...
3831
 *   }
3832
 * }
3833
 *
3834
 *   ...
3835
 *   mg_connect(mgr, "my_site.com:80", ev_handler);
3836
 * ```
3837
 */
3838
struct mg_connection *mg_connect_opt(struct mg_mgr *mgr, const char *address,
3839
                                     MG_CB(mg_event_handler_t handler,
3840
                                           void *user_data),
3841
                                     struct mg_connect_opts opts);
3842

    
3843
#if MG_ENABLE_SSL && MG_NET_IF != MG_NET_IF_SIMPLELINK
3844
/*
3845
 * Note: This function is deprecated. Please, use SSL options in
3846
 * mg_connect_opt.
3847
 *
3848
 * Enables SSL for a given connection.
3849
 * `cert` is a server certificate file name for a listening connection
3850
 * or a client certificate file name for an outgoing connection.
3851
 * The certificate files must be in PEM format. The server certificate file
3852
 * must contain a certificate, concatenated with a private key, optionally
3853
 * concatenated with DH parameters.
3854
 * `ca_cert` is a CA certificate or NULL if peer verification is not
3855
 * required.
3856
 * Return: NULL on success or error message on error.
3857
 */
3858
const char *mg_set_ssl(struct mg_connection *nc, const char *cert,
3859
                       const char *ca_cert);
3860
#endif
3861

    
3862
/*
3863
 * Sends data to the connection.
3864
 *
3865
 * Note that sending functions do not actually push data to the socket.
3866
 * They just append data to the output buffer. MG_EV_SEND will be delivered when
3867
 * the data has actually been pushed out.
3868
 */
3869
void mg_send(struct mg_connection *, const void *buf, int len);
3870

    
3871
/* Enables format string warnings for mg_printf */
3872
#if defined(__GNUC__)
3873
__attribute__((format(printf, 2, 3)))
3874
#endif
3875
/* don't separate from mg_printf declaration */
3876

    
3877
/*
3878
 * Sends `printf`-style formatted data to the connection.
3879
 *
3880
 * See `mg_send` for more details on send semantics.
3881
 */
3882
int mg_printf(struct mg_connection *, const char *fmt, ...);
3883

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

    
3887
/*
3888
 * Creates a socket pair.
3889
 * `sock_type` can be either `SOCK_STREAM` or `SOCK_DGRAM`.
3890
 * Returns 0 on failure and 1 on success.
3891
 */
3892
int mg_socketpair(sock_t[2], int sock_type);
3893

    
3894
#if MG_ENABLE_SYNC_RESOLVER
3895
/*
3896
 * Convert domain name into IP address.
3897
 *
3898
 * This is a utility function. If compilation flags have
3899
 * `-DMG_ENABLE_GETADDRINFO`, then `getaddrinfo()` call is used for name
3900
 * resolution. Otherwise, `gethostbyname()` is used.
3901
 *
3902
 * CAUTION: this function can block.
3903
 * Return 1 on success, 0 on failure.
3904
 */
3905
int mg_resolve(const char *domain_name, char *ip_addr_buf, size_t buf_len);
3906
#endif
3907

    
3908
/*
3909
 * Verify given IP address against the ACL.
3910
 *
3911
 * `remote_ip` - an IPv4 address to check, in host byte order
3912
 * `acl` - a comma separated list of IP subnets: `x.x.x.x/x` or `x.x.x.x`.
3913
 * Each subnet is
3914
 * prepended by either a - or a + sign. A plus sign means allow, where a
3915
 * minus sign means deny. If a subnet mask is omitted, such as `-1.2.3.4`,
3916
 * it means that only that single IP address is denied.
3917
 * Subnet masks may vary from 0 to 32, inclusive. The default setting
3918
 * is to allow all access. On each request the full list is traversed,
3919
 * and the last match wins. Example:
3920
 *
3921
 * `-0.0.0.0/0,+192.168/16` - deny all accesses, only allow 192.168/16 subnet
3922
 *
3923
 * To learn more about subnet masks, see this
3924
 * link:https://en.wikipedia.org/wiki/Subnetwork[Wikipedia page on Subnetwork].
3925
 *
3926
 * Returns -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
3927
 */
3928
int mg_check_ip_acl(const char *acl, uint32_t remote_ip);
3929

    
3930
/*
3931
 * Schedules an MG_EV_TIMER event to be delivered at `timestamp` time.
3932
 * `timestamp` is UNIX time (the number of seconds since Epoch). It is
3933
 * `double` instead of `time_t` to allow for sub-second precision.
3934
 * Returns the old timer value.
3935
 *
3936
 * Example: set the connect timeout to 1.5 seconds:
3937
 *
3938
 * ```
3939
 *  c = mg_connect(&mgr, "cesanta.com", ev_handler);
3940
 *  mg_set_timer(c, mg_time() + 1.5);
3941
 *  ...
3942
 *
3943
 *  void ev_handler(struct mg_connection *c, int ev, void *ev_data) {
3944
 *  switch (ev) {
3945
 *    case MG_EV_CONNECT:
3946
 *      mg_set_timer(c, 0);  // Clear connect timer
3947
 *      break;
3948
 *    case MG_EV_TIMER:
3949
 *      log("Connect timeout");
3950
 *      c->flags |= MG_F_CLOSE_IMMEDIATELY;
3951
 *      break;
3952
 * ```
3953
 */
3954
double mg_set_timer(struct mg_connection *c, double timestamp);
3955

    
3956
/*
3957
 * A sub-second precision version of time().
3958
 */
3959
double mg_time(void);
3960

    
3961
#ifdef __cplusplus
3962
}
3963
#endif /* __cplusplus */
3964

    
3965
#endif /* CS_MONGOOSE_SRC_NET_H_ */
3966
#ifdef MG_MODULE_LINES
3967
#line 1 "mongoose/src/mg_uri.h"
3968
#endif
3969
/*
3970
 * Copyright (c) 2014 Cesanta Software Limited
3971
 * All rights reserved
3972
 */
3973

    
3974
/*
3975
 * === URI
3976
 */
3977

    
3978
#ifndef CS_MONGOOSE_SRC_URI_H_
3979
#define CS_MONGOOSE_SRC_URI_H_
3980

    
3981
/* Amalgamated: #include "mg_net.h" */
3982

    
3983
#ifdef __cplusplus
3984
extern "C" {
3985
#endif /* __cplusplus */
3986

    
3987
/*
3988
 * Parses an URI and fills string chunks with locations of the respective
3989
 * uri components within the input uri string. NULL pointers will be
3990
 * ignored.
3991
 *
3992
 * General syntax:
3993
 *
3994
 *     [scheme://[user_info@]]host[:port][/path][?query][#fragment]
3995
 *
3996
 * Example:
3997
 *
3998
 *     foo.com:80
3999
 *     tcp://foo.com:1234
4000
 *     http://foo.com:80/bar?baz=1
4001
 *     https://user:pw@foo.com:443/blah
4002
 *
4003
 * `path` will include the leading slash. `query` won't include the leading `?`.
4004
 * `host` can contain embedded colons if surrounded by square brackets in order
4005
 * to support IPv6 literal addresses.
4006
 *
4007
 *
4008
 * Returns 0 on success, -1 on error.
4009
 */
4010
int mg_parse_uri(const struct mg_str uri, struct mg_str *scheme,
4011
                 struct mg_str *user_info, struct mg_str *host,
4012
                 unsigned int *port, struct mg_str *path, struct mg_str *query,
4013
                 struct mg_str *fragment);
4014

    
4015
/*
4016
 * Assemble URI from parts. Any of the inputs can be NULL or zero-length mg_str.
4017
 *
4018
 * If normalize_path is true, path is normalized by resolving relative refs.
4019
 *
4020
 * Result is a heap-allocated string (uri->p must be free()d after use).
4021
 *
4022
 * Returns 0 on success, -1 on error.
4023
 */
4024
int mg_assemble_uri(const struct mg_str *scheme, const struct mg_str *user_info,
4025
                    const struct mg_str *host, unsigned int port,
4026
                    const struct mg_str *path, const struct mg_str *query,
4027
                    const struct mg_str *fragment, int normalize_path,
4028
                    struct mg_str *uri);
4029

    
4030
int mg_normalize_uri_path(const struct mg_str *in, struct mg_str *out);
4031

    
4032
#ifdef __cplusplus
4033
}
4034
#endif /* __cplusplus */
4035
#endif /* CS_MONGOOSE_SRC_URI_H_ */
4036
#ifdef MG_MODULE_LINES
4037
#line 1 "mongoose/src/mg_util.h"
4038
#endif
4039
/*
4040
 * Copyright (c) 2014 Cesanta Software Limited
4041
 * All rights reserved
4042
 */
4043

    
4044
/*
4045
 * === Utility API
4046
 */
4047

    
4048
#ifndef CS_MONGOOSE_SRC_UTIL_H_
4049
#define CS_MONGOOSE_SRC_UTIL_H_
4050

    
4051
#include <stdio.h>
4052

    
4053
/* Amalgamated: #include "mg_common.h" */
4054
/* Amalgamated: #include "mg_net_if.h" */
4055

    
4056
#ifdef __cplusplus
4057
extern "C" {
4058
#endif /* __cplusplus */
4059

    
4060
#ifndef MG_MAX_PATH
4061
#ifdef PATH_MAX
4062
#define MG_MAX_PATH PATH_MAX
4063
#else
4064
#define MG_MAX_PATH 256
4065
#endif
4066
#endif
4067

    
4068
/*
4069
 * Fetches substring from input string `s`, `end` into `v`.
4070
 * Skips initial delimiter characters. Records first non-delimiter character
4071
 * at the beginning of substring `v`. Then scans the rest of the string
4072
 * until a delimiter character or end-of-string is found.
4073
 * `delimiters` is a 0-terminated string containing delimiter characters.
4074
 * Either one of `delimiters` or `end_string` terminates the search.
4075
 * Returns an `s` pointer, advanced forward where parsing has stopped.
4076
 */
4077
const char *mg_skip(const char *s, const char *end_string,
4078
                    const char *delimiters, struct mg_str *v);
4079

    
4080
/*
4081
 * Decodes base64-encoded string `s`, `len` into the destination `dst`.
4082
 * The destination has to have enough space to hold the decoded buffer.
4083
 * Decoding stops either when all strings have been decoded or invalid an
4084
 * character appeared.
4085
 * Destination is '\0'-terminated.
4086
 * Returns the number of decoded characters. On success, that should be equal
4087
 * to `len`. On error (invalid character) the return value is smaller then
4088
 * `len`.
4089
 */
4090
int mg_base64_decode(const unsigned char *s, int len, char *dst);
4091

    
4092
/*
4093
 * Base64-encode chunk of memory `src`, `src_len` into the destination `dst`.
4094
 * Destination has to have enough space to hold encoded buffer.
4095
 * Destination is '\0'-terminated.
4096
 */
4097
void mg_base64_encode(const unsigned char *src, int src_len, char *dst);
4098

    
4099
#if MG_ENABLE_FILESYSTEM
4100
/*
4101
 * Performs a 64-bit `stat()` call against a given file.
4102
 *
4103
 * `path` should be UTF8 encoded.
4104
 *
4105
 * Return value is the same as for `stat()` syscall.
4106
 */
4107
int mg_stat(const char *path, cs_stat_t *st);
4108

    
4109
/*
4110
 * Opens the given file and returns a file stream.
4111
 *
4112
 * `path` and `mode` should be UTF8 encoded.
4113
 *
4114
 * Return value is the same as for the `fopen()` call.
4115
 */
4116
FILE *mg_fopen(const char *path, const char *mode);
4117

    
4118
/*
4119
 * Opens the given file and returns a file stream.
4120
 *
4121
 * `path` should be UTF8 encoded.
4122
 *
4123
 * Return value is the same as for the `open()` syscall.
4124
 */
4125
int mg_open(const char *path, int flag, int mode);
4126

    
4127
/*
4128
 * Reads data from the given file stream.
4129
 *
4130
 * Return value is a number of bytes readen.
4131
 */
4132
size_t mg_fread(void *ptr, size_t size, size_t count, FILE *f);
4133

    
4134
/*
4135
 * Writes data to the given file stream.
4136
 *
4137
 * Return value is a number of bytes wtitten.
4138
 */
4139
size_t mg_fwrite(const void *ptr, size_t size, size_t count, FILE *f);
4140

    
4141
#endif /* MG_ENABLE_FILESYSTEM */
4142

    
4143
#if MG_ENABLE_THREADS
4144
/*
4145
 * Starts a new detached thread.
4146
 * Arguments and semantics are the same as pthead's `pthread_create()`.
4147
 * `thread_func` is a thread function, `thread_func_param` is a parameter
4148
 * that is passed to the thread function.
4149
 */
4150
void *mg_start_thread(void *(*thread_func)(void *), void *thread_func_param);
4151
#endif
4152

    
4153
void mg_set_close_on_exec(sock_t);
4154

    
4155
#define MG_SOCK_STRINGIFY_IP 1
4156
#define MG_SOCK_STRINGIFY_PORT 2
4157
#define MG_SOCK_STRINGIFY_REMOTE 4
4158
/*
4159
 * Converts a connection's local or remote address into string.
4160
 *
4161
 * The `flags` parameter is a bit mask that controls the behaviour,
4162
 * see `MG_SOCK_STRINGIFY_*` definitions.
4163
 *
4164
 * - MG_SOCK_STRINGIFY_IP - print IP address
4165
 * - MG_SOCK_STRINGIFY_PORT - print port number
4166
 * - MG_SOCK_STRINGIFY_REMOTE - print remote peer's IP/port, not local address
4167
 *
4168
 * If both port number and IP address are printed, they are separated by `:`.
4169
 * If compiled with `-DMG_ENABLE_IPV6`, IPv6 addresses are supported.
4170
 * Return length of the stringified address.
4171
 */
4172
int mg_conn_addr_to_str(struct mg_connection *c, char *buf, size_t len,
4173
                        int flags);
4174
#if MG_NET_IF == MG_NET_IF_SOCKET
4175
/* Legacy interface. */
4176
void mg_sock_to_str(sock_t sock, char *buf, size_t len, int flags);
4177
#endif
4178

    
4179
/*
4180
 * Convert the socket's address into string.
4181
 *
4182
 * `flags` is MG_SOCK_STRINGIFY_IP and/or MG_SOCK_STRINGIFY_PORT.
4183
 */
4184
int mg_sock_addr_to_str(const union socket_address *sa, char *buf, size_t len,
4185
                        int flags);
4186

    
4187
#if MG_ENABLE_HEXDUMP
4188
/*
4189
 * Generates a human-readable hexdump of memory chunk.
4190
 *
4191
 * Takes a memory buffer `buf` of length `len` and creates a hex dump of that
4192
 * buffer in `dst`. The generated output is a-la hexdump(1).
4193
 * Returns the length of generated string, excluding terminating `\0`. If
4194
 * returned length is bigger than `dst_len`, the overflow bytes are discarded.
4195
 */
4196
int mg_hexdump(const void *buf, int len, char *dst, int dst_len);
4197

    
4198
/* Same as mg_hexdump, but with output going to file instead of a buffer. */
4199
void mg_hexdumpf(FILE *fp, const void *buf, int len);
4200

    
4201
/*
4202
 * Generates human-readable hexdump of the data sent or received by the
4203
 * connection. `path` is a file name where hexdump should be written.
4204
 * `num_bytes` is a number of bytes sent/received. `ev` is one of the `MG_*`
4205
 * events sent to an event handler. This function is supposed to be called from
4206
 * the event handler.
4207
 */
4208
void mg_hexdump_connection(struct mg_connection *nc, const char *path,
4209
                           const void *buf, int num_bytes, int ev);
4210
#endif
4211

    
4212
/*
4213
 * Returns true if target platform is big endian.
4214
 */
4215
int mg_is_big_endian(void);
4216

    
4217
/*
4218
 * Use with cs_base64_init/update/finish in order to write out base64 in chunks.
4219
 */
4220
void mg_mbuf_append_base64_putc(char ch, void *user_data);
4221

    
4222
/*
4223
 * Encode `len` bytes starting at `data` as base64 and append them to an mbuf.
4224
 */
4225
void mg_mbuf_append_base64(struct mbuf *mbuf, const void *data, size_t len);
4226

    
4227
/*
4228
 * Generate a Basic Auth header and appends it to buf.
4229
 * If pass is NULL, then user is expected to contain the credentials pair
4230
 * already encoded as `user:pass`.
4231
 */
4232
void mg_basic_auth_header(const struct mg_str user, const struct mg_str pass,
4233
                          struct mbuf *buf);
4234

    
4235
/*
4236
 * URL-escape the specified string.
4237
 * All non-printable characters are escaped, plus `._-$,;~()/`.
4238
 * Input need not be NUL-terminated, but the returned string is.
4239
 * Returned string is heap-allocated and must be free()'d.
4240
 */
4241
struct mg_str mg_url_encode(const struct mg_str src);
4242

    
4243
#ifdef __cplusplus
4244
}
4245
#endif /* __cplusplus */
4246
#endif /* CS_MONGOOSE_SRC_UTIL_H_ */
4247
#ifdef MG_MODULE_LINES
4248
#line 1 "mongoose/src/mg_http.h"
4249
#endif
4250
/*
4251
 * Copyright (c) 2014 Cesanta Software Limited
4252
 * All rights reserved
4253
 */
4254

    
4255
/*
4256
 * === Common API reference
4257
 */
4258

    
4259
#ifndef CS_MONGOOSE_SRC_HTTP_H_
4260
#define CS_MONGOOSE_SRC_HTTP_H_
4261

    
4262
#if MG_ENABLE_HTTP
4263

    
4264
/* Amalgamated: #include "mg_net.h" */
4265
/* Amalgamated: #include "common/mg_str.h" */
4266

    
4267
#ifdef __cplusplus
4268
extern "C" {
4269
#endif /* __cplusplus */
4270

    
4271
#ifndef MG_MAX_HTTP_HEADERS
4272
#define MG_MAX_HTTP_HEADERS 20
4273
#endif
4274

    
4275
#ifndef MG_MAX_HTTP_REQUEST_SIZE
4276
#define MG_MAX_HTTP_REQUEST_SIZE 1024
4277
#endif
4278

    
4279
#ifndef MG_MAX_HTTP_SEND_MBUF
4280
#define MG_MAX_HTTP_SEND_MBUF 1024
4281
#endif
4282

    
4283
#ifndef MG_CGI_ENVIRONMENT_SIZE
4284
#define MG_CGI_ENVIRONMENT_SIZE 8192
4285
#endif
4286

    
4287
/* HTTP message */
4288
struct http_message {
4289
  struct mg_str message; /* Whole message: request line + headers + body */
4290
  struct mg_str body;    /* Message body. 0-length for requests with no body */
4291

    
4292
  /* HTTP Request line (or HTTP response line) */
4293
  struct mg_str method; /* "GET" */
4294
  struct mg_str uri;    /* "/my_file.html" */
4295
  struct mg_str proto;  /* "HTTP/1.1" -- for both request and response */
4296

    
4297
  /* For responses, code and response status message are set */
4298
  int resp_code;
4299
  struct mg_str resp_status_msg;
4300

    
4301
  /*
4302
   * Query-string part of the URI. For example, for HTTP request
4303
   *    GET /foo/bar?param1=val1&param2=val2
4304
   *    |    uri    |     query_string     |
4305
   *
4306
   * Note that question mark character doesn't belong neither to the uri,
4307
   * nor to the query_string
4308
   */
4309
  struct mg_str query_string;
4310

    
4311
  /* Headers */
4312
  struct mg_str header_names[MG_MAX_HTTP_HEADERS];
4313
  struct mg_str header_values[MG_MAX_HTTP_HEADERS];
4314
};
4315

    
4316
#if MG_ENABLE_HTTP_WEBSOCKET
4317
/* WebSocket message */
4318
struct websocket_message {
4319
  unsigned char *data;
4320
  size_t size;
4321
  unsigned char flags;
4322
};
4323
#endif
4324

    
4325
/* HTTP multipart part */
4326
struct mg_http_multipart_part {
4327
  const char *file_name;
4328
  const char *var_name;
4329
  struct mg_str data;
4330
  int status; /* <0 on error */
4331
  void *user_data;
4332
};
4333

    
4334
/* SSI call context */
4335
struct mg_ssi_call_ctx {
4336
  struct http_message *req; /* The request being processed. */
4337
  struct mg_str file;       /* Filesystem path of the file being processed. */
4338
  struct mg_str arg; /* The argument passed to the tag: <!-- call arg -->. */
4339
};
4340

    
4341
/* HTTP and websocket events. void *ev_data is described in a comment. */
4342
#define MG_EV_HTTP_REQUEST 100 /* struct http_message * */
4343
#define MG_EV_HTTP_REPLY 101   /* struct http_message * */
4344
#define MG_EV_HTTP_CHUNK 102   /* struct http_message * */
4345
#define MG_EV_SSI_CALL 105     /* char * */
4346
#define MG_EV_SSI_CALL_CTX 106 /* struct mg_ssi_call_ctx * */
4347

    
4348
#if MG_ENABLE_HTTP_WEBSOCKET
4349
#define MG_EV_WEBSOCKET_HANDSHAKE_REQUEST 111 /* struct http_message * */
4350
#define MG_EV_WEBSOCKET_HANDSHAKE_DONE 112    /* NULL */
4351
#define MG_EV_WEBSOCKET_FRAME 113             /* struct websocket_message * */
4352
#define MG_EV_WEBSOCKET_CONTROL_FRAME 114     /* struct websocket_message * */
4353
#endif
4354

    
4355
#if MG_ENABLE_HTTP_STREAMING_MULTIPART
4356
#define MG_EV_HTTP_MULTIPART_REQUEST 121 /* struct http_message */
4357
#define MG_EV_HTTP_PART_BEGIN 122        /* struct mg_http_multipart_part */
4358
#define MG_EV_HTTP_PART_DATA 123         /* struct mg_http_multipart_part */
4359
#define MG_EV_HTTP_PART_END 124          /* struct mg_http_multipart_part */
4360
/* struct mg_http_multipart_part */
4361
#define MG_EV_HTTP_MULTIPART_REQUEST_END 125
4362
#endif
4363

    
4364
/*
4365
 * Attaches a built-in HTTP event handler to the given connection.
4366
 * The user-defined event handler will receive following extra events:
4367
 *
4368
 * - MG_EV_HTTP_REQUEST: HTTP request has arrived. Parsed HTTP request
4369
 *  is passed as
4370
 *   `struct http_message` through the handler's `void *ev_data` pointer.
4371
 * - MG_EV_HTTP_REPLY: The HTTP reply has arrived. The parsed HTTP reply is
4372
 *   passed as `struct http_message` through the handler's `void *ev_data`
4373
 *   pointer.
4374
 * - MG_EV_HTTP_CHUNK: The HTTP chunked-encoding chunk has arrived.
4375
 *   The parsed HTTP reply is passed as `struct http_message` through the
4376
 *   handler's `void *ev_data` pointer. `http_message::body` would contain
4377
 *   incomplete, reassembled HTTP body.
4378
 *   It will grow with every new chunk that arrives, and it can
4379
 *   potentially consume a lot of memory. An event handler may process
4380
 *   the body as chunks are coming, and signal Mongoose to delete processed
4381
 *   body by setting `MG_F_DELETE_CHUNK` in `mg_connection::flags`. When
4382
 *   the last zero chunk is received,
4383
 *   Mongoose sends `MG_EV_HTTP_REPLY` event with
4384
 *   full reassembled body (if handler did not signal to delete chunks) or
4385
 *   with empty body (if handler did signal to delete chunks).
4386
 * - MG_EV_WEBSOCKET_HANDSHAKE_REQUEST: server has received the WebSocket
4387
 *   handshake request. `ev_data` contains parsed HTTP request.
4388
 * - MG_EV_WEBSOCKET_HANDSHAKE_DONE: server has completed the WebSocket
4389
 *   handshake. `ev_data` is `NULL`.
4390
 * - MG_EV_WEBSOCKET_FRAME: new WebSocket frame has arrived. `ev_data` is
4391
 *   `struct websocket_message *`
4392
 *
4393
 * When compiled with MG_ENABLE_HTTP_STREAMING_MULTIPART, Mongoose parses
4394
 * multipart requests and splits them into separate events:
4395
 * - MG_EV_HTTP_MULTIPART_REQUEST: Start of the request.
4396
 *   This event is sent before body is parsed. After this, the user
4397
 *   should expect a sequence of PART_BEGIN/DATA/END requests.
4398
 *   This is also the last time when headers and other request fields are
4399
 *   accessible.
4400
 * - MG_EV_HTTP_PART_BEGIN: Start of a part of a multipart message.
4401
 *   Argument: mg_http_multipart_part with var_name and file_name set
4402
 *   (if present). No data is passed in this message.
4403
 * - MG_EV_HTTP_PART_DATA: new portion of data from the multipart message.
4404
 *   Argument: mg_http_multipart_part. var_name and file_name are preserved,
4405
 *   data is available in mg_http_multipart_part.data.
4406
 * - MG_EV_HTTP_PART_END: End of the current part. var_name, file_name are
4407
 *   the same, no data in the message. If status is 0, then the part is
4408
 *   properly terminated with a boundary, status < 0 means that connection
4409
 *   was terminated.
4410
 * - MG_EV_HTTP_MULTIPART_REQUEST_END: End of the multipart request.
4411
 *   Argument: mg_http_multipart_part, var_name and file_name are NULL,
4412
 *   status = 0 means request was properly closed, < 0 means connection
4413
 *   was terminated (note: in this case both PART_END and REQUEST_END are
4414
 *   delivered).
4415
 */
4416
void mg_set_protocol_http_websocket(struct mg_connection *nc);
4417

    
4418
#if MG_ENABLE_HTTP_WEBSOCKET
4419
/*
4420
 * Send websocket handshake to the server.
4421
 *
4422
 * `nc` must be a valid connection, connected to a server. `uri` is an URI
4423
 * to fetch, extra_headers` is extra HTTP headers to send or `NULL`.
4424
 *
4425
 * This function is intended to be used by websocket client.
4426
 *
4427
 * Note that the Host header is mandatory in HTTP/1.1 and must be
4428
 * included in `extra_headers`. `mg_send_websocket_handshake2` offers
4429
 * a better API for that.
4430
 *
4431
 * Deprecated in favour of `mg_send_websocket_handshake2`
4432
 */
4433
void mg_send_websocket_handshake(struct mg_connection *nc, const char *uri,
4434
                                 const char *extra_headers);
4435

    
4436
/*
4437
 * Send websocket handshake to the server.
4438
 *
4439
 * `nc` must be a valid connection, connected to a server. `uri` is an URI
4440
 * to fetch, `host` goes into the `Host` header, `protocol` goes into the
4441
 * `Sec-WebSocket-Proto` header (NULL to omit), extra_headers` is extra HTTP
4442
 * headers to send or `NULL`.
4443
 *
4444
 * This function is intended to be used by websocket client.
4445
 */
4446
void mg_send_websocket_handshake2(struct mg_connection *nc, const char *path,
4447
                                  const char *host, const char *protocol,
4448
                                  const char *extra_headers);
4449

    
4450
/* Like mg_send_websocket_handshake2 but also passes basic auth header */
4451
void mg_send_websocket_handshake3(struct mg_connection *nc, const char *path,
4452
                                  const char *host, const char *protocol,
4453
                                  const char *extra_headers, const char *user,
4454
                                  const char *pass);
4455

    
4456
/* Same as mg_send_websocket_handshake3 but with strings not necessarily
4457
 * NUL-temrinated */
4458
void mg_send_websocket_handshake3v(struct mg_connection *nc,
4459
                                   const struct mg_str path,
4460
                                   const struct mg_str host,
4461
                                   const struct mg_str protocol,
4462
                                   const struct mg_str extra_headers,
4463
                                   const struct mg_str user,
4464
                                   const struct mg_str pass);
4465

    
4466
/*
4467
 * Helper function that creates an outbound WebSocket connection.
4468
 *
4469
 * `url` is a URL to connect to. It must be properly URL-encoded, e.g. have
4470
 * no spaces, etc. By default, `mg_connect_ws()` sends Connection and
4471
 * Host headers. `extra_headers` is an extra HTTP header to send, e.g.
4472
 * `"User-Agent: my-app\r\n"`.
4473
 * If `protocol` is not NULL, then a `Sec-WebSocket-Protocol` header is sent.
4474
 *
4475
 * Examples:
4476
 *
4477
 * ```c
4478
 *   nc1 = mg_connect_ws(mgr, ev_handler_1, "ws://echo.websocket.org", NULL,
4479
 *                       NULL);
4480
 *   nc2 = mg_connect_ws(mgr, ev_handler_1, "wss://echo.websocket.org", NULL,
4481
 *                       NULL);
4482
 *   nc3 = mg_connect_ws(mgr, ev_handler_1, "ws://api.cesanta.com",
4483
 *                       "clubby.cesanta.com", NULL);
4484
 * ```
4485
 */
4486
struct mg_connection *mg_connect_ws(struct mg_mgr *mgr,
4487
                                    MG_CB(mg_event_handler_t event_handler,
4488
                                          void *user_data),
4489
                                    const char *url, const char *protocol,
4490
                                    const char *extra_headers);
4491

    
4492
/*
4493
 * Helper function that creates an outbound WebSocket connection
4494
 *
4495
 * Mostly identical to `mg_connect_ws`, but allows to provide extra parameters
4496
 * (for example, SSL parameters)
4497
 */
4498
struct mg_connection *mg_connect_ws_opt(
4499
    struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data),
4500
    struct mg_connect_opts opts, const char *url, const char *protocol,
4501
    const char *extra_headers);
4502

    
4503
/*
4504
 * Send WebSocket frame to the remote end.
4505
 *
4506
 * `op_and_flags` specifies the frame's type. It's one of:
4507
 *
4508
 * - WEBSOCKET_OP_CONTINUE
4509
 * - WEBSOCKET_OP_TEXT
4510
 * - WEBSOCKET_OP_BINARY
4511
 * - WEBSOCKET_OP_CLOSE
4512
 * - WEBSOCKET_OP_PING
4513
 * - WEBSOCKET_OP_PONG
4514
 *
4515
 * Orred with one of the flags:
4516
 *
4517
 * - WEBSOCKET_DONT_FIN: Don't set the FIN flag on the frame to be sent.
4518
 *
4519
 * `data` and `data_len` contain frame data.
4520
 */
4521
void mg_send_websocket_frame(struct mg_connection *nc, int op_and_flags,
4522
                             const void *data, size_t data_len);
4523

    
4524
/*
4525
 * Like `mg_send_websocket_frame()`, but composes a single frame from multiple
4526
 * buffers.
4527
 */
4528
void mg_send_websocket_framev(struct mg_connection *nc, int op_and_flags,
4529
                              const struct mg_str *strings, int num_strings);
4530

    
4531
/*
4532
 * Sends WebSocket frame to the remote end.
4533
 *
4534
 * Like `mg_send_websocket_frame()`, but allows to create formatted messages
4535
 * with `printf()`-like semantics.
4536
 */
4537
void mg_printf_websocket_frame(struct mg_connection *nc, int op_and_flags,
4538
                               const char *fmt, ...);
4539

    
4540
/* Websocket opcodes, from http://tools.ietf.org/html/rfc6455 */
4541
#define WEBSOCKET_OP_CONTINUE 0
4542
#define WEBSOCKET_OP_TEXT 1
4543
#define WEBSOCKET_OP_BINARY 2
4544
#define WEBSOCKET_OP_CLOSE 8
4545
#define WEBSOCKET_OP_PING 9
4546
#define WEBSOCKET_OP_PONG 10
4547

    
4548
/*
4549
 * If set causes the FIN flag to not be set on outbound
4550
 * frames. This enables sending multiple fragments of a single
4551
 * logical message.
4552
 *
4553
 * The WebSocket protocol mandates that if the FIN flag of a data
4554
 * frame is not set, the next frame must be a WEBSOCKET_OP_CONTINUE.
4555
 * The last frame must have the FIN bit set.
4556
 *
4557
 * Note that mongoose will automatically defragment incoming messages,
4558
 * so this flag is used only on outbound messages.
4559
 */
4560
#define WEBSOCKET_DONT_FIN 0x100
4561

    
4562
#endif /* MG_ENABLE_HTTP_WEBSOCKET */
4563

    
4564
/*
4565
 * Decodes a URL-encoded string.
4566
 *
4567
 * Source string is specified by (`src`, `src_len`), and destination is
4568
 * (`dst`, `dst_len`). If `is_form_url_encoded` is non-zero, then
4569
 * `+` character is decoded as a blank space character. This function
4570
 * guarantees to NUL-terminate the destination. If destination is too small,
4571
 * then the source string is partially decoded and `-1` is returned.
4572
 *Otherwise,
4573
 * a length of the decoded string is returned, not counting final NUL.
4574
 */
4575
int mg_url_decode(const char *src, int src_len, char *dst, int dst_len,
4576
                  int is_form_url_encoded);
4577

    
4578
extern void mg_hash_md5_v(size_t num_msgs, const uint8_t *msgs[],
4579
                          const size_t *msg_lens, uint8_t *digest);
4580
extern void mg_hash_sha1_v(size_t num_msgs, const uint8_t *msgs[],
4581
                           const size_t *msg_lens, uint8_t *digest);
4582

    
4583
/*
4584
 * Flags for `mg_http_is_authorized()`.
4585
 */
4586
#define MG_AUTH_FLAG_IS_DIRECTORY (1 << 0)
4587
#define MG_AUTH_FLAG_IS_GLOBAL_PASS_FILE (1 << 1)
4588
#define MG_AUTH_FLAG_ALLOW_MISSING_FILE (1 << 2)
4589

    
4590
/*
4591
 * Checks whether an http request is authorized. `domain` is the authentication
4592
 * realm, `passwords_file` is a htdigest file (can be created e.g. with
4593
 * `htdigest` utility). If either `domain` or `passwords_file` is NULL, this
4594
 * function always returns 1; otherwise checks the authentication in the
4595
 * http request and returns 1 only if there is a match; 0 otherwise.
4596
 */
4597
int mg_http_is_authorized(struct http_message *hm, struct mg_str path,
4598
                          const char *domain, const char *passwords_file,
4599
                          int flags);
4600

    
4601
/*
4602
 * Sends 401 Unauthorized response.
4603
 */
4604
void mg_http_send_digest_auth_request(struct mg_connection *c,
4605
                                      const char *domain);
4606

    
4607
#ifdef __cplusplus
4608
}
4609
#endif /* __cplusplus */
4610

    
4611
#endif /* MG_ENABLE_HTTP */
4612

    
4613
#endif /* CS_MONGOOSE_SRC_HTTP_H_ */
4614
#ifdef MG_MODULE_LINES
4615
#line 1 "mongoose/src/mg_http_server.h"
4616
#endif
4617
/*
4618
 * === Server API reference
4619
 */
4620

    
4621
#ifndef CS_MONGOOSE_SRC_HTTP_SERVER_H_
4622
#define CS_MONGOOSE_SRC_HTTP_SERVER_H_
4623

    
4624
#if MG_ENABLE_HTTP
4625

    
4626
#ifdef __cplusplus
4627
extern "C" {
4628
#endif /* __cplusplus */
4629

    
4630
/*
4631
 * Parses a HTTP message.
4632
 *
4633
 * `is_req` should be set to 1 if parsing a request, 0 if reply.
4634
 *
4635
 * Returns the number of bytes parsed. If HTTP message is
4636
 * incomplete `0` is returned. On parse error, a negative number is returned.
4637
 */
4638
int mg_parse_http(const char *s, int n, struct http_message *hm, int is_req);
4639

    
4640
/*
4641
 * Searches and returns the header `name` in parsed HTTP message `hm`.
4642
 * If header is not found, NULL is returned. Example:
4643
 *
4644
 *     struct mg_str *host_hdr = mg_get_http_header(hm, "Host");
4645
 */
4646
struct mg_str *mg_get_http_header(struct http_message *hm, const char *name);
4647

    
4648
/*
4649
 * Parses the HTTP header `hdr`. Finds variable `var_name` and stores its value
4650
 * in the buffer `*buf`, `buf_size`. If the buffer size is not enough,
4651
 * allocates a buffer of required size and writes it to `*buf`, similar to
4652
 * asprintf(). The caller should always check whether the buffer was updated,
4653
 * and free it if so.
4654
 *
4655
 * This function is supposed to parse cookies, authentication headers, etc.
4656
 * Example (error handling omitted):
4657
 *
4658
 *     char user_buf[20];
4659
 *     char *user = user_buf;
4660
 *     struct mg_str *hdr = mg_get_http_header(hm, "Authorization");
4661
 *     mg_http_parse_header2(hdr, "username", &user, sizeof(user_buf));
4662
 *     // ... do something useful with user
4663
 *     if (user != user_buf) {
4664
 *       free(user);
4665
 *     }
4666
 *
4667
 * Returns the length of the variable's value. If variable is not found, 0 is
4668
 * returned.
4669
 */
4670
int mg_http_parse_header2(struct mg_str *hdr, const char *var_name, char **buf,
4671
                          size_t buf_size);
4672

    
4673
/*
4674
 * DEPRECATED: use mg_http_parse_header2() instead.
4675
 *
4676
 * Same as mg_http_parse_header2(), but takes buffer as a `char *` (instead of
4677
 * `char **`), and thus it cannot allocate a new buffer if the provided one
4678
 * is not enough, and just returns 0 in that case.
4679
 */
4680
int mg_http_parse_header(struct mg_str *hdr, const char *var_name, char *buf,
4681
                         size_t buf_size)
4682
#ifdef __GNUC__
4683
    __attribute__((deprecated));
4684
#endif
4685
;
4686

    
4687
/*
4688
 * Gets and parses the Authorization: Basic header
4689
 * Returns -1 if no Authorization header is found, or if
4690
 * mg_parse_http_basic_auth
4691
 * fails parsing the resulting header.
4692
 */
4693
int mg_get_http_basic_auth(struct http_message *hm, char *user, size_t user_len,
4694
                           char *pass, size_t pass_len);
4695

    
4696
/*
4697
 * Parses the Authorization: Basic header
4698
 * Returns -1 iif the authorization type is not "Basic" or any other error such
4699
 * as incorrectly encoded base64 user password pair.
4700
 */
4701
int mg_parse_http_basic_auth(struct mg_str *hdr, char *user, size_t user_len,
4702
                             char *pass, size_t pass_len);
4703

    
4704
/*
4705
 * Parses the buffer `buf`, `buf_len` that contains multipart form data chunks.
4706
 * Stores the chunk name in a `var_name`, `var_name_len` buffer.
4707
 * If a chunk is an uploaded file, then `file_name`, `file_name_len` is
4708
 * filled with an uploaded file name. `chunk`, `chunk_len`
4709
 * points to the chunk data.
4710
 *
4711
 * Return: number of bytes to skip to the next chunk or 0 if there are
4712
 *         no more chunks.
4713
 *
4714
 * Usage example:
4715
 *
4716
 * ```c
4717
 *    static void ev_handler(struct mg_connection *nc, int ev, void *ev_data) {
4718
 *      switch(ev) {
4719
 *        case MG_EV_HTTP_REQUEST: {
4720
 *          struct http_message *hm = (struct http_message *) ev_data;
4721
 *          char var_name[100], file_name[100];
4722
 *          const char *chunk;
4723
 *          size_t chunk_len, n1, n2;
4724
 *
4725
 *          n1 = n2 = 0;
4726
 *          while ((n2 = mg_parse_multipart(hm->body.p + n1,
4727
 *                                          hm->body.len - n1,
4728
 *                                          var_name, sizeof(var_name),
4729
 *                                          file_name, sizeof(file_name),
4730
 *                                          &chunk, &chunk_len)) > 0) {
4731
 *            printf("var: %s, file_name: %s, size: %d, chunk: [%.*s]\n",
4732
 *                   var_name, file_name, (int) chunk_len,
4733
 *                   (int) chunk_len, chunk);
4734
 *            n1 += n2;
4735
 *          }
4736
 *        }
4737
 *        break;
4738
 * ```
4739
 */
4740
size_t mg_parse_multipart(const char *buf, size_t buf_len, char *var_name,
4741
                          size_t var_name_len, char *file_name,
4742
                          size_t file_name_len, const char **chunk,
4743
                          size_t *chunk_len);
4744

    
4745
/*
4746
 * Fetches a HTTP form variable.
4747
 *
4748
 * Fetches a variable `name` from a `buf` into a buffer specified by `dst`,
4749
 * `dst_len`. The destination is always zero-terminated. Returns the length of
4750
 * a fetched variable. If not found, 0 is returned. `buf` must be valid
4751
 * url-encoded buffer. If destination is too small or an error occured,
4752
 * negative number is returned.
4753
 */
4754
int mg_get_http_var(const struct mg_str *buf, const char *name, char *dst,
4755
                    size_t dst_len);
4756

    
4757
#if MG_ENABLE_FILESYSTEM
4758
/*
4759
 * This structure defines how `mg_serve_http()` works.
4760
 * Best practice is to set only required settings, and leave the rest as NULL.
4761
 */
4762
struct mg_serve_http_opts {
4763
  /* Path to web root directory */
4764
  const char *document_root;
4765

    
4766
  /* List of index files. Default is "" */
4767
  const char *index_files;
4768

    
4769
  /*
4770
   * Leave as NULL to disable authentication.
4771
   * To enable directory protection with authentication, set this to ".htpasswd"
4772
   * Then, creating ".htpasswd" file in any directory automatically protects
4773
   * it with digest authentication.
4774
   * Use `mongoose` web server binary, or `htdigest` Apache utility to
4775
   * create/manipulate passwords file.
4776
   * Make sure `auth_domain` is set to a valid domain name.
4777
   */
4778
  const char *per_directory_auth_file;
4779

    
4780
  /* Authorization domain (domain name of this web server) */
4781
  const char *auth_domain;
4782

    
4783
  /*
4784
   * Leave as NULL to disable authentication.
4785
   * Normally, only selected directories in the document root are protected.
4786
   * If absolutely every access to the web server needs to be authenticated,
4787
   * regardless of the URI, set this option to the path to the passwords file.
4788
   * Format of that file is the same as ".htpasswd" file. Make sure that file
4789
   * is located outside document root to prevent people fetching it.
4790
   */
4791
  const char *global_auth_file;
4792

    
4793
  /* Set to "no" to disable directory listing. Enabled by default. */
4794
  const char *enable_directory_listing;
4795

    
4796
  /*
4797
   * SSI files pattern. If not set, "**.shtml$|**.shtm$" is used.
4798
   *
4799
   * All files that match ssi_pattern are treated as SSI.
4800
   *
4801
   * Server Side Includes (SSI) is a simple interpreted server-side scripting
4802
   * language which is most commonly used to include the contents of a file
4803
   * into a web page. It can be useful when it is desirable to include a common
4804
   * piece of code throughout a website, for example, headers and footers.
4805
   *
4806
   * In order for a webpage to recognize an SSI-enabled HTML file, the
4807
   * filename should end with a special extension, by default the extension
4808
   * should be either .shtml or .shtm
4809
   *
4810
   * Unknown SSI directives are silently ignored by Mongoose. Currently,
4811
   * the following SSI directives are supported:
4812
   *    &lt;!--#include FILE_TO_INCLUDE --&gt;
4813
   *    &lt;!--#exec "COMMAND_TO_EXECUTE" --&gt;
4814
   *    &lt;!--#call COMMAND --&gt;
4815
   *
4816
   * Note that &lt;!--#include ...> directive supports three path
4817
   *specifications:
4818
   *
4819
   * &lt;!--#include virtual="path" --&gt;  Path is relative to web server root
4820
   * &lt;!--#include abspath="path" --&gt;  Path is absolute or relative to the
4821
   *                                  web server working dir
4822
   * &lt;!--#include file="path" --&gt;,    Path is relative to current document
4823
   * &lt;!--#include "path" --&gt;
4824
   *
4825
   * The include directive may be used to include the contents of a file or
4826
   * the result of running a CGI script.
4827
   *
4828
   * The exec directive is used to execute
4829
   * a command on a server, and show command's output. Example:
4830
   *
4831
   * &lt;!--#exec "ls -l" --&gt;
4832
   *
4833
   * The call directive is a way to invoke a C handler from the HTML page.
4834
   * On each occurence of &lt;!--#call COMMAND OPTIONAL_PARAMS> directive,
4835
   * Mongoose calls a registered event handler with MG_EV_SSI_CALL event,
4836
   * and event parameter will point to the COMMAND OPTIONAL_PARAMS string.
4837
   * An event handler can output any text, for example by calling
4838
   * `mg_printf()`. This is a flexible way of generating a web page on
4839
   * server side by calling a C event handler. Example:
4840
   *
4841
   * &lt;!--#call foo --&gt; ... &lt;!--#call bar --&gt;
4842
   *
4843
   * In the event handler:
4844
   *    case MG_EV_SSI_CALL: {
4845
   *      const char *param = (const char *) ev_data;
4846
   *      if (strcmp(param, "foo") == 0) {
4847
   *        mg_printf(c, "hello from foo");
4848
   *      } else if (strcmp(param, "bar") == 0) {
4849
   *        mg_printf(c, "hello from bar");
4850
   *      }
4851
   *      break;
4852
   *    }
4853
   */
4854
  const char *ssi_pattern;
4855

    
4856
  /* IP ACL. By default, NULL, meaning all IPs are allowed to connect */
4857
  const char *ip_acl;
4858

    
4859
#if MG_ENABLE_HTTP_URL_REWRITES
4860
  /* URL rewrites.
4861
   *
4862
   * Comma-separated list of `uri_pattern=url_file_or_directory_path` rewrites.
4863
   * When HTTP request is received, Mongoose constructs a file name from the
4864
   * requested URI by combining `document_root` and the URI. However, if the
4865
   * rewrite option is used and `uri_pattern` matches requested URI, then
4866
   * `document_root` is ignored. Instead, `url_file_or_directory_path` is used,
4867
   * which should be a full path name or a path relative to the web server's
4868
   * current working directory. It can also be an URI (http:// or https://)
4869
   * in which case mongoose will behave as a reverse proxy for that destination.
4870
   *
4871
   * Note that `uri_pattern`, as all Mongoose patterns, is a prefix pattern.
4872
   *
4873
   * If uri_pattern starts with `@` symbol, then Mongoose compares it with the
4874
   * HOST header of the request. If they are equal, Mongoose sets document root
4875
   * to `file_or_directory_path`, implementing virtual hosts support.
4876
   * Example: `@foo.com=/document/root/for/foo.com`
4877
   *
4878
   * If `uri_pattern` starts with `%` symbol, then Mongoose compares it with
4879
   * the listening port. If they match, then Mongoose issues a 301 redirect.
4880
   * For example, to redirect all HTTP requests to the
4881
   * HTTPS port, do `%80=https://my.site.com`. Note that the request URI is
4882
   * automatically appended to the redirect location.
4883
   */
4884
  const char *url_rewrites;
4885
#endif
4886

    
4887
  /* DAV document root. If NULL, DAV requests are going to fail. */
4888
  const char *dav_document_root;
4889

    
4890
  /*
4891
   * DAV passwords file. If NULL, DAV requests are going to fail.
4892
   * If passwords file is set to "-", then DAV auth is disabled.
4893
   */
4894
  const char *dav_auth_file;
4895

    
4896
  /* Glob pattern for the files to hide. */
4897
  const char *hidden_file_pattern;
4898

    
4899
  /* Set to non-NULL to enable CGI, e.g. **.cgi$|**.php$" */
4900
  const char *cgi_file_pattern;
4901

    
4902
  /* If not NULL, ignore CGI script hashbang and use this interpreter */
4903
  const char *cgi_interpreter;
4904

    
4905
  /*
4906
   * Comma-separated list of Content-Type overrides for path suffixes, e.g.
4907
   * ".txt=text/plain; charset=utf-8,.c=text/plain"
4908
   */
4909
  const char *custom_mime_types;
4910

    
4911
  /*
4912
   * Extra HTTP headers to add to each server response.
4913
   * Example: to enable CORS, set this to "Access-Control-Allow-Origin: *".
4914
   */
4915
  const char *extra_headers;
4916
};
4917

    
4918
/*
4919
 * Serves given HTTP request according to the `options`.
4920
 *
4921
 * Example code snippet:
4922
 *
4923
 * ```c
4924
 * static void ev_handler(struct mg_connection *nc, int ev, void *ev_data) {
4925
 *   struct http_message *hm = (struct http_message *) ev_data;
4926
 *   struct mg_serve_http_opts opts = { .document_root = "/var/www" };  // C99
4927
 *
4928
 *   switch (ev) {
4929
 *     case MG_EV_HTTP_REQUEST:
4930
 *       mg_serve_http(nc, hm, opts);
4931
 *       break;
4932
 *     default:
4933
 *       break;
4934
 *   }
4935
 * }
4936
 * ```
4937
 */
4938
void mg_serve_http(struct mg_connection *nc, struct http_message *hm,
4939
                   struct mg_serve_http_opts opts);
4940

    
4941
/*
4942
 * Serves a specific file with a given MIME type and optional extra headers.
4943
 *
4944
 * Example code snippet:
4945
 *
4946
 * ```c
4947
 * static void ev_handler(struct mg_connection *nc, int ev, void *ev_data) {
4948
 *   switch (ev) {
4949
 *     case MG_EV_HTTP_REQUEST: {
4950
 *       struct http_message *hm = (struct http_message *) ev_data;
4951
 *       mg_http_serve_file(nc, hm, "file.txt",
4952
 *                          mg_mk_str("text/plain"), mg_mk_str(""));
4953
 *       break;
4954
 *     }
4955
 *     ...
4956
 *   }
4957
 * }
4958
 * ```
4959
 */
4960
void mg_http_serve_file(struct mg_connection *nc, struct http_message *hm,
4961
                        const char *path, const struct mg_str mime_type,
4962
                        const struct mg_str extra_headers);
4963

    
4964
#if MG_ENABLE_HTTP_STREAMING_MULTIPART
4965

    
4966
/* Callback prototype for `mg_file_upload_handler()`. */
4967
typedef struct mg_str (*mg_fu_fname_fn)(struct mg_connection *nc,
4968
                                        struct mg_str fname);
4969

    
4970
/*
4971
 * File upload handler.
4972
 * This handler can be used to implement file uploads with minimum code.
4973
 * This handler will process MG_EV_HTTP_PART_* events and store file data into
4974
 * a local file.
4975
 * `local_name_fn` will be invoked with whatever name was provided by the client
4976
 * and will expect the name of the local file to open. A return value of NULL
4977
 * will abort file upload (client will get a "403 Forbidden" response). If
4978
 * non-null, the returned string must be heap-allocated and will be freed by
4979
 * the caller.
4980
 * Exception: it is ok to return the same string verbatim.
4981
 *
4982
 * Example:
4983
 *
4984
 * ```c
4985
 * struct mg_str upload_fname(struct mg_connection *nc, struct mg_str fname) {
4986
 *   // Just return the same filename. Do not actually do this except in test!
4987
 *   // fname is user-controlled and needs to be sanitized.
4988
 *   return fname;
4989
 * }
4990
 * void ev_handler(struct mg_connection *nc, int ev, void *ev_data) {
4991
 *   switch (ev) {
4992
 *     ...
4993
 *     case MG_EV_HTTP_PART_BEGIN:
4994
 *     case MG_EV_HTTP_PART_DATA:
4995
 *     case MG_EV_HTTP_PART_END:
4996
 *       mg_file_upload_handler(nc, ev, ev_data, upload_fname);
4997
 *       break;
4998
 *   }
4999
 * }
5000
 * ```
5001
 */
5002
void mg_file_upload_handler(struct mg_connection *nc, int ev, void *ev_data,
5003
                            mg_fu_fname_fn local_name_fn
5004
                                MG_UD_ARG(void *user_data));
5005
#endif /* MG_ENABLE_HTTP_STREAMING_MULTIPART */
5006
#endif /* MG_ENABLE_FILESYSTEM */
5007

    
5008
/*
5009
 * Registers a callback for a specified http endpoint
5010
 * Note: if callback is registered it is called instead of the
5011
 * callback provided in mg_bind
5012
 *
5013
 * Example code snippet:
5014
 *
5015
 * ```c
5016
 * static void handle_hello1(struct mg_connection *nc, int ev, void *ev_data) {
5017
 *   (void) ev; (void) ev_data;
5018
 *   mg_printf(nc, "HTTP/1.0 200 OK\r\n\r\n[I am Hello1]");
5019
 *  nc->flags |= MG_F_SEND_AND_CLOSE;
5020
 * }
5021
 *
5022
 * static void handle_hello2(struct mg_connection *nc, int ev, void *ev_data) {
5023
 *  (void) ev; (void) ev_data;
5024
 *   mg_printf(nc, "HTTP/1.0 200 OK\r\n\r\n[I am Hello2]");
5025
 *  nc->flags |= MG_F_SEND_AND_CLOSE;
5026
 * }
5027
 *
5028
 * void init() {
5029
 *   nc = mg_bind(&mgr, local_addr, cb1);
5030
 *   mg_register_http_endpoint(nc, "/hello1", handle_hello1);
5031
 *   mg_register_http_endpoint(nc, "/hello1/hello2", handle_hello2);
5032
 * }
5033
 * ```
5034
 */
5035
void mg_register_http_endpoint(struct mg_connection *nc, const char *uri_path,
5036
                               MG_CB(mg_event_handler_t handler,
5037
                                     void *user_data));
5038

    
5039
struct mg_http_endpoint_opts {
5040
  void *user_data;
5041
  /* Authorization domain (realm) */
5042
  const char *auth_domain;
5043
  const char *auth_file;
5044
};
5045

    
5046
void mg_register_http_endpoint_opt(struct mg_connection *nc,
5047
                                   const char *uri_path,
5048
                                   mg_event_handler_t handler,
5049
                                   struct mg_http_endpoint_opts opts);
5050

    
5051
/*
5052
 * Authenticates a HTTP request against an opened password file.
5053
 * Returns 1 if authenticated, 0 otherwise.
5054
 */
5055
int mg_http_check_digest_auth(struct http_message *hm, const char *auth_domain,
5056
                              FILE *fp);
5057

    
5058
/*
5059
 * Authenticates given response params against an opened password file.
5060
 * Returns 1 if authenticated, 0 otherwise.
5061
 *
5062
 * It's used by mg_http_check_digest_auth().
5063
 */
5064
int mg_check_digest_auth(struct mg_str method, struct mg_str uri,
5065
                         struct mg_str username, struct mg_str cnonce,
5066
                         struct mg_str response, struct mg_str qop,
5067
                         struct mg_str nc, struct mg_str nonce,
5068
                         struct mg_str auth_domain, FILE *fp);
5069

    
5070
/*
5071
 * Sends buffer `buf` of size `len` to the client using chunked HTTP encoding.
5072
 * This function sends the buffer size as hex number + newline first, then
5073
 * the buffer itself, then the newline. For example,
5074
 * `mg_send_http_chunk(nc, "foo", 3)` will append the `3\r\nfoo\r\n` string
5075
 * to the `nc->send_mbuf` output IO buffer.
5076
 *
5077
 * NOTE: The HTTP header "Transfer-Encoding: chunked" should be sent prior to
5078
 * using this function.
5079
 *
5080
 * NOTE: do not forget to send an empty chunk at the end of the response,
5081
 * to tell the client that everything was sent. Example:
5082
 *
5083
 * ```
5084
 *   mg_printf_http_chunk(nc, "%s", "my response!");
5085
 *   mg_send_http_chunk(nc, "", 0); // Tell the client we're finished
5086
 * ```
5087
 */
5088
void mg_send_http_chunk(struct mg_connection *nc, const char *buf, size_t len);
5089

    
5090
/*
5091
 * Sends a printf-formatted HTTP chunk.
5092
 * Functionality is similar to `mg_send_http_chunk()`.
5093
 */
5094
void mg_printf_http_chunk(struct mg_connection *nc, const char *fmt, ...);
5095

    
5096
/*
5097
 * Sends the response status line.
5098
 * If `extra_headers` is not NULL, then `extra_headers` are also sent
5099
 * after the response line. `extra_headers` must NOT end end with new line.
5100
 * Example:
5101
 *
5102
 *      mg_send_response_line(nc, 200, "Access-Control-Allow-Origin: *");
5103
 *
5104
 * Will result in:
5105
 *
5106
 *      HTTP/1.1 200 OK\r\n
5107
 *      Access-Control-Allow-Origin: *\r\n
5108
 */
5109
void mg_send_response_line(struct mg_connection *nc, int status_code,
5110
                           const char *extra_headers);
5111

    
5112
/*
5113
 * Sends an error response. If reason is NULL, the message will be inferred
5114
 * from the error code (if supported).
5115
 */
5116
void mg_http_send_error(struct mg_connection *nc, int code, const char *reason);
5117

    
5118
/*
5119
 * Sends a redirect response.
5120
 * `status_code` should be either 301 or 302 and `location` point to the
5121
 * new location.
5122
 * If `extra_headers` is not empty, then `extra_headers` are also sent
5123
 * after the response line. `extra_headers` must NOT end end with new line.
5124
 *
5125
 * Example:
5126
 *
5127
 *      mg_http_send_redirect(nc, 302, mg_mk_str("/login"), mg_mk_str(NULL));
5128
 */
5129
void mg_http_send_redirect(struct mg_connection *nc, int status_code,
5130
                           const struct mg_str location,
5131
                           const struct mg_str extra_headers);
5132

    
5133
/*
5134
 * Sends the response line and headers.
5135
 * This function sends the response line with the `status_code`, and
5136
 * automatically
5137
 * sends one header: either "Content-Length" or "Transfer-Encoding".
5138
 * If `content_length` is negative, then "Transfer-Encoding: chunked" header
5139
 * is sent, otherwise, "Content-Length" header is sent.
5140
 *
5141
 * NOTE: If `Transfer-Encoding` is `chunked`, then message body must be sent
5142
 * using `mg_send_http_chunk()` or `mg_printf_http_chunk()` functions.
5143
 * Otherwise, `mg_send()` or `mg_printf()` must be used.
5144
 * Extra headers could be set through `extra_headers`. Note `extra_headers`
5145
 * must NOT be terminated by a new line.
5146
 */
5147
void mg_send_head(struct mg_connection *n, int status_code,
5148
                  int64_t content_length, const char *extra_headers);
5149

    
5150
/*
5151
 * Sends a printf-formatted HTTP chunk, escaping HTML tags.
5152
 */
5153
void mg_printf_html_escape(struct mg_connection *nc, const char *fmt, ...);
5154

    
5155
#if MG_ENABLE_HTTP_URL_REWRITES
5156
/*
5157
 * Proxies a given request to a given upstream http server. The path prefix
5158
 * in `mount` will be stripped of the path requested to the upstream server,
5159
 * e.g. if mount is /api and upstream is http://localhost:8001/foo
5160
 * then an incoming request to /api/bar will cause a request to
5161
 * http://localhost:8001/foo/bar
5162
 *
5163
 * EXPERIMENTAL API. Please use http_serve_http + url_rewrites if a static
5164
 * mapping is good enough.
5165
 */
5166
void mg_http_reverse_proxy(struct mg_connection *nc,
5167
                           const struct http_message *hm, struct mg_str mount,
5168
                           struct mg_str upstream);
5169
#endif
5170

    
5171
#ifdef __cplusplus
5172
}
5173
#endif /* __cplusplus */
5174

    
5175
#endif /* MG_ENABLE_HTTP */
5176

    
5177
#endif /* CS_MONGOOSE_SRC_HTTP_SERVER_H_ */
5178
#ifdef MG_MODULE_LINES
5179
#line 1 "mongoose/src/mg_http_client.h"
5180
#endif
5181
/*
5182
 * === Client API reference
5183
 */
5184

    
5185
#ifndef CS_MONGOOSE_SRC_HTTP_CLIENT_H_
5186
#define CS_MONGOOSE_SRC_HTTP_CLIENT_H_
5187

    
5188
#ifdef __cplusplus
5189
extern "C" {
5190
#endif /* __cplusplus */
5191

    
5192
/*
5193
 * Helper function that creates an outbound HTTP connection.
5194
 *
5195
 * `url` is the URL to fetch. It must be properly URL-encoded, e.g. have
5196
 * no spaces, etc. By default, `mg_connect_http()` sends the Connection and
5197
 * Host headers. `extra_headers` is an extra HTTP header to send, e.g.
5198
 * `"User-Agent: my-app\r\n"`.
5199
 * If `post_data` is NULL, then a GET request is created. Otherwise, a POST
5200
 * request is created with the specified POST data. Note that if the data being
5201
 * posted is a form submission, the `Content-Type` header should be set
5202
 * accordingly (see example below).
5203
 *
5204
 * Examples:
5205
 *
5206
 * ```c
5207
 *   nc1 = mg_connect_http(mgr, ev_handler_1, "http://www.google.com", NULL,
5208
 *                         NULL);
5209
 *   nc2 = mg_connect_http(mgr, ev_handler_1, "https://github.com", NULL, NULL);
5210
 *   nc3 = mg_connect_http(
5211
 *       mgr, ev_handler_1, "my_server:8000/form_submit/",
5212
 *       "Content-Type: application/x-www-form-urlencoded\r\n",
5213
 *       "var_1=value_1&var_2=value_2");
5214
 * ```
5215
 */
5216
struct mg_connection *mg_connect_http(
5217
    struct mg_mgr *mgr,
5218
    MG_CB(mg_event_handler_t event_handler, void *user_data), const char *url,
5219
    const char *extra_headers, const char *post_data);
5220

    
5221
/*
5222
 * Helper function that creates an outbound HTTP connection.
5223
 *
5224
 * Mostly identical to mg_connect_http, but allows you to provide extra
5225
 *parameters
5226
 * (for example, SSL parameters)
5227
 */
5228
struct mg_connection *mg_connect_http_opt(
5229
    struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data),
5230
    struct mg_connect_opts opts, const char *url, const char *extra_headers,
5231
    const char *post_data);
5232
///*WYF add*************************************/
5233
struct mg_connection *mg_connect_httpDEL(
5234
    struct mg_mgr *mgr,
5235
    MG_CB(mg_event_handler_t event_handler, void *user_data), const char *url,
5236
    const char *extra_headers, const char *post_data);
5237
struct mg_connection *mg_connect_http_optDEL(
5238
    struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data),
5239
    struct mg_connect_opts opts, const char *url, const char *extra_headers,
5240
    const char *post_data);
5241
///*WYF add*************************************/
5242

    
5243
///*LJK add*************************************/
5244
struct mg_connection *mg_connect_httpPUT(
5245
struct mg_mgr *mgr,
5246
	MG_CB(mg_event_handler_t event_handler, void *user_data), const char *url,
5247
	const char *extra_headers, const char *post_data);
5248
struct mg_connection *mg_connect_http_optPUT(
5249
struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data),
5250
struct mg_connect_opts opts, const char *url, const char *extra_headers,
5251
	const char *post_data);
5252

    
5253
struct mg_connection *mg_connect_httpPOST(
5254
struct mg_mgr *mgr,
5255
	MG_CB(mg_event_handler_t event_handler, void *user_data), const char *url,
5256
	const char *extra_headers, const char *post_data);
5257
struct mg_connection *mg_connect_http_optPOST(
5258
struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data),
5259
struct mg_connect_opts opts, const char *url, const char *extra_headers,
5260
	const char *post_data);
5261
///*LJK add*************************************/
5262

    
5263
/* Creates digest authentication header for a client request. */
5264
int mg_http_create_digest_auth_header(char *buf, size_t buf_len,
5265
                                      const char *method, const char *uri,
5266
                                      const char *auth_domain, const char *user,
5267
                                      const char *passwd, const char *nonce);
5268

    
5269
#ifdef __cplusplus
5270
}
5271
#endif /* __cplusplus */
5272
#endif /* CS_MONGOOSE_SRC_HTTP_CLIENT_H_ */
5273
#ifdef MG_MODULE_LINES
5274
#line 1 "mongoose/src/mg_mqtt.h"
5275
#endif
5276
/*
5277
 * Copyright (c) 2014 Cesanta Software Limited
5278
 * All rights reserved
5279
 * This software is dual-licensed: you can redistribute it and/or modify
5280
 * it under the terms of the GNU General Public License version 2 as
5281
 * published by the Free Software Foundation. For the terms of this
5282
 * license, see <http://www.gnu.org/licenses/>.
5283
 *
5284
 * You are free to use this software under the terms of the GNU General
5285
 * Public License, but WITHOUT ANY WARRANTY; without even the implied
5286
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5287
 * See the GNU General Public License for more details.
5288
 *
5289
 * Alternatively, you can license this software under a commercial
5290
 * license, as set out in <https://www.cesanta.com/license>.
5291
 */
5292

    
5293
/*
5294
 * === MQTT API reference
5295
 */
5296

    
5297
#ifndef CS_MONGOOSE_SRC_MQTT_H_
5298
#define CS_MONGOOSE_SRC_MQTT_H_
5299

    
5300
/* Amalgamated: #include "mg_net.h" */
5301

    
5302
struct mg_mqtt_message {
5303
  int cmd;
5304
  int qos;
5305
  int len; /* message length in the IO buffer */
5306
  struct mg_str topic;
5307
  struct mg_str payload;
5308

    
5309
  uint8_t connack_ret_code; /* connack */
5310
  uint16_t message_id;      /* puback */
5311

    
5312
  /* connect */
5313
  uint8_t protocol_version;
5314
  uint8_t connect_flags;
5315
  uint16_t keep_alive_timer;
5316
  struct mg_str protocol_name;
5317
  struct mg_str client_id;
5318
  struct mg_str will_topic;
5319
  struct mg_str will_message;
5320
  struct mg_str user_name;
5321
  struct mg_str password;
5322
};
5323

    
5324
struct mg_mqtt_topic_expression {
5325
  const char *topic;
5326
  uint8_t qos;
5327
};
5328

    
5329
struct mg_send_mqtt_handshake_opts {
5330
  unsigned char flags; /* connection flags */
5331
  uint16_t keep_alive;
5332
  const char *will_topic;
5333
  const char *will_message;
5334
  const char *user_name;
5335
  const char *password;
5336
};
5337

    
5338
/* mg_mqtt_proto_data should be in header to allow external access to it */
5339
struct mg_mqtt_proto_data {
5340
  uint16_t keep_alive;
5341
  double last_control_time;
5342
};
5343

    
5344
/* Message types */
5345
#define MG_MQTT_CMD_CONNECT 1
5346
#define MG_MQTT_CMD_CONNACK 2
5347
#define MG_MQTT_CMD_PUBLISH 3
5348
#define MG_MQTT_CMD_PUBACK 4
5349
#define MG_MQTT_CMD_PUBREC 5
5350
#define MG_MQTT_CMD_PUBREL 6
5351
#define MG_MQTT_CMD_PUBCOMP 7
5352
#define MG_MQTT_CMD_SUBSCRIBE 8
5353
#define MG_MQTT_CMD_SUBACK 9
5354
#define MG_MQTT_CMD_UNSUBSCRIBE 10
5355
#define MG_MQTT_CMD_UNSUBACK 11
5356
#define MG_MQTT_CMD_PINGREQ 12
5357
#define MG_MQTT_CMD_PINGRESP 13
5358
#define MG_MQTT_CMD_DISCONNECT 14
5359

    
5360
/* MQTT event types */
5361
#define MG_MQTT_EVENT_BASE 200
5362
#define MG_EV_MQTT_CONNECT (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_CONNECT)
5363
#define MG_EV_MQTT_CONNACK (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_CONNACK)
5364
#define MG_EV_MQTT_PUBLISH (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_PUBLISH)
5365
#define MG_EV_MQTT_PUBACK (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_PUBACK)
5366
#define MG_EV_MQTT_PUBREC (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_PUBREC)
5367
#define MG_EV_MQTT_PUBREL (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_PUBREL)
5368
#define MG_EV_MQTT_PUBCOMP (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_PUBCOMP)
5369
#define MG_EV_MQTT_SUBSCRIBE (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_SUBSCRIBE)
5370
#define MG_EV_MQTT_SUBACK (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_SUBACK)
5371
#define MG_EV_MQTT_UNSUBSCRIBE (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_UNSUBSCRIBE)
5372
#define MG_EV_MQTT_UNSUBACK (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_UNSUBACK)
5373
#define MG_EV_MQTT_PINGREQ (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_PINGREQ)
5374
#define MG_EV_MQTT_PINGRESP (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_PINGRESP)
5375
#define MG_EV_MQTT_DISCONNECT (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_DISCONNECT)
5376

    
5377
/* Message flags */
5378
#define MG_MQTT_RETAIN 0x1
5379
#define MG_MQTT_DUP 0x4
5380
#define MG_MQTT_QOS(qos) ((qos) << 1)
5381
#define MG_MQTT_GET_QOS(flags) (((flags) &0x6) >> 1)
5382
#define MG_MQTT_SET_QOS(flags, qos) (flags) = ((flags) & ~0x6) | ((qos) << 1)
5383

    
5384
/* Connection flags */
5385
#define MG_MQTT_CLEAN_SESSION 0x02
5386
#define MG_MQTT_HAS_WILL 0x04
5387
#define MG_MQTT_WILL_RETAIN 0x20
5388
#define MG_MQTT_HAS_PASSWORD 0x40
5389
#define MG_MQTT_HAS_USER_NAME 0x80
5390
#define MG_MQTT_GET_WILL_QOS(flags) (((flags) &0x18) >> 3)
5391
#define MG_MQTT_SET_WILL_QOS(flags, qos) \
5392
  (flags) = ((flags) & ~0x18) | ((qos) << 3)
5393

    
5394
/* CONNACK return codes */
5395
#define MG_EV_MQTT_CONNACK_ACCEPTED 0
5396
#define MG_EV_MQTT_CONNACK_UNACCEPTABLE_VERSION 1
5397
#define MG_EV_MQTT_CONNACK_IDENTIFIER_REJECTED 2
5398
#define MG_EV_MQTT_CONNACK_SERVER_UNAVAILABLE 3
5399
#define MG_EV_MQTT_CONNACK_BAD_AUTH 4
5400
#define MG_EV_MQTT_CONNACK_NOT_AUTHORIZED 5
5401

    
5402
#ifdef __cplusplus
5403
extern "C" {
5404
#endif /* __cplusplus */
5405

    
5406
/*
5407
 * Attaches a built-in MQTT event handler to the given connection.
5408
 *
5409
 * The user-defined event handler will receive following extra events:
5410
 *
5411
 * - MG_EV_MQTT_CONNACK
5412
 * - MG_EV_MQTT_PUBLISH
5413
 * - MG_EV_MQTT_PUBACK
5414
 * - MG_EV_MQTT_PUBREC
5415
 * - MG_EV_MQTT_PUBREL
5416
 * - MG_EV_MQTT_PUBCOMP
5417
 * - MG_EV_MQTT_SUBACK
5418
 */
5419
void mg_set_protocol_mqtt(struct mg_connection *nc);
5420

    
5421
/* Sends an MQTT handshake. */
5422
void mg_send_mqtt_handshake(struct mg_connection *nc, const char *client_id);
5423

    
5424
/* Sends an MQTT handshake with optional parameters. */
5425
void mg_send_mqtt_handshake_opt(struct mg_connection *nc, const char *client_id,
5426
                                struct mg_send_mqtt_handshake_opts);
5427

    
5428
/* Publishes a message to a given topic. */
5429
void mg_mqtt_publish(struct mg_connection *nc, const char *topic,
5430
                     uint16_t message_id, int flags, const void *data,
5431
                     size_t len);
5432

    
5433
/* Subscribes to a bunch of topics. */
5434
void mg_mqtt_subscribe(struct mg_connection *nc,
5435
                       const struct mg_mqtt_topic_expression *topics,
5436
                       size_t topics_len, uint16_t message_id);
5437

    
5438
/* Unsubscribes from a bunch of topics. */
5439
void mg_mqtt_unsubscribe(struct mg_connection *nc, char **topics,
5440
                         size_t topics_len, uint16_t message_id);
5441

    
5442
/* Sends a DISCONNECT command. */
5443
void mg_mqtt_disconnect(struct mg_connection *nc);
5444

    
5445
/* Sends a CONNACK command with a given `return_code`. */
5446
void mg_mqtt_connack(struct mg_connection *nc, uint8_t return_code);
5447

    
5448
/* Sends a PUBACK command with a given `message_id`. */
5449
void mg_mqtt_puback(struct mg_connection *nc, uint16_t message_id);
5450

    
5451
/* Sends a PUBREC command with a given `message_id`. */
5452
void mg_mqtt_pubrec(struct mg_connection *nc, uint16_t message_id);
5453

    
5454
/* Sends a PUBREL command with a given `message_id`. */
5455
void mg_mqtt_pubrel(struct mg_connection *nc, uint16_t message_id);
5456

    
5457
/* Sends a PUBCOMP command with a given `message_id`. */
5458
void mg_mqtt_pubcomp(struct mg_connection *nc, uint16_t message_id);
5459

    
5460
/*
5461
 * Sends a SUBACK command with a given `message_id`
5462
 * and a sequence of granted QoSs.
5463
 */
5464
void mg_mqtt_suback(struct mg_connection *nc, uint8_t *qoss, size_t qoss_len,
5465
                    uint16_t message_id);
5466

    
5467
/* Sends a UNSUBACK command with a given `message_id`. */
5468
void mg_mqtt_unsuback(struct mg_connection *nc, uint16_t message_id);
5469

    
5470
/* Sends a PINGREQ command. */
5471
void mg_mqtt_ping(struct mg_connection *nc);
5472

    
5473
/* Sends a PINGRESP command. */
5474
void mg_mqtt_pong(struct mg_connection *nc);
5475

    
5476
/*
5477
 * Extracts the next topic expression from a SUBSCRIBE command payload.
5478
 *
5479
 * The topic expression name will point to a string in the payload buffer.
5480
 * Returns the pos of the next topic expression or -1 when the list
5481
 * of topics is exhausted.
5482
 */
5483
int mg_mqtt_next_subscribe_topic(struct mg_mqtt_message *msg,
5484
                                 struct mg_str *topic, uint8_t *qos, int pos);
5485

    
5486
/*
5487
 * Matches a topic against a topic expression
5488
 *
5489
 * Returns 1 if it matches; 0 otherwise.
5490
 */
5491
int mg_mqtt_match_topic_expression(struct mg_str exp, struct mg_str topic);
5492

    
5493
/*
5494
 * Same as `mg_mqtt_match_topic_expression()`, but takes `exp` as a
5495
 * NULL-terminated string.
5496
 */
5497
int mg_mqtt_vmatch_topic_expression(const char *exp, struct mg_str topic);
5498

    
5499
#ifdef __cplusplus
5500
}
5501
#endif /* __cplusplus */
5502

    
5503
#endif /* CS_MONGOOSE_SRC_MQTT_H_ */
5504
#ifdef MG_MODULE_LINES
5505
#line 1 "mongoose/src/mg_mqtt_server.h"
5506
#endif
5507
/*
5508
 * Copyright (c) 2014 Cesanta Software Limited
5509
 * All rights reserved
5510
 * This software is dual-licensed: you can redistribute it and/or modify
5511
 * it under the terms of the GNU General Public License version 2 as
5512
 * published by the Free Software Foundation. For the terms of this
5513
 * license, see <http://www.gnu.org/licenses/>.
5514
 *
5515
 * You are free to use this software under the terms of the GNU General
5516
 * Public License, but WITHOUT ANY WARRANTY; without even the implied
5517
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5518
 * See the GNU General Public License for more details.
5519
 *
5520
 * Alternatively, you can license this software under a commercial
5521
 * license, as set out in <https://www.cesanta.com/license>.
5522
 */
5523

    
5524
/*
5525
 * === MQTT Server API reference
5526
 */
5527

    
5528
#ifndef CS_MONGOOSE_SRC_MQTT_BROKER_H_
5529
#define CS_MONGOOSE_SRC_MQTT_BROKER_H_
5530

    
5531
#if MG_ENABLE_MQTT_BROKER
5532

    
5533
/* Amalgamated: #include "common/queue.h" */
5534
/* Amalgamated: #include "mg_mqtt.h" */
5535

    
5536
#ifdef __cplusplus
5537
extern "C" {
5538
#endif /* __cplusplus */
5539

    
5540
#ifndef MG_MQTT_MAX_SESSION_SUBSCRIPTIONS
5541
#define MG_MQTT_MAX_SESSION_SUBSCRIPTIONS 512
5542
#endif
5543

    
5544
struct mg_mqtt_broker;
5545

    
5546
/* MQTT session (Broker side). */
5547
struct mg_mqtt_session {
5548
  struct mg_mqtt_broker *brk;       /* Broker */
5549
  LIST_ENTRY(mg_mqtt_session) link; /* mg_mqtt_broker::sessions linkage */
5550
  struct mg_connection *nc;         /* Connection with the client */
5551
  size_t num_subscriptions;         /* Size of `subscriptions` array */
5552
  void *user_data;                  /* User data */
5553
  struct mg_mqtt_topic_expression *subscriptions;
5554
};
5555

    
5556
/* MQTT broker. */
5557
struct mg_mqtt_broker {
5558
  LIST_HEAD(_mg_sesshead, mg_mqtt_session) sessions; /* Session list */
5559
  void *user_data;                                   /* User data */
5560
};
5561

    
5562
/* Initialises a MQTT broker. */
5563
void mg_mqtt_broker_init(struct mg_mqtt_broker *brk, void *user_data);
5564

    
5565
/*
5566
 * Processes a MQTT broker message.
5567
 *
5568
 * The listening connection expects a pointer to an initialised
5569
 * `mg_mqtt_broker` structure in the `user_data` field.
5570
 *
5571
 * Basic usage:
5572
 *
5573
 * ```c
5574
 * mg_mqtt_broker_init(&brk, NULL);
5575
 *
5576
 * if ((nc = mg_bind(&mgr, address, mg_mqtt_broker)) == NULL) {
5577
 *   // fail;
5578
 * }
5579
 * nc->user_data = &brk;
5580
 * ```
5581
 *
5582
 * New incoming connections will receive a `mg_mqtt_session` structure
5583
 * in the connection `user_data`. The original `user_data` will be stored
5584
 * in the `user_data` field of the session structure. This allows the user
5585
 * handler to store user data before `mg_mqtt_broker` creates the session.
5586
 *
5587
 * Since only the MG_EV_ACCEPT message is processed by the listening socket,
5588
 * for most events the `user_data` will thus point to a `mg_mqtt_session`.
5589
 */
5590
void mg_mqtt_broker(struct mg_connection *brk, int ev, void *data);
5591

    
5592
/*
5593
 * Iterates over all MQTT session connections. Example:
5594
 *
5595
 * ```c
5596
 * struct mg_mqtt_session *s;
5597
 * for (s = mg_mqtt_next(brk, NULL); s != NULL; s = mg_mqtt_next(brk, s)) {
5598
 *   // Do something
5599
 * }
5600
 * ```
5601
 */
5602
struct mg_mqtt_session *mg_mqtt_next(struct mg_mqtt_broker *brk,
5603
                                     struct mg_mqtt_session *s);
5604

    
5605
#ifdef __cplusplus
5606
}
5607
#endif /* __cplusplus */
5608

    
5609
#endif /* MG_ENABLE_MQTT_BROKER */
5610
#endif /* CS_MONGOOSE_SRC_MQTT_BROKER_H_ */
5611
#ifdef MG_MODULE_LINES
5612
#line 1 "mongoose/src/mg_dns.h"
5613
#endif
5614
/*
5615
 * Copyright (c) 2014 Cesanta Software Limited
5616
 * All rights reserved
5617
 */
5618

    
5619
/*
5620
 * === DNS API reference
5621
 */
5622

    
5623
#ifndef CS_MONGOOSE_SRC_DNS_H_
5624
#define CS_MONGOOSE_SRC_DNS_H_
5625

    
5626
/* Amalgamated: #include "mg_net.h" */
5627

    
5628
#ifdef __cplusplus
5629
extern "C" {
5630
#endif /* __cplusplus */
5631

    
5632
#define MG_DNS_A_RECORD 0x01     /* Lookup IP address */
5633
#define MG_DNS_CNAME_RECORD 0x05 /* Lookup CNAME */
5634
#define MG_DNS_PTR_RECORD 0x0c   /* Lookup PTR */
5635
#define MG_DNS_TXT_RECORD 0x10   /* Lookup TXT */
5636
#define MG_DNS_AAAA_RECORD 0x1c  /* Lookup IPv6 address */
5637
#define MG_DNS_SRV_RECORD 0x21   /* Lookup SRV */
5638
#define MG_DNS_MX_RECORD 0x0f    /* Lookup mail server for domain */
5639
#define MG_DNS_ANY_RECORD 0xff
5640
#define MG_DNS_NSEC_RECORD 0x2f
5641

    
5642
#define MG_MAX_DNS_QUESTIONS 32
5643
#define MG_MAX_DNS_ANSWERS 32
5644

    
5645
#define MG_DNS_MESSAGE 100 /* High-level DNS message event */
5646

    
5647
enum mg_dns_resource_record_kind {
5648
  MG_DNS_INVALID_RECORD = 0,
5649
  MG_DNS_QUESTION,
5650
  MG_DNS_ANSWER
5651
};
5652

    
5653
/* DNS resource record. */
5654
struct mg_dns_resource_record {
5655
  struct mg_str name; /* buffer with compressed name */
5656
  int rtype;
5657
  int rclass;
5658
  int ttl;
5659
  enum mg_dns_resource_record_kind kind;
5660
  struct mg_str rdata; /* protocol data (can be a compressed name) */
5661
};
5662

    
5663
/* DNS message (request and response). */
5664
struct mg_dns_message {
5665
  struct mg_str pkt; /* packet body */
5666
  uint16_t flags;
5667
  uint16_t transaction_id;
5668
  int num_questions;
5669
  int num_answers;
5670
  struct mg_dns_resource_record questions[MG_MAX_DNS_QUESTIONS];
5671
  struct mg_dns_resource_record answers[MG_MAX_DNS_ANSWERS];
5672
};
5673

    
5674
struct mg_dns_resource_record *mg_dns_next_record(
5675
    struct mg_dns_message *msg, int query, struct mg_dns_resource_record *prev);
5676

    
5677
/*
5678
 * Parses the record data from a DNS resource record.
5679
 *
5680
 *  - A:     struct in_addr *ina
5681
 *  - AAAA:  struct in6_addr *ina
5682
 *  - CNAME: char buffer
5683
 *
5684
 * Returns -1 on error.
5685
 *
5686
 * TODO(mkm): MX
5687
 */
5688
int mg_dns_parse_record_data(struct mg_dns_message *msg,
5689
                             struct mg_dns_resource_record *rr, void *data,
5690
                             size_t data_len);
5691

    
5692
/*
5693
 * Sends a DNS query to the remote end.
5694
 */
5695
void mg_send_dns_query(struct mg_connection *nc, const char *name,
5696
                       int query_type);
5697

    
5698
/*
5699
 * Inserts a DNS header to an IO buffer.
5700
 *
5701
 * Returns the number of bytes inserted.
5702
 */
5703
int mg_dns_insert_header(struct mbuf *io, size_t pos,
5704
                         struct mg_dns_message *msg);
5705

    
5706
/*
5707
 * Appends already encoded questions from an existing message.
5708
 *
5709
 * This is useful when generating a DNS reply message which includes
5710
 * all question records.
5711
 *
5712
 * Returns the number of appended bytes.
5713
 */
5714
int mg_dns_copy_questions(struct mbuf *io, struct mg_dns_message *msg);
5715

    
5716
/*
5717
 * Encodes and appends a DNS resource record to an IO buffer.
5718
 *
5719
 * The record metadata is taken from the `rr` parameter, while the name and data
5720
 * are taken from the parameters, encoded in the appropriate format depending on
5721
 * record type and stored in the IO buffer. The encoded values might contain
5722
 * offsets within the IO buffer. It's thus important that the IO buffer doesn't
5723
 * get trimmed while a sequence of records are encoded while preparing a DNS
5724
 * reply.
5725
 *
5726
 * This function doesn't update the `name` and `rdata` pointers in the `rr`
5727
 * struct because they might be invalidated as soon as the IO buffer grows
5728
 * again.
5729
 *
5730
 * Returns the number of bytes appended or -1 in case of error.
5731
 */
5732
int mg_dns_encode_record(struct mbuf *io, struct mg_dns_resource_record *rr,
5733
                         const char *name, size_t nlen, const void *rdata,
5734
                         size_t rlen);
5735

    
5736
/*
5737
 * Encodes a DNS name.
5738
 */
5739
int mg_dns_encode_name(struct mbuf *io, const char *name, size_t len);
5740

    
5741
/* Low-level: parses a DNS response. */
5742
int mg_parse_dns(const char *buf, int len, struct mg_dns_message *msg);
5743

    
5744
/*
5745
 * Uncompresses a DNS compressed name.
5746
 *
5747
 * The containing DNS message is required because of the compressed encoding
5748
 * and reference suffixes present elsewhere in the packet.
5749
 *
5750
 * If the name is less than `dst_len` characters long, the remainder
5751
 * of `dst` is terminated with `\0` characters. Otherwise, `dst` is not
5752
 * terminated.
5753
 *
5754
 * If `dst_len` is 0 `dst` can be NULL.
5755
 * Returns the uncompressed name length.
5756
 */
5757
size_t mg_dns_uncompress_name(struct mg_dns_message *msg, struct mg_str *name,
5758
                              char *dst, int dst_len);
5759

    
5760
/*
5761
 * Attaches a built-in DNS event handler to the given listening connection.
5762
 *
5763
 * The DNS event handler parses the incoming UDP packets, treating them as DNS
5764
 * requests. If an incoming packet gets successfully parsed by the DNS event
5765
 * handler, a user event handler will receive an `MG_DNS_REQUEST` event, with
5766
 * `ev_data` pointing to the parsed `struct mg_dns_message`.
5767
 *
5768
 * See
5769
 * [captive_dns_server](https://github.com/cesanta/mongoose/tree/master/examples/captive_dns_server)
5770
 * example on how to handle DNS request and send DNS reply.
5771
 */
5772
void mg_set_protocol_dns(struct mg_connection *nc);
5773

    
5774
#ifdef __cplusplus
5775
}
5776
#endif /* __cplusplus */
5777
#endif /* CS_MONGOOSE_SRC_DNS_H_ */
5778
#ifdef MG_MODULE_LINES
5779
#line 1 "mongoose/src/mg_dns_server.h"
5780
#endif
5781
/*
5782
 * Copyright (c) 2014 Cesanta Software Limited
5783
 * All rights reserved
5784
 */
5785

    
5786
/*
5787
 * === DNS server API reference
5788
 *
5789
 * Disabled by default; enable with `-DMG_ENABLE_DNS_SERVER`.
5790
 */
5791

    
5792
#ifndef CS_MONGOOSE_SRC_DNS_SERVER_H_
5793
#define CS_MONGOOSE_SRC_DNS_SERVER_H_
5794

    
5795
#if MG_ENABLE_DNS_SERVER
5796

    
5797
/* Amalgamated: #include "mg_dns.h" */
5798

    
5799
#ifdef __cplusplus
5800
extern "C" {
5801
#endif /* __cplusplus */
5802

    
5803
#define MG_DNS_SERVER_DEFAULT_TTL 3600
5804

    
5805
struct mg_dns_reply {
5806
  struct mg_dns_message *msg;
5807
  struct mbuf *io;
5808
  size_t start;
5809
};
5810

    
5811
/*
5812
 * Creates a DNS reply.
5813
 *
5814
 * The reply will be based on an existing query message `msg`.
5815
 * The query body will be appended to the output buffer.
5816
 * "reply + recursion allowed" will be added to the message flags and the
5817
 * message's num_answers will be set to 0.
5818
 *
5819
 * Answer records can be appended with `mg_dns_send_reply` or by lower
5820
 * level function defined in the DNS API.
5821
 *
5822
 * In order to send a reply use `mg_dns_send_reply`.
5823
 * It's possible to use a connection's send buffer as reply buffer,
5824
 * and it will work for both UDP and TCP connections.
5825
 *
5826
 * Example:
5827
 *
5828
 * ```c
5829
 * reply = mg_dns_create_reply(&nc->send_mbuf, msg);
5830
 * for (i = 0; i < msg->num_questions; i++) {
5831
 *   rr = &msg->questions[i];
5832
 *   if (rr->rtype == MG_DNS_A_RECORD) {
5833
 *     mg_dns_reply_record(&reply, rr, 3600, &dummy_ip_addr, 4);
5834
 *   }
5835
 * }
5836
 * mg_dns_send_reply(nc, &reply);
5837
 * ```
5838
 */
5839
struct mg_dns_reply mg_dns_create_reply(struct mbuf *io,
5840
                                        struct mg_dns_message *msg);
5841

    
5842
/*
5843
 * Appends a DNS reply record to the IO buffer and to the DNS message.
5844
 *
5845
 * The message's num_answers field will be incremented. It's the caller's duty
5846
 * to ensure num_answers is properly initialised.
5847
 *
5848
 * Returns -1 on error.
5849
 */
5850
int mg_dns_reply_record(struct mg_dns_reply *reply,
5851
                        struct mg_dns_resource_record *question,
5852
                        const char *name, int rtype, int ttl, const void *rdata,
5853
                        size_t rdata_len);
5854

    
5855
/*
5856
 * Sends a DNS reply through a connection.
5857
 *
5858
 * The DNS data is stored in an IO buffer pointed by reply structure in `r`.
5859
 * This function mutates the content of that buffer in order to ensure that
5860
 * the DNS header reflects the size and flags of the message, that might have
5861
 * been updated either with `mg_dns_reply_record` or by direct manipulation of
5862
 * `r->message`.
5863
 *
5864
 * Once sent, the IO buffer will be trimmed unless the reply IO buffer
5865
 * is the connection's send buffer and the connection is not in UDP mode.
5866
 */
5867
void mg_dns_send_reply(struct mg_connection *nc, struct mg_dns_reply *r);
5868

    
5869
#ifdef __cplusplus
5870
}
5871
#endif /* __cplusplus */
5872

    
5873
#endif /* MG_ENABLE_DNS_SERVER */
5874
#endif /* CS_MONGOOSE_SRC_DNS_SERVER_H_ */
5875
#ifdef MG_MODULE_LINES
5876
#line 1 "mongoose/src/mg_resolv.h"
5877
#endif
5878
/*
5879
 * Copyright (c) 2014 Cesanta Software Limited
5880
 * All rights reserved
5881
 */
5882

    
5883
/*
5884
 * === API reference
5885
 */
5886

    
5887
#ifndef CS_MONGOOSE_SRC_RESOLV_H_
5888
#define CS_MONGOOSE_SRC_RESOLV_H_
5889

    
5890
/* Amalgamated: #include "mg_dns.h" */
5891

    
5892
#ifdef __cplusplus
5893
extern "C" {
5894
#endif /* __cplusplus */
5895

    
5896
enum mg_resolve_err {
5897
  MG_RESOLVE_OK = 0,
5898
  MG_RESOLVE_NO_ANSWERS = 1,
5899
  MG_RESOLVE_EXCEEDED_RETRY_COUNT = 2,
5900
  MG_RESOLVE_TIMEOUT = 3
5901
};
5902

    
5903
typedef void (*mg_resolve_callback_t)(struct mg_dns_message *dns_message,
5904
                                      void *user_data, enum mg_resolve_err);
5905

    
5906
/* Options for `mg_resolve_async_opt`. */
5907
struct mg_resolve_async_opts {
5908
  const char *nameserver;
5909
  int max_retries;    /* defaults to 2 if zero */
5910
  int timeout;        /* in seconds; defaults to 5 if zero */
5911
  int accept_literal; /* pseudo-resolve literal ipv4 and ipv6 addrs */
5912
  int only_literal;   /* only resolves literal addrs; sync cb invocation */
5913
  struct mg_connection **dns_conn; /* return DNS connection */
5914
};
5915

    
5916
/* See `mg_resolve_async_opt()` */
5917
int mg_resolve_async(struct mg_mgr *mgr, const char *name, int query,
5918
                     mg_resolve_callback_t cb, void *data);
5919

    
5920
/* Set default DNS server */
5921
void mg_set_nameserver(struct mg_mgr *mgr, const char *nameserver);
5922

    
5923
/*
5924
 * Resolved a DNS name asynchronously.
5925
 *
5926
 * Upon successful resolution, the user callback will be invoked
5927
 * with the full DNS response message and a pointer to the user's
5928
 * context `data`.
5929
 *
5930
 * In case of timeout while performing the resolution the callback
5931
 * will receive a NULL `msg`.
5932
 *
5933
 * The DNS answers can be extracted with `mg_next_record` and
5934
 * `mg_dns_parse_record_data`:
5935
 *
5936
 * [source,c]
5937
 * ----
5938
 * struct in_addr ina;
5939
 * struct mg_dns_resource_record *rr = mg_next_record(msg, MG_DNS_A_RECORD,
5940
 *   NULL);
5941
 * mg_dns_parse_record_data(msg, rr, &ina, sizeof(ina));
5942
 * ----
5943
 */
5944
int mg_resolve_async_opt(struct mg_mgr *mgr, const char *name, int query,
5945
                         mg_resolve_callback_t cb, void *data,
5946
                         struct mg_resolve_async_opts opts);
5947

    
5948
/*
5949
 * Resolve a name from `/etc/hosts`.
5950
 *
5951
 * Returns 0 on success, -1 on failure.
5952
 */
5953
int mg_resolve_from_hosts_file(const char *host, union socket_address *usa);
5954

    
5955
#ifdef __cplusplus
5956
}
5957
#endif /* __cplusplus */
5958
#endif /* CS_MONGOOSE_SRC_RESOLV_H_ */
5959
#ifdef MG_MODULE_LINES
5960
#line 1 "mongoose/src/mg_coap.h"
5961
#endif
5962
/*
5963
 * Copyright (c) 2015 Cesanta Software Limited
5964
 * All rights reserved
5965
 * This software is dual-licensed: you can redistribute it and/or modify
5966
 * it under the terms of the GNU General Public License version 2 as
5967
 * published by the Free Software Foundation. For the terms of this
5968
 * license, see <http://www.gnu.org/licenses/>.
5969
 *
5970
 * You are free to use this software under the terms of the GNU General
5971
 * Public License, but WITHOUT ANY WARRANTY; without even the implied
5972
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5973
 * See the GNU General Public License for more details.
5974
 *
5975
 * Alternatively, you can license this software under a commercial
5976
 * license, as set out in <https://www.cesanta.com/license>.
5977
 */
5978

    
5979
/*
5980
 * === CoAP API reference
5981
 *
5982
 * CoAP message format:
5983
 *
5984
 * ```
5985
 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
5986
 * |Ver| T | TKL | Code | Message ID | Token (if any, TKL bytes) ...
5987
 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
5988
 * | Options (if any) ...            |1 1 1 1 1 1 1 1| Payload (if any) ...
5989
 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
5990
 * ```
5991
 */
5992

    
5993
#ifndef CS_MONGOOSE_SRC_COAP_H_
5994
#define CS_MONGOOSE_SRC_COAP_H_
5995

    
5996
#if MG_ENABLE_COAP
5997

    
5998
#define MG_COAP_MSG_TYPE_FIELD 0x2
5999
#define MG_COAP_CODE_CLASS_FIELD 0x4
6000
#define MG_COAP_CODE_DETAIL_FIELD 0x8
6001
#define MG_COAP_MSG_ID_FIELD 0x10
6002
#define MG_COAP_TOKEN_FIELD 0x20
6003
#define MG_COAP_OPTIOMG_FIELD 0x40
6004
#define MG_COAP_PAYLOAD_FIELD 0x80
6005

    
6006
#define MG_COAP_ERROR 0x10000
6007
#define MG_COAP_FORMAT_ERROR (MG_COAP_ERROR | 0x20000)
6008
#define MG_COAP_IGNORE (MG_COAP_ERROR | 0x40000)
6009
#define MG_COAP_NOT_ENOUGH_DATA (MG_COAP_ERROR | 0x80000)
6010
#define MG_COAP_NETWORK_ERROR (MG_COAP_ERROR | 0x100000)
6011

    
6012
#define MG_COAP_MSG_CON 0
6013
#define MG_COAP_MSG_NOC 1
6014
#define MG_COAP_MSG_ACK 2
6015
#define MG_COAP_MSG_RST 3
6016
#define MG_COAP_MSG_MAX 3
6017

    
6018
#define MG_COAP_CODECLASS_REQUEST 0
6019
#define MG_COAP_CODECLASS_RESP_OK 2
6020
#define MG_COAP_CODECLASS_CLIENT_ERR 4
6021
#define MG_COAP_CODECLASS_SRV_ERR 5
6022

    
6023
#define MG_COAP_EVENT_BASE 300
6024
#define MG_EV_COAP_CON (MG_COAP_EVENT_BASE + MG_COAP_MSG_CON)
6025
#define MG_EV_COAP_NOC (MG_COAP_EVENT_BASE + MG_COAP_MSG_NOC)
6026
#define MG_EV_COAP_ACK (MG_COAP_EVENT_BASE + MG_COAP_MSG_ACK)
6027
#define MG_EV_COAP_RST (MG_COAP_EVENT_BASE + MG_COAP_MSG_RST)
6028

    
6029
/*
6030
 * CoAP options.
6031
 * Use mg_coap_add_option and mg_coap_free_options
6032
 * for creation and destruction.
6033
 */
6034
struct mg_coap_option {
6035
  struct mg_coap_option *next;
6036
  uint32_t number;
6037
  struct mg_str value;
6038
};
6039

    
6040
/* CoAP message. See RFC 7252 for details. */
6041
struct mg_coap_message {
6042
  uint32_t flags;
6043
  uint8_t msg_type;
6044
  uint8_t code_class;
6045
  uint8_t code_detail;
6046
  uint16_t msg_id;
6047
  struct mg_str token;
6048
  struct mg_coap_option *options;
6049
  struct mg_str payload;
6050
  struct mg_coap_option *optiomg_tail;
6051
};
6052

    
6053
#ifdef __cplusplus
6054
extern "C" {
6055
#endif /* __cplusplus */
6056

    
6057
/* Sets CoAP protocol handler - triggers CoAP specific events. */
6058
int mg_set_protocol_coap(struct mg_connection *nc);
6059

    
6060
/*
6061
 * Adds a new option to mg_coap_message structure.
6062
 * Returns pointer to the newly created option.
6063
 * Note: options must be freed by using mg_coap_free_options
6064
 */
6065
struct mg_coap_option *mg_coap_add_option(struct mg_coap_message *cm,
6066
                                          uint32_t number, char *value,
6067
                                          size_t len);
6068

    
6069
/*
6070
 * Frees the memory allocated for options.
6071
 * If the cm parameter doesn't contain any option it does nothing.
6072
 */
6073
void mg_coap_free_options(struct mg_coap_message *cm);
6074

    
6075
/*
6076
 * Composes a CoAP message from `mg_coap_message`
6077
 * and sends it into `nc` connection.
6078
 * Returns 0 on success. On error, it is a bitmask:
6079
 *
6080
 * - `#define MG_COAP_ERROR 0x10000`
6081
 * - `#define MG_COAP_FORMAT_ERROR (MG_COAP_ERROR | 0x20000)`
6082
 * - `#define MG_COAP_IGNORE (MG_COAP_ERROR | 0x40000)`
6083
 * - `#define MG_COAP_NOT_ENOUGH_DATA (MG_COAP_ERROR | 0x80000)`
6084
 * - `#define MG_COAP_NETWORK_ERROR (MG_COAP_ERROR | 0x100000)`
6085
 */
6086
uint32_t mg_coap_send_message(struct mg_connection *nc,
6087
                              struct mg_coap_message *cm);
6088

    
6089
/*
6090
 * Composes CoAP acknowledgement from `mg_coap_message`
6091
 * and sends it into `nc` connection.
6092
 * Return value: see `mg_coap_send_message()`
6093
 */
6094
uint32_t mg_coap_send_ack(struct mg_connection *nc, uint16_t msg_id);
6095

    
6096
/*
6097
 * Parses CoAP message and fills mg_coap_message and returns cm->flags.
6098
 * This is a helper function.
6099
 *
6100
 * NOTE: usually CoAP works over UDP, so lack of data means format error.
6101
 * But, in theory, it is possible to use CoAP over TCP (according to RFC)
6102
 *
6103
 * The caller has to check results and treat COAP_NOT_ENOUGH_DATA according to
6104
 * underlying protocol:
6105
 *
6106
 * - in case of UDP COAP_NOT_ENOUGH_DATA means COAP_FORMAT_ERROR,
6107
 * - in case of TCP client can try to receive more data
6108
 *
6109
 * Return value: see `mg_coap_send_message()`
6110
 */
6111
uint32_t mg_coap_parse(struct mbuf *io, struct mg_coap_message *cm);
6112

    
6113
/*
6114
 * Composes CoAP message from mg_coap_message structure.
6115
 * This is a helper function.
6116
 * Return value: see `mg_coap_send_message()`
6117
 */
6118
uint32_t mg_coap_compose(struct mg_coap_message *cm, struct mbuf *io);
6119

    
6120
#ifdef __cplusplus
6121
}
6122
#endif /* __cplusplus */
6123

    
6124
#endif /* MG_ENABLE_COAP */
6125

    
6126
#endif /* CS_MONGOOSE_SRC_COAP_H_ */
6127
#ifdef MG_MODULE_LINES
6128
#line 1 "mongoose/src/mg_sntp.h"
6129
#endif
6130
/*
6131
 * Copyright (c) 2016 Cesanta Software Limited
6132
 * All rights reserved
6133
 */
6134

    
6135
#ifndef CS_MONGOOSE_SRC_SNTP_H_
6136
#define CS_MONGOOSE_SRC_SNTP_H_
6137

    
6138
#if MG_ENABLE_SNTP
6139

    
6140
#define MG_SNTP_EVENT_BASE 500
6141

    
6142
/*
6143
 * Received reply from time server. Event handler parameter contains
6144
 * pointer to mg_sntp_message structure
6145
 */
6146
#define MG_SNTP_REPLY (MG_SNTP_EVENT_BASE + 1)
6147

    
6148
/* Received malformed SNTP packet */
6149
#define MG_SNTP_MALFORMED_REPLY (MG_SNTP_EVENT_BASE + 2)
6150

    
6151
/* Failed to get time from server (timeout etc) */
6152
#define MG_SNTP_FAILED (MG_SNTP_EVENT_BASE + 3)
6153

    
6154
struct mg_sntp_message {
6155
  /* if server sends this flags, user should not send requests to it */
6156
  int kiss_of_death;
6157
  /* usual mg_time */
6158
  double time;
6159
};
6160

    
6161
/* Establishes connection to given sntp server */
6162
struct mg_connection *mg_sntp_connect(struct mg_mgr *mgr,
6163
                                      MG_CB(mg_event_handler_t event_handler,
6164
                                            void *user_data),
6165
                                      const char *sntp_server_name);
6166

    
6167
/* Sends time request to given connection */
6168
void mg_sntp_send_request(struct mg_connection *c);
6169

    
6170
/*
6171
 * Helper function
6172
 * Establishes connection to time server, tries to send request
6173
 * repeats sending SNTP_ATTEMPTS times every SNTP_TIMEOUT sec
6174
 * (if needed)
6175
 * See sntp_client example
6176
 */
6177
struct mg_connection *mg_sntp_get_time(struct mg_mgr *mgr,
6178
                                       mg_event_handler_t event_handler,
6179
                                       const char *sntp_server_name);
6180

    
6181
#endif
6182

    
6183
#endif /* CS_MONGOOSE_SRC_SNTP_H_ */
6184
#ifdef MG_MODULE_LINES
6185
#line 1 "mongoose/src/mg_socks.h"
6186
#endif
6187
/*
6188
 * Copyright (c) 2017 Cesanta Software Limited
6189
 * All rights reserved
6190
 */
6191

    
6192
#ifndef CS_MONGOOSE_SRC_SOCKS_H_
6193
#define CS_MONGOOSE_SRC_SOCKS_H_
6194

    
6195
#if MG_ENABLE_SOCKS
6196

    
6197
#define MG_SOCKS_VERSION 5
6198

    
6199
#define MG_SOCKS_HANDSHAKE_DONE MG_F_USER_1
6200
#define MG_SOCKS_CONNECT_DONE MG_F_USER_2
6201

    
6202
/* SOCKS5 handshake methods */
6203
enum mg_socks_handshake_method {
6204
  MG_SOCKS_HANDSHAKE_NOAUTH = 0,     /* Handshake method - no authentication */
6205
  MG_SOCKS_HANDSHAKE_GSSAPI = 1,     /* Handshake method - GSSAPI auth */
6206
  MG_SOCKS_HANDSHAKE_USERPASS = 2,   /* Handshake method - user/password auth */
6207
  MG_SOCKS_HANDSHAKE_FAILURE = 0xff, /* Handshake method - failure */
6208
};
6209

    
6210
/* SOCKS5 commands */
6211
enum mg_socks_command {
6212
  MG_SOCKS_CMD_CONNECT = 1,       /* Command: CONNECT */
6213
  MG_SOCKS_CMD_BIND = 2,          /* Command: BIND */
6214
  MG_SOCKS_CMD_UDP_ASSOCIATE = 3, /* Command: UDP ASSOCIATE */
6215
};
6216

    
6217
/* SOCKS5 address types */
6218
enum mg_socks_address_type {
6219
  MG_SOCKS_ADDR_IPV4 = 1,   /* Address type: IPv4 */
6220
  MG_SOCKS_ADDR_DOMAIN = 3, /* Address type: Domain name */
6221
  MG_SOCKS_ADDR_IPV6 = 4,   /* Address type: IPv6 */
6222
};
6223

    
6224
/* SOCKS5 response codes */
6225
enum mg_socks_response {
6226
  MG_SOCKS_SUCCESS = 0,            /* Response: success */
6227
  MG_SOCKS_FAILURE = 1,            /* Response: failure */
6228
  MG_SOCKS_NOT_ALLOWED = 2,        /* Response: connection not allowed */
6229
  MG_SOCKS_NET_UNREACHABLE = 3,    /* Response: network unreachable */
6230
  MG_SOCKS_HOST_UNREACHABLE = 4,   /* Response: network unreachable */
6231
  MG_SOCKS_CONN_REFUSED = 5,       /* Response: network unreachable */
6232
  MG_SOCKS_TTL_EXPIRED = 6,        /* Response: network unreachable */
6233
  MG_SOCKS_CMD_NOT_SUPPORTED = 7,  /* Response: network unreachable */
6234
  MG_SOCKS_ADDR_NOT_SUPPORTED = 8, /* Response: network unreachable */
6235
};
6236

    
6237
#ifdef __cplusplus
6238
extern "C" {
6239
#endif /* __cplusplus */
6240

    
6241
/* Turn the connection into the SOCKS server */
6242
void mg_set_protocol_socks(struct mg_connection *c);
6243

    
6244
/* Create socks tunnel for the client connection */
6245
struct mg_iface *mg_socks_mk_iface(struct mg_mgr *, const char *proxy_addr);
6246

    
6247
#ifdef __cplusplus
6248
}
6249
#endif /* __cplusplus */
6250

    
6251
#endif
6252
#endif
(10-10/13)