Statistics
| Branch: | Tag: | Revision:

mongoose / mongoose.c @ 5cdf8383

History | View | Annotate | Download (247 KB)

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

    
11
#ifndef MG_INTERNAL_HEADER_INCLUDED
12
#define MG_INTERNAL_HEADER_INCLUDED
13

    
14
#ifndef MG_MALLOC
15
#define MG_MALLOC malloc
16
#endif
17

    
18
#ifndef MG_CALLOC
19
#define MG_CALLOC calloc
20
#endif
21

    
22
#ifndef MG_REALLOC
23
#define MG_REALLOC realloc
24
#endif
25

    
26
#ifndef MG_FREE
27
#define MG_FREE free
28
#endif
29

    
30
#ifndef MBUF_REALLOC
31
#define MBUF_REALLOC MG_REALLOC
32
#endif
33

    
34
#ifndef MBUF_FREE
35
#define MBUF_FREE MG_FREE
36
#endif
37

    
38
#define MG_SET_PTRPTR(_ptr, _v) \
39
  do {                          \
40
    if (_ptr) *(_ptr) = _v;     \
41
  } while (0)
42

    
43
#ifndef MG_INTERNAL
44
#define MG_INTERNAL static
45
#endif
46

    
47
#if !defined(MG_MGR_EV_MGR)
48
/*
49
 * Switches between different methods of handling sockets. Supported values:
50
 * 0 - select()
51
 * 1 - epoll() (Linux only)
52
 */
53
#define MG_MGR_EV_MGR 0 /* select() */
54
#endif
55

    
56
#ifdef PICOTCP
57
#define NO_LIBC
58
#define MG_DISABLE_FILESYSTEM
59
#define MG_DISABLE_POPEN
60
#define MG_DISABLE_CGI
61
#define MG_DISABLE_DIRECTORY_LISTING
62
#define MG_DISABLE_SOCKETPAIR
63
#define MG_DISABLE_PFS
64
#endif
65

    
66
/* Amalgamated: #include "../mongoose.h" */
67

    
68
/* internals that need to be accessible in unit tests */
69
MG_INTERNAL struct mg_connection *mg_do_connect(struct mg_connection *nc,
70
                                                int proto,
71
                                                union socket_address *sa);
72

    
73
MG_INTERNAL int mg_parse_address(const char *str, union socket_address *sa,
74
                                 int *proto, char *host, size_t host_len);
75
MG_INTERNAL void mg_call(struct mg_connection *nc,
76
                         mg_event_handler_t ev_handler, int ev, void *ev_data);
77
MG_INTERNAL void mg_forward(struct mg_connection *, struct mg_connection *);
78
MG_INTERNAL void mg_add_conn(struct mg_mgr *mgr, struct mg_connection *c);
79
MG_INTERNAL void mg_remove_conn(struct mg_connection *c);
80

    
81
#ifndef MG_DISABLE_FILESYSTEM
82
MG_INTERNAL int find_index_file(char *, size_t, const char *, cs_stat_t *);
83
#endif
84

    
85
#ifdef _WIN32
86
void to_wchar(const char *path, wchar_t *wbuf, size_t wbuf_len);
87
#endif
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
#ifndef MG_DISABLE_FILESYSTEM
105
MG_INTERNAL time_t mg_parse_date_string(const char *datetime);
106
#endif
107

    
108
/* Forward declarations for testing. */
109
extern void *(*test_malloc)(size_t);
110
extern void *(*test_calloc)(size_t, size_t);
111

    
112
#endif /* MG_INTERNAL_HEADER_INCLUDED */
113
#ifdef NS_MODULE_LINES
114
#line 1 "src/../../common/base64.c"
115
/**/
116
#endif
117
/*
118
 * Copyright (c) 2014 Cesanta Software Limited
119
 * All rights reserved
120
 */
121

    
122
#ifndef EXCLUDE_COMMON
123

    
124
/* Amalgamated: #include "base64.h" */
125
#include <string.h>
126

    
127
/* ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/ */
128

    
129
#define NUM_UPPERCASES ('Z' - 'A' + 1)
130
#define NUM_LETTERS (NUM_UPPERCASES * 2)
131
#define NUM_DIGITS ('9' - '0' + 1)
132

    
133
/*
134
 * Emit a base64 code char.
135
 *
136
 * Doesn't use memory, thus it's safe to use to safely dump memory in crashdumps
137
 */
138
static void cs_base64_emit_code(struct cs_base64_ctx *ctx, int v) {
139
  if (v < NUM_UPPERCASES) {
140
    ctx->b64_putc(v + 'A', ctx->user_data);
141
  } else if (v < (NUM_LETTERS)) {
142
    ctx->b64_putc(v - NUM_UPPERCASES + 'a', ctx->user_data);
143
  } else if (v < (NUM_LETTERS + NUM_DIGITS)) {
144
    ctx->b64_putc(v - NUM_LETTERS + '0', ctx->user_data);
145
  } else {
146
    ctx->b64_putc(v - NUM_LETTERS - NUM_DIGITS == 0 ? '+' : '/',
147
                  ctx->user_data);
148
  }
149
}
150

    
151
static void cs_base64_emit_chunk(struct cs_base64_ctx *ctx) {
152
  int a, b, c;
153

    
154
  a = ctx->chunk[0];
155
  b = ctx->chunk[1];
156
  c = ctx->chunk[2];
157

    
158
  cs_base64_emit_code(ctx, a >> 2);
159
  cs_base64_emit_code(ctx, ((a & 3) << 4) | (b >> 4));
160
  if (ctx->chunk_size > 1) {
161
    cs_base64_emit_code(ctx, (b & 15) << 2 | (c >> 6));
162
  }
163
  if (ctx->chunk_size > 2) {
164
    cs_base64_emit_code(ctx, c & 63);
165
  }
166
}
167

    
168
void cs_base64_init(struct cs_base64_ctx *ctx, cs_base64_putc_t b64_putc,
169
                    void *user_data) {
170
  ctx->chunk_size = 0;
171
  ctx->b64_putc = b64_putc;
172
  ctx->user_data = user_data;
173
}
174

    
175
void cs_base64_update(struct cs_base64_ctx *ctx, const char *str, size_t len) {
176
  const unsigned char *src = (const unsigned char *) str;
177
  size_t i;
178
  for (i = 0; i < len; i++) {
179
    ctx->chunk[ctx->chunk_size++] = src[i];
180
    if (ctx->chunk_size == 3) {
181
      cs_base64_emit_chunk(ctx);
182
      ctx->chunk_size = 0;
183
    }
184
  }
185
}
186

    
187
void cs_base64_finish(struct cs_base64_ctx *ctx) {
188
  if (ctx->chunk_size > 0) {
189
    int i;
190
    memset(&ctx->chunk[ctx->chunk_size], 0, 3 - ctx->chunk_size);
191
    cs_base64_emit_chunk(ctx);
192
    for (i = 0; i < (3 - ctx->chunk_size); i++) {
193
      ctx->b64_putc('=', ctx->user_data);
194
    }
195
  }
196
}
197

    
198
#define BASE64_ENCODE_BODY                                                \
199
  static const char *b64 =                                                \
200
      "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; \
201
  int i, j, a, b, c;                                                      \
202
                                                                          \
203
  for (i = j = 0; i < src_len; i += 3) {                                  \
204
    a = src[i];                                                           \
205
    b = i + 1 >= src_len ? 0 : src[i + 1];                                \
206
    c = i + 2 >= src_len ? 0 : src[i + 2];                                \
207
                                                                          \
208
    BASE64_OUT(b64[a >> 2]);                                              \
209
    BASE64_OUT(b64[((a & 3) << 4) | (b >> 4)]);                           \
210
    if (i + 1 < src_len) {                                                \
211
      BASE64_OUT(b64[(b & 15) << 2 | (c >> 6)]);                          \
212
    }                                                                     \
213
    if (i + 2 < src_len) {                                                \
214
      BASE64_OUT(b64[c & 63]);                                            \
215
    }                                                                     \
216
  }                                                                       \
217
                                                                          \
218
  while (j % 4 != 0) {                                                    \
219
    BASE64_OUT('=');                                                      \
220
  }                                                                       \
221
  BASE64_FLUSH()
222

    
223
#define BASE64_OUT(ch) \
224
  do {                 \
225
    dst[j++] = (ch);   \
226
  } while (0)
227

    
228
#define BASE64_FLUSH() \
229
  do {                 \
230
    dst[j++] = '\0';   \
231
  } while (0)
232

    
233
void cs_base64_encode(const unsigned char *src, int src_len, char *dst) {
234
  BASE64_ENCODE_BODY;
235
}
236

    
237
#undef BASE64_OUT
238
#undef BASE64_FLUSH
239

    
240
#define BASE64_OUT(ch)      \
241
  do {                      \
242
    fprintf(f, "%c", (ch)); \
243
    j++;                    \
244
  } while (0)
245

    
246
#define BASE64_FLUSH()
247

    
248
void cs_fprint_base64(FILE *f, const unsigned char *src, int src_len) {
249
  BASE64_ENCODE_BODY;
250
}
251

    
252
#undef BASE64_OUT
253
#undef BASE64_FLUSH
254

    
255
/* Convert one byte of encoded base64 input stream to 6-bit chunk */
256
static unsigned char from_b64(unsigned char ch) {
257
  /* Inverse lookup map */
258
  static const unsigned char tab[128] = {
259
      255, 255, 255, 255,
260
      255, 255, 255, 255, /*  0 */
261
      255, 255, 255, 255,
262
      255, 255, 255, 255, /*  8 */
263
      255, 255, 255, 255,
264
      255, 255, 255, 255, /*  16 */
265
      255, 255, 255, 255,
266
      255, 255, 255, 255, /*  24 */
267
      255, 255, 255, 255,
268
      255, 255, 255, 255, /*  32 */
269
      255, 255, 255, 62,
270
      255, 255, 255, 63, /*  40 */
271
      52,  53,  54,  55,
272
      56,  57,  58,  59, /*  48 */
273
      60,  61,  255, 255,
274
      255, 200, 255, 255, /*  56   '=' is 200, on index 61 */
275
      255, 0,   1,   2,
276
      3,   4,   5,   6, /*  64 */
277
      7,   8,   9,   10,
278
      11,  12,  13,  14, /*  72 */
279
      15,  16,  17,  18,
280
      19,  20,  21,  22, /*  80 */
281
      23,  24,  25,  255,
282
      255, 255, 255, 255, /*  88 */
283
      255, 26,  27,  28,
284
      29,  30,  31,  32, /*  96 */
285
      33,  34,  35,  36,
286
      37,  38,  39,  40, /*  104 */
287
      41,  42,  43,  44,
288
      45,  46,  47,  48, /*  112 */
289
      49,  50,  51,  255,
290
      255, 255, 255, 255, /*  120 */
291
  };
292
  return tab[ch & 127];
293
}
294

    
295
int cs_base64_decode(const unsigned char *s, int len, char *dst) {
296
  unsigned char a, b, c, d;
297
  int orig_len = len;
298
  while (len >= 4 && (a = from_b64(s[0])) != 255 &&
299
         (b = from_b64(s[1])) != 255 && (c = from_b64(s[2])) != 255 &&
300
         (d = from_b64(s[3])) != 255) {
301
    s += 4;
302
    len -= 4;
303
    if (a == 200 || b == 200) break; /* '=' can't be there */
304
    *dst++ = a << 2 | b >> 4;
305
    if (c == 200) break;
306
    *dst++ = b << 4 | c >> 2;
307
    if (d == 200) break;
308
    *dst++ = c << 6 | d;
309
  }
310
  *dst = 0;
311
  return orig_len - len;
312
}
313

    
314
#endif /* EXCLUDE_COMMON */
315
#ifdef NS_MODULE_LINES
316
#line 1 "src/../../common/cs_dbg.c"
317
/**/
318
#endif
319
#include <stdarg.h>
320
#include <stdio.h>
321

    
322
void cs_dbg_printf(const char *fmt, ...) {
323
  va_list ap;
324
  va_start(ap, fmt);
325
  vfprintf(stderr, fmt, ap);
326
  va_end(ap);
327
  fputc('\n', stderr);
328
  fflush(stderr);
329
}
330
#ifdef NS_MODULE_LINES
331
#line 1 "src/../../common/dirent.c"
332
/**/
333
#endif
334
/*
335
 * Copyright (c) 2015 Cesanta Software Limited
336
 * All rights reserved
337
 */
338

    
339
#ifndef EXCLUDE_COMMON
340

    
341
/* Amalgamated: #include "osdep.h" */
342

    
343
/*
344
 * This file contains POSIX opendir/closedir/readdir API implementation
345
 * for systems which do not natively support it (e.g. Windows).
346
 */
347

    
348
#ifndef MG_FREE
349
#define MG_FREE free
350
#endif
351

    
352
#ifndef MG_MALLOC
353
#define MG_MALLOC malloc
354
#endif
355

    
356
#ifdef _WIN32
357
DIR *opendir(const char *name) {
358
  DIR *dir = NULL;
359
  wchar_t wpath[MAX_PATH];
360
  DWORD attrs;
361

    
362
  if (name == NULL) {
363
    SetLastError(ERROR_BAD_ARGUMENTS);
364
  } else if ((dir = (DIR *) MG_MALLOC(sizeof(*dir))) == NULL) {
365
    SetLastError(ERROR_NOT_ENOUGH_MEMORY);
366
  } else {
367
    to_wchar(name, wpath, ARRAY_SIZE(wpath));
368
    attrs = GetFileAttributesW(wpath);
369
    if (attrs != 0xFFFFFFFF && (attrs & FILE_ATTRIBUTE_DIRECTORY)) {
370
      (void) wcscat(wpath, L"\\*");
371
      dir->handle = FindFirstFileW(wpath, &dir->info);
372
      dir->result.d_name[0] = '\0';
373
    } else {
374
      MG_FREE(dir);
375
      dir = NULL;
376
    }
377
  }
378

    
379
  return dir;
380
}
381

    
382
int closedir(DIR *dir) {
383
  int result = 0;
384

    
385
  if (dir != NULL) {
386
    if (dir->handle != INVALID_HANDLE_VALUE)
387
      result = FindClose(dir->handle) ? 0 : -1;
388
    MG_FREE(dir);
389
  } else {
390
    result = -1;
391
    SetLastError(ERROR_BAD_ARGUMENTS);
392
  }
393

    
394
  return result;
395
}
396

    
397
struct dirent *readdir(DIR *dir) {
398
  struct dirent *result = 0;
399

    
400
  if (dir) {
401
    if (dir->handle != INVALID_HANDLE_VALUE) {
402
      result = &dir->result;
403
      (void) WideCharToMultiByte(CP_UTF8, 0, dir->info.cFileName, -1,
404
                                 result->d_name, sizeof(result->d_name), NULL,
405
                                 NULL);
406

    
407
      if (!FindNextFileW(dir->handle, &dir->info)) {
408
        (void) FindClose(dir->handle);
409
        dir->handle = INVALID_HANDLE_VALUE;
410
      }
411

    
412
    } else {
413
      SetLastError(ERROR_FILE_NOT_FOUND);
414
    }
415
  } else {
416
    SetLastError(ERROR_BAD_ARGUMENTS);
417
  }
418

    
419
  return result;
420
}
421
#endif
422

    
423
#endif /* EXCLUDE_COMMON */
424
#ifdef NS_MODULE_LINES
425
#line 1 "src/../deps/frozen/frozen.c"
426
/**/
427
#endif
428
/*
429
 * Copyright (c) 2004-2013 Sergey Lyubka <valenok@gmail.com>
430
 * Copyright (c) 2013 Cesanta Software Limited
431
 * All rights reserved
432
 *
433
 * This library is dual-licensed: you can redistribute it and/or modify
434
 * it under the terms of the GNU General Public License version 2 as
435
 * published by the Free Software Foundation. For the terms of this
436
 * license, see <http: *www.gnu.org/licenses/>.
437
 *
438
 * You are free to use this library under the terms of the GNU General
439
 * Public License, but WITHOUT ANY WARRANTY; without even the implied
440
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
441
 * See the GNU General Public License for more details.
442
 *
443
 * Alternatively, you can license this library under a commercial
444
 * license, as set out in <https://www.cesanta.com/license>.
445
 */
446

    
447
#define _CRT_SECURE_NO_WARNINGS /* Disable deprecation warning in VS2005+ */
448

    
449
#include <stdio.h>
450
#include <stdlib.h>
451
#include <string.h>
452
#include <stdarg.h>
453
/* Amalgamated: #include "frozen.h" */
454

    
455
#ifdef _WIN32
456
#define snprintf _snprintf
457
#endif
458

    
459
#ifndef FROZEN_REALLOC
460
#define FROZEN_REALLOC realloc
461
#endif
462

    
463
#ifndef FROZEN_FREE
464
#define FROZEN_FREE free
465
#endif
466

    
467
struct frozen {
468
  const char *end;
469
  const char *cur;
470
  struct json_token *tokens;
471
  int max_tokens;
472
  int num_tokens;
473
  int do_realloc;
474
};
475

    
476
static int parse_object(struct frozen *f);
477
static int parse_value(struct frozen *f);
478

    
479
#define EXPECT(cond, err_code) do { if (!(cond)) return (err_code); } while (0)
480
#define TRY(expr) do { int _n = expr; if (_n < 0) return _n; } while (0)
481
#define END_OF_STRING (-1)
482

    
483
static int left(const struct frozen *f) {
484
  return f->end - f->cur;
485
}
486

    
487
static int is_space(int ch) {
488
  return ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n';
489
}
490

    
491
static void skip_whitespaces(struct frozen *f) {
492
  while (f->cur < f->end && is_space(*f->cur)) f->cur++;
493
}
494

    
495
static int cur(struct frozen *f) {
496
  skip_whitespaces(f);
497
  return f->cur >= f->end ? END_OF_STRING : * (unsigned char *) f->cur;
498
}
499

    
500
static int test_and_skip(struct frozen *f, int expected) {
501
  int ch = cur(f);
502
  if (ch == expected) { f->cur++; return 0; }
503
  return ch == END_OF_STRING ? JSON_STRING_INCOMPLETE : JSON_STRING_INVALID;
504
}
505

    
506
static int is_alpha(int ch) {
507
  return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z');
508
}
509

    
510
static int is_digit(int ch) {
511
  return ch >= '0' && ch <= '9';
512
}
513

    
514
static int is_hex_digit(int ch) {
515
  return is_digit(ch) || (ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F');
516
}
517

    
518
static int get_escape_len(const char *s, int len) {
519
  switch (*s) {
520
    case 'u':
521
      return len < 6 ? JSON_STRING_INCOMPLETE :
522
        is_hex_digit(s[1]) && is_hex_digit(s[2]) &&
523
        is_hex_digit(s[3]) && is_hex_digit(s[4]) ? 5 : JSON_STRING_INVALID;
524
    case '"': case '\\': case '/': case 'b':
525
    case 'f': case 'n': case 'r': case 't':
526
      return len < 2 ? JSON_STRING_INCOMPLETE : 1;
527
    default:
528
      return JSON_STRING_INVALID;
529
  }
530
}
531

    
532
static int capture_ptr(struct frozen *f, const char *ptr, enum json_type type) {
533
  if (f->do_realloc && f->num_tokens >= f->max_tokens) {
534
    int new_size = f->max_tokens == 0 ? 100 : f->max_tokens * 2;
535
    void *p = FROZEN_REALLOC(f->tokens, new_size * sizeof(f->tokens[0]));
536
    if (p == NULL) return JSON_TOKEN_ARRAY_TOO_SMALL;
537
    f->max_tokens = new_size;
538
    f->tokens = (struct json_token *) p;
539
  }
540
  if (f->tokens == NULL || f->max_tokens == 0) return 0;
541
  if (f->num_tokens >= f->max_tokens) return JSON_TOKEN_ARRAY_TOO_SMALL;
542
  f->tokens[f->num_tokens].ptr = ptr;
543
  f->tokens[f->num_tokens].type = type;
544
  f->num_tokens++;
545
  return 0;
546
}
547

    
548
static int capture_len(struct frozen *f, int token_index, const char *ptr) {
549
  if (f->tokens == 0 || f->max_tokens == 0) return 0;
550
  EXPECT(token_index >= 0 && token_index < f->max_tokens, JSON_STRING_INVALID);
551
  f->tokens[token_index].len = ptr - f->tokens[token_index].ptr;
552
  f->tokens[token_index].num_desc = (f->num_tokens - 1) - token_index;
553
  return 0;
554
}
555

    
556
/* identifier = letter { letter | digit | '_' } */
557
static int parse_identifier(struct frozen *f) {
558
  EXPECT(is_alpha(cur(f)), JSON_STRING_INVALID);
559
  TRY(capture_ptr(f, f->cur, JSON_TYPE_STRING));
560
  while (f->cur < f->end &&
561
         (*f->cur == '_' || is_alpha(*f->cur) || is_digit(*f->cur))) {
562
    f->cur++;
563
  }
564
  capture_len(f, f->num_tokens - 1, f->cur);
565
  return 0;
566
}
567

    
568
static int get_utf8_char_len(unsigned char ch) {
569
  if ((ch & 0x80) == 0) return 1;
570
  switch (ch & 0xf0) {
571
    case 0xf0: return 4;
572
    case 0xe0: return 3;
573
    default: return 2;
574
  }
575
}
576

    
577
/* string = '"' { quoted_printable_chars } '"' */
578
static int parse_string(struct frozen *f) {
579
  int n, ch = 0, len = 0;
580
  TRY(test_and_skip(f, '"'));
581
  TRY(capture_ptr(f, f->cur, JSON_TYPE_STRING));
582
  for (; f->cur < f->end; f->cur += len) {
583
    ch = * (unsigned char *) f->cur;
584
    len = get_utf8_char_len((unsigned char) ch);
585
    EXPECT(ch >= 32 && len > 0, JSON_STRING_INVALID);  /* No control chars */
586
    EXPECT(len < left(f), JSON_STRING_INCOMPLETE);
587
    if (ch == '\\') {
588
      EXPECT((n = get_escape_len(f->cur + 1, left(f))) > 0, n);
589
      len += n;
590
    } else if (ch == '"') {
591
      capture_len(f, f->num_tokens - 1, f->cur);
592
      f->cur++;
593
      break;
594
    };
595
  }
596
  return ch == '"' ? 0 : JSON_STRING_INCOMPLETE;
597
}
598

    
599
/* number = [ '-' ] digit+ [ '.' digit+ ] [ ['e'|'E'] ['+'|'-'] digit+ ] */
600
static int parse_number(struct frozen *f) {
601
  int ch = cur(f);
602
  TRY(capture_ptr(f, f->cur, JSON_TYPE_NUMBER));
603
  if (ch == '-') f->cur++;
604
  EXPECT(f->cur < f->end, JSON_STRING_INCOMPLETE);
605
  EXPECT(is_digit(f->cur[0]), JSON_STRING_INVALID);
606
  while (f->cur < f->end && is_digit(f->cur[0])) f->cur++;
607
  if (f->cur < f->end && f->cur[0] == '.') {
608
    f->cur++;
609
    EXPECT(f->cur < f->end, JSON_STRING_INCOMPLETE);
610
    EXPECT(is_digit(f->cur[0]), JSON_STRING_INVALID);
611
    while (f->cur < f->end && is_digit(f->cur[0])) f->cur++;
612
  }
613
  if (f->cur < f->end && (f->cur[0] == 'e' || f->cur[0] == 'E')) {
614
    f->cur++;
615
    EXPECT(f->cur < f->end, JSON_STRING_INCOMPLETE);
616
    if ((f->cur[0] == '+' || f->cur[0] == '-')) f->cur++;
617
    EXPECT(f->cur < f->end, JSON_STRING_INCOMPLETE);
618
    EXPECT(is_digit(f->cur[0]), JSON_STRING_INVALID);
619
    while (f->cur < f->end && is_digit(f->cur[0])) f->cur++;
620
  }
621
  capture_len(f, f->num_tokens - 1, f->cur);
622
  return 0;
623
}
624

    
625
/* array = '[' [ value { ',' value } ] ']' */
626
static int parse_array(struct frozen *f) {
627
  int ind;
628
  TRY(test_and_skip(f, '['));
629
  TRY(capture_ptr(f, f->cur - 1, JSON_TYPE_ARRAY));
630
  ind = f->num_tokens - 1;
631
  while (cur(f) != ']') {
632
    TRY(parse_value(f));
633
    if (cur(f) == ',') f->cur++;
634
  }
635
  TRY(test_and_skip(f, ']'));
636
  capture_len(f, ind, f->cur);
637
  return 0;
638
}
639

    
640
static int compare(const char *s, const char *str, int len) {
641
  int i = 0;
642
  while (i < len && s[i] == str[i]) i++;
643
  return i == len ? 1 : 0;
644
}
645

    
646
static int expect(struct frozen *f, const char *s, int len, enum json_type t) {
647
  int i, n = left(f);
648

    
649
  TRY(capture_ptr(f, f->cur, t));
650
  for (i = 0; i < len; i++) {
651
    if (i >= n) return JSON_STRING_INCOMPLETE;
652
    if (f->cur[i] != s[i]) return JSON_STRING_INVALID;
653
  }
654
  f->cur += len;
655
  TRY(capture_len(f, f->num_tokens - 1, f->cur));
656

    
657
  return 0;
658
}
659

    
660
/* value = 'null' | 'true' | 'false' | number | string | array | object */
661
static int parse_value(struct frozen *f) {
662
  int ch = cur(f);
663

    
664
  switch (ch) {
665
    case '"': TRY(parse_string(f)); break;
666
    case '{': TRY(parse_object(f)); break;
667
    case '[': TRY(parse_array(f)); break;
668
    case 'n': TRY(expect(f, "null", 4, JSON_TYPE_NULL)); break;
669
    case 't': TRY(expect(f, "true", 4, JSON_TYPE_TRUE)); break;
670
    case 'f': TRY(expect(f, "false", 5, JSON_TYPE_FALSE)); break;
671
    case '-': case '0': case '1': case '2': case '3': case '4':
672
    case '5': case '6': case '7': case '8': case '9':
673
      TRY(parse_number(f));
674
      break;
675
    default:
676
      return ch == END_OF_STRING ? JSON_STRING_INCOMPLETE : JSON_STRING_INVALID;
677
  }
678

    
679
  return 0;
680
}
681

    
682
/* key = identifier | string */
683
static int parse_key(struct frozen *f) {
684
  int ch = cur(f);
685
#if 0
686
  printf("%s 1 [%.*s]\n", __func__, (int) (f->end - f->cur), f->cur);
687
#endif
688
  if (is_alpha(ch)) {
689
    TRY(parse_identifier(f));
690
  } else if (ch == '"') {
691
    TRY(parse_string(f));
692
  } else {
693
    return ch == END_OF_STRING ? JSON_STRING_INCOMPLETE : JSON_STRING_INVALID;
694
  }
695
  return 0;
696
}
697

    
698
/* pair = key ':' value */
699
static int parse_pair(struct frozen *f) {
700
  TRY(parse_key(f));
701
  TRY(test_and_skip(f, ':'));
702
  TRY(parse_value(f));
703
  return 0;
704
}
705

    
706
/* object = '{' pair { ',' pair } '}' */
707
static int parse_object(struct frozen *f) {
708
  int ind;
709
  TRY(test_and_skip(f, '{'));
710
  TRY(capture_ptr(f, f->cur - 1, JSON_TYPE_OBJECT));
711
  ind = f->num_tokens - 1;
712
  while (cur(f) != '}') {
713
    TRY(parse_pair(f));
714
    if (cur(f) == ',') f->cur++;
715
  }
716
  TRY(test_and_skip(f, '}'));
717
  capture_len(f, ind, f->cur);
718
  return 0;
719
}
720

    
721
static int doit(struct frozen *f) {
722
  if (f->cur == 0 || f->end < f->cur) return JSON_STRING_INVALID;
723
  if (f->end == f->cur) return JSON_STRING_INCOMPLETE;
724
  TRY(parse_object(f));
725
  TRY(capture_ptr(f, f->cur, JSON_TYPE_EOF));
726
  capture_len(f, f->num_tokens, f->cur);
727
  return 0;
728
}
729

    
730
/* json = object */
731
int parse_json(const char *s, int s_len, struct json_token *arr, int arr_len) {
732
  struct frozen frozen;
733

    
734
  memset(&frozen, 0, sizeof(frozen));
735
  frozen.end = s + s_len;
736
  frozen.cur = s;
737
  frozen.tokens = arr;
738
  frozen.max_tokens = arr_len;
739

    
740
  TRY(doit(&frozen));
741

    
742
  return frozen.cur - s;
743
}
744

    
745
struct json_token *parse_json2(const char *s, int s_len) {
746
  struct frozen frozen;
747

    
748
  memset(&frozen, 0, sizeof(frozen));
749
  frozen.end = s + s_len;
750
  frozen.cur = s;
751
  frozen.do_realloc = 1;
752

    
753
  if (doit(&frozen) < 0) {
754
    FROZEN_FREE((void *) frozen.tokens);
755
    frozen.tokens = NULL;
756
  }
757
  return frozen.tokens;
758
}
759

    
760
static int path_part_len(const char *p) {
761
  int i = 0;
762
  while (p[i] != '\0' && p[i] != '[' && p[i] != '.') i++;
763
  return i;
764
}
765

    
766
struct json_token *find_json_token(struct json_token *toks, const char *path) {
767
  while (path != 0 && path[0] != '\0') {
768
    int i, ind2 = 0, ind = -1, skip = 2, n = path_part_len(path);
769
    if (path[0] == '[') {
770
      if (toks->type != JSON_TYPE_ARRAY || !is_digit(path[1])) return 0;
771
      for (ind = 0, n = 1; path[n] != ']' && path[n] != '\0'; n++) {
772
        if (!is_digit(path[n])) return 0;
773
        ind *= 10;
774
        ind += path[n] - '0';
775
      }
776
      if (path[n++] != ']') return 0;
777
      skip = 1;  /* In objects, we skip 2 elems while iterating, in arrays 1. */
778
    } else if (toks->type != JSON_TYPE_OBJECT) return 0;
779
    toks++;
780
    for (i = 0; i < toks[-1].num_desc; i += skip, ind2++) {
781
      /* ind == -1 indicated that we're iterating an array, not object */
782
      if (ind == -1 && toks[i].type != JSON_TYPE_STRING) return 0;
783
      if (ind2 == ind ||
784
          (ind == -1 && toks[i].len == n && compare(path, toks[i].ptr, n))) {
785
        i += skip - 1;
786
        break;
787
      };
788
      if (toks[i - 1 + skip].type == JSON_TYPE_ARRAY ||
789
          toks[i - 1 + skip].type == JSON_TYPE_OBJECT) {
790
        i += toks[i - 1 + skip].num_desc;
791
      }
792
    }
793
    if (i == toks[-1].num_desc) return 0;
794
    path += n;
795
    if (path[0] == '.') path++;
796
    if (path[0] == '\0') return &toks[i];
797
    toks += i;
798
  }
799
  return 0;
800
}
801

    
802
int json_emit_long(char *buf, int buf_len, long int value) {
803
  char tmp[20];
804
  int n = snprintf(tmp, sizeof(tmp), "%ld", value);
805
  strncpy(buf, tmp, buf_len > 0 ? buf_len : 0);
806
  return n;
807
}
808

    
809
int json_emit_double(char *buf, int buf_len, double value) {
810
  char tmp[20];
811
  int n = snprintf(tmp, sizeof(tmp), "%g", value);
812
  strncpy(buf, tmp, buf_len > 0 ? buf_len : 0);
813
  return n;
814
}
815

    
816
int json_emit_quoted_str(char *s, int s_len, const char *str, int len) {
817
  const char *begin = s, *end = s + s_len, *str_end = str + len;
818
  char ch;
819

    
820
#define EMIT(x) do { if (s < end) *s = x; s++; } while (0)
821

    
822
  EMIT('"');
823
  while (str < str_end) {
824
    ch = *str++;
825
    switch (ch) {
826
      case '"':  EMIT('\\'); EMIT('"'); break;
827
      case '\\': EMIT('\\'); EMIT('\\'); break;
828
      case '\b': EMIT('\\'); EMIT('b'); break;
829
      case '\f': EMIT('\\'); EMIT('f'); break;
830
      case '\n': EMIT('\\'); EMIT('n'); break;
831
      case '\r': EMIT('\\'); EMIT('r'); break;
832
      case '\t': EMIT('\\'); EMIT('t'); break;
833
      default: EMIT(ch);
834
    }
835
  }
836
  EMIT('"');
837
  if (s < end) {
838
    *s = '\0';
839
  }
840

    
841
  return s - begin;
842
}
843

    
844
int json_emit_unquoted_str(char *buf, int buf_len, const char *str, int len) {
845
  if (buf_len > 0 && len > 0) {
846
    int n = len < buf_len ? len : buf_len;
847
    memcpy(buf, str, n);
848
    if (n < buf_len) {
849
      buf[n] = '\0';
850
    }
851
  }
852
  return len;
853
}
854

    
855
int json_emit_va(char *s, int s_len, const char *fmt, va_list ap) {
856
  const char *end = s + s_len, *str, *orig = s;
857
  size_t len;
858

    
859
  while (*fmt != '\0') {
860
    switch (*fmt) {
861
      case '[': case ']': case '{': case '}': case ',': case ':':
862
      case ' ': case '\r': case '\n': case '\t':
863
        if (s < end) {
864
          *s = *fmt;
865
        }
866
        s++;
867
        break;
868
      case 'i':
869
        s += json_emit_long(s, end - s, va_arg(ap, long));
870
        break;
871
      case 'f':
872
        s += json_emit_double(s, end - s, va_arg(ap, double));
873
        break;
874
      case 'v':
875
        str = va_arg(ap, char *);
876
        len = va_arg(ap, size_t);
877
        s += json_emit_quoted_str(s, end - s, str, len);
878
        break;
879
      case 'V':
880
        str = va_arg(ap, char *);
881
        len = va_arg(ap, size_t);
882
        s += json_emit_unquoted_str(s, end - s, str, len);
883
        break;
884
      case 's':
885
        str = va_arg(ap, char *);
886
        s += json_emit_quoted_str(s, end - s, str, strlen(str));
887
        break;
888
      case 'S':
889
        str = va_arg(ap, char *);
890
        s += json_emit_unquoted_str(s, end - s, str, strlen(str));
891
        break;
892
      case 'T':
893
        s += json_emit_unquoted_str(s, end - s, "true", 4);
894
        break;
895
      case 'F':
896
        s += json_emit_unquoted_str(s, end - s, "false", 5);
897
        break;
898
      case 'N':
899
        s += json_emit_unquoted_str(s, end - s, "null", 4);
900
        break;
901
      default:
902
        return 0;
903
    }
904
    fmt++;
905
  }
906

    
907
  /* Best-effort to 0-terminate generated string */
908
  if (s < end) {
909
    *s = '\0';
910
  }
911

    
912
  return s - orig;
913
}
914

    
915
int json_emit(char *buf, int buf_len, const char *fmt, ...) {
916
  int len;
917
  va_list ap;
918

    
919
  va_start(ap, fmt);
920
  len = json_emit_va(buf, buf_len, fmt, ap);
921
  va_end(ap);
922

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

    
946
#if !defined(DISABLE_MD5) && !defined(EXCLUDE_COMMON)
947

    
948
/* Amalgamated: #include "md5.h" */
949

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

    
966
#define F1(x, y, z) (z ^ (x & (y ^ z)))
967
#define F2(x, y, z) F1(z, x, y)
968
#define F3(x, y, z) (x ^ y ^ z)
969
#define F4(x, y, z) (y ^ (x | ~z))
970

    
971
#define MD5STEP(f, w, x, y, z, data, s) \
972
  (w += f(x, y, z) + data, w = w << s | w >> (32 - s), w += x)
973

    
974
/*
975
 * Start MD5 accumulation.  Set bit count to 0 and buffer to mysterious
976
 * initialization constants.
977
 */
978
void MD5_Init(MD5_CTX *ctx) {
979
  ctx->buf[0] = 0x67452301;
980
  ctx->buf[1] = 0xefcdab89;
981
  ctx->buf[2] = 0x98badcfe;
982
  ctx->buf[3] = 0x10325476;
983

    
984
  ctx->bits[0] = 0;
985
  ctx->bits[1] = 0;
986
}
987

    
988
static void MD5Transform(uint32_t buf[4], uint32_t const in[16]) {
989
  register uint32_t a, b, c, d;
990

    
991
  a = buf[0];
992
  b = buf[1];
993
  c = buf[2];
994
  d = buf[3];
995

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

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

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

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

    
1064
  buf[0] += a;
1065
  buf[1] += b;
1066
  buf[2] += c;
1067
  buf[3] += d;
1068
}
1069

    
1070
void MD5_Update(MD5_CTX *ctx, const unsigned char *buf, size_t len) {
1071
  uint32_t t;
1072

    
1073
  t = ctx->bits[0];
1074
  if ((ctx->bits[0] = t + ((uint32_t) len << 3)) < t) ctx->bits[1]++;
1075
  ctx->bits[1] += (uint32_t) len >> 29;
1076

    
1077
  t = (t >> 3) & 0x3f;
1078

    
1079
  if (t) {
1080
    unsigned char *p = (unsigned char *) ctx->in + t;
1081

    
1082
    t = 64 - t;
1083
    if (len < t) {
1084
      memcpy(p, buf, len);
1085
      return;
1086
    }
1087
    memcpy(p, buf, t);
1088
    byteReverse(ctx->in, 16);
1089
    MD5Transform(ctx->buf, (uint32_t *) ctx->in);
1090
    buf += t;
1091
    len -= t;
1092
  }
1093

    
1094
  while (len >= 64) {
1095
    memcpy(ctx->in, buf, 64);
1096
    byteReverse(ctx->in, 16);
1097
    MD5Transform(ctx->buf, (uint32_t *) ctx->in);
1098
    buf += 64;
1099
    len -= 64;
1100
  }
1101

    
1102
  memcpy(ctx->in, buf, len);
1103
}
1104

    
1105
void MD5_Final(unsigned char digest[16], MD5_CTX *ctx) {
1106
  unsigned count;
1107
  unsigned char *p;
1108
  uint32_t *a;
1109

    
1110
  count = (ctx->bits[0] >> 3) & 0x3F;
1111

    
1112
  p = ctx->in + count;
1113
  *p++ = 0x80;
1114
  count = 64 - 1 - count;
1115
  if (count < 8) {
1116
    memset(p, 0, count);
1117
    byteReverse(ctx->in, 16);
1118
    MD5Transform(ctx->buf, (uint32_t *) ctx->in);
1119
    memset(ctx->in, 0, 56);
1120
  } else {
1121
    memset(p, 0, count - 8);
1122
  }
1123
  byteReverse(ctx->in, 14);
1124

    
1125
  a = (uint32_t *) ctx->in;
1126
  a[14] = ctx->bits[0];
1127
  a[15] = ctx->bits[1];
1128

    
1129
  MD5Transform(ctx->buf, (uint32_t *) ctx->in);
1130
  byteReverse((unsigned char *) ctx->buf, 4);
1131
  memcpy(digest, ctx->buf, 16);
1132
  memset((char *) ctx, 0, sizeof(*ctx));
1133
}
1134
#endif /* CS_ENABLE_NATIVE_MD5 */
1135

    
1136
/*
1137
 * Stringify binary data. Output buffer size must be 2 * size_of_input + 1
1138
 * because each byte of input takes 2 bytes in string representation
1139
 * plus 1 byte for the terminating \0 character.
1140
 */
1141
void cs_to_hex(char *to, const unsigned char *p, size_t len) {
1142
  static const char *hex = "0123456789abcdef";
1143

    
1144
  for (; len--; p++) {
1145
    *to++ = hex[p[0] >> 4];
1146
    *to++ = hex[p[0] & 0x0f];
1147
  }
1148
  *to = '\0';
1149
}
1150

    
1151
char *cs_md5(char buf[33], ...) {
1152
  unsigned char hash[16];
1153
  const unsigned char *p;
1154
  va_list ap;
1155
  MD5_CTX ctx;
1156

    
1157
  MD5_Init(&ctx);
1158

    
1159
  va_start(ap, buf);
1160
  while ((p = va_arg(ap, const unsigned char *) ) != NULL) {
1161
    size_t len = va_arg(ap, size_t);
1162
    MD5_Update(&ctx, p, len);
1163
  }
1164
  va_end(ap);
1165

    
1166
  MD5_Final(hash, &ctx);
1167
  cs_to_hex(buf, hash, sizeof(hash));
1168

    
1169
  return buf;
1170
}
1171

    
1172
#endif /* EXCLUDE_COMMON */
1173
#ifdef NS_MODULE_LINES
1174
#line 1 "src/../../common/mbuf.c"
1175
/**/
1176
#endif
1177
/*
1178
 * Copyright (c) 2014 Cesanta Software Limited
1179
 * All rights reserved
1180
 */
1181

    
1182
#ifndef EXCLUDE_COMMON
1183

    
1184
#include <assert.h>
1185
#include <string.h>
1186
/* Amalgamated: #include "mbuf.h" */
1187

    
1188
#ifndef MBUF_REALLOC
1189
#define MBUF_REALLOC realloc
1190
#endif
1191

    
1192
#ifndef MBUF_FREE
1193
#define MBUF_FREE free
1194
#endif
1195

    
1196
void mbuf_init(struct mbuf *mbuf, size_t initial_size) {
1197
  mbuf->len = mbuf->size = 0;
1198
  mbuf->buf = NULL;
1199
  mbuf_resize(mbuf, initial_size);
1200
}
1201

    
1202
void mbuf_free(struct mbuf *mbuf) {
1203
  if (mbuf->buf != NULL) {
1204
    MBUF_FREE(mbuf->buf);
1205
    mbuf_init(mbuf, 0);
1206
  }
1207
}
1208

    
1209
void mbuf_resize(struct mbuf *a, size_t new_size) {
1210
  if (new_size > a->size || (new_size < a->size && new_size >= a->len)) {
1211
    char *buf = (char *) MBUF_REALLOC(a->buf, new_size);
1212
    /*
1213
     * In case realloc fails, there's not much we can do, except keep things as
1214
     * they are. Note that NULL is a valid return value from realloc when
1215
     * size == 0, but that is covered too.
1216
     */
1217
    if (buf == NULL && new_size != 0) return;
1218
    a->buf = buf;
1219
    a->size = new_size;
1220
  }
1221
}
1222

    
1223
void mbuf_trim(struct mbuf *mbuf) {
1224
  mbuf_resize(mbuf, mbuf->len);
1225
}
1226

    
1227
size_t mbuf_insert(struct mbuf *a, size_t off, const void *buf, size_t len) {
1228
  char *p = NULL;
1229

    
1230
  assert(a != NULL);
1231
  assert(a->len <= a->size);
1232
  assert(off <= a->len);
1233

    
1234
  /* check overflow */
1235
  if (~(size_t) 0 - (size_t) a->buf < len) return 0;
1236

    
1237
  if (a->len + len <= a->size) {
1238
    memmove(a->buf + off + len, a->buf + off, a->len - off);
1239
    if (buf != NULL) {
1240
      memcpy(a->buf + off, buf, len);
1241
    }
1242
    a->len += len;
1243
  } else if ((p = (char *) MBUF_REALLOC(
1244
                  a->buf, (a->len + len) * MBUF_SIZE_MULTIPLIER)) != NULL) {
1245
    a->buf = p;
1246
    memmove(a->buf + off + len, a->buf + off, a->len - off);
1247
    if (buf != NULL) {
1248
      memcpy(a->buf + off, buf, len);
1249
    }
1250
    a->len += len;
1251
    a->size = a->len * MBUF_SIZE_MULTIPLIER;
1252
  } else {
1253
    len = 0;
1254
  }
1255

    
1256
  return len;
1257
}
1258

    
1259
size_t mbuf_append(struct mbuf *a, const void *buf, size_t len) {
1260
  return mbuf_insert(a, a->len, buf, len);
1261
}
1262

    
1263
void mbuf_remove(struct mbuf *mb, size_t n) {
1264
  if (n > 0 && n <= mb->len) {
1265
    memmove(mb->buf, mb->buf + n, mb->len - n);
1266
    mb->len -= n;
1267
  }
1268
}
1269

    
1270
#endif /* EXCLUDE_COMMON */
1271
#ifdef NS_MODULE_LINES
1272
#line 1 "src/../../common/sha1.c"
1273
/**/
1274
#endif
1275
/* Copyright(c) By Steve Reid <steve@edmweb.com> */
1276
/* 100% Public Domain */
1277

    
1278
#if !defined(DISABLE_SHA1) && !defined(EXCLUDE_COMMON)
1279

    
1280
/* Amalgamated: #include "sha1.h" */
1281

    
1282
#define SHA1HANDSOFF
1283
#if defined(__sun)
1284
/* Amalgamated: #include "solarisfixes.h" */
1285
#endif
1286

    
1287
union char64long16 {
1288
  unsigned char c[64];
1289
  uint32_t l[16];
1290
};
1291

    
1292
#define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
1293

    
1294
static uint32_t blk0(union char64long16 *block, int i) {
1295
/* Forrest: SHA expect BIG_ENDIAN, swap if LITTLE_ENDIAN */
1296
#if BYTE_ORDER == LITTLE_ENDIAN
1297
  block->l[i] =
1298
      (rol(block->l[i], 24) & 0xFF00FF00) | (rol(block->l[i], 8) & 0x00FF00FF);
1299
#endif
1300
  return block->l[i];
1301
}
1302

    
1303
/* Avoid redefine warning (ARM /usr/include/sys/ucontext.h define R0~R4) */
1304
#undef blk
1305
#undef R0
1306
#undef R1
1307
#undef R2
1308
#undef R3
1309
#undef R4
1310

    
1311
#define blk(i)                                                               \
1312
  (block->l[i & 15] = rol(block->l[(i + 13) & 15] ^ block->l[(i + 8) & 15] ^ \
1313
                              block->l[(i + 2) & 15] ^ block->l[i & 15],     \
1314
                          1))
1315
#define R0(v, w, x, y, z, i)                                          \
1316
  z += ((w & (x ^ y)) ^ y) + blk0(block, i) + 0x5A827999 + rol(v, 5); \
1317
  w = rol(w, 30);
1318
#define R1(v, w, x, y, z, i)                                  \
1319
  z += ((w & (x ^ y)) ^ y) + blk(i) + 0x5A827999 + rol(v, 5); \
1320
  w = rol(w, 30);
1321
#define R2(v, w, x, y, z, i)                          \
1322
  z += (w ^ x ^ y) + blk(i) + 0x6ED9EBA1 + rol(v, 5); \
1323
  w = rol(w, 30);
1324
#define R3(v, w, x, y, z, i)                                        \
1325
  z += (((w | x) & y) | (w & x)) + blk(i) + 0x8F1BBCDC + rol(v, 5); \
1326
  w = rol(w, 30);
1327
#define R4(v, w, x, y, z, i)                          \
1328
  z += (w ^ x ^ y) + blk(i) + 0xCA62C1D6 + rol(v, 5); \
1329
  w = rol(w, 30);
1330

    
1331
void cs_sha1_transform(uint32_t state[5], const unsigned char buffer[64]) {
1332
  uint32_t a, b, c, d, e;
1333
  union char64long16 block[1];
1334

    
1335
  memcpy(block, buffer, 64);
1336
  a = state[0];
1337
  b = state[1];
1338
  c = state[2];
1339
  d = state[3];
1340
  e = state[4];
1341
  R0(a, b, c, d, e, 0);
1342
  R0(e, a, b, c, d, 1);
1343
  R0(d, e, a, b, c, 2);
1344
  R0(c, d, e, a, b, 3);
1345
  R0(b, c, d, e, a, 4);
1346
  R0(a, b, c, d, e, 5);
1347
  R0(e, a, b, c, d, 6);
1348
  R0(d, e, a, b, c, 7);
1349
  R0(c, d, e, a, b, 8);
1350
  R0(b, c, d, e, a, 9);
1351
  R0(a, b, c, d, e, 10);
1352
  R0(e, a, b, c, d, 11);
1353
  R0(d, e, a, b, c, 12);
1354
  R0(c, d, e, a, b, 13);
1355
  R0(b, c, d, e, a, 14);
1356
  R0(a, b, c, d, e, 15);
1357
  R1(e, a, b, c, d, 16);
1358
  R1(d, e, a, b, c, 17);
1359
  R1(c, d, e, a, b, 18);
1360
  R1(b, c, d, e, a, 19);
1361
  R2(a, b, c, d, e, 20);
1362
  R2(e, a, b, c, d, 21);
1363
  R2(d, e, a, b, c, 22);
1364
  R2(c, d, e, a, b, 23);
1365
  R2(b, c, d, e, a, 24);
1366
  R2(a, b, c, d, e, 25);
1367
  R2(e, a, b, c, d, 26);
1368
  R2(d, e, a, b, c, 27);
1369
  R2(c, d, e, a, b, 28);
1370
  R2(b, c, d, e, a, 29);
1371
  R2(a, b, c, d, e, 30);
1372
  R2(e, a, b, c, d, 31);
1373
  R2(d, e, a, b, c, 32);
1374
  R2(c, d, e, a, b, 33);
1375
  R2(b, c, d, e, a, 34);
1376
  R2(a, b, c, d, e, 35);
1377
  R2(e, a, b, c, d, 36);
1378
  R2(d, e, a, b, c, 37);
1379
  R2(c, d, e, a, b, 38);
1380
  R2(b, c, d, e, a, 39);
1381
  R3(a, b, c, d, e, 40);
1382
  R3(e, a, b, c, d, 41);
1383
  R3(d, e, a, b, c, 42);
1384
  R3(c, d, e, a, b, 43);
1385
  R3(b, c, d, e, a, 44);
1386
  R3(a, b, c, d, e, 45);
1387
  R3(e, a, b, c, d, 46);
1388
  R3(d, e, a, b, c, 47);
1389
  R3(c, d, e, a, b, 48);
1390
  R3(b, c, d, e, a, 49);
1391
  R3(a, b, c, d, e, 50);
1392
  R3(e, a, b, c, d, 51);
1393
  R3(d, e, a, b, c, 52);
1394
  R3(c, d, e, a, b, 53);
1395
  R3(b, c, d, e, a, 54);
1396
  R3(a, b, c, d, e, 55);
1397
  R3(e, a, b, c, d, 56);
1398
  R3(d, e, a, b, c, 57);
1399
  R3(c, d, e, a, b, 58);
1400
  R3(b, c, d, e, a, 59);
1401
  R4(a, b, c, d, e, 60);
1402
  R4(e, a, b, c, d, 61);
1403
  R4(d, e, a, b, c, 62);
1404
  R4(c, d, e, a, b, 63);
1405
  R4(b, c, d, e, a, 64);
1406
  R4(a, b, c, d, e, 65);
1407
  R4(e, a, b, c, d, 66);
1408
  R4(d, e, a, b, c, 67);
1409
  R4(c, d, e, a, b, 68);
1410
  R4(b, c, d, e, a, 69);
1411
  R4(a, b, c, d, e, 70);
1412
  R4(e, a, b, c, d, 71);
1413
  R4(d, e, a, b, c, 72);
1414
  R4(c, d, e, a, b, 73);
1415
  R4(b, c, d, e, a, 74);
1416
  R4(a, b, c, d, e, 75);
1417
  R4(e, a, b, c, d, 76);
1418
  R4(d, e, a, b, c, 77);
1419
  R4(c, d, e, a, b, 78);
1420
  R4(b, c, d, e, a, 79);
1421
  state[0] += a;
1422
  state[1] += b;
1423
  state[2] += c;
1424
  state[3] += d;
1425
  state[4] += e;
1426
  /* Erase working structures. The order of operations is important,
1427
   * used to ensure that compiler doesn't optimize those out. */
1428
  memset(block, 0, sizeof(block));
1429
  a = b = c = d = e = 0;
1430
  (void) a;
1431
  (void) b;
1432
  (void) c;
1433
  (void) d;
1434
  (void) e;
1435
}
1436

    
1437
void cs_sha1_init(cs_sha1_ctx *context) {
1438
  context->state[0] = 0x67452301;
1439
  context->state[1] = 0xEFCDAB89;
1440
  context->state[2] = 0x98BADCFE;
1441
  context->state[3] = 0x10325476;
1442
  context->state[4] = 0xC3D2E1F0;
1443
  context->count[0] = context->count[1] = 0;
1444
}
1445

    
1446
void cs_sha1_update(cs_sha1_ctx *context, const unsigned char *data,
1447
                    uint32_t len) {
1448
  uint32_t i, j;
1449

    
1450
  j = context->count[0];
1451
  if ((context->count[0] += len << 3) < j) context->count[1]++;
1452
  context->count[1] += (len >> 29);
1453
  j = (j >> 3) & 63;
1454
  if ((j + len) > 63) {
1455
    memcpy(&context->buffer[j], data, (i = 64 - j));
1456
    cs_sha1_transform(context->state, context->buffer);
1457
    for (; i + 63 < len; i += 64) {
1458
      cs_sha1_transform(context->state, &data[i]);
1459
    }
1460
    j = 0;
1461
  } else
1462
    i = 0;
1463
  memcpy(&context->buffer[j], &data[i], len - i);
1464
}
1465

    
1466
void cs_sha1_final(unsigned char digest[20], cs_sha1_ctx *context) {
1467
  unsigned i;
1468
  unsigned char finalcount[8], c;
1469

    
1470
  for (i = 0; i < 8; i++) {
1471
    finalcount[i] = (unsigned char) ((context->count[(i >= 4 ? 0 : 1)] >>
1472
                                      ((3 - (i & 3)) * 8)) &
1473
                                     255);
1474
  }
1475
  c = 0200;
1476
  cs_sha1_update(context, &c, 1);
1477
  while ((context->count[0] & 504) != 448) {
1478
    c = 0000;
1479
    cs_sha1_update(context, &c, 1);
1480
  }
1481
  cs_sha1_update(context, finalcount, 8);
1482
  for (i = 0; i < 20; i++) {
1483
    digest[i] =
1484
        (unsigned char) ((context->state[i >> 2] >> ((3 - (i & 3)) * 8)) & 255);
1485
  }
1486
  memset(context, '\0', sizeof(*context));
1487
  memset(&finalcount, '\0', sizeof(finalcount));
1488
}
1489

    
1490
void cs_hmac_sha1(const unsigned char *key, size_t keylen,
1491
                  const unsigned char *data, size_t datalen,
1492
                  unsigned char out[20]) {
1493
  cs_sha1_ctx ctx;
1494
  unsigned char buf1[64], buf2[64], tmp_key[20], i;
1495

    
1496
  if (keylen > sizeof(buf1)) {
1497
    cs_sha1_init(&ctx);
1498
    cs_sha1_update(&ctx, key, keylen);
1499
    cs_sha1_final(tmp_key, &ctx);
1500
    key = tmp_key;
1501
    keylen = sizeof(tmp_key);
1502
  }
1503

    
1504
  memset(buf1, 0, sizeof(buf1));
1505
  memset(buf2, 0, sizeof(buf2));
1506
  memcpy(buf1, key, keylen);
1507
  memcpy(buf2, key, keylen);
1508

    
1509
  for (i = 0; i < sizeof(buf1); i++) {
1510
    buf1[i] ^= 0x36;
1511
    buf2[i] ^= 0x5c;
1512
  }
1513

    
1514
  cs_sha1_init(&ctx);
1515
  cs_sha1_update(&ctx, buf1, sizeof(buf1));
1516
  cs_sha1_update(&ctx, data, datalen);
1517
  cs_sha1_final(out, &ctx);
1518

    
1519
  cs_sha1_init(&ctx);
1520
  cs_sha1_update(&ctx, buf2, sizeof(buf2));
1521
  cs_sha1_update(&ctx, out, 20);
1522
  cs_sha1_final(out, &ctx);
1523
}
1524

    
1525
#endif /* EXCLUDE_COMMON */
1526
#ifdef NS_MODULE_LINES
1527
#line 1 "src/../../common/str_util.c"
1528
/**/
1529
#endif
1530
/*
1531
 * Copyright (c) 2015 Cesanta Software Limited
1532
 * All rights reserved
1533
 */
1534

    
1535
#ifndef EXCLUDE_COMMON
1536

    
1537
/* Amalgamated: #include "osdep.h" */
1538
/* Amalgamated: #include "str_util.h" */
1539

    
1540
#if !(_XOPEN_SOURCE >= 700 || _POSIX_C_SOURCE >= 200809L) &&    \
1541
        !(__DARWIN_C_LEVEL >= 200809L) && !defined(RTOS_SDK) || \
1542
    defined(_WIN32)
1543
size_t strnlen(const char *s, size_t maxlen) {
1544
  size_t l = 0;
1545
  for (; l < maxlen && s[l] != '\0'; l++) {
1546
  }
1547
  return l;
1548
}
1549
#endif
1550

    
1551
#define C_SNPRINTF_APPEND_CHAR(ch)       \
1552
  do {                                   \
1553
    if (i < (int) buf_size) buf[i] = ch; \
1554
    i++;                                 \
1555
  } while (0)
1556

    
1557
#define C_SNPRINTF_FLAG_ZERO 1
1558

    
1559
#ifdef C_DISABLE_BUILTIN_SNPRINTF
1560
int c_vsnprintf(char *buf, size_t buf_size, const char *fmt, va_list ap) {
1561
  return vsnprintf(buf, buf_size, fmt, ap);
1562
}
1563
#else
1564
static int c_itoa(char *buf, size_t buf_size, int64_t num, int base, int flags,
1565
                  int field_width) {
1566
  char tmp[40];
1567
  int i = 0, k = 0, neg = 0;
1568

    
1569
  if (num < 0) {
1570
    neg++;
1571
    num = -num;
1572
  }
1573

    
1574
  /* Print into temporary buffer - in reverse order */
1575
  do {
1576
    int rem = num % base;
1577
    if (rem < 10) {
1578
      tmp[k++] = '0' + rem;
1579
    } else {
1580
      tmp[k++] = 'a' + (rem - 10);
1581
    }
1582
    num /= base;
1583
  } while (num > 0);
1584

    
1585
  /* Zero padding */
1586
  if (flags && C_SNPRINTF_FLAG_ZERO) {
1587
    while (k < field_width && k < (int) sizeof(tmp) - 1) {
1588
      tmp[k++] = '0';
1589
    }
1590
  }
1591

    
1592
  /* And sign */
1593
  if (neg) {
1594
    tmp[k++] = '-';
1595
  }
1596

    
1597
  /* Now output */
1598
  while (--k >= 0) {
1599
    C_SNPRINTF_APPEND_CHAR(tmp[k]);
1600
  }
1601

    
1602
  return i;
1603
}
1604

    
1605
int c_vsnprintf(char *buf, size_t buf_size, const char *fmt, va_list ap) {
1606
  int ch, i = 0, len_mod, flags, precision, field_width;
1607

    
1608
  while ((ch = *fmt++) != '\0') {
1609
    if (ch != '%') {
1610
      C_SNPRINTF_APPEND_CHAR(ch);
1611
    } else {
1612
      /*
1613
       * Conversion specification:
1614
       *   zero or more flags (one of: # 0 - <space> + ')
1615
       *   an optional minimum  field  width (digits)
1616
       *   an  optional precision (. followed by digits, or *)
1617
       *   an optional length modifier (one of: hh h l ll L q j z t)
1618
       *   conversion specifier (one of: d i o u x X e E f F g G a A c s p n)
1619
       */
1620
      flags = field_width = precision = len_mod = 0;
1621

    
1622
      /* Flags. only zero-pad flag is supported. */
1623
      if (*fmt == '0') {
1624
        flags |= C_SNPRINTF_FLAG_ZERO;
1625
      }
1626

    
1627
      /* Field width */
1628
      while (*fmt >= '0' && *fmt <= '9') {
1629
        field_width *= 10;
1630
        field_width += *fmt++ - '0';
1631
      }
1632
      /* Dynamic field width */
1633
      if (*fmt == '*') {
1634
        field_width = va_arg(ap, int);
1635
        fmt++;
1636
      }
1637

    
1638
      /* Precision */
1639
      if (*fmt == '.') {
1640
        fmt++;
1641
        if (*fmt == '*') {
1642
          precision = va_arg(ap, int);
1643
          fmt++;
1644
        } else {
1645
          while (*fmt >= '0' && *fmt <= '9') {
1646
            precision *= 10;
1647
            precision += *fmt++ - '0';
1648
          }
1649
        }
1650
      }
1651

    
1652
      /* Length modifier */
1653
      switch (*fmt) {
1654
        case 'h':
1655
        case 'l':
1656
        case 'L':
1657
        case 'I':
1658
        case 'q':
1659
        case 'j':
1660
        case 'z':
1661
        case 't':
1662
          len_mod = *fmt++;
1663
          if (*fmt == 'h') {
1664
            len_mod = 'H';
1665
            fmt++;
1666
          }
1667
          if (*fmt == 'l') {
1668
            len_mod = 'q';
1669
            fmt++;
1670
          }
1671
          break;
1672
      }
1673

    
1674
      ch = *fmt++;
1675
      if (ch == 's') {
1676
        const char *s = va_arg(ap, const char *); /* Always fetch parameter */
1677
        int j;
1678
        int pad = field_width - (precision >= 0 ? strnlen(s, precision) : 0);
1679
        for (j = 0; j < pad; j++) {
1680
          C_SNPRINTF_APPEND_CHAR(' ');
1681
        }
1682

    
1683
        /* Ignore negative and 0 precisions */
1684
        for (j = 0; (precision <= 0 || j < precision) && s[j] != '\0'; j++) {
1685
          C_SNPRINTF_APPEND_CHAR(s[j]);
1686
        }
1687
      } else if (ch == 'c') {
1688
        ch = va_arg(ap, int); /* Always fetch parameter */
1689
        C_SNPRINTF_APPEND_CHAR(ch);
1690
      } else if (ch == 'd' && len_mod == 0) {
1691
        i += c_itoa(buf + i, buf_size - i, va_arg(ap, int), 10, flags,
1692
                    field_width);
1693
      } else if (ch == 'd' && len_mod == 'l') {
1694
        i += c_itoa(buf + i, buf_size - i, va_arg(ap, long), 10, flags,
1695
                    field_width);
1696
      } else if ((ch == 'x' || ch == 'u') && len_mod == 0) {
1697
        i += c_itoa(buf + i, buf_size - i, va_arg(ap, unsigned),
1698
                    ch == 'x' ? 16 : 10, flags, field_width);
1699
      } else if ((ch == 'x' || ch == 'u') && len_mod == 'l') {
1700
        i += c_itoa(buf + i, buf_size - i, va_arg(ap, unsigned long),
1701
                    ch == 'x' ? 16 : 10, flags, field_width);
1702
      } else if (ch == 'p') {
1703
        unsigned long num = (unsigned long) va_arg(ap, void *);
1704
        C_SNPRINTF_APPEND_CHAR('0');
1705
        C_SNPRINTF_APPEND_CHAR('x');
1706
        i += c_itoa(buf + i, buf_size - i, num, 16, flags, 0);
1707
      } else {
1708
#ifndef NO_LIBC
1709
        /*
1710
         * TODO(lsm): abort is not nice in a library, remove it
1711
         * Also, ESP8266 SDK doesn't have it
1712
         */
1713
        abort();
1714
#endif
1715
      }
1716
    }
1717
  }
1718

    
1719
  /* Zero-terminate the result */
1720
  if (buf_size > 0) {
1721
    buf[i < (int) buf_size ? i : (int) buf_size - 1] = '\0';
1722
  }
1723

    
1724
  return i;
1725
}
1726
#endif
1727

    
1728
int c_snprintf(char *buf, size_t buf_size, const char *fmt, ...) {
1729
  int result;
1730
  va_list ap;
1731
  va_start(ap, fmt);
1732
  result = c_vsnprintf(buf, buf_size, fmt, ap);
1733
  va_end(ap);
1734
  return result;
1735
}
1736

    
1737
#ifdef _WIN32
1738
void to_wchar(const char *path, wchar_t *wbuf, size_t wbuf_len) {
1739
  char buf[MAX_PATH * 2], buf2[MAX_PATH * 2], *p;
1740

    
1741
  strncpy(buf, path, sizeof(buf));
1742
  buf[sizeof(buf) - 1] = '\0';
1743

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

    
1748
  /*
1749
   * Convert to Unicode and back. If doubly-converted string does not
1750
   * match the original, something is fishy, reject.
1751
   */
1752
  memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
1753
  MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int) wbuf_len);
1754
  WideCharToMultiByte(CP_UTF8, 0, wbuf, (int) wbuf_len, buf2, sizeof(buf2),
1755
                      NULL, NULL);
1756
  if (strcmp(buf, buf2) != 0) {
1757
    wbuf[0] = L'\0';
1758
  }
1759
}
1760
#endif /* _WIN32 */
1761

    
1762
#endif /* EXCLUDE_COMMON */
1763
#ifdef NS_MODULE_LINES
1764
#line 1 "src/net.c"
1765
/**/
1766
#endif
1767
/*
1768
 * Copyright (c) 2014 Cesanta Software Limited
1769
 * All rights reserved
1770
 *
1771
 * This software is dual-licensed: you can redistribute it and/or modify
1772
 * it under the terms of the GNU General Public License version 2 as
1773
 * published by the Free Software Foundation. For the terms of this
1774
 * license, see <http://www.gnu.org/licenses/>.
1775
 *
1776
 * You are free to use this software under the terms of the GNU General
1777
 * Public License, but WITHOUT ANY WARRANTY; without even the implied
1778
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
1779
 * See the GNU General Public License for more details.
1780
 *
1781
 * Alternatively, you can license this software under a commercial
1782
 * license, as set out in <https://www.cesanta.com/license>.
1783
 */
1784

    
1785
/* Amalgamated: #include "internal.h" */
1786

    
1787
#if MG_MGR_EV_MGR == 1 /* epoll() */
1788
#include <sys/epoll.h>
1789
#endif
1790

    
1791
#define MG_CTL_MSG_MESSAGE_SIZE 8192
1792
#define MG_VPRINTF_BUFFER_SIZE 100
1793
#define MG_MAX_HOST_LEN 200
1794

    
1795
#define MG_COPY_COMMON_CONNECTION_OPTIONS(dst, src) \
1796
  memcpy(dst, src, sizeof(*dst));
1797

    
1798
/* Which flags can be pre-set by the user at connection creation time. */
1799
#define _MG_ALLOWED_CONNECT_FLAGS_MASK                                   \
1800
  (MG_F_USER_1 | MG_F_USER_2 | MG_F_USER_3 | MG_F_USER_4 | MG_F_USER_5 | \
1801
   MG_F_USER_6 | MG_F_WEBSOCKET_NO_DEFRAG)
1802
/* Which flags should be modifiable by user's callbacks. */
1803
#define _MG_CALLBACK_MODIFIABLE_FLAGS_MASK                               \
1804
  (MG_F_USER_1 | MG_F_USER_2 | MG_F_USER_3 | MG_F_USER_4 | MG_F_USER_5 | \
1805
   MG_F_USER_6 | MG_F_WEBSOCKET_NO_DEFRAG | MG_F_SEND_AND_CLOSE |        \
1806
   MG_F_CLOSE_IMMEDIATELY | MG_F_IS_WEBSOCKET)
1807

    
1808
#ifndef intptr_t
1809
#define intptr_t long
1810
#endif
1811

    
1812
struct ctl_msg {
1813
  mg_event_handler_t callback;
1814
  char message[MG_CTL_MSG_MESSAGE_SIZE];
1815
};
1816

    
1817
int mg_is_error(int n);
1818
void mg_set_non_blocking_mode(sock_t sock);
1819

    
1820
extern void mg_ev_mgr_init(struct mg_mgr *mgr);
1821
extern void mg_ev_mgr_free(struct mg_mgr *mgr);
1822
extern void mg_ev_mgr_add_conn(struct mg_connection *nc);
1823
extern void mg_ev_mgr_remove_conn(struct mg_connection *nc);
1824

    
1825
MG_INTERNAL void mg_add_conn(struct mg_mgr *mgr, struct mg_connection *c) {
1826
  DBG(("%p %p", mgr, c));
1827
  c->mgr = mgr;
1828
  c->next = mgr->active_connections;
1829
  mgr->active_connections = c;
1830
  c->prev = NULL;
1831
  if (c->next != NULL) c->next->prev = c;
1832
  mg_ev_mgr_add_conn(c);
1833
}
1834

    
1835
MG_INTERNAL void mg_remove_conn(struct mg_connection *conn) {
1836
  if (conn->prev == NULL) conn->mgr->active_connections = conn->next;
1837
  if (conn->prev) conn->prev->next = conn->next;
1838
  if (conn->next) conn->next->prev = conn->prev;
1839
  mg_ev_mgr_remove_conn(conn);
1840
}
1841

    
1842
MG_INTERNAL void mg_call(struct mg_connection *nc,
1843
                         mg_event_handler_t ev_handler, int ev, void *ev_data) {
1844
  unsigned long flags_before;
1845

    
1846
  DBG(("%p ev=%d ev_data=%p flags=%lu rmbl=%d smbl=%d", nc, ev, ev_data,
1847
       nc->flags, (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len));
1848

    
1849
#ifndef MG_DISABLE_FILESYSTEM
1850
  /* LCOV_EXCL_START */
1851
  if (nc->mgr->hexdump_file != NULL && ev != MG_EV_POLL &&
1852
      ev != MG_EV_SEND /* handled separately */) {
1853
    int len = (ev == MG_EV_RECV ? *(int *) ev_data : 0);
1854
    mg_hexdump_connection(nc, nc->mgr->hexdump_file, len, ev);
1855
  }
1856
/* LCOV_EXCL_STOP */
1857
#endif
1858

    
1859
  if (ev_handler == NULL) {
1860
    /*
1861
     * If protocol handler is specified, call it. Otherwise, call user-specified
1862
     * event handler.
1863
     */
1864
    ev_handler = nc->proto_handler ? nc->proto_handler : nc->handler;
1865
  }
1866
  if (ev_handler != NULL) {
1867
    flags_before = nc->flags;
1868
    ev_handler(nc, ev, ev_data);
1869
    if (nc->flags != flags_before) {
1870
      nc->flags = (flags_before & ~_MG_CALLBACK_MODIFIABLE_FLAGS_MASK) |
1871
                  (nc->flags & _MG_CALLBACK_MODIFIABLE_FLAGS_MASK);
1872
    }
1873
  }
1874
  DBG(("%p after flags=%d rmbl=%d smbl=%d", nc, (int) nc->flags,
1875
       (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len));
1876
}
1877

    
1878
void mg_if_poll(struct mg_connection *nc, time_t now) {
1879
  mg_call(nc, NULL, MG_EV_POLL, &now);
1880
}
1881

    
1882
static void mg_destroy_conn(struct mg_connection *conn) {
1883
  mg_if_destroy_conn(conn);
1884
  mbuf_free(&conn->recv_mbuf);
1885
  mbuf_free(&conn->send_mbuf);
1886
  MG_FREE(conn);
1887
}
1888

    
1889
void mg_close_conn(struct mg_connection *conn) {
1890
  DBG(("%p %lu", conn, conn->flags));
1891
  if (!(conn->flags & MG_F_CONNECTING)) {
1892
    mg_call(conn, NULL, MG_EV_CLOSE, NULL);
1893
  }
1894
  mg_remove_conn(conn);
1895
  mg_destroy_conn(conn);
1896
}
1897

    
1898
void mg_mgr_init(struct mg_mgr *m, void *user_data) {
1899
  memset(m, 0, sizeof(*m));
1900
  m->ctl[0] = m->ctl[1] = INVALID_SOCKET;
1901
  m->user_data = user_data;
1902

    
1903
#ifdef _WIN32
1904
  {
1905
    WSADATA data;
1906
    WSAStartup(MAKEWORD(2, 2), &data);
1907
  }
1908
#elif !defined(AVR_LIBC) && !defined(MG_ESP8266)
1909
  /* Ignore SIGPIPE signal, so if client cancels the request, it
1910
   * won't kill the whole process. */
1911
  signal(SIGPIPE, SIG_IGN);
1912
#endif
1913

    
1914
#ifdef MG_ENABLE_SSL
1915
  {
1916
    static int init_done;
1917
    if (!init_done) {
1918
      SSL_library_init();
1919
      init_done++;
1920
    }
1921
  }
1922
#endif
1923

    
1924
  mg_ev_mgr_init(m);
1925
  DBG(("=================================="));
1926
  DBG(("init mgr=%p", m));
1927
}
1928

    
1929
#ifdef MG_ENABLE_JAVASCRIPT
1930
static v7_val_t mg_send_js(struct v7 *v7) {
1931
  v7_val_t arg0 = v7_arg(v7, 0);
1932
  v7_val_t arg1 = v7_arg(v7, 1);
1933
  struct mg_connection *c = (struct mg_connection *) v7_to_foreign(arg0);
1934
  size_t len = 0;
1935

    
1936
  if (v7_is_string(arg1)) {
1937
    const char *data = v7_to_string(v7, &arg1, &len);
1938
    mg_send(c, data, len);
1939
  }
1940

    
1941
  return v7_create_number(len);
1942
}
1943

    
1944
enum v7_err mg_enable_javascript(struct mg_mgr *m, struct v7 *v7,
1945
                                 const char *init_file_name) {
1946
  v7_val_t v;
1947
  m->v7 = v7;
1948
  v7_set_method(v7, v7_get_global(v7), "mg_send", mg_send_js);
1949
  return v7_exec_file(v7, init_file_name, &v);
1950
}
1951
#endif
1952

    
1953
void mg_mgr_free(struct mg_mgr *m) {
1954
  struct mg_connection *conn, *tmp_conn;
1955

    
1956
  DBG(("%p", m));
1957
  if (m == NULL) return;
1958
  /* Do one last poll, see https://github.com/cesanta/mongoose/issues/286 */
1959
  mg_mgr_poll(m, 0);
1960

    
1961
#ifndef MG_DISABLE_SOCKETPAIR
1962
  if (m->ctl[0] != INVALID_SOCKET) closesocket(m->ctl[0]);
1963
  if (m->ctl[1] != INVALID_SOCKET) closesocket(m->ctl[1]);
1964
#endif
1965
  m->ctl[0] = m->ctl[1] = INVALID_SOCKET;
1966

    
1967
  for (conn = m->active_connections; conn != NULL; conn = tmp_conn) {
1968
    tmp_conn = conn->next;
1969
    mg_close_conn(conn);
1970
  }
1971

    
1972
  mg_ev_mgr_free(m);
1973
}
1974

    
1975
int mg_vprintf(struct mg_connection *nc, const char *fmt, va_list ap) {
1976
  char mem[MG_VPRINTF_BUFFER_SIZE], *buf = mem;
1977
  int len;
1978

    
1979
  if ((len = mg_avprintf(&buf, sizeof(mem), fmt, ap)) > 0) {
1980
    mg_send(nc, buf, len);
1981
  }
1982
  if (buf != mem && buf != NULL) {
1983
    MG_FREE(buf); /* LCOV_EXCL_LINE */
1984
  }               /* LCOV_EXCL_LINE */
1985

    
1986
  return len;
1987
}
1988

    
1989
int mg_printf(struct mg_connection *conn, const char *fmt, ...) {
1990
  int len;
1991
  va_list ap;
1992
  va_start(ap, fmt);
1993
  len = mg_vprintf(conn, fmt, ap);
1994
  va_end(ap);
1995
  return len;
1996
}
1997

    
1998
#ifndef MG_DISABLE_SYNC_RESOLVER
1999
/* TODO(lsm): use non-blocking resolver */
2000
static int mg_resolve2(const char *host, struct in_addr *ina) {
2001
#ifdef MG_ENABLE_GETADDRINFO
2002
  int rv = 0;
2003
  struct addrinfo hints, *servinfo, *p;
2004
  struct sockaddr_in *h = NULL;
2005
  memset(&hints, 0, sizeof hints);
2006
  hints.ai_family = AF_INET;
2007
  hints.ai_socktype = SOCK_STREAM;
2008
  if ((rv = getaddrinfo(host, NULL, NULL, &servinfo)) != 0) {
2009
    DBG(("getaddrinfo(%s) failed: %s", host, strerror(errno)));
2010
    return 0;
2011
  }
2012
  for (p = servinfo; p != NULL; p = p->ai_next) {
2013
    memcpy(&h, &p->ai_addr, sizeof(struct sockaddr_in *));
2014
    memcpy(ina, &h->sin_addr, sizeof(ina));
2015
  }
2016
  freeaddrinfo(servinfo);
2017
  return 1;
2018
#else
2019
  struct hostent *he;
2020
  if ((he = gethostbyname(host)) == NULL) {
2021
    DBG(("gethostbyname(%s) failed: %s", host, strerror(errno)));
2022
  } else {
2023
    memcpy(ina, he->h_addr_list[0], sizeof(*ina));
2024
    return 1;
2025
  }
2026
  return 0;
2027
#endif /* MG_ENABLE_GETADDRINFO */
2028
}
2029

    
2030
int mg_resolve(const char *host, char *buf, size_t n) {
2031
  struct in_addr ad;
2032
  return mg_resolve2(host, &ad) ? snprintf(buf, n, "%s", inet_ntoa(ad)) : 0;
2033
}
2034
#endif /* MG_DISABLE_SYNC_RESOLVER */
2035

    
2036
MG_INTERNAL struct mg_connection *mg_create_connection(
2037
    struct mg_mgr *mgr, mg_event_handler_t callback,
2038
    struct mg_add_sock_opts opts) {
2039
  struct mg_connection *conn;
2040

    
2041
  if ((conn = (struct mg_connection *) MG_CALLOC(1, sizeof(*conn))) != NULL) {
2042
    conn->sock = INVALID_SOCKET;
2043
    conn->handler = callback;
2044
    conn->mgr = mgr;
2045
    conn->last_io_time = time(NULL);
2046
    conn->flags = opts.flags & _MG_ALLOWED_CONNECT_FLAGS_MASK;
2047
    conn->user_data = opts.user_data;
2048
    /*
2049
     * SIZE_MAX is defined as a long long constant in
2050
     * system headers on some platforms and so it
2051
     * doesn't compile with pedantic ansi flags.
2052
     */
2053
    conn->recv_mbuf_limit = ~0;
2054
  } else {
2055
    MG_SET_PTRPTR(opts.error_string, "failed create connection");
2056
  }
2057

    
2058
  return conn;
2059
}
2060

    
2061
/*
2062
 * Address format: [PROTO://][HOST]:PORT
2063
 *
2064
 * HOST could be IPv4/IPv6 address or a host name.
2065
 * `host` is a destination buffer to hold parsed HOST part. Shoud be at least
2066
 * MG_MAX_HOST_LEN bytes long.
2067
 * `proto` is a returned socket type, either SOCK_STREAM or SOCK_DGRAM
2068
 *
2069
 * Return:
2070
 *   -1   on parse error
2071
 *    0   if HOST needs DNS lookup
2072
 *   >0   length of the address string
2073
 */
2074
MG_INTERNAL int mg_parse_address(const char *str, union socket_address *sa,
2075
                                 int *proto, char *host, size_t host_len) {
2076
  unsigned int a, b, c, d, port = 0;
2077
  int len = 0;
2078
#ifdef MG_ENABLE_IPV6
2079
  char buf[100];
2080
#endif
2081

    
2082
  /*
2083
   * MacOS needs that. If we do not zero it, subsequent bind() will fail.
2084
   * Also, all-zeroes in the socket address means binding to all addresses
2085
   * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT).
2086
   */
2087
  memset(sa, 0, sizeof(*sa));
2088
  sa->sin.sin_family = AF_INET;
2089

    
2090
  *proto = SOCK_STREAM;
2091

    
2092
  if (strncmp(str, "udp://", 6) == 0) {
2093
    str += 6;
2094
    *proto = SOCK_DGRAM;
2095
  } else if (strncmp(str, "tcp://", 6) == 0) {
2096
    str += 6;
2097
  }
2098

    
2099
  if (sscanf(str, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len) == 5) {
2100
    /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
2101
    sa->sin.sin_addr.s_addr =
2102
        htonl(((uint32_t) a << 24) | ((uint32_t) b << 16) | c << 8 | d);
2103
    sa->sin.sin_port = htons((uint16_t) port);
2104
#ifdef MG_ENABLE_IPV6
2105
  } else if (sscanf(str, "[%99[^]]]:%u%n", buf, &port, &len) == 2 &&
2106
             inet_pton(AF_INET6, buf, &sa->sin6.sin6_addr)) {
2107
    /* IPv6 address, e.g. [3ffe:2a00:100:7031::1]:8080 */
2108
    sa->sin6.sin6_family = AF_INET6;
2109
    sa->sin.sin_port = htons((uint16_t) port);
2110
#endif
2111
#ifndef MG_DISABLE_RESOLVER
2112
  } else if (strlen(str) < host_len &&
2113
             sscanf(str, "%[^ :]:%u%n", host, &port, &len) == 2) {
2114
    sa->sin.sin_port = htons((uint16_t) port);
2115
    if (mg_resolve_from_hosts_file(host, sa) != 0) {
2116
      return 0;
2117
    }
2118
#endif
2119
  } else if (sscanf(str, ":%u%n", &port, &len) == 1 ||
2120
             sscanf(str, "%u%n", &port, &len) == 1) {
2121
    /* If only port is specified, bind to IPv4, INADDR_ANY */
2122
    sa->sin.sin_port = htons((uint16_t) port);
2123
  } else {
2124
    return -1;
2125
  }
2126

    
2127
  return port < 0xffffUL && str[len] == '\0' ? len : -1;
2128
}
2129

    
2130
#ifdef MG_ENABLE_SSL
2131
/*
2132
 * Certificate generation script is at
2133
 * https://github.com/cesanta/mongoose/blob/master/scripts/generate_ssl_certificates.sh
2134
 */
2135

    
2136
/*
2137
 * Cipher suite options used for TLS negotiation.
2138
 * https://wiki.mozilla.org/Security/Server_Side_TLS#Recommended_configurations
2139
 */
2140
static const char mg_s_cipher_list[] =
2141
#if defined(MG_SSL_CRYPTO_MODERN)
2142
    "ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:"
2143
    "ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:"
2144
    "DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:"
2145
    "ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:"
2146
    "ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:"
2147
    "ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:"
2148
    "DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:"
2149
    "DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:"
2150
    "!aNULL:!eNULL:!EXPORT:!DES:!RC4:!3DES:!MD5:!PSK"
2151
#elif defined(MG_SSL_CRYPTO_OLD)
2152
    "ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:"
2153
    "ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:"
2154
    "DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:"
2155
    "ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:"
2156
    "ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:"
2157
    "ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:"
2158
    "DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:"
2159
    "DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:ECDHE-RSA-DES-CBC3-SHA:"
2160
    "ECDHE-ECDSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:"
2161
    "AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:DES-CBC3-SHA:"
2162
    "HIGH:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:"
2163
    "!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA"
2164
#else /* Default - intermediate. */
2165
    "ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:"
2166
    "ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:"
2167
    "DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:"
2168
    "ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:"
2169
    "ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:"
2170
    "ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:"
2171
    "DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:"
2172
    "DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:"
2173
    "AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:CAMELLIA:"
2174
    "DES-CBC3-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:"
2175
    "!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA"
2176
#endif
2177
    ;
2178

    
2179
#ifndef MG_DISABLE_PFS
2180
/*
2181
 * Default DH params for PFS cipher negotiation. This is a 2048-bit group.
2182
 * Will be used if none are provided by the user in the certificate file.
2183
 */
2184
static const char mg_s_default_dh_params[] =
2185
    "\
2186
-----BEGIN DH PARAMETERS-----\n\
2187
MIIBCAKCAQEAlvbgD/qh9znWIlGFcV0zdltD7rq8FeShIqIhkQ0C7hYFThrBvF2E\n\
2188
Z9bmgaP+sfQwGpVlv9mtaWjvERbu6mEG7JTkgmVUJrUt/wiRzwTaCXBqZkdUO8Tq\n\
2189
+E6VOEQAilstG90ikN1Tfo+K6+X68XkRUIlgawBTKuvKVwBhuvlqTGerOtnXWnrt\n\
2190
ym//hd3cd5PBYGBix0i7oR4xdghvfR2WLVu0LgdThTBb6XP7gLd19cQ1JuBtAajZ\n\
2191
wMuPn7qlUkEFDIkAZy59/Hue/H2Q2vU/JsvVhHWCQBL4F1ofEAt50il6ZxR1QfFK\n\
2192
9VGKDC4oOgm9DlxwwBoC2FjqmvQlqVV3kwIBAg==\n\
2193
-----END DH PARAMETERS-----\n";
2194
#endif
2195

    
2196
static int mg_use_ca_cert(SSL_CTX *ctx, const char *cert) {
2197
  if (ctx == NULL) {
2198
    return -1;
2199
  } else if (cert == NULL || cert[0] == '\0') {
2200
    return 0;
2201
  }
2202
  SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, 0);
2203
  return SSL_CTX_load_verify_locations(ctx, cert, NULL) == 1 ? 0 : -2;
2204
}
2205

    
2206
static int mg_use_cert(SSL_CTX *ctx, const char *pem_file) {
2207
  if (ctx == NULL) {
2208
    return -1;
2209
  } else if (pem_file == NULL || pem_file[0] == '\0') {
2210
    return 0;
2211
  } else if (SSL_CTX_use_certificate_file(ctx, pem_file, 1) == 0 ||
2212
             SSL_CTX_use_PrivateKey_file(ctx, pem_file, 1) == 0) {
2213
    return -2;
2214
#ifndef MG_DISABLE_PFS
2215
  } else {
2216
    BIO *bio = NULL;
2217
    DH *dh = NULL;
2218

    
2219
    /* Try to read DH parameters from the cert/key file. */
2220
    bio = BIO_new_file(pem_file, "r");
2221
    if (bio != NULL) {
2222
      dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
2223
      BIO_free(bio);
2224
    }
2225
    /*
2226
     * If there are no DH params in the file, fall back to hard-coded ones.
2227
     * Not ideal, but better than nothing.
2228
     */
2229
    if (dh == NULL) {
2230
      bio = BIO_new_mem_buf((void *) mg_s_default_dh_params, -1);
2231
      dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
2232
      BIO_free(bio);
2233
    }
2234
    if (dh != NULL) {
2235
      SSL_CTX_set_tmp_dh(ctx, dh);
2236
      SSL_CTX_set_options(ctx, SSL_OP_SINGLE_DH_USE);
2237
      DH_free(dh);
2238
    }
2239

    
2240
    SSL_CTX_set_mode(ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
2241
    SSL_CTX_use_certificate_chain_file(ctx, pem_file);
2242
    return 0;
2243
#endif
2244
  }
2245
}
2246

    
2247
/*
2248
 * Turn the connection into SSL mode.
2249
 * `cert` is the certificate file in PEM format. For listening connections,
2250
 * certificate file must contain private key and server certificate,
2251
 * concatenated. It may also contain DH params - these will be used for more
2252
 * secure key exchange. `ca_cert` is a certificate authority (CA) PEM file, and
2253
 * it is optional (can be set to NULL). If `ca_cert` is non-NULL, then
2254
 * the connection is so-called two-way-SSL: other peer's certificate is
2255
 * checked against the `ca_cert`.
2256
 *
2257
 * Handy OpenSSL command to generate test self-signed certificate:
2258
 *
2259
 *    openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 999
2260
 *
2261
 * Return NULL on success, or error message on failure.
2262
 */
2263
const char *mg_set_ssl(struct mg_connection *nc, const char *cert,
2264
                       const char *ca_cert) {
2265
  const char *result = NULL;
2266

    
2267
  if ((nc->flags & MG_F_LISTENING) &&
2268
      (nc->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
2269
    result = "SSL_CTX_new() failed";
2270
  } else if (!(nc->flags & MG_F_LISTENING) &&
2271
             (nc->ssl_ctx = SSL_CTX_new(SSLv23_client_method())) == NULL) {
2272
    result = "SSL_CTX_new() failed";
2273
  } else if (mg_use_cert(nc->ssl_ctx, cert) != 0) {
2274
    result = "Invalid ssl cert";
2275
  } else if (mg_use_ca_cert(nc->ssl_ctx, ca_cert) != 0) {
2276
    result = "Invalid CA cert";
2277
  } else if (!(nc->flags & MG_F_LISTENING) &&
2278
             (nc->ssl = SSL_new(nc->ssl_ctx)) == NULL) {
2279
    result = "SSL_new() failed";
2280
  } else if (!(nc->flags & MG_F_LISTENING) && nc->sock != INVALID_SOCKET) {
2281
    /*
2282
     * Socket is open here only if we are connecting to IP address
2283
     * and does not open if we are connecting using async DNS resolver
2284
     */
2285
    SSL_set_fd(nc->ssl, nc->sock);
2286
  }
2287

    
2288
/* TODO(rojer): remove when krypton exposes this function, even a dummy one */
2289
#ifdef OPENSSL_VERSION_NUMBER
2290
  SSL_CTX_set_cipher_list(nc->ssl_ctx, mg_s_cipher_list);
2291
#endif
2292
  return result;
2293
}
2294

    
2295
static int mg_ssl_err(struct mg_connection *conn, int res) {
2296
  int ssl_err = SSL_get_error(conn->ssl, res);
2297
  if (ssl_err == SSL_ERROR_WANT_READ) conn->flags |= MG_F_WANT_READ;
2298
  if (ssl_err == SSL_ERROR_WANT_WRITE) conn->flags |= MG_F_WANT_WRITE;
2299
  return ssl_err;
2300
}
2301
#endif /* MG_ENABLE_SSL */
2302

    
2303
struct mg_connection *mg_if_accept_tcp_cb(struct mg_connection *lc,
2304
                                          union socket_address *sa,
2305
                                          size_t sa_len) {
2306
  struct mg_add_sock_opts opts;
2307
  struct mg_connection *nc;
2308
  (void) sa_len;
2309
  memset(&opts, 0, sizeof(opts));
2310
  nc = mg_create_connection(lc->mgr, lc->handler, opts);
2311
  if (nc == NULL) return NULL;
2312
  nc->listener = lc;
2313
  nc->proto_data = lc->proto_data;
2314
  nc->proto_handler = lc->proto_handler;
2315
  nc->user_data = lc->user_data;
2316
  nc->recv_mbuf_limit = lc->recv_mbuf_limit;
2317
  nc->sa = *sa;
2318
  mg_add_conn(nc->mgr, nc);
2319
  if (nc->ssl == NULL) {
2320
    /* For non-SSL connections deliver MG_EV_ACCEPT right away. */
2321
    mg_call(nc, NULL, MG_EV_ACCEPT, &nc->sa);
2322
  }
2323
  DBG(("%p %p %d %d, %p %p", lc, nc, nc->sock, (int) nc->flags, lc->ssl_ctx,
2324
       nc->ssl));
2325
  return nc;
2326
}
2327

    
2328
static size_t recv_avail_size(struct mg_connection *conn, size_t max) {
2329
  size_t avail;
2330
  if (conn->recv_mbuf_limit < conn->recv_mbuf.len) return 0;
2331
  avail = conn->recv_mbuf_limit - conn->recv_mbuf.len;
2332
  return avail > max ? max : avail;
2333
}
2334

    
2335
#ifdef MG_ENABLE_SSL
2336
static void mg_ssl_begin(struct mg_connection *nc) {
2337
  int server_side = nc->listener != NULL;
2338
  int res = server_side ? SSL_accept(nc->ssl) : SSL_connect(nc->ssl);
2339
  DBG(("%p %d res %d %d %d", nc, server_side, res, errno, mg_ssl_err(nc, res)));
2340

    
2341
  if (res == 1) {
2342
    nc->flags |= MG_F_SSL_HANDSHAKE_DONE;
2343
    nc->flags &= ~(MG_F_WANT_READ | MG_F_WANT_WRITE);
2344

    
2345
    if (server_side) {
2346
      union socket_address sa;
2347
      socklen_t sa_len = sizeof(sa);
2348
      /* In case port was set to 0, get the real port number */
2349
      (void) getsockname(nc->sock, &sa.sa, &sa_len);
2350
      mg_call(nc, NULL, MG_EV_ACCEPT, &sa);
2351
    } else {
2352
      int err = 0;
2353
      mg_call(nc, NULL, MG_EV_CONNECT, &err);
2354
    }
2355
  } else {
2356
    int ssl_err = mg_ssl_err(nc, res);
2357
    if (ssl_err != SSL_ERROR_WANT_READ && ssl_err != SSL_ERROR_WANT_WRITE) {
2358
      nc->flags |= MG_F_CLOSE_IMMEDIATELY;
2359
      if (!server_side) {
2360
        int err = 0;
2361
        mg_call(nc, NULL, MG_EV_CONNECT, &err);
2362
      }
2363
    }
2364
  }
2365
}
2366
#endif /* MG_ENABLE_SSL */
2367

    
2368
void mg_send(struct mg_connection *nc, const void *buf, int len) {
2369
  nc->last_io_time = time(NULL);
2370
  if (nc->flags & MG_F_UDP) {
2371
    mg_if_udp_send(nc, buf, len);
2372
  } else {
2373
    mg_if_tcp_send(nc, buf, len);
2374
  }
2375
#ifndef MG_DISABLE_FILESYSTEM
2376
  if (nc->mgr && nc->mgr->hexdump_file != NULL) {
2377
    mg_hexdump_connection(nc, nc->mgr->hexdump_file, len, MG_EV_SEND);
2378
  }
2379
#endif
2380
}
2381

    
2382
void mg_if_sent_cb(struct mg_connection *nc, int num_sent) {
2383
  if (num_sent < 0) {
2384
    nc->flags |= MG_F_CLOSE_IMMEDIATELY;
2385
  }
2386
  mg_call(nc, NULL, MG_EV_SEND, &num_sent);
2387
}
2388

    
2389
static void mg_recv_common(struct mg_connection *nc, void *buf, int len) {
2390
  DBG(("%p %d %u", nc, len, (unsigned int) nc->recv_mbuf.len));
2391
  nc->last_io_time = time(NULL);
2392
  if (nc->recv_mbuf.len == 0) {
2393
    /* Adopt buf as recv_mbuf's backing store. */
2394
    mbuf_free(&nc->recv_mbuf);
2395
    nc->recv_mbuf.buf = (char *) buf;
2396
    nc->recv_mbuf.size = nc->recv_mbuf.len = len;
2397
  } else {
2398
    size_t avail = recv_avail_size(nc, len);
2399
    len = avail;
2400
    mbuf_append(&nc->recv_mbuf, buf, len);
2401
    MG_FREE(buf);
2402
  }
2403
  mg_call(nc, NULL, MG_EV_RECV, &len);
2404
}
2405

    
2406
void mg_if_recv_tcp_cb(struct mg_connection *nc, void *buf, int len) {
2407
  mg_recv_common(nc, buf, len);
2408
  mg_if_recved(nc, len);
2409
}
2410

    
2411
void mg_if_recv_udp_cb(struct mg_connection *nc, void *buf, int len,
2412
                       union socket_address *sa, size_t sa_len) {
2413
  assert(nc->flags & MG_F_UDP);
2414
  DBG(("%p %u", nc, (unsigned int) len));
2415
  if (nc->flags & MG_F_LISTENING) {
2416
    struct mg_connection *lc = nc;
2417
    /*
2418
     * Do we have an existing connection for this source?
2419
     * This is very inefficient for long connection lists.
2420
     */
2421
    for (nc = mg_next(lc->mgr, NULL); nc != NULL; nc = mg_next(lc->mgr, nc)) {
2422
      if (memcmp(&nc->sa.sa, &sa->sa, sa_len) == 0) break;
2423
    }
2424
    if (nc == NULL) {
2425
      struct mg_add_sock_opts opts;
2426
      memset(&opts, 0, sizeof(opts));
2427
      nc = mg_create_connection(lc->mgr, lc->handler, opts);
2428
    }
2429
    if (nc != NULL) {
2430
      nc->sock = lc->sock;
2431
      nc->listener = lc;
2432
      nc->sa = *sa;
2433
      nc->proto_data = lc->proto_data;
2434
      nc->proto_handler = lc->proto_handler;
2435
      nc->user_data = lc->user_data;
2436
      nc->recv_mbuf_limit = lc->recv_mbuf_limit;
2437
      nc->flags = MG_F_UDP;
2438
      mg_add_conn(lc->mgr, nc);
2439
      mg_call(nc, NULL, MG_EV_ACCEPT, &nc->sa);
2440
    } else {
2441
      DBG(("OOM"));
2442
    }
2443
  }
2444
  if (nc != NULL) {
2445
    mg_recv_common(nc, buf, len);
2446
  } else {
2447
    /* Drop on the floor. */
2448
    MG_FREE(buf);
2449
  }
2450
  mg_if_recved(nc, len);
2451
}
2452

    
2453
/*
2454
 * Schedules an async connect for a resolved address and proto.
2455
 * Called from two places: `mg_connect_opt()` and from async resolver.
2456
 * When called from the async resolver, it must trigger `MG_EV_CONNECT` event
2457
 * with a failure flag to indicate connection failure.
2458
 */
2459
MG_INTERNAL struct mg_connection *mg_do_connect(struct mg_connection *nc,
2460
                                                int proto,
2461
                                                union socket_address *sa) {
2462
  DBG(("%p %s://%s:%hu", nc, proto == SOCK_DGRAM ? "udp" : "tcp",
2463
       inet_ntoa(sa->sin.sin_addr), ntohs(sa->sin.sin_port)));
2464

    
2465
  nc->flags |= MG_F_CONNECTING;
2466
  if (proto == SOCK_DGRAM) {
2467
    mg_if_connect_udp(nc);
2468
  } else {
2469
    mg_if_connect_tcp(nc, sa);
2470
  }
2471
  mg_add_conn(nc->mgr, nc);
2472
  return nc;
2473
}
2474

    
2475
void mg_if_connect_cb(struct mg_connection *nc, int err) {
2476
  DBG(("%p connect, err=%d", nc, err));
2477
  nc->flags &= ~MG_F_CONNECTING;
2478
  if (err == 0) {
2479
#ifdef MG_ENABLE_SSL
2480
    if (nc->ssl != NULL) {
2481
      SSL_set_fd(nc->ssl, nc->sock);
2482
      mg_ssl_begin(nc);
2483
      return;
2484
    }
2485
#endif
2486
  } else {
2487
    nc->flags |= MG_F_CLOSE_IMMEDIATELY;
2488
  }
2489
  mg_call(nc, NULL, MG_EV_CONNECT, &err);
2490
}
2491

    
2492
#ifndef MG_DISABLE_RESOLVER
2493
/*
2494
 * Callback for the async resolver on mg_connect_opt() call.
2495
 * Main task of this function is to trigger MG_EV_CONNECT event with
2496
 *    either failure (and dealloc the connection)
2497
 *    or success (and proceed with connect()
2498
 */
2499
static void resolve_cb(struct mg_dns_message *msg, void *data) {
2500
  struct mg_connection *nc = (struct mg_connection *) data;
2501
  int i;
2502
  int failure = -1;
2503

    
2504
  if (msg != NULL) {
2505
    /*
2506
     * Take the first DNS A answer and run...
2507
     */
2508
    for (i = 0; i < msg->num_answers; i++) {
2509
      if (msg->answers[i].rtype == MG_DNS_A_RECORD) {
2510
        /*
2511
         * Async resolver guarantees that there is at least one answer.
2512
         * TODO(lsm): handle IPv6 answers too
2513
         */
2514
        mg_dns_parse_record_data(msg, &msg->answers[i], &nc->sa.sin.sin_addr,
2515
                                 4);
2516
        mg_do_connect(nc, nc->flags & MG_F_UDP ? SOCK_DGRAM : SOCK_STREAM,
2517
                      &nc->sa);
2518
        return;
2519
      }
2520
    }
2521
  }
2522

    
2523
  /*
2524
   * If we get there was no MG_DNS_A_RECORD in the answer
2525
   */
2526
  mg_call(nc, NULL, MG_EV_CONNECT, &failure);
2527
  mg_destroy_conn(nc);
2528
}
2529
#endif
2530

    
2531
struct mg_connection *mg_connect(struct mg_mgr *mgr, const char *address,
2532
                                 mg_event_handler_t callback) {
2533
  struct mg_connect_opts opts;
2534
  memset(&opts, 0, sizeof(opts));
2535
  return mg_connect_opt(mgr, address, callback, opts);
2536
}
2537

    
2538
struct mg_connection *mg_connect_opt(struct mg_mgr *mgr, const char *address,
2539
                                     mg_event_handler_t callback,
2540
                                     struct mg_connect_opts opts) {
2541
  struct mg_connection *nc = NULL;
2542
  int proto, rc;
2543
  struct mg_add_sock_opts add_sock_opts;
2544
  char host[MG_MAX_HOST_LEN];
2545

    
2546
  MG_COPY_COMMON_CONNECTION_OPTIONS(&add_sock_opts, &opts);
2547

    
2548
  if ((nc = mg_create_connection(mgr, callback, add_sock_opts)) == NULL) {
2549
    return NULL;
2550
  } else if ((rc = mg_parse_address(address, &nc->sa, &proto, host,
2551
                                    sizeof(host))) < 0) {
2552
    /* Address is malformed */
2553
    MG_SET_PTRPTR(opts.error_string, "cannot parse address");
2554
    mg_destroy_conn(nc);
2555
    return NULL;
2556
  }
2557
  nc->flags |= opts.flags & _MG_ALLOWED_CONNECT_FLAGS_MASK;
2558
  nc->flags |= (proto == SOCK_DGRAM) ? MG_F_UDP : 0;
2559
  nc->user_data = opts.user_data;
2560

    
2561
  if (rc == 0) {
2562
#ifndef MG_DISABLE_RESOLVER
2563
    /*
2564
     * DNS resolution is required for host.
2565
     * mg_parse_address() fills port in nc->sa, which we pass to resolve_cb()
2566
     */
2567
    if (mg_resolve_async(nc->mgr, host, MG_DNS_A_RECORD, resolve_cb, nc) != 0) {
2568
      MG_SET_PTRPTR(opts.error_string, "cannot schedule DNS lookup");
2569
      mg_destroy_conn(nc);
2570
      return NULL;
2571
    }
2572

    
2573
    return nc;
2574
#else
2575
    MG_SET_PTRPTR(opts.error_string, "Resolver is disabled");
2576
    mg_destroy_conn(nc);
2577
    return NULL;
2578
#endif
2579
  } else {
2580
    /* Address is parsed and resolved to IP. proceed with connect() */
2581
    return mg_do_connect(nc, proto, &nc->sa);
2582
  }
2583
}
2584

    
2585
struct mg_connection *mg_bind(struct mg_mgr *srv, const char *address,
2586
                              mg_event_handler_t event_handler) {
2587
  struct mg_bind_opts opts;
2588
  memset(&opts, 0, sizeof(opts));
2589
  return mg_bind_opt(srv, address, event_handler, opts);
2590
}
2591

    
2592
struct mg_connection *mg_bind_opt(struct mg_mgr *mgr, const char *address,
2593
                                  mg_event_handler_t callback,
2594
                                  struct mg_bind_opts opts) {
2595
  union socket_address sa;
2596
  struct mg_connection *nc = NULL;
2597
  int proto, rc;
2598
  struct mg_add_sock_opts add_sock_opts;
2599
  char host[MG_MAX_HOST_LEN];
2600

    
2601
  MG_COPY_COMMON_CONNECTION_OPTIONS(&add_sock_opts, &opts);
2602

    
2603
  if (mg_parse_address(address, &sa, &proto, host, sizeof(host)) <= 0) {
2604
    MG_SET_PTRPTR(opts.error_string, "cannot parse address");
2605
    return NULL;
2606
  }
2607

    
2608
  nc = mg_create_connection(mgr, callback, add_sock_opts);
2609
  if (nc == NULL) {
2610
    return NULL;
2611
  }
2612

    
2613
  nc->sa = sa;
2614
  nc->flags |= MG_F_LISTENING;
2615
  if (proto == SOCK_DGRAM) {
2616
    nc->flags |= MG_F_UDP;
2617
    rc = mg_if_listen_udp(nc, &nc->sa);
2618
  } else {
2619
    rc = mg_if_listen_tcp(nc, &nc->sa);
2620
  }
2621
  if (rc != 0) {
2622
    DBG(("Failed to open listener: %d", rc));
2623
    MG_SET_PTRPTR(opts.error_string, "failed to open listener");
2624
    mg_destroy_conn(nc);
2625
    return NULL;
2626
  }
2627
  mg_add_conn(nc->mgr, nc);
2628

    
2629
  return nc;
2630
}
2631

    
2632
struct mg_connection *mg_next(struct mg_mgr *s, struct mg_connection *conn) {
2633
  return conn == NULL ? s->active_connections : conn->next;
2634
}
2635

    
2636
#ifndef MG_DISABLE_SOCKETPAIR
2637
void mg_broadcast(struct mg_mgr *mgr, mg_event_handler_t cb, void *data,
2638
                  size_t len) {
2639
  struct ctl_msg ctl_msg;
2640

    
2641
  /*
2642
   * Mongoose manager has a socketpair, `struct mg_mgr::ctl`,
2643
   * where `mg_broadcast()` pushes the message.
2644
   * `mg_mgr_poll()` wakes up, reads a message from the socket pair, and calls
2645
   * specified callback for each connection. Thus the callback function executes
2646
   * in event manager thread.
2647
   */
2648
  if (mgr->ctl[0] != INVALID_SOCKET && data != NULL &&
2649
      len < sizeof(ctl_msg.message)) {
2650
    size_t dummy;
2651

    
2652
    ctl_msg.callback = cb;
2653
    memcpy(ctl_msg.message, data, len);
2654
    dummy = MG_SEND_FUNC(mgr->ctl[0], (char *) &ctl_msg,
2655
                         offsetof(struct ctl_msg, message) + len, 0);
2656
    dummy = MG_RECV_FUNC(mgr->ctl[0], (char *) &len, 1, 0);
2657
    (void) dummy; /* https://gcc.gnu.org/bugzilla/show_bug.cgi?id=25509 */
2658
  }
2659
}
2660
#endif /* MG_DISABLE_SOCKETPAIR */
2661

    
2662
static int isbyte(int n) {
2663
  return n >= 0 && n <= 255;
2664
}
2665

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

    
2669
  if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5 ||
2670
       sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) &&
2671
      isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) && slash >= 0 &&
2672
      slash < 33) {
2673
    len = n;
2674
    *net =
2675
        ((uint32_t) a << 24) | ((uint32_t) b << 16) | ((uint32_t) c << 8) | d;
2676
    *mask = slash ? 0xffffffffU << (32 - slash) : 0;
2677
  }
2678

    
2679
  return len;
2680
}
2681

    
2682
int mg_check_ip_acl(const char *acl, uint32_t remote_ip) {
2683
  int allowed, flag;
2684
  uint32_t net, mask;
2685
  struct mg_str vec;
2686

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

    
2690
  while ((acl = mg_next_comma_list_entry(acl, &vec, NULL)) != NULL) {
2691
    flag = vec.p[0];
2692
    if ((flag != '+' && flag != '-') ||
2693
        parse_net(&vec.p[1], &net, &mask) == 0) {
2694
      return -1;
2695
    }
2696

    
2697
    if (net == (remote_ip & mask)) {
2698
      allowed = flag;
2699
    }
2700
  }
2701

    
2702
  return allowed == '+';
2703
}
2704

    
2705
/* Move data from one connection to another */
2706
void mg_forward(struct mg_connection *from, struct mg_connection *to) {
2707
  mg_send(to, from->recv_mbuf.buf, from->recv_mbuf.len);
2708
  mbuf_remove(&from->recv_mbuf, from->recv_mbuf.len);
2709
}
2710
#ifdef NS_MODULE_LINES
2711
#line 1 "src/net_if_socket.c"
2712
/**/
2713
#endif
2714
#ifndef MG_DISABLE_SOCKET_IF
2715

    
2716
/* Amalgamated: #include "internal.h" */
2717

    
2718
#define MG_TCP_RECV_BUFFER_SIZE 1024
2719
#define MG_UDP_RECV_BUFFER_SIZE 1500
2720

    
2721
static sock_t mg_open_listening_socket(union socket_address *sa, int proto);
2722
static void mg_sock_set(struct mg_connection *nc, sock_t sock);
2723

    
2724
void mg_set_non_blocking_mode(sock_t sock) {
2725
#ifdef _WIN32
2726
  unsigned long on = 1;
2727
  ioctlsocket(sock, FIONBIO, &on);
2728
#elif defined(MG_CC3200)
2729
  cc3200_set_non_blocking_mode(sock);
2730
#else
2731
  int flags = fcntl(sock, F_GETFL, 0);
2732
  fcntl(sock, F_SETFL, flags | O_NONBLOCK);
2733
#endif
2734
}
2735

    
2736
int mg_is_error(int n) {
2737
#ifdef MG_CC3200
2738
  DBG(("n = %d, errno = %d", n, errno));
2739
  if (n < 0) errno = n;
2740
#endif
2741
  return n == 0 || (n < 0 && errno != EINTR && errno != EINPROGRESS &&
2742
                    errno != EAGAIN && errno != EWOULDBLOCK
2743
#ifdef MG_CC3200
2744
                    && errno != SL_EALREADY
2745
#endif
2746
#ifdef _WIN32
2747
                    && WSAGetLastError() != WSAEINTR &&
2748
                    WSAGetLastError() != WSAEWOULDBLOCK
2749
#endif
2750
                    );
2751
}
2752

    
2753
void mg_if_connect_tcp(struct mg_connection *nc,
2754
                       const union socket_address *sa) {
2755
  int rc;
2756
  nc->sock = socket(AF_INET, SOCK_STREAM, 0);
2757
  if (nc->sock < 0) {
2758
    nc->sock = INVALID_SOCKET;
2759
    nc->err = errno ? errno : 1;
2760
    return;
2761
  }
2762
#if !defined(MG_CC3200) && !defined(MG_ESP8266)
2763
  mg_set_non_blocking_mode(nc->sock);
2764
#endif
2765
  rc = connect(nc->sock, &sa->sa, sizeof(sa->sin));
2766
  nc->err = rc == 0 ? 0 : (errno ? errno : 1);
2767
  DBG(("%p sock %d err %d", nc, nc->sock, nc->err));
2768
}
2769

    
2770
void mg_if_connect_udp(struct mg_connection *nc) {
2771
  nc->sock = socket(AF_INET, SOCK_DGRAM, 0);
2772
  if (nc->sock < 0) {
2773
    nc->sock = INVALID_SOCKET;
2774
    nc->err = errno ? errno : 1;
2775
    return;
2776
  }
2777
  nc->err = 0;
2778
}
2779

    
2780
int mg_if_listen_tcp(struct mg_connection *nc, union socket_address *sa) {
2781
  sock_t sock = mg_open_listening_socket(sa, SOCK_STREAM);
2782
  if (sock < 0) return (errno ? errno : 1);
2783
  mg_sock_set(nc, sock);
2784
  return 0;
2785
}
2786

    
2787
int mg_if_listen_udp(struct mg_connection *nc, union socket_address *sa) {
2788
  sock_t sock = mg_open_listening_socket(sa, SOCK_DGRAM);
2789
  if (sock < 0) return (errno ? errno : 1);
2790
  mg_sock_set(nc, sock);
2791
  return 0;
2792
}
2793

    
2794
void mg_if_tcp_send(struct mg_connection *nc, const void *buf, size_t len) {
2795
  mbuf_append(&nc->send_mbuf, buf, len);
2796
}
2797

    
2798
void mg_if_udp_send(struct mg_connection *nc, const void *buf, size_t len) {
2799
  DBG(("%p %d %d", nc, (int) len, (int) nc->send_mbuf.len));
2800
  mbuf_append(&nc->send_mbuf, buf, len);
2801
}
2802

    
2803
void mg_if_recved(struct mg_connection *nc, size_t len) {
2804
  (void) nc;
2805
  (void) len;
2806
}
2807

    
2808
void mg_if_destroy_conn(struct mg_connection *nc) {
2809
  if (nc->sock == INVALID_SOCKET) return;
2810
#ifdef MG_ENABLE_SSL
2811
  if (nc->ssl != NULL) SSL_free(nc->ssl);
2812
  if (nc->ssl_ctx != NULL) SSL_CTX_free(nc->ssl_ctx);
2813
#endif
2814
  if (!(nc->flags & MG_F_UDP)) {
2815
    closesocket(nc->sock);
2816
  } else {
2817
    /* Only close outgoing UDP sockets or listeners. */
2818
    if (nc->listener == NULL) closesocket(nc->sock);
2819
  }
2820
  /*
2821
   * avoid users accidentally double close a socket
2822
   * because it can lead to difficult to debug situations.
2823
   * It would happen only if reusing a destroyed mg_connection
2824
   * but it's not always possible to run the code through an
2825
   * address sanitizer.
2826
   */
2827
  nc->sock = INVALID_SOCKET;
2828
}
2829

    
2830
static void mg_accept_conn(struct mg_connection *lc) {
2831
  struct mg_connection *nc;
2832
  union socket_address sa;
2833
  socklen_t sa_len = sizeof(sa);
2834
  /* NOTE(lsm): on Windows, sock is always > FD_SETSIZE */
2835
  sock_t sock = accept(lc->sock, &sa.sa, &sa_len);
2836
  if (sock < 0) {
2837
    DBG(("%p: failed to accept: %d", lc, errno));
2838
    return;
2839
  }
2840
  nc = mg_if_accept_tcp_cb(lc, &sa, sa_len);
2841
  if (nc == NULL) {
2842
    closesocket(sock);
2843
    return;
2844
  }
2845
  mg_sock_set(nc, sock);
2846
#ifdef MG_ENABLE_SSL
2847
  if (lc->ssl_ctx != NULL) {
2848
    nc->ssl = SSL_new(lc->ssl_ctx);
2849
    if (nc->ssl == NULL || SSL_set_fd(nc->ssl, sock) != 1) {
2850
      DBG(("SSL error"));
2851
      mg_close_conn(nc);
2852
    }
2853
  }
2854
#endif
2855
}
2856

    
2857
/* 'sa' must be an initialized address to bind to */
2858
static sock_t mg_open_listening_socket(union socket_address *sa, int proto) {
2859
  socklen_t sa_len =
2860
      (sa->sa.sa_family == AF_INET) ? sizeof(sa->sin) : sizeof(sa->sin6);
2861
  sock_t sock = INVALID_SOCKET;
2862
#if !defined(MG_CC3200) && !defined(MG_LWIP)
2863
  int on = 1;
2864
#endif
2865

    
2866
  if ((sock = socket(sa->sa.sa_family, proto, 0)) != INVALID_SOCKET &&
2867
#if !defined(MG_CC3200) && \
2868
    !defined(MG_LWIP) /* CC3200 and LWIP don't support either */
2869
#if defined(_WIN32) && defined(SO_EXCLUSIVEADDRUSE)
2870
      /* "Using SO_REUSEADDR and SO_EXCLUSIVEADDRUSE" http://goo.gl/RmrFTm */
2871
      !setsockopt(sock, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (void *) &on,
2872
                  sizeof(on)) &&
2873
#endif
2874

    
2875
#if !defined(_WIN32) || !defined(SO_EXCLUSIVEADDRUSE)
2876
      /*
2877
       * SO_RESUSEADDR is not enabled on Windows because the semantics of
2878
       * SO_REUSEADDR on UNIX and Windows is different. On Windows,
2879
       * SO_REUSEADDR allows to bind a socket to a port without error even if
2880
       * the port is already open by another program. This is not the behavior
2881
       * SO_REUSEADDR was designed for, and leads to hard-to-track failure
2882
       * scenarios. Therefore, SO_REUSEADDR was disabled on Windows unless
2883
       * SO_EXCLUSIVEADDRUSE is supported and set on a socket.
2884
       */
2885
      !setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *) &on, sizeof(on)) &&
2886
#endif
2887
#endif /* !MG_CC3200 && !MG_LWIP */
2888

    
2889
      !bind(sock, &sa->sa, sa_len) &&
2890
      (proto == SOCK_DGRAM || listen(sock, SOMAXCONN) == 0)) {
2891
#if !defined(MG_CC3200) && !defined(MG_LWIP) /* TODO(rojer): Fix this. */
2892
    mg_set_non_blocking_mode(sock);
2893
    /* In case port was set to 0, get the real port number */
2894
    (void) getsockname(sock, &sa->sa, &sa_len);
2895
#endif
2896
  } else if (sock != INVALID_SOCKET) {
2897
    closesocket(sock);
2898
    sock = INVALID_SOCKET;
2899
  }
2900

    
2901
  return sock;
2902
}
2903

    
2904
static void mg_write_to_socket(struct mg_connection *nc) {
2905
  struct mbuf *io = &nc->send_mbuf;
2906
  int n = 0;
2907

    
2908
#ifdef MG_LWIP
2909
  /* With LWIP we don't know if the socket is ready */
2910
  if (io->len == 0) return;
2911
#endif
2912

    
2913
  assert(io->len > 0);
2914

    
2915
  if (nc->flags & MG_F_UDP) {
2916
    int n =
2917
        sendto(nc->sock, io->buf, io->len, 0, &nc->sa.sa, sizeof(nc->sa.sin));
2918
    DBG(("%p %d %d %d %s:%hu", nc, nc->sock, n, errno,
2919
         inet_ntoa(nc->sa.sin.sin_addr), ntohs(nc->sa.sin.sin_port)));
2920
    if (n > 0) {
2921
      mbuf_remove(io, n);
2922
    }
2923
    mg_if_sent_cb(nc, n);
2924
    return;
2925
  }
2926

    
2927
#ifdef MG_ENABLE_SSL
2928
  if (nc->ssl != NULL) {
2929
    if (nc->flags & MG_F_SSL_HANDSHAKE_DONE) {
2930
      n = SSL_write(nc->ssl, io->buf, io->len);
2931
      if (n <= 0) {
2932
        int ssl_err = mg_ssl_err(nc, n);
2933
        if (ssl_err == SSL_ERROR_WANT_READ || ssl_err == SSL_ERROR_WANT_WRITE) {
2934
          return; /* Call us again */
2935
        } else {
2936
          nc->flags |= MG_F_CLOSE_IMMEDIATELY;
2937
        }
2938
      } else {
2939
        /* Successful SSL operation, clear off SSL wait flags */
2940
        nc->flags &= ~(MG_F_WANT_READ | MG_F_WANT_WRITE);
2941
      }
2942
    } else {
2943
      mg_ssl_begin(nc);
2944
      return;
2945
    }
2946
  } else
2947
#endif
2948
  {
2949
    n = (int) MG_SEND_FUNC(nc->sock, io->buf, io->len, 0);
2950
  }
2951

    
2952
  DBG(("%p %d bytes -> %d", nc, n, nc->sock));
2953

    
2954
  if (n > 0) {
2955
    mbuf_remove(io, n);
2956
  }
2957
  mg_if_sent_cb(nc, n);
2958
}
2959

    
2960
static void mg_read_from_socket(struct mg_connection *conn) {
2961
  int n = 0;
2962
  char *buf = (char *) MG_MALLOC(MG_TCP_RECV_BUFFER_SIZE);
2963

    
2964
  if (buf == NULL) {
2965
    DBG(("OOM"));
2966
    return;
2967
  }
2968

    
2969
#ifdef MG_ENABLE_SSL
2970
  if (conn->ssl != NULL) {
2971
    if (conn->flags & MG_F_SSL_HANDSHAKE_DONE) {
2972
      /* SSL library may have more bytes ready to read then we ask to read.
2973
       * Therefore, read in a loop until we read everything. Without the loop,
2974
       * we skip to the next select() cycle which can just timeout. */
2975
      while ((n = SSL_read(conn->ssl, buf, MG_TCP_RECV_BUFFER_SIZE)) > 0) {
2976
        DBG(("%p %d bytes <- %d (SSL)", conn, n, conn->sock));
2977
        mg_if_recv_tcp_cb(conn, buf, n);
2978
        buf = NULL;
2979
        if (conn->flags & MG_F_CLOSE_IMMEDIATELY) break;
2980
        /* buf has been freed, we need a new one. */
2981
        buf = (char *) MG_MALLOC(MG_TCP_RECV_BUFFER_SIZE);
2982
        if (buf == NULL) break;
2983
      }
2984
      MG_FREE(buf);
2985
      mg_ssl_err(conn, n);
2986
    } else {
2987
      MG_FREE(buf);
2988
      mg_ssl_begin(conn);
2989
      return;
2990
    }
2991
  } else
2992
#endif
2993
  {
2994
    n = (int) MG_RECV_FUNC(conn->sock, buf,
2995
                           recv_avail_size(conn, MG_TCP_RECV_BUFFER_SIZE), 0);
2996
    if (n > 0) {
2997
      DBG(("%p %d bytes (PLAIN) <- %d", conn, n, conn->sock));
2998
      mg_if_recv_tcp_cb(conn, buf, n);
2999
    } else {
3000
      MG_FREE(buf);
3001
    }
3002
    if (mg_is_error(n)) {
3003
      conn->flags |= MG_F_CLOSE_IMMEDIATELY;
3004
    }
3005
  }
3006
}
3007

    
3008
static int mg_recvfrom(struct mg_connection *nc, union socket_address *sa,
3009
                       socklen_t *sa_len, char **buf) {
3010
  int n;
3011
  *buf = (char *) MG_MALLOC(MG_UDP_RECV_BUFFER_SIZE);
3012
  if (*buf == NULL) {
3013
    DBG(("Out of memory"));
3014
    return -ENOMEM;
3015
  }
3016
  n = recvfrom(nc->sock, *buf, MG_UDP_RECV_BUFFER_SIZE, 0, &sa->sa, sa_len);
3017
  if (n <= 0) {
3018
    DBG(("%p recvfrom: %s", nc, strerror(errno)));
3019
    MG_FREE(*buf);
3020
  }
3021
  return n;
3022
}
3023

    
3024
static void mg_handle_udp_read(struct mg_connection *nc) {
3025
  char *buf = NULL;
3026
  union socket_address sa;
3027
  socklen_t sa_len = sizeof(sa);
3028
  int n = mg_recvfrom(nc, &sa, &sa_len, &buf);
3029
  DBG(("%p %d bytes from %s:%d", nc, n, inet_ntoa(nc->sa.sin.sin_addr),
3030
       ntohs(nc->sa.sin.sin_port)));
3031
  mg_if_recv_udp_cb(nc, buf, n, &sa, sa_len);
3032
}
3033

    
3034
#define _MG_F_FD_CAN_READ 1
3035
#define _MG_F_FD_CAN_WRITE 1 << 1
3036
#define _MG_F_FD_ERROR 1 << 2
3037

    
3038
void mg_mgr_handle_conn(struct mg_connection *nc, int fd_flags, time_t now) {
3039
  DBG(("%p fd=%d fd_flags=%d nc_flags=%lu rmbl=%d smbl=%d", nc, nc->sock,
3040
       fd_flags, nc->flags, (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len));
3041

    
3042
  if (nc->flags & MG_F_CONNECTING) {
3043
    if (fd_flags != 0) {
3044
      int err = 0;
3045
#if !defined(MG_CC3200) && !defined(MG_ESP8266)
3046
      if (!(nc->flags & MG_F_UDP)) {
3047
        socklen_t len = sizeof(err);
3048
        int ret =
3049
            getsockopt(nc->sock, SOL_SOCKET, SO_ERROR, (char *) &err, &len);
3050
        if (ret != 0) err = 1;
3051
      }
3052
#else
3053
/* On CC3200 and ESP8266 we use blocking connect. If we got as far as
3054
 * this, it means connect() was successful.
3055
 * TODO(rojer): Figure out why it fails where blocking succeeds.
3056
 */
3057
#endif
3058
      mg_if_connect_cb(nc, err);
3059
    } else if (nc->err != 0) {
3060
      mg_if_connect_cb(nc, nc->err);
3061
    }
3062
  }
3063

    
3064
  if (fd_flags & _MG_F_FD_CAN_READ) {
3065
    if (nc->flags & MG_F_UDP) {
3066
      mg_handle_udp_read(nc);
3067
    } else {
3068
      if (nc->flags & MG_F_LISTENING) {
3069
        /*
3070
         * We're not looping here, and accepting just one connection at
3071
         * a time. The reason is that eCos does not respect non-blocking
3072
         * flag on a listening socket and hangs in a loop.
3073
         */
3074
        if (fd_flags & _MG_F_FD_CAN_READ) mg_accept_conn(nc);
3075
        return;
3076
      } else {
3077
        mg_read_from_socket(nc);
3078
      }
3079
    }
3080
    if (nc->flags & MG_F_CLOSE_IMMEDIATELY) return;
3081
  }
3082

    
3083
  if ((fd_flags & _MG_F_FD_CAN_WRITE) && nc->send_mbuf.len > 0) {
3084
    mg_write_to_socket(nc);
3085
  }
3086

    
3087
  if (!(fd_flags & (_MG_F_FD_CAN_READ | _MG_F_FD_CAN_WRITE))) {
3088
    mg_if_poll(nc, now);
3089
  }
3090

    
3091
  DBG(("%p after fd=%d nc_flags=%lu rmbl=%d smbl=%d", nc, nc->sock, nc->flags,
3092
       (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len));
3093
}
3094

    
3095
#ifndef MG_DISABLE_SOCKETPAIR
3096
static void mg_mgr_handle_ctl_sock(struct mg_mgr *mgr) {
3097
  struct ctl_msg ctl_msg;
3098
  int len =
3099
      (int) MG_RECV_FUNC(mgr->ctl[1], (char *) &ctl_msg, sizeof(ctl_msg), 0);
3100
  size_t dummy = MG_SEND_FUNC(mgr->ctl[1], ctl_msg.message, 1, 0);
3101
  (void) dummy; /* https://gcc.gnu.org/bugzilla/show_bug.cgi?id=25509 */
3102
  if (len >= (int) sizeof(ctl_msg.callback) && ctl_msg.callback != NULL) {
3103
    struct mg_connection *nc;
3104
    for (nc = mg_next(mgr, NULL); nc != NULL; nc = mg_next(mgr, nc)) {
3105
      ctl_msg.callback(nc, MG_EV_POLL, ctl_msg.message);
3106
    }
3107
  }
3108
}
3109
#endif
3110

    
3111
struct mg_connection *mg_add_sock(struct mg_mgr *s, sock_t sock,
3112
                                  mg_event_handler_t callback) {
3113
  struct mg_add_sock_opts opts;
3114
  memset(&opts, 0, sizeof(opts));
3115
  return mg_add_sock_opt(s, sock, callback, opts);
3116
}
3117

    
3118
struct mg_connection *mg_add_sock_opt(struct mg_mgr *s, sock_t sock,
3119
                                      mg_event_handler_t callback,
3120
                                      struct mg_add_sock_opts opts) {
3121
  struct mg_connection *nc = mg_create_connection(s, callback, opts);
3122
  if (nc != NULL) {
3123
    mg_sock_set(nc, sock);
3124
    mg_add_conn(nc->mgr, nc);
3125
  }
3126
  return nc;
3127
}
3128

    
3129
/* Associate a socket to a connection. */
3130
static void mg_sock_set(struct mg_connection *nc, sock_t sock) {
3131
  mg_set_non_blocking_mode(sock);
3132
  mg_set_close_on_exec(sock);
3133
  nc->sock = sock;
3134
  DBG(("%p %d", nc, sock));
3135
}
3136

    
3137
#if MG_MGR_EV_MGR == 1 /* epoll() */
3138

    
3139
#ifndef MG_EPOLL_MAX_EVENTS
3140
#define MG_EPOLL_MAX_EVENTS 100
3141
#endif
3142

    
3143
#define _MG_EPF_EV_EPOLLIN (1 << 0)
3144
#define _MG_EPF_EV_EPOLLOUT (1 << 1)
3145
#define _MG_EPF_NO_POLL (1 << 2)
3146

    
3147
uint32_t mg_epf_to_evflags(unsigned int epf) {
3148
  uint32_t result = 0;
3149
  if (epf & _MG_EPF_EV_EPOLLIN) result |= EPOLLIN;
3150
  if (epf & _MG_EPF_EV_EPOLLOUT) result |= EPOLLOUT;
3151
  return result;
3152
}
3153

    
3154
void mg_ev_mgr_epoll_set_flags(const struct mg_connection *nc,
3155
                               struct epoll_event *ev) {
3156
  /* NOTE: EPOLLERR and EPOLLHUP are always enabled. */
3157
  ev->events = 0;
3158
  if ((nc->flags & MG_F_LISTENING) || nc->recv_mbuf.len < nc->recv_mbuf_limit) {
3159
    ev->events |= EPOLLIN;
3160
  }
3161
  if ((nc->flags & MG_F_CONNECTING) || (nc->send_mbuf.len > 0)) {
3162
    ev->events |= EPOLLOUT;
3163
  }
3164
}
3165

    
3166
void mg_ev_mgr_epoll_ctl(struct mg_connection *nc, int op) {
3167
  int epoll_fd = (intptr_t) nc->mgr->mgr_data;
3168
  struct epoll_event ev;
3169
  assert(op == EPOLL_CTL_ADD || op == EPOLL_CTL_MOD || EPOLL_CTL_DEL);
3170
  DBG(("%p %d %d", nc, nc->sock, op));
3171
  if (nc->sock == INVALID_SOCKET) return;
3172
  if (op != EPOLL_CTL_DEL) {
3173
    mg_ev_mgr_epoll_set_flags(nc, &ev);
3174
    if (op == EPOLL_CTL_MOD) {
3175
      uint32_t old_ev_flags = mg_epf_to_evflags((intptr_t) nc->mgr_data);
3176
      if (ev.events == old_ev_flags) return;
3177
    }
3178
    ev.data.ptr = nc;
3179
  }
3180
  if (epoll_ctl(epoll_fd, op, nc->sock, &ev) != 0) {
3181
    perror("epoll_ctl");
3182
    abort();
3183
  }
3184
}
3185

    
3186
void mg_ev_mgr_init(struct mg_mgr *mgr) {
3187
  int epoll_fd;
3188
  DBG(("%p using epoll()", mgr));
3189
#ifndef MG_DISABLE_SOCKETPAIR
3190
  do {
3191
    mg_socketpair(mgr->ctl, SOCK_DGRAM);
3192
  } while (mgr->ctl[0] == INVALID_SOCKET);
3193
#endif
3194
  epoll_fd = epoll_create(MG_EPOLL_MAX_EVENTS /* unused but required */);
3195
  if (epoll_fd < 0) {
3196
    perror("epoll_ctl");
3197
    abort();
3198
  }
3199
  mgr->mgr_data = (void *) ((intptr_t) epoll_fd);
3200
  if (mgr->ctl[1] != INVALID_SOCKET) {
3201
    struct epoll_event ev;
3202
    ev.events = EPOLLIN;
3203
    ev.data.ptr = NULL;
3204
    if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, mgr->ctl[1], &ev) != 0) {
3205
      perror("epoll_ctl");
3206
      abort();
3207
    }
3208
  }
3209
}
3210

    
3211
void mg_ev_mgr_free(struct mg_mgr *mgr) {
3212
  int epoll_fd = (intptr_t) mgr->mgr_data;
3213
  close(epoll_fd);
3214
}
3215

    
3216
void mg_ev_mgr_add_conn(struct mg_connection *nc) {
3217
  if (!(nc->flags & MG_F_UDP) || nc->listener == NULL) {
3218
    mg_ev_mgr_epoll_ctl(nc, EPOLL_CTL_ADD);
3219
  }
3220
}
3221

    
3222
void mg_ev_mgr_remove_conn(struct mg_connection *nc) {
3223
  if (!(nc->flags & MG_F_UDP) || nc->listener == NULL) {
3224
    mg_ev_mgr_epoll_ctl(nc, EPOLL_CTL_DEL);
3225
  }
3226
}
3227

    
3228
time_t mg_mgr_poll(struct mg_mgr *mgr, int timeout_ms) {
3229
  int epoll_fd = (intptr_t) mgr->mgr_data;
3230
  struct epoll_event events[MG_EPOLL_MAX_EVENTS];
3231
  struct mg_connection *nc, *next;
3232
  int num_ev, fd_flags;
3233
  time_t now;
3234

    
3235
  num_ev = epoll_wait(epoll_fd, events, MG_EPOLL_MAX_EVENTS, timeout_ms);
3236
  now = time(NULL);
3237
  DBG(("epoll_wait @ %ld num_ev=%d", (long) now, num_ev));
3238

    
3239
  while (num_ev-- > 0) {
3240
    intptr_t epf;
3241
    struct epoll_event *ev = events + num_ev;
3242
    nc = (struct mg_connection *) ev->data.ptr;
3243
    if (nc == NULL) {
3244
      mg_mgr_handle_ctl_sock(mgr);
3245
      continue;
3246
    }
3247
    fd_flags = ((ev->events & (EPOLLIN | EPOLLHUP)) ? _MG_F_FD_CAN_READ : 0) |
3248
               ((ev->events & (EPOLLOUT)) ? _MG_F_FD_CAN_WRITE : 0) |
3249
               ((ev->events & (EPOLLERR)) ? _MG_F_FD_ERROR : 0);
3250
    mg_mgr_handle_conn(nc, fd_flags, now);
3251
    epf = (intptr_t) nc->mgr_data;
3252
    epf ^= _MG_EPF_NO_POLL;
3253
    nc->mgr_data = (void *) epf;
3254
  }
3255

    
3256
  for (nc = mgr->active_connections; nc != NULL; nc = next) {
3257
    next = nc->next;
3258
    if (!(((intptr_t) nc->mgr_data) & _MG_EPF_NO_POLL)) {
3259
      mg_mgr_handle_conn(nc, 0, now);
3260
    } else {
3261
      intptr_t epf = (intptr_t) nc->mgr_data;
3262
      epf ^= _MG_EPF_NO_POLL;
3263
      nc->mgr_data = (void *) epf;
3264
    }
3265
    if ((nc->flags & MG_F_CLOSE_IMMEDIATELY) ||
3266
        (nc->send_mbuf.len == 0 && (nc->flags & MG_F_SEND_AND_CLOSE))) {
3267
      mg_close_conn(nc);
3268
    } else {
3269
      if (!(nc->flags & MG_F_UDP) || nc->listener == NULL) {
3270
        mg_ev_mgr_epoll_ctl(nc, EPOLL_CTL_MOD);
3271
      } else {
3272
        /* This is a kludge, but... */
3273
        if (nc->send_mbuf.len > 0) {
3274
          mg_mgr_handle_conn(nc, _MG_F_FD_CAN_WRITE, now);
3275
        }
3276
      }
3277
    }
3278
  }
3279

    
3280
  return now;
3281
}
3282

    
3283
#else /* select() */
3284

    
3285
void mg_ev_mgr_init(struct mg_mgr *mgr) {
3286
  (void) mgr;
3287
  DBG(("%p using select()", mgr));
3288
#ifndef MG_DISABLE_SOCKETPAIR
3289
  do {
3290
    mg_socketpair(mgr->ctl, SOCK_DGRAM);
3291
  } while (mgr->ctl[0] == INVALID_SOCKET);
3292
#endif
3293
}
3294

    
3295
void mg_ev_mgr_free(struct mg_mgr *mgr) {
3296
  (void) mgr;
3297
}
3298

    
3299
void mg_ev_mgr_add_conn(struct mg_connection *nc) {
3300
  (void) nc;
3301
}
3302

    
3303
void mg_ev_mgr_remove_conn(struct mg_connection *nc) {
3304
  (void) nc;
3305
}
3306

    
3307
void mg_add_to_set(sock_t sock, fd_set *set, sock_t *max_fd) {
3308
  if (sock != INVALID_SOCKET) {
3309
    FD_SET(sock, set);
3310
    if (*max_fd == INVALID_SOCKET || sock > *max_fd) {
3311
      *max_fd = sock;
3312
    }
3313
  }
3314
}
3315

    
3316
time_t mg_mgr_poll(struct mg_mgr *mgr, int milli) {
3317
  time_t now = time(NULL);
3318
  struct mg_connection *nc, *tmp;
3319
  struct timeval tv;
3320
  fd_set read_set, write_set, err_set;
3321
  sock_t max_fd = INVALID_SOCKET;
3322
  int num_fds, num_selected;
3323

    
3324
  FD_ZERO(&read_set);
3325
  FD_ZERO(&write_set);
3326
  FD_ZERO(&err_set);
3327
  mg_add_to_set(mgr->ctl[1], &read_set, &max_fd);
3328

    
3329
  for (nc = mgr->active_connections, num_fds = 0; nc != NULL; nc = tmp) {
3330
    tmp = nc->next;
3331

    
3332
    if (nc->sock == INVALID_SOCKET) {
3333
      mg_mgr_handle_conn(nc, 0, now);
3334
      continue;
3335
    }
3336

    
3337
    num_fds++;
3338

    
3339
    if (!(nc->flags & MG_F_WANT_WRITE) &&
3340
        nc->recv_mbuf.len < nc->recv_mbuf_limit &&
3341
        (!(nc->flags & MG_F_UDP) || nc->listener == NULL)) {
3342
      mg_add_to_set(nc->sock, &read_set, &max_fd);
3343
    }
3344

    
3345
    if (((nc->flags & MG_F_CONNECTING) && !(nc->flags & MG_F_WANT_READ)) ||
3346
        (nc->send_mbuf.len > 0 && !(nc->flags & MG_F_CONNECTING))) {
3347
      mg_add_to_set(nc->sock, &write_set, &max_fd);
3348
      mg_add_to_set(nc->sock, &err_set, &max_fd);
3349
    }
3350
  }
3351

    
3352
  tv.tv_sec = milli / 1000;
3353
  tv.tv_usec = (milli % 1000) * 1000;
3354

    
3355
  num_selected = select((int) max_fd + 1, &read_set, &write_set, &err_set, &tv);
3356
  now = time(NULL);
3357
  DBG(("select @ %ld num_ev=%d of %d", (long) now, num_selected, num_fds));
3358

    
3359
#ifndef MG_DISABLE_SOCKETPAIR
3360
  if (num_selected > 0 && mgr->ctl[1] != INVALID_SOCKET &&
3361
      FD_ISSET(mgr->ctl[1], &read_set)) {
3362
    mg_mgr_handle_ctl_sock(mgr);
3363
  }
3364
#endif
3365

    
3366
  for (nc = mgr->active_connections; nc != NULL; nc = tmp) {
3367
    int fd_flags = 0;
3368
    if (num_selected > 0) {
3369
      fd_flags = (FD_ISSET(nc->sock, &read_set) ? _MG_F_FD_CAN_READ : 0) |
3370
                 (FD_ISSET(nc->sock, &write_set) ? _MG_F_FD_CAN_WRITE : 0) |
3371
                 (FD_ISSET(nc->sock, &err_set) ? _MG_F_FD_ERROR : 0);
3372
    }
3373
#ifdef MG_CC3200
3374
    // CC3200 does not report UDP sockets as writeable.
3375
    if (nc->flags & MG_F_UDP &&
3376
        (nc->send_mbuf.len > 0 || nc->flags & MG_F_CONNECTING)) {
3377
      fd_flags |= _MG_F_FD_CAN_WRITE;
3378
    }
3379
#endif
3380
#ifdef MG_LWIP
3381
    /* With LWIP socket emulation layer, we don't get write events */
3382
    fd_flags |= _MG_F_FD_CAN_WRITE;
3383
#endif
3384
    tmp = nc->next;
3385
    mg_mgr_handle_conn(nc, fd_flags, now);
3386
  }
3387

    
3388
  for (nc = mgr->active_connections; nc != NULL; nc = tmp) {
3389
    tmp = nc->next;
3390
    if ((nc->flags & MG_F_CLOSE_IMMEDIATELY) ||
3391
        (nc->send_mbuf.len == 0 && (nc->flags & MG_F_SEND_AND_CLOSE))) {
3392
      mg_close_conn(nc);
3393
    }
3394
  }
3395

    
3396
  return now;
3397
}
3398

    
3399
#endif
3400

    
3401
#ifndef MG_DISABLE_SOCKETPAIR
3402
int mg_socketpair(sock_t sp[2], int sock_type) {
3403
  union socket_address sa;
3404
  sock_t sock;
3405
  socklen_t len = sizeof(sa.sin);
3406
  int ret = 0;
3407

    
3408
  sock = sp[0] = sp[1] = INVALID_SOCKET;
3409

    
3410
  (void) memset(&sa, 0, sizeof(sa));
3411
  sa.sin.sin_family = AF_INET;
3412
  sa.sin.sin_port = htons(0);
3413
  sa.sin.sin_addr.s_addr = htonl(0x7f000001); /* 127.0.0.1 */
3414

    
3415
  if ((sock = socket(AF_INET, sock_type, 0)) == INVALID_SOCKET) {
3416
  } else if (bind(sock, &sa.sa, len) != 0) {
3417
  } else if (sock_type == SOCK_STREAM && listen(sock, 1) != 0) {
3418
  } else if (getsockname(sock, &sa.sa, &len) != 0) {
3419
  } else if ((sp[0] = socket(AF_INET, sock_type, 0)) == INVALID_SOCKET) {
3420
  } else if (connect(sp[0], &sa.sa, len) != 0) {
3421
  } else if (sock_type == SOCK_DGRAM &&
3422
             (getsockname(sp[0], &sa.sa, &len) != 0 ||
3423
              connect(sock, &sa.sa, len) != 0)) {
3424
  } else if ((sp[1] = (sock_type == SOCK_DGRAM ? sock
3425
                                               : accept(sock, &sa.sa, &len))) ==
3426
             INVALID_SOCKET) {
3427
  } else {
3428
    mg_set_close_on_exec(sp[0]);
3429
    mg_set_close_on_exec(sp[1]);
3430
    if (sock_type == SOCK_STREAM) closesocket(sock);
3431
    ret = 1;
3432
  }
3433

    
3434
  if (!ret) {
3435
    if (sp[0] != INVALID_SOCKET) closesocket(sp[0]);
3436
    if (sp[1] != INVALID_SOCKET) closesocket(sp[1]);
3437
    if (sock != INVALID_SOCKET) closesocket(sock);
3438
    sock = sp[0] = sp[1] = INVALID_SOCKET;
3439
  }
3440

    
3441
  return ret;
3442
}
3443
#endif /* MG_DISABLE_SOCKETPAIR */
3444

    
3445
void mg_sock_to_str(sock_t sock, char *buf, size_t len, int flags) {
3446
  union socket_address sa;
3447
#ifndef MG_CC3200
3448
  socklen_t slen = sizeof(sa);
3449
#endif
3450

    
3451
  memset(&sa, 0, sizeof(sa));
3452
#ifndef MG_CC3200
3453
  if (flags & MG_SOCK_STRINGIFY_REMOTE) {
3454
    getpeername(sock, &sa.sa, &slen);
3455
  } else {
3456
    getsockname(sock, &sa.sa, &slen);
3457
  }
3458
#endif
3459
  mg_sock_addr_to_str(&sa, buf, len, flags);
3460
}
3461

    
3462
#endif /* !MG_DISABLE_SOCKET_IF */
3463
#ifdef NS_MODULE_LINES
3464
#line 1 "src/multithreading.c"
3465
/**/
3466
#endif
3467
/*
3468
 * Copyright (c) 2014 Cesanta Software Limited
3469
 * All rights reserved
3470
 */
3471

    
3472
/* Amalgamated: #include "internal.h" */
3473

    
3474
#ifdef MG_ENABLE_THREADS
3475

    
3476
static void multithreaded_ev_handler(struct mg_connection *c, int ev, void *p);
3477

    
3478
/*
3479
 * This thread function executes user event handler.
3480
 * It runs an event manager that has only one connection, until that
3481
 * connection is alive.
3482
 */
3483
static void *per_connection_thread_function(void *param) {
3484
  struct mg_connection *c = (struct mg_connection *) param;
3485
  struct mg_mgr m;
3486

    
3487
  mg_mgr_init(&m, NULL);
3488
  mg_add_conn(&m, c);
3489
  while (m.active_connections != NULL) {
3490
    mg_mgr_poll(&m, 1000);
3491
  }
3492
  mg_mgr_free(&m);
3493

    
3494
  return param;
3495
}
3496

    
3497
static void link_conns(struct mg_connection *c1, struct mg_connection *c2) {
3498
  c1->priv_2 = c2;
3499
  c2->priv_2 = c1;
3500
}
3501

    
3502
static void unlink_conns(struct mg_connection *c) {
3503
  struct mg_connection *peer = (struct mg_connection *) c->priv_2;
3504
  if (peer != NULL) {
3505
    peer->flags |= MG_F_SEND_AND_CLOSE;
3506
    peer->priv_2 = NULL;
3507
  }
3508
  c->priv_2 = NULL;
3509
}
3510

    
3511
static void forwarder_ev_handler(struct mg_connection *c, int ev, void *p) {
3512
  (void) p;
3513
  if (ev == MG_EV_RECV && c->priv_2) {
3514
    mg_forward(c, (struct mg_connection *) c->priv_2);
3515
  } else if (ev == MG_EV_CLOSE) {
3516
    unlink_conns(c);
3517
  }
3518
}
3519

    
3520
static void spawn_handling_thread(struct mg_connection *nc) {
3521
  struct mg_mgr dummy;
3522
  sock_t sp[2];
3523
  struct mg_connection *c[2];
3524

    
3525
  /*
3526
   * Create a socket pair, and wrap each socket into the connection with
3527
   * dummy event manager.
3528
   * c[0] stays in this thread, c[1] goes to another thread.
3529
   */
3530
  mg_socketpair(sp, SOCK_STREAM);
3531
  memset(&dummy, 0, sizeof(dummy));
3532
  c[0] = mg_add_sock(&dummy, sp[0], forwarder_ev_handler);
3533
  c[1] = mg_add_sock(&dummy, sp[1], (mg_event_handler_t) nc->listener->priv_1);
3534

    
3535
  /* Interlink client connection with c[0] */
3536
  link_conns(c[0], nc);
3537

    
3538
  /*
3539
   * Switch c[0] manager from the dummy one to the real one. c[1] manager
3540
   * will be set in another thread, allocated on stack of that thread.
3541
   */
3542
  mg_add_conn(nc->mgr, c[0]);
3543

    
3544
  /*
3545
   * Dress c[1] as nc.
3546
   * TODO(lsm): code in accept_conn() looks similar. Refactor.
3547
   */
3548
  c[1]->listener = nc->listener;
3549
  c[1]->proto_handler = nc->proto_handler;
3550
  c[1]->proto_data = nc->proto_data;
3551
  c[1]->user_data = nc->user_data;
3552

    
3553
  mg_start_thread(per_connection_thread_function, c[1]);
3554
}
3555

    
3556
static void multithreaded_ev_handler(struct mg_connection *c, int ev, void *p) {
3557
  (void) p;
3558
  if (ev == MG_EV_ACCEPT) {
3559
    spawn_handling_thread(c);
3560
    c->handler = forwarder_ev_handler;
3561
  }
3562
}
3563

    
3564
void mg_enable_multithreading(struct mg_connection *nc) {
3565
  /* Wrap user event handler into our multithreaded_ev_handler */
3566
  nc->priv_1 = (void *) nc->handler;
3567
  nc->handler = multithreaded_ev_handler;
3568
}
3569
#endif
3570
#ifdef NS_MODULE_LINES
3571
#line 1 "src/http.c"
3572
/**/
3573
#endif
3574
/*
3575
 * Copyright (c) 2014 Cesanta Software Limited
3576
 * All rights reserved
3577
 */
3578

    
3579
#ifndef MG_DISABLE_HTTP
3580

    
3581
/* Amalgamated: #include "internal.h" */
3582

    
3583
enum http_proto_data_type { DATA_NONE, DATA_FILE, DATA_PUT, DATA_CGI };
3584

    
3585
struct proto_data_http {
3586
  FILE *fp;         /* Opened file. */
3587
  int64_t cl;       /* Content-Length. How many bytes to send. */
3588
  int64_t sent;     /* How many bytes have been already sent. */
3589
  int64_t body_len; /* How many bytes of chunked body was reassembled. */
3590
  struct mg_connection *cgi_nc;
3591
  enum http_proto_data_type type;
3592
};
3593

    
3594
/*
3595
 * This structure helps to create an environment for the spawned CGI program.
3596
 * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
3597
 * last element must be NULL.
3598
 * However, on Windows there is a requirement that all these VARIABLE=VALUE\0
3599
 * strings must reside in a contiguous buffer. The end of the buffer is
3600
 * marked by two '\0' characters.
3601
 * We satisfy both worlds: we create an envp array (which is vars), all
3602
 * entries are actually pointers inside buf.
3603
 */
3604
struct cgi_env_block {
3605
  struct mg_connection *nc;
3606
  char buf[MG_CGI_ENVIRONMENT_SIZE];       /* Environment buffer */
3607
  const char *vars[MG_MAX_CGI_ENVIR_VARS]; /* char *envp[] */
3608
  int len;                                 /* Space taken */
3609
  int nvars;                               /* Number of variables in envp[] */
3610
};
3611

    
3612
#define MIME_ENTRY(_ext, _type) \
3613
  { _ext, sizeof(_ext) - 1, _type }
3614
static const struct {
3615
  const char *extension;
3616
  size_t ext_len;
3617
  const char *mime_type;
3618
} static_builtin_mime_types[] = {
3619
    MIME_ENTRY("html", "text/html"),
3620
    MIME_ENTRY("html", "text/html"),
3621
    MIME_ENTRY("htm", "text/html"),
3622
    MIME_ENTRY("shtm", "text/html"),
3623
    MIME_ENTRY("shtml", "text/html"),
3624
    MIME_ENTRY("css", "text/css"),
3625
    MIME_ENTRY("js", "application/x-javascript"),
3626
    MIME_ENTRY("ico", "image/x-icon"),
3627
    MIME_ENTRY("gif", "image/gif"),
3628
    MIME_ENTRY("jpg", "image/jpeg"),
3629
    MIME_ENTRY("jpeg", "image/jpeg"),
3630
    MIME_ENTRY("png", "image/png"),
3631
    MIME_ENTRY("svg", "image/svg+xml"),
3632
    MIME_ENTRY("txt", "text/plain"),
3633
    MIME_ENTRY("torrent", "application/x-bittorrent"),
3634
    MIME_ENTRY("wav", "audio/x-wav"),
3635
    MIME_ENTRY("mp3", "audio/x-mp3"),
3636
    MIME_ENTRY("mid", "audio/mid"),
3637
    MIME_ENTRY("m3u", "audio/x-mpegurl"),
3638
    MIME_ENTRY("ogg", "application/ogg"),
3639
    MIME_ENTRY("ram", "audio/x-pn-realaudio"),
3640
    MIME_ENTRY("xml", "text/xml"),
3641
    MIME_ENTRY("ttf", "application/x-font-ttf"),
3642
    MIME_ENTRY("json", "application/json"),
3643
    MIME_ENTRY("xslt", "application/xml"),
3644
    MIME_ENTRY("xsl", "application/xml"),
3645
    MIME_ENTRY("ra", "audio/x-pn-realaudio"),
3646
    MIME_ENTRY("doc", "application/msword"),
3647
    MIME_ENTRY("exe", "application/octet-stream"),
3648
    MIME_ENTRY("zip", "application/x-zip-compressed"),
3649
    MIME_ENTRY("xls", "application/excel"),
3650
    MIME_ENTRY("tgz", "application/x-tar-gz"),
3651
    MIME_ENTRY("tar", "application/x-tar"),
3652
    MIME_ENTRY("gz", "application/x-gunzip"),
3653
    MIME_ENTRY("arj", "application/x-arj-compressed"),
3654
    MIME_ENTRY("rar", "application/x-rar-compressed"),
3655
    MIME_ENTRY("rtf", "application/rtf"),
3656
    MIME_ENTRY("pdf", "application/pdf"),
3657
    MIME_ENTRY("swf", "application/x-shockwave-flash"),
3658
    MIME_ENTRY("mpg", "video/mpeg"),
3659
    MIME_ENTRY("webm", "video/webm"),
3660
    MIME_ENTRY("mpeg", "video/mpeg"),
3661
    MIME_ENTRY("mov", "video/quicktime"),
3662
    MIME_ENTRY("mp4", "video/mp4"),
3663
    MIME_ENTRY("m4v", "video/x-m4v"),
3664
    MIME_ENTRY("asf", "video/x-ms-asf"),
3665
    MIME_ENTRY("avi", "video/x-msvideo"),
3666
    MIME_ENTRY("bmp", "image/bmp"),
3667
    {NULL, 0, NULL}};
3668

    
3669
#ifndef MG_DISABLE_FILESYSTEM
3670

    
3671
#ifndef MG_DISABLE_DAV
3672
static int mg_mkdir(const char *path, uint32_t mode) {
3673
#ifndef _WIN32
3674
  return mkdir(path, mode);
3675
#else
3676
  (void) mode;
3677
  return _mkdir(path);
3678
#endif
3679
}
3680
#endif
3681

    
3682
static struct mg_str get_mime_type(const char *path, const char *dflt,
3683
                                   const struct mg_serve_http_opts *opts) {
3684
  const char *ext, *overrides;
3685
  size_t i, path_len;
3686
  struct mg_str r, k, v;
3687

    
3688
  path_len = strlen(path);
3689

    
3690
  overrides = opts->custom_mime_types;
3691
  while ((overrides = mg_next_comma_list_entry(overrides, &k, &v)) != NULL) {
3692
    ext = path + (path_len - k.len);
3693
    if (path_len > k.len && mg_vcasecmp(&k, ext) == 0) {
3694
      return v;
3695
    }
3696
  }
3697

    
3698
  for (i = 0; static_builtin_mime_types[i].extension != NULL; i++) {
3699
    ext = path + (path_len - static_builtin_mime_types[i].ext_len);
3700
    if (path_len > static_builtin_mime_types[i].ext_len && ext[-1] == '.' &&
3701
        mg_casecmp(ext, static_builtin_mime_types[i].extension) == 0) {
3702
      r.p = static_builtin_mime_types[i].mime_type;
3703
      r.len = strlen(r.p);
3704
      return r;
3705
    }
3706
  }
3707

    
3708
  r.p = dflt;
3709
  r.len = strlen(r.p);
3710
  return r;
3711
}
3712
#endif
3713

    
3714
/*
3715
 * Check whether full request is buffered. Return:
3716
 *   -1  if request is malformed
3717
 *    0  if request is not yet fully buffered
3718
 *   >0  actual request length, including last \r\n\r\n
3719
 */
3720
static int get_request_len(const char *s, int buf_len) {
3721
  const unsigned char *buf = (unsigned char *) s;
3722
  int i;
3723

    
3724
  for (i = 0; i < buf_len; i++) {
3725
    if (!isprint(buf[i]) && buf[i] != '\r' && buf[i] != '\n' && buf[i] < 128) {
3726
      return -1;
3727
    } else if (buf[i] == '\n' && i + 1 < buf_len && buf[i + 1] == '\n') {
3728
      return i + 2;
3729
    } else if (buf[i] == '\n' && i + 2 < buf_len && buf[i + 1] == '\r' &&
3730
               buf[i + 2] == '\n') {
3731
      return i + 3;
3732
    }
3733
  }
3734

    
3735
  return 0;
3736
}
3737

    
3738
static const char *parse_http_headers(const char *s, const char *end, int len,
3739
                                      struct http_message *req) {
3740
  int i;
3741
  for (i = 0; i < (int) ARRAY_SIZE(req->header_names) - 1; i++) {
3742
    struct mg_str *k = &req->header_names[i], *v = &req->header_values[i];
3743

    
3744
    s = mg_skip(s, end, ": ", k);
3745
    s = mg_skip(s, end, "\r\n", v);
3746

    
3747
    while (v->len > 0 && v->p[v->len - 1] == ' ') {
3748
      v->len--; /* Trim trailing spaces in header value */
3749
    }
3750

    
3751
    if (k->len == 0 || v->len == 0) {
3752
      k->p = v->p = NULL;
3753
      k->len = v->len = 0;
3754
      break;
3755
    }
3756

    
3757
    if (!mg_ncasecmp(k->p, "Content-Length", 14)) {
3758
      req->body.len = to64(v->p);
3759
      req->message.len = len + req->body.len;
3760
    }
3761
  }
3762

    
3763
  return s;
3764
}
3765

    
3766
int mg_parse_http(const char *s, int n, struct http_message *hm, int is_req) {
3767
  const char *end, *qs;
3768
  int len = get_request_len(s, n);
3769

    
3770
  if (len <= 0) return len;
3771

    
3772
  memset(hm, 0, sizeof(*hm));
3773
  hm->message.p = s;
3774
  hm->body.p = s + len;
3775
  hm->message.len = hm->body.len = (size_t) ~0;
3776
  end = s + len;
3777

    
3778
  /* Request is fully buffered. Skip leading whitespaces. */
3779
  while (s < end && isspace(*(unsigned char *) s)) s++;
3780

    
3781
  if (is_req) {
3782
    /* Parse request line: method, URI, proto */
3783
    s = mg_skip(s, end, " ", &hm->method);
3784
    s = mg_skip(s, end, " ", &hm->uri);
3785
    s = mg_skip(s, end, "\r\n", &hm->proto);
3786
    if (hm->uri.p <= hm->method.p || hm->proto.p <= hm->uri.p) return -1;
3787

    
3788
    /* If URI contains '?' character, initialize query_string */
3789
    if ((qs = (char *) memchr(hm->uri.p, '?', hm->uri.len)) != NULL) {
3790
      hm->query_string.p = qs + 1;
3791
      hm->query_string.len = &hm->uri.p[hm->uri.len] - (qs + 1);
3792
      hm->uri.len = qs - hm->uri.p;
3793
    }
3794
  } else {
3795
    s = mg_skip(s, end, " ", &hm->proto);
3796
    if (end - s < 4 || s[3] != ' ') return -1;
3797
    hm->resp_code = atoi(s);
3798
    if (hm->resp_code < 100 || hm->resp_code >= 600) return -1;
3799
    s += 4;
3800
    s = mg_skip(s, end, "\r\n", &hm->resp_status_msg);
3801
  }
3802

    
3803
  s = parse_http_headers(s, end, len, hm);
3804

    
3805
  /*
3806
   * mg_parse_http() is used to parse both HTTP requests and HTTP
3807
   * responses. If HTTP response does not have Content-Length set, then
3808
   * body is read until socket is closed, i.e. body.len is infinite (~0).
3809
   *
3810
   * For HTTP requests though, according to
3811
   * http://tools.ietf.org/html/rfc7231#section-8.1.3,
3812
   * only POST and PUT methods have defined body semantics.
3813
   * Therefore, if Content-Length is not specified and methods are
3814
   * not one of PUT or POST, set body length to 0.
3815
   *
3816
   * So,
3817
   * if it is HTTP request, and Content-Length is not set,
3818
   * and method is not (PUT or POST) then reset body length to zero.
3819
   */
3820
  if (hm->body.len == (size_t) ~0 && is_req &&
3821
      mg_vcasecmp(&hm->method, "PUT") != 0 &&
3822
      mg_vcasecmp(&hm->method, "POST") != 0) {
3823
    hm->body.len = 0;
3824
    hm->message.len = len;
3825
  }
3826

    
3827
  return len;
3828
}
3829

    
3830
struct mg_str *mg_get_http_header(struct http_message *hm, const char *name) {
3831
  size_t i, len = strlen(name);
3832

    
3833
  for (i = 0; hm->header_names[i].len > 0; i++) {
3834
    struct mg_str *h = &hm->header_names[i], *v = &hm->header_values[i];
3835
    if (h->p != NULL && h->len == len && !mg_ncasecmp(h->p, name, len))
3836
      return v;
3837
  }
3838

    
3839
  return NULL;
3840
}
3841

    
3842
#ifndef MG_DISABLE_HTTP_WEBSOCKET
3843

    
3844
static int is_ws_fragment(unsigned char flags) {
3845
  return (flags & 0x80) == 0 || (flags & 0x0f) == 0;
3846
}
3847

    
3848
static int is_ws_first_fragment(unsigned char flags) {
3849
  return (flags & 0x80) == 0 && (flags & 0x0f) != 0;
3850
}
3851

    
3852
static void handle_incoming_websocket_frame(struct mg_connection *nc,
3853
                                            struct websocket_message *wsm) {
3854
  if (wsm->flags & 0x8) {
3855
    mg_call(nc, nc->handler, MG_EV_WEBSOCKET_CONTROL_FRAME, wsm);
3856
  } else {
3857
    mg_call(nc, nc->handler, MG_EV_WEBSOCKET_FRAME, wsm);
3858
  }
3859
}
3860

    
3861
static int deliver_websocket_data(struct mg_connection *nc) {
3862
  /* Using unsigned char *, cause of integer arithmetic below */
3863
  uint64_t i, data_len = 0, frame_len = 0, buf_len = nc->recv_mbuf.len, len,
3864
              mask_len = 0, header_len = 0;
3865
  unsigned char *p = (unsigned char *) nc->recv_mbuf.buf, *buf = p,
3866
                *e = p + buf_len;
3867
  unsigned *sizep = (unsigned *) &p[1]; /* Size ptr for defragmented frames */
3868
  int ok, reass = buf_len > 0 && is_ws_fragment(p[0]) &&
3869
                  !(nc->flags & MG_F_WEBSOCKET_NO_DEFRAG);
3870

    
3871
  /* If that's a continuation frame that must be reassembled, handle it */
3872
  if (reass && !is_ws_first_fragment(p[0]) && buf_len >= 1 + sizeof(*sizep) &&
3873
      buf_len >= 1 + sizeof(*sizep) + *sizep) {
3874
    buf += 1 + sizeof(*sizep) + *sizep;
3875
    buf_len -= 1 + sizeof(*sizep) + *sizep;
3876
  }
3877

    
3878
  if (buf_len >= 2) {
3879
    len = buf[1] & 127;
3880
    mask_len = buf[1] & 128 ? 4 : 0;
3881
    if (len < 126 && buf_len >= mask_len) {
3882
      data_len = len;
3883
      header_len = 2 + mask_len;
3884
    } else if (len == 126 && buf_len >= 4 + mask_len) {
3885
      header_len = 4 + mask_len;
3886
      data_len = ntohs(*(uint16_t *) &buf[2]);
3887
    } else if (buf_len >= 10 + mask_len) {
3888
      header_len = 10 + mask_len;
3889
      data_len = (((uint64_t) ntohl(*(uint32_t *) &buf[2])) << 32) +
3890
                 ntohl(*(uint32_t *) &buf[6]);
3891
    }
3892
  }
3893

    
3894
  frame_len = header_len + data_len;
3895
  ok = frame_len > 0 && frame_len <= buf_len;
3896

    
3897
  if (ok) {
3898
    struct websocket_message wsm;
3899

    
3900
    wsm.size = (size_t) data_len;
3901
    wsm.data = buf + header_len;
3902
    wsm.flags = buf[0];
3903

    
3904
    /* Apply mask if necessary */
3905
    if (mask_len > 0) {
3906
      for (i = 0; i < data_len; i++) {
3907
        buf[i + header_len] ^= (buf + header_len - mask_len)[i % 4];
3908
      }
3909
    }
3910

    
3911
    if (reass) {
3912
      /* On first fragmented frame, nullify size */
3913
      if (is_ws_first_fragment(wsm.flags)) {
3914
        mbuf_resize(&nc->recv_mbuf, nc->recv_mbuf.size + sizeof(*sizep));
3915
        p[0] &= ~0x0f; /* Next frames will be treated as continuation */
3916
        buf = p + 1 + sizeof(*sizep);
3917
        *sizep = 0; /* TODO(lsm): fix. this can stomp over frame data */
3918
      }
3919

    
3920
      /* Append this frame to the reassembled buffer */
3921
      memmove(buf, wsm.data, e - wsm.data);
3922
      (*sizep) += wsm.size;
3923
      nc->recv_mbuf.len -= wsm.data - buf;
3924

    
3925
      /* On last fragmented frame - call user handler and remove data */
3926
      if (wsm.flags & 0x80) {
3927
        wsm.data = p + 1 + sizeof(*sizep);
3928
        wsm.size = *sizep;
3929
        handle_incoming_websocket_frame(nc, &wsm);
3930
        mbuf_remove(&nc->recv_mbuf, 1 + sizeof(*sizep) + *sizep);
3931
      }
3932
    } else {
3933
      /* TODO(lsm): properly handle OOB control frames during defragmentation */
3934
      handle_incoming_websocket_frame(nc, &wsm);
3935
      mbuf_remove(&nc->recv_mbuf, (size_t) frame_len); /* Cleanup frame */
3936
    }
3937

    
3938
    /* If client closes, close too */
3939
    if ((buf[0] & 0x0f) == WEBSOCKET_OP_CLOSE) {
3940
      nc->flags |= MG_F_SEND_AND_CLOSE;
3941
    }
3942
  }
3943

    
3944
  return ok;
3945
}
3946

    
3947
struct ws_mask_ctx {
3948
  size_t pos; /* zero means unmasked */
3949
  uint32_t mask;
3950
};
3951

    
3952
static uint32_t ws_random_mask(void) {
3953
/*
3954
 * The spec requires WS client to generate hard to
3955
 * guess mask keys. From RFC6455, Section 5.3:
3956
 *
3957
 * The unpredictability of the masking key is essential to prevent
3958
 * authors of malicious applications from selecting the bytes that appear on
3959
 * the wire.
3960
 *
3961
 * Hence this feature is essential when the actual end user of this API
3962
 * is untrusted code that wouldn't have access to a lower level net API
3963
 * anyway (e.g. web browsers). Hence this feature is low prio for most
3964
 * mongoose use cases and thus can be disabled, e.g. when porting to a platform
3965
 * that lacks random().
3966
 */
3967
#ifdef MG_DISABLE_WS_RANDOM_MASK
3968
  return 0xefbeadde; /* generated with a random number generator, I swear */
3969
#else
3970
  if (sizeof(long) >= 4) {
3971
    return (uint32_t) random();
3972
  } else if (sizeof(long) == 2) {
3973
    return (uint32_t) random() << 16 | (uint32_t) random();
3974
  }
3975
#endif
3976
}
3977

    
3978
static void mg_send_ws_header(struct mg_connection *nc, int op, size_t len,
3979
                              struct ws_mask_ctx *ctx) {
3980
  int header_len;
3981
  unsigned char header[10];
3982

    
3983
  header[0] = (op & WEBSOCKET_DONT_FIN ? 0x0 : 0x80) + (op & 0x0f);
3984
  if (len < 126) {
3985
    header[1] = len;
3986
    header_len = 2;
3987
  } else if (len < 65535) {
3988
    uint16_t tmp = htons((uint16_t) len);
3989
    header[1] = 126;
3990
    memcpy(&header[2], &tmp, sizeof(tmp));
3991
    header_len = 4;
3992
  } else {
3993
    uint32_t tmp;
3994
    header[1] = 127;
3995
    tmp = htonl((uint32_t)((uint64_t) len >> 32));
3996
    memcpy(&header[2], &tmp, sizeof(tmp));
3997
    tmp = htonl((uint32_t)(len & 0xffffffff));
3998
    memcpy(&header[6], &tmp, sizeof(tmp));
3999
    header_len = 10;
4000
  }
4001

    
4002
  /* client connections enable masking */
4003
  if (nc->listener == NULL) {
4004
    header[1] |= 1 << 7; /* set masking flag */
4005
    mg_send(nc, header, header_len);
4006
    ctx->mask = ws_random_mask();
4007
    mg_send(nc, &ctx->mask, sizeof(ctx->mask));
4008
    ctx->pos = nc->send_mbuf.len;
4009
  } else {
4010
    mg_send(nc, header, header_len);
4011
    ctx->pos = 0;
4012
  }
4013
}
4014

    
4015
static void ws_mask_frame(struct mbuf *mbuf, struct ws_mask_ctx *ctx) {
4016
  size_t i;
4017
  if (ctx->pos == 0) return;
4018
  for (i = 0; i < (mbuf->len - ctx->pos); i++) {
4019
    mbuf->buf[ctx->pos + i] ^= ((char *) &ctx->mask)[i % 4];
4020
  }
4021
}
4022

    
4023
void mg_send_websocket_frame(struct mg_connection *nc, int op, const void *data,
4024
                             size_t len) {
4025
  struct ws_mask_ctx ctx;
4026
  mg_send_ws_header(nc, op, len, &ctx);
4027
  mg_send(nc, data, len);
4028

    
4029
  ws_mask_frame(&nc->send_mbuf, &ctx);
4030

    
4031
  if (op == WEBSOCKET_OP_CLOSE) {
4032
    nc->flags |= MG_F_SEND_AND_CLOSE;
4033
  }
4034
}
4035

    
4036
void mg_send_websocket_framev(struct mg_connection *nc, int op,
4037
                              const struct mg_str *strv, int strvcnt) {
4038
  struct ws_mask_ctx ctx;
4039
  int i;
4040
  int len = 0;
4041
  for (i = 0; i < strvcnt; i++) {
4042
    len += strv[i].len;
4043
  }
4044

    
4045
  mg_send_ws_header(nc, op, len, &ctx);
4046

    
4047
  for (i = 0; i < strvcnt; i++) {
4048
    mg_send(nc, strv[i].p, strv[i].len);
4049
  }
4050

    
4051
  ws_mask_frame(&nc->send_mbuf, &ctx);
4052

    
4053
  if (op == WEBSOCKET_OP_CLOSE) {
4054
    nc->flags |= MG_F_SEND_AND_CLOSE;
4055
  }
4056
}
4057

    
4058
void mg_printf_websocket_frame(struct mg_connection *nc, int op,
4059
                               const char *fmt, ...) {
4060
  char mem[BUFSIZ], *buf = mem;
4061
  va_list ap;
4062
  int len;
4063

    
4064
  va_start(ap, fmt);
4065
  if ((len = mg_avprintf(&buf, sizeof(mem), fmt, ap)) > 0) {
4066
    mg_send_websocket_frame(nc, op, buf, len);
4067
  }
4068
  va_end(ap);
4069

    
4070
  if (buf != mem && buf != NULL) {
4071
    MG_FREE(buf);
4072
  }
4073
}
4074

    
4075
static void websocket_handler(struct mg_connection *nc, int ev, void *ev_data) {
4076
  nc->handler(nc, ev, ev_data);
4077

    
4078
  switch (ev) {
4079
    case MG_EV_RECV:
4080
      do {
4081
      } while (deliver_websocket_data(nc));
4082
      break;
4083
    case MG_EV_POLL:
4084
      /* Ping idle websocket connections */
4085
      {
4086
        time_t now = *(time_t *) ev_data;
4087
        if (nc->flags & MG_F_IS_WEBSOCKET &&
4088
            now > nc->last_io_time + MG_WEBSOCKET_PING_INTERVAL_SECONDS) {
4089
          mg_send_websocket_frame(nc, WEBSOCKET_OP_PING, "", 0);
4090
        }
4091
      }
4092
      break;
4093
    default:
4094
      break;
4095
  }
4096
}
4097

    
4098
static void ws_handshake(struct mg_connection *nc, const struct mg_str *key) {
4099
  static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
4100
  char buf[500], sha[20], b64_sha[sizeof(sha) * 2];
4101
  cs_sha1_ctx sha_ctx;
4102

    
4103
  snprintf(buf, sizeof(buf), "%.*s%s", (int) key->len, key->p, magic);
4104

    
4105
  cs_sha1_init(&sha_ctx);
4106
  cs_sha1_update(&sha_ctx, (unsigned char *) buf, strlen(buf));
4107
  cs_sha1_final((unsigned char *) sha, &sha_ctx);
4108

    
4109
  mg_base64_encode((unsigned char *) sha, sizeof(sha), b64_sha);
4110
  mg_printf(nc, "%s%s%s",
4111
            "HTTP/1.1 101 Switching Protocols\r\n"
4112
            "Upgrade: websocket\r\n"
4113
            "Connection: Upgrade\r\n"
4114
            "Sec-WebSocket-Accept: ",
4115
            b64_sha, "\r\n\r\n");
4116
}
4117

    
4118
#endif /* MG_DISABLE_HTTP_WEBSOCKET */
4119

    
4120
static void free_http_proto_data(struct mg_connection *nc) {
4121
  struct proto_data_http *dp = (struct proto_data_http *) nc->proto_data;
4122
  if (dp != NULL) {
4123
    if (dp->fp != NULL) {
4124
      fclose(dp->fp);
4125
    }
4126
    if (dp->cgi_nc != NULL) {
4127
      dp->cgi_nc->flags |= MG_F_CLOSE_IMMEDIATELY;
4128
    }
4129
    MG_FREE(dp);
4130
    nc->proto_data = NULL;
4131
  }
4132
}
4133

    
4134
static void transfer_file_data(struct mg_connection *nc) {
4135
  struct proto_data_http *dp = (struct proto_data_http *) nc->proto_data;
4136
  char buf[MG_MAX_HTTP_SEND_IOBUF];
4137
  int64_t left = dp->cl - dp->sent;
4138
  size_t n = 0, to_read = 0;
4139

    
4140
  if (dp->type == DATA_FILE) {
4141
    struct mbuf *io = &nc->send_mbuf;
4142
    if (io->len < sizeof(buf)) {
4143
      to_read = sizeof(buf) - io->len;
4144
    }
4145

    
4146
    if (left > 0 && to_read > (size_t) left) {
4147
      to_read = left;
4148
    }
4149

    
4150
    if (to_read == 0) {
4151
      /* Rate limiting. send_mbuf is too full, wait until it's drained. */
4152
    } else if (dp->sent < dp->cl && (n = fread(buf, 1, to_read, dp->fp)) > 0) {
4153
      mg_send(nc, buf, n);
4154
      dp->sent += n;
4155
    } else {
4156
      free_http_proto_data(nc);
4157
#ifdef MG_DISABLE_HTTP_KEEP_ALIVE
4158
      nc->flags |= MG_F_SEND_AND_CLOSE;
4159
#endif
4160
    }
4161
  } else if (dp->type == DATA_PUT) {
4162
    struct mbuf *io = &nc->recv_mbuf;
4163
    size_t to_write =
4164
        left <= 0 ? 0 : left < (int64_t) io->len ? (size_t) left : io->len;
4165
    size_t n = fwrite(io->buf, 1, to_write, dp->fp);
4166
    if (n > 0) {
4167
      mbuf_remove(io, n);
4168
      dp->sent += n;
4169
    }
4170
    if (n == 0 || dp->sent >= dp->cl) {
4171
      free_http_proto_data(nc);
4172
#ifdef MG_DISABLE_HTTP_KEEP_ALIVE
4173
      nc->flags |= MG_F_SEND_AND_CLOSE;
4174
#endif
4175
    }
4176
  } else if (dp->type == DATA_CGI) {
4177
    /* This is POST data that needs to be forwarded to the CGI process */
4178
    if (dp->cgi_nc != NULL) {
4179
      mg_forward(nc, dp->cgi_nc);
4180
    } else {
4181
      nc->flags |= MG_F_SEND_AND_CLOSE;
4182
    }
4183
  }
4184
}
4185

    
4186
/*
4187
 * Parse chunked-encoded buffer. Return 0 if the buffer is not encoded, or
4188
 * if it's incomplete. If the chunk is fully buffered, return total number of
4189
 * bytes in a chunk, and store data in `data`, `data_len`.
4190
 */
4191
static size_t parse_chunk(char *buf, size_t len, char **chunk_data,
4192
                          size_t *chunk_len) {
4193
  unsigned char *s = (unsigned char *) buf;
4194
  size_t n = 0; /* scanned chunk length */
4195
  size_t i = 0; /* index in s */
4196

    
4197
  /* Scan chunk length. That should be a hexadecimal number. */
4198
  while (i < len && isxdigit(s[i])) {
4199
    n *= 16;
4200
    n += (s[i] >= '0' && s[i] <= '9') ? s[i] - '0' : tolower(s[i]) - 'a' + 10;
4201
    i++;
4202
  }
4203

    
4204
  /* Skip new line */
4205
  if (i == 0 || i + 2 > len || s[i] != '\r' || s[i + 1] != '\n') {
4206
    return 0;
4207
  }
4208
  i += 2;
4209

    
4210
  /* Record where the data is */
4211
  *chunk_data = (char *) s + i;
4212
  *chunk_len = n;
4213

    
4214
  /* Skip data */
4215
  i += n;
4216

    
4217
  /* Skip new line */
4218
  if (i == 0 || i + 2 > len || s[i] != '\r' || s[i + 1] != '\n') {
4219
    return 0;
4220
  }
4221
  return i + 2;
4222
}
4223

    
4224
MG_INTERNAL size_t mg_handle_chunked(struct mg_connection *nc,
4225
                                     struct http_message *hm, char *buf,
4226
                                     size_t blen) {
4227
  struct proto_data_http *dp;
4228
  char *data;
4229
  size_t i, n, data_len, body_len, zero_chunk_received = 0;
4230

    
4231
  /* If not allocated, allocate proto_data to hold reassembled offset */
4232
  if (nc->proto_data == NULL &&
4233
      (nc->proto_data = MG_CALLOC(1, sizeof(*dp))) == NULL) {
4234
    nc->flags |= MG_F_CLOSE_IMMEDIATELY;
4235
    return 0;
4236
  }
4237

    
4238
  /* Find out piece of received data that is not yet reassembled */
4239
  dp = (struct proto_data_http *) nc->proto_data;
4240
  body_len = dp->body_len;
4241
  assert(blen >= body_len);
4242

    
4243
  /* Traverse all fully buffered chunks */
4244
  for (i = body_len; (n = parse_chunk(buf + i, blen - i, &data, &data_len)) > 0;
4245
       i += n) {
4246
    /* Collapse chunk data to the rest of HTTP body */
4247
    memmove(buf + body_len, data, data_len);
4248
    body_len += data_len;
4249
    hm->body.len = body_len;
4250

    
4251
    if (data_len == 0) {
4252
      zero_chunk_received = 1;
4253
      i += n;
4254
      break;
4255
    }
4256
  }
4257

    
4258
  if (i > body_len) {
4259
    /* Shift unparsed content to the parsed body */
4260
    assert(i <= blen);
4261
    memmove(buf + body_len, buf + i, blen - i);
4262
    memset(buf + body_len + blen - i, 0, i - body_len);
4263
    nc->recv_mbuf.len -= i - body_len;
4264
    dp->body_len = body_len;
4265

    
4266
    /* Send MG_EV_HTTP_CHUNK event */
4267
    nc->flags &= ~MG_F_DELETE_CHUNK;
4268
    nc->handler(nc, MG_EV_HTTP_CHUNK, hm);
4269

    
4270
    /* Delete processed data if user set MG_F_DELETE_CHUNK flag */
4271
    if (nc->flags & MG_F_DELETE_CHUNK) {
4272
      memset(buf, 0, body_len);
4273
      memmove(buf, buf + body_len, blen - i);
4274
      nc->recv_mbuf.len -= body_len;
4275
      hm->body.len = dp->body_len = 0;
4276
    }
4277

    
4278
    if (zero_chunk_received) {
4279
      hm->message.len = dp->body_len + blen - i;
4280
    }
4281
  }
4282

    
4283
  return body_len;
4284
}
4285

    
4286
/*
4287
 * lx106 compiler has a bug (TODO(mkm) report and insert tracking bug here)
4288
 * If a big structure is declared in a big function, lx106 gcc will make it
4289
 * even bigger (round up to 4k, from 700 bytes of actual size).
4290
 */
4291
#ifdef MG_ESP8266
4292
static void http_handler2(struct mg_connection *nc, int ev, void *ev_data,
4293
                          struct http_message *hm) __attribute__((noinline));
4294

    
4295
void http_handler(struct mg_connection *nc, int ev, void *ev_data) {
4296
  struct http_message hm;
4297
  http_handler2(nc, ev, ev_data, &hm);
4298
}
4299

    
4300
static void http_handler2(struct mg_connection *nc, int ev, void *ev_data,
4301
                          struct http_message *hm) {
4302
#else
4303
void http_handler(struct mg_connection *nc, int ev, void *ev_data) {
4304
  struct http_message shm;
4305
  struct http_message *hm = &shm;
4306
#endif
4307
  struct mbuf *io = &nc->recv_mbuf;
4308
  int req_len;
4309
  const int is_req = (nc->listener != NULL);
4310
#ifndef MG_DISABLE_HTTP_WEBSOCKET
4311
  struct mg_str *vec;
4312
#endif
4313
  if (ev == MG_EV_CLOSE) {
4314
    /*
4315
     * For HTTP messages without Content-Length, always send HTTP message
4316
     * before MG_EV_CLOSE message.
4317
     */
4318
    if (io->len > 0 && mg_parse_http(io->buf, io->len, hm, is_req) > 0) {
4319
      hm->message.len = io->len;
4320
      hm->body.len = io->buf + io->len - hm->body.p;
4321
      nc->handler(nc, is_req ? MG_EV_HTTP_REQUEST : MG_EV_HTTP_REPLY, hm);
4322
    }
4323
    free_http_proto_data(nc);
4324
  }
4325

    
4326
  if (nc->proto_data != NULL) {
4327
    transfer_file_data(nc);
4328
  }
4329

    
4330
  nc->handler(nc, ev, ev_data);
4331

    
4332
  if (ev == MG_EV_RECV) {
4333
    struct mg_str *s;
4334
    req_len = mg_parse_http(io->buf, io->len, hm, is_req);
4335

    
4336
    if (req_len > 0 &&
4337
        (s = mg_get_http_header(hm, "Transfer-Encoding")) != NULL &&
4338
        mg_vcasecmp(s, "chunked") == 0) {
4339
      mg_handle_chunked(nc, hm, io->buf + req_len, io->len - req_len);
4340
    }
4341

    
4342
    if (req_len < 0 || (req_len == 0 && io->len >= MG_MAX_HTTP_REQUEST_SIZE)) {
4343
      nc->flags |= MG_F_CLOSE_IMMEDIATELY;
4344
    } else if (req_len == 0) {
4345
      /* Do nothing, request is not yet fully buffered */
4346
    }
4347
#ifndef MG_DISABLE_HTTP_WEBSOCKET
4348
    else if (nc->listener == NULL &&
4349
             mg_get_http_header(hm, "Sec-WebSocket-Accept")) {
4350
      /* We're websocket client, got handshake response from server. */
4351
      /* TODO(lsm): check the validity of accept Sec-WebSocket-Accept */
4352
      mbuf_remove(io, req_len);
4353
      nc->proto_handler = websocket_handler;
4354
      nc->flags |= MG_F_IS_WEBSOCKET;
4355
      nc->handler(nc, MG_EV_WEBSOCKET_HANDSHAKE_DONE, NULL);
4356
      websocket_handler(nc, MG_EV_RECV, ev_data);
4357
    } else if (nc->listener != NULL &&
4358
               (vec = mg_get_http_header(hm, "Sec-WebSocket-Key")) != NULL) {
4359
      /* This is a websocket request. Switch protocol handlers. */
4360
      mbuf_remove(io, req_len);
4361
      nc->proto_handler = websocket_handler;
4362
      nc->flags |= MG_F_IS_WEBSOCKET;
4363

    
4364
      /* Send handshake */
4365
      nc->handler(nc, MG_EV_WEBSOCKET_HANDSHAKE_REQUEST, hm);
4366
      if (!(nc->flags & MG_F_CLOSE_IMMEDIATELY)) {
4367
        if (nc->send_mbuf.len == 0) {
4368
          ws_handshake(nc, vec);
4369
        }
4370
        nc->handler(nc, MG_EV_WEBSOCKET_HANDSHAKE_DONE, NULL);
4371
        websocket_handler(nc, MG_EV_RECV, ev_data);
4372
      }
4373
    }
4374
#endif /* MG_DISABLE_HTTP_WEBSOCKET */
4375
    else if (hm->message.len <= io->len) {
4376
      int trigger_ev = nc->listener ? MG_EV_HTTP_REQUEST : MG_EV_HTTP_REPLY;
4377

    
4378
/* Whole HTTP message is fully buffered, call event handler */
4379

    
4380
#ifdef MG_ENABLE_JAVASCRIPT
4381
      v7_val_t v1, v2, headers, req, args, res;
4382
      struct v7 *v7 = nc->mgr->v7;
4383
      const char *ev_name = trigger_ev == MG_EV_HTTP_REPLY ? "onsnd" : "onrcv";
4384
      int i, js_callback_handled_request = 0;
4385

    
4386
      if (v7 != NULL) {
4387
        /* Lookup JS callback */
4388
        v1 = v7_get(v7, v7_get_global(v7), "Http", ~0);
4389
        v2 = v7_get(v7, v1, ev_name, ~0);
4390

    
4391
        /* Create callback params. TODO(lsm): own/disown those */
4392
        args = v7_create_array(v7);
4393
        req = v7_create_object(v7);
4394
        headers = v7_create_object(v7);
4395

    
4396
        /* Populate request object */
4397
        v7_set(v7, req, "method", ~0, 0,
4398
               v7_create_string(v7, hm->method.p, hm->method.len, 1));
4399
        v7_set(v7, req, "uri", ~0, 0,
4400
               v7_create_string(v7, hm->uri.p, hm->uri.len, 1));
4401
        v7_set(v7, req, "body", ~0, 0,
4402
               v7_create_string(v7, hm->body.p, hm->body.len, 1));
4403
        v7_set(v7, req, "headers", ~0, 0, headers);
4404
        for (i = 0; hm->header_names[i].len > 0; i++) {
4405
          const struct mg_str *name = &hm->header_names[i];
4406
          const struct mg_str *value = &hm->header_values[i];
4407
          v7_set(v7, headers, name->p, name->len, 0,
4408
                 v7_create_string(v7, value->p, value->len, 1));
4409
        }
4410

    
4411
        /* Invoke callback. TODO(lsm): report errors */
4412
        v7_array_push(v7, args, v7_create_foreign(nc));
4413
        v7_array_push(v7, args, req);
4414
        if (v7_apply(v7, &res, v2, v7_create_undefined(), args) == V7_OK &&
4415
            v7_is_true(v7, res)) {
4416
          js_callback_handled_request++;
4417
        }
4418
      }
4419

    
4420
      /* If JS callback returns true, stop request processing */
4421
      if (js_callback_handled_request) {
4422
        nc->flags |= MG_F_SEND_AND_CLOSE;
4423
      } else {
4424
        nc->handler(nc, trigger_ev, hm);
4425
      }
4426
#else
4427
      nc->handler(nc, trigger_ev, hm);
4428
#endif
4429
      mbuf_remove(io, hm->message.len);
4430
    }
4431
  }
4432
}
4433

    
4434
void mg_set_protocol_http_websocket(struct mg_connection *nc) {
4435
  nc->proto_handler = http_handler;
4436
}
4437

    
4438
#ifndef MG_DISABLE_HTTP_WEBSOCKET
4439

    
4440
void mg_send_websocket_handshake(struct mg_connection *nc, const char *uri,
4441
                                 const char *extra_headers) {
4442
  unsigned long random = (unsigned long) uri;
4443
  char key[sizeof(random) * 3];
4444

    
4445
  mg_base64_encode((unsigned char *) &random, sizeof(random), key);
4446
  mg_printf(nc,
4447
            "GET %s HTTP/1.1\r\n"
4448
            "Upgrade: websocket\r\n"
4449
            "Connection: Upgrade\r\n"
4450
            "Sec-WebSocket-Version: 13\r\n"
4451
            "Sec-WebSocket-Key: %s\r\n"
4452
            "%s\r\n",
4453
            uri, key, extra_headers == NULL ? "" : extra_headers);
4454
}
4455

    
4456
#endif /* MG_DISABLE_HTTP_WEBSOCKET */
4457

    
4458
#ifndef MG_DISABLE_FILESYSTEM
4459
static void send_http_error(struct mg_connection *nc, int code,
4460
                            const char *reason) {
4461
  if (reason == NULL) {
4462
    reason = "";
4463
  }
4464
  mg_printf(nc, "HTTP/1.1 %d %s\r\nContent-Length: 0\r\n\r\n", code, reason);
4465
}
4466

    
4467
#ifndef MG_DISABLE_SSI
4468
static void send_ssi_file(struct mg_connection *, const char *, FILE *, int,
4469
                          const struct mg_serve_http_opts *);
4470

    
4471
static void send_file_data(struct mg_connection *nc, FILE *fp) {
4472
  char buf[BUFSIZ];
4473
  size_t n;
4474
  while ((n = fread(buf, 1, sizeof(buf), fp)) > 0) {
4475
    mg_send(nc, buf, n);
4476
  }
4477
}
4478

    
4479
static void do_ssi_include(struct mg_connection *nc, const char *ssi, char *tag,
4480
                           int include_level,
4481
                           const struct mg_serve_http_opts *opts) {
4482
  char file_name[BUFSIZ], path[MAX_PATH_SIZE], *p;
4483
  FILE *fp;
4484

    
4485
  /*
4486
   * sscanf() is safe here, since send_ssi_file() also uses buffer
4487
   * of size MG_BUF_LEN to get the tag. So strlen(tag) is always < MG_BUF_LEN.
4488
   */
4489
  if (sscanf(tag, " virtual=\"%[^\"]\"", file_name) == 1) {
4490
    /* File name is relative to the webserver root */
4491
    snprintf(path, sizeof(path), "%s/%s", opts->document_root, file_name);
4492
  } else if (sscanf(tag, " abspath=\"%[^\"]\"", file_name) == 1) {
4493
    /*
4494
     * File name is relative to the webserver working directory
4495
     * or it is absolute system path
4496
     */
4497
    snprintf(path, sizeof(path), "%s", file_name);
4498
  } else if (sscanf(tag, " file=\"%[^\"]\"", file_name) == 1 ||
4499
             sscanf(tag, " \"%[^\"]\"", file_name) == 1) {
4500
    /* File name is relative to the currect document */
4501
    snprintf(path, sizeof(path), "%s", ssi);
4502
    if ((p = strrchr(path, '/')) != NULL) {
4503
      p[1] = '\0';
4504
    }
4505
    snprintf(path + strlen(path), sizeof(path) - strlen(path), "%s", file_name);
4506
  } else {
4507
    mg_printf(nc, "Bad SSI #include: [%s]", tag);
4508
    return;
4509
  }
4510

    
4511
  if ((fp = fopen(path, "rb")) == NULL) {
4512
    mg_printf(nc, "SSI include error: fopen(%s): %s", path, strerror(errno));
4513
  } else {
4514
    mg_set_close_on_exec(fileno(fp));
4515
    if (mg_match_prefix(opts->ssi_pattern, strlen(opts->ssi_pattern), path) >
4516
        0) {
4517
      send_ssi_file(nc, path, fp, include_level + 1, opts);
4518
    } else {
4519
      send_file_data(nc, fp);
4520
    }
4521
    fclose(fp);
4522
  }
4523
}
4524

    
4525
#ifndef MG_DISABLE_POPEN
4526
static void do_ssi_exec(struct mg_connection *nc, char *tag) {
4527
  char cmd[BUFSIZ];
4528
  FILE *fp;
4529

    
4530
  if (sscanf(tag, " \"%[^\"]\"", cmd) != 1) {
4531
    mg_printf(nc, "Bad SSI #exec: [%s]", tag);
4532
  } else if ((fp = popen(cmd, "r")) == NULL) {
4533
    mg_printf(nc, "Cannot SSI #exec: [%s]: %s", cmd, strerror(errno));
4534
  } else {
4535
    send_file_data(nc, fp);
4536
    pclose(fp);
4537
  }
4538
}
4539
#endif /* !MG_DISABLE_POPEN */
4540

    
4541
static void do_ssi_call(struct mg_connection *nc, char *tag) {
4542
  mg_call(nc, NULL, MG_EV_SSI_CALL, tag);
4543
}
4544

    
4545
/*
4546
 * SSI directive has the following format:
4547
 * <!--#directive parameter=value parameter=value -->
4548
 */
4549
static void send_ssi_file(struct mg_connection *nc, const char *path, FILE *fp,
4550
                          int include_level,
4551
                          const struct mg_serve_http_opts *opts) {
4552
  static const struct mg_str btag = MG_STR("<!--#");
4553
  static const struct mg_str d_include = MG_STR("include");
4554
  static const struct mg_str d_call = MG_STR("call");
4555
#ifndef MG_DISABLE_POPEN
4556
  static const struct mg_str d_exec = MG_STR("exec");
4557
#endif
4558
  char buf[BUFSIZ], *p = buf + btag.len; /* p points to SSI directive */
4559
  int ch, offset, len, in_ssi_tag;
4560

    
4561
  if (include_level > 10) {
4562
    mg_printf(nc, "SSI #include level is too deep (%s)", path);
4563
    return;
4564
  }
4565

    
4566
  in_ssi_tag = len = offset = 0;
4567
  while ((ch = fgetc(fp)) != EOF) {
4568
    if (in_ssi_tag && ch == '>' && buf[len - 1] == '-' && buf[len - 2] == '-') {
4569
      size_t i = len - 2;
4570
      in_ssi_tag = 0;
4571

    
4572
      /* Trim closing --> */
4573
      buf[i--] = '\0';
4574
      while (i > 0 && buf[i] == ' ') {
4575
        buf[i--] = '\0';
4576
      }
4577

    
4578
      /* Handle known SSI directives */
4579
      if (memcmp(p, d_include.p, d_include.len) == 0) {
4580
        do_ssi_include(nc, path, p + d_include.len + 1, include_level, opts);
4581
      } else if (memcmp(p, d_call.p, d_call.len) == 0) {
4582
        do_ssi_call(nc, p + d_call.len + 1);
4583
#ifndef MG_DISABLE_POPEN
4584
      } else if (memcmp(p, d_exec.p, d_exec.len) == 0) {
4585
        do_ssi_exec(nc, p + d_exec.len + 1);
4586
#endif
4587
      } else {
4588
        /* Silently ignore unknown SSI directive. */
4589
      }
4590
      len = 0;
4591
    } else if (ch == '<') {
4592
      in_ssi_tag = 1;
4593
      if (len > 0) {
4594
        mg_send(nc, buf, (size_t) len);
4595
      }
4596
      len = 0;
4597
      buf[len++] = ch & 0xff;
4598
    } else if (in_ssi_tag) {
4599
      if (len == (int) btag.len && memcmp(buf, btag.p, btag.len) != 0) {
4600
        /* Not an SSI tag */
4601
        in_ssi_tag = 0;
4602
      } else if (len == (int) sizeof(buf) - 2) {
4603
        mg_printf(nc, "%s: SSI tag is too large", path);
4604
        len = 0;
4605
      }
4606
      buf[len++] = ch & 0xff;
4607
    } else {
4608
      buf[len++] = ch & 0xff;
4609
      if (len == (int) sizeof(buf)) {
4610
        mg_send(nc, buf, (size_t) len);
4611
        len = 0;
4612
      }
4613
    }
4614
  }
4615

    
4616
  /* Send the rest of buffered data */
4617
  if (len > 0) {
4618
    mg_send(nc, buf, (size_t) len);
4619
  }
4620
}
4621

    
4622
static void handle_ssi_request(struct mg_connection *nc, const char *path,
4623
                               const struct mg_serve_http_opts *opts) {
4624
  FILE *fp;
4625
  struct mg_str mime_type;
4626

    
4627
  if ((fp = fopen(path, "rb")) == NULL) {
4628
    send_http_error(nc, 404, "Not Found");
4629
  } else {
4630
    mg_set_close_on_exec(fileno(fp));
4631

    
4632
    mime_type = get_mime_type(path, "text/plain", opts);
4633
    mg_printf(nc,
4634
              "HTTP/1.1 200 OK\r\n"
4635
              "Content-Type: %.*s\r\n"
4636
              "Connection: close\r\n\r\n",
4637
              (int) mime_type.len, mime_type.p);
4638
    send_ssi_file(nc, path, fp, 0, opts);
4639
    fclose(fp);
4640
    nc->flags |= MG_F_SEND_AND_CLOSE;
4641
  }
4642
}
4643
#else
4644
static void handle_ssi_request(struct mg_connection *nc, const char *path,
4645
                               const struct mg_serve_http_opts *opts) {
4646
  (void) path;
4647
  (void) opts;
4648
  send_http_error(nc, 500, "SSI disabled");
4649
}
4650
#endif /* MG_DISABLE_SSI */
4651

    
4652
static void construct_etag(char *buf, size_t buf_len, const cs_stat_t *st) {
4653
  snprintf(buf, buf_len, "\"%lx.%" INT64_FMT "\"", (unsigned long) st->st_mtime,
4654
           (int64_t) st->st_size);
4655
}
4656
static void gmt_time_string(char *buf, size_t buf_len, time_t *t) {
4657
  strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", gmtime(t));
4658
}
4659

    
4660
static int parse_range_header(const struct mg_str *header, int64_t *a,
4661
                              int64_t *b) {
4662
  /*
4663
   * There is no snscanf. Headers are not guaranteed to be NUL-terminated,
4664
   * so we have this. Ugh.
4665
   */
4666
  int result;
4667
  char *p = (char *) MG_MALLOC(header->len + 1);
4668
  if (p == NULL) return 0;
4669
  memcpy(p, header->p, header->len);
4670
  p[header->len] = '\0';
4671
  result = sscanf(p, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
4672
  MG_FREE(p);
4673
  return result;
4674
}
4675

    
4676
static void mg_send_http_file2(struct mg_connection *nc, const char *path,
4677
                               cs_stat_t *st, struct http_message *hm,
4678
                               struct mg_serve_http_opts *opts) {
4679
  struct proto_data_http *dp;
4680
  struct mg_str mime_type;
4681

    
4682
  free_http_proto_data(nc);
4683
  if ((dp = (struct proto_data_http *) MG_CALLOC(1, sizeof(*dp))) == NULL) {
4684
    send_http_error(nc, 500, "Server Error"); /* LCOV_EXCL_LINE */
4685
  } else if ((dp->fp = fopen(path, "rb")) == NULL) {
4686
    MG_FREE(dp);
4687
    nc->proto_data = NULL;
4688
    send_http_error(nc, 500, "Server Error");
4689
  } else if (mg_match_prefix(opts->ssi_pattern, strlen(opts->ssi_pattern),
4690
                             path) > 0) {
4691
    nc->proto_data = (void *) dp;
4692
    handle_ssi_request(nc, path, opts);
4693
  } else {
4694
    char etag[50], current_time[50], last_modified[50], range[50];
4695
    time_t t = time(NULL);
4696
    int64_t r1 = 0, r2 = 0, cl = st->st_size;
4697
    struct mg_str *range_hdr = mg_get_http_header(hm, "Range");
4698
    int n, status_code = 200;
4699
    const char *status_message = "OK";
4700

    
4701
    /* Handle Range header */
4702
    range[0] = '\0';
4703
    if (range_hdr != NULL &&
4704
        (n = parse_range_header(range_hdr, &r1, &r2)) > 0 && r1 >= 0 &&
4705
        r2 >= 0) {
4706
      /* If range is specified like "400-", set second limit to content len */
4707
      if (n == 1) {
4708
        r2 = cl - 1;
4709
      }
4710
      if (r1 > r2 || r2 >= cl) {
4711
        status_code = 416;
4712
        status_message = "Requested range not satisfiable";
4713
        cl = 0;
4714
        snprintf(range, sizeof(range),
4715
                 "Content-Range: bytes */%" INT64_FMT "\r\n",
4716
                 (int64_t) st->st_size);