Project

General

Profile

Feature #3002 » mongoose.c

yan hong, 05/29/2023 10:36 AM

 
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
void mg_ssl_if_init() {
4244
  SSL_library_init();
4245
}
4246

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

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

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

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

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

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

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

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

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

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

    
4345
  nc->flags |= MG_F_SSL;
4346

    
4347
  return MG_SSL_OK;
4348
}
4349

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
4625
#if MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_MBEDTLS
4626

    
4627
#include <mbedtls/debug.h>
4628
#include <mbedtls/ecp.h>
4629
#include <mbedtls/platform.h>
4630
#include <mbedtls/ssl.h>
4631
#include <mbedtls/x509_crt.h>
4632

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

    
4653
struct mg_ssl_if_ctx {
4654
  mbedtls_ssl_config *conf;
4655
  mbedtls_ssl_context *ssl;
4656
  mbedtls_x509_crt *cert;
4657
  mbedtls_pk_context *key;
4658
  mbedtls_x509_crt *ca_cert;
4659
  struct mbuf cipher_suites;
4660
};
4661

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

    
4665
void mg_ssl_if_init() {
4666
}
4667

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

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

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

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

    
4719
  /* TLS 1.2 and up */
4720
  mbedtls_ssl_conf_min_version(ctx->conf, MBEDTLS_SSL_MAJOR_VERSION_3,
4721
                               MBEDTLS_SSL_MINOR_VERSION_3);
4722
  mbedtls_ssl_conf_rng(ctx->conf, mg_ssl_if_mbed_random, nc);
4723

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

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

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

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

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

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

    
4777
  nc->flags |= MG_F_SSL;
4778

    
4779
  return MG_SSL_OK;
4780
}
4781

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
5106
/* Amalgamated: #include "mg_internal.h" */
5107
/* Amalgamated: #include "mg_uri.h" */
5108

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

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

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

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

    
5255
  return 0;
5256
}
5257

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

    
5263
  if (in->len == 0 || *s != '/') {
5264
    out->len = 0;
5265
    return 0;
5266
  }
5267

    
5268
  d = cp;
5269

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

    
5288
  out->p = cp;
5289
  out->len = d - cp;
5290
  return 1;
5291
}
5292

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

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

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

    
5312
  if (host != NULL && host->len > 0) {
5313
    mbuf_append(&out, host->p, host->len);
5314
  }
5315

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

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

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

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

    
5349
  result = 0;
5350

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

    
5370
#if MG_ENABLE_HTTP
5371

    
5372
/* Amalgamated: #include "common/cs_md5.h" */
5373
/* Amalgamated: #include "mg_internal.h" */
5374
/* Amalgamated: #include "mg_util.h" */
5375

    
5376
/* altbuf {{{ */
5377

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

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

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

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

    
5418
    mbuf_append(&ab->m, &c, 1);
5419
    ab->len = ab->m.len;
5420
  }
5421
}
5422

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

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

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

    
5454
/* }}} */
5455

    
5456
static const char *mg_version_header = "Mongoose/" MG_VERSION;
5457

    
5458
enum mg_http_proto_data_type { DATA_NONE, DATA_FILE, DATA_PUT };
5459

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

    
5468
#if MG_ENABLE_HTTP_CGI
5469
struct mg_http_proto_data_cgi {
5470
  struct mg_connection *cgi_nc;
5471
};
5472
#endif
5473

    
5474
struct mg_http_proto_data_chuncked {
5475
  int64_t body_len; /* How many bytes of chunked body was reassembled. */
5476
};
5477

    
5478
struct mg_http_endpoint {
5479
  struct mg_http_endpoint *next;
5480
  struct mg_str uri_pattern; /* owned */
5481
  char *auth_domain;         /* owned */
5482
  char *auth_file;           /* owned */
5483

    
5484
  mg_event_handler_t handler;
5485
#if MG_ENABLE_CALLBACK_USERDATA
5486
  void *user_data;
5487
#endif
5488
};
5489

    
5490
enum mg_http_multipart_stream_state {
5491
  MPS_BEGIN,
5492
  MPS_WAITING_FOR_BOUNDARY,
5493
  MPS_WAITING_FOR_CHUNK,
5494
  MPS_GOT_CHUNK,
5495
  MPS_GOT_BOUNDARY,
5496
  MPS_FINALIZE,
5497
  MPS_FINISHED
5498
};
5499

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

    
5511
struct mg_reverse_proxy_data {
5512
  struct mg_connection *linked_conn;
5513
};
5514

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

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

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

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

    
5559
  return (struct mg_http_proto_data *) c->proto_data;
5560
}
5561

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

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

    
5583
static void mg_http_free_proto_data_endpoints(struct mg_http_endpoint **ep) {
5584
  struct mg_http_endpoint *current = *ep;
5585

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

    
5595
  ep = NULL;
5596
}
5597

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

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

    
5630
#if MG_ENABLE_FILESYSTEM
5631

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

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

    
5695
  path_len = strlen(path);
5696

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

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

    
5715
  r.p = dflt;
5716
  r.len = strlen(r.p);
5717
  return r;
5718
}
5719
#endif
5720

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

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

    
5742
  return 0;
5743
}
5744

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

    
5751
    s = mg_skip(s, end, ": ", k);
5752
    s = mg_skip(s, end, "\r\n", v);
5753

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

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

    
5767
    if (k->len == 0 || v->len == 0) {
5768
      k->p = v->p = NULL;
5769
      k->len = v->len = 0;
5770
      break;
5771
    }
5772

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

    
5778
    i++;
5779
  }
5780

    
5781
  return s;
5782
}
5783

    
5784
int mg_parse_http(const char *s, int n, struct http_message *hm, int is_req) {
5785
  const char *end, *qs;
5786
  int len = mg_http_get_request_len(s, n);
5787

    
5788
  if (len <= 0) return len;
5789

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

    
5796
  /* Request is fully buffered. Skip leading whitespaces. */
5797
  while (s < end && isspace(*(unsigned char *) s)) s++;
5798

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

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

    
5821
  s = mg_http_parse_headers(s, end, len, hm);
5822

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

    
5845
  return len;
5846
}
5847

    
5848
struct mg_str *mg_get_http_header(struct http_message *hm, const char *name) {
5849
  size_t i, len = strlen(name);
5850

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

    
5857
  return NULL;
5858
}
5859

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

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

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

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

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

    
5941
  /* Record where the data is */
5942
  *chunk_data = (char *) s + i;
5943
  *chunk_len = n;
5944

    
5945
  /* Skip data */
5946
  i += n;
5947

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

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

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

    
5974
    if (data_len == 0) {
5975
      zero_chunk_received = 1;
5976
      i += n;
5977
      break;
5978
    }
5979
  }
5980

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

    
5989
    /* Send MG_EV_HTTP_CHUNK event */
5990
    nc->flags &= ~MG_F_DELETE_CHUNK;
5991
    mg_call(nc, nc->handler, nc->user_data, MG_EV_HTTP_CHUNK, hm);
5992

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

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

    
6009
  return body_len;
6010
}
6011

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

    
6019
  if (nc == NULL) {
6020
    return NULL;
6021
  }
6022

    
6023
  pd = mg_http_get_proto_data(nc);
6024

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

    
6035
    ep = ep->next;
6036
  }
6037

    
6038
  return ret;
6039
}
6040

    
6041
#if MG_ENABLE_HTTP_STREAMING_MULTIPART
6042
static void mg_http_multipart_continue(struct mg_connection *nc);
6043

    
6044
static void mg_http_multipart_begin(struct mg_connection *nc,
6045
                                    struct http_message *hm, int req_len);
6046

    
6047
#endif
6048

    
6049
static void mg_http_call_endpoint_handler(struct mg_connection *nc, int ev,
6050
                                          struct http_message *hm);
6051

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

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

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

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

    
6135
#if MG_ENABLE_FILESYSTEM
6136
  if (pd->file.fp != NULL) {
6137
    mg_http_transfer_file_data(nc);
6138
  }
6139
#endif
6140

    
6141
  mg_call(nc, nc->handler, nc->user_data, ev, ev_data);
6142

    
6143
  if (ev == MG_EV_RECV) {
6144
    struct mg_str *s;
6145
    pd->rcvd += *(int *) ev_data;
6146

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

    
6154
    req_len = mg_parse_http(io->buf, io->len, hm, is_req);
6155

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

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

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

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

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

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

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

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

    
6265
  char boundary_buf[100];
6266
  char *boundary = boundary_buf;
6267
  int boundary_len;
6268

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

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

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

    
6292
  /* If we reach this place - that is multipart request */
6293

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

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

    
6313
    mg_http_call_endpoint_handler(nc, MG_EV_HTTP_MULTIPART_REQUEST, hm);
6314

    
6315
    mbuf_remove(io, req_len);
6316
  }
6317
exit_mp:
6318
  if (boundary != boundary_buf) MG_FREE(boundary);
6319
}
6320

    
6321
#define CONTENT_DISPOSITION "Content-Disposition: "
6322

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

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

    
6338
static int mg_http_multipart_got_chunk(struct mg_connection *c) {
6339
  struct mg_http_proto_data *pd = mg_http_get_proto_data(c);
6340
  struct mbuf *io = &c->recv_mbuf;
6341

    
6342
  mg_http_multipart_call_handler(c, MG_EV_HTTP_PART_DATA, io->buf,
6343
                                 pd->mp_stream.prev_io_len);
6344
  mbuf_remove(io, pd->mp_stream.prev_io_len);
6345
  pd->mp_stream.prev_io_len = 0;
6346
  pd->mp_stream.state = MPS_WAITING_FOR_CHUNK;
6347

    
6348
  return 0;
6349
}
6350

    
6351
static int mg_http_multipart_finalize(struct mg_connection *c) {
6352
  struct mg_http_proto_data *pd = mg_http_get_proto_data(c);
6353

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

    
6363
  return 1;
6364
}
6365

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

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

    
6377
  if ((int) io->len < pd->mp_stream.boundary_len + 2) {
6378
    return 0;
6379
  }
6380

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

    
6397
  return 1;
6398
}
6399

    
6400
static void mg_http_parse_header_internal(struct mg_str *hdr,
6401
                                          const char *var_name,
6402
                                          struct altbuf *ab);
6403

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

    
6415
  altbuf_init(&ab_file_name, NULL, 0);
6416
  altbuf_init(&ab_var_name, NULL, 0);
6417

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

    
6425
      header.p = block_begin + sizeof(CONTENT_DISPOSITION) - 1;
6426
      header.len = line_len - sizeof(CONTENT_DISPOSITION) - 1;
6427

    
6428
      altbuf_reset(&ab_var_name);
6429
      mg_http_parse_header_internal(&header, "name", &ab_var_name);
6430

    
6431
      altbuf_reset(&ab_file_name);
6432
      mg_http_parse_header_internal(&header, "filename", &ab_file_name);
6433

    
6434
      block_begin += line_len;
6435
      data_size -= line_len;
6436

    
6437
      continue;
6438
    }
6439

    
6440
    if (line_len == 2 && mg_ncasecmp(block_begin, "\r\n", 2) == 0) {
6441
      mbuf_remove(io, block_begin - io->buf + 2);
6442

    
6443
      if (pd->mp_stream.processing_part != 0) {
6444
        mg_http_multipart_call_handler(c, MG_EV_HTTP_PART_END, NULL, 0);
6445
      }
6446

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

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

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

    
6464
    block_begin += line_len;
6465
  }
6466

    
6467
  pd->mp_stream.state = MPS_WAITING_FOR_BOUNDARY;
6468

    
6469
  altbuf_reset(&ab_var_name);
6470
  altbuf_reset(&ab_file_name);
6471

    
6472
  return 0;
6473
}
6474

    
6475
static int mg_http_multipart_continue_wait_for_chunk(struct mg_connection *c) {
6476
  struct mg_http_proto_data *pd = mg_http_get_proto_data(c);
6477
  struct mbuf *io = &c->recv_mbuf;
6478

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

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

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

    
6551
struct file_upload_state {
6552
  char *lfn;
6553
  size_t num_recd;
6554
  FILE *fp;
6555
};
6556

    
6557
#endif /* MG_ENABLE_HTTP_STREAMING_MULTIPART */
6558

    
6559
void mg_set_protocol_http_websocket(struct mg_connection *nc) {
6560
  nc->proto_handler = mg_http_handler;
6561
}
6562

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

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

    
6689
    default:
6690
      return "OK";
6691
  }
6692
}
6693

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

    
6703
void mg_send_response_line(struct mg_connection *nc, int status_code,
6704
                           const char *extra_headers) {
6705
  mg_send_response_line_s(nc, status_code, mg_mk_str(extra_headers));
6706
}
6707

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

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

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

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

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

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

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

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

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

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

    
6874
    pd->file.cl = cl;
6875
    pd->file.type = DATA_FILE;
6876
    mg_http_transfer_file_data(nc);
6877
  }
6878
}
6879

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

    
6893
#endif
6894

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

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

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

    
6920
  return i >= src_len ? j : -1;
6921
}
6922

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

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

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

    
6966
  return len;
6967
}
6968

    
6969
void mg_send_http_chunk(struct mg_connection *nc, const char *buf, size_t len) {
6970
  char chunk_size[50];
6971
  int n;
6972

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

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

    
6984
  va_start(ap, fmt);
6985
  len = mg_avprintf(&buf, sizeof(mem), fmt, ap);
6986
  va_end(ap);
6987

    
6988
  if (len >= 0) {
6989
    mg_send_http_chunk(nc, buf, len);
6990
  }
6991

    
6992
  /* LCOV_EXCL_START */
6993
  if (buf != mem && buf != NULL) {
6994
    MG_FREE(buf);
6995
  }
6996
  /* LCOV_EXCL_STOP */
6997
}
6998

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

    
7004
  va_start(ap, fmt);
7005
  len = mg_avprintf(&buf, sizeof(mem), fmt, ap);
7006
  va_end(ap);
7007

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

    
7019
  /* LCOV_EXCL_START */
7020
  if (buf != mem && buf != NULL) {
7021
    MG_FREE(buf);
7022
  }
7023
  /* LCOV_EXCL_STOP */
7024
}
7025

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

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

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

    
7050
    if (ch != ' ' && *p != ch) {
7051
      altbuf_reset(ab);
7052
    }
7053
  }
7054

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

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

    
7068
  mg_http_parse_header_internal(hdr, var_name, &ab);
7069

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

    
7078
int mg_http_parse_header(struct mg_str *hdr, const char *var_name, char *buf,
7079
                         size_t buf_size) {
7080
  char *buf2 = buf;
7081

    
7082
  int len = mg_http_parse_header2(hdr, var_name, &buf2, buf_size);
7083

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

    
7090
  return len;
7091
}
7092

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

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

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

    
7108
  buf = (char *) MG_MALLOC(hdr->len);
7109
  cs_base64_decode((unsigned char *) hdr->p + 6, hdr->len, buf, NULL);
7110

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

    
7118
  MG_FREE(buf);
7119
  return res;
7120
}
7121

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

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

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

    
7140
#if !MG_DISABLE_HTTP_DIGEST_AUTH
7141

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

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

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

    
7173
  mg_hash_md5_v(num_msgs, msgs, msg_lens, hash);
7174
  cs_to_hex(buf, hash, sizeof(hash));
7175
}
7176

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

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

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

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

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

    
7232
  char *username = username_buf, *cnonce = cnonce_buf, *response = response_buf,
7233
       *uri = uri_buf, *qop = qop_buf, *nc = nc_buf, *nonce = nonce_buf;
7234

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

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

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

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

    
7272
  return ret;
7273
}
7274

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

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

    
7303
  /* None of the entries in the passwords file matched - return failure */
7304
  return 0;
7305
}
7306

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
7536
  mg_conn_addr_to_str(c, local_port + 1, sizeof(local_port) - 1,
7537
                      MG_SOCK_STRINGIFY_PORT);
7538

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

    
7549
  return 0;
7550
}
7551

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

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

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

    
7580
#if MG_ENABLE_CALLBACK_USERDATA
7581
  (void) user_data;
7582
#endif
7583
}
7584

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

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

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

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

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

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

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

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

    
7642
    mg_printf(be, "%.*s: %.*s\r\n", (int) hn.len, hn.p, (int) hv.len, hv.p);
7643
  }
7644

    
7645
  mg_send(be, "\r\n", 2);
7646
  mg_send(be, hm->body.p, hm->body.len);
7647

    
7648
cleanup:
7649
  if (purl != burl) MG_FREE(purl);
7650
}
7651

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

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

    
7668
  return 0;
7669
}
7670
#endif /* MG_ENABLE_FILESYSTEM */
7671

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

    
7684
  { /* 1. Determine which root to use. */
7685

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

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

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

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

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

    
7835
  for (i = 0; i < ARRAY_SIZE(month_names); i++)
7836
    if (!strcmp(s, month_names[i])) return (int) i;
7837

    
7838
  return -1;
7839
}
7840

    
7841
static int mg_num_leap_years(int year) {
7842
  return year / 4 - year / 100 + year / 400;
7843
}
7844

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

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

    
7868
  return result;
7869
}
7870

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

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

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

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

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

    
7921
  exists = (mg_stat(path, &st) == 0);
7922
  is_directory = exists && S_ISDIR(st.st_mode);
7923

    
7924
  if (is_directory)
7925
    mg_find_index_file(path, opts->index_files, &index_file, &st);
7926

    
7927
  is_cgi =
7928
      (mg_match_prefix(opts->cgi_file_pattern, strlen(opts->cgi_file_pattern),
7929
                       index_file ? index_file : path) > 0);
7930

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

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

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

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

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

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

    
8035
#if MG_ENABLE_HTTP_URL_REWRITES
8036
  if (mg_http_handle_forwarding(nc, hm, &opts)) {
8037
    return;
8038
  }
8039

    
8040
  if (mg_http_send_port_based_redirect(nc, hm, &opts)) {
8041
    return;
8042
  }
8043
#endif
8044

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

    
8074
  MG_FREE(path);
8075
  path = NULL;
8076

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

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

    
8203
#if MG_ENABLE_CALLBACK_USERDATA
8204
  (void) user_data;
8205
#endif
8206
}
8207

    
8208
#endif /* MG_ENABLE_HTTP_STREAMING_MULTIPART */
8209
#endif /* MG_ENABLE_FILESYSTEM */
8210

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

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

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

    
8232
  if (scheme.len == 0 || mg_vcmp(&scheme, scheme1) == 0 ||
8233
      (scheme2 != NULL && mg_vcmp(&scheme, scheme2) == 0)) {
8234
    use_ssl = 0;
8235
    if (port_i == 0) port_i = 80;
8236
  } else if (mg_vcmp(&scheme, scheme_ssl1) == 0 ||
8237
             (scheme2 != NULL && mg_vcmp(&scheme, scheme_ssl2) == 0)) {
8238
    use_ssl = 1;
8239
    if (port_i == 0) port_i = 443;
8240
  } else {
8241
    goto out;
8242
  }
8243

    
8244
  mg_asprintf(&conn_addr, sizeof(conn_addr_buf), "tcp://%.*s:%u",
8245
              (int) host->len, host->p, port_i);
8246
  if (conn_addr == NULL) goto out;
8247

    
8248
  LOG(LL_DEBUG, ("%s use_ssl? %d %s", url, use_ssl, conn_addr));
8249
  if (use_ssl) {
8250
#if MG_ENABLE_SSL
8251
    /*
8252
     * Schema requires SSL, but no SSL parameters were provided in opts.
8253
     * In order to maintain backward compatibility, use a faux-SSL with no
8254
     * verification.
8255
     */
8256
    if (opts.ssl_ca_cert == NULL) {
8257
      opts.ssl_ca_cert = "*";
8258
    }
8259
#else
8260
    MG_SET_PTRPTR(opts.error_string, "ssl is disabled");
8261
    goto out;
8262
#endif
8263
  }
8264

    
8265
  if ((nc = mg_connect_opt(mgr, conn_addr, MG_CB(ev_handler, user_data),
8266
                           opts)) != NULL) {
8267
    mg_set_protocol_http_websocket(nc);
8268
  }
8269

    
8270
out:
8271
  if (conn_addr != NULL && conn_addr != conn_addr_buf) MG_FREE(conn_addr);
8272
  return nc;
8273
}
8274

    
8275
struct mg_connection *mg_connect_http_opt(
8276
    struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data),
8277
    struct mg_connect_opts opts, const char *url, const char *extra_headers,
8278
    const char *post_data) {
8279
  struct mg_str user = MG_NULL_STR, null_str = MG_NULL_STR;
8280
  struct mg_str host = MG_NULL_STR, path = MG_NULL_STR;
8281
  struct mbuf auth;
8282
  struct mg_connection *nc =
8283
      mg_connect_http_base(mgr, MG_CB(ev_handler, user_data), opts, "http",
8284
                           NULL, "https", NULL, url, &path, &user, &host);
8285

    
8286
  if (nc == NULL) {
8287
    return NULL;
8288
  }
8289

    
8290
  mbuf_init(&auth, 0);
8291
  if (user.len > 0) {
8292
    mg_basic_auth_header(user, null_str, &auth);
8293
  }
8294

    
8295
  if (post_data == NULL) post_data = "";
8296
  if (extra_headers == NULL) extra_headers = "";
8297
  if (path.len == 0) path = mg_mk_str("/");
8298
  if (host.len == 0) host = mg_mk_str("");
8299

    
8300
  mg_printf(nc, "%s %.*s HTTP/1.1\r\nHost: %.*s\r\nContent-Length: %" SIZE_T_FMT
8301
                "\r\n%.*s%s\r\n%s",
8302
            (post_data[0] == '\0' ? "GET" : "POST"), (int) path.len, path.p,
8303
            (int) (path.p - host.p), host.p, strlen(post_data), (int) auth.len,
8304
            (auth.buf == NULL ? "" : auth.buf), extra_headers, post_data);
8305

    
8306
  mbuf_free(&auth);
8307
  return nc;
8308
}
8309
///*WYF add*************************************/
8310
struct mg_connection *mg_connect_http_optDEL(
8311
    struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data),
8312
    struct mg_connect_opts opts, const char *url, const char *extra_headers,
8313
    const char *post_data) {
8314
  struct mg_str user = MG_NULL_STR, null_str = MG_NULL_STR;
8315
  struct mg_str host = MG_NULL_STR, path = MG_NULL_STR;
8316
  struct mbuf auth;
8317
  struct mg_connection *nc =
8318
      mg_connect_http_base(mgr, MG_CB(ev_handler, user_data), opts, "http",
8319
                           NULL, "https", NULL, url, &path, &user, &host);
8320

    
8321
  if (nc == NULL) {
8322
    return NULL;
8323
  }
8324

    
8325
  mbuf_init(&auth, 0);
8326
  if (user.len > 0) {
8327
    mg_basic_auth_header(user, null_str, &auth);
8328
  }
8329

    
8330
  if (post_data == NULL) post_data = "";
8331
  if (extra_headers == NULL) extra_headers = "";
8332
  if (path.len == 0) path = mg_mk_str("/");
8333
  if (host.len == 0) host = mg_mk_str("");
8334

    
8335
  mg_printf(nc, "%s %.*s HTTP/1.1\r\nHost: %.*s\r\nContent-Length: %" SIZE_T_FMT
8336
                "\r\n%.*s%s\r\n%s",
8337
            ("DELETE"), (int) path.len, path.p,
8338
            (int) (path.p - host.p), host.p, strlen(post_data), (int) auth.len,
8339
            (auth.buf == NULL ? "" : auth.buf), extra_headers, post_data);
8340

    
8341
  mbuf_free(&auth);
8342
  return nc;
8343
}
8344
struct mg_connection *mg_connect_httpDEL(
8345
    struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data),
8346
    const char *url, const char *extra_headers, const char *post_data) {
8347
  struct mg_connect_opts opts;
8348
  memset(&opts, 0, sizeof(opts));
8349
  return mg_connect_http_optDEL(mgr, MG_CB(ev_handler, user_data), opts, url,
8350
                             extra_headers, post_data);
8351
}
8352
//**WYF add*************************************/
8353

    
8354
//**LJK add*************************************/
8355
struct mg_connection *mg_connect_http_optPUT(
8356
struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data),
8357
struct mg_connect_opts opts, const char *url, const char *extra_headers,
8358
	const char *post_data) {
8359
	struct mg_str user = MG_NULL_STR, null_str = MG_NULL_STR;
8360
	struct mg_str host = MG_NULL_STR, path = MG_NULL_STR;
8361
	struct mbuf auth;
8362
	struct mg_connection *nc =
8363
		mg_connect_http_base(mgr, MG_CB(ev_handler, user_data), opts, "http",
8364
		NULL, "https", NULL, url, &path, &user, &host);
8365

    
8366
	if (nc == NULL) {
8367
		return NULL;
8368
	}
8369

    
8370
	mbuf_init(&auth, 0);
8371
	if (user.len > 0) {
8372
		mg_basic_auth_header(user, null_str, &auth);
8373
	}
8374

    
8375
	if (post_data == NULL) post_data = "";
8376
	if (extra_headers == NULL) extra_headers = "";
8377
	if (path.len == 0) path = mg_mk_str("/");
8378
	if (host.len == 0) host = mg_mk_str("");
8379

    
8380
	mg_printf(nc, "%s %.*s HTTP/1.1\r\nHost: %.*s\r\nContent-Length: %" SIZE_T_FMT
8381
		"\r\n%.*s%s\r\n%s",
8382
		("PUT"), (int)path.len, path.p,
8383
		(int)(path.p - host.p), host.p, strlen(post_data), (int)auth.len,
8384
		(auth.buf == NULL ? "" : auth.buf), extra_headers, post_data);
8385

    
8386
	mbuf_free(&auth);
8387
	return nc;
8388
}
8389
struct mg_connection *mg_connect_httpPUT(
8390
struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data),
8391
	const char *url, const char *extra_headers, const char *post_data) {
8392
	struct mg_connect_opts opts;
8393
	memset(&opts, 0, sizeof(opts));
8394
	return mg_connect_http_optPUT(mgr, MG_CB(ev_handler, user_data), opts, url,
8395
		extra_headers, post_data);
8396
}
8397

    
8398
struct mg_connection *mg_connect_http_optPOST(
8399
struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data),
8400
struct mg_connect_opts opts, const char *url, const char *extra_headers,
8401
	const char *post_data) {
8402
	struct mg_str user = MG_NULL_STR, null_str = MG_NULL_STR;
8403
	struct mg_str host = MG_NULL_STR, path = MG_NULL_STR;
8404
	struct mbuf auth;
8405
	struct mg_connection *nc =
8406
		mg_connect_http_base(mgr, MG_CB(ev_handler, user_data), opts, "http",
8407
		NULL, "https", NULL, url, &path, &user, &host);
8408

    
8409
	if (nc == NULL) {
8410
		return NULL;
8411
	}
8412

    
8413
	mbuf_init(&auth, 0);
8414
	if (user.len > 0) {
8415
		mg_basic_auth_header(user, null_str, &auth);
8416
	}
8417

    
8418
	if (post_data == NULL) post_data = "";
8419
	if (extra_headers == NULL) extra_headers = "";
8420
	if (path.len == 0) path = mg_mk_str("/");
8421
	if (host.len == 0) host = mg_mk_str("");
8422

    
8423
	mg_printf(nc, "%s %.*s HTTP/1.1\r\nHost: %.*s\r\nContent-Length: %" SIZE_T_FMT
8424
		"\r\n%.*s%s\r\n%s",
8425
		("POST"), (int)path.len, path.p,
8426
		(int)(path.p - host.p), host.p, strlen(post_data), (int)auth.len,
8427
		(auth.buf == NULL ? "" : auth.buf), extra_headers, post_data);
8428

    
8429
	mbuf_free(&auth);
8430
	return nc;
8431
}
8432
struct mg_connection *mg_connect_httpPOST(
8433
struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data),
8434
	const char *url, const char *extra_headers, const char *post_data) {
8435
	struct mg_connect_opts opts;
8436
	memset(&opts, 0, sizeof(opts));
8437
	return mg_connect_http_optPOST(mgr, MG_CB(ev_handler, user_data), opts, url,
8438
		extra_headers, post_data);
8439
}
8440
//**LJK add*************************************/
8441

    
8442
struct mg_connection *mg_connect_http(
8443
    struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data),
8444
    const char *url, const char *extra_headers, const char *post_data) {
8445
  struct mg_connect_opts opts;
8446
  memset(&opts, 0, sizeof(opts));
8447
  return mg_connect_http_opt(mgr, MG_CB(ev_handler, user_data), opts, url,
8448
                             extra_headers, post_data);
8449
}
8450

    
8451
size_t mg_parse_multipart(const char *buf, size_t buf_len, char *var_name,
8452
                          size_t var_name_len, char *file_name,
8453
                          size_t file_name_len, const char **data,
8454
                          size_t *data_len) {
8455
  static const char cd[] = "Content-Disposition: ";
8456
  size_t hl, bl, n, ll, pos, cdl = sizeof(cd) - 1;
8457
  int shl;
8458

    
8459
  if (buf == NULL || buf_len <= 0) return 0;
8460
  if ((shl = mg_http_get_request_len(buf, buf_len)) <= 0) return 0;
8461
  hl = shl;
8462
  if (buf[0] != '-' || buf[1] != '-' || buf[2] == '\n') return 0;
8463

    
8464
  /* Get boundary length */
8465
  bl = mg_get_line_len(buf, buf_len);
8466

    
8467
  /* Loop through headers, fetch variable name and file name */
8468
  var_name[0] = file_name[0] = '\0';
8469
  for (n = bl; (ll = mg_get_line_len(buf + n, hl - n)) > 0; n += ll) {
8470
    if (mg_ncasecmp(cd, buf + n, cdl) == 0) {
8471
      struct mg_str header;
8472
      header.p = buf + n + cdl;
8473
      header.len = ll - (cdl + 2);
8474
      {
8475
        char *var_name2 = var_name;
8476
        mg_http_parse_header2(&header, "name", &var_name2, var_name_len);
8477
        /* TODO: handle reallocated buffer correctly */
8478
        if (var_name2 != var_name) {
8479
          MG_FREE(var_name2);
8480
          var_name[0] = '\0';
8481
        }
8482
      }
8483
      {
8484
        char *file_name2 = file_name;
8485
        mg_http_parse_header2(&header, "filename", &file_name2, file_name_len);
8486
        /* TODO: handle reallocated buffer correctly */
8487
        if (file_name2 != file_name) {
8488
          MG_FREE(file_name2);
8489
          file_name[0] = '\0';
8490
        }
8491
      }
8492
    }
8493
  }
8494

    
8495
  /* Scan through the body, search for terminating boundary */
8496
  for (pos = hl; pos + (bl - 2) < buf_len; pos++) {
8497
    if (buf[pos] == '-' && !strncmp(buf, &buf[pos], bl - 2)) {
8498
      if (data_len != NULL) *data_len = (pos - 2) - hl;
8499
      if (data != NULL) *data = buf + hl;
8500
      return pos;
8501
    }
8502
  }
8503

    
8504
  return 0;
8505
}
8506

    
8507
void mg_register_http_endpoint_opt(struct mg_connection *nc,
8508
                                   const char *uri_path,
8509
                                   mg_event_handler_t handler,
8510
                                   struct mg_http_endpoint_opts opts) {
8511
  struct mg_http_proto_data *pd = NULL;
8512
  struct mg_http_endpoint *new_ep = NULL;
8513

    
8514
  if (nc == NULL) return;
8515
  new_ep = (struct mg_http_endpoint *) MG_CALLOC(1, sizeof(*new_ep));
8516
  if (new_ep == NULL) return;
8517

    
8518
  pd = mg_http_get_proto_data(nc);
8519
  new_ep->uri_pattern = mg_strdup(mg_mk_str(uri_path));
8520
  if (opts.auth_domain != NULL && opts.auth_file != NULL) {
8521
    new_ep->auth_domain = strdup(opts.auth_domain);
8522
    new_ep->auth_file = strdup(opts.auth_file);
8523
  }
8524
  new_ep->handler = handler;
8525
#if MG_ENABLE_CALLBACK_USERDATA
8526
  new_ep->user_data = opts.user_data;
8527
#endif
8528
  new_ep->next = pd->endpoints;
8529
  pd->endpoints = new_ep;
8530
}
8531

    
8532
static void mg_http_call_endpoint_handler(struct mg_connection *nc, int ev,
8533
                                          struct http_message *hm) {
8534
  struct mg_http_proto_data *pd = mg_http_get_proto_data(nc);
8535
  void *user_data = nc->user_data;
8536

    
8537
  if (ev == MG_EV_HTTP_REQUEST
8538
#if MG_ENABLE_HTTP_STREAMING_MULTIPART
8539
      || ev == MG_EV_HTTP_MULTIPART_REQUEST
8540
#endif
8541
      ) {
8542
    struct mg_http_endpoint *ep =
8543
        mg_http_get_endpoint_handler(nc->listener, &hm->uri);
8544
    if (ep != NULL) {
8545
#if MG_ENABLE_FILESYSTEM && !MG_DISABLE_HTTP_DIGEST_AUTH
8546
      if (!mg_http_is_authorized(hm, hm->uri, ep->auth_domain, ep->auth_file,
8547
                                 MG_AUTH_FLAG_IS_GLOBAL_PASS_FILE)) {
8548
        mg_http_send_digest_auth_request(nc, ep->auth_domain);
8549
        return;
8550
      }
8551
#endif
8552
      pd->endpoint_handler = ep->handler;
8553
#if MG_ENABLE_CALLBACK_USERDATA
8554
      user_data = ep->user_data;
8555
#endif
8556
    }
8557
  }
8558
  mg_call(nc, pd->endpoint_handler ? pd->endpoint_handler : nc->handler,
8559
          user_data, ev, hm);
8560
}
8561

    
8562
void mg_register_http_endpoint(struct mg_connection *nc, const char *uri_path,
8563
                               MG_CB(mg_event_handler_t handler,
8564
                                     void *user_data)) {
8565
  struct mg_http_endpoint_opts opts;
8566
  memset(&opts, 0, sizeof(opts));
8567
#if MG_ENABLE_CALLBACK_USERDATA
8568
  opts.user_data = user_data;
8569
#endif
8570
  mg_register_http_endpoint_opt(nc, uri_path, handler, opts);
8571
}
8572

    
8573
#endif /* MG_ENABLE_HTTP */
8574
#ifdef MG_MODULE_LINES
8575
#line 1 "mongoose/src/mg_http_cgi.c"
8576
#endif
8577
/*
8578
 * Copyright (c) 2014-2016 Cesanta Software Limited
8579
 * All rights reserved
8580
 */
8581

    
8582
#ifndef _WIN32
8583
#include <signal.h>
8584
#endif
8585

    
8586
#if MG_ENABLE_HTTP && MG_ENABLE_HTTP_CGI
8587

    
8588
#ifndef MG_MAX_CGI_ENVIR_VARS
8589
#define MG_MAX_CGI_ENVIR_VARS 64
8590
#endif
8591

    
8592
#ifndef MG_ENV_EXPORT_TO_CGI
8593
#define MG_ENV_EXPORT_TO_CGI "MONGOOSE_CGI"
8594
#endif
8595

    
8596
#define MG_F_HTTP_CGI_PARSE_HEADERS MG_F_USER_1
8597

    
8598
/*
8599
 * This structure helps to create an environment for the spawned CGI program.
8600
 * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
8601
 * last element must be NULL.
8602
 * However, on Windows there is a requirement that all these VARIABLE=VALUE\0
8603
 * strings must reside in a contiguous buffer. The end of the buffer is
8604
 * marked by two '\0' characters.
8605
 * We satisfy both worlds: we create an envp array (which is vars), all
8606
 * entries are actually pointers inside buf.
8607
 */
8608
struct mg_cgi_env_block {
8609
  struct mg_connection *nc;
8610
  char buf[MG_CGI_ENVIRONMENT_SIZE];       /* Environment buffer */
8611
  const char *vars[MG_MAX_CGI_ENVIR_VARS]; /* char *envp[] */
8612
  int len;                                 /* Space taken */
8613
  int nvars;                               /* Number of variables in envp[] */
8614
};
8615

    
8616
#ifdef _WIN32
8617
struct mg_threadparam {
8618
  sock_t s;
8619
  HANDLE hPipe;
8620
};
8621

    
8622
static int mg_wait_until_ready(sock_t sock, int for_read) {
8623
  fd_set set;
8624
  FD_ZERO(&set);
8625
  FD_SET(sock, &set);
8626
  return select(sock + 1, for_read ? &set : 0, for_read ? 0 : &set, 0, 0) == 1;
8627
}
8628

    
8629
static void *mg_push_to_stdin(void *arg) {
8630
  struct mg_threadparam *tp = (struct mg_threadparam *) arg;
8631
  int n, sent, stop = 0;
8632
  DWORD k;
8633
  char buf[BUFSIZ];
8634

    
8635
  while (!stop && mg_wait_until_ready(tp->s, 1) &&
8636
         (n = recv(tp->s, buf, sizeof(buf), 0)) > 0) {
8637
    if (n == -1 && GetLastError() == WSAEWOULDBLOCK) continue;
8638
    for (sent = 0; !stop && sent < n; sent += k) {
8639
      if (!WriteFile(tp->hPipe, buf + sent, n - sent, &k, 0)) stop = 1;
8640
    }
8641
  }
8642
  DBG(("%s", "FORWARED EVERYTHING TO CGI"));
8643
  CloseHandle(tp->hPipe);
8644
  MG_FREE(tp);
8645
  return NULL;
8646
}
8647

    
8648
static void *mg_pull_from_stdout(void *arg) {
8649
  struct mg_threadparam *tp = (struct mg_threadparam *) arg;
8650
  int k = 0, stop = 0;
8651
  DWORD n, sent;
8652
  char buf[BUFSIZ];
8653

    
8654
  while (!stop && ReadFile(tp->hPipe, buf, sizeof(buf), &n, NULL)) {
8655
    for (sent = 0; !stop && sent < n; sent += k) {
8656
      if (mg_wait_until_ready(tp->s, 0) &&
8657
          (k = send(tp->s, buf + sent, n - sent, 0)) <= 0)
8658
        stop = 1;
8659
    }
8660
  }
8661
  DBG(("%s", "EOF FROM CGI"));
8662
  CloseHandle(tp->hPipe);
8663
  shutdown(tp->s, 2);  // Without this, IO thread may get truncated data
8664
  closesocket(tp->s);
8665
  MG_FREE(tp);
8666
  return NULL;
8667
}
8668

    
8669
static void mg_spawn_stdio_thread(sock_t sock, HANDLE hPipe,
8670
                                  void *(*func)(void *)) {
8671
  struct mg_threadparam *tp = (struct mg_threadparam *) MG_MALLOC(sizeof(*tp));
8672
  if (tp != NULL) {
8673
    tp->s = sock;
8674
    tp->hPipe = hPipe;
8675
    mg_start_thread(func, tp);
8676
  }
8677
}
8678

    
8679
static void mg_abs_path(const char *utf8_path, char *abs_path, size_t len) {
8680
  wchar_t buf[MG_MAX_PATH], buf2[MG_MAX_PATH];
8681
  to_wchar(utf8_path, buf, ARRAY_SIZE(buf));
8682
  GetFullPathNameW(buf, ARRAY_SIZE(buf2), buf2, NULL);
8683
  WideCharToMultiByte(CP_UTF8, 0, buf2, wcslen(buf2) + 1, abs_path, len, 0, 0);
8684
}
8685

    
8686
static int mg_start_process(const char *interp, const char *cmd,
8687
                            const char *env, const char *envp[],
8688
                            const char *dir, sock_t sock) {
8689
  STARTUPINFOW si;
8690
  PROCESS_INFORMATION pi;
8691
  HANDLE a[2], b[2], me = GetCurrentProcess();
8692
  wchar_t wcmd[MG_MAX_PATH], full_dir[MG_MAX_PATH];
8693
  char buf[MG_MAX_PATH], buf2[MG_MAX_PATH], buf5[MG_MAX_PATH],
8694
      buf4[MG_MAX_PATH], cmdline[MG_MAX_PATH];
8695
  DWORD flags = DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS;
8696
  FILE *fp;
8697

    
8698
  memset(&si, 0, sizeof(si));
8699
  memset(&pi, 0, sizeof(pi));
8700

    
8701
  si.cb = sizeof(si);
8702
  si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
8703
  si.wShowWindow = SW_HIDE;
8704
  si.hStdError = GetStdHandle(STD_ERROR_HANDLE);
8705

    
8706
  CreatePipe(&a[0], &a[1], NULL, 0);
8707
  CreatePipe(&b[0], &b[1], NULL, 0);
8708
  DuplicateHandle(me, a[0], me, &si.hStdInput, 0, TRUE, flags);
8709
  DuplicateHandle(me, b[1], me, &si.hStdOutput, 0, TRUE, flags);
8710

    
8711
  if (interp == NULL && (fp = mg_fopen(cmd, "r")) != NULL) {
8712
    buf[0] = buf[1] = '\0';
8713
    fgets(buf, sizeof(buf), fp);
8714
    buf[sizeof(buf) - 1] = '\0';
8715
    if (buf[0] == '#' && buf[1] == '!') {
8716
      interp = buf + 2;
8717
      /* Trim leading spaces: https://github.com/cesanta/mongoose/issues/489 */
8718
      while (*interp != '\0' && isspace(*(unsigned char *) interp)) {
8719
        interp++;
8720
      }
8721
    }
8722
    fclose(fp);
8723
  }
8724

    
8725
  snprintf(buf, sizeof(buf), "%s/%s", dir, cmd);
8726
  mg_abs_path(buf, buf2, ARRAY_SIZE(buf2));
8727

    
8728
  mg_abs_path(dir, buf5, ARRAY_SIZE(buf5));
8729
  to_wchar(dir, full_dir, ARRAY_SIZE(full_dir));
8730

    
8731
  if (interp != NULL) {
8732
    mg_abs_path(interp, buf4, ARRAY_SIZE(buf4));
8733
    snprintf(cmdline, sizeof(cmdline), "%s \"%s\"", buf4, buf2);
8734
  } else {
8735
    snprintf(cmdline, sizeof(cmdline), "\"%s\"", buf2);
8736
  }
8737
  to_wchar(cmdline, wcmd, ARRAY_SIZE(wcmd));
8738

    
8739
  if (CreateProcessW(NULL, wcmd, NULL, NULL, TRUE, CREATE_NEW_PROCESS_GROUP,
8740
                     (void *) env, full_dir, &si, &pi) != 0) {
8741
    mg_spawn_stdio_thread(sock, a[1], mg_push_to_stdin);
8742
    mg_spawn_stdio_thread(sock, b[0], mg_pull_from_stdout);
8743

    
8744
    CloseHandle(si.hStdOutput);
8745
    CloseHandle(si.hStdInput);
8746

    
8747
    CloseHandle(pi.hThread);
8748
    CloseHandle(pi.hProcess);
8749
  } else {
8750
    CloseHandle(a[1]);
8751
    CloseHandle(b[0]);
8752
    closesocket(sock);
8753
  }
8754
  DBG(("CGI command: [%ls] -> %p", wcmd, pi.hProcess));
8755

    
8756
  /* Not closing a[0] and b[1] because we've used DUPLICATE_CLOSE_SOURCE */
8757
  (void) envp;
8758
  return (pi.hProcess != NULL);
8759
}
8760
#else
8761
static int mg_start_process(const char *interp, const char *cmd,
8762
                            const char *env, const char *envp[],
8763
                            const char *dir, sock_t sock) {
8764
  char buf[500];
8765
  pid_t pid = fork();
8766
  (void) env;
8767

    
8768
  if (pid == 0) {
8769
    /*
8770
     * In Linux `chdir` declared with `warn_unused_result` attribute
8771
     * To shutup compiler we have yo use result in some way
8772
     */
8773
    int tmp = chdir(dir);
8774
    (void) tmp;
8775
    (void) dup2(sock, 0);
8776
    (void) dup2(sock, 1);
8777
    closesocket(sock);
8778

    
8779
    /*
8780
     * After exec, all signal handlers are restored to their default values,
8781
     * with one exception of SIGCHLD. According to POSIX.1-2001 and Linux's
8782
     * implementation, SIGCHLD's handler will leave unchanged after exec
8783
     * if it was set to be ignored. Restore it to default action.
8784
     */
8785
    signal(SIGCHLD, SIG_DFL);
8786

    
8787
    if (interp == NULL) {
8788
      execle(cmd, cmd, (char *) 0, envp); /* (char *) 0 to squash warning */
8789
    } else {
8790
      execle(interp, interp, cmd, (char *) 0, envp);
8791
    }
8792
    snprintf(buf, sizeof(buf),
8793
             "Status: 500\r\n\r\n"
8794
             "500 Server Error: %s%s%s: %s",
8795
             interp == NULL ? "" : interp, interp == NULL ? "" : " ", cmd,
8796
             strerror(errno));
8797
    send(1, buf, strlen(buf), 0);
8798
    _exit(EXIT_FAILURE); /* exec call failed */
8799
  }
8800

    
8801
  return (pid != 0);
8802
}
8803
#endif /* _WIN32 */
8804

    
8805
/*
8806
 * Append VARIABLE=VALUE\0 string to the buffer, and add a respective
8807
 * pointer into the vars array.
8808
 */
8809
static char *mg_addenv(struct mg_cgi_env_block *block, const char *fmt, ...) {
8810
  int n, space;
8811
  char *added = block->buf + block->len;
8812
  va_list ap;
8813

    
8814
  /* Calculate how much space is left in the buffer */
8815
  space = sizeof(block->buf) - (block->len + 2);
8816
  if (space > 0) {
8817
    /* Copy VARIABLE=VALUE\0 string into the free space */
8818
    va_start(ap, fmt);
8819
    n = vsnprintf(added, (size_t) space, fmt, ap);
8820
    va_end(ap);
8821

    
8822
    /* Make sure we do not overflow buffer and the envp array */
8823
    if (n > 0 && n + 1 < space &&
8824
        block->nvars < (int) ARRAY_SIZE(block->vars) - 2) {
8825
      /* Append a pointer to the added string into the envp array */
8826
      block->vars[block->nvars++] = added;
8827
      /* Bump up used length counter. Include \0 terminator */
8828
      block->len += n + 1;
8829
    }
8830
  }
8831

    
8832
  return added;
8833
}
8834

    
8835
static void mg_addenv2(struct mg_cgi_env_block *blk, const char *name) {
8836
  const char *s;
8837
  if ((s = getenv(name)) != NULL) mg_addenv(blk, "%s=%s", name, s);
8838
}
8839

    
8840
static void mg_prepare_cgi_environment(struct mg_connection *nc,
8841
                                       const char *prog,
8842
                                       const struct mg_str *path_info,
8843
                                       const struct http_message *hm,
8844
                                       const struct mg_serve_http_opts *opts,
8845
                                       struct mg_cgi_env_block *blk) {
8846
  const char *s;
8847
  struct mg_str *h;
8848
  char *p;
8849
  size_t i;
8850
  char buf[100];
8851
  size_t path_info_len = path_info != NULL ? path_info->len : 0;
8852

    
8853
  blk->len = blk->nvars = 0;
8854
  blk->nc = nc;
8855

    
8856
  if ((s = getenv("SERVER_NAME")) != NULL) {
8857
    mg_addenv(blk, "SERVER_NAME=%s", s);
8858
  } else {
8859
    mg_sock_to_str(nc->sock, buf, sizeof(buf), 3);
8860
    mg_addenv(blk, "SERVER_NAME=%s", buf);
8861
  }
8862
  mg_addenv(blk, "SERVER_ROOT=%s", opts->document_root);
8863
  mg_addenv(blk, "DOCUMENT_ROOT=%s", opts->document_root);
8864
  mg_addenv(blk, "SERVER_SOFTWARE=%s/%s", "Mongoose", MG_VERSION);
8865

    
8866
  /* Prepare the environment block */
8867
  mg_addenv(blk, "%s", "GATEWAY_INTERFACE=CGI/1.1");
8868
  mg_addenv(blk, "%s", "SERVER_PROTOCOL=HTTP/1.1");
8869
  mg_addenv(blk, "%s", "REDIRECT_STATUS=200"); /* For PHP */
8870

    
8871
  mg_addenv(blk, "REQUEST_METHOD=%.*s", (int) hm->method.len, hm->method.p);
8872

    
8873
  mg_addenv(blk, "REQUEST_URI=%.*s%s%.*s", (int) hm->uri.len, hm->uri.p,
8874
            hm->query_string.len == 0 ? "" : "?", (int) hm->query_string.len,
8875
            hm->query_string.p);
8876

    
8877
  mg_conn_addr_to_str(nc, buf, sizeof(buf),
8878
                      MG_SOCK_STRINGIFY_REMOTE | MG_SOCK_STRINGIFY_IP);
8879
  mg_addenv(blk, "REMOTE_ADDR=%s", buf);
8880
  mg_conn_addr_to_str(nc, buf, sizeof(buf), MG_SOCK_STRINGIFY_PORT);
8881
  mg_addenv(blk, "SERVER_PORT=%s", buf);
8882

    
8883
  s = hm->uri.p + hm->uri.len - path_info_len - 1;
8884
  if (*s == '/') {
8885
    const char *base_name = strrchr(prog, DIRSEP);
8886
    mg_addenv(blk, "SCRIPT_NAME=%.*s/%s", (int) (s - hm->uri.p), hm->uri.p,
8887
              (base_name != NULL ? base_name + 1 : prog));
8888
  } else {
8889
    mg_addenv(blk, "SCRIPT_NAME=%.*s", (int) (s - hm->uri.p + 1), hm->uri.p);
8890
  }
8891
  mg_addenv(blk, "SCRIPT_FILENAME=%s", prog);
8892

    
8893
  if (path_info != NULL && path_info->len > 0) {
8894
    mg_addenv(blk, "PATH_INFO=%.*s", (int) path_info->len, path_info->p);
8895
    /* Not really translated... */
8896
    mg_addenv(blk, "PATH_TRANSLATED=%.*s", (int) path_info->len, path_info->p);
8897
  }
8898

    
8899
#if MG_ENABLE_SSL
8900
  mg_addenv(blk, "HTTPS=%s", (nc->flags & MG_F_SSL ? "on" : "off"));
8901
#else
8902
  mg_addenv(blk, "HTTPS=off");
8903
#endif
8904

    
8905
  if ((h = mg_get_http_header((struct http_message *) hm, "Content-Type")) !=
8906
      NULL) {
8907
    mg_addenv(blk, "CONTENT_TYPE=%.*s", (int) h->len, h->p);
8908
  }
8909

    
8910
  if (hm->query_string.len > 0) {
8911
    mg_addenv(blk, "QUERY_STRING=%.*s", (int) hm->query_string.len,
8912
              hm->query_string.p);
8913
  }
8914

    
8915
  if ((h = mg_get_http_header((struct http_message *) hm, "Content-Length")) !=
8916
      NULL) {
8917
    mg_addenv(blk, "CONTENT_LENGTH=%.*s", (int) h->len, h->p);
8918
  }
8919

    
8920
  mg_addenv2(blk, "PATH");
8921
  mg_addenv2(blk, "TMP");
8922
  mg_addenv2(blk, "TEMP");
8923
  mg_addenv2(blk, "TMPDIR");
8924
  mg_addenv2(blk, "PERLLIB");
8925
  mg_addenv2(blk, MG_ENV_EXPORT_TO_CGI);
8926

    
8927
#ifdef _WIN32
8928
  mg_addenv2(blk, "COMSPEC");
8929
  mg_addenv2(blk, "SYSTEMROOT");
8930
  mg_addenv2(blk, "SystemDrive");
8931
  mg_addenv2(blk, "ProgramFiles");
8932
  mg_addenv2(blk, "ProgramFiles(x86)");
8933
  mg_addenv2(blk, "CommonProgramFiles(x86)");
8934
#else
8935
  mg_addenv2(blk, "LD_LIBRARY_PATH");
8936
#endif /* _WIN32 */
8937

    
8938
  /* Add all headers as HTTP_* variables */
8939
  for (i = 0; hm->header_names[i].len > 0; i++) {
8940
    p = mg_addenv(blk, "HTTP_%.*s=%.*s", (int) hm->header_names[i].len,
8941
                  hm->header_names[i].p, (int) hm->header_values[i].len,
8942
                  hm->header_values[i].p);
8943

    
8944
    /* Convert variable name into uppercase, and change - to _ */
8945
    for (; *p != '=' && *p != '\0'; p++) {
8946
      if (*p == '-') *p = '_';
8947
      *p = (char) toupper(*(unsigned char *) p);
8948
    }
8949
  }
8950

    
8951
  blk->vars[blk->nvars++] = NULL;
8952
  blk->buf[blk->len++] = '\0';
8953
}
8954

    
8955
static void mg_cgi_ev_handler(struct mg_connection *cgi_nc, int ev,
8956
                              void *ev_data MG_UD_ARG(void *user_data)) {
8957
#if !MG_ENABLE_CALLBACK_USERDATA
8958
  void *user_data = cgi_nc->user_data;
8959
#endif
8960
  struct mg_connection *nc = (struct mg_connection *) user_data;
8961
  (void) ev_data;
8962

    
8963
  if (nc == NULL) {
8964
    /* The corresponding network connection was closed. */
8965
    cgi_nc->flags |= MG_F_CLOSE_IMMEDIATELY;
8966
    return;
8967
  }
8968

    
8969
  switch (ev) {
8970
    case MG_EV_RECV:
8971
      /*
8972
       * CGI script does not output reply line, like "HTTP/1.1 CODE XXXXX\n"
8973
       * It outputs headers, then body. Headers might include "Status"
8974
       * header, which changes CODE, and it might include "Location" header
8975
       * which changes CODE to 302.
8976
       *
8977
       * Therefore we do not send the output from the CGI script to the user
8978
       * until all CGI headers are received.
8979
       *
8980
       * Here we parse the output from the CGI script, and if all headers has
8981
       * been received, send appropriate reply line, and forward all
8982
       * received headers to the client.
8983
       */
8984
      if (nc->flags & MG_F_HTTP_CGI_PARSE_HEADERS) {
8985
        struct mbuf *io = &cgi_nc->recv_mbuf;
8986
        int len = mg_http_get_request_len(io->buf, io->len);
8987

    
8988
        if (len == 0) break;
8989
        if (len < 0 || io->len > MG_MAX_HTTP_REQUEST_SIZE) {
8990
          cgi_nc->flags |= MG_F_CLOSE_IMMEDIATELY;
8991
          mg_http_send_error(nc, 500, "Bad headers");
8992
        } else {
8993
          struct http_message hm;
8994
          struct mg_str *h;
8995
          mg_http_parse_headers(io->buf, io->buf + io->len, io->len, &hm);
8996
          if (mg_get_http_header(&hm, "Location") != NULL) {
8997
            mg_printf(nc, "%s", "HTTP/1.1 302 Moved\r\n");
8998
          } else if ((h = mg_get_http_header(&hm, "Status")) != NULL) {
8999
            mg_printf(nc, "HTTP/1.1 %.*s\r\n", (int) h->len, h->p);
9000
          } else {
9001
            mg_printf(nc, "%s", "HTTP/1.1 200 OK\r\n");
9002
          }
9003
        }
9004
        nc->flags &= ~MG_F_HTTP_CGI_PARSE_HEADERS;
9005
      }
9006
      if (!(nc->flags & MG_F_HTTP_CGI_PARSE_HEADERS)) {
9007
        mg_forward(cgi_nc, nc);
9008
      }
9009
      break;
9010
    case MG_EV_CLOSE:
9011
      DBG(("%p CLOSE", cgi_nc));
9012
      mg_http_free_proto_data_cgi(&mg_http_get_proto_data(nc)->cgi);
9013
      nc->flags |= MG_F_SEND_AND_CLOSE;
9014
      break;
9015
  }
9016
}
9017

    
9018
MG_INTERNAL void mg_handle_cgi(struct mg_connection *nc, const char *prog,
9019
                               const struct mg_str *path_info,
9020
                               const struct http_message *hm,
9021
                               const struct mg_serve_http_opts *opts) {
9022
  struct mg_cgi_env_block blk;
9023
  char dir[MG_MAX_PATH];
9024
  const char *p;
9025
  sock_t fds[2];
9026

    
9027
  DBG(("%p [%s]", nc, prog));
9028
  mg_prepare_cgi_environment(nc, prog, path_info, hm, opts, &blk);
9029
  /*
9030
   * CGI must be executed in its own directory. 'dir' must point to the
9031
   * directory containing executable program, 'p' must point to the
9032
   * executable program name relative to 'dir'.
9033
   */
9034
  if ((p = strrchr(prog, DIRSEP)) == NULL) {
9035
    snprintf(dir, sizeof(dir), "%s", ".");
9036
  } else {
9037
    snprintf(dir, sizeof(dir), "%.*s", (int) (p - prog), prog);
9038
    prog = p + 1;
9039
  }
9040

    
9041
  if (!mg_socketpair(fds, SOCK_STREAM)) {
9042
    nc->flags |= MG_F_CLOSE_IMMEDIATELY;
9043
    return;
9044
  }
9045

    
9046
#ifndef _WIN32
9047
  struct sigaction sa;
9048

    
9049
  sigemptyset(&sa.sa_mask);
9050
  sa.sa_handler = SIG_IGN;
9051
  sa.sa_flags = 0;
9052
  sigaction(SIGCHLD, &sa, NULL);
9053
#endif
9054

    
9055
  if (mg_start_process(opts->cgi_interpreter, prog, blk.buf, blk.vars, dir,
9056
                       fds[1]) != 0) {
9057
    size_t n = nc->recv_mbuf.len - (hm->message.len - hm->body.len);
9058
    struct mg_connection *cgi_nc =
9059
        mg_add_sock(nc->mgr, fds[0], mg_cgi_ev_handler MG_UD_ARG(nc));
9060
    struct mg_http_proto_data *cgi_pd = mg_http_get_proto_data(nc);
9061
    cgi_pd->cgi.cgi_nc = cgi_nc;
9062
#if !MG_ENABLE_CALLBACK_USERDATA
9063
    cgi_pd->cgi.cgi_nc->user_data = nc;
9064
#endif
9065
    nc->flags |= MG_F_HTTP_CGI_PARSE_HEADERS;
9066
    /* Push POST data to the CGI */
9067
    if (n > 0 && n < nc->recv_mbuf.len) {
9068
      mg_send(cgi_pd->cgi.cgi_nc, hm->body.p, n);
9069
    }
9070
    mbuf_remove(&nc->recv_mbuf, nc->recv_mbuf.len);
9071
  } else {
9072
    closesocket(fds[0]);
9073
    mg_http_send_error(nc, 500, "CGI failure");
9074
  }
9075

    
9076
#ifndef _WIN32
9077
  closesocket(fds[1]); /* On Windows, CGI stdio thread closes that socket */
9078
#endif
9079
}
9080

    
9081
MG_INTERNAL void mg_http_free_proto_data_cgi(struct mg_http_proto_data_cgi *d) {
9082
  if (d == NULL) return;
9083
  if (d->cgi_nc != NULL) {
9084
    d->cgi_nc->flags |= MG_F_CLOSE_IMMEDIATELY;
9085
    d->cgi_nc->user_data = NULL;
9086
  }
9087
  memset(d, 0, sizeof(*d));
9088
}
9089

    
9090
#endif /* MG_ENABLE_HTTP && MG_ENABLE_HTTP_CGI */
9091
#ifdef MG_MODULE_LINES
9092
#line 1 "mongoose/src/mg_http_ssi.c"
9093
#endif
9094
/*
9095
 * Copyright (c) 2014-2016 Cesanta Software Limited
9096
 * All rights reserved
9097
 */
9098

    
9099
#if MG_ENABLE_HTTP && MG_ENABLE_HTTP_SSI && MG_ENABLE_FILESYSTEM
9100

    
9101
static void mg_send_ssi_file(struct mg_connection *nc, struct http_message *hm,
9102
                             const char *path, FILE *fp, int include_level,
9103
                             const struct mg_serve_http_opts *opts);
9104

    
9105
static void mg_send_file_data(struct mg_connection *nc, FILE *fp) {
9106
  char buf[BUFSIZ];
9107
  size_t n;
9108
  while ((n = mg_fread(buf, 1, sizeof(buf), fp)) > 0) {
9109
    mg_send(nc, buf, n);
9110
  }
9111
}
9112

    
9113
static void mg_do_ssi_include(struct mg_connection *nc, struct http_message *hm,
9114
                              const char *ssi, char *tag, int include_level,
9115
                              const struct mg_serve_http_opts *opts) {
9116
  char file_name[MG_MAX_PATH], path[MG_MAX_PATH], *p;
9117
  FILE *fp;
9118

    
9119
  /*
9120
   * sscanf() is safe here, since send_ssi_file() also uses buffer
9121
   * of size MG_BUF_LEN to get the tag. So strlen(tag) is always < MG_BUF_LEN.
9122
   */
9123
  if (sscanf(tag, " virtual=\"%[^\"]\"", file_name) == 1) {
9124
    /* File name is relative to the webserver root */
9125
    snprintf(path, sizeof(path), "%s/%s", opts->document_root, file_name);
9126
  } else if (sscanf(tag, " abspath=\"%[^\"]\"", file_name) == 1) {
9127
    /*
9128
     * File name is relative to the webserver working directory
9129
     * or it is absolute system path
9130
     */
9131
    snprintf(path, sizeof(path), "%s", file_name);
9132
  } else if (sscanf(tag, " file=\"%[^\"]\"", file_name) == 1 ||
9133
             sscanf(tag, " \"%[^\"]\"", file_name) == 1) {
9134
    /* File name is relative to the currect document */
9135
    snprintf(path, sizeof(path), "%s", ssi);
9136
    if ((p = strrchr(path, DIRSEP)) != NULL) {
9137
      p[1] = '\0';
9138
    }
9139
    snprintf(path + strlen(path), sizeof(path) - strlen(path), "%s", file_name);
9140
  } else {
9141
    mg_printf(nc, "Bad SSI #include: [%s]", tag);
9142
    return;
9143
  }
9144

    
9145
  if ((fp = mg_fopen(path, "rb")) == NULL) {
9146
    mg_printf(nc, "SSI include error: mg_fopen(%s): %s", path,
9147
              strerror(mg_get_errno()));
9148
  } else {
9149
    mg_set_close_on_exec((sock_t) fileno(fp));
9150
    if (mg_match_prefix(opts->ssi_pattern, strlen(opts->ssi_pattern), path) >
9151
        0) {
9152
      mg_send_ssi_file(nc, hm, path, fp, include_level + 1, opts);
9153
    } else {
9154
      mg_send_file_data(nc, fp);
9155
    }
9156
    fclose(fp);
9157
  }
9158
}
9159

    
9160
#if MG_ENABLE_HTTP_SSI_EXEC
9161
static void do_ssi_exec(struct mg_connection *nc, char *tag) {
9162
  char cmd[BUFSIZ];
9163
  FILE *fp;
9164

    
9165
  if (sscanf(tag, " \"%[^\"]\"", cmd) != 1) {
9166
    mg_printf(nc, "Bad SSI #exec: [%s]", tag);
9167
  } else if ((fp = popen(cmd, "r")) == NULL) {
9168
    mg_printf(nc, "Cannot SSI #exec: [%s]: %s", cmd, strerror(mg_get_errno()));
9169
  } else {
9170
    mg_send_file_data(nc, fp);
9171
    pclose(fp);
9172
  }
9173
}
9174
#endif /* MG_ENABLE_HTTP_SSI_EXEC */
9175

    
9176
/*
9177
 * SSI directive has the following format:
9178
 * <!--#directive parameter=value parameter=value -->
9179
 */
9180
static void mg_send_ssi_file(struct mg_connection *nc, struct http_message *hm,
9181
                             const char *path, FILE *fp, int include_level,
9182
                             const struct mg_serve_http_opts *opts) {
9183
  static const struct mg_str btag = MG_MK_STR("<!--#");
9184
  static const struct mg_str d_include = MG_MK_STR("include");
9185
  static const struct mg_str d_call = MG_MK_STR("call");
9186
#if MG_ENABLE_HTTP_SSI_EXEC
9187
  static const struct mg_str d_exec = MG_MK_STR("exec");
9188
#endif
9189
  char buf[BUFSIZ], *p = buf + btag.len; /* p points to SSI directive */
9190
  int ch, len, in_ssi_tag;
9191

    
9192
  if (include_level > 10) {
9193
    mg_printf(nc, "SSI #include level is too deep (%s)", path);
9194
    return;
9195
  }
9196

    
9197
  in_ssi_tag = len = 0;
9198
  while ((ch = fgetc(fp)) != EOF) {
9199
    if (in_ssi_tag && ch == '>' && buf[len - 1] == '-' && buf[len - 2] == '-') {
9200
      size_t i = len - 2;
9201
      in_ssi_tag = 0;
9202

    
9203
      /* Trim closing --> */
9204
      buf[i--] = '\0';
9205
      while (i > 0 && buf[i] == ' ') {
9206
        buf[i--] = '\0';
9207
      }
9208

    
9209
      /* Handle known SSI directives */
9210
      if (strncmp(p, d_include.p, d_include.len) == 0) {
9211
        mg_do_ssi_include(nc, hm, path, p + d_include.len + 1, include_level,
9212
                          opts);
9213
      } else if (strncmp(p, d_call.p, d_call.len) == 0) {
9214
        struct mg_ssi_call_ctx cctx;
9215
        memset(&cctx, 0, sizeof(cctx));
9216
        cctx.req = hm;
9217
        cctx.file = mg_mk_str(path);
9218
        cctx.arg = mg_mk_str(p + d_call.len + 1);
9219
        mg_call(nc, NULL, nc->user_data, MG_EV_SSI_CALL,
9220
                (void *) cctx.arg.p); /* NUL added above */
9221
        mg_call(nc, NULL, nc->user_data, MG_EV_SSI_CALL_CTX, &cctx);
9222
#if MG_ENABLE_HTTP_SSI_EXEC
9223
      } else if (strncmp(p, d_exec.p, d_exec.len) == 0) {
9224
        do_ssi_exec(nc, p + d_exec.len + 1);
9225
#endif
9226
      } else {
9227
        /* Silently ignore unknown SSI directive. */
9228
      }
9229
      len = 0;
9230
    } else if (ch == '<') {
9231
      in_ssi_tag = 1;
9232
      if (len > 0) {
9233
        mg_send(nc, buf, (size_t) len);
9234
      }
9235
      len = 0;
9236
      buf[len++] = ch & 0xff;
9237
    } else if (in_ssi_tag) {
9238
      if (len == (int) btag.len && strncmp(buf, btag.p, btag.len) != 0) {
9239
        /* Not an SSI tag */
9240
        in_ssi_tag = 0;
9241
      } else if (len == (int) sizeof(buf) - 2) {
9242
        mg_printf(nc, "%s: SSI tag is too large", path);
9243
        len = 0;
9244
      }
9245
      buf[len++] = ch & 0xff;
9246
    } else {
9247
      buf[len++] = ch & 0xff;
9248
      if (len == (int) sizeof(buf)) {
9249
        mg_send(nc, buf, (size_t) len);
9250
        len = 0;
9251
      }
9252
    }
9253
  }
9254

    
9255
  /* Send the rest of buffered data */
9256
  if (len > 0) {
9257
    mg_send(nc, buf, (size_t) len);
9258
  }
9259
}
9260

    
9261
MG_INTERNAL void mg_handle_ssi_request(struct mg_connection *nc,
9262
                                       struct http_message *hm,
9263
                                       const char *path,
9264
                                       const struct mg_serve_http_opts *opts) {
9265
  FILE *fp;
9266
  struct mg_str mime_type;
9267
  DBG(("%p %s", nc, path));
9268

    
9269
  if ((fp = mg_fopen(path, "rb")) == NULL) {
9270
    mg_http_send_error(nc, 404, NULL);
9271
  } else {
9272
    mg_set_close_on_exec((sock_t) fileno(fp));
9273

    
9274
    mime_type = mg_get_mime_type(path, "text/plain", opts);
9275
    mg_send_response_line(nc, 200, opts->extra_headers);
9276
    mg_printf(nc,
9277
              "Content-Type: %.*s\r\n"
9278
              "Connection: close\r\n\r\n",
9279
              (int) mime_type.len, mime_type.p);
9280
    mg_send_ssi_file(nc, hm, path, fp, 0, opts);
9281
    fclose(fp);
9282
    nc->flags |= MG_F_SEND_AND_CLOSE;
9283
  }
9284
}
9285

    
9286
#endif /* MG_ENABLE_HTTP_SSI && MG_ENABLE_HTTP && MG_ENABLE_FILESYSTEM */
9287
#ifdef MG_MODULE_LINES
9288
#line 1 "mongoose/src/mg_http_webdav.c"
9289
#endif
9290
/*
9291
 * Copyright (c) 2014-2016 Cesanta Software Limited
9292
 * All rights reserved
9293
 */
9294

    
9295
#if MG_ENABLE_HTTP && MG_ENABLE_HTTP_WEBDAV
9296

    
9297
MG_INTERNAL int mg_is_dav_request(const struct mg_str *s) {
9298
  static const char *methods[] = {
9299
    "PUT",
9300
    "DELETE",
9301
    "MKCOL",
9302
    "PROPFIND",
9303
    "MOVE"
9304
#if MG_ENABLE_FAKE_DAVLOCK
9305
    ,
9306
    "LOCK",
9307
    "UNLOCK"
9308
#endif
9309
  };
9310
  size_t i;
9311

    
9312
  for (i = 0; i < ARRAY_SIZE(methods); i++) {
9313
    if (mg_vcmp(s, methods[i]) == 0) {
9314
      return 1;
9315
    }
9316
  }
9317

    
9318
  return 0;
9319
}
9320

    
9321
static int mg_mkdir(const char *path, uint32_t mode) {
9322
#ifndef _WIN32
9323
  return mkdir(path, mode);
9324
#else
9325
  (void) mode;
9326
  return _mkdir(path);
9327
#endif
9328
}
9329

    
9330
static void mg_print_props(struct mg_connection *nc, const char *name,
9331
                           cs_stat_t *stp) {
9332
  char mtime[64];
9333
  time_t t = stp->st_mtime; /* store in local variable for NDK compile */
9334
  struct mg_str name_esc = mg_url_encode(mg_mk_str(name));
9335
  mg_gmt_time_string(mtime, sizeof(mtime), &t);
9336
  mg_printf(nc,
9337
            "<d:response>"
9338
            "<d:href>%s</d:href>"
9339
            "<d:propstat>"
9340
            "<d:prop>"
9341
            "<d:resourcetype>%s</d:resourcetype>"
9342
            "<d:getcontentlength>%" INT64_FMT
9343
            "</d:getcontentlength>"
9344
            "<d:getlastmodified>%s</d:getlastmodified>"
9345
            "</d:prop>"
9346
            "<d:status>HTTP/1.1 200 OK</d:status>"
9347
            "</d:propstat>"
9348
            "</d:response>\n",
9349
            name_esc.p, S_ISDIR(stp->st_mode) ? "<d:collection/>" : "",
9350
            (int64_t) stp->st_size, mtime);
9351
  free((void *) name_esc.p);
9352
}
9353

    
9354
MG_INTERNAL void mg_handle_propfind(struct mg_connection *nc, const char *path,
9355
                                    cs_stat_t *stp, struct http_message *hm,
9356
                                    struct mg_serve_http_opts *opts) {
9357
  static const char header[] =
9358
      "HTTP/1.1 207 Multi-Status\r\n"
9359
      "Connection: close\r\n"
9360
      "Content-Type: text/xml; charset=utf-8\r\n\r\n"
9361
      "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
9362
      "<d:multistatus xmlns:d='DAV:'>\n";
9363
  static const char footer[] = "</d:multistatus>\n";
9364
  const struct mg_str *depth = mg_get_http_header(hm, "Depth");
9365

    
9366
  /* Print properties for the requested resource itself */
9367
  if (S_ISDIR(stp->st_mode) &&
9368
      strcmp(opts->enable_directory_listing, "yes") != 0) {
9369
    mg_printf(nc, "%s", "HTTP/1.1 403 Directory Listing Denied\r\n\r\n");
9370
  } else {
9371
    char uri[MG_MAX_PATH];
9372
    mg_send(nc, header, sizeof(header) - 1);
9373
    snprintf(uri, sizeof(uri), "%.*s", (int) hm->uri.len, hm->uri.p);
9374
    mg_print_props(nc, uri, stp);
9375
    if (S_ISDIR(stp->st_mode) && (depth == NULL || mg_vcmp(depth, "0") != 0)) {
9376
      mg_scan_directory(nc, path, opts, mg_print_props);
9377
    }
9378
    mg_send(nc, footer, sizeof(footer) - 1);
9379
    nc->flags |= MG_F_SEND_AND_CLOSE;
9380
  }
9381
}
9382

    
9383
#if MG_ENABLE_FAKE_DAVLOCK
9384
/*
9385
 * Windows explorer (probably there are another WebDav clients like it)
9386
 * requires LOCK support in webdav. W/out this, it still works, but fails
9387
 * to save file: shows error message and offers "Save As".
9388
 * "Save as" works, but this message is very annoying.
9389
 * This is fake lock, which doesn't lock something, just returns LOCK token,
9390
 * UNLOCK always answers "OK".
9391
 * With this fake LOCK Windows Explorer looks happy and saves file.
9392
 * NOTE: that is not DAV LOCK imlementation, it is just a way to shut up
9393
 * Windows native DAV client. This is why FAKE LOCK is not enabed by default
9394
 */
9395
MG_INTERNAL void mg_handle_lock(struct mg_connection *nc, const char *path) {
9396
  static const char *reply =
9397
      "HTTP/1.1 207 Multi-Status\r\n"
9398
      "Connection: close\r\n"
9399
      "Content-Type: text/xml; charset=utf-8\r\n\r\n"
9400
      "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
9401
      "<d:multistatus xmlns:d='DAV:'>\n"
9402
      "<D:lockdiscovery>\n"
9403
      "<D:activelock>\n"
9404
      "<D:locktoken>\n"
9405
      "<D:href>\n"
9406
      "opaquelocktoken:%s%u"
9407
      "</D:href>"
9408
      "</D:locktoken>"
9409
      "</D:activelock>\n"
9410
      "</D:lockdiscovery>"
9411
      "</d:multistatus>\n";
9412
  mg_printf(nc, reply, path, (unsigned int) mg_time());
9413
  nc->flags |= MG_F_SEND_AND_CLOSE;
9414
}
9415
#endif
9416

    
9417
MG_INTERNAL void mg_handle_mkcol(struct mg_connection *nc, const char *path,
9418
                                 struct http_message *hm) {
9419
  int status_code = 500;
9420
  if (hm->body.len != (size_t) ~0 && hm->body.len > 0) {
9421
    status_code = 415;
9422
  } else if (!mg_mkdir(path, 0755)) {
9423
    status_code = 201;
9424
  } else if (errno == EEXIST) {
9425
    status_code = 405;
9426
  } else if (errno == EACCES) {
9427
    status_code = 403;
9428
  } else if (errno == ENOENT) {
9429
    status_code = 409;
9430
  } else {
9431
    status_code = 500;
9432
  }
9433
  mg_http_send_error(nc, status_code, NULL);
9434
}
9435

    
9436
static int mg_remove_directory(const struct mg_serve_http_opts *opts,
9437
                               const char *dir) {
9438
  char path[MG_MAX_PATH];
9439
  struct dirent *dp;
9440
  cs_stat_t st;
9441
  DIR *dirp;
9442

    
9443
  if ((dirp = opendir(dir)) == NULL) return 0;
9444

    
9445
  while ((dp = readdir(dirp)) != NULL) {
9446
    if (mg_is_file_hidden((const char *) dp->d_name, opts, 1)) {
9447
      continue;
9448
    }
9449
    snprintf(path, sizeof(path), "%s%c%s", dir, '/', dp->d_name);
9450
    mg_stat(path, &st);
9451
    if (S_ISDIR(st.st_mode)) {
9452
      mg_remove_directory(opts, path);
9453
    } else {
9454
      remove(path);
9455
    }
9456
  }
9457
  closedir(dirp);
9458
  rmdir(dir);
9459

    
9460
  return 1;
9461
}
9462

    
9463
MG_INTERNAL void mg_handle_move(struct mg_connection *c,
9464
                                const struct mg_serve_http_opts *opts,
9465
                                const char *path, struct http_message *hm) {
9466
  const struct mg_str *dest = mg_get_http_header(hm, "Destination");
9467
  if (dest == NULL) {
9468
    mg_http_send_error(c, 411, NULL);
9469
  } else {
9470
    const char *p = (char *) memchr(dest->p, '/', dest->len);
9471
    if (p != NULL && p[1] == '/' &&
9472
        (p = (char *) memchr(p + 2, '/', dest->p + dest->len - p)) != NULL) {
9473
      char buf[MG_MAX_PATH];
9474
      snprintf(buf, sizeof(buf), "%s%.*s", opts->dav_document_root,
9475
               (int) (dest->p + dest->len - p), p);
9476
      if (rename(path, buf) == 0) {
9477
        mg_http_send_error(c, 200, NULL);
9478
      } else {
9479
        mg_http_send_error(c, 418, NULL);
9480
      }
9481
    } else {
9482
      mg_http_send_error(c, 500, NULL);
9483
    }
9484
  }
9485
}
9486

    
9487
MG_INTERNAL void mg_handle_delete(struct mg_connection *nc,
9488
                                  const struct mg_serve_http_opts *opts,
9489
                                  const char *path) {
9490
  cs_stat_t st;
9491
  if (mg_stat(path, &st) != 0) {
9492
    mg_http_send_error(nc, 404, NULL);
9493
  } else if (S_ISDIR(st.st_mode)) {
9494
    mg_remove_directory(opts, path);
9495
    mg_http_send_error(nc, 204, NULL);
9496
  } else if (remove(path) == 0) {
9497
    mg_http_send_error(nc, 204, NULL);
9498
  } else {
9499
    mg_http_send_error(nc, 423, NULL);
9500
  }
9501
}
9502

    
9503
/* Return -1 on error, 1 on success. */
9504
static int mg_create_itermediate_directories(const char *path) {
9505
  const char *s;
9506

    
9507
  /* Create intermediate directories if they do not exist */
9508
  for (s = path + 1; *s != '\0'; s++) {
9509
    if (*s == '/') {
9510
      char buf[MG_MAX_PATH];
9511
      cs_stat_t st;
9512
      snprintf(buf, sizeof(buf), "%.*s", (int) (s - path), path);
9513
      buf[sizeof(buf) - 1] = '\0';
9514
      if (mg_stat(buf, &st) != 0 && mg_mkdir(buf, 0755) != 0) {
9515
        return -1;
9516
      }
9517
    }
9518
  }
9519

    
9520
  return 1;
9521
}
9522

    
9523
MG_INTERNAL void mg_handle_put(struct mg_connection *nc, const char *path,
9524
                               struct http_message *hm) {
9525
  struct mg_http_proto_data *pd = mg_http_get_proto_data(nc);
9526
  cs_stat_t st;
9527
  const struct mg_str *cl_hdr = mg_get_http_header(hm, "Content-Length");
9528
  int rc, status_code = mg_stat(path, &st) == 0 ? 200 : 201;
9529

    
9530
  mg_http_free_proto_data_file(&pd->file);
9531
  if ((rc = mg_create_itermediate_directories(path)) == 0) {
9532
    mg_printf(nc, "HTTP/1.1 %d OK\r\nContent-Length: 0\r\n\r\n", status_code);
9533
  } else if (rc == -1) {
9534
    mg_http_send_error(nc, 500, NULL);
9535
  } else if (cl_hdr == NULL) {
9536
    mg_http_send_error(nc, 411, NULL);
9537
  } else if ((pd->file.fp = mg_fopen(path, "w+b")) == NULL) {
9538
    mg_http_send_error(nc, 500, NULL);
9539
  } else {
9540
    const struct mg_str *range_hdr = mg_get_http_header(hm, "Content-Range");
9541
    int64_t r1 = 0, r2 = 0;
9542
    pd->file.type = DATA_PUT;
9543
    mg_set_close_on_exec((sock_t) fileno(pd->file.fp));
9544
    pd->file.cl = to64(cl_hdr->p);
9545
    if (range_hdr != NULL &&
9546
        mg_http_parse_range_header(range_hdr, &r1, &r2) > 0) {
9547
      status_code = 206;
9548
      fseeko(pd->file.fp, r1, SEEK_SET);
9549
      pd->file.cl = r2 > r1 ? r2 - r1 + 1 : pd->file.cl - r1;
9550
    }
9551
    mg_printf(nc, "HTTP/1.1 %d OK\r\nContent-Length: 0\r\n\r\n", status_code);
9552
    /* Remove HTTP request from the mbuf, leave only payload */
9553
    mbuf_remove(&nc->recv_mbuf, hm->message.len - hm->body.len);
9554
    mg_http_transfer_file_data(nc);
9555
  }
9556
}
9557

    
9558
#endif /* MG_ENABLE_HTTP && MG_ENABLE_HTTP_WEBDAV */
9559
#ifdef MG_MODULE_LINES
9560
#line 1 "mongoose/src/mg_http_websocket.c"
9561
#endif
9562
/*
9563
 * Copyright (c) 2014 Cesanta Software Limited
9564
 * All rights reserved
9565
 */
9566

    
9567
#if MG_ENABLE_HTTP && MG_ENABLE_HTTP_WEBSOCKET
9568

    
9569
/* Amalgamated: #include "common/cs_sha1.h" */
9570

    
9571
#ifndef MG_WEBSOCKET_PING_INTERVAL_SECONDS
9572
#define MG_WEBSOCKET_PING_INTERVAL_SECONDS 5
9573
#endif
9574

    
9575
#define FLAGS_MASK_FIN (1 << 7)
9576
#define FLAGS_MASK_OP 0x0f
9577

    
9578
static int mg_is_ws_fragment(unsigned char flags) {
9579
  return (flags & FLAGS_MASK_FIN) == 0 ||
9580
         (flags & FLAGS_MASK_OP) == WEBSOCKET_OP_CONTINUE;
9581
}
9582

    
9583
static int mg_is_ws_first_fragment(unsigned char flags) {
9584
  return (flags & FLAGS_MASK_FIN) == 0 &&
9585
         (flags & FLAGS_MASK_OP) != WEBSOCKET_OP_CONTINUE;
9586
}
9587

    
9588
static int mg_is_ws_control_frame(unsigned char flags) {
9589
  unsigned char op = (flags & FLAGS_MASK_OP);
9590
  return op == WEBSOCKET_OP_CLOSE || op == WEBSOCKET_OP_PING ||
9591
         op == WEBSOCKET_OP_PONG;
9592
}
9593

    
9594
static void mg_handle_incoming_websocket_frame(struct mg_connection *nc,
9595
                                               struct websocket_message *wsm) {
9596
  if (wsm->flags & 0x8) {
9597
    mg_call(nc, nc->handler, nc->user_data, MG_EV_WEBSOCKET_CONTROL_FRAME, wsm);
9598
  } else {
9599
    mg_call(nc, nc->handler, nc->user_data, MG_EV_WEBSOCKET_FRAME, wsm);
9600
  }
9601
}
9602

    
9603
static struct mg_ws_proto_data *mg_ws_get_proto_data(struct mg_connection *nc) {
9604
  struct mg_http_proto_data *htd = mg_http_get_proto_data(nc);
9605
  return (htd != NULL ? &htd->ws_data : NULL);
9606
}
9607

    
9608
/*
9609
 * Sends a Close websocket frame with the given data, and closes the underlying
9610
 * connection. If `len` is ~0, strlen(data) is used.
9611
 */
9612
static void mg_ws_close(struct mg_connection *nc, const void *data,
9613
                        size_t len) {
9614
  if ((int) len == ~0) {
9615
    len = strlen((const char *) data);
9616
  }
9617
  mg_send_websocket_frame(nc, WEBSOCKET_OP_CLOSE, data, len);
9618
  nc->flags |= MG_F_SEND_AND_CLOSE;
9619
}
9620

    
9621
static int mg_deliver_websocket_data(struct mg_connection *nc) {
9622
  /* Using unsigned char *, cause of integer arithmetic below */
9623
  uint64_t i, data_len = 0, frame_len = 0, new_data_len = nc->recv_mbuf.len,
9624
              len, mask_len = 0, header_len = 0;
9625
  struct mg_ws_proto_data *wsd = mg_ws_get_proto_data(nc);
9626
  unsigned char *new_data = (unsigned char *) nc->recv_mbuf.buf,
9627
                *e = (unsigned char *) nc->recv_mbuf.buf + nc->recv_mbuf.len;
9628
  uint8_t flags;
9629
  int ok, reass;
9630

    
9631
  if (wsd->reass_len > 0) {
9632
    /*
9633
     * We already have some previously received data which we need to
9634
     * reassemble and deliver to the client code when we get the final
9635
     * fragment.
9636
     *
9637
     * NOTE: it doesn't mean that the current message must be a continuation:
9638
     * it might be a control frame (Close, Ping or Pong), which should be
9639
     * handled without breaking the fragmented message.
9640
     */
9641

    
9642
    size_t existing_len = wsd->reass_len;
9643
    assert(new_data_len >= existing_len);
9644

    
9645
    new_data += existing_len;
9646
    new_data_len -= existing_len;
9647
  }
9648

    
9649
  flags = new_data[0];
9650

    
9651
  reass = new_data_len > 0 && mg_is_ws_fragment(flags) &&
9652
          !(nc->flags & MG_F_WEBSOCKET_NO_DEFRAG);
9653

    
9654
  if (reass && mg_is_ws_control_frame(flags)) {
9655
    /*
9656
     * Control frames can't be fragmented, so if we encounter fragmented
9657
     * control frame, close connection immediately.
9658
     */
9659
    mg_ws_close(nc, "fragmented control frames are illegal", ~0);
9660
    return 0;
9661
  } else if (new_data_len > 0 && !reass && !mg_is_ws_control_frame(flags) &&
9662
             wsd->reass_len > 0) {
9663
    /*
9664
     * When in the middle of a fragmented message, only the continuations
9665
     * and control frames are allowed.
9666
     */
9667
    mg_ws_close(nc, "non-continuation in the middle of a fragmented message",
9668
                ~0);
9669
    return 0;
9670
  }
9671

    
9672
  if (new_data_len >= 2) {
9673
    len = new_data[1] & 0x7f;
9674
    mask_len = new_data[1] & FLAGS_MASK_FIN ? 4 : 0;
9675
    if (len < 126 && new_data_len >= mask_len) {
9676
      data_len = len;
9677
      header_len = 2 + mask_len;
9678
    } else if (len == 126 && new_data_len >= 4 + mask_len) {
9679
      header_len = 4 + mask_len;
9680
      data_len = ntohs(*(uint16_t *) &new_data[2]);
9681
    } else if (new_data_len >= 10 + mask_len) {
9682
      header_len = 10 + mask_len;
9683
      data_len = (((uint64_t) ntohl(*(uint32_t *) &new_data[2])) << 32) +
9684
                 ntohl(*(uint32_t *) &new_data[6]);
9685
    }
9686
  }
9687

    
9688
  frame_len = header_len + data_len;
9689
  ok = (frame_len > 0 && frame_len <= new_data_len);
9690

    
9691
  /* Check for overflow */
9692
  if (frame_len < header_len || frame_len < data_len) {
9693
    ok = 0;
9694
    mg_ws_close(nc, "overflowed message", ~0);
9695
  }
9696

    
9697
  if (ok) {
9698
    size_t cleanup_len = 0;
9699
    struct websocket_message wsm;
9700

    
9701
    wsm.size = (size_t) data_len;
9702
    wsm.data = new_data + header_len;
9703
    wsm.flags = flags;
9704

    
9705
    /* Apply mask if necessary */
9706
    if (mask_len > 0) {
9707
      for (i = 0; i < data_len; i++) {
9708
        new_data[i + header_len] ^= (new_data + header_len - mask_len)[i % 4];
9709
      }
9710
    }
9711

    
9712
    if (reass) {
9713
      /* This is a message fragment */
9714

    
9715
      if (mg_is_ws_first_fragment(flags)) {
9716
        /*
9717
         * On the first fragmented frame, skip the first byte (op) and also
9718
         * reset size to 1 (op), it'll be incremented with the data len below.
9719
         */
9720
        new_data += 1;
9721
        wsd->reass_len = 1 /* op */;
9722
      }
9723

    
9724
      /* Append this frame to the reassembled buffer */
9725
      memmove(new_data, wsm.data, e - wsm.data);
9726
      wsd->reass_len += wsm.size;
9727
      nc->recv_mbuf.len -= wsm.data - new_data;
9728

    
9729
      if (flags & FLAGS_MASK_FIN) {
9730
        /* On last fragmented frame - call user handler and remove data */
9731
        wsm.flags = FLAGS_MASK_FIN | nc->recv_mbuf.buf[0];
9732
        wsm.data = (unsigned char *) nc->recv_mbuf.buf + 1 /* op */;
9733
        wsm.size = wsd->reass_len - 1 /* op */;
9734
        cleanup_len = wsd->reass_len;
9735
        wsd->reass_len = 0;
9736

    
9737
        /* Pass reassembled message to the client code. */
9738
        mg_handle_incoming_websocket_frame(nc, &wsm);
9739
        mbuf_remove(&nc->recv_mbuf, cleanup_len); /* Cleanup frame */
9740
      }
9741
    } else {
9742
      /*
9743
       * This is a complete message, not a fragment. It might happen in between
9744
       * of a fragmented message (in this case, WebSocket protocol requires
9745
       * current message to be a control frame).
9746
       */
9747
      cleanup_len = (size_t) frame_len;
9748

    
9749
      /* First of all, check if we need to react on a control frame. */
9750
      switch (flags & FLAGS_MASK_OP) {
9751
        case WEBSOCKET_OP_PING:
9752
          mg_send_websocket_frame(nc, WEBSOCKET_OP_PONG, wsm.data, wsm.size);
9753
          break;
9754

    
9755
        case WEBSOCKET_OP_CLOSE:
9756
          mg_ws_close(nc, wsm.data, wsm.size);
9757
          break;
9758
      }
9759

    
9760
      /* Pass received message to the client code. */
9761
      mg_handle_incoming_websocket_frame(nc, &wsm);
9762

    
9763
      /* Cleanup frame */
9764
      memmove(nc->recv_mbuf.buf + wsd->reass_len,
9765
              nc->recv_mbuf.buf + wsd->reass_len + cleanup_len,
9766
              nc->recv_mbuf.len - wsd->reass_len - cleanup_len);
9767
      nc->recv_mbuf.len -= cleanup_len;
9768
    }
9769
  }
9770

    
9771
  return ok;
9772
}
9773

    
9774
struct ws_mask_ctx {
9775
  size_t pos; /* zero means unmasked */
9776
  uint32_t mask;
9777
};
9778

    
9779
static uint32_t mg_ws_random_mask(void) {
9780
  uint32_t mask;
9781
/*
9782
 * The spec requires WS client to generate hard to
9783
 * guess mask keys. From RFC6455, Section 5.3:
9784
 *
9785
 * The unpredictability of the masking key is essential to prevent
9786
 * authors of malicious applications from selecting the bytes that appear on
9787
 * the wire.
9788
 *
9789
 * Hence this feature is essential when the actual end user of this API
9790
 * is untrusted code that wouldn't have access to a lower level net API
9791
 * anyway (e.g. web browsers). Hence this feature is low prio for most
9792
 * mongoose use cases and thus can be disabled, e.g. when porting to a platform
9793
 * that lacks rand().
9794
 */
9795
#if MG_DISABLE_WS_RANDOM_MASK
9796
  mask = 0xefbeadde; /* generated with a random number generator, I swear */
9797
#else
9798
  if (sizeof(long) >= 4) {
9799
    mask = (uint32_t) rand();
9800
  } else if (sizeof(long) == 2) {
9801
    mask = (uint32_t) rand() << 16 | (uint32_t) rand();
9802
  }
9803
#endif
9804
  return mask;
9805
}
9806

    
9807
static void mg_send_ws_header(struct mg_connection *nc, int op, size_t len,
9808
                              struct ws_mask_ctx *ctx) {
9809
  int header_len;
9810
  unsigned char header[10];
9811

    
9812
  header[0] =
9813
      (op & WEBSOCKET_DONT_FIN ? 0x0 : FLAGS_MASK_FIN) | (op & FLAGS_MASK_OP);
9814
  if (len < 126) {
9815
    header[1] = (unsigned char) len;
9816
    header_len = 2;
9817
  } else if (len < 65535) {
9818
    uint16_t tmp = htons((uint16_t) len);
9819
    header[1] = 126;
9820
    memcpy(&header[2], &tmp, sizeof(tmp));
9821
    header_len = 4;
9822
  } else {
9823
    uint32_t tmp;
9824
    header[1] = 127;
9825
    tmp = htonl((uint32_t)((uint64_t) len >> 32));
9826
    memcpy(&header[2], &tmp, sizeof(tmp));
9827
    tmp = htonl((uint32_t)(len & 0xffffffff));
9828
    memcpy(&header[6], &tmp, sizeof(tmp));
9829
    header_len = 10;
9830
  }
9831

    
9832
  /* client connections enable masking */
9833
  if (nc->listener == NULL) {
9834
    header[1] |= 1 << 7; /* set masking flag */
9835
    mg_send(nc, header, header_len);
9836
    ctx->mask = mg_ws_random_mask();
9837
    mg_send(nc, &ctx->mask, sizeof(ctx->mask));
9838
    ctx->pos = nc->send_mbuf.len;
9839
  } else {
9840
    mg_send(nc, header, header_len);
9841
    ctx->pos = 0;
9842
  }
9843
}
9844

    
9845
static void mg_ws_mask_frame(struct mbuf *mbuf, struct ws_mask_ctx *ctx) {
9846
  size_t i;
9847
  if (ctx->pos == 0) return;
9848
  for (i = 0; i < (mbuf->len - ctx->pos); i++) {
9849
    mbuf->buf[ctx->pos + i] ^= ((char *) &ctx->mask)[i % 4];
9850
  }
9851
}
9852

    
9853
void mg_send_websocket_frame(struct mg_connection *nc, int op, const void *data,
9854
                             size_t len) {
9855
  struct ws_mask_ctx ctx;
9856
  DBG(("%p %d %d", nc, op, (int) len));
9857
  mg_send_ws_header(nc, op, len, &ctx);
9858
  mg_send(nc, data, len);
9859

    
9860
  mg_ws_mask_frame(&nc->send_mbuf, &ctx);
9861

    
9862
  if (op == WEBSOCKET_OP_CLOSE) {
9863
    nc->flags |= MG_F_SEND_AND_CLOSE;
9864
  }
9865
}
9866

    
9867
void mg_send_websocket_framev(struct mg_connection *nc, int op,
9868
                              const struct mg_str *strv, int strvcnt) {
9869
  struct ws_mask_ctx ctx;
9870
  int i;
9871
  int len = 0;
9872
  for (i = 0; i < strvcnt; i++) {
9873
    len += strv[i].len;
9874
  }
9875

    
9876
  mg_send_ws_header(nc, op, len, &ctx);
9877

    
9878
  for (i = 0; i < strvcnt; i++) {
9879
    mg_send(nc, strv[i].p, strv[i].len);
9880
  }
9881

    
9882
  mg_ws_mask_frame(&nc->send_mbuf, &ctx);
9883

    
9884
  if (op == WEBSOCKET_OP_CLOSE) {
9885
    nc->flags |= MG_F_SEND_AND_CLOSE;
9886
  }
9887
}
9888

    
9889
void mg_printf_websocket_frame(struct mg_connection *nc, int op,
9890
                               const char *fmt, ...) {
9891
  char mem[MG_VPRINTF_BUFFER_SIZE], *buf = mem;
9892
  va_list ap;
9893
  int len;
9894

    
9895
  va_start(ap, fmt);
9896
  if ((len = mg_avprintf(&buf, sizeof(mem), fmt, ap)) > 0) {
9897
    mg_send_websocket_frame(nc, op, buf, len);
9898
  }
9899
  va_end(ap);
9900

    
9901
  if (buf != mem && buf != NULL) {
9902
    MG_FREE(buf);
9903
  }
9904
}
9905

    
9906
MG_INTERNAL void mg_ws_handler(struct mg_connection *nc, int ev,
9907
                               void *ev_data MG_UD_ARG(void *user_data)) {
9908
  mg_call(nc, nc->handler, nc->user_data, ev, ev_data);
9909

    
9910
  switch (ev) {
9911
    case MG_EV_RECV:
9912
      do {
9913
      } while (mg_deliver_websocket_data(nc));
9914
      break;
9915
    case MG_EV_POLL:
9916
      /* Ping idle websocket connections */
9917
      {
9918
        time_t now = *(time_t *) ev_data;
9919
        if (nc->flags & MG_F_IS_WEBSOCKET &&
9920
            now > nc->last_io_time + MG_WEBSOCKET_PING_INTERVAL_SECONDS) {
9921
          mg_send_websocket_frame(nc, WEBSOCKET_OP_PING, "", 0);
9922
        }
9923
      }
9924
      break;
9925
    default:
9926
      break;
9927
  }
9928
#if MG_ENABLE_CALLBACK_USERDATA
9929
  (void) user_data;
9930
#endif
9931
}
9932

    
9933
#ifndef MG_EXT_SHA1
9934
void mg_hash_sha1_v(size_t num_msgs, const uint8_t *msgs[],
9935
                    const size_t *msg_lens, uint8_t *digest) {
9936
  size_t i;
9937
  cs_sha1_ctx sha_ctx;
9938
  cs_sha1_init(&sha_ctx);
9939
  for (i = 0; i < num_msgs; i++) {
9940
    cs_sha1_update(&sha_ctx, msgs[i], msg_lens[i]);
9941
  }
9942
  cs_sha1_final(digest, &sha_ctx);
9943
}
9944
#else
9945
extern void mg_hash_sha1_v(size_t num_msgs, const uint8_t *msgs[],
9946
                           const size_t *msg_lens, uint8_t *digest);
9947
#endif
9948

    
9949
MG_INTERNAL void mg_ws_handshake(struct mg_connection *nc,
9950
                                 const struct mg_str *key,
9951
                                 struct http_message *hm) {
9952
  static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
9953
  const uint8_t *msgs[2] = {(const uint8_t *) key->p, (const uint8_t *) magic};
9954
  const size_t msg_lens[2] = {key->len, 36};
9955
  unsigned char sha[20];
9956
  char b64_sha[30];
9957
  struct mg_str *s;
9958

    
9959
  mg_hash_sha1_v(2, msgs, msg_lens, sha);
9960
  mg_base64_encode(sha, sizeof(sha), b64_sha);
9961
  mg_printf(nc, "%s",
9962
            "HTTP/1.1 101 Switching Protocols\r\n"
9963
            "Upgrade: websocket\r\n"
9964
            "Connection: Upgrade\r\n");
9965

    
9966
  s = mg_get_http_header(hm, "Sec-WebSocket-Protocol");
9967
  if (s != NULL) {
9968
    mg_printf(nc, "Sec-WebSocket-Protocol: %.*s\r\n", (int) s->len, s->p);
9969
  }
9970
  mg_printf(nc, "Sec-WebSocket-Accept: %s%s", b64_sha, "\r\n\r\n");
9971

    
9972
  DBG(("%p %.*s %s", nc, (int) key->len, key->p, b64_sha));
9973
}
9974

    
9975
void mg_send_websocket_handshake2(struct mg_connection *nc, const char *path,
9976
                                  const char *host, const char *protocol,
9977
                                  const char *extra_headers) {
9978
  mg_send_websocket_handshake3(nc, path, host, protocol, extra_headers, NULL,
9979
                               NULL);
9980
}
9981

    
9982
void mg_send_websocket_handshake3(struct mg_connection *nc, const char *path,
9983
                                  const char *host, const char *protocol,
9984
                                  const char *extra_headers, const char *user,
9985
                                  const char *pass) {
9986
  mg_send_websocket_handshake3v(nc, mg_mk_str(path), mg_mk_str(host),
9987
                                mg_mk_str(protocol), mg_mk_str(extra_headers),
9988
                                mg_mk_str(user), mg_mk_str(pass));
9989
}
9990

    
9991
void mg_send_websocket_handshake3v(struct mg_connection *nc,
9992
                                   const struct mg_str path,
9993
                                   const struct mg_str host,
9994
                                   const struct mg_str protocol,
9995
                                   const struct mg_str extra_headers,
9996
                                   const struct mg_str user,
9997
                                   const struct mg_str pass) {
9998
  struct mbuf auth;
9999
  char key[25];
10000
  uint32_t nonce[4];
10001
  nonce[0] = mg_ws_random_mask();
10002
  nonce[1] = mg_ws_random_mask();
10003
  nonce[2] = mg_ws_random_mask();
10004
  nonce[3] = mg_ws_random_mask();
10005
  mg_base64_encode((unsigned char *) &nonce, sizeof(nonce), key);
10006

    
10007
  mbuf_init(&auth, 0);
10008
  if (user.len > 0) {
10009
    mg_basic_auth_header(user, pass, &auth);
10010
  }
10011

    
10012
  /*
10013
   * NOTE: the  (auth.buf == NULL ? "" : auth.buf) is because cc3200 libc is
10014
   * broken: it doesn't like zero length to be passed to %.*s
10015
   * i.e. sprintf("f%.*so", (int)0, NULL), yields `f\0o`.
10016
   * because it handles NULL specially (and incorrectly).
10017
   */
10018
  mg_printf(nc,
10019
            "GET %.*s HTTP/1.1\r\n"
10020
            "Upgrade: websocket\r\n"
10021
            "Connection: Upgrade\r\n"
10022
            "%.*s"
10023
            "Sec-WebSocket-Version: 13\r\n"
10024
            "Sec-WebSocket-Key: %s\r\n",
10025
            (int) path.len, path.p, (int) auth.len,
10026
            (auth.buf == NULL ? "" : auth.buf), key);
10027

    
10028
  /* TODO(mkm): take default hostname from http proto data if host == NULL */
10029
  if (host.len > 0) {
10030
    int host_len = (int) (path.p - host.p); /* Account for possible :PORT */
10031
    mg_printf(nc, "Host: %.*s\r\n", host_len, host.p);
10032
  }
10033
  if (protocol.len > 0) {
10034
    mg_printf(nc, "Sec-WebSocket-Protocol: %.*s\r\n", (int) protocol.len,
10035
              protocol.p);
10036
  }
10037
  if (extra_headers.len > 0) {
10038
    mg_printf(nc, "%.*s", (int) extra_headers.len, extra_headers.p);
10039
  }
10040
  mg_printf(nc, "\r\n");
10041

    
10042
  mbuf_free(&auth);
10043
}
10044

    
10045
void mg_send_websocket_handshake(struct mg_connection *nc, const char *path,
10046
                                 const char *extra_headers) {
10047
  struct mg_str null_str = MG_NULL_STR;
10048
  mg_send_websocket_handshake3v(
10049
      nc, mg_mk_str(path), null_str /* host */, null_str /* protocol */,
10050
      mg_mk_str(extra_headers), null_str /* user */, null_str /* pass */);
10051
}
10052

    
10053
struct mg_connection *mg_connect_ws_opt(
10054
    struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data),
10055
    struct mg_connect_opts opts, const char *url, const char *protocol,
10056
    const char *extra_headers) {
10057
  struct mg_str null_str = MG_NULL_STR;
10058
  struct mg_str host = MG_NULL_STR, path = MG_NULL_STR, user_info = MG_NULL_STR;
10059
  struct mg_connection *nc =
10060
      mg_connect_http_base(mgr, MG_CB(ev_handler, user_data), opts, "http",
10061
                           "ws", "https", "wss", url, &path, &user_info, &host);
10062
  if (nc != NULL) {
10063
    mg_send_websocket_handshake3v(nc, path, host, mg_mk_str(protocol),
10064
                                  mg_mk_str(extra_headers), user_info,
10065
                                  null_str);
10066
  }
10067
  return nc;
10068
}
10069

    
10070
struct mg_connection *mg_connect_ws(
10071
    struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data),
10072
    const char *url, const char *protocol, const char *extra_headers) {
10073
  struct mg_connect_opts opts;
10074
  memset(&opts, 0, sizeof(opts));
10075
  return mg_connect_ws_opt(mgr, MG_CB(ev_handler, user_data), opts, url,
10076
                           protocol, extra_headers);
10077
}
10078
#endif /* MG_ENABLE_HTTP && MG_ENABLE_HTTP_WEBSOCKET */
10079
#ifdef MG_MODULE_LINES
10080
#line 1 "mongoose/src/mg_util.c"
10081
#endif
10082
/*
10083
 * Copyright (c) 2014 Cesanta Software Limited
10084
 * All rights reserved
10085
 */
10086

    
10087
/* Amalgamated: #include "common/cs_base64.h" */
10088
/* Amalgamated: #include "mg_internal.h" */
10089
/* Amalgamated: #include "mg_util.h" */
10090

    
10091
/* For platforms with limited libc */
10092
#ifndef MAX
10093
#define MAX(a, b) ((a) > (b) ? (a) : (b))
10094
#endif
10095

    
10096
const char *mg_skip(const char *s, const char *end, const char *delims,
10097
                    struct mg_str *v) {
10098
  v->p = s;
10099
  while (s < end && strchr(delims, *(unsigned char *) s) == NULL) s++;
10100
  v->len = s - v->p;
10101
  while (s < end && strchr(delims, *(unsigned char *) s) != NULL) s++;
10102
  return s;
10103
}
10104

    
10105
#if MG_ENABLE_FILESYSTEM && !defined(MG_USER_FILE_FUNCTIONS)
10106
int mg_stat(const char *path, cs_stat_t *st) {
10107
#ifdef _WIN32
10108
  wchar_t wpath[MG_MAX_PATH];
10109
  to_wchar(path, wpath, ARRAY_SIZE(wpath));
10110
  DBG(("[%ls] -> %d", wpath, _wstati64(wpath, st)));
10111
  return _wstati64(wpath, st);
10112
#else
10113
  return stat(path, st);
10114
#endif
10115
}
10116

    
10117
FILE *mg_fopen(const char *path, const char *mode) {
10118
#ifdef _WIN32
10119
  wchar_t wpath[MG_MAX_PATH], wmode[10];
10120
  to_wchar(path, wpath, ARRAY_SIZE(wpath));
10121
  to_wchar(mode, wmode, ARRAY_SIZE(wmode));
10122
  return _wfopen(wpath, wmode);
10123
#else
10124
  return fopen(path, mode);
10125
#endif
10126
}
10127

    
10128
int mg_open(const char *path, int flag, int mode) { /* LCOV_EXCL_LINE */
10129
#if defined(_WIN32) && !defined(WINCE)
10130
  wchar_t wpath[MG_MAX_PATH];
10131
  to_wchar(path, wpath, ARRAY_SIZE(wpath));
10132
  return _wopen(wpath, flag, mode);
10133
#else
10134
  return open(path, flag, mode); /* LCOV_EXCL_LINE */
10135
#endif
10136
}
10137

    
10138
size_t mg_fread(void *ptr, size_t size, size_t count, FILE *f) {
10139
  return fread(ptr, size, count, f);
10140
}
10141

    
10142
size_t mg_fwrite(const void *ptr, size_t size, size_t count, FILE *f) {
10143
  return fwrite(ptr, size, count, f);
10144
}
10145
#endif
10146

    
10147
void mg_base64_encode(const unsigned char *src, int src_len, char *dst) {
10148
  cs_base64_encode(src, src_len, dst);
10149
}
10150

    
10151
int mg_base64_decode(const unsigned char *s, int len, char *dst) {
10152
  return cs_base64_decode(s, len, dst, NULL);
10153
}
10154

    
10155
#if MG_ENABLE_THREADS
10156
void *mg_start_thread(void *(*f)(void *), void *p) {
10157
#ifdef WINCE
10158
  return (void *) CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) f, p, 0, NULL);
10159
#elif defined(_WIN32)
10160
  return (void *) _beginthread((void(__cdecl *) (void *) ) f, 0, p);
10161
#else
10162
  pthread_t thread_id = (pthread_t) 0;
10163
  pthread_attr_t attr;
10164

    
10165
  (void) pthread_attr_init(&attr);
10166
  (void) pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
10167

    
10168
#if defined(MG_STACK_SIZE) && MG_STACK_SIZE > 1
10169
  (void) pthread_attr_setstacksize(&attr, MG_STACK_SIZE);
10170
#endif
10171

    
10172
  pthread_create(&thread_id, &attr, f, p);
10173
  pthread_attr_destroy(&attr);
10174

    
10175
  return (void *) thread_id;
10176
#endif
10177
}
10178
#endif /* MG_ENABLE_THREADS */
10179

    
10180
/* Set close-on-exec bit for a given socket. */
10181
void mg_set_close_on_exec(sock_t sock) {
10182
#if defined(_WIN32) && !defined(WINCE)
10183
  (void) SetHandleInformation((HANDLE) sock, HANDLE_FLAG_INHERIT, 0);
10184
#elif defined(__unix__)
10185
  fcntl(sock, F_SETFD, FD_CLOEXEC);
10186
#else
10187
  (void) sock;
10188
#endif
10189
}
10190

    
10191
int mg_sock_addr_to_str(const union socket_address *sa, char *buf, size_t len,
10192
                        int flags) {
10193
  int is_v6;
10194
  if (buf == NULL || len <= 0) return 0;
10195
  memset(buf, 0, len);
10196
#if MG_ENABLE_IPV6
10197
  is_v6 = sa->sa.sa_family == AF_INET6;
10198
#else
10199
  is_v6 = 0;
10200
#endif
10201
  if (flags & MG_SOCK_STRINGIFY_IP) {
10202
#if MG_ENABLE_IPV6
10203
    const void *addr = NULL;
10204
    char *start = buf;
10205
    socklen_t capacity = len;
10206
    if (!is_v6) {
10207
      addr = &sa->sin.sin_addr;
10208
    } else {
10209
      addr = (void *) &sa->sin6.sin6_addr;
10210
      if (flags & MG_SOCK_STRINGIFY_PORT) {
10211
        *buf = '[';
10212
        start++;
10213
        capacity--;
10214
      }
10215
    }
10216
    if (inet_ntop(sa->sa.sa_family, addr, start, capacity) == NULL) {
10217
      goto cleanup;
10218
    }
10219
#elif defined(_WIN32) || MG_LWIP || (MG_NET_IF == MG_NET_IF_PIC32)
10220
    /* Only Windoze Vista (and newer) have inet_ntop() */
10221
    char *addr_str = inet_ntoa(sa->sin.sin_addr);
10222
    if (addr_str != NULL) {
10223
      strncpy(buf, inet_ntoa(sa->sin.sin_addr), len - 1);
10224
    } else {
10225
      goto cleanup;
10226
    }
10227
#else
10228
    if (inet_ntop(AF_INET, (void *) &sa->sin.sin_addr, buf, len - 1) == NULL) {
10229
      goto cleanup;
10230
    }
10231
#endif
10232
  }
10233
  if (flags & MG_SOCK_STRINGIFY_PORT) {
10234
    int port = ntohs(sa->sin.sin_port);
10235
    if (flags & MG_SOCK_STRINGIFY_IP) {
10236
      int buf_len = strlen(buf);
10237
      snprintf(buf + buf_len, len - (buf_len + 1), "%s:%d", (is_v6 ? "]" : ""),
10238
               port);
10239
    } else {
10240
      snprintf(buf, len, "%d", port);
10241
    }
10242
  }
10243

    
10244
  return strlen(buf);
10245

    
10246
cleanup:
10247
  *buf = '\0';
10248
  return 0;
10249
}
10250

    
10251
int mg_conn_addr_to_str(struct mg_connection *nc, char *buf, size_t len,
10252
                        int flags) {
10253
  union socket_address sa;
10254
  memset(&sa, 0, sizeof(sa));
10255
  mg_if_get_conn_addr(nc, flags & MG_SOCK_STRINGIFY_REMOTE, &sa);
10256
  return mg_sock_addr_to_str(&sa, buf, len, flags);
10257
}
10258

    
10259
#if MG_ENABLE_HEXDUMP
10260
static int mg_hexdump_n(const void *buf, int len, char *dst, int dst_len,
10261
                        int offset) {
10262
  const unsigned char *p = (const unsigned char *) buf;
10263
  char ascii[17] = "";
10264
  int i, idx, n = 0;
10265

    
10266
  for (i = 0; i < len; i++) {
10267
    idx = i % 16;
10268
    if (idx == 0) {
10269
      if (i > 0) n += snprintf(dst + n, MAX(dst_len - n, 0), "  %s\n", ascii);
10270
      n += snprintf(dst + n, MAX(dst_len - n, 0), "%04x ", i + offset);
10271
    }
10272
    if (dst_len - n < 0) {
10273
      return n;
10274
    }
10275
    n += snprintf(dst + n, MAX(dst_len - n, 0), " %02x", p[i]);
10276
    ascii[idx] = p[i] < 0x20 || p[i] > 0x7e ? '.' : p[i];
10277
    ascii[idx + 1] = '\0';
10278
  }
10279

    
10280
  while (i++ % 16) n += snprintf(dst + n, MAX(dst_len - n, 0), "%s", "   ");
10281
  n += snprintf(dst + n, MAX(dst_len - n, 0), "  %s\n", ascii);
10282

    
10283
  return n;
10284
}
10285

    
10286
int mg_hexdump(const void *buf, int len, char *dst, int dst_len) {
10287
  return mg_hexdump_n(buf, len, dst, dst_len, 0);
10288
}
10289

    
10290
void mg_hexdumpf(FILE *fp, const void *buf, int len) {
10291
  char tmp[80];
10292
  int offset = 0, n;
10293
  while (len > 0) {
10294
    n = (len < 16 ? len : 16);
10295
    mg_hexdump_n(((const char *) buf) + offset, n, tmp, sizeof(tmp), offset);
10296
    fputs(tmp, fp);
10297
    offset += n;
10298
    len -= n;
10299
  }
10300
}
10301

    
10302
void mg_hexdump_connection(struct mg_connection *nc, const char *path,
10303
                           const void *buf, int num_bytes, int ev) {
10304
  FILE *fp = NULL;
10305
  char src[60], dst[60];
10306
  const char *tag = NULL;
10307
  switch (ev) {
10308
    case MG_EV_RECV:
10309
      tag = "<-";
10310
      break;
10311
    case MG_EV_SEND:
10312
      tag = "->";
10313
      break;
10314
    case MG_EV_ACCEPT:
10315
      tag = "<A";
10316
      break;
10317
    case MG_EV_CONNECT:
10318
      tag = "C>";
10319
      break;
10320
    case MG_EV_CLOSE:
10321
      tag = "XX";
10322
      break;
10323
  }
10324
  if (tag == NULL) return; /* Don't log MG_EV_TIMER, etc */
10325

    
10326
  if (strcmp(path, "-") == 0) {
10327
    fp = stdout;
10328
  } else if (strcmp(path, "--") == 0) {
10329
    fp = stderr;
10330
#if MG_ENABLE_FILESYSTEM
10331
  } else {
10332
    fp = mg_fopen(path, "a");
10333
#endif
10334
  }
10335
  if (fp == NULL) return;
10336

    
10337
  mg_conn_addr_to_str(nc, src, sizeof(src),
10338
                      MG_SOCK_STRINGIFY_IP | MG_SOCK_STRINGIFY_PORT);
10339
  mg_conn_addr_to_str(nc, dst, sizeof(dst), MG_SOCK_STRINGIFY_IP |
10340
                                                MG_SOCK_STRINGIFY_PORT |
10341
                                                MG_SOCK_STRINGIFY_REMOTE);
10342
  fprintf(fp, "%lu %p %s %s %s %d\n", (unsigned long) mg_time(), (void *) nc,
10343
          src, tag, dst, (int) num_bytes);
10344
  if (num_bytes > 0) {
10345
    mg_hexdumpf(fp, buf, num_bytes);
10346
  }
10347
  if (fp != stdout && fp != stderr) fclose(fp);
10348
}
10349
#endif
10350

    
10351
int mg_is_big_endian(void) {
10352
  static const int n = 1;
10353
  /* TODO(mkm) use compiletime check with 4-byte char literal */
10354
  return ((char *) &n)[0] == 0;
10355
}
10356

    
10357
DO_NOT_WARN_UNUSED MG_INTERNAL int mg_get_errno(void) {
10358
#ifndef WINCE
10359
  return errno;
10360
#else
10361
  /* TODO(alashkin): translate error codes? */
10362
  return GetLastError();
10363
#endif
10364
}
10365

    
10366
void mg_mbuf_append_base64_putc(char ch, void *user_data) {
10367
  struct mbuf *mbuf = (struct mbuf *) user_data;
10368
  mbuf_append(mbuf, &ch, sizeof(ch));
10369
}
10370

    
10371
void mg_mbuf_append_base64(struct mbuf *mbuf, const void *data, size_t len) {
10372
  struct cs_base64_ctx ctx;
10373
  cs_base64_init(&ctx, mg_mbuf_append_base64_putc, mbuf);
10374
  cs_base64_update(&ctx, (const char *) data, len);
10375
  cs_base64_finish(&ctx);
10376
}
10377

    
10378
void mg_basic_auth_header(const struct mg_str user, const struct mg_str pass,
10379
                          struct mbuf *buf) {
10380
  const char *header_prefix = "Authorization: Basic ";
10381
  const char *header_suffix = "\r\n";
10382

    
10383
  struct cs_base64_ctx ctx;
10384
  cs_base64_init(&ctx, mg_mbuf_append_base64_putc, buf);
10385

    
10386
  mbuf_append(buf, header_prefix, strlen(header_prefix));
10387

    
10388
  cs_base64_update(&ctx, user.p, user.len);
10389
  if (pass.len > 0) {
10390
    cs_base64_update(&ctx, ":", 1);
10391
    cs_base64_update(&ctx, pass.p, pass.len);
10392
  }
10393
  cs_base64_finish(&ctx);
10394
  mbuf_append(buf, header_suffix, strlen(header_suffix));
10395
}
10396

    
10397
struct mg_str mg_url_encode(const struct mg_str src) {
10398
  static const char *dont_escape = "._-$,;~()/";
10399
  static const char *hex = "0123456789abcdef";
10400
  size_t i = 0;
10401
  struct mbuf mb;
10402
  mbuf_init(&mb, src.len);
10403

    
10404
  for (i = 0; i < src.len; i++) {
10405
    const unsigned char c = *((const unsigned char *) src.p + i);
10406
    if (isalnum(c) || strchr(dont_escape, c) != NULL) {
10407
      mbuf_append(&mb, &c, 1);
10408
    } else {
10409
      mbuf_append(&mb, "%", 1);
10410
      mbuf_append(&mb, &hex[c >> 4], 1);
10411
      mbuf_append(&mb, &hex[c & 15], 1);
10412
    }
10413
  }
10414
  mbuf_append(&mb, "", 1);
10415
  mbuf_trim(&mb);
10416
  return mg_mk_str_n(mb.buf, mb.len - 1);
10417
}
10418
#ifdef MG_MODULE_LINES
10419
#line 1 "mongoose/src/mg_mqtt.c"
10420
#endif
10421
/*
10422
 * Copyright (c) 2014 Cesanta Software Limited
10423
 * All rights reserved
10424
 */
10425

    
10426
#if MG_ENABLE_MQTT
10427

    
10428
#include <string.h>
10429

    
10430
/* Amalgamated: #include "mg_internal.h" */
10431
/* Amalgamated: #include "mg_mqtt.h" */
10432

    
10433
static uint16_t getu16(const char *p) {
10434
  const uint8_t *up = (const uint8_t *) p;
10435
  return (up[0] << 8) + up[1];
10436
}
10437

    
10438
static const char *scanto(const char *p, struct mg_str *s) {
10439
  s->len = getu16(p);
10440
  s->p = p + 2;
10441
  return s->p + s->len;
10442
}
10443

    
10444
MG_INTERNAL int parse_mqtt(struct mbuf *io, struct mg_mqtt_message *mm) {
10445
  uint8_t header;
10446
  size_t len = 0, len_len = 0;
10447
  const char *p, *end;
10448
  unsigned char lc = 0;
10449
  int cmd;
10450

    
10451
  if (io->len < 2) return MG_MQTT_ERROR_INCOMPLETE_MSG;
10452
  header = io->buf[0];
10453
  cmd = header >> 4;
10454

    
10455
  /* decode mqtt variable length */
10456
  len = len_len = 0;
10457
  p = io->buf + 1;
10458
  while ((size_t)(p - io->buf) < io->len) {
10459
    lc = *((const unsigned char *) p++);
10460
    len += (lc & 0x7f) << 7 * len_len;
10461
    len_len++;
10462
    if (!(lc & 0x80)) break;
10463
    if (len_len > 4) return MG_MQTT_ERROR_MALFORMED_MSG;
10464
  }
10465

    
10466
  end = p + len;
10467
  if (lc & 0x80 || len > (io->len - (p - io->buf))) {
10468
    return MG_MQTT_ERROR_INCOMPLETE_MSG;
10469
  }
10470

    
10471
  mm->cmd = cmd;
10472
  mm->qos = MG_MQTT_GET_QOS(header);
10473

    
10474
  switch (cmd) {
10475
    case MG_MQTT_CMD_CONNECT: {
10476
      p = scanto(p, &mm->protocol_name);
10477
      if (p > end - 4) return MG_MQTT_ERROR_MALFORMED_MSG;
10478
      mm->protocol_version = *(uint8_t *) p++;
10479
      mm->connect_flags = *(uint8_t *) p++;
10480
      mm->keep_alive_timer = getu16(p);
10481
      p += 2;
10482
      if (p >= end) return MG_MQTT_ERROR_MALFORMED_MSG;
10483
      p = scanto(p, &mm->client_id);
10484
      if (p > end) return MG_MQTT_ERROR_MALFORMED_MSG;
10485
      if (mm->connect_flags & MG_MQTT_HAS_WILL) {
10486
        if (p >= end) return MG_MQTT_ERROR_MALFORMED_MSG;
10487
        p = scanto(p, &mm->will_topic);
10488
      }
10489
      if (mm->connect_flags & MG_MQTT_HAS_WILL) {
10490
        if (p >= end) return MG_MQTT_ERROR_MALFORMED_MSG;
10491
        p = scanto(p, &mm->will_message);
10492
      }
10493
      if (mm->connect_flags & MG_MQTT_HAS_USER_NAME) {
10494
        if (p >= end) return MG_MQTT_ERROR_MALFORMED_MSG;
10495
        p = scanto(p, &mm->user_name);
10496
      }
10497
      if (mm->connect_flags & MG_MQTT_HAS_PASSWORD) {
10498
        if (p >= end) return MG_MQTT_ERROR_MALFORMED_MSG;
10499
        p = scanto(p, &mm->password);
10500
      }
10501
      if (p != end) return MG_MQTT_ERROR_MALFORMED_MSG;
10502

    
10503
      LOG(LL_DEBUG,
10504
          ("%d %2x %d proto [%.*s] client_id [%.*s] will_topic [%.*s] "
10505
           "will_msg [%.*s] user_name [%.*s] password [%.*s]",
10506
           (int) len, (int) mm->connect_flags, (int) mm->keep_alive_timer,
10507
           (int) mm->protocol_name.len, mm->protocol_name.p,
10508
           (int) mm->client_id.len, mm->client_id.p, (int) mm->will_topic.len,
10509
           mm->will_topic.p, (int) mm->will_message.len, mm->will_message.p,
10510
           (int) mm->user_name.len, mm->user_name.p, (int) mm->password.len,
10511
           mm->password.p));
10512
      break;
10513
    }
10514
    case MG_MQTT_CMD_CONNACK:
10515
      if (end - p < 2) return MG_MQTT_ERROR_MALFORMED_MSG;
10516
      mm->connack_ret_code = p[1];
10517
      break;
10518
    case MG_MQTT_CMD_PUBACK:
10519
    case MG_MQTT_CMD_PUBREC:
10520
    case MG_MQTT_CMD_PUBREL:
10521
    case MG_MQTT_CMD_PUBCOMP:
10522
    case MG_MQTT_CMD_SUBACK:
10523
      mm->message_id = getu16(p);
10524
      break;
10525
    case MG_MQTT_CMD_PUBLISH: {
10526
      p = scanto(p, &mm->topic);
10527
      if (p > end) return MG_MQTT_ERROR_MALFORMED_MSG;
10528
      if (mm->qos > 0) {
10529
        if (end - p < 2) return MG_MQTT_ERROR_MALFORMED_MSG;
10530
        mm->message_id = getu16(p);
10531
        p += 2;
10532
      }
10533
      mm->payload.p = p;
10534
      mm->payload.len = end - p;
10535
      break;
10536
    }
10537
    case MG_MQTT_CMD_SUBSCRIBE:
10538
      if (end - p < 2) return MG_MQTT_ERROR_MALFORMED_MSG;
10539
      mm->message_id = getu16(p);
10540
      p += 2;
10541
      /*
10542
       * topic expressions are left in the payload and can be parsed with
10543
       * `mg_mqtt_next_subscribe_topic`
10544
       */
10545
      mm->payload.p = p;
10546
      mm->payload.len = end - p;
10547
      break;
10548
    default:
10549
      /* Unhandled command */
10550
      break;
10551
  }
10552

    
10553
  mm->len = end - io->buf;
10554
  return mm->len;
10555
}
10556

    
10557
static void mqtt_handler(struct mg_connection *nc, int ev,
10558
                         void *ev_data MG_UD_ARG(void *user_data)) {
10559
  struct mbuf *io = &nc->recv_mbuf;
10560
  struct mg_mqtt_message mm;
10561
  memset(&mm, 0, sizeof(mm));
10562

    
10563
  nc->handler(nc, ev, ev_data MG_UD_ARG(user_data));
10564

    
10565
  switch (ev) {
10566
    case MG_EV_ACCEPT:
10567
      if (nc->proto_data == NULL) mg_set_protocol_mqtt(nc);
10568
      break;
10569
    case MG_EV_RECV: {
10570
      /* There can be multiple messages in the buffer, process them all. */
10571
      while (1) {
10572
        int len = parse_mqtt(io, &mm);
10573
        if (len < 0) {
10574
          if (len == MG_MQTT_ERROR_MALFORMED_MSG) {
10575
            /* Protocol error. */
10576
            nc->flags |= MG_F_CLOSE_IMMEDIATELY;
10577
          } else if (len == MG_MQTT_ERROR_INCOMPLETE_MSG) {
10578
            /* Not fully buffered, let's check if we have a chance to get more
10579
             * data later */
10580
            if (nc->recv_mbuf_limit > 0 &&
10581
                nc->recv_mbuf.len >= nc->recv_mbuf_limit) {
10582
              LOG(LL_ERROR, ("%p recv buffer (%lu bytes) exceeds the limit "
10583
                             "%lu bytes, and not drained, closing",
10584
                             nc, (unsigned long) nc->recv_mbuf.len,
10585
                             (unsigned long) nc->recv_mbuf_limit));
10586
              nc->flags |= MG_F_CLOSE_IMMEDIATELY;
10587
            }
10588
          } else {
10589
            /* Should never be here */
10590
            LOG(LL_ERROR, ("%p invalid len: %d, closing", nc, len));
10591
            nc->flags |= MG_F_CLOSE_IMMEDIATELY;
10592
          }
10593
          break;
10594
        }
10595

    
10596
        nc->handler(nc, MG_MQTT_EVENT_BASE + mm.cmd, &mm MG_UD_ARG(user_data));
10597
        mbuf_remove(io, len);
10598
      }
10599
      break;
10600
    }
10601
    case MG_EV_POLL: {
10602
      struct mg_mqtt_proto_data *pd =
10603
          (struct mg_mqtt_proto_data *) nc->proto_data;
10604
      double now = mg_time();
10605
      if (pd->keep_alive > 0 && pd->last_control_time > 0 &&
10606
          (now - pd->last_control_time) > pd->keep_alive) {
10607
        LOG(LL_DEBUG, ("Send PINGREQ"));
10608
        mg_mqtt_ping(nc);
10609
      }
10610
      break;
10611
    }
10612
  }
10613
}
10614

    
10615
static void mg_mqtt_proto_data_destructor(void *proto_data) {
10616
  MG_FREE(proto_data);
10617
}
10618

    
10619
int mg_mqtt_match_topic_expression(struct mg_str exp, struct mg_str topic) {
10620
  /* TODO(mkm): implement real matching */
10621
  if (memchr(exp.p, '#', exp.len)) {
10622
    /* exp `foo/#` will become `foo/` */
10623
    exp.len -= 1;
10624
    /*
10625
     * topic should be longer than the expression: e.g. topic `foo/bar` does
10626
     * match `foo/#`, but neither `foo` nor `foo/` do.
10627
     */
10628
    if (topic.len <= exp.len) {
10629
      return 0;
10630
    }
10631

    
10632
    /* Truncate topic so that it'll pass the next length check */
10633
    topic.len = exp.len;
10634
  }
10635
  if (topic.len != exp.len) {
10636
    return 0;
10637
  }
10638
  return strncmp(topic.p, exp.p, exp.len) == 0;
10639
}
10640

    
10641
int mg_mqtt_vmatch_topic_expression(const char *exp, struct mg_str topic) {
10642
  return mg_mqtt_match_topic_expression(mg_mk_str(exp), topic);
10643
}
10644

    
10645
void mg_set_protocol_mqtt(struct mg_connection *nc) {
10646
  nc->proto_handler = mqtt_handler;
10647
  nc->proto_data = MG_CALLOC(1, sizeof(struct mg_mqtt_proto_data));
10648
  nc->proto_data_destructor = mg_mqtt_proto_data_destructor;
10649
}
10650

    
10651
static void mg_mqtt_prepend_header(struct mg_connection *nc, uint8_t cmd,
10652
                                   uint8_t flags, size_t len) {
10653
  struct mg_mqtt_proto_data *pd = (struct mg_mqtt_proto_data *) nc->proto_data;
10654
  size_t off = nc->send_mbuf.len - len;
10655
  uint8_t header = cmd << 4 | (uint8_t) flags;
10656

    
10657
  uint8_t buf[1 + sizeof(size_t)];
10658
  uint8_t *vlen = &buf[1];
10659

    
10660
  assert(nc->send_mbuf.len >= len);
10661

    
10662
  buf[0] = header;
10663

    
10664
  /* mqtt variable length encoding */
10665
  do {
10666
    *vlen = len % 0x80;
10667
    len /= 0x80;
10668
    if (len > 0) *vlen |= 0x80;
10669
    vlen++;
10670
  } while (len > 0);
10671

    
10672
  mbuf_insert(&nc->send_mbuf, off, buf, vlen - buf);
10673
  pd->last_control_time = mg_time();
10674
}
10675

    
10676
void mg_send_mqtt_handshake(struct mg_connection *nc, const char *client_id) {
10677
  static struct mg_send_mqtt_handshake_opts opts;
10678
  mg_send_mqtt_handshake_opt(nc, client_id, opts);
10679
}
10680

    
10681
void mg_send_mqtt_handshake_opt(struct mg_connection *nc, const char *client_id,
10682
                                struct mg_send_mqtt_handshake_opts opts) {
10683
  uint16_t hlen, nlen, rem_len = 0;
10684
  struct mg_mqtt_proto_data *pd = (struct mg_mqtt_proto_data *) nc->proto_data;
10685

    
10686
  mg_send(nc, "\00\04MQTT\04", 7);
10687
  rem_len += 7;
10688

    
10689
  if (opts.user_name != NULL) {
10690
    opts.flags |= MG_MQTT_HAS_USER_NAME;
10691
  }
10692
  if (opts.password != NULL) {
10693
    opts.flags |= MG_MQTT_HAS_PASSWORD;
10694
  }
10695
  if (opts.will_topic != NULL && opts.will_message != NULL) {
10696
    opts.flags |= MG_MQTT_HAS_WILL;
10697
  }
10698
  if (opts.keep_alive == 0) {
10699
    opts.keep_alive = 60;
10700
  }
10701

    
10702
  mg_send(nc, &opts.flags, 1);
10703
  rem_len += 1;
10704

    
10705
  nlen = htons(opts.keep_alive);
10706
  mg_send(nc, &nlen, 2);
10707
  rem_len += 2;
10708

    
10709
  hlen = strlen(client_id);
10710
  nlen = htons((uint16_t) hlen);
10711
  mg_send(nc, &nlen, 2);
10712
  mg_send(nc, client_id, hlen);
10713
  rem_len += 2 + hlen;
10714

    
10715
  if (opts.flags & MG_MQTT_HAS_WILL) {
10716
    hlen = strlen(opts.will_topic);
10717
    nlen = htons((uint16_t) hlen);
10718
    mg_send(nc, &nlen, 2);
10719
    mg_send(nc, opts.will_topic, hlen);
10720
    rem_len += 2 + hlen;
10721

    
10722
    hlen = strlen(opts.will_message);
10723
    nlen = htons((uint16_t) hlen);
10724
    mg_send(nc, &nlen, 2);
10725
    mg_send(nc, opts.will_message, hlen);
10726
    rem_len += 2 + hlen;
10727
  }
10728

    
10729
  if (opts.flags & MG_MQTT_HAS_USER_NAME) {
10730
    hlen = strlen(opts.user_name);
10731
    nlen = htons((uint16_t) hlen);
10732
    mg_send(nc, &nlen, 2);
10733
    mg_send(nc, opts.user_name, hlen);
10734
    rem_len += 2 + hlen;
10735
  }
10736
  if (opts.flags & MG_MQTT_HAS_PASSWORD) {
10737
    hlen = strlen(opts.password);
10738
    nlen = htons((uint16_t) hlen);
10739
    mg_send(nc, &nlen, 2);
10740
    mg_send(nc, opts.password, hlen);
10741
    rem_len += 2 + hlen;
10742
  }
10743

    
10744
  mg_mqtt_prepend_header(nc, MG_MQTT_CMD_CONNECT, 0, rem_len);
10745

    
10746
  if (pd != NULL) {
10747
    pd->keep_alive = opts.keep_alive;
10748
  }
10749
}
10750

    
10751
void mg_mqtt_publish(struct mg_connection *nc, const char *topic,
10752
                     uint16_t message_id, int flags, const void *data,
10753
                     size_t len) {
10754
  size_t old_len = nc->send_mbuf.len;
10755

    
10756
  uint16_t topic_len = htons((uint16_t) strlen(topic));
10757
  uint16_t message_id_net = htons(message_id);
10758

    
10759
  mg_send(nc, &topic_len, 2);
10760
  mg_send(nc, topic, strlen(topic));
10761
  if (MG_MQTT_GET_QOS(flags) > 0) {
10762
    mg_send(nc, &message_id_net, 2);
10763
  }
10764
  mg_send(nc, data, len);
10765

    
10766
  mg_mqtt_prepend_header(nc, MG_MQTT_CMD_PUBLISH, flags,
10767
                         nc->send_mbuf.len - old_len);
10768
}
10769

    
10770
void mg_mqtt_subscribe(struct mg_connection *nc,
10771
                       const struct mg_mqtt_topic_expression *topics,
10772
                       size_t topics_len, uint16_t message_id) {
10773
  size_t old_len = nc->send_mbuf.len;
10774

    
10775
  uint16_t message_id_n = htons(message_id);
10776
  size_t i;
10777

    
10778
  mg_send(nc, (char *) &message_id_n, 2);
10779
  for (i = 0; i < topics_len; i++) {
10780
    uint16_t topic_len_n = htons((uint16_t) strlen(topics[i].topic));
10781
    mg_send(nc, &topic_len_n, 2);
10782
    mg_send(nc, topics[i].topic, strlen(topics[i].topic));
10783
    mg_send(nc, &topics[i].qos, 1);
10784
  }
10785

    
10786
  mg_mqtt_prepend_header(nc, MG_MQTT_CMD_SUBSCRIBE, MG_MQTT_QOS(1),
10787
                         nc->send_mbuf.len - old_len);
10788
}
10789

    
10790
int mg_mqtt_next_subscribe_topic(struct mg_mqtt_message *msg,
10791
                                 struct mg_str *topic, uint8_t *qos, int pos) {
10792
  unsigned char *buf = (unsigned char *) msg->payload.p + pos;
10793
  int new_pos;
10794

    
10795
  if ((size_t) pos >= msg->payload.len) return -1;
10796

    
10797
  topic->len = buf[0] << 8 | buf[1];
10798
  topic->p = (char *) buf + 2;
10799
  new_pos = pos + 2 + topic->len + 1;
10800
  if ((size_t) new_pos > msg->payload.len) return -1;
10801
  *qos = buf[2 + topic->len];
10802
  return new_pos;
10803
}
10804

    
10805
void mg_mqtt_unsubscribe(struct mg_connection *nc, char **topics,
10806
                         size_t topics_len, uint16_t message_id) {
10807
  size_t old_len = nc->send_mbuf.len;
10808

    
10809
  uint16_t message_id_n = htons(message_id);
10810
  size_t i;
10811

    
10812
  mg_send(nc, (char *) &message_id_n, 2);
10813
  for (i = 0; i < topics_len; i++) {
10814
    uint16_t topic_len_n = htons((uint16_t) strlen(topics[i]));
10815
    mg_send(nc, &topic_len_n, 2);
10816
    mg_send(nc, topics[i], strlen(topics[i]));
10817
  }
10818

    
10819
  mg_mqtt_prepend_header(nc, MG_MQTT_CMD_UNSUBSCRIBE, MG_MQTT_QOS(1),
10820
                         nc->send_mbuf.len - old_len);
10821
}
10822

    
10823
void mg_mqtt_connack(struct mg_connection *nc, uint8_t return_code) {
10824
  uint8_t unused = 0;
10825
  mg_send(nc, &unused, 1);
10826
  mg_send(nc, &return_code, 1);
10827
  mg_mqtt_prepend_header(nc, MG_MQTT_CMD_CONNACK, 0, 2);
10828
}
10829

    
10830
/*
10831
 * Sends a command which contains only a `message_id` and a QoS level of 1.
10832
 *
10833
 * Helper function.
10834
 */
10835
static void mg_send_mqtt_short_command(struct mg_connection *nc, uint8_t cmd,
10836
                                       uint16_t message_id) {
10837
  uint16_t message_id_net = htons(message_id);
10838
  uint8_t flags = (cmd == MG_MQTT_CMD_PUBREL ? 2 : 0);
10839
  mg_send(nc, &message_id_net, 2);
10840
  mg_mqtt_prepend_header(nc, cmd, flags, 2 /* len */);
10841
}
10842

    
10843
void mg_mqtt_puback(struct mg_connection *nc, uint16_t message_id) {
10844
  mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBACK, message_id);
10845
}
10846

    
10847
void mg_mqtt_pubrec(struct mg_connection *nc, uint16_t message_id) {
10848
  mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBREC, message_id);
10849
}
10850

    
10851
void mg_mqtt_pubrel(struct mg_connection *nc, uint16_t message_id) {
10852
  mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBREL, message_id);
10853
}
10854

    
10855
void mg_mqtt_pubcomp(struct mg_connection *nc, uint16_t message_id) {
10856
  mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBCOMP, message_id);
10857
}
10858

    
10859
void mg_mqtt_suback(struct mg_connection *nc, uint8_t *qoss, size_t qoss_len,
10860
                    uint16_t message_id) {
10861
  size_t i;
10862
  uint16_t message_id_net = htons(message_id);
10863
  mg_send(nc, &message_id_net, 2);
10864
  for (i = 0; i < qoss_len; i++) {
10865
    mg_send(nc, &qoss[i], 1);
10866
  }
10867
  mg_mqtt_prepend_header(nc, MG_MQTT_CMD_SUBACK, MG_MQTT_QOS(1), 2 + qoss_len);
10868
}
10869

    
10870
void mg_mqtt_unsuback(struct mg_connection *nc, uint16_t message_id) {
10871
  mg_send_mqtt_short_command(nc, MG_MQTT_CMD_UNSUBACK, message_id);
10872
}
10873

    
10874
void mg_mqtt_ping(struct mg_connection *nc) {
10875
  mg_mqtt_prepend_header(nc, MG_MQTT_CMD_PINGREQ, 0, 0);
10876
}
10877

    
10878
void mg_mqtt_pong(struct mg_connection *nc) {
10879
  mg_mqtt_prepend_header(nc, MG_MQTT_CMD_PINGRESP, 0, 0);
10880
}
10881

    
10882
void mg_mqtt_disconnect(struct mg_connection *nc) {
10883
  mg_mqtt_prepend_header(nc, MG_MQTT_CMD_DISCONNECT, 0, 0);
10884
}
10885

    
10886
#endif /* MG_ENABLE_MQTT */
10887
#ifdef MG_MODULE_LINES
10888
#line 1 "mongoose/src/mg_mqtt_server.c"
10889
#endif
10890
/*
10891
 * Copyright (c) 2014 Cesanta Software Limited
10892
 * All rights reserved
10893
 */
10894

    
10895
/* Amalgamated: #include "mg_internal.h" */
10896
/* Amalgamated: #include "mg_mqtt_server.h" */
10897

    
10898
#if MG_ENABLE_MQTT_BROKER
10899

    
10900
static void mg_mqtt_session_init(struct mg_mqtt_broker *brk,
10901
                                 struct mg_mqtt_session *s,
10902
                                 struct mg_connection *nc) {
10903
  s->brk = brk;
10904
  s->subscriptions = NULL;
10905
  s->num_subscriptions = 0;
10906
  s->nc = nc;
10907
}
10908

    
10909
static void mg_mqtt_add_session(struct mg_mqtt_session *s) {
10910
  LIST_INSERT_HEAD(&s->brk->sessions, s, link);
10911
}
10912

    
10913
static void mg_mqtt_remove_session(struct mg_mqtt_session *s) {
10914
  LIST_REMOVE(s, link);
10915
}
10916

    
10917
static void mg_mqtt_destroy_session(struct mg_mqtt_session *s) {
10918
  size_t i;
10919
  for (i = 0; i < s->num_subscriptions; i++) {
10920
    MG_FREE((void *) s->subscriptions[i].topic);
10921
  }
10922
  MG_FREE(s->subscriptions);
10923
  MG_FREE(s);
10924
}
10925

    
10926
static void mg_mqtt_close_session(struct mg_mqtt_session *s) {
10927
  mg_mqtt_remove_session(s);
10928
  mg_mqtt_destroy_session(s);
10929
}
10930

    
10931
void mg_mqtt_broker_init(struct mg_mqtt_broker *brk, void *user_data) {
10932
  LIST_INIT(&brk->sessions);
10933
  brk->user_data = user_data;
10934
}
10935

    
10936
static void mg_mqtt_broker_handle_connect(struct mg_mqtt_broker *brk,
10937
                                          struct mg_connection *nc) {
10938
  struct mg_mqtt_session *s =
10939
      (struct mg_mqtt_session *) MG_CALLOC(1, sizeof *s);
10940
  if (s == NULL) {
10941
    /* LCOV_EXCL_START */
10942
    mg_mqtt_connack(nc, MG_EV_MQTT_CONNACK_SERVER_UNAVAILABLE);
10943
    return;
10944
    /* LCOV_EXCL_STOP */
10945
  }
10946

    
10947
  /* TODO(mkm): check header (magic and version) */
10948

    
10949
  mg_mqtt_session_init(brk, s, nc);
10950
  nc->priv_2 = s;
10951
  mg_mqtt_add_session(s);
10952

    
10953
  mg_mqtt_connack(nc, MG_EV_MQTT_CONNACK_ACCEPTED);
10954
}
10955

    
10956
static void mg_mqtt_broker_handle_subscribe(struct mg_connection *nc,
10957
                                            struct mg_mqtt_message *msg) {
10958
  struct mg_mqtt_session *ss = (struct mg_mqtt_session *) nc->priv_2;
10959
  uint8_t qoss[MG_MQTT_MAX_SESSION_SUBSCRIPTIONS];
10960
  size_t num_subs = 0;
10961
  struct mg_str topic;
10962
  uint8_t qos;
10963
  int pos;
10964
  struct mg_mqtt_topic_expression *te;
10965

    
10966
  for (pos = 0;
10967
       (pos = mg_mqtt_next_subscribe_topic(msg, &topic, &qos, pos)) != -1;) {
10968
    if (num_subs >= sizeof(MG_MQTT_MAX_SESSION_SUBSCRIPTIONS) ||
10969
        (ss->num_subscriptions + num_subs >=
10970
         MG_MQTT_MAX_SESSION_SUBSCRIPTIONS)) {
10971
      nc->flags |= MG_F_CLOSE_IMMEDIATELY;
10972
      return;
10973
    }
10974
    qoss[num_subs++] = qos;
10975
  }
10976

    
10977
  if (num_subs > 0) {
10978
    te = (struct mg_mqtt_topic_expression *) MG_REALLOC(
10979
        ss->subscriptions,
10980
        sizeof(*ss->subscriptions) * (ss->num_subscriptions + num_subs));
10981
    if (te == NULL) {
10982
      nc->flags |= MG_F_CLOSE_IMMEDIATELY;
10983
      return;
10984
    }
10985
    ss->subscriptions = te;
10986
    for (pos = 0;
10987
         pos < (int) msg->payload.len &&
10988
             (pos = mg_mqtt_next_subscribe_topic(msg, &topic, &qos, pos)) != -1;
10989
         ss->num_subscriptions++) {
10990
      te = &ss->subscriptions[ss->num_subscriptions];
10991
      te->topic = (char *) MG_MALLOC(topic.len + 1);
10992
      te->qos = qos;
10993
      memcpy((char *) te->topic, topic.p, topic.len);
10994
      ((char *) te->topic)[topic.len] = '\0';
10995
    }
10996
  }
10997

    
10998
  if (pos == (int) msg->payload.len) {
10999
    mg_mqtt_suback(nc, qoss, num_subs, msg->message_id);
11000
  } else {
11001
    /* We did not fully parse the payload, something must be wrong. */
11002
    nc->flags |= MG_F_CLOSE_IMMEDIATELY;
11003
  }
11004
}
11005

    
11006
static void mg_mqtt_broker_handle_publish(struct mg_mqtt_broker *brk,
11007
                                          struct mg_mqtt_message *msg) {
11008
  struct mg_mqtt_session *s;
11009
  size_t i;
11010

    
11011
  for (s = mg_mqtt_next(brk, NULL); s != NULL; s = mg_mqtt_next(brk, s)) {
11012
    for (i = 0; i < s->num_subscriptions; i++) {
11013
      if (mg_mqtt_vmatch_topic_expression(s->subscriptions[i].topic,
11014
                                          msg->topic)) {
11015
        char buf[100], *p = buf;
11016
        mg_asprintf(&p, sizeof(buf), "%.*s", (int) msg->topic.len,
11017
                    msg->topic.p);
11018
        if (p == NULL) {
11019
          return;
11020
        }
11021
        mg_mqtt_publish(s->nc, p, 0, 0, msg->payload.p, msg->payload.len);
11022
        if (p != buf) {
11023
          MG_FREE(p);
11024
        }
11025
        break;
11026
      }
11027
    }
11028
  }
11029
}
11030

    
11031
void mg_mqtt_broker(struct mg_connection *nc, int ev, void *data) {
11032
  struct mg_mqtt_message *msg = (struct mg_mqtt_message *) data;
11033
  struct mg_mqtt_broker *brk;
11034

    
11035
  if (nc->listener) {
11036
    brk = (struct mg_mqtt_broker *) nc->listener->priv_2;
11037
  } else {
11038
    brk = (struct mg_mqtt_broker *) nc->priv_2;
11039
  }
11040

    
11041
  switch (ev) {
11042
    case MG_EV_ACCEPT:
11043
      if (nc->proto_data == NULL) mg_set_protocol_mqtt(nc);
11044
      nc->priv_2 = NULL; /* Clear up the inherited pointer to broker */
11045
      break;
11046
    case MG_EV_MQTT_CONNECT:
11047
      if (nc->priv_2 == NULL) {
11048
        mg_mqtt_broker_handle_connect(brk, nc);
11049
      } else {
11050
        /* Repeated CONNECT */
11051
        nc->flags |= MG_F_CLOSE_IMMEDIATELY;
11052
      }
11053
      break;
11054
    case MG_EV_MQTT_SUBSCRIBE:
11055
      if (nc->priv_2 != NULL) {
11056
        mg_mqtt_broker_handle_subscribe(nc, msg);
11057
      } else {
11058
        /* Subscribe before CONNECT */
11059
        nc->flags |= MG_F_CLOSE_IMMEDIATELY;
11060
      }
11061
      break;
11062
    case MG_EV_MQTT_PUBLISH:
11063
      if (nc->priv_2 != NULL) {
11064
        mg_mqtt_broker_handle_publish(brk, msg);
11065
      } else {
11066
        /* Publish before CONNECT */
11067
        nc->flags |= MG_F_CLOSE_IMMEDIATELY;
11068
      }
11069
      break;
11070
    case MG_EV_CLOSE:
11071
      if (nc->listener && nc->priv_2 != NULL) {
11072
        mg_mqtt_close_session((struct mg_mqtt_session *) nc->priv_2);
11073
      }
11074
      break;
11075
  }
11076
}
11077

    
11078
struct mg_mqtt_session *mg_mqtt_next(struct mg_mqtt_broker *brk,
11079
                                     struct mg_mqtt_session *s) {
11080
  return s == NULL ? LIST_FIRST(&brk->sessions) : LIST_NEXT(s, link);
11081
}
11082

    
11083
#endif /* MG_ENABLE_MQTT_BROKER */
11084
#ifdef MG_MODULE_LINES
11085
#line 1 "mongoose/src/mg_dns.c"
11086
#endif
11087
/*
11088
 * Copyright (c) 2014 Cesanta Software Limited
11089
 * All rights reserved
11090
 */
11091

    
11092
#if MG_ENABLE_DNS
11093

    
11094
/* Amalgamated: #include "mg_internal.h" */
11095
/* Amalgamated: #include "mg_dns.h" */
11096

    
11097
static int mg_dns_tid = 0xa0;
11098

    
11099
struct mg_dns_header {
11100
  uint16_t transaction_id;
11101
  uint16_t flags;
11102
  uint16_t num_questions;
11103
  uint16_t num_answers;
11104
  uint16_t num_authority_prs;
11105
  uint16_t num_other_prs;
11106
};
11107

    
11108
struct mg_dns_resource_record *mg_dns_next_record(
11109
    struct mg_dns_message *msg, int query,
11110
    struct mg_dns_resource_record *prev) {
11111
  struct mg_dns_resource_record *rr;
11112

    
11113
  for (rr = (prev == NULL ? msg->answers : prev + 1);
11114
       rr - msg->answers < msg->num_answers; rr++) {
11115
    if (rr->rtype == query) {
11116
      return rr;
11117
    }
11118
  }
11119
  return NULL;
11120
}
11121

    
11122
int mg_dns_parse_record_data(struct mg_dns_message *msg,
11123
                             struct mg_dns_resource_record *rr, void *data,
11124
                             size_t data_len) {
11125
  switch (rr->rtype) {
11126
    case MG_DNS_A_RECORD:
11127
      if (data_len < sizeof(struct in_addr)) {
11128
        return -1;
11129
      }
11130
      if (rr->rdata.p + data_len > msg->pkt.p + msg->pkt.len) {
11131
        return -1;
11132
      }
11133
      memcpy(data, rr->rdata.p, data_len);
11134
      return 0;
11135
#if MG_ENABLE_IPV6
11136
    case MG_DNS_AAAA_RECORD:
11137
      if (data_len < sizeof(struct in6_addr)) {
11138
        return -1; /* LCOV_EXCL_LINE */
11139
      }
11140
      memcpy(data, rr->rdata.p, data_len);
11141
      return 0;
11142
#endif
11143
    case MG_DNS_CNAME_RECORD:
11144
      mg_dns_uncompress_name(msg, &rr->rdata, (char *) data, data_len);
11145
      return 0;
11146
  }
11147

    
11148
  return -1;
11149
}
11150

    
11151
int mg_dns_insert_header(struct mbuf *io, size_t pos,
11152
                         struct mg_dns_message *msg) {
11153
  struct mg_dns_header header;
11154

    
11155
  memset(&header, 0, sizeof(header));
11156
  header.transaction_id = msg->transaction_id;
11157
  header.flags = htons(msg->flags);
11158
  header.num_questions = htons(msg->num_questions);
11159
  header.num_answers = htons(msg->num_answers);
11160

    
11161
  return mbuf_insert(io, pos, &header, sizeof(header));
11162
}
11163

    
11164
int mg_dns_copy_questions(struct mbuf *io, struct mg_dns_message *msg) {
11165
  unsigned char *begin, *end;
11166
  struct mg_dns_resource_record *last_q;
11167
  if (msg->num_questions <= 0) return 0;
11168
  begin = (unsigned char *) msg->pkt.p + sizeof(struct mg_dns_header);
11169
  last_q = &msg->questions[msg->num_questions - 1];
11170
  end = (unsigned char *) last_q->name.p + last_q->name.len + 4;
11171
  return mbuf_append(io, begin, end - begin);
11172
}
11173

    
11174
int mg_dns_encode_name(struct mbuf *io, const char *name, size_t len) {
11175
  const char *s;
11176
  unsigned char n;
11177
  size_t pos = io->len;
11178

    
11179
  do {
11180
    if ((s = strchr(name, '.')) == NULL) {
11181
      s = name + len;
11182
    }
11183

    
11184
    if (s - name > 127) {
11185
      return -1; /* TODO(mkm) cover */
11186
    }
11187
    n = s - name;           /* chunk length */
11188
    mbuf_append(io, &n, 1); /* send length */
11189
    mbuf_append(io, name, n);
11190

    
11191
    if (*s == '.') {
11192
      n++;
11193
    }
11194

    
11195
    name += n;
11196
    len -= n;
11197
  } while (*s != '\0');
11198
  mbuf_append(io, "\0", 1); /* Mark end of host name */
11199

    
11200
  return io->len - pos;
11201
}
11202

    
11203
int mg_dns_encode_record(struct mbuf *io, struct mg_dns_resource_record *rr,
11204
                         const char *name, size_t nlen, const void *rdata,
11205
                         size_t rlen) {
11206
  size_t pos = io->len;
11207
  uint16_t u16;
11208
  uint32_t u32;
11209

    
11210
  if (rr->kind == MG_DNS_INVALID_RECORD) {
11211
    return -1; /* LCOV_EXCL_LINE */
11212
  }
11213

    
11214
  if (mg_dns_encode_name(io, name, nlen) == -1) {
11215
    return -1;
11216
  }
11217

    
11218
  u16 = htons(rr->rtype);
11219
  mbuf_append(io, &u16, 2);
11220
  u16 = htons(rr->rclass);
11221
  mbuf_append(io, &u16, 2);
11222

    
11223
  if (rr->kind == MG_DNS_ANSWER) {
11224
    u32 = htonl(rr->ttl);
11225
    mbuf_append(io, &u32, 4);
11226

    
11227
    if (rr->rtype == MG_DNS_CNAME_RECORD) {
11228
      int clen;
11229
      /* fill size after encoding */
11230
      size_t off = io->len;
11231
      mbuf_append(io, &u16, 2);
11232
      if ((clen = mg_dns_encode_name(io, (const char *) rdata, rlen)) == -1) {
11233
        return -1;
11234
      }
11235
      u16 = clen;
11236
      io->buf[off] = u16 >> 8;
11237
      io->buf[off + 1] = u16 & 0xff;
11238
    } else {
11239
      u16 = htons((uint16_t) rlen);
11240
      mbuf_append(io, &u16, 2);
11241
      mbuf_append(io, rdata, rlen);
11242
    }
11243
  }
11244

    
11245
  return io->len - pos;
11246
}
11247

    
11248
void mg_send_dns_query(struct mg_connection *nc, const char *name,
11249
                       int query_type) {
11250
  struct mg_dns_message *msg =
11251
      (struct mg_dns_message *) MG_CALLOC(1, sizeof(*msg));
11252
  struct mbuf pkt;
11253
  struct mg_dns_resource_record *rr = &msg->questions[0];
11254

    
11255
  DBG(("%s %d", name, query_type));
11256

    
11257
  mbuf_init(&pkt, 64 /* Start small, it'll grow as needed. */);
11258

    
11259
  msg->transaction_id = ++mg_dns_tid;
11260
  msg->flags = 0x100;
11261
  msg->num_questions = 1;
11262

    
11263
  mg_dns_insert_header(&pkt, 0, msg);
11264

    
11265
  rr->rtype = query_type;
11266
  rr->rclass = 1; /* Class: inet */
11267
  rr->kind = MG_DNS_QUESTION;
11268

    
11269
  if (mg_dns_encode_record(&pkt, rr, name, strlen(name), NULL, 0) == -1) {
11270
    /* TODO(mkm): return an error code */
11271
    goto cleanup; /* LCOV_EXCL_LINE */
11272
  }
11273

    
11274
  /* TCP DNS requires messages to be prefixed with len */
11275
  if (!(nc->flags & MG_F_UDP)) {
11276
    uint16_t len = htons((uint16_t) pkt.len);
11277
    mbuf_insert(&pkt, 0, &len, 2);
11278
  }
11279

    
11280
  mg_send(nc, pkt.buf, pkt.len);
11281
  mbuf_free(&pkt);
11282

    
11283
cleanup:
11284
  MG_FREE(msg);
11285
}
11286

    
11287
static unsigned char *mg_parse_dns_resource_record(
11288
    unsigned char *data, unsigned char *end, struct mg_dns_resource_record *rr,
11289
    int reply) {
11290
  unsigned char *name = data;
11291
  int chunk_len, data_len;
11292

    
11293
  while (data < end && (chunk_len = *data)) {
11294
    if (((unsigned char *) data)[0] & 0xc0) {
11295
      data += 1;
11296
      break;
11297
    }
11298
    data += chunk_len + 1;
11299
  }
11300

    
11301
  if (data > end - 5) {
11302
    return NULL;
11303
  }
11304

    
11305
  rr->name.p = (char *) name;
11306
  rr->name.len = data - name + 1;
11307
  data++;
11308

    
11309
  rr->rtype = data[0] << 8 | data[1];
11310
  data += 2;
11311

    
11312
  rr->rclass = data[0] << 8 | data[1];
11313
  data += 2;
11314

    
11315
  rr->kind = reply ? MG_DNS_ANSWER : MG_DNS_QUESTION;
11316
  if (reply) {
11317
    if (data >= end - 6) {
11318
      return NULL;
11319
    }
11320

    
11321
    rr->ttl = (uint32_t) data[0] << 24 | (uint32_t) data[1] << 16 |
11322
              data[2] << 8 | data[3];
11323
    data += 4;
11324

    
11325
    data_len = *data << 8 | *(data + 1);
11326
    data += 2;
11327

    
11328
    rr->rdata.p = (char *) data;
11329
    rr->rdata.len = data_len;
11330
    data += data_len;
11331
  }
11332
  return data;
11333
}
11334

    
11335
int mg_parse_dns(const char *buf, int len, struct mg_dns_message *msg) {
11336
  struct mg_dns_header *header = (struct mg_dns_header *) buf;
11337
  unsigned char *data = (unsigned char *) buf + sizeof(*header);
11338
  unsigned char *end = (unsigned char *) buf + len;
11339
  int i;
11340

    
11341
  memset(msg, 0, sizeof(*msg));
11342
  msg->pkt.p = buf;
11343
  msg->pkt.len = len;
11344

    
11345
  if (len < (int) sizeof(*header)) return -1;
11346

    
11347
  msg->transaction_id = header->transaction_id;
11348
  msg->flags = ntohs(header->flags);
11349
  msg->num_questions = ntohs(header->num_questions);
11350
  if (msg->num_questions > (int) ARRAY_SIZE(msg->questions)) {
11351
    msg->num_questions = (int) ARRAY_SIZE(msg->questions);
11352
  }
11353
  msg->num_answers = ntohs(header->num_answers);
11354
  if (msg->num_answers > (int) ARRAY_SIZE(msg->answers)) {
11355
    msg->num_answers = (int) ARRAY_SIZE(msg->answers);
11356
  }
11357

    
11358
  for (i = 0; i < msg->num_questions; i++) {
11359
    data = mg_parse_dns_resource_record(data, end, &msg->questions[i], 0);
11360
    if (data == NULL) return -1;
11361
  }
11362

    
11363
  for (i = 0; i < msg->num_answers; i++) {
11364
    data = mg_parse_dns_resource_record(data, end, &msg->answers[i], 1);
11365
    if (data == NULL) return -1;
11366
  }
11367

    
11368
  return 0;
11369
}
11370

    
11371
size_t mg_dns_uncompress_name(struct mg_dns_message *msg, struct mg_str *name,
11372
                              char *dst, int dst_len) {
11373
  int chunk_len, num_ptrs = 0;
11374
  char *old_dst = dst;
11375
  const unsigned char *data = (unsigned char *) name->p;
11376
  const unsigned char *end = (unsigned char *) msg->pkt.p + msg->pkt.len;
11377

    
11378
  if (data >= end) {
11379
    return 0;
11380
  }
11381

    
11382
  while ((chunk_len = *data++)) {
11383
    int leeway = dst_len - (dst - old_dst);
11384
    if (data >= end) {
11385
      return 0;
11386
    }
11387

    
11388
    if ((chunk_len & 0xc0) == 0xc0) {
11389
      uint16_t off = (data[-1] & (~0xc0)) << 8 | data[0];
11390
      if (off >= msg->pkt.len) {
11391
        return 0;
11392
      }
11393
      /* Basic circular loop avoidance: allow up to 16 pointer hops. */
11394
      if (++num_ptrs > 15) {
11395
        return 0;
11396
      }
11397
      data = (unsigned char *) msg->pkt.p + off;
11398
      continue;
11399
    }
11400
    if (chunk_len > 63) {
11401
      return 0;
11402
    }
11403
    if (chunk_len > leeway) {
11404
      chunk_len = leeway;
11405
    }
11406

    
11407
    if (data + chunk_len >= end) {
11408
      return 0;
11409
    }
11410

    
11411
    memcpy(dst, data, chunk_len);
11412
    data += chunk_len;
11413
    dst += chunk_len;
11414
    leeway -= chunk_len;
11415
    if (leeway == 0) {
11416
      return dst - old_dst;
11417
    }
11418
    *dst++ = '.';
11419
  }
11420

    
11421
  if (dst != old_dst) {
11422
    *--dst = 0;
11423
  }
11424
  return dst - old_dst;
11425
}
11426

    
11427
static void dns_handler(struct mg_connection *nc, int ev,
11428
                        void *ev_data MG_UD_ARG(void *user_data)) {
11429
  struct mbuf *io = &nc->recv_mbuf;
11430
  struct mg_dns_message msg;
11431

    
11432
  /* Pass low-level events to the user handler */
11433
  nc->handler(nc, ev, ev_data MG_UD_ARG(user_data));
11434

    
11435
  switch (ev) {
11436
    case MG_EV_RECV:
11437
      if (!(nc->flags & MG_F_UDP)) {
11438
        mbuf_remove(&nc->recv_mbuf, 2);
11439
      }
11440
      if (mg_parse_dns(nc->recv_mbuf.buf, nc->recv_mbuf.len, &msg) == -1) {
11441
        /* reply + recursion allowed + format error */
11442
        memset(&msg, 0, sizeof(msg));
11443
        msg.flags = 0x8081;
11444
        mg_dns_insert_header(io, 0, &msg);
11445
        if (!(nc->flags & MG_F_UDP)) {
11446
          uint16_t len = htons((uint16_t) io->len);
11447
          mbuf_insert(io, 0, &len, 2);
11448
        }
11449
        mg_send(nc, io->buf, io->len);
11450
      } else {
11451
        /* Call user handler with parsed message */
11452
        nc->handler(nc, MG_DNS_MESSAGE, &msg MG_UD_ARG(user_data));
11453
      }
11454
      mbuf_remove(io, io->len);
11455
      break;
11456
  }
11457
}
11458

    
11459
void mg_set_protocol_dns(struct mg_connection *nc) {
11460
  nc->proto_handler = dns_handler;
11461
}
11462

    
11463
#endif /* MG_ENABLE_DNS */
11464
#ifdef MG_MODULE_LINES
11465
#line 1 "mongoose/src/mg_dns_server.c"
11466
#endif
11467
/*
11468
 * Copyright (c) 2014 Cesanta Software Limited
11469
 * All rights reserved
11470
 */
11471

    
11472
#if MG_ENABLE_DNS_SERVER
11473

    
11474
/* Amalgamated: #include "mg_internal.h" */
11475
/* Amalgamated: #include "dns-server.h" */
11476

    
11477
struct mg_dns_reply mg_dns_create_reply(struct mbuf *io,
11478
                                        struct mg_dns_message *msg) {
11479
  struct mg_dns_reply rep;
11480
  rep.msg = msg;
11481
  rep.io = io;
11482
  rep.start = io->len;
11483

    
11484
  /* reply + recursion allowed */
11485
  msg->flags |= 0x8080;
11486
  mg_dns_copy_questions(io, msg);
11487

    
11488
  msg->num_answers = 0;
11489
  return rep;
11490
}
11491

    
11492
void mg_dns_send_reply(struct mg_connection *nc, struct mg_dns_reply *r) {
11493
  size_t sent = r->io->len - r->start;
11494
  mg_dns_insert_header(r->io, r->start, r->msg);
11495
  if (!(nc->flags & MG_F_UDP)) {
11496
    uint16_t len = htons((uint16_t) sent);
11497
    mbuf_insert(r->io, r->start, &len, 2);
11498
  }
11499

    
11500
  if (&nc->send_mbuf != r->io) {
11501
    mg_send(nc, r->io->buf + r->start, r->io->len - r->start);
11502
    r->io->len = r->start;
11503
  }
11504
}
11505

    
11506
int mg_dns_reply_record(struct mg_dns_reply *reply,
11507
                        struct mg_dns_resource_record *question,
11508
                        const char *name, int rtype, int ttl, const void *rdata,
11509
                        size_t rdata_len) {
11510
  struct mg_dns_message *msg = (struct mg_dns_message *) reply->msg;
11511
  char rname[512];
11512
  struct mg_dns_resource_record *ans = &msg->answers[msg->num_answers];
11513
  if (msg->num_answers >= MG_MAX_DNS_ANSWERS) {
11514
    return -1; /* LCOV_EXCL_LINE */
11515
  }
11516

    
11517
  if (name == NULL) {
11518
    name = rname;
11519
    rname[511] = 0;
11520
    mg_dns_uncompress_name(msg, &question->name, rname, sizeof(rname) - 1);
11521
  }
11522

    
11523
  *ans = *question;
11524
  ans->kind = MG_DNS_ANSWER;
11525
  ans->rtype = rtype;
11526
  ans->ttl = ttl;
11527

    
11528
  if (mg_dns_encode_record(reply->io, ans, name, strlen(name), rdata,
11529
                           rdata_len) == -1) {
11530
    return -1; /* LCOV_EXCL_LINE */
11531
  };
11532

    
11533
  msg->num_answers++;
11534
  return 0;
11535
}
11536

    
11537
#endif /* MG_ENABLE_DNS_SERVER */
11538
#ifdef MG_MODULE_LINES
11539
#line 1 "mongoose/src/mg_resolv.c"
11540
#endif
11541
/*
11542
 * Copyright (c) 2014 Cesanta Software Limited
11543
 * All rights reserved
11544
 */
11545

    
11546
#if MG_ENABLE_ASYNC_RESOLVER
11547

    
11548
/* Amalgamated: #include "mg_internal.h" */
11549
/* Amalgamated: #include "mg_resolv.h" */
11550

    
11551
#ifndef MG_DEFAULT_NAMESERVER
11552
#define MG_DEFAULT_NAMESERVER "8.8.8.8"
11553
#endif
11554

    
11555
struct mg_resolve_async_request {
11556
  char name[1024];
11557
  int query;
11558
  mg_resolve_callback_t callback;
11559
  void *data;
11560
  time_t timeout;
11561
  int max_retries;
11562
  enum mg_resolve_err err;
11563

    
11564
  /* state */
11565
  time_t last_time;
11566
  int retries;
11567
};
11568

    
11569
/*
11570
 * Find what nameserver to use.
11571
 *
11572
 * Return 0 if OK, -1 if error
11573
 */
11574
static int mg_get_ip_address_of_nameserver(char *name, size_t name_len) {
11575
  int ret = -1;
11576

    
11577
#ifdef _WIN32
11578
  int i;
11579
  LONG err;
11580
  HKEY hKey, hSub;
11581
  wchar_t subkey[512], value[128],
11582
      *key = L"SYSTEM\\ControlSet001\\Services\\Tcpip\\Parameters\\Interfaces";
11583

    
11584
  if ((err = RegOpenKeyExW(HKEY_LOCAL_MACHINE, key, 0, KEY_READ, &hKey)) !=
11585
      ERROR_SUCCESS) {
11586
    fprintf(stderr, "cannot open reg key %S: %ld\n", key, err);
11587
    ret = -1;
11588
  } else {
11589
    for (ret = -1, i = 0; 1; i++) {
11590
      DWORD subkey_size = sizeof(subkey), type, len = sizeof(value);
11591
      if (RegEnumKeyExW(hKey, i, subkey, &subkey_size, NULL, NULL, NULL,
11592
                        NULL) != ERROR_SUCCESS) {
11593
        break;
11594
      }
11595
      if (RegOpenKeyExW(hKey, subkey, 0, KEY_READ, &hSub) == ERROR_SUCCESS &&
11596
          ((RegQueryValueExW(hSub, L"NameServer", 0, &type, (void *) value,
11597
                             &len) == ERROR_SUCCESS &&
11598
            value[0] != '\0') ||
11599
           (RegQueryValueExW(hSub, L"DhcpNameServer", 0, &type, (void *) value,
11600
                             &len) == ERROR_SUCCESS &&
11601
            value[0] != '\0'))) {
11602
        /*
11603
         * See https://github.com/cesanta/mongoose/issues/176
11604
         * The value taken from the registry can be empty, a single
11605
         * IP address, or multiple IP addresses separated by comma.
11606
         * If it's empty, check the next interface.
11607
         * If it's multiple IP addresses, take the first one.
11608
         */
11609
        wchar_t *comma = wcschr(value, ',');
11610
        if (comma != NULL) {
11611
          *comma = '\0';
11612
        }
11613
        /* %S will convert wchar_t -> char */
11614
        snprintf(name, name_len, "%S", value);
11615
        ret = 0;
11616
        RegCloseKey(hSub);
11617
        break;
11618
      }
11619
    }
11620
    RegCloseKey(hKey);
11621
  }
11622
#elif MG_ENABLE_FILESYSTEM && defined(MG_RESOLV_CONF_FILE_NAME)
11623
  FILE *fp;
11624
  char line[512];
11625

    
11626
  if ((fp = mg_fopen(MG_RESOLV_CONF_FILE_NAME, "r")) == NULL) {
11627
    ret = -1;
11628
  } else {
11629
    /* Try to figure out what nameserver to use */
11630
    for (ret = -1; fgets(line, sizeof(line), fp) != NULL;) {
11631
      unsigned int a, b, c, d;
11632
      if (sscanf(line, "nameserver %u.%u.%u.%u", &a, &b, &c, &d) == 4) {
11633
        snprintf(name, name_len, "%u.%u.%u.%u", a, b, c, d);
11634
        ret = 0;
11635
        break;
11636
      }
11637
    }
11638
    (void) fclose(fp);
11639
  }
11640
#else
11641
  snprintf(name, name_len, "%s", MG_DEFAULT_NAMESERVER);
11642
#endif /* _WIN32 */
11643

    
11644
  return ret;
11645
}
11646

    
11647
int mg_resolve_from_hosts_file(const char *name, union socket_address *usa) {
11648
#if MG_ENABLE_FILESYSTEM && defined(MG_HOSTS_FILE_NAME)
11649
  /* TODO(mkm) cache /etc/hosts */
11650
  FILE *fp;
11651
  char line[1024];
11652
  char *p;
11653
  char alias[256];
11654
  unsigned int a, b, c, d;
11655
  int len = 0;
11656

    
11657
  if ((fp = mg_fopen(MG_HOSTS_FILE_NAME, "r")) == NULL) {
11658
    return -1;
11659
  }
11660

    
11661
  for (; fgets(line, sizeof(line), fp) != NULL;) {
11662
    if (line[0] == '#') continue;
11663

    
11664
    if (sscanf(line, "%u.%u.%u.%u%n", &a, &b, &c, &d, &len) == 0) {
11665
      /* TODO(mkm): handle ipv6 */
11666
      continue;
11667
    }
11668
    for (p = line + len; sscanf(p, "%s%n", alias, &len) == 1; p += len) {
11669
      if (strcmp(alias, name) == 0) {
11670
        usa->sin.sin_addr.s_addr = htonl(a << 24 | b << 16 | c << 8 | d);
11671
        fclose(fp);
11672
        return 0;
11673
      }
11674
    }
11675
  }
11676

    
11677
  fclose(fp);
11678
#else
11679
  (void) name;
11680
  (void) usa;
11681
#endif
11682

    
11683
  return -1;
11684
}
11685

    
11686
static void mg_resolve_async_eh(struct mg_connection *nc, int ev,
11687
                                void *data MG_UD_ARG(void *user_data)) {
11688
  time_t now = (time_t) mg_time();
11689
  struct mg_resolve_async_request *req;
11690
  struct mg_dns_message *msg;
11691
  int first = 0;
11692
#if !MG_ENABLE_CALLBACK_USERDATA
11693
  void *user_data = nc->user_data;
11694
#endif
11695

    
11696
  if (ev != MG_EV_POLL) DBG(("ev=%d user_data=%p", ev, user_data));
11697

    
11698
  req = (struct mg_resolve_async_request *) user_data;
11699

    
11700
  if (req == NULL) {
11701
    return;
11702
  }
11703

    
11704
  switch (ev) {
11705
    case MG_EV_CONNECT:
11706
      /* don't depend on timer not being at epoch for sending out first req */
11707
      first = 1;
11708
    /* fallthrough */
11709
    case MG_EV_POLL:
11710
      if (req->retries > req->max_retries) {
11711
        req->err = MG_RESOLVE_EXCEEDED_RETRY_COUNT;
11712
        nc->flags |= MG_F_CLOSE_IMMEDIATELY;
11713
        break;
11714
      }
11715
      if (first || now - req->last_time >= req->timeout) {
11716
        mg_send_dns_query(nc, req->name, req->query);
11717
        req->last_time = now;
11718
        req->retries++;
11719
      }
11720
      break;
11721
    case MG_EV_RECV:
11722
      msg = (struct mg_dns_message *) MG_MALLOC(sizeof(*msg));
11723
      if (mg_parse_dns(nc->recv_mbuf.buf, *(int *) data, msg) == 0 &&
11724
          msg->num_answers > 0) {
11725
        req->callback(msg, req->data, MG_RESOLVE_OK);
11726
        nc->user_data = NULL;
11727
        MG_FREE(req);
11728
      } else {
11729
        req->err = MG_RESOLVE_NO_ANSWERS;
11730
      }
11731
      MG_FREE(msg);
11732
      nc->flags |= MG_F_CLOSE_IMMEDIATELY;
11733
      break;
11734
    case MG_EV_SEND:
11735
      /*
11736
       * If a send error occurs, prevent closing of the connection by the core.
11737
       * We will retry after timeout.
11738
       */
11739
      nc->flags &= ~MG_F_CLOSE_IMMEDIATELY;
11740
      mbuf_remove(&nc->send_mbuf, nc->send_mbuf.len);
11741
      break;
11742
    case MG_EV_TIMER:
11743
      req->err = MG_RESOLVE_TIMEOUT;
11744
      nc->flags |= MG_F_CLOSE_IMMEDIATELY;
11745
      break;
11746
    case MG_EV_CLOSE:
11747
      /* If we got here with request still not done, fire an error callback. */
11748
      if (req != NULL) {
11749
        char addr[32];
11750
        mg_sock_addr_to_str(&nc->sa, addr, sizeof(addr), MG_SOCK_STRINGIFY_IP);
11751
#ifdef MG_LOG_DNS_FAILURES
11752
        LOG(LL_ERROR, ("Failed to resolve '%s', server %s", req->name, addr));
11753
#endif
11754
        req->callback(NULL, req->data, req->err);
11755
        nc->user_data = NULL;
11756
        MG_FREE(req);
11757
      }
11758
      break;
11759
  }
11760
}
11761

    
11762
int mg_resolve_async(struct mg_mgr *mgr, const char *name, int query,
11763
                     mg_resolve_callback_t cb, void *data) {
11764
  struct mg_resolve_async_opts opts;
11765
  memset(&opts, 0, sizeof(opts));
11766
  return mg_resolve_async_opt(mgr, name, query, cb, data, opts);
11767
}
11768

    
11769
int mg_resolve_async_opt(struct mg_mgr *mgr, const char *name, int query,
11770
                         mg_resolve_callback_t cb, void *data,
11771
                         struct mg_resolve_async_opts opts) {
11772
  struct mg_resolve_async_request *req;
11773
  struct mg_connection *dns_nc;
11774
  const char *nameserver = opts.nameserver;
11775
  char dns_server_buff[17], nameserver_url[26];
11776

    
11777
  if (nameserver == NULL) {
11778
    nameserver = mgr->nameserver;
11779
  }
11780

    
11781
  DBG(("%s %d %p", name, query, opts.dns_conn));
11782

    
11783
  /* resolve with DNS */
11784
  req = (struct mg_resolve_async_request *) MG_CALLOC(1, sizeof(*req));
11785
  if (req == NULL) {
11786
    return -1;
11787
  }
11788

    
11789
  strncpy(req->name, name, sizeof(req->name));
11790
  req->name[sizeof(req->name) - 1] = '\0';
11791

    
11792
  req->query = query;
11793
  req->callback = cb;
11794
  req->data = data;
11795
  /* TODO(mkm): parse defaults out of resolve.conf */
11796
  req->max_retries = opts.max_retries ? opts.max_retries : 2;
11797
  req->timeout = opts.timeout ? opts.timeout : 5;
11798

    
11799
  /* Lazily initialize dns server */
11800
  if (nameserver == NULL) {
11801
    if (mg_get_ip_address_of_nameserver(dns_server_buff,
11802
                                        sizeof(dns_server_buff)) != -1) {
11803
      nameserver = dns_server_buff;
11804
    } else {
11805
      nameserver = MG_DEFAULT_NAMESERVER;
11806
    }
11807
  }
11808

    
11809
  snprintf(nameserver_url, sizeof(nameserver_url), "udp://%s:53", nameserver);
11810

    
11811
  dns_nc = mg_connect(mgr, nameserver_url, MG_CB(mg_resolve_async_eh, NULL));
11812
  if (dns_nc == NULL) {
11813
    MG_FREE(req);
11814
    return -1;
11815
  }
11816
  dns_nc->user_data = req;
11817
  if (opts.dns_conn != NULL) {
11818
    *opts.dns_conn = dns_nc;
11819
  }
11820

    
11821
  return 0;
11822
}
11823

    
11824
void mg_set_nameserver(struct mg_mgr *mgr, const char *nameserver) {
11825
  MG_FREE((char *) mgr->nameserver);
11826
  mgr->nameserver = NULL;
11827
  if (nameserver != NULL) {
11828
    mgr->nameserver = strdup(nameserver);
11829
  }
11830
}
11831

    
11832
#endif /* MG_ENABLE_ASYNC_RESOLVER */
11833
#ifdef MG_MODULE_LINES
11834
#line 1 "mongoose/src/mg_coap.c"
11835
#endif
11836
/*
11837
 * Copyright (c) 2015 Cesanta Software Limited
11838
 * All rights reserved
11839
 * This software is dual-licensed: you can redistribute it and/or modify
11840
 * it under the terms of the GNU General Public License version 2 as
11841
 * published by the Free Software Foundation. For the terms of this
11842
 * license, see <http://www.gnu.org/licenses/>.
11843
 *
11844
 * You are free to use this software under the terms of the GNU General
11845
 * Public License, but WITHOUT ANY WARRANTY; without even the implied
11846
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
11847
 * See the GNU General Public License for more details.
11848
 *
11849
 * Alternatively, you can license this software under a commercial
11850
 * license, as set out in <https://www.cesanta.com/license>.
11851
 */
11852

    
11853
/* Amalgamated: #include "mg_internal.h" */
11854
/* Amalgamated: #include "mg_coap.h" */
11855

    
11856
#if MG_ENABLE_COAP
11857

    
11858
void mg_coap_free_options(struct mg_coap_message *cm) {
11859
  while (cm->options != NULL) {
11860
    struct mg_coap_option *next = cm->options->next;
11861
    MG_FREE(cm->options);
11862
    cm->options = next;
11863
  }
11864
}
11865

    
11866
struct mg_coap_option *mg_coap_add_option(struct mg_coap_message *cm,
11867
                                          uint32_t number, char *value,
11868
                                          size_t len) {
11869
  struct mg_coap_option *new_option =
11870
      (struct mg_coap_option *) MG_CALLOC(1, sizeof(*new_option));
11871

    
11872
  new_option->number = number;
11873
  new_option->value.p = value;
11874
  new_option->value.len = len;
11875

    
11876
  if (cm->options == NULL) {
11877
    cm->options = cm->optiomg_tail = new_option;
11878
  } else {
11879
    /*
11880
     * A very simple attention to help clients to compose options:
11881
     * CoAP wants to see options ASC ordered.
11882
     * Could be change by using sort in coap_compose
11883
     */
11884
    if (cm->optiomg_tail->number <= new_option->number) {
11885
      /* if option is already ordered just add it */
11886
      cm->optiomg_tail = cm->optiomg_tail->next = new_option;
11887
    } else {
11888
      /* looking for appropriate position */
11889
      struct mg_coap_option *current_opt = cm->options;
11890
      struct mg_coap_option *prev_opt = 0;
11891

    
11892
      while (current_opt != NULL) {
11893
        if (current_opt->number > new_option->number) {
11894
          break;
11895
        }
11896
        prev_opt = current_opt;
11897
        current_opt = current_opt->next;
11898
      }
11899

    
11900
      if (prev_opt != NULL) {
11901
        prev_opt->next = new_option;
11902
        new_option->next = current_opt;
11903
      } else {
11904
        /* insert new_option to the beginning */
11905
        new_option->next = cm->options;
11906
        cm->options = new_option;
11907
      }
11908
    }
11909
  }
11910

    
11911
  return new_option;
11912
}
11913

    
11914
/*
11915
 * Fills CoAP header in mg_coap_message.
11916
 *
11917
 * Helper function.
11918
 */
11919
static char *coap_parse_header(char *ptr, struct mbuf *io,
11920
                               struct mg_coap_message *cm) {
11921
  if (io->len < sizeof(uint32_t)) {
11922
    cm->flags |= MG_COAP_NOT_ENOUGH_DATA;
11923
    return NULL;
11924
  }
11925

    
11926
  /*
11927
   * Version (Ver):  2-bit unsigned integer.  Indicates the CoAP version
11928
   * number.  Implementations of this specification MUST set this field
11929
   * to 1 (01 binary).  Other values are reserved for future versions.
11930
   * Messages with unknown version numbers MUST be silently ignored.
11931
   */
11932
  if (((uint8_t) *ptr >> 6) != 1) {
11933
    cm->flags |= MG_COAP_IGNORE;
11934
    return NULL;
11935
  }
11936

    
11937
  /*
11938
   * Type (T):  2-bit unsigned integer.  Indicates if this message is of
11939
   * type Confirmable (0), Non-confirmable (1), Acknowledgement (2), or
11940
   * Reset (3).
11941
   */
11942
  cm->msg_type = ((uint8_t) *ptr & 0x30) >> 4;
11943
  cm->flags |= MG_COAP_MSG_TYPE_FIELD;
11944

    
11945
  /*
11946
   * Token Length (TKL):  4-bit unsigned integer.  Indicates the length of
11947
   * the variable-length Token field (0-8 bytes).  Lengths 9-15 are
11948
   * reserved, MUST NOT be sent, and MUST be processed as a message
11949
   * format error.
11950
   */
11951
  cm->token.len = *ptr & 0x0F;
11952
  if (cm->token.len > 8) {
11953
    cm->flags |= MG_COAP_FORMAT_ERROR;
11954
    return NULL;
11955
  }
11956

    
11957
  ptr++;
11958

    
11959
  /*
11960
   * Code:  8-bit unsigned integer, split into a 3-bit class (most
11961
   * significant bits) and a 5-bit detail (least significant bits)
11962
   */
11963
  cm->code_class = (uint8_t) *ptr >> 5;
11964
  cm->code_detail = *ptr & 0x1F;
11965
  cm->flags |= (MG_COAP_CODE_CLASS_FIELD | MG_COAP_CODE_DETAIL_FIELD);
11966

    
11967
  ptr++;
11968

    
11969
  /* Message ID:  16-bit unsigned integer in network byte order. */
11970
  cm->msg_id = (uint8_t) *ptr << 8 | (uint8_t) * (ptr + 1);
11971
  cm->flags |= MG_COAP_MSG_ID_FIELD;
11972

    
11973
  ptr += 2;
11974

    
11975
  return ptr;
11976
}
11977

    
11978
/*
11979
 * Fills token information in mg_coap_message.
11980
 *
11981
 * Helper function.
11982
 */
11983
static char *coap_get_token(char *ptr, struct mbuf *io,
11984
                            struct mg_coap_message *cm) {
11985
  if (cm->token.len != 0) {
11986
    if (ptr + cm->token.len > io->buf + io->len) {
11987
      cm->flags |= MG_COAP_NOT_ENOUGH_DATA;
11988
      return NULL;
11989
    } else {
11990
      cm->token.p = ptr;
11991
      ptr += cm->token.len;
11992
      cm->flags |= MG_COAP_TOKEN_FIELD;
11993
    }
11994
  }
11995

    
11996
  return ptr;
11997
}
11998

    
11999
/*
12000
 * Returns Option Delta or Length.
12001
 *
12002
 * Helper function.
12003
 */
12004
static int coap_get_ext_opt(char *ptr, struct mbuf *io, uint16_t *opt_info) {
12005
  int ret = 0;
12006

    
12007
  if (*opt_info == 13) {
12008
    /*
12009
     * 13:  An 8-bit unsigned integer follows the initial byte and
12010
     * indicates the Option Delta/Length minus 13.
12011
     */
12012
    if (ptr < io->buf + io->len) {
12013
      *opt_info = (uint8_t) *ptr + 13;
12014
      ret = sizeof(uint8_t);
12015
    } else {
12016
      ret = -1; /* LCOV_EXCL_LINE */
12017
    }
12018
  } else if (*opt_info == 14) {
12019
    /*
12020
     * 14:  A 16-bit unsigned integer in network byte order follows the
12021
     * initial byte and indicates the Option Delta/Length minus 269.
12022
     */
12023
    if (ptr + sizeof(uint8_t) < io->buf + io->len) {
12024
      *opt_info = ((uint8_t) *ptr << 8 | (uint8_t) * (ptr + 1)) + 269;
12025
      ret = sizeof(uint16_t);
12026
    } else {
12027
      ret = -1; /* LCOV_EXCL_LINE */
12028
    }
12029
  }
12030

    
12031
  return ret;
12032
}
12033

    
12034
/*
12035
 * Fills options in mg_coap_message.
12036
 *
12037
 * Helper function.
12038
 *
12039
 * General options format:
12040
 * +---------------+---------------+
12041
 * | Option Delta  | Option Length |  1 byte
12042
 * +---------------+---------------+
12043
 * \    Option Delta (extended)    \  0-2 bytes
12044
 * +-------------------------------+
12045
 * / Option Length  (extended)     \  0-2 bytes
12046
 * +-------------------------------+
12047
 * \         Option Value          \  0 or more bytes
12048
 * +-------------------------------+
12049
 */
12050
static char *coap_get_options(char *ptr, struct mbuf *io,
12051
                              struct mg_coap_message *cm) {
12052
  uint16_t prev_opt = 0;
12053

    
12054
  if (ptr == io->buf + io->len) {
12055
    /* end of packet, ok */
12056
    return NULL;
12057
  }
12058

    
12059
  /* 0xFF is payload marker */
12060
  while (ptr < io->buf + io->len && (uint8_t) *ptr != 0xFF) {
12061
    uint16_t option_delta, option_lenght;
12062
    int optinfo_len;
12063

    
12064
    /* Option Delta:  4-bit unsigned integer */
12065
    option_delta = ((uint8_t) *ptr & 0xF0) >> 4;
12066
    /* Option Length:  4-bit unsigned integer */
12067
    option_lenght = *ptr & 0x0F;
12068

    
12069
    if (option_delta == 15 || option_lenght == 15) {
12070
      /*
12071
       * 15:  Reserved for future use.  If the field is set to this value,
12072
       * it MUST be processed as a message format error
12073
       */
12074
      cm->flags |= MG_COAP_FORMAT_ERROR;
12075
      break;
12076
    }
12077

    
12078
    ptr++;
12079

    
12080
    /* check for extended option delta */
12081
    optinfo_len = coap_get_ext_opt(ptr, io, &option_delta);
12082
    if (optinfo_len == -1) {
12083
      cm->flags |= MG_COAP_NOT_ENOUGH_DATA; /* LCOV_EXCL_LINE */
12084
      break;                                /* LCOV_EXCL_LINE */
12085
    }
12086

    
12087
    ptr += optinfo_len;
12088

    
12089
    /* check or extended option lenght */
12090
    optinfo_len = coap_get_ext_opt(ptr, io, &option_lenght);
12091
    if (optinfo_len == -1) {
12092
      cm->flags |= MG_COAP_NOT_ENOUGH_DATA; /* LCOV_EXCL_LINE */
12093
      break;                                /* LCOV_EXCL_LINE */
12094
    }
12095

    
12096
    ptr += optinfo_len;
12097

    
12098
    /*
12099
     * Instead of specifying the Option Number directly, the instances MUST
12100
     * appear in order of their Option Numbers and a delta encoding is used
12101
     * between them.
12102
     */
12103
    option_delta += prev_opt;
12104

    
12105
    mg_coap_add_option(cm, option_delta, ptr, option_lenght);
12106

    
12107
    prev_opt = option_delta;
12108

    
12109
    if (ptr + option_lenght > io->buf + io->len) {
12110
      cm->flags |= MG_COAP_NOT_ENOUGH_DATA; /* LCOV_EXCL_LINE */
12111
      break;                                /* LCOV_EXCL_LINE */
12112
    }
12113

    
12114
    ptr += option_lenght;
12115
  }
12116

    
12117
  if ((cm->flags & MG_COAP_ERROR) != 0) {
12118
    mg_coap_free_options(cm);
12119
    return NULL;
12120
  }
12121

    
12122
  cm->flags |= MG_COAP_OPTIOMG_FIELD;
12123

    
12124
  if (ptr == io->buf + io->len) {
12125
    /* end of packet, ok */
12126
    return NULL;
12127
  }
12128

    
12129
  ptr++;
12130

    
12131
  return ptr;
12132
}
12133

    
12134
uint32_t mg_coap_parse(struct mbuf *io, struct mg_coap_message *cm) {
12135
  char *ptr;
12136

    
12137
  memset(cm, 0, sizeof(*cm));
12138

    
12139
  if ((ptr = coap_parse_header(io->buf, io, cm)) == NULL) {
12140
    return cm->flags;
12141
  }
12142

    
12143
  if ((ptr = coap_get_token(ptr, io, cm)) == NULL) {
12144
    return cm->flags;
12145
  }
12146

    
12147
  if ((ptr = coap_get_options(ptr, io, cm)) == NULL) {
12148
    return cm->flags;
12149
  }
12150

    
12151
  /* the rest is payload */
12152
  cm->payload.len = io->len - (ptr - io->buf);
12153
  if (cm->payload.len != 0) {
12154
    cm->payload.p = ptr;
12155
    cm->flags |= MG_COAP_PAYLOAD_FIELD;
12156
  }
12157

    
12158
  return cm->flags;
12159
}
12160

    
12161
/*
12162
 * Calculates extended size of given Opt Number/Length in coap message.
12163
 *
12164
 * Helper function.
12165
 */
12166
static size_t coap_get_ext_opt_size(uint32_t value) {
12167
  int ret = 0;
12168

    
12169
  if (value >= 13 && value <= 0xFF + 13) {
12170
    ret = sizeof(uint8_t);
12171
  } else if (value > 0xFF + 13 && value <= 0xFFFF + 269) {
12172
    ret = sizeof(uint16_t);
12173
  }
12174

    
12175
  return ret;
12176
}
12177

    
12178
/*
12179
 * Splits given Opt Number/Length into base and ext values.
12180
 *
12181
 * Helper function.
12182
 */
12183
static int coap_split_opt(uint32_t value, uint8_t *base, uint16_t *ext) {
12184
  int ret = 0;
12185

    
12186
  if (value < 13) {
12187
    *base = value;
12188
  } else if (value >= 13 && value <= 0xFF + 13) {
12189
    *base = 13;
12190
    *ext = value - 13;
12191
    ret = sizeof(uint8_t);
12192
  } else if (value > 0xFF + 13 && value <= 0xFFFF + 269) {
12193
    *base = 14;
12194
    *ext = value - 269;
12195
    ret = sizeof(uint16_t);
12196
  }
12197

    
12198
  return ret;
12199
}
12200

    
12201
/*
12202
 * Puts uint16_t (in network order) into given char stream.
12203
 *
12204
 * Helper function.
12205
 */
12206
static char *coap_add_uint16(char *ptr, uint16_t val) {
12207
  *ptr = val >> 8;
12208
  ptr++;
12209
  *ptr = val & 0x00FF;
12210
  ptr++;
12211
  return ptr;
12212
}
12213

    
12214
/*
12215
 * Puts extended value of Opt Number/Length into given char stream.
12216
 *
12217
 * Helper function.
12218
 */
12219
static char *coap_add_opt_info(char *ptr, uint16_t val, size_t len) {
12220
  if (len == sizeof(uint8_t)) {
12221
    *ptr = (char) val;
12222
    ptr++;
12223
  } else if (len == sizeof(uint16_t)) {
12224
    ptr = coap_add_uint16(ptr, val);
12225
  }
12226

    
12227
  return ptr;
12228
}
12229

    
12230
/*
12231
 * Verifies given mg_coap_message and calculates message size for it.
12232
 *
12233
 * Helper function.
12234
 */
12235
static uint32_t coap_calculate_packet_size(struct mg_coap_message *cm,
12236
                                           size_t *len) {
12237
  struct mg_coap_option *opt;
12238
  uint32_t prev_opt_number;
12239

    
12240
  *len = 4; /* header */
12241
  if (cm->msg_type > MG_COAP_MSG_MAX) {
12242
    return MG_COAP_ERROR | MG_COAP_MSG_TYPE_FIELD;
12243
  }
12244
  if (cm->token.len > 8) {
12245
    return MG_COAP_ERROR | MG_COAP_TOKEN_FIELD;
12246
  }
12247
  if (cm->code_class > 7) {
12248
    return MG_COAP_ERROR | MG_COAP_CODE_CLASS_FIELD;
12249
  }
12250
  if (cm->code_detail > 31) {
12251
    return MG_COAP_ERROR | MG_COAP_CODE_DETAIL_FIELD;
12252
  }
12253

    
12254
  *len += cm->token.len;
12255
  if (cm->payload.len != 0) {
12256
    *len += cm->payload.len + 1; /* ... + 1; add payload marker */
12257
  }
12258

    
12259
  opt = cm->options;
12260
  prev_opt_number = 0;
12261
  while (opt != NULL) {
12262
    *len += 1; /* basic delta/length */
12263
    *len += coap_get_ext_opt_size(opt->number - prev_opt_number);
12264
    *len += coap_get_ext_opt_size((uint32_t) opt->value.len);
12265
    /*
12266
     * Current implementation performs check if
12267
     * option_number > previous option_number and produces an error
12268
     * TODO(alashkin): write design doc with limitations
12269
     * May be resorting is more suitable solution.
12270
     */
12271
    if ((opt->next != NULL && opt->number > opt->next->number) ||
12272
        opt->value.len > 0xFFFF + 269 ||
12273
        opt->number - prev_opt_number > 0xFFFF + 269) {
12274
      return MG_COAP_ERROR | MG_COAP_OPTIOMG_FIELD;
12275
    }
12276
    *len += opt->value.len;
12277
    prev_opt_number = opt->number;
12278
    opt = opt->next;
12279
  }
12280

    
12281
  return 0;
12282
}
12283

    
12284
uint32_t mg_coap_compose(struct mg_coap_message *cm, struct mbuf *io) {
12285
  struct mg_coap_option *opt;
12286
  uint32_t res, prev_opt_number;
12287
  size_t prev_io_len, packet_size;
12288
  char *ptr;
12289

    
12290
  res = coap_calculate_packet_size(cm, &packet_size);
12291
  if (res != 0) {
12292
    return res;
12293
  }
12294

    
12295
  /* saving previous lenght to handle non-empty mbuf */
12296
  prev_io_len = io->len;
12297
  if (mbuf_append(io, NULL, packet_size) == 0) return MG_COAP_ERROR;
12298
  ptr = io->buf + prev_io_len;
12299

    
12300
  /*
12301
   * since cm is verified, it is possible to use bits shift operator
12302
   * without additional zeroing of unused bits
12303
   */
12304

    
12305
  /* ver: 2 bits, msg_type: 2 bits, toklen: 4 bits */
12306
  *ptr = (1 << 6) | (cm->msg_type << 4) | (uint8_t)(cm->token.len);
12307
  ptr++;
12308

    
12309
  /* code class: 3 bits, code detail: 5 bits */
12310
  *ptr = (cm->code_class << 5) | (cm->code_detail);
12311
  ptr++;
12312

    
12313
  ptr = coap_add_uint16(ptr, cm->msg_id);
12314

    
12315
  if (cm->token.len != 0) {
12316
    memcpy(ptr, cm->token.p, cm->token.len);
12317
    ptr += cm->token.len;
12318
  }
12319

    
12320
  opt = cm->options;
12321
  prev_opt_number = 0;
12322
  while (opt != NULL) {
12323
    uint8_t delta_base = 0, length_base = 0;
12324
    uint16_t delta_ext = 0, length_ext = 0;
12325

    
12326
    size_t opt_delta_len =
12327
        coap_split_opt(opt->number - prev_opt_number, &delta_base, &delta_ext);
12328
    size_t opt_lenght_len =
12329
        coap_split_opt((uint32_t) opt->value.len, &length_base, &length_ext);
12330

    
12331
    *ptr = (delta_base << 4) | length_base;
12332
    ptr++;
12333

    
12334
    ptr = coap_add_opt_info(ptr, delta_ext, opt_delta_len);
12335
    ptr = coap_add_opt_info(ptr, length_ext, opt_lenght_len);
12336

    
12337
    if (opt->value.len != 0) {
12338
      memcpy(ptr, opt->value.p, opt->value.len);
12339
      ptr += opt->value.len;
12340
    }
12341

    
12342
    prev_opt_number = opt->number;
12343
    opt = opt->next;
12344
  }
12345

    
12346
  if (cm->payload.len != 0) {
12347
    *ptr = (char) -1;
12348
    ptr++;
12349
    memcpy(ptr, cm->payload.p, cm->payload.len);
12350
  }
12351

    
12352
  return 0;
12353
}
12354

    
12355
uint32_t mg_coap_send_message(struct mg_connection *nc,
12356
                              struct mg_coap_message *cm) {
12357
  struct mbuf packet_out;
12358
  uint32_t compose_res;
12359

    
12360
  mbuf_init(&packet_out, 0);
12361
  compose_res = mg_coap_compose(cm, &packet_out);
12362
  if (compose_res != 0) {
12363
    return compose_res; /* LCOV_EXCL_LINE */
12364
  }
12365

    
12366
  mg_send(nc, packet_out.buf, (int) packet_out.len);
12367
  mbuf_free(&packet_out);
12368

    
12369
  return 0;
12370
}
12371

    
12372
uint32_t mg_coap_send_ack(struct mg_connection *nc, uint16_t msg_id) {
12373
  struct mg_coap_message cm;
12374
  memset(&cm, 0, sizeof(cm));
12375
  cm.msg_type = MG_COAP_MSG_ACK;
12376
  cm.msg_id = msg_id;
12377

    
12378
  return mg_coap_send_message(nc, &cm);
12379
}
12380

    
12381
static void coap_handler(struct mg_connection *nc, int ev,
12382
                         void *ev_data MG_UD_ARG(void *user_data)) {
12383
  struct mbuf *io = &nc->recv_mbuf;
12384
  struct mg_coap_message cm;
12385
  uint32_t parse_res;
12386

    
12387
  memset(&cm, 0, sizeof(cm));
12388

    
12389
  nc->handler(nc, ev, ev_data MG_UD_ARG(user_data));
12390

    
12391
  switch (ev) {
12392
    case MG_EV_RECV:
12393
      parse_res = mg_coap_parse(io, &cm);
12394
      if ((parse_res & MG_COAP_IGNORE) == 0) {
12395
        if ((cm.flags & MG_COAP_NOT_ENOUGH_DATA) != 0) {
12396
          /*
12397
           * Since we support UDP only
12398
           * MG_COAP_NOT_ENOUGH_DATA == MG_COAP_FORMAT_ERROR
12399
           */
12400
          cm.flags |= MG_COAP_FORMAT_ERROR; /* LCOV_EXCL_LINE */
12401
        }                                   /* LCOV_EXCL_LINE */
12402
        nc->handler(nc, MG_COAP_EVENT_BASE + cm.msg_type,
12403
                    &cm MG_UD_ARG(user_data));
12404
      }
12405

    
12406
      mg_coap_free_options(&cm);
12407
      mbuf_remove(io, io->len);
12408
      break;
12409
  }
12410
}
12411
/*
12412
 * Attach built-in CoAP event handler to the given connection.
12413
 *
12414
 * The user-defined event handler will receive following extra events:
12415
 *
12416
 * - MG_EV_COAP_CON
12417
 * - MG_EV_COAP_NOC
12418
 * - MG_EV_COAP_ACK
12419
 * - MG_EV_COAP_RST
12420
 */
12421
int mg_set_protocol_coap(struct mg_connection *nc) {
12422
  /* supports UDP only */
12423
  if ((nc->flags & MG_F_UDP) == 0) {
12424
    return -1;
12425
  }
12426

    
12427
  nc->proto_handler = coap_handler;
12428

    
12429
  return 0;
12430
}
12431

    
12432
#endif /* MG_ENABLE_COAP */
12433
#ifdef MG_MODULE_LINES
12434
#line 1 "mongoose/src/mg_sntp.c"
12435
#endif
12436
/*
12437
 * Copyright (c) 2016 Cesanta Software Limited
12438
 * All rights reserved
12439
 */
12440

    
12441
/* Amalgamated: #include "mg_internal.h" */
12442
/* Amalgamated: #include "mg_sntp.h" */
12443
/* Amalgamated: #include "mg_util.h" */
12444

    
12445
#if MG_ENABLE_SNTP
12446

    
12447
#define SNTP_TIME_OFFSET 2208988800
12448

    
12449
#ifndef SNTP_TIMEOUT
12450
#define SNTP_TIMEOUT 10
12451
#endif
12452

    
12453
#ifndef SNTP_ATTEMPTS
12454
#define SNTP_ATTEMPTS 3
12455
#endif
12456

    
12457
static uint64_t mg_get_sec(uint64_t val) {
12458
  return (val & 0xFFFFFFFF00000000) >> 32;
12459
}
12460

    
12461
static uint64_t mg_get_usec(uint64_t val) {
12462
  uint64_t tmp = (val & 0x00000000FFFFFFFF);
12463
  tmp *= 1000000;
12464
  tmp >>= 32;
12465
  return tmp;
12466
}
12467

    
12468
static void mg_ntp_to_tv(uint64_t val, struct timeval *tv) {
12469
  uint64_t tmp;
12470
  tmp = mg_get_sec(val);
12471
  tmp -= SNTP_TIME_OFFSET;
12472
  tv->tv_sec = tmp;
12473
  tv->tv_usec = mg_get_usec(val);
12474
}
12475

    
12476
static void mg_get_ntp_ts(const char *ntp, uint64_t *val) {
12477
  uint32_t tmp;
12478
  memcpy(&tmp, ntp, sizeof(tmp));
12479
  tmp = ntohl(tmp);
12480
  *val = (uint64_t) tmp << 32;
12481
  memcpy(&tmp, ntp + 4, sizeof(tmp));
12482
  tmp = ntohl(tmp);
12483
  *val |= tmp;
12484
}
12485

    
12486
void mg_sntp_send_request(struct mg_connection *c) {
12487
  uint8_t buf[48] = {0};
12488
  /*
12489
   * header - 8 bit:
12490
   * LI (2 bit) - 3 (not in sync), VN (3 bit) - 4 (version),
12491
   * mode (3 bit) - 3 (client)
12492
   */
12493
  buf[0] = (3 << 6) | (4 << 3) | 3;
12494

    
12495
/*
12496
 * Next fields should be empty in client request
12497
 * stratum, 8 bit
12498
 * poll interval, 8 bit
12499
 * rrecision, 8 bit
12500
 * root delay, 32 bit
12501
 * root dispersion, 32 bit
12502
 * ref id, 32 bit
12503
 * ref timestamp, 64 bit
12504
 * originate Timestamp, 64 bit
12505
 * receive Timestamp, 64 bit
12506
*/
12507

    
12508
/*
12509
 * convert time to sntp format (sntp starts from 00:00:00 01.01.1900)
12510
 * according to rfc868 it is 2208988800L sec
12511
 * this information is used to correct roundtrip delay
12512
 * but if local clock is absolutely broken (and doesn't work even
12513
 * as simple timer), it is better to disable it
12514
*/
12515
#ifndef MG_SNTP_NO_DELAY_CORRECTION
12516
  uint32_t sec;
12517
  sec = htonl((uint32_t)(mg_time() + SNTP_TIME_OFFSET));
12518
  memcpy(&buf[40], &sec, sizeof(sec));
12519
#endif
12520

    
12521
  mg_send(c, buf, sizeof(buf));
12522
}
12523

    
12524
#ifndef MG_SNTP_NO_DELAY_CORRECTION
12525
static uint64_t mg_calculate_delay(uint64_t t1, uint64_t t2, uint64_t t3) {
12526
  /* roundloop delay = (T4 - T1) - (T3 - T2) */
12527
  uint64_t d1 = ((mg_time() + SNTP_TIME_OFFSET) * 1000000) -
12528
                (mg_get_sec(t1) * 1000000 + mg_get_usec(t1));
12529
  uint64_t d2 = (mg_get_sec(t3) * 1000000 + mg_get_usec(t3)) -
12530
                (mg_get_sec(t2) * 1000000 + mg_get_usec(t2));
12531

    
12532
  return (d1 > d2) ? d1 - d2 : 0;
12533
}
12534
#endif
12535

    
12536
MG_INTERNAL int mg_sntp_parse_reply(const char *buf, int len,
12537
                                    struct mg_sntp_message *msg) {
12538
  uint8_t hdr;
12539
  uint64_t trsm_ts_T3, delay = 0;
12540
  int mode;
12541
  struct timeval tv;
12542

    
12543
  if (len < 48) {
12544
    return -1;
12545
  }
12546

    
12547
  hdr = buf[0];
12548

    
12549
  if ((hdr & 0x38) >> 3 != 4) {
12550
    /* Wrong version */
12551
    return -1;
12552
  }
12553

    
12554
  mode = hdr & 0x7;
12555
  if (mode != 4 && mode != 5) {
12556
    /* Not a server reply */
12557
    return -1;
12558
  }
12559

    
12560
  memset(msg, 0, sizeof(*msg));
12561

    
12562
  msg->kiss_of_death = (buf[1] == 0); /* Server asks to not send requests */
12563

    
12564
  mg_get_ntp_ts(&buf[40], &trsm_ts_T3);
12565

    
12566
#ifndef MG_SNTP_NO_DELAY_CORRECTION
12567
  {
12568
    uint64_t orig_ts_T1, recv_ts_T2;
12569
    mg_get_ntp_ts(&buf[24], &orig_ts_T1);
12570
    mg_get_ntp_ts(&buf[32], &recv_ts_T2);
12571
    delay = mg_calculate_delay(orig_ts_T1, recv_ts_T2, trsm_ts_T3);
12572
  }
12573
#endif
12574

    
12575
  mg_ntp_to_tv(trsm_ts_T3, &tv);
12576

    
12577
  msg->time = (double) tv.tv_sec + (((double) tv.tv_usec + delay) / 1000000.0);
12578

    
12579
  return 0;
12580
}
12581

    
12582
static void mg_sntp_handler(struct mg_connection *c, int ev,
12583
                            void *ev_data MG_UD_ARG(void *user_data)) {
12584
  struct mbuf *io = &c->recv_mbuf;
12585
  struct mg_sntp_message msg;
12586

    
12587
  c->handler(c, ev, ev_data MG_UD_ARG(user_data));
12588

    
12589
  switch (ev) {
12590
    case MG_EV_RECV: {
12591
      if (mg_sntp_parse_reply(io->buf, io->len, &msg) < 0) {
12592
        DBG(("Invalid SNTP packet received (%d)", (int) io->len));
12593
        c->handler(c, MG_SNTP_MALFORMED_REPLY, NULL MG_UD_ARG(user_data));
12594
      } else {
12595
        c->handler(c, MG_SNTP_REPLY, (void *) &msg MG_UD_ARG(user_data));
12596
      }
12597

    
12598
      mbuf_remove(io, io->len);
12599
      break;
12600
    }
12601
  }
12602
}
12603

    
12604
int mg_set_protocol_sntp(struct mg_connection *c) {
12605
  if ((c->flags & MG_F_UDP) == 0) {
12606
    return -1;
12607
  }
12608

    
12609
  c->proto_handler = mg_sntp_handler;
12610

    
12611
  return 0;
12612
}
12613

    
12614
struct mg_connection *mg_sntp_connect(struct mg_mgr *mgr,
12615
                                      MG_CB(mg_event_handler_t event_handler,
12616
                                            void *user_data),
12617
                                      const char *sntp_server_name) {
12618
  struct mg_connection *c = NULL;
12619
  char url[100], *p_url = url;
12620
  const char *proto = "", *port = "", *tmp;
12621

    
12622
  /* If port is not specified, use default (123) */
12623
  tmp = strchr(sntp_server_name, ':');
12624
  if (tmp != NULL && *(tmp + 1) == '/') {
12625
    tmp = strchr(tmp + 1, ':');
12626
  }
12627

    
12628
  if (tmp == NULL) {
12629
    port = ":123";
12630
  }
12631

    
12632
  /* Add udp:// if needed */
12633
  if (strncmp(sntp_server_name, "udp://", 6) != 0) {
12634
    proto = "udp://";
12635
  }
12636

    
12637
  mg_asprintf(&p_url, sizeof(url), "%s%s%s", proto, sntp_server_name, port);
12638

    
12639
  c = mg_connect(mgr, p_url, event_handler MG_UD_ARG(user_data));
12640

    
12641
  if (c == NULL) {
12642
    goto cleanup;
12643
  }
12644

    
12645
  mg_set_protocol_sntp(c);
12646

    
12647
cleanup:
12648
  if (p_url != url) {
12649
    MG_FREE(p_url);
12650
  }
12651

    
12652
  return c;
12653
}
12654

    
12655
struct sntp_data {
12656
  mg_event_handler_t hander;
12657
  int count;
12658
};
12659

    
12660
static void mg_sntp_util_ev_handler(struct mg_connection *c, int ev,
12661
                                    void *ev_data MG_UD_ARG(void *user_data)) {
12662
#if !MG_ENABLE_CALLBACK_USERDATA
12663
  void *user_data = c->user_data;
12664
#endif
12665
  struct sntp_data *sd = (struct sntp_data *) user_data;
12666

    
12667
  switch (ev) {
12668
    case MG_EV_CONNECT:
12669
      if (*(int *) ev_data != 0) {
12670
        mg_call(c, sd->hander, c->user_data, MG_SNTP_FAILED, NULL);
12671
        break;
12672
      }
12673
    /* fallthrough */
12674
    case MG_EV_TIMER:
12675
      if (sd->count <= SNTP_ATTEMPTS) {
12676
        mg_sntp_send_request(c);
12677
        mg_set_timer(c, mg_time() + 10);
12678
        sd->count++;
12679
      } else {
12680
        mg_call(c, sd->hander, c->user_data, MG_SNTP_FAILED, NULL);
12681
        c->flags |= MG_F_CLOSE_IMMEDIATELY;
12682
      }
12683
      break;
12684
    case MG_SNTP_MALFORMED_REPLY:
12685
      mg_call(c, sd->hander, c->user_data, MG_SNTP_FAILED, NULL);
12686
      c->flags |= MG_F_CLOSE_IMMEDIATELY;
12687
      break;
12688
    case MG_SNTP_REPLY:
12689
      mg_call(c, sd->hander, c->user_data, MG_SNTP_REPLY, ev_data);
12690
      c->flags |= MG_F_CLOSE_IMMEDIATELY;
12691
      break;
12692
    case MG_EV_CLOSE:
12693
      MG_FREE(user_data);
12694
      c->user_data = NULL;
12695
      break;
12696
  }
12697
}
12698

    
12699
struct mg_connection *mg_sntp_get_time(struct mg_mgr *mgr,
12700
                                       mg_event_handler_t event_handler,
12701
                                       const char *sntp_server_name) {
12702
  struct mg_connection *c;
12703
  struct sntp_data *sd = (struct sntp_data *) MG_CALLOC(1, sizeof(*sd));
12704
  if (sd == NULL) {
12705
    return NULL;
12706
  }
12707

    
12708
  c = mg_sntp_connect(mgr, MG_CB(mg_sntp_util_ev_handler, sd),
12709
                      sntp_server_name);
12710
  if (c == NULL) {
12711
    MG_FREE(sd);
12712
    return NULL;
12713
  }
12714

    
12715
  sd->hander = event_handler;
12716
#if !MG_ENABLE_CALLBACK_USERDATA
12717
  c->user_data = sd;
12718
#endif
12719

    
12720
  return c;
12721
}
12722

    
12723
#endif /* MG_ENABLE_SNTP */
12724
#ifdef MG_MODULE_LINES
12725
#line 1 "mongoose/src/mg_socks.c"
12726
#endif
12727
/*
12728
 * Copyright (c) 2017 Cesanta Software Limited
12729
 * All rights reserved
12730
 */
12731

    
12732
#if MG_ENABLE_SOCKS
12733

    
12734
/* Amalgamated: #include "mg_socks.h" */
12735
/* Amalgamated: #include "mg_internal.h" */
12736

    
12737
/*
12738
 *  https://www.ietf.org/rfc/rfc1928.txt paragraph 3, handle client handshake
12739
 *
12740
 *  +----+----------+----------+
12741
 *  |VER | NMETHODS | METHODS  |
12742
 *  +----+----------+----------+
12743
 *  | 1  |    1     | 1 to 255 |
12744
 *  +----+----------+----------+
12745
 */
12746
static void mg_socks5_handshake(struct mg_connection *c) {
12747
  struct mbuf *r = &c->recv_mbuf;
12748
  if (r->buf[0] != MG_SOCKS_VERSION) {
12749
    c->flags |= MG_F_CLOSE_IMMEDIATELY;
12750
  } else if (r->len > 2 && (size_t) r->buf[1] + 2 <= r->len) {
12751
    /* https://www.ietf.org/rfc/rfc1928.txt paragraph 3 */
12752
    unsigned char reply[2] = {MG_SOCKS_VERSION, MG_SOCKS_HANDSHAKE_FAILURE};
12753
    int i;
12754
    for (i = 2; i < r->buf[1] + 2; i++) {
12755
      /* TODO(lsm): support other auth methods */
12756
      if (r->buf[i] == MG_SOCKS_HANDSHAKE_NOAUTH) reply[1] = r->buf[i];
12757
    }
12758
    mbuf_remove(r, 2 + r->buf[1]);
12759
    mg_send(c, reply, sizeof(reply));
12760
    c->flags |= MG_SOCKS_HANDSHAKE_DONE; /* Mark handshake done */
12761
  }
12762
}
12763

    
12764
static void disband(struct mg_connection *c) {
12765
  struct mg_connection *c2 = (struct mg_connection *) c->user_data;
12766
  if (c2 != NULL) {
12767
    c2->flags |= MG_F_SEND_AND_CLOSE;
12768
    c2->user_data = NULL;
12769
  }
12770
  c->flags |= MG_F_SEND_AND_CLOSE;
12771
  c->user_data = NULL;
12772
}
12773

    
12774
static void relay_data(struct mg_connection *c) {
12775
  struct mg_connection *c2 = (struct mg_connection *) c->user_data;
12776
  if (c2 != NULL) {
12777
    mg_send(c2, c->recv_mbuf.buf, c->recv_mbuf.len);
12778
    mbuf_remove(&c->recv_mbuf, c->recv_mbuf.len);
12779
  } else {
12780
    c->flags |= MG_F_SEND_AND_CLOSE;
12781
  }
12782
}
12783

    
12784
static void serv_ev_handler(struct mg_connection *c, int ev, void *ev_data) {
12785
  if (ev == MG_EV_CLOSE) {
12786
    disband(c);
12787
  } else if (ev == MG_EV_RECV) {
12788
    relay_data(c);
12789
  } else if (ev == MG_EV_CONNECT) {
12790
    int res = *(int *) ev_data;
12791
    if (res != 0) LOG(LL_ERROR, ("connect error: %d", res));
12792
  }
12793
}
12794

    
12795
static void mg_socks5_connect(struct mg_connection *c, const char *addr) {
12796
  struct mg_connection *serv = mg_connect(c->mgr, addr, serv_ev_handler);
12797
  serv->user_data = c;
12798
  c->user_data = serv;
12799
}
12800

    
12801
/*
12802
 *  Request, https://www.ietf.org/rfc/rfc1928.txt paragraph 4
12803
 *
12804
 *  +----+-----+-------+------+----------+----------+
12805
 *  |VER | CMD |  RSV  | ATYP | DST.ADDR | DST.PORT |
12806
 *  +----+-----+-------+------+----------+----------+
12807
 *  | 1  |  1  | X'00' |  1   | Variable |    2     |
12808
 *  +----+-----+-------+------+----------+----------+
12809
 */
12810
static void mg_socks5_handle_request(struct mg_connection *c) {
12811
  struct mbuf *r = &c->recv_mbuf;
12812
  unsigned char *p = (unsigned char *) r->buf;
12813
  unsigned char addr_len = 4, reply = MG_SOCKS_SUCCESS;
12814
  int ver, cmd, atyp;
12815
  char addr[300];
12816

    
12817
  if (r->len < 8) return; /* return if not fully buffered. min DST.ADDR is 2 */
12818
  ver = p[0];
12819
  cmd = p[1];
12820
  atyp = p[3];
12821

    
12822
  /* TODO(lsm): support other commands */
12823
  if (ver != MG_SOCKS_VERSION || cmd != MG_SOCKS_CMD_CONNECT) {
12824
    reply = MG_SOCKS_CMD_NOT_SUPPORTED;
12825
  } else if (atyp == MG_SOCKS_ADDR_IPV4) {
12826
    addr_len = 4;
12827
    if (r->len < (size_t) addr_len + 6) return; /* return if not buffered */
12828
    snprintf(addr, sizeof(addr), "%d.%d.%d.%d:%d", p[4], p[5], p[6], p[7],
12829
             p[8] << 8 | p[9]);
12830
    mg_socks5_connect(c, addr);
12831
  } else if (atyp == MG_SOCKS_ADDR_IPV6) {
12832
    addr_len = 16;
12833
    if (r->len < (size_t) addr_len + 6) return; /* return if not buffered */
12834
    snprintf(addr, sizeof(addr), "[%x:%x:%x:%x:%x:%x:%x:%x]:%d",
12835
             p[4] << 8 | p[5], p[6] << 8 | p[7], p[8] << 8 | p[9],
12836
             p[10] << 8 | p[11], p[12] << 8 | p[13], p[14] << 8 | p[15],
12837
             p[16] << 8 | p[17], p[18] << 8 | p[19], p[20] << 8 | p[21]);
12838
    mg_socks5_connect(c, addr);
12839
  } else if (atyp == MG_SOCKS_ADDR_DOMAIN) {
12840
    addr_len = p[4] + 1;
12841
    if (r->len < (size_t) addr_len + 6) return; /* return if not buffered */
12842
    snprintf(addr, sizeof(addr), "%.*s:%d", p[4], p + 5,
12843
             p[4 + addr_len] << 8 | p[4 + addr_len + 1]);
12844
    mg_socks5_connect(c, addr);
12845
  } else {
12846
    reply = MG_SOCKS_ADDR_NOT_SUPPORTED;
12847
  }
12848

    
12849
  /*
12850
   *  Reply, https://www.ietf.org/rfc/rfc1928.txt paragraph 5
12851
   *
12852
   *  +----+-----+-------+------+----------+----------+
12853
   *  |VER | REP |  RSV  | ATYP | BND.ADDR | BND.PORT |
12854
   *  +----+-----+-------+------+----------+----------+
12855
   *  | 1  |  1  | X'00' |  1   | Variable |    2     |
12856
   *  +----+-----+-------+------+----------+----------+
12857
   */
12858
  {
12859
    unsigned char buf[] = {MG_SOCKS_VERSION, reply, 0};
12860
    mg_send(c, buf, sizeof(buf));
12861
  }
12862
  mg_send(c, r->buf + 3, addr_len + 1 + 2);
12863

    
12864
  mbuf_remove(r, 6 + addr_len);      /* Remove request from the input stream */
12865
  c->flags |= MG_SOCKS_CONNECT_DONE; /* Mark ourselves as connected */
12866
}
12867

    
12868
static void socks_handler(struct mg_connection *c, int ev, void *ev_data) {
12869
  if (ev == MG_EV_RECV) {
12870
    if (!(c->flags & MG_SOCKS_HANDSHAKE_DONE)) mg_socks5_handshake(c);
12871
    if (c->flags & MG_SOCKS_HANDSHAKE_DONE &&
12872
        !(c->flags & MG_SOCKS_CONNECT_DONE)) {
12873
      mg_socks5_handle_request(c);
12874
    }
12875
    if (c->flags & MG_SOCKS_CONNECT_DONE) relay_data(c);
12876
  } else if (ev == MG_EV_CLOSE) {
12877
    disband(c);
12878
  }
12879
  (void) ev_data;
12880
}
12881

    
12882
void mg_set_protocol_socks(struct mg_connection *c) {
12883
  c->proto_handler = socks_handler;
12884
}
12885
#endif
12886
#ifdef MG_MODULE_LINES
12887
#line 1 "common/platforms/cc3200/cc3200_libc.c"
12888
#endif
12889
/*
12890
 * Copyright (c) 2014-2016 Cesanta Software Limited
12891
 * All rights reserved
12892
 */
12893

    
12894
#if CS_PLATFORM == CS_P_CC3200
12895

    
12896
/* Amalgamated: #include "common/mg_mem.h" */
12897
#include <stdio.h>
12898
#include <string.h>
12899

    
12900
#ifndef __TI_COMPILER_VERSION__
12901
#include <reent.h>
12902
#include <sys/stat.h>
12903
#include <sys/time.h>
12904
#include <unistd.h>
12905
#endif
12906

    
12907
#include <inc/hw_types.h>
12908
#include <inc/hw_memmap.h>
12909
#include <driverlib/prcm.h>
12910
#include <driverlib/rom.h>
12911
#include <driverlib/rom_map.h>
12912
#include <driverlib/uart.h>
12913
#include <driverlib/utils.h>
12914

    
12915
#define CONSOLE_UART UARTA0_BASE
12916

    
12917
#ifdef __TI_COMPILER_VERSION__
12918
int asprintf(char **strp, const char *fmt, ...) {
12919
  va_list ap;
12920
  int len;
12921

    
12922
  *strp = MG_MALLOC(BUFSIZ);
12923
  if (*strp == NULL) return -1;
12924

    
12925
  va_start(ap, fmt);
12926
  len = vsnprintf(*strp, BUFSIZ, fmt, ap);
12927
  va_end(ap);
12928

    
12929
  if (len > 0) {
12930
    *strp = MG_REALLOC(*strp, len + 1);
12931
    if (*strp == NULL) return -1;
12932
  }
12933

    
12934
  if (len >= BUFSIZ) {
12935
    va_start(ap, fmt);
12936
    len = vsnprintf(*strp, len + 1, fmt, ap);
12937
    va_end(ap);
12938
  }
12939

    
12940
  return len;
12941
}
12942

    
12943
#if MG_TI_NO_HOST_INTERFACE
12944
time_t HOSTtime() {
12945
  struct timeval tp;
12946
  gettimeofday(&tp, NULL);
12947
  return tp.tv_sec;
12948
}
12949
#endif
12950

    
12951
#endif /* __TI_COMPILER_VERSION__ */
12952

    
12953
void fprint_str(FILE *fp, const char *str) {
12954
  while (*str != '\0') {
12955
    if (*str == '\n') MAP_UARTCharPut(CONSOLE_UART, '\r');
12956
    MAP_UARTCharPut(CONSOLE_UART, *str++);
12957
  }
12958
}
12959

    
12960
void _exit(int status) {
12961
  fprint_str(stderr, "_exit\n");
12962
  /* cause an unaligned access exception, that will drop you into gdb */
12963
  *(int *) 1 = status;
12964
  while (1)
12965
    ; /* avoid gcc warning because stdlib abort() has noreturn attribute */
12966
}
12967

    
12968
void _not_implemented(const char *what) {
12969
  fprint_str(stderr, what);
12970
  fprint_str(stderr, " is not implemented\n");
12971
  _exit(42);
12972
}
12973

    
12974
int _kill(int pid, int sig) {
12975
  (void) pid;
12976
  (void) sig;
12977
  _not_implemented("_kill");
12978
  return -1;
12979
}
12980

    
12981
int _getpid() {
12982
  fprint_str(stderr, "_getpid is not implemented\n");
12983
  return 42;
12984
}
12985

    
12986
int _isatty(int fd) {
12987
  /* 0, 1 and 2 are TTYs. */
12988
  return fd < 2;
12989
}
12990

    
12991
#endif /* CS_PLATFORM == CS_P_CC3200 */
12992
#ifdef MG_MODULE_LINES
12993
#line 1 "common/platforms/msp432/msp432_libc.c"
12994
#endif
12995
/*
12996
 * Copyright (c) 2014-2016 Cesanta Software Limited
12997
 * All rights reserved
12998
 */
12999

    
13000
#if CS_PLATFORM == CS_P_MSP432
13001

    
13002
#include <ti/sysbios/BIOS.h>
13003
#include <ti/sysbios/knl/Clock.h>
13004

    
13005
int gettimeofday(struct timeval *tp, void *tzp) {
13006
  uint32_t ticks = Clock_getTicks();
13007
  tp->tv_sec = ticks / 1000;
13008
  tp->tv_usec = (ticks % 1000) * 1000;
13009
  return 0;
13010
}
13011

    
13012
#endif /* CS_PLATFORM == CS_P_MSP432 */
13013
#ifdef MG_MODULE_LINES
13014
#line 1 "common/platforms/nrf5/nrf5_libc.c"
13015
#endif
13016
/*
13017
 * Copyright (c) 2014-2016 Cesanta Software Limited
13018
 * All rights reserved
13019
 */
13020

    
13021
#if (CS_PLATFORM == CS_P_NRF51 || CS_PLATFORM == CS_P_NRF52) && \
13022
    defined(__ARMCC_VERSION)
13023
int gettimeofday(struct timeval *tp, void *tzp) {
13024
  /* TODO */
13025
  tp->tv_sec = 0;
13026
  tp->tv_usec = 0;
13027
  return 0;
13028
}
13029
#endif
13030
#ifdef MG_MODULE_LINES
13031
#line 1 "common/platforms/simplelink/sl_fs_slfs.h"
13032
#endif
13033
/*
13034
 * Copyright (c) 2014-2016 Cesanta Software Limited
13035
 * All rights reserved
13036
 */
13037

    
13038
#ifndef CS_COMMON_PLATFORMS_SIMPLELINK_SL_FS_SLFS_H_
13039
#define CS_COMMON_PLATFORMS_SIMPLELINK_SL_FS_SLFS_H_
13040

    
13041
#if defined(MG_FS_SLFS)
13042

    
13043
#include <stdio.h>
13044
#ifndef __TI_COMPILER_VERSION__
13045
#include <unistd.h>
13046
#include <sys/stat.h>
13047
#endif
13048

    
13049
#define MAX_OPEN_SLFS_FILES 8
13050

    
13051
/* Indirect libc interface - same functions, different names. */
13052
int fs_slfs_open(const char *pathname, int flags, mode_t mode);
13053
int fs_slfs_close(int fd);
13054
ssize_t fs_slfs_read(int fd, void *buf, size_t count);
13055
ssize_t fs_slfs_write(int fd, const void *buf, size_t count);
13056
int fs_slfs_stat(const char *pathname, struct stat *s);
13057
int fs_slfs_fstat(int fd, struct stat *s);
13058
off_t fs_slfs_lseek(int fd, off_t offset, int whence);
13059
int fs_slfs_unlink(const char *filename);
13060
int fs_slfs_rename(const char *from, const char *to);
13061

    
13062
void fs_slfs_set_new_file_size(const char *name, size_t size);
13063

    
13064
#endif /* defined(MG_FS_SLFS) */
13065

    
13066
#endif /* CS_COMMON_PLATFORMS_SIMPLELINK_SL_FS_SLFS_H_ */
13067
#ifdef MG_MODULE_LINES
13068
#line 1 "common/platforms/simplelink/sl_fs_slfs.c"
13069
#endif
13070
/*
13071
 * Copyright (c) 2014-2016 Cesanta Software Limited
13072
 * All rights reserved
13073
 */
13074

    
13075
/* Standard libc interface to TI SimpleLink FS. */
13076

    
13077
#if defined(MG_FS_SLFS) || defined(CC3200_FS_SLFS)
13078

    
13079
/* Amalgamated: #include "common/platforms/simplelink/sl_fs_slfs.h" */
13080

    
13081
#include <errno.h>
13082

    
13083
#if CS_PLATFORM == CS_P_CC3200
13084
#include <inc/hw_types.h>
13085
#endif
13086

    
13087
/* Amalgamated: #include "common/cs_dbg.h" */
13088
/* Amalgamated: #include "common/mg_mem.h" */
13089

    
13090
#if SL_MAJOR_VERSION_NUM < 2
13091
int slfs_open(const unsigned char *fname, uint32_t flags) {
13092
  _i32 fh;
13093
  _i32 r = sl_FsOpen(fname, flags, NULL /* token */, &fh);
13094
  return (r < 0 ? r : fh);
13095
}
13096
#else /* SL_MAJOR_VERSION_NUM >= 2 */
13097
int slfs_open(const unsigned char *fname, uint32_t flags) {
13098
  return sl_FsOpen(fname, flags, NULL /* token */);
13099
}
13100
#endif
13101

    
13102
/* From sl_fs.c */
13103
int set_errno(int e);
13104
const char *drop_dir(const char *fname, bool *is_slfs);
13105

    
13106
/*
13107
 * With SLFS, you have to pre-declare max file size. Yes. Really.
13108
 * 64K should be enough for everyone. Right?
13109
 */
13110
#ifndef FS_SLFS_MAX_FILE_SIZE
13111
#define FS_SLFS_MAX_FILE_SIZE (64 * 1024)
13112
#endif
13113

    
13114
struct sl_file_size_hint {
13115
  char *name;
13116
  size_t size;
13117
};
13118

    
13119
struct sl_fd_info {
13120
  _i32 fh;
13121
  _off_t pos;
13122
  size_t size;
13123
};
13124

    
13125
static struct sl_fd_info s_sl_fds[MAX_OPEN_SLFS_FILES];
13126
static struct sl_file_size_hint s_sl_file_size_hints[MAX_OPEN_SLFS_FILES];
13127

    
13128
static int sl_fs_to_errno(_i32 r) {
13129
  DBG(("SL error: %d", (int) r));
13130
  switch (r) {
13131
    case SL_FS_OK:
13132
      return 0;
13133
    case SL_ERROR_FS_FILE_NAME_EXIST:
13134
      return EEXIST;
13135
    case SL_ERROR_FS_WRONG_FILE_NAME:
13136
      return EINVAL;
13137
    case SL_ERROR_FS_NO_AVAILABLE_NV_INDEX:
13138
    case SL_ERROR_FS_NOT_ENOUGH_STORAGE_SPACE:
13139
      return ENOSPC;
13140
    case SL_ERROR_FS_FAILED_TO_ALLOCATE_MEM:
13141
      return ENOMEM;
13142
    case SL_ERROR_FS_FILE_NOT_EXISTS:
13143
      return ENOENT;
13144
    case SL_ERROR_FS_NOT_SUPPORTED:
13145
      return ENOTSUP;
13146
  }
13147
  return ENXIO;
13148
}
13149

    
13150
int fs_slfs_open(const char *pathname, int flags, mode_t mode) {
13151
  int fd;
13152
  for (fd = 0; fd < MAX_OPEN_SLFS_FILES; fd++) {
13153
    if (s_sl_fds[fd].fh <= 0) break;
13154
  }
13155
  if (fd >= MAX_OPEN_SLFS_FILES) return set_errno(ENOMEM);
13156
  struct sl_fd_info *fi = &s_sl_fds[fd];
13157

    
13158
  /*
13159
   * Apply path manipulations again, in case we got here directly
13160
   * (via TI libc's "add_device").
13161
   */
13162
  pathname = drop_dir(pathname, NULL);
13163

    
13164
  _u32 am = 0;
13165
  fi->size = (size_t) -1;
13166
  int rw = (flags & 3);
13167
  size_t new_size = FS_SLFS_MAX_FILE_SIZE;
13168
  if (rw == O_RDONLY) {
13169
    SlFsFileInfo_t sl_fi;
13170
    _i32 r = sl_FsGetInfo((const _u8 *) pathname, 0, &sl_fi);
13171
    if (r == SL_FS_OK) {
13172
      fi->size = SL_FI_FILE_SIZE(sl_fi);
13173
    }
13174
    am = SL_FS_READ;
13175
  } else {
13176
    if (!(flags & O_TRUNC) || (flags & O_APPEND)) {
13177
      // FailFS files cannot be opened for append and will be truncated
13178
      // when opened for write.
13179
      return set_errno(ENOTSUP);
13180
    }
13181
    if (flags & O_CREAT) {
13182
      size_t i;
13183
      for (i = 0; i < MAX_OPEN_SLFS_FILES; i++) {
13184
        if (s_sl_file_size_hints[i].name != NULL &&
13185
            strcmp(s_sl_file_size_hints[i].name, pathname) == 0) {
13186
          new_size = s_sl_file_size_hints[i].size;
13187
          MG_FREE(s_sl_file_size_hints[i].name);
13188
          s_sl_file_size_hints[i].name = NULL;
13189
          break;
13190
        }
13191
      }
13192
      am = FS_MODE_OPEN_CREATE(new_size, 0);
13193
    } else {
13194
      am = SL_FS_WRITE;
13195
    }
13196
  }
13197
  fi->fh = slfs_open((_u8 *) pathname, am);
13198
  LOG(LL_DEBUG, ("sl_FsOpen(%s, 0x%x) sz %u = %d", pathname, (int) am,
13199
                 (unsigned int) new_size, (int) fi->fh));
13200
  int r;
13201
  if (fi->fh >= 0) {
13202
    fi->pos = 0;
13203
    r = fd;
13204
  } else {
13205
    r = set_errno(sl_fs_to_errno(fi->fh));
13206
  }
13207
  return r;
13208
}
13209

    
13210
int fs_slfs_close(int fd) {
13211
  struct sl_fd_info *fi = &s_sl_fds[fd];
13212
  if (fi->fh <= 0) return set_errno(EBADF);
13213
  _i32 r = sl_FsClose(fi->fh, NULL, NULL, 0);
13214
  LOG(LL_DEBUG, ("sl_FsClose(%d) = %d", (int) fi->fh, (int) r));
13215
  s_sl_fds[fd].fh = -1;
13216
  return set_errno(sl_fs_to_errno(r));
13217
}
13218

    
13219
ssize_t fs_slfs_read(int fd, void *buf, size_t count) {
13220
  struct sl_fd_info *fi = &s_sl_fds[fd];
13221
  if (fi->fh <= 0) return set_errno(EBADF);
13222
  /* Simulate EOF. sl_FsRead @ file_size return SL_FS_ERR_OFFSET_OUT_OF_RANGE.
13223
   */
13224
  if (fi->pos == fi->size) return 0;
13225
  _i32 r = sl_FsRead(fi->fh, fi->pos, buf, count);
13226
  DBG(("sl_FsRead(%d, %d, %d) = %d", (int) fi->fh, (int) fi->pos, (int) count,
13227
       (int) r));
13228
  if (r >= 0) {
13229
    fi->pos += r;
13230
    return r;
13231
  }
13232
  return set_errno(sl_fs_to_errno(r));
13233
}
13234

    
13235
ssize_t fs_slfs_write(int fd, const void *buf, size_t count) {
13236
  struct sl_fd_info *fi = &s_sl_fds[fd];
13237
  if (fi->fh <= 0) return set_errno(EBADF);
13238
  _i32 r = sl_FsWrite(fi->fh, fi->pos, (_u8 *) buf, count);
13239
  DBG(("sl_FsWrite(%d, %d, %d) = %d", (int) fi->fh, (int) fi->pos, (int) count,
13240
       (int) r));
13241
  if (r >= 0) {
13242
    fi->pos += r;
13243
    return r;
13244
  }
13245
  return set_errno(sl_fs_to_errno(r));
13246
}
13247

    
13248
int fs_slfs_stat(const char *pathname, struct stat *s) {
13249
  SlFsFileInfo_t sl_fi;
13250
  /*
13251
   * Apply path manipulations again, in case we got here directly
13252
   * (via TI libc's "add_device").
13253
   */
13254
  pathname = drop_dir(pathname, NULL);
13255
  _i32 r = sl_FsGetInfo((const _u8 *) pathname, 0, &sl_fi);
13256
  if (r == SL_FS_OK) {
13257
    s->st_mode = S_IFREG | 0666;
13258
    s->st_nlink = 1;
13259
    s->st_size = SL_FI_FILE_SIZE(sl_fi);
13260
    return 0;
13261
  }
13262
  return set_errno(sl_fs_to_errno(r));
13263
}
13264

    
13265
int fs_slfs_fstat(int fd, struct stat *s) {
13266
  struct sl_fd_info *fi = &s_sl_fds[fd];
13267
  if (fi->fh <= 0) return set_errno(EBADF);
13268
  s->st_mode = 0666;
13269
  s->st_mode = S_IFREG | 0666;
13270
  s->st_nlink = 1;
13271
  s->st_size = fi->size;
13272
  return 0;
13273
}
13274

    
13275
off_t fs_slfs_lseek(int fd, off_t offset, int whence) {
13276
  if (s_sl_fds[fd].fh <= 0) return set_errno(EBADF);
13277
  switch (whence) {
13278
    case SEEK_SET:
13279
      s_sl_fds[fd].pos = offset;
13280
      break;
13281
    case SEEK_CUR:
13282
      s_sl_fds[fd].pos += offset;
13283
      break;
13284
    case SEEK_END:
13285
      return set_errno(ENOTSUP);
13286
  }
13287
  return 0;
13288
}
13289

    
13290
int fs_slfs_unlink(const char *pathname) {
13291
  /*
13292
   * Apply path manipulations again, in case we got here directly
13293
   * (via TI libc's "add_device").
13294
   */
13295
  pathname = drop_dir(pathname, NULL);
13296
  return set_errno(sl_fs_to_errno(sl_FsDel((const _u8 *) pathname, 0)));
13297
}
13298

    
13299
int fs_slfs_rename(const char *from, const char *to) {
13300
  return set_errno(ENOTSUP);
13301
}
13302

    
13303
void fs_slfs_set_new_file_size(const char *name, size_t size) {
13304
  int i;
13305
  for (i = 0; i < MAX_OPEN_SLFS_FILES; i++) {
13306
    if (s_sl_file_size_hints[i].name == NULL) {
13307
      DBG(("File size hint: %s %d", name, (int) size));
13308
      s_sl_file_size_hints[i].name = strdup(name);
13309
      s_sl_file_size_hints[i].size = size;
13310
      break;
13311
    }
13312
  }
13313
}
13314

    
13315
#endif /* defined(MG_FS_SLFS) || defined(CC3200_FS_SLFS) */
13316
#ifdef MG_MODULE_LINES
13317
#line 1 "common/platforms/simplelink/sl_fs.c"
13318
#endif
13319
/*
13320
 * Copyright (c) 2014-2016 Cesanta Software Limited
13321
 * All rights reserved
13322
 */
13323

    
13324
#if MG_NET_IF == MG_NET_IF_SIMPLELINK && \
13325
    (defined(MG_FS_SLFS) || defined(MG_FS_SPIFFS))
13326

    
13327
int set_errno(int e) {
13328
  errno = e;
13329
  return (e == 0 ? 0 : -1);
13330
}
13331

    
13332
const char *drop_dir(const char *fname, bool *is_slfs) {
13333
  if (is_slfs != NULL) {
13334
    *is_slfs = (strncmp(fname, "SL:", 3) == 0);
13335
    if (*is_slfs) fname += 3;
13336
  }
13337
  /* Drop "./", if any */
13338
  if (fname[0] == '.' && fname[1] == '/') {
13339
    fname += 2;
13340
  }
13341
  /*
13342
   * Drop / if it is the only one in the path.
13343
   * This allows use of /pretend/directories but serves /file.txt as normal.
13344
   */
13345
  if (fname[0] == '/' && strchr(fname + 1, '/') == NULL) {
13346
    fname++;
13347
  }
13348
  return fname;
13349
}
13350

    
13351
#if !defined(MG_FS_NO_VFS)
13352

    
13353
#include <errno.h>
13354
#include <stdbool.h>
13355
#include <stdio.h>
13356
#include <stdlib.h>
13357
#include <string.h>
13358
#ifdef __TI_COMPILER_VERSION__
13359
#include <file.h>
13360
#endif
13361

    
13362
/* Amalgamated: #include "common/cs_dbg.h" */
13363
/* Amalgamated: #include "common/platform.h" */
13364

    
13365
#ifdef CC3200_FS_SPIFFS
13366
/* Amalgamated: #include "cc3200_fs_spiffs.h" */
13367
#endif
13368

    
13369
#ifdef MG_FS_SLFS
13370
/* Amalgamated: #include "sl_fs_slfs.h" */
13371
#endif
13372

    
13373
#define NUM_SYS_FDS 3
13374
#define SPIFFS_FD_BASE 10
13375
#define SLFS_FD_BASE 100
13376

    
13377
#if !defined(MG_UART_CHAR_PUT) && !defined(MG_UART_WRITE)
13378
#if CS_PLATFORM == CS_P_CC3200
13379
#include <inc/hw_types.h>
13380
#include <inc/hw_memmap.h>
13381
#include <driverlib/rom.h>
13382
#include <driverlib/rom_map.h>
13383
#include <driverlib/uart.h>
13384
#define MG_UART_CHAR_PUT(fd, c) MAP_UARTCharPut(UARTA0_BASE, c);
13385
#else
13386
#define MG_UART_WRITE(fd, buf, len)
13387
#endif /* CS_PLATFORM == CS_P_CC3200 */
13388
#endif /* !MG_UART_CHAR_PUT */
13389

    
13390
enum fd_type {
13391
  FD_INVALID,
13392
  FD_SYS,
13393
#ifdef CC3200_FS_SPIFFS
13394
  FD_SPIFFS,
13395
#endif
13396
#ifdef MG_FS_SLFS
13397
  FD_SLFS
13398
#endif
13399
};
13400
static int fd_type(int fd) {
13401
  if (fd >= 0 && fd < NUM_SYS_FDS) return FD_SYS;
13402
#ifdef CC3200_FS_SPIFFS
13403
  if (fd >= SPIFFS_FD_BASE && fd < SPIFFS_FD_BASE + MAX_OPEN_SPIFFS_FILES) {
13404
    return FD_SPIFFS;
13405
  }
13406
#endif
13407
#ifdef MG_FS_SLFS
13408
  if (fd >= SLFS_FD_BASE && fd < SLFS_FD_BASE + MAX_OPEN_SLFS_FILES) {
13409
    return FD_SLFS;
13410
  }
13411
#endif
13412
  return FD_INVALID;
13413
}
13414

    
13415
#if MG_TI_NO_HOST_INTERFACE
13416
int open(const char *pathname, unsigned flags, int mode) {
13417
#else
13418
int _open(const char *pathname, int flags, mode_t mode) {
13419
#endif
13420
  int fd = -1;
13421
  bool is_sl;
13422
  const char *fname = drop_dir(pathname, &is_sl);
13423
  if (is_sl) {
13424
#ifdef MG_FS_SLFS
13425
    fd = fs_slfs_open(fname, flags, mode);
13426
    if (fd >= 0) fd += SLFS_FD_BASE;
13427
#endif
13428
  } else {
13429
#ifdef CC3200_FS_SPIFFS
13430
    fd = fs_spiffs_open(fname, flags, mode);
13431
    if (fd >= 0) fd += SPIFFS_FD_BASE;
13432
#endif
13433
  }
13434
  LOG(LL_DEBUG,
13435
      ("open(%s, 0x%x) = %d, fname = %s", pathname, flags, fd, fname));
13436
  return fd;
13437
}
13438

    
13439
int _stat(const char *pathname, struct stat *st) {
13440
  int res = -1;
13441
  bool is_sl;
13442
  const char *fname = drop_dir(pathname, &is_sl);
13443
  memset(st, 0, sizeof(*st));
13444
  /* Simulate statting the root directory. */
13445
  if (fname[0] == '\0' || strcmp(fname, ".") == 0) {
13446
    st->st_ino = 0;
13447
    st->st_mode = S_IFDIR | 0777;
13448
    st->st_nlink = 1;
13449
    st->st_size = 0;
13450
    return 0;
13451
  }
13452
  if (is_sl) {
13453
#ifdef MG_FS_SLFS
13454
    res = fs_slfs_stat(fname, st);
13455
#endif
13456
  } else {
13457
#ifdef CC3200_FS_SPIFFS
13458
    res = fs_spiffs_stat(fname, st);
13459
#endif
13460
  }
13461
  LOG(LL_DEBUG, ("stat(%s) = %d; fname = %s", pathname, res, fname));
13462
  return res;
13463
}
13464

    
13465
#if MG_TI_NO_HOST_INTERFACE
13466
int close(int fd) {
13467
#else
13468
int _close(int fd) {
13469
#endif
13470
  int r = -1;
13471
  switch (fd_type(fd)) {
13472
    case FD_INVALID:
13473
      r = set_errno(EBADF);
13474
      break;
13475
    case FD_SYS:
13476
      r = set_errno(EACCES);
13477
      break;
13478
#ifdef CC3200_FS_SPIFFS
13479
    case FD_SPIFFS:
13480
      r = fs_spiffs_close(fd - SPIFFS_FD_BASE);
13481
      break;
13482
#endif
13483
#ifdef MG_FS_SLFS
13484
    case FD_SLFS:
13485
      r = fs_slfs_close(fd - SLFS_FD_BASE);
13486
      break;
13487
#endif
13488
  }
13489
  DBG(("close(%d) = %d", fd, r));
13490
  return r;
13491
}
13492

    
13493
#if MG_TI_NO_HOST_INTERFACE
13494
off_t lseek(int fd, off_t offset, int whence) {
13495
#else
13496
off_t _lseek(int fd, off_t offset, int whence) {
13497
#endif
13498
  int r = -1;
13499
  switch (fd_type(fd)) {
13500
    case FD_INVALID:
13501
      r = set_errno(EBADF);
13502
      break;
13503
    case FD_SYS:
13504
      r = set_errno(ESPIPE);
13505
      break;
13506
#ifdef CC3200_FS_SPIFFS
13507
    case FD_SPIFFS:
13508
      r = fs_spiffs_lseek(fd - SPIFFS_FD_BASE, offset, whence);
13509
      break;
13510
#endif
13511
#ifdef MG_FS_SLFS
13512
    case FD_SLFS:
13513
      r = fs_slfs_lseek(fd - SLFS_FD_BASE, offset, whence);
13514
      break;
13515
#endif
13516
  }
13517
  DBG(("lseek(%d, %d, %d) = %d", fd, (int) offset, whence, r));
13518
  return r;
13519
}
13520

    
13521
int _fstat(int fd, struct stat *s) {
13522
  int r = -1;
13523
  memset(s, 0, sizeof(*s));
13524
  switch (fd_type(fd)) {
13525
    case FD_INVALID:
13526
      r = set_errno(EBADF);
13527
      break;
13528
    case FD_SYS: {
13529
      /* Create barely passable stats for STD{IN,OUT,ERR}. */
13530
      memset(s, 0, sizeof(*s));
13531
      s->st_ino = fd;
13532
      s->st_mode = S_IFCHR | 0666;
13533
      r = 0;
13534
      break;
13535
    }
13536
#ifdef CC3200_FS_SPIFFS
13537
    case FD_SPIFFS:
13538
      r = fs_spiffs_fstat(fd - SPIFFS_FD_BASE, s);
13539
      break;
13540
#endif
13541
#ifdef MG_FS_SLFS
13542
    case FD_SLFS:
13543
      r = fs_slfs_fstat(fd - SLFS_FD_BASE, s);
13544
      break;
13545
#endif
13546
  }
13547
  DBG(("fstat(%d) = %d", fd, r));
13548
  return r;
13549
}
13550

    
13551
#if MG_TI_NO_HOST_INTERFACE
13552
int read(int fd, char *buf, unsigned count) {
13553
#else
13554
ssize_t _read(int fd, void *buf, size_t count) {
13555
#endif
13556
  int r = -1;
13557
  switch (fd_type(fd)) {
13558
    case FD_INVALID:
13559
      r = set_errno(EBADF);
13560
      break;
13561
    case FD_SYS: {
13562
      if (fd != 0) {
13563
        r = set_errno(EACCES);
13564
        break;
13565
      }
13566
      /* Should we allow reading from stdin = uart? */
13567
      r = set_errno(ENOTSUP);
13568
      break;
13569
    }
13570
#ifdef CC3200_FS_SPIFFS
13571
    case FD_SPIFFS:
13572
      r = fs_spiffs_read(fd - SPIFFS_FD_BASE, buf, count);
13573
      break;
13574
#endif
13575
#ifdef MG_FS_SLFS
13576
    case FD_SLFS:
13577
      r = fs_slfs_read(fd - SLFS_FD_BASE, buf, count);
13578
      break;
13579
#endif
13580
  }
13581
  DBG(("read(%d, %u) = %d", fd, count, r));
13582
  return r;
13583
}
13584

    
13585
#if MG_TI_NO_HOST_INTERFACE
13586
int write(int fd, const char *buf, unsigned count) {
13587
#else
13588
ssize_t _write(int fd, const void *buf, size_t count) {
13589
#endif
13590
  int r = -1;
13591
  switch (fd_type(fd)) {
13592
    case FD_INVALID:
13593
      r = set_errno(EBADF);
13594
      break;
13595
    case FD_SYS: {
13596
      if (fd == 0) {
13597
        r = set_errno(EACCES);
13598
        break;
13599
      }
13600
#ifdef MG_UART_WRITE
13601
      MG_UART_WRITE(fd, buf, count);
13602
#elif defined(MG_UART_CHAR_PUT)
13603
      {
13604
        size_t i;
13605
        for (i = 0; i < count; i++) {
13606
          const char c = ((const char *) buf)[i];
13607
          if (c == '\n') MG_UART_CHAR_PUT(fd, '\r');
13608
          MG_UART_CHAR_PUT(fd, c);
13609
        }
13610
      }
13611
#endif
13612
      r = count;
13613
      break;
13614
    }
13615
#ifdef CC3200_FS_SPIFFS
13616
    case FD_SPIFFS:
13617
      r = fs_spiffs_write(fd - SPIFFS_FD_BASE, buf, count);
13618
      break;
13619
#endif
13620
#ifdef MG_FS_SLFS
13621
    case FD_SLFS:
13622
      r = fs_slfs_write(fd - SLFS_FD_BASE, buf, count);
13623
      break;
13624
#endif
13625
  }
13626
  return r;
13627
}
13628

    
13629
/*
13630
 * On Newlib we override rename directly too, because the default
13631
 * implementation using _link and _unlink doesn't work for us.
13632
 */
13633
#if MG_TI_NO_HOST_INTERFACE || defined(_NEWLIB_VERSION)
13634
int rename(const char *frompath, const char *topath) {
13635
  int r = -1;
13636
  bool is_sl_from, is_sl_to;
13637
  const char *from = drop_dir(frompath, &is_sl_from);
13638
  const char *to = drop_dir(topath, &is_sl_to);
13639
  if (is_sl_from || is_sl_to) {
13640
    set_errno(ENOTSUP);
13641
  } else {
13642
#ifdef CC3200_FS_SPIFFS
13643
    r = fs_spiffs_rename(from, to);
13644
#endif
13645
  }
13646
  DBG(("rename(%s, %s) = %d", from, to, r));
13647
  return r;
13648
}
13649
#endif /* MG_TI_NO_HOST_INTERFACE || defined(_NEWLIB_VERSION) */
13650

    
13651
#if MG_TI_NO_HOST_INTERFACE
13652
int unlink(const char *pathname) {
13653
#else
13654
int _unlink(const char *pathname) {
13655
#endif
13656
  int r = -1;
13657
  bool is_sl;
13658
  const char *fname = drop_dir(pathname, &is_sl);
13659
  if (is_sl) {
13660
#ifdef MG_FS_SLFS
13661
    r = fs_slfs_unlink(fname);
13662
#endif
13663
  } else {
13664
#ifdef CC3200_FS_SPIFFS
13665
    r = fs_spiffs_unlink(fname);
13666
#endif
13667
  }
13668
  DBG(("unlink(%s) = %d, fname = %s", pathname, r, fname));
13669
  return r;
13670
}
13671

    
13672
#ifdef CC3200_FS_SPIFFS /* FailFS does not support listing files. */
13673
DIR *opendir(const char *dir_name) {
13674
  DIR *r = NULL;
13675
  bool is_sl;
13676
  drop_dir(dir_name, &is_sl);
13677
  if (is_sl) {
13678
    r = NULL;
13679
    set_errno(ENOTSUP);
13680
  } else {
13681
    r = fs_spiffs_opendir(dir_name);
13682
  }
13683
  DBG(("opendir(%s) = %p", dir_name, r));
13684
  return r;
13685
}
13686

    
13687
struct dirent *readdir(DIR *dir) {
13688
  struct dirent *res = fs_spiffs_readdir(dir);
13689
  DBG(("readdir(%p) = %p", dir, res));
13690
  return res;
13691
}
13692

    
13693
int closedir(DIR *dir) {
13694
  int res = fs_spiffs_closedir(dir);
13695
  DBG(("closedir(%p) = %d", dir, res));
13696
  return res;
13697
}
13698

    
13699
int rmdir(const char *path) {
13700
  return fs_spiffs_rmdir(path);
13701
}
13702

    
13703
int mkdir(const char *path, mode_t mode) {
13704
  (void) path;
13705
  (void) mode;
13706
  /* for spiffs supports only root dir, which comes from mongoose as '.' */
13707
  return (strlen(path) == 1 && *path == '.') ? 0 : ENOTDIR;
13708
}
13709
#endif
13710

    
13711
int sl_fs_init(void) {
13712
  int ret = 1;
13713
#ifdef __TI_COMPILER_VERSION__
13714
#ifdef MG_FS_SLFS
13715
#pragma diag_push
13716
#pragma diag_suppress 169 /* Nothing we can do about the prototype mismatch. \
13717
                             */
13718
  ret = (add_device("SL", _MSA, fs_slfs_open, fs_slfs_close, fs_slfs_read,
13719
                    fs_slfs_write, fs_slfs_lseek, fs_slfs_unlink,
13720
                    fs_slfs_rename) == 0);
13721
#pragma diag_pop
13722
#endif
13723
#endif
13724
  return ret;
13725
}
13726

    
13727
#endif /* !defined(MG_FS_NO_VFS) */
13728
#endif /* MG_NET_IF == MG_NET_IF_SIMPLELINK && (defined(MG_FS_SLFS) || \
13729
          defined(MG_FS_SPIFFS)) */
13730
#ifdef MG_MODULE_LINES
13731
#line 1 "common/platforms/simplelink/sl_socket.c"
13732
#endif
13733
/*
13734
 * Copyright (c) 2014-2016 Cesanta Software Limited
13735
 * All rights reserved
13736
 */
13737

    
13738
#if MG_NET_IF == MG_NET_IF_SIMPLELINK
13739

    
13740
#include <errno.h>
13741
#include <stdio.h>
13742

    
13743
/* Amalgamated: #include "common/platform.h" */
13744

    
13745
const char *inet_ntop(int af, const void *src, char *dst, socklen_t size) {
13746
  int res;
13747
  struct in_addr *in = (struct in_addr *) src;
13748
  if (af != AF_INET) {
13749
    errno = ENOTSUP;
13750
    return NULL;
13751
  }
13752
  res = snprintf(dst, size, "%lu.%lu.%lu.%lu", SL_IPV4_BYTE(in->s_addr, 0),
13753
                 SL_IPV4_BYTE(in->s_addr, 1), SL_IPV4_BYTE(in->s_addr, 2),
13754
                 SL_IPV4_BYTE(in->s_addr, 3));
13755
  return res > 0 ? dst : NULL;
13756
}
13757

    
13758
char *inet_ntoa(struct in_addr n) {
13759
  static char a[16];
13760
  return (char *) inet_ntop(AF_INET, &n, a, sizeof(a));
13761
}
13762

    
13763
int inet_pton(int af, const char *src, void *dst) {
13764
  uint32_t a0, a1, a2, a3;
13765
  uint8_t *db = (uint8_t *) dst;
13766
  if (af != AF_INET) {
13767
    errno = ENOTSUP;
13768
    return 0;
13769
  }
13770
  if (sscanf(src, "%lu.%lu.%lu.%lu", &a0, &a1, &a2, &a3) != 4) {
13771
    return 0;
13772
  }
13773
  *db = a3;
13774
  *(db + 1) = a2;
13775
  *(db + 2) = a1;
13776
  *(db + 3) = a0;
13777
  return 1;
13778
}
13779

    
13780
#endif /* MG_NET_IF == MG_NET_IF_SIMPLELINK */
13781
#ifdef MG_MODULE_LINES
13782
#line 1 "common/platforms/simplelink/sl_mg_task.c"
13783
#endif
13784
#if MG_NET_IF == MG_NET_IF_SIMPLELINK && !defined(MG_SIMPLELINK_NO_OSI)
13785

    
13786
/* Amalgamated: #include "mg_task.h" */
13787

    
13788
#include <oslib/osi.h>
13789

    
13790
enum mg_q_msg_type {
13791
  MG_Q_MSG_CB,
13792
};
13793
struct mg_q_msg {
13794
  enum mg_q_msg_type type;
13795
  void (*cb)(struct mg_mgr *mgr, void *arg);
13796
  void *arg;
13797
};
13798
static OsiMsgQ_t s_mg_q;
13799
static void mg_task(void *arg);
13800

    
13801
bool mg_start_task(int priority, int stack_size, mg_init_cb mg_init) {
13802
  if (osi_MsgQCreate(&s_mg_q, "MG", sizeof(struct mg_q_msg), 16) != OSI_OK) {
13803
    return false;
13804
  }
13805
  if (osi_TaskCreate(mg_task, (const signed char *) "MG", stack_size,
13806
                     (void *) mg_init, priority, NULL) != OSI_OK) {
13807
    return false;
13808
  }
13809
  return true;
13810
}
13811

    
13812
static void mg_task(void *arg) {
13813
  struct mg_mgr mgr;
13814
  mg_init_cb mg_init = (mg_init_cb) arg;
13815
  mg_mgr_init(&mgr, NULL);
13816
  mg_init(&mgr);
13817
  while (1) {
13818
    struct mg_q_msg msg;
13819
    mg_mgr_poll(&mgr, 1);
13820
    if (osi_MsgQRead(&s_mg_q, &msg, 1) != OSI_OK) continue;
13821
    switch (msg.type) {
13822
      case MG_Q_MSG_CB: {
13823
        msg.cb(&mgr, msg.arg);
13824
      }
13825
    }
13826
  }
13827
}
13828

    
13829
void mg_run_in_task(void (*cb)(struct mg_mgr *mgr, void *arg), void *cb_arg) {
13830
  struct mg_q_msg msg = {MG_Q_MSG_CB, cb, cb_arg};
13831
  osi_MsgQWrite(&s_mg_q, &msg, OSI_NO_WAIT);
13832
}
13833

    
13834
#endif /* MG_NET_IF == MG_NET_IF_SIMPLELINK && !defined(MG_SIMPLELINK_NO_OSI) \
13835
          */
13836
#ifdef MG_MODULE_LINES
13837
#line 1 "common/platforms/simplelink/sl_net_if.h"
13838
#endif
13839
/*
13840
 * Copyright (c) 2014-2016 Cesanta Software Limited
13841
 * All rights reserved
13842
 */
13843

    
13844
#ifndef CS_COMMON_PLATFORMS_SIMPLELINK_SL_NET_IF_H_
13845
#define CS_COMMON_PLATFORMS_SIMPLELINK_SL_NET_IF_H_
13846

    
13847
/* Amalgamated: #include "mongoose/src/net_if.h" */
13848

    
13849
#ifdef __cplusplus
13850
extern "C" {
13851
#endif /* __cplusplus */
13852

    
13853
#ifndef MG_ENABLE_NET_IF_SIMPLELINK
13854
#define MG_ENABLE_NET_IF_SIMPLELINK MG_NET_IF == MG_NET_IF_SIMPLELINK
13855
#endif
13856

    
13857
extern const struct mg_iface_vtable mg_simplelink_iface_vtable;
13858

    
13859
#ifdef __cplusplus
13860
}
13861
#endif /* __cplusplus */
13862

    
13863
#endif /* CS_COMMON_PLATFORMS_SIMPLELINK_SL_NET_IF_H_ */
13864
#ifdef MG_MODULE_LINES
13865
#line 1 "common/platforms/simplelink/sl_net_if.c"
13866
#endif
13867
/*
13868
 * Copyright (c) 2014-2016 Cesanta Software Limited
13869
 * All rights reserved
13870
 */
13871

    
13872
/* Amalgamated: #include "common/platforms/simplelink/sl_net_if.h" */
13873

    
13874
#if MG_ENABLE_NET_IF_SIMPLELINK
13875

    
13876
/* Amalgamated: #include "mongoose/src/internal.h" */
13877
/* Amalgamated: #include "mongoose/src/util.h" */
13878

    
13879
#define MG_TCP_RECV_BUFFER_SIZE 1024
13880
#define MG_UDP_RECV_BUFFER_SIZE 1500
13881

    
13882
static sock_t mg_open_listening_socket(struct mg_connection *nc,
13883
                                       union socket_address *sa, int type,
13884
                                       int proto);
13885

    
13886
void mg_set_non_blocking_mode(sock_t sock) {
13887
  SlSockNonblocking_t opt;
13888
#if SL_MAJOR_VERSION_NUM < 2
13889
  opt.NonblockingEnabled = 1;
13890
#else
13891
  opt.NonBlockingEnabled = 1;
13892
#endif
13893
  sl_SetSockOpt(sock, SL_SOL_SOCKET, SL_SO_NONBLOCKING, &opt, sizeof(opt));
13894
}
13895

    
13896
static int mg_is_error(int n) {
13897
  return (n < 0 && n != SL_ERROR_BSD_EALREADY && n != SL_ERROR_BSD_EAGAIN);
13898
}
13899

    
13900
void mg_sl_if_connect_tcp(struct mg_connection *nc,
13901
                          const union socket_address *sa) {
13902
  int proto = 0;
13903
  if (nc->flags & MG_F_SSL) proto = SL_SEC_SOCKET;
13904
  sock_t sock = sl_Socket(AF_INET, SOCK_STREAM, proto);
13905
  if (sock < 0) {
13906
    nc->err = sock;
13907
    goto out;
13908
  }
13909
  mg_sock_set(nc, sock);
13910
#if MG_ENABLE_SSL
13911
  nc->err = sl_set_ssl_opts(sock, nc);
13912
  if (nc->err != 0) goto out;
13913
#endif
13914
  nc->err = sl_Connect(sock, &sa->sa, sizeof(sa->sin));
13915
out:
13916
  DBG(("%p to %s:%d sock %d %d err %d", nc, inet_ntoa(sa->sin.sin_addr),
13917
       ntohs(sa->sin.sin_port), nc->sock, proto, nc->err));
13918
}
13919

    
13920
void mg_sl_if_connect_udp(struct mg_connection *nc) {
13921
  sock_t sock = sl_Socket(AF_INET, SOCK_DGRAM, 0);
13922
  if (sock < 0) {
13923
    nc->err = sock;
13924
    return;
13925
  }
13926
  mg_sock_set(nc, sock);
13927
  nc->err = 0;
13928
}
13929

    
13930
int mg_sl_if_listen_tcp(struct mg_connection *nc, union socket_address *sa) {
13931
  int proto = 0;
13932
  if (nc->flags & MG_F_SSL) proto = SL_SEC_SOCKET;
13933
  sock_t sock = mg_open_listening_socket(nc, sa, SOCK_STREAM, proto);
13934
  if (sock < 0) return sock;
13935
  mg_sock_set(nc, sock);
13936
  return 0;
13937
}
13938

    
13939
int mg_sl_if_listen_udp(struct mg_connection *nc, union socket_address *sa) {
13940
  sock_t sock = mg_open_listening_socket(nc, sa, SOCK_DGRAM, 0);
13941
  if (sock == INVALID_SOCKET) return (errno ? errno : 1);
13942
  mg_sock_set(nc, sock);
13943
  return 0;
13944
}
13945

    
13946
void mg_sl_if_tcp_send(struct mg_connection *nc, const void *buf, size_t len) {
13947
  mbuf_append(&nc->send_mbuf, buf, len);
13948
}
13949

    
13950
void mg_sl_if_udp_send(struct mg_connection *nc, const void *buf, size_t len) {
13951
  mbuf_append(&nc->send_mbuf, buf, len);
13952
}
13953

    
13954
void mg_sl_if_recved(struct mg_connection *nc, size_t len) {
13955
  (void) nc;
13956
  (void) len;
13957
}
13958

    
13959
int mg_sl_if_create_conn(struct mg_connection *nc) {
13960
  (void) nc;
13961
  return 1;
13962
}
13963

    
13964
void mg_sl_if_destroy_conn(struct mg_connection *nc) {
13965
  if (nc->sock == INVALID_SOCKET) return;
13966
  /* For UDP, only close outgoing sockets or listeners. */
13967
  if (!(nc->flags & MG_F_UDP) || nc->listener == NULL) {
13968
    sl_Close(nc->sock);
13969
  }
13970
  nc->sock = INVALID_SOCKET;
13971
}
13972

    
13973
static int mg_accept_conn(struct mg_connection *lc) {
13974
  struct mg_connection *nc;
13975
  union socket_address sa;
13976
  socklen_t sa_len = sizeof(sa);
13977
  sock_t sock = sl_Accept(lc->sock, &sa.sa, &sa_len);
13978
  if (sock < 0) {
13979
    DBG(("%p: failed to accept: %d", lc, sock));
13980
    return 0;
13981
  }
13982
  nc = mg_if_accept_new_conn(lc);
13983
  if (nc == NULL) {
13984
    sl_Close(sock);
13985
    return 0;
13986
  }
13987
  DBG(("%p conn from %s:%d", nc, inet_ntoa(sa.sin.sin_addr),
13988
       ntohs(sa.sin.sin_port)));
13989
  mg_sock_set(nc, sock);
13990
  if (nc->flags & MG_F_SSL) nc->flags |= MG_F_SSL_HANDSHAKE_DONE;
13991
  mg_if_accept_tcp_cb(nc, &sa, sa_len);
13992
  return 1;
13993
}
13994

    
13995
/* 'sa' must be an initialized address to bind to */
13996
static sock_t mg_open_listening_socket(struct mg_connection *nc,
13997
                                       union socket_address *sa, int type,
13998
                                       int proto) {
13999
  int r;
14000
  socklen_t sa_len =
14001
      (sa->sa.sa_family == AF_INET) ? sizeof(sa->sin) : sizeof(sa->sin6);
14002
  sock_t sock = sl_Socket(sa->sa.sa_family, type, proto);
14003
  if (sock < 0) return sock;
14004
  if ((r = sl_Bind(sock, &sa->sa, sa_len)) < 0) goto clean;
14005
  if (type != SOCK_DGRAM) {
14006
#if MG_ENABLE_SSL
14007
    if ((r = sl_set_ssl_opts(sock, nc)) < 0) goto clean;
14008
#endif
14009
    if ((r = sl_Listen(sock, SOMAXCONN)) < 0) goto clean;
14010
  }
14011
  mg_set_non_blocking_mode(sock);
14012
clean:
14013
  if (r < 0) {
14014
    sl_Close(sock);
14015
    sock = r;
14016
  }
14017
  return sock;
14018
}
14019

    
14020
static void mg_write_to_socket(struct mg_connection *nc) {
14021
  struct mbuf *io = &nc->send_mbuf;
14022
  int n = 0;
14023

    
14024
  if (nc->flags & MG_F_UDP) {
14025
    n = sl_SendTo(nc->sock, io->buf, io->len, 0, &nc->sa.sa,
14026
                  sizeof(nc->sa.sin));
14027
    DBG(("%p %d %d %d %s:%hu", nc, nc->sock, n, errno,
14028
         inet_ntoa(nc->sa.sin.sin_addr), ntohs(nc->sa.sin.sin_port)));
14029
  } else {
14030
    n = (int) sl_Send(nc->sock, io->buf, io->len, 0);
14031
    DBG(("%p %d bytes -> %d", nc, n, nc->sock));
14032
  }
14033

    
14034
  if (n > 0) {
14035
    mg_if_sent_cb(nc, n);
14036
  } else if (n < 0 && mg_is_error(n)) {
14037
    /* Something went wrong, drop the connection. */
14038
    nc->flags |= MG_F_CLOSE_IMMEDIATELY;
14039
  }
14040
}
14041

    
14042
MG_INTERNAL size_t recv_avail_size(struct mg_connection *conn, size_t max) {
14043
  size_t avail;
14044
  if (conn->recv_mbuf_limit < conn->recv_mbuf.len) return 0;
14045
  avail = conn->recv_mbuf_limit - conn->recv_mbuf.len;
14046
  return avail > max ? max : avail;
14047
}
14048

    
14049
static void mg_handle_tcp_read(struct mg_connection *conn) {
14050
  int n = 0;
14051
  char *buf = (char *) MG_MALLOC(MG_TCP_RECV_BUFFER_SIZE);
14052

    
14053
  if (buf == NULL) {
14054
    DBG(("OOM"));
14055
    return;
14056
  }
14057

    
14058
  n = (int) sl_Recv(conn->sock, buf,
14059
                    recv_avail_size(conn, MG_TCP_RECV_BUFFER_SIZE), 0);
14060
  DBG(("%p %d bytes <- %d", conn, n, conn->sock));
14061
  if (n > 0) {
14062
    mg_if_recv_tcp_cb(conn, buf, n, 1 /* own */);
14063
  } else {
14064
    MG_FREE(buf);
14065
  }
14066
  if (n == 0) {
14067
    /* Orderly shutdown of the socket, try flushing output. */
14068
    conn->flags |= MG_F_SEND_AND_CLOSE;
14069
  } else if (mg_is_error(n)) {
14070
    conn->flags |= MG_F_CLOSE_IMMEDIATELY;
14071
  }
14072
}
14073

    
14074
static void mg_handle_udp_read(struct mg_connection *nc) {
14075
  char *buf = (char *) MG_MALLOC(MG_UDP_RECV_BUFFER_SIZE);
14076
  if (buf == NULL) return;
14077
  union socket_address sa;
14078
  socklen_t sa_len = sizeof(sa);
14079
  int n = sl_RecvFrom(nc->sock, buf, MG_UDP_RECV_BUFFER_SIZE, 0,
14080
                      (SlSockAddr_t *) &sa, &sa_len);
14081
  DBG(("%p %d bytes from %s:%d", nc, n, inet_ntoa(nc->sa.sin.sin_addr),
14082
       ntohs(nc->sa.sin.sin_port)));
14083
  if (n > 0) {
14084
    mg_if_recv_udp_cb(nc, buf, n, &sa, sa_len);
14085
  } else {
14086
    MG_FREE(buf);
14087
  }
14088
}
14089

    
14090
#define _MG_F_FD_CAN_READ 1
14091
#define _MG_F_FD_CAN_WRITE 1 << 1
14092
#define _MG_F_FD_ERROR 1 << 2
14093

    
14094
void mg_mgr_handle_conn(struct mg_connection *nc, int fd_flags, double now) {
14095
  DBG(("%p fd=%d fd_flags=%d nc_flags=%lu rmbl=%d smbl=%d", nc, nc->sock,
14096
       fd_flags, nc->flags, (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len));
14097

    
14098
  if (nc->flags & MG_F_CONNECTING) {
14099
    if (nc->flags & MG_F_UDP || nc->err != SL_ERROR_BSD_EALREADY) {
14100
      mg_if_connect_cb(nc, nc->err);
14101
    } else {
14102
      /* In SimpleLink, to get status of non-blocking connect() we need to wait
14103
       * until socket is writable and repeat the call to sl_Connect again,
14104
       * which will now return the real status. */
14105
      if (fd_flags & _MG_F_FD_CAN_WRITE) {
14106
        nc->err = sl_Connect(nc->sock, &nc->sa.sa, sizeof(nc->sa.sin));
14107
        DBG(("%p conn res=%d", nc, nc->err));
14108
        if (nc->err == SL_ERROR_BSD_ESECSNOVERIFY ||
14109
            /* TODO(rojer): Provide API to set the date for verification. */
14110
            nc->err == SL_ERROR_BSD_ESECDATEERROR
14111
#if SL_MAJOR_VERSION_NUM >= 2
14112
            /* Per SWRU455, this error does not mean verification failed,
14113
             * it only means that the cert used is not present in the trusted
14114
             * root CA catalog. Which is perfectly fine. */
14115
            ||
14116
            nc->err == SL_ERROR_BSD_ESECUNKNOWNROOTCA
14117
#endif
14118
            ) {
14119
          nc->err = 0;
14120
        }
14121
        if (nc->flags & MG_F_SSL && nc->err == 0) {
14122
          nc->flags |= MG_F_SSL_HANDSHAKE_DONE;
14123
        }
14124
        mg_if_connect_cb(nc, nc->err);
14125
      }
14126
    }
14127
    /* Ignore read/write in further processing, we've handled it. */
14128
    fd_flags &= ~(_MG_F_FD_CAN_READ | _MG_F_FD_CAN_WRITE);
14129
  }
14130

    
14131
  if (fd_flags & _MG_F_FD_CAN_READ) {
14132
    if (nc->flags & MG_F_UDP) {
14133
      mg_handle_udp_read(nc);
14134
    } else {
14135
      if (nc->flags & MG_F_LISTENING) {
14136
        mg_accept_conn(nc);
14137
      } else {
14138
        mg_handle_tcp_read(nc);
14139
      }
14140
    }
14141
  }
14142

    
14143
  if (!(nc->flags & MG_F_CLOSE_IMMEDIATELY)) {
14144
    if ((fd_flags & _MG_F_FD_CAN_WRITE) && nc->send_mbuf.len > 0) {
14145
      mg_write_to_socket(nc);
14146
    }
14147

    
14148
    if (!(fd_flags & (_MG_F_FD_CAN_READ | _MG_F_FD_CAN_WRITE))) {
14149
      mg_if_poll(nc, now);
14150
    }
14151
    mg_if_timer(nc, now);
14152
  }
14153

    
14154
  DBG(("%p after fd=%d nc_flags=%lu rmbl=%d smbl=%d", nc, nc->sock, nc->flags,
14155
       (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len));
14156
}
14157

    
14158
/* Associate a socket to a connection. */
14159
void mg_sl_if_sock_set(struct mg_connection *nc, sock_t sock) {
14160
  mg_set_non_blocking_mode(sock);
14161
  nc->sock = sock;
14162
  DBG(("%p %d", nc, sock));
14163
}
14164

    
14165
void mg_sl_if_init(struct mg_iface *iface) {
14166
  (void) iface;
14167
  DBG(("%p using sl_Select()", iface->mgr));
14168
}
14169

    
14170
void mg_sl_if_free(struct mg_iface *iface) {
14171
  (void) iface;
14172
}
14173

    
14174
void mg_sl_if_add_conn(struct mg_connection *nc) {
14175
  (void) nc;
14176
}
14177

    
14178
void mg_sl_if_remove_conn(struct mg_connection *nc) {
14179
  (void) nc;
14180
}
14181

    
14182
time_t mg_sl_if_poll(struct mg_iface *iface, int timeout_ms) {
14183
  struct mg_mgr *mgr = iface->mgr;
14184
  double now = mg_time();
14185
  double min_timer;
14186
  struct mg_connection *nc, *tmp;
14187
  struct SlTimeval_t tv;
14188
  SlFdSet_t read_set, write_set, err_set;
14189
  sock_t max_fd = INVALID_SOCKET;
14190
  int num_fds, num_ev = 0, num_timers = 0;
14191

    
14192
  SL_SOCKET_FD_ZERO(&read_set);
14193
  SL_SOCKET_FD_ZERO(&write_set);
14194
  SL_SOCKET_FD_ZERO(&err_set);
14195

    
14196
  /*
14197
   * Note: it is ok to have connections with sock == INVALID_SOCKET in the list,
14198
   * e.g. timer-only "connections".
14199
   */
14200
  min_timer = 0;
14201
  for (nc = mgr->active_connections, num_fds = 0; nc != NULL; nc = tmp) {
14202
    tmp = nc->next;
14203

    
14204
    if (nc->sock != INVALID_SOCKET) {
14205
      num_fds++;
14206

    
14207
      if (!(nc->flags & MG_F_WANT_WRITE) &&
14208
          nc->recv_mbuf.len < nc->recv_mbuf_limit &&
14209
          (!(nc->flags & MG_F_UDP) || nc->listener == NULL)) {
14210
        SL_SOCKET_FD_SET(nc->sock, &read_set);
14211
        if (max_fd == INVALID_SOCKET || nc->sock > max_fd) max_fd = nc->sock;
14212
      }
14213

    
14214
      if (((nc->flags & MG_F_CONNECTING) && !(nc->flags & MG_F_WANT_READ)) ||
14215
          (nc->send_mbuf.len > 0 && !(nc->flags & MG_F_CONNECTING))) {
14216
        SL_SOCKET_FD_SET(nc->sock, &write_set);
14217
        SL_SOCKET_FD_SET(nc->sock, &err_set);
14218
        if (max_fd == INVALID_SOCKET || nc->sock > max_fd) max_fd = nc->sock;
14219
      }
14220
    }
14221

    
14222
    if (nc->ev_timer_time > 0) {
14223
      if (num_timers == 0 || nc->ev_timer_time < min_timer) {
14224
        min_timer = nc->ev_timer_time;
14225
      }
14226
      num_timers++;
14227
    }
14228
  }
14229

    
14230
  /*
14231
   * If there is a timer to be fired earlier than the requested timeout,
14232
   * adjust the timeout.
14233
   */
14234
  if (num_timers > 0) {
14235
    double timer_timeout_ms = (min_timer - mg_time()) * 1000 + 1 /* rounding */;
14236
    if (timer_timeout_ms < timeout_ms) {
14237
      timeout_ms = timer_timeout_ms;
14238
    }
14239
  }
14240
  if (timeout_ms < 0) timeout_ms = 0;
14241

    
14242
  tv.tv_sec = timeout_ms / 1000;
14243
  tv.tv_usec = (timeout_ms % 1000) * 1000;
14244

    
14245
  if (num_fds > 0) {
14246
    num_ev = sl_Select((int) max_fd + 1, &read_set, &write_set, &err_set, &tv);
14247
  }
14248

    
14249
  now = mg_time();
14250
  DBG(("sl_Select @ %ld num_ev=%d of %d, timeout=%d", (long) now, num_ev,
14251
       num_fds, timeout_ms));
14252

    
14253
  for (nc = mgr->active_connections; nc != NULL; nc = tmp) {
14254
    int fd_flags = 0;
14255
    if (nc->sock != INVALID_SOCKET) {
14256
      if (num_ev > 0) {
14257
        fd_flags =
14258
            (SL_SOCKET_FD_ISSET(nc->sock, &read_set) &&
14259
                     (!(nc->flags & MG_F_UDP) || nc->listener == NULL)
14260
                 ? _MG_F_FD_CAN_READ
14261
                 : 0) |
14262
            (SL_SOCKET_FD_ISSET(nc->sock, &write_set) ? _MG_F_FD_CAN_WRITE
14263
                                                      : 0) |
14264
            (SL_SOCKET_FD_ISSET(nc->sock, &err_set) ? _MG_F_FD_ERROR : 0);
14265
      }
14266
      /* SimpleLink does not report UDP sockets as writable. */
14267
      if (nc->flags & MG_F_UDP && nc->send_mbuf.len > 0) {
14268
        fd_flags |= _MG_F_FD_CAN_WRITE;
14269
      }
14270
    }
14271
    tmp = nc->next;
14272
    mg_mgr_handle_conn(nc, fd_flags, now);
14273
  }
14274

    
14275
  for (nc = mgr->active_connections; nc != NULL; nc = tmp) {
14276
    tmp = nc->next;
14277
    if ((nc->flags & MG_F_CLOSE_IMMEDIATELY) ||
14278
        (nc->send_mbuf.len == 0 && (nc->flags & MG_F_SEND_AND_CLOSE))) {
14279
      mg_close_conn(nc);
14280
    }
14281
  }
14282

    
14283
  return now;
14284
}
14285

    
14286
void mg_sl_if_get_conn_addr(struct mg_connection *nc, int remote,
14287
                            union socket_address *sa) {
14288
  /* SimpleLink does not provide a way to get socket's peer address after
14289
   * accept or connect. Address should have been preserved in the connection,
14290
   * so we do our best here by using it. */
14291
  if (remote) memcpy(sa, &nc->sa, sizeof(*sa));
14292
}
14293

    
14294
void sl_restart_cb(struct mg_mgr *mgr) {
14295
  /*
14296
   * SimpleLink has been restarted, meaning all sockets have been invalidated.
14297
   * We try our best - we'll restart the listeners, but for outgoing
14298
   * connections we have no option but to terminate.
14299
   */
14300
  struct mg_connection *nc;
14301
  for (nc = mg_next(mgr, NULL); nc != NULL; nc = mg_next(mgr, nc)) {
14302
    if (nc->sock == INVALID_SOCKET) continue; /* Could be a timer */
14303
    if (nc->flags & MG_F_LISTENING) {
14304
      DBG(("restarting %p %s:%d", nc, inet_ntoa(nc->sa.sin.sin_addr),
14305
           ntohs(nc->sa.sin.sin_port)));
14306
      int res = (nc->flags & MG_F_UDP ? mg_sl_if_listen_udp(nc, &nc->sa)
14307
                                      : mg_sl_if_listen_tcp(nc, &nc->sa));
14308
      if (res == 0) continue;
14309
      /* Well, we tried and failed. Fall through to closing. */
14310
    }
14311
    nc->sock = INVALID_SOCKET;
14312
    DBG(("terminating %p %s:%d", nc, inet_ntoa(nc->sa.sin.sin_addr),
14313
         ntohs(nc->sa.sin.sin_port)));
14314
    /* TODO(rojer): Outgoing UDP? */
14315
    nc->flags |= MG_F_CLOSE_IMMEDIATELY;
14316
  }
14317
}
14318

    
14319
/* clang-format off */
14320
#define MG_SL_IFACE_VTABLE                                              \
14321
  {                                                                     \
14322
    mg_sl_if_init,                                                      \
14323
    mg_sl_if_free,                                                      \
14324
    mg_sl_if_add_conn,                                                  \
14325
    mg_sl_if_remove_conn,                                               \
14326
    mg_sl_if_poll,                                                      \
14327
    mg_sl_if_listen_tcp,                                                \
14328
    mg_sl_if_listen_udp,                                                \
14329
    mg_sl_if_connect_tcp,                                               \
14330
    mg_sl_if_connect_udp,                                               \
14331
    mg_sl_if_tcp_send,                                                  \
14332
    mg_sl_if_udp_send,                                                  \
14333
    mg_sl_if_recved,                                                    \
14334
    mg_sl_if_create_conn,                                               \
14335
    mg_sl_if_destroy_conn,                                              \
14336
    mg_sl_if_sock_set,                                                  \
14337
    mg_sl_if_get_conn_addr,                                             \
14338
  }
14339
/* clang-format on */
14340

    
14341
const struct mg_iface_vtable mg_simplelink_iface_vtable = MG_SL_IFACE_VTABLE;
14342
#if MG_NET_IF == MG_NET_IF_SIMPLELINK
14343
const struct mg_iface_vtable mg_default_iface_vtable = MG_SL_IFACE_VTABLE;
14344
#endif
14345

    
14346
#endif /* MG_ENABLE_NET_IF_SIMPLELINK */
14347
#ifdef MG_MODULE_LINES
14348
#line 1 "common/platforms/simplelink/sl_ssl_if.c"
14349
#endif
14350
/*
14351
 * Copyright (c) 2014-2016 Cesanta Software Limited
14352
 * All rights reserved
14353
 */
14354

    
14355
#if MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_SIMPLELINK
14356

    
14357
/* Amalgamated: #include "common/mg_mem.h" */
14358

    
14359
#ifndef MG_SSL_IF_SIMPLELINK_SLFS_PREFIX
14360
#define MG_SSL_IF_SIMPLELINK_SLFS_PREFIX "SL:"
14361
#endif
14362

    
14363
#define MG_SSL_IF_SIMPLELINK_SLFS_PREFIX_LEN \
14364
  (sizeof(MG_SSL_IF_SIMPLELINK_SLFS_PREFIX) - 1)
14365

    
14366
struct mg_ssl_if_ctx {
14367
  char *ssl_cert;
14368
  char *ssl_key;
14369
  char *ssl_ca_cert;
14370
  char *ssl_server_name;
14371
};
14372

    
14373
void mg_ssl_if_init() {
14374
}
14375

    
14376
enum mg_ssl_if_result mg_ssl_if_conn_init(
14377
    struct mg_connection *nc, const struct mg_ssl_if_conn_params *params,
14378
    const char **err_msg) {
14379
  struct mg_ssl_if_ctx *ctx =
14380
      (struct mg_ssl_if_ctx *) MG_CALLOC(1, sizeof(*ctx));
14381
  if (ctx == NULL) {
14382
    MG_SET_PTRPTR(err_msg, "Out of memory");
14383
    return MG_SSL_ERROR;
14384
  }
14385
  nc->ssl_if_data = ctx;
14386

    
14387
  if (params->cert != NULL || params->key != NULL) {
14388
    if (params->cert != NULL && params->key != NULL) {
14389
      ctx->ssl_cert = strdup(params->cert);
14390
      ctx->ssl_key = strdup(params->key);
14391
    } else {
14392
      MG_SET_PTRPTR(err_msg, "Both cert and key are required.");
14393
      return MG_SSL_ERROR;
14394
    }
14395
  }
14396
  if (params->ca_cert != NULL && strcmp(params->ca_cert, "*") != 0) {
14397
    ctx->ssl_ca_cert = strdup(params->ca_cert);
14398
  }
14399
  /* TODO(rojer): cipher_suites. */
14400
  if (params->server_name != NULL) {
14401
    ctx->ssl_server_name = strdup(params->server_name);
14402
  }
14403
  return MG_SSL_OK;
14404
}
14405

    
14406
void mg_ssl_if_conn_close_notify(struct mg_connection *nc) {
14407
  /* Nothing to do */
14408
  (void) nc;
14409
}
14410

    
14411
void mg_ssl_if_conn_free(struct mg_connection *nc) {
14412
  struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
14413
  if (ctx == NULL) return;
14414
  nc->ssl_if_data = NULL;
14415
  MG_FREE(ctx->ssl_cert);
14416
  MG_FREE(ctx->ssl_key);
14417
  MG_FREE(ctx->ssl_ca_cert);
14418
  MG_FREE(ctx->ssl_server_name);
14419
  memset(ctx, 0, sizeof(*ctx));
14420
  MG_FREE(ctx);
14421
}
14422

    
14423
bool pem_to_der(const char *pem_file, const char *der_file) {
14424
  bool ret = false;
14425
  FILE *pf = NULL, *df = NULL;
14426
  bool writing = false;
14427
  pf = fopen(pem_file, "r");
14428
  if (pf == NULL) goto clean;
14429
  remove(der_file);
14430
  fs_slfs_set_new_file_size(der_file + MG_SSL_IF_SIMPLELINK_SLFS_PREFIX_LEN,
14431
                            2048);
14432
  df = fopen(der_file, "w");
14433
  if (df == NULL) goto clean;
14434
  while (1) {
14435
    char pem_buf[70];
14436
    char der_buf[48];
14437
    if (!fgets(pem_buf, sizeof(pem_buf), pf)) break;
14438
    if (writing) {
14439
      if (strstr(pem_buf, "-----END ") != NULL) {
14440
        ret = true;
14441
        break;
14442
      }
14443
      int l = 0;
14444
      while (!isspace((unsigned int) pem_buf[l])) l++;
14445
      int der_len = 0;
14446
      cs_base64_decode((const unsigned char *) pem_buf, sizeof(pem_buf),
14447
                       der_buf, &der_len);
14448
      if (der_len <= 0) break;
14449
      if (fwrite(der_buf, 1, der_len, df) != der_len) break;
14450
    } else if (strstr(pem_buf, "-----BEGIN ") != NULL) {
14451
      writing = true;
14452
    }
14453
  }
14454

    
14455
clean:
14456
  if (pf != NULL) fclose(pf);
14457
  if (df != NULL) {
14458
    fclose(df);
14459
    if (!ret) remove(der_file);
14460
  }
14461
  return ret;
14462
}
14463

    
14464
#if MG_ENABLE_FILESYSTEM && defined(MG_FS_SLFS)
14465
/* If the file's extension is .pem, convert it to DER format and put on SLFS. */
14466
static char *sl_pem2der(const char *pem_file) {
14467
  const char *pem_ext = strstr(pem_file, ".pem");
14468
  if (pem_ext == NULL || *(pem_ext + 4) != '\0') {
14469
    return strdup(pem_file);
14470
  }
14471
  char *der_file = NULL;
14472
  /* DER file must be located on SLFS, add prefix. */
14473
  int l = mg_asprintf(&der_file, 0, MG_SSL_IF_SIMPLELINK_SLFS_PREFIX "%.*s.der",
14474
                      (int) (pem_ext - pem_file), pem_file);
14475
  if (der_file == NULL) return NULL;
14476
  bool result = false;
14477
  cs_stat_t st;
14478
  if (mg_stat(der_file, &st) != 0) {
14479
    result = pem_to_der(pem_file, der_file);
14480
    LOG(LL_DEBUG, ("%s -> %s = %d", pem_file, der_file, result));
14481
  } else {
14482
    /* File exists, assume it's already been converted. */
14483
    result = true;
14484
  }
14485
  if (result) {
14486
    /* Strip the SL: prefix we added since NWP does not expect it. */
14487
    memmove(der_file, der_file + MG_SSL_IF_SIMPLELINK_SLFS_PREFIX_LEN,
14488
            l - 2 /* including \0 */);
14489
  } else {
14490
    MG_FREE(der_file);
14491
    der_file = NULL;
14492
  }
14493
  return der_file;
14494
}
14495
#else
14496
static char *sl_pem2der(const char *pem_file) {
14497
  return strdup(pem_file);
14498
}
14499
#endif
14500

    
14501
int sl_set_ssl_opts(int sock, struct mg_connection *nc) {
14502
  int err;
14503
  const struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
14504
  DBG(("%p ssl ctx: %p", nc, ctx));
14505

    
14506
  if (ctx != NULL) {
14507
    DBG(("%p %s,%s,%s,%s", nc, (ctx->ssl_cert ? ctx->ssl_cert : "-"),
14508
         (ctx->ssl_key ? ctx->ssl_cert : "-"),
14509
         (ctx->ssl_ca_cert ? ctx->ssl_ca_cert : "-"),
14510
         (ctx->ssl_server_name ? ctx->ssl_server_name : "-")));
14511
    if (ctx->ssl_cert != NULL && ctx->ssl_key != NULL) {
14512
      char *ssl_cert = sl_pem2der(ctx->ssl_cert);
14513
      char *ssl_key = sl_pem2der(ctx->ssl_key);
14514
      if (ssl_cert != NULL && ssl_key != NULL) {
14515
        err = sl_SetSockOpt(sock, SL_SOL_SOCKET,
14516
                            SL_SO_SECURE_FILES_CERTIFICATE_FILE_NAME, ssl_cert,
14517
                            strlen(ssl_cert));
14518
        LOG(LL_INFO, ("CERTIFICATE_FILE_NAME %s -> %d", ssl_cert, err));
14519
        err = sl_SetSockOpt(sock, SL_SOL_SOCKET,
14520
                            SL_SO_SECURE_FILES_PRIVATE_KEY_FILE_NAME, ssl_key,
14521
                            strlen(ssl_key));
14522
        LOG(LL_INFO, ("PRIVATE_KEY_FILE_NAME %s -> %d", ssl_key, err));
14523
      } else {
14524
        err = -1;
14525
      }
14526
      MG_FREE(ssl_cert);
14527
      MG_FREE(ssl_key);
14528
      if (err != 0) return err;
14529
    }
14530
    if (ctx->ssl_ca_cert != NULL) {
14531
      if (ctx->ssl_ca_cert[0] != '\0') {
14532
        char *ssl_ca_cert = sl_pem2der(ctx->ssl_ca_cert);
14533
        if (ssl_ca_cert != NULL) {
14534
          err = sl_SetSockOpt(sock, SL_SOL_SOCKET,
14535
                              SL_SO_SECURE_FILES_CA_FILE_NAME, ssl_ca_cert,
14536
                              strlen(ssl_ca_cert));
14537
          LOG(LL_INFO, ("CA_FILE_NAME %s -> %d", ssl_ca_cert, err));
14538
        } else {
14539
          err = -1;
14540
        }
14541
        MG_FREE(ssl_ca_cert);
14542
        if (err != 0) return err;
14543
      }
14544
    }
14545
    if (ctx->ssl_server_name != NULL) {
14546
      err = sl_SetSockOpt(sock, SL_SOL_SOCKET,
14547
                          SL_SO_SECURE_DOMAIN_NAME_VERIFICATION,
14548
                          ctx->ssl_server_name, strlen(ctx->ssl_server_name));
14549
      DBG(("DOMAIN_NAME_VERIFICATION %s -> %d", ctx->ssl_server_name, err));
14550
      /* Domain name verificationw as added in a NWP service pack, older
14551
       * versions return SL_ERROR_BSD_ENOPROTOOPT. There isn't much we can do
14552
       * about it,
14553
       * so we ignore the error. */
14554
      if (err != 0 && err != SL_ERROR_BSD_ENOPROTOOPT) return err;
14555
    }
14556
  }
14557
  return 0;
14558
}
14559

    
14560
#endif /* MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_SIMPLELINK */
14561
#ifdef MG_MODULE_LINES
14562
#line 1 "common/platforms/lwip/mg_lwip_net_if.h"
14563
#endif
14564
/*
14565
 * Copyright (c) 2014-2016 Cesanta Software Limited
14566
 * All rights reserved
14567
 */
14568

    
14569
#ifndef CS_COMMON_PLATFORMS_LWIP_MG_NET_IF_LWIP_H_
14570
#define CS_COMMON_PLATFORMS_LWIP_MG_NET_IF_LWIP_H_
14571

    
14572
#ifndef MG_ENABLE_NET_IF_LWIP_LOW_LEVEL
14573
#define MG_ENABLE_NET_IF_LWIP_LOW_LEVEL MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL
14574
#endif
14575

    
14576
#if MG_ENABLE_NET_IF_LWIP_LOW_LEVEL
14577

    
14578
#include <stdint.h>
14579

    
14580
extern const struct mg_iface_vtable mg_lwip_iface_vtable;
14581

    
14582
struct mg_lwip_conn_state {
14583
  struct mg_connection *nc;
14584
  struct mg_connection *lc;
14585
  union {
14586
    struct tcp_pcb *tcp;
14587
    struct udp_pcb *udp;
14588
  } pcb;
14589
  err_t err;
14590
  size_t num_sent; /* Number of acknowledged bytes to be reported to the core */
14591
  struct pbuf *rx_chain; /* Chain of incoming data segments. */
14592
  size_t rx_offset; /* Offset within the first pbuf (if partially consumed) */
14593
  /* Last SSL write size, for retries. */
14594
  int last_ssl_write_size;
14595
  /* Whether MG_SIG_RECV is already pending for this connection */
14596
  int recv_pending : 1;
14597
  /* Whether the connection is about to close, just `rx_chain` needs to drain */
14598
  int draining_rx_chain : 1;
14599
};
14600

    
14601
enum mg_sig_type {
14602
  MG_SIG_CONNECT_RESULT = 1,
14603
  MG_SIG_RECV = 2,
14604
  MG_SIG_CLOSE_CONN = 3,
14605
  MG_SIG_TOMBSTONE = 4,
14606
  MG_SIG_ACCEPT = 5,
14607
};
14608

    
14609
void mg_lwip_post_signal(enum mg_sig_type sig, struct mg_connection *nc);
14610

    
14611
/* To be implemented by the platform. */
14612
void mg_lwip_mgr_schedule_poll(struct mg_mgr *mgr);
14613

    
14614
#endif /* MG_ENABLE_NET_IF_LWIP_LOW_LEVEL */
14615

    
14616
#endif /* CS_COMMON_PLATFORMS_LWIP_MG_NET_IF_LWIP_H_ */
14617
#ifdef MG_MODULE_LINES
14618
#line 1 "common/platforms/lwip/mg_lwip_net_if.c"
14619
#endif
14620
/*
14621
 * Copyright (c) 2014-2016 Cesanta Software Limited
14622
 * All rights reserved
14623
 */
14624

    
14625
#if MG_ENABLE_NET_IF_LWIP_LOW_LEVEL
14626

    
14627
/* Amalgamated: #include "common/mg_mem.h" */
14628

    
14629
#include <lwip/init.h>
14630
#include <lwip/pbuf.h>
14631
#include <lwip/tcp.h>
14632
#include <lwip/tcpip.h>
14633
#if ((LWIP_VERSION_MAJOR << 8) | LWIP_VERSION_MINOR) >= 0x0105
14634
#include <lwip/priv/tcp_priv.h> /* For tcp_seg */
14635
#else
14636
#include <lwip/tcp_impl.h>
14637
#endif
14638
#include <lwip/udp.h>
14639

    
14640
/* Amalgamated: #include "common/cs_dbg.h" */
14641

    
14642
/*
14643
 * Newest versions of LWIP have ip_2_ip4, older have ipX_2_ip,
14644
 * even older have nothing.
14645
 */
14646
#ifndef ip_2_ip4
14647
#ifdef ipX_2_ip
14648
#define ip_2_ip4(addr) ipX_2_ip(addr)
14649
#else
14650
#define ip_2_ip4(addr) (addr)
14651
#endif
14652
#endif
14653

    
14654
/*
14655
 * Depending on whether Mongoose is compiled with ipv6 support, use right
14656
 * lwip functions
14657
 */
14658
#if MG_ENABLE_IPV6
14659
#define TCP_NEW tcp_new_ip6
14660
#define TCP_BIND tcp_bind_ip6
14661
#define UDP_BIND udp_bind_ip6
14662
#define IPADDR_NTOA(x) ip6addr_ntoa((const ip6_addr_t *)(x))
14663
#define SET_ADDR(dst, src)                               \
14664
  memcpy((dst)->sin6.sin6_addr.s6_addr, (src)->ip6.addr, \
14665
         sizeof((dst)->sin6.sin6_addr.s6_addr))
14666
#else
14667
#define TCP_NEW tcp_new
14668
#define TCP_BIND tcp_bind
14669
#define UDP_BIND udp_bind
14670
#define IPADDR_NTOA ipaddr_ntoa
14671
#define SET_ADDR(dst, src) (dst)->sin.sin_addr.s_addr = ip_2_ip4(src)->addr
14672
#endif
14673

    
14674
#if NO_SYS
14675
#define tcpip_callback(fn, arg) (fn)(arg)
14676
typedef void (*tcpip_callback_fn)(void *arg);
14677
#endif
14678

    
14679
void mg_lwip_ssl_do_hs(struct mg_connection *nc);
14680
void mg_lwip_ssl_send(struct mg_connection *nc);
14681
void mg_lwip_ssl_recv(struct mg_connection *nc);
14682

    
14683
void mg_lwip_if_init(struct mg_iface *iface);
14684
void mg_lwip_if_free(struct mg_iface *iface);
14685
void mg_lwip_if_add_conn(struct mg_connection *nc);
14686
void mg_lwip_if_remove_conn(struct mg_connection *nc);
14687
time_t mg_lwip_if_poll(struct mg_iface *iface, int timeout_ms);
14688

    
14689
#if defined(RTOS_SDK) || defined(ESP_PLATFORM)
14690
extern void mgos_lock();
14691
extern void mgos_unlock();
14692
#else
14693
#define mgos_lock()
14694
#define mgos_unlock()
14695
#endif
14696

    
14697
static void mg_lwip_recv_common(struct mg_connection *nc, struct pbuf *p);
14698

    
14699
#if LWIP_TCP_KEEPALIVE
14700
void mg_lwip_set_keepalive_params(struct mg_connection *nc, int idle,
14701
                                  int interval, int count) {
14702
  if (nc->sock == INVALID_SOCKET || nc->flags & MG_F_UDP) {
14703
    return;
14704
  }
14705
  struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
14706
  struct tcp_pcb *tpcb = cs->pcb.tcp;
14707
  if (idle > 0 && interval > 0 && count > 0) {
14708
    tpcb->keep_idle = idle * 1000;
14709
    tpcb->keep_intvl = interval * 1000;
14710
    tpcb->keep_cnt = count;
14711
    tpcb->so_options |= SOF_KEEPALIVE;
14712
  } else {
14713
    tpcb->so_options &= ~SOF_KEEPALIVE;
14714
  }
14715
}
14716
#elif !defined(MG_NO_LWIP_TCP_KEEPALIVE)
14717
#warning LWIP TCP keepalive is disabled. Please consider enabling it.
14718
#endif /* LWIP_TCP_KEEPALIVE */
14719

    
14720
static err_t mg_lwip_tcp_conn_cb(void *arg, struct tcp_pcb *tpcb, err_t err) {
14721
  struct mg_connection *nc = (struct mg_connection *) arg;
14722
  DBG(("%p connect to %s:%u = %d", nc, IPADDR_NTOA(ipX_2_ip(&tpcb->remote_ip)),
14723
       tpcb->remote_port, err));
14724
  if (nc == NULL) {
14725
    tcp_abort(tpcb);
14726
    return ERR_ARG;
14727
  }
14728
  struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
14729
  cs->err = err;
14730
#if LWIP_TCP_KEEPALIVE
14731
  if (err == 0) mg_lwip_set_keepalive_params(nc, 60, 10, 6);
14732
#endif
14733
  mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc);
14734
  return ERR_OK;
14735
}
14736

    
14737
static void mg_lwip_tcp_error_cb(void *arg, err_t err) {
14738
  struct mg_connection *nc = (struct mg_connection *) arg;
14739
  DBG(("%p conn error %d", nc, err));
14740
  if (nc == NULL) return;
14741
  struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
14742
  cs->pcb.tcp = NULL; /* Has already been deallocated */
14743
  if (nc->flags & MG_F_CONNECTING) {
14744
    cs->err = err;
14745
    mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc);
14746
  } else {
14747
    mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc);
14748
  }
14749
}
14750

    
14751
static err_t mg_lwip_tcp_recv_cb(void *arg, struct tcp_pcb *tpcb,
14752
                                 struct pbuf *p, err_t err) {
14753
  struct mg_connection *nc = (struct mg_connection *) arg;
14754
  DBG(("%p %p %u %d", nc, tpcb, (p != NULL ? p->tot_len : 0), err));
14755
  if (p == NULL) {
14756
    if (nc != NULL && !(nc->flags & MG_F_CLOSE_IMMEDIATELY)) {
14757
      struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
14758
      if (cs->rx_chain != NULL) {
14759
        /*
14760
         * rx_chain still contains non-consumed data, don't close the
14761
         * connection
14762
         */
14763
        cs->draining_rx_chain = 1;
14764
      } else {
14765
        mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc);
14766
      }
14767
    } else {
14768
      /* Tombstoned connection, do nothing. */
14769
    }
14770
    return ERR_OK;
14771
  } else if (nc == NULL) {
14772
    tcp_abort(tpcb);
14773
    return ERR_ARG;
14774
  }
14775
  struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
14776
  /*
14777
   * If we get a chain of more than one segment at once, we need to bump
14778
   * refcount on the subsequent bufs to make them independent.
14779
   */
14780
  if (p->next != NULL) {
14781
    struct pbuf *q = p->next;
14782
    for (; q != NULL; q = q->next) pbuf_ref(q);
14783
  }
14784
  mgos_lock();
14785
  if (cs->rx_chain == NULL) {
14786
    cs->rx_offset = 0;
14787
  } else if (pbuf_clen(cs->rx_chain) >= 4) {
14788
    /* ESP SDK has a limited pool of 5 pbufs. We must not hog them all or RX
14789
     * will be completely blocked. We already have at least 4 in the chain,
14790
     * this one is, so we have to make a copy and release this one. */
14791
    struct pbuf *np = pbuf_alloc(PBUF_RAW, p->tot_len, PBUF_RAM);
14792
    if (np != NULL) {
14793
      pbuf_copy(np, p);
14794
      pbuf_free(p);
14795
      p = np;
14796
    }
14797
  }
14798
  mgos_unlock();
14799
  mg_lwip_recv_common(nc, p);
14800
  return ERR_OK;
14801
}
14802

    
14803
static void mg_lwip_consume_rx_chain_tcp(struct mg_connection *nc) {
14804
  struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
14805
  if (cs->rx_chain == NULL) return;
14806
#if MG_ENABLE_SSL
14807
  if (nc->flags & MG_F_SSL) {
14808
    if (nc->flags & MG_F_SSL_HANDSHAKE_DONE) {
14809
      mg_lwip_ssl_recv(nc);
14810
    } else {
14811
      mg_lwip_ssl_do_hs(nc);
14812
    }
14813
    return;
14814
  }
14815
#endif
14816
  mgos_lock();
14817
  while (cs->rx_chain != NULL && nc->recv_mbuf.len < nc->recv_mbuf_limit) {
14818
    struct pbuf *seg = cs->rx_chain;
14819

    
14820
    size_t seg_len = (seg->len - cs->rx_offset);
14821
    size_t buf_avail = (nc->recv_mbuf_limit - nc->recv_mbuf.len);
14822
    size_t len = MIN(seg_len, buf_avail);
14823

    
14824
    char *data = (char *) MG_MALLOC(len);
14825
    if (data == NULL) {
14826
      mgos_unlock();
14827
      DBG(("OOM"));
14828
      return;
14829
    }
14830
    pbuf_copy_partial(seg, data, len, cs->rx_offset);
14831
    cs->rx_offset += len;
14832
    if (cs->rx_offset == cs->rx_chain->len) {
14833
      cs->rx_chain = pbuf_dechain(cs->rx_chain);
14834
      pbuf_free(seg);
14835
      cs->rx_offset = 0;
14836
    }
14837
    mgos_unlock();
14838
    mg_if_recv_tcp_cb(nc, data, len, 1 /* own */);
14839
    mgos_lock();
14840
  }
14841
  mgos_unlock();
14842
}
14843

    
14844
static void mg_lwip_handle_recv_tcp(struct mg_connection *nc) {
14845
  mg_lwip_consume_rx_chain_tcp(nc);
14846

    
14847
  if (nc->send_mbuf.len > 0) {
14848
    mg_lwip_mgr_schedule_poll(nc->mgr);
14849
  }
14850
}
14851

    
14852
static err_t mg_lwip_tcp_sent_cb(void *arg, struct tcp_pcb *tpcb,
14853
                                 u16_t num_sent) {
14854
  struct mg_connection *nc = (struct mg_connection *) arg;
14855
  DBG(("%p %p %u %p %p", nc, tpcb, num_sent, tpcb->unsent, tpcb->unacked));
14856
  if (nc == NULL) return ERR_OK;
14857
  if ((nc->flags & MG_F_SEND_AND_CLOSE) && !(nc->flags & MG_F_WANT_WRITE) &&
14858
      nc->send_mbuf.len == 0 && tpcb->unsent == NULL && tpcb->unacked == NULL) {
14859
    mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc);
14860
  }
14861
  return ERR_OK;
14862
}
14863

    
14864
struct mg_lwip_if_connect_tcp_ctx {
14865
  struct mg_connection *nc;
14866
  const union socket_address *sa;
14867
};
14868

    
14869
static void mg_lwip_if_connect_tcp_tcpip(void *arg) {
14870
  struct mg_lwip_if_connect_tcp_ctx *ctx =
14871
      (struct mg_lwip_if_connect_tcp_ctx *) arg;
14872
  struct mg_connection *nc = ctx->nc;
14873
  const union socket_address *sa = ctx->sa;
14874

    
14875
  struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
14876
  struct tcp_pcb *tpcb = TCP_NEW();
14877
  cs->pcb.tcp = tpcb;
14878
  ip_addr_t *ip = (ip_addr_t *) &sa->sin.sin_addr.s_addr;
14879
  u16_t port = ntohs(sa->sin.sin_port);
14880
  tcp_arg(tpcb, nc);
14881
  tcp_err(tpcb, mg_lwip_tcp_error_cb);
14882
  tcp_sent(tpcb, mg_lwip_tcp_sent_cb);
14883
  tcp_recv(tpcb, mg_lwip_tcp_recv_cb);
14884
  cs->err = TCP_BIND(tpcb, IP_ADDR_ANY, 0 /* any port */);
14885
  DBG(("%p tcp_bind = %d", nc, cs->err));
14886
  if (cs->err != ERR_OK) {
14887
    mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc);
14888
    return;
14889
  }
14890
  cs->err = tcp_connect(tpcb, ip, port, mg_lwip_tcp_conn_cb);
14891
  DBG(("%p tcp_connect %p = %d", nc, tpcb, cs->err));
14892
  if (cs->err != ERR_OK) {
14893
    mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc);
14894
    return;
14895
  }
14896
}
14897

    
14898
void mg_lwip_if_connect_tcp(struct mg_connection *nc,
14899
                            const union socket_address *sa) {
14900
  struct mg_lwip_if_connect_tcp_ctx ctx = {.nc = nc, .sa = sa};
14901
  tcpip_callback(mg_lwip_if_connect_tcp_tcpip, &ctx);
14902
}
14903

    
14904
/*
14905
 * Lwip included in the SDKs for nRF5x chips has different type for the
14906
 * callback of `udp_recv()`
14907
 */
14908
#if ((LWIP_VERSION_MAJOR << 8) | LWIP_VERSION_MINOR) >= 0x0105
14909
static void mg_lwip_udp_recv_cb(void *arg, struct udp_pcb *pcb, struct pbuf *p,
14910
                                const ip_addr_t *addr, u16_t port)
14911
#else
14912
static void mg_lwip_udp_recv_cb(void *arg, struct udp_pcb *pcb, struct pbuf *p,
14913
                                ip_addr_t *addr, u16_t port)
14914
#endif
14915
{
14916
  struct mg_connection *nc = (struct mg_connection *) arg;
14917
  DBG(("%p %s:%u %p %u %u", nc, IPADDR_NTOA(addr), port, p, p->ref, p->len));
14918
  /* Put address in a separate pbuf and tack it onto the packet. */
14919
  struct pbuf *sap =
14920
      pbuf_alloc(PBUF_RAW, sizeof(union socket_address), PBUF_RAM);
14921
  if (sap == NULL) {
14922
    pbuf_free(p);
14923
    return;
14924
  }
14925
  union socket_address *sa = (union socket_address *) sap->payload;
14926
#if ((LWIP_VERSION_MAJOR << 8) | LWIP_VERSION_MINOR) >= 0x0105
14927
  sa->sin.sin_addr.s_addr = ip_2_ip4(addr)->addr;
14928
#else
14929
  sa->sin.sin_addr.s_addr = addr->addr;
14930
#endif
14931
  sa->sin.sin_port = htons(port);
14932
  /* Logic in the recv handler requires that there be exactly one data pbuf. */
14933
  p = pbuf_coalesce(p, PBUF_RAW);
14934
  pbuf_chain(sap, p);
14935
  mg_lwip_recv_common(nc, sap);
14936
  (void) pcb;
14937
}
14938

    
14939
static void mg_lwip_recv_common(struct mg_connection *nc, struct pbuf *p) {
14940
  struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
14941
  mgos_lock();
14942
  if (cs->rx_chain == NULL) {
14943
    cs->rx_chain = p;
14944
  } else {
14945
    pbuf_chain(cs->rx_chain, p);
14946
  }
14947
  if (!cs->recv_pending) {
14948
    cs->recv_pending = 1;
14949
    mg_lwip_post_signal(MG_SIG_RECV, nc);
14950
  }
14951
  mgos_unlock();
14952
}
14953

    
14954
static void mg_lwip_handle_recv_udp(struct mg_connection *nc) {
14955
  struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
14956
  /*
14957
   * For UDP, RX chain consists of interleaved address and packet bufs:
14958
   * Address pbuf followed by exactly one data pbuf (recv_cb took care of that).
14959
   */
14960
  while (cs->rx_chain != NULL) {
14961
    struct pbuf *sap = cs->rx_chain;
14962
    struct pbuf *p = sap->next;
14963
    cs->rx_chain = pbuf_dechain(p);
14964
    size_t data_len = p->len;
14965
    char *data = (char *) MG_MALLOC(data_len);
14966
    if (data != NULL) {
14967
      pbuf_copy_partial(p, data, data_len, 0);
14968
      pbuf_free(p);
14969
      mg_if_recv_udp_cb(nc, data, data_len,
14970
                        (union socket_address *) sap->payload, sap->len);
14971
      pbuf_free(sap);
14972
    } else {
14973
      pbuf_free(p);
14974
      pbuf_free(sap);
14975
    }
14976
  }
14977
}
14978

    
14979
static void mg_lwip_if_connect_udp_tcpip(void *arg) {
14980
  struct mg_connection *nc = (struct mg_connection *) arg;
14981
  struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
14982
  struct udp_pcb *upcb = udp_new();
14983
  cs->err = UDP_BIND(upcb, IP_ADDR_ANY, 0 /* any port */);
14984
  DBG(("%p udp_bind %p = %d", nc, upcb, cs->err));
14985
  if (cs->err == ERR_OK) {
14986
    udp_recv(upcb, mg_lwip_udp_recv_cb, nc);
14987
    cs->pcb.udp = upcb;
14988
  } else {
14989
    udp_remove(upcb);
14990
  }
14991
  mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc);
14992
}
14993

    
14994
void mg_lwip_if_connect_udp(struct mg_connection *nc) {
14995
  tcpip_callback(mg_lwip_if_connect_udp_tcpip, nc);
14996
}
14997

    
14998
void mg_lwip_accept_conn(struct mg_connection *nc, struct tcp_pcb *tpcb) {
14999
  union socket_address sa;
15000
  SET_ADDR(&sa, &tpcb->remote_ip);
15001
  sa.sin.sin_port = htons(tpcb->remote_port);
15002
  mg_if_accept_tcp_cb(nc, &sa, sizeof(sa.sin));
15003
}
15004

    
15005
static void tcp_close_tcpip(void *arg) {
15006
  tcp_close((struct tcp_pcb *) arg);
15007
}
15008

    
15009
void mg_lwip_handle_accept(struct mg_connection *nc) {
15010
  struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
15011
  if (cs->pcb.tcp == NULL) return;
15012
#if MG_ENABLE_SSL
15013
  if (cs->lc->flags & MG_F_SSL) {
15014
    if (mg_ssl_if_conn_accept(nc, cs->lc) != MG_SSL_OK) {
15015
      LOG(LL_ERROR, ("SSL error"));
15016
      tcpip_callback(tcp_close_tcpip, cs->pcb.tcp);
15017
    }
15018
  } else
15019
#endif
15020
  {
15021
    mg_lwip_accept_conn(nc, cs->pcb.tcp);
15022
  }
15023
}
15024

    
15025
static err_t mg_lwip_accept_cb(void *arg, struct tcp_pcb *newtpcb, err_t err) {
15026
  struct mg_connection *lc = (struct mg_connection *) arg, *nc;
15027
  struct mg_lwip_conn_state *lcs, *cs;
15028
  struct tcp_pcb_listen *lpcb;
15029
  LOG(LL_DEBUG,
15030
      ("%p conn %p from %s:%u", lc, newtpcb,
15031
       IPADDR_NTOA(ipX_2_ip(&newtpcb->remote_ip)), newtpcb->remote_port));
15032
  if (lc == NULL) {
15033
    tcp_abort(newtpcb);
15034
    return ERR_ABRT;
15035
  }
15036
  lcs = (struct mg_lwip_conn_state *) lc->sock;
15037
  lpcb = (struct tcp_pcb_listen *) lcs->pcb.tcp;
15038
#if TCP_LISTEN_BACKLOG
15039
  tcp_accepted(lpcb);
15040
#endif
15041
  nc = mg_if_accept_new_conn(lc);
15042
  if (nc == NULL) {
15043
    tcp_abort(newtpcb);
15044
    return ERR_ABRT;
15045
  }
15046
  cs = (struct mg_lwip_conn_state *) nc->sock;
15047
  cs->lc = lc;
15048
  cs->pcb.tcp = newtpcb;
15049
  /* We need to set up callbacks before returning because data may start
15050
   * arriving immediately. */
15051
  tcp_arg(newtpcb, nc);
15052
  tcp_err(newtpcb, mg_lwip_tcp_error_cb);
15053
  tcp_sent(newtpcb, mg_lwip_tcp_sent_cb);
15054
  tcp_recv(newtpcb, mg_lwip_tcp_recv_cb);
15055
#if LWIP_TCP_KEEPALIVE
15056
  mg_lwip_set_keepalive_params(nc, 60, 10, 6);
15057
#endif
15058
  mg_lwip_post_signal(MG_SIG_ACCEPT, nc);
15059
  (void) err;
15060
  (void) lpcb;
15061
  return ERR_OK;
15062
}
15063

    
15064
struct mg_lwip_if_listen_ctx {
15065
  struct mg_connection *nc;
15066
  union socket_address *sa;
15067
  int ret;
15068
};
15069

    
15070
static void mg_lwip_if_listen_tcp_tcpip(void *arg) {
15071
  struct mg_lwip_if_listen_ctx *ctx = (struct mg_lwip_if_listen_ctx *) arg;
15072
  struct mg_connection *nc = ctx->nc;
15073
  union socket_address *sa = ctx->sa;
15074
  struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
15075
  struct tcp_pcb *tpcb = TCP_NEW();
15076
  ip_addr_t *ip = (ip_addr_t *) &sa->sin.sin_addr.s_addr;
15077
  u16_t port = ntohs(sa->sin.sin_port);
15078
  cs->err = TCP_BIND(tpcb, ip, port);
15079
  DBG(("%p tcp_bind(%s:%u) = %d", nc, IPADDR_NTOA(ip), port, cs->err));
15080
  if (cs->err != ERR_OK) {
15081
    tcp_close(tpcb);
15082
    ctx->ret = -1;
15083
    return;
15084
  }
15085
  tcp_arg(tpcb, nc);
15086
  tpcb = tcp_listen(tpcb);
15087
  cs->pcb.tcp = tpcb;
15088
  tcp_accept(tpcb, mg_lwip_accept_cb);
15089
  ctx->ret = 0;
15090
}
15091

    
15092
int mg_lwip_if_listen_tcp(struct mg_connection *nc, union socket_address *sa) {
15093
  struct mg_lwip_if_listen_ctx ctx = {.nc = nc, .sa = sa};
15094
  tcpip_callback(mg_lwip_if_listen_tcp_tcpip, &ctx);
15095
  return ctx.ret;
15096
}
15097

    
15098
static void mg_lwip_if_listen_udp_tcpip(void *arg) {
15099
  struct mg_lwip_if_listen_ctx *ctx = (struct mg_lwip_if_listen_ctx *) arg;
15100
  struct mg_connection *nc = ctx->nc;
15101
  union socket_address *sa = ctx->sa;
15102
  struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
15103
  struct udp_pcb *upcb = udp_new();
15104
  ip_addr_t *ip = (ip_addr_t *) &sa->sin.sin_addr.s_addr;
15105
  u16_t port = ntohs(sa->sin.sin_port);
15106
  cs->err = UDP_BIND(upcb, ip, port);
15107
  DBG(("%p udb_bind(%s:%u) = %d", nc, IPADDR_NTOA(ip), port, cs->err));
15108
  if (cs->err != ERR_OK) {
15109
    udp_remove(upcb);
15110
    ctx->ret = -1;
15111
  } else {
15112
    udp_recv(upcb, mg_lwip_udp_recv_cb, nc);
15113
    cs->pcb.udp = upcb;
15114
    ctx->ret = 0;
15115
  }
15116
}
15117

    
15118
int mg_lwip_if_listen_udp(struct mg_connection *nc, union socket_address *sa) {
15119
  struct mg_lwip_if_listen_ctx ctx = {.nc = nc, .sa = sa};
15120
  tcpip_callback(mg_lwip_if_listen_udp_tcpip, &ctx);
15121
  return ctx.ret;
15122
}
15123

    
15124
struct mg_lwip_tcp_write_ctx {
15125
  struct mg_connection *nc;
15126
  const void *data;
15127
  uint16_t len;
15128
  int ret;
15129
};
15130

    
15131
static void tcp_output_tcpip(void *arg) {
15132
  tcp_output((struct tcp_pcb *) arg);
15133
}
15134

    
15135
static void mg_lwip_tcp_write_tcpip(void *arg) {
15136
  struct mg_lwip_tcp_write_ctx *ctx = (struct mg_lwip_tcp_write_ctx *) arg;
15137
  struct mg_connection *nc = ctx->nc;
15138
  struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
15139
  struct tcp_pcb *tpcb = cs->pcb.tcp;
15140
  size_t len = MIN(tpcb->mss, MIN(ctx->len, tpcb->snd_buf));
15141
  size_t unsent, unacked;
15142
  if (len == 0) {
15143
    DBG(("%p no buf avail %u %u %p %p", tpcb, tpcb->snd_buf, tpcb->snd_queuelen,
15144
         tpcb->unsent, tpcb->unacked));
15145
    tcpip_callback(tcp_output_tcpip, tpcb);
15146
    ctx->ret = 0;
15147
    return;
15148
  }
15149
  unsent = (tpcb->unsent != NULL ? tpcb->unsent->len : 0);
15150
  unacked = (tpcb->unacked != NULL ? tpcb->unacked->len : 0);
15151
/*
15152
 * On ESP8266 we only allow one TCP segment in flight at any given time.
15153
 * This may increase latency and reduce efficiency of tcp windowing,
15154
 * but memory is scarce and precious on that platform so we do this to
15155
 * reduce footprint.
15156
 */
15157
#if CS_PLATFORM == CS_P_ESP8266
15158
  if (unacked > 0) {
15159
    ctx->ret = 0;
15160
    return;
15161
  }
15162
  len = MIN(len, (TCP_MSS - unsent));
15163
#endif
15164
  cs->err = tcp_write(tpcb, ctx->data, len, TCP_WRITE_FLAG_COPY);
15165
  unsent = (tpcb->unsent != NULL ? tpcb->unsent->len : 0);
15166
  unacked = (tpcb->unacked != NULL ? tpcb->unacked->len : 0);
15167
  DBG(("%p tcp_write %u = %d, %u %u", tpcb, len, cs->err, unsent, unacked));
15168
  if (cs->err != ERR_OK) {
15169
    /*
15170
     * We ignore ERR_MEM because memory will be freed up when the data is sent
15171
     * and we'll retry.
15172
     */
15173
    ctx->ret = (cs->err == ERR_MEM ? 0 : -1);
15174
    return;
15175
  }
15176
  ctx->ret = len;
15177
}
15178

    
15179
static int mg_lwip_tcp_write(struct mg_connection *nc, const void *data,
15180
                             uint16_t len) {
15181
  struct mg_lwip_tcp_write_ctx ctx = {.nc = nc, .data = data, .len = len};
15182
  struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
15183
  struct tcp_pcb *tpcb = cs->pcb.tcp;
15184
  if (tpcb == NULL) {
15185
    return -1;
15186
  }
15187
  tcpip_callback(mg_lwip_tcp_write_tcpip, &ctx);
15188
  return ctx.ret;
15189
}
15190

    
15191
struct udp_sendto_ctx {
15192
  struct udp_pcb *upcb;
15193
  struct pbuf *p;
15194
  ip_addr_t *ip;
15195
  uint16_t port;
15196
  int ret;
15197
};
15198

    
15199
static void udp_sendto_tcpip(void *arg) {
15200
  struct udp_sendto_ctx *ctx = (struct udp_sendto_ctx *) arg;
15201
  ctx->ret = udp_sendto(ctx->upcb, ctx->p, ctx->ip, ctx->port);
15202
}
15203

    
15204
static int mg_lwip_udp_send(struct mg_connection *nc, const void *data,
15205
                            uint16_t len) {
15206
  struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
15207
  if (cs->pcb.udp == NULL) {
15208
    /*
15209
     * In case of UDP, this usually means, what
15210
     * async DNS resolve is still in progress and connection
15211
     * is not ready yet
15212
     */
15213
    DBG(("%p socket is not connected", nc));
15214
    return -1;
15215
  }
15216
  struct udp_pcb *upcb = cs->pcb.udp;
15217
  struct pbuf *p = pbuf_alloc(PBUF_TRANSPORT, len, PBUF_RAM);
15218
#if defined(LWIP_IPV4) && LWIP_IPV4 && defined(LWIP_IPV6) && LWIP_IPV6
15219
  ip_addr_t ip = {.u_addr.ip4.addr = nc->sa.sin.sin_addr.s_addr, .type = 0};
15220
#else
15221
  ip_addr_t ip = {.addr = nc->sa.sin.sin_addr.s_addr};
15222
#endif
15223
  u16_t port = ntohs(nc->sa.sin.sin_port);
15224
  if (p == NULL) {
15225
    DBG(("OOM"));
15226
    return 0;
15227
  }
15228
  memcpy(p->payload, data, len);
15229
  struct udp_sendto_ctx ctx = {.upcb = upcb, .p = p, .ip = &ip, .port = port};
15230
  tcpip_callback(udp_sendto_tcpip, &ctx);
15231
  cs->err = ctx.ret;
15232
  pbuf_free(p);
15233
  return (cs->err == ERR_OK ? len : -1);
15234
}
15235

    
15236
static void mg_lwip_send_more(struct mg_connection *nc) {
15237
  int num_sent = 0;
15238
  if (nc->sock == INVALID_SOCKET) return;
15239
  if (nc->flags & MG_F_UDP) {
15240
    num_sent = mg_lwip_udp_send(nc, nc->send_mbuf.buf, nc->send_mbuf.len);
15241
    DBG(("%p mg_lwip_udp_send %u = %d", nc, nc->send_mbuf.len, num_sent));
15242
  } else {
15243
    num_sent = mg_lwip_tcp_write(nc, nc->send_mbuf.buf, nc->send_mbuf.len);
15244
    DBG(("%p mg_lwip_tcp_write %u = %d", nc, nc->send_mbuf.len, num_sent));
15245
  }
15246
  if (num_sent == 0) return;
15247
  if (num_sent > 0) {
15248
    mg_if_sent_cb(nc, num_sent);
15249
  } else {
15250
    mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc);
15251
  }
15252
}
15253

    
15254
void mg_lwip_if_tcp_send(struct mg_connection *nc, const void *buf,
15255
                         size_t len) {
15256
  mbuf_append(&nc->send_mbuf, buf, len);
15257
  mg_lwip_mgr_schedule_poll(nc->mgr);
15258
}
15259

    
15260
void mg_lwip_if_udp_send(struct mg_connection *nc, const void *buf,
15261
                         size_t len) {
15262
  mbuf_append(&nc->send_mbuf, buf, len);
15263
  mg_lwip_mgr_schedule_poll(nc->mgr);
15264
}
15265

    
15266
struct tcp_recved_ctx {
15267
  struct tcp_pcb *tpcb;
15268
  size_t len;
15269
};
15270

    
15271
void tcp_recved_tcpip(void *arg) {
15272
  struct tcp_recved_ctx *ctx = (struct tcp_recved_ctx *) arg;
15273
  tcp_recved(ctx->tpcb, ctx->len);
15274
}
15275

    
15276
void mg_lwip_if_recved(struct mg_connection *nc, size_t len) {
15277
  if (nc->flags & MG_F_UDP) return;
15278
  struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
15279
  if (nc->sock == INVALID_SOCKET || cs->pcb.tcp == NULL) {
15280
    DBG(("%p invalid socket", nc));
15281
    return;
15282
  }
15283
  DBG(("%p %p %u %u", nc, cs->pcb.tcp, len,
15284
       (cs->rx_chain ? cs->rx_chain->tot_len : 0)));
15285
  struct tcp_recved_ctx ctx = {.tpcb = cs->pcb.tcp, .len = len};
15286
#if MG_ENABLE_SSL
15287
  if (!(nc->flags & MG_F_SSL)) {
15288
    tcpip_callback(tcp_recved_tcpip, &ctx);
15289
  } else {
15290
    /* Currently SSL acknowledges data immediately.
15291
     * TODO(rojer): Find a way to propagate mg_lwip_if_recved. */
15292
  }
15293
#else
15294
  tcpip_callback(tcp_recved_tcpip, &ctx);
15295
#endif
15296
  mbuf_trim(&nc->recv_mbuf);
15297
}
15298

    
15299
int mg_lwip_if_create_conn(struct mg_connection *nc) {
15300
  struct mg_lwip_conn_state *cs =
15301
      (struct mg_lwip_conn_state *) MG_CALLOC(1, sizeof(*cs));
15302
  if (cs == NULL) return 0;
15303
  cs->nc = nc;
15304
  nc->sock = (intptr_t) cs;
15305
  return 1;
15306
}
15307

    
15308
static void udp_remove_tcpip(void *arg) {
15309
  udp_remove((struct udp_pcb *) arg);
15310
}
15311

    
15312
void mg_lwip_if_destroy_conn(struct mg_connection *nc) {
15313
  if (nc->sock == INVALID_SOCKET) return;
15314
  struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
15315
  if (!(nc->flags & MG_F_UDP)) {
15316
    struct tcp_pcb *tpcb = cs->pcb.tcp;
15317
    if (tpcb != NULL) {
15318
      tcp_arg(tpcb, NULL);
15319
      DBG(("%p tcp_close %p", nc, tpcb));
15320
      tcp_arg(tpcb, NULL);
15321
      tcpip_callback(tcp_close_tcpip, tpcb);
15322
    }
15323
    while (cs->rx_chain != NULL) {
15324
      struct pbuf *seg = cs->rx_chain;
15325
      cs->rx_chain = pbuf_dechain(cs->rx_chain);
15326
      pbuf_free(seg);
15327
    }
15328
    memset(cs, 0, sizeof(*cs));
15329
    MG_FREE(cs);
15330
  } else if (nc->listener == NULL) {
15331
    /* Only close outgoing UDP pcb or listeners. */
15332
    struct udp_pcb *upcb = cs->pcb.udp;
15333
    if (upcb != NULL) {
15334
      DBG(("%p udp_remove %p", nc, upcb));
15335
      tcpip_callback(udp_remove_tcpip, upcb);
15336
    }
15337
    memset(cs, 0, sizeof(*cs));
15338
    MG_FREE(cs);
15339
  }
15340
  nc->sock = INVALID_SOCKET;
15341
}
15342

    
15343
void mg_lwip_if_get_conn_addr(struct mg_connection *nc, int remote,
15344
                              union socket_address *sa) {
15345
  memset(sa, 0, sizeof(*sa));
15346
  if (nc == NULL || nc->sock == INVALID_SOCKET) return;
15347
  struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
15348
  if (nc->flags & MG_F_UDP) {
15349
    struct udp_pcb *upcb = cs->pcb.udp;
15350
    if (remote) {
15351
      memcpy(sa, &nc->sa, sizeof(*sa));
15352
    } else if (upcb != NULL) {
15353
      sa->sin.sin_port = htons(upcb->local_port);
15354
      SET_ADDR(sa, &upcb->local_ip);
15355
    }
15356
  } else {
15357
    struct tcp_pcb *tpcb = cs->pcb.tcp;
15358
    if (remote) {
15359
      memcpy(sa, &nc->sa, sizeof(*sa));
15360
    } else if (tpcb != NULL) {
15361
      sa->sin.sin_port = htons(tpcb->local_port);
15362
      SET_ADDR(sa, &tpcb->local_ip);
15363
    }
15364
  }
15365
}
15366

    
15367
void mg_lwip_if_sock_set(struct mg_connection *nc, sock_t sock) {
15368
  nc->sock = sock;
15369
}
15370

    
15371
/* clang-format off */
15372
#define MG_LWIP_IFACE_VTABLE                                          \
15373
  {                                                                   \
15374
    mg_lwip_if_init,                                                  \
15375
    mg_lwip_if_free,                                                  \
15376
    mg_lwip_if_add_conn,                                              \
15377
    mg_lwip_if_remove_conn,                                           \
15378
    mg_lwip_if_poll,                                                  \
15379
    mg_lwip_if_listen_tcp,                                            \
15380
    mg_lwip_if_listen_udp,                                            \
15381
    mg_lwip_if_connect_tcp,                                           \
15382
    mg_lwip_if_connect_udp,                                           \
15383
    mg_lwip_if_tcp_send,                                              \
15384
    mg_lwip_if_udp_send,                                              \
15385
    mg_lwip_if_recved,                                                \
15386
    mg_lwip_if_create_conn,                                           \
15387
    mg_lwip_if_destroy_conn,                                          \
15388
    mg_lwip_if_sock_set,                                              \
15389
    mg_lwip_if_get_conn_addr,                                         \
15390
  }
15391
/* clang-format on */
15392

    
15393
const struct mg_iface_vtable mg_lwip_iface_vtable = MG_LWIP_IFACE_VTABLE;
15394
#if MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL
15395
const struct mg_iface_vtable mg_default_iface_vtable = MG_LWIP_IFACE_VTABLE;
15396
#endif
15397

    
15398
#endif /* MG_ENABLE_NET_IF_LWIP_LOW_LEVEL */
15399
#ifdef MG_MODULE_LINES
15400
#line 1 "common/platforms/lwip/mg_lwip_ev_mgr.c"
15401
#endif
15402
/*
15403
 * Copyright (c) 2014-2016 Cesanta Software Limited
15404
 * All rights reserved
15405
 */
15406

    
15407
#if MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL
15408

    
15409
#ifndef MG_SIG_QUEUE_LEN
15410
#define MG_SIG_QUEUE_LEN 32
15411
#endif
15412

    
15413
struct mg_ev_mgr_lwip_signal {
15414
  int sig;
15415
  struct mg_connection *nc;
15416
};
15417

    
15418
struct mg_ev_mgr_lwip_data {
15419
  struct mg_ev_mgr_lwip_signal sig_queue[MG_SIG_QUEUE_LEN];
15420
  int sig_queue_len;
15421
  int start_index;
15422
};
15423

    
15424
void mg_lwip_post_signal(enum mg_sig_type sig, struct mg_connection *nc) {
15425
  struct mg_ev_mgr_lwip_data *md =
15426
      (struct mg_ev_mgr_lwip_data *) nc->iface->data;
15427
  mgos_lock();
15428
  if (md->sig_queue_len >= MG_SIG_QUEUE_LEN) {
15429
    mgos_unlock();
15430
    return;
15431
  }
15432
  int end_index = (md->start_index + md->sig_queue_len) % MG_SIG_QUEUE_LEN;
15433
  md->sig_queue[end_index].sig = sig;
15434
  md->sig_queue[end_index].nc = nc;
15435
  md->sig_queue_len++;
15436
  mg_lwip_mgr_schedule_poll(nc->mgr);
15437
  mgos_unlock();
15438
}
15439

    
15440
void mg_ev_mgr_lwip_process_signals(struct mg_mgr *mgr) {
15441
  struct mg_ev_mgr_lwip_data *md =
15442
      (struct mg_ev_mgr_lwip_data *) mgr->ifaces[MG_MAIN_IFACE]->data;
15443
  while (md->sig_queue_len > 0) {
15444
    mgos_lock();
15445
    int sig = md->sig_queue[md->start_index].sig;
15446
    struct mg_connection *nc = md->sig_queue[md->start_index].nc;
15447
    struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
15448
    md->start_index = (md->start_index + 1) % MG_SIG_QUEUE_LEN;
15449
    md->sig_queue_len--;
15450
    mgos_unlock();
15451
    if (nc->iface == NULL || nc->mgr == NULL) continue;
15452
    switch (sig) {
15453
      case MG_SIG_CONNECT_RESULT: {
15454
#if MG_ENABLE_SSL
15455
        if (cs->err == 0 && (nc->flags & MG_F_SSL) &&
15456
            !(nc->flags & MG_F_SSL_HANDSHAKE_DONE)) {
15457
          mg_lwip_ssl_do_hs(nc);
15458
        } else
15459
#endif
15460
        {
15461
          mg_if_connect_cb(nc, cs->err);
15462
        }
15463
        break;
15464
      }
15465
      case MG_SIG_CLOSE_CONN: {
15466
        nc->flags |= MG_F_SEND_AND_CLOSE;
15467
        mg_close_conn(nc);
15468
        break;
15469
      }
15470
      case MG_SIG_RECV: {
15471
        cs->recv_pending = 0;
15472
        if (nc->flags & MG_F_UDP) {
15473
          mg_lwip_handle_recv_udp(nc);
15474
        } else {
15475
          mg_lwip_handle_recv_tcp(nc);
15476
        }
15477
        break;
15478
      }
15479
      case MG_SIG_TOMBSTONE: {
15480
        break;
15481
      }
15482
      case MG_SIG_ACCEPT: {
15483
        mg_lwip_handle_accept(nc);
15484
        break;
15485
      }
15486
    }
15487
  }
15488
}
15489

    
15490
void mg_lwip_if_init(struct mg_iface *iface) {
15491
  LOG(LL_INFO, ("%p Mongoose init", iface));
15492
  iface->data = MG_CALLOC(1, sizeof(struct mg_ev_mgr_lwip_data));
15493
}
15494

    
15495
void mg_lwip_if_free(struct mg_iface *iface) {
15496
  MG_FREE(iface->data);
15497
  iface->data = NULL;
15498
}
15499

    
15500
void mg_lwip_if_add_conn(struct mg_connection *nc) {
15501
  (void) nc;
15502
}
15503

    
15504
void mg_lwip_if_remove_conn(struct mg_connection *nc) {
15505
  struct mg_ev_mgr_lwip_data *md =
15506
      (struct mg_ev_mgr_lwip_data *) nc->iface->data;
15507
  /* Walk the queue and null-out further signals for this conn. */
15508
  for (int i = 0; i < MG_SIG_QUEUE_LEN; i++) {
15509
    if (md->sig_queue[i].nc == nc) {
15510
      md->sig_queue[i].sig = MG_SIG_TOMBSTONE;
15511
    }
15512
  }
15513
}
15514

    
15515
time_t mg_lwip_if_poll(struct mg_iface *iface, int timeout_ms) {
15516
  struct mg_mgr *mgr = iface->mgr;
15517
  int n = 0;
15518
  double now = mg_time();
15519
  struct mg_connection *nc, *tmp;
15520
  double min_timer = 0;
15521
  int num_timers = 0;
15522
#if 0
15523
  DBG(("begin poll @%u", (unsigned int) (now * 1000)));
15524
#endif
15525
  mg_ev_mgr_lwip_process_signals(mgr);
15526
  for (nc = mgr->active_connections; nc != NULL; nc = tmp) {
15527
    struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
15528
    tmp = nc->next;
15529
    n++;
15530
    if ((nc->flags & MG_F_CLOSE_IMMEDIATELY) ||
15531
        ((nc->flags & MG_F_SEND_AND_CLOSE) && (nc->flags & MG_F_UDP) &&
15532
         (nc->send_mbuf.len == 0))) {
15533
      mg_close_conn(nc);
15534
      continue;
15535
    }
15536
    mg_if_poll(nc, now);
15537
    mg_if_timer(nc, now);
15538
#if MG_ENABLE_SSL
15539
    if ((nc->flags & MG_F_SSL) && cs != NULL && cs->pcb.tcp != NULL &&
15540
        cs->pcb.tcp->state == ESTABLISHED) {
15541
      if (((nc->flags & MG_F_WANT_WRITE) ||
15542
           ((nc->send_mbuf.len > 0) &&
15543
            (nc->flags & MG_F_SSL_HANDSHAKE_DONE))) &&
15544
          cs->pcb.tcp->snd_buf > 0) {
15545
        /* Can write more. */
15546
        if (nc->flags & MG_F_SSL_HANDSHAKE_DONE) {
15547
          if (!(nc->flags & MG_F_CONNECTING)) mg_lwip_ssl_send(nc);
15548
        } else {
15549
          mg_lwip_ssl_do_hs(nc);
15550
        }
15551
      }
15552
      if (cs->rx_chain != NULL || (nc->flags & MG_F_WANT_READ)) {
15553
        if (nc->flags & MG_F_SSL_HANDSHAKE_DONE) {
15554
          if (!(nc->flags & MG_F_CONNECTING)) mg_lwip_ssl_recv(nc);
15555
        } else {
15556
          mg_lwip_ssl_do_hs(nc);
15557
        }
15558
      }
15559
    } else
15560
#endif /* MG_ENABLE_SSL */
15561
    {
15562
      if (nc->send_mbuf.len > 0 && !(nc->flags & MG_F_CONNECTING)) {
15563
        mg_lwip_send_more(nc);
15564
      }
15565
    }
15566
    if (nc->sock != INVALID_SOCKET &&
15567
        !(nc->flags & (MG_F_UDP | MG_F_LISTENING)) && cs->pcb.tcp != NULL &&
15568
        cs->pcb.tcp->unsent != NULL) {
15569
      tcpip_callback(tcp_output_tcpip, cs->pcb.tcp);
15570
    }
15571
    if (nc->ev_timer_time > 0) {
15572
      if (num_timers == 0 || nc->ev_timer_time < min_timer) {
15573
        min_timer = nc->ev_timer_time;
15574
      }
15575
      num_timers++;
15576
    }
15577

    
15578
    if (nc->sock != INVALID_SOCKET) {
15579
      /* Try to consume data from cs->rx_chain */
15580
      mg_lwip_consume_rx_chain_tcp(nc);
15581

    
15582
      /*
15583
       * If the connection is about to close, and rx_chain is finally empty,
15584
       * send the MG_SIG_CLOSE_CONN signal
15585
       */
15586
      if (cs->draining_rx_chain && cs->rx_chain == NULL) {
15587
        mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc);
15588
      }
15589
    }
15590
  }
15591
#if 0
15592
  DBG(("end poll @%u, %d conns, %d timers (min %u), next in %d ms",
15593
       (unsigned int) (now * 1000), n, num_timers,
15594
       (unsigned int) (min_timer * 1000), timeout_ms));
15595
#endif
15596
  (void) timeout_ms;
15597
  return now;
15598
}
15599

    
15600
uint32_t mg_lwip_get_poll_delay_ms(struct mg_mgr *mgr) {
15601
  struct mg_connection *nc;
15602
  double now;
15603
  double min_timer = 0;
15604
  int num_timers = 0;
15605
  mg_ev_mgr_lwip_process_signals(mgr);
15606
  for (nc = mg_next(mgr, NULL); nc != NULL; nc = mg_next(mgr, nc)) {
15607
    struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
15608
    if (nc->ev_timer_time > 0) {
15609
      if (num_timers == 0 || nc->ev_timer_time < min_timer) {
15610
        min_timer = nc->ev_timer_time;
15611
      }
15612
      num_timers++;
15613
    }
15614
    if (nc->send_mbuf.len > 0
15615
#if MG_ENABLE_SSL
15616
        || (nc->flags & MG_F_WANT_WRITE)
15617
#endif
15618
            ) {
15619
      int can_send = 0;
15620
      /* We have stuff to send, but can we? */
15621
      if (nc->flags & MG_F_UDP) {
15622
        /* UDP is always ready for sending. */
15623
        can_send = (cs->pcb.udp != NULL);
15624
      } else {
15625
        can_send = (cs->pcb.tcp != NULL && cs->pcb.tcp->snd_buf > 0);
15626
      }
15627
      /* We want and can send, request a poll immediately. */
15628
      if (can_send) return 0;
15629
    }
15630
  }
15631
  uint32_t timeout_ms = ~0;
15632
  now = mg_time();
15633
  if (num_timers > 0) {
15634
    /* If we have a timer that is past due, do a poll ASAP. */
15635
    if (min_timer < now) return 0;
15636
    double timer_timeout_ms = (min_timer - now) * 1000 + 1 /* rounding */;
15637
    if (timer_timeout_ms < timeout_ms) {
15638
      timeout_ms = timer_timeout_ms;
15639
    }
15640
  }
15641
  return timeout_ms;
15642
}
15643

    
15644
#endif /* MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL */
15645
#ifdef MG_MODULE_LINES
15646
#line 1 "common/platforms/lwip/mg_lwip_ssl_if.c"
15647
#endif
15648
/*
15649
 * Copyright (c) 2014-2016 Cesanta Software Limited
15650
 * All rights reserved
15651
 */
15652

    
15653
#if MG_ENABLE_SSL && MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL
15654

    
15655
/* Amalgamated: #include "common/mg_mem.h" */
15656
/* Amalgamated: #include "common/cs_dbg.h" */
15657

    
15658
#include <lwip/pbuf.h>
15659
#include <lwip/tcp.h>
15660

    
15661
#ifndef MG_LWIP_SSL_IO_SIZE
15662
#define MG_LWIP_SSL_IO_SIZE 1024
15663
#endif
15664

    
15665
#ifndef MIN
15666
#define MIN(a, b) ((a) < (b) ? (a) : (b))
15667
#endif
15668

    
15669
void mg_lwip_ssl_do_hs(struct mg_connection *nc) {
15670
  struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
15671
  int server_side = (nc->listener != NULL);
15672
  enum mg_ssl_if_result res;
15673
  if (nc->flags & MG_F_CLOSE_IMMEDIATELY) return;
15674
  res = mg_ssl_if_handshake(nc);
15675
  DBG(("%p %lu %d %d", nc, nc->flags, server_side, res));
15676
  if (res != MG_SSL_OK) {
15677
    if (res == MG_SSL_WANT_WRITE) {
15678
      nc->flags |= MG_F_WANT_WRITE;
15679
      cs->err = 0;
15680
    } else if (res == MG_SSL_WANT_READ) {
15681
      /*
15682
       * Nothing to do in particular, we are callback-driven.
15683
       * What we definitely do not need anymore is SSL reading (nothing left).
15684
       */
15685
      nc->flags &= ~MG_F_WANT_READ;
15686
      cs->err = 0;
15687
    } else {
15688
      cs->err = res;
15689
      if (server_side) {
15690
        mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc);
15691
      } else {
15692
        mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc);
15693
      }
15694
    }
15695
  } else {
15696
    cs->err = 0;
15697
    nc->flags &= ~MG_F_WANT_WRITE;
15698
    /*
15699
     * Handshake is done. Schedule a read immediately to consume app data
15700
     * which may already be waiting.
15701
     */
15702
    nc->flags |= (MG_F_SSL_HANDSHAKE_DONE | MG_F_WANT_READ);
15703
    if (server_side) {
15704
      mg_lwip_accept_conn(nc, cs->pcb.tcp);
15705
    } else {
15706
      mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc);
15707
    }
15708
  }
15709
}
15710

    
15711
void mg_lwip_ssl_send(struct mg_connection *nc) {
15712
  if (nc->sock == INVALID_SOCKET) {
15713
    DBG(("%p invalid socket", nc));
15714
    return;
15715
  }
15716
  struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
15717
  /* It's ok if the buffer is empty. Return value of 0 may also be valid. */
15718
  int len = cs->last_ssl_write_size;
15719
  if (len == 0) {
15720
    len = MIN(MG_LWIP_SSL_IO_SIZE, nc->send_mbuf.len);
15721
  }
15722
  int ret = mg_ssl_if_write(nc, nc->send_mbuf.buf, len);
15723
  DBG(("%p SSL_write %u = %d", nc, len, ret));
15724
  if (ret > 0) {
15725
    mg_if_sent_cb(nc, ret);
15726
    cs->last_ssl_write_size = 0;
15727
  } else if (ret < 0) {
15728
    /* This is tricky. We must remember the exact data we were sending to retry
15729
     * exactly the same send next time. */
15730
    cs->last_ssl_write_size = len;
15731
  }
15732
  if (ret == len) {
15733
    nc->flags &= ~MG_F_WANT_WRITE;
15734
  } else if (ret == MG_SSL_WANT_WRITE) {
15735
    nc->flags |= MG_F_WANT_WRITE;
15736
  } else {
15737
    mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc);
15738
  }
15739
}
15740

    
15741
void mg_lwip_ssl_recv(struct mg_connection *nc) {
15742
  struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
15743
  /* Don't deliver data before connect callback */
15744
  if (nc->flags & MG_F_CONNECTING) return;
15745
  while (nc->recv_mbuf.len < nc->recv_mbuf_limit) {
15746
    char *buf = (char *) MG_MALLOC(MG_LWIP_SSL_IO_SIZE);
15747
    if (buf == NULL) return;
15748
    int ret = mg_ssl_if_read(nc, buf, MG_LWIP_SSL_IO_SIZE);
15749
    DBG(("%p %p SSL_read %u = %d", nc, cs->rx_chain, MG_LWIP_SSL_IO_SIZE, ret));
15750
    if (ret <= 0) {
15751
      MG_FREE(buf);
15752
      if (ret == MG_SSL_WANT_WRITE) {
15753
        nc->flags |= MG_F_WANT_WRITE;
15754
        return;
15755
      } else if (ret == MG_SSL_WANT_READ) {
15756
        /*
15757
         * Nothing to do in particular, we are callback-driven.
15758
         * What we definitely do not need anymore is SSL reading (nothing left).
15759
         */
15760
        nc->flags &= ~MG_F_WANT_READ;
15761
        cs->err = 0;
15762
        return;
15763
      } else {
15764
        mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc);
15765
        return;
15766
      }
15767
    } else {
15768
      mg_if_recv_tcp_cb(nc, buf, ret, 1 /* own */);
15769
    }
15770
  }
15771
}
15772

    
15773
#ifdef KR_VERSION
15774

    
15775
ssize_t kr_send(int fd, const void *buf, size_t len) {
15776
  struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) fd;
15777
  int ret = mg_lwip_tcp_write(cs->nc, buf, len);
15778
  DBG(("%p mg_lwip_tcp_write %u = %d", cs->nc, len, ret));
15779
  if (ret == 0) ret = KR_IO_WOULDBLOCK;
15780
  return ret;
15781
}
15782

    
15783
ssize_t kr_recv(int fd, void *buf, size_t len) {
15784
  struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) fd;
15785
  struct pbuf *seg = cs->rx_chain;
15786
  if (seg == NULL) {
15787
    DBG(("%u - nothing to read", len));
15788
    return KR_IO_WOULDBLOCK;
15789
  }
15790
  size_t seg_len = (seg->len - cs->rx_offset);
15791
  DBG(("%u %u %u %u", len, cs->rx_chain->len, seg_len, cs->rx_chain->tot_len));
15792
  len = MIN(len, seg_len);
15793
  pbuf_copy_partial(seg, buf, len, cs->rx_offset);
15794
  cs->rx_offset += len;
15795
  tcp_recved(cs->pcb.tcp, len);
15796
  if (cs->rx_offset == cs->rx_chain->len) {
15797
    cs->rx_chain = pbuf_dechain(cs->rx_chain);
15798
    pbuf_free(seg);
15799
    cs->rx_offset = 0;
15800
  }
15801
  return len;
15802
}
15803

    
15804
#elif MG_SSL_IF == MG_SSL_IF_MBEDTLS
15805

    
15806
int ssl_socket_send(void *ctx, const unsigned char *buf, size_t len) {
15807
  struct mg_connection *nc = (struct mg_connection *) ctx;
15808
  struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
15809
  int ret = mg_lwip_tcp_write(cs->nc, buf, len);
15810
  if (ret == 0) ret = MBEDTLS_ERR_SSL_WANT_WRITE;
15811
  LOG(LL_DEBUG, ("%p %d -> %d", nc, len, ret));
15812
  return ret;
15813
}
15814

    
15815
int ssl_socket_recv(void *ctx, unsigned char *buf, size_t len) {
15816
  struct mg_connection *nc = (struct mg_connection *) ctx;
15817
  struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
15818
  struct pbuf *seg = cs->rx_chain;
15819
  if (seg == NULL) {
15820
    DBG(("%u - nothing to read", len));
15821
    return MBEDTLS_ERR_SSL_WANT_READ;
15822
  }
15823
  size_t seg_len = (seg->len - cs->rx_offset);
15824
  DBG(("%u %u %u %u", len, cs->rx_chain->len, seg_len, cs->rx_chain->tot_len));
15825
  mgos_lock();
15826
  len = MIN(len, seg_len);
15827
  pbuf_copy_partial(seg, buf, len, cs->rx_offset);
15828
  cs->rx_offset += len;
15829
  /* TCP PCB may be NULL if connection has already been closed
15830
   * but we still have data to deliver to SSL. */
15831
  if (cs->pcb.tcp != NULL) tcp_recved(cs->pcb.tcp, len);
15832
  if (cs->rx_offset == cs->rx_chain->len) {
15833
    cs->rx_chain = pbuf_dechain(cs->rx_chain);
15834
    pbuf_free(seg);
15835
    cs->rx_offset = 0;
15836
  }
15837
  mgos_unlock();
15838
  LOG(LL_DEBUG, ("%p <- %d", nc, (int) len));
15839
  return len;
15840
}
15841

    
15842
#endif
15843

    
15844
#endif /* MG_ENABLE_SSL && MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL */
15845
#ifdef MG_MODULE_LINES
15846
#line 1 "common/platforms/wince/wince_libc.c"
15847
#endif
15848
/*
15849
 * Copyright (c) 2016 Cesanta Software Limited
15850
 * All rights reserved
15851
 */
15852

    
15853
#ifdef WINCE
15854

    
15855
const char *strerror(int err) {
15856
  /*
15857
   * TODO(alashkin): there is no strerror on WinCE;
15858
   * look for similar wce_xxxx function
15859
   */
15860
  static char buf[10];
15861
  snprintf(buf, sizeof(buf), "%d", err);
15862
  return buf;
15863
}
15864

    
15865
int open(const char *filename, int oflag, int pmode) {
15866
  /*
15867
   * TODO(alashkin): mg_open function is not used in mongoose
15868
   * but exists in documentation as utility function
15869
   * Shall we delete it at all or implement for WinCE as well?
15870
   */
15871
  DebugBreak();
15872
  return 0; /* for compiler */
15873
}
15874

    
15875
int _wstati64(const wchar_t *path, cs_stat_t *st) {
15876
  DWORD fa = GetFileAttributesW(path);
15877
  if (fa == INVALID_FILE_ATTRIBUTES) {
15878
    return -1;
15879
  }
15880
  memset(st, 0, sizeof(*st));
15881
  if ((fa & FILE_ATTRIBUTE_DIRECTORY) == 0) {
15882
    HANDLE h;
15883
    FILETIME ftime;
15884
    st->st_mode |= _S_IFREG;
15885
    h = CreateFileW(path, GENERIC_READ, 0, NULL, OPEN_EXISTING,
15886
                    FILE_ATTRIBUTE_NORMAL, NULL);
15887
    if (h == INVALID_HANDLE_VALUE) {
15888
      return -1;
15889
    }
15890
    st->st_size = GetFileSize(h, NULL);
15891
    GetFileTime(h, NULL, NULL, &ftime);
15892
    st->st_mtime = (uint32_t)((((uint64_t) ftime.dwLowDateTime +
15893
                                ((uint64_t) ftime.dwHighDateTime << 32)) /
15894
                               10000000.0) -
15895
                              11644473600);
15896
    CloseHandle(h);
15897
  } else {
15898
    st->st_mode |= _S_IFDIR;
15899
  }
15900
  return 0;
15901
}
15902

    
15903
/* Windows CE doesn't have neither gmtime nor strftime */
15904
static void mg_gmt_time_string(char *buf, size_t buf_len, time_t *t) {
15905
  FILETIME ft;
15906
  SYSTEMTIME systime;
15907
  if (t != NULL) {
15908
    uint64_t filetime = (*t + 11644473600) * 10000000;
15909
    ft.dwLowDateTime = filetime & 0xFFFFFFFF;
15910
    ft.dwHighDateTime = (filetime & 0xFFFFFFFF00000000) >> 32;
15911
    FileTimeToSystemTime(&ft, &systime);
15912
  } else {
15913
    GetSystemTime(&systime);
15914
  }
15915
  /* There is no PRIu16 in WinCE SDK */
15916
  snprintf(buf, buf_len, "%d.%d.%d %d:%d:%d GMT", (int) systime.wYear,
15917
           (int) systime.wMonth, (int) systime.wDay, (int) systime.wHour,
15918
           (int) systime.wMinute, (int) systime.wSecond);
15919
}
15920

    
15921
#endif
15922
#ifdef MG_MODULE_LINES
15923
#line 1 "common/platforms/pic32/pic32_net_if.h"
15924
#endif
15925
/*
15926
 * Copyright (c) 2014-2016 Cesanta Software Limited
15927
 * All rights reserved
15928
 */
15929

    
15930
#ifndef CS_COMMON_PLATFORMS_PIC32_NET_IF_H_
15931
#define CS_COMMON_PLATFORMS_PIC32_NET_IF_H_
15932

    
15933
/* Amalgamated: #include "mongoose/src/net_if.h" */
15934

    
15935
#ifdef __cplusplus
15936
extern "C" {
15937
#endif /* __cplusplus */
15938

    
15939
#ifndef MG_ENABLE_NET_IF_PIC32
15940
#define MG_ENABLE_NET_IF_PIC32 MG_NET_IF == MG_NET_IF_PIC32
15941
#endif
15942

    
15943
extern const struct mg_iface_vtable mg_pic32_iface_vtable;
15944

    
15945
#ifdef __cplusplus
15946
}
15947
#endif /* __cplusplus */
15948

    
15949
#endif /* CS_COMMON_PLATFORMS_PIC32_NET_IF_H_ */
15950
#ifdef MG_MODULE_LINES
15951
#line 1 "common/platforms/pic32/pic32_net_if.c"
15952
#endif
15953
/*
15954
 * Copyright (c) 2014-2016 Cesanta Software Limited
15955
 * All rights reserved
15956
 */
15957

    
15958
#if MG_ENABLE_NET_IF_PIC32
15959

    
15960
int mg_pic32_if_create_conn(struct mg_connection *nc) {
15961
  (void) nc;
15962
  return 1;
15963
}
15964

    
15965
void mg_pic32_if_recved(struct mg_connection *nc, size_t len) {
15966
  (void) nc;
15967
  (void) len;
15968
}
15969

    
15970
void mg_pic32_if_add_conn(struct mg_connection *nc) {
15971
  (void) nc;
15972
}
15973

    
15974
void mg_pic32_if_init(struct mg_iface *iface) {
15975
  (void) iface;
15976
  (void) mg_get_errno(); /* Shutup compiler */
15977
}
15978

    
15979
void mg_pic32_if_free(struct mg_iface *iface) {
15980
  (void) iface;
15981
}
15982

    
15983
void mg_pic32_if_remove_conn(struct mg_connection *nc) {
15984
  (void) nc;
15985
}
15986

    
15987
void mg_pic32_if_destroy_conn(struct mg_connection *nc) {
15988
  if (nc->sock == INVALID_SOCKET) return;
15989
  /* For UDP, only close outgoing sockets or listeners. */
15990
  if (!(nc->flags & MG_F_UDP)) {
15991
    /* Close TCP */
15992
    TCPIP_TCP_Close((TCP_SOCKET) nc->sock);
15993
  } else if (nc->listener == NULL) {
15994
    /* Only close outgoing UDP or listeners. */
15995
    TCPIP_UDP_Close((UDP_SOCKET) nc->sock);
15996
  }
15997

    
15998
  nc->sock = INVALID_SOCKET;
15999
}
16000

    
16001
int mg_pic32_if_listen_udp(struct mg_connection *nc, union socket_address *sa) {
16002
  nc->sock = TCPIP_UDP_ServerOpen(
16003
      sa->sin.sin_family == AF_INET ? IP_ADDRESS_TYPE_IPV4
16004
                                    : IP_ADDRESS_TYPE_IPV6,
16005
      ntohs(sa->sin.sin_port),
16006
      sa->sin.sin_addr.s_addr == 0 ? 0 : (IP_MULTI_ADDRESS *) &sa->sin);
16007
  if (nc->sock == INVALID_SOCKET) {
16008
    return -1;
16009
  }
16010
  return 0;
16011
}
16012

    
16013
void mg_pic32_if_udp_send(struct mg_connection *nc, const void *buf,
16014
                          size_t len) {
16015
  mbuf_append(&nc->send_mbuf, buf, len);
16016
}
16017

    
16018
void mg_pic32_if_tcp_send(struct mg_connection *nc, const void *buf,
16019
                          size_t len) {
16020
  mbuf_append(&nc->send_mbuf, buf, len);
16021
}
16022

    
16023
int mg_pic32_if_listen_tcp(struct mg_connection *nc, union socket_address *sa) {
16024
  nc->sock = TCPIP_TCP_ServerOpen(
16025
      sa->sin.sin_family == AF_INET ? IP_ADDRESS_TYPE_IPV4
16026
                                    : IP_ADDRESS_TYPE_IPV6,
16027
      ntohs(sa->sin.sin_port),
16028
      sa->sin.sin_addr.s_addr == 0 ? 0 : (IP_MULTI_ADDRESS *) &sa->sin);
16029
  memcpy(&nc->sa, sa, sizeof(*sa));
16030
  if (nc->sock == INVALID_SOCKET) {
16031
    return -1;
16032
  }
16033
  return 0;
16034
}
16035

    
16036
static int mg_accept_conn(struct mg_connection *lc) {
16037
  struct mg_connection *nc;
16038
  TCP_SOCKET_INFO si;
16039
  union socket_address sa;
16040

    
16041
  nc = mg_if_accept_new_conn(lc);
16042

    
16043
  if (nc == NULL) {
16044
    return 0;
16045
  }
16046

    
16047
  nc->sock = lc->sock;
16048
  nc->flags &= ~MG_F_LISTENING;
16049

    
16050
  if (!TCPIP_TCP_SocketInfoGet((TCP_SOCKET) nc->sock, &si)) {
16051
    return 0;
16052
  }
16053

    
16054
  if (si.addressType == IP_ADDRESS_TYPE_IPV4) {
16055
    sa.sin.sin_family = AF_INET;
16056
    sa.sin.sin_port = htons(si.remotePort);
16057
    sa.sin.sin_addr.s_addr = si.remoteIPaddress.v4Add.Val;
16058
  } else {
16059
    /* TODO(alashkin): do something with _potential_ IPv6 */
16060
    memset(&sa, 0, sizeof(sa));
16061
  }
16062

    
16063
  mg_if_accept_tcp_cb(nc, (union socket_address *) &sa, sizeof(sa));
16064

    
16065
  return mg_pic32_if_listen_tcp(lc, &lc->sa) >= 0;
16066
}
16067

    
16068
char *inet_ntoa(struct in_addr in) {
16069
  static char addr[17];
16070
  snprintf(addr, sizeof(addr), "%d.%d.%d.%d", (int) in.S_un.S_un_b.s_b1,
16071
           (int) in.S_un.S_un_b.s_b2, (int) in.S_un.S_un_b.s_b3,
16072
           (int) in.S_un.S_un_b.s_b4);
16073
  return addr;
16074
}
16075

    
16076
static void mg_handle_send(struct mg_connection *nc) {
16077
  uint16_t bytes_written = 0;
16078
  if (nc->flags & MG_F_UDP) {
16079
    if (!TCPIP_UDP_RemoteBind(
16080
            (UDP_SOCKET) nc->sock,
16081
            nc->sa.sin.sin_family == AF_INET ? IP_ADDRESS_TYPE_IPV4
16082
                                             : IP_ADDRESS_TYPE_IPV6,
16083
            ntohs(nc->sa.sin.sin_port), (IP_MULTI_ADDRESS *) &nc->sa.sin)) {
16084
      nc->flags |= MG_F_CLOSE_IMMEDIATELY;
16085
      return;
16086
    }
16087
    bytes_written = TCPIP_UDP_TxPutIsReady((UDP_SOCKET) nc->sock, 0);
16088
    if (bytes_written >= nc->send_mbuf.len) {
16089
      if (TCPIP_UDP_ArrayPut((UDP_SOCKET) nc->sock,
16090
                             (uint8_t *) nc->send_mbuf.buf,
16091
                             nc->send_mbuf.len) != nc->send_mbuf.len) {
16092
        nc->flags |= MG_F_CLOSE_IMMEDIATELY;
16093
        bytes_written = 0;
16094
      }
16095
    }
16096
  } else {
16097
    bytes_written = TCPIP_TCP_FifoTxFreeGet((TCP_SOCKET) nc->sock);
16098
    if (bytes_written != 0) {
16099
      if (bytes_written > nc->send_mbuf.len) {
16100
        bytes_written = nc->send_mbuf.len;
16101
      }
16102
      if (TCPIP_TCP_ArrayPut((TCP_SOCKET) nc->sock,
16103
                             (uint8_t *) nc->send_mbuf.buf,
16104
                             bytes_written) != bytes_written) {
16105
        nc->flags |= MG_F_CLOSE_IMMEDIATELY;
16106
        bytes_written = 0;
16107
      }
16108
    }
16109
  }
16110

    
16111
  mg_if_sent_cb(nc, bytes_written);
16112
}
16113

    
16114
static void mg_handle_recv(struct mg_connection *nc) {
16115
  uint16_t bytes_read = 0;
16116
  uint8_t *buf = NULL;
16117
  if (nc->flags & MG_F_UDP) {
16118
    bytes_read = TCPIP_UDP_GetIsReady((UDP_SOCKET) nc->sock);
16119
    if (bytes_read != 0 &&
16120
        (nc->recv_mbuf_limit == -1 ||
16121
         nc->recv_mbuf.len + bytes_read < nc->recv_mbuf_limit)) {
16122
      buf = (uint8_t *) MG_MALLOC(bytes_read);
16123
      if (TCPIP_UDP_ArrayGet((UDP_SOCKET) nc->sock, buf, bytes_read) !=
16124
          bytes_read) {
16125
        nc->flags |= MG_F_CLOSE_IMMEDIATELY;
16126
        bytes_read = 0;
16127
        MG_FREE(buf);
16128
      }
16129
    }
16130
  } else {
16131
    bytes_read = TCPIP_TCP_GetIsReady((TCP_SOCKET) nc->sock);
16132
    if (bytes_read != 0) {
16133
      if (nc->recv_mbuf_limit != -1 &&
16134
          nc->recv_mbuf_limit - nc->recv_mbuf.len > bytes_read) {
16135
        bytes_read = nc->recv_mbuf_limit - nc->recv_mbuf.len;
16136
      }
16137
      buf = (uint8_t *) MG_MALLOC(bytes_read);
16138
      if (TCPIP_TCP_ArrayGet((TCP_SOCKET) nc->sock, buf, bytes_read) !=
16139
          bytes_read) {
16140
        nc->flags |= MG_F_CLOSE_IMMEDIATELY;
16141
        MG_FREE(buf);
16142
        bytes_read = 0;
16143
      }
16144
    }
16145
  }
16146

    
16147
  if (bytes_read != 0) {
16148
    mg_if_recv_tcp_cb(nc, buf, bytes_read, 1 /* own */);
16149
  }
16150
}
16151

    
16152
time_t mg_pic32_if_poll(struct mg_iface *iface, int timeout_ms) {
16153
  struct mg_mgr *mgr = iface->mgr;
16154
  double now = mg_time();
16155
  struct mg_connection *nc, *tmp;
16156

    
16157
  for (nc = mgr->active_connections; nc != NULL; nc = tmp) {
16158
    tmp = nc->next;
16159

    
16160
    if (nc->flags & MG_F_CONNECTING) {
16161
      /* processing connections */
16162
      if (nc->flags & MG_F_UDP ||
16163
          TCPIP_TCP_IsConnected((TCP_SOCKET) nc->sock)) {
16164
        mg_if_connect_cb(nc, 0);
16165
      }
16166
    } else if (nc->flags & MG_F_LISTENING) {
16167
      if (TCPIP_TCP_IsConnected((TCP_SOCKET) nc->sock)) {
16168
        /* accept new connections */
16169
        mg_accept_conn(nc);
16170
      }
16171
    } else {
16172
      if (nc->send_mbuf.len != 0) {
16173
        mg_handle_send(nc);
16174
      }
16175

    
16176
      if (nc->recv_mbuf_limit == -1 ||
16177
          nc->recv_mbuf.len < nc->recv_mbuf_limit) {
16178
        mg_handle_recv(nc);
16179
      }
16180
    }
16181
  }
16182

    
16183
  for (nc = mgr->active_connections; nc != NULL; nc = tmp) {
16184
    tmp = nc->next;
16185
    if ((nc->flags & MG_F_CLOSE_IMMEDIATELY) ||
16186
        (nc->send_mbuf.len == 0 && (nc->flags & MG_F_SEND_AND_CLOSE))) {
16187
      mg_close_conn(nc);
16188
    }
16189
  }
16190

    
16191
  return now;
16192
}
16193

    
16194
void mg_pic32_if_sock_set(struct mg_connection *nc, sock_t sock) {
16195
  nc->sock = sock;
16196
}
16197

    
16198
void mg_pic32_if_get_conn_addr(struct mg_connection *nc, int remote,
16199
                               union socket_address *sa) {
16200
  /* TODO(alaskin): not implemented yet */
16201
}
16202

    
16203
void mg_pic32_if_connect_tcp(struct mg_connection *nc,
16204
                             const union socket_address *sa) {
16205
  nc->sock = TCPIP_TCP_ClientOpen(
16206
      sa->sin.sin_family == AF_INET ? IP_ADDRESS_TYPE_IPV4
16207
                                    : IP_ADDRESS_TYPE_IPV6,
16208
      ntohs(sa->sin.sin_port), (IP_MULTI_ADDRESS *) &sa->sin);
16209
  nc->err = (nc->sock == INVALID_SOCKET) ? -1 : 0;
16210
}
16211

    
16212
void mg_pic32_if_connect_udp(struct mg_connection *nc) {
16213
  nc->sock = TCPIP_UDP_ClientOpen(IP_ADDRESS_TYPE_ANY, 0, NULL);
16214
  nc->err = (nc->sock == INVALID_SOCKET) ? -1 : 0;
16215
}
16216

    
16217
/* clang-format off */
16218
#define MG_PIC32_IFACE_VTABLE                                   \
16219
  {                                                             \
16220
    mg_pic32_if_init,                                           \
16221
    mg_pic32_if_free,                                           \
16222
    mg_pic32_if_add_conn,                                       \
16223
    mg_pic32_if_remove_conn,                                    \
16224
    mg_pic32_if_poll,                                           \
16225
    mg_pic32_if_listen_tcp,                                     \
16226
    mg_pic32_if_listen_udp,                                     \
16227
    mg_pic32_if_connect_tcp,                                    \
16228
    mg_pic32_if_connect_udp,                                    \
16229
    mg_pic32_if_tcp_send,                                       \
16230
    mg_pic32_if_udp_send,                                       \
16231
    mg_pic32_if_recved,                                         \
16232
    mg_pic32_if_create_conn,                                    \
16233
    mg_pic32_if_destroy_conn,                                   \
16234
    mg_pic32_if_sock_set,                                       \
16235
    mg_pic32_if_get_conn_addr,                                  \
16236
  }
16237
/* clang-format on */
16238

    
16239
const struct mg_iface_vtable mg_pic32_iface_vtable = MG_PIC32_IFACE_VTABLE;
16240
#if MG_NET_IF == MG_NET_IF_PIC32
16241
const struct mg_iface_vtable mg_default_iface_vtable = MG_PIC32_IFACE_VTABLE;
16242
#endif
16243

    
16244
#endif /* MG_ENABLE_NET_IF_PIC32 */
16245
#ifdef MG_MODULE_LINES
16246
#line 1 "common/platforms/windows/windows_direct.c"
16247
#endif
16248
/*
16249
 * Copyright (c) 2017 Cesanta Software Limited
16250
 * All rights reserved
16251
 */
16252

    
16253
#ifdef _WIN32
16254

    
16255
int rmdir(const char *dirname) {
16256
  return _rmdir(dirname);
16257
}
16258

    
16259
unsigned int sleep(unsigned int seconds) {
16260
  Sleep(seconds * 1000);
16261
  return 0;
16262
}
16263

    
16264
#endif /* _WIN32 */
(3-3/9)