Project

General

Profile

Feature #2758 » mongoose.c

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

 
1
#include "mongoose.h"
2
#ifdef MG_MODULE_LINES
3
#line 1 "mongoose/src/mg_internal.h"
4
#endif
5
/*
6
 * Copyright (c) 2014 Cesanta Software Limited
7
 * All rights reserved
8
 */
9

    
10
#ifndef CS_MONGOOSE_SRC_INTERNAL_H_
11
#define CS_MONGOOSE_SRC_INTERNAL_H_
12

    
13
/* Amalgamated: #include "common/mg_mem.h" */
14

    
15
#ifndef MBUF_REALLOC
16
#define MBUF_REALLOC MG_REALLOC
17
#endif
18

    
19
#ifndef MBUF_FREE
20
#define MBUF_FREE MG_FREE
21
#endif
22

    
23
#define MG_SET_PTRPTR(_ptr, _v) \
24
  do {                          \
25
    if (_ptr) *(_ptr) = _v;     \
26
  } while (0)
27

    
28
#ifndef MG_INTERNAL
29
#define MG_INTERNAL static
30
#endif
31

    
32
#ifdef PICOTCP
33
#define NO_LIBC
34
#define MG_DISABLE_PFS
35
#endif
36

    
37
/* Amalgamated: #include "common/cs_dbg.h" */
38
/* Amalgamated: #include "mg_http.h" */
39
/* Amalgamated: #include "mg_net.h" */
40

    
41
#define MG_CTL_MSG_MESSAGE_SIZE 8192
42

    
43
/* internals that need to be accessible in unit tests */
44
MG_INTERNAL struct mg_connection *mg_do_connect(struct mg_connection *nc,
45
                                                int proto,
46
                                                union socket_address *sa);
47

    
48
MG_INTERNAL int mg_parse_address(const char *str, union socket_address *sa,
49
                                 int *proto, char *host, size_t host_len);
50
MG_INTERNAL void mg_call(struct mg_connection *nc,
51
                         mg_event_handler_t ev_handler, void *user_data, int ev,
52
                         void *ev_data);
53
void mg_forward(struct mg_connection *from, struct mg_connection *to);
54
MG_INTERNAL void mg_add_conn(struct mg_mgr *mgr, struct mg_connection *c);
55
MG_INTERNAL void mg_remove_conn(struct mg_connection *c);
56
MG_INTERNAL struct mg_connection *mg_create_connection(
57
    struct mg_mgr *mgr, mg_event_handler_t callback,
58
    struct mg_add_sock_opts opts);
59
#ifdef _WIN32
60
/* Retur value is the same as for MultiByteToWideChar. */
61
int to_wchar(const char *path, wchar_t *wbuf, size_t wbuf_len);
62
#endif
63

    
64
struct ctl_msg {
65
  mg_event_handler_t callback;
66
  char message[MG_CTL_MSG_MESSAGE_SIZE];
67
};
68

    
69
#if MG_ENABLE_MQTT
70
struct mg_mqtt_message;
71

    
72
#define MG_MQTT_ERROR_INCOMPLETE_MSG -1
73
#define MG_MQTT_ERROR_MALFORMED_MSG -2
74

    
75
MG_INTERNAL int parse_mqtt(struct mbuf *io, struct mg_mqtt_message *mm);
76
#endif
77

    
78
/* Forward declarations for testing. */
79
extern void *(*test_malloc)(size_t size);
80
extern void *(*test_calloc)(size_t count, size_t size);
81

    
82
#ifndef MIN
83
#define MIN(a, b) ((a) < (b) ? (a) : (b))
84
#endif
85

    
86
#if MG_ENABLE_HTTP
87
struct mg_serve_http_opts;
88

    
89
/*
90
 * Reassemble the content of the buffer (buf, blen) which should be
91
 * in the HTTP chunked encoding, by collapsing data chunks to the
92
 * beginning of the buffer.
93
 *
94
 * If chunks get reassembled, modify hm->body to point to the reassembled
95
 * body and fire MG_EV_HTTP_CHUNK event. If handler sets MG_F_DELETE_CHUNK
96
 * in nc->flags, delete reassembled body from the mbuf.
97
 *
98
 * Return reassembled body size.
99
 */
100
MG_INTERNAL size_t mg_handle_chunked(struct mg_connection *nc,
101
                                     struct http_message *hm, char *buf,
102
                                     size_t blen);
103

    
104
#if MG_ENABLE_FILESYSTEM
105
MG_INTERNAL int mg_uri_to_local_path(struct http_message *hm,
106
                                     const struct mg_serve_http_opts *opts,
107
                                     char **local_path,
108
                                     struct mg_str *remainder);
109
MG_INTERNAL time_t mg_parse_date_string(const char *datetime);
110
MG_INTERNAL int mg_is_not_modified(struct http_message *hm, cs_stat_t *st);
111
#endif
112
#if MG_ENABLE_HTTP_CGI
113
MG_INTERNAL void mg_handle_cgi(struct mg_connection *nc, const char *prog,
114
                               const struct mg_str *path_info,
115
                               const struct http_message *hm,
116
                               const struct mg_serve_http_opts *opts);
117
struct mg_http_proto_data_cgi;
118
MG_INTERNAL void mg_http_free_proto_data_cgi(struct mg_http_proto_data_cgi *d);
119
#endif
120
#if MG_ENABLE_HTTP_SSI
121
MG_INTERNAL void mg_handle_ssi_request(struct mg_connection *nc,
122
                                       struct http_message *hm,
123
                                       const char *path,
124
                                       const struct mg_serve_http_opts *opts);
125
#endif
126
#if MG_ENABLE_HTTP_WEBDAV
127
MG_INTERNAL int mg_is_dav_request(const struct mg_str *s);
128
MG_INTERNAL void mg_handle_propfind(struct mg_connection *nc, const char *path,
129
                                    cs_stat_t *stp, struct http_message *hm,
130
                                    struct mg_serve_http_opts *opts);
131
MG_INTERNAL void mg_handle_lock(struct mg_connection *nc, const char *path);
132
MG_INTERNAL void mg_handle_mkcol(struct mg_connection *nc, const char *path,
133
                                 struct http_message *hm);
134
MG_INTERNAL void mg_handle_move(struct mg_connection *c,
135
                                const struct mg_serve_http_opts *opts,
136
                                const char *path, struct http_message *hm);
137
MG_INTERNAL void mg_handle_delete(struct mg_connection *nc,
138
                                  const struct mg_serve_http_opts *opts,
139
                                  const char *path);
140
MG_INTERNAL void mg_handle_put(struct mg_connection *nc, const char *path,
141
                               struct http_message *hm);
142
#endif
143
#if MG_ENABLE_HTTP_WEBSOCKET
144
MG_INTERNAL void mg_ws_handler(struct mg_connection *nc, int ev,
145
                               void *ev_data MG_UD_ARG(void *user_data));
146
MG_INTERNAL void mg_ws_handshake(struct mg_connection *nc,
147
                                 const struct mg_str *key,
148
                                 struct http_message *);
149
#endif
150
#endif /* MG_ENABLE_HTTP */
151

    
152
MG_INTERNAL int mg_get_errno(void);
153

    
154
MG_INTERNAL void mg_close_conn(struct mg_connection *conn);
155

    
156
#if MG_ENABLE_SNTP
157
MG_INTERNAL int mg_sntp_parse_reply(const char *buf, int len,
158
                                    struct mg_sntp_message *msg);
159
#endif
160

    
161
#endif /* CS_MONGOOSE_SRC_INTERNAL_H_ */
162
#ifdef MG_MODULE_LINES
163
#line 1 "common/mg_mem.h"
164
#endif
165
/*
166
 * Copyright (c) 2014-2016 Cesanta Software Limited
167
 * All rights reserved
168
 */
169

    
170
#ifndef CS_COMMON_MG_MEM_H_
171
#define CS_COMMON_MG_MEM_H_
172

    
173
#ifdef __cplusplus
174
extern "C" {
175
#endif
176

    
177
#ifndef MG_MALLOC
178
#define MG_MALLOC malloc
179
#endif
180

    
181
#ifndef MG_CALLOC
182
#define MG_CALLOC calloc
183
#endif
184

    
185
#ifndef MG_REALLOC
186
#define MG_REALLOC realloc
187
#endif
188

    
189
#ifndef MG_FREE
190
#define MG_FREE free
191
#endif
192

    
193
#ifdef __cplusplus
194
}
195
#endif
196

    
197
#endif /* CS_COMMON_MG_MEM_H_ */
198
#ifdef MG_MODULE_LINES
199
#line 1 "common/cs_base64.c"
200
#endif
201
/*
202
 * Copyright (c) 2014 Cesanta Software Limited
203
 * All rights reserved
204
 */
205

    
206
#ifndef EXCLUDE_COMMON
207

    
208
/* Amalgamated: #include "common/cs_base64.h" */
209

    
210
#include <string.h>
211

    
212
/* Amalgamated: #include "common/cs_dbg.h" */
213

    
214
/* ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/ */
215

    
216
#define NUM_UPPERCASES ('Z' - 'A' + 1)
217
#define NUM_LETTERS (NUM_UPPERCASES * 2)
218
#define NUM_DIGITS ('9' - '0' + 1)
219

    
220
/*
221
 * Emit a base64 code char.
222
 *
223
 * Doesn't use memory, thus it's safe to use to safely dump memory in crashdumps
224
 */
225
static void cs_base64_emit_code(struct cs_base64_ctx *ctx, int v) {
226
  if (v < NUM_UPPERCASES) {
227
    ctx->b64_putc(v + 'A', ctx->user_data);
228
  } else if (v < (NUM_LETTERS)) {
229
    ctx->b64_putc(v - NUM_UPPERCASES + 'a', ctx->user_data);
230
  } else if (v < (NUM_LETTERS + NUM_DIGITS)) {
231
    ctx->b64_putc(v - NUM_LETTERS + '0', ctx->user_data);
232
  } else {
233
    ctx->b64_putc(v - NUM_LETTERS - NUM_DIGITS == 0 ? '+' : '/',
234
                  ctx->user_data);
235
  }
236
}
237

    
238
static void cs_base64_emit_chunk(struct cs_base64_ctx *ctx) {
239
  int a, b, c;
240

    
241
  a = ctx->chunk[0];
242
  b = ctx->chunk[1];
243
  c = ctx->chunk[2];
244

    
245
  cs_base64_emit_code(ctx, a >> 2);
246
  cs_base64_emit_code(ctx, ((a & 3) << 4) | (b >> 4));
247
  if (ctx->chunk_size > 1) {
248
    cs_base64_emit_code(ctx, (b & 15) << 2 | (c >> 6));
249
  }
250
  if (ctx->chunk_size > 2) {
251
    cs_base64_emit_code(ctx, c & 63);
252
  }
253
}
254

    
255
void cs_base64_init(struct cs_base64_ctx *ctx, cs_base64_putc_t b64_putc,
256
                    void *user_data) {
257
  ctx->chunk_size = 0;
258
  ctx->b64_putc = b64_putc;
259
  ctx->user_data = user_data;
260
}
261

    
262
void cs_base64_update(struct cs_base64_ctx *ctx, const char *str, size_t len) {
263
  const unsigned char *src = (const unsigned char *) str;
264
  size_t i;
265
  for (i = 0; i < len; i++) {
266
    ctx->chunk[ctx->chunk_size++] = src[i];
267
    if (ctx->chunk_size == 3) {
268
      cs_base64_emit_chunk(ctx);
269
      ctx->chunk_size = 0;
270
    }
271
  }
272
}
273

    
274
void cs_base64_finish(struct cs_base64_ctx *ctx) {
275
  if (ctx->chunk_size > 0) {
276
    int i;
277
    memset(&ctx->chunk[ctx->chunk_size], 0, 3 - ctx->chunk_size);
278
    cs_base64_emit_chunk(ctx);
279
    for (i = 0; i < (3 - ctx->chunk_size); i++) {
280
      ctx->b64_putc('=', ctx->user_data);
281
    }
282
  }
283
}
284

    
285
#define BASE64_ENCODE_BODY                                                \
286
  static const char *b64 =                                                \
287
      "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; \
288
  int i, j, a, b, c;                                                      \
289
                                                                          \
290
  for (i = j = 0; i < src_len; i += 3) {                                  \
291
    a = src[i];                                                           \
292
    b = i + 1 >= src_len ? 0 : src[i + 1];                                \
293
    c = i + 2 >= src_len ? 0 : src[i + 2];                                \
294
                                                                          \
295
    BASE64_OUT(b64[a >> 2]);                                              \
296
    BASE64_OUT(b64[((a & 3) << 4) | (b >> 4)]);                           \
297
    if (i + 1 < src_len) {                                                \
298
      BASE64_OUT(b64[(b & 15) << 2 | (c >> 6)]);                          \
299
    }                                                                     \
300
    if (i + 2 < src_len) {                                                \
301
      BASE64_OUT(b64[c & 63]);                                            \
302
    }                                                                     \
303
  }                                                                       \
304
                                                                          \
305
  while (j % 4 != 0) {                                                    \
306
    BASE64_OUT('=');                                                      \
307
  }                                                                       \
308
  BASE64_FLUSH()
309

    
310
#define BASE64_OUT(ch) \
311
  do {                 \
312
    dst[j++] = (ch);   \
313
  } while (0)
314

    
315
#define BASE64_FLUSH() \
316
  do {                 \
317
    dst[j++] = '\0';   \
318
  } while (0)
319

    
320
void cs_base64_encode(const unsigned char *src, int src_len, char *dst) {
321
  BASE64_ENCODE_BODY;
322
}
323

    
324
#undef BASE64_OUT
325
#undef BASE64_FLUSH
326

    
327
#if CS_ENABLE_STDIO
328
#define BASE64_OUT(ch)      \
329
  do {                      \
330
    fprintf(f, "%c", (ch)); \
331
    j++;                    \
332
  } while (0)
333

    
334
#define BASE64_FLUSH()
335

    
336
void cs_fprint_base64(FILE *f, const unsigned char *src, int src_len) {
337
  BASE64_ENCODE_BODY;
338
}
339

    
340
#undef BASE64_OUT
341
#undef BASE64_FLUSH
342
#endif /* CS_ENABLE_STDIO */
343

    
344
/* Convert one byte of encoded base64 input stream to 6-bit chunk */
345
static unsigned char from_b64(unsigned char ch) {
346
  /* Inverse lookup map */
347
  static const unsigned char tab[128] = {
348
      255, 255, 255, 255,
349
      255, 255, 255, 255, /*  0 */
350
      255, 255, 255, 255,
351
      255, 255, 255, 255, /*  8 */
352
      255, 255, 255, 255,
353
      255, 255, 255, 255, /*  16 */
354
      255, 255, 255, 255,
355
      255, 255, 255, 255, /*  24 */
356
      255, 255, 255, 255,
357
      255, 255, 255, 255, /*  32 */
358
      255, 255, 255, 62,
359
      255, 255, 255, 63, /*  40 */
360
      52,  53,  54,  55,
361
      56,  57,  58,  59, /*  48 */
362
      60,  61,  255, 255,
363
      255, 200, 255, 255, /*  56   '=' is 200, on index 61 */
364
      255, 0,   1,   2,
365
      3,   4,   5,   6, /*  64 */
366
      7,   8,   9,   10,
367
      11,  12,  13,  14, /*  72 */
368
      15,  16,  17,  18,
369
      19,  20,  21,  22, /*  80 */
370
      23,  24,  25,  255,
371
      255, 255, 255, 255, /*  88 */
372
      255, 26,  27,  28,
373
      29,  30,  31,  32, /*  96 */
374
      33,  34,  35,  36,
375
      37,  38,  39,  40, /*  104 */
376
      41,  42,  43,  44,
377
      45,  46,  47,  48, /*  112 */
378
      49,  50,  51,  255,
379
      255, 255, 255, 255, /*  120 */
380
  };
381
  return tab[ch & 127];
382
}
383

    
384
int cs_base64_decode(const unsigned char *s, int len, char *dst, int *dec_len) {
385
  unsigned char a, b, c, d;
386
  int orig_len = len;
387
  char *orig_dst = dst;
388
  while (len >= 4 && (a = from_b64(s[0])) != 255 &&
389
         (b = from_b64(s[1])) != 255 && (c = from_b64(s[2])) != 255 &&
390
         (d = from_b64(s[3])) != 255) {
391
    s += 4;
392
    len -= 4;
393
    if (a == 200 || b == 200) break; /* '=' can't be there */
394
    *dst++ = a << 2 | b >> 4;
395
    if (c == 200) break;
396
    *dst++ = b << 4 | c >> 2;
397
    if (d == 200) break;
398
    *dst++ = c << 6 | d;
399
  }
400
  *dst = 0;
401
  if (dec_len != NULL) *dec_len = (dst - orig_dst);
402
  return orig_len - len;
403
}
404

    
405
#endif /* EXCLUDE_COMMON */
406
#ifdef MG_MODULE_LINES
407
#line 1 "common/cs_dbg.h"
408
#endif
409
/*
410
 * Copyright (c) 2014-2016 Cesanta Software Limited
411
 * All rights reserved
412
 */
413

    
414
#ifndef CS_COMMON_CS_DBG_H_
415
#define CS_COMMON_CS_DBG_H_
416

    
417
/* Amalgamated: #include "common/platform.h" */
418

    
419
#if CS_ENABLE_STDIO
420
#include <stdio.h>
421
#endif
422

    
423
#ifndef CS_ENABLE_DEBUG
424
#define CS_ENABLE_DEBUG 0
425
#endif
426

    
427
#ifndef CS_LOG_ENABLE_TS_DIFF
428
#define CS_LOG_ENABLE_TS_DIFF 0
429
#endif
430

    
431
#ifdef __cplusplus
432
extern "C" {
433
#endif /* __cplusplus */
434

    
435
/*
436
 * Log level; `LL_INFO` is the default. Use `cs_log_set_level()` to change it.
437
 */
438
enum cs_log_level {
439
  LL_NONE = -1,
440
  LL_ERROR = 0,
441
  LL_WARN = 1,
442
  LL_INFO = 2,
443
  LL_DEBUG = 3,
444
  LL_VERBOSE_DEBUG = 4,
445

    
446
  _LL_MIN = -2,
447
  _LL_MAX = 5,
448
};
449

    
450
/*
451
 * Set max log level to print; messages with the level above the given one will
452
 * not be printed.
453
 */
454
void cs_log_set_level(enum cs_log_level level);
455

    
456
/*
457
 * Set log filter. NULL (a default) logs everything.
458
 * Otherwise, function name and file name will be tested against the given
459
 * pattern, and only matching messages will be printed.
460
 *
461
 * For the pattern syntax, refer to `mg_match_prefix()` in `str_util.h`.
462
 *
463
 * Example:
464
 * ```c
465
 * void foo(void) {
466
 *   LOG(LL_INFO, ("hello from foo"));
467
 * }
468
 *
469
 * void bar(void) {
470
 *   LOG(LL_INFO, ("hello from bar"));
471
 * }
472
 *
473
 * void test(void) {
474
 *   cs_log_set_filter(NULL);
475
 *   foo();
476
 *   bar();
477
 *
478
 *   cs_log_set_filter("f*");
479
 *   foo();
480
 *   bar(); // Will NOT print anything
481
 *
482
 *   cs_log_set_filter("bar");
483
 *   foo(); // Will NOT print anything
484
 *   bar();
485
 * }
486
 * ```
487
 */
488
void cs_log_set_filter(const char *pattern);
489

    
490
/*
491
 * Helper function which prints message prefix with the given `level`, function
492
 * name `func` and `filename`. If message should be printed (accordingly to the
493
 * current log level and filter), prints the prefix and returns 1, otherwise
494
 * returns 0.
495
 *
496
 * Clients should typically just use `LOG()` macro.
497
 */
498
int cs_log_print_prefix(enum cs_log_level level, const char *func,
499
                        const char *filename);
500

    
501
extern enum cs_log_level cs_log_threshold;
502

    
503
#if CS_ENABLE_STDIO
504

    
505
/*
506
 * Set file to write logs into. If `NULL`, logs go to `stderr`.
507
 */
508
void cs_log_set_file(FILE *file);
509

    
510
/*
511
 * Prints log to the current log file, appends "\n" in the end and flushes the
512
 * stream.
513
 */
514
void cs_log_printf(const char *fmt, ...)
515
#ifdef __GNUC__
516
    __attribute__((format(printf, 1, 2)))
517
#endif
518
    ;
519

    
520
/*
521
 * Format and print message `x` with the given level `l`. Example:
522
 *
523
 * ```c
524
 * LOG(LL_INFO, ("my info message: %d", 123));
525
 * LOG(LL_DEBUG, ("my debug message: %d", 123));
526
 * ```
527
 */
528
#define LOG(l, x)                                                    \
529
  do {                                                               \
530
    if (cs_log_print_prefix(l, __func__, __FILE__)) cs_log_printf x; \
531
  } while (0)
532

    
533
#ifndef CS_NDEBUG
534

    
535
/*
536
 * Shortcut for `LOG(LL_VERBOSE_DEBUG, (...))`
537
 */
538
#define DBG(x) LOG(LL_VERBOSE_DEBUG, x)
539

    
540
#else /* NDEBUG */
541

    
542
#define DBG(x)
543

    
544
#endif
545

    
546
#else /* CS_ENABLE_STDIO */
547

    
548
#define LOG(l, x)
549
#define DBG(x)
550

    
551
#endif
552

    
553
#ifdef __cplusplus
554
}
555
#endif /* __cplusplus */
556

    
557
#endif /* CS_COMMON_CS_DBG_H_ */
558
#ifdef MG_MODULE_LINES
559
#line 1 "common/cs_dbg.c"
560
#endif
561
/*
562
 * Copyright (c) 2014-2016 Cesanta Software Limited
563
 * All rights reserved
564
 */
565

    
566
/* Amalgamated: #include "common/cs_dbg.h" */
567

    
568
#include <stdarg.h>
569
#include <stdio.h>
570
#include <string.h>
571

    
572
/* Amalgamated: #include "common/cs_time.h" */
573
/* Amalgamated: #include "common/str_util.h" */
574

    
575
enum cs_log_level cs_log_threshold WEAK =
576
#if CS_ENABLE_DEBUG
577
    LL_VERBOSE_DEBUG;
578
#else
579
    LL_ERROR;
580
#endif
581

    
582
static char *s_filter_pattern = NULL;
583
static size_t s_filter_pattern_len;
584

    
585
void cs_log_set_filter(const char *pattern) WEAK;
586

    
587
#if CS_ENABLE_STDIO
588

    
589
FILE *cs_log_file WEAK = NULL;
590

    
591
#if CS_LOG_ENABLE_TS_DIFF
592
double cs_log_ts WEAK;
593
#endif
594

    
595
enum cs_log_level cs_log_cur_msg_level WEAK = LL_NONE;
596

    
597
void cs_log_set_filter(const char *pattern) {
598
  free(s_filter_pattern);
599
  if (pattern != NULL) {
600
    s_filter_pattern = strdup(pattern);
601
    s_filter_pattern_len = strlen(pattern);
602
  } else {
603
    s_filter_pattern = NULL;
604
    s_filter_pattern_len = 0;
605
  }
606
}
607

    
608
int cs_log_print_prefix(enum cs_log_level, const char *, const char *) WEAK;
609
int cs_log_print_prefix(enum cs_log_level level, const char *func,
610
                        const char *filename) {
611
  char prefix[21];
612

    
613
  if (level > cs_log_threshold) return 0;
614
  if (s_filter_pattern != NULL &&
615
      mg_match_prefix(s_filter_pattern, s_filter_pattern_len, func) == 0 &&
616
      mg_match_prefix(s_filter_pattern, s_filter_pattern_len, filename) == 0) {
617
    return 0;
618
  }
619

    
620
  strncpy(prefix, func, 20);
621
  prefix[20] = '\0';
622
  if (cs_log_file == NULL) cs_log_file = stderr;
623
  cs_log_cur_msg_level = level;
624
  fprintf(cs_log_file, "%-20s ", prefix);
625
#if CS_LOG_ENABLE_TS_DIFF
626
  {
627
    double now = cs_time();
628
    fprintf(cs_log_file, "%7u ", (unsigned int) ((now - cs_log_ts) * 1000000));
629
    cs_log_ts = now;
630
  }
631
#endif
632
  return 1;
633
}
634

    
635
void cs_log_printf(const char *fmt, ...) WEAK;
636
void cs_log_printf(const char *fmt, ...) {
637
  va_list ap;
638
  va_start(ap, fmt);
639
  vfprintf(cs_log_file, fmt, ap);
640
  va_end(ap);
641
  fputc('\n', cs_log_file);
642
  fflush(cs_log_file);
643
  cs_log_cur_msg_level = LL_NONE;
644
}
645

    
646
void cs_log_set_file(FILE *file) WEAK;
647
void cs_log_set_file(FILE *file) {
648
  cs_log_file = file;
649
}
650

    
651
#else
652

    
653
void cs_log_set_filter(const char *pattern) {
654
  (void) pattern;
655
}
656

    
657
#endif /* CS_ENABLE_STDIO */
658

    
659
void cs_log_set_level(enum cs_log_level level) WEAK;
660
void cs_log_set_level(enum cs_log_level level) {
661
  cs_log_threshold = level;
662
#if CS_LOG_ENABLE_TS_DIFF && CS_ENABLE_STDIO
663
  cs_log_ts = cs_time();
664
#endif
665
}
666
#ifdef MG_MODULE_LINES
667
#line 1 "common/cs_dirent.h"
668
#endif
669
/*
670
 * Copyright (c) 2014-2016 Cesanta Software Limited
671
 * All rights reserved
672
 */
673

    
674
#ifndef CS_COMMON_CS_DIRENT_H_
675
#define CS_COMMON_CS_DIRENT_H_
676

    
677
#include <limits.h>
678

    
679
/* Amalgamated: #include "common/platform.h" */
680

    
681
#ifdef __cplusplus
682
extern "C" {
683
#endif /* __cplusplus */
684

    
685
#ifdef CS_DEFINE_DIRENT
686
typedef struct { int dummy; } DIR;
687

    
688
struct dirent {
689
  int d_ino;
690
#ifdef _WIN32
691
  char d_name[MAX_PATH];
692
#else
693
  /* TODO(rojer): Use PATH_MAX but make sure it's sane on every platform */
694
  char d_name[256];
695
#endif
696
};
697

    
698
DIR *opendir(const char *dir_name);
699
int closedir(DIR *dir);
700
struct dirent *readdir(DIR *dir);
701
#endif /* CS_DEFINE_DIRENT */
702

    
703
#ifdef __cplusplus
704
}
705
#endif /* __cplusplus */
706

    
707
#endif /* CS_COMMON_CS_DIRENT_H_ */
708
#ifdef MG_MODULE_LINES
709
#line 1 "common/cs_dirent.c"
710
#endif
711
/*
712
 * Copyright (c) 2015 Cesanta Software Limited
713
 * All rights reserved
714
 */
715

    
716
#ifndef EXCLUDE_COMMON
717

    
718
/* Amalgamated: #include "common/mg_mem.h" */
719
/* Amalgamated: #include "common/cs_dirent.h" */
720

    
721
/*
722
 * This file contains POSIX opendir/closedir/readdir API implementation
723
 * for systems which do not natively support it (e.g. Windows).
724
 */
725

    
726
#ifdef _WIN32
727
struct win32_dir {
728
  DIR d;
729
  HANDLE handle;
730
  WIN32_FIND_DATAW info;
731
  struct dirent result;
732
};
733

    
734
DIR *opendir(const char *name) {
735
  struct win32_dir *dir = NULL;
736
  wchar_t wpath[MAX_PATH];
737
  DWORD attrs;
738

    
739
  if (name == NULL) {
740
    SetLastError(ERROR_BAD_ARGUMENTS);
741
  } else if ((dir = (struct win32_dir *) MG_MALLOC(sizeof(*dir))) == NULL) {
742
    SetLastError(ERROR_NOT_ENOUGH_MEMORY);
743
  } else {
744
    to_wchar(name, wpath, ARRAY_SIZE(wpath));
745
    attrs = GetFileAttributesW(wpath);
746
    if (attrs != 0xFFFFFFFF && (attrs & FILE_ATTRIBUTE_DIRECTORY)) {
747
      (void) wcscat(wpath, L"\\*");
748
      dir->handle = FindFirstFileW(wpath, &dir->info);
749
      dir->result.d_name[0] = '\0';
750
    } else {
751
      MG_FREE(dir);
752
      dir = NULL;
753
    }
754
  }
755

    
756
  return (DIR *) dir;
757
}
758

    
759
int closedir(DIR *d) {
760
  struct win32_dir *dir = (struct win32_dir *) d;
761
  int result = 0;
762

    
763
  if (dir != NULL) {
764
    if (dir->handle != INVALID_HANDLE_VALUE)
765
      result = FindClose(dir->handle) ? 0 : -1;
766
    MG_FREE(dir);
767
  } else {
768
    result = -1;
769
    SetLastError(ERROR_BAD_ARGUMENTS);
770
  }
771

    
772
  return result;
773
}
774

    
775
struct dirent *readdir(DIR *d) {
776
  struct win32_dir *dir = (struct win32_dir *) d;
777
  struct dirent *result = NULL;
778

    
779
  if (dir) {
780
    memset(&dir->result, 0, sizeof(dir->result));
781
    if (dir->handle != INVALID_HANDLE_VALUE) {
782
      result = &dir->result;
783
      (void) WideCharToMultiByte(CP_UTF8, 0, dir->info.cFileName, -1,
784
                                 result->d_name, sizeof(result->d_name), NULL,
785
                                 NULL);
786

    
787
      if (!FindNextFileW(dir->handle, &dir->info)) {
788
        (void) FindClose(dir->handle);
789
        dir->handle = INVALID_HANDLE_VALUE;
790
      }
791

    
792
    } else {
793
      SetLastError(ERROR_FILE_NOT_FOUND);
794
    }
795
  } else {
796
    SetLastError(ERROR_BAD_ARGUMENTS);
797
  }
798

    
799
  return result;
800
}
801
#endif
802

    
803
#endif /* EXCLUDE_COMMON */
804

    
805
/* ISO C requires a translation unit to contain at least one declaration */
806
typedef int cs_dirent_dummy;
807
#ifdef MG_MODULE_LINES
808
#line 1 "common/cs_time.c"
809
#endif
810
/*
811
 * Copyright (c) 2014-2016 Cesanta Software Limited
812
 * All rights reserved
813
 */
814

    
815
/* Amalgamated: #include "common/cs_time.h" */
816

    
817
#ifndef _WIN32
818
#include <stddef.h>
819
/*
820
 * There is no sys/time.h on ARMCC.
821
 */
822
#if !(defined(__ARMCC_VERSION) || defined(__ICCARM__)) && \
823
    !defined(__TI_COMPILER_VERSION__) &&                  \
824
    (!defined(CS_PLATFORM) || CS_PLATFORM != CS_P_NXP_LPC)
825
#include <sys/time.h>
826
#endif
827
#else
828
#include <windows.h>
829
#endif
830

    
831
double cs_time(void) WEAK;
832
double cs_time(void) {
833
  double now;
834
#ifndef _WIN32
835
  struct timeval tv;
836
  if (gettimeofday(&tv, NULL /* tz */) != 0) return 0;
837
  now = (double) tv.tv_sec + (((double) tv.tv_usec) / 1000000.0);
838
#else
839
  SYSTEMTIME sysnow;
840
  FILETIME ftime;
841
  GetLocalTime(&sysnow);
842
  SystemTimeToFileTime(&sysnow, &ftime);
843
  /*
844
   * 1. VC 6.0 doesn't support conversion uint64 -> double, so, using int64
845
   * This should not cause a problems in this (21th) century
846
   * 2. Windows FILETIME is a number of 100-nanosecond intervals since January
847
   * 1, 1601 while time_t is a number of _seconds_ since January 1, 1970 UTC,
848
   * thus, we need to convert to seconds and adjust amount (subtract 11644473600
849
   * seconds)
850
   */
851
  now = (double) (((int64_t) ftime.dwLowDateTime +
852
                   ((int64_t) ftime.dwHighDateTime << 32)) /
853
                  10000000.0) -
854
        11644473600;
855
#endif /* _WIN32 */
856
  return now;
857
}
858

    
859
double cs_timegm(const struct tm *tm) {
860
  /* Month-to-day offset for non-leap-years. */
861
  static const int month_day[12] = {0,   31,  59,  90,  120, 151,
862
                                    181, 212, 243, 273, 304, 334};
863

    
864
  /* Most of the calculation is easy; leap years are the main difficulty. */
865
  int month = tm->tm_mon % 12;
866
  int year = tm->tm_year + tm->tm_mon / 12;
867
  int year_for_leap;
868
  int64_t rt;
869

    
870
  if (month < 0) { /* Negative values % 12 are still negative. */
871
    month += 12;
872
    --year;
873
  }
874

    
875
  /* This is the number of Februaries since 1900. */
876
  year_for_leap = (month > 1) ? year + 1 : year;
877

    
878
  rt =
879
      tm->tm_sec /* Seconds */
880
      +
881
      60 *
882
          (tm->tm_min /* Minute = 60 seconds */
883
           +
884
           60 * (tm->tm_hour /* Hour = 60 minutes */
885
                 +
886
                 24 * (month_day[month] + tm->tm_mday - 1 /* Day = 24 hours */
887
                       + 365 * (year - 70)                /* Year = 365 days */
888
                       + (year_for_leap - 69) / 4 /* Every 4 years is leap... */
889
                       - (year_for_leap - 1) / 100 /* Except centuries... */
890
                       + (year_for_leap + 299) / 400))); /* Except 400s. */
891
  return rt < 0 ? -1 : (double) rt;
892
}
893
#ifdef MG_MODULE_LINES
894
#line 1 "common/cs_endian.h"
895
#endif
896
/*
897
 * Copyright (c) 2014-2016 Cesanta Software Limited
898
 * All rights reserved
899
 */
900

    
901
#ifndef CS_COMMON_CS_ENDIAN_H_
902
#define CS_COMMON_CS_ENDIAN_H_
903

    
904
#ifdef __cplusplus
905
extern "C" {
906
#endif
907

    
908
/*
909
 * clang with std=-c99 uses __LITTLE_ENDIAN, by default
910
 * while for ex, RTOS gcc - LITTLE_ENDIAN, by default
911
 * it depends on __USE_BSD, but let's have everything
912
 */
913
#if !defined(BYTE_ORDER) && defined(__BYTE_ORDER)
914
#define BYTE_ORDER __BYTE_ORDER
915
#ifndef LITTLE_ENDIAN
916
#define LITTLE_ENDIAN __LITTLE_ENDIAN
917
#endif /* LITTLE_ENDIAN */
918
#ifndef BIG_ENDIAN
919
#define BIG_ENDIAN __LITTLE_ENDIAN
920
#endif /* BIG_ENDIAN */
921
#endif /* BYTE_ORDER */
922

    
923
#ifdef __cplusplus
924
}
925
#endif
926

    
927
#endif /* CS_COMMON_CS_ENDIAN_H_ */
928
#ifdef MG_MODULE_LINES
929
#line 1 "common/cs_md5.c"
930
#endif
931
/*
932
 * This code implements the MD5 message-digest algorithm.
933
 * The algorithm is due to Ron Rivest.  This code was
934
 * written by Colin Plumb in 1993, no copyright is claimed.
935
 * This code is in the public domain; do with it what you wish.
936
 *
937
 * Equivalent code is available from RSA Data Security, Inc.
938
 * This code has been tested against that, and is equivalent,
939
 * except that you don't need to include two pages of legalese
940
 * with every copy.
941
 *
942
 * To compute the message digest of a chunk of bytes, declare an
943
 * MD5Context structure, pass it to MD5Init, call MD5Update as
944
 * needed on buffers full of bytes, and then call MD5Final, which
945
 * will fill a supplied 16-byte array with the digest.
946
 */
947

    
948
/* Amalgamated: #include "common/cs_md5.h" */
949
/* Amalgamated: #include "common/str_util.h" */
950

    
951
#if !defined(EXCLUDE_COMMON)
952
#if !CS_DISABLE_MD5
953

    
954
/* Amalgamated: #include "common/cs_endian.h" */
955

    
956
static void byteReverse(unsigned char *buf, unsigned longs) {
957
/* Forrest: MD5 expect LITTLE_ENDIAN, swap if BIG_ENDIAN */
958
#if BYTE_ORDER == BIG_ENDIAN
959
  do {
960
    uint32_t t = (uint32_t)((unsigned) buf[3] << 8 | buf[2]) << 16 |
961
                 ((unsigned) buf[1] << 8 | buf[0]);
962
    *(uint32_t *) buf = t;
963
    buf += 4;
964
  } while (--longs);
965
#else
966
  (void) buf;
967
  (void) longs;
968
#endif
969
}
970

    
971
#define F1(x, y, z) (z ^ (x & (y ^ z)))
972
#define F2(x, y, z) F1(z, x, y)
973
#define F3(x, y, z) (x ^ y ^ z)
974
#define F4(x, y, z) (y ^ (x | ~z))
975

    
976
#define MD5STEP(f, w, x, y, z, data, s) \
977
  (w += f(x, y, z) + data, w = w << s | w >> (32 - s), w += x)
978

    
979
/*
980
 * Start MD5 accumulation.  Set bit count to 0 and buffer to mysterious
981
 * initialization constants.
982
 */
983
void cs_md5_init(cs_md5_ctx *ctx) {
984
  ctx->buf[0] = 0x67452301;
985
  ctx->buf[1] = 0xefcdab89;
986
  ctx->buf[2] = 0x98badcfe;
987
  ctx->buf[3] = 0x10325476;
988

    
989
  ctx->bits[0] = 0;
990
  ctx->bits[1] = 0;
991
}
992

    
993
static void cs_md5_transform(uint32_t buf[4], uint32_t const in[16]) {
994
  register uint32_t a, b, c, d;
995

    
996
  a = buf[0];
997
  b = buf[1];
998
  c = buf[2];
999
  d = buf[3];
1000

    
1001
  MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
1002
  MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
1003
  MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
1004
  MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
1005
  MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
1006
  MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
1007
  MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
1008
  MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
1009
  MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
1010
  MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
1011
  MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
1012
  MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
1013
  MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
1014
  MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
1015
  MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
1016
  MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
1017

    
1018
  MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
1019
  MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
1020
  MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
1021
  MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
1022
  MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
1023
  MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
1024
  MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
1025
  MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
1026
  MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
1027
  MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
1028
  MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
1029
  MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
1030
  MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
1031
  MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
1032
  MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
1033
  MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
1034

    
1035
  MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
1036
  MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
1037
  MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
1038
  MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
1039
  MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
1040
  MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
1041
  MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
1042
  MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
1043
  MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
1044
  MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
1045
  MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
1046
  MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
1047
  MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
1048
  MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
1049
  MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
1050
  MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
1051

    
1052
  MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
1053
  MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
1054
  MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
1055
  MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
1056
  MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
1057
  MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
1058
  MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
1059
  MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
1060
  MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
1061
  MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
1062
  MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
1063
  MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
1064
  MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
1065
  MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
1066
  MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
1067
  MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
1068

    
1069
  buf[0] += a;
1070
  buf[1] += b;
1071
  buf[2] += c;
1072
  buf[3] += d;
1073
}
1074

    
1075
void cs_md5_update(cs_md5_ctx *ctx, const unsigned char *buf, size_t len) {
1076
  uint32_t t;
1077

    
1078
  t = ctx->bits[0];
1079
  if ((ctx->bits[0] = t + ((uint32_t) len << 3)) < t) ctx->bits[1]++;
1080
  ctx->bits[1] += (uint32_t) len >> 29;
1081

    
1082
  t = (t >> 3) & 0x3f;
1083

    
1084
  if (t) {
1085
    unsigned char *p = (unsigned char *) ctx->in + t;
1086

    
1087
    t = 64 - t;
1088
    if (len < t) {
1089
      memcpy(p, buf, len);
1090
      return;
1091
    }
1092
    memcpy(p, buf, t);
1093
    byteReverse(ctx->in, 16);
1094
    cs_md5_transform(ctx->buf, (uint32_t *) ctx->in);
1095
    buf += t;
1096
    len -= t;
1097
  }
1098

    
1099
  while (len >= 64) {
1100
    memcpy(ctx->in, buf, 64);
1101
    byteReverse(ctx->in, 16);
1102
    cs_md5_transform(ctx->buf, (uint32_t *) ctx->in);
1103
    buf += 64;
1104
    len -= 64;
1105
  }
1106

    
1107
  memcpy(ctx->in, buf, len);
1108
}
1109

    
1110
void cs_md5_final(unsigned char digest[16], cs_md5_ctx *ctx) {
1111
  unsigned count;
1112
  unsigned char *p;
1113
  uint32_t *a;
1114

    
1115
  count = (ctx->bits[0] >> 3) & 0x3F;
1116

    
1117
  p = ctx->in + count;
1118
  *p++ = 0x80;
1119
  count = 64 - 1 - count;
1120
  if (count < 8) {
1121
    memset(p, 0, count);
1122
    byteReverse(ctx->in, 16);
1123
    cs_md5_transform(ctx->buf, (uint32_t *) ctx->in);
1124
    memset(ctx->in, 0, 56);
1125
  } else {
1126
    memset(p, 0, count - 8);
1127
  }
1128
  byteReverse(ctx->in, 14);
1129

    
1130
  a = (uint32_t *) ctx->in;
1131
  a[14] = ctx->bits[0];
1132
  a[15] = ctx->bits[1];
1133

    
1134
  cs_md5_transform(ctx->buf, (uint32_t *) ctx->in);
1135
  byteReverse((unsigned char *) ctx->buf, 4);
1136
  memcpy(digest, ctx->buf, 16);
1137
  memset((char *) ctx, 0, sizeof(*ctx));
1138
}
1139

    
1140
#endif /* CS_DISABLE_MD5 */
1141
#endif /* EXCLUDE_COMMON */
1142
#ifdef MG_MODULE_LINES
1143
#line 1 "common/cs_sha1.c"
1144
#endif
1145
/* Copyright(c) By Steve Reid <steve@edmweb.com> */
1146
/* 100% Public Domain */
1147

    
1148
/* Amalgamated: #include "common/cs_sha1.h" */
1149

    
1150
#if !CS_DISABLE_SHA1 && !defined(EXCLUDE_COMMON)
1151

    
1152
/* Amalgamated: #include "common/cs_endian.h" */
1153

    
1154
#define SHA1HANDSOFF
1155
#if defined(__sun)
1156
/* Amalgamated: #include "common/solarisfixes.h" */
1157
#endif
1158

    
1159
union char64long16 {
1160
  unsigned char c[64];
1161
  uint32_t l[16];
1162
};
1163

    
1164
#define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
1165

    
1166
static uint32_t blk0(union char64long16 *block, int i) {
1167
/* Forrest: SHA expect BIG_ENDIAN, swap if LITTLE_ENDIAN */
1168
#if BYTE_ORDER == LITTLE_ENDIAN
1169
  block->l[i] =
1170
      (rol(block->l[i], 24) & 0xFF00FF00) | (rol(block->l[i], 8) & 0x00FF00FF);
1171
#endif
1172
  return block->l[i];
1173
}
1174

    
1175
/* Avoid redefine warning (ARM /usr/include/sys/ucontext.h define R0~R4) */
1176
#undef blk
1177
#undef R0
1178
#undef R1
1179
#undef R2
1180
#undef R3
1181
#undef R4
1182

    
1183
#define blk(i)                                                               \
1184
  (block->l[i & 15] = rol(block->l[(i + 13) & 15] ^ block->l[(i + 8) & 15] ^ \
1185
                              block->l[(i + 2) & 15] ^ block->l[i & 15],     \
1186
                          1))
1187
#define R0(v, w, x, y, z, i)                                          \
1188
  z += ((w & (x ^ y)) ^ y) + blk0(block, i) + 0x5A827999 + rol(v, 5); \
1189
  w = rol(w, 30);
1190
#define R1(v, w, x, y, z, i)                                  \
1191
  z += ((w & (x ^ y)) ^ y) + blk(i) + 0x5A827999 + rol(v, 5); \
1192
  w = rol(w, 30);
1193
#define R2(v, w, x, y, z, i)                          \
1194
  z += (w ^ x ^ y) + blk(i) + 0x6ED9EBA1 + rol(v, 5); \
1195
  w = rol(w, 30);
1196
#define R3(v, w, x, y, z, i)                                        \
1197
  z += (((w | x) & y) | (w & x)) + blk(i) + 0x8F1BBCDC + rol(v, 5); \
1198
  w = rol(w, 30);
1199
#define R4(v, w, x, y, z, i)                          \
1200
  z += (w ^ x ^ y) + blk(i) + 0xCA62C1D6 + rol(v, 5); \
1201
  w = rol(w, 30);
1202

    
1203
void cs_sha1_transform(uint32_t state[5], const unsigned char buffer[64]) {
1204
  uint32_t a, b, c, d, e;
1205
  union char64long16 block[1];
1206

    
1207
  memcpy(block, buffer, 64);
1208
  a = state[0];
1209
  b = state[1];
1210
  c = state[2];
1211
  d = state[3];
1212
  e = state[4];
1213
  R0(a, b, c, d, e, 0);
1214
  R0(e, a, b, c, d, 1);
1215
  R0(d, e, a, b, c, 2);
1216
  R0(c, d, e, a, b, 3);
1217
  R0(b, c, d, e, a, 4);
1218
  R0(a, b, c, d, e, 5);
1219
  R0(e, a, b, c, d, 6);
1220
  R0(d, e, a, b, c, 7);
1221
  R0(c, d, e, a, b, 8);
1222
  R0(b, c, d, e, a, 9);
1223
  R0(a, b, c, d, e, 10);
1224
  R0(e, a, b, c, d, 11);
1225
  R0(d, e, a, b, c, 12);
1226
  R0(c, d, e, a, b, 13);
1227
  R0(b, c, d, e, a, 14);
1228
  R0(a, b, c, d, e, 15);
1229
  R1(e, a, b, c, d, 16);
1230
  R1(d, e, a, b, c, 17);
1231
  R1(c, d, e, a, b, 18);
1232
  R1(b, c, d, e, a, 19);
1233
  R2(a, b, c, d, e, 20);
1234
  R2(e, a, b, c, d, 21);
1235
  R2(d, e, a, b, c, 22);
1236
  R2(c, d, e, a, b, 23);
1237
  R2(b, c, d, e, a, 24);
1238
  R2(a, b, c, d, e, 25);
1239
  R2(e, a, b, c, d, 26);
1240
  R2(d, e, a, b, c, 27);
1241
  R2(c, d, e, a, b, 28);
1242
  R2(b, c, d, e, a, 29);
1243
  R2(a, b, c, d, e, 30);
1244
  R2(e, a, b, c, d, 31);
1245
  R2(d, e, a, b, c, 32);
1246
  R2(c, d, e, a, b, 33);
1247
  R2(b, c, d, e, a, 34);
1248
  R2(a, b, c, d, e, 35);
1249
  R2(e, a, b, c, d, 36);
1250
  R2(d, e, a, b, c, 37);
1251
  R2(c, d, e, a, b, 38);
1252
  R2(b, c, d, e, a, 39);
1253
  R3(a, b, c, d, e, 40);
1254
  R3(e, a, b, c, d, 41);
1255
  R3(d, e, a, b, c, 42);
1256
  R3(c, d, e, a, b, 43);
1257
  R3(b, c, d, e, a, 44);
1258
  R3(a, b, c, d, e, 45);
1259
  R3(e, a, b, c, d, 46);
1260
  R3(d, e, a, b, c, 47);
1261
  R3(c, d, e, a, b, 48);
1262
  R3(b, c, d, e, a, 49);
1263
  R3(a, b, c, d, e, 50);
1264
  R3(e, a, b, c, d, 51);
1265
  R3(d, e, a, b, c, 52);
1266
  R3(c, d, e, a, b, 53);
1267
  R3(b, c, d, e, a, 54);
1268
  R3(a, b, c, d, e, 55);
1269
  R3(e, a, b, c, d, 56);
1270
  R3(d, e, a, b, c, 57);
1271
  R3(c, d, e, a, b, 58);
1272
  R3(b, c, d, e, a, 59);
1273
  R4(a, b, c, d, e, 60);
1274
  R4(e, a, b, c, d, 61);
1275
  R4(d, e, a, b, c, 62);
1276
  R4(c, d, e, a, b, 63);
1277
  R4(b, c, d, e, a, 64);
1278
  R4(a, b, c, d, e, 65);
1279
  R4(e, a, b, c, d, 66);
1280
  R4(d, e, a, b, c, 67);
1281
  R4(c, d, e, a, b, 68);
1282
  R4(b, c, d, e, a, 69);
1283
  R4(a, b, c, d, e, 70);
1284
  R4(e, a, b, c, d, 71);
1285
  R4(d, e, a, b, c, 72);
1286
  R4(c, d, e, a, b, 73);
1287
  R4(b, c, d, e, a, 74);
1288
  R4(a, b, c, d, e, 75);
1289
  R4(e, a, b, c, d, 76);
1290
  R4(d, e, a, b, c, 77);
1291
  R4(c, d, e, a, b, 78);
1292
  R4(b, c, d, e, a, 79);
1293
  state[0] += a;
1294
  state[1] += b;
1295
  state[2] += c;
1296
  state[3] += d;
1297
  state[4] += e;
1298
  /* Erase working structures. The order of operations is important,
1299
   * used to ensure that compiler doesn't optimize those out. */
1300
  memset(block, 0, sizeof(block));
1301
  a = b = c = d = e = 0;
1302
  (void) a;
1303
  (void) b;
1304
  (void) c;
1305
  (void) d;
1306
  (void) e;
1307
}
1308

    
1309
void cs_sha1_init(cs_sha1_ctx *context) {
1310
  context->state[0] = 0x67452301;
1311
  context->state[1] = 0xEFCDAB89;
1312
  context->state[2] = 0x98BADCFE;
1313
  context->state[3] = 0x10325476;
1314
  context->state[4] = 0xC3D2E1F0;
1315
  context->count[0] = context->count[1] = 0;
1316
}
1317

    
1318
void cs_sha1_update(cs_sha1_ctx *context, const unsigned char *data,
1319
                    uint32_t len) {
1320
  uint32_t i, j;
1321

    
1322
  j = context->count[0];
1323
  if ((context->count[0] += len << 3) < j) context->count[1]++;
1324
  context->count[1] += (len >> 29);
1325
  j = (j >> 3) & 63;
1326
  if ((j + len) > 63) {
1327
    memcpy(&context->buffer[j], data, (i = 64 - j));
1328
    cs_sha1_transform(context->state, context->buffer);
1329
    for (; i + 63 < len; i += 64) {
1330
      cs_sha1_transform(context->state, &data[i]);
1331
    }
1332
    j = 0;
1333
  } else
1334
    i = 0;
1335
  memcpy(&context->buffer[j], &data[i], len - i);
1336
}
1337

    
1338
void cs_sha1_final(unsigned char digest[20], cs_sha1_ctx *context) {
1339
  unsigned i;
1340
  unsigned char finalcount[8], c;
1341

    
1342
  for (i = 0; i < 8; i++) {
1343
    finalcount[i] = (unsigned char) ((context->count[(i >= 4 ? 0 : 1)] >>
1344
                                      ((3 - (i & 3)) * 8)) &
1345
                                     255);
1346
  }
1347
  c = 0200;
1348
  cs_sha1_update(context, &c, 1);
1349
  while ((context->count[0] & 504) != 448) {
1350
    c = 0000;
1351
    cs_sha1_update(context, &c, 1);
1352
  }
1353
  cs_sha1_update(context, finalcount, 8);
1354
  for (i = 0; i < 20; i++) {
1355
    digest[i] =
1356
        (unsigned char) ((context->state[i >> 2] >> ((3 - (i & 3)) * 8)) & 255);
1357
  }
1358
  memset(context, '\0', sizeof(*context));
1359
  memset(&finalcount, '\0', sizeof(finalcount));
1360
}
1361

    
1362
void cs_hmac_sha1(const unsigned char *key, size_t keylen,
1363
                  const unsigned char *data, size_t datalen,
1364
                  unsigned char out[20]) {
1365
  cs_sha1_ctx ctx;
1366
  unsigned char buf1[64], buf2[64], tmp_key[20], i;
1367

    
1368
  if (keylen > sizeof(buf1)) {
1369
    cs_sha1_init(&ctx);
1370
    cs_sha1_update(&ctx, key, keylen);
1371
    cs_sha1_final(tmp_key, &ctx);
1372
    key = tmp_key;
1373
    keylen = sizeof(tmp_key);
1374
  }
1375

    
1376
  memset(buf1, 0, sizeof(buf1));
1377
  memset(buf2, 0, sizeof(buf2));
1378
  memcpy(buf1, key, keylen);
1379
  memcpy(buf2, key, keylen);
1380

    
1381
  for (i = 0; i < sizeof(buf1); i++) {
1382
    buf1[i] ^= 0x36;
1383
    buf2[i] ^= 0x5c;
1384
  }
1385

    
1386
  cs_sha1_init(&ctx);
1387
  cs_sha1_update(&ctx, buf1, sizeof(buf1));
1388
  cs_sha1_update(&ctx, data, datalen);
1389
  cs_sha1_final(out, &ctx);
1390

    
1391
  cs_sha1_init(&ctx);
1392
  cs_sha1_update(&ctx, buf2, sizeof(buf2));
1393
  cs_sha1_update(&ctx, out, 20);
1394
  cs_sha1_final(out, &ctx);
1395
}
1396

    
1397
#endif /* EXCLUDE_COMMON */
1398
#ifdef MG_MODULE_LINES
1399
#line 1 "common/mbuf.c"
1400
#endif
1401
/*
1402
 * Copyright (c) 2014 Cesanta Software Limited
1403
 * All rights reserved
1404
 */
1405

    
1406
#ifndef EXCLUDE_COMMON
1407

    
1408
#include <assert.h>
1409
#include <string.h>
1410
/* Amalgamated: #include "common/mbuf.h" */
1411

    
1412
#ifndef MBUF_REALLOC
1413
#define MBUF_REALLOC realloc
1414
#endif
1415

    
1416
#ifndef MBUF_FREE
1417
#define MBUF_FREE free
1418
#endif
1419

    
1420
void mbuf_init(struct mbuf *mbuf, size_t initial_size) WEAK;
1421
void mbuf_init(struct mbuf *mbuf, size_t initial_size) {
1422
  mbuf->len = mbuf->size = 0;
1423
  mbuf->buf = NULL;
1424
  mbuf_resize(mbuf, initial_size);
1425
}
1426

    
1427
void mbuf_free(struct mbuf *mbuf) WEAK;
1428
void mbuf_free(struct mbuf *mbuf) {
1429
  if (mbuf->buf != NULL) {
1430
    MBUF_FREE(mbuf->buf);
1431
    mbuf_init(mbuf, 0);
1432
  }
1433
}
1434

    
1435
void mbuf_resize(struct mbuf *a, size_t new_size) WEAK;
1436
void mbuf_resize(struct mbuf *a, size_t new_size) {
1437
  if (new_size > a->size || (new_size < a->size && new_size >= a->len)) {
1438
    char *buf = (char *) MBUF_REALLOC(a->buf, new_size);
1439
    /*
1440
     * In case realloc fails, there's not much we can do, except keep things as
1441
     * they are. Note that NULL is a valid return value from realloc when
1442
     * size == 0, but that is covered too.
1443
     */
1444
    if (buf == NULL && new_size != 0) return;
1445
    a->buf = buf;
1446
    a->size = new_size;
1447
  }
1448
}
1449

    
1450
void mbuf_trim(struct mbuf *mbuf) WEAK;
1451
void mbuf_trim(struct mbuf *mbuf) {
1452
  mbuf_resize(mbuf, mbuf->len);
1453
}
1454

    
1455
size_t mbuf_insert(struct mbuf *a, size_t off, const void *buf, size_t) WEAK;
1456
size_t mbuf_insert(struct mbuf *a, size_t off, const void *buf, size_t len) {
1457
  char *p = NULL;
1458

    
1459
  assert(a != NULL);
1460
  assert(a->len <= a->size);
1461
  assert(off <= a->len);
1462

    
1463
  /* check overflow */
1464
  if (~(size_t) 0 - (size_t) a->buf < len) return 0;
1465

    
1466
  if (a->len + len <= a->size) {
1467
    memmove(a->buf + off + len, a->buf + off, a->len - off);
1468
    if (buf != NULL) {
1469
      memcpy(a->buf + off, buf, len);
1470
    }
1471
    a->len += len;
1472
  } else {
1473
    size_t new_size = (size_t)((a->len + len) * MBUF_SIZE_MULTIPLIER);
1474
    if ((p = (char *) MBUF_REALLOC(a->buf, new_size)) != NULL) {
1475
      a->buf = p;
1476
      memmove(a->buf + off + len, a->buf + off, a->len - off);
1477
      if (buf != NULL) memcpy(a->buf + off, buf, len);
1478
      a->len += len;
1479
      a->size = new_size;
1480
    } else {
1481
      len = 0;
1482
    }
1483
  }
1484

    
1485
  return len;
1486
}
1487

    
1488
size_t mbuf_append(struct mbuf *a, const void *buf, size_t len) WEAK;
1489
size_t mbuf_append(struct mbuf *a, const void *buf, size_t len) {
1490
  return mbuf_insert(a, a->len, buf, len);
1491
}
1492

    
1493
void mbuf_remove(struct mbuf *mb, size_t n) WEAK;
1494
void mbuf_remove(struct mbuf *mb, size_t n) {
1495
  if (n > 0 && n <= mb->len) {
1496
    memmove(mb->buf, mb->buf + n, mb->len - n);
1497
    mb->len -= n;
1498
  }
1499
}
1500

    
1501
#endif /* EXCLUDE_COMMON */
1502
#ifdef MG_MODULE_LINES
1503
#line 1 "common/mg_str.c"
1504
#endif
1505
/*
1506
 * Copyright (c) 2014-2016 Cesanta Software Limited
1507
 * All rights reserved
1508
 */
1509

    
1510
/* Amalgamated: #include "common/mg_mem.h" */
1511
/* Amalgamated: #include "common/mg_str.h" */
1512

    
1513
#include <stdlib.h>
1514
#include <string.h>
1515

    
1516
int mg_ncasecmp(const char *s1, const char *s2, size_t len) WEAK;
1517

    
1518
struct mg_str mg_mk_str(const char *s) WEAK;
1519
struct mg_str mg_mk_str(const char *s) {
1520
  struct mg_str ret = {s, 0};
1521
  if (s != NULL) ret.len = strlen(s);
1522
  return ret;
1523
}
1524

    
1525
struct mg_str mg_mk_str_n(const char *s, size_t len) WEAK;
1526
struct mg_str mg_mk_str_n(const char *s, size_t len) {
1527
  struct mg_str ret = {s, len};
1528
  return ret;
1529
}
1530

    
1531
int mg_vcmp(const struct mg_str *str1, const char *str2) WEAK;
1532
int mg_vcmp(const struct mg_str *str1, const char *str2) {
1533
  size_t n2 = strlen(str2), n1 = str1->len;
1534
  int r = strncmp(str1->p, str2, (n1 < n2) ? n1 : n2);
1535
  if (r == 0) {
1536
    return n1 - n2;
1537
  }
1538
  return r;
1539
}
1540

    
1541
int mg_vcasecmp(const struct mg_str *str1, const char *str2) WEAK;
1542
int mg_vcasecmp(const struct mg_str *str1, const char *str2) {
1543
  size_t n2 = strlen(str2), n1 = str1->len;
1544
  int r = mg_ncasecmp(str1->p, str2, (n1 < n2) ? n1 : n2);
1545
  if (r == 0) {
1546
    return n1 - n2;
1547
  }
1548
  return r;
1549
}
1550

    
1551
static struct mg_str mg_strdup_common(const struct mg_str s,
1552
                                      int nul_terminate) {
1553
  struct mg_str r = {NULL, 0};
1554
  if (s.len > 0 && s.p != NULL) {
1555
    char *sc = (char *) MG_MALLOC(s.len + (nul_terminate ? 1 : 0));
1556
    if (sc != NULL) {
1557
      memcpy(sc, s.p, s.len);
1558
      if (nul_terminate) sc[s.len] = '\0';
1559
      r.p = sc;
1560
      r.len = s.len;
1561
    }
1562
  }
1563
  return r;
1564
}
1565

    
1566
struct mg_str mg_strdup(const struct mg_str s) WEAK;
1567
struct mg_str mg_strdup(const struct mg_str s) {
1568
  return mg_strdup_common(s, 0 /* NUL-terminate */);
1569
}
1570

    
1571
struct mg_str mg_strdup_nul(const struct mg_str s) WEAK;
1572
struct mg_str mg_strdup_nul(const struct mg_str s) {
1573
  return mg_strdup_common(s, 1 /* NUL-terminate */);
1574
}
1575

    
1576
const char *mg_strchr(const struct mg_str s, int c) WEAK;
1577
const char *mg_strchr(const struct mg_str s, int c) {
1578
  size_t i;
1579
  for (i = 0; i < s.len; i++) {
1580
    if (s.p[i] == c) return &s.p[i];
1581
  }
1582
  return NULL;
1583
}
1584

    
1585
int mg_strcmp(const struct mg_str str1, const struct mg_str str2) WEAK;
1586
int mg_strcmp(const struct mg_str str1, const struct mg_str str2) {
1587
  size_t i = 0;
1588
  while (i < str1.len && i < str2.len) {
1589
    if (str1.p[i] < str2.p[i]) return -1;
1590
    if (str1.p[i] > str2.p[i]) return 1;
1591
    i++;
1592
  }
1593
  if (i < str1.len) return 1;
1594
  if (i < str2.len) return -1;
1595
  return 0;
1596
}
1597

    
1598
int mg_strncmp(const struct mg_str, const struct mg_str, size_t n) WEAK;
1599
int mg_strncmp(const struct mg_str str1, const struct mg_str str2, size_t n) {
1600
  struct mg_str s1 = str1;
1601
  struct mg_str s2 = str2;
1602

    
1603
  if (s1.len > n) {
1604
    s1.len = n;
1605
  }
1606
  if (s2.len > n) {
1607
    s2.len = n;
1608
  }
1609
  return mg_strcmp(s1, s2);
1610
}
1611

    
1612
const char *mg_strstr(const struct mg_str haystack,
1613
                      const struct mg_str needle) WEAK;
1614
const char *mg_strstr(const struct mg_str haystack,
1615
                      const struct mg_str needle) {
1616
  size_t i;
1617
  if (needle.len > haystack.len) return NULL;
1618
  for (i = 0; i <= haystack.len - needle.len; i++) {
1619
    if (memcmp(haystack.p + i, needle.p, needle.len) == 0) {
1620
      return haystack.p + i;
1621
    }
1622
  }
1623
  return NULL;
1624
}
1625
#ifdef MG_MODULE_LINES
1626
#line 1 "common/str_util.c"
1627
#endif
1628
/*
1629
 * Copyright (c) 2015 Cesanta Software Limited
1630
 * All rights reserved
1631
 */
1632

    
1633
#ifndef EXCLUDE_COMMON
1634

    
1635
/* Amalgamated: #include "common/str_util.h" */
1636
/* Amalgamated: #include "common/mg_mem.h" */
1637
/* Amalgamated: #include "common/platform.h" */
1638

    
1639
#ifndef C_DISABLE_BUILTIN_SNPRINTF
1640
#define C_DISABLE_BUILTIN_SNPRINTF 0
1641
#endif
1642

    
1643
/* Amalgamated: #include "common/mg_mem.h" */
1644

    
1645
size_t c_strnlen(const char *s, size_t maxlen) WEAK;
1646
size_t c_strnlen(const char *s, size_t maxlen) {
1647
  size_t l = 0;
1648
  for (; l < maxlen && s[l] != '\0'; l++) {
1649
  }
1650
  return l;
1651
}
1652

    
1653
#define C_SNPRINTF_APPEND_CHAR(ch)       \
1654
  do {                                   \
1655
    if (i < (int) buf_size) buf[i] = ch; \
1656
    i++;                                 \
1657
  } while (0)
1658

    
1659
#define C_SNPRINTF_FLAG_ZERO 1
1660

    
1661
#if C_DISABLE_BUILTIN_SNPRINTF
1662
int c_vsnprintf(char *buf, size_t buf_size, const char *fmt, va_list ap) WEAK;
1663
int c_vsnprintf(char *buf, size_t buf_size, const char *fmt, va_list ap) {
1664
  return vsnprintf(buf, buf_size, fmt, ap);
1665
}
1666
#else
1667
static int c_itoa(char *buf, size_t buf_size, int64_t num, int base, int flags,
1668
                  int field_width) {
1669
  char tmp[40];
1670
  int i = 0, k = 0, neg = 0;
1671

    
1672
  if (num < 0) {
1673
    neg++;
1674
    num = -num;
1675
  }
1676

    
1677
  /* Print into temporary buffer - in reverse order */
1678
  do {
1679
    int rem = num % base;
1680
    if (rem < 10) {
1681
      tmp[k++] = '0' + rem;
1682
    } else {
1683
      tmp[k++] = 'a' + (rem - 10);
1684
    }
1685
    num /= base;
1686
  } while (num > 0);
1687

    
1688
  /* Zero padding */
1689
  if (flags && C_SNPRINTF_FLAG_ZERO) {
1690
    while (k < field_width && k < (int) sizeof(tmp) - 1) {
1691
      tmp[k++] = '0';
1692
    }
1693
  }
1694

    
1695
  /* And sign */
1696
  if (neg) {
1697
    tmp[k++] = '-';
1698
  }
1699

    
1700
  /* Now output */
1701
  while (--k >= 0) {
1702
    C_SNPRINTF_APPEND_CHAR(tmp[k]);
1703
  }
1704

    
1705
  return i;
1706
}
1707

    
1708
int c_vsnprintf(char *buf, size_t buf_size, const char *fmt, va_list ap) WEAK;
1709
int c_vsnprintf(char *buf, size_t buf_size, const char *fmt, va_list ap) {
1710
  int ch, i = 0, len_mod, flags, precision, field_width;
1711

    
1712
  while ((ch = *fmt++) != '\0') {
1713
    if (ch != '%') {
1714
      C_SNPRINTF_APPEND_CHAR(ch);
1715
    } else {
1716
      /*
1717
       * Conversion specification:
1718
       *   zero or more flags (one of: # 0 - <space> + ')
1719
       *   an optional minimum  field  width (digits)
1720
       *   an  optional precision (. followed by digits, or *)
1721
       *   an optional length modifier (one of: hh h l ll L q j z t)
1722
       *   conversion specifier (one of: d i o u x X e E f F g G a A c s p n)
1723
       */
1724
      flags = field_width = precision = len_mod = 0;
1725

    
1726
      /* Flags. only zero-pad flag is supported. */
1727
      if (*fmt == '0') {
1728
        flags |= C_SNPRINTF_FLAG_ZERO;
1729
      }
1730

    
1731
      /* Field width */
1732
      while (*fmt >= '0' && *fmt <= '9') {
1733
        field_width *= 10;
1734
        field_width += *fmt++ - '0';
1735
      }
1736
      /* Dynamic field width */
1737
      if (*fmt == '*') {
1738
        field_width = va_arg(ap, int);
1739
        fmt++;
1740
      }
1741

    
1742
      /* Precision */
1743
      if (*fmt == '.') {
1744
        fmt++;
1745
        if (*fmt == '*') {
1746
          precision = va_arg(ap, int);
1747
          fmt++;
1748
        } else {
1749
          while (*fmt >= '0' && *fmt <= '9') {
1750
            precision *= 10;
1751
            precision += *fmt++ - '0';
1752
          }
1753
        }
1754
      }
1755

    
1756
      /* Length modifier */
1757
      switch (*fmt) {
1758
        case 'h':
1759
        case 'l':
1760
        case 'L':
1761
        case 'I':
1762
        case 'q':
1763
        case 'j':
1764
        case 'z':
1765
        case 't':
1766
          len_mod = *fmt++;
1767
          if (*fmt == 'h') {
1768
            len_mod = 'H';
1769
            fmt++;
1770
          }
1771
          if (*fmt == 'l') {
1772
            len_mod = 'q';
1773
            fmt++;
1774
          }
1775
          break;
1776
      }
1777

    
1778
      ch = *fmt++;
1779
      if (ch == 's') {
1780
        const char *s = va_arg(ap, const char *); /* Always fetch parameter */
1781
        int j;
1782
        int pad = field_width - (precision >= 0 ? c_strnlen(s, precision) : 0);
1783
        for (j = 0; j < pad; j++) {
1784
          C_SNPRINTF_APPEND_CHAR(' ');
1785
        }
1786

    
1787
        /* `s` may be NULL in case of %.*s */
1788
        if (s != NULL) {
1789
          /* Ignore negative and 0 precisions */
1790
          for (j = 0; (precision <= 0 || j < precision) && s[j] != '\0'; j++) {
1791
            C_SNPRINTF_APPEND_CHAR(s[j]);
1792
          }
1793
        }
1794
      } else if (ch == 'c') {
1795
        ch = va_arg(ap, int); /* Always fetch parameter */
1796
        C_SNPRINTF_APPEND_CHAR(ch);
1797
      } else if (ch == 'd' && len_mod == 0) {
1798
        i += c_itoa(buf + i, buf_size - i, va_arg(ap, int), 10, flags,
1799
                    field_width);
1800
      } else if (ch == 'd' && len_mod == 'l') {
1801
        i += c_itoa(buf + i, buf_size - i, va_arg(ap, long), 10, flags,
1802
                    field_width);
1803
#ifdef SSIZE_MAX
1804
      } else if (ch == 'd' && len_mod == 'z') {
1805
        i += c_itoa(buf + i, buf_size - i, va_arg(ap, ssize_t), 10, flags,
1806
                    field_width);
1807
#endif
1808
      } else if (ch == 'd' && len_mod == 'q') {
1809
        i += c_itoa(buf + i, buf_size - i, va_arg(ap, int64_t), 10, flags,
1810
                    field_width);
1811
      } else if ((ch == 'x' || ch == 'u') && len_mod == 0) {
1812
        i += c_itoa(buf + i, buf_size - i, va_arg(ap, unsigned),
1813
                    ch == 'x' ? 16 : 10, flags, field_width);
1814
      } else if ((ch == 'x' || ch == 'u') && len_mod == 'l') {
1815
        i += c_itoa(buf + i, buf_size - i, va_arg(ap, unsigned long),
1816
                    ch == 'x' ? 16 : 10, flags, field_width);
1817
      } else if ((ch == 'x' || ch == 'u') && len_mod == 'z') {
1818
        i += c_itoa(buf + i, buf_size - i, va_arg(ap, size_t),
1819
                    ch == 'x' ? 16 : 10, flags, field_width);
1820
      } else if (ch == 'p') {
1821
        unsigned long num = (unsigned long) (uintptr_t) va_arg(ap, void *);
1822
        C_SNPRINTF_APPEND_CHAR('0');
1823
        C_SNPRINTF_APPEND_CHAR('x');
1824
        i += c_itoa(buf + i, buf_size - i, num, 16, flags, 0);
1825
      } else {
1826
#ifndef NO_LIBC
1827
        /*
1828
         * TODO(lsm): abort is not nice in a library, remove it
1829
         * Also, ESP8266 SDK doesn't have it
1830
         */
1831
        abort();
1832
#endif
1833
      }
1834
    }
1835
  }
1836

    
1837
  /* Zero-terminate the result */
1838
  if (buf_size > 0) {
1839
    buf[i < (int) buf_size ? i : (int) buf_size - 1] = '\0';
1840
  }
1841

    
1842
  return i;
1843
}
1844
#endif
1845

    
1846
int c_snprintf(char *buf, size_t buf_size, const char *fmt, ...) WEAK;
1847
int c_snprintf(char *buf, size_t buf_size, const char *fmt, ...) {
1848
  int result;
1849
  va_list ap;
1850
  va_start(ap, fmt);
1851
  result = c_vsnprintf(buf, buf_size, fmt, ap);
1852
  va_end(ap);
1853
  return result;
1854
}
1855

    
1856
#ifdef _WIN32
1857
int to_wchar(const char *path, wchar_t *wbuf, size_t wbuf_len) {
1858
  int ret;
1859
  char buf[MAX_PATH * 2], buf2[MAX_PATH * 2], *p;
1860

    
1861
  strncpy(buf, path, sizeof(buf));
1862
  buf[sizeof(buf) - 1] = '\0';
1863

    
1864
  /* Trim trailing slashes. Leave backslash for paths like "X:\" */
1865
  p = buf + strlen(buf) - 1;
1866
  while (p > buf && p[-1] != ':' && (p[0] == '\\' || p[0] == '/')) *p-- = '\0';
1867

    
1868
  memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
1869
  ret = MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int) wbuf_len);
1870

    
1871
  /*
1872
   * Convert back to Unicode. If doubly-converted string does not match the
1873
   * original, something is fishy, reject.
1874
   */
1875
  WideCharToMultiByte(CP_UTF8, 0, wbuf, (int) wbuf_len, buf2, sizeof(buf2),
1876
                      NULL, NULL);
1877
  if (strcmp(buf, buf2) != 0) {
1878
    wbuf[0] = L'\0';
1879
    ret = 0;
1880
  }
1881

    
1882
  return ret;
1883
}
1884
#endif /* _WIN32 */
1885

    
1886
/* The simplest O(mn) algorithm. Better implementation are GPLed */
1887
const char *c_strnstr(const char *s, const char *find, size_t slen) WEAK;
1888
const char *c_strnstr(const char *s, const char *find, size_t slen) {
1889
  size_t find_length = strlen(find);
1890
  size_t i;
1891

    
1892
  for (i = 0; i < slen; i++) {
1893
    if (i + find_length > slen) {
1894
      return NULL;
1895
    }
1896

    
1897
    if (strncmp(&s[i], find, find_length) == 0) {
1898
      return &s[i];
1899
    }
1900
  }
1901

    
1902
  return NULL;
1903
}
1904

    
1905
#if CS_ENABLE_STRDUP
1906
char *strdup(const char *src) WEAK;
1907
char *strdup(const char *src) {
1908
  size_t len = strlen(src) + 1;
1909
  char *ret = MG_MALLOC(len);
1910
  if (ret != NULL) {
1911
    strcpy(ret, src);
1912
  }
1913
  return ret;
1914
}
1915
#endif
1916

    
1917
void cs_to_hex(char *to, const unsigned char *p, size_t len) WEAK;
1918
void cs_to_hex(char *to, const unsigned char *p, size_t len) {
1919
  static const char *hex = "0123456789abcdef";
1920

    
1921
  for (; len--; p++) {
1922
    *to++ = hex[p[0] >> 4];
1923
    *to++ = hex[p[0] & 0x0f];
1924
  }
1925
  *to = '\0';
1926
}
1927

    
1928
static int fourbit(int ch) {
1929
  if (ch >= '0' && ch <= '9') {
1930
    return ch - '0';
1931
  } else if (ch >= 'a' && ch <= 'f') {
1932
    return ch - 'a' + 10;
1933
  } else if (ch >= 'A' && ch <= 'F') {
1934
    return ch - 'A' + 10;
1935
  }
1936
  return 0;
1937
}
1938

    
1939
void cs_from_hex(char *to, const char *p, size_t len) WEAK;
1940
void cs_from_hex(char *to, const char *p, size_t len) {
1941
  size_t i;
1942

    
1943
  for (i = 0; i < len; i += 2) {
1944
    *to++ = (fourbit(p[i]) << 4) + fourbit(p[i + 1]);
1945
  }
1946
  *to = '\0';
1947
}
1948

    
1949
#if CS_ENABLE_TO64
1950
int64_t cs_to64(const char *s) WEAK;
1951
int64_t cs_to64(const char *s) {
1952
  int64_t result = 0;
1953
  int64_t neg = 1;
1954
  while (*s && isspace((unsigned char) *s)) s++;
1955
  if (*s == '-') {
1956
    neg = -1;
1957
    s++;
1958
  }
1959
  while (isdigit((unsigned char) *s)) {
1960
    result *= 10;
1961
    result += (*s - '0');
1962
    s++;
1963
  }
1964
  return result * neg;
1965
}
1966
#endif
1967

    
1968
static int str_util_lowercase(const char *s) {
1969
  return tolower(*(const unsigned char *) s);
1970
}
1971

    
1972
int mg_ncasecmp(const char *s1, const char *s2, size_t len) WEAK;
1973
int mg_ncasecmp(const char *s1, const char *s2, size_t len) {
1974
  int diff = 0;
1975

    
1976
  if (len > 0) do {
1977
      diff = str_util_lowercase(s1++) - str_util_lowercase(s2++);
1978
    } while (diff == 0 && s1[-1] != '\0' && --len > 0);
1979

    
1980
  return diff;
1981
}
1982

    
1983
int mg_casecmp(const char *s1, const char *s2) WEAK;
1984
int mg_casecmp(const char *s1, const char *s2) {
1985
  return mg_ncasecmp(s1, s2, (size_t) ~0);
1986
}
1987

    
1988
int mg_asprintf(char **buf, size_t size, const char *fmt, ...) WEAK;
1989
int mg_asprintf(char **buf, size_t size, const char *fmt, ...) {
1990
  int ret;
1991
  va_list ap;
1992
  va_start(ap, fmt);
1993
  ret = mg_avprintf(buf, size, fmt, ap);
1994
  va_end(ap);
1995
  return ret;
1996
}
1997

    
1998
int mg_avprintf(char **buf, size_t size, const char *fmt, va_list ap) WEAK;
1999
int mg_avprintf(char **buf, size_t size, const char *fmt, va_list ap) {
2000
  va_list ap_copy;
2001
  int len;
2002

    
2003
  va_copy(ap_copy, ap);
2004
  len = vsnprintf(*buf, size, fmt, ap_copy);
2005
  va_end(ap_copy);
2006

    
2007
  if (len < 0) {
2008
    /* eCos and Windows are not standard-compliant and return -1 when
2009
     * the buffer is too small. Keep allocating larger buffers until we
2010
     * succeed or out of memory. */
2011
    *buf = NULL; /* LCOV_EXCL_START */
2012
    while (len < 0) {
2013
      MG_FREE(*buf);
2014
      if (size == 0) {
2015
        size = 5;
2016
      }
2017
      size *= 2;
2018
      if ((*buf = (char *) MG_MALLOC(size)) == NULL) {
2019
        len = -1;
2020
        break;
2021
      }
2022
      va_copy(ap_copy, ap);
2023
      len = vsnprintf(*buf, size - 1, fmt, ap_copy);
2024
      va_end(ap_copy);
2025
    }
2026

    
2027
    /*
2028
     * Microsoft version of vsnprintf() is not always null-terminated, so put
2029
     * the terminator manually
2030
     */
2031
    (*buf)[len] = 0;
2032
    /* LCOV_EXCL_STOP */
2033
  } else if (len >= (int) size) {
2034
    /* Standard-compliant code path. Allocate a buffer that is large enough. */
2035
    if ((*buf = (char *) MG_MALLOC(len + 1)) == NULL) {
2036
      len = -1; /* LCOV_EXCL_LINE */
2037
    } else {    /* LCOV_EXCL_LINE */
2038
      va_copy(ap_copy, ap);
2039
      len = vsnprintf(*buf, len + 1, fmt, ap_copy);
2040
      va_end(ap_copy);
2041
    }
2042
  }
2043

    
2044
  return len;
2045
}
2046

    
2047
const char *mg_next_comma_list_entry(const char *, struct mg_str *,
2048
                                     struct mg_str *) WEAK;
2049
const char *mg_next_comma_list_entry(const char *list, struct mg_str *val,
2050
                                     struct mg_str *eq_val) {
2051
  struct mg_str ret = mg_next_comma_list_entry_n(mg_mk_str(list), val, eq_val);
2052
  return ret.p;
2053
}
2054

    
2055
struct mg_str mg_next_comma_list_entry_n(struct mg_str list, struct mg_str *val,
2056
                                         struct mg_str *eq_val) WEAK;
2057
struct mg_str mg_next_comma_list_entry_n(struct mg_str list, struct mg_str *val,
2058
                                         struct mg_str *eq_val) {
2059
  if (list.len == 0) {
2060
    /* End of the list */
2061
    list = mg_mk_str(NULL);
2062
  } else {
2063
    const char *chr = NULL;
2064
    *val = list;
2065

    
2066
    if ((chr = mg_strchr(*val, ',')) != NULL) {
2067
      /* Comma found. Store length and shift the list ptr */
2068
      val->len = chr - val->p;
2069
      chr++;
2070
      list.len -= (chr - list.p);
2071
      list.p = chr;
2072
    } else {
2073
      /* This value is the last one */
2074
      list = mg_mk_str_n(list.p + list.len, 0);
2075
    }
2076

    
2077
    if (eq_val != NULL) {
2078
      /* Value has form "x=y", adjust pointers and lengths */
2079
      /* so that val points to "x", and eq_val points to "y". */
2080
      eq_val->len = 0;
2081
      eq_val->p = (const char *) memchr(val->p, '=', val->len);
2082
      if (eq_val->p != NULL) {
2083
        eq_val->p++; /* Skip over '=' character */
2084
        eq_val->len = val->p + val->len - eq_val->p;
2085
        val->len = (eq_val->p - val->p) - 1;
2086
      }
2087
    }
2088
  }
2089

    
2090
  return list;
2091
}
2092

    
2093
size_t mg_match_prefix_n(const struct mg_str, const struct mg_str) WEAK;
2094
size_t mg_match_prefix_n(const struct mg_str pattern, const struct mg_str str) {
2095
  const char *or_str;
2096
  size_t res = 0, len = 0, i = 0, j = 0;
2097

    
2098
  if ((or_str = (const char *) memchr(pattern.p, '|', pattern.len)) != NULL ||
2099
      (or_str = (const char *) memchr(pattern.p, ',', pattern.len)) != NULL) {
2100
    struct mg_str pstr = {pattern.p, (size_t)(or_str - pattern.p)};
2101
    res = mg_match_prefix_n(pstr, str);
2102
    if (res > 0) return res;
2103
    pstr.p = or_str + 1;
2104
    pstr.len = (pattern.p + pattern.len) - (or_str + 1);
2105
    return mg_match_prefix_n(pstr, str);
2106
  }
2107

    
2108
  for (; i < pattern.len && j < str.len; i++, j++) {
2109
    if (pattern.p[i] == '?') {
2110
      continue;
2111
    } else if (pattern.p[i] == '*') {
2112
      i++;
2113
      if (i < pattern.len && pattern.p[i] == '*') {
2114
        i++;
2115
        len = str.len - j;
2116
      } else {
2117
        len = 0;
2118
        while (j + len < str.len && str.p[j + len] != '/') len++;
2119
      }
2120
      if (i == pattern.len || (pattern.p[i] == '$' && i == pattern.len - 1))
2121
        return j + len;
2122
      do {
2123
        const struct mg_str pstr = {pattern.p + i, pattern.len - i};
2124
        const struct mg_str sstr = {str.p + j + len, str.len - j - len};
2125
        res = mg_match_prefix_n(pstr, sstr);
2126
      } while (res == 0 && len != 0 && len-- > 0);
2127
      return res == 0 ? 0 : j + res + len;
2128
    } else if (str_util_lowercase(&pattern.p[i]) !=
2129
               str_util_lowercase(&str.p[j])) {
2130
      break;
2131
    }
2132
  }
2133
  if (i < pattern.len && pattern.p[i] == '$') {
2134
    return j == str.len ? str.len : 0;
2135
  }
2136
  return i == pattern.len ? j : 0;
2137
}
2138

    
2139
size_t mg_match_prefix(const char *, int, const char *) WEAK;
2140
size_t mg_match_prefix(const char *pattern, int pattern_len, const char *str) {
2141
  const struct mg_str pstr = {pattern, (size_t) pattern_len};
2142
  struct mg_str s = {str, 0};
2143
  if (str != NULL) s.len = strlen(str);
2144
  return mg_match_prefix_n(pstr, s);
2145
}
2146

    
2147
#endif /* EXCLUDE_COMMON */
2148
#ifdef MG_MODULE_LINES
2149
#line 1 "mongoose/src/mg_net.c"
2150
#endif
2151
/*
2152
 * Copyright (c) 2014 Cesanta Software Limited
2153
 * All rights reserved
2154
 *
2155
 * This software is dual-licensed: you can redistribute it and/or modify
2156
 * it under the terms of the GNU General Public License version 2 as
2157
 * published by the Free Software Foundation. For the terms of this
2158
 * license, see <http://www.gnu.org/licenses/>.
2159
 *
2160
 * You are free to use this software under the terms of the GNU General
2161
 * Public License, but WITHOUT ANY WARRANTY; without even the implied
2162
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
2163
 * See the GNU General Public License for more details.
2164
 *
2165
 * Alternatively, you can license this software under a commercial
2166
 * license, as set out in <https://www.cesanta.com/license>.
2167
 */
2168

    
2169
/* Amalgamated: #include "common/cs_time.h" */
2170
/* Amalgamated: #include "mg_dns.h" */
2171
/* Amalgamated: #include "mg_internal.h" */
2172
/* Amalgamated: #include "mg_resolv.h" */
2173
/* Amalgamated: #include "mg_util.h" */
2174

    
2175
#define MG_MAX_HOST_LEN 200
2176

    
2177
#define MG_COPY_COMMON_CONNECTION_OPTIONS(dst, src) \
2178
  memcpy(dst, src, sizeof(*dst));
2179

    
2180
/* Which flags can be pre-set by the user at connection creation time. */
2181
#define _MG_ALLOWED_CONNECT_FLAGS_MASK                                   \
2182
  (MG_F_USER_1 | MG_F_USER_2 | MG_F_USER_3 | MG_F_USER_4 | MG_F_USER_5 | \
2183
   MG_F_USER_6 | MG_F_WEBSOCKET_NO_DEFRAG | MG_F_ENABLE_BROADCAST)
2184
/* Which flags should be modifiable by user's callbacks. */
2185
#define _MG_CALLBACK_MODIFIABLE_FLAGS_MASK                               \
2186
  (MG_F_USER_1 | MG_F_USER_2 | MG_F_USER_3 | MG_F_USER_4 | MG_F_USER_5 | \
2187
   MG_F_USER_6 | MG_F_WEBSOCKET_NO_DEFRAG | MG_F_SEND_AND_CLOSE |        \
2188
   MG_F_CLOSE_IMMEDIATELY | MG_F_IS_WEBSOCKET | MG_F_DELETE_CHUNK)
2189

    
2190
#ifndef intptr_t
2191
#define intptr_t long
2192
#endif
2193

    
2194
MG_INTERNAL void mg_add_conn(struct mg_mgr *mgr, struct mg_connection *c) {
2195
  DBG(("%p %p", mgr, c));
2196
  c->mgr = mgr;
2197
  c->next = mgr->active_connections;
2198
  mgr->active_connections = c;
2199
  c->prev = NULL;
2200
  if (c->next != NULL) c->next->prev = c;
2201
  if (c->sock != INVALID_SOCKET) {
2202
    c->iface->vtable->add_conn(c);
2203
  }
2204
}
2205

    
2206
MG_INTERNAL void mg_remove_conn(struct mg_connection *conn) {
2207
  if (conn->prev == NULL) conn->mgr->active_connections = conn->next;
2208
  if (conn->prev) conn->prev->next = conn->next;
2209
  if (conn->next) conn->next->prev = conn->prev;
2210
  conn->prev = conn->next = NULL;
2211
  conn->iface->vtable->remove_conn(conn);
2212
}
2213

    
2214
MG_INTERNAL void mg_call(struct mg_connection *nc,
2215
                         mg_event_handler_t ev_handler, void *user_data, int ev,
2216
                         void *ev_data) {
2217
  static int nesting_level = 0;
2218
  nesting_level++;
2219
  if (ev_handler == NULL) {
2220
    /*
2221
     * If protocol handler is specified, call it. Otherwise, call user-specified
2222
     * event handler.
2223
     */
2224
    ev_handler = nc->proto_handler ? nc->proto_handler : nc->handler;
2225
  }
2226
  if (ev != MG_EV_POLL) {
2227
    DBG(("%p %s ev=%d ev_data=%p flags=%lu rmbl=%d smbl=%d", nc,
2228
         ev_handler == nc->handler ? "user" : "proto", ev, ev_data, nc->flags,
2229
         (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len));
2230
  }
2231

    
2232
#if !defined(NO_LIBC) && MG_ENABLE_HEXDUMP
2233
  if (nc->mgr->hexdump_file != NULL && ev != MG_EV_POLL && ev != MG_EV_RECV &&
2234
      ev != MG_EV_SEND /* handled separately */) {
2235
    mg_hexdump_connection(nc, nc->mgr->hexdump_file, NULL, 0, ev);
2236
  }
2237
#endif
2238
  if (ev_handler != NULL) {
2239
    unsigned long flags_before = nc->flags;
2240
    size_t recv_mbuf_before = nc->recv_mbuf.len, recved;
2241
    ev_handler(nc, ev, ev_data MG_UD_ARG(user_data));
2242
    recved = (recv_mbuf_before - nc->recv_mbuf.len);
2243
    /* Prevent user handler from fiddling with system flags. */
2244
    if (ev_handler == nc->handler && nc->flags != flags_before) {
2245
      nc->flags = (flags_before & ~_MG_CALLBACK_MODIFIABLE_FLAGS_MASK) |
2246
                  (nc->flags & _MG_CALLBACK_MODIFIABLE_FLAGS_MASK);
2247
    }
2248
    /* It's important to not double-count recved bytes, and since mg_call can be
2249
     * called recursively (e.g. proto_handler invokes user handler), we keep
2250
     * track of recursion and only report received bytes at the top level. */
2251
    if (nesting_level == 1 && recved > 0 && !(nc->flags & MG_F_UDP)) {
2252
      nc->iface->vtable->recved(nc, recved);
2253
    }
2254
  }
2255
  if (ev != MG_EV_POLL) {
2256
    DBG(("%p after %s flags=%lu rmbl=%d smbl=%d", nc,
2257
         ev_handler == nc->handler ? "user" : "proto", nc->flags,
2258
         (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len));
2259
  }
2260
  nesting_level--;
2261
#if !MG_ENABLE_CALLBACK_USERDATA
2262
  (void) user_data;
2263
#endif
2264
}
2265

    
2266
void mg_if_timer(struct mg_connection *c, double now) {
2267
  if (c->ev_timer_time > 0 && now >= c->ev_timer_time) {
2268
    double old_value = c->ev_timer_time;
2269
    c->ev_timer_time = 0;
2270
    mg_call(c, NULL, c->user_data, MG_EV_TIMER, &old_value);
2271
  }
2272
}
2273

    
2274
void mg_if_poll(struct mg_connection *nc, time_t now) {
2275
  if (!(nc->flags & MG_F_SSL) || (nc->flags & MG_F_SSL_HANDSHAKE_DONE)) {
2276
    mg_call(nc, NULL, nc->user_data, MG_EV_POLL, &now);
2277
  }
2278
}
2279

    
2280
void mg_destroy_conn(struct mg_connection *conn, int destroy_if) {
2281
  if (destroy_if) conn->iface->vtable->destroy_conn(conn);
2282
  if (conn->proto_data != NULL && conn->proto_data_destructor != NULL) {
2283
    conn->proto_data_destructor(conn->proto_data);
2284
  }
2285
#if MG_ENABLE_SSL
2286
  mg_ssl_if_conn_free(conn);
2287
#endif
2288
  mbuf_free(&conn->recv_mbuf);
2289
  mbuf_free(&conn->send_mbuf);
2290

    
2291
  memset(conn, 0, sizeof(*conn));
2292
  MG_FREE(conn);
2293
}
2294

    
2295
void mg_close_conn(struct mg_connection *conn) {
2296
  DBG(("%p %lu %d", conn, conn->flags, conn->sock));
2297
#if MG_ENABLE_SSL
2298
  if (conn->flags & MG_F_SSL_HANDSHAKE_DONE) {
2299
    mg_ssl_if_conn_close_notify(conn);
2300
  }
2301
#endif
2302
  mg_remove_conn(conn);
2303
  conn->iface->vtable->destroy_conn(conn);
2304
  mg_call(conn, NULL, conn->user_data, MG_EV_CLOSE, NULL);
2305
  mg_destroy_conn(conn, 0 /* destroy_if */);
2306
}
2307

    
2308
void mg_mgr_init(struct mg_mgr *m, void *user_data) {
2309
  struct mg_mgr_init_opts opts;
2310
  memset(&opts, 0, sizeof(opts));
2311
  mg_mgr_init_opt(m, user_data, opts);
2312
}
2313

    
2314
void mg_mgr_init_opt(struct mg_mgr *m, void *user_data,
2315
                     struct mg_mgr_init_opts opts) {
2316
  memset(m, 0, sizeof(*m));
2317
#if MG_ENABLE_BROADCAST
2318
  m->ctl[0] = m->ctl[1] = INVALID_SOCKET;
2319
#endif
2320
  m->user_data = user_data;
2321

    
2322
#ifdef _WIN32
2323
  {
2324
    WSADATA data;
2325
    WSAStartup(MAKEWORD(2, 2), &data);
2326
  }
2327
#elif defined(__unix__)
2328
  /* Ignore SIGPIPE signal, so if client cancels the request, it
2329
   * won't kill the whole process. */
2330
  signal(SIGPIPE, SIG_IGN);
2331
#endif
2332

    
2333
#if MG_ENABLE_SSL
2334
  {
2335
    static int init_done;
2336
    if (!init_done) {
2337
      mg_ssl_if_init();
2338
      init_done++;
2339
    }
2340
  }
2341
#endif
2342
  {
2343
    int i;
2344
    if (opts.num_ifaces == 0) {
2345
      opts.num_ifaces = mg_num_ifaces;
2346
      opts.ifaces = mg_ifaces;
2347
    }
2348
    if (opts.main_iface != NULL) {
2349
      opts.ifaces[MG_MAIN_IFACE] = opts.main_iface;
2350
    }
2351
    m->num_ifaces = opts.num_ifaces;
2352
    m->ifaces =
2353
        (struct mg_iface **) MG_MALLOC(sizeof(*m->ifaces) * opts.num_ifaces);
2354
    for (i = 0; i < mg_num_ifaces; i++) {
2355
      m->ifaces[i] = mg_if_create_iface(opts.ifaces[i], m);
2356
      m->ifaces[i]->vtable->init(m->ifaces[i]);
2357
    }
2358
  }
2359
  if (opts.nameserver != NULL) {
2360
    m->nameserver = strdup(opts.nameserver);
2361
  }
2362
  DBG(("=================================="));
2363
  DBG(("init mgr=%p", m));
2364
}
2365

    
2366
void mg_mgr_free(struct mg_mgr *m) {
2367
  struct mg_connection *conn, *tmp_conn;
2368

    
2369
  DBG(("%p", m));
2370
  if (m == NULL) return;
2371
  /* Do one last poll, see https://github.com/cesanta/mongoose/issues/286 */
2372
  mg_mgr_poll(m, 0);
2373

    
2374
#if MG_ENABLE_BROADCAST
2375
  if (m->ctl[0] != INVALID_SOCKET) closesocket(m->ctl[0]);
2376
  if (m->ctl[1] != INVALID_SOCKET) closesocket(m->ctl[1]);
2377
  m->ctl[0] = m->ctl[1] = INVALID_SOCKET;
2378
#endif
2379

    
2380
  for (conn = m->active_connections; conn != NULL; conn = tmp_conn) {
2381
    tmp_conn = conn->next;
2382
    mg_close_conn(conn);
2383
  }
2384

    
2385
  {
2386
    int i;
2387
    for (i = 0; i < m->num_ifaces; i++) {
2388
      m->ifaces[i]->vtable->free(m->ifaces[i]);
2389
      MG_FREE(m->ifaces[i]);
2390
    }
2391
    MG_FREE(m->ifaces);
2392
  }
2393

    
2394
  MG_FREE((char *) m->nameserver);
2395
}
2396

    
2397
time_t mg_mgr_poll(struct mg_mgr *m, int timeout_ms) {
2398
  int i;
2399
  time_t now = 0; /* oh GCC, seriously ? */
2400

    
2401
  if (m->num_ifaces == 0) {
2402
    LOG(LL_ERROR, ("cannot poll: no interfaces"));
2403
    return 0;
2404
  }
2405

    
2406
  for (i = 0; i < m->num_ifaces; i++) {
2407
    now = m->ifaces[i]->vtable->poll(m->ifaces[i], timeout_ms);
2408
  }
2409
  return now;
2410
}
2411

    
2412
int mg_vprintf(struct mg_connection *nc, const char *fmt, va_list ap) {
2413
  char mem[MG_VPRINTF_BUFFER_SIZE], *buf = mem;
2414
  int len;
2415

    
2416
  if ((len = mg_avprintf(&buf, sizeof(mem), fmt, ap)) > 0) {
2417
    mg_send(nc, buf, len);
2418
  }
2419
  if (buf != mem && buf != NULL) {
2420
    MG_FREE(buf); /* LCOV_EXCL_LINE */
2421
  }               /* LCOV_EXCL_LINE */
2422

    
2423
  return len;
2424
}
2425

    
2426
int mg_printf(struct mg_connection *conn, const char *fmt, ...) {
2427
  int len;
2428
  va_list ap;
2429
  va_start(ap, fmt);
2430
  len = mg_vprintf(conn, fmt, ap);
2431
  va_end(ap);
2432
  return len;
2433
}
2434

    
2435
#if MG_ENABLE_SYNC_RESOLVER
2436
/* TODO(lsm): use non-blocking resolver */
2437
static int mg_resolve2(const char *host, struct in_addr *ina) {
2438
#if MG_ENABLE_GETADDRINFO
2439
  int rv = 0;
2440
  struct addrinfo hints, *servinfo, *p;
2441
  struct sockaddr_in *h = NULL;
2442
  memset(&hints, 0, sizeof hints);
2443
  hints.ai_family = AF_INET;
2444
  hints.ai_socktype = SOCK_STREAM;
2445
  if ((rv = getaddrinfo(host, NULL, NULL, &servinfo)) != 0) {
2446
    DBG(("getaddrinfo(%s) failed: %s", host, strerror(mg_get_errno())));
2447
    return 0;
2448
  }
2449
  for (p = servinfo; p != NULL; p = p->ai_next) {
2450
    memcpy(&h, &p->ai_addr, sizeof(struct sockaddr_in *));
2451
    memcpy(ina, &h->sin_addr, sizeof(ina));
2452
  }
2453
  freeaddrinfo(servinfo);
2454
  return 1;
2455
#else
2456
  struct hostent *he;
2457
  if ((he = gethostbyname(host)) == NULL) {
2458
    DBG(("gethostbyname(%s) failed: %s", host, strerror(mg_get_errno())));
2459
  } else {
2460
    memcpy(ina, he->h_addr_list[0], sizeof(*ina));
2461
    return 1;
2462
  }
2463
  return 0;
2464
#endif /* MG_ENABLE_GETADDRINFO */
2465
}
2466

    
2467
int mg_resolve(const char *host, char *buf, size_t n) {
2468
  struct in_addr ad;
2469
  return mg_resolve2(host, &ad) ? snprintf(buf, n, "%s", inet_ntoa(ad)) : 0;
2470
}
2471
#endif /* MG_ENABLE_SYNC_RESOLVER */
2472

    
2473
MG_INTERNAL struct mg_connection *mg_create_connection_base(
2474
    struct mg_mgr *mgr, mg_event_handler_t callback,
2475
    struct mg_add_sock_opts opts) {
2476
  struct mg_connection *conn;
2477

    
2478
  if ((conn = (struct mg_connection *) MG_CALLOC(1, sizeof(*conn))) != NULL) {
2479
    conn->sock = INVALID_SOCKET;
2480
    conn->handler = callback;
2481
    conn->mgr = mgr;
2482
    conn->last_io_time = (time_t) mg_time();
2483
    conn->iface =
2484
        (opts.iface != NULL ? opts.iface : mgr->ifaces[MG_MAIN_IFACE]);
2485
    conn->flags = opts.flags & _MG_ALLOWED_CONNECT_FLAGS_MASK;
2486
    conn->user_data = opts.user_data;
2487
    /*
2488
     * SIZE_MAX is defined as a long long constant in
2489
     * system headers on some platforms and so it
2490
     * doesn't compile with pedantic ansi flags.
2491
     */
2492
    conn->recv_mbuf_limit = ~0;
2493
  } else {
2494
    MG_SET_PTRPTR(opts.error_string, "failed to create connection");
2495
  }
2496

    
2497
  return conn;
2498
}
2499

    
2500
MG_INTERNAL struct mg_connection *mg_create_connection(
2501
    struct mg_mgr *mgr, mg_event_handler_t callback,
2502
    struct mg_add_sock_opts opts) {
2503
  struct mg_connection *conn = mg_create_connection_base(mgr, callback, opts);
2504

    
2505
  if (conn != NULL && !conn->iface->vtable->create_conn(conn)) {
2506
    MG_FREE(conn);
2507
    conn = NULL;
2508
  }
2509
  if (conn == NULL) {
2510
    MG_SET_PTRPTR(opts.error_string, "failed to init connection");
2511
  }
2512

    
2513
  return conn;
2514
}
2515

    
2516
/*
2517
 * Address format: [PROTO://][HOST]:PORT
2518
 *
2519
 * HOST could be IPv4/IPv6 address or a host name.
2520
 * `host` is a destination buffer to hold parsed HOST part. Should be at least
2521
 * MG_MAX_HOST_LEN bytes long.
2522
 * `proto` is a returned socket type, either SOCK_STREAM or SOCK_DGRAM
2523
 *
2524
 * Return:
2525
 *   -1   on parse error
2526
 *    0   if HOST needs DNS lookup
2527
 *   >0   length of the address string
2528
 */
2529
MG_INTERNAL int mg_parse_address(const char *str, union socket_address *sa,
2530
                                 int *proto, char *host, size_t host_len) {
2531
  unsigned int a, b, c, d, port = 0;
2532
  int ch, len = 0;
2533
#if MG_ENABLE_IPV6
2534
  char buf[100];
2535
#endif
2536

    
2537
  /*
2538
   * MacOS needs that. If we do not zero it, subsequent bind() will fail.
2539
   * Also, all-zeroes in the socket address means binding to all addresses
2540
   * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT).
2541
   */
2542
  memset(sa, 0, sizeof(*sa));
2543
  sa->sin.sin_family = AF_INET;
2544

    
2545
  *proto = SOCK_STREAM;
2546

    
2547
  if (strncmp(str, "udp://", 6) == 0) {
2548
    str += 6;
2549
    *proto = SOCK_DGRAM;
2550
  } else if (strncmp(str, "tcp://", 6) == 0) {
2551
    str += 6;
2552
  }
2553

    
2554
  if (sscanf(str, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len) == 5) {
2555
    /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
2556
    sa->sin.sin_addr.s_addr =
2557
        htonl(((uint32_t) a << 24) | ((uint32_t) b << 16) | c << 8 | d);
2558
    sa->sin.sin_port = htons((uint16_t) port);
2559
#if MG_ENABLE_IPV6
2560
  } else if (sscanf(str, "[%99[^]]]:%u%n", buf, &port, &len) == 2 &&
2561
             inet_pton(AF_INET6, buf, &sa->sin6.sin6_addr)) {
2562
    /* IPv6 address, e.g. [3ffe:2a00:100:7031::1]:8080 */
2563
    sa->sin6.sin6_family = AF_INET6;
2564
    sa->sin.sin_port = htons((uint16_t) port);
2565
#endif
2566
#if MG_ENABLE_ASYNC_RESOLVER
2567
  } else if (strlen(str) < host_len &&
2568
             sscanf(str, "%[^ :]:%u%n", host, &port, &len) == 2) {
2569
    sa->sin.sin_port = htons((uint16_t) port);
2570
    if (mg_resolve_from_hosts_file(host, sa) != 0) {
2571
      /*
2572
       * if resolving from hosts file failed and the host
2573
       * we are trying to resolve is `localhost` - we should
2574
       * try to resolve it using `gethostbyname` and do not try
2575
       * to resolve it via DNS server if gethostbyname has failed too
2576
       */
2577
      if (mg_ncasecmp(host, "localhost", 9) != 0) {
2578
        return 0;
2579
      }
2580

    
2581
#if MG_ENABLE_SYNC_RESOLVER
2582
      if (!mg_resolve2(host, &sa->sin.sin_addr)) {
2583
        return -1;
2584
      }
2585
#else
2586
      return -1;
2587
#endif
2588
    }
2589
#endif
2590
  } else if (sscanf(str, ":%u%n", &port, &len) == 1 ||
2591
             sscanf(str, "%u%n", &port, &len) == 1) {
2592
    /* If only port is specified, bind to IPv4, INADDR_ANY */
2593
    sa->sin.sin_port = htons((uint16_t) port);
2594
  } else {
2595
    return -1;
2596
  }
2597

    
2598
  /* Required for MG_ENABLE_ASYNC_RESOLVER=0 */
2599
  (void) host;
2600
  (void) host_len;
2601

    
2602
  ch = str[len]; /* Character that follows the address */
2603
  return port < 0xffffUL && (ch == '\0' || ch == ',' || isspace(ch)) ? len : -1;
2604
}
2605

    
2606
struct mg_connection *mg_if_accept_new_conn(struct mg_connection *lc) {
2607
  struct mg_add_sock_opts opts;
2608
  struct mg_connection *nc;
2609
  memset(&opts, 0, sizeof(opts));
2610
  nc = mg_create_connection(lc->mgr, lc->handler, opts);
2611
  if (nc == NULL) return NULL;
2612
  nc->listener = lc;
2613
  nc->proto_handler = lc->proto_handler;
2614
  nc->user_data = lc->user_data;
2615
  nc->recv_mbuf_limit = lc->recv_mbuf_limit;
2616
  nc->iface = lc->iface;
2617
  if (lc->flags & MG_F_SSL) nc->flags |= MG_F_SSL;
2618
  mg_add_conn(nc->mgr, nc);
2619
  DBG(("%p %p %d %d", lc, nc, nc->sock, (int) nc->flags));
2620
  return nc;
2621
}
2622

    
2623
void mg_if_accept_tcp_cb(struct mg_connection *nc, union socket_address *sa,
2624
                         size_t sa_len) {
2625
  (void) sa_len;
2626
  nc->sa = *sa;
2627
  mg_call(nc, NULL, nc->user_data, MG_EV_ACCEPT, &nc->sa);
2628
}
2629

    
2630
void mg_send(struct mg_connection *nc, const void *buf, int len) {
2631
  nc->last_io_time = (time_t) mg_time();
2632
  if (nc->flags & MG_F_UDP) {
2633
    nc->iface->vtable->udp_send(nc, buf, len);
2634
  } else {
2635
    nc->iface->vtable->tcp_send(nc, buf, len);
2636
  }
2637
}
2638

    
2639
void mg_if_sent_cb(struct mg_connection *nc, int num_sent) {
2640
  DBG(("%p %d", nc, num_sent));
2641
#if !defined(NO_LIBC) && MG_ENABLE_HEXDUMP
2642
  if (nc->mgr && nc->mgr->hexdump_file != NULL) {
2643
    char *buf = nc->send_mbuf.buf;
2644
    mg_hexdump_connection(nc, nc->mgr->hexdump_file, buf, num_sent, MG_EV_SEND);
2645
  }
2646
#endif
2647
  if (num_sent < 0) {
2648
    nc->flags |= MG_F_CLOSE_IMMEDIATELY;
2649
  } else {
2650
    mbuf_remove(&nc->send_mbuf, num_sent);
2651
    mbuf_trim(&nc->send_mbuf);
2652
  }
2653
  mg_call(nc, NULL, nc->user_data, MG_EV_SEND, &num_sent);
2654
}
2655

    
2656
MG_INTERNAL void mg_recv_common(struct mg_connection *nc, void *buf, int len,
2657
                                int own) {
2658
  DBG(("%p %d %u", nc, len, (unsigned int) nc->recv_mbuf.len));
2659

    
2660
#if !defined(NO_LIBC) && MG_ENABLE_HEXDUMP
2661
  if (nc->mgr && nc->mgr->hexdump_file != NULL) {
2662
    mg_hexdump_connection(nc, nc->mgr->hexdump_file, buf, len, MG_EV_RECV);
2663
  }
2664
#endif
2665

    
2666
  if (nc->flags & MG_F_CLOSE_IMMEDIATELY) {
2667
    DBG(("%p discarded %d bytes", nc, len));
2668
    /*
2669
     * This connection will not survive next poll. Do not deliver events,
2670
     * send data to /dev/null without acking.
2671
     */
2672
    if (own) {
2673
      MG_FREE(buf);
2674
    }
2675
    return;
2676
  }
2677
  nc->last_io_time = (time_t) mg_time();
2678
  if (!own) {
2679
    mbuf_append(&nc->recv_mbuf, buf, len);
2680
  } else if (nc->recv_mbuf.len == 0) {
2681
    /* Adopt buf as recv_mbuf's backing store. */
2682
    mbuf_free(&nc->recv_mbuf);
2683
    nc->recv_mbuf.buf = (char *) buf;
2684
    nc->recv_mbuf.size = nc->recv_mbuf.len = len;
2685
  } else {
2686
    mbuf_append(&nc->recv_mbuf, buf, len);
2687
    MG_FREE(buf);
2688
  }
2689
  mg_call(nc, NULL, nc->user_data, MG_EV_RECV, &len);
2690
}
2691

    
2692
void mg_if_recv_tcp_cb(struct mg_connection *nc, void *buf, int len, int own) {
2693
  mg_recv_common(nc, buf, len, own);
2694
}
2695

    
2696
void mg_if_recv_udp_cb(struct mg_connection *nc, void *buf, int len,
2697
                       union socket_address *sa, size_t sa_len) {
2698
  assert(nc->flags & MG_F_UDP);
2699
  DBG(("%p %u", nc, (unsigned int) len));
2700
  if (nc->flags & MG_F_LISTENING) {
2701
    struct mg_connection *lc = nc;
2702
    /*
2703
     * Do we have an existing connection for this source?
2704
     * This is very inefficient for long connection lists.
2705
     */
2706
    for (nc = mg_next(lc->mgr, NULL); nc != NULL; nc = mg_next(lc->mgr, nc)) {
2707
      if (memcmp(&nc->sa.sa, &sa->sa, sa_len) == 0 && nc->listener == lc) {
2708
        break;
2709
      }
2710
    }
2711
    if (nc == NULL) {
2712
      struct mg_add_sock_opts opts;
2713
      memset(&opts, 0, sizeof(opts));
2714
      /* Create fake connection w/out sock initialization */
2715
      nc = mg_create_connection_base(lc->mgr, lc->handler, opts);
2716
      if (nc != NULL) {
2717
        nc->sock = lc->sock;
2718
        nc->listener = lc;
2719
        nc->sa = *sa;
2720
        nc->proto_handler = lc->proto_handler;
2721
        nc->user_data = lc->user_data;
2722
        nc->recv_mbuf_limit = lc->recv_mbuf_limit;
2723
        nc->flags = MG_F_UDP;
2724
        /*
2725
         * Long-lived UDP "connections" i.e. interactions that involve more
2726
         * than one request and response are rare, most are transactional:
2727
         * response is sent and the "connection" is closed. Or - should be.
2728
         * But users (including ourselves) tend to forget about that part,
2729
         * because UDP is connectionless and one does not think about
2730
         * processing a UDP request as handling a connection that needs to be
2731
         * closed. Thus, we begin with SEND_AND_CLOSE flag set, which should
2732
         * be a reasonable default for most use cases, but it is possible to
2733
         * turn it off the connection should be kept alive after processing.
2734
         */
2735
        nc->flags |= MG_F_SEND_AND_CLOSE;
2736
        mg_add_conn(lc->mgr, nc);
2737
        mg_call(nc, NULL, nc->user_data, MG_EV_ACCEPT, &nc->sa);
2738
      } else {
2739
        DBG(("OOM"));
2740
        /* No return here, we still need to drop on the floor */
2741
      }
2742
    }
2743
  }
2744
  if (nc != NULL) {
2745
    mg_recv_common(nc, buf, len, 1);
2746
  } else {
2747
    /* Drop on the floor. */
2748
    MG_FREE(buf);
2749
  }
2750
}
2751

    
2752
/*
2753
 * Schedules an async connect for a resolved address and proto.
2754
 * Called from two places: `mg_connect_opt()` and from async resolver.
2755
 * When called from the async resolver, it must trigger `MG_EV_CONNECT` event
2756
 * with a failure flag to indicate connection failure.
2757
 */
2758
MG_INTERNAL struct mg_connection *mg_do_connect(struct mg_connection *nc,
2759
                                                int proto,
2760
                                                union socket_address *sa) {
2761
  DBG(("%p %s://%s:%hu", nc, proto == SOCK_DGRAM ? "udp" : "tcp",
2762
       inet_ntoa(sa->sin.sin_addr), ntohs(sa->sin.sin_port)));
2763

    
2764
  nc->flags |= MG_F_CONNECTING;
2765
  if (proto == SOCK_DGRAM) {
2766
    nc->iface->vtable->connect_udp(nc);
2767
  } else {
2768
    nc->iface->vtable->connect_tcp(nc, sa);
2769
  }
2770
  mg_add_conn(nc->mgr, nc);
2771
  return nc;
2772
}
2773

    
2774
void mg_if_connect_cb(struct mg_connection *nc, int err) {
2775
  DBG(("%p connect, err=%d", nc, err));
2776
  nc->flags &= ~MG_F_CONNECTING;
2777
  if (err != 0) {
2778
    nc->flags |= MG_F_CLOSE_IMMEDIATELY;
2779
  }
2780
  mg_call(nc, NULL, nc->user_data, MG_EV_CONNECT, &err);
2781
}
2782

    
2783
#if MG_ENABLE_ASYNC_RESOLVER
2784
/*
2785
 * Callback for the async resolver on mg_connect_opt() call.
2786
 * Main task of this function is to trigger MG_EV_CONNECT event with
2787
 *    either failure (and dealloc the connection)
2788
 *    or success (and proceed with connect()
2789
 */
2790
static void resolve_cb(struct mg_dns_message *msg, void *data,
2791
                       enum mg_resolve_err e) {
2792
  struct mg_connection *nc = (struct mg_connection *) data;
2793
  int i;
2794
  int failure = -1;
2795

    
2796
  nc->flags &= ~MG_F_RESOLVING;
2797
  if (msg != NULL) {
2798
    /*
2799
     * Take the first DNS A answer and run...
2800
     */
2801
    for (i = 0; i < msg->num_answers; i++) {
2802
      if (msg->answers[i].rtype == MG_DNS_A_RECORD) {
2803
        /*
2804
         * Async resolver guarantees that there is at least one answer.
2805
         * TODO(lsm): handle IPv6 answers too
2806
         */
2807
        mg_dns_parse_record_data(msg, &msg->answers[i], &nc->sa.sin.sin_addr,
2808
                                 4);
2809
        mg_do_connect(nc, nc->flags & MG_F_UDP ? SOCK_DGRAM : SOCK_STREAM,
2810
                      &nc->sa);
2811
        return;
2812
      }
2813
    }
2814
  }
2815

    
2816
  if (e == MG_RESOLVE_TIMEOUT) {
2817
    double now = mg_time();
2818
    mg_call(nc, NULL, nc->user_data, MG_EV_TIMER, &now);
2819
  }
2820

    
2821
  /*
2822
   * If we get there was no MG_DNS_A_RECORD in the answer
2823
   */
2824
  mg_call(nc, NULL, nc->user_data, MG_EV_CONNECT, &failure);
2825
  mg_call(nc, NULL, nc->user_data, MG_EV_CLOSE, NULL);
2826
  mg_destroy_conn(nc, 1 /* destroy_if */);
2827
}
2828
#endif
2829

    
2830
struct mg_connection *mg_connect(struct mg_mgr *mgr, const char *address,
2831
                                 MG_CB(mg_event_handler_t callback,
2832
                                       void *user_data)) {
2833
  struct mg_connect_opts opts;
2834
  memset(&opts, 0, sizeof(opts));
2835
  return mg_connect_opt(mgr, address, MG_CB(callback, user_data), opts);
2836
}
2837

    
2838
struct mg_connection *mg_connect_opt(struct mg_mgr *mgr, const char *address,
2839
                                     MG_CB(mg_event_handler_t callback,
2840
                                           void *user_data),
2841
                                     struct mg_connect_opts opts) {
2842
  struct mg_connection *nc = NULL;
2843
  int proto, rc;
2844
  struct mg_add_sock_opts add_sock_opts;
2845
  char host[MG_MAX_HOST_LEN];
2846

    
2847
  MG_COPY_COMMON_CONNECTION_OPTIONS(&add_sock_opts, &opts);
2848

    
2849
  if ((nc = mg_create_connection(mgr, callback, add_sock_opts)) == NULL) {
2850
    return NULL;
2851
  }
2852

    
2853
  if ((rc = mg_parse_address(address, &nc->sa, &proto, host, sizeof(host))) <
2854
      0) {
2855
    /* Address is malformed */
2856
    MG_SET_PTRPTR(opts.error_string, "cannot parse address");
2857
    mg_destroy_conn(nc, 1 /* destroy_if */);
2858
    return NULL;
2859
  }
2860

    
2861
  nc->flags |= opts.flags & _MG_ALLOWED_CONNECT_FLAGS_MASK;
2862
  nc->flags |= (proto == SOCK_DGRAM) ? MG_F_UDP : 0;
2863
#if MG_ENABLE_CALLBACK_USERDATA
2864
  nc->user_data = user_data;
2865
#else
2866
  nc->user_data = opts.user_data;
2867
#endif
2868

    
2869
#if MG_ENABLE_SSL
2870
  DBG(("%p %s %s,%s,%s", nc, address, (opts.ssl_cert ? opts.ssl_cert : "-"),
2871
       (opts.ssl_key ? opts.ssl_key : "-"),
2872
       (opts.ssl_ca_cert ? opts.ssl_ca_cert : "-")));
2873

    
2874
  if (opts.ssl_cert != NULL || opts.ssl_ca_cert != NULL ||
2875
      opts.ssl_psk_identity != NULL) {
2876
    const char *err_msg = NULL;
2877
    struct mg_ssl_if_conn_params params;
2878
    if (nc->flags & MG_F_UDP) {
2879
      MG_SET_PTRPTR(opts.error_string, "SSL for UDP is not supported");
2880
      mg_destroy_conn(nc, 1 /* destroy_if */);
2881
      return NULL;
2882
    }
2883
    memset(&params, 0, sizeof(params));
2884
    params.cert = opts.ssl_cert;
2885
    params.key = opts.ssl_key;
2886
    params.ca_cert = opts.ssl_ca_cert;
2887
    params.cipher_suites = opts.ssl_cipher_suites;
2888
    params.psk_identity = opts.ssl_psk_identity;
2889
    params.psk_key = opts.ssl_psk_key;
2890
    if (opts.ssl_ca_cert != NULL) {
2891
      if (opts.ssl_server_name != NULL) {
2892
        if (strcmp(opts.ssl_server_name, "*") != 0) {
2893
          params.server_name = opts.ssl_server_name;
2894
        }
2895
      } else if (rc == 0) { /* If it's a DNS name, use host. */
2896
        params.server_name = host;
2897
      }
2898
    }
2899
    if (mg_ssl_if_conn_init(nc, &params, &err_msg) != MG_SSL_OK) {
2900
      MG_SET_PTRPTR(opts.error_string, err_msg);
2901
      mg_destroy_conn(nc, 1 /* destroy_if */);
2902
      return NULL;
2903
    }
2904
    nc->flags |= MG_F_SSL;
2905
  }
2906
#endif /* MG_ENABLE_SSL */
2907

    
2908
  if (rc == 0) {
2909
#if MG_ENABLE_ASYNC_RESOLVER
2910
    /*
2911
     * DNS resolution is required for host.
2912
     * mg_parse_address() fills port in nc->sa, which we pass to resolve_cb()
2913
     */
2914
    struct mg_connection *dns_conn = NULL;
2915
    struct mg_resolve_async_opts o;
2916
    memset(&o, 0, sizeof(o));
2917
    o.dns_conn = &dns_conn;
2918
    o.nameserver = opts.nameserver;
2919
    if (mg_resolve_async_opt(nc->mgr, host, MG_DNS_A_RECORD, resolve_cb, nc,
2920
                             o) != 0) {
2921
      MG_SET_PTRPTR(opts.error_string, "cannot schedule DNS lookup");
2922
      mg_destroy_conn(nc, 1 /* destroy_if */);
2923
      return NULL;
2924
    }
2925
    nc->priv_2 = dns_conn;
2926
    nc->flags |= MG_F_RESOLVING;
2927
    return nc;
2928
#else
2929
    MG_SET_PTRPTR(opts.error_string, "Resolver is disabled");
2930
    mg_destroy_conn(nc, 1 /* destroy_if */);
2931
    return NULL;
2932
#endif
2933
  } else {
2934
    /* Address is parsed and resolved to IP. proceed with connect() */
2935
    return mg_do_connect(nc, proto, &nc->sa);
2936
  }
2937
}
2938

    
2939
struct mg_connection *mg_bind(struct mg_mgr *srv, const char *address,
2940
                              MG_CB(mg_event_handler_t event_handler,
2941
                                    void *user_data)) {
2942
  struct mg_bind_opts opts;
2943
  memset(&opts, 0, sizeof(opts));
2944
  return mg_bind_opt(srv, address, MG_CB(event_handler, user_data), opts);
2945
}
2946

    
2947
struct mg_connection *mg_bind_opt(struct mg_mgr *mgr, const char *address,
2948
                                  MG_CB(mg_event_handler_t callback,
2949
                                        void *user_data),
2950
                                  struct mg_bind_opts opts) {
2951
  union socket_address sa;
2952
  struct mg_connection *nc = NULL;
2953
  int proto, rc;
2954
  struct mg_add_sock_opts add_sock_opts;
2955
  char host[MG_MAX_HOST_LEN];
2956

    
2957
#if MG_ENABLE_CALLBACK_USERDATA
2958
  opts.user_data = user_data;
2959
#endif
2960

    
2961
  if (callback == NULL) {
2962
    MG_SET_PTRPTR(opts.error_string, "handler is required");
2963
    return NULL;
2964
  }
2965

    
2966
  MG_COPY_COMMON_CONNECTION_OPTIONS(&add_sock_opts, &opts);
2967

    
2968
  if (mg_parse_address(address, &sa, &proto, host, sizeof(host)) <= 0) {
2969
    MG_SET_PTRPTR(opts.error_string, "cannot parse address");
2970
    return NULL;
2971
  }
2972

    
2973
  nc = mg_create_connection(mgr, callback, add_sock_opts);
2974
  if (nc == NULL) {
2975
    return NULL;
2976
  }
2977

    
2978
  nc->sa = sa;
2979
  nc->flags |= MG_F_LISTENING;
2980
  if (proto == SOCK_DGRAM) nc->flags |= MG_F_UDP;
2981

    
2982
#if MG_ENABLE_SSL
2983
  DBG(("%p %s %s,%s,%s", nc, address, (opts.ssl_cert ? opts.ssl_cert : "-"),
2984
       (opts.ssl_key ? opts.ssl_key : "-"),
2985
       (opts.ssl_ca_cert ? opts.ssl_ca_cert : "-")));
2986

    
2987
  if (opts.ssl_cert != NULL || opts.ssl_ca_cert != NULL) {
2988
    const char *err_msg = NULL;
2989
    struct mg_ssl_if_conn_params params;
2990
    if (nc->flags & MG_F_UDP) {
2991
      MG_SET_PTRPTR(opts.error_string, "SSL for UDP is not supported");
2992
      mg_destroy_conn(nc, 1 /* destroy_if */);
2993
      return NULL;
2994
    }
2995
    memset(&params, 0, sizeof(params));
2996
    params.cert = opts.ssl_cert;
2997
    params.key = opts.ssl_key;
2998
    params.ca_cert = opts.ssl_ca_cert;
2999
    params.cipher_suites = opts.ssl_cipher_suites;
3000
    if (mg_ssl_if_conn_init(nc, &params, &err_msg) != MG_SSL_OK) {
3001
      MG_SET_PTRPTR(opts.error_string, err_msg);
3002
      mg_destroy_conn(nc, 1 /* destroy_if */);
3003
      return NULL;
3004
    }
3005
    nc->flags |= MG_F_SSL;
3006
  }
3007
#endif /* MG_ENABLE_SSL */
3008

    
3009
  if (nc->flags & MG_F_UDP) {
3010
    rc = nc->iface->vtable->listen_udp(nc, &nc->sa);
3011
  } else {
3012
    rc = nc->iface->vtable->listen_tcp(nc, &nc->sa);
3013
  }
3014
  if (rc != 0) {
3015
    DBG(("Failed to open listener: %d", rc));
3016
    MG_SET_PTRPTR(opts.error_string, "failed to open listener");
3017
    mg_destroy_conn(nc, 1 /* destroy_if */);
3018
    return NULL;
3019
  }
3020
  mg_add_conn(nc->mgr, nc);
3021

    
3022
  return nc;
3023
}
3024

    
3025
struct mg_connection *mg_next(struct mg_mgr *s, struct mg_connection *conn) {
3026
  return conn == NULL ? s->active_connections : conn->next;
3027
}
3028

    
3029
#if MG_ENABLE_BROADCAST
3030
void mg_broadcast(struct mg_mgr *mgr, mg_event_handler_t cb, void *data,
3031
                  size_t len) {
3032
  struct ctl_msg ctl_msg;
3033

    
3034
  /*
3035
   * Mongoose manager has a socketpair, `struct mg_mgr::ctl`,
3036
   * where `mg_broadcast()` pushes the message.
3037
   * `mg_mgr_poll()` wakes up, reads a message from the socket pair, and calls
3038
   * specified callback for each connection. Thus the callback function executes
3039
   * in event manager thread.
3040
   */
3041
  if (mgr->ctl[0] != INVALID_SOCKET && data != NULL &&
3042
      len < sizeof(ctl_msg.message)) {
3043
    size_t dummy;
3044

    
3045
    ctl_msg.callback = cb;
3046
    memcpy(ctl_msg.message, data, len);
3047
    dummy = MG_SEND_FUNC(mgr->ctl[0], (char *) &ctl_msg,
3048
                         offsetof(struct ctl_msg, message) + len, 0);
3049
    dummy = MG_RECV_FUNC(mgr->ctl[0], (char *) &len, 1, 0);
3050
    (void) dummy; /* https://gcc.gnu.org/bugzilla/show_bug.cgi?id=25509 */
3051
  }
3052
}
3053
#endif /* MG_ENABLE_BROADCAST */
3054

    
3055
static int isbyte(int n) {
3056
  return n >= 0 && n <= 255;
3057
}
3058

    
3059
static int parse_net(const char *spec, uint32_t *net, uint32_t *mask) {
3060
  int n, a, b, c, d, slash = 32, len = 0;
3061

    
3062
  if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5 ||
3063
       sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) &&
3064
      isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) && slash >= 0 &&
3065
      slash < 33) {
3066
    len = n;
3067
    *net =
3068
        ((uint32_t) a << 24) | ((uint32_t) b << 16) | ((uint32_t) c << 8) | d;
3069
    *mask = slash ? 0xffffffffU << (32 - slash) : 0;
3070
  }
3071

    
3072
  return len;
3073
}
3074

    
3075
int mg_check_ip_acl(const char *acl, uint32_t remote_ip) {
3076
  int allowed, flag;
3077
  uint32_t net, mask;
3078
  struct mg_str vec;
3079

    
3080
  /* If any ACL is set, deny by default */
3081
  allowed = (acl == NULL || *acl == '\0') ? '+' : '-';
3082

    
3083
  while ((acl = mg_next_comma_list_entry(acl, &vec, NULL)) != NULL) {
3084
    flag = vec.p[0];
3085
    if ((flag != '+' && flag != '-') ||
3086
        parse_net(&vec.p[1], &net, &mask) == 0) {
3087
      return -1;
3088
    }
3089

    
3090
    if (net == (remote_ip & mask)) {
3091
      allowed = flag;
3092
    }
3093
  }
3094

    
3095
  DBG(("%08x %c", (unsigned int) remote_ip, allowed));
3096
  return allowed == '+';
3097
}
3098

    
3099
/* Move data from one connection to another */
3100
void mg_forward(struct mg_connection *from, struct mg_connection *to) {
3101
  mg_send(to, from->recv_mbuf.buf, from->recv_mbuf.len);
3102
  mbuf_remove(&from->recv_mbuf, from->recv_mbuf.len);
3103
}
3104

    
3105
double mg_set_timer(struct mg_connection *c, double timestamp) {
3106
  double result = c->ev_timer_time;
3107
  c->ev_timer_time = timestamp;
3108
  /*
3109
   * If this connection is resolving, it's not in the list of active
3110
   * connections, so not processed yet. It has a DNS resolver connection
3111
   * linked to it. Set up a timer for the DNS connection.
3112
   */
3113
  DBG(("%p %p %d -> %lu", c, c->priv_2, (c->flags & MG_F_RESOLVING ? 1 : 0),
3114
       (unsigned long) timestamp));
3115
  if ((c->flags & MG_F_RESOLVING) && c->priv_2 != NULL) {
3116
    ((struct mg_connection *) c->priv_2)->ev_timer_time = timestamp;
3117
  }
3118
  return result;
3119
}
3120

    
3121
void mg_sock_set(struct mg_connection *nc, sock_t sock) {
3122
  if (sock != INVALID_SOCKET) {
3123
    nc->iface->vtable->sock_set(nc, sock);
3124
  }
3125
}
3126

    
3127
void mg_if_get_conn_addr(struct mg_connection *nc, int remote,
3128
                         union socket_address *sa) {
3129
  nc->iface->vtable->get_conn_addr(nc, remote, sa);
3130
}
3131

    
3132
struct mg_connection *mg_add_sock_opt(struct mg_mgr *s, sock_t sock,
3133
                                      MG_CB(mg_event_handler_t callback,
3134
                                            void *user_data),
3135
                                      struct mg_add_sock_opts opts) {
3136
#if MG_ENABLE_CALLBACK_USERDATA
3137
  opts.user_data = user_data;
3138
#endif
3139

    
3140
  struct mg_connection *nc = mg_create_connection_base(s, callback, opts);
3141
  if (nc != NULL) {
3142
    mg_sock_set(nc, sock);
3143
    mg_add_conn(nc->mgr, nc);
3144
  }
3145
  return nc;
3146
}
3147

    
3148
struct mg_connection *mg_add_sock(struct mg_mgr *s, sock_t sock,
3149
                                  MG_CB(mg_event_handler_t callback,
3150
                                        void *user_data)) {
3151
  struct mg_add_sock_opts opts;
3152
  memset(&opts, 0, sizeof(opts));
3153
  return mg_add_sock_opt(s, sock, MG_CB(callback, user_data), opts);
3154
}
3155

    
3156
double mg_time(void) {
3157
  return cs_time();
3158
}
3159
#ifdef MG_MODULE_LINES
3160
#line 1 "mongoose/src/mg_net_if_socket.h"
3161
#endif
3162
/*
3163
 * Copyright (c) 2014-2016 Cesanta Software Limited
3164
 * All rights reserved
3165
 */
3166

    
3167
#ifndef CS_MONGOOSE_SRC_NET_IF_SOCKET_H_
3168
#define CS_MONGOOSE_SRC_NET_IF_SOCKET_H_
3169

    
3170
/* Amalgamated: #include "mg_net_if.h" */
3171

    
3172
#ifdef __cplusplus
3173
extern "C" {
3174
#endif /* __cplusplus */
3175

    
3176
#ifndef MG_ENABLE_NET_IF_SOCKET
3177
#define MG_ENABLE_NET_IF_SOCKET MG_NET_IF == MG_NET_IF_SOCKET
3178
#endif
3179

    
3180
extern const struct mg_iface_vtable mg_socket_iface_vtable;
3181

    
3182
#ifdef __cplusplus
3183
}
3184
#endif /* __cplusplus */
3185

    
3186
#endif /* CS_MONGOOSE_SRC_NET_IF_SOCKET_H_ */
3187
#ifdef MG_MODULE_LINES
3188
#line 1 "mongoose/src/mg_net_if_socks.h"
3189
#endif
3190
/*
3191
* Copyright (c) 2014-2017 Cesanta Software Limited
3192
* All rights reserved
3193
*/
3194

    
3195
#ifndef CS_MONGOOSE_SRC_NET_IF_SOCKS_H_
3196
#define CS_MONGOOSE_SRC_NET_IF_SOCKS_H_
3197

    
3198
#if MG_ENABLE_SOCKS
3199
/* Amalgamated: #include "mg_net_if.h" */
3200

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

    
3205
extern const struct mg_iface_vtable mg_socks_iface_vtable;
3206

    
3207
#ifdef __cplusplus
3208
}
3209
#endif /* __cplusplus */
3210
#endif /* MG_ENABLE_SOCKS */
3211
#endif /* CS_MONGOOSE_SRC_NET_IF_SOCKS_H_ */
3212
#ifdef MG_MODULE_LINES
3213
#line 1 "mongoose/src/mg_net_if.c"
3214
#endif
3215
/* Amalgamated: #include "mg_net_if.h" */
3216
/* Amalgamated: #include "mg_internal.h" */
3217
/* Amalgamated: #include "mg_net_if_socket.h" */
3218

    
3219
extern const struct mg_iface_vtable mg_default_iface_vtable;
3220

    
3221
const struct mg_iface_vtable *mg_ifaces[] = {
3222
    &mg_default_iface_vtable,
3223
};
3224

    
3225
int mg_num_ifaces = (int) (sizeof(mg_ifaces) / sizeof(mg_ifaces[0]));
3226

    
3227
struct mg_iface *mg_if_create_iface(const struct mg_iface_vtable *vtable,
3228
                                    struct mg_mgr *mgr) {
3229
  struct mg_iface *iface = (struct mg_iface *) MG_CALLOC(1, sizeof(*iface));
3230
  iface->mgr = mgr;
3231
  iface->data = NULL;
3232
  iface->vtable = vtable;
3233
  return iface;
3234
}
3235

    
3236
struct mg_iface *mg_find_iface(struct mg_mgr *mgr,
3237
                               const struct mg_iface_vtable *vtable,
3238
                               struct mg_iface *from) {
3239
  int i = 0;
3240
  if (from != NULL) {
3241
    for (i = 0; i < mgr->num_ifaces; i++) {
3242
      if (mgr->ifaces[i] == from) {
3243
        i++;
3244
        break;
3245
      }
3246
    }
3247
  }
3248

    
3249
  for (; i < mgr->num_ifaces; i++) {
3250
    if (mgr->ifaces[i]->vtable == vtable) {
3251
      return mgr->ifaces[i];
3252
    }
3253
  }
3254
  return NULL;
3255
}
3256
#ifdef MG_MODULE_LINES
3257
#line 1 "mongoose/src/mg_net_if_socket.c"
3258
#endif
3259
/*
3260
 * Copyright (c) 2014-2016 Cesanta Software Limited
3261
 * All rights reserved
3262
 */
3263

    
3264
#if MG_ENABLE_NET_IF_SOCKET
3265

    
3266
/* Amalgamated: #include "mg_net_if_socket.h" */
3267
/* Amalgamated: #include "mg_internal.h" */
3268
/* Amalgamated: #include "mg_util.h" */
3269

    
3270
#define MG_TCP_RECV_BUFFER_SIZE 1024
3271
#define MG_UDP_RECV_BUFFER_SIZE 1500
3272

    
3273
static sock_t mg_open_listening_socket(union socket_address *sa, int type,
3274
                                       int proto);
3275
#if MG_ENABLE_SSL
3276
static void mg_ssl_begin(struct mg_connection *nc);
3277
#endif
3278

    
3279
void mg_set_non_blocking_mode(sock_t sock) {
3280
#ifdef _WIN32
3281
  unsigned long on = 1;
3282
  ioctlsocket(sock, FIONBIO, &on);
3283
#else
3284
  int flags = fcntl(sock, F_GETFL, 0);
3285
  fcntl(sock, F_SETFL, flags | O_NONBLOCK);
3286
#endif
3287
}
3288

    
3289
static int mg_is_error(void) {
3290
  int err = mg_get_errno();
3291
  return err != EINPROGRESS && err != EWOULDBLOCK
3292
#ifndef WINCE
3293
         && err != EAGAIN && err != EINTR
3294
#endif
3295
#ifdef _WIN32
3296
         && WSAGetLastError() != WSAEINTR && WSAGetLastError() != WSAEWOULDBLOCK
3297
#endif
3298
      ;
3299
}
3300

    
3301
void mg_socket_if_connect_tcp(struct mg_connection *nc,
3302
                              const union socket_address *sa) {
3303
  int rc, proto = 0;
3304
  nc->sock = socket(AF_INET, SOCK_STREAM, proto);
3305
  if (nc->sock == INVALID_SOCKET) {
3306
    nc->err = mg_get_errno() ? mg_get_errno() : 1;
3307
    return;
3308
  }
3309
#if !defined(MG_ESP8266)
3310
  mg_set_non_blocking_mode(nc->sock);
3311
#endif
3312
  rc = connect(nc->sock, &sa->sa, sizeof(sa->sin));
3313
  nc->err = rc < 0 && mg_is_error() ? mg_get_errno() : 0;
3314
  DBG(("%p sock %d rc %d errno %d err %d", nc, nc->sock, rc, mg_get_errno(),
3315
       nc->err));
3316
}
3317

    
3318
void mg_socket_if_connect_udp(struct mg_connection *nc) {
3319
  nc->sock = socket(AF_INET, SOCK_DGRAM, 0);
3320
  if (nc->sock == INVALID_SOCKET) {
3321
    nc->err = mg_get_errno() ? mg_get_errno() : 1;
3322
    return;
3323
  }
3324
  if (nc->flags & MG_F_ENABLE_BROADCAST) {
3325
    int optval = 1;
3326
    if (setsockopt(nc->sock, SOL_SOCKET, SO_BROADCAST, (const char *) &optval,
3327
                   sizeof(optval)) < 0) {
3328
      nc->err = mg_get_errno() ? mg_get_errno() : 1;
3329
      return;
3330
    }
3331
  }
3332
  nc->err = 0;
3333
}
3334

    
3335
int mg_socket_if_listen_tcp(struct mg_connection *nc,
3336
                            union socket_address *sa) {
3337
  int proto = 0;
3338
  sock_t sock = mg_open_listening_socket(sa, SOCK_STREAM, proto);
3339
  if (sock == INVALID_SOCKET) {
3340
    return (mg_get_errno() ? mg_get_errno() : 1);
3341
  }
3342
  mg_sock_set(nc, sock);
3343
  return 0;
3344
}
3345

    
3346
int mg_socket_if_listen_udp(struct mg_connection *nc,
3347
                            union socket_address *sa) {
3348
  sock_t sock = mg_open_listening_socket(sa, SOCK_DGRAM, 0);
3349
  if (sock == INVALID_SOCKET) return (mg_get_errno() ? mg_get_errno() : 1);
3350
  mg_sock_set(nc, sock);
3351
  return 0;
3352
}
3353

    
3354
void mg_socket_if_tcp_send(struct mg_connection *nc, const void *buf,
3355
                           size_t len) {
3356
  mbuf_append(&nc->send_mbuf, buf, len);
3357
}
3358

    
3359
void mg_socket_if_udp_send(struct mg_connection *nc, const void *buf,
3360
                           size_t len) {
3361
  mbuf_append(&nc->send_mbuf, buf, len);
3362
}
3363

    
3364
void mg_socket_if_recved(struct mg_connection *nc, size_t len) {
3365
  (void) nc;
3366
  (void) len;
3367
}
3368

    
3369
int mg_socket_if_create_conn(struct mg_connection *nc) {
3370
  (void) nc;
3371
  return 1;
3372
}
3373

    
3374
void mg_socket_if_destroy_conn(struct mg_connection *nc) {
3375
  if (nc->sock == INVALID_SOCKET) return;
3376
  if (!(nc->flags & MG_F_UDP)) {
3377
    closesocket(nc->sock);
3378
  } else {
3379
    /* Only close outgoing UDP sockets or listeners. */
3380
    if (nc->listener == NULL) closesocket(nc->sock);
3381
  }
3382
  nc->sock = INVALID_SOCKET;
3383
}
3384

    
3385
static int mg_accept_conn(struct mg_connection *lc) {
3386
  struct mg_connection *nc;
3387
  union socket_address sa;
3388
  socklen_t sa_len = sizeof(sa);
3389
  /* NOTE(lsm): on Windows, sock is always > FD_SETSIZE */
3390
  sock_t sock = accept(lc->sock, &sa.sa, &sa_len);
3391
  if (sock == INVALID_SOCKET) {
3392
    if (mg_is_error()) DBG(("%p: failed to accept: %d", lc, mg_get_errno()));
3393
    return 0;
3394
  }
3395
  nc = mg_if_accept_new_conn(lc);
3396
  if (nc == NULL) {
3397
    closesocket(sock);
3398
    return 0;
3399
  }
3400
  DBG(("%p conn from %s:%d", nc, inet_ntoa(sa.sin.sin_addr),
3401
       ntohs(sa.sin.sin_port)));
3402
  mg_sock_set(nc, sock);
3403
#if MG_ENABLE_SSL
3404
  if (lc->flags & MG_F_SSL) {
3405
    if (mg_ssl_if_conn_accept(nc, lc) != MG_SSL_OK) mg_close_conn(nc);
3406
  } else
3407
#endif
3408
  {
3409
    mg_if_accept_tcp_cb(nc, &sa, sa_len);
3410
  }
3411
  return 1;
3412
}
3413

    
3414
/* 'sa' must be an initialized address to bind to */
3415
static sock_t mg_open_listening_socket(union socket_address *sa, int type,
3416
                                       int proto) {
3417
  socklen_t sa_len =
3418
      (sa->sa.sa_family == AF_INET) ? sizeof(sa->sin) : sizeof(sa->sin6);
3419
  sock_t sock = INVALID_SOCKET;
3420
#if !MG_LWIP
3421
  int on = 1;
3422
#endif
3423

    
3424
  if ((sock = socket(sa->sa.sa_family, type, proto)) != INVALID_SOCKET &&
3425
#if !MG_LWIP /* LWIP doesn't support either */
3426
#if defined(_WIN32) && defined(SO_EXCLUSIVEADDRUSE) && !defined(WINCE)
3427
      /* "Using SO_REUSEADDR and SO_EXCLUSIVEADDRUSE" http://goo.gl/RmrFTm */
3428
      !setsockopt(sock, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (void *) &on,
3429
                  sizeof(on)) &&
3430
#endif
3431

    
3432
#if !defined(_WIN32) || !defined(SO_EXCLUSIVEADDRUSE)
3433
      /*
3434
       * SO_RESUSEADDR is not enabled on Windows because the semantics of
3435
       * SO_REUSEADDR on UNIX and Windows is different. On Windows,
3436
       * SO_REUSEADDR allows to bind a socket to a port without error even if
3437
       * the port is already open by another program. This is not the behavior
3438
       * SO_REUSEADDR was designed for, and leads to hard-to-track failure
3439
       * scenarios. Therefore, SO_REUSEADDR was disabled on Windows unless
3440
       * SO_EXCLUSIVEADDRUSE is supported and set on a socket.
3441
       */
3442
      !setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *) &on, sizeof(on)) &&
3443
#endif
3444
#endif /* !MG_LWIP */
3445

    
3446
      !bind(sock, &sa->sa, sa_len) &&
3447
      (type == SOCK_DGRAM || listen(sock, SOMAXCONN) == 0)) {
3448
#if !MG_LWIP
3449
    mg_set_non_blocking_mode(sock);
3450
    /* In case port was set to 0, get the real port number */
3451
    (void) getsockname(sock, &sa->sa, &sa_len);
3452
#endif
3453
  } else if (sock != INVALID_SOCKET) {
3454
    closesocket(sock);
3455
    sock = INVALID_SOCKET;
3456
  }
3457

    
3458
  return sock;
3459
}
3460

    
3461
static void mg_write_to_socket(struct mg_connection *nc) {
3462
  struct mbuf *io = &nc->send_mbuf;
3463
  int n = 0;
3464

    
3465
#if MG_LWIP
3466
  /* With LWIP we don't know if the socket is ready */
3467
  if (io->len == 0) return;
3468
#endif
3469

    
3470
  assert(io->len > 0);
3471

    
3472
  if (nc->flags & MG_F_UDP) {
3473
    int n =
3474
        sendto(nc->sock, io->buf, io->len, 0, &nc->sa.sa, sizeof(nc->sa.sin));
3475
    DBG(("%p %d %d %d %s:%hu", nc, nc->sock, n, mg_get_errno(),
3476
         inet_ntoa(nc->sa.sin.sin_addr), ntohs(nc->sa.sin.sin_port)));
3477
    mg_if_sent_cb(nc, n);
3478
    return;
3479
  }
3480

    
3481
#if MG_ENABLE_SSL
3482
  if (nc->flags & MG_F_SSL) {
3483
    if (nc->flags & MG_F_SSL_HANDSHAKE_DONE) {
3484
      n = mg_ssl_if_write(nc, io->buf, io->len);
3485
      DBG(("%p %d bytes -> %d (SSL)", nc, n, nc->sock));
3486
      if (n < 0) {
3487
        if (n != MG_SSL_WANT_READ && n != MG_SSL_WANT_WRITE) {
3488
          nc->flags |= MG_F_CLOSE_IMMEDIATELY;
3489
        }
3490
        return;
3491
      } else {
3492
        /* Successful SSL operation, clear off SSL wait flags */
3493
        nc->flags &= ~(MG_F_WANT_READ | MG_F_WANT_WRITE);
3494
      }
3495
    } else {
3496
      mg_ssl_begin(nc);
3497
      return;
3498
    }
3499
  } else
3500
#endif
3501
  {
3502
    n = (int) MG_SEND_FUNC(nc->sock, io->buf, io->len, 0);
3503
    DBG(("%p %d bytes -> %d", nc, n, nc->sock));
3504
  }
3505

    
3506
  mg_if_sent_cb(nc, n);
3507
}
3508

    
3509
MG_INTERNAL size_t recv_avail_size(struct mg_connection *conn, size_t max) {
3510
  size_t avail;
3511
  if (conn->recv_mbuf_limit < conn->recv_mbuf.len) return 0;
3512
  avail = conn->recv_mbuf_limit - conn->recv_mbuf.len;
3513
  return avail > max ? max : avail;
3514
}
3515

    
3516
static void mg_handle_tcp_read(struct mg_connection *conn) {
3517
  int n = 0;
3518
  char *buf = (char *) MG_MALLOC(MG_TCP_RECV_BUFFER_SIZE);
3519

    
3520
  if (buf == NULL) {
3521
    DBG(("OOM"));
3522
    return;
3523
  }
3524

    
3525
#if MG_ENABLE_SSL
3526
  if (conn->flags & MG_F_SSL) {
3527
    if (conn->flags & MG_F_SSL_HANDSHAKE_DONE) {
3528
      /* SSL library may have more bytes ready to read than we ask to read.
3529
       * Therefore, read in a loop until we read everything. Without the loop,
3530
       * we skip to the next select() cycle which can just timeout. */
3531
      while ((n = mg_ssl_if_read(conn, buf, MG_TCP_RECV_BUFFER_SIZE)) > 0) {
3532
        DBG(("%p %d bytes <- %d (SSL)", conn, n, conn->sock));
3533
        mg_if_recv_tcp_cb(conn, buf, n, 1 /* own */);
3534
        buf = NULL;
3535
        if (conn->flags & MG_F_CLOSE_IMMEDIATELY) break;
3536
        /* buf has been freed, we need a new one. */
3537
        buf = (char *) MG_MALLOC(MG_TCP_RECV_BUFFER_SIZE);
3538
        if (buf == NULL) break;
3539
      }
3540
      MG_FREE(buf);
3541
      if (n < 0 && n != MG_SSL_WANT_READ) conn->flags |= MG_F_CLOSE_IMMEDIATELY;
3542
    } else {
3543
      MG_FREE(buf);
3544
      mg_ssl_begin(conn);
3545
      return;
3546
    }
3547
  } else
3548
#endif
3549
  {
3550
    n = (int) MG_RECV_FUNC(conn->sock, buf,
3551
                           recv_avail_size(conn, MG_TCP_RECV_BUFFER_SIZE), 0);
3552
    DBG(("%p %d bytes (PLAIN) <- %d", conn, n, conn->sock));
3553
    if (n > 0) {
3554
      mg_if_recv_tcp_cb(conn, buf, n, 1 /* own */);
3555
    } else {
3556
      MG_FREE(buf);
3557
    }
3558
    if (n == 0) {
3559
      /* Orderly shutdown of the socket, try flushing output. */
3560
      conn->flags |= MG_F_SEND_AND_CLOSE;
3561
    } else if (n < 0 && mg_is_error()) {
3562
      conn->flags |= MG_F_CLOSE_IMMEDIATELY;
3563
    }
3564
  }
3565
}
3566

    
3567
static int mg_recvfrom(struct mg_connection *nc, union socket_address *sa,
3568
                       socklen_t *sa_len, char **buf) {
3569
  int n;
3570
  *buf = (char *) MG_MALLOC(MG_UDP_RECV_BUFFER_SIZE);
3571
  if (*buf == NULL) {
3572
    DBG(("Out of memory"));
3573
    return -ENOMEM;
3574
  }
3575
  n = recvfrom(nc->sock, *buf, MG_UDP_RECV_BUFFER_SIZE, 0, &sa->sa, sa_len);
3576
  if (n <= 0) {
3577
    DBG(("%p recvfrom: %s", nc, strerror(mg_get_errno())));
3578
    MG_FREE(*buf);
3579
  }
3580
  return n;
3581
}
3582

    
3583
static void mg_handle_udp_read(struct mg_connection *nc) {
3584
  char *buf = NULL;
3585
  union socket_address sa;
3586
  socklen_t sa_len = sizeof(sa);
3587
  int n = mg_recvfrom(nc, &sa, &sa_len, &buf);
3588
  DBG(("%p %d bytes from %s:%d", nc, n, inet_ntoa(nc->sa.sin.sin_addr),
3589
       ntohs(nc->sa.sin.sin_port)));
3590
  mg_if_recv_udp_cb(nc, buf, n, &sa, sa_len);
3591
}
3592

    
3593
#if MG_ENABLE_SSL
3594
static void mg_ssl_begin(struct mg_connection *nc) {
3595
  int server_side = (nc->listener != NULL);
3596
  enum mg_ssl_if_result res = mg_ssl_if_handshake(nc);
3597
  DBG(("%p %d res %d", nc, server_side, res));
3598

    
3599
  if (res == MG_SSL_OK) {
3600
    nc->flags |= MG_F_SSL_HANDSHAKE_DONE;
3601
    nc->flags &= ~(MG_F_WANT_READ | MG_F_WANT_WRITE);
3602

    
3603
    if (server_side) {
3604
      union socket_address sa;
3605
      socklen_t sa_len = sizeof(sa);
3606
      (void) getpeername(nc->sock, &sa.sa, &sa_len);
3607
      mg_if_accept_tcp_cb(nc, &sa, sa_len);
3608
    } else {
3609
      mg_if_connect_cb(nc, 0);
3610
    }
3611
  } else if (res != MG_SSL_WANT_READ && res != MG_SSL_WANT_WRITE) {
3612
    if (!server_side) {
3613
      mg_if_connect_cb(nc, res);
3614
    }
3615
    nc->flags |= MG_F_CLOSE_IMMEDIATELY;
3616
  }
3617
}
3618
#endif /* MG_ENABLE_SSL */
3619

    
3620
#define _MG_F_FD_CAN_READ 1
3621
#define _MG_F_FD_CAN_WRITE 1 << 1
3622
#define _MG_F_FD_ERROR 1 << 2
3623

    
3624
void mg_mgr_handle_conn(struct mg_connection *nc, int fd_flags, double now) {
3625
  int worth_logging =
3626
      fd_flags != 0 || (nc->flags & (MG_F_WANT_READ | MG_F_WANT_WRITE));
3627
  if (worth_logging) {
3628
    DBG(("%p fd=%d fd_flags=%d nc_flags=%lu rmbl=%d smbl=%d", nc, nc->sock,
3629
         fd_flags, nc->flags, (int) nc->recv_mbuf.len,
3630
         (int) nc->send_mbuf.len));
3631
  }
3632

    
3633
  if (nc->flags & MG_F_CONNECTING) {
3634
    if (fd_flags != 0) {
3635
      int err = 0;
3636
#if !defined(MG_ESP8266)
3637
      if (!(nc->flags & MG_F_UDP)) {
3638
        socklen_t len = sizeof(err);
3639
        int ret =
3640
            getsockopt(nc->sock, SOL_SOCKET, SO_ERROR, (char *) &err, &len);
3641
        if (ret != 0) {
3642
          err = 1;
3643
        } else if (err == EAGAIN || err == EWOULDBLOCK) {
3644
          err = 0;
3645
        }
3646
      }
3647
#else
3648
      /*
3649
       * On ESP8266 we use blocking connect.
3650
       */
3651
      err = nc->err;
3652
#endif
3653
#if MG_ENABLE_SSL
3654
      if ((nc->flags & MG_F_SSL) && err == 0) {
3655
        mg_ssl_begin(nc);
3656
      } else {
3657
        mg_if_connect_cb(nc, err);
3658
      }
3659
#else
3660
      mg_if_connect_cb(nc, err);
3661
#endif
3662
    } else if (nc->err != 0) {
3663
      mg_if_connect_cb(nc, nc->err);
3664
    }
3665
  }
3666

    
3667
  if (fd_flags & _MG_F_FD_CAN_READ) {
3668
    if (nc->flags & MG_F_UDP) {
3669
      mg_handle_udp_read(nc);
3670
    } else {
3671
      if (nc->flags & MG_F_LISTENING) {
3672
        /*
3673
         * We're not looping here, and accepting just one connection at
3674
         * a time. The reason is that eCos does not respect non-blocking
3675
         * flag on a listening socket and hangs in a loop.
3676
         */
3677
        mg_accept_conn(nc);
3678
      } else {
3679
        mg_handle_tcp_read(nc);
3680
      }
3681
    }
3682
  }
3683

    
3684
  if (!(nc->flags & MG_F_CLOSE_IMMEDIATELY)) {
3685
    if ((fd_flags & _MG_F_FD_CAN_WRITE) && nc->send_mbuf.len > 0) {
3686
      mg_write_to_socket(nc);
3687
    }
3688
    mg_if_poll(nc, (time_t) now);
3689
    mg_if_timer(nc, now);
3690
  }
3691

    
3692
  if (worth_logging) {
3693
    DBG(("%p after fd=%d nc_flags=%lu rmbl=%d smbl=%d", nc, nc->sock, nc->flags,
3694
         (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len));
3695
  }
3696
}
3697

    
3698
#if MG_ENABLE_BROADCAST
3699
static void mg_mgr_handle_ctl_sock(struct mg_mgr *mgr) {
3700
  struct ctl_msg ctl_msg;
3701
  int len =
3702
      (int) MG_RECV_FUNC(mgr->ctl[1], (char *) &ctl_msg, sizeof(ctl_msg), 0);
3703
  size_t dummy = MG_SEND_FUNC(mgr->ctl[1], ctl_msg.message, 1, 0);
3704
  DBG(("read %d from ctl socket", len));
3705
  (void) dummy; /* https://gcc.gnu.org/bugzilla/show_bug.cgi?id=25509 */
3706
  if (len >= (int) sizeof(ctl_msg.callback) && ctl_msg.callback != NULL) {
3707
    struct mg_connection *nc;
3708
    for (nc = mg_next(mgr, NULL); nc != NULL; nc = mg_next(mgr, nc)) {
3709
      ctl_msg.callback(nc, MG_EV_POLL,
3710
                       ctl_msg.message MG_UD_ARG(nc->user_data));
3711
    }
3712
  }
3713
}
3714
#endif
3715

    
3716
/* Associate a socket to a connection. */
3717
void mg_socket_if_sock_set(struct mg_connection *nc, sock_t sock) {
3718
  mg_set_non_blocking_mode(sock);
3719
  mg_set_close_on_exec(sock);
3720
  nc->sock = sock;
3721
  DBG(("%p %d", nc, sock));
3722
}
3723

    
3724
void mg_socket_if_init(struct mg_iface *iface) {
3725
  (void) iface;
3726
  DBG(("%p using select()", iface->mgr));
3727
#if MG_ENABLE_BROADCAST
3728
  mg_socketpair(iface->mgr->ctl, SOCK_DGRAM);
3729
#endif
3730
}
3731

    
3732
void mg_socket_if_free(struct mg_iface *iface) {
3733
  (void) iface;
3734
}
3735

    
3736
void mg_socket_if_add_conn(struct mg_connection *nc) {
3737
  (void) nc;
3738
}
3739

    
3740
void mg_socket_if_remove_conn(struct mg_connection *nc) {
3741
  (void) nc;
3742
}
3743

    
3744
void mg_add_to_set(sock_t sock, fd_set *set, sock_t *max_fd) {
3745
  if (sock != INVALID_SOCKET
3746
#ifdef __unix__
3747
      && sock < (sock_t) FD_SETSIZE
3748
#endif
3749
      ) {
3750
    FD_SET(sock, set);
3751
    if (*max_fd == INVALID_SOCKET || sock > *max_fd) {
3752
      *max_fd = sock;
3753
    }
3754
  }
3755
}
3756

    
3757
time_t mg_socket_if_poll(struct mg_iface *iface, int timeout_ms) {
3758
  struct mg_mgr *mgr = iface->mgr;
3759
  double now = mg_time();
3760
  double min_timer;
3761
  struct mg_connection *nc, *tmp;
3762
  struct timeval tv;
3763
  fd_set read_set, write_set, err_set;
3764
  sock_t max_fd = INVALID_SOCKET;
3765
  int num_fds, num_ev, num_timers = 0;
3766
#ifdef __unix__
3767
  int try_dup = 1;
3768
#endif
3769

    
3770
  FD_ZERO(&read_set);
3771
  FD_ZERO(&write_set);
3772
  FD_ZERO(&err_set);
3773
#if MG_ENABLE_BROADCAST
3774
  mg_add_to_set(mgr->ctl[1], &read_set, &max_fd);
3775
#endif
3776

    
3777
  /*
3778
   * Note: it is ok to have connections with sock == INVALID_SOCKET in the list,
3779
   * e.g. timer-only "connections".
3780
   */
3781
  min_timer = 0;
3782
  for (nc = mgr->active_connections, num_fds = 0; nc != NULL; nc = tmp) {
3783
    tmp = nc->next;
3784

    
3785
    if (nc->sock != INVALID_SOCKET) {
3786
      num_fds++;
3787

    
3788
#ifdef __unix__
3789
      /* A hack to make sure all our file descriptos fit into FD_SETSIZE. */
3790
      if (nc->sock >= (sock_t) FD_SETSIZE && try_dup) {
3791
        int new_sock = dup(nc->sock);
3792
        if (new_sock >= 0) {
3793
          if (new_sock < (sock_t) FD_SETSIZE) {
3794
            closesocket(nc->sock);
3795
            DBG(("new sock %d -> %d", nc->sock, new_sock));
3796
            nc->sock = new_sock;
3797
          } else {
3798
            closesocket(new_sock);
3799
            DBG(("new sock is still larger than FD_SETSIZE, disregard"));
3800
            try_dup = 0;
3801
          }
3802
        } else {
3803
          try_dup = 0;
3804
        }
3805
      }
3806
#endif
3807

    
3808
      if (!(nc->flags & MG_F_WANT_WRITE) &&
3809
          nc->recv_mbuf.len < nc->recv_mbuf_limit &&
3810
          (!(nc->flags & MG_F_UDP) || nc->listener == NULL)) {
3811
        mg_add_to_set(nc->sock, &read_set, &max_fd);
3812
      }
3813

    
3814
      if (((nc->flags & MG_F_CONNECTING) && !(nc->flags & MG_F_WANT_READ)) ||
3815
          (nc->send_mbuf.len > 0 && !(nc->flags & MG_F_CONNECTING))) {
3816
        mg_add_to_set(nc->sock, &write_set, &max_fd);
3817
        mg_add_to_set(nc->sock, &err_set, &max_fd);
3818
      }
3819
    }
3820

    
3821
    if (nc->ev_timer_time > 0) {
3822
      if (num_timers == 0 || nc->ev_timer_time < min_timer) {
3823
        min_timer = nc->ev_timer_time;
3824
      }
3825
      num_timers++;
3826
    }
3827
  }
3828

    
3829
  /*
3830
   * If there is a timer to be fired earlier than the requested timeout,
3831
   * adjust the timeout.
3832
   */
3833
  if (num_timers > 0) {
3834
    double timer_timeout_ms = (min_timer - mg_time()) * 1000 + 1 /* rounding */;
3835
    if (timer_timeout_ms < timeout_ms) {
3836
      timeout_ms = (int) timer_timeout_ms;
3837
    }
3838
  }
3839
  if (timeout_ms < 0) timeout_ms = 0;
3840

    
3841
  tv.tv_sec = timeout_ms / 1000;
3842
  tv.tv_usec = (timeout_ms % 1000) * 1000;
3843

    
3844
  num_ev = select((int) max_fd + 1, &read_set, &write_set, &err_set, &tv);
3845
  now = mg_time();
3846
#if 0
3847
  DBG(("select @ %ld num_ev=%d of %d, timeout=%d", (long) now, num_ev, num_fds,
3848
       timeout_ms));
3849
#endif
3850

    
3851
#if MG_ENABLE_BROADCAST
3852
  if (num_ev > 0 && mgr->ctl[1] != INVALID_SOCKET &&
3853
      FD_ISSET(mgr->ctl[1], &read_set)) {
3854
    mg_mgr_handle_ctl_sock(mgr);
3855
  }
3856
#endif
3857

    
3858
  for (nc = mgr->active_connections; nc != NULL; nc = tmp) {
3859
    int fd_flags = 0;
3860
    if (nc->sock != INVALID_SOCKET) {
3861
      if (num_ev > 0) {
3862
        fd_flags = (FD_ISSET(nc->sock, &read_set) &&
3863
                            (!(nc->flags & MG_F_UDP) || nc->listener == NULL)
3864
                        ? _MG_F_FD_CAN_READ
3865
                        : 0) |
3866
                   (FD_ISSET(nc->sock, &write_set) ? _MG_F_FD_CAN_WRITE : 0) |
3867
                   (FD_ISSET(nc->sock, &err_set) ? _MG_F_FD_ERROR : 0);
3868
      }
3869
#if MG_LWIP
3870
      /* With LWIP socket emulation layer, we don't get write events for UDP */
3871
      if ((nc->flags & MG_F_UDP) && nc->listener == NULL) {
3872
        fd_flags |= _MG_F_FD_CAN_WRITE;
3873
      }
3874
#endif
3875
    }
3876
    tmp = nc->next;
3877
    mg_mgr_handle_conn(nc, fd_flags, now);
3878
  }
3879

    
3880
  for (nc = mgr->active_connections; nc != NULL; nc = tmp) {
3881
    tmp = nc->next;
3882
    if ((nc->flags & MG_F_CLOSE_IMMEDIATELY) ||
3883
        (nc->send_mbuf.len == 0 && (nc->flags & MG_F_SEND_AND_CLOSE))) {
3884
      mg_close_conn(nc);
3885
    }
3886
  }
3887

    
3888
  return (time_t) now;
3889
}
3890

    
3891
#if MG_ENABLE_BROADCAST
3892
MG_INTERNAL void mg_socketpair_close(sock_t *sock) {
3893
  while (1) {
3894
    if (closesocket(*sock) == -1 && errno == EINTR) continue;
3895
    break;
3896
  }
3897
  *sock = INVALID_SOCKET;
3898
}
3899

    
3900
MG_INTERNAL sock_t
3901
mg_socketpair_accept(sock_t sock, union socket_address *sa, socklen_t sa_len) {
3902
  sock_t rc;
3903
  while (1) {
3904
    if ((rc = accept(sock, &sa->sa, &sa_len)) == INVALID_SOCKET &&
3905
        errno == EINTR)
3906
      continue;
3907
    break;
3908
  }
3909
  return rc;
3910
}
3911

    
3912
int mg_socketpair(sock_t sp[2], int sock_type) {
3913
  union socket_address sa;
3914
  sock_t sock;
3915
  socklen_t len = sizeof(sa.sin);
3916
  int ret = 0;
3917

    
3918
  sock = sp[0] = sp[1] = INVALID_SOCKET;
3919

    
3920
  (void) memset(&sa, 0, sizeof(sa));
3921
  sa.sin.sin_family = AF_INET;
3922
  sa.sin.sin_port = htons(0);
3923
  sa.sin.sin_addr.s_addr = htonl(0x7f000001); /* 127.0.0.1 */
3924

    
3925
  if ((sock = socket(AF_INET, sock_type, 0)) == INVALID_SOCKET) {
3926
  } else if (bind(sock, &sa.sa, len) != 0) {
3927
  } else if (sock_type == SOCK_STREAM && listen(sock, 1) != 0) {
3928
  } else if (getsockname(sock, &sa.sa, &len) != 0) {
3929
  } else if ((sp[0] = socket(AF_INET, sock_type, 0)) == INVALID_SOCKET) {
3930
  } else if (connect(sp[0], &sa.sa, len) != 0) {
3931
  } else if (sock_type == SOCK_DGRAM &&
3932
             (getsockname(sp[0], &sa.sa, &len) != 0 ||
3933
              connect(sock, &sa.sa, len) != 0)) {
3934
  } else if ((sp[1] = (sock_type == SOCK_DGRAM ? sock : mg_socketpair_accept(
3935
                                                            sock, &sa, len))) ==
3936
             INVALID_SOCKET) {
3937
  } else {
3938
    mg_set_close_on_exec(sp[0]);
3939
    mg_set_close_on_exec(sp[1]);
3940
    if (sock_type == SOCK_STREAM) mg_socketpair_close(&sock);
3941
    ret = 1;
3942
  }
3943

    
3944
  if (!ret) {
3945
    if (sp[0] != INVALID_SOCKET) mg_socketpair_close(&sp[0]);
3946
    if (sp[1] != INVALID_SOCKET) mg_socketpair_close(&sp[1]);
3947
    if (sock != INVALID_SOCKET) mg_socketpair_close(&sock);
3948
  }
3949

    
3950
  return ret;
3951
}
3952
#endif /* MG_ENABLE_BROADCAST */
3953

    
3954
static void mg_sock_get_addr(sock_t sock, int remote,
3955
                             union socket_address *sa) {
3956
  socklen_t slen = sizeof(*sa);
3957
  memset(sa, 0, slen);
3958
  if (remote) {
3959
    getpeername(sock, &sa->sa, &slen);
3960
  } else {
3961
    getsockname(sock, &sa->sa, &slen);
3962
  }
3963
}
3964

    
3965
void mg_sock_to_str(sock_t sock, char *buf, size_t len, int flags) {
3966
  union socket_address sa;
3967
  mg_sock_get_addr(sock, flags & MG_SOCK_STRINGIFY_REMOTE, &sa);
3968
  mg_sock_addr_to_str(&sa, buf, len, flags);
3969
}
3970

    
3971
void mg_socket_if_get_conn_addr(struct mg_connection *nc, int remote,
3972
                                union socket_address *sa) {
3973
  if ((nc->flags & MG_F_UDP) && remote) {
3974
    memcpy(sa, &nc->sa, sizeof(*sa));
3975
    return;
3976
  }
3977
  mg_sock_get_addr(nc->sock, remote, sa);
3978
}
3979

    
3980
/* clang-format off */
3981
#define MG_SOCKET_IFACE_VTABLE                                          \
3982
  {                                                                     \
3983
    mg_socket_if_init,                                                  \
3984
    mg_socket_if_free,                                                  \
3985
    mg_socket_if_add_conn,                                              \
3986
    mg_socket_if_remove_conn,                                           \
3987
    mg_socket_if_poll,                                                  \
3988
    mg_socket_if_listen_tcp,                                            \
3989
    mg_socket_if_listen_udp,                                            \
3990
    mg_socket_if_connect_tcp,                                           \
3991
    mg_socket_if_connect_udp,                                           \
3992
    mg_socket_if_tcp_send,                                              \
3993
    mg_socket_if_udp_send,                                              \
3994
    mg_socket_if_recved,                                                \
3995
    mg_socket_if_create_conn,                                           \
3996
    mg_socket_if_destroy_conn,                                          \
3997
    mg_socket_if_sock_set,                                              \
3998
    mg_socket_if_get_conn_addr,                                         \
3999
  }
4000
/* clang-format on */
4001

    
4002
const struct mg_iface_vtable mg_socket_iface_vtable = MG_SOCKET_IFACE_VTABLE;
4003
#if MG_NET_IF == MG_NET_IF_SOCKET
4004
const struct mg_iface_vtable mg_default_iface_vtable = MG_SOCKET_IFACE_VTABLE;
4005
#endif
4006

    
4007
#endif /* MG_ENABLE_NET_IF_SOCKET */
4008
#ifdef MG_MODULE_LINES
4009
#line 1 "mongoose/src/mg_net_if_socks.c"
4010
#endif
4011
/*
4012
 * Copyright (c) 2014-2016 Cesanta Software Limited
4013
 * All rights reserved
4014
 */
4015

    
4016
#if MG_ENABLE_SOCKS
4017

    
4018
struct socksdata {
4019
  char *proxy_addr;        /* HOST:PORT of the socks5 proxy server */
4020
  struct mg_connection *s; /* Respective connection to the server */
4021
  struct mg_connection *c; /* Connection to the client */
4022
  struct mbuf tmp;         /* Temporary buffer for sent data */
4023
};
4024

    
4025
static void socks_if_disband(struct socksdata *d) {
4026
  LOG(LL_DEBUG, ("disbanding proxy %p %p", d->c, d->s));
4027
  if (d->c) d->c->flags |= MG_F_SEND_AND_CLOSE;
4028
  if (d->s) d->s->flags |= MG_F_SEND_AND_CLOSE;
4029
  d->c = d->s = NULL;
4030
}
4031

    
4032
static void socks_if_handler(struct mg_connection *c, int ev, void *ev_data) {
4033
  struct socksdata *d = (struct socksdata *) c->user_data;
4034
  if (ev == MG_EV_CONNECT) {
4035
    int res = *(int *) ev_data;
4036
    if (res == 0) {
4037
      /* Send handshake to the proxy server */
4038
      unsigned char buf[] = {MG_SOCKS_VERSION, 1, MG_SOCKS_HANDSHAKE_NOAUTH};
4039
      mg_send(d->s, buf, sizeof(buf));
4040
      LOG(LL_DEBUG, ("Sent handshake to %s", d->proxy_addr));
4041
    } else {
4042
      LOG(LL_ERROR, ("Cannot connect to %s: %d", d->proxy_addr, res));
4043
      d->c->flags |= MG_F_CLOSE_IMMEDIATELY;
4044
    }
4045
  } else if (ev == MG_EV_CLOSE) {
4046
    socks_if_disband(d);
4047
  } else if (ev == MG_EV_RECV) {
4048
    /* Handle handshake reply */
4049
    if (!(c->flags & MG_SOCKS_HANDSHAKE_DONE)) {
4050
      /* TODO(lsm): process IPv6 too */
4051
      unsigned char buf[10] = {MG_SOCKS_VERSION, MG_SOCKS_CMD_CONNECT, 0,
4052
                               MG_SOCKS_ADDR_IPV4};
4053
      if (c->recv_mbuf.len < 2) return;
4054
      if ((unsigned char) c->recv_mbuf.buf[1] == MG_SOCKS_HANDSHAKE_FAILURE) {
4055
        LOG(LL_ERROR, ("Server kicked us out"));
4056
        socks_if_disband(d);
4057
        return;
4058
      }
4059
      mbuf_remove(&c->recv_mbuf, 2);
4060
      c->flags |= MG_SOCKS_HANDSHAKE_DONE;
4061

    
4062
      /* Send connect request */
4063
      memcpy(buf + 4, &d->c->sa.sin.sin_addr, 4);
4064
      memcpy(buf + 8, &d->c->sa.sin.sin_port, 2);
4065
      mg_send(c, buf, sizeof(buf));
4066
    }
4067
    /* Process connect request */
4068
    if ((c->flags & MG_SOCKS_HANDSHAKE_DONE) &&
4069
        !(c->flags & MG_SOCKS_CONNECT_DONE)) {
4070
      if (c->recv_mbuf.len < 10) return;
4071
      if (c->recv_mbuf.buf[1] != MG_SOCKS_SUCCESS) {
4072
        LOG(LL_ERROR, ("Socks connection error: %d", c->recv_mbuf.buf[1]));
4073
        socks_if_disband(d);
4074
        return;
4075
      }
4076
      mbuf_remove(&c->recv_mbuf, 10);
4077
      c->flags |= MG_SOCKS_CONNECT_DONE;
4078
      /* Connected. Move sent data from client, if any, to server */
4079
      if (d->s && d->c) {
4080
        mbuf_append(&d->s->send_mbuf, d->tmp.buf, d->tmp.len);
4081
        mbuf_free(&d->tmp);
4082
      }
4083
    }
4084
    /* All flags are set, we're in relay mode */
4085
    if ((c->flags & MG_SOCKS_CONNECT_DONE) && d->c && d->s) {
4086
      mbuf_append(&d->c->recv_mbuf, d->s->recv_mbuf.buf, d->s->recv_mbuf.len);
4087
      mbuf_remove(&d->s->recv_mbuf, d->s->recv_mbuf.len);
4088
    }
4089
  }
4090
}
4091

    
4092
static void mg_socks_if_connect_tcp(struct mg_connection *c,
4093
                                    const union socket_address *sa) {
4094
  struct socksdata *d = (struct socksdata *) c->iface->data;
4095
  d->c = c;
4096
  d->s = mg_connect(c->mgr, d->proxy_addr, socks_if_handler);
4097
  d->s->user_data = d;
4098
  LOG(LL_DEBUG, ("%p %s", c, d->proxy_addr));
4099
  (void) sa;
4100
}
4101

    
4102
static void mg_socks_if_connect_udp(struct mg_connection *c) {
4103
  (void) c;
4104
}
4105

    
4106
static int mg_socks_if_listen_tcp(struct mg_connection *c,
4107
                                  union socket_address *sa) {
4108
  (void) c;
4109
  (void) sa;
4110
  return 0;
4111
}
4112

    
4113
static int mg_socks_if_listen_udp(struct mg_connection *c,
4114
                                  union socket_address *sa) {
4115
  (void) c;
4116
  (void) sa;
4117
  return -1;
4118
}
4119

    
4120
static void mg_socks_if_tcp_send(struct mg_connection *c, const void *buf,
4121
                                 size_t len) {
4122
  struct socksdata *d = (struct socksdata *) c->iface->data;
4123
  LOG(LL_DEBUG, ("%p -> %p %d %d", c, buf, (int) len, (int) c->send_mbuf.len));
4124
  if (d && d->s && d->s->flags & MG_SOCKS_CONNECT_DONE) {
4125
    mbuf_append(&d->s->send_mbuf, d->tmp.buf, d->tmp.len);
4126
    mbuf_append(&d->s->send_mbuf, buf, len);
4127
    mbuf_free(&d->tmp);
4128
  } else {
4129
    mbuf_append(&d->tmp, buf, len);
4130
  }
4131
}
4132

    
4133
static void mg_socks_if_udp_send(struct mg_connection *c, const void *buf,
4134
                                 size_t len) {
4135
  (void) c;
4136
  (void) buf;
4137
  (void) len;
4138
}
4139

    
4140
static void mg_socks_if_recved(struct mg_connection *c, size_t len) {
4141
  (void) c;
4142
  (void) len;
4143
}
4144

    
4145
static int mg_socks_if_create_conn(struct mg_connection *c) {
4146
  (void) c;
4147
  return 1;
4148
}
4149

    
4150
static void mg_socks_if_destroy_conn(struct mg_connection *c) {
4151
  c->iface->vtable->free(c->iface);
4152
  MG_FREE(c->iface);
4153
  c->iface = NULL;
4154
  LOG(LL_DEBUG, ("%p", c));
4155
}
4156

    
4157
static void mg_socks_if_sock_set(struct mg_connection *c, sock_t sock) {
4158
  (void) c;
4159
  (void) sock;
4160
}
4161

    
4162
static void mg_socks_if_init(struct mg_iface *iface) {
4163
  (void) iface;
4164
}
4165

    
4166
static void mg_socks_if_free(struct mg_iface *iface) {
4167
  struct socksdata *d = (struct socksdata *) iface->data;
4168
  LOG(LL_DEBUG, ("%p", iface));
4169
  if (d != NULL) {
4170
    socks_if_disband(d);
4171
    mbuf_free(&d->tmp);
4172
    MG_FREE(d->proxy_addr);
4173
    MG_FREE(d);
4174
    iface->data = NULL;
4175
  }
4176
}
4177

    
4178
static void mg_socks_if_add_conn(struct mg_connection *c) {
4179
  c->sock = INVALID_SOCKET;
4180
}
4181

    
4182
static void mg_socks_if_remove_conn(struct mg_connection *c) {
4183
  (void) c;
4184
}
4185

    
4186
static time_t mg_socks_if_poll(struct mg_iface *iface, int timeout_ms) {
4187
  LOG(LL_DEBUG, ("%p", iface));
4188
  (void) iface;
4189
  (void) timeout_ms;
4190
  return (time_t) cs_time();
4191
}
4192

    
4193
static void mg_socks_if_get_conn_addr(struct mg_connection *c, int remote,
4194
                                      union socket_address *sa) {
4195
  LOG(LL_DEBUG, ("%p", c));
4196
  (void) c;
4197
  (void) remote;
4198
  (void) sa;
4199
}
4200

    
4201
const struct mg_iface_vtable mg_socks_iface_vtable = {
4202
    mg_socks_if_init,        mg_socks_if_free,
4203
    mg_socks_if_add_conn,    mg_socks_if_remove_conn,
4204
    mg_socks_if_poll,        mg_socks_if_listen_tcp,
4205
    mg_socks_if_listen_udp,  mg_socks_if_connect_tcp,
4206
    mg_socks_if_connect_udp, mg_socks_if_tcp_send,
4207
    mg_socks_if_udp_send,    mg_socks_if_recved,
4208
    mg_socks_if_create_conn, mg_socks_if_destroy_conn,
4209
    mg_socks_if_sock_set,    mg_socks_if_get_conn_addr,
4210
};
4211

    
4212
struct mg_iface *mg_socks_mk_iface(struct mg_mgr *mgr, const char *proxy_addr) {
4213
  struct mg_iface *iface = mg_if_create_iface(&mg_socks_iface_vtable, mgr);
4214
  iface->data = MG_CALLOC(1, sizeof(struct socksdata));
4215
  ((struct socksdata *) iface->data)->proxy_addr = strdup(proxy_addr);
4216
  return iface;
4217
}
4218

    
4219
#endif
4220
#ifdef MG_MODULE_LINES
4221
#line 1 "mongoose/src/mg_ssl_if_openssl.c"
4222
#endif
4223
/*
4224
 * Copyright (c) 2014-2016 Cesanta Software Limited
4225
 * All rights reserved
4226
 */
4227

    
4228
#if MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_OPENSSL
4229

    
4230
#ifdef __APPLE__
4231
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
4232
#endif
4233

    
4234
#include <openssl/ssl.h>
4235

    
4236
struct mg_ssl_if_ctx {
4237
  SSL *ssl;
4238
  SSL_CTX *ssl_ctx;
4239
  struct mbuf psk;
4240
  size_t identity_len;
4241
};
4242

    
4243

    
4244

    
4245

    
4246
void mg_ssl_if_init() {
4247
  SSL_library_init();
4248
}
4249

    
4250
enum mg_ssl_if_result mg_ssl_if_conn_accept(struct mg_connection *nc,
4251
                                            struct mg_connection *lc) {
4252
  struct mg_ssl_if_ctx *ctx =
4253
      (struct mg_ssl_if_ctx *) MG_CALLOC(1, sizeof(*ctx));
4254
  struct mg_ssl_if_ctx *lc_ctx = (struct mg_ssl_if_ctx *) lc->ssl_if_data;
4255
  nc->ssl_if_data = ctx;
4256
  if (ctx == NULL || lc_ctx == NULL) return MG_SSL_ERROR;
4257
  ctx->ssl_ctx = lc_ctx->ssl_ctx;
4258
  if ((ctx->ssl = SSL_new(ctx->ssl_ctx)) == NULL) {
4259
    return MG_SSL_ERROR;
4260
  }
4261
  return MG_SSL_OK;
4262
}
4263

    
4264
static enum mg_ssl_if_result mg_use_cert(SSL_CTX *ctx, const char *cert,
4265
                                         const char *key, const char **err_msg);
4266
static enum mg_ssl_if_result mg_use_ca_cert(SSL_CTX *ctx, const char *cert);
4267
static enum mg_ssl_if_result mg_set_cipher_list(SSL_CTX *ctx, const char *cl);
4268
static enum mg_ssl_if_result mg_ssl_if_ossl_set_psk(struct mg_ssl_if_ctx *ctx,
4269
                                                    const char *identity,
4270
                                                    const char *key_str);
4271

    
4272
enum mg_ssl_if_result mg_ssl_if_conn_init(
4273
    struct mg_connection *nc, const struct mg_ssl_if_conn_params *params,
4274
    const char **err_msg) {
4275
  struct mg_ssl_if_ctx *ctx =
4276
      (struct mg_ssl_if_ctx *) MG_CALLOC(1, sizeof(*ctx));
4277
  DBG(("%p %s,%s,%s", nc, (params->cert ? params->cert : ""),
4278
       (params->key ? params->key : ""),
4279
       (params->ca_cert ? params->ca_cert : "")));
4280
  if (ctx == NULL) {
4281
    MG_SET_PTRPTR(err_msg, "Out of memory");
4282
    return MG_SSL_ERROR;
4283
  }
4284
  nc->ssl_if_data = ctx;
4285
  if (nc->flags & MG_F_LISTENING) {
4286
    ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method());
4287
  } else {
4288
    ctx->ssl_ctx = SSL_CTX_new(SSLv23_client_method());
4289
  }
4290
  if (ctx->ssl_ctx == NULL) {
4291
    MG_SET_PTRPTR(err_msg, "Failed to create SSL context");
4292
    return MG_SSL_ERROR;
4293
  }
4294

    
4295
#ifndef KR_VERSION
4296
  /* Disable deprecated protocols. */
4297
  SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_NO_SSLv2);
4298
  SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_NO_SSLv3);
4299
  SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_NO_TLSv1);
4300
#ifdef MG_SSL_OPENSSL_NO_COMPRESSION
4301
  SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
4302
#endif
4303
#ifdef MG_SSL_OPENSSL_CIPHER_SERVER_PREFERENCE
4304
  SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
4305
#endif
4306
#else
4307
/* Krypton only supports TLSv1.2 anyway. */
4308
#endif
4309

    
4310
  if (params->cert != NULL &&
4311
      mg_use_cert(ctx->ssl_ctx, params->cert, params->key, err_msg) !=
4312
          MG_SSL_OK) {
4313
    return MG_SSL_ERROR;
4314
  }
4315

    
4316
  if (params->ca_cert != NULL &&
4317
      mg_use_ca_cert(ctx->ssl_ctx, params->ca_cert) != MG_SSL_OK) {
4318
    MG_SET_PTRPTR(err_msg, "Invalid SSL CA cert");
4319
    return MG_SSL_ERROR;
4320
  }
4321

    
4322
  if (params->server_name != NULL) {
4323
#ifdef KR_VERSION
4324
    SSL_CTX_kr_set_verify_name(ctx->ssl_ctx, params->server_name);
4325
#else
4326
/* TODO(rojer): Implement server name verification on OpenSSL. */
4327
#endif
4328
  }
4329

    
4330
  if (mg_set_cipher_list(ctx->ssl_ctx, params->cipher_suites) != MG_SSL_OK) {
4331
    MG_SET_PTRPTR(err_msg, "Invalid cipher suite list");
4332
    return MG_SSL_ERROR;
4333
  }
4334

    
4335
  mbuf_init(&ctx->psk, 0);
4336
  if (mg_ssl_if_ossl_set_psk(ctx, params->psk_identity, params->psk_key) !=
4337
      MG_SSL_OK) {
4338
    MG_SET_PTRPTR(err_msg, "Invalid PSK settings");
4339
    return MG_SSL_ERROR;
4340
  }
4341

    
4342
  if (!(nc->flags & MG_F_LISTENING) &&
4343
      (ctx->ssl = SSL_new(ctx->ssl_ctx)) == NULL) {
4344
    MG_SET_PTRPTR(err_msg, "Failed to create SSL session");
4345
    return MG_SSL_ERROR;
4346
  }
4347

    
4348
  nc->flags |= MG_F_SSL;
4349

    
4350
  return MG_SSL_OK;
4351
}
4352

    
4353
static enum mg_ssl_if_result mg_ssl_if_ssl_err(struct mg_connection *nc,
4354
                                               int res) {
4355
  struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
4356
  int err = SSL_get_error(ctx->ssl, res);
4357
  if (err == SSL_ERROR_WANT_READ) return MG_SSL_WANT_READ;
4358
  if (err == SSL_ERROR_WANT_WRITE) return MG_SSL_WANT_WRITE;
4359
  DBG(("%p %p SSL error: %d %d", nc, ctx->ssl_ctx, res, err));
4360
  nc->err = err;
4361
  return MG_SSL_ERROR;
4362
}
4363

    
4364
enum mg_ssl_if_result mg_ssl_if_handshake(struct mg_connection *nc) {
4365
  struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
4366
  int server_side = (nc->listener != NULL);
4367
  int res;
4368
  /* If descriptor is not yet set, do it now. */
4369
  if (SSL_get_fd(ctx->ssl) < 0) {
4370
    if (SSL_set_fd(ctx->ssl, nc->sock) != 1) return MG_SSL_ERROR;
4371
  }
4372
  res = server_side ? SSL_accept(ctx->ssl) : SSL_connect(ctx->ssl);
4373
  if (res != 1) return mg_ssl_if_ssl_err(nc, res);
4374
  return MG_SSL_OK;
4375
}
4376

    
4377
int mg_ssl_if_read(struct mg_connection *nc, void *buf, size_t buf_size) {
4378
  struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
4379
  int n = SSL_read(ctx->ssl, buf, buf_size);
4380
  DBG(("%p %d -> %d", nc, (int) buf_size, n));
4381
  if (n < 0) return mg_ssl_if_ssl_err(nc, n);
4382
  if (n == 0) nc->flags |= MG_F_CLOSE_IMMEDIATELY;
4383
  return n;
4384
}
4385

    
4386
int mg_ssl_if_write(struct mg_connection *nc, const void *data, size_t len) {
4387
  struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
4388
  int n = SSL_write(ctx->ssl, data, len);
4389
  DBG(("%p %d -> %d", nc, (int) len, n));
4390
  if (n <= 0) return mg_ssl_if_ssl_err(nc, n);
4391
  return n;
4392
}
4393

    
4394
void mg_ssl_if_conn_close_notify(struct mg_connection *nc) {
4395
  struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
4396
  if (ctx == NULL) return;
4397
  SSL_shutdown(ctx->ssl);
4398
}
4399

    
4400
void mg_ssl_if_conn_free(struct mg_connection *nc) {
4401
  struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
4402
  if (ctx == NULL) return;
4403
  nc->ssl_if_data = NULL;
4404
  if (ctx->ssl != NULL) SSL_free(ctx->ssl);
4405
  if (ctx->ssl_ctx != NULL && nc->listener == NULL) SSL_CTX_free(ctx->ssl_ctx);
4406
  mbuf_free(&ctx->psk);
4407
  memset(ctx, 0, sizeof(*ctx));
4408
  MG_FREE(ctx);
4409
}
4410

    
4411
/*
4412
 * Cipher suite options used for TLS negotiation.
4413
 * https://wiki.mozilla.org/Security/Server_Side_TLS#Recommended_configurations
4414
 */
4415
static const char mg_s_cipher_list[] =
4416
#if defined(MG_SSL_CRYPTO_MODERN)
4417
    "ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:"
4418
    "ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:"
4419
    "DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:"
4420
    "ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:"
4421
    "ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:"
4422
    "ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:"
4423
    "DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:"
4424
    "DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:"
4425
    "!aNULL:!eNULL:!EXPORT:!DES:!RC4:!3DES:!MD5:!PSK"
4426
#elif defined(MG_SSL_CRYPTO_OLD)
4427
    "ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:"
4428
    "ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:"
4429
    "DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:"
4430
    "ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:"
4431
    "ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:"
4432
    "ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:"
4433
    "DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:"
4434
    "DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:ECDHE-RSA-DES-CBC3-SHA:"
4435
    "ECDHE-ECDSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:"
4436
    "AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:DES-CBC3-SHA:"
4437
    "HIGH:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:"
4438
    "!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA"
4439
#else /* Default - intermediate. */
4440
    "ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:"
4441
    "ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:"
4442
    "DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:"
4443
    "ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:"
4444
    "ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:"
4445
    "ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:"
4446
    "DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:"
4447
    "DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:"
4448
    "AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:CAMELLIA:"
4449
    "DES-CBC3-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:"
4450
    "!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA"
4451
#endif
4452
    ;
4453

    
4454
/*
4455
 * Default DH params for PFS cipher negotiation. This is a 2048-bit group.
4456
 * Will be used if none are provided by the user in the certificate file.
4457
 */
4458
#if !MG_DISABLE_PFS && !defined(KR_VERSION)
4459
static const char mg_s_default_dh_params[] =
4460
    "\
4461
-----BEGIN DH PARAMETERS-----\n\
4462
MIIBCAKCAQEAlvbgD/qh9znWIlGFcV0zdltD7rq8FeShIqIhkQ0C7hYFThrBvF2E\n\
4463
Z9bmgaP+sfQwGpVlv9mtaWjvERbu6mEG7JTkgmVUJrUt/wiRzwTaCXBqZkdUO8Tq\n\
4464
+E6VOEQAilstG90ikN1Tfo+K6+X68XkRUIlgawBTKuvKVwBhuvlqTGerOtnXWnrt\n\
4465
ym//hd3cd5PBYGBix0i7oR4xdghvfR2WLVu0LgdThTBb6XP7gLd19cQ1JuBtAajZ\n\
4466
wMuPn7qlUkEFDIkAZy59/Hue/H2Q2vU/JsvVhHWCQBL4F1ofEAt50il6ZxR1QfFK\n\
4467
9VGKDC4oOgm9DlxwwBoC2FjqmvQlqVV3kwIBAg==\n\
4468
-----END DH PARAMETERS-----\n";
4469
#endif
4470

    
4471
static enum mg_ssl_if_result mg_use_ca_cert(SSL_CTX *ctx, const char *cert) {
4472
  if (cert == NULL || strcmp(cert, "*") == 0) {
4473
    return MG_SSL_OK;
4474
  }
4475
  SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, 0);
4476
  return SSL_CTX_load_verify_locations(ctx, cert, NULL) == 1 ? MG_SSL_OK
4477
                                                             : MG_SSL_ERROR;
4478
}
4479

    
4480
static enum mg_ssl_if_result mg_use_cert(SSL_CTX *ctx, const char *cert,
4481
                                         const char *key,
4482
                                         const char **err_msg) {
4483
  if (key == NULL) key = cert;
4484
  if (cert == NULL || cert[0] == '\0' || key == NULL || key[0] == '\0') {
4485
    return MG_SSL_OK;
4486
  } else if (SSL_CTX_use_certificate_file(ctx, cert, 1) == 0) {
4487
    MG_SET_PTRPTR(err_msg, "Invalid SSL cert");
4488
    return MG_SSL_ERROR;
4489
  } else if (SSL_CTX_use_PrivateKey_file(ctx, key, 1) == 0) {
4490
    MG_SET_PTRPTR(err_msg, "Invalid SSL key");
4491
    return MG_SSL_ERROR;
4492
  } else if (SSL_CTX_use_certificate_chain_file(ctx, cert) == 0) {
4493
    MG_SET_PTRPTR(err_msg, "Invalid CA bundle");
4494
    return MG_SSL_ERROR;
4495
  } else {
4496
    SSL_CTX_set_mode(ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
4497
#if !MG_DISABLE_PFS && !defined(KR_VERSION)
4498
    BIO *bio = NULL;
4499
    DH *dh = NULL;
4500

    
4501
    /* Try to read DH parameters from the cert/key file. */
4502
    bio = BIO_new_file(cert, "r");
4503
    if (bio != NULL) {
4504
      dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
4505
      BIO_free(bio);
4506
    }
4507
    /*
4508
     * If there are no DH params in the file, fall back to hard-coded ones.
4509
     * Not ideal, but better than nothing.
4510
     */
4511
    if (dh == NULL) {
4512
      bio = BIO_new_mem_buf((void *) mg_s_default_dh_params, -1);
4513
      dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
4514
      BIO_free(bio);
4515
    }
4516
    if (dh != NULL) {
4517
      SSL_CTX_set_tmp_dh(ctx, dh);
4518
      SSL_CTX_set_options(ctx, SSL_OP_SINGLE_DH_USE);
4519
      DH_free(dh);
4520
    }
4521
#if OPENSSL_VERSION_NUMBER > 0x10002000L
4522
    SSL_CTX_set_ecdh_auto(ctx, 1);
4523
#endif
4524
#endif
4525
  }
4526
  return MG_SSL_OK;
4527
}
4528

    
4529
static enum mg_ssl_if_result mg_set_cipher_list(SSL_CTX *ctx, const char *cl) {
4530
  return (SSL_CTX_set_cipher_list(ctx, cl ? cl : mg_s_cipher_list) == 1
4531
              ? MG_SSL_OK
4532
              : MG_SSL_ERROR);
4533
}
4534

    
4535
#ifndef KR_VERSION
4536
static unsigned int mg_ssl_if_ossl_psk_cb(SSL *ssl, const char *hint,
4537
                                          char *identity,
4538
                                          unsigned int max_identity_len,
4539
                                          unsigned char *psk,
4540
                                          unsigned int max_psk_len) {
4541
  struct mg_ssl_if_ctx *ctx =
4542
      (struct mg_ssl_if_ctx *) SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl));
4543
  size_t key_len = ctx->psk.len - ctx->identity_len - 1;
4544
  DBG(("hint: '%s'", (hint ? hint : "")));
4545
  if (ctx->identity_len + 1 > max_identity_len) {
4546
    DBG(("identity too long"));
4547
    return 0;
4548
  }
4549
  if (key_len > max_psk_len) {
4550
    DBG(("key too long"));
4551
    return 0;
4552
  }
4553
  memcpy(identity, ctx->psk.buf, ctx->identity_len + 1);
4554
  memcpy(psk, ctx->psk.buf + ctx->identity_len + 1, key_len);
4555
  (void) ssl;
4556
  return key_len;
4557
}
4558

    
4559
static enum mg_ssl_if_result mg_ssl_if_ossl_set_psk(struct mg_ssl_if_ctx *ctx,
4560
                                                    const char *identity,
4561
                                                    const char *key_str) {
4562
  unsigned char key[32];
4563
  size_t key_len;
4564
  size_t i = 0;
4565
  if (identity == NULL && key_str == NULL) return MG_SSL_OK;
4566
  if (identity == NULL || key_str == NULL) return MG_SSL_ERROR;
4567
  key_len = strlen(key_str);
4568
  if (key_len != 32 && key_len != 64) return MG_SSL_ERROR;
4569
  memset(key, 0, sizeof(key));
4570
  key_len = 0;
4571
  for (i = 0; key_str[i] != '\0'; i++) {
4572
    unsigned char c;
4573
    char hc = tolower((int) key_str[i]);
4574
    if (hc >= '0' && hc <= '9') {
4575
      c = hc - '0';
4576
    } else if (hc >= 'a' && hc <= 'f') {
4577
      c = hc - 'a' + 0xa;
4578
    } else {
4579
      return MG_SSL_ERROR;
4580
    }
4581
    key_len = i / 2;
4582
    key[key_len] <<= 4;
4583
    key[key_len] |= c;
4584
  }
4585
  key_len++;
4586
  DBG(("identity = '%s', key = (%u)", identity, (unsigned int) key_len));
4587
  ctx->identity_len = strlen(identity);
4588
  mbuf_append(&ctx->psk, identity, ctx->identity_len + 1);
4589
  mbuf_append(&ctx->psk, key, key_len);
4590
  SSL_CTX_set_psk_client_callback(ctx->ssl_ctx, mg_ssl_if_ossl_psk_cb);
4591
  SSL_CTX_set_app_data(ctx->ssl_ctx, ctx);
4592
  return MG_SSL_OK;
4593
}
4594
#else
4595
static enum mg_ssl_if_result mg_ssl_if_ossl_set_psk(struct mg_ssl_if_ctx *ctx,
4596
                                                    const char *identity,
4597
                                                    const char *key_str) {
4598
  (void) ctx;
4599
  (void) identity;
4600
  (void) key_str;
4601
  /* Krypton does not support PSK. */
4602
  return MG_SSL_ERROR;
4603
}
4604
#endif /* defined(KR_VERSION) */
4605

    
4606
const char *mg_set_ssl(struct mg_connection *nc, const char *cert,
4607
                       const char *ca_cert) {
4608
  const char *err_msg = NULL;
4609
  struct mg_ssl_if_conn_params params;
4610
  memset(&params, 0, sizeof(params));
4611
  params.cert = cert;
4612
  params.ca_cert = ca_cert;
4613
  if (mg_ssl_if_conn_init(nc, &params, &err_msg) != MG_SSL_OK) {
4614
    return err_msg;
4615
  }
4616
  return NULL;
4617
}
4618

    
4619
#endif /* MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_OPENSSL */
4620
#ifdef MG_MODULE_LINES
4621
#line 1 "mongoose/src/mg_ssl_if_mbedtls.c"
4622
#endif
4623
/*
4624
 * Copyright (c) 2014-2016 Cesanta Software Limited
4625
 * All rights reserved
4626
 */
4627

    
4628
#if MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_MBEDTLS
4629

    
4630
#include <mbedtls/debug.h>
4631
#include <mbedtls/ecp.h>
4632
#include <mbedtls/platform.h>
4633
#include <mbedtls/ssl.h>
4634
#include <mbedtls/x509_crt.h>
4635

    
4636
static void mg_ssl_mbed_log(void *ctx, int level, const char *file, int line,
4637
                            const char *str) {
4638
  enum cs_log_level cs_level;
4639
  switch (level) {
4640
    case 1:
4641
      cs_level = LL_ERROR;
4642
      break;
4643
    case 2:
4644
    case 3:
4645
      cs_level = LL_DEBUG;
4646
      break;
4647
    default:
4648
      cs_level = LL_VERBOSE_DEBUG;
4649
  }
4650
  /* mbedTLS passes strings with \n at the end, strip it. */
4651
  LOG(cs_level, ("%p %.*s", ctx, (int) (strlen(str) - 1), str));
4652
  (void) file;
4653
  (void) line;
4654
}
4655

    
4656
struct mg_ssl_if_ctx {
4657
  mbedtls_ssl_config *conf;
4658
  mbedtls_ssl_context *ssl;
4659
  mbedtls_x509_crt *cert;
4660
  mbedtls_pk_context *key;
4661
  mbedtls_x509_crt *ca_cert;
4662
  struct mbuf cipher_suites;
4663
};
4664

    
4665
/* Must be provided by the platform. ctx is struct mg_connection. */
4666
extern int mg_ssl_if_mbed_random(void *ctx, unsigned char *buf, size_t len);
4667

    
4668
void mg_ssl_if_init() {
4669
}
4670

    
4671
enum mg_ssl_if_result mg_ssl_if_conn_accept(struct mg_connection *nc,
4672
                                            struct mg_connection *lc) {
4673
  struct mg_ssl_if_ctx *ctx =
4674
      (struct mg_ssl_if_ctx *) MG_CALLOC(1, sizeof(*ctx));
4675
  struct mg_ssl_if_ctx *lc_ctx = (struct mg_ssl_if_ctx *) lc->ssl_if_data;
4676
  nc->ssl_if_data = ctx;
4677
  if (ctx == NULL || lc_ctx == NULL) return MG_SSL_ERROR;
4678
  ctx->ssl = (mbedtls_ssl_context *) MG_CALLOC(1, sizeof(*ctx->ssl));
4679
  if (mbedtls_ssl_setup(ctx->ssl, lc_ctx->conf) != 0) {
4680
    return MG_SSL_ERROR;
4681
  }
4682
  return MG_SSL_OK;
4683
}
4684

    
4685
static enum mg_ssl_if_result mg_use_cert(struct mg_ssl_if_ctx *ctx,
4686
                                         const char *cert, const char *key,
4687
                                         const char **err_msg);
4688
static enum mg_ssl_if_result mg_use_ca_cert(struct mg_ssl_if_ctx *ctx,
4689
                                            const char *cert);
4690
static enum mg_ssl_if_result mg_set_cipher_list(struct mg_ssl_if_ctx *ctx,
4691
                                                const char *ciphers);
4692
static enum mg_ssl_if_result mg_ssl_if_mbed_set_psk(struct mg_ssl_if_ctx *ctx,
4693
                                                    const char *identity,
4694
                                                    const char *key);
4695

    
4696
enum mg_ssl_if_result mg_ssl_if_conn_init(
4697
    struct mg_connection *nc, const struct mg_ssl_if_conn_params *params,
4698
    const char **err_msg) {
4699
  struct mg_ssl_if_ctx *ctx =
4700
      (struct mg_ssl_if_ctx *) MG_CALLOC(1, sizeof(*ctx));
4701
  DBG(("%p %s,%s,%s", nc, (params->cert ? params->cert : ""),
4702
       (params->key ? params->key : ""),
4703
       (params->ca_cert ? params->ca_cert : "")));
4704

    
4705
  if (ctx == NULL) {
4706
    MG_SET_PTRPTR(err_msg, "Out of memory");
4707
    return MG_SSL_ERROR;
4708
  }
4709
  nc->ssl_if_data = ctx;
4710
  ctx->conf = (mbedtls_ssl_config *) MG_CALLOC(1, sizeof(*ctx->conf));
4711
  mbuf_init(&ctx->cipher_suites, 0);
4712
  mbedtls_ssl_config_init(ctx->conf);
4713
  mbedtls_ssl_conf_dbg(ctx->conf, mg_ssl_mbed_log, nc);
4714
  if (mbedtls_ssl_config_defaults(
4715
          ctx->conf, (nc->flags & MG_F_LISTENING ? MBEDTLS_SSL_IS_SERVER
4716
                                                 : MBEDTLS_SSL_IS_CLIENT),
4717
          MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_PRESET_DEFAULT) != 0) {
4718
    MG_SET_PTRPTR(err_msg, "Failed to init SSL config");
4719
    return MG_SSL_ERROR;
4720
  }
4721

    
4722
  /* TLS 1.2 and up */
4723
  mbedtls_ssl_conf_min_version(ctx->conf, MBEDTLS_SSL_MAJOR_VERSION_3,
4724
                               MBEDTLS_SSL_MINOR_VERSION_3);
4725
  mbedtls_ssl_conf_rng(ctx->conf, mg_ssl_if_mbed_random, nc);
4726

    
4727
  if (params->cert != NULL &&
4728
      mg_use_cert(ctx, params->cert, params->key, err_msg) != MG_SSL_OK) {
4729
    return MG_SSL_ERROR;
4730
  }
4731

    
4732
  if (params->ca_cert != NULL &&
4733
      mg_use_ca_cert(ctx, params->ca_cert) != MG_SSL_OK) {
4734
    MG_SET_PTRPTR(err_msg, "Invalid SSL CA cert");
4735
    return MG_SSL_ERROR;
4736
  }
4737

    
4738
  if (mg_set_cipher_list(ctx, params->cipher_suites) != MG_SSL_OK) {
4739
    MG_SET_PTRPTR(err_msg, "Invalid cipher suite list");
4740
    return MG_SSL_ERROR;
4741
  }
4742

    
4743
  if (mg_ssl_if_mbed_set_psk(ctx, params->psk_identity, params->psk_key) !=
4744
      MG_SSL_OK) {
4745
    MG_SET_PTRPTR(err_msg, "Invalid PSK settings");
4746
    return MG_SSL_ERROR;
4747
  }
4748

    
4749
  if (!(nc->flags & MG_F_LISTENING)) {
4750
    ctx->ssl = (mbedtls_ssl_context *) MG_CALLOC(1, sizeof(*ctx->ssl));
4751
    mbedtls_ssl_init(ctx->ssl);
4752
    if (mbedtls_ssl_setup(ctx->ssl, ctx->conf) != 0) {
4753
      MG_SET_PTRPTR(err_msg, "Failed to create SSL session");
4754
      return MG_SSL_ERROR;
4755
    }
4756
    if (params->server_name != NULL &&
4757
        mbedtls_ssl_set_hostname(ctx->ssl, params->server_name) != 0) {
4758
      return MG_SSL_ERROR;
4759
    }
4760
  }
4761

    
4762
#ifdef MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN
4763
  if (mbedtls_ssl_conf_max_frag_len(ctx->conf,
4764
#if MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN == 512
4765
                                    MBEDTLS_SSL_MAX_FRAG_LEN_512
4766
#elif MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN == 1024
4767
                                    MBEDTLS_SSL_MAX_FRAG_LEN_1024
4768
#elif MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN == 2048
4769
                                    MBEDTLS_SSL_MAX_FRAG_LEN_2048
4770
#elif MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN == 4096
4771
                                    MBEDTLS_SSL_MAX_FRAG_LEN_4096
4772
#else
4773
#error Invalid MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN
4774
#endif
4775
                                    ) != 0) {
4776
    return MG_SSL_ERROR;
4777
  }
4778
#endif
4779

    
4780
  nc->flags |= MG_F_SSL;
4781

    
4782
  return MG_SSL_OK;
4783
}
4784

    
4785
#if MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL
4786
int ssl_socket_send(void *ctx, const unsigned char *buf, size_t len);
4787
int ssl_socket_recv(void *ctx, unsigned char *buf, size_t len);
4788
#else
4789
static int ssl_socket_send(void *ctx, const unsigned char *buf, size_t len) {
4790
  struct mg_connection *nc = (struct mg_connection *) ctx;
4791
  int n = (int) MG_SEND_FUNC(nc->sock, buf, len, 0);
4792
  LOG(LL_DEBUG, ("%p %d -> %d", nc, (int) len, n));
4793
  if (n >= 0) return n;
4794
  n = mg_get_errno();
4795
  return ((n == EAGAIN || n == EINPROGRESS) ? MBEDTLS_ERR_SSL_WANT_WRITE : -1);
4796
}
4797

    
4798
static int ssl_socket_recv(void *ctx, unsigned char *buf, size_t len) {
4799
  struct mg_connection *nc = (struct mg_connection *) ctx;
4800
  int n = (int) MG_RECV_FUNC(nc->sock, buf, len, 0);
4801
  LOG(LL_DEBUG, ("%p %d <- %d", nc, (int) len, n));
4802
  if (n >= 0) return n;
4803
  n = mg_get_errno();
4804
  return ((n == EAGAIN || n == EINPROGRESS) ? MBEDTLS_ERR_SSL_WANT_READ : -1);
4805
}
4806
#endif
4807

    
4808
static enum mg_ssl_if_result mg_ssl_if_mbed_err(struct mg_connection *nc,
4809
                                                int ret) {
4810
  if (ret == MBEDTLS_ERR_SSL_WANT_READ) return MG_SSL_WANT_READ;
4811
  if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) return MG_SSL_WANT_WRITE;
4812
  if (ret !=
4813
      MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) { /* CLOSE_NOTIFY = Normal shutdown */
4814
    LOG(LL_ERROR, ("%p SSL error: %d", nc, ret));
4815
  }
4816
  nc->err = ret;
4817
  nc->flags |= MG_F_CLOSE_IMMEDIATELY;
4818
  return MG_SSL_ERROR;
4819
}
4820

    
4821
static void mg_ssl_if_mbed_free_certs_and_keys(struct mg_ssl_if_ctx *ctx) {
4822
  if (ctx->cert != NULL) {
4823
    mbedtls_x509_crt_free(ctx->cert);
4824
    MG_FREE(ctx->cert);
4825
    ctx->cert = NULL;
4826
    mbedtls_pk_free(ctx->key);
4827
    MG_FREE(ctx->key);
4828
    ctx->key = NULL;
4829
  }
4830
  if (ctx->ca_cert != NULL) {
4831
    mbedtls_ssl_conf_ca_chain(ctx->conf, NULL, NULL);
4832
#ifdef MBEDTLS_X509_CA_CHAIN_ON_DISK
4833
    if (ctx->ca_cert->ca_chain_file != NULL) {
4834
      MG_FREE((void *) ctx->ca_cert->ca_chain_file);
4835
      ctx->ca_cert->ca_chain_file = NULL;
4836
    }
4837
#endif
4838
    mbedtls_x509_crt_free(ctx->ca_cert);
4839
    MG_FREE(ctx->ca_cert);
4840
    ctx->ca_cert = NULL;
4841
  }
4842
}
4843

    
4844
enum mg_ssl_if_result mg_ssl_if_handshake(struct mg_connection *nc) {
4845
  struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
4846
  int err;
4847
  /* If bio is not yet set, do it now. */
4848
  if (ctx->ssl->p_bio == NULL) {
4849
    mbedtls_ssl_set_bio(ctx->ssl, nc, ssl_socket_send, ssl_socket_recv, NULL);
4850
  }
4851
  err = mbedtls_ssl_handshake(ctx->ssl);
4852
  if (err != 0) return mg_ssl_if_mbed_err(nc, err);
4853
#ifdef MG_SSL_IF_MBEDTLS_FREE_CERTS
4854
  /*
4855
   * Free the peer certificate, we don't need it after handshake.
4856
   * Note that this effectively disables renegotiation.
4857
   */
4858
  mbedtls_x509_crt_free(ctx->ssl->session->peer_cert);
4859
  mbedtls_free(ctx->ssl->session->peer_cert);
4860
  ctx->ssl->session->peer_cert = NULL;
4861
  /* On a client connection we can also free our own and CA certs. */
4862
  if (nc->listener == NULL) {
4863
    if (ctx->conf->key_cert != NULL) {
4864
      /* Note that this assumes one key_cert entry, which matches our init. */
4865
      MG_FREE(ctx->conf->key_cert);
4866
      ctx->conf->key_cert = NULL;
4867
    }
4868
    mbedtls_ssl_conf_ca_chain(ctx->conf, NULL, NULL);
4869
    mg_ssl_if_mbed_free_certs_and_keys(ctx);
4870
  }
4871
#endif
4872
  return MG_SSL_OK;
4873
}
4874

    
4875
int mg_ssl_if_read(struct mg_connection *nc, void *buf, size_t buf_size) {
4876
  struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
4877
  int n = mbedtls_ssl_read(ctx->ssl, (unsigned char *) buf, buf_size);
4878
  DBG(("%p %d -> %d", nc, (int) buf_size, n));
4879
  if (n < 0) return mg_ssl_if_mbed_err(nc, n);
4880
  if (n == 0) nc->flags |= MG_F_CLOSE_IMMEDIATELY;
4881
  return n;
4882
}
4883

    
4884
int mg_ssl_if_write(struct mg_connection *nc, const void *data, size_t len) {
4885
  struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
4886
  int n = mbedtls_ssl_write(ctx->ssl, (const unsigned char *) data, len);
4887
  DBG(("%p %d -> %d", nc, (int) len, n));
4888
  if (n < 0) return mg_ssl_if_mbed_err(nc, n);
4889
  return n;
4890
}
4891

    
4892
void mg_ssl_if_conn_close_notify(struct mg_connection *nc) {
4893
  struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
4894
  if (ctx == NULL) return;
4895
  mbedtls_ssl_close_notify(ctx->ssl);
4896
}
4897

    
4898
void mg_ssl_if_conn_free(struct mg_connection *nc) {
4899
  struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
4900
  if (ctx == NULL) return;
4901
  nc->ssl_if_data = NULL;
4902
  if (ctx->ssl != NULL) {
4903
    mbedtls_ssl_free(ctx->ssl);
4904
    MG_FREE(ctx->ssl);
4905
  }
4906
  mg_ssl_if_mbed_free_certs_and_keys(ctx);
4907
  if (ctx->conf != NULL) {
4908
    mbedtls_ssl_config_free(ctx->conf);
4909
    MG_FREE(ctx->conf);
4910
  }
4911
  mbuf_free(&ctx->cipher_suites);
4912
  memset(ctx, 0, sizeof(*ctx));
4913
  MG_FREE(ctx);
4914
}
4915

    
4916
static enum mg_ssl_if_result mg_use_ca_cert(struct mg_ssl_if_ctx *ctx,
4917
                                            const char *ca_cert) {
4918
  if (ca_cert == NULL || strcmp(ca_cert, "*") == 0) {
4919
    mbedtls_ssl_conf_authmode(ctx->conf, MBEDTLS_SSL_VERIFY_NONE);
4920
    return MG_SSL_OK;
4921
  }
4922
  ctx->ca_cert = (mbedtls_x509_crt *) MG_CALLOC(1, sizeof(*ctx->ca_cert));
4923
  mbedtls_x509_crt_init(ctx->ca_cert);
4924
#ifdef MBEDTLS_X509_CA_CHAIN_ON_DISK
4925
  ca_cert = strdup(ca_cert);
4926
  if (mbedtls_x509_crt_set_ca_chain_file(ctx->ca_cert, ca_cert) != 0) {
4927
    return MG_SSL_ERROR;
4928
  }
4929
#else
4930
  if (mbedtls_x509_crt_parse_file(ctx->ca_cert, ca_cert) != 0) {
4931
    return MG_SSL_ERROR;
4932
  }
4933
#endif
4934
  mbedtls_ssl_conf_ca_chain(ctx->conf, ctx->ca_cert, NULL);
4935
  mbedtls_ssl_conf_authmode(ctx->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
4936
  return MG_SSL_OK;
4937
}
4938

    
4939
static enum mg_ssl_if_result mg_use_cert(struct mg_ssl_if_ctx *ctx,
4940
                                         const char *cert, const char *key,
4941
                                         const char **err_msg) {
4942
  if (key == NULL) key = cert;
4943
  if (cert == NULL || cert[0] == '\0' || key == NULL || key[0] == '\0') {
4944
    return MG_SSL_OK;
4945
  }
4946
  ctx->cert = (mbedtls_x509_crt *) MG_CALLOC(1, sizeof(*ctx->cert));
4947
  mbedtls_x509_crt_init(ctx->cert);
4948
  ctx->key = (mbedtls_pk_context *) MG_CALLOC(1, sizeof(*ctx->key));
4949
  mbedtls_pk_init(ctx->key);
4950
  if (mbedtls_x509_crt_parse_file(ctx->cert, cert) != 0) {
4951
    MG_SET_PTRPTR(err_msg, "Invalid SSL cert");
4952
    return MG_SSL_ERROR;
4953
  }
4954
  if (mbedtls_pk_parse_keyfile(ctx->key, key, NULL) != 0) {
4955
    MG_SET_PTRPTR(err_msg, "Invalid SSL key");
4956
    return MG_SSL_ERROR;
4957
  }
4958
  if (mbedtls_ssl_conf_own_cert(ctx->conf, ctx->cert, ctx->key) != 0) {
4959
    MG_SET_PTRPTR(err_msg, "Invalid SSL key or cert");
4960
    return MG_SSL_ERROR;
4961
  }
4962
  return MG_SSL_OK;
4963
}
4964

    
4965
static const int mg_s_cipher_list[] = {
4966
#if CS_PLATFORM != CS_P_ESP8266
4967
    MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
4968
    MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,
4969
    MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
4970
    MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,
4971
    MBEDTLS_TLS_DHE_RSA_WITH_AES_128_GCM_SHA256,
4972
    MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256,
4973
    MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256,
4974
    MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256,
4975
    MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA,
4976
    MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256,
4977
    MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256,
4978
    MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA,
4979
    MBEDTLS_TLS_RSA_WITH_AES_128_GCM_SHA256,
4980
    MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA256,
4981
    MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA,
4982
#else
4983
    /*
4984
     * ECDHE is way too slow on ESP8266 w/o cryptochip, this sometimes results
4985
     * in WiFi STA deauths. Use weaker but faster cipher suites. Sad but true.
4986
     * Disable DHE completely because it's just hopelessly slow.
4987
     */
4988
    MBEDTLS_TLS_RSA_WITH_AES_128_GCM_SHA256,
4989
    MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA256,
4990
    MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
4991
    MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,
4992
    MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
4993
    MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,
4994
    MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256,
4995
    MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256,
4996
    MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA,
4997
    MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256,
4998
    MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256,
4999
    MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA,
5000
    MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA,
5001
#endif /* CS_PLATFORM != CS_P_ESP8266 */
5002
    0,
5003
};
5004

    
5005
/*
5006
 * Ciphers can be specified as a colon-separated list of cipher suite names.
5007
 * These can be found in
5008
 * https://github.com/ARMmbed/mbedtls/blob/development/library/ssl_ciphersuites.c#L267
5009
 * E.g.: TLS-ECDHE-ECDSA-WITH-AES-128-GCM-SHA256:TLS-DHE-RSA-WITH-AES-256-CCM
5010
 */
5011
static enum mg_ssl_if_result mg_set_cipher_list(struct mg_ssl_if_ctx *ctx,
5012
                                                const char *ciphers) {
5013
  if (ciphers != NULL) {
5014
    int l, id;
5015
    const char *s = ciphers, *e;
5016
    char tmp[50];
5017
    while (s != NULL) {
5018
      e = strchr(s, ':');
5019
      l = (e != NULL ? (e - s) : (int) strlen(s));
5020
      strncpy(tmp, s, l);
5021
      tmp[l] = '\0';
5022
      id = mbedtls_ssl_get_ciphersuite_id(tmp);
5023
      DBG(("%s -> %04x", tmp, id));
5024
      if (id != 0) {
5025
        mbuf_append(&ctx->cipher_suites, &id, sizeof(id));
5026
      }
5027
      s = (e != NULL ? e + 1 : NULL);
5028
    }
5029
    if (ctx->cipher_suites.len == 0) return MG_SSL_ERROR;
5030
    id = 0;
5031
    mbuf_append(&ctx->cipher_suites, &id, sizeof(id));
5032
    mbuf_trim(&ctx->cipher_suites);
5033
    mbedtls_ssl_conf_ciphersuites(ctx->conf,
5034
                                  (const int *) ctx->cipher_suites.buf);
5035
  } else {
5036
    mbedtls_ssl_conf_ciphersuites(ctx->conf, mg_s_cipher_list);
5037
  }
5038
  return MG_SSL_OK;
5039
}
5040

    
5041
static enum mg_ssl_if_result mg_ssl_if_mbed_set_psk(struct mg_ssl_if_ctx *ctx,
5042
                                                    const char *identity,
5043
                                                    const char *key_str) {
5044
  unsigned char key[32];
5045
  size_t key_len;
5046
  if (identity == NULL && key_str == NULL) return MG_SSL_OK;
5047
  if (identity == NULL || key_str == NULL) return MG_SSL_ERROR;
5048
  key_len = strlen(key_str);
5049
  if (key_len != 32 && key_len != 64) return MG_SSL_ERROR;
5050
  size_t i = 0;
5051
  memset(key, 0, sizeof(key));
5052
  key_len = 0;
5053
  for (i = 0; key_str[i] != '\0'; i++) {
5054
    unsigned char c;
5055
    char hc = tolower((int) key_str[i]);
5056
    if (hc >= '0' && hc <= '9') {
5057
      c = hc - '0';
5058
    } else if (hc >= 'a' && hc <= 'f') {
5059
      c = hc - 'a' + 0xa;
5060
    } else {
5061
      return MG_SSL_ERROR;
5062
    }
5063
    key_len = i / 2;
5064
    key[key_len] <<= 4;
5065
    key[key_len] |= c;
5066
  }
5067
  key_len++;
5068
  DBG(("identity = '%s', key = (%u)", identity, (unsigned int) key_len));
5069
  /* mbedTLS makes copies of psk and identity. */
5070
  if (mbedtls_ssl_conf_psk(ctx->conf, (const unsigned char *) key, key_len,
5071
                           (const unsigned char *) identity,
5072
                           strlen(identity)) != 0) {
5073
    return MG_SSL_ERROR;
5074
  }
5075
  return MG_SSL_OK;
5076
}
5077

    
5078
const char *mg_set_ssl(struct mg_connection *nc, const char *cert,
5079
                       const char *ca_cert) {
5080
  const char *err_msg = NULL;
5081
  struct mg_ssl_if_conn_params params;
5082
  memset(&params, 0, sizeof(params));
5083
  params.cert = cert;
5084
  params.ca_cert = ca_cert;
5085
  if (mg_ssl_if_conn_init(nc, &params, &err_msg) != MG_SSL_OK) {
5086
    return err_msg;
5087
  }
5088
  return NULL;
5089
}
5090

    
5091
/* Lazy RNG. Warning: it would be a bad idea to do this in production! */
5092
#ifdef MG_SSL_MBED_DUMMY_RANDOM
5093
int mg_ssl_if_mbed_random(void *ctx, unsigned char *buf, size_t len) {
5094
  (void) ctx;
5095
  while (len--) *buf++ = rand();
5096
  return 0;
5097
}
5098
#endif
5099

    
5100
#endif /* MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_MBEDTLS */
5101
#ifdef MG_MODULE_LINES
5102
#line 1 "mongoose/src/mg_uri.c"
5103
#endif
5104
/*
5105
 * Copyright (c) 2014 Cesanta Software Limited
5106
 * All rights reserved
5107
 */
5108

    
5109
/* Amalgamated: #include "mg_internal.h" */
5110
/* Amalgamated: #include "mg_uri.h" */
5111

    
5112
/*
5113
 * scan string until encountering one of `seps`, keeping track of component
5114
 * boundaries in `res`.
5115
 *
5116
 * `p` will point to the char after the separator or it will be `end`.
5117
 */
5118
static void parse_uri_component(const char **p, const char *end,
5119
                                const char *seps, struct mg_str *res) {
5120
  const char *q;
5121
  res->p = *p;
5122
  for (; *p < end; (*p)++) {
5123
    for (q = seps; *q != '\0'; q++) {
5124
      if (**p == *q) break;
5125
    }
5126
    if (*q != '\0') break;
5127
  }
5128
  res->len = (*p) - res->p;
5129
  if (*p < end) (*p)++;
5130
}
5131

    
5132
int mg_parse_uri(const struct mg_str uri, struct mg_str *scheme,
5133
                 struct mg_str *user_info, struct mg_str *host,
5134
                 unsigned int *port, struct mg_str *path, struct mg_str *query,
5135
                 struct mg_str *fragment) {
5136
  struct mg_str rscheme = {0, 0}, ruser_info = {0, 0}, rhost = {0, 0},
5137
                rpath = {0, 0}, rquery = {0, 0}, rfragment = {0, 0};
5138
  unsigned int rport = 0;
5139
  enum {
5140
    P_START,
5141
    P_SCHEME_OR_PORT,
5142
    P_USER_INFO,
5143
    P_HOST,
5144
    P_PORT,
5145
    P_REST
5146
  } state = P_START;
5147

    
5148
  const char *p = uri.p, *end = p + uri.len;
5149
  while (p < end) {
5150
    switch (state) {
5151
      case P_START:
5152
        /*
5153
         * expecting on of:
5154
         * - `scheme://xxxx`
5155
         * - `xxxx:port`
5156
         * - `[a:b:c]:port`
5157
         * - `xxxx/path`
5158
         */
5159
        if (*p == '[') {
5160
          state = P_HOST;
5161
          break;
5162
        }
5163
        for (; p < end; p++) {
5164
          if (*p == ':') {
5165
            state = P_SCHEME_OR_PORT;
5166
            break;
5167
          } else if (*p == '/') {
5168
            state = P_REST;
5169
            break;
5170
          }
5171
        }
5172
        if (state == P_START || state == P_REST) {
5173
          rhost.p = uri.p;
5174
          rhost.len = p - uri.p;
5175
        }
5176
        break;
5177
      case P_SCHEME_OR_PORT:
5178
        if (end - p >= 3 && strncmp(p, "://", 3) == 0) {
5179
          rscheme.p = uri.p;
5180
          rscheme.len = p - uri.p;
5181
          state = P_USER_INFO;
5182
          p += 3;
5183
        } else {
5184
          rhost.p = uri.p;
5185
          rhost.len = p - uri.p;
5186
          state = P_PORT;
5187
        }
5188
        break;
5189
      case P_USER_INFO:
5190
        ruser_info.p = p;
5191
        for (; p < end; p++) {
5192
          if (*p == '@' || *p == '[' || *p == '/') {
5193
            break;
5194
          }
5195
        }
5196
        if (p == end || *p == '/' || *p == '[') {
5197
          /* backtrack and parse as host */
5198
          p = ruser_info.p;
5199
        }
5200
        ruser_info.len = p - ruser_info.p;
5201
        state = P_HOST;
5202
        break;
5203
      case P_HOST:
5204
        if (*p == '@') p++;
5205
        rhost.p = p;
5206
        if (*p == '[') {
5207
          int found = 0;
5208
          for (; !found && p < end; p++) {
5209
            found = (*p == ']');
5210
          }
5211
          if (!found) return -1;
5212
        } else {
5213
          for (; p < end; p++) {
5214
            if (*p == ':' || *p == '/') break;
5215
          }
5216
        }
5217
        rhost.len = p - rhost.p;
5218
        if (p < end) {
5219
          if (*p == ':') {
5220
            state = P_PORT;
5221
            break;
5222
          } else if (*p == '/') {
5223
            state = P_REST;
5224
            break;
5225
          }
5226
        }
5227
        break;
5228
      case P_PORT:
5229
        p++;
5230
        for (; p < end; p++) {
5231
          if (*p == '/') {
5232
            state = P_REST;
5233
            break;
5234
          }
5235
          rport *= 10;
5236
          rport += *p - '0';
5237
        }
5238
        break;
5239
      case P_REST:
5240
        /* `p` points to separator. `path` includes the separator */
5241
        parse_uri_component(&p, end, "?#", &rpath);
5242
        if (p < end && *(p - 1) == '?') {
5243
          parse_uri_component(&p, end, "#", &rquery);
5244
        }
5245
        parse_uri_component(&p, end, "", &rfragment);
5246
        break;
5247
    }
5248
  }
5249

    
5250
  if (scheme != 0) *scheme = rscheme;
5251
  if (user_info != 0) *user_info = ruser_info;
5252
  if (host != 0) *host = rhost;
5253
  if (port != 0) *port = rport;
5254
  if (path != 0) *path = rpath;
5255
  if (query != 0) *query = rquery;
5256
  if (fragment != 0) *fragment = rfragment;
5257

    
5258
  return 0;
5259
}
5260

    
5261
/* Normalize the URI path. Remove/resolve "." and "..". */
5262
int mg_normalize_uri_path(const struct mg_str *in, struct mg_str *out) {
5263
  const char *s = in->p, *se = s + in->len;
5264
  char *cp = (char *) out->p, *d;
5265

    
5266
  if (in->len == 0 || *s != '/') {
5267
    out->len = 0;
5268
    return 0;
5269
  }
5270

    
5271
  d = cp;
5272

    
5273
  while (s < se) {
5274
    const char *next = s;
5275
    struct mg_str component;
5276
    parse_uri_component(&next, se, "/", &component);
5277
    if (mg_vcmp(&component, ".") == 0) {
5278
      /* Yum. */
5279
    } else if (mg_vcmp(&component, "..") == 0) {
5280
      /* Backtrack to previous slash. */
5281
      if (d > cp + 1 && *(d - 1) == '/') d--;
5282
      while (d > cp && *(d - 1) != '/') d--;
5283
    } else {
5284
      memmove(d, s, next - s);
5285
      d += next - s;
5286
    }
5287
    s = next;
5288
  }
5289
  if (d == cp) *d++ = '/';
5290

    
5291
  out->p = cp;
5292
  out->len = d - cp;
5293
  return 1;
5294
}
5295

    
5296
int mg_assemble_uri(const struct mg_str *scheme, const struct mg_str *user_info,
5297
                    const struct mg_str *host, unsigned int port,
5298
                    const struct mg_str *path, const struct mg_str *query,
5299
                    const struct mg_str *fragment, int normalize_path,
5300
                    struct mg_str *uri) {
5301
  int result = -1;
5302
  struct mbuf out;
5303
  mbuf_init(&out, 0);
5304

    
5305
  if (scheme != NULL && scheme->len > 0) {
5306
    mbuf_append(&out, scheme->p, scheme->len);
5307
    mbuf_append(&out, "://", 3);
5308
  }
5309

    
5310
  if (user_info != NULL && user_info->len > 0) {
5311
    mbuf_append(&out, user_info->p, user_info->len);
5312
    mbuf_append(&out, "@", 1);
5313
  }
5314

    
5315
  if (host != NULL && host->len > 0) {
5316
    mbuf_append(&out, host->p, host->len);
5317
  }
5318

    
5319
  if (port != 0) {
5320
    char port_str[20];
5321
    int port_str_len = sprintf(port_str, ":%u", port);
5322
    mbuf_append(&out, port_str, port_str_len);
5323
  }
5324

    
5325
  if (path != NULL && path->len > 0) {
5326
    if (normalize_path) {
5327
      struct mg_str npath = mg_strdup(*path);
5328
      if (npath.len != path->len) goto out;
5329
      if (!mg_normalize_uri_path(path, &npath)) {
5330
        free((void *) npath.p);
5331
        goto out;
5332
      }
5333
      mbuf_append(&out, npath.p, npath.len);
5334
      free((void *) npath.p);
5335
    } else {
5336
      mbuf_append(&out, path->p, path->len);
5337
    }
5338
  } else if (normalize_path) {
5339
    mbuf_append(&out, "/", 1);
5340
  }
5341

    
5342
  if (query != NULL && query->len > 0) {
5343
    mbuf_append(&out, "?", 1);
5344
    mbuf_append(&out, query->p, query->len);
5345
  }
5346

    
5347
  if (fragment != NULL && fragment->len > 0) {
5348
    mbuf_append(&out, "#", 1);
5349
    mbuf_append(&out, fragment->p, fragment->len);
5350
  }
5351

    
5352
  result = 0;
5353

    
5354
out:
5355
  if (result == 0) {
5356
    uri->p = out.buf;
5357
    uri->len = out.len;
5358
  } else {
5359
    mbuf_free(&out);
5360
    uri->p = NULL;
5361
    uri->len = 0;
5362
  }
5363
  return result;
5364
}
5365
#ifdef MG_MODULE_LINES
5366
#line 1 "mongoose/src/mg_http.c"
5367
#endif
5368
/*
5369
 * Copyright (c) 2014 Cesanta Software Limited
5370
 * All rights reserved
5371
 */
5372

    
5373
#if MG_ENABLE_HTTP
5374

    
5375
/* Amalgamated: #include "common/cs_md5.h" */
5376
/* Amalgamated: #include "mg_internal.h" */
5377
/* Amalgamated: #include "mg_util.h" */
5378

    
5379
/* altbuf {{{ */
5380

    
5381
/*
5382
 * Alternate buffer: fills the client-provided buffer with data; and if it's
5383
 * not large enough, allocates another buffer (via mbuf), similar to asprintf.
5384
 */
5385
struct altbuf {
5386
  struct mbuf m;
5387
  char *user_buf;
5388
  size_t len;
5389
  size_t user_buf_size;
5390
};
5391

    
5392
/*
5393
 * Initializes altbuf; `buf`, `buf_size` is the client-provided buffer.
5394
 */
5395
MG_INTERNAL void altbuf_init(struct altbuf *ab, char *buf, size_t buf_size) {
5396
  mbuf_init(&ab->m, 0);
5397
  ab->user_buf = buf;
5398
  ab->user_buf_size = buf_size;
5399
  ab->len = 0;
5400
}
5401

    
5402
/*
5403
 * Appends a single char to the altbuf.
5404
 */
5405
MG_INTERNAL void altbuf_append(struct altbuf *ab, char c) {
5406
  if (ab->len < ab->user_buf_size) {
5407
    /* The data fits into the original buffer */
5408
    ab->user_buf[ab->len++] = c;
5409
  } else {
5410
    /* The data can't fit into the original buffer, so write it to mbuf.  */
5411

    
5412
    /*
5413
     * First of all, see if that's the first byte which overflows the original
5414
     * buffer: if so, copy the existing data from there to a newly allocated
5415
     * mbuf.
5416
     */
5417
    if (ab->len > 0 && ab->m.len == 0) {
5418
      mbuf_append(&ab->m, ab->user_buf, ab->len);
5419
    }
5420

    
5421
    mbuf_append(&ab->m, &c, 1);
5422
    ab->len = ab->m.len;
5423
  }
5424
}
5425

    
5426
/*
5427
 * Resets any data previously appended to altbuf.
5428
 */
5429
MG_INTERNAL void altbuf_reset(struct altbuf *ab) {
5430
  mbuf_free(&ab->m);
5431
  ab->len = 0;
5432
}
5433

    
5434
/*
5435
 * Returns whether the additional buffer was allocated (and thus the data
5436
 * is in the mbuf, not the client-provided buffer)
5437
 */
5438
MG_INTERNAL int altbuf_reallocated(struct altbuf *ab) {
5439
  return ab->len > ab->user_buf_size;
5440
}
5441

    
5442
/*
5443
 * Returns the actual buffer with data, either the client-provided or a newly
5444
 * allocated one. If `trim` is non-zero, mbuf-backed buffer is trimmed first.
5445
 */
5446
MG_INTERNAL char *altbuf_get_buf(struct altbuf *ab, int trim) {
5447
  if (altbuf_reallocated(ab)) {
5448
    if (trim) {
5449
      mbuf_trim(&ab->m);
5450
    }
5451
    return ab->m.buf;
5452
  } else {
5453
    return ab->user_buf;
5454
  }
5455
}
5456

    
5457
/* }}} */
5458

    
5459
static const char *mg_version_header = "Mongoose/" MG_VERSION;
5460

    
5461
enum mg_http_proto_data_type { DATA_NONE, DATA_FILE, DATA_PUT };
5462

    
5463
struct mg_http_proto_data_file {
5464
  FILE *fp;      /* Opened file. */
5465
  int64_t cl;    /* Content-Length. How many bytes to send. */
5466
  int64_t sent;  /* How many bytes have been already sent. */
5467
  int keepalive; /* Keep connection open after sending. */
5468
  enum mg_http_proto_data_type type;
5469
};
5470

    
5471
#if MG_ENABLE_HTTP_CGI
5472
struct mg_http_proto_data_cgi {
5473
  struct mg_connection *cgi_nc;
5474
};
5475
#endif
5476

    
5477
struct mg_http_proto_data_chuncked {
5478
  int64_t body_len; /* How many bytes of chunked body was reassembled. */
5479
};
5480

    
5481
struct mg_http_endpoint {
5482
  struct mg_http_endpoint *next;
5483
  struct mg_str uri_pattern; /* owned */
5484
  char *auth_domain;         /* owned */
5485
  char *auth_file;           /* owned */
5486

    
5487
  mg_event_handler_t handler;
5488
#if MG_ENABLE_CALLBACK_USERDATA
5489
  void *user_data;
5490
#endif
5491
};
5492

    
5493
enum mg_http_multipart_stream_state {
5494
  MPS_BEGIN,
5495
  MPS_WAITING_FOR_BOUNDARY,
5496
  MPS_WAITING_FOR_CHUNK,
5497
  MPS_GOT_CHUNK,
5498
  MPS_GOT_BOUNDARY,
5499
  MPS_FINALIZE,
5500
  MPS_FINISHED
5501
};
5502

    
5503
struct mg_http_multipart_stream {
5504
  const char *boundary;
5505
  int boundary_len;
5506
  const char *var_name;
5507
  const char *file_name;
5508
  void *user_data;
5509
  int prev_io_len;
5510
  enum mg_http_multipart_stream_state state;
5511
  int processing_part;
5512
};
5513

    
5514
struct mg_reverse_proxy_data {
5515
  struct mg_connection *linked_conn;
5516
};
5517

    
5518
struct mg_ws_proto_data {
5519
  /*
5520
   * Defragmented size of the frame so far.
5521
   *
5522
   * First byte of nc->recv_mbuf.buf is an op, the rest of the data is
5523
   * defragmented data.
5524
   */
5525
  size_t reass_len;
5526
};
5527

    
5528
struct mg_http_proto_data {
5529
#if MG_ENABLE_FILESYSTEM
5530
  struct mg_http_proto_data_file file;
5531
#endif
5532
#if MG_ENABLE_HTTP_CGI
5533
  struct mg_http_proto_data_cgi cgi;
5534
#endif
5535
#if MG_ENABLE_HTTP_STREAMING_MULTIPART
5536
  struct mg_http_multipart_stream mp_stream;
5537
#endif
5538
#if MG_ENABLE_HTTP_WEBSOCKET
5539
  struct mg_ws_proto_data ws_data;
5540
#endif
5541
  struct mg_http_proto_data_chuncked chunk;
5542
  struct mg_http_endpoint *endpoints;
5543
  mg_event_handler_t endpoint_handler;
5544
  struct mg_reverse_proxy_data reverse_proxy_data;
5545
  size_t rcvd; /* How many bytes we have received. */
5546
};
5547

    
5548
static void mg_http_conn_destructor(void *proto_data);
5549
struct mg_connection *mg_connect_http_base(
5550
    struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data),
5551
    struct mg_connect_opts opts, const char *scheme1, const char *scheme2,
5552
    const char *scheme_ssl1, const char *scheme_ssl2, const char *url,
5553
    struct mg_str *path, struct mg_str *user_info, struct mg_str *host);
5554

    
5555
static struct mg_http_proto_data *mg_http_get_proto_data(
5556
    struct mg_connection *c) {
5557
  if (c->proto_data == NULL) {
5558
    c->proto_data = MG_CALLOC(1, sizeof(struct mg_http_proto_data));
5559
    c->proto_data_destructor = mg_http_conn_destructor;
5560
  }
5561

    
5562
  return (struct mg_http_proto_data *) c->proto_data;
5563
}
5564

    
5565
#if MG_ENABLE_HTTP_STREAMING_MULTIPART
5566
static void mg_http_free_proto_data_mp_stream(
5567
    struct mg_http_multipart_stream *mp) {
5568
  MG_FREE((void *) mp->boundary);
5569
  MG_FREE((void *) mp->var_name);
5570
  MG_FREE((void *) mp->file_name);
5571
  memset(mp, 0, sizeof(*mp));
5572
}
5573
#endif
5574

    
5575
#if MG_ENABLE_FILESYSTEM
5576
static void mg_http_free_proto_data_file(struct mg_http_proto_data_file *d) {
5577
  if (d != NULL) {
5578
    if (d->fp != NULL) {
5579
      fclose(d->fp);
5580
    }
5581
    memset(d, 0, sizeof(struct mg_http_proto_data_file));
5582
  }
5583
}
5584
#endif
5585

    
5586
static void mg_http_free_proto_data_endpoints(struct mg_http_endpoint **ep) {
5587
  struct mg_http_endpoint *current = *ep;
5588

    
5589
  while (current != NULL) {
5590
    struct mg_http_endpoint *tmp = current->next;
5591
    MG_FREE((void *) current->uri_pattern.p);
5592
    MG_FREE((void *) current->auth_domain);
5593
    MG_FREE((void *) current->auth_file);
5594
    MG_FREE(current);
5595
    current = tmp;
5596
  }
5597

    
5598
  ep = NULL;
5599
}
5600

    
5601
static void mg_http_free_reverse_proxy_data(struct mg_reverse_proxy_data *rpd) {
5602
  if (rpd->linked_conn != NULL) {
5603
    /*
5604
     * Connection has linked one, we have to unlink & close it
5605
     * since _this_ connection is going to die and
5606
     * it doesn't make sense to keep another one
5607
     */
5608
    struct mg_http_proto_data *pd = mg_http_get_proto_data(rpd->linked_conn);
5609
    if (pd->reverse_proxy_data.linked_conn != NULL) {
5610
      pd->reverse_proxy_data.linked_conn->flags |= MG_F_SEND_AND_CLOSE;
5611
      pd->reverse_proxy_data.linked_conn = NULL;
5612
    }
5613
    rpd->linked_conn = NULL;
5614
  }
5615
}
5616

    
5617
static void mg_http_conn_destructor(void *proto_data) {
5618
  struct mg_http_proto_data *pd = (struct mg_http_proto_data *) proto_data;
5619
#if MG_ENABLE_FILESYSTEM
5620
  mg_http_free_proto_data_file(&pd->file);
5621
#endif
5622
#if MG_ENABLE_HTTP_CGI
5623
  mg_http_free_proto_data_cgi(&pd->cgi);
5624
#endif
5625
#if MG_ENABLE_HTTP_STREAMING_MULTIPART
5626
  mg_http_free_proto_data_mp_stream(&pd->mp_stream);
5627
#endif
5628
  mg_http_free_proto_data_endpoints(&pd->endpoints);
5629
  mg_http_free_reverse_proxy_data(&pd->reverse_proxy_data);
5630
  MG_FREE(proto_data);
5631
}
5632

    
5633
#if MG_ENABLE_FILESYSTEM
5634

    
5635
#define MIME_ENTRY(_ext, _type) \
5636
  { _ext, sizeof(_ext) - 1, _type }
5637
static const struct {
5638
  const char *extension;
5639
  size_t ext_len;
5640
  const char *mime_type;
5641
} mg_static_builtin_mime_types[] = {
5642
    MIME_ENTRY("html", "text/html"),
5643
    MIME_ENTRY("html", "text/html"),
5644
    MIME_ENTRY("htm", "text/html"),
5645
    MIME_ENTRY("shtm", "text/html"),
5646
    MIME_ENTRY("shtml", "text/html"),
5647
    MIME_ENTRY("css", "text/css"),
5648
    MIME_ENTRY("js", "application/x-javascript"),
5649
    MIME_ENTRY("ico", "image/x-icon"),
5650
    MIME_ENTRY("gif", "image/gif"),
5651
    MIME_ENTRY("jpg", "image/jpeg"),
5652
    MIME_ENTRY("jpeg", "image/jpeg"),
5653
    MIME_ENTRY("png", "image/png"),
5654
    MIME_ENTRY("svg", "image/svg+xml"),
5655
    MIME_ENTRY("txt", "text/plain"),
5656
    MIME_ENTRY("torrent", "application/x-bittorrent"),
5657
    MIME_ENTRY("wav", "audio/x-wav"),
5658
    MIME_ENTRY("mp3", "audio/x-mp3"),
5659
    MIME_ENTRY("mid", "audio/mid"),
5660
    MIME_ENTRY("m3u", "audio/x-mpegurl"),
5661
    MIME_ENTRY("ogg", "application/ogg"),
5662
    MIME_ENTRY("ram", "audio/x-pn-realaudio"),
5663
    MIME_ENTRY("xml", "text/xml"),
5664
    MIME_ENTRY("ttf", "application/x-font-ttf"),
5665
    MIME_ENTRY("json", "application/json"),
5666
    MIME_ENTRY("xslt", "application/xml"),
5667
    MIME_ENTRY("xsl", "application/xml"),
5668
    MIME_ENTRY("ra", "audio/x-pn-realaudio"),
5669
    MIME_ENTRY("doc", "application/msword"),
5670
    MIME_ENTRY("exe", "application/octet-stream"),
5671
    MIME_ENTRY("zip", "application/x-zip-compressed"),
5672
    MIME_ENTRY("xls", "application/excel"),
5673
    MIME_ENTRY("tgz", "application/x-tar-gz"),
5674
    MIME_ENTRY("tar", "application/x-tar"),
5675
    MIME_ENTRY("gz", "application/x-gunzip"),
5676
    MIME_ENTRY("arj", "application/x-arj-compressed"),
5677
    MIME_ENTRY("rar", "application/x-rar-compressed"),
5678
    MIME_ENTRY("rtf", "application/rtf"),
5679
    MIME_ENTRY("pdf", "application/pdf"),
5680
    MIME_ENTRY("swf", "application/x-shockwave-flash"),
5681
    MIME_ENTRY("mpg", "video/mpeg"),
5682
    MIME_ENTRY("webm", "video/webm"),
5683
    MIME_ENTRY("mpeg", "video/mpeg"),
5684
    MIME_ENTRY("mov", "video/quicktime"),
5685
    MIME_ENTRY("mp4", "video/mp4"),
5686
    MIME_ENTRY("m4v", "video/x-m4v"),
5687
    MIME_ENTRY("asf", "video/x-ms-asf"),
5688
    MIME_ENTRY("avi", "video/x-msvideo"),
5689
    MIME_ENTRY("bmp", "image/bmp"),
5690
    {NULL, 0, NULL}};
5691

    
5692
static struct mg_str mg_get_mime_type(const char *path, const char *dflt,
5693
                                      const struct mg_serve_http_opts *opts) {
5694
  const char *ext, *overrides;
5695
  size_t i, path_len;
5696
  struct mg_str r, k, v;
5697

    
5698
  path_len = strlen(path);
5699

    
5700
  overrides = opts->custom_mime_types;
5701
  while ((overrides = mg_next_comma_list_entry(overrides, &k, &v)) != NULL) {
5702
    ext = path + (path_len - k.len);
5703
    if (path_len > k.len && mg_vcasecmp(&k, ext) == 0) {
5704
      return v;
5705
    }
5706
  }
5707

    
5708
  for (i = 0; mg_static_builtin_mime_types[i].extension != NULL; i++) {
5709
    ext = path + (path_len - mg_static_builtin_mime_types[i].ext_len);
5710
    if (path_len > mg_static_builtin_mime_types[i].ext_len && ext[-1] == '.' &&
5711
        mg_casecmp(ext, mg_static_builtin_mime_types[i].extension) == 0) {
5712
      r.p = mg_static_builtin_mime_types[i].mime_type;
5713
      r.len = strlen(r.p);
5714
      return r;
5715
    }
5716
  }
5717

    
5718
  r.p = dflt;
5719
  r.len = strlen(r.p);
5720
  return r;
5721
}
5722
#endif
5723

    
5724
/*
5725
 * Check whether full request is buffered. Return:
5726
 *   -1  if request is malformed
5727
 *    0  if request is not yet fully buffered
5728
 *   >0  actual request length, including last \r\n\r\n
5729
 */
5730
static int mg_http_get_request_len(const char *s, int buf_len) {
5731
  const unsigned char *buf = (unsigned char *) s;
5732
  int i;
5733

    
5734
  for (i = 0; i < buf_len; i++) {
5735
    if (!isprint(buf[i]) && buf[i] != '\r' && buf[i] != '\n' && buf[i] < 128) {
5736
      return -1;
5737
    } else if (buf[i] == '\n' && i + 1 < buf_len && buf[i + 1] == '\n') {
5738
      return i + 2;
5739
    } else if (buf[i] == '\n' && i + 2 < buf_len && buf[i + 1] == '\r' &&
5740
               buf[i + 2] == '\n') {
5741
      return i + 3;
5742
    }
5743
  }
5744

    
5745
  return 0;
5746
}
5747

    
5748
static const char *mg_http_parse_headers(const char *s, const char *end,
5749
                                         int len, struct http_message *req) {
5750
  int i = 0;
5751
  while (i < (int) ARRAY_SIZE(req->header_names) - 1) {
5752
    struct mg_str *k = &req->header_names[i], *v = &req->header_values[i];
5753

    
5754
    s = mg_skip(s, end, ": ", k);
5755
    s = mg_skip(s, end, "\r\n", v);
5756

    
5757
    while (v->len > 0 && v->p[v->len - 1] == ' ') {
5758
      v->len--; /* Trim trailing spaces in header value */
5759
    }
5760

    
5761
    /*
5762
     * If header value is empty - skip it and go to next (if any).
5763
     * NOTE: Do not add it to headers_values because such addition changes API
5764
     * behaviour
5765
     */
5766
    if (k->len != 0 && v->len == 0) {
5767
      continue;
5768
    }
5769

    
5770
    if (k->len == 0 || v->len == 0) {
5771
      k->p = v->p = NULL;
5772
      k->len = v->len = 0;
5773
      break;
5774
    }
5775

    
5776
    if (!mg_ncasecmp(k->p, "Content-Length", 14)) {
5777
      req->body.len = (size_t) to64(v->p);
5778
      req->message.len = len + req->body.len;
5779
    }
5780

    
5781
    i++;
5782
  }
5783

    
5784
  return s;
5785
}
5786

    
5787
int mg_parse_http(const char *s, int n, struct http_message *hm, int is_req) {
5788
  const char *end, *qs;
5789
  int len = mg_http_get_request_len(s, n);
5790

    
5791
  if (len <= 0) return len;
5792

    
5793
  memset(hm, 0, sizeof(*hm));
5794
  hm->message.p = s;
5795
  hm->body.p = s + len;
5796
  hm->message.len = hm->body.len = (size_t) ~0;
5797
  end = s + len;
5798

    
5799
  /* Request is fully buffered. Skip leading whitespaces. */
5800
  while (s < end && isspace(*(unsigned char *) s)) s++;
5801

    
5802
  if (is_req) {
5803
    /* Parse request line: method, URI, proto */
5804
    s = mg_skip(s, end, " ", &hm->method);
5805
    s = mg_skip(s, end, " ", &hm->uri);
5806
    s = mg_skip(s, end, "\r\n", &hm->proto);
5807
    if (hm->uri.p <= hm->method.p || hm->proto.p <= hm->uri.p) return -1;
5808

    
5809
    /* If URI contains '?' character, initialize query_string */
5810
    if ((qs = (char *) memchr(hm->uri.p, '?', hm->uri.len)) != NULL) {
5811
      hm->query_string.p = qs + 1;
5812
      hm->query_string.len = &hm->uri.p[hm->uri.len] - (qs + 1);
5813
      hm->uri.len = qs - hm->uri.p;
5814
    }
5815
  } else {
5816
    s = mg_skip(s, end, " ", &hm->proto);
5817
    if (end - s < 4 || s[3] != ' ') return -1;
5818
    hm->resp_code = atoi(s);
5819
    if (hm->resp_code < 100 || hm->resp_code >= 600) return -1;
5820
    s += 4;
5821
    s = mg_skip(s, end, "\r\n", &hm->resp_status_msg);
5822
  }
5823

    
5824
  s = mg_http_parse_headers(s, end, len, hm);
5825

    
5826
  /*
5827
   * mg_parse_http() is used to parse both HTTP requests and HTTP
5828
   * responses. If HTTP response does not have Content-Length set, then
5829
   * body is read until socket is closed, i.e. body.len is infinite (~0).
5830
   *
5831
   * For HTTP requests though, according to
5832
   * http://tools.ietf.org/html/rfc7231#section-8.1.3,
5833
   * only POST and PUT methods have defined body semantics.
5834
   * Therefore, if Content-Length is not specified and methods are
5835
   * not one of PUT or POST, set body length to 0.
5836
   *
5837
   * So,
5838
   * if it is HTTP request, and Content-Length is not set,
5839
   * and method is not (PUT or POST) then reset body length to zero.
5840
   */
5841
  if (hm->body.len == (size_t) ~0 && is_req &&
5842
      mg_vcasecmp(&hm->method, "PUT") != 0 &&
5843
      mg_vcasecmp(&hm->method, "POST") != 0) {
5844
    hm->body.len = 0;
5845
    hm->message.len = len;
5846
  }
5847

    
5848
  return len;
5849
}
5850

    
5851
struct mg_str *mg_get_http_header(struct http_message *hm, const char *name) {
5852
  size_t i, len = strlen(name);
5853

    
5854
  for (i = 0; hm->header_names[i].len > 0; i++) {
5855
    struct mg_str *h = &hm->header_names[i], *v = &hm->header_values[i];
5856
    if (h->p != NULL && h->len == len && !mg_ncasecmp(h->p, name, len))
5857
      return v;
5858
  }
5859

    
5860
  return NULL;
5861
}
5862

    
5863
#if MG_ENABLE_FILESYSTEM
5864
static void mg_http_transfer_file_data(struct mg_connection *nc) {
5865
  struct mg_http_proto_data *pd = mg_http_get_proto_data(nc);
5866
  char buf[MG_MAX_HTTP_SEND_MBUF];
5867
  size_t n = 0, to_read = 0, left = (size_t)(pd->file.cl - pd->file.sent);
5868

    
5869
  if (pd->file.type == DATA_FILE) {
5870
    struct mbuf *io = &nc->send_mbuf;
5871
    if (io->len >= MG_MAX_HTTP_SEND_MBUF) {
5872
      to_read = 0;
5873
    } else {
5874
      to_read = MG_MAX_HTTP_SEND_MBUF - io->len;
5875
    }
5876
    if (to_read > left) {
5877
      to_read = left;
5878
    }
5879
    if (to_read > 0) {
5880
      n = mg_fread(buf, 1, to_read, pd->file.fp);
5881
      if (n > 0) {
5882
        mg_send(nc, buf, n);
5883
        pd->file.sent += n;
5884
        DBG(("%p sent %d (total %d)", nc, (int) n, (int) pd->file.sent));
5885
      }
5886
    } else {
5887
      /* Rate-limited */
5888
    }
5889
    if (pd->file.sent >= pd->file.cl) {
5890
      LOG(LL_DEBUG, ("%p done, %d bytes", nc, (int) pd->file.sent));
5891
      if (!pd->file.keepalive) nc->flags |= MG_F_SEND_AND_CLOSE;
5892
      mg_http_free_proto_data_file(&pd->file);
5893
    }
5894
  } else if (pd->file.type == DATA_PUT) {
5895
    struct mbuf *io = &nc->recv_mbuf;
5896
    size_t to_write = left <= 0 ? 0 : left < io->len ? (size_t) left : io->len;
5897
    size_t n = mg_fwrite(io->buf, 1, to_write, pd->file.fp);
5898
    if (n > 0) {
5899
      mbuf_remove(io, n);
5900
      pd->file.sent += n;
5901
    }
5902
    if (n == 0 || pd->file.sent >= pd->file.cl) {
5903
      if (!pd->file.keepalive) nc->flags |= MG_F_SEND_AND_CLOSE;
5904
      mg_http_free_proto_data_file(&pd->file);
5905
    }
5906
  }
5907
#if MG_ENABLE_HTTP_CGI
5908
  else if (pd->cgi.cgi_nc != NULL) {
5909
    /* This is POST data that needs to be forwarded to the CGI process */
5910
    if (pd->cgi.cgi_nc != NULL) {
5911
      mg_forward(nc, pd->cgi.cgi_nc);
5912
    } else {
5913
      nc->flags |= MG_F_SEND_AND_CLOSE;
5914
    }
5915
  }
5916
#endif
5917
}
5918
#endif /* MG_ENABLE_FILESYSTEM */
5919

    
5920
/*
5921
 * Parse chunked-encoded buffer. Return 0 if the buffer is not encoded, or
5922
 * if it's incomplete. If the chunk is fully buffered, return total number of
5923
 * bytes in a chunk, and store data in `data`, `data_len`.
5924
 */
5925
static size_t mg_http_parse_chunk(char *buf, size_t len, char **chunk_data,
5926
                                  size_t *chunk_len) {
5927
  unsigned char *s = (unsigned char *) buf;
5928
  size_t n = 0; /* scanned chunk length */
5929
  size_t i = 0; /* index in s */
5930

    
5931
  /* Scan chunk length. That should be a hexadecimal number. */
5932
  while (i < len && isxdigit(s[i])) {
5933
    n *= 16;
5934
    n += (s[i] >= '0' && s[i] <= '9') ? s[i] - '0' : tolower(s[i]) - 'a' + 10;
5935
    i++;
5936
  }
5937

    
5938
  /* Skip new line */
5939
  if (i == 0 || i + 2 > len || s[i] != '\r' || s[i + 1] != '\n') {
5940
    return 0;
5941
  }
5942
  i += 2;
5943

    
5944
  /* Record where the data is */
5945
  *chunk_data = (char *) s + i;
5946
  *chunk_len = n;
5947

    
5948
  /* Skip data */
5949
  i += n;
5950

    
5951
  /* Skip new line */
5952
  if (i == 0 || i + 2 > len || s[i] != '\r' || s[i + 1] != '\n') {
5953
    return 0;
5954
  }
5955
  return i + 2;
5956
}
5957

    
5958
MG_INTERNAL size_t mg_handle_chunked(struct mg_connection *nc,
5959
                                     struct http_message *hm, char *buf,
5960
                                     size_t blen) {
5961
  struct mg_http_proto_data *pd = mg_http_get_proto_data(nc);
5962
  char *data;
5963
  size_t i, n, data_len, body_len, zero_chunk_received = 0;
5964
  /* Find out piece of received data that is not yet reassembled */
5965
  body_len = (size_t) pd->chunk.body_len;
5966
  assert(blen >= body_len);
5967

    
5968
  /* Traverse all fully buffered chunks */
5969
  for (i = body_len;
5970
       (n = mg_http_parse_chunk(buf + i, blen - i, &data, &data_len)) > 0;
5971
       i += n) {
5972
    /* Collapse chunk data to the rest of HTTP body */
5973
    memmove(buf + body_len, data, data_len);
5974
    body_len += data_len;
5975
    hm->body.len = body_len;
5976

    
5977
    if (data_len == 0) {
5978
      zero_chunk_received = 1;
5979
      i += n;
5980
      break;
5981
    }
5982
  }
5983

    
5984
  if (i > body_len) {
5985
    /* Shift unparsed content to the parsed body */
5986
    assert(i <= blen);
5987
    memmove(buf + body_len, buf + i, blen - i);
5988
    memset(buf + body_len + blen - i, 0, i - body_len);
5989
    nc->recv_mbuf.len -= i - body_len;
5990
    pd->chunk.body_len = body_len;
5991

    
5992
    /* Send MG_EV_HTTP_CHUNK event */
5993
    nc->flags &= ~MG_F_DELETE_CHUNK;
5994
    mg_call(nc, nc->handler, nc->user_data, MG_EV_HTTP_CHUNK, hm);
5995

    
5996
    /* Delete processed data if user set MG_F_DELETE_CHUNK flag */
5997
    if (nc->flags & MG_F_DELETE_CHUNK) {
5998
      memset(buf, 0, body_len);
5999
      memmove(buf, buf + body_len, blen - i);
6000
      nc->recv_mbuf.len -= body_len;
6001
      hm->body.len = 0;
6002
      pd->chunk.body_len = 0;
6003
    }
6004

    
6005
    if (zero_chunk_received) {
6006
      /* Total message size is len(body) + len(headers) */
6007
      hm->message.len =
6008
          (size_t) pd->chunk.body_len + blen - i + (hm->body.p - hm->message.p);
6009
    }
6010
  }
6011

    
6012
  return body_len;
6013
}
6014

    
6015
struct mg_http_endpoint *mg_http_get_endpoint_handler(struct mg_connection *nc,
6016
                                                      struct mg_str *uri_path) {
6017
  struct mg_http_proto_data *pd;
6018
  struct mg_http_endpoint *ret = NULL;
6019
  int matched, matched_max = 0;
6020
  struct mg_http_endpoint *ep;
6021

    
6022
  if (nc == NULL) {
6023
    return NULL;
6024
  }
6025

    
6026
  pd = mg_http_get_proto_data(nc);
6027

    
6028
  ep = pd->endpoints;
6029
  while (ep != NULL) {
6030
    if ((matched = mg_match_prefix_n(ep->uri_pattern, *uri_path)) > 0) {
6031
      if (matched > matched_max) {
6032
        /* Looking for the longest suitable handler */
6033
        ret = ep;
6034
        matched_max = matched;
6035
      }
6036
    }
6037

    
6038
    ep = ep->next;
6039
  }
6040

    
6041
  return ret;
6042
}
6043

    
6044
#if MG_ENABLE_HTTP_STREAMING_MULTIPART
6045
static void mg_http_multipart_continue(struct mg_connection *nc);
6046

    
6047
static void mg_http_multipart_begin(struct mg_connection *nc,
6048
                                    struct http_message *hm, int req_len);
6049

    
6050
#endif
6051

    
6052
static void mg_http_call_endpoint_handler(struct mg_connection *nc, int ev,
6053
                                          struct http_message *hm);
6054

    
6055
static void deliver_chunk(struct mg_connection *c, struct http_message *hm,
6056
                          int req_len) {
6057
  /* Incomplete message received. Send MG_EV_HTTP_CHUNK event */
6058
  hm->body.len = c->recv_mbuf.len - req_len;
6059
  c->flags &= ~MG_F_DELETE_CHUNK;
6060
  mg_call(c, c->handler, c->user_data, MG_EV_HTTP_CHUNK, hm);
6061
  /* Delete processed data if user set MG_F_DELETE_CHUNK flag */
6062
  if (c->flags & MG_F_DELETE_CHUNK) c->recv_mbuf.len = req_len;
6063
}
6064

    
6065
/*
6066
 * lx106 compiler has a bug (TODO(mkm) report and insert tracking bug here)
6067
 * If a big structure is declared in a big function, lx106 gcc will make it
6068
 * even bigger (round up to 4k, from 700 bytes of actual size).
6069
 */
6070
#ifdef __xtensa__
6071
static void mg_http_handler2(struct mg_connection *nc, int ev,
6072
                             void *ev_data MG_UD_ARG(void *user_data),
6073
                             struct http_message *hm) __attribute__((noinline));
6074

    
6075
void mg_http_handler(struct mg_connection *nc, int ev,
6076
                     void *ev_data MG_UD_ARG(void *user_data)) {
6077
  struct http_message hm;
6078
  mg_http_handler2(nc, ev, ev_data MG_UD_ARG(user_data), &hm);
6079
}
6080

    
6081
static void mg_http_handler2(struct mg_connection *nc, int ev,
6082
                             void *ev_data MG_UD_ARG(void *user_data),
6083
                             struct http_message *hm) {
6084
#else  /* !__XTENSA__ */
6085
void mg_http_handler(struct mg_connection *nc, int ev,
6086
                     void *ev_data MG_UD_ARG(void *user_data)) {
6087
  struct http_message shm, *hm = &shm;
6088
#endif /* __XTENSA__ */
6089
  struct mg_http_proto_data *pd = mg_http_get_proto_data(nc);
6090
  struct mbuf *io = &nc->recv_mbuf;
6091
  int req_len;
6092
  const int is_req = (nc->listener != NULL);
6093
#if MG_ENABLE_HTTP_WEBSOCKET
6094
  struct mg_str *vec;
6095
#endif
6096
  if (ev == MG_EV_CLOSE) {
6097
#if MG_ENABLE_HTTP_CGI
6098
    /* Close associated CGI forwarder connection */
6099
    if (pd->cgi.cgi_nc != NULL) {
6100
      pd->cgi.cgi_nc->user_data = NULL;
6101
      pd->cgi.cgi_nc->flags |= MG_F_CLOSE_IMMEDIATELY;
6102
    }
6103
#endif
6104
#if MG_ENABLE_HTTP_STREAMING_MULTIPART
6105
    if (pd->mp_stream.boundary != NULL) {
6106
      /*
6107
       * Multipart message is in progress, but connection is closed.
6108
       * Finish part and request with an error flag.
6109
       */
6110
      struct mg_http_multipart_part mp;
6111
      memset(&mp, 0, sizeof(mp));
6112
      mp.status = -1;
6113
      mp.var_name = pd->mp_stream.var_name;
6114
      mp.file_name = pd->mp_stream.file_name;
6115
      mg_call(nc, (pd->endpoint_handler ? pd->endpoint_handler : nc->handler),
6116
              nc->user_data, MG_EV_HTTP_PART_END, &mp);
6117
      mp.var_name = NULL;
6118
      mp.file_name = NULL;
6119
      mg_call(nc, (pd->endpoint_handler ? pd->endpoint_handler : nc->handler),
6120
              nc->user_data, MG_EV_HTTP_MULTIPART_REQUEST_END, &mp);
6121
    } else
6122
#endif
6123
        if (io->len > 0 &&
6124
            (req_len = mg_parse_http(io->buf, io->len, hm, is_req)) > 0) {
6125
      /*
6126
      * For HTTP messages without Content-Length, always send HTTP message
6127
      * before MG_EV_CLOSE message.
6128
      */
6129
      int ev2 = is_req ? MG_EV_HTTP_REQUEST : MG_EV_HTTP_REPLY;
6130
      hm->message.len = io->len;
6131
      hm->body.len = io->buf + io->len - hm->body.p;
6132
      deliver_chunk(nc, hm, req_len);
6133
      mg_http_call_endpoint_handler(nc, ev2, hm);
6134
    }
6135
    pd->rcvd = 0;
6136
  }
6137

    
6138
#if MG_ENABLE_FILESYSTEM
6139
  if (pd->file.fp != NULL) {
6140
    mg_http_transfer_file_data(nc);
6141
  }
6142
#endif
6143

    
6144
  mg_call(nc, nc->handler, nc->user_data, ev, ev_data);
6145

    
6146
  if (ev == MG_EV_RECV) {
6147
    struct mg_str *s;
6148
    pd->rcvd += *(int *) ev_data;
6149

    
6150
#if MG_ENABLE_HTTP_STREAMING_MULTIPART
6151
    if (pd->mp_stream.boundary != NULL) {
6152
      mg_http_multipart_continue(nc);
6153
      return;
6154
    }
6155
#endif /* MG_ENABLE_HTTP_STREAMING_MULTIPART */
6156

    
6157
    req_len = mg_parse_http(io->buf, io->len, hm, is_req);
6158

    
6159
    if (req_len > 0 &&
6160
        (s = mg_get_http_header(hm, "Transfer-Encoding")) != NULL &&
6161
        mg_vcasecmp(s, "chunked") == 0) {
6162
      mg_handle_chunked(nc, hm, io->buf + req_len, io->len - req_len);
6163
    }
6164

    
6165
#if MG_ENABLE_HTTP_STREAMING_MULTIPART
6166
    if (req_len > 0 && (s = mg_get_http_header(hm, "Content-Type")) != NULL &&
6167
        s->len >= 9 && strncmp(s->p, "multipart", 9) == 0) {
6168
      mg_http_multipart_begin(nc, hm, req_len);
6169
      mg_http_multipart_continue(nc);
6170
      return;
6171
    }
6172
#endif /* MG_ENABLE_HTTP_STREAMING_MULTIPART */
6173

    
6174
    /* TODO(alashkin): refactor this ifelseifelseifelseifelse */
6175
    if ((req_len < 0 ||
6176
         (req_len == 0 && io->len >= MG_MAX_HTTP_REQUEST_SIZE))) {
6177
      DBG(("invalid request"));
6178
      nc->flags |= MG_F_CLOSE_IMMEDIATELY;
6179
    } else if (req_len == 0) {
6180
      /* Do nothing, request is not yet fully buffered */
6181
    }
6182
#if MG_ENABLE_HTTP_WEBSOCKET
6183
    else if (nc->listener == NULL &&
6184
             mg_get_http_header(hm, "Sec-WebSocket-Accept")) {
6185
      /* We're websocket client, got handshake response from server. */
6186
      /* TODO(lsm): check the validity of accept Sec-WebSocket-Accept */
6187
      mbuf_remove(io, req_len);
6188
      nc->proto_handler = mg_ws_handler;
6189
      nc->flags |= MG_F_IS_WEBSOCKET;
6190
      mg_call(nc, nc->handler, nc->user_data, MG_EV_WEBSOCKET_HANDSHAKE_DONE,
6191
              NULL);
6192
      mg_ws_handler(nc, MG_EV_RECV, ev_data MG_UD_ARG(user_data));
6193
    } else if (nc->listener != NULL &&
6194
               (vec = mg_get_http_header(hm, "Sec-WebSocket-Key")) != NULL) {
6195
      struct mg_http_endpoint *ep;
6196

    
6197
      /* This is a websocket request. Switch protocol handlers. */
6198
      mbuf_remove(io, req_len);
6199
      nc->proto_handler = mg_ws_handler;
6200
      nc->flags |= MG_F_IS_WEBSOCKET;
6201

    
6202
      /*
6203
       * If we have a handler set up with mg_register_http_endpoint(),
6204
       * deliver subsequent websocket events to this handler after the
6205
       * protocol switch.
6206
       */
6207
      ep = mg_http_get_endpoint_handler(nc->listener, &hm->uri);
6208
      if (ep != NULL) {
6209
        nc->handler = ep->handler;
6210
#if MG_ENABLE_CALLBACK_USERDATA
6211
        nc->user_data = ep->user_data;
6212
#endif
6213
      }
6214

    
6215
      /* Send handshake */
6216
      mg_call(nc, nc->handler, nc->user_data, MG_EV_WEBSOCKET_HANDSHAKE_REQUEST,
6217
              hm);
6218
      if (!(nc->flags & (MG_F_CLOSE_IMMEDIATELY | MG_F_SEND_AND_CLOSE))) {
6219
        if (nc->send_mbuf.len == 0) {
6220
          mg_ws_handshake(nc, vec, hm);
6221
        }
6222
        mg_call(nc, nc->handler, nc->user_data, MG_EV_WEBSOCKET_HANDSHAKE_DONE,
6223
                NULL);
6224
        mg_ws_handler(nc, MG_EV_RECV, ev_data MG_UD_ARG(user_data));
6225
      }
6226
    }
6227
#endif /* MG_ENABLE_HTTP_WEBSOCKET */
6228
    else if (hm->message.len > pd->rcvd) {
6229
      /* Not yet received all HTTP body, deliver MG_EV_HTTP_CHUNK */
6230
      deliver_chunk(nc, hm, req_len);
6231
      if (nc->recv_mbuf_limit > 0 && nc->recv_mbuf.len >= nc->recv_mbuf_limit) {
6232
        LOG(LL_ERROR, ("%p recv buffer (%lu bytes) exceeds the limit "
6233
                       "%lu bytes, and not drained, closing",
6234
                       nc, (unsigned long) nc->recv_mbuf.len,
6235
                       (unsigned long) nc->recv_mbuf_limit));
6236
        nc->flags |= MG_F_CLOSE_IMMEDIATELY;
6237
      }
6238
    } else {
6239
      /* We did receive all HTTP body. */
6240
      int trigger_ev = nc->listener ? MG_EV_HTTP_REQUEST : MG_EV_HTTP_REPLY;
6241
      char addr[32];
6242
      mg_sock_addr_to_str(&nc->sa, addr, sizeof(addr),
6243
                          MG_SOCK_STRINGIFY_IP | MG_SOCK_STRINGIFY_PORT);
6244
      DBG(("%p %s %.*s %.*s", nc, addr, (int) hm->method.len, hm->method.p,
6245
           (int) hm->uri.len, hm->uri.p));
6246
      deliver_chunk(nc, hm, req_len);
6247
      /* Whole HTTP message is fully buffered, call event handler */
6248
      mg_http_call_endpoint_handler(nc, trigger_ev, hm);
6249
      mbuf_remove(io, hm->message.len);
6250
      pd->rcvd = 0;
6251
    }
6252
  }
6253
}
6254

    
6255
static size_t mg_get_line_len(const char *buf, size_t buf_len) {
6256
  size_t len = 0;
6257
  while (len < buf_len && buf[len] != '\n') len++;
6258
  return len == buf_len ? 0 : len + 1;
6259
}
6260

    
6261
#if MG_ENABLE_HTTP_STREAMING_MULTIPART
6262
static void mg_http_multipart_begin(struct mg_connection *nc,
6263
                                    struct http_message *hm, int req_len) {
6264
  struct mg_http_proto_data *pd = mg_http_get_proto_data(nc);
6265
  struct mg_str *ct;
6266
  struct mbuf *io = &nc->recv_mbuf;
6267

    
6268
  char boundary_buf[100];
6269
  char *boundary = boundary_buf;
6270
  int boundary_len;
6271

    
6272
  ct = mg_get_http_header(hm, "Content-Type");
6273
  if (ct == NULL) {
6274
    /* We need more data - or it isn't multipart mesage */
6275
    goto exit_mp;
6276
  }
6277

    
6278
  /* Content-type should start with "multipart" */
6279
  if (ct->len < 9 || strncmp(ct->p, "multipart", 9) != 0) {
6280
    goto exit_mp;
6281
  }
6282

    
6283
  boundary_len =
6284
      mg_http_parse_header2(ct, "boundary", &boundary, sizeof(boundary_buf));
6285
  if (boundary_len == 0) {
6286
    /*
6287
     * Content type is multipart, but there is no boundary,
6288
     * probably malformed request
6289
     */
6290
    nc->flags = MG_F_CLOSE_IMMEDIATELY;
6291
    DBG(("invalid request"));
6292
    goto exit_mp;
6293
  }
6294

    
6295
  /* If we reach this place - that is multipart request */
6296

    
6297
  if (pd->mp_stream.boundary != NULL) {
6298
    /*
6299
     * Another streaming request was in progress,
6300
     * looks like protocol error
6301
     */
6302
    nc->flags |= MG_F_CLOSE_IMMEDIATELY;
6303
  } else {
6304
    struct mg_http_endpoint *ep = NULL;
6305
    pd->mp_stream.state = MPS_BEGIN;
6306
    pd->mp_stream.boundary = strdup(boundary);
6307
    pd->mp_stream.boundary_len = strlen(boundary);
6308
    pd->mp_stream.var_name = pd->mp_stream.file_name = NULL;
6309
    pd->endpoint_handler = nc->handler;
6310

    
6311
    ep = mg_http_get_endpoint_handler(nc->listener, &hm->uri);
6312
    if (ep != NULL) {
6313
      pd->endpoint_handler = ep->handler;
6314
    }
6315

    
6316
    mg_http_call_endpoint_handler(nc, MG_EV_HTTP_MULTIPART_REQUEST, hm);
6317

    
6318
    mbuf_remove(io, req_len);
6319
  }
6320
exit_mp:
6321
  if (boundary != boundary_buf) MG_FREE(boundary);
6322
}
6323

    
6324
#define CONTENT_DISPOSITION "Content-Disposition: "
6325

    
6326
static void mg_http_multipart_call_handler(struct mg_connection *c, int ev,
6327
                                           const char *data, size_t data_len) {
6328
  struct mg_http_multipart_part mp;
6329
  struct mg_http_proto_data *pd = mg_http_get_proto_data(c);
6330
  memset(&mp, 0, sizeof(mp));
6331

    
6332
  mp.var_name = pd->mp_stream.var_name;
6333
  mp.file_name = pd->mp_stream.file_name;
6334
  mp.user_data = pd->mp_stream.user_data;
6335
  mp.data.p = data;
6336
  mp.data.len = data_len;
6337
  mg_call(c, pd->endpoint_handler, c->user_data, ev, &mp);
6338
  pd->mp_stream.user_data = mp.user_data;
6339
}
6340

    
6341
static int mg_http_multipart_got_chunk(struct mg_connection *c) {
6342
  struct mg_http_proto_data *pd = mg_http_get_proto_data(c);
6343
  struct mbuf *io = &c->recv_mbuf;
6344

    
6345
  mg_http_multipart_call_handler(c, MG_EV_HTTP_PART_DATA, io->buf,
6346
                                 pd->mp_stream.prev_io_len);
6347
  mbuf_remove(io, pd->mp_stream.prev_io_len);
6348
  pd->mp_stream.prev_io_len = 0;
6349
  pd->mp_stream.state = MPS_WAITING_FOR_CHUNK;
6350

    
6351
  return 0;
6352
}
6353

    
6354
static int mg_http_multipart_finalize(struct mg_connection *c) {
6355
  struct mg_http_proto_data *pd = mg_http_get_proto_data(c);
6356

    
6357
  mg_http_multipart_call_handler(c, MG_EV_HTTP_PART_END, NULL, 0);
6358
  MG_FREE((void *) pd->mp_stream.file_name);
6359
  pd->mp_stream.file_name = NULL;
6360
  MG_FREE((void *) pd->mp_stream.var_name);
6361
  pd->mp_stream.var_name = NULL;
6362
  mg_http_multipart_call_handler(c, MG_EV_HTTP_MULTIPART_REQUEST_END, NULL, 0);
6363
  mg_http_free_proto_data_mp_stream(&pd->mp_stream);
6364
  pd->mp_stream.state = MPS_FINISHED;
6365

    
6366
  return 1;
6367
}
6368

    
6369
static int mg_http_multipart_wait_for_boundary(struct mg_connection *c) {
6370
  const char *boundary;
6371
  struct mbuf *io = &c->recv_mbuf;
6372
  struct mg_http_proto_data *pd = mg_http_get_proto_data(c);
6373

    
6374
  if (pd->mp_stream.boundary == NULL) {
6375
    pd->mp_stream.state = MPS_FINALIZE;
6376
    DBG(("Invalid request: boundary not initialized"));
6377
    return 0;
6378
  }
6379

    
6380
  if ((int) io->len < pd->mp_stream.boundary_len + 2) {
6381
    return 0;
6382
  }
6383

    
6384
  boundary = c_strnstr(io->buf, pd->mp_stream.boundary, io->len);
6385
  if (boundary != NULL) {
6386
    const char *boundary_end = (boundary + pd->mp_stream.boundary_len);
6387
    if (io->len - (boundary_end - io->buf) < 4) {
6388
      return 0;
6389
    }
6390
    if (strncmp(boundary_end, "--\r\n", 4) == 0) {
6391
      pd->mp_stream.state = MPS_FINALIZE;
6392
      mbuf_remove(io, (boundary_end - io->buf) + 4);
6393
    } else {
6394
      pd->mp_stream.state = MPS_GOT_BOUNDARY;
6395
    }
6396
  } else {
6397
    return 0;
6398
  }
6399

    
6400
  return 1;
6401
}
6402

    
6403
static void mg_http_parse_header_internal(struct mg_str *hdr,
6404
                                          const char *var_name,
6405
                                          struct altbuf *ab);
6406

    
6407
static int mg_http_multipart_process_boundary(struct mg_connection *c) {
6408
  int data_size;
6409
  const char *boundary, *block_begin;
6410
  struct mbuf *io = &c->recv_mbuf;
6411
  struct mg_http_proto_data *pd = mg_http_get_proto_data(c);
6412
  struct altbuf ab_file_name, ab_var_name;
6413
  int line_len;
6414
  boundary = c_strnstr(io->buf, pd->mp_stream.boundary, io->len);
6415
  block_begin = boundary + pd->mp_stream.boundary_len + 2;
6416
  data_size = io->len - (block_begin - io->buf);
6417

    
6418
  altbuf_init(&ab_file_name, NULL, 0);
6419
  altbuf_init(&ab_var_name, NULL, 0);
6420

    
6421
  while (data_size > 0 &&
6422
         (line_len = mg_get_line_len(block_begin, data_size)) != 0) {
6423
    if (line_len > (int) sizeof(CONTENT_DISPOSITION) &&
6424
        mg_ncasecmp(block_begin, CONTENT_DISPOSITION,
6425
                    sizeof(CONTENT_DISPOSITION) - 1) == 0) {
6426
      struct mg_str header;
6427

    
6428
      header.p = block_begin + sizeof(CONTENT_DISPOSITION) - 1;
6429
      header.len = line_len - sizeof(CONTENT_DISPOSITION) - 1;
6430

    
6431
      altbuf_reset(&ab_var_name);
6432
      mg_http_parse_header_internal(&header, "name", &ab_var_name);
6433

    
6434
      altbuf_reset(&ab_file_name);
6435
      mg_http_parse_header_internal(&header, "filename", &ab_file_name);
6436

    
6437
      block_begin += line_len;
6438
      data_size -= line_len;
6439

    
6440
      continue;
6441
    }
6442

    
6443
    if (line_len == 2 && mg_ncasecmp(block_begin, "\r\n", 2) == 0) {
6444
      mbuf_remove(io, block_begin - io->buf + 2);
6445

    
6446
      if (pd->mp_stream.processing_part != 0) {
6447
        mg_http_multipart_call_handler(c, MG_EV_HTTP_PART_END, NULL, 0);
6448
      }
6449

    
6450
      /* Reserve 2 bytes for "\r\n" in file_name and var_name */
6451
      altbuf_append(&ab_file_name, '\0');
6452
      altbuf_append(&ab_file_name, '\0');
6453
      altbuf_append(&ab_var_name, '\0');
6454
      altbuf_append(&ab_var_name, '\0');
6455

    
6456
      MG_FREE((void *) pd->mp_stream.file_name);
6457
      pd->mp_stream.file_name = altbuf_get_buf(&ab_file_name, 1 /* trim */);
6458
      MG_FREE((void *) pd->mp_stream.var_name);
6459
      pd->mp_stream.var_name = altbuf_get_buf(&ab_var_name, 1 /* trim */);
6460

    
6461
      mg_http_multipart_call_handler(c, MG_EV_HTTP_PART_BEGIN, NULL, 0);
6462
      pd->mp_stream.state = MPS_WAITING_FOR_CHUNK;
6463
      pd->mp_stream.processing_part++;
6464
      return 1;
6465
    }
6466

    
6467
    block_begin += line_len;
6468
  }
6469

    
6470
  pd->mp_stream.state = MPS_WAITING_FOR_BOUNDARY;
6471

    
6472
  altbuf_reset(&ab_var_name);
6473
  altbuf_reset(&ab_file_name);
6474

    
6475
  return 0;
6476
}
6477

    
6478
static int mg_http_multipart_continue_wait_for_chunk(struct mg_connection *c) {
6479
  struct mg_http_proto_data *pd = mg_http_get_proto_data(c);
6480
  struct mbuf *io = &c->recv_mbuf;
6481

    
6482
  const char *boundary;
6483
  if ((int) io->len < pd->mp_stream.boundary_len + 6 /* \r\n, --, -- */) {
6484
    return 0;
6485
  }
6486

    
6487
  boundary = c_strnstr(io->buf, pd->mp_stream.boundary, io->len);
6488
  if (boundary == NULL && pd->mp_stream.prev_io_len == 0) {
6489
    pd->mp_stream.prev_io_len = io->len;
6490
    return 0;
6491
  } else if (boundary == NULL &&
6492
             (int) io->len >
6493
                 pd->mp_stream.prev_io_len + pd->mp_stream.boundary_len + 4) {
6494
    pd->mp_stream.state = MPS_GOT_CHUNK;
6495
    return 1;
6496
  } else if (boundary != NULL) {
6497
    int data_size = (boundary - io->buf - 4);
6498
    mg_http_multipart_call_handler(c, MG_EV_HTTP_PART_DATA, io->buf, data_size);
6499
    mbuf_remove(io, (boundary - io->buf));
6500
    pd->mp_stream.prev_io_len = 0;
6501
    pd->mp_stream.state = MPS_WAITING_FOR_BOUNDARY;
6502
    return 1;
6503
  } else {
6504
    return 0;
6505
  }
6506
}
6507

    
6508
static void mg_http_multipart_continue(struct mg_connection *c) {
6509
  struct mg_http_proto_data *pd = mg_http_get_proto_data(c);
6510
  while (1) {
6511
    switch (pd->mp_stream.state) {
6512
      case MPS_BEGIN: {
6513
        pd->mp_stream.state = MPS_WAITING_FOR_BOUNDARY;
6514
        break;
6515
      }
6516
      case MPS_WAITING_FOR_BOUNDARY: {
6517
        if (mg_http_multipart_wait_for_boundary(c) == 0) {
6518
          return;
6519
        }
6520
        break;
6521
      }
6522
      case MPS_GOT_BOUNDARY: {
6523
        if (mg_http_multipart_process_boundary(c) == 0) {
6524
          return;
6525
        }
6526
        break;
6527
      }
6528
      case MPS_WAITING_FOR_CHUNK: {
6529
        if (mg_http_multipart_continue_wait_for_chunk(c) == 0) {
6530
          return;
6531
        }
6532
        break;
6533
      }
6534
      case MPS_GOT_CHUNK: {
6535
        if (mg_http_multipart_got_chunk(c) == 0) {
6536
          return;
6537
        }
6538
        break;
6539
      }
6540
      case MPS_FINALIZE: {
6541
        if (mg_http_multipart_finalize(c) == 0) {
6542
          return;
6543
        }
6544
        break;
6545
      }
6546
      case MPS_FINISHED: {
6547
        mbuf_remove(&c->recv_mbuf, c->recv_mbuf.len);
6548
        return;
6549
      }
6550
    }
6551
  }
6552
}
6553

    
6554
struct file_upload_state {
6555
  char *lfn;
6556
  size_t num_recd;
6557
  FILE *fp;
6558
};
6559

    
6560
#endif /* MG_ENABLE_HTTP_STREAMING_MULTIPART */
6561

    
6562
void mg_set_protocol_http_websocket(struct mg_connection *nc) {
6563
  nc->proto_handler = mg_http_handler;
6564
}
6565

    
6566
const char *mg_status_message(int status_code) {
6567
  switch (status_code) {
6568
    case 206:
6569
      return "Partial Content";
6570
    case 301:
6571
      return "Moved";
6572
    case 302:
6573
      return "Found";
6574
    case 400:
6575
      return "Bad Request";
6576
    case 401:
6577
      return "Unauthorized";
6578
    case 403:
6579
      return "Forbidden";
6580
    case 404:
6581
      return "Not Found";
6582
    case 416:
6583
      return "Requested Range Not Satisfiable";
6584
    case 418:
6585
      return "I'm a teapot";
6586
    case 500:
6587
      return "Internal Server Error";
6588
    case 502:
6589
      return "Bad Gateway";
6590
    case 503:
6591
      return "Service Unavailable";
6592

    
6593
#if MG_ENABLE_EXTRA_ERRORS_DESC
6594
    case 100:
6595
      return "Continue";
6596
    case 101:
6597
      return "Switching Protocols";
6598
    case 102:
6599
      return "Processing";
6600
    case 200:
6601
      return "OK";
6602
    case 201:
6603
      return "Created";
6604
    case 202:
6605
      return "Accepted";
6606
    case 203:
6607
      return "Non-Authoritative Information";
6608
    case 204:
6609
      return "No Content";
6610
    case 205:
6611
      return "Reset Content";
6612
    case 207:
6613
      return "Multi-Status";
6614
    case 208:
6615
      return "Already Reported";
6616
    case 226:
6617
      return "IM Used";
6618
    case 300:
6619
      return "Multiple Choices";
6620
    case 303:
6621
      return "See Other";
6622
    case 304:
6623
      return "Not Modified";
6624
    case 305:
6625
      return "Use Proxy";
6626
    case 306:
6627
      return "Switch Proxy";
6628
    case 307:
6629
      return "Temporary Redirect";
6630
    case 308:
6631
      return "Permanent Redirect";
6632
    case 402:
6633
      return "Payment Required";
6634
    case 405:
6635
      return "Method Not Allowed";
6636
    case 406:
6637
      return "Not Acceptable";
6638
    case 407:
6639
      return "Proxy Authentication Required";
6640
    case 408:
6641
      return "Request Timeout";
6642
    case 409:
6643
      return "Conflict";
6644
    case 410:
6645
      return "Gone";
6646
    case 411:
6647
      return "Length Required";
6648
    case 412:
6649
      return "Precondition Failed";
6650
    case 413:
6651
      return "Payload Too Large";
6652
    case 414:
6653
      return "URI Too Long";
6654
    case 415:
6655
      return "Unsupported Media Type";
6656
    case 417:
6657
      return "Expectation Failed";
6658
    case 422:
6659
      return "Unprocessable Entity";
6660
    case 423:
6661
      return "Locked";
6662
    case 424:
6663
      return "Failed Dependency";
6664
    case 426:
6665
      return "Upgrade Required";
6666
    case 428:
6667
      return "Precondition Required";
6668
    case 429:
6669
      return "Too Many Requests";
6670
    case 431:
6671
      return "Request Header Fields Too Large";
6672
    case 451:
6673
      return "Unavailable For Legal Reasons";
6674
    case 501:
6675
      return "Not Implemented";
6676
    case 504:
6677
      return "Gateway Timeout";
6678
    case 505:
6679
      return "HTTP Version Not Supported";
6680
    case 506:
6681
      return "Variant Also Negotiates";
6682
    case 507:
6683
      return "Insufficient Storage";
6684
    case 508:
6685
      return "Loop Detected";
6686
    case 510:
6687
      return "Not Extended";
6688
    case 511:
6689
      return "Network Authentication Required";
6690
#endif /* MG_ENABLE_EXTRA_ERRORS_DESC */
6691

    
6692
    default:
6693
      return "OK";
6694
  }
6695
}
6696

    
6697
void mg_send_response_line_s(struct mg_connection *nc, int status_code,
6698
                             const struct mg_str extra_headers) {
6699
  mg_printf(nc, "HTTP/1.1 %d %s\r\nServer: %s\r\n", status_code,
6700
            mg_status_message(status_code), mg_version_header);
6701
  if (extra_headers.len > 0) {
6702
    mg_printf(nc, "%.*s\r\n", (int) extra_headers.len, extra_headers.p);
6703
  }
6704
}
6705

    
6706
void mg_send_response_line(struct mg_connection *nc, int status_code,
6707
                           const char *extra_headers) {
6708
  mg_send_response_line_s(nc, status_code, mg_mk_str(extra_headers));
6709
}
6710

    
6711
void mg_http_send_redirect(struct mg_connection *nc, int status_code,
6712
                           const struct mg_str location,
6713
                           const struct mg_str extra_headers) {
6714
  char bbody[100], *pbody = bbody;
6715
  int bl = mg_asprintf(&pbody, sizeof(bbody),
6716
                       "<p>Moved <a href='%.*s'>here</a>.\r\n",
6717
                       (int) location.len, location.p);
6718
  char bhead[150], *phead = bhead;
6719
  mg_asprintf(&phead, sizeof(bhead),
6720
              "Location: %.*s\r\n"
6721
              "Content-Type: text/html\r\n"
6722
              "Content-Length: %d\r\n"
6723
              "Cache-Control: no-cache\r\n"
6724
              "%.*s%s",
6725
              (int) location.len, location.p, bl, (int) extra_headers.len,
6726
              extra_headers.p, (extra_headers.len > 0 ? "\r\n" : ""));
6727
  mg_send_response_line(nc, status_code, phead);
6728
  if (phead != bhead) MG_FREE(phead);
6729
  mg_send(nc, pbody, bl);
6730
  if (pbody != bbody) MG_FREE(pbody);
6731
}
6732

    
6733
void mg_send_head(struct mg_connection *c, int status_code,
6734
                  int64_t content_length, const char *extra_headers) {
6735
  mg_send_response_line(c, status_code, extra_headers);
6736
  if (content_length < 0) {
6737
    mg_printf(c, "%s", "Transfer-Encoding: chunked\r\n");
6738
  } else {
6739
    mg_printf(c, "Content-Length: %" INT64_FMT "\r\n", content_length);
6740
  }
6741
  mg_send(c, "\r\n", 2);
6742
}
6743

    
6744
void mg_http_send_error(struct mg_connection *nc, int code,
6745
                        const char *reason) {
6746
  if (!reason) reason = mg_status_message(code);
6747
  LOG(LL_DEBUG, ("%p %d %s", nc, code, reason));
6748
  mg_send_head(nc, code, strlen(reason),
6749
               "Content-Type: text/plain\r\nConnection: close");
6750
  mg_send(nc, reason, strlen(reason));
6751
  nc->flags |= MG_F_SEND_AND_CLOSE;
6752
}
6753

    
6754
#if MG_ENABLE_FILESYSTEM
6755
static void mg_http_construct_etag(char *buf, size_t buf_len,
6756
                                   const cs_stat_t *st) {
6757
  snprintf(buf, buf_len, "\"%lx.%" INT64_FMT "\"", (unsigned long) st->st_mtime,
6758
           (int64_t) st->st_size);
6759
}
6760

    
6761
#ifndef WINCE
6762
static void mg_gmt_time_string(char *buf, size_t buf_len, time_t *t) {
6763
  strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", gmtime(t));
6764
}
6765
#else
6766
/* Look wince_lib.c for WindowsCE implementation */
6767
static void mg_gmt_time_string(char *buf, size_t buf_len, time_t *t);
6768
#endif
6769

    
6770
static int mg_http_parse_range_header(const struct mg_str *header, int64_t *a,
6771
                                      int64_t *b) {
6772
  /*
6773
   * There is no snscanf. Headers are not guaranteed to be NUL-terminated,
6774
   * so we have this. Ugh.
6775
   */
6776
  int result;
6777
  char *p = (char *) MG_MALLOC(header->len + 1);
6778
  if (p == NULL) return 0;
6779
  memcpy(p, header->p, header->len);
6780
  p[header->len] = '\0';
6781
  result = sscanf(p, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
6782
  MG_FREE(p);
6783
  return result;
6784
}
6785

    
6786
void mg_http_serve_file(struct mg_connection *nc, struct http_message *hm,
6787
                        const char *path, const struct mg_str mime_type,
6788
                        const struct mg_str extra_headers) {
6789
  struct mg_http_proto_data *pd = mg_http_get_proto_data(nc);
6790
  cs_stat_t st;
6791
  LOG(LL_DEBUG, ("%p [%s] %.*s", nc, path, (int) mime_type.len, mime_type.p));
6792
  if (mg_stat(path, &st) != 0 || (pd->file.fp = mg_fopen(path, "rb")) == NULL) {
6793
    int code, err = mg_get_errno();
6794
    switch (err) {
6795
      case EACCES:
6796
        code = 403;
6797
        break;
6798
      case ENOENT:
6799
        code = 404;
6800
        break;
6801
      default:
6802
        code = 500;
6803
    };
6804
    mg_http_send_error(nc, code, "Open failed");
6805
  } else {
6806
    char etag[50], current_time[50], last_modified[50], range[70];
6807
    time_t t = (time_t) mg_time();
6808
    int64_t r1 = 0, r2 = 0, cl = st.st_size;
6809
    struct mg_str *range_hdr = mg_get_http_header(hm, "Range");
6810
    int n, status_code = 200;
6811

    
6812
    /* Handle Range header */
6813
    range[0] = '\0';
6814
    if (range_hdr != NULL &&
6815
        (n = mg_http_parse_range_header(range_hdr, &r1, &r2)) > 0 && r1 >= 0 &&
6816
        r2 >= 0) {
6817
      /* If range is specified like "400-", set second limit to content len */
6818
      if (n == 1) {
6819
        r2 = cl - 1;
6820
      }
6821
      if (r1 > r2 || r2 >= cl) {
6822
        status_code = 416;
6823
        cl = 0;
6824
        snprintf(range, sizeof(range),
6825
                 "Content-Range: bytes */%" INT64_FMT "\r\n",
6826
                 (int64_t) st.st_size);
6827
      } else {
6828
        status_code = 206;
6829
        cl = r2 - r1 + 1;
6830
        snprintf(range, sizeof(range), "Content-Range: bytes %" INT64_FMT
6831
                                       "-%" INT64_FMT "/%" INT64_FMT "\r\n",
6832
                 r1, r1 + cl - 1, (int64_t) st.st_size);
6833
#if _FILE_OFFSET_BITS == 64 || _POSIX_C_SOURCE >= 200112L || \
6834
    _XOPEN_SOURCE >= 600
6835
        fseeko(pd->file.fp, r1, SEEK_SET);
6836
#else
6837
        fseek(pd->file.fp, (long) r1, SEEK_SET);
6838
#endif
6839
      }
6840
    }
6841

    
6842
#if !MG_DISABLE_HTTP_KEEP_ALIVE
6843
    {
6844
      struct mg_str *conn_hdr = mg_get_http_header(hm, "Connection");
6845
      if (conn_hdr != NULL) {
6846
        pd->file.keepalive = (mg_vcasecmp(conn_hdr, "keep-alive") == 0);
6847
      } else {
6848
        pd->file.keepalive = (mg_vcmp(&hm->proto, "HTTP/1.1") == 0);
6849
      }
6850
    }
6851
#endif
6852

    
6853
    mg_http_construct_etag(etag, sizeof(etag), &st);
6854
    mg_gmt_time_string(current_time, sizeof(current_time), &t);
6855
    mg_gmt_time_string(last_modified, sizeof(last_modified), &st.st_mtime);
6856
    /*
6857
     * Content length casted to size_t because:
6858
     * 1) that's the maximum buffer size anyway
6859
     * 2) ESP8266 RTOS SDK newlib vprintf cannot contain a 64bit arg at non-last
6860
     *    position
6861
     * TODO(mkm): fix ESP8266 RTOS SDK
6862
     */
6863
    mg_send_response_line_s(nc, status_code, extra_headers);
6864
    mg_printf(nc,
6865
              "Date: %s\r\n"
6866
              "Last-Modified: %s\r\n"
6867
              "Accept-Ranges: bytes\r\n"
6868
              "Content-Type: %.*s\r\n"
6869
              "Connection: %s\r\n"
6870
              "Content-Length: %" SIZE_T_FMT
6871
              "\r\n"
6872
              "%sEtag: %s\r\n\r\n",
6873
              current_time, last_modified, (int) mime_type.len, mime_type.p,
6874
              (pd->file.keepalive ? "keep-alive" : "close"), (size_t) cl, range,
6875
              etag);
6876

    
6877
    pd->file.cl = cl;
6878
    pd->file.type = DATA_FILE;
6879
    mg_http_transfer_file_data(nc);
6880
  }
6881
}
6882

    
6883
static void mg_http_serve_file2(struct mg_connection *nc, const char *path,
6884
                                struct http_message *hm,
6885
                                struct mg_serve_http_opts *opts) {
6886
#if MG_ENABLE_HTTP_SSI
6887
  if (mg_match_prefix(opts->ssi_pattern, strlen(opts->ssi_pattern), path) > 0) {
6888
    mg_handle_ssi_request(nc, hm, path, opts);
6889
    return;
6890
  }
6891
#endif
6892
  mg_http_serve_file(nc, hm, path, mg_get_mime_type(path, "text/plain", opts),
6893
                     mg_mk_str(opts->extra_headers));
6894
}
6895

    
6896
#endif
6897

    
6898
int mg_url_decode(const char *src, int src_len, char *dst, int dst_len,
6899
                  int is_form_url_encoded) {
6900
  int i, j, a, b;
6901
#define HEXTOI(x) (isdigit(x) ? x - '0' : x - 'W')
6902

    
6903
  for (i = j = 0; i < src_len && j < dst_len - 1; i++, j++) {
6904
    if (src[i] == '%') {
6905
      if (i < src_len - 2 && isxdigit(*(const unsigned char *) (src + i + 1)) &&
6906
          isxdigit(*(const unsigned char *) (src + i + 2))) {
6907
        a = tolower(*(const unsigned char *) (src + i + 1));
6908
        b = tolower(*(const unsigned char *) (src + i + 2));
6909
        dst[j] = (char) ((HEXTOI(a) << 4) | HEXTOI(b));
6910
        i += 2;
6911
      } else {
6912
        return -1;
6913
      }
6914
    } else if (is_form_url_encoded && src[i] == '+') {
6915
      dst[j] = ' ';
6916
    } else {
6917
      dst[j] = src[i];
6918
    }
6919
  }
6920

    
6921
  dst[j] = '\0'; /* Null-terminate the destination */
6922

    
6923
  return i >= src_len ? j : -1;
6924
}
6925

    
6926
int mg_get_http_var(const struct mg_str *buf, const char *name, char *dst,
6927
                    size_t dst_len) {
6928
  const char *p, *e, *s;
6929
  size_t name_len;
6930
  int len;
6931

    
6932
  /*
6933
   * According to the documentation function returns negative
6934
   * value in case of error. For debug purposes it returns:
6935
   * -1 - src is wrong (NUUL)
6936
   * -2 - dst is wrong (NULL)
6937
   * -3 - failed to decode url or dst is to small
6938
   * -4 - name does not exist
6939
   */
6940
  if (dst == NULL || dst_len == 0) {
6941
    len = -2;
6942
  } else if (buf->p == NULL || name == NULL || buf->len == 0) {
6943
    len = -1;
6944
    dst[0] = '\0';
6945
  } else {
6946
    name_len = strlen(name);
6947
    e = buf->p + buf->len;
6948
    len = -4;
6949
    dst[0] = '\0';
6950

    
6951
    for (p = buf->p; p + name_len < e; p++) {
6952
      if ((p == buf->p || p[-1] == '&') && p[name_len] == '=' &&
6953
          !mg_ncasecmp(name, p, name_len)) {
6954
        p += name_len + 1;
6955
        s = (const char *) memchr(p, '&', (size_t)(e - p));
6956
        if (s == NULL) {
6957
          s = e;
6958
        }
6959
        len = mg_url_decode(p, (size_t)(s - p), dst, dst_len, 1);
6960
        /* -1 means: failed to decode or dst is too small */
6961
        if (len == -1) {
6962
          len = -3;
6963
        }
6964
        break;
6965
      }
6966
    }
6967
  }
6968

    
6969
  return len;
6970
}
6971

    
6972
void mg_send_http_chunk(struct mg_connection *nc, const char *buf, size_t len) {
6973
  char chunk_size[50];
6974
  int n;
6975

    
6976
  n = snprintf(chunk_size, sizeof(chunk_size), "%lX\r\n", (unsigned long) len);
6977
  mg_send(nc, chunk_size, n);
6978
  mg_send(nc, buf, len);
6979
  mg_send(nc, "\r\n", 2);
6980
}
6981

    
6982
void mg_printf_http_chunk(struct mg_connection *nc, const char *fmt, ...) {
6983
  char mem[MG_VPRINTF_BUFFER_SIZE], *buf = mem;
6984
  int len;
6985
  va_list ap;
6986

    
6987
  va_start(ap, fmt);
6988
  len = mg_avprintf(&buf, sizeof(mem), fmt, ap);
6989
  va_end(ap);
6990

    
6991
  if (len >= 0) {
6992
    mg_send_http_chunk(nc, buf, len);
6993
  }
6994

    
6995
  /* LCOV_EXCL_START */
6996
  if (buf != mem && buf != NULL) {
6997
    MG_FREE(buf);
6998
  }
6999
  /* LCOV_EXCL_STOP */
7000
}
7001

    
7002
void mg_printf_html_escape(struct mg_connection *nc, const char *fmt, ...) {
7003
  char mem[MG_VPRINTF_BUFFER_SIZE], *buf = mem;
7004
  int i, j, len;
7005
  va_list ap;
7006

    
7007
  va_start(ap, fmt);
7008
  len = mg_avprintf(&buf, sizeof(mem), fmt, ap);
7009
  va_end(ap);
7010

    
7011
  if (len >= 0) {
7012
    for (i = j = 0; i < len; i++) {
7013
      if (buf[i] == '<' || buf[i] == '>') {
7014
        mg_send(nc, buf + j, i - j);
7015
        mg_send(nc, buf[i] == '<' ? "&lt;" : "&gt;", 4);
7016
        j = i + 1;
7017
      }
7018
    }
7019
    mg_send(nc, buf + j, i - j);
7020
  }
7021

    
7022
  /* LCOV_EXCL_START */
7023
  if (buf != mem && buf != NULL) {
7024
    MG_FREE(buf);
7025
  }
7026
  /* LCOV_EXCL_STOP */
7027
}
7028

    
7029
static void mg_http_parse_header_internal(struct mg_str *hdr,
7030
                                          const char *var_name,
7031
                                          struct altbuf *ab) {
7032
  int ch = ' ', ch1 = ',', n = strlen(var_name);
7033
  const char *p, *end = hdr ? hdr->p + hdr->len : NULL, *s = NULL;
7034

    
7035
  /* Find where variable starts */
7036
  for (s = hdr->p; s != NULL && s + n < end; s++) {
7037
    if ((s == hdr->p || s[-1] == ch || s[-1] == ch1 || s[-1] == ';') &&
7038
        s[n] == '=' && !strncmp(s, var_name, n))
7039
      break;
7040
  }
7041

    
7042
  if (s != NULL && &s[n + 1] < end) {
7043
    s += n + 1;
7044
    if (*s == '"' || *s == '\'') {
7045
      ch = ch1 = *s++;
7046
    }
7047
    p = s;
7048
    while (p < end && p[0] != ch && p[0] != ch1) {
7049
      if (ch != ' ' && p[0] == '\\' && p[1] == ch) p++;
7050
      altbuf_append(ab, *p++);
7051
    }
7052

    
7053
    if (ch != ' ' && *p != ch) {
7054
      altbuf_reset(ab);
7055
    }
7056
  }
7057

    
7058
  /* If there is some data, append a NUL. */
7059
  if (ab->len > 0) {
7060
    altbuf_append(ab, '\0');
7061
  }
7062
}
7063

    
7064
int mg_http_parse_header2(struct mg_str *hdr, const char *var_name, char **buf,
7065
                          size_t buf_size) {
7066
  struct altbuf ab;
7067
  altbuf_init(&ab, *buf, buf_size);
7068
  if (hdr == NULL) return 0;
7069
  if (*buf != NULL && buf_size > 0) *buf[0] = '\0';
7070

    
7071
  mg_http_parse_header_internal(hdr, var_name, &ab);
7072

    
7073
  /*
7074
   * Get a (trimmed) buffer, and return a len without a NUL byte which might
7075
   * have been added.
7076
   */
7077
  *buf = altbuf_get_buf(&ab, 1 /* trim */);
7078
  return ab.len > 0 ? ab.len - 1 : 0;
7079
}
7080

    
7081
int mg_http_parse_header(struct mg_str *hdr, const char *var_name, char *buf,
7082
                         size_t buf_size) {
7083
  char *buf2 = buf;
7084

    
7085
  int len = mg_http_parse_header2(hdr, var_name, &buf2, buf_size);
7086

    
7087
  if (buf2 != buf) {
7088
    /* Buffer was not enough and was reallocated: free it and just return 0 */
7089
    MG_FREE(buf2);
7090
    return 0;
7091
  }
7092

    
7093
  return len;
7094
}
7095

    
7096
int mg_get_http_basic_auth(struct http_message *hm, char *user, size_t user_len,
7097
                           char *pass, size_t pass_len) {
7098
  struct mg_str *hdr = mg_get_http_header(hm, "Authorization");
7099
  if (hdr == NULL) return -1;
7100
  return mg_parse_http_basic_auth(hdr, user, user_len, pass, pass_len);
7101
}
7102

    
7103
int mg_parse_http_basic_auth(struct mg_str *hdr, char *user, size_t user_len,
7104
                             char *pass, size_t pass_len) {
7105
  char *buf = NULL;
7106
  char fmt[64];
7107
  int res = 0;
7108

    
7109
  if (mg_strncmp(*hdr, mg_mk_str("Basic "), 6) != 0) return -1;
7110

    
7111
  buf = (char *) MG_MALLOC(hdr->len);
7112
  cs_base64_decode((unsigned char *) hdr->p + 6, hdr->len, buf, NULL);
7113

    
7114
  /* e.g. "%123[^:]:%321[^\n]" */
7115
  snprintf(fmt, sizeof(fmt), "%%%" SIZE_T_FMT "[^:]:%%%" SIZE_T_FMT "[^\n]",
7116
           user_len - 1, pass_len - 1);
7117
  if (sscanf(buf, fmt, user, pass) == 0) {
7118
    res = -1;
7119
  }
7120

    
7121
  MG_FREE(buf);
7122
  return res;
7123
}
7124

    
7125
#if MG_ENABLE_FILESYSTEM
7126
static int mg_is_file_hidden(const char *path,
7127
                             const struct mg_serve_http_opts *opts,
7128
                             int exclude_specials) {
7129
  const char *p1 = opts->per_directory_auth_file;
7130
  const char *p2 = opts->hidden_file_pattern;
7131

    
7132
  /* Strip directory path from the file name */
7133
  const char *pdir = strrchr(path, DIRSEP);
7134
  if (pdir != NULL) {
7135
    path = pdir + 1;
7136
  }
7137

    
7138
  return (exclude_specials && (!strcmp(path, ".") || !strcmp(path, ".."))) ||
7139
         (p1 != NULL && mg_match_prefix(p1, strlen(p1), path) == strlen(p1)) ||
7140
         (p2 != NULL && mg_match_prefix(p2, strlen(p2), path) > 0);
7141
}
7142

    
7143
#if !MG_DISABLE_HTTP_DIGEST_AUTH
7144

    
7145
#ifndef MG_EXT_MD5
7146
void mg_hash_md5_v(size_t num_msgs, const uint8_t *msgs[],
7147
                   const size_t *msg_lens, uint8_t *digest) {
7148
  size_t i;
7149
  cs_md5_ctx md5_ctx;
7150
  cs_md5_init(&md5_ctx);
7151
  for (i = 0; i < num_msgs; i++) {
7152
    cs_md5_update(&md5_ctx, msgs[i], msg_lens[i]);
7153
  }
7154
  cs_md5_final(digest, &md5_ctx);
7155
}
7156
#else
7157
extern void mg_hash_md5_v(size_t num_msgs, const uint8_t *msgs[],
7158
                          const size_t *msg_lens, uint8_t *digest);
7159
#endif
7160

    
7161
void cs_md5(char buf[33], ...) {
7162
  unsigned char hash[16];
7163
  const uint8_t *msgs[20], *p;
7164
  size_t msg_lens[20];
7165
  size_t num_msgs = 0;
7166
  va_list ap;
7167

    
7168
  va_start(ap, buf);
7169
  while ((p = va_arg(ap, const unsigned char *) ) != NULL) {
7170
    msgs[num_msgs] = p;
7171
    msg_lens[num_msgs] = va_arg(ap, size_t);
7172
    num_msgs++;
7173
  }
7174
  va_end(ap);
7175

    
7176
  mg_hash_md5_v(num_msgs, msgs, msg_lens, hash);
7177
  cs_to_hex(buf, hash, sizeof(hash));
7178
}
7179

    
7180
static void mg_mkmd5resp(const char *method, size_t method_len, const char *uri,
7181
                         size_t uri_len, const char *ha1, size_t ha1_len,
7182
                         const char *nonce, size_t nonce_len, const char *nc,
7183
                         size_t nc_len, const char *cnonce, size_t cnonce_len,
7184
                         const char *qop, size_t qop_len, char *resp) {
7185
  static const char colon[] = ":";
7186
  static const size_t one = 1;
7187
  char ha2[33];
7188
  cs_md5(ha2, method, method_len, colon, one, uri, uri_len, NULL);
7189
  cs_md5(resp, ha1, ha1_len, colon, one, nonce, nonce_len, colon, one, nc,
7190
         nc_len, colon, one, cnonce, cnonce_len, colon, one, qop, qop_len,
7191
         colon, one, ha2, sizeof(ha2) - 1, NULL);
7192
}
7193

    
7194
int mg_http_create_digest_auth_header(char *buf, size_t buf_len,
7195
                                      const char *method, const char *uri,
7196
                                      const char *auth_domain, const char *user,
7197
                                      const char *passwd, const char *nonce) {
7198
  static const char colon[] = ":", qop[] = "auth";
7199
  static const size_t one = 1;
7200
  char ha1[33], resp[33], cnonce[40];
7201

    
7202
  snprintf(cnonce, sizeof(cnonce), "%lx", (unsigned long) mg_time());
7203
  cs_md5(ha1, user, (size_t) strlen(user), colon, one, auth_domain,
7204
         (size_t) strlen(auth_domain), colon, one, passwd,
7205
         (size_t) strlen(passwd), NULL);
7206
  mg_mkmd5resp(method, strlen(method), uri, strlen(uri), ha1, sizeof(ha1) - 1,
7207
               nonce, strlen(nonce), "1", one, cnonce, strlen(cnonce), qop,
7208
               sizeof(qop) - 1, resp);
7209
  return snprintf(buf, buf_len,
7210
                  "Authorization: Digest username=\"%s\","
7211
                  "realm=\"%s\",uri=\"%s\",qop=%s,nc=1,cnonce=%s,"
7212
                  "nonce=%s,response=%s\r\n",
7213
                  user, auth_domain, uri, qop, cnonce, nonce, resp);
7214
}
7215

    
7216
/*
7217
 * Check for authentication timeout.
7218
 * Clients send time stamp encoded in nonce. Make sure it is not too old,
7219
 * to prevent replay attacks.
7220
 * Assumption: nonce is a hexadecimal number of seconds since 1970.
7221
 */
7222
static int mg_check_nonce(const char *nonce) {
7223
  unsigned long now = (unsigned long) mg_time();
7224
  unsigned long val = (unsigned long) strtoul(nonce, NULL, 16);
7225
  return (now >= val) && (now - val < 60 * 60);
7226
}
7227

    
7228
int mg_http_check_digest_auth(struct http_message *hm, const char *auth_domain,
7229
                              FILE *fp) {
7230
  int ret = 0;
7231
  struct mg_str *hdr;
7232
  char username_buf[50], cnonce_buf[64], response_buf[40], uri_buf[200],
7233
      qop_buf[20], nc_buf[20], nonce_buf[16];
7234

    
7235
  char *username = username_buf, *cnonce = cnonce_buf, *response = response_buf,
7236
       *uri = uri_buf, *qop = qop_buf, *nc = nc_buf, *nonce = nonce_buf;
7237

    
7238
  /* Parse "Authorization:" header, fail fast on parse error */
7239
  if (hm == NULL || fp == NULL ||
7240
      (hdr = mg_get_http_header(hm, "Authorization")) == NULL ||
7241
      mg_http_parse_header2(hdr, "username", &username, sizeof(username_buf)) ==
7242
          0 ||
7243
      mg_http_parse_header2(hdr, "cnonce", &cnonce, sizeof(cnonce_buf)) == 0 ||
7244
      mg_http_parse_header2(hdr, "response", &response, sizeof(response_buf)) ==
7245
          0 ||
7246
      mg_http_parse_header2(hdr, "uri", &uri, sizeof(uri_buf)) == 0 ||
7247
      mg_http_parse_header2(hdr, "qop", &qop, sizeof(qop_buf)) == 0 ||
7248
      mg_http_parse_header2(hdr, "nc", &nc, sizeof(nc_buf)) == 0 ||
7249
      mg_http_parse_header2(hdr, "nonce", &nonce, sizeof(nonce_buf)) == 0 ||
7250
      mg_check_nonce(nonce) == 0) {
7251
    ret = 0;
7252
    goto clean;
7253
  }
7254

    
7255
  /* NOTE(lsm): due to a bug in MSIE, we do not compare URIs */
7256

    
7257
  ret = mg_check_digest_auth(
7258
      hm->method,
7259
      mg_mk_str_n(
7260
          hm->uri.p,
7261
          hm->uri.len + (hm->query_string.len ? hm->query_string.len + 1 : 0)),
7262
      mg_mk_str(username), mg_mk_str(cnonce), mg_mk_str(response),
7263
      mg_mk_str(qop), mg_mk_str(nc), mg_mk_str(nonce), mg_mk_str(auth_domain),
7264
      fp);
7265

    
7266
clean:
7267
  if (username != username_buf) MG_FREE(username);
7268
  if (cnonce != cnonce_buf) MG_FREE(cnonce);
7269
  if (response != response_buf) MG_FREE(response);
7270
  if (uri != uri_buf) MG_FREE(uri);
7271
  if (qop != qop_buf) MG_FREE(qop);
7272
  if (nc != nc_buf) MG_FREE(nc);
7273
  if (nonce != nonce_buf) MG_FREE(nonce);
7274

    
7275
  return ret;
7276
}
7277

    
7278
int mg_check_digest_auth(struct mg_str method, struct mg_str uri,
7279
                         struct mg_str username, struct mg_str cnonce,
7280
                         struct mg_str response, struct mg_str qop,
7281
                         struct mg_str nc, struct mg_str nonce,
7282
                         struct mg_str auth_domain, FILE *fp) {
7283
  char buf[128], f_user[sizeof(buf)], f_ha1[sizeof(buf)], f_domain[sizeof(buf)];
7284
  char expected_response[33];
7285

    
7286
  /*
7287
   * Read passwords file line by line. If should have htdigest format,
7288
   * i.e. each line should be a colon-separated sequence:
7289
   * USER_NAME:DOMAIN_NAME:HA1_HASH_OF_USER_DOMAIN_AND_PASSWORD
7290
   */
7291
  while (fgets(buf, sizeof(buf), fp) != NULL) {
7292
    if (sscanf(buf, "%[^:]:%[^:]:%s", f_user, f_domain, f_ha1) == 3 &&
7293
        mg_vcmp(&username, f_user) == 0 &&
7294
        mg_vcmp(&auth_domain, f_domain) == 0) {
7295
      /* Username and domain matched, check the password */
7296
      mg_mkmd5resp(method.p, method.len, uri.p, uri.len, f_ha1, strlen(f_ha1),
7297
                   nonce.p, nonce.len, nc.p, nc.len, cnonce.p, cnonce.len,
7298
                   qop.p, qop.len, expected_response);
7299
      LOG(LL_DEBUG,
7300
          ("%.*s %s %.*s %s", (int) username.len, username.p, f_domain,
7301
           (int) response.len, response.p, expected_response));
7302
      return mg_ncasecmp(response.p, expected_response, response.len) == 0;
7303
    }
7304
  }
7305

    
7306
  /* None of the entries in the passwords file matched - return failure */
7307
  return 0;
7308
}
7309

    
7310
int mg_http_is_authorized(struct http_message *hm, struct mg_str path,
7311
                          const char *domain, const char *passwords_file,
7312
                          int flags) {
7313
  char buf[MG_MAX_PATH];
7314
  const char *p;
7315
  FILE *fp;
7316
  int authorized = 1;
7317

    
7318
  if (domain != NULL && passwords_file != NULL) {
7319
    if (flags & MG_AUTH_FLAG_IS_GLOBAL_PASS_FILE) {
7320
      fp = mg_fopen(passwords_file, "r");
7321
    } else if (flags & MG_AUTH_FLAG_IS_DIRECTORY) {
7322
      snprintf(buf, sizeof(buf), "%.*s%c%s", (int) path.len, path.p, DIRSEP,
7323
               passwords_file);
7324
      fp = mg_fopen(buf, "r");
7325
    } else {
7326
      p = strrchr(path.p, DIRSEP);
7327
      if (p == NULL) p = path.p;
7328
      snprintf(buf, sizeof(buf), "%.*s%c%s", (int) (p - path.p), path.p, DIRSEP,
7329
               passwords_file);
7330
      fp = mg_fopen(buf, "r");
7331
    }
7332

    
7333
    if (fp != NULL) {
7334
      authorized = mg_http_check_digest_auth(hm, domain, fp);
7335
      fclose(fp);
7336
    } else if (!(flags & MG_AUTH_FLAG_ALLOW_MISSING_FILE)) {
7337
      authorized = 0;
7338
    }
7339
  }
7340

    
7341
  LOG(LL_DEBUG, ("%.*s %s %x %d", (int) path.len, path.p,
7342
                 passwords_file ? passwords_file : "", flags, authorized));
7343
  return authorized;
7344
}
7345
#else
7346
int mg_http_is_authorized(struct http_message *hm, const struct mg_str path,
7347
                          const char *domain, const char *passwords_file,
7348
                          int flags) {
7349
  (void) hm;
7350
  (void) path;
7351
  (void) domain;
7352
  (void) passwords_file;
7353
  (void) flags;
7354
  return 1;
7355
}
7356
#endif
7357

    
7358
#if MG_ENABLE_DIRECTORY_LISTING
7359
static void mg_escape(const char *src, char *dst, size_t dst_len) {
7360
  size_t n = 0;
7361
  while (*src != '\0' && n + 5 < dst_len) {
7362
    unsigned char ch = *(unsigned char *) src++;
7363
    if (ch == '<') {
7364
      n += snprintf(dst + n, dst_len - n, "%s", "&lt;");
7365
    } else {
7366
      dst[n++] = ch;
7367
    }
7368
  }
7369
  dst[n] = '\0';
7370
}
7371

    
7372
static void mg_print_dir_entry(struct mg_connection *nc, const char *file_name,
7373
                               cs_stat_t *stp) {
7374
  char size[64], mod[64], path[MG_MAX_PATH];
7375
  int64_t fsize = stp->st_size;
7376
  int is_dir = S_ISDIR(stp->st_mode);
7377
  const char *slash = is_dir ? "/" : "";
7378
  struct mg_str href;
7379

    
7380
  if (is_dir) {
7381
    snprintf(size, sizeof(size), "%s", "[DIRECTORY]");
7382
  } else {
7383
    /*
7384
     * We use (double) cast below because MSVC 6 compiler cannot
7385
     * convert unsigned __int64 to double.
7386
     */
7387
    if (fsize < 1024) {
7388
      snprintf(size, sizeof(size), "%d", (int) fsize);
7389
    } else if (fsize < 0x100000) {
7390
      snprintf(size, sizeof(size), "%.1fk", (double) fsize / 1024.0);
7391
    } else if (fsize < 0x40000000) {
7392
      snprintf(size, sizeof(size), "%.1fM", (double) fsize / 1048576);
7393
    } else {
7394
      snprintf(size, sizeof(size), "%.1fG", (double) fsize / 1073741824);
7395
    }
7396
  }
7397
  strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", localtime(&stp->st_mtime));
7398
  mg_escape(file_name, path, sizeof(path));
7399
  href = mg_url_encode(mg_mk_str(file_name));
7400
  mg_printf_http_chunk(nc,
7401
                       "<tr><td><a href=\"%s%s\">%s%s</a></td>"
7402
                       "<td>%s</td><td name=%" INT64_FMT ">%s</td></tr>\n",
7403
                       href.p, slash, path, slash, mod, is_dir ? -1 : fsize,
7404
                       size);
7405
  free((void *) href.p);
7406
}
7407

    
7408
static void mg_scan_directory(struct mg_connection *nc, const char *dir,
7409
                              const struct mg_serve_http_opts *opts,
7410
                              void (*func)(struct mg_connection *, const char *,
7411
                                           cs_stat_t *)) {
7412
  char path[MG_MAX_PATH];
7413
  cs_stat_t st;
7414
  struct dirent *dp;
7415
  DIR *dirp;
7416

    
7417
  LOG(LL_DEBUG, ("%p [%s]", nc, dir));
7418
  if ((dirp = (opendir(dir))) != NULL) {
7419
    while ((dp = readdir(dirp)) != NULL) {
7420
      /* Do not show current dir and hidden files */
7421
      if (mg_is_file_hidden((const char *) dp->d_name, opts, 1)) {
7422
        continue;
7423
      }
7424
      snprintf(path, sizeof(path), "%s/%s", dir, dp->d_name);
7425
      if (mg_stat(path, &st) == 0) {
7426
        func(nc, (const char *) dp->d_name, &st);
7427
      }
7428
    }
7429
    closedir(dirp);
7430
  } else {
7431
    LOG(LL_DEBUG, ("%p opendir(%s) -> %d", nc, dir, mg_get_errno()));
7432
  }
7433
}
7434

    
7435
static void mg_send_directory_listing(struct mg_connection *nc, const char *dir,
7436
                                      struct http_message *hm,
7437
                                      struct mg_serve_http_opts *opts) {
7438
  static const char *sort_js_code =
7439
      "<script>function srt(tb, sc, so, d) {"
7440
      "var tr = Array.prototype.slice.call(tb.rows, 0),"
7441
      "tr = tr.sort(function (a, b) { var c1 = a.cells[sc], c2 = b.cells[sc],"
7442
      "n1 = c1.getAttribute('name'), n2 = c2.getAttribute('name'), "
7443
      "t1 = a.cells[2].getAttribute('name'), "
7444
      "t2 = b.cells[2].getAttribute('name'); "
7445
      "return so * (t1 < 0 && t2 >= 0 ? -1 : t2 < 0 && t1 >= 0 ? 1 : "
7446
      "n1 ? parseInt(n2) - parseInt(n1) : "
7447
      "c1.textContent.trim().localeCompare(c2.textContent.trim())); });";
7448
  static const char *sort_js_code2 =
7449
      "for (var i = 0; i < tr.length; i++) tb.appendChild(tr[i]); "
7450
      "if (!d) window.location.hash = ('sc=' + sc + '&so=' + so); "
7451
      "};"
7452
      "window.onload = function() {"
7453
      "var tb = document.getElementById('tb');"
7454
      "var m = /sc=([012]).so=(1|-1)/.exec(window.location.hash) || [0, 2, 1];"
7455
      "var sc = m[1], so = m[2]; document.onclick = function(ev) { "
7456
      "var c = ev.target.rel; if (c) {if (c == sc) so *= -1; srt(tb, c, so); "
7457
      "sc = c; ev.preventDefault();}};"
7458
      "srt(tb, sc, so, true);"
7459
      "}"
7460
      "</script>";
7461

    
7462
  mg_send_response_line(nc, 200, opts->extra_headers);
7463
  mg_printf(nc, "%s: %s\r\n%s: %s\r\n\r\n", "Transfer-Encoding", "chunked",
7464
            "Content-Type", "text/html; charset=utf-8");
7465

    
7466
  mg_printf_http_chunk(
7467
      nc,
7468
      "<html><head><title>Index of %.*s</title>%s%s"
7469
      "<style>th,td {text-align: left; padding-right: 1em; "
7470
      "font-family: monospace; }</style></head>\n"
7471
      "<body><h1>Index of %.*s</h1>\n<table cellpadding=0><thead>"
7472
      "<tr><th><a href=# rel=0>Name</a></th><th>"
7473
      "<a href=# rel=1>Modified</a</th>"
7474
      "<th><a href=# rel=2>Size</a></th></tr>"
7475
      "<tr><td colspan=3><hr></td></tr>\n"
7476
      "</thead>\n"
7477
      "<tbody id=tb>",
7478
      (int) hm->uri.len, hm->uri.p, sort_js_code, sort_js_code2,
7479
      (int) hm->uri.len, hm->uri.p);
7480
  mg_scan_directory(nc, dir, opts, mg_print_dir_entry);
7481
  mg_printf_http_chunk(nc,
7482
                       "</tbody><tr><td colspan=3><hr></td></tr>\n"
7483
                       "</table>\n"
7484
                       "<address>%s</address>\n"
7485
                       "</body></html>",
7486
                       mg_version_header);
7487
  mg_send_http_chunk(nc, "", 0);
7488
  /* TODO(rojer): Remove when cesanta/dev/issues/197 is fixed. */
7489
  nc->flags |= MG_F_SEND_AND_CLOSE;
7490
}
7491
#endif /* MG_ENABLE_DIRECTORY_LISTING */
7492

    
7493
/*
7494
 * Given a directory path, find one of the files specified in the
7495
 * comma-separated list of index files `list`.
7496
 * First found index file wins. If an index file is found, then gets
7497
 * appended to the `path`, stat-ed, and result of `stat()` passed to `stp`.
7498
 * If index file is not found, then `path` and `stp` remain unchanged.
7499
 */
7500
MG_INTERNAL void mg_find_index_file(const char *path, const char *list,
7501
                                    char **index_file, cs_stat_t *stp) {
7502
  struct mg_str vec;
7503
  size_t path_len = strlen(path);
7504
  int found = 0;
7505
  *index_file = NULL;
7506

    
7507
  /* Traverse index files list. For each entry, append it to the given */
7508
  /* path and see if the file exists. If it exists, break the loop */
7509
  while ((list = mg_next_comma_list_entry(list, &vec, NULL)) != NULL) {
7510
    cs_stat_t st;
7511
    size_t len = path_len + 1 + vec.len + 1;
7512
    *index_file = (char *) MG_REALLOC(*index_file, len);
7513
    if (*index_file == NULL) break;
7514
    snprintf(*index_file, len, "%s%c%.*s", path, DIRSEP, (int) vec.len, vec.p);
7515

    
7516
    /* Does it exist? Is it a file? */
7517
    if (mg_stat(*index_file, &st) == 0 && S_ISREG(st.st_mode)) {
7518
      /* Yes it does, break the loop */
7519
      *stp = st;
7520
      found = 1;
7521
      break;
7522
    }
7523
  }
7524
  if (!found) {
7525
    MG_FREE(*index_file);
7526
    *index_file = NULL;
7527
  }
7528
  LOG(LL_DEBUG, ("[%s] [%s]", path, (*index_file ? *index_file : "")));
7529
}
7530

    
7531
#if MG_ENABLE_HTTP_URL_REWRITES
7532
static int mg_http_send_port_based_redirect(
7533
    struct mg_connection *c, struct http_message *hm,
7534
    const struct mg_serve_http_opts *opts) {
7535
  const char *rewrites = opts->url_rewrites;
7536
  struct mg_str a, b;
7537
  char local_port[20] = {'%'};
7538

    
7539
  mg_conn_addr_to_str(c, local_port + 1, sizeof(local_port) - 1,
7540
                      MG_SOCK_STRINGIFY_PORT);
7541

    
7542
  while ((rewrites = mg_next_comma_list_entry(rewrites, &a, &b)) != NULL) {
7543
    if (mg_vcmp(&a, local_port) == 0) {
7544
      mg_send_response_line(c, 301, NULL);
7545
      mg_printf(c, "Content-Length: 0\r\nLocation: %.*s%.*s\r\n\r\n",
7546
                (int) b.len, b.p, (int) (hm->proto.p - hm->uri.p - 1),
7547
                hm->uri.p);
7548
      return 1;
7549
    }
7550
  }
7551

    
7552
  return 0;
7553
}
7554

    
7555
static void mg_reverse_proxy_handler(struct mg_connection *nc, int ev,
7556
                                     void *ev_data MG_UD_ARG(void *user_data)) {
7557
  struct http_message *hm = (struct http_message *) ev_data;
7558
  struct mg_http_proto_data *pd = mg_http_get_proto_data(nc);
7559

    
7560
  if (pd == NULL || pd->reverse_proxy_data.linked_conn == NULL) {
7561
    DBG(("%p: upstream closed", nc));
7562
    return;
7563
  }
7564

    
7565
  switch (ev) {
7566
    case MG_EV_CONNECT:
7567
      if (*(int *) ev_data != 0) {
7568
        mg_http_send_error(pd->reverse_proxy_data.linked_conn, 502, NULL);
7569
      }
7570
      break;
7571
    /* TODO(mkm): handle streaming */
7572
    case MG_EV_HTTP_REPLY:
7573
      mg_send(pd->reverse_proxy_data.linked_conn, hm->message.p,
7574
              hm->message.len);
7575
      pd->reverse_proxy_data.linked_conn->flags |= MG_F_SEND_AND_CLOSE;
7576
      nc->flags |= MG_F_CLOSE_IMMEDIATELY;
7577
      break;
7578
    case MG_EV_CLOSE:
7579
      pd->reverse_proxy_data.linked_conn->flags |= MG_F_SEND_AND_CLOSE;
7580
      break;
7581
  }
7582

    
7583
#if MG_ENABLE_CALLBACK_USERDATA
7584
  (void) user_data;
7585
#endif
7586
}
7587

    
7588
void mg_http_reverse_proxy(struct mg_connection *nc,
7589
                           const struct http_message *hm, struct mg_str mount,
7590
                           struct mg_str upstream) {
7591
  struct mg_connection *be;
7592
  char burl[256], *purl = burl;
7593
  int i;
7594
  const char *error;
7595
  struct mg_connect_opts opts;
7596
  struct mg_str path = MG_NULL_STR, user_info = MG_NULL_STR, host = MG_NULL_STR;
7597
  memset(&opts, 0, sizeof(opts));
7598
  opts.error_string = &error;
7599

    
7600
  mg_asprintf(&purl, sizeof(burl), "%.*s%.*s", (int) upstream.len, upstream.p,
7601
              (int) (hm->uri.len - mount.len), hm->uri.p + mount.len);
7602

    
7603
  be = mg_connect_http_base(nc->mgr, MG_CB(mg_reverse_proxy_handler, NULL),
7604
                            opts, "http", NULL, "https", NULL, purl, &path,
7605
                            &user_info, &host);
7606
  LOG(LL_DEBUG, ("Proxying %.*s to %s (rule: %.*s)", (int) hm->uri.len,
7607
                 hm->uri.p, purl, (int) mount.len, mount.p));
7608

    
7609
  if (be == NULL) {
7610
    LOG(LL_ERROR, ("Error connecting to %s: %s", purl, error));
7611
    mg_http_send_error(nc, 502, NULL);
7612
    goto cleanup;
7613
  }
7614

    
7615
  /* link connections to each other, they must live and die together */
7616
  mg_http_get_proto_data(be)->reverse_proxy_data.linked_conn = nc;
7617
  mg_http_get_proto_data(nc)->reverse_proxy_data.linked_conn = be;
7618

    
7619
  /* send request upstream */
7620
  mg_printf(be, "%.*s %.*s HTTP/1.1\r\n", (int) hm->method.len, hm->method.p,
7621
            (int) path.len, path.p);
7622

    
7623
  mg_printf(be, "Host: %.*s\r\n", (int) host.len, host.p);
7624
  for (i = 0; i < MG_MAX_HTTP_HEADERS && hm->header_names[i].len > 0; i++) {
7625
    struct mg_str hn = hm->header_names[i];
7626
    struct mg_str hv = hm->header_values[i];
7627

    
7628
    /* we rewrite the host header */
7629
    if (mg_vcasecmp(&hn, "Host") == 0) continue;
7630
    /*
7631
     * Don't pass chunked transfer encoding to the client because hm->body is
7632
     * already dechunked when we arrive here.
7633
     */
7634
    if (mg_vcasecmp(&hn, "Transfer-encoding") == 0 &&
7635
        mg_vcasecmp(&hv, "chunked") == 0) {
7636
      mg_printf(be, "Content-Length: %" SIZE_T_FMT "\r\n", hm->body.len);
7637
      continue;
7638
    }
7639
    /* We don't support proxying Expect: 100-continue. */
7640
    if (mg_vcasecmp(&hn, "Expect") == 0 &&
7641
        mg_vcasecmp(&hv, "100-continue") == 0) {
7642
      continue;
7643
    }
7644

    
7645
    mg_printf(be, "%.*s: %.*s\r\n", (int) hn.len, hn.p, (int) hv.len, hv.p);
7646
  }
7647

    
7648
  mg_send(be, "\r\n", 2);
7649
  mg_send(be, hm->body.p, hm->body.len);
7650

    
7651
cleanup:
7652
  if (purl != burl) MG_FREE(purl);
7653
}
7654

    
7655
static int mg_http_handle_forwarding(struct mg_connection *nc,
7656
                                     struct http_message *hm,
7657
                                     const struct mg_serve_http_opts *opts) {
7658
  const char *rewrites = opts->url_rewrites;
7659
  struct mg_str a, b;
7660
  struct mg_str p1 = MG_MK_STR("http://"), p2 = MG_MK_STR("https://");
7661

    
7662
  while ((rewrites = mg_next_comma_list_entry(rewrites, &a, &b)) != NULL) {
7663
    if (mg_strncmp(a, hm->uri, a.len) == 0) {
7664
      if (mg_strncmp(b, p1, p1.len) == 0 || mg_strncmp(b, p2, p2.len) == 0) {
7665
        mg_http_reverse_proxy(nc, hm, a, b);
7666
        return 1;
7667
      }
7668
    }
7669
  }
7670

    
7671
  return 0;
7672
}
7673
#endif /* MG_ENABLE_FILESYSTEM */
7674

    
7675
MG_INTERNAL int mg_uri_to_local_path(struct http_message *hm,
7676
                                     const struct mg_serve_http_opts *opts,
7677
                                     char **local_path,
7678
                                     struct mg_str *remainder) {
7679
  int ok = 1;
7680
  const char *cp = hm->uri.p, *cp_end = hm->uri.p + hm->uri.len;
7681
  struct mg_str root = {NULL, 0};
7682
  const char *file_uri_start = cp;
7683
  *local_path = NULL;
7684
  remainder->p = NULL;
7685
  remainder->len = 0;
7686

    
7687
  { /* 1. Determine which root to use. */
7688

    
7689
#if MG_ENABLE_HTTP_URL_REWRITES
7690
    const char *rewrites = opts->url_rewrites;
7691
#else
7692
    const char *rewrites = "";
7693
#endif
7694
    struct mg_str *hh = mg_get_http_header(hm, "Host");
7695
    struct mg_str a, b;
7696
    /* Check rewrites first. */
7697
    while ((rewrites = mg_next_comma_list_entry(rewrites, &a, &b)) != NULL) {
7698
      if (a.len > 1 && a.p[0] == '@') {
7699
        /* Host rewrite. */
7700
        if (hh != NULL && hh->len == a.len - 1 &&
7701
            mg_ncasecmp(a.p + 1, hh->p, a.len - 1) == 0) {
7702
          root = b;
7703
          break;
7704
        }
7705
      } else {
7706
        /* Regular rewrite, URI=directory */
7707
        size_t match_len = mg_match_prefix_n(a, hm->uri);
7708
        if (match_len > 0) {
7709
          file_uri_start = hm->uri.p + match_len;
7710
          if (*file_uri_start == '/' || file_uri_start == cp_end) {
7711
            /* Match ended at component boundary, ok. */
7712
          } else if (*(file_uri_start - 1) == '/') {
7713
            /* Pattern ends with '/', backtrack. */
7714
            file_uri_start--;
7715
          } else {
7716
            /* No match: must fall on the component boundary. */
7717
            continue;
7718
          }
7719
          root = b;
7720
          break;
7721
        }
7722
      }
7723
    }
7724
    /* If no rewrite rules matched, use DAV or regular document root. */
7725
    if (root.p == NULL) {
7726
#if MG_ENABLE_HTTP_WEBDAV
7727
      if (opts->dav_document_root != NULL && mg_is_dav_request(&hm->method)) {
7728
        root.p = opts->dav_document_root;
7729
        root.len = strlen(opts->dav_document_root);
7730
      } else
7731
#endif
7732
      {
7733
        root.p = opts->document_root;
7734
        root.len = strlen(opts->document_root);
7735
      }
7736
    }
7737
    assert(root.p != NULL && root.len > 0);
7738
  }
7739

    
7740
  { /* 2. Find where in the canonical URI path the local path ends. */
7741
    const char *u = file_uri_start + 1;
7742
    char *lp = (char *) MG_MALLOC(root.len + hm->uri.len + 1);
7743
    char *lp_end = lp + root.len + hm->uri.len + 1;
7744
    char *p = lp, *ps;
7745
    int exists = 1;
7746
    if (lp == NULL) {
7747
      ok = 0;
7748
      goto out;
7749
    }
7750
    memcpy(p, root.p, root.len);
7751
    p += root.len;
7752
    if (*(p - 1) == DIRSEP) p--;
7753
    *p = '\0';
7754
    ps = p;
7755

    
7756
    /* Chop off URI path components one by one and build local path. */
7757
    while (u <= cp_end) {
7758
      const char *next = u;
7759
      struct mg_str component;
7760
      if (exists) {
7761
        cs_stat_t st;
7762
        exists = (mg_stat(lp, &st) == 0);
7763
        if (exists && S_ISREG(st.st_mode)) {
7764
          /* We found the terminal, the rest of the URI (if any) is path_info.
7765
           */
7766
          if (*(u - 1) == '/') u--;
7767
          break;
7768
        }
7769
      }
7770
      if (u >= cp_end) break;
7771
      parse_uri_component((const char **) &next, cp_end, "/", &component);
7772
      if (component.len > 0) {
7773
        int len;
7774
        memmove(p + 1, component.p, component.len);
7775
        len = mg_url_decode(p + 1, component.len, p + 1, lp_end - p - 1, 0);
7776
        if (len <= 0) {
7777
          ok = 0;
7778
          break;
7779
        }
7780
        component.p = p + 1;
7781
        component.len = len;
7782
        if (mg_vcmp(&component, ".") == 0) {
7783
          /* Yum. */
7784
        } else if (mg_vcmp(&component, "..") == 0) {
7785
          while (p > ps && *p != DIRSEP) p--;
7786
          *p = '\0';
7787
        } else {
7788
          size_t i;
7789
#ifdef _WIN32
7790
          /* On Windows, make sure it's valid Unicode (no funny stuff). */
7791
          wchar_t buf[MG_MAX_PATH * 2];
7792
          if (to_wchar(component.p, buf, MG_MAX_PATH) == 0) {
7793
            DBG(("[%.*s] smells funny", (int) component.len, component.p));
7794
            ok = 0;
7795
            break;
7796
          }
7797
#endif
7798
          *p++ = DIRSEP;
7799
          /* No NULs and DIRSEPs in the component (percent-encoded). */
7800
          for (i = 0; i < component.len; i++, p++) {
7801
            if (*p == '\0' || *p == DIRSEP
7802
#ifdef _WIN32
7803
                /* On Windows, "/" is also accepted, so check for that too. */
7804
                ||
7805
                *p == '/'
7806
#endif
7807
                ) {
7808
              ok = 0;
7809
              break;
7810
            }
7811
          }
7812
        }
7813
      }
7814
      u = next;
7815
    }
7816
    if (ok) {
7817
      *local_path = lp;
7818
      if (u > cp_end) u = cp_end;
7819
      remainder->p = u;
7820
      remainder->len = cp_end - u;
7821
    } else {
7822
      MG_FREE(lp);
7823
    }
7824
  }
7825

    
7826
out:
7827
  LOG(LL_DEBUG,
7828
      ("'%.*s' -> '%s' + '%.*s'", (int) hm->uri.len, hm->uri.p,
7829
       *local_path ? *local_path : "", (int) remainder->len, remainder->p));
7830
  return ok;
7831
}
7832

    
7833
static int mg_get_month_index(const char *s) {
7834
  static const char *month_names[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
7835
                                      "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
7836
  size_t i;
7837

    
7838
  for (i = 0; i < ARRAY_SIZE(month_names); i++)
7839
    if (!strcmp(s, month_names[i])) return (int) i;
7840

    
7841
  return -1;
7842
}
7843

    
7844
static int mg_num_leap_years(int year) {
7845
  return year / 4 - year / 100 + year / 400;
7846
}
7847

    
7848
/* Parse UTC date-time string, and return the corresponding time_t value. */
7849
MG_INTERNAL time_t mg_parse_date_string(const char *datetime) {
7850
  static const unsigned short days_before_month[] = {
7851
      0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};
7852
  char month_str[32];
7853
  int second, minute, hour, day, month, year, leap_days, days;
7854
  time_t result = (time_t) 0;
7855

    
7856
  if (((sscanf(datetime, "%d/%3s/%d %d:%d:%d", &day, month_str, &year, &hour,
7857
               &minute, &second) == 6) ||
7858
       (sscanf(datetime, "%d %3s %d %d:%d:%d", &day, month_str, &year, &hour,
7859
               &minute, &second) == 6) ||
7860
       (sscanf(datetime, "%*3s, %d %3s %d %d:%d:%d", &day, month_str, &year,
7861
               &hour, &minute, &second) == 6) ||
7862
       (sscanf(datetime, "%d-%3s-%d %d:%d:%d", &day, month_str, &year, &hour,
7863
               &minute, &second) == 6)) &&
7864
      year > 1970 && (month = mg_get_month_index(month_str)) != -1) {
7865
    leap_days = mg_num_leap_years(year) - mg_num_leap_years(1970);
7866
    year -= 1970;
7867
    days = year * 365 + days_before_month[month] + (day - 1) + leap_days;
7868
    result = days * 24 * 3600 + hour * 3600 + minute * 60 + second;
7869
  }
7870

    
7871
  return result;
7872
}
7873

    
7874
MG_INTERNAL int mg_is_not_modified(struct http_message *hm, cs_stat_t *st) {
7875
  struct mg_str *hdr;
7876
  if ((hdr = mg_get_http_header(hm, "If-None-Match")) != NULL) {
7877
    char etag[64];
7878
    mg_http_construct_etag(etag, sizeof(etag), st);
7879
    return mg_vcasecmp(hdr, etag) == 0;
7880
  } else if ((hdr = mg_get_http_header(hm, "If-Modified-Since")) != NULL) {
7881
    return st->st_mtime <= mg_parse_date_string(hdr->p);
7882
  } else {
7883
    return 0;
7884
  }
7885
}
7886

    
7887
void mg_http_send_digest_auth_request(struct mg_connection *c,
7888
                                      const char *domain) {
7889
  mg_printf(c,
7890
            "HTTP/1.1 401 Unauthorized\r\n"
7891
            "WWW-Authenticate: Digest qop=\"auth\", "
7892
            "realm=\"%s\", nonce=\"%lx\"\r\n"
7893
            "Content-Length: 0\r\n\r\n",
7894
            domain, (unsigned long) mg_time());
7895
}
7896

    
7897
static void mg_http_send_options(struct mg_connection *nc) {
7898
  mg_printf(nc, "%s",
7899
            "HTTP/1.1 200 OK\r\nAllow: GET, POST, HEAD, CONNECT, OPTIONS"
7900
#if MG_ENABLE_HTTP_WEBDAV
7901
            ", MKCOL, PUT, DELETE, PROPFIND, MOVE\r\nDAV: 1,2"
7902
#endif
7903
            "\r\n\r\n");
7904
  nc->flags |= MG_F_SEND_AND_CLOSE;
7905
}
7906

    
7907
static int mg_is_creation_request(const struct http_message *hm) {
7908
  return mg_vcmp(&hm->method, "MKCOL") == 0 || mg_vcmp(&hm->method, "PUT") == 0;
7909
}
7910

    
7911
MG_INTERNAL void mg_send_http_file(struct mg_connection *nc, char *path,
7912
                                   const struct mg_str *path_info,
7913
                                   struct http_message *hm,
7914
                                   struct mg_serve_http_opts *opts) {
7915
  int exists, is_directory, is_cgi;
7916
#if MG_ENABLE_HTTP_WEBDAV
7917
  int is_dav = mg_is_dav_request(&hm->method);
7918
#else
7919
  int is_dav = 0;
7920
#endif
7921
  char *index_file = NULL;
7922
  cs_stat_t st;
7923

    
7924
  exists = (mg_stat(path, &st) == 0);
7925
  is_directory = exists && S_ISDIR(st.st_mode);
7926

    
7927
  if (is_directory)
7928
    mg_find_index_file(path, opts->index_files, &index_file, &st);
7929

    
7930
  is_cgi =
7931
      (mg_match_prefix(opts->cgi_file_pattern, strlen(opts->cgi_file_pattern),
7932
                       index_file ? index_file : path) > 0);
7933

    
7934
  LOG(LL_DEBUG,
7935
      ("%p %.*s [%s] exists=%d is_dir=%d is_dav=%d is_cgi=%d index=%s", nc,
7936
       (int) hm->method.len, hm->method.p, path, exists, is_directory, is_dav,
7937
       is_cgi, index_file ? index_file : ""));
7938

    
7939
  if (is_directory && hm->uri.p[hm->uri.len - 1] != '/' && !is_dav) {
7940
    mg_printf(nc,
7941
              "HTTP/1.1 301 Moved\r\nLocation: %.*s/\r\n"
7942
              "Content-Length: 0\r\n\r\n",
7943
              (int) hm->uri.len, hm->uri.p);
7944
    MG_FREE(index_file);
7945
    return;
7946
  }
7947

    
7948
  /* If we have path_info, the only way to handle it is CGI. */
7949
  if (path_info->len > 0 && !is_cgi) {
7950
    mg_http_send_error(nc, 501, NULL);
7951
    MG_FREE(index_file);
7952
    return;
7953
  }
7954

    
7955
  if (is_dav && opts->dav_document_root == NULL) {
7956
    mg_http_send_error(nc, 501, NULL);
7957
  } else if (!mg_http_is_authorized(
7958
                 hm, mg_mk_str(path), opts->auth_domain, opts->global_auth_file,
7959
                 ((is_directory ? MG_AUTH_FLAG_IS_DIRECTORY : 0) |
7960
                  MG_AUTH_FLAG_IS_GLOBAL_PASS_FILE |
7961
                  MG_AUTH_FLAG_ALLOW_MISSING_FILE)) ||
7962
             !mg_http_is_authorized(
7963
                 hm, mg_mk_str(path), opts->auth_domain,
7964
                 opts->per_directory_auth_file,
7965
                 ((is_directory ? MG_AUTH_FLAG_IS_DIRECTORY : 0) |
7966
                  MG_AUTH_FLAG_ALLOW_MISSING_FILE))) {
7967
    mg_http_send_digest_auth_request(nc, opts->auth_domain);
7968
  } else if (is_cgi) {
7969
#if MG_ENABLE_HTTP_CGI
7970
    mg_handle_cgi(nc, index_file ? index_file : path, path_info, hm, opts);
7971
#else
7972
    mg_http_send_error(nc, 501, NULL);
7973
#endif /* MG_ENABLE_HTTP_CGI */
7974
  } else if ((!exists ||
7975
              mg_is_file_hidden(path, opts, 0 /* specials are ok */)) &&
7976
             !mg_is_creation_request(hm)) {
7977
    mg_http_send_error(nc, 404, NULL);
7978
#if MG_ENABLE_HTTP_WEBDAV
7979
  } else if (!mg_vcmp(&hm->method, "PROPFIND")) {
7980
    mg_handle_propfind(nc, path, &st, hm, opts);
7981
#if !MG_DISABLE_DAV_AUTH
7982
  } else if (is_dav &&
7983
             (opts->dav_auth_file == NULL ||
7984
              (strcmp(opts->dav_auth_file, "-") != 0 &&
7985
               !mg_http_is_authorized(
7986
                   hm, mg_mk_str(path), opts->auth_domain, opts->dav_auth_file,
7987
                   ((is_directory ? MG_AUTH_FLAG_IS_DIRECTORY : 0) |
7988
                    MG_AUTH_FLAG_IS_GLOBAL_PASS_FILE |
7989
                    MG_AUTH_FLAG_ALLOW_MISSING_FILE))))) {
7990
    mg_http_send_digest_auth_request(nc, opts->auth_domain);
7991
#endif
7992
  } else if (!mg_vcmp(&hm->method, "MKCOL")) {
7993
    mg_handle_mkcol(nc, path, hm);
7994
  } else if (!mg_vcmp(&hm->method, "DELETE")) {
7995
    mg_handle_delete(nc, opts, path);
7996
  } else if (!mg_vcmp(&hm->method, "PUT")) {
7997
    mg_handle_put(nc, path, hm);
7998
  } else if (!mg_vcmp(&hm->method, "MOVE")) {
7999
    mg_handle_move(nc, opts, path, hm);
8000
#if MG_ENABLE_FAKE_DAVLOCK
8001
  } else if (!mg_vcmp(&hm->method, "LOCK")) {
8002
    mg_handle_lock(nc, path);
8003
#endif
8004
#endif /* MG_ENABLE_HTTP_WEBDAV */
8005
  } else if (!mg_vcmp(&hm->method, "OPTIONS")) {
8006
    mg_http_send_options(nc);
8007
  } else if (is_directory && index_file == NULL) {
8008
#if MG_ENABLE_DIRECTORY_LISTING
8009
    if (strcmp(opts->enable_directory_listing, "yes") == 0) {
8010
      mg_send_directory_listing(nc, path, hm, opts);
8011
    } else {
8012
      mg_http_send_error(nc, 403, NULL);
8013
    }
8014
#else
8015
    mg_http_send_error(nc, 501, NULL);
8016
#endif
8017
  } else if (mg_is_not_modified(hm, &st)) {
8018
    mg_http_send_error(nc, 304, "Not Modified");
8019
  } else {
8020
    mg_http_serve_file2(nc, index_file ? index_file : path, hm, opts);
8021
  }
8022
  MG_FREE(index_file);
8023
}
8024

    
8025
void mg_serve_http(struct mg_connection *nc, struct http_message *hm,
8026
                   struct mg_serve_http_opts opts) {
8027
  char *path = NULL;
8028
  struct mg_str *hdr, path_info;
8029
  uint32_t remote_ip = ntohl(*(uint32_t *) &nc->sa.sin.sin_addr);
8030

    
8031
  if (mg_check_ip_acl(opts.ip_acl, remote_ip) != 1) {
8032
    /* Not allowed to connect */
8033
    mg_http_send_error(nc, 403, NULL);
8034
    nc->flags |= MG_F_SEND_AND_CLOSE;
8035
    return;
8036
  }
8037

    
8038
#if MG_ENABLE_HTTP_URL_REWRITES
8039
  if (mg_http_handle_forwarding(nc, hm, &opts)) {
8040
    return;
8041
  }
8042

    
8043
  if (mg_http_send_port_based_redirect(nc, hm, &opts)) {
8044
    return;
8045
  }
8046
#endif
8047

    
8048
  if (opts.document_root == NULL) {
8049
    opts.document_root = ".";
8050
  }
8051
  if (opts.per_directory_auth_file == NULL) {
8052
    opts.per_directory_auth_file = ".htpasswd";
8053
  }
8054
  if (opts.enable_directory_listing == NULL) {
8055
    opts.enable_directory_listing = "yes";
8056
  }
8057
  if (opts.cgi_file_pattern == NULL) {
8058
    opts.cgi_file_pattern = "**.cgi$|**.php$";
8059
  }
8060
  if (opts.ssi_pattern == NULL) {
8061
    opts.ssi_pattern = "**.shtml$|**.shtm$";
8062
  }
8063
  if (opts.index_files == NULL) {
8064
    opts.index_files = "index.html,index.htm,index.shtml,index.cgi,index.php";
8065
  }
8066
  /* Normalize path - resolve "." and ".." (in-place). */
8067
  if (!mg_normalize_uri_path(&hm->uri, &hm->uri)) {
8068
    mg_http_send_error(nc, 400, NULL);
8069
    return;
8070
  }
8071
  if (mg_uri_to_local_path(hm, &opts, &path, &path_info) == 0) {
8072
    mg_http_send_error(nc, 404, NULL);
8073
    return;
8074
  }
8075
  mg_send_http_file(nc, path, &path_info, hm, &opts);
8076

    
8077
  MG_FREE(path);
8078
  path = NULL;
8079

    
8080
  /* Close connection for non-keep-alive requests */
8081
  if (mg_vcmp(&hm->proto, "HTTP/1.1") != 0 ||
8082
      ((hdr = mg_get_http_header(hm, "Connection")) != NULL &&
8083
       mg_vcmp(hdr, "keep-alive") != 0)) {
8084
#if 0
8085
    nc->flags |= MG_F_SEND_AND_CLOSE;
8086
#endif
8087
  }
8088
}
8089

    
8090
#if MG_ENABLE_HTTP_STREAMING_MULTIPART
8091
void mg_file_upload_handler(struct mg_connection *nc, int ev, void *ev_data,
8092
                            mg_fu_fname_fn local_name_fn
8093
                                MG_UD_ARG(void *user_data)) {
8094
  switch (ev) {
8095
    case MG_EV_HTTP_PART_BEGIN: {
8096
      struct mg_http_multipart_part *mp =
8097
          (struct mg_http_multipart_part *) ev_data;
8098
      struct file_upload_state *fus =
8099
          (struct file_upload_state *) MG_CALLOC(1, sizeof(*fus));
8100
      struct mg_str lfn = local_name_fn(nc, mg_mk_str(mp->file_name));
8101
      mp->user_data = NULL;
8102
      if (lfn.p == NULL || lfn.len == 0) {
8103
        LOG(LL_ERROR, ("%p Not allowed to upload %s", nc, mp->file_name));
8104
        mg_printf(nc,
8105
                  "HTTP/1.1 403 Not Allowed\r\n"
8106
                  "Content-Type: text/plain\r\n"
8107
                  "Connection: close\r\n\r\n"
8108
                  "Not allowed to upload %s\r\n",
8109
                  mp->file_name);
8110
        nc->flags |= MG_F_SEND_AND_CLOSE;
8111
        return;
8112
      }
8113
      fus->lfn = (char *) MG_MALLOC(lfn.len + 1);
8114
      memcpy(fus->lfn, lfn.p, lfn.len);
8115
      fus->lfn[lfn.len] = '\0';
8116
      if (lfn.p != mp->file_name) MG_FREE((char *) lfn.p);
8117
      LOG(LL_DEBUG,
8118
          ("%p Receiving file %s -> %s", nc, mp->file_name, fus->lfn));
8119
      fus->fp = mg_fopen(fus->lfn, "w");
8120
      if (fus->fp == NULL) {
8121
        mg_printf(nc,
8122
                  "HTTP/1.1 500 Internal Server Error\r\n"
8123
                  "Content-Type: text/plain\r\n"
8124
                  "Connection: close\r\n\r\n");
8125
        LOG(LL_ERROR, ("Failed to open %s: %d\n", fus->lfn, mg_get_errno()));
8126
        mg_printf(nc, "Failed to open %s: %d\n", fus->lfn, mg_get_errno());
8127
        /* Do not close the connection just yet, discard remainder of the data.
8128
         * This is because at the time of writing some browsers (Chrome) fail to
8129
         * render response before all the data is sent. */
8130
      }
8131
      mp->user_data = (void *) fus;
8132
      break;
8133
    }
8134
    case MG_EV_HTTP_PART_DATA: {
8135
      struct mg_http_multipart_part *mp =
8136
          (struct mg_http_multipart_part *) ev_data;
8137
      struct file_upload_state *fus =
8138
          (struct file_upload_state *) mp->user_data;
8139
      if (fus == NULL || fus->fp == NULL) break;
8140
      if (mg_fwrite(mp->data.p, 1, mp->data.len, fus->fp) != mp->data.len) {
8141
        LOG(LL_ERROR, ("Failed to write to %s: %d, wrote %d", fus->lfn,
8142
                       mg_get_errno(), (int) fus->num_recd));
8143
        if (mg_get_errno() == ENOSPC
8144
#ifdef SPIFFS_ERR_FULL
8145
            || mg_get_errno() == SPIFFS_ERR_FULL
8146
#endif
8147
            ) {
8148
          mg_printf(nc,
8149
                    "HTTP/1.1 413 Payload Too Large\r\n"
8150
                    "Content-Type: text/plain\r\n"
8151
                    "Connection: close\r\n\r\n");
8152
          mg_printf(nc, "Failed to write to %s: no space left; wrote %d\r\n",
8153
                    fus->lfn, (int) fus->num_recd);
8154
        } else {
8155
          mg_printf(nc,
8156
                    "HTTP/1.1 500 Internal Server Error\r\n"
8157
                    "Content-Type: text/plain\r\n"
8158
                    "Connection: close\r\n\r\n");
8159
          mg_printf(nc, "Failed to write to %s: %d, wrote %d", mp->file_name,
8160
                    mg_get_errno(), (int) fus->num_recd);
8161
        }
8162
        fclose(fus->fp);
8163
        remove(fus->lfn);
8164
        fus->fp = NULL;
8165
        /* Do not close the connection just yet, discard remainder of the data.
8166
         * This is because at the time of writing some browsers (Chrome) fail to
8167
         * render response before all the data is sent. */
8168
        return;
8169
      }
8170
      fus->num_recd += mp->data.len;
8171
      LOG(LL_DEBUG, ("%p rec'd %d bytes, %d total", nc, (int) mp->data.len,
8172
                     (int) fus->num_recd));
8173
      break;
8174
    }
8175
    case MG_EV_HTTP_PART_END: {
8176
      struct mg_http_multipart_part *mp =
8177
          (struct mg_http_multipart_part *) ev_data;
8178
      struct file_upload_state *fus =
8179
          (struct file_upload_state *) mp->user_data;
8180
      if (fus == NULL) break;
8181
      if (mp->status >= 0 && fus->fp != NULL) {
8182
        LOG(LL_DEBUG, ("%p Uploaded %s (%s), %d bytes", nc, mp->file_name,
8183
                       fus->lfn, (int) fus->num_recd));
8184
        mg_printf(nc,
8185
                  "HTTP/1.1 200 OK\r\n"
8186
                  "Content-Type: text/plain\r\n"
8187
                  "Connection: close\r\n\r\n"
8188
                  "Ok, %s - %d bytes.\r\n",
8189
                  mp->file_name, (int) fus->num_recd);
8190
      } else {
8191
        LOG(LL_ERROR, ("Failed to store %s (%s)", mp->file_name, fus->lfn));
8192
        /*
8193
         * mp->status < 0 means connection was terminated, so no reason to send
8194
         * HTTP reply
8195
         */
8196
      }
8197
      if (fus->fp != NULL) fclose(fus->fp);
8198
      MG_FREE(fus->lfn);
8199
      MG_FREE(fus);
8200
      mp->user_data = NULL;
8201
      nc->flags |= MG_F_SEND_AND_CLOSE;
8202
      break;
8203
    }
8204
  }
8205

    
8206
#if MG_ENABLE_CALLBACK_USERDATA
8207
  (void) user_data;
8208
#endif
8209
}
8210

    
8211
#endif /* MG_ENABLE_HTTP_STREAMING_MULTIPART */
8212
#endif /* MG_ENABLE_FILESYSTEM */
8213

    
8214
struct mg_connection *mg_connect_http_base(
8215
    struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data),
8216
    struct mg_connect_opts opts, const char *scheme1, const char *scheme2,
8217
    const char *scheme_ssl1, const char *scheme_ssl2, const char *url,
8218
    struct mg_str *path, struct mg_str *user_info, struct mg_str *host) {
8219
  struct mg_connection *nc = NULL;
8220
  unsigned int port_i = 0;
8221
  int use_ssl = 0;
8222
  struct mg_str scheme, query, fragment;
8223
  char conn_addr_buf[2];
8224
  char *conn_addr = conn_addr_buf;
8225

    
8226
  if (mg_parse_uri(mg_mk_str(url), &scheme, user_info, host, &port_i, path,
8227
                   &query, &fragment) != 0) {
8228
    MG_SET_PTRPTR(opts.error_string, "cannot parse url");
8229
    goto out;
8230
  }
8231

    
8232
  /* If query is present, do not strip it. Pass to the caller. */
8233
  if (query.len > 0) path->len += query.len + 1;
8234

    
8235
  if (scheme.len == 0 || mg_vcmp(&scheme, scheme1) == 0 ||
8236
      (scheme2 != NULL && mg_vcmp(&scheme, scheme2) == 0)) {
8237
    use_ssl = 0;
8238
    if (port_i == 0) port_i = 80;
8239
  } else if (mg_vcmp(&scheme, scheme_ssl1) == 0 ||
8240
             (scheme2 != NULL && mg_vcmp(&scheme, scheme_ssl2) == 0)) {
8241
    use_ssl = 1;
8242
    if (port_i == 0) port_i = 443;
8243
  } else {
8244
    goto out;
8245
  }
8246

    
8247
  mg_asprintf(&conn_addr, sizeof(conn_addr_buf), "tcp://%.*s:%u",
8248
              (int) host->len, host->p, port_i);
8249
  if (conn_addr == NULL) goto out;
8250

    
8251
  LOG(LL_DEBUG, ("%s use_ssl? %d %s", url, use_ssl, conn_addr));
8252
  if (use_ssl) {
8253
#if MG_ENABLE_SSL
8254
    /*
8255
     * Schema requires SSL, but no SSL parameters were provided in opts.
8256
     * In order to maintain backward compatibility, use a faux-SSL with no
8257
     * verification.
8258
     */
8259
    if (opts.ssl_ca_cert == NULL) {
8260
      opts.ssl_ca_cert = "*";
8261
    }
8262
#else
8263
    MG_SET_PTRPTR(opts.error_string, "ssl is disabled");
8264
    goto out;
8265
#endif
8266
  }
8267

    
8268
  if ((nc = mg_connect_opt(mgr, conn_addr, MG_CB(ev_handler, user_data),
8269
                           opts)) != NULL) {
8270
    mg_set_protocol_http_websocket(nc);
8271
  }
8272

    
8273
out:
8274
  if (conn_addr != NULL && conn_addr != conn_addr_buf) MG_FREE(conn_addr);
8275
  return nc;
8276
}
8277

    
8278
struct mg_connection *mg_connect_http_opt(
8279
    struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data),
8280
    struct mg_connect_opts opts, const char *url, const char *extra_headers,
8281
    const char *post_data) {
8282
  struct mg_str user = MG_NULL_STR, null_str = MG_NULL_STR;
8283
  struct mg_str host = MG_NULL_STR, path = MG_NULL_STR;
8284
  struct mbuf auth;
8285
  struct mg_connection *nc =
8286
      mg_connect_http_base(mgr, MG_CB(ev_handler, user_data), opts, "http",
8287
                           NULL, "https", NULL, url, &path, &user, &host);
8288

    
8289
  if (nc == NULL) {
8290
    return NULL;
8291
  }
8292

    
8293
  mbuf_init(&auth, 0);
8294
  if (user.len > 0) {
8295
    mg_basic_auth_header(user, null_str, &auth);
8296
  }
8297

    
8298
  if (post_data == NULL) post_data = "";
8299
  if (extra_headers == NULL) extra_headers = "";
8300
  if (path.len == 0) path = mg_mk_str("/");
8301
  if (host.len == 0) host = mg_mk_str("");
8302

    
8303
  mg_printf(nc, "%s %.*s HTTP/1.1\r\nHost: %.*s\r\nContent-Length: %" SIZE_T_FMT
8304
                "\r\n%.*s%s\r\n%s",
8305
            (post_data[0] == '\0' ? "GET" : "POST"), (int) path.len, path.p,
8306
            (int) (path.p - host.p), host.p, strlen(post_data), (int) auth.len,
8307
            (auth.buf == NULL ? "" : auth.buf), extra_headers, post_data);
8308

    
8309
  mbuf_free(&auth);
8310
  return nc;
8311
}
8312
///*WYF add*************************************/
8313
struct mg_connection *mg_connect_http_optDEL(
8314
    struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data),
8315
    struct mg_connect_opts opts, const char *url, const char *extra_headers,
8316
    const char *post_data) {
8317
  struct mg_str user = MG_NULL_STR, null_str = MG_NULL_STR;
8318
  struct mg_str host = MG_NULL_STR, path = MG_NULL_STR;
8319
  struct mbuf auth;
8320
  struct mg_connection *nc =
8321
      mg_connect_http_base(mgr, MG_CB(ev_handler, user_data), opts, "http",
8322
                           NULL, "https", NULL, url, &path, &user, &host);
8323

    
8324
  if (nc == NULL) {
8325
    return NULL;
8326
  }
8327

    
8328
  mbuf_init(&auth, 0);
8329
  if (user.len > 0) {
8330
    mg_basic_auth_header(user, null_str, &auth);
8331
  }
8332

    
8333
  if (post_data == NULL) post_data = "";
8334
  if (extra_headers == NULL) extra_headers = "";
8335
  if (path.len == 0) path = mg_mk_str("/");
8336
  if (host.len == 0) host = mg_mk_str("");
8337

    
8338
  mg_printf(nc, "%s %.*s HTTP/1.1\r\nHost: %.*s\r\nContent-Length: %" SIZE_T_FMT
8339
                "\r\n%.*s%s\r\n%s",
8340
            ("DELETE"), (int) path.len, path.p,
8341
            (int) (path.p - host.p), host.p, strlen(post_data), (int) auth.len,
8342
            (auth.buf == NULL ? "" : auth.buf), extra_headers, post_data);
8343

    
8344
  mbuf_free(&auth);
8345
  return nc;
8346
}
8347
struct mg_connection *mg_connect_httpDEL(
8348
    struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data),
8349
    const char *url, const char *extra_headers, const char *post_data) {
8350
  struct mg_connect_opts opts;
8351
  memset(&opts, 0, sizeof(opts));
8352
  return mg_connect_http_optDEL(mgr, MG_CB(ev_handler, user_data), opts, url,
8353
                             extra_headers, post_data);
8354
}
8355
//**WYF add*************************************/
8356

    
8357
//**LJK add*************************************/
8358
struct mg_connection *mg_connect_http_optPUT(
8359
struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data),
8360
struct mg_connect_opts opts, const char *url, const char *extra_headers,
8361
	const char *post_data) {
8362
	struct mg_str user = MG_NULL_STR, null_str = MG_NULL_STR;
8363
	struct mg_str host = MG_NULL_STR, path = MG_NULL_STR;
8364
	struct mbuf auth;
8365
	struct mg_connection *nc =
8366
		mg_connect_http_base(mgr, MG_CB(ev_handler, user_data), opts, "http",
8367
		NULL, "https", NULL, url, &path, &user, &host);
8368

    
8369
	if (nc == NULL) {
8370
		return NULL;
8371
	}
8372

    
8373
	mbuf_init(&auth, 0);
8374
	if (user.len > 0) {
8375
		mg_basic_auth_header(user, null_str, &auth);
8376
	}
8377

    
8378
	if (post_data == NULL) post_data = "";
8379
	if (extra_headers == NULL) extra_headers = "";
8380
	if (path.len == 0) path = mg_mk_str("/");
8381
	if (host.len == 0) host = mg_mk_str("");
8382

    
8383
	mg_printf(nc, "%s %.*s HTTP/1.1\r\nHost: %.*s\r\nContent-Length: %" SIZE_T_FMT
8384
		"\r\n%.*s%s\r\n%s",
8385
		("PUT"), (int)path.len, path.p,
8386
		(int)(path.p - host.p), host.p, strlen(post_data), (int)auth.len,
8387
		(auth.buf == NULL ? "" : auth.buf), extra_headers, post_data);
8388

    
8389
	mbuf_free(&auth);
8390
	return nc;
8391
}
8392
struct mg_connection *mg_connect_httpPUT(
8393
struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data),
8394
	const char *url, const char *extra_headers, const char *post_data) {
8395
	struct mg_connect_opts opts;
8396
	memset(&opts, 0, sizeof(opts));
8397
	return mg_connect_http_optPUT(mgr, MG_CB(ev_handler, user_data), opts, url,
8398
		extra_headers, post_data);
8399
}
8400

    
8401
struct mg_connection *mg_connect_http_optPOST(
8402
struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data),
8403
struct mg_connect_opts opts, const char *url, const char *extra_headers,
8404
	const char *post_data) {
8405
	struct mg_str user = MG_NULL_STR, null_str = MG_NULL_STR;
8406
	struct mg_str host = MG_NULL_STR, path = MG_NULL_STR;
8407
	struct mbuf auth;
8408
	struct mg_connection *nc =
8409
		mg_connect_http_base(mgr, MG_CB(ev_handler, user_data), opts, "http",
8410
		NULL, "https", NULL, url, &path, &user, &host);
8411

    
8412
	if (nc == NULL) {
8413
		return NULL;
8414
	}
8415

    
8416
	mbuf_init(&auth, 0);
8417
	if (user.len > 0) {
8418
		mg_basic_auth_header(user, null_str, &auth);
8419
	}
8420

    
8421
	if (post_data == NULL) post_data = "";
8422
	if (extra_headers == NULL) extra_headers = "";
8423
	if (path.len == 0) path = mg_mk_str("/");
8424
	if (host.len == 0) host = mg_mk_str("");
8425

    
8426
	mg_printf(nc, "%s %.*s HTTP/1.1\r\nHost: %.*s\r\nContent-Length: %" SIZE_T_FMT
8427
		"\r\n%.*s%s\r\n%s",
8428
		("POST"), (int)path.len, path.p,
8429
		(int)(path.p - host.p), host.p, strlen(post_data), (int)auth.len,
8430
		(auth.buf == NULL ? "" : auth.buf), extra_headers, post_data);
8431

    
8432
	mbuf_free(&auth);
8433
	return nc;
8434
}
8435
struct mg_connection *mg_connect_httpPOST(
8436
struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data),
8437
	const char *url, const char *extra_headers, const char *post_data) {
8438
	struct mg_connect_opts opts;
8439
	memset(&opts, 0, sizeof(opts));
8440
	return mg_connect_http_optPOST(mgr, MG_CB(ev_handler, user_data), opts, url,
8441
		extra_headers, post_data);
8442
}
8443
//**LJK add*************************************/
8444

    
8445
struct mg_connection *mg_connect_http(
8446
    struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data),
8447
    const char *url, const char *extra_headers, const char *post_data) {
8448
  struct mg_connect_opts opts;
8449
  memset(&opts, 0, sizeof(opts));
8450
  return mg_connect_http_opt(mgr, MG_CB(ev_handler, user_data), opts, url,
8451
                             extra_headers, post_data);
8452
}
8453

    
8454
size_t mg_parse_multipart(const char *buf, size_t buf_len, char *var_name,
8455
                          size_t var_name_len, char *file_name,
8456
                          size_t file_name_len, const char **data,
8457
                          size_t *data_len) {
8458
  static const char cd[] = "Content-Disposition: ";
8459
  size_t hl, bl, n, ll, pos, cdl = sizeof(cd) - 1;
8460
  int shl;
8461

    
8462
  if (buf == NULL || buf_len <= 0) return 0;
8463
  if ((shl = mg_http_get_request_len(buf, buf_len)) <= 0) return 0;
8464
  hl = shl;
8465
  if (buf[0] != '-' || buf[1] != '-' || buf[2] == '\n') return 0;
8466

    
8467
  /* Get boundary length */
8468
  bl = mg_get_line_len(buf, buf_len);
8469

    
8470
  /* Loop through headers, fetch variable name and file name */
8471
  var_name[0] = file_name[0] = '\0';
8472
  for (n = bl; (ll = mg_get_line_len(buf + n, hl - n)) > 0; n += ll) {
8473
    if (mg_ncasecmp(cd, buf + n, cdl) == 0) {
8474
      struct mg_str header;
8475
      header.p = buf + n + cdl;
8476
      header.len = ll - (cdl + 2);
8477
      {
8478
        char *var_name2 = var_name;
8479
        mg_http_parse_header2(&header, "name", &var_name2, var_name_len);
8480
        /* TODO: handle reallocated buffer correctly */
8481
        if (var_name2 != var_name) {
8482
          MG_FREE(var_name2);
8483
          var_name[0] = '\0';
8484
        }
8485
      }
8486
      {
8487
        char *file_name2 = file_name;
8488
        mg_http_parse_header2(&header, "filename", &file_name2, file_name_len);
8489
        /* TODO: handle reallocated buffer correctly */
8490
        if (file_name2 != file_name) {
8491
          MG_FREE(file_name2);
8492
          file_name[0] = '\0';
8493
        }
8494
      }
8495
    }
8496
  }
8497

    
8498
  /* Scan through the body, search for terminating boundary */
8499
  for (pos = hl; pos + (bl - 2) < buf_len; pos++) {
8500
    if (buf[pos] == '-' && !strncmp(buf, &buf[pos], bl - 2)) {
8501
      if (data_len != NULL) *data_len = (pos - 2) - hl;
8502
      if (data != NULL) *data = buf + hl;
8503
      return pos;
8504
    }
8505
  }
8506

    
8507
  return 0;
8508
}
8509

    
8510
void mg_register_http_endpoint_opt(struct mg_connection *nc,
8511
                                   const char *uri_path,
8512
                                   mg_event_handler_t handler,
8513
                                   struct mg_http_endpoint_opts opts) {
8514
  struct mg_http_proto_data *pd = NULL;
8515
  struct mg_http_endpoint *new_ep = NULL;
8516

    
8517
  if (nc == NULL) return;
8518
  new_ep = (struct mg_http_endpoint *) MG_CALLOC(1, sizeof(*new_ep));
8519
  if (new_ep == NULL) return;
8520

    
8521
  pd = mg_http_get_proto_data(nc);
8522
  new_ep->uri_pattern = mg_strdup(mg_mk_str(uri_path));
8523
  if (opts.auth_domain != NULL && opts.auth_file != NULL) {
8524
    new_ep->auth_domain = strdup(opts.auth_domain);
8525
    new_ep->auth_file = strdup(opts.auth_file);
8526
  }
8527
  new_ep->handler = handler;
8528
#if MG_ENABLE_CALLBACK_USERDATA
8529
  new_ep->user_data = opts.user_data;
8530
#endif
8531
  new_ep->next = pd->endpoints;
8532
  pd->endpoints = new_ep;
8533
}
8534

    
8535
static void mg_http_call_endpoint_handler(struct mg_connection *nc, int ev,
8536
                                          struct http_message *hm) {
8537
  struct mg_http_proto_data *pd = mg_http_get_proto_data(nc);
8538
  void *user_data = nc->user_data;
8539

    
8540
  if (ev == MG_EV_HTTP_REQUEST
8541
#if MG_ENABLE_HTTP_STREAMING_MULTIPART
8542
      || ev == MG_EV_HTTP_MULTIPART_REQUEST
8543
#endif
8544
      ) {
8545
    struct mg_http_endpoint *ep =
8546
        mg_http_get_endpoint_handler(nc->listener, &hm->uri);
8547
    if (ep != NULL) {
8548
#if MG_ENABLE_FILESYSTEM && !MG_DISABLE_HTTP_DIGEST_AUTH
8549
      if (!mg_http_is_authorized(hm, hm->uri, ep->auth_domain, ep->auth_file,
8550
                                 MG_AUTH_FLAG_IS_GLOBAL_PASS_FILE)) {
8551
        mg_http_send_digest_auth_request(nc, ep->auth_domain);
8552
        return;
8553
      }
8554
#endif
8555
      pd->endpoint_handler = ep->handler;
8556
#if MG_ENABLE_CALLBACK_USERDATA
8557
      user_data = ep->user_data;
8558
#endif
8559
    }
8560
  }
8561
  mg_call(nc, pd->endpoint_handler ? pd->endpoint_handler : nc->handler,
8562
          user_data, ev, hm);
8563
}
8564

    
8565
void mg_register_http_endpoint(struct mg_connection *nc, const char *uri_path,
8566
                               MG_CB(mg_event_handler_t handler,
8567
                                     void *user_data)) {
8568
  struct mg_http_endpoint_opts opts;
8569
  memset(&opts, 0, sizeof(opts));
8570
#if MG_ENABLE_CALLBACK_USERDATA
8571
  opts.user_data = user_data;
8572
#endif
8573
  mg_register_http_endpoint_opt(nc, uri_path, handler, opts);
8574
}
8575

    
8576
#endif /* MG_ENABLE_HTTP */
8577
#ifdef MG_MODULE_LINES
8578
#line 1 "mongoose/src/mg_http_cgi.c"
8579
#endif
8580
/*
8581
 * Copyright (c) 2014-2016 Cesanta Software Limited
8582
 * All rights reserved
8583
 */
8584

    
8585
#ifndef _WIN32
8586
#include <signal.h>
8587
#endif
8588

    
8589
#if MG_ENABLE_HTTP && MG_ENABLE_HTTP_CGI
8590

    
8591
#ifndef MG_MAX_CGI_ENVIR_VARS
8592
#define MG_MAX_CGI_ENVIR_VARS 64
8593
#endif
8594

    
8595
#ifndef MG_ENV_EXPORT_TO_CGI
8596
#define MG_ENV_EXPORT_TO_CGI "MONGOOSE_CGI"
8597
#endif
8598

    
8599
#define MG_F_HTTP_CGI_PARSE_HEADERS MG_F_USER_1
8600

    
8601
/*
8602
 * This structure helps to create an environment for the spawned CGI program.
8603
 * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
8604
 * last element must be NULL.
8605
 * However, on Windows there is a requirement that all these VARIABLE=VALUE\0
8606
 * strings must reside in a contiguous buffer. The end of the buffer is
8607
 * marked by two '\0' characters.
8608
 * We satisfy both worlds: we create an envp array (which is vars), all
8609
 * entries are actually pointers inside buf.
8610
 */
8611
struct mg_cgi_env_block {
8612
  struct mg_connection *nc;
8613
  char buf[MG_CGI_ENVIRONMENT_SIZE];       /* Environment buffer */
8614
  const char *vars[MG_MAX_CGI_ENVIR_VARS]; /* char *envp[] */
8615
  int len;                                 /* Space taken */
8616
  int nvars;                               /* Number of variables in envp[] */
8617
};
8618

    
8619
#ifdef _WIN32
8620
struct mg_threadparam {
8621
  sock_t s;
8622
  HANDLE hPipe;
8623
};
8624

    
8625
static int mg_wait_until_ready(sock_t sock, int for_read) {
8626
  fd_set set;
8627
  FD_ZERO(&set);
8628
  FD_SET(sock, &set);
8629
  return select(sock + 1, for_read ? &set : 0, for_read ? 0 : &set, 0, 0) == 1;
8630
}
8631

    
8632
static void *mg_push_to_stdin(void *arg) {
8633
  struct mg_threadparam *tp = (struct mg_threadparam *) arg;
8634
  int n, sent, stop = 0;
8635
  DWORD k;
8636
  char buf[BUFSIZ];
8637

    
8638
  while (!stop && mg_wait_until_ready(tp->s, 1) &&
8639
         (n = recv(tp->s, buf, sizeof(buf), 0)) > 0) {
8640
    if (n == -1 && GetLastError() == WSAEWOULDBLOCK) continue;
8641
    for (sent = 0; !stop && sent < n; sent += k) {
8642
      if (!WriteFile(tp->hPipe, buf + sent, n - sent, &k, 0)) stop = 1;
8643
    }
8644
  }
8645
  DBG(("%s", "FORWARED EVERYTHING TO CGI"));
8646
  CloseHandle(tp->hPipe);
8647
  MG_FREE(tp);
8648
  return NULL;
8649
}
8650

    
8651
static void *mg_pull_from_stdout(void *arg) {
8652
  struct mg_threadparam *tp = (struct mg_threadparam *) arg;
8653
  int k = 0, stop = 0;
8654
  DWORD n, sent;
8655
  char buf[BUFSIZ];
8656

    
8657
  while (!stop && ReadFile(tp->hPipe, buf, sizeof(buf), &n, NULL)) {
8658
    for (sent = 0; !stop && sent < n; sent += k) {
8659
      if (mg_wait_until_ready(tp->s, 0) &&
8660
          (k = send(tp->s, buf + sent, n - sent, 0)) <= 0)
8661
        stop = 1;
8662
    }
8663
  }
8664
  DBG(("%s", "EOF FROM CGI"));
8665
  CloseHandle(tp->hPipe);
8666
  shutdown(tp->s, 2);  // Without this, IO thread may get truncated data
8667
  closesocket(tp->s);
8668
  MG_FREE(tp);
8669
  return NULL;
8670
}
8671

    
8672
static void mg_spawn_stdio_thread(sock_t sock, HANDLE hPipe,
8673
                                  void *(*func)(void *)) {
8674
  struct mg_threadparam *tp = (struct mg_threadparam *) MG_MALLOC(sizeof(*tp));
8675
  if (tp != NULL) {
8676
    tp->s = sock;
8677
    tp->hPipe = hPipe;
8678
    mg_start_thread(func, tp);
8679
  }
8680
}
8681

    
8682
static void mg_abs_path(const char *utf8_path, char *abs_path, size_t len) {
8683
  wchar_t buf[MG_MAX_PATH], buf2[MG_MAX_PATH];
8684
  to_wchar(utf8_path, buf, ARRAY_SIZE(buf));
8685
  GetFullPathNameW(buf, ARRAY_SIZE(buf2), buf2, NULL);
8686
  WideCharToMultiByte(CP_UTF8, 0, buf2, wcslen(buf2) + 1, abs_path, len, 0, 0);
8687
}
8688

    
8689
static int mg_start_process(const char *interp, const char *cmd,
8690
                            const char *env, const char *envp[],
8691
                            const char *dir, sock_t sock) {
8692
  STARTUPINFOW si;
8693
  PROCESS_INFORMATION pi;
8694
  HANDLE a[2], b[2], me = GetCurrentProcess();
8695
  wchar_t wcmd[MG_MAX_PATH], full_dir[MG_MAX_PATH];
8696
  char buf[MG_MAX_PATH], buf2[MG_MAX_PATH], buf5[MG_MAX_PATH],
8697
      buf4[MG_MAX_PATH], cmdline[MG_MAX_PATH];
8698
  DWORD flags = DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS;
8699
  FILE *fp;
8700

    
8701
  memset(&si, 0, sizeof(si));
8702
  memset(&pi, 0, sizeof(pi));
8703

    
8704
  si.cb = sizeof(si);
8705
  si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
8706
  si.wShowWindow = SW_HIDE;
8707
  si.hStdError = GetStdHandle(STD_ERROR_HANDLE);
8708

    
8709
  CreatePipe(&a[0], &a[1], NULL, 0);
8710
  CreatePipe(&b[0], &b[1], NULL, 0);
8711
  DuplicateHandle(me, a[0], me, &si.hStdInput, 0, TRUE, flags);
8712
  DuplicateHandle(me, b[1], me, &si.hStdOutput, 0, TRUE, flags);
8713

    
8714
  if (interp == NULL && (fp = mg_fopen(cmd, "r")) != NULL) {
8715
    buf[0] = buf[1] = '\0';
8716
    fgets(buf, sizeof(buf), fp);
8717
    buf[sizeof(buf) - 1] = '\0';
8718
    if (buf[0] == '#' && buf[1] == '!') {
8719
      interp = buf + 2;
8720
      /* Trim leading spaces: https://github.com/cesanta/mongoose/issues/489 */
8721
      while (*interp != '\0' && isspace(*(unsigned char *) interp)) {
8722
        interp++;
8723
      }
8724
    }
8725
    fclose(fp);
8726
  }
8727

    
8728
  snprintf(buf, sizeof(buf), "%s/%s", dir, cmd);
8729
  mg_abs_path(buf, buf2, ARRAY_SIZE(buf2));
8730

    
8731
  mg_abs_path(dir, buf5, ARRAY_SIZE(buf5));
8732
  to_wchar(dir, full_dir, ARRAY_SIZE(full_dir));
8733

    
8734
  if (interp != NULL) {
8735
    mg_abs_path(interp, buf4, ARRAY_SIZE(buf4));
8736
    snprintf(cmdline, sizeof(cmdline), "%s \"%s\"", buf4, buf2);
8737
  } else {
8738
    snprintf(cmdline, sizeof(cmdline), "\"%s\"", buf2);
8739
  }
8740
  to_wchar(cmdline, wcmd, ARRAY_SIZE(wcmd));
8741

    
8742
  if (CreateProcessW(NULL, wcmd, NULL, NULL, TRUE, CREATE_NEW_PROCESS_GROUP,
8743
                     (void *) env, full_dir, &si, &pi) != 0) {
8744
    mg_spawn_stdio_thread(sock, a[1], mg_push_to_stdin);
8745
    mg_spawn_stdio_thread(sock, b[0], mg_pull_from_stdout);
8746

    
8747
    CloseHandle(si.hStdOutput);
8748
    CloseHandle(si.hStdInput);
8749

    
8750
    CloseHandle(pi.hThread);
8751
    CloseHandle(pi.hProcess);
8752
  } else {
8753
    CloseHandle(a[1]);
8754
    CloseHandle(b[0]);
8755
    closesocket(sock);
8756
  }
8757
  DBG(("CGI command: [%ls] -> %p", wcmd, pi.hProcess));
8758

    
8759
  /* Not closing a[0] and b[1] because we've used DUPLICATE_CLOSE_SOURCE */
8760
  (void) envp;
8761
  return (pi.hProcess != NULL);
8762
}
8763
#else
8764
static int mg_start_process(const char *interp, const char *cmd,
8765
                            const char *env, const char *envp[],
8766
                            const char *dir, sock_t sock) {
8767
  char buf[500];
8768
  pid_t pid = fork();
8769
  (void) env;
8770

    
8771
  if (pid == 0) {
8772
    /*
8773
     * In Linux `chdir` declared with `warn_unused_result` attribute
8774
     * To shutup compiler we have yo use result in some way
8775
     */
8776
    int tmp = chdir(dir);
8777
    (void) tmp;
8778
    (void) dup2(sock, 0);
8779
    (void) dup2(sock, 1);
8780
    closesocket(sock);
8781

    
8782
    /*
8783
     * After exec, all signal handlers are restored to their default values,
8784
     * with one exception of SIGCHLD. According to POSIX.1-2001 and Linux's
8785
     * implementation, SIGCHLD's handler will leave unchanged after exec
8786
     * if it was set to be ignored. Restore it to default action.
8787
     */
8788
    signal(SIGCHLD, SIG_DFL);
8789

    
8790
    if (interp == NULL) {
8791
      execle(cmd, cmd, (char *) 0, envp); /* (char *) 0 to squash warning */
8792
    } else {
8793
      execle(interp, interp, cmd, (char *) 0, envp);
8794
    }
8795
    snprintf(buf, sizeof(buf),
8796
             "Status: 500\r\n\r\n"
8797
             "500 Server Error: %s%s%s: %s",
8798
             interp == NULL ? "" : interp, interp == NULL ? "" : " ", cmd,
8799
             strerror(errno));
8800
    send(1, buf, strlen(buf), 0);
8801
    _exit(EXIT_FAILURE); /* exec call failed */
8802
  }
8803

    
8804
  return (pid != 0);
8805
}
8806
#endif /* _WIN32 */
8807

    
8808
/*
8809
 * Append VARIABLE=VALUE\0 string to the buffer, and add a respective
8810
 * pointer into the vars array.
8811
 */
8812
static char *mg_addenv(struct mg_cgi_env_block *block, const char *fmt, ...) {
8813
  int n, space;
8814
  char *added = block->buf + block->len;
8815
  va_list ap;
8816

    
8817
  /* Calculate how much space is left in the buffer */
8818
  space = sizeof(block->buf) - (block->len + 2);
8819
  if (space > 0) {
8820
    /* Copy VARIABLE=VALUE\0 string into the free space */
8821
    va_start(ap, fmt);
8822
    n = vsnprintf(added, (size_t) space, fmt, ap);
8823
    va_end(ap);
8824

    
8825
    /* Make sure we do not overflow buffer and the envp array */
8826
    if (n > 0 && n + 1 < space &&
8827
        block->nvars < (int) ARRAY_SIZE(block->vars) - 2) {
8828
      /* Append a pointer to the added string into the envp array */
8829
      block->vars[block->nvars++] = added;
8830
      /* Bump up used length counter. Include \0 terminator */
8831
      block->len += n + 1;
8832
    }
8833
  }
8834

    
8835
  return added;
8836
}
8837

    
8838
static void mg_addenv2(struct mg_cgi_env_block *blk, const char *name) {
8839
  const char *s;
8840
  if ((s = getenv(name)) != NULL) mg_addenv(blk, "%s=%s", name, s);
8841
}
8842

    
8843
static void mg_prepare_cgi_environment(struct mg_connection *nc,
8844
                                       const char *prog,
8845
                                       const struct mg_str *path_info,
8846
                                       const struct http_message *hm,
8847
                                       const struct mg_serve_http_opts *opts,
8848
                                       struct mg_cgi_env_block *blk) {
8849
  const char *s;
8850
  struct mg_str *h;
8851
  char *p;
8852
  size_t i;
8853
  char buf[100];
8854
  size_t path_info_len = path_info != NULL ? path_info->len : 0;
8855

    
8856
  blk->len = blk->nvars = 0;
8857
  blk->nc = nc;
8858

    
8859
  if ((s = getenv("SERVER_NAME")) != NULL) {
8860
    mg_addenv(blk, "SERVER_NAME=%s", s);
8861
  } else {
8862
    mg_sock_to_str(nc->sock, buf, sizeof(buf), 3);
8863
    mg_addenv(blk, "SERVER_NAME=%s", buf);
8864
  }
8865
  mg_addenv(blk, "SERVER_ROOT=%s", opts->document_root);
8866
  mg_addenv(blk, "DOCUMENT_ROOT=%s", opts->document_root);
8867
  mg_addenv(blk, "SERVER_SOFTWARE=%s/%s", "Mongoose", MG_VERSION);
8868

    
8869
  /* Prepare the environment block */
8870
  mg_addenv(blk, "%s", "GATEWAY_INTERFACE=CGI/1.1");
8871
  mg_addenv(blk, "%s", "SERVER_PROTOCOL=HTTP/1.1");
8872
  mg_addenv(blk, "%s", "REDIRECT_STATUS=200"); /* For PHP */
8873

    
8874
  mg_addenv(blk, "REQUEST_METHOD=%.*s", (int) hm->method.len, hm->method.p);
8875

    
8876
  mg_addenv(blk, "REQUEST_URI=%.*s%s%.*s", (int) hm->uri.len, hm->uri.p,
8877
            hm->query_string.len == 0 ? "" : "?", (int) hm->query_string.len,
8878
            hm->query_string.p);
8879

    
8880
  mg_conn_addr_to_str(nc, buf, sizeof(buf),
8881
                      MG_SOCK_STRINGIFY_REMOTE | MG_SOCK_STRINGIFY_IP);
8882
  mg_addenv(blk, "REMOTE_ADDR=%s", buf);
8883
  mg_conn_addr_to_str(nc, buf, sizeof(buf), MG_SOCK_STRINGIFY_PORT);
8884
  mg_addenv(blk, "SERVER_PORT=%s", buf);
8885

    
8886
  s = hm->uri.p + hm->uri.len - path_info_len - 1;
8887
  if (*s == '/') {
8888
    const char *base_name = strrchr(prog, DIRSEP);
8889
    mg_addenv(blk, "SCRIPT_NAME=%.*s/%s", (int) (s - hm->uri.p), hm->uri.p,
8890
              (base_name != NULL ? base_name + 1 : prog));
8891
  } else {
8892
    mg_addenv(blk, "SCRIPT_NAME=%.*s", (int) (s - hm->uri.p + 1), hm->uri.p);
8893
  }
8894
  mg_addenv(blk, "SCRIPT_FILENAME=%s", prog);
8895

    
8896
  if (path_info != NULL && path_info->len > 0) {
8897
    mg_addenv(blk, "PATH_INFO=%.*s", (int) path_info->len, path_info->p);
8898
    /* Not really translated... */
8899
    mg_addenv(blk, "PATH_TRANSLATED=%.*s", (int) path_info->len, path_info->p);
8900
  }
8901

    
8902
#if MG_ENABLE_SSL
8903
  mg_addenv(blk, "HTTPS=%s", (nc->flags & MG_F_SSL ? "on" : "off"));
8904
#else
8905
  mg_addenv(blk, "HTTPS=off");
8906
#endif
8907

    
8908
  if ((h = mg_get_http_header((struct http_message *) hm, "Content-Type")) !=
8909
      NULL) {
8910
    mg_addenv(blk, "CONTENT_TYPE=%.*s", (int) h->len, h->p);
8911
  }
8912

    
8913
  if (hm->query_string.len > 0) {
8914
    mg_addenv(blk, "QUERY_STRING=%.*s", (int) hm->query_string.len,
8915
              hm->query_string.p);
8916
  }
8917

    
8918
  if ((h = mg_get_http_header((struct http_message *) hm, "Content-Length")) !=
8919
      NULL) {
8920
    mg_addenv(blk, "CONTENT_LENGTH=%.*s", (int) h->len, h->p);
8921
  }
8922

    
8923
  mg_addenv2(blk, "PATH");
8924
  mg_addenv2(blk, "TMP");
8925
  mg_addenv2(blk, "TEMP");
8926
  mg_addenv2(blk, "TMPDIR");
8927
  mg_addenv2(blk, "PERLLIB");
8928
  mg_addenv2(blk, MG_ENV_EXPORT_TO_CGI);
8929

    
8930
#ifdef _WIN32
8931
  mg_addenv2(blk, "COMSPEC");
8932
  mg_addenv2(blk, "SYSTEMROOT");
8933
  mg_addenv2(blk, "SystemDrive");
8934
  mg_addenv2(blk, "ProgramFiles");
8935
  mg_addenv2(blk, "ProgramFiles(x86)");
8936
  mg_addenv2(blk, "CommonProgramFiles(x86)");
8937
#else
8938
  mg_addenv2(blk, "LD_LIBRARY_PATH");
8939
#endif /* _WIN32 */
8940

    
8941
  /* Add all headers as HTTP_* variables */
8942
  for (i = 0; hm->header_names[i].len > 0; i++) {
8943
    p = mg_addenv(blk, "HTTP_%.*s=%.*s", (int) hm->header_names[i].len,
8944
                  hm->header_names[i].p, (int) hm->header_values[i].len,
8945
                  hm->header_values[i].p);
8946

    
8947
    /* Convert variable name into uppercase, and change - to _ */
8948
    for (; *p != '=' && *p != '\0'; p++) {
8949
      if (*p == '-') *p = '_';
8950
      *p = (char) toupper(*(unsigned char *) p);
8951
    }
8952
  }
8953

    
8954
  blk->vars[blk->nvars++] = NULL;
8955
  blk->buf[blk->len++] = '\0';
8956
}
8957

    
8958
static void mg_cgi_ev_handler(struct mg_connection *cgi_nc, int ev,
8959
                              void *ev_data MG_UD_ARG(void *user_data)) {
8960
#if !MG_ENABLE_CALLBACK_USERDATA
8961
  void *user_data = cgi_nc->user_data;
8962
#endif
8963
  struct mg_connection *nc = (struct mg_connection *) user_data;
8964
  (void) ev_data;
8965

    
8966
  if (nc == NULL) {
8967
    /* The corresponding network connection was closed. */
8968
    cgi_nc->flags |= MG_F_CLOSE_IMMEDIATELY;
8969
    return;
8970
  }
8971

    
8972
  switch (ev) {
8973
    case MG_EV_RECV:
8974
      /*
8975
       * CGI script does not output reply line, like "HTTP/1.1 CODE XXXXX\n"
8976
       * It outputs headers, then body. Headers might include "Status"
8977
       * header, which changes CODE, and it might include "Location" header
8978
       * which changes CODE to 302.
8979
       *
8980
       * Therefore we do not send the output from the CGI script to the user
8981
       * until all CGI headers are received.
8982
       *
8983
       * Here we parse the output from the CGI script, and if all headers has
8984
       * been received, send appropriate reply line, and forward all
8985
       * received headers to the client.
8986
       */
8987
      if (nc->flags & MG_F_HTTP_CGI_PARSE_HEADERS) {
8988
        struct mbuf *io = &cgi_nc->recv_mbuf;
8989
        int len = mg_http_get_request_len(io->buf, io->len);
8990

    
8991
        if (len == 0) break;
8992
        if (len < 0 || io->len > MG_MAX_HTTP_REQUEST_SIZE) {
8993
          cgi_nc->flags |= MG_F_CLOSE_IMMEDIATELY;
8994
          mg_http_send_error(nc, 500, "Bad headers");
8995
        } else {
8996
          struct http_message hm;
8997
          struct mg_str *h;
8998
          mg_http_parse_headers(io->buf, io->buf + io->len, io->len, &hm);
8999
          if (mg_get_http_header(&hm, "Location") != NULL) {
9000
            mg_printf(nc, "%s", "HTTP/1.1 302 Moved\r\n");
9001
          } else if ((h = mg_get_http_header(&hm, "Status")) != NULL) {
9002
            mg_printf(nc, "HTTP/1.1 %.*s\r\n", (int) h->len, h->p);
9003
          } else {
9004
            mg_printf(nc, "%s", "HTTP/1.1 200 OK\r\n");
9005
          }
9006
        }
9007
        nc->flags &= ~MG_F_HTTP_CGI_PARSE_HEADERS;
9008
      }
9009
      if (!(nc->flags & MG_F_HTTP_CGI_PARSE_HEADERS)) {
9010
        mg_forward(cgi_nc, nc);
9011
      }
9012
      break;
9013
    case MG_EV_CLOSE:
9014
      DBG(("%p CLOSE", cgi_nc));
9015
      mg_http_free_proto_data_cgi(&mg_http_get_proto_data(nc)->cgi);
9016
      nc->flags |= MG_F_SEND_AND_CLOSE;
9017
      break;
9018
  }
9019
}
9020

    
9021
MG_INTERNAL void mg_handle_cgi(struct mg_connection *nc, const char *prog,
9022
                               const struct mg_str *path_info,
9023
                               const struct http_message *hm,
9024
                               const struct mg_serve_http_opts *opts) {
9025
  struct mg_cgi_env_block blk;
9026
  char dir[MG_MAX_PATH];
9027
  const char *p;
9028
  sock_t fds[2];
9029

    
9030
  DBG(("%p [%s]", nc, prog));
9031
  mg_prepare_cgi_environment(nc, prog, path_info, hm, opts, &blk);
9032
  /*
9033
   * CGI must be executed in its own directory. 'dir' must point to the
9034
   * directory containing executable program, 'p' must point to the
9035
   * executable program name relative to 'dir'.
9036
   */
9037
  if ((p = strrchr(prog, DIRSEP)) == NULL) {
9038
    snprintf(dir, sizeof(dir), "%s", ".");
9039
  } else {
9040
    snprintf(dir, sizeof(dir), "%.*s", (int) (p - prog), prog);
9041
    prog = p + 1;
9042
  }
9043

    
9044
  if (!mg_socketpair(fds, SOCK_STREAM)) {
9045
    nc->flags |= MG_F_CLOSE_IMMEDIATELY;
9046
    return;
9047
  }
9048

    
9049
#ifndef _WIN32
9050
  struct sigaction sa;
9051

    
9052
  sigemptyset(&sa.sa_mask);
9053
  sa.sa_handler = SIG_IGN;
9054
  sa.sa_flags = 0;
9055
  sigaction(SIGCHLD, &sa, NULL);
9056
#endif
9057

    
9058
  if (mg_start_process(opts->cgi_interpreter, prog, blk.buf, blk.vars, dir,
9059
                       fds[1]) != 0) {
9060
    size_t n = nc->recv_mbuf.len - (hm->message.len - hm->body.len);
9061
    struct mg_connection *cgi_nc =
9062
        mg_add_sock(nc->mgr, fds[0], mg_cgi_ev_handler MG_UD_ARG(nc));
9063
    struct mg_http_proto_data *cgi_pd = mg_http_get_proto_data(nc);
9064
    cgi_pd->cgi.cgi_nc = cgi_nc;
9065
#if !MG_ENABLE_CALLBACK_USERDATA
9066
    cgi_pd->cgi.cgi_nc->user_data = nc;
9067
#endif
9068
    nc->flags |= MG_F_HTTP_CGI_PARSE_HEADERS;
9069
    /* Push POST data to the CGI */
9070
    if (n > 0 && n < nc->recv_mbuf.len) {
9071
      mg_send(cgi_pd->cgi.cgi_nc, hm->body.p, n);
9072
    }
9073
    mbuf_remove(&nc->recv_mbuf, nc->recv_mbuf.len);
9074
  } else {
9075
    closesocket(fds[0]);
9076
    mg_http_send_error(nc, 500, "CGI failure");
9077
  }
9078

    
9079
#ifndef _WIN32
9080
  closesocket(fds[1]); /* On Windows, CGI stdio thread closes that socket */
9081
#endif
9082
}
9083

    
9084
MG_INTERNAL void mg_http_free_proto_data_cgi(struct mg_http_proto_data_cgi *d) {
9085
  if (d == NULL) return;
9086
  if (d->cgi_nc != NULL) {
9087
    d->cgi_nc->flags |= MG_F_CLOSE_IMMEDIATELY;
9088
    d->cgi_nc->user_data = NULL;
9089
  }
9090
  memset(d, 0, sizeof(*d));
9091
}
9092

    
9093
#endif /* MG_ENABLE_HTTP && MG_ENABLE_HTTP_CGI */
9094
#ifdef MG_MODULE_LINES
9095
#line 1 "mongoose/src/mg_http_ssi.c"
9096
#endif
9097
/*
9098
 * Copyright (c) 2014-2016 Cesanta Software Limited
9099
 * All rights reserved
9100
 */
9101

    
9102
#if MG_ENABLE_HTTP && MG_ENABLE_HTTP_SSI && MG_ENABLE_FILESYSTEM
9103

    
9104
static void mg_send_ssi_file(struct mg_connection *nc, struct http_message *hm,
9105
                             const char *path, FILE *fp, int include_level,
9106
                             const struct mg_serve_http_opts *opts);
9107

    
9108
static void mg_send_file_data(struct mg_connection *nc, FILE *fp) {
9109
  char buf[BUFSIZ];
9110
  size_t n;
9111
  while ((n = mg_fread(buf, 1, sizeof(buf), fp)) > 0) {
9112
    mg_send(nc, buf, n);
9113
  }
9114
}
9115

    
9116
static void mg_do_ssi_include(struct mg_connection *nc, struct http_message *hm,
9117
                              const char *ssi, char *tag, int include_level,
9118
                              const struct mg_serve_http_opts *opts) {
9119
  char file_name[MG_MAX_PATH], path[MG_MAX_PATH], *p;
9120
  FILE *fp;
9121

    
9122
  /*
9123
   * sscanf() is safe here, since send_ssi_file() also uses buffer
9124
   * of size MG_BUF_LEN to get the tag. So strlen(tag) is always < MG_BUF_LEN.
9125
   */
9126
  if (sscanf(tag, " virtual=\"%[^\"]\"", file_name) == 1) {
9127
    /* File name is relative to the webserver root */
9128
    snprintf(path, sizeof(path), "%s/%s", opts->document_root, file_name);
9129
  } else if (sscanf(tag, " abspath=\"%[^\"]\"", file_name) == 1) {
9130
    /*
9131
     * File name is relative to the webserver working directory
9132
     * or it is absolute system path
9133
     */
9134
    snprintf(path, sizeof(path), "%s", file_name);
9135
  } else if (sscanf(tag, " file=\"%[^\"]\"", file_name) == 1 ||
9136
             sscanf(tag, " \"%[^\"]\"", file_name) == 1) {
9137
    /* File name is relative to the currect document */
9138
    snprintf(path, sizeof(path), "%s", ssi);
9139
    if ((p = strrchr(path, DIRSEP)) != NULL) {
9140
      p[1] = '\0';
9141
    }
9142
    snprintf(path + strlen(path), sizeof(path) - strlen(path), "%s", file_name);
9143
  } else {
9144
    mg_printf(nc, "Bad SSI #include: [%s]", tag);
9145
    return;
9146
  }
9147

    
9148
  if ((fp = mg_fopen(path, "rb")) == NULL) {
9149
    mg_printf(nc, "SSI include error: mg_fopen(%s): %s", path,
9150
              strerror(mg_get_errno()));
9151
  } else {
9152
    mg_set_close_on_exec((sock_t) fileno(fp));
9153
    if (mg_match_prefix(opts->ssi_pattern, strlen(opts->ssi_pattern), path) >
9154
        0) {
9155
      mg_send_ssi_file(nc, hm, path, fp, include_level + 1, opts);
9156
    } else {
9157
      mg_send_file_data(nc, fp);
9158
    }
9159
    fclose(fp);
9160
  }
9161
}
9162

    
9163
#if MG_ENABLE_HTTP_SSI_EXEC
9164
static void do_ssi_exec(struct mg_connection *nc, char *tag) {
9165
  char cmd[BUFSIZ];
9166
  FILE *fp;
9167

    
9168
  if (sscanf(tag, " \"%[^\"]\"", cmd) != 1) {
9169
    mg_printf(nc, "Bad SSI #exec: [%s]", tag);
9170
  } else if ((fp = popen(cmd, "r")) == NULL) {
9171
    mg_printf(nc, "Cannot SSI #exec: [%s]: %s", cmd, strerror(mg_get_errno()));
9172
  } else {
9173
    mg_send_file_data(nc, fp);
9174
    pclose(fp);
9175
  }
9176
}
9177
#endif /* MG_ENABLE_HTTP_SSI_EXEC */
9178

    
9179
/*
9180
 * SSI directive has the following format:
9181
 * <!--#directive parameter=value parameter=value -->
9182
 */
9183
static void mg_send_ssi_file(struct mg_connection *nc, struct http_message *hm,
9184
                             const char *path, FILE *fp, int include_level,
9185
                             const struct mg_serve_http_opts *opts) {
9186
  static const struct mg_str btag = MG_MK_STR("<!--#");
9187
  static const struct mg_str d_include = MG_MK_STR("include");
9188
  static const struct mg_str d_call = MG_MK_STR("call");
9189
#if MG_ENABLE_HTTP_SSI_EXEC
9190
  static const struct mg_str d_exec = MG_MK_STR("exec");
9191
#endif
9192
  char buf[BUFSIZ], *p = buf + btag.len; /* p points to SSI directive */
9193
  int ch, len, in_ssi_tag;
9194

    
9195
  if (include_level > 10) {
9196
    mg_printf(nc, "SSI #include level is too deep (%s)", path);
9197
    return;
9198
  }
9199

    
9200
  in_ssi_tag = len = 0;
9201
  while ((ch = fgetc(fp)) != EOF) {
9202
    if (in_ssi_tag && ch == '>' && buf[len - 1] == '-' && buf[len - 2] == '-') {
9203
      size_t i = len - 2;
9204
      in_ssi_tag = 0;
9205

    
9206
      /* Trim closing --> */
9207
      buf[i--] = '\0';
9208
      while (i > 0 && buf[i] == ' ') {
9209
        buf[i--] = '\0';
9210
      }
9211

    
9212
      /* Handle known SSI directives */
9213
      if (strncmp(p, d_include.p, d_include.len) == 0) {
9214
        mg_do_ssi_include(nc, hm, path, p + d_include.len + 1, include_level,
9215
                          opts);
9216
      } else if (strncmp(p, d_call.p, d_call.len) == 0) {
9217
        struct mg_ssi_call_ctx cctx;
9218
        memset(&cctx, 0, sizeof(cctx));
9219
        cctx.req = hm;
9220
        cctx.file = mg_mk_str(path);
9221
        cctx.arg = mg_mk_str(p + d_call.len + 1);
9222
        mg_call(nc, NULL, nc->user_data, MG_EV_SSI_CALL,
9223
                (void *) cctx.arg.p); /* NUL added above */
9224
        mg_call(nc, NULL, nc->user_data, MG_EV_SSI_CALL_CTX, &cctx);
9225
#if MG_ENABLE_HTTP_SSI_EXEC
9226
      } else if (strncmp(p, d_exec.p, d_exec.len) == 0) {
9227
        do_ssi_exec(nc, p + d_exec.len + 1);
9228
#endif
9229
      } else {
9230
        /* Silently ignore unknown SSI directive. */
9231
      }
9232
      len = 0;
9233
    } else if (ch == '<') {
9234
      in_ssi_tag = 1;
9235
      if (len > 0) {
9236
        mg_send(nc, buf, (size_t) len);
9237
      }
9238
      len = 0;
9239
      buf[len++] = ch & 0xff;
9240
    } else if (in_ssi_tag) {
9241
      if (len == (int) btag.len && strncmp(buf, btag.p, btag.len) != 0) {
9242
        /* Not an SSI tag */
9243
        in_ssi_tag = 0;
9244
      } else if (len == (int) sizeof(buf) - 2) {
9245
        mg_printf(nc, "%s: SSI tag is too large", path);
9246
        len = 0;
9247
      }
9248
      buf[len++] = ch & 0xff;
9249
    } else {
9250
      buf[len++] = ch & 0xff;
9251
      if (len == (int) sizeof(buf)) {
9252
        mg_send(nc, buf, (size_t) len);
9253
        len = 0;
9254
      }
9255
    }
9256
  }
9257

    
9258
  /* Send the rest of buffered data */
9259
  if (len > 0) {
9260
    mg_send(nc, buf, (size_t) len);
9261
  }
9262
}
9263

    
9264
MG_INTERNAL void mg_handle_ssi_request(struct mg_connection *nc,
9265
                                       struct http_message *hm,
9266
                                       const char *path,
9267
                                       const struct mg_serve_http_opts *opts) {
9268
  FILE *fp;
9269
  struct mg_str mime_type;
9270
  DBG(("%p %s", nc, path));
9271

    
9272
  if ((fp = mg_fopen(path, "rb")) == NULL) {
9273
    mg_http_send_error(nc, 404, NULL);
9274
  } else {
9275
    mg_set_close_on_exec((sock_t) fileno(fp));
9276

    
9277
    mime_type = mg_get_mime_type(path, "text/plain", opts);
9278
    mg_send_response_line(nc, 200, opts->extra_headers);
9279
    mg_printf(nc,
9280
              "Content-Type: %.*s\r\n"
9281
              "Connection: close\r\n\r\n",
9282
              (int) mime_type.len, mime_type.p);
9283
    mg_send_ssi_file(nc, hm, path, fp, 0, opts);
9284
    fclose(fp);
9285
    nc->flags |= MG_F_SEND_AND_CLOSE;
9286
  }
9287
}
9288

    
9289
#endif /* MG_ENABLE_HTTP_SSI && MG_ENABLE_HTTP && MG_ENABLE_FILESYSTEM */
9290
#ifdef MG_MODULE_LINES
9291
#line 1 "mongoose/src/mg_http_webdav.c"
9292
#endif
9293
/*
9294
 * Copyright (c) 2014-2016 Cesanta Software Limited
9295
 * All rights reserved
9296
 */
9297

    
9298
#if MG_ENABLE_HTTP && MG_ENABLE_HTTP_WEBDAV
9299

    
9300
MG_INTERNAL int mg_is_dav_request(const struct mg_str *s) {
9301
  static const char *methods[] = {
9302
    "PUT",
9303
    "DELETE",
9304
    "MKCOL",
9305
    "PROPFIND",
9306
    "MOVE"
9307
#if MG_ENABLE_FAKE_DAVLOCK
9308
    ,
9309
    "LOCK",
9310
    "UNLOCK"
9311
#endif
9312
  };
9313
  size_t i;
9314

    
9315
  for (i = 0; i < ARRAY_SIZE(methods); i++) {
9316
    if (mg_vcmp(s, methods[i]) == 0) {
9317
      return 1;
9318
    }
9319
  }
9320

    
9321
  return 0;
9322
}
9323

    
9324
static int mg_mkdir(const char *path, uint32_t mode) {
9325
#ifndef _WIN32
9326
  return mkdir(path, mode);
9327
#else
9328
  (void) mode;
9329
  return _mkdir(path);
9330
#endif
9331
}
9332

    
9333
static void mg_print_props(struct mg_connection *nc, const char *name,
9334
                           cs_stat_t *stp) {
9335
  char mtime[64];
9336
  time_t t = stp->st_mtime; /* store in local variable for NDK compile */
9337
  struct mg_str name_esc = mg_url_encode(mg_mk_str(name));
9338
  mg_gmt_time_string(mtime, sizeof(mtime), &t);
9339
  mg_printf(nc,
9340
            "<d:response>"
9341
            "<d:href>%s</d:href>"
9342
            "<d:propstat>"
9343
            "<d:prop>"
9344
            "<d:resourcetype>%s</d:resourcetype>"
9345
            "<d:getcontentlength>%" INT64_FMT
9346
            "</d:getcontentlength>"
9347
            "<d:getlastmodified>%s</d:getlastmodified>"
9348
            "</d:prop>"
9349
            "<d:status>HTTP/1.1 200 OK</d:status>"
9350
            "</d:propstat>"
9351
            "</d:response>\n",
9352
            name_esc.p, S_ISDIR(stp->st_mode) ? "<d:collection/>" : "",
9353
            (int64_t) stp->st_size, mtime);
9354
  free((void *) name_esc.p);
9355
}
9356

    
9357
MG_INTERNAL void mg_handle_propfind(struct mg_connection *nc, const char *path,
9358
                                    cs_stat_t *stp, struct http_message *hm,
9359
                                    struct mg_serve_http_opts *opts) {
9360
  static const char header[] =
9361
      "HTTP/1.1 207 Multi-Status\r\n"
9362
      "Connection: close\r\n"
9363
      "Content-Type: text/xml; charset=utf-8\r\n\r\n"
9364
      "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
9365
      "<d:multistatus xmlns:d='DAV:'>\n";
9366
  static const char footer[] = "</d:multistatus>\n";
9367
  const struct mg_str *depth = mg_get_http_header(hm, "Depth");
9368

    
9369
  /* Print properties for the requested resource itself */
9370
  if (S_ISDIR(stp->st_mode) &&
9371
      strcmp(opts->enable_directory_listing, "yes") != 0) {
9372
    mg_printf(nc, "%s", "HTTP/1.1 403 Directory Listing Denied\r\n\r\n");
9373
  } else {
9374
    char uri[MG_MAX_PATH];
9375
    mg_send(nc, header, sizeof(header) - 1);
9376
    snprintf(uri, sizeof(uri), "%.*s", (int) hm->uri.len, hm->uri.p);
9377
    mg_print_props(nc, uri, stp);
9378
    if (S_ISDIR(stp->st_mode) && (depth == NULL || mg_vcmp(depth, "0") != 0)) {
9379
      mg_scan_directory(nc, path, opts, mg_print_props);
9380
    }
9381
    mg_send(nc, footer, sizeof(footer) - 1);
9382
    nc->flags |= MG_F_SEND_AND_CLOSE;
9383
  }
9384
}
9385

    
9386
#if MG_ENABLE_FAKE_DAVLOCK
9387
/*
9388
 * Windows explorer (probably there are another WebDav clients like it)
9389
 * requires LOCK support in webdav. W/out this, it still works, but fails
9390
 * to save file: shows error message and offers "Save As".
9391
 * "Save as" works, but this message is very annoying.
9392
 * This is fake lock, which doesn't lock something, just returns LOCK token,
9393
 * UNLOCK always answers "OK".
9394
 * With this fake LOCK Windows Explorer looks happy and saves file.
9395
 * NOTE: that is not DAV LOCK imlementation, it is just a way to shut up
9396
 * Windows native DAV client. This is why FAKE LOCK is not enabed by default
9397
 */
9398
MG_INTERNAL void mg_handle_lock(struct mg_connection *nc, const char *path) {
9399
  static const char *reply =
9400
      "HTTP/1.1 207 Multi-Status\r\n"
9401
      "Connection: close\r\n"
9402
      "Content-Type: text/xml; charset=utf-8\r\n\r\n"
9403
      "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
9404
      "<d:multistatus xmlns:d='DAV:'>\n"
9405
      "<D:lockdiscovery>\n"
9406
      "<D:activelock>\n"
9407
      "<D:locktoken>\n"
9408
      "<D:href>\n"
9409
      "opaquelocktoken:%s%u"
9410
      "</D:href>"
9411
      "</D:locktoken>"
9412
      "</D:activelock>\n"
9413
      "</D:lockdiscovery>"
9414
      "</d:multistatus>\n";
9415
  mg_printf(nc, reply, path, (unsigned int) mg_time());
9416
  nc->flags |= MG_F_SEND_AND_CLOSE;
9417
}
9418
#endif
9419

    
9420
MG_INTERNAL void mg_handle_mkcol(struct mg_connection *nc, const char *path,
9421
                                 struct http_message *hm) {
9422
  int status_code = 500;
9423
  if (hm->body.len != (size_t) ~0 && hm->body.len > 0) {
9424
    status_code = 415;
9425
  } else if (!mg_mkdir(path, 0755)) {
9426
    status_code = 201;
9427
  } else if (errno == EEXIST) {
9428
    status_code = 405;
9429
  } else if (errno == EACCES) {
9430
    status_code = 403;
9431
  } else if (errno == ENOENT) {
9432
    status_code = 409;
9433
  } else {
9434
    status_code = 500;
9435
  }
9436
  mg_http_send_error(nc, status_code, NULL);
9437
}
9438

    
9439
static int mg_remove_directory(const struct mg_serve_http_opts *opts,
9440
                               const char *dir) {
9441
  char path[MG_MAX_PATH];
9442
  struct dirent *dp;
9443
  cs_stat_t st;
9444
  DIR *dirp;
9445

    
9446
  if ((dirp = opendir(dir)) == NULL) return 0;
9447

    
9448
  while ((dp = readdir(dirp)) != NULL) {
9449
    if (mg_is_file_hidden((const char *) dp->d_name, opts, 1)) {
9450
      continue;
9451
    }
9452
    snprintf(path, sizeof(path), "%s%c%s", dir, '/', dp->d_name);
9453
    mg_stat(path, &st);
9454
    if (S_ISDIR(st.st_mode)) {
9455
      mg_remove_directory(opts, path);
9456
    } else {
9457
      remove(path);
9458
    }
9459
  }
9460
  closedir(dirp);
9461
  rmdir(dir);
9462

    
9463
  return 1;
9464
}
9465

    
9466
MG_INTERNAL void mg_handle_move(struct mg_connection *c,
9467
                                const struct mg_serve_http_opts *opts,
9468
                                const char *path, struct http_message *hm) {
9469
  const struct mg_str *dest = mg_get_http_header(hm, "Destination");
9470
  if (dest == NULL) {
9471
    mg_http_send_error(c, 411, NULL);
9472
  } else {
9473
    const char *p = (char *) memchr(dest->p, '/', dest->len);
9474
    if (p != NULL && p[1] == '/' &&
9475
        (p = (char *) memchr(p + 2, '/', dest->p + dest->len - p)) != NULL) {
9476
      char buf[MG_MAX_PATH];
9477
      snprintf(buf, sizeof(buf), "%s%.*s", opts->dav_document_root,
9478
               (int) (dest->p + dest->len - p), p);
9479
      if (rename(path, buf) == 0) {
9480
        mg_http_send_error(c, 200, NULL);
9481
      } else {
9482
        mg_http_send_error(c, 418, NULL);
9483
      }
9484
    } else {
9485
      mg_http_send_error(c, 500, NULL);
9486
    }
9487
  }
9488
}
9489

    
9490
MG_INTERNAL void mg_handle_delete(struct mg_connection *nc,
9491
                                  const struct mg_serve_http_opts *opts,
9492
                                  const char *path) {
9493
  cs_stat_t st;
9494
  if (mg_stat(path, &st) != 0) {
9495
    mg_http_send_error(nc, 404, NULL);
9496
  } else if (S_ISDIR(st.st_mode)) {
9497
    mg_remove_directory(opts, path);
9498
    mg_http_send_error(nc, 204, NULL);
9499
  } else if (remove(path) == 0) {
9500
    mg_http_send_error(nc, 204, NULL);
9501
  } else {
9502
    mg_http_send_error(nc, 423, NULL);
9503
  }
9504
}
9505

    
9506
/* Return -1 on error, 1 on success. */
9507
static int mg_create_itermediate_directories(const char *path) {
9508
  const char *s;
9509

    
9510
  /* Create intermediate directories if they do not exist */
9511
  for (s = path + 1; *s != '\0'; s++) {
9512
    if (*s == '/') {
9513
      char buf[MG_MAX_PATH];
9514
      cs_stat_t st;
9515
      snprintf(buf, sizeof(buf), "%.*s", (int) (s - path), path);
9516
      buf[sizeof(buf) - 1] = '\0';
9517
      if (mg_stat(buf, &st) != 0 && mg_mkdir(buf, 0755) != 0) {
9518
        return -1;
9519
      }
9520
    }
9521
  }
9522

    
9523
  return 1;
9524
}
9525

    
9526
MG_INTERNAL void mg_handle_put(struct mg_connection *nc, const char *path,
9527
                               struct http_message *hm) {
9528
  struct mg_http_proto_data *pd = mg_http_get_proto_data(nc);
9529
  cs_stat_t st;
9530
  const struct mg_str *cl_hdr = mg_get_http_header(hm, "Content-Length");
9531
  int rc, status_code = mg_stat(path, &st) == 0 ? 200 : 201;
9532

    
9533
  mg_http_free_proto_data_file(&pd->file);
9534
  if ((rc = mg_create_itermediate_directories(path)) == 0) {
9535
    mg_printf(nc, "HTTP/1.1 %d OK\r\nContent-Length: 0\r\n\r\n", status_code);
9536
  } else if (rc == -1) {
9537
    mg_http_send_error(nc, 500, NULL);
9538
  } else if (cl_hdr == NULL) {
9539
    mg_http_send_error(nc, 411, NULL);
9540
  } else if ((pd->file.fp = mg_fopen(path, "w+b")) == NULL) {
9541
    mg_http_send_error(nc, 500, NULL);
9542
  } else {
9543
    const struct mg_str *range_hdr = mg_get_http_header(hm, "Content-Range");
9544
    int64_t r1 = 0, r2 = 0;
9545
    pd->file.type = DATA_PUT;
9546
    mg_set_close_on_exec((sock_t) fileno(pd->file.fp));
9547
    pd->file.cl = to64(cl_hdr->p);
9548
    if (range_hdr != NULL &&
9549
        mg_http_parse_range_header(range_hdr, &r1, &r2) > 0) {
9550
      status_code = 206;
9551
      fseeko(pd->file.fp, r1, SEEK_SET);
9552
      pd->file.cl = r2 > r1 ? r2 - r1 + 1 : pd->file.cl - r1;
9553
    }
9554
    mg_printf(nc, "HTTP/1.1 %d OK\r\nContent-Length: 0\r\n\r\n", status_code);
9555
    /* Remove HTTP request from the mbuf, leave only payload */
9556
    mbuf_remove(&nc->recv_mbuf, hm->message.len - hm->body.len);
9557
    mg_http_transfer_file_data(nc);
9558
  }
9559
}
9560

    
9561
#endif /* MG_ENABLE_HTTP && MG_ENABLE_HTTP_WEBDAV */
9562
#ifdef MG_MODULE_LINES
9563
#line 1 "mongoose/src/mg_http_websocket.c"
9564
#endif
9565
/*
9566
 * Copyright (c) 2014 Cesanta Software Limited
9567
 * All rights reserved
9568
 */
9569

    
9570
#if MG_ENABLE_HTTP && MG_ENABLE_HTTP_WEBSOCKET
9571

    
9572
/* Amalgamated: #include "common/cs_sha1.h" */
9573

    
9574
#ifndef MG_WEBSOCKET_PING_INTERVAL_SECONDS
9575
#define MG_WEBSOCKET_PING_INTERVAL_SECONDS 5
9576
#endif
9577

    
9578
#define FLAGS_MASK_FIN (1 << 7)
9579
#define FLAGS_MASK_OP 0x0f
9580

    
9581
static int mg_is_ws_fragment(unsigned char flags) {
9582
  return (flags & FLAGS_MASK_FIN) == 0 ||
9583
         (flags & FLAGS_MASK_OP) == WEBSOCKET_OP_CONTINUE;
9584
}
9585

    
9586
static int mg_is_ws_first_fragment(unsigned char flags) {
9587
  return (flags & FLAGS_MASK_FIN) == 0 &&
9588
         (flags & FLAGS_MASK_OP) != WEBSOCKET_OP_CONTINUE;
9589
}
9590

    
9591
static int mg_is_ws_control_frame(unsigned char flags) {
9592
  unsigned char op = (flags & FLAGS_MASK_OP);
9593
  return op == WEBSOCKET_OP_CLOSE || op == WEBSOCKET_OP_PING ||
9594
         op == WEBSOCKET_OP_PONG;
9595
}
9596

    
9597
static void mg_handle_incoming_websocket_frame(struct mg_connection *nc,
9598
                                               struct websocket_message *wsm) {
9599
  if (wsm->flags & 0x8) {
9600
    mg_call(nc, nc->handler, nc->user_data, MG_EV_WEBSOCKET_CONTROL_FRAME, wsm);
9601
  } else {
9602
    mg_call(nc, nc->handler, nc->user_data, MG_EV_WEBSOCKET_FRAME, wsm);
9603
  }
9604
}
9605

    
9606
static struct mg_ws_proto_data *mg_ws_get_proto_data(struct mg_connection *nc) {
9607
  struct mg_http_proto_data *htd = mg_http_get_proto_data(nc);
9608
  return (htd != NULL ? &htd->ws_data : NULL);
9609
}
9610

    
9611
/*
9612
 * Sends a Close websocket frame with the given data, and closes the underlying
9613
 * connection. If `len` is ~0, strlen(data) is used.
9614
 */
9615
static void mg_ws_close(struct mg_connection *nc, const void *data,
9616
                        size_t len) {
9617
  if ((int) len == ~0) {
9618
    len = strlen((const char *) data);
9619
  }
9620
  mg_send_websocket_frame(nc, WEBSOCKET_OP_CLOSE, data, len);
9621
  nc->flags |= MG_F_SEND_AND_CLOSE;
9622
}
9623

    
9624
static int mg_deliver_websocket_data(struct mg_connection *nc) {
9625
  /* Using unsigned char *, cause of integer arithmetic below */
9626
  uint64_t i, data_len = 0, frame_len = 0, new_data_len = nc->recv_mbuf.len,
9627
              len, mask_len = 0, header_len = 0;
9628
  struct mg_ws_proto_data *wsd = mg_ws_get_proto_data(nc);
9629
  unsigned char *new_data = (unsigned char *) nc->recv_mbuf.buf,
9630
                *e = (unsigned char *) nc->recv_mbuf.buf + nc->recv_mbuf.len;
9631
  uint8_t flags;
9632
  int ok, reass;
9633

    
9634
  if (wsd->reass_len > 0) {
9635
    /*
9636
     * We already have some previously received data which we need to
9637
     * reassemble and deliver to the client code when we get the final
9638
     * fragment.
9639
     *
9640
     * NOTE: it doesn't mean that the current message must be a continuation:
9641
     * it might be a control frame (Close, Ping or Pong), which should be
9642
     * handled without breaking the fragmented message.
9643
     */
9644

    
9645
    size_t existing_len = wsd->reass_len;
9646
    assert(new_data_len >= existing_len);
9647

    
9648
    new_data += existing_len;
9649
    new_data_len -= existing_len;
9650
  }
9651

    
9652
  flags = new_data[0];
9653

    
9654
  reass = new_data_len > 0 && mg_is_ws_fragment(flags) &&
9655
          !(nc->flags & MG_F_WEBSOCKET_NO_DEFRAG);
9656

    
9657
  if (reass && mg_is_ws_control_frame(flags)) {
9658
    /*
9659
     * Control frames can't be fragmented, so if we encounter fragmented
9660
     * control frame, close connection immediately.
9661
     */
9662
    mg_ws_close(nc, "fragmented control frames are illegal", ~0);
9663
    return 0;
9664
  } else if (new_data_len > 0 && !reass && !mg_is_ws_control_frame(flags) &&
9665
             wsd->reass_len > 0) {
9666
    /*
9667
     * When in the middle of a fragmented message, only the continuations
9668
     * and control frames are allowed.
9669
     */
9670
    mg_ws_close(nc, "non-continuation in the middle of a fragmented message",
9671
                ~0);
9672
    return 0;
9673
  }
9674

    
9675
  if (new_data_len >= 2) {
9676
    len = new_data[1] & 0x7f;
9677
    mask_len = new_data[1] & FLAGS_MASK_FIN ? 4 : 0;
9678
    if (len < 126 && new_data_len >= mask_len) {
9679
      data_len = len;
9680
      header_len = 2 + mask_len;
9681
    } else if (len == 126 && new_data_len >= 4 + mask_len) {
9682
      header_len = 4 + mask_len;
9683
      data_len = ntohs(*(uint16_t *) &new_data[2]);
9684
    } else if (new_data_len >= 10 + mask_len) {
9685
      header_len = 10 + mask_len;
9686
      data_len = (((uint64_t) ntohl(*(uint32_t *) &new_data[2])) << 32) +
9687
                 ntohl(*(uint32_t *) &new_data[6]);
9688
    }
9689
  }
9690

    
9691
  frame_len = header_len + data_len;
9692
  ok = (frame_len > 0 && frame_len <= new_data_len);
9693

    
9694
  /* Check for overflow */
9695
  if (frame_len < header_len || frame_len < data_len) {
9696
    ok = 0;
9697
    mg_ws_close(nc, "overflowed message", ~0);
9698
  }
9699

    
9700
  if (ok) {
9701
    size_t cleanup_len = 0;
9702
    struct websocket_message wsm;
9703

    
9704
    wsm.size = (size_t) data_len;
9705
    wsm.data = new_data + header_len;
9706
    wsm.flags = flags;
9707

    
9708
    /* Apply mask if necessary */
9709
    if (mask_len > 0) {
9710
      for (i = 0; i < data_len; i++) {
9711
        new_data[i + header_len] ^= (new_data + header_len - mask_len)[i % 4];
9712
      }
9713
    }
9714

    
9715
    if (reass) {
9716
      /* This is a message fragment */
9717

    
9718
      if (mg_is_ws_first_fragment(flags)) {
9719
        /*
9720
         * On the first fragmented frame, skip the first byte (op) and also
9721
         * reset size to 1 (op), it'll be incremented with the data len below.
9722
         */
9723
        new_data += 1;
9724
        wsd->reass_len = 1 /* op */;
9725
      }
9726

    
9727
      /* Append this frame to the reassembled buffer */
9728
      memmove(new_data, wsm.data, e - wsm.data);
9729
      wsd->reass_len += wsm.size;
9730
      nc->recv_mbuf.len -= wsm.data - new_data;
9731

    
9732
      if (flags & FLAGS_MASK_FIN) {
9733
        /* On last fragmented frame - call user handler and remove data */
9734
        wsm.flags = FLAGS_MASK_FIN | nc->recv_mbuf.buf[0];
9735
        wsm.data = (unsigned char *) nc->recv_mbuf.buf + 1 /* op */;
9736
        wsm.size = wsd->reass_len - 1 /* op */;
9737
        cleanup_len = wsd->reass_len;
9738
        wsd->reass_len = 0;
9739

    
9740
        /* Pass reassembled message to the client code. */
9741
        mg_handle_incoming_websocket_frame(nc, &wsm);
9742
        mbuf_remove(&nc->recv_mbuf, cleanup_len); /* Cleanup frame */
9743
      }
9744
    } else {
9745
      /*
9746
       * This is a complete message, not a fragment. It might happen in between
9747
       * of a fragmented message (in this case, WebSocket protocol requires
9748
       * current message to be a control frame).
9749
       */
9750
      cleanup_len = (size_t) frame_len;
9751

    
9752
      /* First of all, check if we need to react on a control frame. */
9753
      switch (flags & FLAGS_MASK_OP) {
9754
        case WEBSOCKET_OP_PING:
9755
          mg_send_websocket_frame(nc, WEBSOCKET_OP_PONG, wsm.data, wsm.size);
9756
          break;
9757

    
9758
        case WEBSOCKET_OP_CLOSE:
9759
          mg_ws_close(nc, wsm.data, wsm.size);
9760
          break;
9761
      }
9762

    
9763
      /* Pass received message to the client code. */
9764
      mg_handle_incoming_websocket_frame(nc, &wsm);
9765

    
9766
      /* Cleanup frame */
9767
      memmove(nc->recv_mbuf.buf + wsd->reass_len,
9768
              nc->recv_mbuf.buf + wsd->reass_len + cleanup_len,
9769
              nc->recv_mbuf.len - wsd->reass_len - cleanup_len);
9770
      nc->recv_mbuf.len -= cleanup_len;
9771
    }
9772
  }
9773

    
9774
  return ok;
9775
}
9776

    
9777
struct ws_mask_ctx {
9778
  size_t pos; /* zero means unmasked */
9779
  uint32_t mask;
9780
};
9781

    
9782
static uint32_t mg_ws_random_mask(void) {
9783
  uint32_t mask;
9784
/*
9785
 * The spec requires WS client to generate hard to
9786
 * guess mask keys. From RFC6455, Section 5.3:
9787
 *
9788
 * The unpredictability of the masking key is essential to prevent
9789
 * authors of malicious applications from selecting the bytes that appear on
9790
 * the wire.
9791
 *
9792
 * Hence this feature is essential when the actual end user of this API
9793
 * is untrusted code that wouldn't have access to a lower level net API
9794
 * anyway (e.g. web browsers). Hence this feature is low prio for most
9795
 * mongoose use cases and thus can be disabled, e.g. when porting to a platform
9796
 * that lacks rand().
9797
 */
9798
#if MG_DISABLE_WS_RANDOM_MASK
9799
  mask = 0xefbeadde; /* generated with a random number generator, I swear */
9800
#else
9801
  if (sizeof(long) >= 4) {
9802
    mask = (uint32_t) rand();
9803
  } else if (sizeof(long) == 2) {
9804
    mask = (uint32_t) rand() << 16 | (uint32_t) rand();
9805
  }
9806
#endif
9807
  return mask;
9808
}
9809

    
9810
static void mg_send_ws_header(struct mg_connection *nc, int op, size_t len,
9811
                              struct ws_mask_ctx *ctx) {
9812
  int header_len;
9813
  unsigned char header[10];
9814

    
9815
  header[0] =
9816
      (op & WEBSOCKET_DONT_FIN ? 0x0 : FLAGS_MASK_FIN) | (op & FLAGS_MASK_OP);
9817
  if (len < 126) {
9818
    header[1] = (unsigned char) len;
9819
    header_len = 2;
9820
  } else if (len < 65535) {
9821
    uint16_t tmp = htons((uint16_t) len);
9822
    header[1] = 126;
9823
    memcpy(&header[2], &tmp, sizeof(tmp));
9824
    header_len = 4;
9825
  } else {
9826
    uint32_t tmp;
9827
    header[1] = 127;
9828
    tmp = htonl((uint32_t)((uint64_t) len >> 32));
9829
    memcpy(&header[2], &tmp, sizeof(tmp));
9830
    tmp = htonl((uint32_t)(len & 0xffffffff));
9831
    memcpy(&header[6], &tmp, sizeof(tmp));
9832
    header_len = 10;
9833
  }
9834

    
9835
  /* client connections enable masking */
9836
  if (nc->listener == NULL) {
9837
    header[1] |= 1 << 7; /* set masking flag */
9838
    mg_send(nc, header, header_len);
9839
    ctx->mask = mg_ws_random_mask();
9840
    mg_send(nc, &ctx->mask, sizeof(ctx->mask));
9841
    ctx->pos = nc->send_mbuf.len;
9842
  } else {
9843
    mg_send(nc, header, header_len);
9844
    ctx->pos = 0;
9845
  }
9846
}
9847

    
9848
static void mg_ws_mask_frame(struct mbuf *mbuf, struct ws_mask_ctx *ctx) {
9849
  size_t i;
9850
  if (ctx->pos == 0) return;
9851
  for (i = 0; i < (mbuf->len - ctx->pos); i++) {
9852
    mbuf->buf[ctx->pos + i] ^= ((char *) &ctx->mask)[i % 4];
9853
  }
9854
}
9855

    
9856
void mg_send_websocket_frame(struct mg_connection *nc, int op, const void *data,
9857
                             size_t len) {
9858
  struct ws_mask_ctx ctx;
9859
  DBG(("%p %d %d", nc, op, (int) len));
9860
  mg_send_ws_header(nc, op, len, &ctx);
9861
  mg_send(nc, data, len);
9862

    
9863
  mg_ws_mask_frame(&nc->send_mbuf, &ctx);
9864

    
9865
  if (op == WEBSOCKET_OP_CLOSE) {
9866
    nc->flags |= MG_F_SEND_AND_CLOSE;
9867
  }
9868
}
9869

    
9870
void mg_send_websocket_framev(struct mg_connection *nc, int op,
9871
                              const struct mg_str *strv, int strvcnt) {
9872
  struct ws_mask_ctx ctx;
9873
  int i;
9874
  int len = 0;
9875
  for (i = 0; i < strvcnt; i++) {
9876
    len += strv[i].len;
9877
  }
9878

    
9879
  mg_send_ws_header(nc, op, len, &ctx);
9880

    
9881
  for (i = 0; i < strvcnt; i++) {
9882
    mg_send(nc, strv[i].p, strv[i].len);
9883
  }
9884

    
9885
  mg_ws_mask_frame(&nc->send_mbuf, &ctx);
9886

    
9887
  if (op == WEBSOCKET_OP_CLOSE) {
9888
    nc->flags |= MG_F_SEND_AND_CLOSE;
9889
  }
9890
}
9891

    
9892
void mg_printf_websocket_frame(struct mg_connection *nc, int op,
9893
                               const char *fmt, ...) {
9894
  char mem[MG_VPRINTF_BUFFER_SIZE], *buf = mem;
9895
  va_list ap;
9896
  int len;
9897

    
9898
  va_start(ap, fmt);
9899
  if ((len = mg_avprintf(&buf, sizeof(mem), fmt, ap)) > 0) {
9900
    mg_send_websocket_frame(nc, op, buf, len);
9901
  }
9902
  va_end(ap);
9903

    
9904
  if (buf != mem && buf != NULL) {
9905
    MG_FREE(buf);
9906
  }
9907
}
9908

    
9909
MG_INTERNAL void mg_ws_handler(struct mg_connection *nc, int ev,
9910
                               void *ev_data MG_UD_ARG(void *user_data)) {
9911
  mg_call(nc, nc->handler, nc->user_data, ev, ev_data);
9912

    
9913
  switch (ev) {
9914
    case MG_EV_RECV:
9915
      do {
9916
      } while (mg_deliver_websocket_data(nc));
9917
      break;
9918
    case MG_EV_POLL:
9919
      /* Ping idle websocket connections */
9920
      {
9921
        time_t now = *(time_t *) ev_data;
9922
        if (nc->flags & MG_F_IS_WEBSOCKET &&
9923
            now > nc->last_io_time + MG_WEBSOCKET_PING_INTERVAL_SECONDS) {
9924
          mg_send_websocket_frame(nc, WEBSOCKET_OP_PING, "", 0);
9925
        }
9926
      }
9927
      break;
9928
    default:
9929
      break;
9930
  }
9931
#if MG_ENABLE_CALLBACK_USERDATA
9932
  (void) user_data;
9933
#endif
9934
}
9935

    
9936
#ifndef MG_EXT_SHA1
9937
void mg_hash_sha1_v(size_t num_msgs, const uint8_t *msgs[],
9938
                    const size_t *msg_lens, uint8_t *digest) {
9939
  size_t i;
9940
  cs_sha1_ctx sha_ctx;
9941
  cs_sha1_init(&sha_ctx);
9942
  for (i = 0; i < num_msgs; i++) {
9943
    cs_sha1_update(&sha_ctx, msgs[i], msg_lens[i]);
9944
  }
9945
  cs_sha1_final(digest, &sha_ctx);
9946
}
9947
#else
9948
extern void mg_hash_sha1_v(size_t num_msgs, const uint8_t *msgs[],
9949
                           const size_t *msg_lens, uint8_t *digest);
9950
#endif
9951

    
9952
MG_INTERNAL void mg_ws_handshake(struct mg_connection *nc,
9953
                                 const struct mg_str *key,
9954
                                 struct http_message *hm) {
9955
  static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
9956
  const uint8_t *msgs[2] = {(const uint8_t *) key->p, (const uint8_t *) magic};
9957
  const size_t msg_lens[2] = {key->len, 36};
9958
  unsigned char sha[20];
9959
  char b64_sha[30];
9960
  struct mg_str *s;
9961

    
9962
  mg_hash_sha1_v(2, msgs, msg_lens, sha);
9963
  mg_base64_encode(sha, sizeof(sha), b64_sha);
9964
  mg_printf(nc, "%s",
9965
            "HTTP/1.1 101 Switching Protocols\r\n"
9966
            "Upgrade: websocket\r\n"
9967
            "Connection: Upgrade\r\n");
9968

    
9969
  s = mg_get_http_header(hm, "Sec-WebSocket-Protocol");
9970
  if (s != NULL) {
9971
    mg_printf(nc, "Sec-WebSocket-Protocol: %.*s\r\n", (int) s->len, s->p);
9972
  }
9973
  mg_printf(nc, "Sec-WebSocket-Accept: %s%s", b64_sha, "\r\n\r\n");
9974

    
9975
  DBG(("%p %.*s %s", nc, (int) key->len, key->p, b64_sha));
9976
}
9977

    
9978
void mg_send_websocket_handshake2(struct mg_connection *nc, const char *path,
9979
                                  const char *host, const char *protocol,
9980
                                  const char *extra_headers) {
9981
  mg_send_websocket_handshake3(nc, path, host, protocol, extra_headers, NULL,
9982
                               NULL);
9983
}
9984

    
9985
void mg_send_websocket_handshake3(struct mg_connection *nc, const char *path,
9986
                                  const char *host, const char *protocol,
9987
                                  const char *extra_headers, const char *user,
9988
                                  const char *pass) {
9989
  mg_send_websocket_handshake3v(nc, mg_mk_str(path), mg_mk_str(host),
9990
                                mg_mk_str(protocol), mg_mk_str(extra_headers),
9991
                                mg_mk_str(user), mg_mk_str(pass));
9992
}
9993

    
9994
void mg_send_websocket_handshake3v(struct mg_connection *nc,
9995
                                   const struct mg_str path,
9996
                                   const struct mg_str host,
9997
                                   const struct mg_str protocol,
9998
                                   const struct mg_str extra_headers,
9999
                                   const struct mg_str user,
10000
                                   const struct mg_str pass) {
10001
  struct mbuf auth;
10002
  char key[25];
10003
  uint32_t nonce[4];
10004
  nonce[0] = mg_ws_random_mask();
10005
  nonce[1] = mg_ws_random_mask();
10006
  nonce[2] = mg_ws_random_mask();
10007
  nonce[3] = mg_ws_random_mask();
10008
  mg_base64_encode((unsigned char *) &nonce, sizeof(nonce), key);
10009

    
10010
  mbuf_init(&auth, 0);
10011
  if (user.len > 0) {
10012
    mg_basic_auth_header(user, pass, &auth);
10013
  }
10014

    
10015
  /*
10016
   * NOTE: the  (auth.buf == NULL ? "" : auth.buf) is because cc3200 libc is
10017
   * broken: it doesn't like zero length to be passed to %.*s
10018
   * i.e. sprintf("f%.*so", (int)0, NULL), yields `f\0o`.
10019
   * because it handles NULL specially (and incorrectly).
10020
   */
10021
  mg_printf(nc,
10022
            "GET %.*s HTTP/1.1\r\n"
10023
            "Upgrade: websocket\r\n"
10024
            "Connection: Upgrade\r\n"
10025
            "%.*s"
10026
            "Sec-WebSocket-Version: 13\r\n"
10027
            "Sec-WebSocket-Key: %s\r\n",
10028
            (int) path.len, path.p, (int) auth.len,
10029
            (auth.buf == NULL ? "" : auth.buf), key);
10030

    
10031
  /* TODO(mkm): take default hostname from http proto data if host == NULL */
10032
  if (host.len > 0) {
10033
    int host_len = (int) (path.p - host.p); /* Account for possible :PORT */
10034
    mg_printf(nc, "Host: %.*s\r\n", host_len, host.p);
10035
  }
10036
  if (protocol.len > 0) {
10037
    mg_printf(nc, "Sec-WebSocket-Protocol: %.*s\r\n", (int) protocol.len,
10038
              protocol.p);
10039
  }
10040
  if (extra_headers.len > 0) {
10041
    mg_printf(nc, "%.*s", (int) extra_headers.len, extra_headers.p);
10042
  }
10043
  mg_printf(nc, "\r\n");
10044

    
10045
  mbuf_free(&auth);
10046
}
10047

    
10048
void mg_send_websocket_handshake(struct mg_connection *nc, const char *path,
10049
                                 const char *extra_headers) {
10050
  struct mg_str null_str = MG_NULL_STR;
10051
  mg_send_websocket_handshake3v(
10052
      nc, mg_mk_str(path), null_str /* host */, null_str /* protocol */,
10053
      mg_mk_str(extra_headers), null_str /* user */, null_str /* pass */);
10054
}
10055

    
10056
struct mg_connection *mg_connect_ws_opt(
10057
    struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data),
10058
    struct mg_connect_opts opts, const char *url, const char *protocol,
10059
    const char *extra_headers) {
10060
  struct mg_str null_str = MG_NULL_STR;
10061
  struct mg_str host = MG_NULL_STR, path = MG_NULL_STR, user_info = MG_NULL_STR;
10062
  struct mg_connection *nc =
10063
      mg_connect_http_base(mgr, MG_CB(ev_handler, user_data), opts, "http",
10064
                           "ws", "https", "wss", url, &path, &user_info, &host);
10065
  if (nc != NULL) {
10066
    mg_send_websocket_handshake3v(nc, path, host, mg_mk_str(protocol),
10067
                                  mg_mk_str(extra_headers), user_info,
10068
                                  null_str);
10069
  }
10070
  return nc;
10071
}
10072

    
10073
struct mg_connection *mg_connect_ws(
10074
    struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data),
10075
    const char *url, const char *protocol, const char *extra_headers) {
10076
  struct mg_connect_opts opts;
10077
  memset(&opts, 0, sizeof(opts));
10078
  return mg_connect_ws_opt(mgr, MG_CB(ev_handler, user_data), opts, url,
10079
                           protocol, extra_headers);
10080
}
10081
#endif /* MG_ENABLE_HTTP && MG_ENABLE_HTTP_WEBSOCKET */
10082
#ifdef MG_MODULE_LINES
10083
#line 1 "mongoose/src/mg_util.c"
10084
#endif
10085
/*
10086
 * Copyright (c) 2014 Cesanta Software Limited
10087
 * All rights reserved
10088
 */
10089

    
10090
/* Amalgamated: #include "common/cs_base64.h" */
10091
/* Amalgamated: #include "mg_internal.h" */
10092
/* Amalgamated: #include "mg_util.h" */
10093

    
10094
/* For platforms with limited libc */
10095
#ifndef MAX
10096
#define MAX(a, b) ((a) > (b) ? (a) : (b))
10097
#endif
10098

    
10099
const char *mg_skip(const char *s, const char *end, const char *delims,
10100
                    struct mg_str *v) {
10101
  v->p = s;
10102
  while (s < end && strchr(delims, *(unsigned char *) s) == NULL) s++;
10103
  v->len = s - v->p;
10104
  while (s < end && strchr(delims, *(unsigned char *) s) != NULL) s++;
10105
  return s;
10106
}
10107

    
10108
#if MG_ENABLE_FILESYSTEM && !defined(MG_USER_FILE_FUNCTIONS)
10109
int mg_stat(const char *path, cs_stat_t *st) {
10110
#ifdef _WIN32
10111
  wchar_t wpath[MG_MAX_PATH];
10112
  to_wchar(path, wpath, ARRAY_SIZE(wpath));
10113
  DBG(("[%ls] -> %d", wpath, _wstati64(wpath, st)));
10114
  return _wstati64(wpath, st);
10115
#else
10116
  return stat(path, st);
10117
#endif
10118
}
10119

    
10120
FILE *mg_fopen(const char *path, const char *mode) {
10121
#ifdef _WIN32
10122
  wchar_t wpath[MG_MAX_PATH], wmode[10];
10123
  to_wchar(path, wpath, ARRAY_SIZE(wpath));
10124
  to_wchar(mode, wmode, ARRAY_SIZE(wmode));
10125
  return _wfopen(wpath, wmode);
10126
#else
10127
  return fopen(path, mode);
10128
#endif
10129
}
10130

    
10131
int mg_open(const char *path, int flag, int mode) { /* LCOV_EXCL_LINE */
10132
#if defined(_WIN32) && !defined(WINCE)
10133
  wchar_t wpath[MG_MAX_PATH];
10134
  to_wchar(path, wpath, ARRAY_SIZE(wpath));
10135
  return _wopen(wpath, flag, mode);
10136
#else
10137
  return open(path, flag, mode); /* LCOV_EXCL_LINE */
10138
#endif
10139
}
10140

    
10141
size_t mg_fread(void *ptr, size_t size, size_t count, FILE *f) {
10142
  return fread(ptr, size, count, f);
10143
}
10144

    
10145
size_t mg_fwrite(const void *ptr, size_t size, size_t count, FILE *f) {
10146
  return fwrite(ptr, size, count, f);
10147
}
10148
#endif
10149

    
10150
void mg_base64_encode(const unsigned char *src, int src_len, char *dst) {
10151
  cs_base64_encode(src, src_len, dst);
10152
}
10153

    
10154
int mg_base64_decode(const unsigned char *s, int len, char *dst) {
10155
  return cs_base64_decode(s, len, dst, NULL);
10156
}
10157

    
10158
#if MG_ENABLE_THREADS
10159
void *mg_start_thread(void *(*f)(void *), void *p) {
10160
#ifdef WINCE
10161
  return (void *) CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) f, p, 0, NULL);
10162
#elif defined(_WIN32)
10163
  return (void *) _beginthread((void(__cdecl *) (void *) ) f, 0, p);
10164
#else
10165
  pthread_t thread_id = (pthread_t) 0;
10166
  pthread_attr_t attr;
10167

    
10168
  (void) pthread_attr_init(&attr);
10169
  (void) pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
10170

    
10171
#if defined(MG_STACK_SIZE) && MG_STACK_SIZE > 1
10172
  (void) pthread_attr_setstacksize(&attr, MG_STACK_SIZE);
10173
#endif
10174

    
10175
  pthread_create(&thread_id, &attr, f, p);
10176
  pthread_attr_destroy(&attr);
10177

    
10178
  return (void *) thread_id;
10179
#endif
10180
}
10181
#endif /* MG_ENABLE_THREADS */
10182

    
10183
/* Set close-on-exec bit for a given socket. */
10184
void mg_set_close_on_exec(sock_t sock) {
10185
#if defined(_WIN32) && !defined(WINCE)
10186
  (void) SetHandleInformation((HANDLE) sock, HANDLE_FLAG_INHERIT, 0);
10187
#elif defined(__unix__)
10188
  fcntl(sock, F_SETFD, FD_CLOEXEC);
10189
#else
10190
  (void) sock;
10191
#endif
10192
}
10193

    
10194
int mg_sock_addr_to_str(const union socket_address *sa, char *buf, size_t len,
10195
                        int flags) {
10196
  int is_v6;
10197
  if (buf == NULL || len <= 0) return 0;
10198
  memset(buf, 0, len);
10199
#if MG_ENABLE_IPV6
10200
  is_v6 = sa->sa.sa_family == AF_INET6;
10201
#else
10202
  is_v6 = 0;
10203
#endif
10204
  if (flags & MG_SOCK_STRINGIFY_IP) {
10205
#if MG_ENABLE_IPV6
10206
    const void *addr = NULL;
10207
    char *start = buf;
10208
    socklen_t capacity = len;
10209
    if (!is_v6) {
10210
      addr = &sa->sin.sin_addr;
10211
    } else {
10212
      addr = (void *) &sa->sin6.sin6_addr;
10213
      if (flags & MG_SOCK_STRINGIFY_PORT) {
10214
        *buf = '[';
10215
        start++;
10216
        capacity--;
10217
      }
10218
    }
10219
    if (inet_ntop(sa->sa.sa_family, addr, start, capacity) == NULL) {
10220
      goto cleanup;
10221
    }
10222
#elif defined(_WIN32) || MG_LWIP || (MG_NET_IF == MG_NET_IF_PIC32)
10223
    /* Only Windoze Vista (and newer) have inet_ntop() */
10224
    char *addr_str = inet_ntoa(sa->sin.sin_addr);
10225
    if (addr_str != NULL) {
10226
      strncpy(buf, inet_ntoa(sa->sin.sin_addr), len - 1);
10227
    } else {
10228
      goto cleanup;
10229
    }
10230
#else
10231
    if (inet_ntop(AF_INET, (void *) &sa->sin.sin_addr, buf, len - 1) == NULL) {
10232
      goto cleanup;
10233
    }
10234
#endif
10235
  }
10236
  if (flags & MG_SOCK_STRINGIFY_PORT) {
10237
    int port = ntohs(sa->sin.sin_port);
10238
    if (flags & MG_SOCK_STRINGIFY_IP) {
10239
      int buf_len = strlen(buf);
10240
      snprintf(buf + buf_len, len - (buf_len + 1), "%s:%d", (is_v6 ? "]" : ""),
10241
               port);
10242
    } else {
10243
      snprintf(buf, len, "%d", port);
10244
    }
10245
  }
10246

    
10247
  return strlen(buf);
10248

    
10249
cleanup:
10250
  *buf = '\0';
10251
  return 0;
10252
}
10253

    
10254
int mg_conn_addr_to_str(struct mg_connection *nc, char *buf, size_t len,
10255
                        int flags) {
10256
  union socket_address sa;
10257
  memset(&sa, 0, sizeof(sa));
10258
  mg_if_get_conn_addr(nc, flags & MG_SOCK_STRINGIFY_REMOTE, &sa);
10259
  return mg_sock_addr_to_str(&sa, buf, len, flags);
10260
}
10261

    
10262
#if MG_ENABLE_HEXDUMP
10263
static int mg_hexdump_n(const void *buf, int len, char *dst, int dst_len,
10264
                        int offset) {
10265
  const unsigned char *p = (const unsigned char *) buf;
10266
  char ascii[17] = "";
10267
  int i, idx, n = 0;
10268

    
10269
  for (i = 0; i < len; i++) {
10270
    idx = i % 16;
10271
    if (idx == 0) {
10272
      if (i > 0) n += snprintf(dst + n, MAX(dst_len - n, 0), "  %s\n", ascii);
10273
      n += snprintf(dst + n, MAX(dst_len - n, 0), "%04x ", i + offset);
10274
    }
10275
    if (dst_len - n < 0) {
10276
      return n;
10277
    }
10278
    n += snprintf(dst + n, MAX(dst_len - n, 0), " %02x", p[i]);
10279
    ascii[idx] = p[i] < 0x20 || p[i] > 0x7e ? '.' : p[i];
10280
    ascii[idx + 1] = '\0';
10281
  }
10282

    
10283
  while (i++ % 16) n += snprintf(dst + n, MAX(dst_len - n, 0), "%s", "   ");
10284
  n += snprintf(dst + n, MAX(dst_len - n, 0), "  %s\n", ascii);
10285

    
10286
  return n;
10287
}
10288

    
10289
int mg_hexdump(const void *buf, int len, char *dst, int dst_len) {
10290
  return mg_hexdump_n(buf, len, dst, dst_len, 0);
10291
}
10292

    
10293
void mg_hexdumpf(FILE *fp, const void *buf, int len) {
10294
  char tmp[80];
10295
  int offset = 0, n;
10296
  while (len > 0) {
10297
    n = (len < 16 ? len : 16);
10298
    mg_hexdump_n(((const char *) buf) + offset, n, tmp, sizeof(tmp), offset);
10299
    fputs(tmp, fp);
10300
    offset += n;
10301
    len -= n;
10302
  }
10303
}
10304

    
10305
void mg_hexdump_connection(struct mg_connection *nc, const char *path,
10306
                           const void *buf, int num_bytes, int ev) {
10307
  FILE *fp = NULL;
10308
  char src[60], dst[60];
10309
  const char *tag = NULL;
10310
  switch (ev) {
10311
    case MG_EV_RECV:
10312
      tag = "<-";
10313
      break;
10314
    case MG_EV_SEND:
10315
      tag = "->";
10316
      break;
10317
    case MG_EV_ACCEPT:
10318
      tag = "<A";
10319
      break;
10320
    case MG_EV_CONNECT:
10321
      tag = "C>";
10322
      break;
10323
    case MG_EV_CLOSE:
10324
      tag = "XX";
10325
      break;
10326
  }
10327
  if (tag == NULL) return; /* Don't log MG_EV_TIMER, etc */
10328

    
10329
  if (strcmp(path, "-") == 0) {
10330
    fp = stdout;
10331
  } else if (strcmp(path, "--") == 0) {
10332
    fp = stderr;
10333
#if MG_ENABLE_FILESYSTEM
10334
  } else {
10335
    fp = mg_fopen(path, "a");
10336
#endif
10337
  }
10338
  if (fp == NULL) return;
10339

    
10340
  mg_conn_addr_to_str(nc, src, sizeof(src),
10341
                      MG_SOCK_STRINGIFY_IP | MG_SOCK_STRINGIFY_PORT);
10342
  mg_conn_addr_to_str(nc, dst, sizeof(dst), MG_SOCK_STRINGIFY_IP |
10343
                                                MG_SOCK_STRINGIFY_PORT |
10344
                                                MG_SOCK_STRINGIFY_REMOTE);
10345
  fprintf(fp, "%lu %p %s %s %s %d\n", (unsigned long) mg_time(), (void *) nc,
10346
          src, tag, dst, (int) num_bytes);
10347
  if (num_bytes > 0) {
10348
    mg_hexdumpf(fp, buf, num_bytes);
10349
  }
10350
  if (fp != stdout && fp != stderr) fclose(fp);
10351
}
10352
#endif
10353

    
10354
int mg_is_big_endian(void) {
10355
  static const int n = 1;
10356
  /* TODO(mkm) use compiletime check with 4-byte char literal */
10357
  return ((char *) &n)[0] == 0;
10358
}
10359

    
10360
DO_NOT_WARN_UNUSED MG_INTERNAL int mg_get_errno(void) {
10361
#ifndef WINCE
10362
  return errno;
10363
#else
10364
  /* TODO(alashkin): translate error codes? */
10365
  return GetLastError();
10366
#endif
10367
}
10368

    
10369
void mg_mbuf_append_base64_putc(char ch, void *user_data) {
10370
  struct mbuf *mbuf = (struct mbuf *) user_data;
10371
  mbuf_append(mbuf, &ch, sizeof(ch));
10372
}
10373

    
10374
void mg_mbuf_append_base64(struct mbuf *mbuf, const void *data, size_t len) {
10375
  struct cs_base64_ctx ctx;
10376
  cs_base64_init(&ctx, mg_mbuf_append_base64_putc, mbuf);
10377
  cs_base64_update(&ctx, (const char *) data, len);
10378
  cs_base64_finish(&ctx);
10379
}
10380

    
10381
void mg_basic_auth_header(const struct mg_str user, const struct mg_str pass,
10382
                          struct mbuf *buf) {
10383
  const char *header_prefix = "Authorization: Basic ";
10384
  const char *header_suffix = "\r\n";
10385

    
10386
  struct cs_base64_ctx ctx;
10387
  cs_base64_init(&ctx, mg_mbuf_append_base64_putc, buf);
10388

    
10389
  mbuf_append(buf, header_prefix, strlen(header_prefix));
10390

    
10391
  cs_base64_update(&ctx, user.p, user.len);
10392
  if (pass.len > 0) {
10393
    cs_base64_update(&ctx, ":", 1);
10394
    cs_base64_update(&ctx, pass.p, pass.len);
10395
  }
10396
  cs_base64_finish(&ctx);
10397
  mbuf_append(buf, header_suffix, strlen(header_suffix));
10398
}
10399

    
10400
struct mg_str mg_url_encode(const struct mg_str src) {
10401
  static const char *dont_escape = "._-$,;~()/";
10402
  static const char *hex = "0123456789abcdef";
10403
  size_t i = 0;
10404
  struct mbuf mb;
10405
  mbuf_init(&mb, src.len);
10406

    
10407
  for (i = 0; i < src.len; i++) {
10408
    const unsigned char c = *((const unsigned char *) src.p + i);
10409
    if (isalnum(c) || strchr(dont_escape, c) != NULL) {
10410
      mbuf_append(&mb, &c, 1);
10411
    } else {
10412
      mbuf_append(&mb, "%", 1);
10413
      mbuf_append(&mb, &hex[c >> 4], 1);
10414
      mbuf_append(&mb, &hex[c & 15], 1);
10415
    }
10416
  }
10417
  mbuf_append(&mb, "", 1);
10418
  mbuf_trim(&mb);
10419
  return mg_mk_str_n(mb.buf, mb.len - 1);
10420
}
10421
#ifdef MG_MODULE_LINES
10422
#line 1 "mongoose/src/mg_mqtt.c"
10423
#endif
10424
/*
10425
 * Copyright (c) 2014 Cesanta Software Limited
10426
 * All rights reserved
10427
 */
10428

    
10429
#if MG_ENABLE_MQTT
10430

    
10431
#include <string.h>
10432

    
10433
/* Amalgamated: #include "mg_internal.h" */
10434
/* Amalgamated: #include "mg_mqtt.h" */
10435

    
10436
static uint16_t getu16(const char *p) {
10437
  const uint8_t *up = (const uint8_t *) p;
10438
  return (up[0] << 8) + up[1];
10439
}
10440

    
10441
static const char *scanto(const char *p, struct mg_str *s) {
10442
  s->len = getu16(p);
10443
  s->p = p + 2;
10444
  return s->p + s->len;
10445
}
10446

    
10447
MG_INTERNAL int parse_mqtt(struct mbuf *io, struct mg_mqtt_message *mm) {
10448
  uint8_t header;
10449
  size_t len = 0, len_len = 0;
10450
  const char *p, *end;
10451
  unsigned char lc = 0;
10452
  int cmd;
10453

    
10454
  if (io->len < 2) return MG_MQTT_ERROR_INCOMPLETE_MSG;
10455
  header = io->buf[0];
10456
  cmd = header >> 4;
10457

    
10458
  /* decode mqtt variable length */
10459
  len = len_len = 0;
10460
  p = io->buf + 1;
10461
  while ((size_t)(p - io->buf) < io->len) {
10462
    lc = *((const unsigned char *) p++);
10463
    len += (lc & 0x7f) << 7 * len_len;
10464
    len_len++;
10465
    if (!(lc & 0x80)) break;
10466
    if (len_len > 4) return MG_MQTT_ERROR_MALFORMED_MSG;
10467
  }
10468

    
10469
  end = p + len;
10470
  if (lc & 0x80 || len > (io->len - (p - io->buf))) {
10471
    return MG_MQTT_ERROR_INCOMPLETE_MSG;
10472
  }
10473

    
10474
  mm->cmd = cmd;
10475
  mm->qos = MG_MQTT_GET_QOS(header);
10476

    
10477
  switch (cmd) {
10478
    case MG_MQTT_CMD_CONNECT: {
10479
      p = scanto(p, &mm->protocol_name);
10480
      if (p > end - 4) return MG_MQTT_ERROR_MALFORMED_MSG;
10481
      mm->protocol_version = *(uint8_t *) p++;
10482
      mm->connect_flags = *(uint8_t *) p++;
10483
      mm->keep_alive_timer = getu16(p);
10484
      p += 2;
10485
      if (p >= end) return MG_MQTT_ERROR_MALFORMED_MSG;
10486
      p = scanto(p, &mm->client_id);
10487
      if (p > end) return MG_MQTT_ERROR_MALFORMED_MSG;
10488
      if (mm->connect_flags & MG_MQTT_HAS_WILL) {
10489
        if (p >= end) return MG_MQTT_ERROR_MALFORMED_MSG;
10490
        p = scanto(p, &mm->will_topic);
10491
      }
10492
      if (mm->connect_flags & MG_MQTT_HAS_WILL) {
10493
        if (p >= end) return MG_MQTT_ERROR_MALFORMED_MSG;
10494
        p = scanto(p, &mm->will_message);
10495
      }
10496
      if (mm->connect_flags & MG_MQTT_HAS_USER_NAME) {
10497
        if (p >= end) return MG_MQTT_ERROR_MALFORMED_MSG;
10498
        p = scanto(p, &mm->user_name);
10499
      }
10500
      if (mm->connect_flags & MG_MQTT_HAS_PASSWORD) {
10501
        if (p >= end) return MG_MQTT_ERROR_MALFORMED_MSG;
10502
        p = scanto(p, &mm->password);
10503
      }
10504
      if (p != end) return MG_MQTT_ERROR_MALFORMED_MSG;
10505

    
10506
      LOG(LL_DEBUG,
10507
          ("%d %2x %d proto [%.*s] client_id [%.*s] will_topic [%.*s] "
10508
           "will_msg [%.*s] user_name [%.*s] password [%.*s]",
10509
           (int) len, (int) mm->connect_flags, (int) mm->keep_alive_timer,
10510
           (int) mm->protocol_name.len, mm->protocol_name.p,
10511
           (int) mm->client_id.len, mm->client_id.p, (int) mm->will_topic.len,
10512
           mm->will_topic.p, (int) mm->will_message.len, mm->will_message.p,
10513
           (int) mm->user_name.len, mm->user_name.p, (int) mm->password.len,
10514
           mm->password.p));
10515
      break;
10516
    }
10517
    case MG_MQTT_CMD_CONNACK:
10518
      if (end - p < 2) return MG_MQTT_ERROR_MALFORMED_MSG;
10519
      mm->connack_ret_code = p[1];
10520
      break;
10521
    case MG_MQTT_CMD_PUBACK:
10522
    case MG_MQTT_CMD_PUBREC:
10523
    case MG_MQTT_CMD_PUBREL:
10524
    case MG_MQTT_CMD_PUBCOMP:
10525
    case MG_MQTT_CMD_SUBACK:
10526
      mm->message_id = getu16(p);
10527
      break;
10528
    case MG_MQTT_CMD_PUBLISH: {
10529
      p = scanto(p, &mm->topic);
10530
      if (p > end) return MG_MQTT_ERROR_MALFORMED_MSG;
10531
      if (mm->qos > 0) {
10532
        if (end - p < 2) return MG_MQTT_ERROR_MALFORMED_MSG;
10533
        mm->message_id = getu16(p);
10534
        p += 2;
10535
      }
10536
      mm->payload.p = p;
10537
      mm->payload.len = end - p;
10538
      break;
10539
    }
10540
    case MG_MQTT_CMD_SUBSCRIBE:
10541
      if (end - p < 2) return MG_MQTT_ERROR_MALFORMED_MSG;
10542
      mm->message_id = getu16(p);
10543
      p += 2;
10544
      /*
10545
       * topic expressions are left in the payload and can be parsed with
10546
       * `mg_mqtt_next_subscribe_topic`
10547
       */
10548
      mm->payload.p = p;
10549
      mm->payload.len = end - p;
10550
      break;
10551
    default:
10552
      /* Unhandled command */
10553
      break;
10554
  }
10555

    
10556
  mm->len = end - io->buf;
10557
  return mm->len;
10558
}
10559

    
10560
static void mqtt_handler(struct mg_connection *nc, int ev,
10561
                         void *ev_data MG_UD_ARG(void *user_data)) {
10562
  struct mbuf *io = &nc->recv_mbuf;
10563
  struct mg_mqtt_message mm;
10564
  memset(&mm, 0, sizeof(mm));
10565

    
10566
  nc->handler(nc, ev, ev_data MG_UD_ARG(user_data));
10567

    
10568
  switch (ev) {
10569
    case MG_EV_ACCEPT:
10570
      if (nc->proto_data == NULL) mg_set_protocol_mqtt(nc);
10571
      break;
10572
    case MG_EV_RECV: {
10573
      /* There can be multiple messages in the buffer, process them all. */
10574
      while (1) {
10575
        int len = parse_mqtt(io, &mm);
10576
        if (len < 0) {
10577
          if (len == MG_MQTT_ERROR_MALFORMED_MSG) {
10578
            /* Protocol error. */
10579
            nc->flags |= MG_F_CLOSE_IMMEDIATELY;
10580
          } else if (len == MG_MQTT_ERROR_INCOMPLETE_MSG) {
10581
            /* Not fully buffered, let's check if we have a chance to get more
10582
             * data later */
10583
            if (nc->recv_mbuf_limit > 0 &&
10584
                nc->recv_mbuf.len >= nc->recv_mbuf_limit) {
10585
              LOG(LL_ERROR, ("%p recv buffer (%lu bytes) exceeds the limit "
10586
                             "%lu bytes, and not drained, closing",
10587
                             nc, (unsigned long) nc->recv_mbuf.len,
10588
                             (unsigned long) nc->recv_mbuf_limit));
10589
              nc->flags |= MG_F_CLOSE_IMMEDIATELY;
10590
            }
10591
          } else {
10592
            /* Should never be here */
10593
            LOG(LL_ERROR, ("%p invalid len: %d, closing", nc, len));
10594
            nc->flags |= MG_F_CLOSE_IMMEDIATELY;
10595
          }
10596
          break;
10597
        }
10598

    
10599
        nc->handler(nc, MG_MQTT_EVENT_BASE + mm.cmd, &mm MG_UD_ARG(user_data));
10600
        mbuf_remove(io, len);
10601
      }
10602
      break;
10603
    }
10604
    case MG_EV_POLL: {
10605
      struct mg_mqtt_proto_data *pd =
10606
          (struct mg_mqtt_proto_data *) nc->proto_data;
10607
      double now = mg_time();
10608
      if (pd->keep_alive > 0 && pd->last_control_time > 0 &&
10609
          (now - pd->last_control_time) > pd->keep_alive) {
10610
        LOG(LL_DEBUG, ("Send PINGREQ"));
10611
        mg_mqtt_ping(nc);
10612
      }
10613
      break;
10614
    }
10615
  }
10616
}
10617

    
10618
static void mg_mqtt_proto_data_destructor(void *proto_data) {
10619
  MG_FREE(proto_data);
10620
}
10621

    
10622
int mg_mqtt_match_topic_expression(struct mg_str exp, struct mg_str topic) {
10623
  /* TODO(mkm): implement real matching */
10624
  if (memchr(exp.p, '#', exp.len)) {
10625
    /* exp `foo/#` will become `foo/` */
10626
    exp.len -= 1;
10627
    /*
10628
     * topic should be longer than the expression: e.g. topic `foo/bar` does
10629
     * match `foo/#`, but neither `foo` nor `foo/` do.
10630
     */
10631
    if (topic.len <= exp.len) {
10632
      return 0;
10633
    }
10634

    
10635
    /* Truncate topic so that it'll pass the next length check */
10636
    topic.len = exp.len;
10637
  }
10638
  if (topic.len != exp.len) {
10639
    return 0;
10640
  }
10641
  return strncmp(topic.p, exp.p, exp.len) == 0;
10642
}
10643

    
10644
int mg_mqtt_vmatch_topic_expression(const char *exp, struct mg_str topic) {
10645
  return mg_mqtt_match_topic_expression(mg_mk_str(exp), topic);
10646
}
10647

    
10648
void mg_set_protocol_mqtt(struct mg_connection *nc) {
10649
  nc->proto_handler = mqtt_handler;
10650
  nc->proto_data = MG_CALLOC(1, sizeof(struct mg_mqtt_proto_data));
10651
  nc->proto_data_destructor = mg_mqtt_proto_data_destructor;
10652
}
10653

    
10654
static void mg_mqtt_prepend_header(struct mg_connection *nc, uint8_t cmd,
10655
                                   uint8_t flags, size_t len) {
10656
  struct mg_mqtt_proto_data *pd = (struct mg_mqtt_proto_data *) nc->proto_data;
10657
  size_t off = nc->send_mbuf.len - len;
10658
  uint8_t header = cmd << 4 | (uint8_t) flags;
10659

    
10660
  uint8_t buf[1 + sizeof(size_t)];
10661
  uint8_t *vlen = &buf[1];
10662

    
10663
  assert(nc->send_mbuf.len >= len);
10664

    
10665
  buf[0] = header;
10666

    
10667
  /* mqtt variable length encoding */
10668
  do {
10669
    *vlen = len % 0x80;
10670
    len /= 0x80;
10671
    if (len > 0) *vlen |= 0x80;
10672
    vlen++;
10673
  } while (len > 0);
10674

    
10675
  mbuf_insert(&nc->send_mbuf, off, buf, vlen - buf);
10676
  pd->last_control_time = mg_time();
10677
}
10678

    
10679
void mg_send_mqtt_handshake(struct mg_connection *nc, const char *client_id) {
10680
  static struct mg_send_mqtt_handshake_opts opts;
10681
  mg_send_mqtt_handshake_opt(nc, client_id, opts);
10682
}
10683

    
10684
void mg_send_mqtt_handshake_opt(struct mg_connection *nc, const char *client_id,
10685
                                struct mg_send_mqtt_handshake_opts opts) {
10686
  uint16_t hlen, nlen, rem_len = 0;
10687
  struct mg_mqtt_proto_data *pd = (struct mg_mqtt_proto_data *) nc->proto_data;
10688

    
10689
  mg_send(nc, "\00\04MQTT\04", 7);
10690
  rem_len += 7;
10691

    
10692
  if (opts.user_name != NULL) {
10693
    opts.flags |= MG_MQTT_HAS_USER_NAME;
10694
  }
10695
  if (opts.password != NULL) {
10696
    opts.flags |= MG_MQTT_HAS_PASSWORD;
10697
  }
10698
  if (opts.will_topic != NULL && opts.will_message != NULL) {
10699
    opts.flags |= MG_MQTT_HAS_WILL;
10700
  }
10701
  if (opts.keep_alive == 0) {
10702
    opts.keep_alive = 60;
10703
  }
10704

    
10705
  mg_send(nc, &opts.flags, 1);
10706
  rem_len += 1;
10707

    
10708
  nlen = htons(opts.keep_alive);
10709
  mg_send(nc, &nlen, 2);
10710
  rem_len += 2;
10711

    
10712
  hlen = strlen(client_id);
10713
  nlen = htons((uint16_t) hlen);
10714
  mg_send(nc, &nlen, 2);
10715
  mg_send(nc, client_id, hlen);
10716
  rem_len += 2 + hlen;
10717

    
10718
  if (opts.flags & MG_MQTT_HAS_WILL) {
10719
    hlen = strlen(opts.will_topic);
10720
    nlen = htons((uint16_t) hlen);
10721
    mg_send(nc, &nlen, 2);
10722
    mg_send(nc, opts.will_topic, hlen);
10723
    rem_len += 2 + hlen;
10724

    
10725
    hlen = strlen(opts.will_message);
10726
    nlen = htons((uint16_t) hlen);
10727
    mg_send(nc, &nlen, 2);
10728
    mg_send(nc, opts.will_message, hlen);
10729
    rem_len += 2 + hlen;
10730
  }
10731

    
10732
  if (opts.flags & MG_MQTT_HAS_USER_NAME) {
10733
    hlen = strlen(opts.user_name);
10734
    nlen = htons((uint16_t) hlen);
10735
    mg_send(nc, &nlen, 2);
10736
    mg_send(nc, opts.user_name, hlen);
10737
    rem_len += 2 + hlen;
10738
  }
10739
  if (opts.flags & MG_MQTT_HAS_PASSWORD) {
10740
    hlen = strlen(opts.password);
10741
    nlen = htons((uint16_t) hlen);
10742
    mg_send(nc, &nlen, 2);
10743
    mg_send(nc, opts.password, hlen);
10744
    rem_len += 2 + hlen;
10745
  }
10746

    
10747
  mg_mqtt_prepend_header(nc, MG_MQTT_CMD_CONNECT, 0, rem_len);
10748

    
10749
  if (pd != NULL) {
10750
    pd->keep_alive = opts.keep_alive;
10751
  }
10752
}
10753

    
10754
void mg_mqtt_publish(struct mg_connection *nc, const char *topic,
10755
                     uint16_t message_id, int flags, const void *data,
10756
                     size_t len) {
10757
  size_t old_len = nc->send_mbuf.len;
10758

    
10759
  uint16_t topic_len = htons((uint16_t) strlen(topic));
10760
  uint16_t message_id_net = htons(message_id);
10761

    
10762
  mg_send(nc, &topic_len, 2);
10763
  mg_send(nc, topic, strlen(topic));
10764
  if (MG_MQTT_GET_QOS(flags) > 0) {
10765
    mg_send(nc, &message_id_net, 2);
10766
  }
10767
  mg_send(nc, data, len);
10768

    
10769
  mg_mqtt_prepend_header(nc, MG_MQTT_CMD_PUBLISH, flags,
10770
                         nc->send_mbuf.len - old_len);
10771
}
10772

    
10773
void mg_mqtt_subscribe(struct mg_connection *nc,
10774
                       const struct mg_mqtt_topic_expression *topics,
10775
                       size_t topics_len, uint16_t message_id) {
10776
  size_t old_len = nc->send_mbuf.len;
10777

    
10778
  uint16_t message_id_n = htons(message_id);
10779
  size_t i;
10780

    
10781
  mg_send(nc, (char *) &message_id_n, 2);
10782
  for (i = 0; i < topics_len; i++) {
10783
    uint16_t topic_len_n = htons((uint16_t) strlen(topics[i].topic));
10784
    mg_send(nc, &topic_len_n, 2);
10785
    mg_send(nc, topics[i].topic, strlen(topics[i].topic));
10786
    mg_send(nc, &topics[i].qos, 1);
10787
  }
10788

    
10789
  mg_mqtt_prepend_header(nc, MG_MQTT_CMD_SUBSCRIBE, MG_MQTT_QOS(1),
10790
                         nc->send_mbuf.len - old_len);
10791
}
10792

    
10793
int mg_mqtt_next_subscribe_topic(struct mg_mqtt_message *msg,
10794
                                 struct mg_str *topic, uint8_t *qos, int pos) {
10795
  unsigned char *buf = (unsigned char *) msg->payload.p + pos;
10796
  int new_pos;
10797

    
10798
  if ((size_t) pos >= msg->payload.len) return -1;
10799

    
10800
  topic->len = buf[0] << 8 | buf[1];
10801
  topic->p = (char *) buf + 2;
10802
  new_pos = pos + 2 + topic->len + 1;
10803
  if ((size_t) new_pos > msg->payload.len) return -1;
10804
  *qos = buf[2 + topic->len];
10805
  return new_pos;
10806
}
10807

    
10808
void mg_mqtt_unsubscribe(struct mg_connection *nc, char **topics,
10809
                         size_t topics_len, uint16_t message_id) {
10810
  size_t old_len = nc->send_mbuf.len;
10811

    
10812
  uint16_t message_id_n = htons(message_id);
10813
  size_t i;
10814

    
10815
  mg_send(nc, (char *) &message_id_n, 2);
10816
  for (i = 0; i < topics_len; i++) {
10817
    uint16_t topic_len_n = htons((uint16_t) strlen(topics[i]));
10818
    mg_send(nc, &topic_len_n, 2);
10819
    mg_send(nc, topics[i], strlen(topics[i]));
10820
  }
10821

    
10822
  mg_mqtt_prepend_header(nc, MG_MQTT_CMD_UNSUBSCRIBE, MG_MQTT_QOS(1),
10823
                         nc->send_mbuf.len - old_len);
10824
}
10825

    
10826
void mg_mqtt_connack(struct mg_connection *nc, uint8_t return_code) {
10827
  uint8_t unused = 0;
10828
  mg_send(nc, &unused, 1);
10829
  mg_send(nc, &return_code, 1);
10830
  mg_mqtt_prepend_header(nc, MG_MQTT_CMD_CONNACK, 0, 2);
10831
}
10832

    
10833
/*
10834
 * Sends a command which contains only a `message_id` and a QoS level of 1.
10835
 *
10836
 * Helper function.
10837
 */
10838
static void mg_send_mqtt_short_command(struct mg_connection *nc, uint8_t cmd,
10839
                                       uint16_t message_id) {
10840
  uint16_t message_id_net = htons(message_id);
10841
  uint8_t flags = (cmd == MG_MQTT_CMD_PUBREL ? 2 : 0);
10842
  mg_send(nc, &message_id_net, 2);
10843
  mg_mqtt_prepend_header(nc, cmd, flags, 2 /* len */);
10844
}
10845

    
10846
void mg_mqtt_puback(struct mg_connection *nc, uint16_t message_id) {
10847
  mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBACK, message_id);
10848
}
10849

    
10850
void mg_mqtt_pubrec(struct mg_connection *nc, uint16_t message_id) {
10851
  mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBREC, message_id);
10852
}
10853

    
10854
void mg_mqtt_pubrel(struct mg_connection *nc, uint16_t message_id) {
10855
  mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBREL, message_id);
10856
}
10857

    
10858
void mg_mqtt_pubcomp(struct mg_connection *nc, uint16_t message_id) {
10859
  mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBCOMP, message_id);
10860
}
10861

    
10862
void mg_mqtt_suback(struct mg_connection *nc, uint8_t *qoss, size_t qoss_len,
10863
                    uint16_t message_id) {
10864
  size_t i;
10865
  uint16_t message_id_net = htons(message_id);
10866
  mg_send(nc, &message_id_net, 2);
10867
  for (i = 0; i < qoss_len; i++) {
10868
    mg_send(nc, &qoss[i], 1);
10869
  }
10870
  mg_mqtt_prepend_header(nc, MG_MQTT_CMD_SUBACK, MG_MQTT_QOS(1), 2 + qoss_len);
10871
}
10872

    
10873
void mg_mqtt_unsuback(struct mg_connection *nc, uint16_t message_id) {
10874
  mg_send_mqtt_short_command(nc, MG_MQTT_CMD_UNSUBACK, message_id);
10875
}
10876

    
10877
void mg_mqtt_ping(struct mg_connection *nc) {
10878
  mg_mqtt_prepend_header(nc, MG_MQTT_CMD_PINGREQ, 0, 0);
10879
}
10880

    
10881
void mg_mqtt_pong(struct mg_connection *nc) {
10882
  mg_mqtt_prepend_header(nc, MG_MQTT_CMD_PINGRESP, 0, 0);
10883
}
10884

    
10885
void mg_mqtt_disconnect(struct mg_connection *nc) {
10886
  mg_mqtt_prepend_header(nc, MG_MQTT_CMD_DISCONNECT, 0, 0);
10887
}
10888

    
10889
#endif /* MG_ENABLE_MQTT */
10890
#ifdef MG_MODULE_LINES
10891
#line 1 "mongoose/src/mg_mqtt_server.c"
10892
#endif
10893
/*
10894
 * Copyright (c) 2014 Cesanta Software Limited
10895
 * All rights reserved
10896
 */
10897

    
10898
/* Amalgamated: #include "mg_internal.h" */
10899
/* Amalgamated: #include "mg_mqtt_server.h" */
10900

    
10901
#if MG_ENABLE_MQTT_BROKER
10902

    
10903
static void mg_mqtt_session_init(struct mg_mqtt_broker *brk,
10904
                                 struct mg_mqtt_session *s,
10905
                                 struct mg_connection *nc) {
10906
  s->brk = brk;
10907
  s->subscriptions = NULL;
10908
  s->num_subscriptions = 0;
10909
  s->nc = nc;
10910
}
10911

    
10912
static void mg_mqtt_add_session(struct mg_mqtt_session *s) {
10913
  LIST_INSERT_HEAD(&s->brk->sessions, s, link);
10914
}
10915

    
10916
static void mg_mqtt_remove_session(struct mg_mqtt_session *s) {
10917
  LIST_REMOVE(s, link);
10918
}
10919

    
10920
static void mg_mqtt_destroy_session(struct mg_mqtt_session *s) {
10921
  size_t i;
10922
  for (i = 0; i < s->num_subscriptions; i++) {
10923
    MG_FREE((void *) s->subscriptions[i].topic);
10924
  }
10925
  MG_FREE(s->subscriptions);
10926
  MG_FREE(s);
10927
}
10928

    
10929
static void mg_mqtt_close_session(struct mg_mqtt_session *s) {
10930
  mg_mqtt_remove_session(s);
10931
  mg_mqtt_destroy_session(s);
10932
}
10933

    
10934
void mg_mqtt_broker_init(struct mg_mqtt_broker *brk, void *user_data) {
10935
  LIST_INIT(&brk->sessions);
10936
  brk->user_data = user_data;
10937
}
10938

    
10939
static void mg_mqtt_broker_handle_connect(struct mg_mqtt_broker *brk,
10940
                                          struct mg_connection *nc) {
10941
  struct mg_mqtt_session *s =
10942
      (struct mg_mqtt_session *) MG_CALLOC(1, sizeof *s);
10943
  if (s == NULL) {
10944
    /* LCOV_EXCL_START */
10945
    mg_mqtt_connack(nc, MG_EV_MQTT_CONNACK_SERVER_UNAVAILABLE);
10946
    return;
10947
    /* LCOV_EXCL_STOP */
10948
  }
10949

    
10950
  /* TODO(mkm): check header (magic and version) */
10951

    
10952
  mg_mqtt_session_init(brk, s, nc);
10953
  nc->priv_2 = s;
10954
  mg_mqtt_add_session(s);
10955

    
10956
  mg_mqtt_connack(nc, MG_EV_MQTT_CONNACK_ACCEPTED);
10957
}
10958

    
10959
static void mg_mqtt_broker_handle_subscribe(struct mg_connection *nc,
10960
                                            struct mg_mqtt_message *msg) {
10961
  struct mg_mqtt_session *ss = (struct mg_mqtt_session *) nc->priv_2;
10962
  uint8_t qoss[MG_MQTT_MAX_SESSION_SUBSCRIPTIONS];
10963
  size_t num_subs = 0;
10964
  struct mg_str topic;
10965
  uint8_t qos;
10966
  int pos;
10967
  struct mg_mqtt_topic_expression *te;
10968

    
10969
  for (pos = 0;
10970
       (pos = mg_mqtt_next_subscribe_topic(msg, &topic, &qos, pos)) != -1;) {
10971
    if (num_subs >= sizeof(MG_MQTT_MAX_SESSION_SUBSCRIPTIONS) ||
10972
        (ss->num_subscriptions + num_subs >=
10973
         MG_MQTT_MAX_SESSION_SUBSCRIPTIONS)) {
10974
      nc->flags |= MG_F_CLOSE_IMMEDIATELY;
10975
      return;
10976
    }
10977
    qoss[num_subs++] = qos;
10978
  }
10979

    
10980
  if (num_subs > 0) {
10981
    te = (struct mg_mqtt_topic_expression *) MG_REALLOC(
10982
        ss->subscriptions,
10983
        sizeof(*ss->subscriptions) * (ss->num_subscriptions + num_subs));
10984
    if (te == NULL) {
10985
      nc->flags |= MG_F_CLOSE_IMMEDIATELY;
10986
      return;
10987
    }
10988
    ss->subscriptions = te;
10989
    for (pos = 0;
10990
         pos < (int) msg->payload.len &&
10991
             (pos = mg_mqtt_next_subscribe_topic(msg, &topic, &qos, pos)) != -1;
10992
         ss->num_subscriptions++) {
10993
      te = &ss->subscriptions[ss->num_subscriptions];
10994
      te->topic = (char *) MG_MALLOC(topic.len + 1);
10995
      te->qos = qos;
10996
      memcpy((char *) te->topic, topic.p, topic.len);
10997
      ((char *) te->topic)[topic.len] = '\0';
10998
    }
10999
  }
11000

    
11001
  if (pos == (int) msg->payload.len) {
11002
    mg_mqtt_suback(nc, qoss, num_subs, msg->message_id);
11003
  } else {
11004
    /* We did not fully parse the payload, something must be wrong. */
11005
    nc->flags |= MG_F_CLOSE_IMMEDIATELY;
11006
  }
11007
}
11008

    
11009
static void mg_mqtt_broker_handle_publish(struct mg_mqtt_broker *brk,
11010
                                          struct mg_mqtt_message *msg) {
11011
  struct mg_mqtt_session *s;
11012
  size_t i;
11013

    
11014
  for (s = mg_mqtt_next(brk, NULL); s != NULL; s = mg_mqtt_next(brk, s)) {
11015
    for (i = 0; i < s->num_subscriptions; i++) {
11016
      if (mg_mqtt_vmatch_topic_expression(s->subscriptions[i].topic,
11017
                                          msg->topic)) {
11018
        char buf[100], *p = buf;
11019
        mg_asprintf(&p, sizeof(buf), "%.*s", (int) msg->topic.len,
11020
                    msg->topic.p);
11021
        if (p == NULL) {
11022
          return;
11023
        }
11024
        mg_mqtt_publish(s->nc, p, 0, 0, msg->payload.p, msg->payload.len);
11025
        if (p != buf) {
11026
          MG_FREE(p);
11027
        }
11028
        break;
11029
      }
11030
    }
11031
  }
11032
}
11033

    
11034
void mg_mqtt_broker(struct mg_connection *nc, int ev, void *data) {
11035
  struct mg_mqtt_message *msg = (struct mg_mqtt_message *) data;
11036
  struct mg_mqtt_broker *brk;
11037

    
11038
  if (nc->listener) {
11039
    brk = (struct mg_mqtt_broker *) nc->listener->priv_2;
11040
  } else {
11041
    brk = (struct mg_mqtt_broker *) nc->priv_2;
11042
  }
11043

    
11044
  switch (ev) {
11045
    case MG_EV_ACCEPT:
11046
      if (nc->proto_data == NULL) mg_set_protocol_mqtt(nc);
11047
      nc->priv_2 = NULL; /* Clear up the inherited pointer to broker */
11048
      break;
11049
    case MG_EV_MQTT_CONNECT:
11050
      if (nc->priv_2 == NULL) {
11051
        mg_mqtt_broker_handle_connect(brk, nc);
11052
      } else {
11053
        /* Repeated CONNECT */
11054
        nc->flags |= MG_F_CLOSE_IMMEDIATELY;
11055
      }
11056
      break;
11057
    case MG_EV_MQTT_SUBSCRIBE:
11058
      if (nc->priv_2 != NULL) {
11059
        mg_mqtt_broker_handle_subscribe(nc, msg);
11060
      } else {
11061
        /* Subscribe before CONNECT */
11062
        nc->flags |= MG_F_CLOSE_IMMEDIATELY;
11063
      }
11064
      break;
11065
    case MG_EV_MQTT_PUBLISH:
11066
      if (nc->priv_2 != NULL) {
11067
        mg_mqtt_broker_handle_publish(brk, msg);
11068
      } else {
11069
        /* Publish before CONNECT */
11070
        nc->flags |= MG_F_CLOSE_IMMEDIATELY;
11071
      }
11072
      break;
11073
    case MG_EV_CLOSE:
11074
      if (nc->listener && nc->priv_2 != NULL) {
11075
        mg_mqtt_close_session((struct mg_mqtt_session *) nc->priv_2);
11076
      }
11077
      break;
11078
  }
11079
}
11080

    
11081
struct mg_mqtt_session *mg_mqtt_next(struct mg_mqtt_broker *brk,
11082
                                     struct mg_mqtt_session *s) {
11083
  return s == NULL ? LIST_FIRST(&brk->sessions) : LIST_NEXT(s, link);
11084
}
11085

    
11086
#endif /* MG_ENABLE_MQTT_BROKER */
11087
#ifdef MG_MODULE_LINES
11088
#line 1 "mongoose/src/mg_dns.c"
11089
#endif
11090
/*
11091
 * Copyright (c) 2014 Cesanta Software Limited
11092
 * All rights reserved
11093
 */
11094

    
11095
#if MG_ENABLE_DNS
11096

    
11097
/* Amalgamated: #include "mg_internal.h" */
11098
/* Amalgamated: #include "mg_dns.h" */
11099

    
11100
static int mg_dns_tid = 0xa0;
11101

    
11102
struct mg_dns_header {
11103
  uint16_t transaction_id;
11104
  uint16_t flags;
11105
  uint16_t num_questions;
11106
  uint16_t num_answers;
11107
  uint16_t num_authority_prs;
11108
  uint16_t num_other_prs;
11109
};
11110

    
11111
struct mg_dns_resource_record *mg_dns_next_record(
11112
    struct mg_dns_message *msg, int query,
11113
    struct mg_dns_resource_record *prev) {
11114
  struct mg_dns_resource_record *rr;
11115

    
11116
  for (rr = (prev == NULL ? msg->answers : prev + 1);
11117
       rr - msg->answers < msg->num_answers; rr++) {
11118
    if (rr->rtype == query) {
11119
      return rr;
11120
    }
11121
  }
11122
  return NULL;
11123
}
11124

    
11125
int mg_dns_parse_record_data(struct mg_dns_message *msg,
11126
                             struct mg_dns_resource_record *rr, void *data,
11127
                             size_t data_len) {
11128
  switch (rr->rtype) {
11129
    case MG_DNS_A_RECORD:
11130
      if (data_len < sizeof(struct in_addr)) {
11131
        return -1;
11132
      }
11133
      if (rr->rdata.p + data_len > msg->pkt.p + msg->pkt.len) {
11134
        return -1;
11135
      }
11136
      memcpy(data, rr->rdata.p, data_len);
11137
      return 0;
11138
#if MG_ENABLE_IPV6
11139
    case MG_DNS_AAAA_RECORD:
11140
      if (data_len < sizeof(struct in6_addr)) {
11141
        return -1; /* LCOV_EXCL_LINE */
11142
      }
11143
      memcpy(data, rr->rdata.p, data_len);
11144
      return 0;
11145
#endif
11146
    case MG_DNS_CNAME_RECORD:
11147
      mg_dns_uncompress_name(msg, &rr->rdata, (char *) data, data_len);
11148
      return 0;
11149
  }
11150

    
11151
  return -1;
11152
}
11153

    
11154
int mg_dns_insert_header(struct mbuf *io, size_t pos,
11155
                         struct mg_dns_message *msg) {
11156
  struct mg_dns_header header;
11157

    
11158
  memset(&header, 0, sizeof(header));
11159
  header.transaction_id = msg->transaction_id;
11160
  header.flags = htons(msg->flags);
11161
  header.num_questions = htons(msg->num_questions);
11162
  header.num_answers = htons(msg->num_answers);
11163

    
11164
  return mbuf_insert(io, pos, &header, sizeof(header));
11165
}
11166

    
11167
int mg_dns_copy_questions(struct mbuf *io, struct mg_dns_message *msg) {
11168
  unsigned char *begin, *end;
11169
  struct mg_dns_resource_record *last_q;
11170
  if (msg->num_questions <= 0) return 0;
11171
  begin = (unsigned char *) msg->pkt.p + sizeof(struct mg_dns_header);
11172
  last_q = &msg->questions[msg->num_questions - 1];
11173
  end = (unsigned char *) last_q->name.p + last_q->name.len + 4;
11174
  return mbuf_append(io, begin, end - begin);
11175
}
11176

    
11177
int mg_dns_encode_name(struct mbuf *io, const char *name, size_t len) {
11178
  const char *s;
11179
  unsigned char n;
11180
  size_t pos = io->len;
11181

    
11182
  do {
11183
    if ((s = strchr(name, '.')) == NULL) {
11184
      s = name + len;
11185
    }
11186

    
11187
    if (s - name > 127) {
11188
      return -1; /* TODO(mkm) cover */
11189
    }
11190
    n = s - name;           /* chunk length */
11191
    mbuf_append(io, &n, 1); /* send length */
11192
    mbuf_append(io, name, n);
11193

    
11194
    if (*s == '.') {
11195
      n++;
11196
    }
11197

    
11198
    name += n;
11199
    len -= n;
11200
  } while (*s != '\0');
11201
  mbuf_append(io, "\0", 1); /* Mark end of host name */
11202

    
11203
  return io->len - pos;
11204
}
11205

    
11206
int mg_dns_encode_record(struct mbuf *io, struct mg_dns_resource_record *rr,
11207
                         const char *name, size_t nlen, const void *rdata,
11208
                         size_t rlen) {
11209
  size_t pos = io->len;
11210
  uint16_t u16;
11211
  uint32_t u32;
11212

    
11213
  if (rr->kind == MG_DNS_INVALID_RECORD) {
11214
    return -1; /* LCOV_EXCL_LINE */
11215
  }
11216

    
11217
  if (mg_dns_encode_name(io, name, nlen) == -1) {
11218
    return -1;
11219
  }
11220

    
11221
  u16 = htons(rr->rtype);
11222
  mbuf_append(io, &u16, 2);
11223
  u16 = htons(rr->rclass);
11224
  mbuf_append(io, &u16, 2);
11225

    
11226
  if (rr->kind == MG_DNS_ANSWER) {
11227
    u32 = htonl(rr->ttl);
11228
    mbuf_append(io, &u32, 4);
11229

    
11230
    if (rr->rtype == MG_DNS_CNAME_RECORD) {
11231
      int clen;
11232
      /* fill size after encoding */
11233
      size_t off = io->len;
11234
      mbuf_append(io, &u16, 2);
11235
      if ((clen = mg_dns_encode_name(io, (const char *) rdata, rlen)) == -1) {
11236
        return -1;
11237
      }
11238
      u16 = clen;
11239
      io->buf[off] = u16 >> 8;
11240
      io->buf[off + 1] = u16 & 0xff;
11241
    } else {
11242
      u16 = htons((uint16_t) rlen);
11243
      mbuf_append(io, &u16, 2);
11244
      mbuf_append(io, rdata, rlen);
11245
    }
11246
  }
11247

    
11248
  return io->len - pos;
11249
}
11250

    
11251
void mg_send_dns_query(struct mg_connection *nc, const char *name,
11252
                       int query_type) {
11253
  struct mg_dns_message *msg =
11254
      (struct mg_dns_message *) MG_CALLOC(1, sizeof(*msg));
11255
  struct mbuf pkt;
11256
  struct mg_dns_resource_record *rr = &msg->questions[0];
11257

    
11258
  DBG(("%s %d", name, query_type));
11259

    
11260
  mbuf_init(&pkt, 64 /* Start small, it'll grow as needed. */);
11261

    
11262
  msg->transaction_id = ++mg_dns_tid;
11263
  msg->flags = 0x100;
11264
  msg->num_questions = 1;
11265

    
11266
  mg_dns_insert_header(&pkt, 0, msg);
11267

    
11268
  rr->rtype = query_type;
11269
  rr->rclass = 1; /* Class: inet */
11270
  rr->kind = MG_DNS_QUESTION;
11271

    
11272
  if (mg_dns_encode_record(&pkt, rr, name, strlen(name), NULL, 0) == -1) {
11273
    /* TODO(mkm): return an error code */
11274
    goto cleanup; /* LCOV_EXCL_LINE */
11275
  }
11276

    
11277
  /* TCP DNS requires messages to be prefixed with len */
11278
  if (!(nc->flags & MG_F_UDP)) {
11279
    uint16_t len = htons((uint16_t) pkt.len);
11280
    mbuf_insert(&pkt, 0, &len, 2);
11281
  }
11282

    
11283
  mg_send(nc, pkt.buf, pkt.len);
11284
  mbuf_free(&pkt);
11285

    
11286
cleanup:
11287
  MG_FREE(msg);
11288
}
11289

    
11290
static unsigned char *mg_parse_dns_resource_record(
11291
    unsigned char *data, unsigned char *end, struct mg_dns_resource_record *rr,
11292
    int reply) {
11293
  unsigned char *name = data;
11294
  int chunk_len, data_len;
11295

    
11296
  while (data < end && (chunk_len = *data)) {
11297
    if (((unsigned char *) data)[0] & 0xc0) {
11298
      data += 1;
11299
      break;
11300
    }
11301
    data += chunk_len + 1;
11302
  }
11303

    
11304
  if (data > end - 5) {
11305
    return NULL;
11306
  }
11307

    
11308
  rr->name.p = (char *) name;
11309
  rr->name.len = data - name + 1;
11310
  data++;
11311

    
11312
  rr->rtype = data[0] << 8 | data[1];
11313
  data += 2;
11314

    
11315
  rr->rclass = data[0] << 8 | data[1];
11316
  data += 2;
11317

    
11318
  rr->kind = reply ? MG_DNS_ANSWER : MG_DNS_QUESTION;
11319
  if (reply) {
11320
    if (data >= end - 6) {
11321
      return NULL;
11322
    }
11323

    
11324
    rr->ttl = (uint32_t) data[0] << 24 | (uint32_t) data[1] << 16 |
11325
              data[2] << 8 | data[3];
11326
    data += 4;
11327

    
11328
    data_len = *data << 8 | *(data + 1);
11329
    data += 2;
11330

    
11331
    rr->rdata.p = (char *) data;
11332
    rr->rdata.len = data_len;
11333
    data += data_len;
11334
  }
11335
  return data;
11336
}
11337

    
11338
int mg_parse_dns(const char *buf, int len, struct mg_dns_message *msg) {
11339
  struct mg_dns_header *header = (struct mg_dns_header *) buf;
11340
  unsigned char *data = (unsigned char *) buf + sizeof(*header);
11341
  unsigned char *end = (unsigned char *) buf + len;
11342
  int i;
11343

    
11344
  memset(msg, 0, sizeof(*msg));
11345
  msg->pkt.p = buf;
11346
  msg->pkt.len = len;
11347

    
11348
  if (len < (int) sizeof(*header)) return -1;
11349

    
11350
  msg->transaction_id = header->transaction_id;
11351
  msg->flags = ntohs(header->flags);
11352
  msg->num_questions = ntohs(header->num_questions);
11353
  if (msg->num_questions > (int) ARRAY_SIZE(msg->questions)) {
11354
    msg->num_questions = (int) ARRAY_SIZE(msg->questions);
11355
  }
11356
  msg->num_answers = ntohs(header->num_answers);
11357
  if (msg->num_answers > (int) ARRAY_SIZE(msg->answers)) {
11358
    msg->num_answers = (int) ARRAY_SIZE(msg->answers);
11359
  }
11360

    
11361
  for (i = 0; i < msg->num_questions; i++) {
11362
    data = mg_parse_dns_resource_record(data, end, &msg->questions[i], 0);
11363
    if (data == NULL) return -1;
11364
  }
11365

    
11366
  for (i = 0; i < msg->num_answers; i++) {
11367
    data = mg_parse_dns_resource_record(data, end, &msg->answers[i], 1);
11368
    if (data == NULL) return -1;
11369
  }
11370

    
11371
  return 0;
11372
}
11373

    
11374
size_t mg_dns_uncompress_name(struct mg_dns_message *msg, struct mg_str *name,
11375
                              char *dst, int dst_len) {
11376
  int chunk_len, num_ptrs = 0;
11377
  char *old_dst = dst;
11378
  const unsigned char *data = (unsigned char *) name->p;
11379
  const unsigned char *end = (unsigned char *) msg->pkt.p + msg->pkt.len;
11380

    
11381
  if (data >= end) {
11382
    return 0;
11383
  }
11384

    
11385
  while ((chunk_len = *data++)) {
11386
    int leeway = dst_len - (dst - old_dst);
11387
    if (data >= end) {
11388
      return 0;
11389
    }
11390

    
11391
    if ((chunk_len & 0xc0) == 0xc0) {
11392
      uint16_t off = (data[-1] & (~0xc0)) << 8 | data[0];
11393
      if (off >= msg->pkt.len) {
11394
        return 0;
11395
      }
11396
      /* Basic circular loop avoidance: allow up to 16 pointer hops. */
11397
      if (++num_ptrs > 15) {
11398
        return 0;
11399
      }
11400
      data = (unsigned char *) msg->pkt.p + off;
11401
      continue;
11402
    }
11403
    if (chunk_len > 63) {
11404
      return 0;
11405
    }
11406
    if (chunk_len > leeway) {
11407
      chunk_len = leeway;
11408
    }
11409

    
11410
    if (data + chunk_len >= end) {
11411
      return 0;
11412
    }
11413

    
11414
    memcpy(dst, data, chunk_len);
11415
    data += chunk_len;
11416
    dst += chunk_len;
11417
    leeway -= chunk_len;
11418
    if (leeway == 0) {
11419
      return dst - old_dst;
11420
    }
11421
    *dst++ = '.';
11422
  }
11423

    
11424
  if (dst != old_dst) {
11425
    *--dst = 0;
11426
  }
11427
  return dst - old_dst;
11428
}
11429

    
11430
static void dns_handler(struct mg_connection *nc, int ev,
11431
                        void *ev_data MG_UD_ARG(void *user_data)) {
11432
  struct mbuf *io = &nc->recv_mbuf;
11433
  struct mg_dns_message msg;
11434

    
11435
  /* Pass low-level events to the user handler */
11436
  nc->handler(nc, ev, ev_data MG_UD_ARG(user_data));
11437

    
11438
  switch (ev) {
11439
    case MG_EV_RECV:
11440
      if (!(nc->flags & MG_F_UDP)) {
11441
        mbuf_remove(&nc->recv_mbuf, 2);
11442
      }
11443
      if (mg_parse_dns(nc->recv_mbuf.buf, nc->recv_mbuf.len, &msg) == -1) {
11444
        /* reply + recursion allowed + format error */
11445
        memset(&msg, 0, sizeof(msg));
11446
        msg.flags = 0x8081;
11447
        mg_dns_insert_header(io, 0, &msg);
11448
        if (!(nc->flags & MG_F_UDP)) {
11449
          uint16_t len = htons((uint16_t) io->len);
11450
          mbuf_insert(io, 0, &len, 2);
11451
        }
11452
        mg_send(nc, io->buf, io->len);
11453
      } else {
11454
        /* Call user handler with parsed message */
11455
        nc->handler(nc, MG_DNS_MESSAGE, &msg MG_UD_ARG(user_data));
11456
      }
11457
      mbuf_remove(io, io->len);
11458
      break;
11459
  }
11460
}
11461

    
11462
void mg_set_protocol_dns(struct mg_connection *nc) {
11463
  nc->proto_handler = dns_handler;
11464
}
11465

    
11466
#endif /* MG_ENABLE_DNS */
11467
#ifdef MG_MODULE_LINES
11468
#line 1 "mongoose/src/mg_dns_server.c"
11469
#endif
11470
/*
11471
 * Copyright (c) 2014 Cesanta Software Limited
11472
 * All rights reserved
11473
 */
11474

    
11475
#if MG_ENABLE_DNS_SERVER
11476

    
11477
/* Amalgamated: #include "mg_internal.h" */
11478
/* Amalgamated: #include "dns-server.h" */
11479

    
11480
struct mg_dns_reply mg_dns_create_reply(struct mbuf *io,
11481
                                        struct mg_dns_message *msg) {
11482
  struct mg_dns_reply rep;
11483
  rep.msg = msg;
11484
  rep.io = io;
11485
  rep.start = io->len;
11486

    
11487
  /* reply + recursion allowed */
11488
  msg->flags |= 0x8080;
11489
  mg_dns_copy_questions(io, msg);
11490

    
11491
  msg->num_answers = 0;
11492
  return rep;
11493
}
11494

    
11495
void mg_dns_send_reply(struct mg_connection *nc, struct mg_dns_reply *r) {
11496
  size_t sent = r->io->len - r->start;
11497
  mg_dns_insert_header(r->io, r->start, r->msg);
11498
  if (!(nc->flags & MG_F_UDP)) {
11499
    uint16_t len = htons((uint16_t) sent);
11500
    mbuf_insert(r->io, r->start, &len, 2);
11501
  }
11502

    
11503
  if (&nc->send_mbuf != r->io) {
11504
    mg_send(nc, r->io->buf + r->start, r->io->len - r->start);
11505
    r->io->len = r->start;
11506
  }
11507
}
11508

    
11509
int mg_dns_reply_record(struct mg_dns_reply *reply,
11510
                        struct mg_dns_resource_record *question,
11511
                        const char *name, int rtype, int ttl, const void *rdata,
11512
                        size_t rdata_len) {
11513
  struct mg_dns_message *msg = (struct mg_dns_message *) reply->msg;
11514
  char rname[512];
11515
  struct mg_dns_resource_record *ans = &msg->answers[msg->num_answers];
11516
  if (msg->num_answers >= MG_MAX_DNS_ANSWERS) {
11517
    return -1; /* LCOV_EXCL_LINE */
11518
  }
11519

    
11520
  if (name == NULL) {
11521
    name = rname;
11522
    rname[511] = 0;
11523
    mg_dns_uncompress_name(msg, &question->name, rname, sizeof(rname) - 1);
11524
  }
11525

    
11526
  *ans = *question;
11527
  ans->kind = MG_DNS_ANSWER;
11528
  ans->rtype = rtype;
11529
  ans->ttl = ttl;
11530

    
11531
  if (mg_dns_encode_record(reply->io, ans, name, strlen(name), rdata,
11532
                           rdata_len) == -1) {
11533
    return -1; /* LCOV_EXCL_LINE */
11534
  };
11535

    
11536
  msg->num_answers++;
11537
  return 0;
11538
}
11539

    
11540
#endif /* MG_ENABLE_DNS_SERVER */
11541
#ifdef MG_MODULE_LINES
11542
#line 1 "mongoose/src/mg_resolv.c"
11543
#endif
11544
/*
11545
 * Copyright (c) 2014 Cesanta Software Limited
11546
 * All rights reserved
11547
 */
11548

    
11549
#if MG_ENABLE_ASYNC_RESOLVER
11550

    
11551
/* Amalgamated: #include "mg_internal.h" */
11552
/* Amalgamated: #include "mg_resolv.h" */
11553

    
11554
#ifndef MG_DEFAULT_NAMESERVER
11555
#define MG_DEFAULT_NAMESERVER "8.8.8.8"
11556
#endif
11557

    
11558
struct mg_resolve_async_request {
11559
  char name[1024];
11560
  int query;
11561
  mg_resolve_callback_t callback;
11562
  void *data;
11563
  time_t timeout;
11564
  int max_retries;
11565
  enum mg_resolve_err err;
11566

    
11567
  /* state */
11568
  time_t last_time;
11569
  int retries;
11570
};
11571

    
11572
/*
11573
 * Find what nameserver to use.
11574
 *
11575
 * Return 0 if OK, -1 if error
11576
 */
11577
static int mg_get_ip_address_of_nameserver(char *name, size_t name_len) {
11578
  int ret = -1;
11579

    
11580
#ifdef _WIN32
11581
  int i;
11582
  LONG err;
11583
  HKEY hKey, hSub;
11584
  wchar_t subkey[512], value[128],
11585
      *key = L"SYSTEM\\ControlSet001\\Services\\Tcpip\\Parameters\\Interfaces";
11586

    
11587
  if ((err = RegOpenKeyExW(HKEY_LOCAL_MACHINE, key, 0, KEY_READ, &hKey)) !=
11588
      ERROR_SUCCESS) {
11589
    fprintf(stderr, "cannot open reg key %S: %ld\n", key, err);
11590
    ret = -1;
11591
  } else {
11592
    for (ret = -1, i = 0; 1; i++) {
11593
      DWORD subkey_size = sizeof(subkey), type, len = sizeof(value);
11594
      if (RegEnumKeyExW(hKey, i, subkey, &subkey_size, NULL, NULL, NULL,
11595
                        NULL) != ERROR_SUCCESS) {
11596
        break;
11597
      }
11598
      if (RegOpenKeyExW(hKey, subkey, 0, KEY_READ, &hSub) == ERROR_SUCCESS &&
11599
          ((RegQueryValueExW(hSub, L"NameServer", 0, &type, (void *) value,
11600
                             &len) == ERROR_SUCCESS &&
11601
            value[0] != '\0') ||
11602
           (RegQueryValueExW(hSub, L"DhcpNameServer", 0, &type, (void *) value,
11603
                             &len) == ERROR_SUCCESS &&
11604
            value[0] != '\0'))) {
11605
        /*
11606
         * See https://github.com/cesanta/mongoose/issues/176
11607
         * The value taken from the registry can be empty, a single
11608
         * IP address, or multiple IP addresses separated by comma.
11609
         * If it's empty, check the next interface.
11610
         * If it's multiple IP addresses, take the first one.
11611
         */
11612
        wchar_t *comma = wcschr(value, ',');
11613
        if (comma != NULL) {
11614
          *comma = '\0';
11615
        }
11616
        /* %S will convert wchar_t -> char */
11617
        snprintf(name, name_len, "%S", value);
11618
        ret = 0;
11619
        RegCloseKey(hSub);
11620
        break;
11621
      }
11622
    }
11623
    RegCloseKey(hKey);
11624
  }
11625
#elif MG_ENABLE_FILESYSTEM && defined(MG_RESOLV_CONF_FILE_NAME)
11626
  FILE *fp;
11627
  char line[512];
11628

    
11629
  if ((fp = mg_fopen(MG_RESOLV_CONF_FILE_NAME, "r")) == NULL) {
11630
    ret = -1;
11631
  } else {
11632
    /* Try to figure out what nameserver to use */
11633
    for (ret = -1; fgets(line, sizeof(line), fp) != NULL;) {
11634
      unsigned int a, b, c, d;
11635
      if (sscanf(line, "nameserver %u.%u.%u.%u", &a, &b, &c, &d) == 4) {
11636
        snprintf(name, name_len, "%u.%u.%u.%u", a, b, c, d);
11637
        ret = 0;
11638
        break;
11639
      }
11640
    }
11641
    (void) fclose(fp);
11642
  }
11643
#else
11644
  snprintf(name, name_len, "%s", MG_DEFAULT_NAMESERVER);
11645
#endif /* _WIN32 */
11646

    
11647
  return ret;
11648
}
11649

    
11650
int mg_resolve_from_hosts_file(const char *name, union socket_address *usa) {
11651
#if MG_ENABLE_FILESYSTEM && defined(MG_HOSTS_FILE_NAME)
11652
  /* TODO(mkm) cache /etc/hosts */
11653
  FILE *fp;
11654
  char line[1024];
11655
  char *p;
11656
  char alias[256];
11657
  unsigned int a, b, c, d;
11658
  int len = 0;
11659

    
11660
  if ((fp = mg_fopen(MG_HOSTS_FILE_NAME, "r")) == NULL) {
11661
    return -1;
11662
  }
11663

    
11664
  for (; fgets(line, sizeof(line), fp) != NULL;) {
11665
    if (line[0] == '#') continue;
11666

    
11667
    if (sscanf(line, "%u.%u.%u.%u%n", &a, &b, &c, &d, &len) == 0) {
11668
      /* TODO(mkm): handle ipv6 */
11669
      continue;
11670
    }
11671
    for (p = line + len; sscanf(p, "%s%n", alias, &len) == 1; p += len) {
11672
      if (strcmp(alias, name) == 0) {
11673
        usa->sin.sin_addr.s_addr = htonl(a << 24 | b << 16 | c << 8 | d);
11674
        fclose(fp);
11675
        return 0;
11676
      }
11677
    }
11678
  }
11679

    
11680
  fclose(fp);
11681
#else
11682
  (void) name;
11683
  (void) usa;
11684
#endif
11685

    
11686
  return -1;
11687
}
11688

    
11689
static void mg_resolve_async_eh(struct mg_connection *nc, int ev,
11690
                                void *data MG_UD_ARG(void *user_data)) {
11691
  time_t now = (time_t) mg_time();
11692
  struct mg_resolve_async_request *req;
11693
  struct mg_dns_message *msg;
11694
  int first = 0;
11695
#if !MG_ENABLE_CALLBACK_USERDATA
11696
  void *user_data = nc->user_data;
11697
#endif
11698

    
11699
  if (ev != MG_EV_POLL) DBG(("ev=%d user_data=%p", ev, user_data));
11700

    
11701
  req = (struct mg_resolve_async_request *) user_data;
11702

    
11703
  if (req == NULL) {
11704
    return;
11705
  }
11706

    
11707
  switch (ev) {
11708
    case MG_EV_CONNECT:
11709
      /* don't depend on timer not being at epoch for sending out first req */
11710
      first = 1;
11711
    /* fallthrough */
11712
    case MG_EV_POLL:
11713
      if (req->retries > req->max_retries) {
11714
        req->err = MG_RESOLVE_EXCEEDED_RETRY_COUNT;
11715
        nc->flags |= MG_F_CLOSE_IMMEDIATELY;
11716
        break;
11717
      }
11718
      if (first || now - req->last_time >= req->timeout) {
11719
        mg_send_dns_query(nc, req->name, req->query);
11720
        req->last_time = now;
11721
        req->retries++;
11722
      }
11723
      break;
11724
    case MG_EV_RECV:
11725
      msg = (struct mg_dns_message *) MG_MALLOC(sizeof(*msg));
11726
      if (mg_parse_dns(nc->recv_mbuf.buf, *(int *) data, msg) == 0 &&
11727
          msg->num_answers > 0) {
11728
        req->callback(msg, req->data, MG_RESOLVE_OK);
11729
        nc->user_data = NULL;
11730
        MG_FREE(req);
11731
      } else {
11732
        req->err = MG_RESOLVE_NO_ANSWERS;
11733
      }
11734
      MG_FREE(msg);
11735
      nc->flags |= MG_F_CLOSE_IMMEDIATELY;
11736
      break;
11737
    case MG_EV_SEND:
11738
      /*
11739
       * If a send error occurs, prevent closing of the connection by the core.
11740
       * We will retry after timeout.
11741
       */
11742
      nc->flags &= ~MG_F_CLOSE_IMMEDIATELY;
11743
      mbuf_remove(&nc->send_mbuf, nc->send_mbuf.len);
11744
      break;
11745
    case MG_EV_TIMER:
11746
      req->err = MG_RESOLVE_TIMEOUT;
11747
      nc->flags |= MG_F_CLOSE_IMMEDIATELY;
11748
      break;
11749
    case MG_EV_CLOSE:
11750
      /* If we got here with request still not done, fire an error callback. */
11751
      if (req != NULL) {
11752
        char addr[32];
11753
        mg_sock_addr_to_str(&nc->sa, addr, sizeof(addr), MG_SOCK_STRINGIFY_IP);
11754
#ifdef MG_LOG_DNS_FAILURES
11755
        LOG(LL_ERROR, ("Failed to resolve '%s', server %s", req->name, addr));
11756
#endif
11757
        req->callback(NULL, req->data, req->err);
11758
        nc->user_data = NULL;
11759
        MG_FREE(req);
11760
      }
11761
      break;
11762
  }
11763
}
11764

    
11765
int mg_resolve_async(struct mg_mgr *mgr, const char *name, int query,
11766
                     mg_resolve_callback_t cb, void *data) {
11767
  struct mg_resolve_async_opts opts;
11768
  memset(&opts, 0, sizeof(opts));
11769
  return mg_resolve_async_opt(mgr, name, query, cb, data, opts);
11770
}
11771

    
11772
int mg_resolve_async_opt(struct mg_mgr *mgr, const char *name, int query,
11773
                         mg_resolve_callback_t cb, void *data,
11774
                         struct mg_resolve_async_opts opts) {
11775
  struct mg_resolve_async_request *req;
11776
  struct mg_connection *dns_nc;
11777
  const char *nameserver = opts.nameserver;
11778
  char dns_server_buff[17], nameserver_url[26];
11779

    
11780
  if (nameserver == NULL) {
11781
    nameserver = mgr->nameserver;
11782
  }
11783

    
11784
  DBG(("%s %d %p", name, query, opts.dns_conn));
11785

    
11786
  /* resolve with DNS */
11787
  req = (struct mg_resolve_async_request *) MG_CALLOC(1, sizeof(*req));
11788
  if (req == NULL) {
11789
    return -1;
11790
  }
11791

    
11792
  strncpy(req->name, name, sizeof(req->name));
11793
  req->name[sizeof(req->name) - 1] = '\0';
11794

    
11795
  req->query = query;
11796
  req->callback = cb;
11797
  req->data = data;
11798
  /* TODO(mkm): parse defaults out of resolve.conf */
11799
  req->max_retries = opts.max_retries ? opts.max_retries : 2;
11800
  req->timeout = opts.timeout ? opts.timeout : 5;
11801

    
11802
  /* Lazily initialize dns server */
11803
  if (nameserver == NULL) {
11804
    if (mg_get_ip_address_of_nameserver(dns_server_buff,
11805
                                        sizeof(dns_server_buff)) != -1) {
11806
      nameserver = dns_server_buff;
11807
    } else {
11808
      nameserver = MG_DEFAULT_NAMESERVER;
11809
    }
11810
  }
11811

    
11812
  snprintf(nameserver_url, sizeof(nameserver_url), "udp://%s:53", nameserver);
11813

    
11814
  dns_nc = mg_connect(mgr, nameserver_url, MG_CB(mg_resolve_async_eh, NULL));
11815
  if (dns_nc == NULL) {
11816
    MG_FREE(req);
11817
    return -1;
11818
  }
11819
  dns_nc->user_data = req;
11820
  if (opts.dns_conn != NULL) {
11821
    *opts.dns_conn = dns_nc;
11822
  }
11823

    
11824
  return 0;
11825
}
11826

    
11827
void mg_set_nameserver(struct mg_mgr *mgr, const char *nameserver) {
11828
  MG_FREE((char *) mgr->nameserver);
11829
  mgr->nameserver = NULL;
11830
  if (nameserver != NULL) {
11831
    mgr->nameserver = strdup(nameserver);
11832
  }
11833
}
11834

    
11835
#endif /* MG_ENABLE_ASYNC_RESOLVER */
11836
#ifdef MG_MODULE_LINES
11837
#line 1 "mongoose/src/mg_coap.c"
11838
#endif
11839
/*
11840
 * Copyright (c) 2015 Cesanta Software Limited
11841
 * All rights reserved
11842
 * This software is dual-licensed: you can redistribute it and/or modify
11843
 * it under the terms of the GNU General Public License version 2 as
11844
 * published by the Free Software Foundation. For the terms of this
11845
 * license, see <http://www.gnu.org/licenses/>.
11846
 *
11847
 * You are free to use this software under the terms of the GNU General
11848
 * Public License, but WITHOUT ANY WARRANTY; without even the implied
11849
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
11850
 * See the GNU General Public License for more details.
11851
 *
11852
 * Alternatively, you can license this software under a commercial
11853
 * license, as set out in <https://www.cesanta.com/license>.
11854
 */
11855

    
11856
/* Amalgamated: #include "mg_internal.h" */
11857
/* Amalgamated: #include "mg_coap.h" */
11858

    
11859
#if MG_ENABLE_COAP
11860

    
11861
void mg_coap_free_options(struct mg_coap_message *cm) {
11862
  while (cm->options != NULL) {
11863
    struct mg_coap_option *next = cm->options->next;
11864
    MG_FREE(cm->options);
11865
    cm->options = next;
11866
  }
11867
}
11868

    
11869
struct mg_coap_option *mg_coap_add_option(struct mg_coap_message *cm,
11870
                                          uint32_t number, char *value,
11871
                                          size_t len) {
11872
  struct mg_coap_option *new_option =
11873
      (struct mg_coap_option *) MG_CALLOC(1, sizeof(*new_option));
11874

    
11875
  new_option->number = number;
11876
  new_option->value.p = value;
11877
  new_option->value.len = len;
11878

    
11879
  if (cm->options == NULL) {
11880
    cm->options = cm->optiomg_tail = new_option;
11881
  } else {
11882
    /*
11883
     * A very simple attention to help clients to compose options:
11884
     * CoAP wants to see options ASC ordered.
11885
     * Could be change by using sort in coap_compose
11886
     */
11887
    if (cm->optiomg_tail->number <= new_option->number) {
11888
      /* if option is already ordered just add it */
11889
      cm->optiomg_tail = cm->optiomg_tail->next = new_option;
11890
    } else {
11891
      /* looking for appropriate position */
11892
      struct mg_coap_option *current_opt = cm->options;
11893
      struct mg_coap_option *prev_opt = 0;
11894

    
11895
      while (current_opt != NULL) {
11896
        if (current_opt->number > new_option->number) {
11897
          break;
11898
        }
11899
        prev_opt = current_opt;
11900
        current_opt = current_opt->next;
11901
      }
11902

    
11903
      if (prev_opt != NULL) {
11904
        prev_opt->next = new_option;
11905
        new_option->next = current_opt;
11906
      } else {
11907
        /* insert new_option to the beginning */
11908
        new_option->next = cm->options;
11909
        cm->options = new_option;
11910
      }
11911
    }
11912
  }
11913

    
11914
  return new_option;
11915
}
11916

    
11917
/*
11918
 * Fills CoAP header in mg_coap_message.
11919
 *
11920
 * Helper function.
11921
 */
11922
static char *coap_parse_header(char *ptr, struct mbuf *io,
11923
                               struct mg_coap_message *cm) {
11924
  if (io->len < sizeof(uint32_t)) {
11925
    cm->flags |= MG_COAP_NOT_ENOUGH_DATA;
11926
    return NULL;
11927
  }
11928

    
11929
  /*
11930
   * Version (Ver):  2-bit unsigned integer.  Indicates the CoAP version
11931
   * number.  Implementations of this specification MUST set this field
11932
   * to 1 (01 binary).  Other values are reserved for future versions.
11933
   * Messages with unknown version numbers MUST be silently ignored.
11934
   */
11935
  if (((uint8_t) *ptr >> 6) != 1) {
11936
    cm->flags |= MG_COAP_IGNORE;
11937
    return NULL;
11938
  }
11939

    
11940
  /*
11941
   * Type (T):  2-bit unsigned integer.  Indicates if this message is of
11942
   * type Confirmable (0), Non-confirmable (1), Acknowledgement (2), or
11943
   * Reset (3).
11944
   */
11945
  cm->msg_type = ((uint8_t) *ptr & 0x30) >> 4;
11946
  cm->flags |= MG_COAP_MSG_TYPE_FIELD;
11947

    
11948
  /*
11949
   * Token Length (TKL):  4-bit unsigned integer.  Indicates the length of
11950
   * the variable-length Token field (0-8 bytes).  Lengths 9-15 are
11951
   * reserved, MUST NOT be sent, and MUST be processed as a message
11952
   * format error.
11953
   */
11954
  cm->token.len = *ptr & 0x0F;
11955
  if (cm->token.len > 8) {
11956
    cm->flags |= MG_COAP_FORMAT_ERROR;
11957
    return NULL;
11958
  }
11959

    
11960
  ptr++;
11961

    
11962
  /*
11963
   * Code:  8-bit unsigned integer, split into a 3-bit class (most
11964
   * significant bits) and a 5-bit detail (least significant bits)
11965
   */
11966
  cm->code_class = (uint8_t) *ptr >> 5;
11967
  cm->code_detail = *ptr & 0x1F;
11968
  cm->flags |= (MG_COAP_CODE_CLASS_FIELD | MG_COAP_CODE_DETAIL_FIELD);
11969

    
11970
  ptr++;
11971

    
11972
  /* Message ID:  16-bit unsigned integer in network byte order. */
11973
  cm->msg_id = (uint8_t) *ptr << 8 | (uint8_t) * (ptr + 1);
11974
  cm->flags |= MG_COAP_MSG_ID_FIELD;
11975

    
11976
  ptr += 2;
11977

    
11978
  return ptr;
11979
}
11980

    
11981
/*
11982
 * Fills token information in mg_coap_message.
11983
 *
11984
 * Helper function.
11985
 */
11986
static char *coap_get_token(char *ptr, struct mbuf *io,
11987
                            struct mg_coap_message *cm) {
11988
  if (cm->token.len != 0) {
11989
    if (ptr + cm->token.len > io->buf + io->len) {
11990
      cm->flags |= MG_COAP_NOT_ENOUGH_DATA;
11991
      return NULL;
11992
    } else {
11993
      cm->token.p = ptr;
11994
      ptr += cm->token.len;
11995
      cm->flags |= MG_COAP_TOKEN_FIELD;
11996
    }
11997
  }
11998

    
11999
  return ptr;
12000
}
12001

    
12002
/*
12003
 * Returns Option Delta or Length.
12004
 *
12005
 * Helper function.
12006
 */
12007
static int coap_get_ext_opt(char *ptr, struct mbuf *io, uint16_t *opt_info) {
12008
  int ret = 0;
12009

    
12010
  if (*opt_info == 13) {
12011
    /*
12012
     * 13:  An 8-bit unsigned integer follows the initial byte and
12013
     * indicates the Option Delta/Length minus 13.
12014
     */
12015
    if (ptr < io->buf + io->len) {
12016
      *opt_info = (uint8_t) *ptr + 13;
12017
      ret = sizeof(uint8_t);
12018
    } else {
12019
      ret = -1; /* LCOV_EXCL_LINE */
12020
    }
12021
  } else if (*opt_info == 14) {
12022
    /*
12023
     * 14:  A 16-bit unsigned integer in network byte order follows the
12024
     * initial byte and indicates the Option Delta/Length minus 269.
12025
     */
12026
    if (ptr + sizeof(uint8_t) < io->buf + io->len) {
12027
      *opt_info = ((uint8_t) *ptr << 8 | (uint8_t) * (ptr + 1)) + 269;
12028
      ret = sizeof(uint16_t);
12029
    } else {
12030
      ret = -1; /* LCOV_EXCL_LINE */
12031
    }
12032
  }
12033

    
12034
  return ret;
12035
}
12036

    
12037
/*
12038
 * Fills options in mg_coap_message.
12039
 *
12040
 * Helper function.
12041
 *
12042
 * General options format:
12043
 * +---------------+---------------+
12044
 * | Option Delta  | Option Length |  1 byte
12045
 * +---------------+---------------+
12046
 * \    Option Delta (extended)    \  0-2 bytes
12047
 * +-------------------------------+
12048
 * / Option Length  (extended)     \  0-2 bytes
12049
 * +-------------------------------+
12050
 * \         Option Value          \  0 or more bytes
12051
 * +-------------------------------+
12052
 */
12053
static char *coap_get_options(char *ptr, struct mbuf *io,
12054
                              struct mg_coap_message *cm) {
12055
  uint16_t prev_opt = 0;
12056

    
12057
  if (ptr == io->buf + io->len) {
12058
    /* end of packet, ok */
12059
    return NULL;
12060
  }
12061

    
12062
  /* 0xFF is payload marker */
12063
  while (ptr < io->buf + io->len && (uint8_t) *ptr != 0xFF) {
12064
    uint16_t option_delta, option_lenght;
12065
    int optinfo_len;
12066

    
12067
    /* Option Delta:  4-bit unsigned integer */
12068
    option_delta = ((uint8_t) *ptr & 0xF0) >> 4;
12069
    /* Option Length:  4-bit unsigned integer */
12070
    option_lenght = *ptr & 0x0F;
12071

    
12072
    if (option_delta == 15 || option_lenght == 15) {
12073
      /*
12074
       * 15:  Reserved for future use.  If the field is set to this value,
12075
       * it MUST be processed as a message format error
12076
       */
12077
      cm->flags |= MG_COAP_FORMAT_ERROR;
12078
      break;
12079
    }
12080

    
12081
    ptr++;
12082

    
12083
    /* check for extended option delta */
12084
    optinfo_len = coap_get_ext_opt(ptr, io, &option_delta);
12085
    if (optinfo_len == -1) {
12086
      cm->flags |= MG_COAP_NOT_ENOUGH_DATA; /* LCOV_EXCL_LINE */
12087
      break;                                /* LCOV_EXCL_LINE */
12088
    }
12089

    
12090
    ptr += optinfo_len;
12091

    
12092
    /* check or extended option lenght */
12093
    optinfo_len = coap_get_ext_opt(ptr, io, &option_lenght);
12094
    if (optinfo_len == -1) {
12095
      cm->flags |= MG_COAP_NOT_ENOUGH_DATA; /* LCOV_EXCL_LINE */
12096
      break;                                /* LCOV_EXCL_LINE */
12097
    }
12098

    
12099
    ptr += optinfo_len;
12100

    
12101
    /*
12102
     * Instead of specifying the Option Number directly, the instances MUST
12103
     * appear in order of their Option Numbers and a delta encoding is used
12104
     * between them.
12105
     */
12106
    option_delta += prev_opt;
12107

    
12108
    mg_coap_add_option(cm, option_delta, ptr, option_lenght);
12109

    
12110
    prev_opt = option_delta;
12111

    
12112
    if (ptr + option_lenght > io->buf + io->len) {
12113
      cm->flags |= MG_COAP_NOT_ENOUGH_DATA; /* LCOV_EXCL_LINE */
12114
      break;                                /* LCOV_EXCL_LINE */
12115
    }
12116

    
12117
    ptr += option_lenght;
12118
  }
12119

    
12120
  if ((cm->flags & MG_COAP_ERROR) != 0) {
12121
    mg_coap_free_options(cm);
12122
    return NULL;
12123
  }
12124

    
12125
  cm->flags |= MG_COAP_OPTIOMG_FIELD;
12126

    
12127
  if (ptr == io->buf + io->len) {
12128
    /* end of packet, ok */
12129
    return NULL;
12130
  }
12131

    
12132
  ptr++;
12133

    
12134
  return ptr;
12135
}
12136

    
12137
uint32_t mg_coap_parse(struct mbuf *io, struct mg_coap_message *cm) {
12138
  char *ptr;
12139

    
12140
  memset(cm, 0, sizeof(*cm));
12141

    
12142
  if ((ptr = coap_parse_header(io->buf, io, cm)) == NULL) {
12143
    return cm->flags;
12144
  }
12145

    
12146
  if ((ptr = coap_get_token(ptr, io, cm)) == NULL) {
12147
    return cm->flags;
12148
  }
12149

    
12150
  if ((ptr = coap_get_options(ptr, io, cm)) == NULL) {
12151
    return cm->flags;
12152
  }
12153

    
12154
  /* the rest is payload */
12155
  cm->payload.len = io->len - (ptr - io->buf);
12156
  if (cm->payload.len != 0) {
12157
    cm->payload.p = ptr;
12158
    cm->flags |= MG_COAP_PAYLOAD_FIELD;
12159
  }
12160

    
12161
  return cm->flags;
12162
}
12163

    
12164
/*
12165
 * Calculates extended size of given Opt Number/Length in coap message.
12166
 *
12167
 * Helper function.
12168
 */
12169
static size_t coap_get_ext_opt_size(uint32_t value) {
12170
  int ret = 0;
12171

    
12172
  if (value >= 13 && value <= 0xFF + 13) {
12173
    ret = sizeof(uint8_t);
12174
  } else if (value > 0xFF + 13 && value <= 0xFFFF + 269) {
12175
    ret = sizeof(uint16_t);
12176
  }
12177

    
12178
  return ret;
12179
}
12180

    
12181
/*
12182
 * Splits given Opt Number/Length into base and ext values.
12183
 *
12184
 * Helper function.
12185
 */
12186
static int coap_split_opt(uint32_t value, uint8_t *base, uint16_t *ext) {
12187
  int ret = 0;
12188

    
12189
  if (value < 13) {
12190
    *base = value;
12191
  } else if (value >= 13 && value <= 0xFF + 13) {
12192
    *base = 13;
12193
    *ext = value - 13;
12194
    ret = sizeof(uint8_t);
12195
  } else if (value > 0xFF + 13 && value <= 0xFFFF + 269) {
12196
    *base = 14;
12197
    *ext = value - 269;
12198
    ret = sizeof(uint16_t);
12199
  }
12200

    
12201
  return ret;
12202
}
12203

    
12204
/*
12205
 * Puts uint16_t (in network order) into given char stream.
12206
 *
12207
 * Helper function.
12208
 */
12209
static char *coap_add_uint16(char *ptr, uint16_t val) {
12210
  *ptr = val >> 8;
12211
  ptr++;
12212
  *ptr = val & 0x00FF;
12213
  ptr++;
12214
  return ptr;
12215
}
12216

    
12217
/*
12218
 * Puts extended value of Opt Number/Length into given char stream.
12219
 *
12220
 * Helper function.
12221
 */
12222
static char *coap_add_opt_info(char *ptr, uint16_t val, size_t len) {
12223
  if (len == sizeof(uint8_t)) {
12224
    *ptr = (char) val;
12225
    ptr++;
12226
  } else if (len == sizeof(uint16_t)) {
12227
    ptr = coap_add_uint16(ptr, val);
12228
  }
12229

    
12230
  return ptr;
12231
}
12232

    
12233
/*
12234
 * Verifies given mg_coap_message and calculates message size for it.
12235
 *
12236
 * Helper function.
12237
 */
12238
static uint32_t coap_calculate_packet_size(struct mg_coap_message *cm,
12239
                                           size_t *len) {
12240
  struct mg_coap_option *opt;
12241
  uint32_t prev_opt_number;
12242

    
12243
  *len = 4; /* header */
12244
  if (cm->msg_type > MG_COAP_MSG_MAX) {
12245
    return MG_COAP_ERROR | MG_COAP_MSG_TYPE_FIELD;
12246
  }
12247
  if (cm->token.len > 8) {
12248
    return MG_COAP_ERROR | MG_COAP_TOKEN_FIELD;
12249
  }
12250
  if (cm->code_class > 7) {
12251
    return MG_COAP_ERROR | MG_COAP_CODE_CLASS_FIELD;
12252
  }
12253
  if (cm->code_detail > 31) {
12254
    return MG_COAP_ERROR | MG_COAP_CODE_DETAIL_FIELD;
12255
  }
12256

    
12257
  *len += cm->token.len;
12258
  if (cm->payload.len != 0) {
12259
    *len += cm->payload.len + 1; /* ... + 1; add payload marker */
12260
  }
12261

    
12262
  opt = cm->options;
12263
  prev_opt_number = 0;
12264
  while (opt != NULL) {
12265
    *len += 1; /* basic delta/length */
12266
    *len += coap_get_ext_opt_size(opt->number - prev_opt_number);
12267
    *len += coap_get_ext_opt_size((uint32_t) opt->value.len);
12268
    /*
12269
     * Current implementation performs check if
12270
     * option_number > previous option_number and produces an error
12271
     * TODO(alashkin): write design doc with limitations
12272
     * May be resorting is more suitable solution.
12273
     */
12274
    if ((opt->next != NULL && opt->number > opt->next->number) ||
12275
        opt->value.len > 0xFFFF + 269 ||
12276
        opt->number - prev_opt_number > 0xFFFF + 269) {
12277
      return MG_COAP_ERROR | MG_COAP_OPTIOMG_FIELD;
12278
    }
12279
    *len += opt->value.len;
12280
    prev_opt_number = opt->number;
12281
    opt = opt->next;
12282
  }
12283

    
12284
  return 0;
12285
}
12286

    
12287
uint32_t mg_coap_compose(struct mg_coap_message *cm, struct mbuf *io) {
12288
  struct mg_coap_option *opt;
12289
  uint32_t res, prev_opt_number;
12290
  size_t prev_io_len, packet_size;
12291
  char *ptr;
12292

    
12293
  res = coap_calculate_packet_size(cm, &packet_size);
12294
  if (res != 0) {
12295
    return res;
12296
  }
12297

    
12298
  /* saving previous lenght to handle non-empty mbuf */
12299
  prev_io_len = io->len;
12300
  if (mbuf_append(io, NULL, packet_size) == 0) return MG_COAP_ERROR;
12301
  ptr = io->buf + prev_io_len;
12302

    
12303
  /*
12304
   * since cm is verified, it is possible to use bits shift operator
12305
   * without additional zeroing of unused bits
12306
   */
12307

    
12308
  /* ver: 2 bits, msg_type: 2 bits, toklen: 4 bits */
12309
  *ptr = (1 << 6) | (cm->msg_type << 4) | (uint8_t)(cm->token.len);
12310
  ptr++;
12311

    
12312
  /* code class: 3 bits, code detail: 5 bits */
12313
  *ptr = (cm->code_class << 5) | (cm->code_detail);
12314
  ptr++;
12315

    
12316
  ptr = coap_add_uint16(ptr, cm->msg_id);
12317

    
12318
  if (cm->token.len != 0) {
12319
    memcpy(ptr, cm->token.p, cm->token.len);
12320
    ptr += cm->token.len;
12321
  }
12322

    
12323
  opt = cm->options;
12324
  prev_opt_number = 0;
12325
  while (opt != NULL) {
12326
    uint8_t delta_base = 0, length_base = 0;
12327
    uint16_t delta_ext = 0, length_ext = 0;
12328

    
12329
    size_t opt_delta_len =
12330
        coap_split_opt(opt->number - prev_opt_number, &delta_base, &delta_ext);
12331
    size_t opt_lenght_len =
12332
        coap_split_opt((uint32_t) opt->value.len, &length_base, &length_ext);
12333

    
12334
    *ptr = (delta_base << 4) | length_base;
12335
    ptr++;
12336

    
12337
    ptr = coap_add_opt_info(ptr, delta_ext, opt_delta_len);
12338
    ptr = coap_add_opt_info(ptr, length_ext, opt_lenght_len);
12339

    
12340
    if (opt->value.len != 0) {
12341
      memcpy(ptr, opt->value.p, opt->value.len);
12342
      ptr += opt->value.len;
12343
    }
12344

    
12345
    prev_opt_number = opt->number;
12346
    opt = opt->next;
12347
  }
12348

    
12349
  if (cm->payload.len != 0) {
12350
    *ptr = (char) -1;
12351
    ptr++;
12352
    memcpy(ptr, cm->payload.p, cm->payload.len);
12353
  }
12354

    
12355
  return 0;
12356
}
12357

    
12358
uint32_t mg_coap_send_message(struct mg_connection *nc,
12359
                              struct mg_coap_message *cm) {
12360
  struct mbuf packet_out;
12361
  uint32_t compose_res;
12362

    
12363
  mbuf_init(&packet_out, 0);
12364
  compose_res = mg_coap_compose(cm, &packet_out);
12365
  if (compose_res != 0) {
12366
    return compose_res; /* LCOV_EXCL_LINE */
12367
  }
12368

    
12369
  mg_send(nc, packet_out.buf, (int) packet_out.len);
12370
  mbuf_free(&packet_out);
12371

    
12372
  return 0;
12373
}
12374

    
12375
uint32_t mg_coap_send_ack(struct mg_connection *nc, uint16_t msg_id) {
12376
  struct mg_coap_message cm;
12377
  memset(&cm, 0, sizeof(cm));
12378
  cm.msg_type = MG_COAP_MSG_ACK;
12379
  cm.msg_id = msg_id;
12380

    
12381
  return mg_coap_send_message(nc, &cm);
12382
}
12383

    
12384
static void coap_handler(struct mg_connection *nc, int ev,
12385
                         void *ev_data MG_UD_ARG(void *user_data)) {
12386
  struct mbuf *io = &nc->recv_mbuf;
12387
  struct mg_coap_message cm;
12388
  uint32_t parse_res;
12389

    
12390
  memset(&cm, 0, sizeof(cm));
12391

    
12392
  nc->handler(nc, ev, ev_data MG_UD_ARG(user_data));
12393

    
12394
  switch (ev) {
12395
    case MG_EV_RECV:
12396
      parse_res = mg_coap_parse(io, &cm);
12397
      if ((parse_res & MG_COAP_IGNORE) == 0) {
12398
        if ((cm.flags & MG_COAP_NOT_ENOUGH_DATA) != 0) {
12399
          /*
12400
           * Since we support UDP only
12401
           * MG_COAP_NOT_ENOUGH_DATA == MG_COAP_FORMAT_ERROR
12402
           */
12403
          cm.flags |= MG_COAP_FORMAT_ERROR; /* LCOV_EXCL_LINE */
12404
        }                                   /* LCOV_EXCL_LINE */
12405
        nc->handler(nc, MG_COAP_EVENT_BASE + cm.msg_type,
12406
                    &cm MG_UD_ARG(user_data));
12407
      }
12408

    
12409
      mg_coap_free_options(&cm);
12410
      mbuf_remove(io, io->len);
12411
      break;
12412
  }
12413
}
12414
/*
12415
 * Attach built-in CoAP event handler to the given connection.
12416
 *
12417
 * The user-defined event handler will receive following extra events:
12418
 *
12419
 * - MG_EV_COAP_CON
12420
 * - MG_EV_COAP_NOC
12421
 * - MG_EV_COAP_ACK
12422
 * - MG_EV_COAP_RST
12423
 */
12424
int mg_set_protocol_coap(struct mg_connection *nc) {
12425
  /* supports UDP only */
12426
  if ((nc->flags & MG_F_UDP) == 0) {
12427
    return -1;
12428
  }
12429

    
12430
  nc->proto_handler = coap_handler;
12431

    
12432
  return 0;
12433
}
12434

    
12435
#endif /* MG_ENABLE_COAP */
12436
#ifdef MG_MODULE_LINES
12437
#line 1 "mongoose/src/mg_sntp.c"
12438
#endif
12439
/*
12440
 * Copyright (c) 2016 Cesanta Software Limited
12441
 * All rights reserved
12442
 */
12443

    
12444
/* Amalgamated: #include "mg_internal.h" */
12445
/* Amalgamated: #include "mg_sntp.h" */
12446
/* Amalgamated: #include "mg_util.h" */
12447

    
12448
#if MG_ENABLE_SNTP
12449

    
12450
#define SNTP_TIME_OFFSET 2208988800
12451

    
12452
#ifndef SNTP_TIMEOUT
12453
#define SNTP_TIMEOUT 10
12454
#endif
12455

    
12456
#ifndef SNTP_ATTEMPTS
12457
#define SNTP_ATTEMPTS 3
12458
#endif
12459

    
12460
static uint64_t mg_get_sec(uint64_t val) {
12461
  return (val & 0xFFFFFFFF00000000) >> 32;
12462
}
12463

    
12464
static uint64_t mg_get_usec(uint64_t val) {
12465
  uint64_t tmp = (val & 0x00000000FFFFFFFF);
12466
  tmp *= 1000000;
12467
  tmp >>= 32;
12468
  return tmp;
12469
}
12470

    
12471
static void mg_ntp_to_tv(uint64_t val, struct timeval *tv) {
12472
  uint64_t tmp;
12473
  tmp = mg_get_sec(val);
12474
  tmp -= SNTP_TIME_OFFSET;
12475
  tv->tv_sec = tmp;
12476
  tv->tv_usec = mg_get_usec(val);
12477
}
12478

    
12479
static void mg_get_ntp_ts(const char *ntp, uint64_t *val) {
12480
  uint32_t tmp;
12481
  memcpy(&tmp, ntp, sizeof(tmp));
12482
  tmp = ntohl(tmp);
12483
  *val = (uint64_t) tmp << 32;
12484
  memcpy(&tmp, ntp + 4, sizeof(tmp));
12485
  tmp = ntohl(tmp);
12486
  *val |= tmp;
12487
}
12488

    
12489
void mg_sntp_send_request(struct mg_connection *c) {
12490
  uint8_t buf[48] = {0};
12491
  /*
12492
   * header - 8 bit:
12493
   * LI (2 bit) - 3 (not in sync), VN (3 bit) - 4 (version),
12494
   * mode (3 bit) - 3 (client)
12495
   */
12496
  buf[0] = (3 << 6) | (4 << 3) | 3;
12497

    
12498
/*
12499
 * Next fields should be empty in client request
12500
 * stratum, 8 bit
12501
 * poll interval, 8 bit
12502
 * rrecision, 8 bit
12503
 * root delay, 32 bit
12504
 * root dispersion, 32 bit
12505
 * ref id, 32 bit
12506
 * ref timestamp, 64 bit
12507
 * originate Timestamp, 64 bit
12508
 * receive Timestamp, 64 bit
12509
*/
12510

    
12511
/*
12512
 * convert time to sntp format (sntp starts from 00:00:00 01.01.1900)
12513
 * according to rfc868 it is 2208988800L sec
12514
 * this information is used to correct roundtrip delay
12515
 * but if local clock is absolutely broken (and doesn't work even
12516
 * as simple timer), it is better to disable it
12517
*/
12518
#ifndef MG_SNTP_NO_DELAY_CORRECTION
12519
  uint32_t sec;
12520
  sec = htonl((uint32_t)(mg_time() + SNTP_TIME_OFFSET));
12521
  memcpy(&buf[40], &sec, sizeof(sec));
12522
#endif
12523

    
12524
  mg_send(c, buf, sizeof(buf));
12525
}
12526

    
12527
#ifndef MG_SNTP_NO_DELAY_CORRECTION
12528
static uint64_t mg_calculate_delay(uint64_t t1, uint64_t t2, uint64_t t3) {
12529
  /* roundloop delay = (T4 - T1) - (T3 - T2) */
12530
  uint64_t d1 = ((mg_time() + SNTP_TIME_OFFSET) * 1000000) -
12531
                (mg_get_sec(t1) * 1000000 + mg_get_usec(t1));
12532
  uint64_t d2 = (mg_get_sec(t3) * 1000000 + mg_get_usec(t3)) -
12533
                (mg_get_sec(t2) * 1000000 + mg_get_usec(t2));
12534

    
12535
  return (d1 > d2) ? d1 - d2 : 0;
12536
}
12537
#endif
12538

    
12539
MG_INTERNAL int mg_sntp_parse_reply(const char *buf, int len,
12540
                                    struct mg_sntp_message *msg) {
12541
  uint8_t hdr;
12542
  uint64_t trsm_ts_T3, delay = 0;
12543
  int mode;
12544
  struct timeval tv;
12545

    
12546
  if (len < 48) {
12547
    return -1;
12548
  }
12549

    
12550
  hdr = buf[0];
12551

    
12552
  if ((hdr & 0x38) >> 3 != 4) {
12553
    /* Wrong version */
12554
    return -1;
12555
  }
12556

    
12557
  mode = hdr & 0x7;
12558
  if (mode != 4 && mode != 5) {
12559
    /* Not a server reply */
12560
    return -1;
12561
  }
12562

    
12563
  memset(msg, 0, sizeof(*msg));
12564

    
12565
  msg->kiss_of_death = (buf[1] == 0); /* Server asks to not send requests */
12566

    
12567
  mg_get_ntp_ts(&buf[40], &trsm_ts_T3);
12568

    
12569
#ifndef MG_SNTP_NO_DELAY_CORRECTION
12570
  {
12571
    uint64_t orig_ts_T1, recv_ts_T2;
12572
    mg_get_ntp_ts(&buf[24], &orig_ts_T1);
12573
    mg_get_ntp_ts(&buf[32], &recv_ts_T2);
12574
    delay = mg_calculate_delay(orig_ts_T1, recv_ts_T2, trsm_ts_T3);
12575
  }
12576
#endif
12577

    
12578
  mg_ntp_to_tv(trsm_ts_T3, &tv);
12579

    
12580
  msg->time = (double) tv.tv_sec + (((double) tv.tv_usec + delay) / 1000000.0);
12581

    
12582
  return 0;
12583
}
12584

    
12585
static void mg_sntp_handler(struct mg_connection *c, int ev,
12586
                            void *ev_data MG_UD_ARG(void *user_data)) {
12587
  struct mbuf *io = &c->recv_mbuf;
12588
  struct mg_sntp_message msg;
12589

    
12590
  c->handler(c, ev, ev_data MG_UD_ARG(user_data));
12591

    
12592
  switch (ev) {
12593
    case MG_EV_RECV: {
12594
      if (mg_sntp_parse_reply(io->buf, io->len, &msg) < 0) {
12595
        DBG(("Invalid SNTP packet received (%d)", (int) io->len));
12596
        c->handler(c, MG_SNTP_MALFORMED_REPLY, NULL MG_UD_ARG(user_data));
12597
      } else {
12598
        c->handler(c, MG_SNTP_REPLY, (void *) &msg MG_UD_ARG(user_data));
12599
      }
12600

    
12601
      mbuf_remove(io, io->len);
12602
      break;
12603
    }
12604
  }
12605
}
12606

    
12607
int mg_set_protocol_sntp(struct mg_connection *c) {
12608
  if ((c->flags & MG_F_UDP) == 0) {
12609
    return -1;
12610
  }
12611

    
12612
  c->proto_handler = mg_sntp_handler;
12613

    
12614
  return 0;
12615
}
12616

    
12617
struct mg_connection *mg_sntp_connect(struct mg_mgr *mgr,
12618
                                      MG_CB(mg_event_handler_t event_handler,
12619
                                            void *user_data),
12620
                                      const char *sntp_server_name) {
12621
  struct mg_connection *c = NULL;
12622
  char url[100], *p_url = url;
12623
  const char *proto = "", *port = "", *tmp;
12624

    
12625
  /* If port is not specified, use default (123) */
12626
  tmp = strchr(sntp_server_name, ':');
12627
  if (tmp != NULL && *(tmp + 1) == '/') {
12628
    tmp = strchr(tmp + 1, ':');
12629
  }
12630

    
12631
  if (tmp == NULL) {
12632
    port = ":123";
12633
  }
12634

    
12635
  /* Add udp:// if needed */
12636
  if (strncmp(sntp_server_name, "udp://", 6) != 0) {
12637
    proto = "udp://";
12638
  }
12639

    
12640
  mg_asprintf(&p_url, sizeof(url), "%s%s%s", proto, sntp_server_name, port);
12641

    
12642
  c = mg_connect(mgr, p_url, event_handler MG_UD_ARG(user_data));
12643

    
12644
  if (c == NULL) {
12645
    goto cleanup;
12646
  }
12647

    
12648
  mg_set_protocol_sntp(c);
12649

    
12650
cleanup:
12651
  if (p_url != url) {
12652
    MG_FREE(p_url);
12653
  }
12654

    
12655
  return c;
12656
}
12657

    
12658
struct sntp_data {
12659
  mg_event_handler_t hander;
12660
  int count;
12661
};
12662

    
12663
static void mg_sntp_util_ev_handler(struct mg_connection *c, int ev,
12664
                                    void *ev_data MG_UD_ARG(void *user_data)) {
12665
#if !MG_ENABLE_CALLBACK_USERDATA
12666
  void *user_data = c->user_data;
12667
#endif
12668
  struct sntp_data *sd = (struct sntp_data *) user_data;
12669

    
12670
  switch (ev) {
12671
    case MG_EV_CONNECT:
12672
      if (*(int *) ev_data != 0) {
12673
        mg_call(c, sd->hander, c->user_data, MG_SNTP_FAILED, NULL);
12674
        break;
12675
      }
12676
    /* fallthrough */
12677
    case MG_EV_TIMER:
12678
      if (sd->count <= SNTP_ATTEMPTS) {
12679
        mg_sntp_send_request(c);
12680
        mg_set_timer(c, mg_time() + 10);
12681
        sd->count++;
12682
      } else {
12683
        mg_call(c, sd->hander, c->user_data, MG_SNTP_FAILED, NULL);
12684
        c->flags |= MG_F_CLOSE_IMMEDIATELY;
12685
      }
12686
      break;
12687
    case MG_SNTP_MALFORMED_REPLY:
12688
      mg_call(c, sd->hander, c->user_data, MG_SNTP_FAILED, NULL);
12689
      c->flags |= MG_F_CLOSE_IMMEDIATELY;
12690
      break;
12691
    case MG_SNTP_REPLY:
12692
      mg_call(c, sd->hander, c->user_data, MG_SNTP_REPLY, ev_data);
12693
      c->flags |= MG_F_CLOSE_IMMEDIATELY;
12694
      break;
12695
    case MG_EV_CLOSE:
12696
      MG_FREE(user_data);
12697
      c->user_data = NULL;
12698
      break;
12699
  }
12700
}
12701

    
12702
struct mg_connection *mg_sntp_get_time(struct mg_mgr *mgr,
12703
                                       mg_event_handler_t event_handler,
12704
                                       const char *sntp_server_name) {
12705
  struct mg_connection *c;
12706
  struct sntp_data *sd = (struct sntp_data *) MG_CALLOC(1, sizeof(*sd));
12707
  if (sd == NULL) {
12708
    return NULL;
12709
  }
12710

    
12711
  c = mg_sntp_connect(mgr, MG_CB(mg_sntp_util_ev_handler, sd),
12712
                      sntp_server_name);
12713
  if (c == NULL) {
12714
    MG_FREE(sd);
12715
    return NULL;
12716
  }
12717

    
12718
  sd->hander = event_handler;
12719
#if !MG_ENABLE_CALLBACK_USERDATA
12720
  c->user_data = sd;
12721
#endif
12722

    
12723
  return c;
12724
}
12725

    
12726
#endif /* MG_ENABLE_SNTP */
12727
#ifdef MG_MODULE_LINES
12728
#line 1 "mongoose/src/mg_socks.c"
12729
#endif
12730
/*
12731
 * Copyright (c) 2017 Cesanta Software Limited
12732
 * All rights reserved
12733
 */
12734

    
12735
#if MG_ENABLE_SOCKS
12736

    
12737
/* Amalgamated: #include "mg_socks.h" */
12738
/* Amalgamated: #include "mg_internal.h" */
12739

    
12740
/*
12741
 *  https://www.ietf.org/rfc/rfc1928.txt paragraph 3, handle client handshake
12742
 *
12743
 *  +----+----------+----------+
12744
 *  |VER | NMETHODS | METHODS  |
12745
 *  +----+----------+----------+
12746
 *  | 1  |    1     | 1 to 255 |
12747
 *  +----+----------+----------+
12748
 */
12749
static void mg_socks5_handshake(struct mg_connection *c) {
12750
  struct mbuf *r = &c->recv_mbuf;
12751
  if (r->buf[0] != MG_SOCKS_VERSION) {
12752
    c->flags |= MG_F_CLOSE_IMMEDIATELY;
12753
  } else if (r->len > 2 && (size_t) r->buf[1] + 2 <= r->len) {
12754
    /* https://www.ietf.org/rfc/rfc1928.txt paragraph 3 */
12755
    unsigned char reply[2] = {MG_SOCKS_VERSION, MG_SOCKS_HANDSHAKE_FAILURE};
12756
    int i;
12757
    for (i = 2; i < r->buf[1] + 2; i++) {
12758
      /* TODO(lsm): support other auth methods */
12759
      if (r->buf[i] == MG_SOCKS_HANDSHAKE_NOAUTH) reply[1] = r->buf[i];
12760
    }
12761
    mbuf_remove(r, 2 + r->buf[1]);
12762
    mg_send(c, reply, sizeof(reply));
12763
    c->flags |= MG_SOCKS_HANDSHAKE_DONE; /* Mark handshake done */
12764
  }
12765
}
12766

    
12767
static void disband(struct mg_connection *c) {
12768
  struct mg_connection *c2 = (struct mg_connection *) c->user_data;
12769
  if (c2 != NULL) {
12770
    c2->flags |= MG_F_SEND_AND_CLOSE;
12771
    c2->user_data = NULL;
12772
  }
12773
  c->flags |= MG_F_SEND_AND_CLOSE;
12774
  c->user_data = NULL;
12775
}
12776

    
12777
static void relay_data(struct mg_connection *c) {
12778
  struct mg_connection *c2 = (struct mg_connection *) c->user_data;
12779
  if (c2 != NULL) {
12780
    mg_send(c2, c->recv_mbuf.buf, c->recv_mbuf.len);
12781
    mbuf_remove(&c->recv_mbuf, c->recv_mbuf.len);
12782
  } else {
12783
    c->flags |= MG_F_SEND_AND_CLOSE;
12784
  }
12785
}
12786

    
12787
static void serv_ev_handler(struct mg_connection *c, int ev, void *ev_data) {
12788
  if (ev == MG_EV_CLOSE) {
12789
    disband(c);
12790
  } else if (ev == MG_EV_RECV) {
12791
    relay_data(c);
12792
  } else if (ev == MG_EV_CONNECT) {
12793
    int res = *(int *) ev_data;
12794
    if (res != 0) LOG(LL_ERROR, ("connect error: %d", res));
12795
  }
12796
}
12797

    
12798
static void mg_socks5_connect(struct mg_connection *c, const char *addr) {
12799
  struct mg_connection *serv = mg_connect(c->mgr, addr, serv_ev_handler);
12800
  serv->user_data = c;
12801
  c->user_data = serv;
12802
}
12803

    
12804
/*
12805
 *  Request, https://www.ietf.org/rfc/rfc1928.txt paragraph 4
12806
 *
12807
 *  +----+-----+-------+------+----------+----------+
12808
 *  |VER | CMD |  RSV  | ATYP | DST.ADDR | DST.PORT |
12809
 *  +----+-----+-------+------+----------+----------+
12810
 *  | 1  |  1  | X'00' |  1   | Variable |    2     |
12811
 *  +----+-----+-------+------+----------+----------+
12812
 */
12813
static void mg_socks5_handle_request(struct mg_connection *c) {
12814
  struct mbuf *r = &c->recv_mbuf;
12815
  unsigned char *p = (unsigned char *) r->buf;
12816
  unsigned char addr_len = 4, reply = MG_SOCKS_SUCCESS;
12817
  int ver, cmd, atyp;
12818
  char addr[300];
12819

    
12820
  if (r->len < 8) return; /* return if not fully buffered. min DST.ADDR is 2 */
12821
  ver = p[0];
12822
  cmd = p[1];
12823
  atyp = p[3];
12824

    
12825
  /* TODO(lsm): support other commands */
12826
  if (ver != MG_SOCKS_VERSION || cmd != MG_SOCKS_CMD_CONNECT) {
12827
    reply = MG_SOCKS_CMD_NOT_SUPPORTED;
12828
  } else if (atyp == MG_SOCKS_ADDR_IPV4) {
12829
    addr_len = 4;
12830
    if (r->len < (size_t) addr_len + 6) return; /* return if not buffered */
12831
    snprintf(addr, sizeof(addr), "%d.%d.%d.%d:%d", p[4], p[5], p[6], p[7],
12832
             p[8] << 8 | p[9]);
12833
    mg_socks5_connect(c, addr);
12834
  } else if (atyp == MG_SOCKS_ADDR_IPV6) {
12835
    addr_len = 16;
12836
    if (r->len < (size_t) addr_len + 6) return; /* return if not buffered */
12837
    snprintf(addr, sizeof(addr), "[%x:%x:%x:%x:%x:%x:%x:%x]:%d",
12838
             p[4] << 8 | p[5], p[6] << 8 | p[7], p[8] << 8 | p[9],
12839
             p[10] << 8 | p[11], p[12] << 8 | p[13], p[14] << 8 | p[15],
12840
             p[16] << 8 | p[17], p[18] << 8 | p[19], p[20] << 8 | p[21]);
12841
    mg_socks5_connect(c, addr);
12842
  } else if (atyp == MG_SOCKS_ADDR_DOMAIN) {
12843
    addr_len = p[4] + 1;
12844
    if (r->len < (size_t) addr_len + 6) return; /* return if not buffered */
12845
    snprintf(addr, sizeof(addr), "%.*s:%d", p[4], p + 5,
12846
             p[4 + addr_len] << 8 | p[4 + addr_len + 1]);
12847
    mg_socks5_connect(c, addr);
12848
  } else {
12849
    reply = MG_SOCKS_ADDR_NOT_SUPPORTED;
12850
  }
12851

    
12852
  /*
12853
   *  Reply, https://www.ietf.org/rfc/rfc1928.txt paragraph 5
12854
   *
12855
   *  +----+-----+-------+------+----------+----------+
12856
   *  |VER | REP |  RSV  | ATYP | BND.ADDR | BND.PORT |
12857
   *  +----+-----+-------+------+----------+----------+
12858
   *  | 1  |  1  | X'00' |  1   | Variable |    2     |
12859
   *  +----+-----+-------+------+----------+----------+
12860
   */
12861
  {
12862
    unsigned char buf[] = {MG_SOCKS_VERSION, reply, 0};
12863
    mg_send(c, buf, sizeof(buf));
12864
  }
12865
  mg_send(c, r->buf + 3, addr_len + 1 + 2);
12866

    
12867
  mbuf_remove(r, 6 + addr_len);      /* Remove request from the input stream */
12868
  c->flags |= MG_SOCKS_CONNECT_DONE; /* Mark ourselves as connected */
12869
}
12870

    
12871
static void socks_handler(struct mg_connection *c, int ev, void *ev_data) {
12872
  if (ev == MG_EV_RECV) {
12873
    if (!(c->flags & MG_SOCKS_HANDSHAKE_DONE)) mg_socks5_handshake(c);
12874
    if (c->flags & MG_SOCKS_HANDSHAKE_DONE &&
12875
        !(c->flags & MG_SOCKS_CONNECT_DONE)) {
12876
      mg_socks5_handle_request(c);
12877
    }
12878
    if (c->flags & MG_SOCKS_CONNECT_DONE) relay_data(c);
12879
  } else if (ev == MG_EV_CLOSE) {
12880
    disband(c);
12881
  }
12882
  (void) ev_data;
12883
}
12884

    
12885
void mg_set_protocol_socks(struct mg_connection *c) {
12886
  c->proto_handler = socks_handler;
12887
}
12888
#endif
12889
#ifdef MG_MODULE_LINES
12890
#line 1 "common/platforms/cc3200/cc3200_libc.c"
12891
#endif
12892
/*
12893
 * Copyright (c) 2014-2016 Cesanta Software Limited
12894
 * All rights reserved
12895
 */
12896

    
12897
#if CS_PLATFORM == CS_P_CC3200
12898

    
12899
/* Amalgamated: #include "common/mg_mem.h" */
12900
#include <stdio.h>
12901
#include <string.h>
12902

    
12903
#ifndef __TI_COMPILER_VERSION__
12904
#include <reent.h>
12905
#include <sys/stat.h>
12906
#include <sys/time.h>
12907
#include <unistd.h>
12908
#endif
12909

    
12910
#include <inc/hw_types.h>
12911
#include <inc/hw_memmap.h>
12912
#include <driverlib/prcm.h>
12913
#include <driverlib/rom.h>
12914
#include <driverlib/rom_map.h>
12915
#include <driverlib/uart.h>
12916
#include <driverlib/utils.h>
12917

    
12918
#define CONSOLE_UART UARTA0_BASE
12919

    
12920
#ifdef __TI_COMPILER_VERSION__
12921
int asprintf(char **strp, const char *fmt, ...) {
12922
  va_list ap;
12923
  int len;
12924

    
12925
  *strp = MG_MALLOC(BUFSIZ);
12926
  if (*strp == NULL) return -1;
12927

    
12928
  va_start(ap, fmt);
12929
  len = vsnprintf(*strp, BUFSIZ, fmt, ap);
12930
  va_end(ap);
12931

    
12932
  if (len > 0) {
12933
    *strp = MG_REALLOC(*strp, len + 1);
12934
    if (*strp == NULL) return -1;
12935
  }
12936

    
12937
  if (len >= BUFSIZ) {
12938
    va_start(ap, fmt);
12939
    len = vsnprintf(*strp, len + 1, fmt, ap);
12940
    va_end(ap);
12941
  }
12942

    
12943
  return len;
12944
}
12945

    
12946
#if MG_TI_NO_HOST_INTERFACE
12947
time_t HOSTtime() {
12948
  struct timeval tp;
12949
  gettimeofday(&tp, NULL);
12950
  return tp.tv_sec;
12951
}
12952
#endif
12953

    
12954
#endif /* __TI_COMPILER_VERSION__ */
12955

    
12956
void fprint_str(FILE *fp, const char *str) {
12957
  while (*str != '\0') {
12958
    if (*str == '\n') MAP_UARTCharPut(CONSOLE_UART, '\r');
12959
    MAP_UARTCharPut(CONSOLE_UART, *str++);
12960
  }
12961
}
12962

    
12963
void _exit(int status) {
12964
  fprint_str(stderr, "_exit\n");
12965
  /* cause an unaligned access exception, that will drop you into gdb */
12966
  *(int *) 1 = status;
12967
  while (1)
12968
    ; /* avoid gcc warning because stdlib abort() has noreturn attribute */
12969
}
12970

    
12971
void _not_implemented(const char *what) {
12972
  fprint_str(stderr, what);
12973
  fprint_str(stderr, " is not implemented\n");
12974
  _exit(42);
12975
}
12976

    
12977
int _kill(int pid, int sig) {
12978
  (void) pid;
12979
  (void) sig;
12980
  _not_implemented("_kill");
12981
  return -1;
12982
}
12983

    
12984
int _getpid() {
12985
  fprint_str(stderr, "_getpid is not implemented\n");
12986
  return 42;
12987
}
12988

    
12989
int _isatty(int fd) {
12990
  /* 0, 1 and 2 are TTYs. */
12991
  return fd < 2;
12992
}
12993

    
12994
#endif /* CS_PLATFORM == CS_P_CC3200 */
12995
#ifdef MG_MODULE_LINES
12996
#line 1 "common/platforms/msp432/msp432_libc.c"
12997
#endif
12998
/*
12999
 * Copyright (c) 2014-2016 Cesanta Software Limited
13000
 * All rights reserved
13001
 */
13002

    
13003
#if CS_PLATFORM == CS_P_MSP432
13004

    
13005
#include <ti/sysbios/BIOS.h>
13006
#include <ti/sysbios/knl/Clock.h>
13007

    
13008
int gettimeofday(struct timeval *tp, void *tzp) {
13009
  uint32_t ticks = Clock_getTicks();
13010
  tp->tv_sec = ticks / 1000;
13011
  tp->tv_usec = (ticks % 1000) * 1000;
13012
  return 0;
13013
}
13014

    
13015
#endif /* CS_PLATFORM == CS_P_MSP432 */
13016
#ifdef MG_MODULE_LINES
13017
#line 1 "common/platforms/nrf5/nrf5_libc.c"
13018
#endif
13019
/*
13020
 * Copyright (c) 2014-2016 Cesanta Software Limited
13021
 * All rights reserved
13022
 */
13023

    
13024
#if (CS_PLATFORM == CS_P_NRF51 || CS_PLATFORM == CS_P_NRF52) && \
13025
    defined(__ARMCC_VERSION)
13026
int gettimeofday(struct timeval *tp, void *tzp) {
13027
  /* TODO */
13028
  tp->tv_sec = 0;
13029
  tp->tv_usec = 0;
13030
  return 0;
13031
}
13032
#endif
13033
#ifdef MG_MODULE_LINES
13034
#line 1 "common/platforms/simplelink/sl_fs_slfs.h"
13035
#endif
13036
/*
13037
 * Copyright (c) 2014-2016 Cesanta Software Limited
13038
 * All rights reserved
13039
 */
13040

    
13041
#ifndef CS_COMMON_PLATFORMS_SIMPLELINK_SL_FS_SLFS_H_
13042
#define CS_COMMON_PLATFORMS_SIMPLELINK_SL_FS_SLFS_H_
13043

    
13044
#if defined(MG_FS_SLFS)
13045

    
13046
#include <stdio.h>
13047
#ifndef __TI_COMPILER_VERSION__
13048
#include <unistd.h>
13049
#include <sys/stat.h>
13050
#endif
13051

    
13052
#define MAX_OPEN_SLFS_FILES 8
13053

    
13054
/* Indirect libc interface - same functions, different names. */
13055
int fs_slfs_open(const char *pathname, int flags, mode_t mode);
13056
int fs_slfs_close(int fd);
13057
ssize_t fs_slfs_read(int fd, void *buf, size_t count);
13058
ssize_t fs_slfs_write(int fd, const void *buf, size_t count);
13059
int fs_slfs_stat(const char *pathname, struct stat *s);
13060
int fs_slfs_fstat(int fd, struct stat *s);
13061
off_t fs_slfs_lseek(int fd, off_t offset, int whence);
13062
int fs_slfs_unlink(const char *filename);
13063
int fs_slfs_rename(const char *from, const char *to);
13064

    
13065
void fs_slfs_set_new_file_size(const char *name, size_t size);
13066

    
13067
#endif /* defined(MG_FS_SLFS) */
13068

    
13069
#endif /* CS_COMMON_PLATFORMS_SIMPLELINK_SL_FS_SLFS_H_ */
13070
#ifdef MG_MODULE_LINES
13071
#line 1 "common/platforms/simplelink/sl_fs_slfs.c"
13072
#endif
13073
/*
13074
 * Copyright (c) 2014-2016 Cesanta Software Limited
13075
 * All rights reserved
13076
 */
13077

    
13078
/* Standard libc interface to TI SimpleLink FS. */
13079

    
13080
#if defined(MG_FS_SLFS) || defined(CC3200_FS_SLFS)
13081

    
13082
/* Amalgamated: #include "common/platforms/simplelink/sl_fs_slfs.h" */
13083

    
13084
#include <errno.h>
13085

    
13086
#if CS_PLATFORM == CS_P_CC3200
13087
#include <inc/hw_types.h>
13088
#endif
13089

    
13090
/* Amalgamated: #include "common/cs_dbg.h" */
13091
/* Amalgamated: #include "common/mg_mem.h" */
13092

    
13093
#if SL_MAJOR_VERSION_NUM < 2
13094
int slfs_open(const unsigned char *fname, uint32_t flags) {
13095
  _i32 fh;
13096
  _i32 r = sl_FsOpen(fname, flags, NULL /* token */, &fh);
13097
  return (r < 0 ? r : fh);
13098
}
13099
#else /* SL_MAJOR_VERSION_NUM >= 2 */
13100
int slfs_open(const unsigned char *fname, uint32_t flags) {
13101
  return sl_FsOpen(fname, flags, NULL /* token */);
13102
}
13103
#endif
13104

    
13105
/* From sl_fs.c */
13106
int set_errno(int e);
13107
const char *drop_dir(const char *fname, bool *is_slfs);
13108

    
13109
/*
13110
 * With SLFS, you have to pre-declare max file size. Yes. Really.
13111
 * 64K should be enough for everyone. Right?
13112
 */
13113
#ifndef FS_SLFS_MAX_FILE_SIZE
13114
#define FS_SLFS_MAX_FILE_SIZE (64 * 1024)
13115
#endif
13116

    
13117
struct sl_file_size_hint {
13118
  char *name;
13119
  size_t size;
13120
};
13121

    
13122
struct sl_fd_info {
13123
  _i32 fh;
13124
  _off_t pos;
13125
  size_t size;
13126
};
13127

    
13128
static struct sl_fd_info s_sl_fds[MAX_OPEN_SLFS_FILES];
13129
static struct sl_file_size_hint s_sl_file_size_hints[MAX_OPEN_SLFS_FILES];
13130

    
13131
static int sl_fs_to_errno(_i32 r) {
13132
  DBG(("SL error: %d", (int) r));
13133
  switch (r) {
13134
    case SL_FS_OK:
13135
      return 0;
13136
    case SL_ERROR_FS_FILE_NAME_EXIST:
13137
      return EEXIST;
13138
    case SL_ERROR_FS_WRONG_FILE_NAME:
13139
      return EINVAL;
13140
    case SL_ERROR_FS_NO_AVAILABLE_NV_INDEX:
13141
    case SL_ERROR_FS_NOT_ENOUGH_STORAGE_SPACE:
13142
      return ENOSPC;
13143
    case SL_ERROR_FS_FAILED_TO_ALLOCATE_MEM:
13144
      return ENOMEM;
13145
    case SL_ERROR_FS_FILE_NOT_EXISTS:
13146
      return ENOENT;
13147
    case SL_ERROR_FS_NOT_SUPPORTED:
13148
      return ENOTSUP;
13149
  }
13150
  return ENXIO;
13151
}
13152

    
13153
int fs_slfs_open(const char *pathname, int flags, mode_t mode) {
13154
  int fd;
13155
  for (fd = 0; fd < MAX_OPEN_SLFS_FILES; fd++) {
13156
    if (s_sl_fds[fd].fh <= 0) break;
13157
  }
13158
  if (fd >= MAX_OPEN_SLFS_FILES) return set_errno(ENOMEM);
13159
  struct sl_fd_info *fi = &s_sl_fds[fd];
13160

    
13161
  /*
13162
   * Apply path manipulations again, in case we got here directly
13163
   * (via TI libc's "add_device").
13164
   */
13165
  pathname = drop_dir(pathname, NULL);
13166

    
13167
  _u32 am = 0;
13168
  fi->size = (size_t) -1;
13169
  int rw = (flags & 3);
13170
  size_t new_size = FS_SLFS_MAX_FILE_SIZE;
13171
  if (rw == O_RDONLY) {
13172
    SlFsFileInfo_t sl_fi;
13173
    _i32 r = sl_FsGetInfo((const _u8 *) pathname, 0, &sl_fi);
13174
    if (r == SL_FS_OK) {
13175
      fi->size = SL_FI_FILE_SIZE(sl_fi);
13176
    }
13177
    am = SL_FS_READ;
13178
  } else {
13179
    if (!(flags & O_TRUNC) || (flags & O_APPEND)) {
13180
      // FailFS files cannot be opened for append and will be truncated
13181
      // when opened for write.
13182
      return set_errno(ENOTSUP);
13183
    }
13184
    if (flags & O_CREAT) {
13185
      size_t i;
13186
      for (i = 0; i < MAX_OPEN_SLFS_FILES; i++) {
13187
        if (s_sl_file_size_hints[i].name != NULL &&
13188
            strcmp(s_sl_file_size_hints[i].name, pathname) == 0) {
13189
          new_size = s_sl_file_size_hints[i].size;
13190
          MG_FREE(s_sl_file_size_hints[i].name);
13191
          s_sl_file_size_hints[i].name = NULL;
13192
          break;
13193
        }
13194
      }
13195
      am = FS_MODE_OPEN_CREATE(new_size, 0);
13196
    } else {
13197
      am = SL_FS_WRITE;
13198
    }
13199
  }
13200
  fi->fh = slfs_open((_u8 *) pathname, am);
13201
  LOG(LL_DEBUG, ("sl_FsOpen(%s, 0x%x) sz %u = %d", pathname, (int) am,
13202
                 (unsigned int) new_size, (int) fi->fh));
13203
  int r;
13204
  if (fi->fh >= 0) {
13205
    fi->pos = 0;
13206
    r = fd;
13207
  } else {
13208
    r = set_errno(sl_fs_to_errno(fi->fh));
13209
  }
13210
  return r;
13211
}
13212

    
13213
int fs_slfs_close(int fd) {
13214
  struct sl_fd_info *fi = &s_sl_fds[fd];
13215
  if (fi->fh <= 0) return set_errno(EBADF);
13216
  _i32 r = sl_FsClose(fi->fh, NULL, NULL, 0);
13217
  LOG(LL_DEBUG, ("sl_FsClose(%d) = %d", (int) fi->fh, (int) r));
13218
  s_sl_fds[fd].fh = -1;
13219
  return set_errno(sl_fs_to_errno(r));
13220
}
13221

    
13222
ssize_t fs_slfs_read(int fd, void *buf, size_t count) {
13223
  struct sl_fd_info *fi = &s_sl_fds[fd];
13224
  if (fi->fh <= 0) return set_errno(EBADF);
13225
  /* Simulate EOF. sl_FsRead @ file_size return SL_FS_ERR_OFFSET_OUT_OF_RANGE.
13226
   */
13227
  if (fi->pos == fi->size) return 0;
13228
  _i32 r = sl_FsRead(fi->fh, fi->pos, buf, count);
13229
  DBG(("sl_FsRead(%d, %d, %d) = %d", (int) fi->fh, (int) fi->pos, (int) count,
13230
       (int) r));
13231
  if (r >= 0) {
13232
    fi->pos += r;
13233
    return r;
13234
  }
13235
  return set_errno(sl_fs_to_errno(r));
13236
}
13237

    
13238
ssize_t fs_slfs_write(int fd, const void *buf, size_t count) {
13239
  struct sl_fd_info *fi = &s_sl_fds[fd];
13240
  if (fi->fh <= 0) return set_errno(EBADF);
13241
  _i32 r = sl_FsWrite(fi->fh, fi->pos, (_u8 *) buf, count);
13242
  DBG(("sl_FsWrite(%d, %d, %d) = %d", (int) fi->fh, (int) fi->pos, (int) count,
13243
       (int) r));
13244
  if (r >= 0) {
13245
    fi->pos += r;
13246
    return r;
13247
  }
13248
  return set_errno(sl_fs_to_errno(r));
13249
}
13250

    
13251
int fs_slfs_stat(const char *pathname, struct stat *s) {
13252
  SlFsFileInfo_t sl_fi;
13253
  /*
13254
   * Apply path manipulations again, in case we got here directly
13255
   * (via TI libc's "add_device").
13256
   */
13257
  pathname = drop_dir(pathname, NULL);
13258
  _i32 r = sl_FsGetInfo((const _u8 *) pathname, 0, &sl_fi);
13259
  if (r == SL_FS_OK) {
13260
    s->st_mode = S_IFREG | 0666;
13261
    s->st_nlink = 1;
13262
    s->st_size = SL_FI_FILE_SIZE(sl_fi);
13263
    return 0;
13264
  }
13265
  return set_errno(sl_fs_to_errno(r));
13266
}
13267

    
13268
int fs_slfs_fstat(int fd, struct stat *s) {
13269
  struct sl_fd_info *fi = &s_sl_fds[fd];
13270
  if (fi->fh <= 0) return set_errno(EBADF);
13271
  s->st_mode = 0666;
13272
  s->st_mode = S_IFREG | 0666;
13273
  s->st_nlink = 1;
13274
  s->st_size = fi->size;
13275
  return 0;
13276
}
13277

    
13278
off_t fs_slfs_lseek(int fd, off_t offset, int whence) {
13279
  if (s_sl_fds[fd].fh <= 0) return set_errno(EBADF);
13280
  switch (whence) {
13281
    case SEEK_SET:
13282
      s_sl_fds[fd].pos = offset;
13283
      break;
13284
    case SEEK_CUR:
13285
      s_sl_fds[fd].pos += offset;
13286
      break;
13287
    case SEEK_END:
13288
      return set_errno(ENOTSUP);
13289
  }
13290
  return 0;
13291
}
13292

    
13293
int fs_slfs_unlink(const char *pathname) {
13294
  /*
13295
   * Apply path manipulations again, in case we got here directly
13296
   * (via TI libc's "add_device").
13297
   */
13298
  pathname = drop_dir(pathname, NULL);
13299
  return set_errno(sl_fs_to_errno(sl_FsDel((const _u8 *) pathname, 0)));
13300
}
13301

    
13302
int fs_slfs_rename(const char *from, const char *to) {
13303
  return set_errno(ENOTSUP);
13304
}
13305

    
13306
void fs_slfs_set_new_file_size(const char *name, size_t size) {
13307
  int i;
13308
  for (i = 0; i < MAX_OPEN_SLFS_FILES; i++) {
13309
    if (s_sl_file_size_hints[i].name == NULL) {
13310
      DBG(("File size hint: %s %d", name, (int) size));
13311
      s_sl_file_size_hints[i].name = strdup(name);
13312
      s_sl_file_size_hints[i].size = size;
13313
      break;
13314
    }
13315
  }
13316
}
13317

    
13318
#endif /* defined(MG_FS_SLFS) || defined(CC3200_FS_SLFS) */
13319
#ifdef MG_MODULE_LINES
13320
#line 1 "common/platforms/simplelink/sl_fs.c"
13321
#endif
13322
/*
13323
 * Copyright (c) 2014-2016 Cesanta Software Limited
13324
 * All rights reserved
13325
 */
13326

    
13327
#if MG_NET_IF == MG_NET_IF_SIMPLELINK && \
13328
    (defined(MG_FS_SLFS) || defined(MG_FS_SPIFFS))
13329

    
13330
int set_errno(int e) {
13331
  errno = e;
13332
  return (e == 0 ? 0 : -1);
13333
}
13334

    
13335
const char *drop_dir(const char *fname, bool *is_slfs) {
13336
  if (is_slfs != NULL) {
13337
    *is_slfs = (strncmp(fname, "SL:", 3) == 0);
13338
    if (*is_slfs) fname += 3;
13339
  }
13340
  /* Drop "./", if any */
13341
  if (fname[0] == '.' && fname[1] == '/') {
13342
    fname += 2;
13343
  }
13344
  /*
13345
   * Drop / if it is the only one in the path.
13346
   * This allows use of /pretend/directories but serves /file.txt as normal.
13347
   */
13348
  if (fname[0] == '/' && strchr(fname + 1, '/') == NULL) {
13349
    fname++;
13350
  }
13351
  return fname;
13352
}
13353

    
13354
#if !defined(MG_FS_NO_VFS)
13355

    
13356
#include <errno.h>
13357
#include <stdbool.h>
13358
#include <stdio.h>
13359
#include <stdlib.h>
13360
#include <string.h>
13361
#ifdef __TI_COMPILER_VERSION__
13362
#include <file.h>
13363
#endif
13364

    
13365
/* Amalgamated: #include "common/cs_dbg.h" */
13366
/* Amalgamated: #include "common/platform.h" */
13367

    
13368
#ifdef CC3200_FS_SPIFFS
13369
/* Amalgamated: #include "cc3200_fs_spiffs.h" */
13370
#endif
13371

    
13372
#ifdef MG_FS_SLFS
13373
/* Amalgamated: #include "sl_fs_slfs.h" */
13374
#endif
13375

    
13376
#define NUM_SYS_FDS 3
13377
#define SPIFFS_FD_BASE 10
13378
#define SLFS_FD_BASE 100
13379

    
13380
#if !defined(MG_UART_CHAR_PUT) && !defined(MG_UART_WRITE)
13381
#if CS_PLATFORM == CS_P_CC3200
13382
#include <inc/hw_types.h>
13383
#include <inc/hw_memmap.h>
13384
#include <driverlib/rom.h>
13385
#include <driverlib/rom_map.h>
13386
#include <driverlib/uart.h>
13387
#define MG_UART_CHAR_PUT(fd, c) MAP_UARTCharPut(UARTA0_BASE, c);
13388
#else
13389
#define MG_UART_WRITE(fd, buf, len)
13390
#endif /* CS_PLATFORM == CS_P_CC3200 */
13391
#endif /* !MG_UART_CHAR_PUT */
13392

    
13393
enum fd_type {
13394
  FD_INVALID,
13395
  FD_SYS,
13396
#ifdef CC3200_FS_SPIFFS
13397
  FD_SPIFFS,
13398
#endif
13399
#ifdef MG_FS_SLFS
13400
  FD_SLFS
13401
#endif
13402
};
13403
static int fd_type(int fd) {
13404
  if (fd >= 0 && fd < NUM_SYS_FDS) return FD_SYS;
13405
#ifdef CC3200_FS_SPIFFS
13406
  if (fd >= SPIFFS_FD_BASE && fd < SPIFFS_FD_BASE + MAX_OPEN_SPIFFS_FILES) {
13407
    return FD_SPIFFS;
13408
  }
13409
#endif
13410
#ifdef MG_FS_SLFS
13411
  if (fd >= SLFS_FD_BASE && fd < SLFS_FD_BASE + MAX_OPEN_SLFS_FILES) {
13412
    return FD_SLFS;
13413
  }
13414
#endif
13415
  return FD_INVALID;
13416
}
13417

    
13418
#if MG_TI_NO_HOST_INTERFACE
13419
int open(const char *pathname, unsigned flags, int mode) {
13420
#else
13421
int _open(const char *pathname, int flags, mode_t mode) {
13422
#endif
13423
  int fd = -1;
13424
  bool is_sl;
13425
  const char *fname = drop_dir(pathname, &is_sl);
13426
  if (is_sl) {
13427
#ifdef MG_FS_SLFS
13428
    fd = fs_slfs_open(fname, flags, mode);
13429
    if (fd >= 0) fd += SLFS_FD_BASE;
13430
#endif
13431
  } else {
13432
#ifdef CC3200_FS_SPIFFS
13433
    fd = fs_spiffs_open(fname, flags, mode);
13434
    if (fd >= 0) fd += SPIFFS_FD_BASE;
13435
#endif
13436
  }
13437
  LOG(LL_DEBUG,
13438
      ("open(%s, 0x%x) = %d, fname = %s", pathname, flags, fd, fname));
13439
  return fd;
13440
}
13441

    
13442
int _stat(const char *pathname, struct stat *st) {
13443
  int res = -1;
13444
  bool is_sl;
13445
  const char *fname = drop_dir(pathname, &is_sl);
13446
  memset(st, 0, sizeof(*st));
13447
  /* Simulate statting the root directory. */
13448
  if (fname[0] == '\0' || strcmp(fname, ".") == 0) {
13449
    st->st_ino = 0;
13450
    st->st_mode = S_IFDIR | 0777;
13451
    st->st_nlink = 1;
13452
    st->st_size = 0;
13453
    return 0;
13454
  }
13455
  if (is_sl) {
13456
#ifdef MG_FS_SLFS
13457
    res = fs_slfs_stat(fname, st);
13458
#endif
13459
  } else {
13460
#ifdef CC3200_FS_SPIFFS
13461
    res = fs_spiffs_stat(fname, st);
13462
#endif
13463
  }
13464
  LOG(LL_DEBUG, ("stat(%s) = %d; fname = %s", pathname, res, fname));
13465
  return res;
13466
}
13467

    
13468
#if MG_TI_NO_HOST_INTERFACE
13469
int close(int fd) {
13470
#else
13471
int _close(int fd) {
13472
#endif
13473
  int r = -1;
13474
  switch (fd_type(fd)) {
13475
    case FD_INVALID:
13476
      r = set_errno(EBADF);
13477
      break;
13478
    case FD_SYS:
13479
      r = set_errno(EACCES);
13480
      break;
13481
#ifdef CC3200_FS_SPIFFS
13482
    case FD_SPIFFS:
13483
      r = fs_spiffs_close(fd - SPIFFS_FD_BASE);
13484
      break;
13485
#endif
13486
#ifdef MG_FS_SLFS
13487
    case FD_SLFS:
13488
      r = fs_slfs_close(fd - SLFS_FD_BASE);
13489
      break;
13490
#endif
13491
  }
13492
  DBG(("close(%d) = %d", fd, r));
13493
  return r;
13494
}
13495

    
13496
#if MG_TI_NO_HOST_INTERFACE
13497
off_t lseek(int fd, off_t offset, int whence) {
13498
#else
13499
off_t _lseek(int fd, off_t offset, int whence) {
13500
#endif
13501
  int r = -1;
13502
  switch (fd_type(fd)) {
13503
    case FD_INVALID:
13504
      r = set_errno(EBADF);
13505
      break;
13506
    case FD_SYS:
13507
      r = set_errno(ESPIPE);
13508
      break;
13509
#ifdef CC3200_FS_SPIFFS
13510
    case FD_SPIFFS:
13511
      r = fs_spiffs_lseek(fd - SPIFFS_FD_BASE, offset, whence);
13512
      break;
13513
#endif
13514
#ifdef MG_FS_SLFS
13515
    case FD_SLFS:
13516
      r = fs_slfs_lseek(fd - SLFS_FD_BASE, offset, whence);
13517
      break;
13518
#endif
13519
  }
13520
  DBG(("lseek(%d, %d, %d) = %d", fd, (int) offset, whence, r));
13521
  return r;
13522
}
13523

    
13524
int _fstat(int fd, struct stat *s) {
13525
  int r = -1;
13526
  memset(s, 0, sizeof(*s));
13527
  switch (fd_type(fd)) {
13528
    case FD_INVALID:
13529
      r = set_errno(EBADF);
13530
      break;
13531
    case FD_SYS: {
13532
      /* Create barely passable stats for STD{IN,OUT,ERR}. */
13533
      memset(s, 0, sizeof(*s));
13534
      s->st_ino = fd;
13535
      s->st_mode = S_IFCHR | 0666;
13536
      r = 0;
13537
      break;
13538
    }
13539
#ifdef CC3200_FS_SPIFFS
13540
    case FD_SPIFFS:
13541
      r = fs_spiffs_fstat(fd - SPIFFS_FD_BASE, s);
13542
      break;
13543
#endif
13544
#ifdef MG_FS_SLFS
13545
    case FD_SLFS:
13546
      r = fs_slfs_fstat(fd - SLFS_FD_BASE, s);
13547
      break;
13548
#endif
13549
  }
13550
  DBG(("fstat(%d) = %d", fd, r));
13551
  return r;
13552
}
13553

    
13554
#if MG_TI_NO_HOST_INTERFACE
13555
int read(int fd, char *buf, unsigned count) {
13556
#else
13557
ssize_t _read(int fd, void *buf, size_t count) {
13558
#endif
13559
  int r = -1;
13560
  switch (fd_type(fd)) {
13561
    case FD_INVALID:
13562
      r = set_errno(EBADF);
13563
      break;
13564
    case FD_SYS: {
13565
      if (fd != 0) {
13566
        r = set_errno(EACCES);
13567
        break;
13568
      }
13569
      /* Should we allow reading from stdin = uart? */
13570
      r = set_errno(ENOTSUP);
13571
      break;
13572
    }
13573
#ifdef CC3200_FS_SPIFFS
13574
    case FD_SPIFFS:
13575
      r = fs_spiffs_read(fd - SPIFFS_FD_BASE, buf, count);
13576
      break;
13577
#endif
13578
#ifdef MG_FS_SLFS
13579
    case FD_SLFS:
13580
      r = fs_slfs_read(fd - SLFS_FD_BASE, buf, count);
13581
      break;
13582
#endif
13583
  }
13584
  DBG(("read(%d, %u) = %d", fd, count, r));
13585
  return r;
13586
}
13587

    
13588
#if MG_TI_NO_HOST_INTERFACE
13589
int write(int fd, const char *buf, unsigned count) {
13590
#else
13591
ssize_t _write(int fd, const void *buf, size_t count) {
13592
#endif
13593
  int r = -1;
13594
  switch (fd_type(fd)) {
13595
    case FD_INVALID:
13596
      r = set_errno(EBADF);
13597
      break;
13598
    case FD_SYS: {
13599
      if (fd == 0) {
13600
        r = set_errno(EACCES);
13601
        break;
13602
      }
13603
#ifdef MG_UART_WRITE
13604
      MG_UART_WRITE(fd, buf, count);
13605
#elif defined(MG_UART_CHAR_PUT)
13606
      {
13607
        size_t i;
13608
        for (i = 0; i < count; i++) {
13609
          const char c = ((const char *) buf)[i];
13610
          if (c == '\n') MG_UART_CHAR_PUT(fd, '\r');
13611
          MG_UART_CHAR_PUT(fd, c);
13612
        }
13613
      }
13614
#endif
13615
      r = count;
13616
      break;
13617
    }
13618
#ifdef CC3200_FS_SPIFFS
13619
    case FD_SPIFFS:
13620
      r = fs_spiffs_write(fd - SPIFFS_FD_BASE, buf, count);
13621
      break;
13622
#endif
13623
#ifdef MG_FS_SLFS
13624
    case FD_SLFS:
13625
      r = fs_slfs_write(fd - SLFS_FD_BASE, buf, count);
13626
      break;
13627
#endif
13628
  }
13629
  return r;
13630
}
13631

    
13632
/*
13633
 * On Newlib we override rename directly too, because the default
13634
 * implementation using _link and _unlink doesn't work for us.
13635
 */
13636
#if MG_TI_NO_HOST_INTERFACE || defined(_NEWLIB_VERSION)
13637
int rename(const char *frompath, const char *topath) {
13638
  int r = -1;
13639
  bool is_sl_from, is_sl_to;
13640
  const char *from = drop_dir(frompath, &is_sl_from);
13641
  const char *to = drop_dir(topath, &is_sl_to);
13642
  if (is_sl_from || is_sl_to) {
13643
    set_errno(ENOTSUP);
13644
  } else {
13645
#ifdef CC3200_FS_SPIFFS
13646
    r = fs_spiffs_rename(from, to);
13647
#endif
13648
  }
13649
  DBG(("rename(%s, %s) = %d", from, to, r));
13650
  return r;
13651
}
13652
#endif /* MG_TI_NO_HOST_INTERFACE || defined(_NEWLIB_VERSION) */
13653

    
13654
#if MG_TI_NO_HOST_INTERFACE
13655
int unlink(const char *pathname) {
13656
#else
13657
int _unlink(const char *pathname) {
13658
#endif
13659
  int r = -1;
13660
  bool is_sl;
13661
  const char *fname = drop_dir(pathname, &is_sl);
13662
  if (is_sl) {
13663
#ifdef MG_FS_SLFS
13664
    r = fs_slfs_unlink(fname);
13665
#endif
13666
  } else {
13667
#ifdef CC3200_FS_SPIFFS
13668
    r = fs_spiffs_unlink(fname);
13669
#endif
13670
  }
13671
  DBG(("unlink(%s) = %d, fname = %s", pathname, r, fname));
13672
  return r;
13673
}
13674

    
13675
#ifdef CC3200_FS_SPIFFS /* FailFS does not support listing files. */
13676
DIR *opendir(const char *dir_name) {
13677
  DIR *r = NULL;
13678
  bool is_sl;
13679
  drop_dir(dir_name, &is_sl);
13680
  if (is_sl) {
13681
    r = NULL;
13682
    set_errno(ENOTSUP);
13683
  } else {
13684
    r = fs_spiffs_opendir(dir_name);
13685
  }
13686
  DBG(("opendir(%s) = %p", dir_name, r));
13687
  return r;
13688
}
13689

    
13690
struct dirent *readdir(DIR *dir) {
13691
  struct dirent *res = fs_spiffs_readdir(dir);
13692
  DBG(("readdir(%p) = %p", dir, res));
13693
  return res;
13694
}
13695

    
13696
int closedir(DIR *dir) {
13697
  int res = fs_spiffs_closedir(dir);
13698
  DBG(("closedir(%p) = %d", dir, res));
13699
  return res;
13700
}
13701

    
13702
int rmdir(const char *path) {
13703
  return fs_spiffs_rmdir(path);
13704
}
13705

    
13706
int mkdir(const char *path, mode_t mode) {
13707
  (void) path;
13708
  (void) mode;
13709
  /* for spiffs supports only root dir, which comes from mongoose as '.' */
13710
  return (strlen(path) == 1 && *path == '.') ? 0 : ENOTDIR;
13711
}
13712
#endif
13713

    
13714
int sl_fs_init(void) {
13715
  int ret = 1;
13716
#ifdef __TI_COMPILER_VERSION__
13717
#ifdef MG_FS_SLFS
13718
#pragma diag_push
13719
#pragma diag_suppress 169 /* Nothing we can do about the prototype mismatch. \
13720
                             */
13721
  ret = (add_device("SL", _MSA, fs_slfs_open, fs_slfs_close, fs_slfs_read,
13722
                    fs_slfs_write, fs_slfs_lseek, fs_slfs_unlink,
13723
                    fs_slfs_rename) == 0);
13724
#pragma diag_pop
13725
#endif
13726
#endif
13727
  return ret;
13728
}
13729

    
13730
#endif /* !defined(MG_FS_NO_VFS) */
13731
#endif /* MG_NET_IF == MG_NET_IF_SIMPLELINK && (defined(MG_FS_SLFS) || \
13732
          defined(MG_FS_SPIFFS)) */
13733
#ifdef MG_MODULE_LINES
13734
#line 1 "common/platforms/simplelink/sl_socket.c"
13735
#endif
13736
/*
13737
 * Copyright (c) 2014-2016 Cesanta Software Limited
13738
 * All rights reserved
13739
 */
13740

    
13741
#if MG_NET_IF == MG_NET_IF_SIMPLELINK
13742

    
13743
#include <errno.h>
13744
#include <stdio.h>
13745

    
13746
/* Amalgamated: #include "common/platform.h" */
13747

    
13748
const char *inet_ntop(int af, const void *src, char *dst, socklen_t size) {
13749
  int res;
13750
  struct in_addr *in = (struct in_addr *) src;
13751
  if (af != AF_INET) {
13752
    errno = ENOTSUP;
13753
    return NULL;
13754
  }
13755
  res = snprintf(dst, size, "%lu.%lu.%lu.%lu", SL_IPV4_BYTE(in->s_addr, 0),
13756
                 SL_IPV4_BYTE(in->s_addr, 1), SL_IPV4_BYTE(in->s_addr, 2),
13757
                 SL_IPV4_BYTE(in->s_addr, 3));
13758
  return res > 0 ? dst : NULL;
13759
}
13760

    
13761
char *inet_ntoa(struct in_addr n) {
13762
  static char a[16];
13763
  return (char *) inet_ntop(AF_INET, &n, a, sizeof(a));
13764
}
13765

    
13766
int inet_pton(int af, const char *src, void *dst) {
13767
  uint32_t a0, a1, a2, a3;
13768
  uint8_t *db = (uint8_t *) dst;
13769
  if (af != AF_INET) {
13770
    errno = ENOTSUP;
13771
    return 0;
13772
  }
13773
  if (sscanf(src, "%lu.%lu.%lu.%lu", &a0, &a1, &a2, &a3) != 4) {
13774
    return 0;
13775
  }
13776
  *db = a3;
13777
  *(db + 1) = a2;
13778
  *(db + 2) = a1;
13779
  *(db + 3) = a0;
13780
  return 1;
13781
}
13782

    
13783
#endif /* MG_NET_IF == MG_NET_IF_SIMPLELINK */
13784
#ifdef MG_MODULE_LINES
13785
#line 1 "common/platforms/simplelink/sl_mg_task.c"
13786
#endif
13787
#if MG_NET_IF == MG_NET_IF_SIMPLELINK && !defined(MG_SIMPLELINK_NO_OSI)
13788

    
13789
/* Amalgamated: #include "mg_task.h" */
13790

    
13791
#include <oslib/osi.h>
13792

    
13793
enum mg_q_msg_type {
13794
  MG_Q_MSG_CB,
13795
};
13796
struct mg_q_msg {
13797
  enum mg_q_msg_type type;
13798
  void (*cb)(struct mg_mgr *mgr, void *arg);
13799
  void *arg;
13800
};
13801
static OsiMsgQ_t s_mg_q;
13802
static void mg_task(void *arg);
13803

    
13804
bool mg_start_task(int priority, int stack_size, mg_init_cb mg_init) {
13805
  if (osi_MsgQCreate(&s_mg_q, "MG", sizeof(struct mg_q_msg), 16) != OSI_OK) {
13806
    return false;
13807
  }
13808
  if (osi_TaskCreate(mg_task, (const signed char *) "MG", stack_size,
13809
                     (void *) mg_init, priority, NULL) != OSI_OK) {
13810
    return false;
13811
  }
13812
  return true;
13813
}
13814

    
13815
static void mg_task(void *arg) {
13816
  struct mg_mgr mgr;
13817
  mg_init_cb mg_init = (mg_init_cb) arg;
13818
  mg_mgr_init(&mgr, NULL);
13819
  mg_init(&mgr);
13820
  while (1) {
13821
    struct mg_q_msg msg;
13822
    mg_mgr_poll(&mgr, 1);
13823
    if (osi_MsgQRead(&s_mg_q, &msg, 1) != OSI_OK) continue;
13824
    switch (msg.type) {
13825
      case MG_Q_MSG_CB: {
13826
        msg.cb(&mgr, msg.arg);
13827
      }
13828
    }
13829
  }
13830
}
13831

    
13832
void mg_run_in_task(void (*cb)(struct mg_mgr *mgr, void *arg), void *cb_arg) {
13833
  struct mg_q_msg msg = {MG_Q_MSG_CB, cb, cb_arg};
13834
  osi_MsgQWrite(&s_mg_q, &msg, OSI_NO_WAIT);
13835
}
13836

    
13837
#endif /* MG_NET_IF == MG_NET_IF_SIMPLELINK && !defined(MG_SIMPLELINK_NO_OSI) \
13838
          */
13839
#ifdef MG_MODULE_LINES
13840
#line 1 "common/platforms/simplelink/sl_net_if.h"
13841
#endif
13842
/*
13843
 * Copyright (c) 2014-2016 Cesanta Software Limited
13844
 * All rights reserved
13845
 */
13846

    
13847
#ifndef CS_COMMON_PLATFORMS_SIMPLELINK_SL_NET_IF_H_
13848
#define CS_COMMON_PLATFORMS_SIMPLELINK_SL_NET_IF_H_
13849

    
13850
/* Amalgamated: #include "mongoose/src/net_if.h" */
13851

    
13852
#ifdef __cplusplus
13853
extern "C" {
13854
#endif /* __cplusplus */
13855

    
13856
#ifndef MG_ENABLE_NET_IF_SIMPLELINK
13857
#define MG_ENABLE_NET_IF_SIMPLELINK MG_NET_IF == MG_NET_IF_SIMPLELINK
13858
#endif
13859

    
13860
extern const struct mg_iface_vtable mg_simplelink_iface_vtable;
13861

    
13862
#ifdef __cplusplus
13863
}
13864
#endif /* __cplusplus */
13865

    
13866
#endif /* CS_COMMON_PLATFORMS_SIMPLELINK_SL_NET_IF_H_ */
13867
#ifdef MG_MODULE_LINES
13868
#line 1 "common/platforms/simplelink/sl_net_if.c"
13869
#endif
13870
/*
13871
 * Copyright (c) 2014-2016 Cesanta Software Limited
13872
 * All rights reserved
13873
 */
13874

    
13875
/* Amalgamated: #include "common/platforms/simplelink/sl_net_if.h" */
13876

    
13877
#if MG_ENABLE_NET_IF_SIMPLELINK
13878

    
13879
/* Amalgamated: #include "mongoose/src/internal.h" */
13880
/* Amalgamated: #include "mongoose/src/util.h" */
13881

    
13882
#define MG_TCP_RECV_BUFFER_SIZE 1024
13883
#define MG_UDP_RECV_BUFFER_SIZE 1500
13884

    
13885
static sock_t mg_open_listening_socket(struct mg_connection *nc,
13886
                                       union socket_address *sa, int type,
13887
                                       int proto);
13888

    
13889
void mg_set_non_blocking_mode(sock_t sock) {
13890
  SlSockNonblocking_t opt;
13891
#if SL_MAJOR_VERSION_NUM < 2
13892
  opt.NonblockingEnabled = 1;
13893
#else
13894
  opt.NonBlockingEnabled = 1;
13895
#endif
13896
  sl_SetSockOpt(sock, SL_SOL_SOCKET, SL_SO_NONBLOCKING, &opt, sizeof(opt));
13897
}
13898

    
13899
static int mg_is_error(int n) {
13900
  return (n < 0 && n != SL_ERROR_BSD_EALREADY && n != SL_ERROR_BSD_EAGAIN);
13901
}
13902

    
13903
void mg_sl_if_connect_tcp(struct mg_connection *nc,
13904
                          const union socket_address *sa) {
13905
  int proto = 0;
13906
  if (nc->flags & MG_F_SSL) proto = SL_SEC_SOCKET;
13907
  sock_t sock = sl_Socket(AF_INET, SOCK_STREAM, proto);
13908
  if (sock < 0) {
13909
    nc->err = sock;
13910
    goto out;
13911
  }
13912
  mg_sock_set(nc, sock);
13913
#if MG_ENABLE_SSL
13914
  nc->err = sl_set_ssl_opts(sock, nc);
13915
  if (nc->err != 0) goto out;
13916
#endif
13917
  nc->err = sl_Connect(sock, &sa->sa, sizeof(sa->sin));
13918
out:
13919
  DBG(("%p to %s:%d sock %d %d err %d", nc, inet_ntoa(sa->sin.sin_addr),
13920
       ntohs(sa->sin.sin_port), nc->sock, proto, nc->err));
13921
}
13922

    
13923
void mg_sl_if_connect_udp(struct mg_connection *nc) {
13924
  sock_t sock = sl_Socket(AF_INET, SOCK_DGRAM, 0);
13925
  if (sock < 0) {
13926
    nc->err = sock;
13927
    return;
13928
  }
13929
  mg_sock_set(nc, sock);
13930
  nc->err = 0;
13931
}
13932

    
13933
int mg_sl_if_listen_tcp(struct mg_connection *nc, union socket_address *sa) {
13934
  int proto = 0;
13935
  if (nc->flags & MG_F_SSL) proto = SL_SEC_SOCKET;
13936
  sock_t sock = mg_open_listening_socket(nc, sa, SOCK_STREAM, proto);
13937
  if (sock < 0) return sock;
13938
  mg_sock_set(nc, sock);
13939
  return 0;
13940
}
13941

    
13942
int mg_sl_if_listen_udp(struct mg_connection *nc, union socket_address *sa) {
13943
  sock_t sock = mg_open_listening_socket(nc, sa, SOCK_DGRAM, 0);
13944
  if (sock == INVALID_SOCKET) return (errno ? errno : 1);
13945
  mg_sock_set(nc, sock);
13946
  return 0;
13947
}
13948

    
13949
void mg_sl_if_tcp_send(struct mg_connection *nc, const void *buf, size_t len) {
13950
  mbuf_append(&nc->send_mbuf, buf, len);
13951
}
13952

    
13953
void mg_sl_if_udp_send(struct mg_connection *nc, const void *buf, size_t len) {
13954
  mbuf_append(&nc->send_mbuf, buf, len);
13955
}
13956

    
13957
void mg_sl_if_recved(struct mg_connection *nc, size_t len) {
13958
  (void) nc;
13959
  (void) len;
13960
}
13961

    
13962
int mg_sl_if_create_conn(struct mg_connection *nc) {
13963
  (void) nc;
13964
  return 1;
13965
}
13966

    
13967
void mg_sl_if_destroy_conn(struct mg_connection *nc) {
13968
  if (nc->sock == INVALID_SOCKET) return;
13969
  /* For UDP, only close outgoing sockets or listeners. */
13970
  if (!(nc->flags & MG_F_UDP) || nc->listener == NULL) {
13971
    sl_Close(nc->sock);
13972
  }
13973
  nc->sock = INVALID_SOCKET;
13974
}
13975

    
13976
static int mg_accept_conn(struct mg_connection *lc) {
13977
  struct mg_connection *nc;
13978
  union socket_address sa;
13979
  socklen_t sa_len = sizeof(sa);
13980
  sock_t sock = sl_Accept(lc->sock, &sa.sa, &sa_len);
13981
  if (sock < 0) {
13982
    DBG(("%p: failed to accept: %d", lc, sock));
13983
    return 0;
13984
  }
13985
  nc = mg_if_accept_new_conn(lc);
13986
  if (nc == NULL) {
13987
    sl_Close(sock);
13988
    return 0;
13989
  }
13990
  DBG(("%p conn from %s:%d", nc, inet_ntoa(sa.sin.sin_addr),
13991
       ntohs(sa.sin.sin_port)));
13992
  mg_sock_set(nc, sock);
13993
  if (nc->flags & MG_F_SSL) nc->flags |= MG_F_SSL_HANDSHAKE_DONE;
13994
  mg_if_accept_tcp_cb(nc, &sa, sa_len);
13995
  return 1;
13996
}
13997

    
13998
/* 'sa' must be an initialized address to bind to */
13999
static sock_t mg_open_listening_socket(struct mg_connection *nc,
14000
                                       union socket_address *sa, int type,
14001
                                       int proto) {
14002
  int r;
14003
  socklen_t sa_len =
14004
      (sa->sa.sa_family == AF_INET) ? sizeof(sa->sin) : sizeof(sa->sin6);
14005
  sock_t sock = sl_Socket(sa->sa.sa_family, type, proto);
14006
  if (sock < 0) return sock;
14007
  if ((r = sl_Bind(sock, &sa->sa, sa_len)) < 0) goto clean;
14008
  if (type != SOCK_DGRAM) {
14009
#if MG_ENABLE_SSL
14010
    if ((r = sl_set_ssl_opts(sock, nc)) < 0) goto clean;
14011
#endif
14012
    if ((r = sl_Listen(sock, SOMAXCONN)) < 0) goto clean;
14013
  }
14014
  mg_set_non_blocking_mode(sock);
14015
clean:
14016
  if (r < 0) {
14017
    sl_Close(sock);
14018
    sock = r;
14019
  }
14020
  return sock;
14021
}
14022

    
14023
static void mg_write_to_socket(struct mg_connection *nc) {
14024
  struct mbuf *io = &nc->send_mbuf;
14025
  int n = 0;
14026

    
14027
  if (nc->flags & MG_F_UDP) {
14028
    n = sl_SendTo(nc->sock, io->buf, io->len, 0, &nc->sa.sa,
14029
                  sizeof(nc->sa.sin));
14030
    DBG(("%p %d %d %d %s:%hu", nc, nc->sock, n, errno,
14031
         inet_ntoa(nc->sa.sin.sin_addr), ntohs(nc->sa.sin.sin_port)));
14032
  } else {
14033
    n = (int) sl_Send(nc->sock, io->buf, io->len, 0);
14034
    DBG(("%p %d bytes -> %d", nc, n, nc->sock));
14035
  }
14036

    
14037
  if (n > 0) {
14038
    mg_if_sent_cb(nc, n);
14039
  } else if (n < 0 && mg_is_error(n)) {
14040
    /* Something went wrong, drop the connection. */
14041
    nc->flags |= MG_F_CLOSE_IMMEDIATELY;
14042
  }
14043
}
14044

    
14045
MG_INTERNAL size_t recv_avail_size(struct mg_connection *conn, size_t max) {
14046
  size_t avail;
14047
  if (conn->recv_mbuf_limit < conn->recv_mbuf.len) return 0;
14048
  avail = conn->recv_mbuf_limit - conn->recv_mbuf.len;
14049
  return avail > max ? max : avail;
14050
}
14051

    
14052
static void mg_handle_tcp_read(struct mg_connection *conn) {
14053
  int n = 0;
14054
  char *buf = (char *) MG_MALLOC(MG_TCP_RECV_BUFFER_SIZE);
14055

    
14056
  if (buf == NULL) {
14057
    DBG(("OOM"));
14058
    return;
14059
  }
14060

    
14061
  n = (int) sl_Recv(conn->sock, buf,
14062
                    recv_avail_size(conn, MG_TCP_RECV_BUFFER_SIZE), 0);
14063
  DBG(("%p %d bytes <- %d", conn, n, conn->sock));
14064
  if (n > 0) {
14065
    mg_if_recv_tcp_cb(conn, buf, n, 1 /* own */);
14066
  } else {
14067
    MG_FREE(buf);
14068
  }
14069
  if (n == 0) {
14070
    /* Orderly shutdown of the socket, try flushing output. */
14071
    conn->flags |= MG_F_SEND_AND_CLOSE;
14072
  } else if (mg_is_error(n)) {
14073
    conn->flags |= MG_F_CLOSE_IMMEDIATELY;
14074
  }
14075
}
14076

    
14077
static void mg_handle_udp_read(struct mg_connection *nc) {
14078
  char *buf = (char *) MG_MALLOC(MG_UDP_RECV_BUFFER_SIZE);
14079
  if (buf == NULL) return;
14080
  union socket_address sa;
14081
  socklen_t sa_len = sizeof(sa);
14082
  int n = sl_RecvFrom(nc->sock, buf, MG_UDP_RECV_BUFFER_SIZE, 0,
14083
                      (SlSockAddr_t *) &sa, &sa_len);
14084
  DBG(("%p %d bytes from %s:%d", nc, n, inet_ntoa(nc->sa.sin.sin_addr),
14085
       ntohs(nc->sa.sin.sin_port)));
14086
  if (n > 0) {
14087
    mg_if_recv_udp_cb(nc, buf, n, &sa, sa_len);
14088
  } else {
14089
    MG_FREE(buf);
14090
  }
14091
}
14092

    
14093
#define _MG_F_FD_CAN_READ 1
14094
#define _MG_F_FD_CAN_WRITE 1 << 1
14095
#define _MG_F_FD_ERROR 1 << 2
14096

    
14097
void mg_mgr_handle_conn(struct mg_connection *nc, int fd_flags, double now) {
14098
  DBG(("%p fd=%d fd_flags=%d nc_flags=%lu rmbl=%d smbl=%d", nc, nc->sock,
14099
       fd_flags, nc->flags, (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len));
14100

    
14101
  if (nc->flags & MG_F_CONNECTING) {
14102
    if (nc->flags & MG_F_UDP || nc->err != SL_ERROR_BSD_EALREADY) {
14103
      mg_if_connect_cb(nc, nc->err);
14104
    } else {
14105
      /* In SimpleLink, to get status of non-blocking connect() we need to wait
14106
       * until socket is writable and repeat the call to sl_Connect again,
14107
       * which will now return the real status. */
14108
      if (fd_flags & _MG_F_FD_CAN_WRITE) {
14109
        nc->err = sl_Connect(nc->sock, &nc->sa.sa, sizeof(nc->sa.sin));
14110
        DBG(("%p conn res=%d", nc, nc->err));
14111
        if (nc->err == SL_ERROR_BSD_ESECSNOVERIFY ||
14112
            /* TODO(rojer): Provide API to set the date for verification. */
14113
            nc->err == SL_ERROR_BSD_ESECDATEERROR
14114
#if SL_MAJOR_VERSION_NUM >= 2
14115
            /* Per SWRU455, this error does not mean verification failed,
14116
             * it only means that the cert used is not present in the trusted
14117
             * root CA catalog. Which is perfectly fine. */
14118
            ||
14119
            nc->err == SL_ERROR_BSD_ESECUNKNOWNROOTCA
14120
#endif
14121
            ) {
14122
          nc->err = 0;
14123
        }
14124
        if (nc->flags & MG_F_SSL && nc->err == 0) {
14125
          nc->flags |= MG_F_SSL_HANDSHAKE_DONE;
14126
        }
14127
        mg_if_connect_cb(nc, nc->err);
14128
      }
14129
    }
14130
    /* Ignore read/write in further processing, we've handled it. */
14131
    fd_flags &= ~(_MG_F_FD_CAN_READ | _MG_F_FD_CAN_WRITE);
14132
  }
14133

    
14134
  if (fd_flags & _MG_F_FD_CAN_READ) {
14135
    if (nc->flags & MG_F_UDP) {
14136
      mg_handle_udp_read(nc);
14137
    } else {
14138
      if (nc->flags & MG_F_LISTENING) {
14139
        mg_accept_conn(nc);
14140
      } else {
14141
        mg_handle_tcp_read(nc);
14142
      }
14143
    }
14144
  }
14145

    
14146
  if (!(nc->flags & MG_F_CLOSE_IMMEDIATELY)) {
14147
    if ((fd_flags & _MG_F_FD_CAN_WRITE) && nc->send_mbuf.len > 0) {
14148
      mg_write_to_socket(nc);
14149
    }
14150

    
14151
    if (!(fd_flags & (_MG_F_FD_CAN_READ | _MG_F_FD_CAN_WRITE))) {
14152
      mg_if_poll(nc, now);
14153
    }
14154
    mg_if_timer(nc, now);
14155
  }
14156

    
14157
  DBG(("%p after fd=%d nc_flags=%lu rmbl=%d smbl=%d", nc, nc->sock, nc->flags,
14158
       (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len));
14159
}
14160

    
14161
/* Associate a socket to a connection. */
14162
void mg_sl_if_sock_set(struct mg_connection *nc, sock_t sock) {
14163
  mg_set_non_blocking_mode(sock);
14164
  nc->sock = sock;
14165
  DBG(("%p %d", nc, sock));
14166
}
14167

    
14168
void mg_sl_if_init(struct mg_iface *iface) {
14169
  (void) iface;
14170
  DBG(("%p using sl_Select()", iface->mgr));
14171
}
14172

    
14173
void mg_sl_if_free(struct mg_iface *iface) {
14174
  (void) iface;
14175
}
14176

    
14177
void mg_sl_if_add_conn(struct mg_connection *nc) {
14178
  (void) nc;
14179
}
14180

    
14181
void mg_sl_if_remove_conn(struct mg_connection *nc) {
14182
  (void) nc;
14183
}
14184

    
14185
time_t mg_sl_if_poll(struct mg_iface *iface, int timeout_ms) {
14186
  struct mg_mgr *mgr = iface->mgr;
14187
  double now = mg_time();
14188
  double min_timer;
14189
  struct mg_connection *nc, *tmp;
14190
  struct SlTimeval_t tv;
14191
  SlFdSet_t read_set, write_set, err_set;
14192
  sock_t max_fd = INVALID_SOCKET;
14193
  int num_fds, num_ev = 0, num_timers = 0;
14194

    
14195
  SL_SOCKET_FD_ZERO(&read_set);
14196
  SL_SOCKET_FD_ZERO(&write_set);
14197
  SL_SOCKET_FD_ZERO(&err_set);
14198

    
14199
  /*
14200
   * Note: it is ok to have connections with sock == INVALID_SOCKET in the list,
14201
   * e.g. timer-only "connections".
14202
   */
14203
  min_timer = 0;
14204
  for (nc = mgr->active_connections, num_fds = 0; nc != NULL; nc = tmp) {
14205
    tmp = nc->next;
14206

    
14207
    if (nc->sock != INVALID_SOCKET) {
14208
      num_fds++;
14209

    
14210
      if (!(nc->flags & MG_F_WANT_WRITE) &&
14211
          nc->recv_mbuf.len < nc->recv_mbuf_limit &&
14212
          (!(nc->flags & MG_F_UDP) || nc->listener == NULL)) {
14213
        SL_SOCKET_FD_SET(nc->sock, &read_set);
14214
        if (max_fd == INVALID_SOCKET || nc->sock > max_fd) max_fd = nc->sock;
14215
      }
14216

    
14217
      if (((nc->flags & MG_F_CONNECTING) && !(nc->flags & MG_F_WANT_READ)) ||
14218
          (nc->send_mbuf.len > 0 && !(nc->flags & MG_F_CONNECTING))) {
14219
        SL_SOCKET_FD_SET(nc->sock, &write_set);
14220
        SL_SOCKET_FD_SET(nc->sock, &err_set);
14221
        if (max_fd == INVALID_SOCKET || nc->sock > max_fd) max_fd = nc->sock;
14222
      }
14223
    }
14224

    
14225
    if (nc->ev_timer_time > 0) {
14226
      if (num_timers == 0 || nc->ev_timer_time < min_timer) {
14227
        min_timer = nc->ev_timer_time;
14228
      }
14229
      num_timers++;
14230
    }
14231
  }
14232

    
14233
  /*
14234
   * If there is a timer to be fired earlier than the requested timeout,
14235
   * adjust the timeout.
14236
   */
14237
  if (num_timers > 0) {
14238
    double timer_timeout_ms = (min_timer - mg_time()) * 1000 + 1 /* rounding */;
14239
    if (timer_timeout_ms < timeout_ms) {
14240
      timeout_ms = timer_timeout_ms;
14241
    }
14242
  }
14243
  if (timeout_ms < 0) timeout_ms = 0;
14244

    
14245
  tv.tv_sec = timeout_ms / 1000;
14246
  tv.tv_usec = (timeout_ms % 1000) * 1000;
14247

    
14248
  if (num_fds > 0) {
14249
    num_ev = sl_Select((int) max_fd + 1, &read_set, &write_set, &err_set, &tv);
14250
  }
14251

    
14252
  now = mg_time();
14253
  DBG(("sl_Select @ %ld num_ev=%d of %d, timeout=%d", (long) now, num_ev,
14254
       num_fds, timeout_ms));
14255

    
14256
  for (nc = mgr->active_connections; nc != NULL; nc = tmp) {
14257
    int fd_flags = 0;
14258
    if (nc->sock != INVALID_SOCKET) {
14259
      if (num_ev > 0) {
14260
        fd_flags =
14261
            (SL_SOCKET_FD_ISSET(nc->sock, &read_set) &&
14262
                     (!(nc->flags & MG_F_UDP) || nc->listener == NULL)
14263
                 ? _MG_F_FD_CAN_READ
14264
                 : 0) |
14265
            (SL_SOCKET_FD_ISSET(nc->sock, &write_set) ? _MG_F_FD_CAN_WRITE
14266
                                                      : 0) |
14267
            (SL_SOCKET_FD_ISSET(nc->sock, &err_set) ? _MG_F_FD_ERROR : 0);
14268
      }
14269
      /* SimpleLink does not report UDP sockets as writable. */
14270
      if (nc->flags & MG_F_UDP && nc->send_mbuf.len > 0) {
14271
        fd_flags |= _MG_F_FD_CAN_WRITE;
14272
      }
14273
    }
14274
    tmp = nc->next;
14275
    mg_mgr_handle_conn(nc, fd_flags, now);
14276
  }
14277

    
14278
  for (nc = mgr->active_connections; nc != NULL; nc = tmp) {
14279
    tmp = nc->next;
14280
    if ((nc->flags & MG_F_CLOSE_IMMEDIATELY) ||
14281
        (nc->send_mbuf.len == 0 && (nc->flags & MG_F_SEND_AND_CLOSE))) {
14282
      mg_close_conn(nc);
14283
    }
14284
  }
14285

    
14286
  return now;
14287
}
14288

    
14289
void mg_sl_if_get_conn_addr(struct mg_connection *nc, int remote,
14290
                            union socket_address *sa) {
14291
  /* SimpleLink does not provide a way to get socket's peer address after
14292
   * accept or connect. Address should have been preserved in the connection,
14293
   * so we do our best here by using it. */
14294
  if (remote) memcpy(sa, &nc->sa, sizeof(*sa));
14295
}
14296

    
14297
void sl_restart_cb(struct mg_mgr *mgr) {
14298
  /*
14299
   * SimpleLink has been restarted, meaning all sockets have been invalidated.
14300
   * We try our best - we'll restart the listeners, but for outgoing
14301
   * connections we have no option but to terminate.
14302
   */
14303
  struct mg_connection *nc;
14304
  for (nc = mg_next(mgr, NULL); nc != NULL; nc = mg_next(mgr, nc)) {
14305
    if (nc->sock == INVALID_SOCKET) continue; /* Could be a timer */
14306
    if (nc->flags & MG_F_LISTENING) {
14307
      DBG(("restarting %p %s:%d", nc, inet_ntoa(nc->sa.sin.sin_addr),
14308
           ntohs(nc->sa.sin.sin_port)));
14309
      int res = (nc->flags & MG_F_UDP ? mg_sl_if_listen_udp(nc, &nc->sa)
14310
                                      : mg_sl_if_listen_tcp(nc, &nc->sa));
14311
      if (res == 0) continue;
14312
      /* Well, we tried and failed. Fall through to closing. */
14313
    }
14314
    nc->sock = INVALID_SOCKET;
14315
    DBG(("terminating %p %s:%d", nc, inet_ntoa(nc->sa.sin.sin_addr),
14316
         ntohs(nc->sa.sin.sin_port)));
14317
    /* TODO(rojer): Outgoing UDP? */
14318
    nc->flags |= MG_F_CLOSE_IMMEDIATELY;
14319
  }
14320
}
14321

    
14322
/* clang-format off */
14323
#define MG_SL_IFACE_VTABLE                                              \
14324
  {                                                                     \
14325
    mg_sl_if_init,                                                      \
14326
    mg_sl_if_free,                                                      \
14327
    mg_sl_if_add_conn,                                                  \
14328
    mg_sl_if_remove_conn,                                               \
14329
    mg_sl_if_poll,                                                      \
14330
    mg_sl_if_listen_tcp,                                                \
14331
    mg_sl_if_listen_udp,                                                \
14332
    mg_sl_if_connect_tcp,                                               \
14333
    mg_sl_if_connect_udp,                                               \
14334
    mg_sl_if_tcp_send,                                                  \
14335
    mg_sl_if_udp_send,                                                  \
14336
    mg_sl_if_recved,                                                    \
14337
    mg_sl_if_create_conn,                                               \
14338
    mg_sl_if_destroy_conn,                                              \
14339
    mg_sl_if_sock_set,                                                  \
14340
    mg_sl_if_get_conn_addr,                                             \
14341
  }
14342
/* clang-format on */
14343

    
14344
const struct mg_iface_vtable mg_simplelink_iface_vtable = MG_SL_IFACE_VTABLE;
14345
#if MG_NET_IF == MG_NET_IF_SIMPLELINK
14346
const struct mg_iface_vtable mg_default_iface_vtable = MG_SL_IFACE_VTABLE;
14347
#endif
14348

    
14349
#endif /* MG_ENABLE_NET_IF_SIMPLELINK */
14350
#ifdef MG_MODULE_LINES
14351
#line 1 "common/platforms/simplelink/sl_ssl_if.c"
14352
#endif
14353
/*
14354
 * Copyright (c) 2014-2016 Cesanta Software Limited
14355
 * All rights reserved
14356
 */
14357

    
14358
#if MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_SIMPLELINK
14359

    
14360
/* Amalgamated: #include "common/mg_mem.h" */
14361

    
14362
#ifndef MG_SSL_IF_SIMPLELINK_SLFS_PREFIX
14363
#define MG_SSL_IF_SIMPLELINK_SLFS_PREFIX "SL:"
14364
#endif
14365

    
14366
#define MG_SSL_IF_SIMPLELINK_SLFS_PREFIX_LEN \
14367
  (sizeof(MG_SSL_IF_SIMPLELINK_SLFS_PREFIX) - 1)
14368

    
14369
struct mg_ssl_if_ctx {
14370
  char *ssl_cert;
14371
  char *ssl_key;
14372
  char *ssl_ca_cert;
14373
  char *ssl_server_name;
14374
};
14375

    
14376
void mg_ssl_if_init() {
14377
}
14378

    
14379
enum mg_ssl_if_result mg_ssl_if_conn_init(
14380
    struct mg_connection *nc, const struct mg_ssl_if_conn_params *params,
14381
    const char **err_msg) {
14382
  struct mg_ssl_if_ctx *ctx =
14383
      (struct mg_ssl_if_ctx *) MG_CALLOC(1, sizeof(*ctx));
14384
  if (ctx == NULL) {
14385
    MG_SET_PTRPTR(err_msg, "Out of memory");
14386
    return MG_SSL_ERROR;
14387
  }
14388
  nc->ssl_if_data = ctx;
14389

    
14390
  if (params->cert != NULL || params->key != NULL) {
14391
    if (params->cert != NULL && params->key != NULL) {
14392
      ctx->ssl_cert = strdup(params->cert);
14393
      ctx->ssl_key = strdup(params->key);
14394
    } else {
14395
      MG_SET_PTRPTR(err_msg, "Both cert and key are required.");
14396
      return MG_SSL_ERROR;
14397
    }
14398
  }
14399
  if (params->ca_cert != NULL && strcmp(params->ca_cert, "*") != 0) {
14400
    ctx->ssl_ca_cert = strdup(params->ca_cert);
14401
  }
14402
  /* TODO(rojer): cipher_suites. */
14403
  if (params->server_name != NULL) {
14404
    ctx->ssl_server_name = strdup(params->server_name);
14405
  }
14406
  return MG_SSL_OK;
14407
}
14408

    
14409
void mg_ssl_if_conn_close_notify(struct mg_connection *nc) {
14410
  /* Nothing to do */
14411
  (void) nc;
14412
}
14413

    
14414
void mg_ssl_if_conn_free(struct mg_connection *nc) {
14415
  struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
14416
  if (ctx == NULL) return;
14417
  nc->ssl_if_data = NULL;
14418
  MG_FREE(ctx->ssl_cert);
14419
  MG_FREE(ctx->ssl_key);
14420
  MG_FREE(ctx->ssl_ca_cert);
14421
  MG_FREE(ctx->ssl_server_name);
14422
  memset(ctx, 0, sizeof(*ctx));
14423
  MG_FREE(ctx);
14424
}
14425

    
14426
bool pem_to_der(const char *pem_file, const char *der_file) {
14427
  bool ret = false;
14428
  FILE *pf = NULL, *df = NULL;
14429
  bool writing = false;
14430
  pf = fopen(pem_file, "r");
14431
  if (pf == NULL) goto clean;
14432
  remove(der_file);
14433
  fs_slfs_set_new_file_size(der_file + MG_SSL_IF_SIMPLELINK_SLFS_PREFIX_LEN,
14434
                            2048);
14435
  df = fopen(der_file, "w");
14436
  if (df == NULL) goto clean;
14437
  while (1) {
14438
    char pem_buf[70];
14439
    char der_buf[48];
14440
    if (!fgets(pem_buf, sizeof(pem_buf), pf)) break;
14441
    if (writing) {
14442
      if (strstr(pem_buf, "-----END ") != NULL) {
14443
        ret = true;
14444
        break;
14445
      }
14446
      int l = 0;
14447
      while (!isspace((unsigned int) pem_buf[l])) l++;
14448
      int der_len = 0;
14449
      cs_base64_decode((const unsigned char *) pem_buf, sizeof(pem_buf),
14450
                       der_buf, &der_len);
14451
      if (der_len <= 0) break;
14452
      if (fwrite(der_buf, 1, der_len, df) != der_len) break;
14453
    } else if (strstr(pem_buf, "-----BEGIN ") != NULL) {
14454
      writing = true;
14455
    }
14456
  }
14457

    
14458
clean:
14459
  if (pf != NULL) fclose(pf);
14460
  if (df != NULL) {
14461
    fclose(df);
14462
    if (!ret) remove(der_file);
14463
  }
14464
  return ret;
14465
}
14466

    
14467
#if MG_ENABLE_FILESYSTEM && defined(MG_FS_SLFS)
14468
/* If the file's extension is .pem, convert it to DER format and put on SLFS. */
14469
static char *sl_pem2der(const char *pem_file) {
14470
  const char *pem_ext = strstr(pem_file, ".pem");
14471
  if (pem_ext == NULL || *(pem_ext + 4) != '\0') {
14472
    return strdup(pem_file);
14473
  }
14474
  char *der_file = NULL;
14475
  /* DER file must be located on SLFS, add prefix. */
14476
  int l = mg_asprintf(&der_file, 0, MG_SSL_IF_SIMPLELINK_SLFS_PREFIX "%.*s.der",
14477
                      (int) (pem_ext - pem_file), pem_file);
14478
  if (der_file == NULL) return NULL;
14479
  bool result = false;
14480
  cs_stat_t st;
14481
  if (mg_stat(der_file, &st) != 0) {
14482
    result = pem_to_der(pem_file, der_file);
14483
    LOG(LL_DEBUG, ("%s -> %s = %d", pem_file, der_file, result));
14484
  } else {
14485
    /* File exists, assume it's already been converted. */
14486
    result = true;
14487
  }
14488
  if (result) {
14489
    /* Strip the SL: prefix we added since NWP does not expect it. */
14490
    memmove(der_file, der_file + MG_SSL_IF_SIMPLELINK_SLFS_PREFIX_LEN,
14491
            l - 2 /* including \0 */);
14492
  } else {
14493
    MG_FREE(der_file);
14494
    der_file = NULL;
14495
  }
14496
  return der_file;
14497
}
14498
#else
14499
static char *sl_pem2der(const char *pem_file) {
14500
  return strdup(pem_file);
14501
}
14502
#endif
14503

    
14504
int sl_set_ssl_opts(int sock, struct mg_connection *nc) {
14505
  int err;
14506
  const struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
14507
  DBG(("%p ssl ctx: %p", nc, ctx));
14508

    
14509
  if (ctx != NULL) {
14510
    DBG(("%p %s,%s,%s,%s", nc, (ctx->ssl_cert ? ctx->ssl_cert : "-"),
14511
         (ctx->ssl_key ? ctx->ssl_cert : "-"),
14512
         (ctx->ssl_ca_cert ? ctx->ssl_ca_cert : "-"),
14513
         (ctx->ssl_server_name ? ctx->ssl_server_name : "-")));
14514
    if (ctx->ssl_cert != NULL && ctx->ssl_key != NULL) {
14515
      char *ssl_cert = sl_pem2der(ctx->ssl_cert);
14516
      char *ssl_key = sl_pem2der(ctx->ssl_key);
14517
      if (ssl_cert != NULL && ssl_key != NULL) {
14518
        err = sl_SetSockOpt(sock, SL_SOL_SOCKET,
14519
                            SL_SO_SECURE_FILES_CERTIFICATE_FILE_NAME, ssl_cert,
14520
                            strlen(ssl_cert));
14521
        LOG(LL_INFO, ("CERTIFICATE_FILE_NAME %s -> %d", ssl_cert, err));
14522
        err = sl_SetSockOpt(sock, SL_SOL_SOCKET,
14523
                            SL_SO_SECURE_FILES_PRIVATE_KEY_FILE_NAME, ssl_key,
14524
                            strlen(ssl_key));
14525
        LOG(LL_INFO, ("PRIVATE_KEY_FILE_NAME %s -> %d", ssl_key, err));
14526
      } else {
14527
        err = -1;
14528
      }
14529
      MG_FREE(ssl_cert);
14530
      MG_FREE(ssl_key);
14531
      if (err != 0) return err;
14532
    }
14533
    if (ctx->ssl_ca_cert != NULL) {
14534
      if (ctx->ssl_ca_cert[0] != '\0') {
14535
        char *ssl_ca_cert = sl_pem2der(ctx->ssl_ca_cert);
14536
        if (ssl_ca_cert != NULL) {
14537
          err = sl_SetSockOpt(sock, SL_SOL_SOCKET,
14538
                              SL_SO_SECURE_FILES_CA_FILE_NAME, ssl_ca_cert,
14539
                              strlen(ssl_ca_cert));
14540
          LOG(LL_INFO, ("CA_FILE_NAME %s -> %d", ssl_ca_cert, err));
14541
        } else {
14542
          err = -1;
14543
        }
14544
        MG_FREE(ssl_ca_cert);
14545
        if (err != 0) return err;
14546
      }
14547
    }
14548
    if (ctx->ssl_server_name != NULL) {
14549
      err = sl_SetSockOpt(sock, SL_SOL_SOCKET,
14550
                          SL_SO_SECURE_DOMAIN_NAME_VERIFICATION,
14551
                          ctx->ssl_server_name, strlen(ctx->ssl_server_name));
14552
      DBG(("DOMAIN_NAME_VERIFICATION %s -> %d", ctx->ssl_server_name, err));
14553
      /* Domain name verificationw as added in a NWP service pack, older
14554
       * versions return SL_ERROR_BSD_ENOPROTOOPT. There isn't much we can do
14555
       * about it,
14556
       * so we ignore the error. */
14557
      if (err != 0 && err != SL_ERROR_BSD_ENOPROTOOPT) return err;
14558
    }
14559
  }
14560
  return 0;
14561
}
14562

    
14563
#endif /* MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_SIMPLELINK */
14564
#ifdef MG_MODULE_LINES
14565
#line 1 "common/platforms/lwip/mg_lwip_net_if.h"
14566
#endif
14567
/*
14568
 * Copyright (c) 2014-2016 Cesanta Software Limited
14569
 * All rights reserved
14570
 */
14571

    
14572
#ifndef CS_COMMON_PLATFORMS_LWIP_MG_NET_IF_LWIP_H_
14573
#define CS_COMMON_PLATFORMS_LWIP_MG_NET_IF_LWIP_H_
14574

    
14575
#ifndef MG_ENABLE_NET_IF_LWIP_LOW_LEVEL
14576
#define MG_ENABLE_NET_IF_LWIP_LOW_LEVEL MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL
14577
#endif
14578

    
14579
#if MG_ENABLE_NET_IF_LWIP_LOW_LEVEL
14580

    
14581
#include <stdint.h>
14582

    
14583
extern const struct mg_iface_vtable mg_lwip_iface_vtable;
14584

    
14585
struct mg_lwip_conn_state {
14586
  struct mg_connection *nc;
14587
  struct mg_connection *lc;
14588
  union {
14589
    struct tcp_pcb *tcp;
14590
    struct udp_pcb *udp;
14591
  } pcb;
14592
  err_t err;
14593
  size_t num_sent; /* Number of acknowledged bytes to be reported to the core */
14594
  struct pbuf *rx_chain; /* Chain of incoming data segments. */
14595
  size_t rx_offset; /* Offset within the first pbuf (if partially consumed) */
14596
  /* Last SSL write size, for retries. */
14597
  int last_ssl_write_size;
14598
  /* Whether MG_SIG_RECV is already pending for this connection */
14599
  int recv_pending : 1;
14600
  /* Whether the connection is about to close, just `rx_chain` needs to drain */
14601
  int draining_rx_chain : 1;
14602
};
14603

    
14604
enum mg_sig_type {
14605
  MG_SIG_CONNECT_RESULT = 1,
14606
  MG_SIG_RECV = 2,
14607
  MG_SIG_CLOSE_CONN = 3,
14608
  MG_SIG_TOMBSTONE = 4,
14609
  MG_SIG_ACCEPT = 5,
14610
};
14611

    
14612
void mg_lwip_post_signal(enum mg_sig_type sig, struct mg_connection *nc);
14613

    
14614
/* To be implemented by the platform. */
14615
void mg_lwip_mgr_schedule_poll(struct mg_mgr *mgr);
14616

    
14617
#endif /* MG_ENABLE_NET_IF_LWIP_LOW_LEVEL */
14618

    
14619
#endif /* CS_COMMON_PLATFORMS_LWIP_MG_NET_IF_LWIP_H_ */
14620
#ifdef MG_MODULE_LINES
14621
#line 1 "common/platforms/lwip/mg_lwip_net_if.c"
14622
#endif
14623
/*
14624
 * Copyright (c) 2014-2016 Cesanta Software Limited
14625
 * All rights reserved
14626
 */
14627

    
14628
#if MG_ENABLE_NET_IF_LWIP_LOW_LEVEL
14629

    
14630
/* Amalgamated: #include "common/mg_mem.h" */
14631

    
14632
#include <lwip/init.h>
14633
#include <lwip/pbuf.h>
14634
#include <lwip/tcp.h>
14635
#include <lwip/tcpip.h>
14636
#if ((LWIP_VERSION_MAJOR << 8) | LWIP_VERSION_MINOR) >= 0x0105
14637
#include <lwip/priv/tcp_priv.h> /* For tcp_seg */
14638
#else
14639
#include <lwip/tcp_impl.h>
14640
#endif
14641
#include <lwip/udp.h>
14642

    
14643
/* Amalgamated: #include "common/cs_dbg.h" */
14644

    
14645
/*
14646
 * Newest versions of LWIP have ip_2_ip4, older have ipX_2_ip,
14647
 * even older have nothing.
14648
 */
14649
#ifndef ip_2_ip4
14650
#ifdef ipX_2_ip
14651
#define ip_2_ip4(addr) ipX_2_ip(addr)
14652
#else
14653
#define ip_2_ip4(addr) (addr)
14654
#endif
14655
#endif
14656

    
14657
/*
14658
 * Depending on whether Mongoose is compiled with ipv6 support, use right
14659
 * lwip functions
14660
 */
14661
#if MG_ENABLE_IPV6
14662
#define TCP_NEW tcp_new_ip6
14663
#define TCP_BIND tcp_bind_ip6
14664
#define UDP_BIND udp_bind_ip6
14665
#define IPADDR_NTOA(x) ip6addr_ntoa((const ip6_addr_t *)(x))
14666
#define SET_ADDR(dst, src)                               \
14667
  memcpy((dst)->sin6.sin6_addr.s6_addr, (src)->ip6.addr, \
14668
         sizeof((dst)->sin6.sin6_addr.s6_addr))
14669
#else
14670
#define TCP_NEW tcp_new
14671
#define TCP_BIND tcp_bind
14672
#define UDP_BIND udp_bind
14673
#define IPADDR_NTOA ipaddr_ntoa
14674
#define SET_ADDR(dst, src) (dst)->sin.sin_addr.s_addr = ip_2_ip4(src)->addr
14675
#endif
14676

    
14677
#if NO_SYS
14678
#define tcpip_callback(fn, arg) (fn)(arg)
14679
typedef void (*tcpip_callback_fn)(void *arg);
14680
#endif
14681

    
14682
void mg_lwip_ssl_do_hs(struct mg_connection *nc);
14683
void mg_lwip_ssl_send(struct mg_connection *nc);
14684
void mg_lwip_ssl_recv(struct mg_connection *nc);
14685

    
14686
void mg_lwip_if_init(struct mg_iface *iface);
14687
void mg_lwip_if_free(struct mg_iface *iface);
14688
void mg_lwip_if_add_conn(struct mg_connection *nc);
14689
void mg_lwip_if_remove_conn(struct mg_connection *nc);
14690
time_t mg_lwip_if_poll(struct mg_iface *iface, int timeout_ms);
14691

    
14692
#if defined(RTOS_SDK) || defined(ESP_PLATFORM)
14693
extern void mgos_lock();
14694
extern void mgos_unlock();
14695
#else
14696
#define mgos_lock()
14697
#define mgos_unlock()
14698
#endif
14699

    
14700
static void mg_lwip_recv_common(struct mg_connection *nc, struct pbuf *p);
14701

    
14702
#if LWIP_TCP_KEEPALIVE
14703
void mg_lwip_set_keepalive_params(struct mg_connection *nc, int idle,
14704
                                  int interval, int count) {
14705
  if (nc->sock == INVALID_SOCKET || nc->flags & MG_F_UDP) {
14706
    return;
14707
  }
14708
  struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
14709
  struct tcp_pcb *tpcb = cs->pcb.tcp;
14710
  if (idle > 0 && interval > 0 && count > 0) {
14711
    tpcb->keep_idle = idle * 1000;
14712
    tpcb->keep_intvl = interval * 1000;
14713
    tpcb->keep_cnt = count;
14714
    tpcb->so_options |= SOF_KEEPALIVE;
14715
  } else {
14716
    tpcb->so_options &= ~SOF_KEEPALIVE;
14717
  }
14718
}
14719
#elif !defined(MG_NO_LWIP_TCP_KEEPALIVE)
14720
#warning LWIP TCP keepalive is disabled. Please consider enabling it.
14721
#endif /* LWIP_TCP_KEEPALIVE */
14722

    
14723
static err_t mg_lwip_tcp_conn_cb(void *arg, struct tcp_pcb *tpcb, err_t err) {
14724
  struct mg_connection *nc = (struct mg_connection *) arg;
14725
  DBG(("%p connect to %s:%u = %d", nc, IPADDR_NTOA(ipX_2_ip(&tpcb->remote_ip)),
14726
       tpcb->remote_port, err));
14727
  if (nc == NULL) {
14728
    tcp_abort(tpcb);
14729
    return ERR_ARG;
14730
  }
14731
  struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
14732
  cs->err = err;
14733
#if LWIP_TCP_KEEPALIVE
14734
  if (err == 0) mg_lwip_set_keepalive_params(nc, 60, 10, 6);
14735
#endif
14736
  mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc);
14737
  return ERR_OK;
14738
}
14739

    
14740
static void mg_lwip_tcp_error_cb(void *arg, err_t err) {
14741
  struct mg_connection *nc = (struct mg_connection *) arg;
14742
  DBG(("%p conn error %d", nc, err));
14743
  if (nc == NULL) return;
14744
  struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
14745
  cs->pcb.tcp = NULL; /* Has already been deallocated */
14746
  if (nc->flags & MG_F_CONNECTING) {
14747
    cs->err = err;
14748
    mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc);
14749
  } else {
14750
    mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc);
14751
  }
14752
}
14753

    
14754
static err_t mg_lwip_tcp_recv_cb(void *arg, struct tcp_pcb *tpcb,
14755
                                 struct pbuf *p, err_t err) {
14756
  struct mg_connection *nc = (struct mg_connection *) arg;
14757
  DBG(("%p %p %u %d", nc, tpcb, (p != NULL ? p->tot_len : 0), err));
14758
  if (p == NULL) {
14759
    if (nc != NULL && !(nc->flags & MG_F_CLOSE_IMMEDIATELY)) {
14760
      struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
14761
      if (cs->rx_chain != NULL) {
14762
        /*
14763
         * rx_chain still contains non-consumed data, don't close the
14764
         * connection
14765
         */
14766
        cs->draining_rx_chain = 1;
14767
      } else {
14768
        mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc);
14769
      }
14770
    } else {
14771
      /* Tombstoned connection, do nothing. */
14772
    }
14773
    return ERR_OK;
14774
  } else if (nc == NULL) {
14775
    tcp_abort(tpcb);
14776
    return ERR_ARG;
14777
  }
14778
  struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
14779
  /*
14780
   * If we get a chain of more than one segment at once, we need to bump
14781
   * refcount on the subsequent bufs to make them independent.
14782
   */
14783
  if (p->next != NULL) {
14784
    struct pbuf *q = p->next;
14785
    for (; q != NULL; q = q->next) pbuf_ref(q);
14786
  }
14787
  mgos_lock();
14788
  if (cs->rx_chain == NULL) {
14789
    cs->rx_offset = 0;
14790
  } else if (pbuf_clen(cs->rx_chain) >= 4) {
14791
    /* ESP SDK has a limited pool of 5 pbufs. We must not hog them all or RX
14792
     * will be completely blocked. We already have at least 4 in the chain,
14793
     * this one is, so we have to make a copy and release this one. */
14794
    struct pbuf *np = pbuf_alloc(PBUF_RAW, p->tot_len, PBUF_RAM);
14795
    if (np != NULL) {
14796
      pbuf_copy(np, p);
14797
      pbuf_free(p);
14798
      p = np;
14799
    }
14800
  }
14801
  mgos_unlock();
14802
  mg_lwip_recv_common(nc, p);
14803
  return ERR_OK;
14804
}
14805

    
14806
static void mg_lwip_consume_rx_chain_tcp(struct mg_connection *nc) {
14807
  struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
14808
  if (cs->rx_chain == NULL) return;
14809
#if MG_ENABLE_SSL
14810
  if (nc->flags & MG_F_SSL) {
14811
    if (nc->flags & MG_F_SSL_HANDSHAKE_DONE) {
14812
      mg_lwip_ssl_recv(nc);
14813
    } else {
14814
      mg_lwip_ssl_do_hs(nc);
14815
    }
14816
    return;
14817
  }
14818
#endif
14819
  mgos_lock();
14820
  while (cs->rx_chain != NULL && nc->recv_mbuf.len < nc->recv_mbuf_limit) {
14821
    struct pbuf *seg = cs->rx_chain;
14822

    
14823
    size_t seg_len = (seg->len - cs->rx_offset);
14824
    size_t buf_avail = (nc->recv_mbuf_limit - nc->recv_mbuf.len);
14825
    size_t len = MIN(seg_len, buf_avail);
14826

    
14827
    char *data = (char *) MG_MALLOC(len);
14828
    if (data == NULL) {
14829
      mgos_unlock();
14830
      DBG(("OOM"));
14831
      return;
14832
    }
14833
    pbuf_copy_partial(seg, data, len, cs->rx_offset);
14834
    cs->rx_offset += len;
14835
    if (cs->rx_offset == cs->rx_chain->len) {
14836
      cs->rx_chain = pbuf_dechain(cs->rx_chain);
14837
      pbuf_free(seg);
14838
      cs->rx_offset = 0;
14839
    }
14840
    mgos_unlock();
14841
    mg_if_recv_tcp_cb(nc, data, len, 1 /* own */);
14842
    mgos_lock();
14843
  }
14844
  mgos_unlock();
14845
}
14846

    
14847
static void mg_lwip_handle_recv_tcp(struct mg_connection *nc) {
14848
  mg_lwip_consume_rx_chain_tcp(nc);
14849

    
14850
  if (nc->send_mbuf.len > 0) {
14851
    mg_lwip_mgr_schedule_poll(nc->mgr);
14852
  }
14853
}
14854

    
14855
static err_t mg_lwip_tcp_sent_cb(void *arg, struct tcp_pcb *tpcb,
14856
                                 u16_t num_sent) {
14857
  struct mg_connection *nc = (struct mg_connection *) arg;
14858
  DBG(("%p %p %u %p %p", nc, tpcb, num_sent, tpcb->unsent, tpcb->unacked));
14859
  if (nc == NULL) return ERR_OK;
14860
  if ((nc->flags & MG_F_SEND_AND_CLOSE) && !(nc->flags & MG_F_WANT_WRITE) &&
14861
      nc->send_mbuf.len == 0 && tpcb->unsent == NULL && tpcb->unacked == NULL) {
14862
    mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc);
14863
  }
14864
  return ERR_OK;
14865
}
14866

    
14867
struct mg_lwip_if_connect_tcp_ctx {
14868
  struct mg_connection *nc;
14869
  const union socket_address *sa;
14870
};
14871

    
14872
static void mg_lwip_if_connect_tcp_tcpip(void *arg) {
14873
  struct mg_lwip_if_connect_tcp_ctx *ctx =
14874
      (struct mg_lwip_if_connect_tcp_ctx *) arg;
14875
  struct mg_connection *nc = ctx->nc;
14876
  const union socket_address *sa = ctx->sa;
14877

    
14878
  struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
14879
  struct tcp_pcb *tpcb = TCP_NEW();
14880
  cs->pcb.tcp = tpcb;
14881
  ip_addr_t *ip = (ip_addr_t *) &sa->sin.sin_addr.s_addr;
14882
  u16_t port = ntohs(sa->sin.sin_port);
14883
  tcp_arg(tpcb, nc);
14884
  tcp_err(tpcb, mg_lwip_tcp_error_cb);
14885
  tcp_sent(tpcb, mg_lwip_tcp_sent_cb);
14886
  tcp_recv(tpcb, mg_lwip_tcp_recv_cb);
14887
  cs->err = TCP_BIND(tpcb, IP_ADDR_ANY, 0 /* any port */);
14888
  DBG(("%p tcp_bind = %d", nc, cs->err));
14889
  if (cs->err != ERR_OK) {
14890
    mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc);
14891
    return;
14892
  }
14893
  cs->err = tcp_connect(tpcb, ip, port, mg_lwip_tcp_conn_cb);
14894
  DBG(("%p tcp_connect %p = %d", nc, tpcb, cs->err));
14895
  if (cs->err != ERR_OK) {
14896
    mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc);
14897
    return;
14898
  }
14899
}
14900

    
14901
void mg_lwip_if_connect_tcp(struct mg_connection *nc,
14902
                            const union socket_address *sa) {
14903
  struct mg_lwip_if_connect_tcp_ctx ctx = {.nc = nc, .sa = sa};
14904
  tcpip_callback(mg_lwip_if_connect_tcp_tcpip, &ctx);
14905
}
14906

    
14907
/*
14908
 * Lwip included in the SDKs for nRF5x chips has different type for the
14909
 * callback of `udp_recv()`
14910
 */
14911
#if ((LWIP_VERSION_MAJOR << 8) | LWIP_VERSION_MINOR) >= 0x0105
14912
static void mg_lwip_udp_recv_cb(void *arg, struct udp_pcb *pcb, struct pbuf *p,
14913
                                const ip_addr_t *addr, u16_t port)
14914
#else
14915
static void mg_lwip_udp_recv_cb(void *arg, struct udp_pcb *pcb, struct pbuf *p,
14916
                                ip_addr_t *addr, u16_t port)
14917
#endif
14918
{
14919
  struct mg_connection *nc = (struct mg_connection *) arg;
14920
  DBG(("%p %s:%u %p %u %u", nc, IPADDR_NTOA(addr), port, p, p->ref, p->len));
14921
  /* Put address in a separate pbuf and tack it onto the packet. */
14922
  struct pbuf *sap =
14923
      pbuf_alloc(PBUF_RAW, sizeof(union socket_address), PBUF_RAM);
14924
  if (sap == NULL) {
14925
    pbuf_free(p);
14926
    return;
14927
  }
14928
  union socket_address *sa = (union socket_address *) sap->payload;
14929
#if ((LWIP_VERSION_MAJOR << 8) | LWIP_VERSION_MINOR) >= 0x0105
14930
  sa->sin.sin_addr.s_addr = ip_2_ip4(addr)->addr;
14931
#else
14932
  sa->sin.sin_addr.s_addr = addr->addr;
14933
#endif
14934
  sa->sin.sin_port = htons(port);
14935
  /* Logic in the recv handler requires that there be exactly one data pbuf. */
14936
  p = pbuf_coalesce(p, PBUF_RAW);
14937
  pbuf_chain(sap, p);
14938
  mg_lwip_recv_common(nc, sap);
14939
  (void) pcb;
14940
}
14941

    
14942
static void mg_lwip_recv_common(struct mg_connection *nc, struct pbuf *p) {
14943
  struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
14944
  mgos_lock();
14945
  if (cs->rx_chain == NULL) {
14946
    cs->rx_chain = p;
14947
  } else {
14948
    pbuf_chain(cs->rx_chain, p);
14949
  }
14950
  if (!cs->recv_pending) {
14951
    cs->recv_pending = 1;
14952
    mg_lwip_post_signal(MG_SIG_RECV, nc);
14953
  }
14954
  mgos_unlock();
14955
}
14956

    
14957
static void mg_lwip_handle_recv_udp(struct mg_connection *nc) {
14958
  struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
14959
  /*
14960
   * For UDP, RX chain consists of interleaved address and packet bufs:
14961
   * Address pbuf followed by exactly one data pbuf (recv_cb took care of that).
14962
   */
14963
  while (cs->rx_chain != NULL) {
14964
    struct pbuf *sap = cs->rx_chain;
14965
    struct pbuf *p = sap->next;
14966
    cs->rx_chain = pbuf_dechain(p);
14967
    size_t data_len = p->len;
14968
    char *data = (char *) MG_MALLOC(data_len);
14969
    if (data != NULL) {
14970
      pbuf_copy_partial(p, data, data_len, 0);
14971
      pbuf_free(p);
14972
      mg_if_recv_udp_cb(nc, data, data_len,
14973
                        (union socket_address *) sap->payload, sap->len);
14974
      pbuf_free(sap);
14975
    } else {
14976
      pbuf_free(p);
14977
      pbuf_free(sap);
14978
    }
14979
  }
14980
}
14981

    
14982
static void mg_lwip_if_connect_udp_tcpip(void *arg) {
14983
  struct mg_connection *nc = (struct mg_connection *) arg;
14984
  struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
14985
  struct udp_pcb *upcb = udp_new();
14986
  cs->err = UDP_BIND(upcb, IP_ADDR_ANY, 0 /* any port */);
14987
  DBG(("%p udp_bind %p = %d", nc, upcb, cs->err));
14988
  if (cs->err == ERR_OK) {
14989
    udp_recv(upcb, mg_lwip_udp_recv_cb, nc);
14990
    cs->pcb.udp = upcb;
14991
  } else {
14992
    udp_remove(upcb);
14993
  }
14994
  mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc);
14995
}
14996

    
14997
void mg_lwip_if_connect_udp(struct mg_connection *nc) {
14998
  tcpip_callback(mg_lwip_if_connect_udp_tcpip, nc);
14999
}
15000

    
15001
void mg_lwip_accept_conn(struct mg_connection *nc, struct tcp_pcb *tpcb) {
15002
  union socket_address sa;
15003
  SET_ADDR(&sa, &tpcb->remote_ip);
15004
  sa.sin.sin_port = htons(tpcb->remote_port);
15005
  mg_if_accept_tcp_cb(nc, &sa, sizeof(sa.sin));
15006
}
15007

    
15008
static void tcp_close_tcpip(void *arg) {
15009
  tcp_close((struct tcp_pcb *) arg);
15010
}
15011

    
15012
void mg_lwip_handle_accept(struct mg_connection *nc) {
15013
  struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
15014
  if (cs->pcb.tcp == NULL) return;
15015
#if MG_ENABLE_SSL
15016
  if (cs->lc->flags & MG_F_SSL) {
15017
    if (mg_ssl_if_conn_accept(nc, cs->lc) != MG_SSL_OK) {
15018
      LOG(LL_ERROR, ("SSL error"));
15019
      tcpip_callback(tcp_close_tcpip, cs->pcb.tcp);
15020
    }
15021
  } else
15022
#endif
15023
  {
15024
    mg_lwip_accept_conn(nc, cs->pcb.tcp);
15025
  }
15026
}
15027

    
15028
static err_t mg_lwip_accept_cb(void *arg, struct tcp_pcb *newtpcb, err_t err) {
15029
  struct mg_connection *lc = (struct mg_connection *) arg, *nc;
15030
  struct mg_lwip_conn_state *lcs, *cs;
15031
  struct tcp_pcb_listen *lpcb;
15032
  LOG(LL_DEBUG,
15033
      ("%p conn %p from %s:%u", lc, newtpcb,
15034
       IPADDR_NTOA(ipX_2_ip(&newtpcb->remote_ip)), newtpcb->remote_port));
15035
  if (lc == NULL) {
15036
    tcp_abort(newtpcb);
15037
    return ERR_ABRT;
15038
  }
15039
  lcs = (struct mg_lwip_conn_state *) lc->sock;
15040
  lpcb = (struct tcp_pcb_listen *) lcs->pcb.tcp;
15041
#if TCP_LISTEN_BACKLOG
15042
  tcp_accepted(lpcb);
15043
#endif
15044
  nc = mg_if_accept_new_conn(lc);
15045
  if (nc == NULL) {
15046
    tcp_abort(newtpcb);
15047
    return ERR_ABRT;
15048
  }
15049
  cs = (struct mg_lwip_conn_state *) nc->sock;
15050
  cs->lc = lc;
15051
  cs->pcb.tcp = newtpcb;
15052
  /* We need to set up callbacks before returning because data may start
15053
   * arriving immediately. */
15054
  tcp_arg(newtpcb, nc);
15055
  tcp_err(newtpcb, mg_lwip_tcp_error_cb);
15056
  tcp_sent(newtpcb, mg_lwip_tcp_sent_cb);
15057
  tcp_recv(newtpcb, mg_lwip_tcp_recv_cb);
15058
#if LWIP_TCP_KEEPALIVE
15059
  mg_lwip_set_keepalive_params(nc, 60, 10, 6);
15060
#endif
15061
  mg_lwip_post_signal(MG_SIG_ACCEPT, nc);
15062
  (void) err;
15063
  (void) lpcb;
15064
  return ERR_OK;
15065
}
15066

    
15067
struct mg_lwip_if_listen_ctx {
15068
  struct mg_connection *nc;
15069
  union socket_address *sa;
15070
  int ret;
15071
};
15072

    
15073
static void mg_lwip_if_listen_tcp_tcpip(void *arg) {
15074
  struct mg_lwip_if_listen_ctx *ctx = (struct mg_lwip_if_listen_ctx *) arg;
15075
  struct mg_connection *nc = ctx->nc;
15076
  union socket_address *sa = ctx->sa;
15077
  struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
15078
  struct tcp_pcb *tpcb = TCP_NEW();
15079
  ip_addr_t *ip = (ip_addr_t *) &sa->sin.sin_addr.s_addr;
15080
  u16_t port = ntohs(sa->sin.sin_port);
15081
  cs->err = TCP_BIND(tpcb, ip, port);
15082
  DBG(("%p tcp_bind(%s:%u) = %d", nc, IPADDR_NTOA(ip), port, cs->err));
15083
  if (cs->err != ERR_OK) {
15084
    tcp_close(tpcb);
15085
    ctx->ret = -1;
15086
    return;
15087
  }
15088
  tcp_arg(tpcb, nc);
15089
  tpcb = tcp_listen(tpcb);
15090
  cs->pcb.tcp = tpcb;
15091
  tcp_accept(tpcb, mg_lwip_accept_cb);
15092
  ctx->ret = 0;
15093
}
15094

    
15095
int mg_lwip_if_listen_tcp(struct mg_connection *nc, union socket_address *sa) {
15096
  struct mg_lwip_if_listen_ctx ctx = {.nc = nc, .sa = sa};
15097
  tcpip_callback(mg_lwip_if_listen_tcp_tcpip, &ctx);
15098
  return ctx.ret;
15099
}
15100

    
15101
static void mg_lwip_if_listen_udp_tcpip(void *arg) {
15102
  struct mg_lwip_if_listen_ctx *ctx = (struct mg_lwip_if_listen_ctx *) arg;
15103
  struct mg_connection *nc = ctx->nc;
15104
  union socket_address *sa = ctx->sa;
15105
  struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
15106
  struct udp_pcb *upcb = udp_new();
15107
  ip_addr_t *ip = (ip_addr_t *) &sa->sin.sin_addr.s_addr;
15108
  u16_t port = ntohs(sa->sin.sin_port);
15109
  cs->err = UDP_BIND(upcb, ip, port);
15110
  DBG(("%p udb_bind(%s:%u) = %d", nc, IPADDR_NTOA(ip), port, cs->err));
15111
  if (cs->err != ERR_OK) {
15112
    udp_remove(upcb);
15113
    ctx->ret = -1;
15114
  } else {
15115
    udp_recv(upcb, mg_lwip_udp_recv_cb, nc);
15116
    cs->pcb.udp = upcb;
15117
    ctx->ret = 0;
15118
  }
15119
}
15120

    
15121
int mg_lwip_if_listen_udp(struct mg_connection *nc, union socket_address *sa) {
15122
  struct mg_lwip_if_listen_ctx ctx = {.nc = nc, .sa = sa};
15123
  tcpip_callback(mg_lwip_if_listen_udp_tcpip, &ctx);
15124
  return ctx.ret;
15125
}
15126

    
15127
struct mg_lwip_tcp_write_ctx {
15128
  struct mg_connection *nc;
15129
  const void *data;
15130
  uint16_t len;
15131
  int ret;
15132
};
15133

    
15134
static void tcp_output_tcpip(void *arg) {
15135
  tcp_output((struct tcp_pcb *) arg);
15136
}
15137

    
15138
static void mg_lwip_tcp_write_tcpip(void *arg) {
15139
  struct mg_lwip_tcp_write_ctx *ctx = (struct mg_lwip_tcp_write_ctx *) arg;
15140
  struct mg_connection *nc = ctx->nc;
15141
  struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
15142
  struct tcp_pcb *tpcb = cs->pcb.tcp;
15143
  size_t len = MIN(tpcb->mss, MIN(ctx->len, tpcb->snd_buf));
15144
  size_t unsent, unacked;
15145
  if (len == 0) {
15146
    DBG(("%p no buf avail %u %u %p %p", tpcb, tpcb->snd_buf, tpcb->snd_queuelen,
15147
         tpcb->unsent, tpcb->unacked));
15148
    tcpip_callback(tcp_output_tcpip, tpcb);
15149
    ctx->ret = 0;
15150
    return;
15151
  }
15152
  unsent = (tpcb->unsent != NULL ? tpcb->unsent->len : 0);
15153
  unacked = (tpcb->unacked != NULL ? tpcb->unacked->len : 0);
15154
/*
15155
 * On ESP8266 we only allow one TCP segment in flight at any given time.
15156
 * This may increase latency and reduce efficiency of tcp windowing,
15157
 * but memory is scarce and precious on that platform so we do this to
15158
 * reduce footprint.
15159
 */
15160
#if CS_PLATFORM == CS_P_ESP8266
15161
  if (unacked > 0) {
15162
    ctx->ret = 0;
15163
    return;
15164
  }
15165
  len = MIN(len, (TCP_MSS - unsent));
15166
#endif
15167
  cs->err = tcp_write(tpcb, ctx->data, len, TCP_WRITE_FLAG_COPY);
15168
  unsent = (tpcb->unsent != NULL ? tpcb->unsent->len : 0);
15169
  unacked = (tpcb->unacked != NULL ? tpcb->unacked->len : 0);
15170
  DBG(("%p tcp_write %u = %d, %u %u", tpcb, len, cs->err, unsent, unacked));
15171
  if (cs->err != ERR_OK) {
15172
    /*
15173
     * We ignore ERR_MEM because memory will be freed up when the data is sent
15174
     * and we'll retry.
15175
     */
15176
    ctx->ret = (cs->err == ERR_MEM ? 0 : -1);
15177
    return;
15178
  }
15179
  ctx->ret = len;
15180
}
15181

    
15182
static int mg_lwip_tcp_write(struct mg_connection *nc, const void *data,
15183
                             uint16_t len) {
15184
  struct mg_lwip_tcp_write_ctx ctx = {.nc = nc, .data = data, .len = len};
15185
  struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
15186
  struct tcp_pcb *tpcb = cs->pcb.tcp;
15187
  if (tpcb == NULL) {
15188
    return -1;
15189
  }
15190
  tcpip_callback(mg_lwip_tcp_write_tcpip, &ctx);
15191
  return ctx.ret;
15192
}
15193

    
15194
struct udp_sendto_ctx {
15195
  struct udp_pcb *upcb;
15196
  struct pbuf *p;
15197
  ip_addr_t *ip;
15198
  uint16_t port;
15199
  int ret;
15200
};
15201

    
15202
static void udp_sendto_tcpip(void *arg) {
15203
  struct udp_sendto_ctx *ctx = (struct udp_sendto_ctx *) arg;
15204
  ctx->ret = udp_sendto(ctx->upcb, ctx->p, ctx->ip, ctx->port);
15205
}
15206

    
15207
static int mg_lwip_udp_send(struct mg_connection *nc, const void *data,
15208
                            uint16_t len) {
15209
  struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
15210
  if (cs->pcb.udp == NULL) {
15211
    /*
15212
     * In case of UDP, this usually means, what
15213
     * async DNS resolve is still in progress and connection
15214
     * is not ready yet
15215
     */
15216
    DBG(("%p socket is not connected", nc));
15217
    return -1;
15218
  }
15219
  struct udp_pcb *upcb = cs->pcb.udp;
15220
  struct pbuf *p = pbuf_alloc(PBUF_TRANSPORT, len, PBUF_RAM);
15221
#if defined(LWIP_IPV4) && LWIP_IPV4 && defined(LWIP_IPV6) && LWIP_IPV6
15222
  ip_addr_t ip = {.u_addr.ip4.addr = nc->sa.sin.sin_addr.s_addr, .type = 0};
15223
#else
15224
  ip_addr_t ip = {.addr = nc->sa.sin.sin_addr.s_addr};
15225
#endif
15226
  u16_t port = ntohs(nc->sa.sin.sin_port);
15227
  if (p == NULL) {
15228
    DBG(("OOM"));
15229
    return 0;
15230
  }
15231
  memcpy(p->payload, data, len);
15232
  struct udp_sendto_ctx ctx = {.upcb = upcb, .p = p, .ip = &ip, .port = port};
15233
  tcpip_callback(udp_sendto_tcpip, &ctx);
15234
  cs->err = ctx.ret;
15235
  pbuf_free(p);
15236
  return (cs->err == ERR_OK ? len : -1);
15237
}
15238

    
15239
static void mg_lwip_send_more(struct mg_connection *nc) {
15240
  int num_sent = 0;
15241
  if (nc->sock == INVALID_SOCKET) return;
15242
  if (nc->flags & MG_F_UDP) {
15243
    num_sent = mg_lwip_udp_send(nc, nc->send_mbuf.buf, nc->send_mbuf.len);
15244
    DBG(("%p mg_lwip_udp_send %u = %d", nc, nc->send_mbuf.len, num_sent));
15245
  } else {
15246
    num_sent = mg_lwip_tcp_write(nc, nc->send_mbuf.buf, nc->send_mbuf.len);
15247
    DBG(("%p mg_lwip_tcp_write %u = %d", nc, nc->send_mbuf.len, num_sent));
15248
  }
15249
  if (num_sent == 0) return;
15250
  if (num_sent > 0) {
15251
    mg_if_sent_cb(nc, num_sent);
15252
  } else {
15253
    mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc);
15254
  }
15255
}
15256

    
15257
void mg_lwip_if_tcp_send(struct mg_connection *nc, const void *buf,
15258
                         size_t len) {
15259
  mbuf_append(&nc->send_mbuf, buf, len);
15260
  mg_lwip_mgr_schedule_poll(nc->mgr);
15261
}
15262

    
15263
void mg_lwip_if_udp_send(struct mg_connection *nc, const void *buf,
15264
                         size_t len) {
15265
  mbuf_append(&nc->send_mbuf, buf, len);
15266
  mg_lwip_mgr_schedule_poll(nc->mgr);
15267
}
15268

    
15269
struct tcp_recved_ctx {
15270
  struct tcp_pcb *tpcb;
15271
  size_t len;
15272
};
15273

    
15274
void tcp_recved_tcpip(void *arg) {
15275
  struct tcp_recved_ctx *ctx = (struct tcp_recved_ctx *) arg;
15276
  tcp_recved(ctx->tpcb, ctx->len);
15277
}
15278

    
15279
void mg_lwip_if_recved(struct mg_connection *nc, size_t len) {
15280
  if (nc->flags & MG_F_UDP) return;
15281
  struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
15282
  if (nc->sock == INVALID_SOCKET || cs->pcb.tcp == NULL) {
15283
    DBG(("%p invalid socket", nc));
15284
    return;
15285
  }
15286
  DBG(("%p %p %u %u", nc, cs->pcb.tcp, len,
15287
       (cs->rx_chain ? cs->rx_chain->tot_len : 0)));
15288
  struct tcp_recved_ctx ctx = {.tpcb = cs->pcb.tcp, .len = len};
15289
#if MG_ENABLE_SSL
15290
  if (!(nc->flags & MG_F_SSL)) {
15291
    tcpip_callback(tcp_recved_tcpip, &ctx);
15292
  } else {
15293
    /* Currently SSL acknowledges data immediately.
15294
     * TODO(rojer): Find a way to propagate mg_lwip_if_recved. */
15295
  }
15296
#else
15297
  tcpip_callback(tcp_recved_tcpip, &ctx);
15298
#endif
15299
  mbuf_trim(&nc->recv_mbuf);
15300
}
15301

    
15302
int mg_lwip_if_create_conn(struct mg_connection *nc) {
15303
  struct mg_lwip_conn_state *cs =
15304
      (struct mg_lwip_conn_state *) MG_CALLOC(1, sizeof(*cs));
15305
  if (cs == NULL) return 0;
15306
  cs->nc = nc;
15307
  nc->sock = (intptr_t) cs;
15308
  return 1;
15309
}
15310

    
15311
static void udp_remove_tcpip(void *arg) {
15312
  udp_remove((struct udp_pcb *) arg);
15313
}
15314

    
15315
void mg_lwip_if_destroy_conn(struct mg_connection *nc) {
15316
  if (nc->sock == INVALID_SOCKET) return;
15317
  struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
15318
  if (!(nc->flags & MG_F_UDP)) {
15319
    struct tcp_pcb *tpcb = cs->pcb.tcp;
15320
    if (tpcb != NULL) {
15321
      tcp_arg(tpcb, NULL);
15322
      DBG(("%p tcp_close %p", nc, tpcb));
15323
      tcp_arg(tpcb, NULL);
15324
      tcpip_callback(tcp_close_tcpip, tpcb);
15325
    }
15326
    while (cs->rx_chain != NULL) {
15327
      struct pbuf *seg = cs->rx_chain;
15328
      cs->rx_chain = pbuf_dechain(cs->rx_chain);
15329
      pbuf_free(seg);
15330
    }
15331
    memset(cs, 0, sizeof(*cs));
15332
    MG_FREE(cs);
15333
  } else if (nc->listener == NULL) {
15334
    /* Only close outgoing UDP pcb or listeners. */
15335
    struct udp_pcb *upcb = cs->pcb.udp;
15336
    if (upcb != NULL) {
15337
      DBG(("%p udp_remove %p", nc, upcb));
15338
      tcpip_callback(udp_remove_tcpip, upcb);
15339
    }
15340
    memset(cs, 0, sizeof(*cs));
15341
    MG_FREE(cs);
15342
  }
15343
  nc->sock = INVALID_SOCKET;
15344
}
15345

    
15346
void mg_lwip_if_get_conn_addr(struct mg_connection *nc, int remote,
15347
                              union socket_address *sa) {
15348
  memset(sa, 0, sizeof(*sa));
15349
  if (nc == NULL || nc->sock == INVALID_SOCKET) return;
15350
  struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
15351
  if (nc->flags & MG_F_UDP) {
15352
    struct udp_pcb *upcb = cs->pcb.udp;
15353
    if (remote) {
15354
      memcpy(sa, &nc->sa, sizeof(*sa));
15355
    } else if (upcb != NULL) {
15356
      sa->sin.sin_port = htons(upcb->local_port);
15357
      SET_ADDR(sa, &upcb->local_ip);
15358
    }
15359
  } else {
15360
    struct tcp_pcb *tpcb = cs->pcb.tcp;
15361
    if (remote) {
15362
      memcpy(sa, &nc->sa, sizeof(*sa));
15363
    } else if (tpcb != NULL) {
15364
      sa->sin.sin_port = htons(tpcb->local_port);
15365
      SET_ADDR(sa, &tpcb->local_ip);
15366
    }
15367
  }
15368
}
15369

    
15370
void mg_lwip_if_sock_set(struct mg_connection *nc, sock_t sock) {
15371
  nc->sock = sock;
15372
}
15373

    
15374
/* clang-format off */
15375
#define MG_LWIP_IFACE_VTABLE                                          \
15376
  {                                                                   \
15377
    mg_lwip_if_init,                                                  \
15378
    mg_lwip_if_free,                                                  \
15379
    mg_lwip_if_add_conn,                                              \
15380
    mg_lwip_if_remove_conn,                                           \
15381
    mg_lwip_if_poll,                                                  \
15382
    mg_lwip_if_listen_tcp,                                            \
15383
    mg_lwip_if_listen_udp,                                            \
15384
    mg_lwip_if_connect_tcp,                                           \
15385
    mg_lwip_if_connect_udp,                                           \
15386
    mg_lwip_if_tcp_send,                                              \
15387
    mg_lwip_if_udp_send,                                              \
15388
    mg_lwip_if_recved,                                                \
15389
    mg_lwip_if_create_conn,                                           \
15390
    mg_lwip_if_destroy_conn,                                          \
15391
    mg_lwip_if_sock_set,                                              \
15392
    mg_lwip_if_get_conn_addr,                                         \
15393
  }
15394
/* clang-format on */
15395

    
15396
const struct mg_iface_vtable mg_lwip_iface_vtable = MG_LWIP_IFACE_VTABLE;
15397
#if MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL
15398
const struct mg_iface_vtable mg_default_iface_vtable = MG_LWIP_IFACE_VTABLE;
15399
#endif
15400

    
15401
#endif /* MG_ENABLE_NET_IF_LWIP_LOW_LEVEL */
15402
#ifdef MG_MODULE_LINES
15403
#line 1 "common/platforms/lwip/mg_lwip_ev_mgr.c"
15404
#endif
15405
/*
15406
 * Copyright (c) 2014-2016 Cesanta Software Limited
15407
 * All rights reserved
15408
 */
15409

    
15410
#if MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL
15411

    
15412
#ifndef MG_SIG_QUEUE_LEN
15413
#define MG_SIG_QUEUE_LEN 32
15414
#endif
15415

    
15416
struct mg_ev_mgr_lwip_signal {
15417
  int sig;
15418
  struct mg_connection *nc;
15419
};
15420

    
15421
struct mg_ev_mgr_lwip_data {
15422
  struct mg_ev_mgr_lwip_signal sig_queue[MG_SIG_QUEUE_LEN];
15423
  int sig_queue_len;
15424
  int start_index;
15425
};
15426

    
15427
void mg_lwip_post_signal(enum mg_sig_type sig, struct mg_connection *nc) {
15428
  struct mg_ev_mgr_lwip_data *md =
15429
      (struct mg_ev_mgr_lwip_data *) nc->iface->data;
15430
  mgos_lock();
15431
  if (md->sig_queue_len >= MG_SIG_QUEUE_LEN) {
15432
    mgos_unlock();
15433
    return;
15434
  }
15435
  int end_index = (md->start_index + md->sig_queue_len) % MG_SIG_QUEUE_LEN;
15436
  md->sig_queue[end_index].sig = sig;
15437
  md->sig_queue[end_index].nc = nc;
15438
  md->sig_queue_len++;
15439
  mg_lwip_mgr_schedule_poll(nc->mgr);
15440
  mgos_unlock();
15441
}
15442

    
15443
void mg_ev_mgr_lwip_process_signals(struct mg_mgr *mgr) {
15444
  struct mg_ev_mgr_lwip_data *md =
15445
      (struct mg_ev_mgr_lwip_data *) mgr->ifaces[MG_MAIN_IFACE]->data;
15446
  while (md->sig_queue_len > 0) {
15447
    mgos_lock();
15448
    int sig = md->sig_queue[md->start_index].sig;
15449
    struct mg_connection *nc = md->sig_queue[md->start_index].nc;
15450
    struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
15451
    md->start_index = (md->start_index + 1) % MG_SIG_QUEUE_LEN;
15452
    md->sig_queue_len--;
15453
    mgos_unlock();
15454
    if (nc->iface == NULL || nc->mgr == NULL) continue;
15455
    switch (sig) {
15456
      case MG_SIG_CONNECT_RESULT: {
15457
#if MG_ENABLE_SSL
15458
        if (cs->err == 0 && (nc->flags & MG_F_SSL) &&
15459
            !(nc->flags & MG_F_SSL_HANDSHAKE_DONE)) {
15460
          mg_lwip_ssl_do_hs(nc);
15461
        } else
15462
#endif
15463
        {
15464
          mg_if_connect_cb(nc, cs->err);
15465
        }
15466
        break;
15467
      }
15468
      case MG_SIG_CLOSE_CONN: {
15469
        nc->flags |= MG_F_SEND_AND_CLOSE;
15470
        mg_close_conn(nc);
15471
        break;
15472
      }
15473
      case MG_SIG_RECV: {
15474
        cs->recv_pending = 0;
15475
        if (nc->flags & MG_F_UDP) {
15476
          mg_lwip_handle_recv_udp(nc);
15477
        } else {
15478
          mg_lwip_handle_recv_tcp(nc);
15479
        }
15480
        break;
15481
      }
15482
      case MG_SIG_TOMBSTONE: {
15483
        break;
15484
      }
15485
      case MG_SIG_ACCEPT: {
15486
        mg_lwip_handle_accept(nc);
15487
        break;
15488
      }
15489
    }
15490
  }
15491
}
15492

    
15493
void mg_lwip_if_init(struct mg_iface *iface) {
15494
  LOG(LL_INFO, ("%p Mongoose init", iface));
15495
  iface->data = MG_CALLOC(1, sizeof(struct mg_ev_mgr_lwip_data));
15496
}
15497

    
15498
void mg_lwip_if_free(struct mg_iface *iface) {
15499
  MG_FREE(iface->data);
15500
  iface->data = NULL;
15501
}
15502

    
15503
void mg_lwip_if_add_conn(struct mg_connection *nc) {
15504
  (void) nc;
15505
}
15506

    
15507
void mg_lwip_if_remove_conn(struct mg_connection *nc) {
15508
  struct mg_ev_mgr_lwip_data *md =
15509
      (struct mg_ev_mgr_lwip_data *) nc->iface->data;
15510
  /* Walk the queue and null-out further signals for this conn. */
15511
  for (int i = 0; i < MG_SIG_QUEUE_LEN; i++) {
15512
    if (md->sig_queue[i].nc == nc) {
15513
      md->sig_queue[i].sig = MG_SIG_TOMBSTONE;
15514
    }
15515
  }
15516
}
15517

    
15518
time_t mg_lwip_if_poll(struct mg_iface *iface, int timeout_ms) {
15519
  struct mg_mgr *mgr = iface->mgr;
15520
  int n = 0;
15521
  double now = mg_time();
15522
  struct mg_connection *nc, *tmp;
15523
  double min_timer = 0;
15524
  int num_timers = 0;
15525
#if 0
15526
  DBG(("begin poll @%u", (unsigned int) (now * 1000)));
15527
#endif
15528
  mg_ev_mgr_lwip_process_signals(mgr);
15529
  for (nc = mgr->active_connections; nc != NULL; nc = tmp) {
15530
    struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
15531
    tmp = nc->next;
15532
    n++;
15533
    if ((nc->flags & MG_F_CLOSE_IMMEDIATELY) ||
15534
        ((nc->flags & MG_F_SEND_AND_CLOSE) && (nc->flags & MG_F_UDP) &&
15535
         (nc->send_mbuf.len == 0))) {
15536
      mg_close_conn(nc);
15537
      continue;
15538
    }
15539
    mg_if_poll(nc, now);
15540
    mg_if_timer(nc, now);
15541
#if MG_ENABLE_SSL
15542
    if ((nc->flags & MG_F_SSL) && cs != NULL && cs->pcb.tcp != NULL &&
15543
        cs->pcb.tcp->state == ESTABLISHED) {
15544
      if (((nc->flags & MG_F_WANT_WRITE) ||
15545
           ((nc->send_mbuf.len > 0) &&
15546
            (nc->flags & MG_F_SSL_HANDSHAKE_DONE))) &&
15547
          cs->pcb.tcp->snd_buf > 0) {
15548
        /* Can write more. */
15549
        if (nc->flags & MG_F_SSL_HANDSHAKE_DONE) {
15550
          if (!(nc->flags & MG_F_CONNECTING)) mg_lwip_ssl_send(nc);
15551
        } else {
15552
          mg_lwip_ssl_do_hs(nc);
15553
        }
15554
      }
15555
      if (cs->rx_chain != NULL || (nc->flags & MG_F_WANT_READ)) {
15556
        if (nc->flags & MG_F_SSL_HANDSHAKE_DONE) {
15557
          if (!(nc->flags & MG_F_CONNECTING)) mg_lwip_ssl_recv(nc);
15558
        } else {
15559
          mg_lwip_ssl_do_hs(nc);
15560
        }
15561
      }
15562
    } else
15563
#endif /* MG_ENABLE_SSL */
15564
    {
15565
      if (nc->send_mbuf.len > 0 && !(nc->flags & MG_F_CONNECTING)) {
15566
        mg_lwip_send_more(nc);
15567
      }
15568
    }
15569
    if (nc->sock != INVALID_SOCKET &&
15570
        !(nc->flags & (MG_F_UDP | MG_F_LISTENING)) && cs->pcb.tcp != NULL &&
15571
        cs->pcb.tcp->unsent != NULL) {
15572
      tcpip_callback(tcp_output_tcpip, cs->pcb.tcp);
15573
    }
15574
    if (nc->ev_timer_time > 0) {
15575
      if (num_timers == 0 || nc->ev_timer_time < min_timer) {
15576
        min_timer = nc->ev_timer_time;
15577
      }
15578
      num_timers++;
15579
    }
15580

    
15581
    if (nc->sock != INVALID_SOCKET) {
15582
      /* Try to consume data from cs->rx_chain */
15583
      mg_lwip_consume_rx_chain_tcp(nc);
15584

    
15585
      /*
15586
       * If the connection is about to close, and rx_chain is finally empty,
15587
       * send the MG_SIG_CLOSE_CONN signal
15588
       */
15589
      if (cs->draining_rx_chain && cs->rx_chain == NULL) {
15590
        mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc);
15591
      }
15592
    }
15593
  }
15594
#if 0
15595
  DBG(("end poll @%u, %d conns, %d timers (min %u), next in %d ms",
15596
       (unsigned int) (now * 1000), n, num_timers,
15597
       (unsigned int) (min_timer * 1000), timeout_ms));
15598
#endif
15599
  (void) timeout_ms;
15600
  return now;
15601
}
15602

    
15603
uint32_t mg_lwip_get_poll_delay_ms(struct mg_mgr *mgr) {
15604
  struct mg_connection *nc;
15605
  double now;
15606
  double min_timer = 0;
15607
  int num_timers = 0;
15608
  mg_ev_mgr_lwip_process_signals(mgr);
15609
  for (nc = mg_next(mgr, NULL); nc != NULL; nc = mg_next(mgr, nc)) {
15610
    struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
15611
    if (nc->ev_timer_time > 0) {
15612
      if (num_timers == 0 || nc->ev_timer_time < min_timer) {
15613
        min_timer = nc->ev_timer_time;
15614
      }
15615
      num_timers++;
15616
    }
15617
    if (nc->send_mbuf.len > 0
15618
#if MG_ENABLE_SSL
15619
        || (nc->flags & MG_F_WANT_WRITE)
15620
#endif
15621
            ) {
15622
      int can_send = 0;
15623
      /* We have stuff to send, but can we? */
15624
      if (nc->flags & MG_F_UDP) {
15625
        /* UDP is always ready for sending. */
15626
        can_send = (cs->pcb.udp != NULL);
15627
      } else {
15628
        can_send = (cs->pcb.tcp != NULL && cs->pcb.tcp->snd_buf > 0);
15629
      }
15630
      /* We want and can send, request a poll immediately. */
15631
      if (can_send) return 0;
15632
    }
15633
  }
15634
  uint32_t timeout_ms = ~0;
15635
  now = mg_time();
15636
  if (num_timers > 0) {
15637
    /* If we have a timer that is past due, do a poll ASAP. */
15638
    if (min_timer < now) return 0;
15639
    double timer_timeout_ms = (min_timer - now) * 1000 + 1 /* rounding */;
15640
    if (timer_timeout_ms < timeout_ms) {
15641
      timeout_ms = timer_timeout_ms;
15642
    }
15643
  }
15644
  return timeout_ms;
15645
}
15646

    
15647
#endif /* MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL */
15648
#ifdef MG_MODULE_LINES
15649
#line 1 "common/platforms/lwip/mg_lwip_ssl_if.c"
15650
#endif
15651
/*
15652
 * Copyright (c) 2014-2016 Cesanta Software Limited
15653
 * All rights reserved
15654
 */
15655

    
15656
#if MG_ENABLE_SSL && MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL
15657

    
15658
/* Amalgamated: #include "common/mg_mem.h" */
15659
/* Amalgamated: #include "common/cs_dbg.h" */
15660

    
15661
#include <lwip/pbuf.h>
15662
#include <lwip/tcp.h>
15663

    
15664
#ifndef MG_LWIP_SSL_IO_SIZE
15665
#define MG_LWIP_SSL_IO_SIZE 1024
15666
#endif
15667

    
15668
#ifndef MIN
15669
#define MIN(a, b) ((a) < (b) ? (a) : (b))
15670
#endif
15671

    
15672
void mg_lwip_ssl_do_hs(struct mg_connection *nc) {
15673
  struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
15674
  int server_side = (nc->listener != NULL);
15675
  enum mg_ssl_if_result res;
15676
  if (nc->flags & MG_F_CLOSE_IMMEDIATELY) return;
15677
  res = mg_ssl_if_handshake(nc);
15678
  DBG(("%p %lu %d %d", nc, nc->flags, server_side, res));
15679
  if (res != MG_SSL_OK) {
15680
    if (res == MG_SSL_WANT_WRITE) {
15681
      nc->flags |= MG_F_WANT_WRITE;
15682
      cs->err = 0;
15683
    } else if (res == MG_SSL_WANT_READ) {
15684
      /*
15685
       * Nothing to do in particular, we are callback-driven.
15686
       * What we definitely do not need anymore is SSL reading (nothing left).
15687
       */
15688
      nc->flags &= ~MG_F_WANT_READ;
15689
      cs->err = 0;
15690
    } else {
15691
      cs->err = res;
15692
      if (server_side) {
15693
        mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc);
15694
      } else {
15695
        mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc);
15696
      }
15697
    }
15698
  } else {
15699
    cs->err = 0;
15700
    nc->flags &= ~MG_F_WANT_WRITE;
15701
    /*
15702
     * Handshake is done. Schedule a read immediately to consume app data
15703
     * which may already be waiting.
15704
     */
15705
    nc->flags |= (MG_F_SSL_HANDSHAKE_DONE | MG_F_WANT_READ);
15706
    if (server_side) {
15707
      mg_lwip_accept_conn(nc, cs->pcb.tcp);
15708
    } else {
15709
      mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc);
15710
    }
15711
  }
15712
}
15713

    
15714
void mg_lwip_ssl_send(struct mg_connection *nc) {
15715
  if (nc->sock == INVALID_SOCKET) {
15716
    DBG(("%p invalid socket", nc));
15717
    return;
15718
  }
15719
  struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
15720
  /* It's ok if the buffer is empty. Return value of 0 may also be valid. */
15721
  int len = cs->last_ssl_write_size;
15722
  if (len == 0) {
15723
    len = MIN(MG_LWIP_SSL_IO_SIZE, nc->send_mbuf.len);
15724
  }
15725
  int ret = mg_ssl_if_write(nc, nc->send_mbuf.buf, len);
15726
  DBG(("%p SSL_write %u = %d", nc, len, ret));
15727
  if (ret > 0) {
15728
    mg_if_sent_cb(nc, ret);
15729
    cs->last_ssl_write_size = 0;
15730
  } else if (ret < 0) {
15731
    /* This is tricky. We must remember the exact data we were sending to retry
15732
     * exactly the same send next time. */
15733
    cs->last_ssl_write_size = len;
15734
  }
15735
  if (ret == len) {
15736
    nc->flags &= ~MG_F_WANT_WRITE;
15737
  } else if (ret == MG_SSL_WANT_WRITE) {
15738
    nc->flags |= MG_F_WANT_WRITE;
15739
  } else {
15740
    mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc);
15741
  }
15742
}
15743

    
15744
void mg_lwip_ssl_recv(struct mg_connection *nc) {
15745
  struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
15746
  /* Don't deliver data before connect callback */
15747
  if (nc->flags & MG_F_CONNECTING) return;
15748
  while (nc->recv_mbuf.len < nc->recv_mbuf_limit) {
15749
    char *buf = (char *) MG_MALLOC(MG_LWIP_SSL_IO_SIZE);
15750
    if (buf == NULL) return;
15751
    int ret = mg_ssl_if_read(nc, buf, MG_LWIP_SSL_IO_SIZE);
15752
    DBG(("%p %p SSL_read %u = %d", nc, cs->rx_chain, MG_LWIP_SSL_IO_SIZE, ret));
15753
    if (ret <= 0) {
15754
      MG_FREE(buf);
15755
      if (ret == MG_SSL_WANT_WRITE) {
15756
        nc->flags |= MG_F_WANT_WRITE;
15757
        return;
15758
      } else if (ret == MG_SSL_WANT_READ) {
15759
        /*
15760
         * Nothing to do in particular, we are callback-driven.
15761
         * What we definitely do not need anymore is SSL reading (nothing left).
15762
         */
15763
        nc->flags &= ~MG_F_WANT_READ;
15764
        cs->err = 0;
15765
        return;
15766
      } else {
15767
        mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc);
15768
        return;
15769
      }
15770
    } else {
15771
      mg_if_recv_tcp_cb(nc, buf, ret, 1 /* own */);
15772
    }
15773
  }
15774
}
15775

    
15776
#ifdef KR_VERSION
15777

    
15778
ssize_t kr_send(int fd, const void *buf, size_t len) {
15779
  struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) fd;
15780
  int ret = mg_lwip_tcp_write(cs->nc, buf, len);
15781
  DBG(("%p mg_lwip_tcp_write %u = %d", cs->nc, len, ret));
15782
  if (ret == 0) ret = KR_IO_WOULDBLOCK;
15783
  return ret;
15784
}
15785

    
15786
ssize_t kr_recv(int fd, void *buf, size_t len) {
15787
  struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) fd;
15788
  struct pbuf *seg = cs->rx_chain;
15789
  if (seg == NULL) {
15790
    DBG(("%u - nothing to read", len));
15791
    return KR_IO_WOULDBLOCK;
15792
  }
15793
  size_t seg_len = (seg->len - cs->rx_offset);
15794
  DBG(("%u %u %u %u", len, cs->rx_chain->len, seg_len, cs->rx_chain->tot_len));
15795
  len = MIN(len, seg_len);
15796
  pbuf_copy_partial(seg, buf, len, cs->rx_offset);
15797
  cs->rx_offset += len;
15798
  tcp_recved(cs->pcb.tcp, len);
15799
  if (cs->rx_offset == cs->rx_chain->len) {
15800
    cs->rx_chain = pbuf_dechain(cs->rx_chain);
15801
    pbuf_free(seg);
15802
    cs->rx_offset = 0;
15803
  }
15804
  return len;
15805
}
15806

    
15807
#elif MG_SSL_IF == MG_SSL_IF_MBEDTLS
15808

    
15809
int ssl_socket_send(void *ctx, const unsigned char *buf, size_t len) {
15810
  struct mg_connection *nc = (struct mg_connection *) ctx;
15811
  struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
15812
  int ret = mg_lwip_tcp_write(cs->nc, buf, len);
15813
  if (ret == 0) ret = MBEDTLS_ERR_SSL_WANT_WRITE;
15814
  LOG(LL_DEBUG, ("%p %d -> %d", nc, len, ret));
15815
  return ret;
15816
}
15817

    
15818
int ssl_socket_recv(void *ctx, unsigned char *buf, size_t len) {
15819
  struct mg_connection *nc = (struct mg_connection *) ctx;
15820
  struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
15821
  struct pbuf *seg = cs->rx_chain;
15822
  if (seg == NULL) {
15823
    DBG(("%u - nothing to read", len));
15824
    return MBEDTLS_ERR_SSL_WANT_READ;
15825
  }
15826
  size_t seg_len = (seg->len - cs->rx_offset);
15827
  DBG(("%u %u %u %u", len, cs->rx_chain->len, seg_len, cs->rx_chain->tot_len));
15828
  mgos_lock();
15829
  len = MIN(len, seg_len);
15830
  pbuf_copy_partial(seg, buf, len, cs->rx_offset);
15831
  cs->rx_offset += len;
15832
  /* TCP PCB may be NULL if connection has already been closed
15833
   * but we still have data to deliver to SSL. */
15834
  if (cs->pcb.tcp != NULL) tcp_recved(cs->pcb.tcp, len);
15835
  if (cs->rx_offset == cs->rx_chain->len) {
15836
    cs->rx_chain = pbuf_dechain(cs->rx_chain);
15837
    pbuf_free(seg);
15838
    cs->rx_offset = 0;
15839
  }
15840
  mgos_unlock();
15841
  LOG(LL_DEBUG, ("%p <- %d", nc, (int) len));
15842
  return len;
15843
}
15844

    
15845
#endif
15846

    
15847
#endif /* MG_ENABLE_SSL && MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL */
15848
#ifdef MG_MODULE_LINES
15849
#line 1 "common/platforms/wince/wince_libc.c"
15850
#endif
15851
/*
15852
 * Copyright (c) 2016 Cesanta Software Limited
15853
 * All rights reserved
15854
 */
15855

    
15856
#ifdef WINCE
15857

    
15858
const char *strerror(int err) {
15859
  /*
15860
   * TODO(alashkin): there is no strerror on WinCE;
15861
   * look for similar wce_xxxx function
15862
   */
15863
  static char buf[10];
15864
  snprintf(buf, sizeof(buf), "%d", err);
15865
  return buf;
15866
}
15867

    
15868
int open(const char *filename, int oflag, int pmode) {
15869
  /*
15870
   * TODO(alashkin): mg_open function is not used in mongoose
15871
   * but exists in documentation as utility function
15872
   * Shall we delete it at all or implement for WinCE as well?
15873
   */
15874
  DebugBreak();
15875
  return 0; /* for compiler */
15876
}
15877

    
15878
int _wstati64(const wchar_t *path, cs_stat_t *st) {
15879
  DWORD fa = GetFileAttributesW(path);
15880
  if (fa == INVALID_FILE_ATTRIBUTES) {
15881
    return -1;
15882
  }
15883
  memset(st, 0, sizeof(*st));
15884
  if ((fa & FILE_ATTRIBUTE_DIRECTORY) == 0) {
15885
    HANDLE h;
15886
    FILETIME ftime;
15887
    st->st_mode |= _S_IFREG;
15888
    h = CreateFileW(path, GENERIC_READ, 0, NULL, OPEN_EXISTING,
15889
                    FILE_ATTRIBUTE_NORMAL, NULL);
15890
    if (h == INVALID_HANDLE_VALUE) {
15891
      return -1;
15892
    }
15893
    st->st_size = GetFileSize(h, NULL);
15894
    GetFileTime(h, NULL, NULL, &ftime);
15895
    st->st_mtime = (uint32_t)((((uint64_t) ftime.dwLowDateTime +
15896
                                ((uint64_t) ftime.dwHighDateTime << 32)) /
15897
                               10000000.0) -
15898
                              11644473600);
15899
    CloseHandle(h);
15900
  } else {
15901
    st->st_mode |= _S_IFDIR;
15902
  }
15903
  return 0;
15904
}
15905

    
15906
/* Windows CE doesn't have neither gmtime nor strftime */
15907
static void mg_gmt_time_string(char *buf, size_t buf_len, time_t *t) {
15908
  FILETIME ft;
15909
  SYSTEMTIME systime;
15910
  if (t != NULL) {
15911
    uint64_t filetime = (*t + 11644473600) * 10000000;
15912
    ft.dwLowDateTime = filetime & 0xFFFFFFFF;
15913
    ft.dwHighDateTime = (filetime & 0xFFFFFFFF00000000) >> 32;
15914
    FileTimeToSystemTime(&ft, &systime);
15915
  } else {
15916
    GetSystemTime(&systime);
15917
  }
15918
  /* There is no PRIu16 in WinCE SDK */
15919
  snprintf(buf, buf_len, "%d.%d.%d %d:%d:%d GMT", (int) systime.wYear,
15920
           (int) systime.wMonth, (int) systime.wDay, (int) systime.wHour,
15921
           (int) systime.wMinute, (int) systime.wSecond);
15922
}
15923

    
15924
#endif
15925
#ifdef MG_MODULE_LINES
15926
#line 1 "common/platforms/pic32/pic32_net_if.h"
15927
#endif
15928
/*
15929
 * Copyright (c) 2014-2016 Cesanta Software Limited
15930
 * All rights reserved
15931
 */
15932

    
15933
#ifndef CS_COMMON_PLATFORMS_PIC32_NET_IF_H_
15934
#define CS_COMMON_PLATFORMS_PIC32_NET_IF_H_
15935

    
15936
/* Amalgamated: #include "mongoose/src/net_if.h" */
15937

    
15938
#ifdef __cplusplus
15939
extern "C" {
15940
#endif /* __cplusplus */
15941

    
15942
#ifndef MG_ENABLE_NET_IF_PIC32
15943
#define MG_ENABLE_NET_IF_PIC32 MG_NET_IF == MG_NET_IF_PIC32
15944
#endif
15945

    
15946
extern const struct mg_iface_vtable mg_pic32_iface_vtable;
15947

    
15948
#ifdef __cplusplus
15949
}
15950
#endif /* __cplusplus */
15951

    
15952
#endif /* CS_COMMON_PLATFORMS_PIC32_NET_IF_H_ */
15953
#ifdef MG_MODULE_LINES
15954
#line 1 "common/platforms/pic32/pic32_net_if.c"
15955
#endif
15956
/*
15957
 * Copyright (c) 2014-2016 Cesanta Software Limited
15958
 * All rights reserved
15959
 */
15960

    
15961
#if MG_ENABLE_NET_IF_PIC32
15962

    
15963
int mg_pic32_if_create_conn(struct mg_connection *nc) {
15964
  (void) nc;
15965
  return 1;
15966
}
15967

    
15968
void mg_pic32_if_recved(struct mg_connection *nc, size_t len) {
15969
  (void) nc;
15970
  (void) len;
15971
}
15972

    
15973
void mg_pic32_if_add_conn(struct mg_connection *nc) {
15974
  (void) nc;
15975
}
15976

    
15977
void mg_pic32_if_init(struct mg_iface *iface) {
15978
  (void) iface;
15979
  (void) mg_get_errno(); /* Shutup compiler */
15980
}
15981

    
15982
void mg_pic32_if_free(struct mg_iface *iface) {
15983
  (void) iface;
15984
}
15985

    
15986
void mg_pic32_if_remove_conn(struct mg_connection *nc) {
15987
  (void) nc;
15988
}
15989

    
15990
void mg_pic32_if_destroy_conn(struct mg_connection *nc) {
15991
  if (nc->sock == INVALID_SOCKET) return;
15992
  /* For UDP, only close outgoing sockets or listeners. */
15993
  if (!(nc->flags & MG_F_UDP)) {
15994
    /* Close TCP */
15995
    TCPIP_TCP_Close((TCP_SOCKET) nc->sock);
15996
  } else if (nc->listener == NULL) {
15997
    /* Only close outgoing UDP or listeners. */
15998
    TCPIP_UDP_Close((UDP_SOCKET) nc->sock);
15999
  }
16000

    
16001
  nc->sock = INVALID_SOCKET;
16002
}
16003

    
16004
int mg_pic32_if_listen_udp(struct mg_connection *nc, union socket_address *sa) {
16005
  nc->sock = TCPIP_UDP_ServerOpen(
16006
      sa->sin.sin_family == AF_INET ? IP_ADDRESS_TYPE_IPV4
16007
                                    : IP_ADDRESS_TYPE_IPV6,
16008
      ntohs(sa->sin.sin_port),
16009
      sa->sin.sin_addr.s_addr == 0 ? 0 : (IP_MULTI_ADDRESS *) &sa->sin);
16010
  if (nc->sock == INVALID_SOCKET) {
16011
    return -1;
16012
  }
16013
  return 0;
16014
}
16015

    
16016
void mg_pic32_if_udp_send(struct mg_connection *nc, const void *buf,
16017
                          size_t len) {
16018
  mbuf_append(&nc->send_mbuf, buf, len);
16019
}
16020

    
16021
void mg_pic32_if_tcp_send(struct mg_connection *nc, const void *buf,
16022
                          size_t len) {
16023
  mbuf_append(&nc->send_mbuf, buf, len);
16024
}
16025

    
16026
int mg_pic32_if_listen_tcp(struct mg_connection *nc, union socket_address *sa) {
16027
  nc->sock = TCPIP_TCP_ServerOpen(
16028
      sa->sin.sin_family == AF_INET ? IP_ADDRESS_TYPE_IPV4
16029
                                    : IP_ADDRESS_TYPE_IPV6,
16030
      ntohs(sa->sin.sin_port),
16031
      sa->sin.sin_addr.s_addr == 0 ? 0 : (IP_MULTI_ADDRESS *) &sa->sin);
16032
  memcpy(&nc->sa, sa, sizeof(*sa));
16033
  if (nc->sock == INVALID_SOCKET) {
16034
    return -1;
16035
  }
16036
  return 0;
16037
}
16038

    
16039
static int mg_accept_conn(struct mg_connection *lc) {
16040
  struct mg_connection *nc;
16041
  TCP_SOCKET_INFO si;
16042
  union socket_address sa;
16043

    
16044
  nc = mg_if_accept_new_conn(lc);
16045

    
16046
  if (nc == NULL) {
16047
    return 0;
16048
  }
16049

    
16050
  nc->sock = lc->sock;
16051
  nc->flags &= ~MG_F_LISTENING;
16052

    
16053
  if (!TCPIP_TCP_SocketInfoGet((TCP_SOCKET) nc->sock, &si)) {
16054
    return 0;
16055
  }
16056

    
16057
  if (si.addressType == IP_ADDRESS_TYPE_IPV4) {
16058
    sa.sin.sin_family = AF_INET;
16059
    sa.sin.sin_port = htons(si.remotePort);
16060
    sa.sin.sin_addr.s_addr = si.remoteIPaddress.v4Add.Val;
16061
  } else {
16062
    /* TODO(alashkin): do something with _potential_ IPv6 */
16063
    memset(&sa, 0, sizeof(sa));
16064
  }
16065

    
16066
  mg_if_accept_tcp_cb(nc, (union socket_address *) &sa, sizeof(sa));
16067

    
16068
  return mg_pic32_if_listen_tcp(lc, &lc->sa) >= 0;
16069
}
16070

    
16071
char *inet_ntoa(struct in_addr in) {
16072
  static char addr[17];
16073
  snprintf(addr, sizeof(addr), "%d.%d.%d.%d", (int) in.S_un.S_un_b.s_b1,
16074
           (int) in.S_un.S_un_b.s_b2, (int) in.S_un.S_un_b.s_b3,
16075
           (int) in.S_un.S_un_b.s_b4);
16076
  return addr;
16077
}
16078

    
16079
static void mg_handle_send(struct mg_connection *nc) {
16080
  uint16_t bytes_written = 0;
16081
  if (nc->flags & MG_F_UDP) {
16082
    if (!TCPIP_UDP_RemoteBind(
16083
            (UDP_SOCKET) nc->sock,
16084
            nc->sa.sin.sin_family == AF_INET ? IP_ADDRESS_TYPE_IPV4
16085
                                             : IP_ADDRESS_TYPE_IPV6,
16086
            ntohs(nc->sa.sin.sin_port), (IP_MULTI_ADDRESS *) &nc->sa.sin)) {
16087
      nc->flags |= MG_F_CLOSE_IMMEDIATELY;
16088
      return;
16089
    }
16090
    bytes_written = TCPIP_UDP_TxPutIsReady((UDP_SOCKET) nc->sock, 0);
16091
    if (bytes_written >= nc->send_mbuf.len) {
16092
      if (TCPIP_UDP_ArrayPut((UDP_SOCKET) nc->sock,
16093
                             (uint8_t *) nc->send_mbuf.buf,
16094
                             nc->send_mbuf.len) != nc->send_mbuf.len) {
16095
        nc->flags |= MG_F_CLOSE_IMMEDIATELY;
16096
        bytes_written = 0;
16097
      }
16098
    }
16099
  } else {
16100
    bytes_written = TCPIP_TCP_FifoTxFreeGet((TCP_SOCKET) nc->sock);
16101
    if (bytes_written != 0) {
16102
      if (bytes_written > nc->send_mbuf.len) {
16103
        bytes_written = nc->send_mbuf.len;
16104
      }
16105
      if (TCPIP_TCP_ArrayPut((TCP_SOCKET) nc->sock,
16106
                             (uint8_t *) nc->send_mbuf.buf,
16107
                             bytes_written) != bytes_written) {
16108
        nc->flags |= MG_F_CLOSE_IMMEDIATELY;
16109
        bytes_written = 0;
16110
      }
16111
    }
16112
  }
16113

    
16114
  mg_if_sent_cb(nc, bytes_written);
16115
}
16116

    
16117
static void mg_handle_recv(struct mg_connection *nc) {
16118
  uint16_t bytes_read = 0;
16119
  uint8_t *buf = NULL;
16120
  if (nc->flags & MG_F_UDP) {
16121
    bytes_read = TCPIP_UDP_GetIsReady((UDP_SOCKET) nc->sock);
16122
    if (bytes_read != 0 &&
16123
        (nc->recv_mbuf_limit == -1 ||
16124
         nc->recv_mbuf.len + bytes_read < nc->recv_mbuf_limit)) {
16125
      buf = (uint8_t *) MG_MALLOC(bytes_read);
16126
      if (TCPIP_UDP_ArrayGet((UDP_SOCKET) nc->sock, buf, bytes_read) !=
16127
          bytes_read) {
16128
        nc->flags |= MG_F_CLOSE_IMMEDIATELY;
16129
        bytes_read = 0;
16130
        MG_FREE(buf);
16131
      }
16132
    }
16133
  } else {
16134
    bytes_read = TCPIP_TCP_GetIsReady((TCP_SOCKET) nc->sock);
16135
    if (bytes_read != 0) {
16136
      if (nc->recv_mbuf_limit != -1 &&
16137
          nc->recv_mbuf_limit - nc->recv_mbuf.len > bytes_read) {
16138
        bytes_read = nc->recv_mbuf_limit - nc->recv_mbuf.len;
16139
      }
16140
      buf = (uint8_t *) MG_MALLOC(bytes_read);
16141
      if (TCPIP_TCP_ArrayGet((TCP_SOCKET) nc->sock, buf, bytes_read) !=
16142
          bytes_read) {
16143
        nc->flags |= MG_F_CLOSE_IMMEDIATELY;
16144
        MG_FREE(buf);
16145
        bytes_read = 0;
16146
      }
16147
    }
16148
  }
16149

    
16150
  if (bytes_read != 0) {
16151
    mg_if_recv_tcp_cb(nc, buf, bytes_read, 1 /* own */);
16152
  }
16153
}
16154

    
16155
time_t mg_pic32_if_poll(struct mg_iface *iface, int timeout_ms) {
16156
  struct mg_mgr *mgr = iface->mgr;
16157
  double now = mg_time();
16158
  struct mg_connection *nc, *tmp;
16159

    
16160
  for (nc = mgr->active_connections; nc != NULL; nc = tmp) {
16161
    tmp = nc->next;
16162

    
16163
    if (nc->flags & MG_F_CONNECTING) {
16164
      /* processing connections */
16165
      if (nc->flags & MG_F_UDP ||
16166
          TCPIP_TCP_IsConnected((TCP_SOCKET) nc->sock)) {
16167
        mg_if_connect_cb(nc, 0);
16168
      }
16169
    } else if (nc->flags & MG_F_LISTENING) {
16170
      if (TCPIP_TCP_IsConnected((TCP_SOCKET) nc->sock)) {
16171
        /* accept new connections */
16172
        mg_accept_conn(nc);
16173
      }
16174
    } else {
16175
      if (nc->send_mbuf.len != 0) {
16176
        mg_handle_send(nc);
16177
      }
16178

    
16179
      if (nc->recv_mbuf_limit == -1 ||
16180
          nc->recv_mbuf.len < nc->recv_mbuf_limit) {
16181
        mg_handle_recv(nc);
16182
      }
16183
    }
16184
  }
16185

    
16186
  for (nc = mgr->active_connections; nc != NULL; nc = tmp) {
16187
    tmp = nc->next;
16188
    if ((nc->flags & MG_F_CLOSE_IMMEDIATELY) ||
16189
        (nc->send_mbuf.len == 0 && (nc->flags & MG_F_SEND_AND_CLOSE))) {
16190
      mg_close_conn(nc);
16191
    }
16192
  }
16193

    
16194
  return now;
16195
}
16196

    
16197
void mg_pic32_if_sock_set(struct mg_connection *nc, sock_t sock) {
16198
  nc->sock = sock;
16199
}
16200

    
16201
void mg_pic32_if_get_conn_addr(struct mg_connection *nc, int remote,
16202
                               union socket_address *sa) {
16203
  /* TODO(alaskin): not implemented yet */
16204
}
16205

    
16206
void mg_pic32_if_connect_tcp(struct mg_connection *nc,
16207
                             const union socket_address *sa) {
16208
  nc->sock = TCPIP_TCP_ClientOpen(
16209
      sa->sin.sin_family == AF_INET ? IP_ADDRESS_TYPE_IPV4
16210
                                    : IP_ADDRESS_TYPE_IPV6,
16211
      ntohs(sa->sin.sin_port), (IP_MULTI_ADDRESS *) &sa->sin);
16212
  nc->err = (nc->sock == INVALID_SOCKET) ? -1 : 0;
16213
}
16214

    
16215
void mg_pic32_if_connect_udp(struct mg_connection *nc) {
16216
  nc->sock = TCPIP_UDP_ClientOpen(IP_ADDRESS_TYPE_ANY, 0, NULL);
16217
  nc->err = (nc->sock == INVALID_SOCKET) ? -1 : 0;
16218
}
16219

    
16220
/* clang-format off */
16221
#define MG_PIC32_IFACE_VTABLE                                   \
16222
  {                                                             \
16223
    mg_pic32_if_init,                                           \
16224
    mg_pic32_if_free,                                           \
16225
    mg_pic32_if_add_conn,                                       \
16226
    mg_pic32_if_remove_conn,                                    \
16227
    mg_pic32_if_poll,                                           \
16228
    mg_pic32_if_listen_tcp,                                     \
16229
    mg_pic32_if_listen_udp,                                     \
16230
    mg_pic32_if_connect_tcp,                                    \
16231
    mg_pic32_if_connect_udp,                                    \
16232
    mg_pic32_if_tcp_send,                                       \
16233
    mg_pic32_if_udp_send,                                       \
16234
    mg_pic32_if_recved,                                         \
16235
    mg_pic32_if_create_conn,                                    \
16236
    mg_pic32_if_destroy_conn,                                   \
16237
    mg_pic32_if_sock_set,                                       \
16238
    mg_pic32_if_get_conn_addr,                                  \
16239
  }
16240
/* clang-format on */
16241

    
16242
const struct mg_iface_vtable mg_pic32_iface_vtable = MG_PIC32_IFACE_VTABLE;
16243
#if MG_NET_IF == MG_NET_IF_PIC32
16244
const struct mg_iface_vtable mg_default_iface_vtable = MG_PIC32_IFACE_VTABLE;
16245
#endif
16246

    
16247
#endif /* MG_ENABLE_NET_IF_PIC32 */
16248
#ifdef MG_MODULE_LINES
16249
#line 1 "common/platforms/windows/windows_direct.c"
16250
#endif
16251
/*
16252
 * Copyright (c) 2017 Cesanta Software Limited
16253
 * All rights reserved
16254
 */
16255

    
16256
#ifdef _WIN32
16257

    
16258
int rmdir(const char *dirname) {
16259
  return _rmdir(dirname);
16260
}
16261

    
16262
unsigned int sleep(unsigned int seconds) {
16263
  Sleep(seconds * 1000);
16264
  return 0;
16265
}
16266

    
16267
#endif /* _WIN32 */
(9-9/13)