mongoose.c 237 KB
Newer Older
1 2 3 4
#include "mongoose.h"
#ifdef NS_MODULE_LINES
#line 1 "src/internal.h"
/**/
5
#endif
6 7 8 9
/*
 * Copyright (c) 2014 Cesanta Software Limited
 * All rights reserved
 */
Sergey Lyubka's avatar
Sergey Lyubka committed
10

11 12
#ifndef MG_INTERNAL_HEADER_INCLUDED
#define MG_INTERNAL_HEADER_INCLUDED
Sergey Lyubka's avatar
Sergey Lyubka committed
13

14 15
#ifndef MG_MALLOC
#define MG_MALLOC malloc
Sergey Lyubka's avatar
Sergey Lyubka committed
16 17
#endif

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

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

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

#ifndef MBUF_REALLOC
31
#define MBUF_REALLOC MG_REALLOC
Sergey Lyubka's avatar
Sergey Lyubka committed
32 33
#endif

34
#ifndef MBUF_FREE
35
#define MBUF_FREE MG_FREE
Sergey Lyubka's avatar
Sergey Lyubka committed
36 37
#endif

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

43 44
#ifndef MG_INTERNAL
#define MG_INTERNAL static
45
#endif
Sergey Lyubka's avatar
Sergey Lyubka committed
46

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

56 57
#ifdef PICOTCP
#define NO_LIBC
58 59 60 61 62 63
#define MG_DISABLE_FILESYSTEM
#define MG_DISABLE_POPEN
#define MG_DISABLE_CGI
#define MG_DISABLE_DIRECTORY_LISTING
#define MG_DISABLE_SOCKETPAIR
#define MG_DISABLE_PFS
Sergey Lyubka's avatar
Sergey Lyubka committed
64 65
#endif

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

68
/* internals that need to be accessible in unit tests */
69
MG_INTERNAL struct mg_connection *mg_finish_connect(struct mg_connection *nc,
70 71 72
                                                    int proto,
                                                    union socket_address *sa,
                                                    struct mg_add_sock_opts);
Sergey Lyubka's avatar
Sergey Lyubka committed
73

74
MG_INTERNAL int mg_parse_address(const char *str, union socket_address *sa,
75
                                 int *proto, char *host, size_t host_len);
76 77 78 79
MG_INTERNAL void mg_call(struct mg_connection *, int ev, void *ev_data);
MG_INTERNAL void mg_forward(struct mg_connection *, struct mg_connection *);
MG_INTERNAL void mg_add_conn(struct mg_mgr *mgr, struct mg_connection *c);
MG_INTERNAL void mg_remove_conn(struct mg_connection *c);
Sergey Lyubka's avatar
Sergey Lyubka committed
80

81 82
#ifndef MG_DISABLE_FILESYSTEM
MG_INTERNAL int find_index_file(char *, size_t, const char *, cs_stat_t *);
Sergey Lyubka's avatar
Sergey Lyubka committed
83 84
#endif

85 86
#ifdef _WIN32
void to_wchar(const char *path, wchar_t *wbuf, size_t wbuf_len);
Sergey Lyubka's avatar
Sergey Lyubka committed
87 88
#endif

89 90 91 92 93 94
/*
 * Reassemble the content of the buffer (buf, blen) which should be
 * in the HTTP chunked encoding, by collapsing data chunks to the
 * beginning of the buffer.
 *
 * 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 97 98 99
 * in nc->flags, delete reassembled body from the mbuf.
 *
 * Return reassembled body size.
 */
100
MG_INTERNAL size_t mg_handle_chunked(struct mg_connection *nc,
101 102 103 104 105 106 107
                                     struct http_message *hm, char *buf,
                                     size_t blen);

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

108
#endif /* MG_INTERNAL_HEADER_INCLUDED */
109 110 111
#ifdef NS_MODULE_LINES
#line 1 "src/../../common/mbuf.c"
/**/
Sergey Lyubka's avatar
Sergey Lyubka committed
112
#endif
113 114 115 116
/*
 * Copyright (c) 2014 Cesanta Software Limited
 * All rights reserved
 */
Sergey Lyubka's avatar
Sergey Lyubka committed
117

118 119 120 121 122 123 124 125
#ifndef EXCLUDE_COMMON

#include <assert.h>
#include <string.h>
/* Amalgamated: #include "mbuf.h" */

#ifndef MBUF_REALLOC
#define MBUF_REALLOC realloc
126 127
#endif

128 129 130
#ifndef MBUF_FREE
#define MBUF_FREE free
#endif
131

132 133 134 135 136
void mbuf_init(struct mbuf *mbuf, size_t initial_size) {
  mbuf->len = mbuf->size = 0;
  mbuf->buf = NULL;
  mbuf_resize(mbuf, initial_size);
}
137

138 139 140 141
void mbuf_free(struct mbuf *mbuf) {
  if (mbuf->buf != NULL) {
    MBUF_FREE(mbuf->buf);
    mbuf_init(mbuf, 0);
142 143 144
  }
}

145 146 147 148 149 150 151
void mbuf_resize(struct mbuf *a, size_t new_size) {
  char *p;
  if ((new_size > a->size || (new_size < a->size && new_size >= a->len)) &&
      (p = (char *) MBUF_REALLOC(a->buf, new_size)) != NULL) {
    a->size = new_size;
    a->buf = p;
  }
Sergey Lyubka's avatar
Sergey Lyubka committed
152 153
}

154 155
void mbuf_trim(struct mbuf *mbuf) {
  mbuf_resize(mbuf, mbuf->len);
Sergey Lyubka's avatar
Sergey Lyubka committed
156 157
}

158
size_t mbuf_insert(struct mbuf *a, size_t off, const void *buf, size_t len) {
Sergey Lyubka's avatar
Sergey Lyubka committed
159 160
  char *p = NULL;

161 162 163
  assert(a != NULL);
  assert(a->len <= a->size);
  assert(off <= a->len);
Sergey Lyubka's avatar
Sergey Lyubka committed
164

Sergey Lyubka's avatar
Sergey Lyubka committed
165
  /* check overflow */
166
  if (~(size_t) 0 - (size_t) a->buf < len) return 0;
Sergey Lyubka's avatar
Sergey Lyubka committed
167

168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
  if (a->len + len <= a->size) {
    memmove(a->buf + off + len, a->buf + off, a->len - off);
    if (buf != NULL) {
      memcpy(a->buf + off, buf, len);
    }
    a->len += len;
  } else if ((p = (char *) MBUF_REALLOC(
                  a->buf, (a->len + len) * MBUF_SIZE_MULTIPLIER)) != NULL) {
    a->buf = p;
    memmove(a->buf + off + len, a->buf + off, a->len - off);
    if (buf != NULL) {
      memcpy(a->buf + off, buf, len);
    }
    a->len += len;
    a->size = a->len * MBUF_SIZE_MULTIPLIER;
Sergey Lyubka's avatar
Sergey Lyubka committed
183 184 185 186 187 188 189
  } else {
    len = 0;
  }

  return len;
}

190 191
size_t mbuf_append(struct mbuf *a, const void *buf, size_t len) {
  return mbuf_insert(a, a->len, buf, len);
Sergey Lyubka's avatar
Sergey Lyubka committed
192 193
}

194 195 196 197
void mbuf_remove(struct mbuf *mb, size_t n) {
  if (n > 0 && n <= mb->len) {
    memmove(mb->buf, mb->buf + n, mb->len - n);
    mb->len -= n;
198 199 200
  }
}

201 202 203 204 205 206 207
#endif /* EXCLUDE_COMMON */
#ifdef NS_MODULE_LINES
#line 1 "src/../../common/sha1.c"
/**/
#endif
/* Copyright(c) By Steve Reid <steve@edmweb.com> */
/* 100% Public Domain */
Sergey Lyubka's avatar
Sergey Lyubka committed
208

209
#if !defined(DISABLE_SHA1) && !defined(EXCLUDE_COMMON)
Sergey Lyubka's avatar
Sergey Lyubka committed
210

211 212 213 214 215
/* Amalgamated: #include "sha1.h" */

#define SHA1HANDSOFF
#if defined(__sun)
/* Amalgamated: #include "solarisfixes.h" */
Sergey Lyubka's avatar
Sergey Lyubka committed
216 217
#endif

218 219 220 221
union char64long16 {
  unsigned char c[64];
  uint32_t l[16];
};
Sergey Lyubka's avatar
Sergey Lyubka committed
222

223 224 225 226 227 228 229
#define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))

static uint32_t blk0(union char64long16 *block, int i) {
/* Forrest: SHA expect BIG_ENDIAN, swap if LITTLE_ENDIAN */
#if BYTE_ORDER == LITTLE_ENDIAN
  block->l[i] =
      (rol(block->l[i], 24) & 0xFF00FF00) | (rol(block->l[i], 8) & 0x00FF00FF);
Sergey Lyubka's avatar
Sergey Lyubka committed
230
#endif
231
  return block->l[i];
Sergey Lyubka's avatar
Sergey Lyubka committed
232 233
}

234 235 236 237 238 239 240
/* Avoid redefine warning (ARM /usr/include/sys/ucontext.h define R0~R4) */
#undef blk
#undef R0
#undef R1
#undef R2
#undef R3
#undef R4
Sergey Lyubka's avatar
Sergey Lyubka committed
241

242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365
#define blk(i)                                                               \
  (block->l[i & 15] = rol(block->l[(i + 13) & 15] ^ block->l[(i + 8) & 15] ^ \
                              block->l[(i + 2) & 15] ^ block->l[i & 15],     \
                          1))
#define R0(v, w, x, y, z, i)                                          \
  z += ((w & (x ^ y)) ^ y) + blk0(block, i) + 0x5A827999 + rol(v, 5); \
  w = rol(w, 30);
#define R1(v, w, x, y, z, i)                                  \
  z += ((w & (x ^ y)) ^ y) + blk(i) + 0x5A827999 + rol(v, 5); \
  w = rol(w, 30);
#define R2(v, w, x, y, z, i)                          \
  z += (w ^ x ^ y) + blk(i) + 0x6ED9EBA1 + rol(v, 5); \
  w = rol(w, 30);
#define R3(v, w, x, y, z, i)                                        \
  z += (((w | x) & y) | (w & x)) + blk(i) + 0x8F1BBCDC + rol(v, 5); \
  w = rol(w, 30);
#define R4(v, w, x, y, z, i)                          \
  z += (w ^ x ^ y) + blk(i) + 0xCA62C1D6 + rol(v, 5); \
  w = rol(w, 30);

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

  memcpy(block, buffer, 64);
  a = state[0];
  b = state[1];
  c = state[2];
  d = state[3];
  e = state[4];
  R0(a, b, c, d, e, 0);
  R0(e, a, b, c, d, 1);
  R0(d, e, a, b, c, 2);
  R0(c, d, e, a, b, 3);
  R0(b, c, d, e, a, 4);
  R0(a, b, c, d, e, 5);
  R0(e, a, b, c, d, 6);
  R0(d, e, a, b, c, 7);
  R0(c, d, e, a, b, 8);
  R0(b, c, d, e, a, 9);
  R0(a, b, c, d, e, 10);
  R0(e, a, b, c, d, 11);
  R0(d, e, a, b, c, 12);
  R0(c, d, e, a, b, 13);
  R0(b, c, d, e, a, 14);
  R0(a, b, c, d, e, 15);
  R1(e, a, b, c, d, 16);
  R1(d, e, a, b, c, 17);
  R1(c, d, e, a, b, 18);
  R1(b, c, d, e, a, 19);
  R2(a, b, c, d, e, 20);
  R2(e, a, b, c, d, 21);
  R2(d, e, a, b, c, 22);
  R2(c, d, e, a, b, 23);
  R2(b, c, d, e, a, 24);
  R2(a, b, c, d, e, 25);
  R2(e, a, b, c, d, 26);
  R2(d, e, a, b, c, 27);
  R2(c, d, e, a, b, 28);
  R2(b, c, d, e, a, 29);
  R2(a, b, c, d, e, 30);
  R2(e, a, b, c, d, 31);
  R2(d, e, a, b, c, 32);
  R2(c, d, e, a, b, 33);
  R2(b, c, d, e, a, 34);
  R2(a, b, c, d, e, 35);
  R2(e, a, b, c, d, 36);
  R2(d, e, a, b, c, 37);
  R2(c, d, e, a, b, 38);
  R2(b, c, d, e, a, 39);
  R3(a, b, c, d, e, 40);
  R3(e, a, b, c, d, 41);
  R3(d, e, a, b, c, 42);
  R3(c, d, e, a, b, 43);
  R3(b, c, d, e, a, 44);
  R3(a, b, c, d, e, 45);
  R3(e, a, b, c, d, 46);
  R3(d, e, a, b, c, 47);
  R3(c, d, e, a, b, 48);
  R3(b, c, d, e, a, 49);
  R3(a, b, c, d, e, 50);
  R3(e, a, b, c, d, 51);
  R3(d, e, a, b, c, 52);
  R3(c, d, e, a, b, 53);
  R3(b, c, d, e, a, 54);
  R3(a, b, c, d, e, 55);
  R3(e, a, b, c, d, 56);
  R3(d, e, a, b, c, 57);
  R3(c, d, e, a, b, 58);
  R3(b, c, d, e, a, 59);
  R4(a, b, c, d, e, 60);
  R4(e, a, b, c, d, 61);
  R4(d, e, a, b, c, 62);
  R4(c, d, e, a, b, 63);
  R4(b, c, d, e, a, 64);
  R4(a, b, c, d, e, 65);
  R4(e, a, b, c, d, 66);
  R4(d, e, a, b, c, 67);
  R4(c, d, e, a, b, 68);
  R4(b, c, d, e, a, 69);
  R4(a, b, c, d, e, 70);
  R4(e, a, b, c, d, 71);
  R4(d, e, a, b, c, 72);
  R4(c, d, e, a, b, 73);
  R4(b, c, d, e, a, 74);
  R4(a, b, c, d, e, 75);
  R4(e, a, b, c, d, 76);
  R4(d, e, a, b, c, 77);
  R4(c, d, e, a, b, 78);
  R4(b, c, d, e, a, 79);
  state[0] += a;
  state[1] += b;
  state[2] += c;
  state[3] += d;
  state[4] += e;
  /* Erase working structures. The order of operations is important,
   * used to ensure that compiler doesn't optimize those out. */
  memset(block, 0, sizeof(block));
  a = b = c = d = e = 0;
  (void) a;
  (void) b;
  (void) c;
  (void) d;
  (void) e;
Sergey Lyubka's avatar
Sergey Lyubka committed
366 367
}

368 369 370 371 372 373 374 375
void cs_sha1_init(cs_sha1_ctx *context) {
  context->state[0] = 0x67452301;
  context->state[1] = 0xEFCDAB89;
  context->state[2] = 0x98BADCFE;
  context->state[3] = 0x10325476;
  context->state[4] = 0xC3D2E1F0;
  context->count[0] = context->count[1] = 0;
}
Sergey Lyubka's avatar
Sergey Lyubka committed
376

377 378
void cs_sha1_update(cs_sha1_ctx *context, const unsigned char *data, uint32_t len) {
  uint32_t i, j;
Sergey Lyubka's avatar
Sergey Lyubka committed
379

380 381 382 383 384 385 386 387 388
  j = context->count[0];
  if ((context->count[0] += len << 3) < j) context->count[1]++;
  context->count[1] += (len >> 29);
  j = (j >> 3) & 63;
  if ((j + len) > 63) {
    memcpy(&context->buffer[j], data, (i = 64 - j));
    cs_sha1_transform(context->state, context->buffer);
    for (; i + 63 < len; i += 64) {
      cs_sha1_transform(context->state, &data[i]);
Sergey Lyubka's avatar
Sergey Lyubka committed
389
    }
390 391 392 393
    j = 0;
  } else
    i = 0;
  memcpy(&context->buffer[j], &data[i], len - i);
Sergey Lyubka's avatar
Sergey Lyubka committed
394 395
}

396 397 398
void cs_sha1_final(unsigned char digest[20], cs_sha1_ctx *context) {
  unsigned i;
  unsigned char finalcount[8], c;
Sergey Lyubka's avatar
Sergey Lyubka committed
399

400 401 402 403
  for (i = 0; i < 8; i++) {
    finalcount[i] = (unsigned char) ((context->count[(i >= 4 ? 0 : 1)] >>
                                      ((3 - (i & 3)) * 8)) &
                                     255);
Sergey Lyubka's avatar
Sergey Lyubka committed
404
  }
405 406 407 408 409
  c = 0200;
  cs_sha1_update(context, &c, 1);
  while ((context->count[0] & 504) != 448) {
    c = 0000;
    cs_sha1_update(context, &c, 1);
Sergey Lyubka's avatar
Sergey Lyubka committed
410
  }
411 412 413 414 415 416 417
  cs_sha1_update(context, finalcount, 8);
  for (i = 0; i < 20; i++) {
    digest[i] =
        (unsigned char) ((context->state[i >> 2] >> ((3 - (i & 3)) * 8)) & 255);
  }
  memset(context, '\0', sizeof(*context));
  memset(&finalcount, '\0', sizeof(finalcount));
Sergey Lyubka's avatar
Sergey Lyubka committed
418 419
}

420 421 422
void cs_hmac_sha1(const unsigned char *key, size_t keylen,
                  const unsigned char *data, size_t datalen,
                  unsigned char out[20]) {
423 424
  cs_sha1_ctx ctx;
  unsigned char buf1[64], buf2[64], tmp_key[20], i;
425

426 427 428 429 430 431
  if (keylen > sizeof(buf1)) {
    cs_sha1_init(&ctx);
    cs_sha1_update(&ctx, key, keylen);
    cs_sha1_final(tmp_key, &ctx);
    key = tmp_key;
    keylen = sizeof(tmp_key);
432 433
  }

434 435 436 437 438 439 440 441
  memset(buf1, 0, sizeof(buf1));
  memset(buf2, 0, sizeof(buf2));
  memcpy(buf1, key, keylen);
  memcpy(buf2, key, keylen);

  for (i = 0; i < sizeof(buf1); i++) {
    buf1[i] ^= 0x36;
    buf2[i] ^= 0x5c;
442
  }
443

444 445 446 447 448 449 450 451 452
  cs_sha1_init(&ctx);
  cs_sha1_update(&ctx, buf1, sizeof(buf1));
  cs_sha1_update(&ctx, data, datalen);
  cs_sha1_final(out, &ctx);

  cs_sha1_init(&ctx);
  cs_sha1_update(&ctx, buf2, sizeof(buf2));
  cs_sha1_update(&ctx, out, 20);
  cs_sha1_final(out, &ctx);
Sergey Lyubka's avatar
Sergey Lyubka committed
453 454
}

455 456 457 458
#endif /* EXCLUDE_COMMON */
#ifdef NS_MODULE_LINES
#line 1 "src/../../common/md5.c"
/**/
459
#endif
460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475
/*
 * This code implements the MD5 message-digest algorithm.
 * The algorithm is due to Ron Rivest.  This code was
 * written by Colin Plumb in 1993, no copyright is claimed.
 * This code is in the public domain; do with it what you wish.
 *
 * Equivalent code is available from RSA Data Security, Inc.
 * This code has been tested against that, and is equivalent,
 * except that you don't need to include two pages of legalese
 * with every copy.
 *
 * To compute the message digest of a chunk of bytes, declare an
 * MD5Context structure, pass it to MD5Init, call MD5Update as
 * needed on buffers full of bytes, and then call MD5Final, which
 * will fill a supplied 16-byte array with the digest.
 */
Sergey Lyubka's avatar
Sergey Lyubka committed
476

477
#if !defined(DISABLE_MD5) && !defined(EXCLUDE_COMMON)
478

479
/* Amalgamated: #include "md5.h" */
Sergey Lyubka's avatar
Sergey Lyubka committed
480

481 482 483 484 485 486 487 488 489
static void byteReverse(unsigned char *buf, unsigned longs) {
/* Forrest: MD5 expect LITTLE_ENDIAN, swap if BIG_ENDIAN */
#if BYTE_ORDER == BIG_ENDIAN
  do {
    uint32_t t = (uint32_t)((unsigned) buf[3] << 8 | buf[2]) << 16 |
                 ((unsigned) buf[1] << 8 | buf[0]);
    *(uint32_t *) buf = t;
    buf += 4;
  } while (--longs);
Sergey Lyubka's avatar
Sergey Lyubka committed
490
#else
491 492
  (void) buf;
  (void) longs;
Sergey Lyubka's avatar
Sergey Lyubka committed
493 494 495
#endif
}

496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677
#define F1(x, y, z) (z ^ (x & (y ^ z)))
#define F2(x, y, z) F1(z, x, y)
#define F3(x, y, z) (x ^ y ^ z)
#define F4(x, y, z) (y ^ (x | ~z))

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

/*
 * Start MD5 accumulation.  Set bit count to 0 and buffer to mysterious
 * initialization constants.
 */
void MD5_Init(MD5_CTX *ctx) {
  ctx->buf[0] = 0x67452301;
  ctx->buf[1] = 0xefcdab89;
  ctx->buf[2] = 0x98badcfe;
  ctx->buf[3] = 0x10325476;

  ctx->bits[0] = 0;
  ctx->bits[1] = 0;
}

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

  a = buf[0];
  b = buf[1];
  c = buf[2];
  d = buf[3];

  MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
  MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
  MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
  MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
  MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
  MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
  MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
  MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
  MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
  MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
  MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
  MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
  MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
  MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
  MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
  MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);

  MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
  MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
  MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
  MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
  MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
  MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
  MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
  MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
  MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
  MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
  MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
  MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
  MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
  MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
  MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
  MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);

  MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
  MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
  MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
  MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
  MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
  MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
  MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
  MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
  MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
  MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
  MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
  MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
  MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
  MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
  MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
  MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);

  MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
  MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
  MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
  MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
  MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
  MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
  MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
  MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
  MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
  MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
  MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
  MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
  MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
  MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
  MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
  MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);

  buf[0] += a;
  buf[1] += b;
  buf[2] += c;
  buf[3] += d;
}

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

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

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

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

    t = 64 - t;
    if (len < t) {
      memcpy(p, buf, len);
      return;
    }
    memcpy(p, buf, t);
    byteReverse(ctx->in, 16);
    MD5Transform(ctx->buf, (uint32_t *) ctx->in);
    buf += t;
    len -= t;
  }

  while (len >= 64) {
    memcpy(ctx->in, buf, 64);
    byteReverse(ctx->in, 16);
    MD5Transform(ctx->buf, (uint32_t *) ctx->in);
    buf += 64;
    len -= 64;
  }

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

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

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

  p = ctx->in + count;
  *p++ = 0x80;
  count = 64 - 1 - count;
  if (count < 8) {
    memset(p, 0, count);
    byteReverse(ctx->in, 16);
    MD5Transform(ctx->buf, (uint32_t *) ctx->in);
    memset(ctx->in, 0, 56);
  } else {
    memset(p, 0, count - 8);
  }
  byteReverse(ctx->in, 14);

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

  MD5Transform(ctx->buf, (uint32_t *) ctx->in);
  byteReverse((unsigned char *) ctx->buf, 4);
  memcpy(digest, ctx->buf, 16);
  memset((char *) ctx, 0, sizeof(*ctx));
}

#endif /* EXCLUDE_COMMON */
#ifdef NS_MODULE_LINES
#line 1 "src/../../common/base64.c"
/**/
#endif
/*
 * Copyright (c) 2014 Cesanta Software Limited
 * All rights reserved
 */

#ifndef EXCLUDE_COMMON

/* Amalgamated: #include "base64.h" */
678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749
#include <string.h>

/* ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/ */

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

/*
 * Emit a base64 code char.
 *
 * Doesn't use memory, thus it's safe to use to safely dump memory in crashdumps
 */
static void cs_base64_emit_code(struct cs_base64_ctx *ctx, int v) {
  if (v < NUM_UPPERCASES) {
    ctx->b64_putc(v + 'A', ctx->user_data);
  } else if (v < (NUM_LETTERS)) {
    ctx->b64_putc(v - NUM_UPPERCASES + 'a', ctx->user_data);
  } else if (v < (NUM_LETTERS + NUM_DIGITS)) {
    ctx->b64_putc(v - NUM_LETTERS + '0', ctx->user_data);
  } else {
    ctx->b64_putc(v - NUM_LETTERS - NUM_DIGITS == 0 ? '+' : '/',
                  ctx->user_data);
  }
}

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

  a = ctx->chunk[0];
  b = ctx->chunk[1];
  c = ctx->chunk[2];

  cs_base64_emit_code(ctx, a >> 2);
  cs_base64_emit_code(ctx, ((a & 3) << 4) | (b >> 4));
  if (ctx->chunk_size > 1) {
    cs_base64_emit_code(ctx, (b & 15) << 2 | (c >> 6));
  }
  if (ctx->chunk_size > 2) {
    cs_base64_emit_code(ctx, c & 63);
  }
}

void cs_base64_init(struct cs_base64_ctx *ctx, cs_base64_putc_t b64_putc,
                    void *user_data) {
  ctx->chunk_size = 0;
  ctx->b64_putc = b64_putc;
  ctx->user_data = user_data;
}

void cs_base64_update(struct cs_base64_ctx *ctx, const char *str, size_t len) {
  const unsigned char *src = (const unsigned char *) str;
  size_t i;
  for (i = 0; i < len; i++) {
    ctx->chunk[ctx->chunk_size++] = src[i];
    if (ctx->chunk_size == 3) {
      cs_base64_emit_chunk(ctx);
      ctx->chunk_size = 0;
    }
  }
}

void cs_base64_finish(struct cs_base64_ctx *ctx) {
  if (ctx->chunk_size > 0) {
    int i;
    memset(&ctx->chunk[ctx->chunk_size], 0, 3 - ctx->chunk_size);
    cs_base64_emit_chunk(ctx);
    for (i = 0; i < (3 - ctx->chunk_size); i++) {
      ctx->b64_putc('=', ctx->user_data);
    }
  }
}
750

751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785
#define BASE64_ENCODE_BODY                                                \
  static const char *b64 =                                                \
      "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; \
  int i, j, a, b, c;                                                      \
                                                                          \
  for (i = j = 0; i < src_len; i += 3) {                                  \
    a = src[i];                                                           \
    b = i + 1 >= src_len ? 0 : src[i + 1];                                \
    c = i + 2 >= src_len ? 0 : src[i + 2];                                \
                                                                          \
    BASE64_OUT(b64[a >> 2]);                                              \
    BASE64_OUT(b64[((a & 3) << 4) | (b >> 4)]);                           \
    if (i + 1 < src_len) {                                                \
      BASE64_OUT(b64[(b & 15) << 2 | (c >> 6)]);                          \
    }                                                                     \
    if (i + 2 < src_len) {                                                \
      BASE64_OUT(b64[c & 63]);                                            \
    }                                                                     \
  }                                                                       \
                                                                          \
  while (j % 4 != 0) {                                                    \
    BASE64_OUT('=');                                                      \
  }                                                                       \
  BASE64_FLUSH()

#define BASE64_OUT(ch) \
  do {                 \
    dst[j++] = (ch);   \
  } while (0)

#define BASE64_FLUSH() \
  do {                 \
    dst[j++] = '\0';   \
  } while (0)

786
void cs_base64_encode(const unsigned char *src, int src_len, char *dst) {
787
  BASE64_ENCODE_BODY;
788 789
}

790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807
#undef BASE64_OUT
#undef BASE64_FLUSH

#define BASE64_OUT(ch)      \
  do {                      \
    fprintf(f, "%c", (ch)); \
    j++;                    \
  } while (0)

#define BASE64_FLUSH()

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

#undef BASE64_OUT
#undef BASE64_FLUSH

808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122
/* Convert one byte of encoded base64 input stream to 6-bit chunk */
static unsigned char from_b64(unsigned char ch) {
  /* Inverse lookup map */
  static const unsigned char tab[128] = {
      255, 255, 255, 255,
      255, 255, 255, 255, /*  0 */
      255, 255, 255, 255,
      255, 255, 255, 255, /*  8 */
      255, 255, 255, 255,
      255, 255, 255, 255, /*  16 */
      255, 255, 255, 255,
      255, 255, 255, 255, /*  24 */
      255, 255, 255, 255,
      255, 255, 255, 255, /*  32 */
      255, 255, 255, 62,
      255, 255, 255, 63, /*  40 */
      52,  53,  54,  55,
      56,  57,  58,  59, /*  48 */
      60,  61,  255, 255,
      255, 200, 255, 255, /*  56   '=' is 200, on index 61 */
      255, 0,   1,   2,
      3,   4,   5,   6, /*  64 */
      7,   8,   9,   10,
      11,  12,  13,  14, /*  72 */
      15,  16,  17,  18,
      19,  20,  21,  22, /*  80 */
      23,  24,  25,  255,
      255, 255, 255, 255, /*  88 */
      255, 26,  27,  28,
      29,  30,  31,  32, /*  96 */
      33,  34,  35,  36,
      37,  38,  39,  40, /*  104 */
      41,  42,  43,  44,
      45,  46,  47,  48, /*  112 */
      49,  50,  51,  255,
      255, 255, 255, 255, /*  120 */
  };
  return tab[ch & 127];
}

int cs_base64_decode(const unsigned char *s, int len, char *dst) {
  unsigned char a, b, c, d;
  int orig_len = len;
  while (len >= 4 && (a = from_b64(s[0])) != 255 &&
         (b = from_b64(s[1])) != 255 && (c = from_b64(s[2])) != 255 &&
         (d = from_b64(s[3])) != 255) {
    s += 4;
    len -= 4;
    if (a == 200 || b == 200) break; /* '=' can't be there */
    *dst++ = a << 2 | b >> 4;
    if (c == 200) break;
    *dst++ = b << 4 | c >> 2;
    if (d == 200) break;
    *dst++ = c << 6 | d;
  }
  *dst = 0;
  return orig_len - len;
}

#endif /* EXCLUDE_COMMON */
#ifdef NS_MODULE_LINES
#line 1 "src/../../common/str_util.c"
/**/
#endif
/*
 * Copyright (c) 2015 Cesanta Software Limited
 * All rights reserved
 */

#ifndef EXCLUDE_COMMON

/* Amalgamated: #include "osdep.h" */
/* Amalgamated: #include "str_util.h" */

#if !(_XOPEN_SOURCE >= 700 || _POSIX_C_SOURCE >= 200809L) &&    \
        !(__DARWIN_C_LEVEL >= 200809L) && !defined(RTOS_SDK) || \
    defined(_WIN32)
int strnlen(const char *s, size_t maxlen) {
  size_t l = 0;
  for (; l < maxlen && s[l] != '\0'; l++) {
  }
  return l;
}
#endif

#define C_SNPRINTF_APPEND_CHAR(ch)       \
  do {                                   \
    if (i < (int) buf_size) buf[i] = ch; \
    i++;                                 \
  } while (0)

#define C_SNPRINTF_FLAG_ZERO 1

#ifdef C_DISABLE_BUILTIN_SNPRINTF
int c_vsnprintf(char *buf, size_t buf_size, const char *fmt, va_list ap) {
  return vsnprintf(buf, buf_size, fmt, ap);
}
#else
static int c_itoa(char *buf, size_t buf_size, int64_t num, int base, int flags,
                  int field_width) {
  char tmp[40];
  int i = 0, k = 0, neg = 0;

  if (num < 0) {
    neg++;
    num = -num;
  }

  /* Print into temporary buffer - in reverse order */
  do {
    int rem = num % base;
    if (rem < 10) {
      tmp[k++] = '0' + rem;
    } else {
      tmp[k++] = 'a' + (rem - 10);
    }
    num /= base;
  } while (num > 0);

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

  /* And sign */
  if (neg) {
    tmp[k++] = '-';
  }

  /* Now output */
  while (--k >= 0) {
    C_SNPRINTF_APPEND_CHAR(tmp[k]);
  }

  return i;
}

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

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

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

      /* Field width */
      while (*fmt >= '0' && *fmt <= '9') {
        field_width *= 10;
        field_width += *fmt++ - '0';
      }
      /* Dynamic field width */
      if (*fmt == '*') {
        field_width = va_arg(ap, int);
        fmt++;
      }

      /* Precision */
      if (*fmt == '.') {
        fmt++;
        if (*fmt == '*') {
          precision = va_arg(ap, int);
          fmt++;
        } else {
          while (*fmt >= '0' && *fmt <= '9') {
            precision *= 10;
            precision += *fmt++ - '0';
          }
        }
      }

      /* Length modifier */
      switch (*fmt) {
        case 'h':
        case 'l':
        case 'L':
        case 'I':
        case 'q':
        case 'j':
        case 'z':
        case 't':
          len_mod = *fmt++;
          if (*fmt == 'h') {
            len_mod = 'H';
            fmt++;
          }
          if (*fmt == 'l') {
            len_mod = 'q';
            fmt++;
          }
          break;
      }

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

        /* Ignore negative and 0 precisions */
        for (j = 0; (precision <= 0 || j < precision) && s[j] != '\0'; j++) {
          C_SNPRINTF_APPEND_CHAR(s[j]);
        }
      } else if (ch == 'c') {
        ch = va_arg(ap, int); /* Always fetch parameter */
        C_SNPRINTF_APPEND_CHAR(ch);
      } else if (ch == 'd' && len_mod == 0) {
        i += c_itoa(buf + i, buf_size - i, va_arg(ap, int), 10, flags,
                    field_width);
      } else if (ch == 'd' && len_mod == 'l') {
        i += c_itoa(buf + i, buf_size - i, va_arg(ap, long), 10, flags,
                    field_width);
      } else if ((ch == 'x' || ch == 'u') && len_mod == 0) {
        i += c_itoa(buf + i, buf_size - i, va_arg(ap, unsigned),
                    ch == 'x' ? 16 : 10, flags, field_width);
      } else if ((ch == 'x' || ch == 'u') && len_mod == 'l') {
        i += c_itoa(buf + i, buf_size - i, va_arg(ap, unsigned long),
                    ch == 'x' ? 16 : 10, flags, field_width);
      } else if (ch == 'p') {
        unsigned long num = (unsigned long) va_arg(ap, void *);
        C_SNPRINTF_APPEND_CHAR('0');
        C_SNPRINTF_APPEND_CHAR('x');
        i += c_itoa(buf + i, buf_size - i, num, 16, flags, 0);
      } else {
#ifndef NO_LIBC
        /*
         * TODO(lsm): abort is not nice in a library, remove it
         * Also, ESP8266 SDK doesn't have it
         */
        abort();
#endif
      }
    }
  }

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

  return i;
}
#endif

int c_snprintf(char *buf, size_t buf_size, const char *fmt, ...) {
  int result;
  va_list ap;
  va_start(ap, fmt);
  result = c_vsnprintf(buf, buf_size, fmt, ap);
  va_end(ap);
  return result;
}

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

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

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

  /*
   * Convert to Unicode and back. If doubly-converted string does not
   * match the original, something is fishy, reject.
   */
  memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int) wbuf_len);
  WideCharToMultiByte(CP_UTF8, 0, wbuf, (int) wbuf_len, buf2, sizeof(buf2),
                      NULL, NULL);
  if (strcmp(buf, buf2) != 0) {
    wbuf[0] = L'\0';
  }
}
#endif /* _WIN32 */

#endif /* EXCLUDE_COMMON */
#ifdef NS_MODULE_LINES
#line 1 "src/../../common/dirent.c"
/**/
#endif
/*
 * Copyright (c) 2015 Cesanta Software Limited
 * All rights reserved
 */

#ifndef EXCLUDE_COMMON

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

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

1123 1124
#ifndef MG_FREE
#define MG_FREE free
1125 1126
#endif

1127 1128
#ifndef MG_MALLOC
#define MG_MALLOC malloc
1129 1130 1131 1132 1133 1134 1135 1136 1137 1138
#endif

#ifdef _WIN32
DIR *opendir(const char *name) {
  DIR *dir = NULL;
  wchar_t wpath[MAX_PATH];
  DWORD attrs;

  if (name == NULL) {
    SetLastError(ERROR_BAD_ARGUMENTS);
1139
  } else if ((dir = (DIR *) MG_MALLOC(sizeof(*dir))) == NULL) {
1140 1141 1142 1143 1144 1145 1146 1147 1148
    SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  } else {
    to_wchar(name, wpath, ARRAY_SIZE(wpath));
    attrs = GetFileAttributesW(wpath);
    if (attrs != 0xFFFFFFFF && (attrs & FILE_ATTRIBUTE_DIRECTORY)) {
      (void) wcscat(wpath, L"\\*");
      dir->handle = FindFirstFileW(wpath, &dir->info);
      dir->result.d_name[0] = '\0';
    } else {
1149
      MG_FREE(dir);
1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162
      dir = NULL;
    }
  }

  return dir;
}

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

  if (dir != NULL) {
    if (dir->handle != INVALID_HANDLE_VALUE)
      result = FindClose(dir->handle) ? 0 : -1;
1163
    MG_FREE(dir);
1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723
  } else {
    result = -1;
    SetLastError(ERROR_BAD_ARGUMENTS);
  }

  return result;
}

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

  if (dir) {
    if (dir->handle != INVALID_HANDLE_VALUE) {
      result = &dir->result;
      (void) WideCharToMultiByte(CP_UTF8, 0, dir->info.cFileName, -1,
                                 result->d_name, sizeof(result->d_name), NULL,
                                 NULL);

      if (!FindNextFileW(dir->handle, &dir->info)) {
        (void) FindClose(dir->handle);
        dir->handle = INVALID_HANDLE_VALUE;
      }

    } else {
      SetLastError(ERROR_FILE_NOT_FOUND);
    }
  } else {
    SetLastError(ERROR_BAD_ARGUMENTS);
  }

  return result;
}
#endif

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

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

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
/* Amalgamated: #include "frozen.h" */

#ifdef _WIN32
#define snprintf _snprintf
#endif

#ifndef FROZEN_REALLOC
#define FROZEN_REALLOC realloc
#endif

#ifndef FROZEN_FREE
#define FROZEN_FREE free
#endif

struct frozen {
  const char *end;
  const char *cur;
  struct json_token *tokens;
  int max_tokens;
  int num_tokens;
  int do_realloc;
};

static int parse_object(struct frozen *f);
static int parse_value(struct frozen *f);

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

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

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

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

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

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

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

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

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

static int get_escape_len(const char *s, int len) {
  switch (*s) {
    case 'u':
      return len < 6 ? JSON_STRING_INCOMPLETE :
        is_hex_digit(s[1]) && is_hex_digit(s[2]) &&
        is_hex_digit(s[3]) && is_hex_digit(s[4]) ? 5 : JSON_STRING_INVALID;
    case '"': case '\\': case '/': case 'b':
    case 'f': case 'n': case 'r': case 't':
      return len < 2 ? JSON_STRING_INCOMPLETE : 1;
    default:
      return JSON_STRING_INVALID;
  }
}

static int capture_ptr(struct frozen *f, const char *ptr, enum json_type type) {
  if (f->do_realloc && f->num_tokens >= f->max_tokens) {
    int new_size = f->max_tokens == 0 ? 100 : f->max_tokens * 2;
    void *p = FROZEN_REALLOC(f->tokens, new_size * sizeof(f->tokens[0]));
    if (p == NULL) return JSON_TOKEN_ARRAY_TOO_SMALL;
    f->max_tokens = new_size;
    f->tokens = (struct json_token *) p;
  }
  if (f->tokens == NULL || f->max_tokens == 0) return 0;
  if (f->num_tokens >= f->max_tokens) return JSON_TOKEN_ARRAY_TOO_SMALL;
  f->tokens[f->num_tokens].ptr = ptr;
  f->tokens[f->num_tokens].type = type;
  f->num_tokens++;
  return 0;
}

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

/* identifier = letter { letter | digit | '_' } */
static int parse_identifier(struct frozen *f) {
  EXPECT(is_alpha(cur(f)), JSON_STRING_INVALID);
  TRY(capture_ptr(f, f->cur, JSON_TYPE_STRING));
  while (f->cur < f->end &&
         (*f->cur == '_' || is_alpha(*f->cur) || is_digit(*f->cur))) {
    f->cur++;
  }
  capture_len(f, f->num_tokens - 1, f->cur);
  return 0;
}

static int get_utf8_char_len(unsigned char ch) {
  if ((ch & 0x80) == 0) return 1;
  switch (ch & 0xf0) {
    case 0xf0: return 4;
    case 0xe0: return 3;
    default: return 2;
  }
}

/* string = '"' { quoted_printable_chars } '"' */
static int parse_string(struct frozen *f) {
  int n, ch = 0, len = 0;
  TRY(test_and_skip(f, '"'));
  TRY(capture_ptr(f, f->cur, JSON_TYPE_STRING));
  for (; f->cur < f->end; f->cur += len) {
    ch = * (unsigned char *) f->cur;
    len = get_utf8_char_len((unsigned char) ch);
    EXPECT(ch >= 32 && len > 0, JSON_STRING_INVALID);  /* No control chars */
    EXPECT(len < left(f), JSON_STRING_INCOMPLETE);
    if (ch == '\\') {
      EXPECT((n = get_escape_len(f->cur + 1, left(f))) > 0, n);
      len += n;
    } else if (ch == '"') {
      capture_len(f, f->num_tokens - 1, f->cur);
      f->cur++;
      break;
    };
  }
  return ch == '"' ? 0 : JSON_STRING_INCOMPLETE;
}

/* number = [ '-' ] digit+ [ '.' digit+ ] [ ['e'|'E'] ['+'|'-'] digit+ ] */
static int parse_number(struct frozen *f) {
  int ch = cur(f);
  TRY(capture_ptr(f, f->cur, JSON_TYPE_NUMBER));
  if (ch == '-') f->cur++;
  EXPECT(f->cur < f->end, JSON_STRING_INCOMPLETE);
  EXPECT(is_digit(f->cur[0]), JSON_STRING_INVALID);
  while (f->cur < f->end && is_digit(f->cur[0])) f->cur++;
  if (f->cur < f->end && f->cur[0] == '.') {
    f->cur++;
    EXPECT(f->cur < f->end, JSON_STRING_INCOMPLETE);
    EXPECT(is_digit(f->cur[0]), JSON_STRING_INVALID);
    while (f->cur < f->end && is_digit(f->cur[0])) f->cur++;
  }
  if (f->cur < f->end && (f->cur[0] == 'e' || f->cur[0] == 'E')) {
    f->cur++;
    EXPECT(f->cur < f->end, JSON_STRING_INCOMPLETE);
    if ((f->cur[0] == '+' || f->cur[0] == '-')) f->cur++;
    EXPECT(f->cur < f->end, JSON_STRING_INCOMPLETE);
    EXPECT(is_digit(f->cur[0]), JSON_STRING_INVALID);
    while (f->cur < f->end && is_digit(f->cur[0])) f->cur++;
  }
  capture_len(f, f->num_tokens - 1, f->cur);
  return 0;
}

/* array = '[' [ value { ',' value } ] ']' */
static int parse_array(struct frozen *f) {
  int ind;
  TRY(test_and_skip(f, '['));
  TRY(capture_ptr(f, f->cur - 1, JSON_TYPE_ARRAY));
  ind = f->num_tokens - 1;
  while (cur(f) != ']') {
    TRY(parse_value(f));
    if (cur(f) == ',') f->cur++;
  }
  TRY(test_and_skip(f, ']'));
  capture_len(f, ind, f->cur);
  return 0;
}

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

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

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

  return 0;
}

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

  switch (ch) {
    case '"': TRY(parse_string(f)); break;
    case '{': TRY(parse_object(f)); break;
    case '[': TRY(parse_array(f)); break;
    case 'n': TRY(expect(f, "null", 4, JSON_TYPE_NULL)); break;
    case 't': TRY(expect(f, "true", 4, JSON_TYPE_TRUE)); break;
    case 'f': TRY(expect(f, "false", 5, JSON_TYPE_FALSE)); break;
    case '-': case '0': case '1': case '2': case '3': case '4':
    case '5': case '6': case '7': case '8': case '9':
      TRY(parse_number(f));
      break;
    default:
      return ch == END_OF_STRING ? JSON_STRING_INCOMPLETE : JSON_STRING_INVALID;
  }

  return 0;
}

/* key = identifier | string */
static int parse_key(struct frozen *f) {
  int ch = cur(f);
#if 0
  printf("%s 1 [%.*s]\n", __func__, (int) (f->end - f->cur), f->cur);
#endif
  if (is_alpha(ch)) {
    TRY(parse_identifier(f));
  } else if (ch == '"') {
    TRY(parse_string(f));
  } else {
    return ch == END_OF_STRING ? JSON_STRING_INCOMPLETE : JSON_STRING_INVALID;
  }
  return 0;
}

/* pair = key ':' value */
static int parse_pair(struct frozen *f) {
  TRY(parse_key(f));
  TRY(test_and_skip(f, ':'));
  TRY(parse_value(f));
  return 0;
}

/* object = '{' pair { ',' pair } '}' */
static int parse_object(struct frozen *f) {
  int ind;
  TRY(test_and_skip(f, '{'));
  TRY(capture_ptr(f, f->cur - 1, JSON_TYPE_OBJECT));
  ind = f->num_tokens - 1;
  while (cur(f) != '}') {
    TRY(parse_pair(f));
    if (cur(f) == ',') f->cur++;
  }
  TRY(test_and_skip(f, '}'));
  capture_len(f, ind, f->cur);
  return 0;
}

static int doit(struct frozen *f) {
  if (f->cur == 0 || f->end < f->cur) return JSON_STRING_INVALID;
  if (f->end == f->cur) return JSON_STRING_INCOMPLETE;
  TRY(parse_object(f));
  TRY(capture_ptr(f, f->cur, JSON_TYPE_EOF));
  capture_len(f, f->num_tokens, f->cur);
  return 0;
}

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

  memset(&frozen, 0, sizeof(frozen));
  frozen.end = s + s_len;
  frozen.cur = s;
  frozen.tokens = arr;
  frozen.max_tokens = arr_len;

  TRY(doit(&frozen));

  return frozen.cur - s;
}

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

  memset(&frozen, 0, sizeof(frozen));
  frozen.end = s + s_len;
  frozen.cur = s;
  frozen.do_realloc = 1;

  if (doit(&frozen) < 0) {
    FROZEN_FREE((void *) frozen.tokens);
    frozen.tokens = NULL;
  }
  return frozen.tokens;
}

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

struct json_token *find_json_token(struct json_token *toks, const char *path) {
  while (path != 0 && path[0] != '\0') {
    int i, ind2 = 0, ind = -1, skip = 2, n = path_part_len(path);
    if (path[0] == '[') {
      if (toks->type != JSON_TYPE_ARRAY || !is_digit(path[1])) return 0;
      for (ind = 0, n = 1; path[n] != ']' && path[n] != '\0'; n++) {
        if (!is_digit(path[n])) return 0;
        ind *= 10;
        ind += path[n] - '0';
      }
      if (path[n++] != ']') return 0;
      skip = 1;  /* In objects, we skip 2 elems while iterating, in arrays 1. */
    } else if (toks->type != JSON_TYPE_OBJECT) return 0;
    toks++;
    for (i = 0; i < toks[-1].num_desc; i += skip, ind2++) {
      /* ind == -1 indicated that we're iterating an array, not object */
      if (ind == -1 && toks[i].type != JSON_TYPE_STRING) return 0;
      if (ind2 == ind ||
          (ind == -1 && toks[i].len == n && compare(path, toks[i].ptr, n))) {
        i += skip - 1;
        break;
      };
      if (toks[i - 1 + skip].type == JSON_TYPE_ARRAY ||
          toks[i - 1 + skip].type == JSON_TYPE_OBJECT) {
        i += toks[i - 1 + skip].num_desc;
      }
    }
    if (i == toks[-1].num_desc) return 0;
    path += n;
    if (path[0] == '.') path++;
    if (path[0] == '\0') return &toks[i];
    toks += i;
  }
  return 0;
}

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

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

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

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

  EMIT('"');
  while (str < str_end) {
    ch = *str++;
    switch (ch) {
      case '"':  EMIT('\\'); EMIT('"'); break;
      case '\\': EMIT('\\'); EMIT('\\'); break;
      case '\b': EMIT('\\'); EMIT('b'); break;
      case '\f': EMIT('\\'); EMIT('f'); break;
      case '\n': EMIT('\\'); EMIT('n'); break;
      case '\r': EMIT('\\'); EMIT('r'); break;
      case '\t': EMIT('\\'); EMIT('t'); break;
      default: EMIT(ch);
    }
  }
  EMIT('"');
  if (s < end) {
    *s = '\0';
  }

  return s - begin;
}

int json_emit_unquoted_str(char *buf, int buf_len, const char *str, int len) {
  if (buf_len > 0 && len > 0) {
    int n = len < buf_len ? len : buf_len;
    memcpy(buf, str, n);
    if (n < buf_len) {
      buf[n] = '\0';
    }
  }
  return len;
}

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

  while (*fmt != '\0') {
    switch (*fmt) {
      case '[': case ']': case '{': case '}': case ',': case ':':
      case ' ': case '\r': case '\n': case '\t':
        if (s < end) {
          *s = *fmt;
        }
        s++;
        break;
      case 'i':
        s += json_emit_long(s, end - s, va_arg(ap, long));
        break;
      case 'f':
        s += json_emit_double(s, end - s, va_arg(ap, double));
        break;
      case 'v':
        str = va_arg(ap, char *);
        len = va_arg(ap, size_t);
        s += json_emit_quoted_str(s, end - s, str, len);
        break;
      case 'V':
        str = va_arg(ap, char *);
        len = va_arg(ap, size_t);
        s += json_emit_unquoted_str(s, end - s, str, len);
        break;
      case 's':
        str = va_arg(ap, char *);
        s += json_emit_quoted_str(s, end - s, str, strlen(str));
        break;
      case 'S':
        str = va_arg(ap, char *);
        s += json_emit_unquoted_str(s, end - s, str, strlen(str));
        break;
      case 'T':
        s += json_emit_unquoted_str(s, end - s, "true", 4);
        break;
      case 'F':
        s += json_emit_unquoted_str(s, end - s, "false", 5);
        break;
      case 'N':
        s += json_emit_unquoted_str(s, end - s, "null", 4);
        break;
      default:
        return 0;
    }
    fmt++;
  }

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

  return s - orig;
}

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

  va_start(ap, fmt);
  len = json_emit_va(buf, buf_len, fmt, ap);
  va_end(ap);

  return len;
}
#ifdef NS_MODULE_LINES
#line 1 "src/net.c"
/**/
#endif
/*
 * Copyright (c) 2014 Cesanta Software Limited
 * All rights reserved
 *
 * This software is dual-licensed: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation. For the terms of this
 * license, see <http://www.gnu.org/licenses/>.
 *
 * You are free to use this software under the terms of the GNU General
 * Public License, but WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * Alternatively, you can license this software under a commercial
 * license, as set out in <https://www.cesanta.com/license>.
 */

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

1724
#if MG_MGR_EV_MGR == 1 /* epoll() */
1725 1726 1727
#include <sys/epoll.h>
#endif

1728 1729 1730 1731 1732
#define MG_CTL_MSG_MESSAGE_SIZE 8192
#define MG_READ_BUFFER_SIZE 1024
#define MG_UDP_RECEIVE_BUFFER_SIZE 1500
#define MG_VPRINTF_BUFFER_SIZE 100
#define MG_MAX_HOST_LEN 200
1733

1734
#define MG_COPY_COMMON_CONNECTION_OPTIONS(dst, src) \
1735 1736 1737
  memcpy(dst, src, sizeof(*dst));

/* Which flags can be pre-set by the user at connection creation time. */
1738 1739 1740
#define _MG_ALLOWED_CONNECT_FLAGS_MASK                                   \
  (MG_F_USER_1 | MG_F_USER_2 | MG_F_USER_3 | MG_F_USER_4 | MG_F_USER_5 | \
   MG_F_USER_6 | MG_F_WEBSOCKET_NO_DEFRAG)
1741
/* Which flags should be modifiable by user's callbacks. */
1742 1743 1744 1745
#define _MG_CALLBACK_MODIFIABLE_FLAGS_MASK                               \
  (MG_F_USER_1 | MG_F_USER_2 | MG_F_USER_3 | MG_F_USER_4 | MG_F_USER_5 | \
   MG_F_USER_6 | MG_F_WEBSOCKET_NO_DEFRAG | MG_F_SEND_AND_CLOSE |        \
   MG_F_DONT_SEND | MG_F_CLOSE_IMMEDIATELY | MG_F_IS_WEBSOCKET)
1746 1747 1748 1749 1750 1751 1752

#ifndef intptr_t
#define intptr_t long
#endif

struct ctl_msg {
  mg_event_handler_t callback;
1753
  char message[MG_CTL_MSG_MESSAGE_SIZE];
1754 1755 1756 1757 1758 1759 1760
};

static void mg_ev_mgr_init(struct mg_mgr *mgr);
static void mg_ev_mgr_free(struct mg_mgr *mgr);
static void mg_ev_mgr_add_conn(struct mg_connection *nc);
static void mg_ev_mgr_remove_conn(struct mg_connection *nc);

1761
MG_INTERNAL void mg_add_conn(struct mg_mgr *mgr, struct mg_connection *c) {
1762 1763 1764 1765 1766 1767 1768 1769
  c->mgr = mgr;
  c->next = mgr->active_connections;
  mgr->active_connections = c;
  c->prev = NULL;
  if (c->next != NULL) c->next->prev = c;
  mg_ev_mgr_add_conn(c);
}

1770
MG_INTERNAL void mg_remove_conn(struct mg_connection *conn) {
1771 1772 1773 1774 1775 1776
  if (conn->prev == NULL) conn->mgr->active_connections = conn->next;
  if (conn->prev) conn->prev->next = conn->next;
  if (conn->next) conn->next->prev = conn->prev;
  mg_ev_mgr_remove_conn(conn);
}

1777
MG_INTERNAL void mg_call(struct mg_connection *nc, int ev, void *ev_data) {
1778 1779 1780 1781 1782 1783
  unsigned long flags_before;
  mg_event_handler_t ev_handler;

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

1784
#ifndef MG_DISABLE_FILESYSTEM
1785
  /* LCOV_EXCL_START */
1786 1787 1788
  if (nc->mgr->hexdump_file != NULL && ev != MG_EV_POLL &&
      ev != MG_EV_SEND /* handled separately */) {
    int len = (ev == MG_EV_RECV ? *(int *) ev_data : 0);
1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802
    mg_hexdump_connection(nc, nc->mgr->hexdump_file, len, ev);
  }
/* LCOV_EXCL_STOP */
#endif

  /*
   * If protocol handler is specified, call it. Otherwise, call user-specified
   * event handler.
   */
  ev_handler = nc->proto_handler ? nc->proto_handler : nc->handler;
  if (ev_handler != NULL) {
    flags_before = nc->flags;
    ev_handler(nc, ev, ev_data);
    if (nc->flags != flags_before) {
1803 1804
      nc->flags = (flags_before & ~_MG_CALLBACK_MODIFIABLE_FLAGS_MASK) |
                  (nc->flags & _MG_CALLBACK_MODIFIABLE_FLAGS_MASK);
1805 1806 1807 1808 1809 1810
    }
  }
  DBG(("call done, flags %d", (int) nc->flags));
}

static size_t mg_out(struct mg_connection *nc, const void *buf, size_t len) {
1811
  if (nc->flags & MG_F_UDP) {
1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834
    int n = sendto(nc->sock, buf, len, 0, &nc->sa.sa, sizeof(nc->sa.sin));
    DBG(("%p %d %d %d %s:%hu", nc, nc->sock, n, errno,
         inet_ntoa(nc->sa.sin.sin_addr), ntohs(nc->sa.sin.sin_port)));
    return n < 0 ? 0 : n;
  } else {
    return mbuf_append(&nc->send_mbuf, buf, len);
  }
}

static void mg_destroy_conn(struct mg_connection *conn) {
  if (conn->sock != INVALID_SOCKET) {
    closesocket(conn->sock);
    /*
     * avoid users accidentally double close a socket
     * because it can lead to difficult to debug situations.
     * It would happen only if reusing a destroyed mg_connection
     * but it's not always possible to run the code through an
     * address sanitizer.
     */
    conn->sock = INVALID_SOCKET;
  }
  mbuf_free(&conn->recv_mbuf);
  mbuf_free(&conn->send_mbuf);
1835
#ifdef MG_ENABLE_SSL
1836 1837 1838 1839 1840 1841 1842
  if (conn->ssl != NULL) {
    SSL_free(conn->ssl);
  }
  if (conn->ssl_ctx != NULL) {
    SSL_CTX_free(conn->ssl_ctx);
  }
#endif
1843
  MG_FREE(conn);
1844 1845 1846 1847
}

static void mg_close_conn(struct mg_connection *conn) {
  DBG(("%p %lu", conn, conn->flags));
1848 1849
  if (!(conn->flags & MG_F_CONNECTING)) {
    mg_call(conn, MG_EV_CLOSE, NULL);
1850 1851 1852 1853 1854
  }
  mg_remove_conn(conn);
  mg_destroy_conn(conn);
}

1855 1856 1857 1858
void mg_mgr_init(struct mg_mgr *m, void *user_data) {
  memset(m, 0, sizeof(*m));
  m->ctl[0] = m->ctl[1] = INVALID_SOCKET;
  m->user_data = user_data;
1859 1860 1861 1862 1863 1864

#ifdef _WIN32
  {
    WSADATA data;
    WSAStartup(MAKEWORD(2, 2), &data);
  }
1865
#elif !defined(AVR_LIBC) && !defined(MG_ESP8266)
1866 1867 1868 1869 1870
  /* Ignore SIGPIPE signal, so if client cancels the request, it
   * won't kill the whole process. */
  signal(SIGPIPE, SIG_IGN);
#endif

1871
#ifndef MG_DISABLE_SOCKETPAIR
1872
  do {
1873 1874
    mg_socketpair(m->ctl, SOCK_DGRAM);
  } while (m->ctl[0] == INVALID_SOCKET);
1875 1876
#endif

1877
#ifdef MG_ENABLE_SSL
1878 1879 1880 1881 1882 1883 1884 1885
  {
    static int init_done;
    if (!init_done) {
      SSL_library_init();
      init_done++;
    }
  }
#endif
1886 1887

  mg_ev_mgr_init(m);
1888
  DBG(("=================================="));
1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906
  DBG(("init mgr=%p", m));
}

#ifdef MG_ENABLE_JAVASCRIPT
static v7_val_t mg_send_js(struct v7 *v7, v7_val_t this_obj, v7_val_t args) {
  v7_val_t arg0 = v7_array_get(v7, args, 0);
  v7_val_t arg1 = v7_array_get(v7, args, 1);
  struct mg_connection *c = (struct mg_connection *) v7_to_foreign(arg0);
  size_t len = 0;

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

  (void) this_obj;

  return v7_create_number(len);
1907 1908
}

1909 1910 1911 1912 1913 1914 1915 1916 1917 1918
enum v7_err mg_enable_javascript(struct mg_mgr *m, struct v7 *v7,
                                 const char *init_file_name) {
  v7_val_t v;
  m->v7 = v7;
  v7_set_method(v7, v7_get_global_object(v7), "mg_send", mg_send_js);
  return v7_exec_file(v7, init_file_name, &v);
}
#endif

void mg_mgr_free(struct mg_mgr *m) {
1919 1920
  struct mg_connection *conn, *tmp_conn;

1921 1922
  DBG(("%p", m));
  if (m == NULL) return;
1923
  /* Do one last poll, see https://github.com/cesanta/mongoose/issues/286 */
1924
  mg_mgr_poll(m, 0);
1925

1926 1927 1928
  if (m->ctl[0] != INVALID_SOCKET) closesocket(m->ctl[0]);
  if (m->ctl[1] != INVALID_SOCKET) closesocket(m->ctl[1]);
  m->ctl[0] = m->ctl[1] = INVALID_SOCKET;
1929

1930
  for (conn = m->active_connections; conn != NULL; conn = tmp_conn) {
1931 1932 1933 1934
    tmp_conn = conn->next;
    mg_close_conn(conn);
  }

1935
  mg_ev_mgr_free(m);
1936 1937 1938
}

int mg_vprintf(struct mg_connection *nc, const char *fmt, va_list ap) {
1939
  char mem[MG_VPRINTF_BUFFER_SIZE], *buf = mem;
1940 1941 1942 1943 1944 1945
  int len;

  if ((len = mg_avprintf(&buf, sizeof(mem), fmt, ap)) > 0) {
    mg_out(nc, buf, len);
  }
  if (buf != mem && buf != NULL) {
1946
    MG_FREE(buf); /* LCOV_EXCL_LINE */
1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964
  }               /* LCOV_EXCL_LINE */

  return len;
}

int mg_printf(struct mg_connection *conn, const char *fmt, ...) {
  int len;
  va_list ap;
  va_start(ap, fmt);
  len = mg_vprintf(conn, fmt, ap);
  va_end(ap);
  return len;
}

static void mg_set_non_blocking_mode(sock_t sock) {
#ifdef _WIN32
  unsigned long on = 1;
  ioctlsocket(sock, FIONBIO, &on);
1965
#elif defined(MG_CC3200)
1966 1967 1968 1969 1970 1971 1972
  cc3200_set_non_blocking_mode(sock);
#else
  int flags = fcntl(sock, F_GETFL, 0);
  fcntl(sock, F_SETFL, flags | O_NONBLOCK);
#endif
}

1973
#ifndef MG_DISABLE_SOCKETPAIR
1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014
int mg_socketpair(sock_t sp[2], int sock_type) {
  union socket_address sa;
  sock_t sock;
  socklen_t len = sizeof(sa.sin);
  int ret = 0;

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

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

  if ((sock = socket(AF_INET, sock_type, 0)) == INVALID_SOCKET) {
  } else if (bind(sock, &sa.sa, len) != 0) {
  } else if (sock_type == SOCK_STREAM && listen(sock, 1) != 0) {
  } else if (getsockname(sock, &sa.sa, &len) != 0) {
  } else if ((sp[0] = socket(AF_INET, sock_type, 0)) == INVALID_SOCKET) {
  } else if (connect(sp[0], &sa.sa, len) != 0) {
  } else if (sock_type == SOCK_DGRAM &&
             (getsockname(sp[0], &sa.sa, &len) != 0 ||
              connect(sock, &sa.sa, len) != 0)) {
  } else if ((sp[1] = (sock_type == SOCK_DGRAM ? sock
                                               : accept(sock, &sa.sa, &len))) ==
             INVALID_SOCKET) {
  } else {
    mg_set_close_on_exec(sp[0]);
    mg_set_close_on_exec(sp[1]);
    if (sock_type == SOCK_STREAM) closesocket(sock);
    ret = 1;
  }

  if (!ret) {
    if (sp[0] != INVALID_SOCKET) closesocket(sp[0]);
    if (sp[1] != INVALID_SOCKET) closesocket(sp[1]);
    if (sock != INVALID_SOCKET) closesocket(sock);
    sock = sp[0] = sp[1] = INVALID_SOCKET;
  }

  return ret;
}
2015
#endif /* MG_DISABLE_SOCKETPAIR */
2016 2017 2018

/* TODO(lsm): use non-blocking resolver */
static int mg_resolve2(const char *host, struct in_addr *ina) {
2019
#ifdef MG_ENABLE_GETADDRINFO
2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044
  int rv = 0;
  struct addrinfo hints, *servinfo, *p;
  struct sockaddr_in *h = NULL;
  memset(&hints, 0, sizeof hints);
  hints.ai_family = AF_INET;
  hints.ai_socktype = SOCK_STREAM;
  if ((rv = getaddrinfo(host, NULL, NULL, &servinfo)) != 0) {
    DBG(("getaddrinfo(%s) failed: %s", host, strerror(errno)));
    return 0;
  }
  for (p = servinfo; p != NULL; p = p->ai_next) {
    memcpy(&h, &p->ai_addr, sizeof(struct sockaddr_in *));
    memcpy(ina, &h->sin_addr, sizeof(ina));
  }
  freeaddrinfo(servinfo);
  return 1;
#else
  struct hostent *he;
  if ((he = gethostbyname(host)) == NULL) {
    DBG(("gethostbyname(%s) failed: %s", host, strerror(errno)));
  } else {
    memcpy(ina, he->h_addr_list[0], sizeof(*ina));
    return 1;
  }
  return 0;
2045
#endif /* MG_ENABLE_GETADDRINFO */
2046 2047 2048 2049 2050 2051 2052
}

int mg_resolve(const char *host, char *buf, size_t n) {
  struct in_addr ad;
  return mg_resolve2(host, &ad) ? snprintf(buf, n, "%s", inet_ntoa(ad)) : 0;
}

2053
MG_INTERNAL struct mg_connection *mg_create_connection(
2054 2055 2056 2057
    struct mg_mgr *mgr, mg_event_handler_t callback,
    struct mg_add_sock_opts opts) {
  struct mg_connection *conn;

2058
  if ((conn = (struct mg_connection *) MG_MALLOC(sizeof(*conn))) != NULL) {
2059 2060 2061 2062 2063
    memset(conn, 0, sizeof(*conn));
    conn->sock = INVALID_SOCKET;
    conn->handler = callback;
    conn->mgr = mgr;
    conn->last_io_time = time(NULL);
2064
    conn->flags = opts.flags & _MG_ALLOWED_CONNECT_FLAGS_MASK;
2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077
    conn->user_data = opts.user_data;
    /*
     * SIZE_MAX is defined as a long long constant in
     * system headers on some platforms and so it
     * doesn't compile with pedantic ansi flags.
     */
    conn->recv_mbuf_limit = ~0;
  }

  return conn;
}

/* Associate a socket to a connection and and add to the manager. */
2078
MG_INTERNAL void mg_set_sock(struct mg_connection *nc, sock_t sock) {
2079
#if !defined(MG_CC3200)
2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096
  /* Can't get non-blocking connect to work.
   * TODO(rojer): Figure out why it fails where blocking succeeds.
   */
  mg_set_non_blocking_mode(sock);
#endif
  mg_set_close_on_exec(sock);
  nc->sock = sock;
  mg_add_conn(nc->mgr, nc);

  DBG(("%p %d", nc, sock));
}

/*
 * Address format: [PROTO://][HOST]:PORT
 *
 * HOST could be IPv4/IPv6 address or a host name.
 * `host` is a destination buffer to hold parsed HOST part. Shoud be at least
2097
 * MG_MAX_HOST_LEN bytes long.
2098 2099 2100 2101 2102 2103 2104
 * `proto` is a returned socket type, either SOCK_STREAM or SOCK_DGRAM
 *
 * Return:
 *   -1   on parse error
 *    0   if HOST needs DNS lookup
 *   >0   length of the address string
 */
2105
MG_INTERNAL int mg_parse_address(const char *str, union socket_address *sa,
2106 2107 2108
                                 int *proto, char *host, size_t host_len) {
  unsigned int a, b, c, d, port = 0;
  int len = 0;
2109
#ifdef MG_ENABLE_IPV6
2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134
  char buf[100];
#endif

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

  *proto = SOCK_STREAM;

  if (strncmp(str, "udp://", 6) == 0) {
    str += 6;
    *proto = SOCK_DGRAM;
  } else if (strncmp(str, "tcp://", 6) == 0) {
    str += 6;
  }

  if (sscanf(str, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len) == 5) {
    /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
    sa->sin.sin_addr.s_addr =
        htonl(((uint32_t) a << 24) | ((uint32_t) b << 16) | c << 8 | d);
    sa->sin.sin_port = htons((uint16_t) port);
2135
#ifdef MG_ENABLE_IPV6
2136 2137 2138 2139 2140 2141
  } else if (sscanf(str, "[%99[^]]]:%u%n", buf, &port, &len) == 2 &&
             inet_pton(AF_INET6, buf, &sa->sin6.sin6_addr)) {
    /* IPv6 address, e.g. [3ffe:2a00:100:7031::1]:8080 */
    sa->sin6.sin6_family = AF_INET6;
    sa->sin.sin_port = htons((uint16_t) port);
#endif
2142
#ifndef MG_DISABLE_RESOLVER
2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165
  } else if (strlen(str) < host_len &&
             sscanf(str, "%[^ :]:%u%n", host, &port, &len) == 2) {
    sa->sin.sin_port = htons((uint16_t) port);
    if (mg_resolve_from_hosts_file(host, sa) != 0) {
      return 0;
    }
#endif
  } else if (sscanf(str, ":%u%n", &port, &len) == 1 ||
             sscanf(str, "%u%n", &port, &len) == 1) {
    /* If only port is specified, bind to IPv4, INADDR_ANY */
    sa->sin.sin_port = htons((uint16_t) port);
  } else {
    return -1;
  }

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

/* 'sa' must be an initialized address to bind to */
static sock_t mg_open_listening_socket(union socket_address *sa, int proto) {
  socklen_t sa_len =
      (sa->sa.sa_family == AF_INET) ? sizeof(sa->sin) : sizeof(sa->sin6);
  sock_t sock = INVALID_SOCKET;
2166
#if !defined(MG_CC3200) && !defined(RTOS_SDK)
2167 2168 2169 2170
  int on = 1;
#endif

  if ((sock = socket(sa->sa.sa_family, proto, 0)) != INVALID_SOCKET &&
2171 2172
#if !defined(MG_CC3200) && \
    !defined(RTOS_SDK) /* CC3200 nor ESP8266 don't support either */
2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190
#if defined(_WIN32) && defined(SO_EXCLUSIVEADDRUSE)
      /* "Using SO_REUSEADDR and SO_EXCLUSIVEADDRUSE" http://goo.gl/RmrFTm */
      !setsockopt(sock, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (void *) &on,
                  sizeof(on)) &&
#endif

#if !defined(_WIN32) || !defined(SO_EXCLUSIVEADDRUSE)
      /*
       * SO_RESUSEADDR is not enabled on Windows because the semantics of
       * SO_REUSEADDR on UNIX and Windows is different. On Windows,
       * SO_REUSEADDR allows to bind a socket to a port without error even if
       * the port is already open by another program. This is not the behavior
       * SO_REUSEADDR was designed for, and leads to hard-to-track failure
       * scenarios. Therefore, SO_REUSEADDR was disabled on Windows unless
       * SO_EXCLUSIVEADDRUSE is supported and set on a socket.
       */
      !setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *) &on, sizeof(on)) &&
#endif
2191
#endif /* !MG_CC3200 */
2192 2193 2194

      !bind(sock, &sa->sa, sa_len) &&
      (proto == SOCK_DGRAM || listen(sock, SOMAXCONN) == 0)) {
2195
#if !defined(MG_CC3200) && !defined(RTOS_SDK) /* TODO(rojer): Fix this. */
2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207
    mg_set_non_blocking_mode(sock);
    /* In case port was set to 0, get the real port number */
    (void) getsockname(sock, &sa->sa, &sa_len);
#endif
  } else if (sock != INVALID_SOCKET) {
    closesocket(sock);
    sock = INVALID_SOCKET;
  }

  return sock;
}

2208
#ifdef MG_ENABLE_SSL
2209 2210 2211 2212 2213 2214 2215 2216 2217 2218
/*
 * Certificate generation script is at
 * https://github.com/cesanta/mongoose/blob/master/scripts/generate_ssl_certificates.sh
 */

/*
 * Cipher suite options used for TLS negotiation.
 * https://wiki.mozilla.org/Security/Server_Side_TLS#Recommended_configurations
 */
static const char mg_s_cipher_list[] =
2219
#if defined(MG_SSL_CRYPTO_MODERN)
2220 2221 2222 2223 2224 2225 2226 2227 2228
    "ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:"
    "ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:"
    "DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:"
    "ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:"
    "ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:"
    "ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:"
    "DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:"
    "DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:"
    "!aNULL:!eNULL:!EXPORT:!DES:!RC4:!3DES:!MD5:!PSK"
2229
#elif defined(MG_SSL_CRYPTO_OLD)
2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256
    "ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:"
    "ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:"
    "DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:"
    "ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:"
    "ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:"
    "ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:"
    "DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:"
    "DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:ECDHE-RSA-DES-CBC3-SHA:"
    "ECDHE-ECDSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:"
    "AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:DES-CBC3-SHA:"
    "HIGH:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:"
    "!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA"
#else /* Default - intermediate. */
    "ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:"
    "ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:"
    "DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:"
    "ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:"
    "ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:"
    "ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:"
    "DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:"
    "DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:"
    "AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:CAMELLIA:"
    "DES-CBC3-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:"
    "!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA"
#endif
    ;

2257
#ifndef MG_DISABLE_PFS
2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291
/*
 * Default DH params for PFS cipher negotiation. This is a 2048-bit group.
 * Will be used if none are provided by the user in the certificate file.
 */
static const char mg_s_default_dh_params[] =
    "\
-----BEGIN DH PARAMETERS-----\n\
MIIBCAKCAQEAlvbgD/qh9znWIlGFcV0zdltD7rq8FeShIqIhkQ0C7hYFThrBvF2E\n\
Z9bmgaP+sfQwGpVlv9mtaWjvERbu6mEG7JTkgmVUJrUt/wiRzwTaCXBqZkdUO8Tq\n\
+E6VOEQAilstG90ikN1Tfo+K6+X68XkRUIlgawBTKuvKVwBhuvlqTGerOtnXWnrt\n\
ym//hd3cd5PBYGBix0i7oR4xdghvfR2WLVu0LgdThTBb6XP7gLd19cQ1JuBtAajZ\n\
wMuPn7qlUkEFDIkAZy59/Hue/H2Q2vU/JsvVhHWCQBL4F1ofEAt50il6ZxR1QfFK\n\
9VGKDC4oOgm9DlxwwBoC2FjqmvQlqVV3kwIBAg==\n\
-----END DH PARAMETERS-----\n";
#endif

static int mg_use_ca_cert(SSL_CTX *ctx, const char *cert) {
  if (ctx == NULL) {
    return -1;
  } else if (cert == NULL || cert[0] == '\0') {
    return 0;
  }
  SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, 0);
  return SSL_CTX_load_verify_locations(ctx, cert, NULL) == 1 ? 0 : -2;
}

static int mg_use_cert(SSL_CTX *ctx, const char *pem_file) {
  if (ctx == NULL) {
    return -1;
  } else if (pem_file == NULL || pem_file[0] == '\0') {
    return 0;
  } else if (SSL_CTX_use_certificate_file(ctx, pem_file, 1) == 0 ||
             SSL_CTX_use_PrivateKey_file(ctx, pem_file, 1) == 0) {
    return -2;
2292
#ifndef MG_DISABLE_PFS
2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344
  } else {
    BIO *bio = NULL;
    DH *dh = NULL;

    /* Try to read DH parameters from the cert/key file. */
    bio = BIO_new_file(pem_file, "r");
    if (bio != NULL) {
      dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
      BIO_free(bio);
    }
    /*
     * If there are no DH params in the file, fall back to hard-coded ones.
     * Not ideal, but better than nothing.
     */
    if (dh == NULL) {
      bio = BIO_new_mem_buf((void *) mg_s_default_dh_params, -1);
      dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
      BIO_free(bio);
    }
    if (dh != NULL) {
      SSL_CTX_set_tmp_dh(ctx, dh);
      SSL_CTX_set_options(ctx, SSL_OP_SINGLE_DH_USE);
      DH_free(dh);
    }

    SSL_CTX_set_mode(ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
    SSL_CTX_use_certificate_chain_file(ctx, pem_file);
    return 0;
#endif
  }
}

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

2345
  if ((nc->flags & MG_F_LISTENING) &&
2346 2347
      (nc->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
    result = "SSL_CTX_new() failed";
2348
  } else if (!(nc->flags & MG_F_LISTENING) &&
2349 2350 2351 2352 2353 2354
             (nc->ssl_ctx = SSL_CTX_new(SSLv23_client_method())) == NULL) {
    result = "SSL_CTX_new() failed";
  } else if (mg_use_cert(nc->ssl_ctx, cert) != 0) {
    result = "Invalid ssl cert";
  } else if (mg_use_ca_cert(nc->ssl_ctx, ca_cert) != 0) {
    result = "Invalid CA cert";
2355
  } else if (!(nc->flags & MG_F_LISTENING) &&
2356 2357
             (nc->ssl = SSL_new(nc->ssl_ctx)) == NULL) {
    result = "SSL_new() failed";
2358
  } else if (!(nc->flags & MG_F_LISTENING) && nc->sock != INVALID_SOCKET) {
2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374
    /*
     * Socket is open here only if we are connecting to IP address
     * and does not open if we are connecting using async DNS resolver
     */
    SSL_set_fd(nc->ssl, nc->sock);
  }

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

static int mg_ssl_err(struct mg_connection *conn, int res) {
  int ssl_err = SSL_get_error(conn->ssl, res);
2375 2376
  if (ssl_err == SSL_ERROR_WANT_READ) conn->flags |= MG_F_WANT_READ;
  if (ssl_err == SSL_ERROR_WANT_WRITE) conn->flags |= MG_F_WANT_WRITE;
2377 2378
  return ssl_err;
}
2379
#endif /* MG_ENABLE_SSL */
2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390

static struct mg_connection *accept_conn(struct mg_connection *ls) {
  struct mg_connection *c = NULL;
  union socket_address sa;
  socklen_t len = sizeof(sa);
  sock_t sock = INVALID_SOCKET;

  /* NOTE(lsm): on Windows, sock is always > FD_SETSIZE */
  if ((sock = accept(ls->sock, &sa.sa, &len)) == INVALID_SOCKET) {
  } else if ((c = mg_add_sock(ls->mgr, sock, ls->handler)) == NULL) {
    closesocket(sock);
2391
#ifdef MG_ENABLE_SSL
2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404
  } else if (ls->ssl_ctx != NULL && ((c->ssl = SSL_new(ls->ssl_ctx)) == NULL ||
                                     SSL_set_fd(c->ssl, sock) != 1)) {
    DBG(("SSL error"));
    mg_close_conn(c);
    c = NULL;
#endif
  } else {
    c->listener = ls;
    c->proto_data = ls->proto_data;
    c->proto_handler = ls->proto_handler;
    c->user_data = ls->user_data;
    c->recv_mbuf_limit = ls->recv_mbuf_limit;
    if (c->ssl == NULL) { /* SSL connections need to perform handshake. */
2405
      mg_call(c, MG_EV_ACCEPT, &sa);
2406 2407 2408 2409 2410 2411 2412 2413
    }
    DBG(("%p %d %p %p", c, c->sock, c->ssl_ctx, c->ssl));
  }

  return c;
}

static int mg_is_error(int n) {
2414
#ifdef MG_CC3200
2415 2416 2417 2418 2419
  DBG(("n = %d, errno = %d", n, errno));
  if (n < 0) errno = n;
#endif
  return n == 0 || (n < 0 && errno != EINTR && errno != EINPROGRESS &&
                    errno != EAGAIN && errno != EWOULDBLOCK
2420
#ifdef MG_CC3200
2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436
                    && errno != SL_EALREADY
#endif
#ifdef _WIN32
                    && WSAGetLastError() != WSAEINTR &&
                    WSAGetLastError() != WSAEWOULDBLOCK
#endif
                    );
}

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

2437
#ifdef MG_ENABLE_SSL
2438 2439 2440 2441 2442
static void mg_ssl_begin(struct mg_connection *nc) {
  int server_side = nc->listener != NULL;
  int res = server_side ? SSL_accept(nc->ssl) : SSL_connect(nc->ssl);

  if (res == 1) {
2443 2444
    nc->flags |= MG_F_SSL_HANDSHAKE_DONE;
    nc->flags &= ~(MG_F_WANT_READ | MG_F_WANT_WRITE);
2445 2446 2447 2448 2449 2450

    if (server_side) {
      union socket_address sa;
      socklen_t sa_len = sizeof(sa);
      /* In case port was set to 0, get the real port number */
      (void) getsockname(nc->sock, &sa.sa, &sa_len);
2451
      mg_call(nc, MG_EV_ACCEPT, &sa);
2452 2453 2454 2455
    }
  } else {
    int ssl_err = mg_ssl_err(nc, res);
    if (ssl_err != SSL_ERROR_WANT_READ && ssl_err != SSL_ERROR_WANT_WRITE) {
2456
      nc->flags |= MG_F_CLOSE_IMMEDIATELY;
2457 2458 2459
    }
  }
}
2460
#endif /* MG_ENABLE_SSL */
2461 2462

static void mg_read_from_socket(struct mg_connection *conn) {
2463
  char buf[MG_READ_BUFFER_SIZE];
2464
  int n = 0;
2465

2466
  if (conn->flags & MG_F_CONNECTING) {
2467
    int ok = 1, ret;
2468
#if !defined(MG_CC3200) && !defined(MG_ESP8266)
2469 2470 2471 2472
    socklen_t len = sizeof(ok);
#endif

    (void) ret;
2473
#if defined(MG_CC3200) || defined(MG_ESP8266)
2474
    /* On CC3200 and ESP8266 we use blocking connect. If we got as far as this,
2475 2476 2477 2478 2479 2480 2481 2482
     * this means connect() was successful.
     * TODO(rojer): Figure out why it fails where blocking succeeds.
     */
    mg_set_non_blocking_mode(conn->sock);
    ret = ok = 0;
#else
    ret = getsockopt(conn->sock, SOL_SOCKET, SO_ERROR, (char *) &ok, &len);
#endif
2483
#ifdef MG_ENABLE_SSL
2484 2485 2486 2487 2488 2489
    if (ret == 0 && ok == 0 && conn->ssl != NULL) {
      mg_ssl_begin(conn);
    }
#endif
    DBG(("%p connect ok=%d", conn, ok));
    if (ok != 0) {
2490
      conn->flags |= MG_F_CLOSE_IMMEDIATELY;
2491
    } else {
2492
      conn->flags &= ~MG_F_CONNECTING;
2493
    }
2494
    mg_call(conn, MG_EV_CONNECT, &ok);
2495 2496 2497
    return;
  }

2498
#ifdef MG_ENABLE_SSL
2499
  if (conn->ssl != NULL) {
2500
    if (conn->flags & MG_F_SSL_HANDSHAKE_DONE) {
2501 2502 2503 2504 2505 2506
      /* SSL library may have more bytes ready to read then we ask to read.
       * Therefore, read in a loop until we read everything. Without the loop,
       * we skip to the next select() cycle which can just timeout. */
      while ((n = SSL_read(conn->ssl, buf, sizeof(buf))) > 0) {
        DBG(("%p %d bytes <- %d (SSL)", conn, n, conn->sock));
        mbuf_append(&conn->recv_mbuf, buf, n);
2507 2508
        mg_call(conn, MG_EV_RECV, &n);
        if (conn->flags & MG_F_CLOSE_IMMEDIATELY) break;
2509 2510 2511 2512 2513 2514 2515 2516
      }
      mg_ssl_err(conn, n);
    } else {
      mg_ssl_begin(conn);
      return;
    }
  } else
#endif
2517
    while ((n = (int) MG_EV_RECV_FUNC(
2518
                conn->sock, buf, recv_avail_size(conn, sizeof(buf)), 0)) > 0) {
2519 2520
      DBG(("%p %d bytes (PLAIN) <- %d", conn, n, conn->sock));
      mbuf_append(&conn->recv_mbuf, buf, n);
2521 2522
      mg_call(conn, MG_EV_RECV, &n);
      if (conn->flags & MG_F_CLOSE_IMMEDIATELY) break;
2523
    }
2524
  DBG(("recv returns %d", n));
2525 2526

  if (mg_is_error(n)) {
2527
    conn->flags |= MG_F_CLOSE_IMMEDIATELY;
2528 2529 2530 2531 2532 2533 2534
  }
}

static void mg_write_to_socket(struct mg_connection *conn) {
  struct mbuf *io = &conn->send_mbuf;
  int n = 0;

2535 2536 2537 2538 2539
#ifdef RTOS_SDK
  /* In ESP8266 RTOS_SDK we don't know if the socket is ready */
  if (io->len == 0) return;
#endif

2540 2541
  assert(io->len > 0);

2542
#ifdef MG_ENABLE_SSL
2543
  if (conn->ssl != NULL) {
2544
    if (conn->flags & MG_F_SSL_HANDSHAKE_DONE) {
2545 2546 2547 2548 2549 2550
      n = SSL_write(conn->ssl, io->buf, io->len);
      if (n <= 0) {
        int ssl_err = mg_ssl_err(conn, n);
        if (ssl_err == SSL_ERROR_WANT_READ || ssl_err == SSL_ERROR_WANT_WRITE) {
          return; /* Call us again */
        } else {
2551
          conn->flags |= MG_F_CLOSE_IMMEDIATELY;
2552 2553 2554
        }
      } else {
        /* Successful SSL operation, clear off SSL wait flags */
2555
        conn->flags &= ~(MG_F_WANT_READ | MG_F_WANT_WRITE);
2556 2557 2558 2559 2560 2561 2562 2563
      }
    } else {
      mg_ssl_begin(conn);
      return;
    }
  } else
#endif
  {
2564
    n = (int) MG_EV_SEND_FUNC(conn->sock, io->buf, io->len, 0);
2565 2566 2567 2568 2569
  }

  DBG(("%p %d bytes -> %d", conn, n, conn->sock));

  if (mg_is_error(n)) {
2570
    conn->flags |= MG_F_CLOSE_IMMEDIATELY;
2571
  } else if (n > 0) {
2572
#ifndef MG_DISABLE_FILESYSTEM
2573 2574
    /* LCOV_EXCL_START */
    if (conn->mgr->hexdump_file != NULL) {
2575
      mg_hexdump_connection(conn, conn->mgr->hexdump_file, n, MG_EV_SEND);
2576 2577 2578 2579 2580
    }
/* LCOV_EXCL_STOP */
#endif
    mbuf_remove(io, n);
  }
2581
  mg_call(conn, MG_EV_SEND, &n);
2582 2583 2584 2585 2586 2587 2588 2589
}

int mg_send(struct mg_connection *conn, const void *buf, int len) {
  return (int) mg_out(conn, buf, len);
}

static void mg_handle_udp(struct mg_connection *ls) {
  struct mg_connection nc;
2590
  char buf[MG_UDP_RECEIVE_BUFFER_SIZE];
2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607
  int n;
  socklen_t s_len = sizeof(nc.sa);

  memset(&nc, 0, sizeof(nc));
  n = recvfrom(ls->sock, buf, sizeof(buf), 0, &nc.sa.sa, &s_len);
  if (n <= 0) {
    DBG(("%p recvfrom: %s", ls, strerror(errno)));
  } else {
    union socket_address sa = nc.sa;
    /* Copy all attributes, preserving sender address */
    nc = *ls;

    /* Then override some */
    nc.sa = sa;
    nc.recv_mbuf.buf = buf;
    nc.recv_mbuf.len = nc.recv_mbuf.size = n;
    nc.listener = ls;
2608
    nc.flags = MG_F_UDP;
2609

2610
    /* Call MG_EV_RECV handler */
2611
    DBG(("%p %d bytes received", ls, n));
2612
    mg_call(&nc, MG_EV_RECV, &n);
2613 2614 2615 2616 2617 2618 2619 2620 2621

    /*
     * See https://github.com/cesanta/mongoose/issues/207
     * mg_call migth set flags. They need to be synced back to ls.
     */
    ls->flags = nc.flags;
  }
}

2622 2623 2624
#define _MG_F_FD_CAN_READ 1
#define _MG_F_FD_CAN_WRITE 1 << 1
#define _MG_F_FD_ERROR 1 << 2
2625 2626 2627 2628 2629 2630 2631

static void mg_mgr_handle_connection(struct mg_connection *nc, int fd_flags,
                                     time_t now) {
  DBG(("%p fd=%d fd_flags=%d nc_flags=%lu rmbl=%d smbl=%d", nc, nc->sock,
       fd_flags, nc->flags, (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len));
  if (fd_flags != 0) nc->last_io_time = now;

2632
  if (nc->flags & MG_F_CONNECTING) {
2633 2634 2635 2636 2637 2638
    if (fd_flags != 0) {
      mg_read_from_socket(nc);
    }
    return;
  }

2639
  if (nc->flags & MG_F_LISTENING) {
2640 2641 2642 2643 2644
    /*
     * We're not looping here, and accepting just one connection at
     * a time. The reason is that eCos does not respect non-blocking
     * flag on a listening socket and hangs in a loop.
     */
2645
    if (fd_flags & _MG_F_FD_CAN_READ) accept_conn(nc);
2646 2647 2648
    return;
  }

2649 2650
  if (fd_flags & _MG_F_FD_CAN_READ) {
    if (nc->flags & MG_F_UDP) {
2651 2652 2653 2654
      mg_handle_udp(nc);
    } else {
      mg_read_from_socket(nc);
    }
2655
    if (nc->flags & MG_F_CLOSE_IMMEDIATELY) return;
2656 2657
  }

2658 2659
  if ((fd_flags & _MG_F_FD_CAN_WRITE) && !(nc->flags & MG_F_DONT_SEND) &&
      !(nc->flags & MG_F_UDP)) { /* Writes to UDP sockets are not buffered. */
2660 2661 2662
    mg_write_to_socket(nc);
  }

2663 2664
  if (!(fd_flags & (_MG_F_FD_CAN_READ | _MG_F_FD_CAN_WRITE))) {
    mg_call(nc, MG_EV_POLL, &now);
2665 2666 2667 2668 2669 2670
  }

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

2671
#ifndef MG_DISABLE_SOCKETPAIR
2672 2673 2674
static void mg_mgr_handle_ctl_sock(struct mg_mgr *mgr) {
  struct ctl_msg ctl_msg;
  int len =
2675 2676
      (int) MG_EV_RECV_FUNC(mgr->ctl[1], (char *) &ctl_msg, sizeof(ctl_msg), 0);
  MG_EV_SEND_FUNC(mgr->ctl[1], ctl_msg.message, 1, 0);
2677 2678 2679
  if (len >= (int) sizeof(ctl_msg.callback) && ctl_msg.callback != NULL) {
    struct mg_connection *nc;
    for (nc = mg_next(mgr, NULL); nc != NULL; nc = mg_next(mgr, nc)) {
2680
      ctl_msg.callback(nc, MG_EV_POLL, ctl_msg.message);
2681 2682 2683
    }
  }
}
2684
#endif
2685

2686
#if MG_MGR_EV_MGR == 1 /* epoll() */
2687

2688 2689
#ifndef MG_EPOLL_MAX_EVENTS
#define MG_EPOLL_MAX_EVENTS 100
2690 2691
#endif

2692 2693 2694
#define _MG_EPF_EV_EPOLLIN (1 << 0)
#define _MG_EPF_EV_EPOLLOUT (1 << 1)
#define _MG_EPF_NO_POLL (1 << 2)
2695 2696 2697

static uint32_t mg_epf_to_evflags(unsigned int epf) {
  uint32_t result = 0;
2698 2699
  if (epf & _MG_EPF_EV_EPOLLIN) result |= EPOLLIN;
  if (epf & _MG_EPF_EV_EPOLLOUT) result |= EPOLLOUT;
2700 2701 2702 2703 2704 2705 2706 2707 2708 2709
  return result;
}

static void mg_ev_mgr_epoll_set_flags(const struct mg_connection *nc,
                                      struct epoll_event *ev) {
  /* NOTE: EPOLLERR and EPOLLHUP are always enabled. */
  ev->events = 0;
  if (nc->recv_mbuf.len < nc->recv_mbuf_limit) {
    ev->events |= EPOLLIN;
  }
2710 2711
  if ((nc->flags & MG_F_CONNECTING) ||
      (nc->send_mbuf.len > 0 && !(nc->flags & MG_F_DONT_SEND))) {
2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736
    ev->events |= EPOLLOUT;
  }
}

static void mg_ev_mgr_epoll_ctl(struct mg_connection *nc, int op) {
  int epoll_fd = (intptr_t) nc->mgr->mgr_data;
  struct epoll_event ev;
  assert(op == EPOLL_CTL_ADD || op == EPOLL_CTL_MOD || EPOLL_CTL_DEL);
  if (op != EPOLL_CTL_DEL) {
    mg_ev_mgr_epoll_set_flags(nc, &ev);
    if (op == EPOLL_CTL_MOD) {
      uint32_t old_ev_flags = mg_epf_to_evflags((intptr_t) nc->mgr_data);
      if (ev.events == old_ev_flags) return;
    }
    ev.data.ptr = nc;
  }
  if (epoll_ctl(epoll_fd, op, nc->sock, &ev) != 0) {
    perror("epoll_ctl");
    abort();
  }
}

static void mg_ev_mgr_init(struct mg_mgr *mgr) {
  int epoll_fd;
  DBG(("%p using epoll()", mgr));
2737
  epoll_fd = epoll_create(MG_EPOLL_MAX_EVENTS /* unused but required */);
2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768
  if (epoll_fd < 0) {
    perror("epoll_ctl");
    abort();
  }
  mgr->mgr_data = (void *) ((intptr_t) epoll_fd);
  if (mgr->ctl[1] != INVALID_SOCKET) {
    struct epoll_event ev;
    ev.events = EPOLLIN;
    ev.data.ptr = NULL;
    if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, mgr->ctl[1], &ev) != 0) {
      perror("epoll_ctl");
      abort();
    }
  }
}

static void mg_ev_mgr_free(struct mg_mgr *mgr) {
  int epoll_fd = (intptr_t) mgr->mgr_data;
  close(epoll_fd);
}

static void mg_ev_mgr_add_conn(struct mg_connection *nc) {
  mg_ev_mgr_epoll_ctl(nc, EPOLL_CTL_ADD);
}

static void mg_ev_mgr_remove_conn(struct mg_connection *nc) {
  mg_ev_mgr_epoll_ctl(nc, EPOLL_CTL_DEL);
}

time_t mg_mgr_poll(struct mg_mgr *mgr, int timeout_ms) {
  int epoll_fd = (intptr_t) mgr->mgr_data;
2769
  struct epoll_event events[MG_EPOLL_MAX_EVENTS];
2770 2771 2772 2773
  struct mg_connection *nc, *next;
  int num_ev, fd_flags;
  time_t now;

2774
  num_ev = epoll_wait(epoll_fd, events, MG_EPOLL_MAX_EVENTS, timeout_ms);
2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785
  now = time(NULL);
  DBG(("epoll_wait @ %ld num_ev=%d", (long) now, num_ev));

  while (num_ev-- > 0) {
    intptr_t epf;
    struct epoll_event *ev = events + num_ev;
    nc = (struct mg_connection *) ev->data.ptr;
    if (nc == NULL) {
      mg_mgr_handle_ctl_sock(mgr);
      continue;
    }
2786 2787 2788
    fd_flags = ((ev->events & (EPOLLIN | EPOLLHUP)) ? _MG_F_FD_CAN_READ : 0) |
               ((ev->events & (EPOLLOUT)) ? _MG_F_FD_CAN_WRITE : 0) |
               ((ev->events & (EPOLLERR)) ? _MG_F_FD_ERROR : 0);
2789 2790
    mg_mgr_handle_connection(nc, fd_flags, now);
    epf = (intptr_t) nc->mgr_data;
2791
    epf ^= _MG_EPF_NO_POLL;
2792 2793 2794 2795 2796
    nc->mgr_data = (void *) epf;
  }

  for (nc = mgr->active_connections; nc != NULL; nc = next) {
    next = nc->next;
2797
    if (!(((intptr_t) nc->mgr_data) & _MG_EPF_NO_POLL)) {
2798 2799 2800
      mg_mgr_handle_connection(nc, 0, now);
    } else {
      intptr_t epf = (intptr_t) nc->mgr_data;
2801
      epf ^= _MG_EPF_NO_POLL;
2802 2803
      nc->mgr_data = (void *) epf;
    }
2804 2805
    if ((nc->flags & MG_F_CLOSE_IMMEDIATELY) ||
        (nc->send_mbuf.len == 0 && (nc->flags & MG_F_SEND_AND_CLOSE))) {
2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858
      mg_close_conn(nc);
    } else {
      mg_ev_mgr_epoll_ctl(nc, EPOLL_CTL_MOD);
    }
  }

  return now;
}

#else /* select() */

static void mg_ev_mgr_init(struct mg_mgr *mgr) {
  (void) mgr;
  DBG(("%p using select()", mgr));
}

static void mg_ev_mgr_free(struct mg_mgr *mgr) {
  (void) mgr;
}

static void mg_ev_mgr_add_conn(struct mg_connection *nc) {
  (void) nc;
}

static void mg_ev_mgr_remove_conn(struct mg_connection *nc) {
  (void) nc;
}

static void mg_add_to_set(sock_t sock, fd_set *set, sock_t *max_fd) {
  if (sock != INVALID_SOCKET) {
    FD_SET(sock, set);
    if (*max_fd == INVALID_SOCKET || sock > *max_fd) {
      *max_fd = sock;
    }
  }
}

time_t mg_mgr_poll(struct mg_mgr *mgr, int milli) {
  time_t now;
  struct mg_connection *nc, *tmp;
  struct timeval tv;
  fd_set read_set, write_set, err_set;
  sock_t max_fd = INVALID_SOCKET;
  int num_selected;

  FD_ZERO(&read_set);
  FD_ZERO(&write_set);
  FD_ZERO(&err_set);
  mg_add_to_set(mgr->ctl[1], &read_set, &max_fd);

  for (nc = mgr->active_connections; nc != NULL; nc = tmp) {
    tmp = nc->next;

2859
    if (!(nc->flags & MG_F_WANT_WRITE) &&
2860 2861 2862 2863
        nc->recv_mbuf.len < nc->recv_mbuf_limit) {
      mg_add_to_set(nc->sock, &read_set, &max_fd);
    }

2864 2865 2866
    if (((nc->flags & MG_F_CONNECTING) && !(nc->flags & MG_F_WANT_READ)) ||
        (nc->send_mbuf.len > 0 && !(nc->flags & MG_F_CONNECTING) &&
         !(nc->flags & MG_F_DONT_SEND))) {
2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878
      mg_add_to_set(nc->sock, &write_set, &max_fd);
      mg_add_to_set(nc->sock, &err_set, &max_fd);
    }
  }

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

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

2879
#ifndef MG_DISABLE_SOCKETPAIR
2880 2881 2882 2883
  if (num_selected > 0 && mgr->ctl[1] != INVALID_SOCKET &&
      FD_ISSET(mgr->ctl[1], &read_set)) {
    mg_mgr_handle_ctl_sock(mgr);
  }
2884
#endif
2885 2886 2887 2888

  for (nc = mgr->active_connections; nc != NULL; nc = tmp) {
    int fd_flags = 0;
    if (num_selected > 0) {
2889 2890 2891
      fd_flags = (FD_ISSET(nc->sock, &read_set) ? _MG_F_FD_CAN_READ : 0) |
                 (FD_ISSET(nc->sock, &write_set) ? _MG_F_FD_CAN_WRITE : 0) |
                 (FD_ISSET(nc->sock, &err_set) ? _MG_F_FD_ERROR : 0);
2892
    }
2893
#ifdef MG_CC3200
2894
    // CC3200 does not report UDP sockets as writeable.
2895 2896 2897
    if (nc->flags & MG_F_UDP &&
        (nc->send_mbuf.len > 0 || nc->flags & MG_F_CONNECTING)) {
      fd_flags |= _MG_F_FD_CAN_WRITE;
2898
    }
2899 2900 2901 2902
#endif
#ifdef RTOS_SDK
    /* In ESP8266 RTOS_SDK we don't get write events */
    fd_flags |= _MG_F_FD_CAN_WRITE;
2903 2904 2905 2906 2907 2908 2909
#endif
    tmp = nc->next;
    mg_mgr_handle_connection(nc, fd_flags, now);
  }

  for (nc = mgr->active_connections; nc != NULL; nc = tmp) {
    tmp = nc->next;
2910 2911
    if ((nc->flags & MG_F_CLOSE_IMMEDIATELY) ||
        (nc->send_mbuf.len == 0 && (nc->flags & MG_F_SEND_AND_CLOSE))) {
2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923
      mg_close_conn(nc);
    }
  }

  return now;
}

#endif

/*
 * Schedules an async connect for a resolved address and proto.
 * Called from two places: `mg_connect_opt()` and from async resolver.
2924
 * When called from the async resolver, it must trigger `MG_EV_CONNECT` event
2925 2926
 * with a failure flag to indicate connection failure.
 */
2927
MG_INTERNAL struct mg_connection *mg_finish_connect(struct mg_connection *nc,
2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938
                                                    int proto,
                                                    union socket_address *sa,
                                                    struct mg_add_sock_opts o) {
  sock_t sock = INVALID_SOCKET;
  int rc;

  DBG(("%p %s://%s:%hu", nc, proto == SOCK_DGRAM ? "udp" : "tcp",
       inet_ntoa(nc->sa.sin.sin_addr), ntohs(nc->sa.sin.sin_port)));

  if ((sock = socket(AF_INET, proto, 0)) == INVALID_SOCKET) {
    int failure = errno;
2939 2940 2941
    MG_SET_PTRPTR(o.error_string, "cannot create socket");
    if (nc->flags & MG_F_CONNECTING) {
      mg_call(nc, MG_EV_CONNECT, &failure);
2942 2943 2944 2945 2946
    }
    mg_destroy_conn(nc);
    return NULL;
  }

2947
#if !defined(MG_CC3200) && !defined(MG_ESP8266)
2948 2949 2950 2951 2952
  mg_set_non_blocking_mode(sock);
#endif
  rc = (proto == SOCK_DGRAM) ? 0 : connect(sock, &sa->sa, sizeof(sa->sin));

  if (rc != 0 && mg_is_error(rc)) {
2953 2954 2955
    MG_SET_PTRPTR(o.error_string, "cannot connect to socket");
    if (nc->flags & MG_F_CONNECTING) {
      mg_call(nc, MG_EV_CONNECT, &rc);
2956 2957 2958 2959 2960
    }
    mg_destroy_conn(nc);
    close(sock);
    return NULL;
  }
Sergey Lyubka's avatar
Sergey Lyubka committed
2961

2962 2963
  /* Fire MG_EV_CONNECT on next poll. */
  nc->flags |= MG_F_CONNECTING;
2964 2965 2966 2967

  /* No mg_destroy_conn() call after this! */
  mg_set_sock(nc, sock);

2968
#ifdef MG_ENABLE_SSL
2969 2970 2971 2972 2973
  /*
   * If we are using async resolver, socket isn't open
   * before this place, so
   * for SSL connections we have to add socket to SSL fd set
   */
2974
  if (nc->ssl != NULL && !(nc->flags & MG_F_LISTENING)) {
2975 2976 2977 2978 2979 2980 2981
    SSL_set_fd(nc->ssl, nc->sock);
  }
#endif

  return nc;
}

2982
#ifndef MG_DISABLE_RESOLVER
2983 2984
/*
 * Callback for the async resolver on mg_connect_opt() call.
2985
 * Main task of this function is to trigger MG_EV_CONNECT event with
2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998
 *    either failure (and dealloc the connection)
 *    or success (and proceed with connect()
 */
static void resolve_cb(struct mg_dmg_message *msg, void *data) {
  struct mg_connection *nc = (struct mg_connection *) data;
  int i;
  int failure = -1;

  if (msg != NULL) {
    /*
     * Take the first DNS A answer and run...
     */
    for (i = 0; i < msg->num_answers; i++) {
2999
      if (msg->answers[i].rtype == MG_DNS_A_RECORD) {
3000 3001 3002 3003 3004 3005 3006
        static struct mg_add_sock_opts opts;
        /*
         * Async resolver guarantees that there is at least one answer.
         * TODO(lsm): handle IPv6 answers too
         */
        mg_dmg_parse_record_data(msg, &msg->answers[i], &nc->sa.sin.sin_addr,
                                 4);
3007 3008 3009
        /* Make mg_finish_connect() trigger MG_EV_CONNECT on failure */
        nc->flags |= MG_F_CONNECTING;
        mg_finish_connect(nc, nc->flags & MG_F_UDP ? SOCK_DGRAM : SOCK_STREAM,
3010 3011 3012 3013 3014 3015 3016
                          &nc->sa, opts);
        return;
      }
    }
  }

  /*
3017
   * If we get there was no MG_DNS_A_RECORD in the answer
3018
   */
3019
  mg_call(nc, MG_EV_CONNECT, &failure);
3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035
  mg_destroy_conn(nc);
}
#endif

struct mg_connection *mg_connect(struct mg_mgr *mgr, const char *address,
                                 mg_event_handler_t callback) {
  static struct mg_connect_opts opts;
  return mg_connect_opt(mgr, address, callback, opts);
}

struct mg_connection *mg_connect_opt(struct mg_mgr *mgr, const char *address,
                                     mg_event_handler_t callback,
                                     struct mg_connect_opts opts) {
  struct mg_connection *nc = NULL;
  int proto, rc;
  struct mg_add_sock_opts add_sock_opts;
3036
  char host[MG_MAX_HOST_LEN];
3037

3038
  MG_COPY_COMMON_CONNECTION_OPTIONS(&add_sock_opts, &opts);
3039 3040 3041 3042 3043 3044

  if ((nc = mg_create_connection(mgr, callback, add_sock_opts)) == NULL) {
    return NULL;
  } else if ((rc = mg_parse_address(address, &nc->sa, &proto, host,
                                    sizeof(host))) < 0) {
    /* Address is malformed */
3045
    MG_SET_PTRPTR(opts.error_string, "cannot parse address");
3046 3047 3048
    mg_destroy_conn(nc);
    return NULL;
  }
3049 3050
  nc->flags |= opts.flags & _MG_ALLOWED_CONNECT_FLAGS_MASK;
  nc->flags |= (proto == SOCK_DGRAM) ? MG_F_UDP : 0;
3051 3052 3053
  nc->user_data = opts.user_data;

  if (rc == 0) {
3054
#ifndef MG_DISABLE_RESOLVER
3055 3056 3057 3058
    /*
     * DNS resolution is required for host.
     * mg_parse_address() fills port in nc->sa, which we pass to resolve_cb()
     */
3059 3060
    if (mg_resolve_async(nc->mgr, host, MG_DNS_A_RECORD, resolve_cb, nc) != 0) {
      MG_SET_PTRPTR(opts.error_string, "cannot schedule DNS lookup");
3061 3062 3063 3064 3065 3066
      mg_destroy_conn(nc);
      return NULL;
    }

    return nc;
#else
3067
    MG_SET_PTRPTR(opts.error_string, "Resolver is disabled");
3068 3069 3070
    mg_destroy_conn(nc);
    return NULL;
#endif
Sergey Lyubka's avatar
Sergey Lyubka committed
3071
  } else {
3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090
    /* Address is parsed and resolved to IP. proceed with connect() */
    return mg_finish_connect(nc, proto, &nc->sa, add_sock_opts);
  }
}

struct mg_connection *mg_bind(struct mg_mgr *srv, const char *address,
                              mg_event_handler_t event_handler) {
  static struct mg_bind_opts opts;
  return mg_bind_opt(srv, address, event_handler, opts);
}

struct mg_connection *mg_bind_opt(struct mg_mgr *mgr, const char *address,
                                  mg_event_handler_t callback,
                                  struct mg_bind_opts opts) {
  union socket_address sa;
  struct mg_connection *nc = NULL;
  int proto;
  sock_t sock;
  struct mg_add_sock_opts add_sock_opts;
3091
  char host[MG_MAX_HOST_LEN];
3092

3093
  MG_COPY_COMMON_CONNECTION_OPTIONS(&add_sock_opts, &opts);
3094 3095

  if (mg_parse_address(address, &sa, &proto, host, sizeof(host)) <= 0) {
3096
    MG_SET_PTRPTR(opts.error_string, "cannot parse address");
3097 3098
  } else if ((sock = mg_open_listening_socket(&sa, proto)) == INVALID_SOCKET) {
    DBG(("Failed to open listener: %d", errno));
3099
    MG_SET_PTRPTR(opts.error_string, "failed to open listener");
3100 3101 3102 3103 3104 3105 3106 3107 3108 3109
  } else if ((nc = mg_add_sock_opt(mgr, sock, callback, add_sock_opts)) ==
             NULL) {
    /* opts.error_string set by mg_add_sock_opt */
    DBG(("Failed to mg_add_sock"));
    closesocket(sock);
  } else {
    nc->sa = sa;
    nc->handler = callback;

    if (proto == SOCK_DGRAM) {
3110
      nc->flags |= MG_F_UDP;
3111
    } else {
3112
      nc->flags |= MG_F_LISTENING;
3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155
    }

    DBG(("%p sock %d/%d", nc, sock, proto));
  }

  return nc;
}

struct mg_connection *mg_add_sock(struct mg_mgr *s, sock_t sock,
                                  mg_event_handler_t callback) {
  static struct mg_add_sock_opts opts;
  return mg_add_sock_opt(s, sock, callback, opts);
}

struct mg_connection *mg_add_sock_opt(struct mg_mgr *s, sock_t sock,
                                      mg_event_handler_t callback,
                                      struct mg_add_sock_opts opts) {
  struct mg_connection *nc = mg_create_connection(s, callback, opts);
  if (nc != NULL) {
    mg_set_sock(nc, sock);
  }
  return nc;
}

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

void mg_broadcast(struct mg_mgr *mgr, mg_event_handler_t cb, void *data,
                  size_t len) {
  struct ctl_msg ctl_msg;

  /*
   * Mongoose manager has a socketpair, `struct mg_mgr::ctl`,
   * where `mg_broadcast()` pushes the message.
   * `mg_mgr_poll()` wakes up, reads a message from the socket pair, and calls
   * specified callback for each connection. Thus the callback function executes
   * in event manager thread.
   */
  if (mgr->ctl[0] != INVALID_SOCKET && data != NULL &&
      len < sizeof(ctl_msg.message)) {
    ctl_msg.callback = cb;
    memcpy(ctl_msg.message, data, len);
3156 3157 3158
    MG_EV_SEND_FUNC(mgr->ctl[0], (char *) &ctl_msg,
                    offsetof(struct ctl_msg, message) + len, 0);
    MG_EV_RECV_FUNC(mgr->ctl[0], (char *) &len, 1, 0);
3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220
  }
}

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

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

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

  return len;
}

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

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

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

    if (net == (remote_ip & mask)) {
      allowed = flag;
    }
  }

  return allowed == '+';
}

/* Move data from one connection to another */
void mg_forward(struct mg_connection *from, struct mg_connection *to) {
  mg_send(to, from->recv_mbuf.buf, from->recv_mbuf.len);
  mbuf_remove(&from->recv_mbuf, from->recv_mbuf.len);
}
#ifdef NS_MODULE_LINES
#line 1 "src/multithreading.c"
/**/
#endif
/*
 * Copyright (c) 2014 Cesanta Software Limited
 * All rights reserved
 */

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

3221
#ifdef MG_ENABLE_THREADS
3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251

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

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

  mg_mgr_init(&m, NULL);
  mg_add_conn(&m, c);
  while (m.active_connections != NULL) {
    mg_mgr_poll(&m, 1000);
  }
  mg_mgr_free(&m);

  return param;
}

static void link_conns(struct mg_connection *c1, struct mg_connection *c2) {
  c1->priv_2 = c2;
  c2->priv_2 = c1;
}

static void unlink_conns(struct mg_connection *c) {
  struct mg_connection *peer = (struct mg_connection *) c->priv_2;
  if (peer != NULL) {
3252
    peer->flags |= MG_F_SEND_AND_CLOSE;
3253 3254 3255 3256 3257 3258 3259
    peer->priv_2 = NULL;
  }
  c->priv_2 = NULL;
}

static void forwarder_ev_handler(struct mg_connection *c, int ev, void *p) {
  (void) p;
3260
  if (ev == MG_EV_RECV && c->priv_2) {
3261
    mg_forward(c, (struct mg_connection *) c->priv_2);
3262
  } else if (ev == MG_EV_CLOSE) {
3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304
    unlink_conns(c);
  }
}

static void spawn_handling_thread(struct mg_connection *nc) {
  struct mg_mgr dummy;
  sock_t sp[2];
  struct mg_connection *c[2];

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

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

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

  /*
   * Dress c[1] as nc.
   * TODO(lsm): code in accept_conn() looks similar. Refactor.
   */
  c[1]->listener = nc->listener;
  c[1]->proto_handler = nc->proto_handler;
  c[1]->proto_data = nc->proto_data;
  c[1]->user_data = nc->user_data;

  mg_start_thread(per_connection_thread_function, c[1]);
}

static void multithreaded_ev_handler(struct mg_connection *c, int ev, void *p) {
  (void) p;
3305
  if (ev == MG_EV_ACCEPT) {
3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325
    spawn_handling_thread(c);
    c->handler = forwarder_ev_handler;
  }
}

void mg_enable_multithreading(struct mg_connection *nc) {
  /* Wrap user event handler into our multithreaded_ev_handler */
  nc->priv_1 = (void *) nc->handler;
  nc->handler = multithreaded_ev_handler;
}
#endif
#ifdef NS_MODULE_LINES
#line 1 "src/http.c"
/**/
#endif
/*
 * Copyright (c) 2014 Cesanta Software Limited
 * All rights reserved
 */

3326
#ifndef MG_DISABLE_HTTP
3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352

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

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

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

/*
 * This structure helps to create an environment for the spawned CGI program.
 * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
 * last element must be NULL.
 * However, on Windows there is a requirement that all these VARIABLE=VALUE\0
 * strings must reside in a contiguous buffer. The end of the buffer is
 * marked by two '\0' characters.
 * We satisfy both worlds: we create an envp array (which is vars), all
 * entries are actually pointers inside buf.
 */
struct cgi_env_block {
  struct mg_connection *nc;
3353 3354
  char buf[MG_CGI_ENVIRONMENT_SIZE];       /* Environment buffer */
  const char *vars[MG_MAX_CGI_ENVIR_VARS]; /* char *envp[] */
3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415
  int len;                                 /* Space taken */
  int nvars;                               /* Number of variables in envp[] */
};

#define MIME_ENTRY(_ext, _type) \
  { _ext, sizeof(_ext) - 1, _type }
static const struct {
  const char *extension;
  size_t ext_len;
  const char *mime_type;
} static_builtin_mime_types[] = {
    MIME_ENTRY("html", "text/html"),
    MIME_ENTRY("html", "text/html"),
    MIME_ENTRY("htm", "text/html"),
    MIME_ENTRY("shtm", "text/html"),
    MIME_ENTRY("shtml", "text/html"),
    MIME_ENTRY("css", "text/css"),
    MIME_ENTRY("js", "application/x-javascript"),
    MIME_ENTRY("ico", "image/x-icon"),
    MIME_ENTRY("gif", "image/gif"),
    MIME_ENTRY("jpg", "image/jpeg"),
    MIME_ENTRY("jpeg", "image/jpeg"),
    MIME_ENTRY("png", "image/png"),
    MIME_ENTRY("svg", "image/svg+xml"),
    MIME_ENTRY("txt", "text/plain"),
    MIME_ENTRY("torrent", "application/x-bittorrent"),
    MIME_ENTRY("wav", "audio/x-wav"),
    MIME_ENTRY("mp3", "audio/x-mp3"),
    MIME_ENTRY("mid", "audio/mid"),
    MIME_ENTRY("m3u", "audio/x-mpegurl"),
    MIME_ENTRY("ogg", "application/ogg"),
    MIME_ENTRY("ram", "audio/x-pn-realaudio"),
    MIME_ENTRY("xml", "text/xml"),
    MIME_ENTRY("ttf", "application/x-font-ttf"),
    MIME_ENTRY("json", "application/json"),
    MIME_ENTRY("xslt", "application/xml"),
    MIME_ENTRY("xsl", "application/xml"),
    MIME_ENTRY("ra", "audio/x-pn-realaudio"),
    MIME_ENTRY("doc", "application/msword"),
    MIME_ENTRY("exe", "application/octet-stream"),
    MIME_ENTRY("zip", "application/x-zip-compressed"),
    MIME_ENTRY("xls", "application/excel"),
    MIME_ENTRY("tgz", "application/x-tar-gz"),
    MIME_ENTRY("tar", "application/x-tar"),
    MIME_ENTRY("gz", "application/x-gunzip"),
    MIME_ENTRY("arj", "application/x-arj-compressed"),
    MIME_ENTRY("rar", "application/x-rar-compressed"),
    MIME_ENTRY("rtf", "application/rtf"),
    MIME_ENTRY("pdf", "application/pdf"),
    MIME_ENTRY("swf", "application/x-shockwave-flash"),
    MIME_ENTRY("mpg", "video/mpeg"),
    MIME_ENTRY("webm", "video/webm"),
    MIME_ENTRY("mpeg", "video/mpeg"),
    MIME_ENTRY("mov", "video/quicktime"),
    MIME_ENTRY("mp4", "video/mp4"),
    MIME_ENTRY("m4v", "video/x-m4v"),
    MIME_ENTRY("asf", "video/x-ms-asf"),
    MIME_ENTRY("avi", "video/x-msvideo"),
    MIME_ENTRY("bmp", "image/bmp"),
    {NULL, 0, NULL}};

3416
#ifndef MG_DISABLE_FILESYSTEM
3417

3418
#ifndef MG_DISABLE_DAV
3419 3420 3421 3422 3423 3424 3425 3426
static int mg_mkdir(const char *path, uint32_t mode) {
#ifndef _WIN32
  return mkdir(path, mode);
#else
  (void) mode;
  return _mkdir(path);
#endif
}
3427
#endif
3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588

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

  path_len = strlen(path);

  overrides = opts->custom_mime_types;
  while ((overrides = mg_next_comma_list_entry(overrides, &k, &v)) != NULL) {
    ext = path + (path_len - k.len);
    if (path_len > k.len && mg_vcasecmp(&k, ext) == 0) {
      return v;
    }
  }

  for (i = 0; static_builtin_mime_types[i].extension != NULL; i++) {
    ext = path + (path_len - static_builtin_mime_types[i].ext_len);
    if (path_len > static_builtin_mime_types[i].ext_len && ext[-1] == '.' &&
        mg_casecmp(ext, static_builtin_mime_types[i].extension) == 0) {
      r.p = static_builtin_mime_types[i].mime_type;
      r.len = strlen(r.p);
      return r;
    }
  }

  r.p = dflt;
  r.len = strlen(r.p);
  return r;
}
#endif

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

  for (i = 0; i < buf_len; i++) {
    if (!isprint(buf[i]) && buf[i] != '\r' && buf[i] != '\n' && buf[i] < 128) {
      return -1;
    } else if (buf[i] == '\n' && i + 1 < buf_len && buf[i + 1] == '\n') {
      return i + 2;
    } else if (buf[i] == '\n' && i + 2 < buf_len && buf[i + 1] == '\r' &&
               buf[i + 2] == '\n') {
      return i + 3;
    }
  }

  return 0;
}

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

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

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

    if (k->len == 0 || v->len == 0) {
      k->p = v->p = NULL;
      k->len = v->len = 0;
      break;
    }

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

  return s;
}

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

  if (len <= 0) return len;

  memset(hm, 0, sizeof(*hm));
  hm->message.p = s;
  hm->body.p = s + len;
  hm->message.len = hm->body.len = (size_t) ~0;
  end = s + len;

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

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

    /* If URI contains '?' character, initialize query_string */
    if ((qs = (char *) memchr(hm->uri.p, '?', hm->uri.len)) != NULL) {
      hm->query_string.p = qs + 1;
      hm->query_string.len = &hm->uri.p[hm->uri.len] - (qs + 1);
      hm->uri.len = qs - hm->uri.p;
    }
  } else {
    s = mg_skip(s, end, " ", &hm->proto);
    if (end - s < 4 || s[3] != ' ') return -1;
    hm->resp_code = atoi(s);
    if (hm->resp_code < 100 || hm->resp_code >= 600) return -1;
    s += 4;
    s = mg_skip(s, end, "\r\n", &hm->resp_status_msg);
  }

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

  /*
   * mg_parse_http() is used to parse both HTTP requests and HTTP
   * responses. If HTTP response does not have Content-Length set, then
   * body is read until socket is closed, i.e. body.len is infinite (~0).
   *
   * For HTTP requests though, according to
   * http://tools.ietf.org/html/rfc7231#section-8.1.3,
   * only POST and PUT methods have defined body semantics.
   * Therefore, if Content-Length is not specified and methods are
   * not one of PUT or POST, set body length to 0.
   *
   * So,
   * if it is HTTP request, and Content-Length is not set,
   * and method is not (PUT or POST) then reset body length to zero.
   */
  if (hm->body.len == (size_t) ~0 && is_req &&
      mg_vcasecmp(&hm->method, "PUT") != 0 &&
      mg_vcasecmp(&hm->method, "POST") != 0) {
    hm->body.len = 0;
    hm->message.len = len;
  }

  return len;
}

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

  for (i = 0; i < ARRAY_SIZE(hm->header_names); i++) {
    struct mg_str *h = &hm->header_names[i], *v = &hm->header_values[i];
    if (h->p != NULL && h->len == len && !mg_ncasecmp(h->p, name, len))
      return v;
  }

  return NULL;
}

3589
#ifndef MG_DISABLE_HTTP_WEBSOCKET
3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601

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

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

static void handle_incoming_websocket_frame(struct mg_connection *nc,
                                            struct websocket_message *wsm) {
  if (wsm->flags & 0x8) {
3602
    nc->handler(nc, MG_EV_WEBSOCKET_CONTROL_FRAME, wsm);
3603
  } else {
3604
    nc->handler(nc, MG_EV_WEBSOCKET_FRAME, wsm);
3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615
  }
}

static int deliver_websocket_data(struct mg_connection *nc) {
  /* Using unsigned char *, cause of integer arithmetic below */
  uint64_t i, data_len = 0, frame_len = 0, buf_len = nc->recv_mbuf.len, len,
              mask_len = 0, header_len = 0;
  unsigned char *p = (unsigned char *) nc->recv_mbuf.buf, *buf = p,
                *e = p + buf_len;
  unsigned *sizep = (unsigned *) &p[1]; /* Size ptr for defragmented frames */
  int ok, reass = buf_len > 0 && is_ws_fragment(p[0]) &&
3616
                  !(nc->flags & MG_F_WEBSOCKET_NO_DEFRAG);
3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638

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

  if (buf_len >= 2) {
    len = buf[1] & 127;
    mask_len = buf[1] & 128 ? 4 : 0;
    if (len < 126 && buf_len >= mask_len) {
      data_len = len;
      header_len = 2 + mask_len;
    } else if (len == 126 && buf_len >= 4 + mask_len) {
      header_len = 4 + mask_len;
      data_len = ntohs(*(uint16_t *) &buf[2]);
    } else if (buf_len >= 10 + mask_len) {
      header_len = 10 + mask_len;
      data_len = (((uint64_t) ntohl(*(uint32_t *) &buf[2])) << 32) +
                 ntohl(*(uint32_t *) &buf[6]);
    }
Sergey Lyubka's avatar
Sergey Lyubka committed
3639 3640
  }

3641 3642
  frame_len = header_len + data_len;
  ok = frame_len > 0 && frame_len <= buf_len;
3643

3644 3645
  if (ok) {
    struct websocket_message wsm;
Sergey Lyubka's avatar
Sergey Lyubka committed
3646

3647 3648 3649
    wsm.size = (size_t) data_len;
    wsm.data = buf + header_len;
    wsm.flags = buf[0];
3650

3651 3652 3653 3654 3655 3656
    /* Apply mask if necessary */
    if (mask_len > 0) {
      for (i = 0; i < data_len; i++) {
        buf[i + header_len] ^= (buf + header_len - mask_len)[i % 4];
      }
    }
3657

3658 3659 3660 3661 3662 3663 3664 3665
    if (reass) {
      /* On first fragmented frame, nullify size */
      if (is_ws_first_fragment(wsm.flags)) {
        mbuf_resize(&nc->recv_mbuf, nc->recv_mbuf.size + sizeof(*sizep));
        p[0] &= ~0x0f; /* Next frames will be treated as continuation */
        buf = p + 1 + sizeof(*sizep);
        *sizep = 0; /* TODO(lsm): fix. this can stomp over frame data */
      }
3666

3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686
      /* Append this frame to the reassembled buffer */
      memmove(buf, wsm.data, e - wsm.data);
      (*sizep) += wsm.size;
      nc->recv_mbuf.len -= wsm.data - buf;

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

    /* If client closes, close too */
    if ((buf[0] & 0x0f) == WEBSOCKET_OP_CLOSE) {
3687
      nc->flags |= MG_F_SEND_AND_CLOSE;
3688
    }
3689 3690
  }

3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713
  return ok;
}

struct ws_mask_ctx {
  size_t pos; /* zero means unmasked */
  uint32_t mask;
};

static uint32_t ws_random_mask() {
/*
 * The spec requires WS client to generate hard to
 * guess mask keys. From RFC6455, Section 5.3:
 *
 * The unpredictability of the masking key is essential to prevent
 * authors of malicious applications from selecting the bytes that appear on
 * the wire.
 *
 * Hence this feature is essential when the actual end user of this API
 * is untrusted code that wouldn't have access to a lower level net API
 * anyway (e.g. web browsers). Hence this feature is low prio for most
 * mongoose use cases and thus can be disabled, e.g. when porting to a platform
 * that lacks random().
 */
3714
#if MG_DISABLE_WS_RANDOM_MASK
3715
  return 0xefbeadde; /* generated with a random number generator, I swear */
3716
#else
3717 3718 3719 3720
  if (sizeof(long) >= 4) {
    return (uint32_t) random();
  } else if (sizeof(long) == 2) {
    return (uint32_t) random() << 16 | (uint32_t) random();
3721
  }
3722
#endif
3723 3724
}

3725 3726 3727 3728 3729
static void mg_send_ws_header(struct mg_connection *nc, int op, size_t len,
                              struct ws_mask_ctx *ctx) {
  int header_len;
  unsigned char header[10];

3730
  header[0] = (op & WEBSOCKET_DONT_FIN ? 0x0 : 0x80) + (op & 0x0f);
3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759
  if (len < 126) {
    header[1] = len;
    header_len = 2;
  } else if (len < 65535) {
    uint16_t tmp = htons((uint16_t) len);
    header[1] = 126;
    memcpy(&header[2], &tmp, sizeof(tmp));
    header_len = 4;
  } else {
    uint32_t tmp;
    header[1] = 127;
    tmp = htonl((uint32_t)((uint64_t) len >> 32));
    memcpy(&header[2], &tmp, sizeof(tmp));
    tmp = htonl((uint32_t)(len & 0xffffffff));
    memcpy(&header[6], &tmp, sizeof(tmp));
    header_len = 10;
  }

  /* client connections enable masking */
  if (nc->listener == NULL) {
    header[1] |= 1 << 7; /* set masking flag */
    mg_send(nc, header, header_len);
    ctx->mask = ws_random_mask();
    mg_send(nc, &ctx->mask, sizeof(ctx->mask));
    ctx->pos = nc->send_mbuf.len;
  } else {
    mg_send(nc, header, header_len);
    ctx->pos = 0;
  }
3760 3761
}

3762 3763 3764 3765 3766 3767 3768
static void ws_mask_frame(struct mbuf *mbuf, struct ws_mask_ctx *ctx) {
  size_t i;
  if (ctx->pos == 0) return;
  for (i = 0; i < (mbuf->len - ctx->pos); i++) {
    mbuf->buf[ctx->pos + i] ^= ((char *) &ctx->mask)[i % 4];
  }
}
Sergey Lyubka's avatar
Sergey Lyubka committed
3769

3770 3771 3772 3773 3774
void mg_send_websocket_frame(struct mg_connection *nc, int op, const void *data,
                             size_t len) {
  struct ws_mask_ctx ctx;
  mg_send_ws_header(nc, op, len, &ctx);
  mg_send(nc, data, len);
Sergey Lyubka's avatar
Sergey Lyubka committed
3775

3776
  ws_mask_frame(&nc->send_mbuf, &ctx);
3777

3778
  if (op == WEBSOCKET_OP_CLOSE) {
3779
    nc->flags |= MG_F_SEND_AND_CLOSE;
3780
  }
3781
}
3782

3783 3784 3785 3786 3787 3788 3789
void mg_send_websocket_framev(struct mg_connection *nc, int op,
                              const struct mg_str *strv, int strvcnt) {
  struct ws_mask_ctx ctx;
  int i;
  int len = 0;
  for (i = 0; i < strvcnt; i++) {
    len += strv[i].len;
Sergey Lyubka's avatar
Sergey Lyubka committed
3790 3791
  }

3792
  mg_send_ws_header(nc, op, len, &ctx);
3793

3794 3795 3796
  for (i = 0; i < strvcnt; i++) {
    mg_send(nc, strv[i].p, strv[i].len);
  }
Sergey Lyubka's avatar
Sergey Lyubka committed
3797

3798
  ws_mask_frame(&nc->send_mbuf, &ctx);
Sergey Lyubka's avatar
Sergey Lyubka committed
3799

3800
  if (op == WEBSOCKET_OP_CLOSE) {
3801
    nc->flags |= MG_F_SEND_AND_CLOSE;
Sergey Lyubka's avatar
Sergey Lyubka committed
3802 3803 3804
  }
}

3805 3806 3807 3808 3809
void mg_printf_websocket_frame(struct mg_connection *nc, int op,
                               const char *fmt, ...) {
  char mem[4192], *buf = mem;
  va_list ap;
  int len;
3810

3811 3812 3813
  va_start(ap, fmt);
  if ((len = mg_avprintf(&buf, sizeof(mem), fmt, ap)) > 0) {
    mg_send_websocket_frame(nc, op, buf, len);
3814
  }
3815
  va_end(ap);
Sergey Lyubka's avatar
Sergey Lyubka committed
3816

3817
  if (buf != mem && buf != NULL) {
3818
    MG_FREE(buf);
Sergey Lyubka's avatar
Sergey Lyubka committed
3819 3820
  }
}
3821

3822 3823
static void websocket_handler(struct mg_connection *nc, int ev, void *ev_data) {
  nc->handler(nc, ev, ev_data);
3824

3825
  switch (ev) {
3826
    case MG_EV_RECV:
3827 3828 3829
      do {
      } while (deliver_websocket_data(nc));
      break;
3830
    case MG_EV_POLL:
3831 3832 3833
      /* Ping idle websocket connections */
      {
        time_t now = *(time_t *) ev_data;
3834 3835
        if (nc->flags & MG_F_IS_WEBSOCKET &&
            now > nc->last_io_time + MG_WEBSOCKET_PING_INTERVAL_SECONDS) {
3836 3837 3838 3839 3840 3841 3842 3843
          mg_send_websocket_frame(nc, WEBSOCKET_OP_PING, "", 0);
        }
      }
      break;
    default:
      break;
  }
}
3844

3845 3846 3847 3848
static void ws_handshake(struct mg_connection *nc, const struct mg_str *key) {
  static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  char buf[500], sha[20], b64_sha[sizeof(sha) * 2];
  cs_sha1_ctx sha_ctx;
3849

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

3852 3853 3854
  cs_sha1_init(&sha_ctx);
  cs_sha1_update(&sha_ctx, (unsigned char *) buf, strlen(buf));
  cs_sha1_final((unsigned char *) sha, &sha_ctx);
Sergey Lyubka's avatar
Sergey Lyubka committed
3855

3856 3857 3858 3859 3860 3861 3862
  mg_base64_encode((unsigned char *) sha, sizeof(sha), b64_sha);
  mg_printf(nc, "%s%s%s",
            "HTTP/1.1 101 Switching Protocols\r\n"
            "Upgrade: websocket\r\n"
            "Connection: Upgrade\r\n"
            "Sec-WebSocket-Accept: ",
            b64_sha, "\r\n\r\n");
3863
}
Sergey Lyubka's avatar
Sergey Lyubka committed
3864

3865
#endif /* MG_DISABLE_HTTP_WEBSOCKET */
Sergey Lyubka's avatar
Sergey Lyubka committed
3866

3867 3868 3869 3870 3871 3872 3873
static void free_http_proto_data(struct mg_connection *nc) {
  struct proto_data_http *dp = (struct proto_data_http *) nc->proto_data;
  if (dp != NULL) {
    if (dp->fp != NULL) {
      fclose(dp->fp);
    }
    if (dp->cgi_nc != NULL) {
3874
      dp->cgi_nc->flags |= MG_F_CLOSE_IMMEDIATELY;
3875
    }
3876
    MG_FREE(dp);
3877
    nc->proto_data = NULL;
Sergey Lyubka's avatar
Sergey Lyubka committed
3878 3879 3880
  }
}

3881 3882
static void transfer_file_data(struct mg_connection *nc) {
  struct proto_data_http *dp = (struct proto_data_http *) nc->proto_data;
3883
  char buf[MG_MAX_HTTP_SEND_IOBUF];
3884 3885
  int64_t left = dp->cl - dp->sent;
  size_t n = 0, to_read = 0;
Sergey Lyubka's avatar
Sergey Lyubka committed
3886

3887 3888 3889 3890 3891
  if (dp->type == DATA_FILE) {
    struct mbuf *io = &nc->send_mbuf;
    if (io->len < sizeof(buf)) {
      to_read = sizeof(buf) - io->len;
    }
Sergey Lyubka's avatar
Sergey Lyubka committed
3892

3893 3894 3895 3896 3897 3898 3899 3900 3901
    if (left > 0 && to_read > (size_t) left) {
      to_read = left;
    }

    if (to_read == 0) {
      /* Rate limiting. send_mbuf is too full, wait until it's drained. */
    } else if (dp->sent < dp->cl && (n = fread(buf, 1, to_read, dp->fp)) > 0) {
      mg_send(nc, buf, n);
      dp->sent += n;
3902
    } else {
3903
      free_http_proto_data(nc);
3904
    }
3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915
  } else if (dp->type == DATA_PUT) {
    struct mbuf *io = &nc->recv_mbuf;
    size_t to_write =
        left <= 0 ? 0 : left < (int64_t) io->len ? (size_t) left : io->len;
    size_t n = fwrite(io->buf, 1, to_write, dp->fp);
    if (n > 0) {
      mbuf_remove(io, n);
      dp->sent += n;
    }
    if (n == 0 || dp->sent >= dp->cl) {
      free_http_proto_data(nc);
3916
    }
3917 3918 3919 3920 3921
  } else if (dp->type == DATA_CGI) {
    /* This is POST data that needs to be forwarded to the CGI process */
    if (dp->cgi_nc != NULL) {
      mg_forward(nc, dp->cgi_nc);
    } else {
3922
      nc->flags |= MG_F_SEND_AND_CLOSE;
3923 3924 3925
    }
  }
}
Sergey Lyubka's avatar
Sergey Lyubka committed
3926

3927 3928 3929 3930 3931 3932 3933 3934 3935 3936
/*
 * Parse chunked-encoded buffer. Return 0 if the buffer is not encoded, or
 * if it's incomplete. If the chunk is fully buffered, return total number of
 * bytes in a chunk, and store data in `data`, `data_len`.
 */
static size_t parse_chunk(char *buf, size_t len, char **chunk_data,
                          size_t *chunk_len) {
  unsigned char *s = (unsigned char *) buf;
  size_t n = 0; /* scanned chunk length */
  size_t i = 0; /* index in s */
3937

3938 3939 3940 3941 3942
  /* Scan chunk length. That should be a hexadecimal number. */
  while (i < len && isxdigit(s[i])) {
    n *= 16;
    n += (s[i] >= '0' && s[i] <= '9') ? s[i] - '0' : tolower(s[i]) - 'a' + 10;
    i++;
3943
  }
Sergey Lyubka's avatar
Sergey Lyubka committed
3944

3945 3946 3947 3948 3949
  /* Skip new line */
  if (i == 0 || i + 2 > len || s[i] != '\r' || s[i + 1] != '\n') {
    return 0;
  }
  i += 2;
Sergey Lyubka's avatar
Sergey Lyubka committed
3950

3951 3952 3953
  /* Record where the data is */
  *chunk_data = (char *) s + i;
  *chunk_len = n;
Sergey Lyubka's avatar
Sergey Lyubka committed
3954

3955 3956 3957 3958 3959 3960 3961 3962
  /* Skip data */
  i += n;

  /* Skip new line */
  if (i == 0 || i + 2 > len || s[i] != '\r' || s[i + 1] != '\n') {
    return 0;
  }
  return i + 2;
Sergey Lyubka's avatar
Sergey Lyubka committed
3963 3964
}

3965
MG_INTERNAL size_t mg_handle_chunked(struct mg_connection *nc,
3966 3967 3968 3969 3970
                                     struct http_message *hm, char *buf,
                                     size_t blen) {
  struct proto_data_http *dp;
  char *data;
  size_t i, n, data_len, body_len, zero_chunk_received = 0;
Sergey Lyubka's avatar
Sergey Lyubka committed
3971

3972 3973
  /* If not allocated, allocate proto_data to hold reassembled offset */
  if (nc->proto_data == NULL &&
3974 3975
      (nc->proto_data = MG_CALLOC(1, sizeof(*dp))) == NULL) {
    nc->flags |= MG_F_CLOSE_IMMEDIATELY;
3976 3977
    return 0;
  }
Sergey Lyubka's avatar
Sergey Lyubka committed
3978

3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995
  /* Find out piece of received data that is not yet reassembled */
  dp = (struct proto_data_http *) nc->proto_data;
  body_len = dp->body_len;
  assert(blen >= body_len);

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

    if (data_len == 0) {
      zero_chunk_received = 1;
      i += n;
      break;
Sergey Lyubka's avatar
Sergey Lyubka committed
3996 3997 3998
    }
  }

3999 4000 4001 4002 4003 4004 4005 4006
  if (i > body_len) {
    /* Shift unparsed content to the parsed body */
    assert(i <= blen);
    memmove(buf + body_len, buf + i, blen - i);
    memset(buf + body_len + blen - i, 0, i - body_len);
    nc->recv_mbuf.len -= i - body_len;
    dp->body_len = body_len;

4007 4008 4009
    /* Send MG_EV_HTTP_CHUNK event */
    nc->flags &= ~MG_F_DELETE_CHUNK;
    nc->handler(nc, MG_EV_HTTP_CHUNK, hm);
4010

4011 4012
    /* Delete processed data if user set MG_F_DELETE_CHUNK flag */
    if (nc->flags & MG_F_DELETE_CHUNK) {
4013 4014 4015 4016
      memset(buf, 0, body_len);
      memmove(buf, buf + body_len, blen - i);
      nc->recv_mbuf.len -= body_len;
      hm->body.len = dp->body_len = 0;
Sergey Lyubka's avatar
Sergey Lyubka committed
4017
    }
4018 4019 4020

    if (zero_chunk_received) {
      hm->message.len = dp->body_len + blen - i;
4021
    }
Sergey Lyubka's avatar
Sergey Lyubka committed
4022
  }
4023

4024
  return body_len;
Sergey Lyubka's avatar
Sergey Lyubka committed
4025 4026
}

4027 4028 4029 4030 4031
static void http_handler(struct mg_connection *nc, int ev, void *ev_data) {
  struct mbuf *io = &nc->recv_mbuf;
  struct http_message hm;
  int req_len;
  const int is_req = (nc->listener != NULL);
4032
#ifndef MG_DISABLE_HTTP_WEBSOCKET
4033
  struct mg_str *vec;
Sergey Lyubka's avatar
Sergey Lyubka committed
4034
#endif
4035 4036 4037 4038 4039 4040 4041 4042 4043 4044
  if (ev == MG_EV_CLOSE) {
    /*
     * For HTTP messages without Content-Length, always send HTTP message
     * before MG_EV_CLOSE message.
     */
    if (io->len > 0 && mg_parse_http(io->buf, io->len, &hm, is_req) > 0) {
      hm.message.len = io->len;
      hm.body.len = io->buf + io->len - hm.body.p;
      nc->handler(nc, is_req ? MG_EV_HTTP_REQUEST : MG_EV_HTTP_REPLY, &hm);
    }
4045 4046
    free_http_proto_data(nc);
  }
Sergey Lyubka's avatar
Sergey Lyubka committed
4047

4048 4049 4050
  if (nc->proto_data != NULL) {
    transfer_file_data(nc);
  }
Sergey Lyubka's avatar
Sergey Lyubka committed
4051

4052 4053
  nc->handler(nc, ev, ev_data);

4054
  if (ev == MG_EV_RECV) {
4055 4056 4057 4058 4059 4060 4061 4062 4063
    struct mg_str *s;
    req_len = mg_parse_http(io->buf, io->len, &hm, is_req);

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

4064 4065
    if (req_len < 0 || (req_len == 0 && io->len >= MG_MAX_HTTP_REQUEST_SIZE)) {
      nc->flags |= MG_F_CLOSE_IMMEDIATELY;
4066 4067 4068
    } else if (req_len == 0) {
      /* Do nothing, request is not yet fully buffered */
    }
4069
#ifndef MG_DISABLE_HTTP_WEBSOCKET
4070 4071 4072 4073 4074 4075
    else if (nc->listener == NULL &&
             mg_get_http_header(&hm, "Sec-WebSocket-Accept")) {
      /* We're websocket client, got handshake response from server. */
      /* TODO(lsm): check the validity of accept Sec-WebSocket-Accept */
      mbuf_remove(io, req_len);
      nc->proto_handler = websocket_handler;
4076 4077 4078
      nc->flags |= MG_F_IS_WEBSOCKET;
      nc->handler(nc, MG_EV_WEBSOCKET_HANDSHAKE_DONE, NULL);
      websocket_handler(nc, MG_EV_RECV, ev_data);
4079 4080 4081 4082 4083
    } else if (nc->listener != NULL &&
               (vec = mg_get_http_header(&hm, "Sec-WebSocket-Key")) != NULL) {
      /* This is a websocket request. Switch protocol handlers. */
      mbuf_remove(io, req_len);
      nc->proto_handler = websocket_handler;
4084
      nc->flags |= MG_F_IS_WEBSOCKET;
4085 4086

      /* Send handshake */
4087 4088
      nc->handler(nc, MG_EV_WEBSOCKET_HANDSHAKE_REQUEST, &hm);
      if (!(nc->flags & MG_F_CLOSE_IMMEDIATELY)) {
4089 4090 4091
        if (nc->send_mbuf.len == 0) {
          ws_handshake(nc, vec);
        }
4092 4093
        nc->handler(nc, MG_EV_WEBSOCKET_HANDSHAKE_DONE, NULL);
        websocket_handler(nc, MG_EV_RECV, ev_data);
4094 4095
      }
    }
4096
#endif /* MG_DISABLE_HTTP_WEBSOCKET */
4097
    else if (hm.message.len <= io->len) {
4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150
      int trigger_ev = nc->listener ? MG_EV_HTTP_REQUEST : MG_EV_HTTP_REPLY;

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

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

      if (v7 != NULL) {
        /* Lookup JS callback */
        v1 = v7_get(v7, v7_get_global_object(v7), "Http", ~0);
        v2 = v7_get(v7, v1, ev_name, ~0);

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

        /* Populate request object */
        v7_set(v7, req, "method", ~0, 0,
               v7_create_string(v7, hm.method.p, hm.method.len, 1));
        v7_set(v7, req, "uri", ~0, 0,
               v7_create_string(v7, hm.uri.p, hm.uri.len, 1));
        v7_set(v7, req, "body", ~0, 0,
               v7_create_string(v7, hm.body.p, hm.body.len, 1));
        v7_set(v7, req, "headers", ~0, 0, headers);
        for (i = 0; hm.header_names[i].len > 0; i++) {
          const struct mg_str *name = &hm.header_names[i];
          const struct mg_str *value = &hm.header_values[i];
          v7_set(v7, headers, name->p, name->len, 0,
                 v7_create_string(v7, value->p, value->len, 1));
        }

        /* Invoke callback. TODO(lsm): report errors */
        v7_array_push(v7, args, v7_create_foreign(nc));
        v7_array_push(v7, args, req);
        if (v7_apply(v7, &res, v2, v7_create_undefined(), args) == V7_OK &&
            v7_is_true(v7, res)) {
          js_callback_handled_request++;
        }
      }

      /* If JS callback returns true, stop request processing */
      if (js_callback_handled_request) {
        nc->flags |= MG_F_SEND_AND_CLOSE;
      } else {
        nc->handler(nc, trigger_ev, &hm);
      }
#else
      nc->handler(nc, trigger_ev, &hm);
#endif
4151 4152
      mbuf_remove(io, hm.message.len);
    }
Sergey Lyubka's avatar
Sergey Lyubka committed
4153 4154 4155
  }
}

4156 4157
void mg_set_protocol_http_websocket(struct mg_connection *nc) {
  nc->proto_handler = http_handler;
4158 4159
}

4160
#ifndef MG_DISABLE_HTTP_WEBSOCKET
4161

4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175
void mg_send_websocket_handshake(struct mg_connection *nc, const char *uri,
                                 const char *extra_headers) {
  unsigned long random = (unsigned long) uri;
  char key[sizeof(random) * 3];

  mg_base64_encode((unsigned char *) &random, sizeof(random), key);
  mg_printf(nc,
            "GET %s HTTP/1.1\r\n"
            "Upgrade: websocket\r\n"
            "Connection: Upgrade\r\n"
            "Sec-WebSocket-Version: 13\r\n"
            "Sec-WebSocket-Key: %s\r\n"
            "%s\r\n",
            uri, key, extra_headers == NULL ? "" : extra_headers);
Sergey Lyubka's avatar
Sergey Lyubka committed
4176 4177
}

4178
#endif /* MG_DISABLE_HTTP_WEBSOCKET */
4179

4180
#ifndef MG_DISABLE_FILESYSTEM
4181 4182 4183 4184
static void send_http_error(struct mg_connection *nc, int code,
                            const char *reason) {
  if (reason == NULL) {
    reason = "";
Sergey Lyubka's avatar
Sergey Lyubka committed
4185
  }
4186
  mg_printf(nc, "HTTP/1.1 %d %s\r\nContent-Length: 0\r\n\r\n", code, reason);
Sergey Lyubka's avatar
Sergey Lyubka committed
4187 4188
}

4189
#ifndef MG_DISABLE_SSI
4190 4191
static void send_ssi_file(struct mg_connection *, const char *, FILE *, int,
                          const struct mg_serve_http_opts *);
Sergey Lyubka's avatar
Sergey Lyubka committed
4192

4193 4194 4195 4196 4197
static void send_file_data(struct mg_connection *nc, FILE *fp) {
  char buf[BUFSIZ];
  size_t n;
  while ((n = fread(buf, 1, sizeof(buf), fp)) > 0) {
    mg_send(nc, buf, n);
Sergey Lyubka's avatar
Sergey Lyubka committed
4198
  }
4199
}
Sergey Lyubka's avatar
Sergey Lyubka committed
4200

4201 4202 4203 4204 4205
static void do_ssi_include(struct mg_connection *nc, const char *ssi, char *tag,
                           int include_level,
                           const struct mg_serve_http_opts *opts) {
  char file_name[BUFSIZ], path[MAX_PATH_SIZE], *p;
  FILE *fp;
Sergey Lyubka's avatar
Sergey Lyubka committed
4206

4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225
  /*
   * sscanf() is safe here, since send_ssi_file() also uses buffer
   * of size MG_BUF_LEN to get the tag. So strlen(tag) is always < MG_BUF_LEN.
   */
  if (sscanf(tag, " virtual=\"%[^\"]\"", file_name) == 1) {
    /* File name is relative to the webserver root */
    snprintf(path, sizeof(path), "%s/%s", opts->document_root, file_name);
  } else if (sscanf(tag, " abspath=\"%[^\"]\"", file_name) == 1) {
    /*
     * File name is relative to the webserver working directory
     * or it is absolute system path
     */
    snprintf(path, sizeof(path), "%s", file_name);
  } else if (sscanf(tag, " file=\"%[^\"]\"", file_name) == 1 ||
             sscanf(tag, " \"%[^\"]\"", file_name) == 1) {
    /* File name is relative to the currect document */
    snprintf(path, sizeof(path), "%s", ssi);
    if ((p = strrchr(path, '/')) != NULL) {
      p[1] = '\0';
4226
    }
4227 4228 4229 4230 4231
    snprintf(path + strlen(path), sizeof(path) - strlen(path), "%s", file_name);
  } else {
    mg_printf(nc, "Bad SSI #include: [%s]", tag);
    return;
  }
4232

4233 4234 4235 4236 4237 4238 4239 4240 4241
  if ((fp = fopen(path, "rb")) == NULL) {
    mg_printf(nc, "SSI include error: fopen(%s): %s", path, strerror(errno));
  } else {
    mg_set_close_on_exec(fileno(fp));
    if (mg_match_prefix(opts->ssi_pattern, strlen(opts->ssi_pattern), path) >
        0) {
      send_ssi_file(nc, path, fp, include_level + 1, opts);
    } else {
      send_file_data(nc, fp);
Sergey Lyubka's avatar
Sergey Lyubka committed
4242
    }
4243
    fclose(fp);
Sergey Lyubka's avatar
Sergey Lyubka committed
4244
  }
4245
}
Sergey Lyubka's avatar
Sergey Lyubka committed
4246

4247
#ifndef MG_DISABLE_POPEN
4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258
static void do_ssi_exec(struct mg_connection *nc, char *tag) {
  char cmd[BUFSIZ];
  FILE *fp;

  if (sscanf(tag, " \"%[^\"]\"", cmd) != 1) {
    mg_printf(nc, "Bad SSI #exec: [%s]", tag);
  } else if ((fp = popen(cmd, "r")) == NULL) {
    mg_printf(nc, "Cannot SSI #exec: [%s]: %s", cmd, strerror(errno));
  } else {
    send_file_data(nc, fp);
    pclose(fp);
Sergey Lyubka's avatar
Sergey Lyubka committed
4259
  }
4260
}
4261
#endif /* !MG_DISABLE_POPEN */
Sergey Lyubka's avatar
Sergey Lyubka committed
4262

4263
static void do_ssi_call(struct mg_connection *nc, char *tag) {
4264
  mg_call(nc, MG_EV_SSI_CALL, tag);
Sergey Lyubka's avatar
Sergey Lyubka committed
4265 4266
}

4267 4268 4269 4270 4271 4272 4273
/*
 * SSI directive has the following format:
 * <!--#directive parameter=value parameter=value -->
 */
static void send_ssi_file(struct mg_connection *nc, const char *path, FILE *fp,
                          int include_level,
                          const struct mg_serve_http_opts *opts) {
4274 4275 4276
  static const struct mg_str btag = MG_STR("<!--#");
  static const struct mg_str d_include = MG_STR("include");
  static const struct mg_str d_call = MG_STR("call");
4277
#ifndef MG_DISABLE_POPEN
4278
  static const struct mg_str d_exec = MG_STR("exec");
4279
#endif
4280 4281
  char buf[BUFSIZ], *p = buf + btag.len; /* p points to SSI directive */
  int ch, offset, len, in_ssi_tag;
4282

4283 4284 4285
  if (include_level > 10) {
    mg_printf(nc, "SSI #include level is too deep (%s)", path);
    return;
Sergey Lyubka's avatar
Sergey Lyubka committed
4286 4287
  }

4288 4289 4290 4291 4292
  in_ssi_tag = len = offset = 0;
  while ((ch = fgetc(fp)) != EOF) {
    if (in_ssi_tag && ch == '>' && buf[len - 1] == '-' && buf[len - 2] == '-') {
      size_t i = len - 2;
      in_ssi_tag = 0;
Sergey Lyubka's avatar
Sergey Lyubka committed
4293

4294 4295 4296 4297 4298
      /* Trim closing --> */
      buf[i--] = '\0';
      while (i > 0 && buf[i] == ' ') {
        buf[i--] = '\0';
      }
Sergey Lyubka's avatar
Sergey Lyubka committed
4299

4300 4301 4302 4303 4304
      /* Handle known SSI directives */
      if (memcmp(p, d_include.p, d_include.len) == 0) {
        do_ssi_include(nc, path, p + d_include.len + 1, include_level, opts);
      } else if (memcmp(p, d_call.p, d_call.len) == 0) {
        do_ssi_call(nc, p + d_call.len + 1);
4305
#ifndef MG_DISABLE_POPEN
4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328
      } else if (memcmp(p, d_exec.p, d_exec.len) == 0) {
        do_ssi_exec(nc, p + d_exec.len + 1);
#endif
      } else {
        /* Silently ignore unknown SSI directive. */
      }
      len = 0;
    } else if (in_ssi_tag) {
      if (len == (int) btag.len && memcmp(buf, btag.p, btag.len) != 0) {
        /* Not an SSI tag */
        in_ssi_tag = 0;
      } else if (len == (int) sizeof(buf) - 2) {
        mg_printf(nc, "%s: SSI tag is too large", path);
        len = 0;
      }
      buf[len++] = ch & 0xff;
    } else if (ch == '<') {
      in_ssi_tag = 1;
      if (len > 0) {
        mg_send(nc, buf, (size_t) len);
      }
      len = 0;
      buf[len++] = ch & 0xff;
4329
    } else {
4330 4331 4332 4333 4334
      buf[len++] = ch & 0xff;
      if (len == (int) sizeof(buf)) {
        mg_send(nc, buf, (size_t) len);
        len = 0;
      }
4335
    }
Sergey Lyubka's avatar
Sergey Lyubka committed
4336 4337
  }

4338 4339 4340 4341
  /* Send the rest of buffered data */
  if (len > 0) {
    mg_send(nc, buf, (size_t) len);
  }
Sergey Lyubka's avatar
Sergey Lyubka committed
4342 4343
}

4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361
static void handle_ssi_request(struct mg_connection *nc, const char *path,
                               const struct mg_serve_http_opts *opts) {
  FILE *fp;
  struct mg_str mime_type;

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

    mime_type = get_mime_type(path, "text/plain", opts);
    mg_printf(nc,
              "HTTP/1.1 200 OK\r\n"
              "Content-Type: %.*s\r\n"
              "Connection: close\r\n\r\n",
              (int) mime_type.len, mime_type.p);
    send_ssi_file(nc, path, fp, 0, opts);
    fclose(fp);
4362
    nc->flags |= MG_F_SEND_AND_CLOSE;
Sergey Lyubka's avatar
Sergey Lyubka committed
4363 4364
  }
}
4365 4366 4367 4368 4369 4370 4371
#else
static void handle_ssi_request(struct mg_connection *nc, const char *path,
                               const struct mg_serve_http_opts *opts) {
  (void) path;
  (void) opts;
  send_http_error(nc, 500, "SSI disabled");
}
4372
#endif /* MG_DISABLE_SSI */
Sergey Lyubka's avatar
Sergey Lyubka committed
4373

4374 4375 4376 4377 4378 4379
static void construct_etag(char *buf, size_t buf_len, const cs_stat_t *st) {
  snprintf(buf, buf_len, "\"%lx.%" INT64_FMT "\"", (unsigned long) st->st_mtime,
           (int64_t) st->st_size);
}
static void gmt_time_string(char *buf, size_t buf_len, time_t *t) {
  strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", gmtime(t));
Sergey Lyubka's avatar
Sergey Lyubka committed
4380 4381
}

4382 4383 4384 4385 4386 4387 4388
static int parse_range_header(const struct mg_str *header, int64_t *a,
                              int64_t *b) {
  /*
   * There is no snscanf. Headers are not guaranteed to be NUL-terminated,
   * so we have this. Ugh.
   */
  int result;
4389
  char *p = (char *) MG_MALLOC(header->len + 1);
4390 4391 4392 4393
  if (p == NULL) return 0;
  memcpy(p, header->p, header->len);
  p[header->len] = '\0';
  result = sscanf(p, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
4394
  MG_FREE(p);
4395
  return result;
Sergey Lyubka's avatar
Sergey Lyubka committed
4396 4397
}

4398 4399 4400 4401 4402 4403 4404
static void mg_send_http_file2(struct mg_connection *nc, const char *path,
                               cs_stat_t *st, struct http_message *hm,
                               struct mg_serve_http_opts *opts) {
  struct proto_data_http *dp;
  struct mg_str mime_type;

  free_http_proto_data(nc);
4405
  if ((dp = (struct proto_data_http *) MG_CALLOC(1, sizeof(*dp))) == NULL) {
4406 4407
    send_http_error(nc, 500, "Server Error"); /* LCOV_EXCL_LINE */
  } else if ((dp->fp = fopen(path, "rb")) == NULL) {
4408
    MG_FREE(dp);
4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447
    nc->proto_data = NULL;
    send_http_error(nc, 500, "Server Error");
  } else if (mg_match_prefix(opts->ssi_pattern, strlen(opts->ssi_pattern),
                             path) > 0) {
    handle_ssi_request(nc, path, opts);
  } else {
    char etag[50], current_time[50], last_modified[50], range[50];
    time_t t = time(NULL);
    int64_t r1 = 0, r2 = 0, cl = st->st_size;
    struct mg_str *range_hdr = mg_get_http_header(hm, "Range");
    int n, status_code = 200;
    const char *status_message = "OK";

    /* Handle Range header */
    range[0] = '\0';
    if (range_hdr != NULL &&
        (n = parse_range_header(range_hdr, &r1, &r2)) > 0 && r1 >= 0 &&
        r2 >= 0) {
      /* If range is specified like "400-", set second limit to content len */
      if (n == 1) {
        r2 = cl - 1;
      }
      if (r1 > r2 || r2 >= cl) {
        status_code = 416;
        status_message = "Requested range not satisfiable";
        cl = 0;
        snprintf(range, sizeof(range),
                 "Content-Range: bytes */%" INT64_FMT "\r\n",
                 (int64_t) st->st_size);
      } else {
        status_code = 206;
        status_message = "Partial Content";
        cl = r2 - r1 + 1;
        snprintf(range, sizeof(range), "Content-Range: bytes %" INT64_FMT
                                       "-%" INT64_FMT "/%" INT64_FMT "\r\n",
                 r1, r1 + cl - 1, (int64_t) st->st_size);
        fseeko(dp->fp, r1, SEEK_SET);
      }
    }
Sergey Lyubka's avatar
Sergey Lyubka committed
4448

4449 4450 4451 4452
    construct_etag(etag, sizeof(etag), st);
    gmt_time_string(current_time, sizeof(current_time), &t);
    gmt_time_string(last_modified, sizeof(last_modified), &st->st_mtime);
    mime_type = get_mime_type(path, "text/plain", opts);
4453
    /*
4454 4455 4456 4457 4458
     * Content length casted to size_t because:
     * 1) that's the maximum buffer size anyway
     * 2) ESP8266 RTOS SDK newlib vprintf cannot contain a 64bit arg at non-last
     *    position
     * TODO(mkm): fix ESP8266 RTOS SDK
4459
     */
4460 4461 4462 4463 4464
    mg_printf(nc,
              "HTTP/1.1 %d %s\r\n"
              "Date: %s\r\n"
              "Last-Modified: %s\r\n"
              "Accept-Ranges: bytes\r\n"
4465 4466 4467 4468
              "Content-Type: %.*s\r\n"
              "Content-Length: %" SIZE_T_FMT
              "\r\n"
              "%sEtag: %s\r\n\r\n",
4469
              status_code, status_message, current_time, last_modified,
4470
              (int) mime_type.len, mime_type.p, (size_t) cl, range, etag);
4471

4472 4473 4474 4475 4476 4477
    nc->proto_data = (void *) dp;
    dp->cl = cl;
    dp->type = DATA_FILE;
    transfer_file_data(nc);
  }
}
Sergey Lyubka's avatar
Sergey Lyubka committed
4478

4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494
static void remove_double_dots(char *s) {
  char *p = s;

  while (*s != '\0') {
    *p++ = *s++;
    if (s[-1] == '/' || s[-1] == '\\') {
      while (s[0] != '\0') {
        if (s[0] == '/' || s[0] == '\\') {
          s++;
        } else if (s[0] == '.' && s[1] == '.') {
          s += 2;
        } else {
          break;
        }
      }
    }
4495
  }
4496 4497
  *p = '\0';
}
Sergey Lyubka's avatar
Sergey Lyubka committed
4498

Sergey Lyubka's avatar
Sergey Lyubka committed
4499 4500
#endif

4501 4502 4503 4504
static int mg_url_decode(const char *src, int src_len, char *dst, int dst_len,
                         int is_form_url_encoded) {
  int i, j, a, b;
#define HEXTOI(x) (isdigit(x) ? x - '0' : x - 'W')
Sergey Lyubka's avatar
Sergey Lyubka committed
4505

4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522
  for (i = j = 0; i < src_len && j < dst_len - 1; i++, j++) {
    if (src[i] == '%') {
      if (i < src_len - 2 && isxdigit(*(const unsigned char *) (src + i + 1)) &&
          isxdigit(*(const unsigned char *) (src + i + 2))) {
        a = tolower(*(const unsigned char *) (src + i + 1));
        b = tolower(*(const unsigned char *) (src + i + 2));
        dst[j] = (char) ((HEXTOI(a) << 4) | HEXTOI(b));
        i += 2;
      } else {
        return -1;
      }
    } else if (is_form_url_encoded && src[i] == '+') {
      dst[j] = ' ';
    } else {
      dst[j] = src[i];
    }
  }
Sergey Lyubka's avatar
Sergey Lyubka committed
4523

4524
  dst[j] = '\0'; /* Null-terminate the destination */
Sergey Lyubka's avatar
Sergey Lyubka committed
4525

4526
  return i >= src_len ? j : -1;
Sergey Lyubka's avatar
Sergey Lyubka committed
4527
}
4528

4529 4530 4531 4532 4533
int mg_get_http_var(const struct mg_str *buf, const char *name, char *dst,
                    size_t dst_len) {
  const char *p, *e, *s;
  size_t name_len;
  int len;
4534

4535 4536 4537 4538 4539 4540 4541 4542 4543 4544
  if (dst == NULL || dst_len == 0) {
    len = -2;
  } else if (buf->p == NULL || name == NULL || buf->len == 0) {
    len = -1;
    dst[0] = '\0';
  } else {
    name_len = strlen(name);
    e = buf->p + buf->len;
    len = -1;
    dst[0] = '\0';
4545

4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561
    for (p = buf->p; p + name_len < e; p++) {
      if ((p == buf->p || p[-1] == '&') && p[name_len] == '=' &&
          !mg_ncasecmp(name, p, name_len)) {
        p += name_len + 1;
        s = (const char *) memchr(p, '&', (size_t)(e - p));
        if (s == NULL) {
          s = e;
        }
        len = mg_url_decode(p, (size_t)(s - p), dst, dst_len, 1);
        if (len == -1) {
          len = -2;
        }
        break;
      }
    }
  }
4562

4563 4564
  return len;
}
Sergey Lyubka's avatar
Sergey Lyubka committed
4565

4566 4567 4568
void mg_send_http_chunk(struct mg_connection *nc, const char *buf, size_t len) {
  char chunk_size[50];
  int n;
4569

4570 4571 4572 4573 4574
  n = snprintf(chunk_size, sizeof(chunk_size), "%lX\r\n", (unsigned long) len);
  mg_send(nc, chunk_size, n);
  mg_send(nc, buf, len);
  mg_send(nc, "\r\n", 2);
}
4575

4576 4577 4578 4579
void mg_printf_http_chunk(struct mg_connection *nc, const char *fmt, ...) {
  char mem[500], *buf = mem;
  int len;
  va_list ap;
4580

4581 4582 4583
  va_start(ap, fmt);
  len = mg_avprintf(&buf, sizeof(mem), fmt, ap);
  va_end(ap);
4584

4585 4586 4587
  if (len >= 0) {
    mg_send_http_chunk(nc, buf, len);
  }
4588

4589 4590
  /* LCOV_EXCL_START */
  if (buf != mem && buf != NULL) {
4591
    MG_FREE(buf);
4592 4593 4594
  }
  /* LCOV_EXCL_STOP */
}
Sergey Lyubka's avatar
Sergey Lyubka committed
4595

4596 4597 4598 4599
void mg_printf_html_escape(struct mg_connection *nc, const char *fmt, ...) {
  char mem[500], *buf = mem;
  int i, j, len;
  va_list ap;
Sergey Lyubka's avatar
Sergey Lyubka committed
4600

4601 4602 4603
  va_start(ap, fmt);
  len = mg_avprintf(&buf, sizeof(mem), fmt, ap);
  va_end(ap);
4604

4605 4606 4607 4608 4609 4610 4611 4612 4613 4614
  if (len >= 0) {
    for (i = j = 0; i < len; i++) {
      if (buf[i] == '<' || buf[i] == '>') {
        mg_send(nc, buf + j, i - j);
        mg_send(nc, buf[i] == '<' ? "&lt;" : "&gt;", 4);
        j = i + 1;
      }
    }
    mg_send(nc, buf + j, i - j);
  }
4615

4616 4617
  /* LCOV_EXCL_START */
  if (buf != mem && buf != NULL) {
4618
    MG_FREE(buf);
4619 4620 4621
  }
  /* LCOV_EXCL_STOP */
}
4622

4623 4624 4625 4626
int mg_http_parse_header(struct mg_str *hdr, const char *var_name, char *buf,
                         size_t buf_size) {
  int ch = ' ', ch1 = ',', len = 0, n = strlen(var_name);
  const char *p, *end = hdr->p + hdr->len, *s = NULL;
Sergey Lyubka's avatar
Sergey Lyubka committed
4627

4628
  if (buf != NULL && buf_size > 0) buf[0] = '\0';
4629

4630 4631 4632 4633 4634 4635
  /* Find where variable starts */
  for (s = hdr->p; s != NULL && s + n < end; s++) {
    if ((s == hdr->p || s[-1] == ch || s[-1] == ch1) && s[n] == '=' &&
        !memcmp(s, var_name, n))
      break;
  }
4636

4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654
  if (s != NULL && &s[n + 1] < end) {
    s += n + 1;
    if (*s == '"' || *s == '\'') {
      ch = ch1 = *s++;
    }
    p = s;
    while (p < end && p[0] != ch && p[0] != ch1 && len < (int) buf_size) {
      if (ch != ' ' && p[0] == '\\' && p[1] == ch) p++;
      buf[len++] = *p++;
    }
    if (len >= (int) buf_size || (ch != ' ' && *p != ch)) {
      len = 0;
    } else {
      if (len > 0 && s[len - 1] == ',') len--;
      if (len > 0 && s[len - 1] == ';') len--;
      buf[len] = '\0';
    }
  }
Sergey Lyubka's avatar
Sergey Lyubka committed
4655

4656 4657
  return len;
}
4658

4659
#ifndef MG_DISABLE_FILESYSTEM
4660 4661 4662 4663 4664 4665 4666 4667
static int is_file_hidden(const char *path,
                          const struct mg_serve_http_opts *opts) {
  const char *p1 = opts->per_directory_auth_file;
  const char *p2 = opts->hidden_file_pattern;
  return !strcmp(path, ".") || !strcmp(path, "..") ||
         (p1 != NULL && !strcmp(path, p1)) ||
         (p2 != NULL && mg_match_prefix(p2, strlen(p2), path) > 0);
}
Sergey Lyubka's avatar
Sergey Lyubka committed
4668

4669
#ifndef MG_DISABLE_HTTP_DIGEST_AUTH
4670 4671 4672 4673 4674
static FILE *open_auth_file(const char *path, int is_directory,
                            const struct mg_serve_http_opts *opts) {
  char buf[MAX_PATH_SIZE];
  const char *p;
  FILE *fp = NULL;
4675

4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689
  if (opts->global_auth_file != NULL) {
    fp = fopen(opts->global_auth_file, "r");
  } else if (is_directory && opts->per_directory_auth_file) {
    snprintf(buf, sizeof(buf), "%s%c%s", path, DIRSEP,
             opts->per_directory_auth_file);
    fp = fopen(buf, "r");
  } else if (opts->per_directory_auth_file) {
    if ((p = strrchr(path, '/')) == NULL && (p = strrchr(path, '\\')) == NULL) {
      p = path;
    }
    snprintf(buf, sizeof(buf), "%.*s/%s", (int) (p - path), path,
             opts->per_directory_auth_file);
    fp = fopen(buf, "r");
  }
4690

4691
  return fp;
4692 4693
}

4694 4695 4696 4697 4698 4699 4700
/*
 * Stringify binary data. Output buffer size must be 2 * size_of_input + 1
 * because each byte of input takes 2 bytes in string representation
 * plus 1 byte for the terminating \0 character.
 */
static void bin2str(char *to, const unsigned char *p, size_t len) {
  static const char *hex = "0123456789abcdef";
4701

4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713
  for (; len--; p++) {
    *to++ = hex[p[0] >> 4];
    *to++ = hex[p[0] & 0x0f];
  }
  *to = '\0';
}

static char *mg_md5(char *buf, ...) {
  unsigned char hash[16];
  const unsigned char *p;
  va_list ap;
  MD5_CTX ctx;
4714

4715
  MD5_Init(&ctx);
4716

4717 4718 4719 4720
  va_start(ap, buf);
  while ((p = va_arg(ap, const unsigned char *) ) != NULL) {
    size_t len = va_arg(ap, size_t);
    MD5_Update(&ctx, p, len);
4721
  }
4722
  va_end(ap);
4723

4724 4725
  MD5_Final(hash, &ctx);
  bin2str(buf, hash, sizeof(hash));
4726

4727
  return buf;
4728
}
4729

4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764
static void mkmd5resp(const char *method, size_t method_len, const char *uri,
                      size_t uri_len, const char *ha1, size_t ha1_len,
                      const char *nonce, size_t nonce_len, const char *nc,
                      size_t nc_len, const char *cnonce, size_t cnonce_len,
                      const char *qop, size_t qop_len, char *resp) {
  static const char colon[] = ":";
  static const size_t one = 1;
  char ha2[33];

  mg_md5(ha2, method, method_len, colon, one, uri, uri_len, NULL);
  mg_md5(resp, ha1, ha1_len, colon, one, nonce, nonce_len, colon, one, nc,
         nc_len, colon, one, cnonce, cnonce_len, colon, one, qop, qop_len,
         colon, one, ha2, sizeof(ha2) - 1, NULL);
}

int mg_http_create_digest_auth_header(char *buf, size_t buf_len,
                                      const char *method, const char *uri,
                                      const char *auth_domain, const char *user,
                                      const char *passwd) {
  static const char colon[] = ":", qop[] = "auth";
  static const size_t one = 1;
  char ha1[33], resp[33], cnonce[40];

  snprintf(cnonce, sizeof(cnonce), "%x", (unsigned int) time(NULL));
  mg_md5(ha1, user, (size_t) strlen(user), colon, one, auth_domain,
         (size_t) strlen(auth_domain), colon, one, passwd,
         (size_t) strlen(passwd), NULL);
  mkmd5resp(method, strlen(method), uri, strlen(uri), ha1, sizeof(ha1) - 1,
            cnonce, strlen(cnonce), "1", one, cnonce, strlen(cnonce), qop,
            sizeof(qop) - 1, resp);
  return snprintf(buf, buf_len,
                  "Authorization: Digest username=\"%s\","
                  "realm=\"%s\",uri=\"%s\",qop=%s,nc=1,cnonce=%s,"
                  "nonce=%s,response=%s\r\n",
                  user, auth_domain, uri, qop, cnonce, cnonce, resp);
4765 4766
}

4767 4768 4769 4770 4771 4772 4773 4774 4775 4776
/*
 * Check for authentication timeout.
 * Clients send time stamp encoded in nonce. Make sure it is not too old,
 * to prevent replay attacks.
 * Assumption: nonce is a hexadecimal number of seconds since 1970.
 */
static int check_nonce(const char *nonce) {
  unsigned long now = (unsigned long) time(NULL);
  unsigned long val = (unsigned long) strtoul(nonce, NULL, 16);
  return 1 || now < val || now - val < 3600;
4777 4778
}

4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802
/*
 * Authenticate HTTP request against opened passwords file.
 * Returns 1 if authenticated, 0 otherwise.
 */
static int mg_http_check_digest_auth(struct http_message *hm,
                                     const char *auth_domain, FILE *fp) {
  struct mg_str *hdr;
  char buf[128], f_user[sizeof(buf)], f_ha1[sizeof(buf)], f_domain[sizeof(buf)];
  char user[50], cnonce[20], response[40], uri[200], qop[20], nc[20], nonce[30];
  char expected_response[33];

  /* Parse "Authorization:" header, fail fast on parse error */
  if (hm == NULL || fp == NULL ||
      (hdr = mg_get_http_header(hm, "Authorization")) == NULL ||
      mg_http_parse_header(hdr, "username", user, sizeof(user)) == 0 ||
      mg_http_parse_header(hdr, "cnonce", cnonce, sizeof(cnonce)) == 0 ||
      mg_http_parse_header(hdr, "response", response, sizeof(response)) == 0 ||
      mg_http_parse_header(hdr, "uri", uri, sizeof(uri)) == 0 ||
      mg_http_parse_header(hdr, "qop", qop, sizeof(qop)) == 0 ||
      mg_http_parse_header(hdr, "nc", nc, sizeof(nc)) == 0 ||
      mg_http_parse_header(hdr, "nonce", nonce, sizeof(nonce)) == 0 ||
      check_nonce(nonce) == 0) {
    return 0;
  }
4803

4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820
  /*
   * Read passwords file line by line. If should have htdigest format,
   * i.e. each line should be a colon-separated sequence:
   * USER_NAME:DOMAIN_NAME:HA1_HASH_OF_USER_DOMAIN_AND_PASSWORD
   */
  while (fgets(buf, sizeof(buf), fp) != NULL) {
    if (sscanf(buf, "%[^:]:%[^:]:%s", f_user, f_domain, f_ha1) == 3 &&
        strcmp(user, f_user) == 0 &&
        /* NOTE(lsm): due to a bug in MSIE, we do not compare URIs */
        strcmp(auth_domain, f_domain) == 0) {
      /* User and domain matched, check the password */
      mkmd5resp(hm->method.p, hm->method.len, hm->uri.p, hm->uri.len, f_ha1,
                strlen(f_ha1), nonce, strlen(nonce), nc, strlen(nc), cnonce,
                strlen(cnonce), qop, strlen(qop), expected_response);
      return mg_casecmp(response, expected_response) == 0;
    }
  }
Sergey Lyubka's avatar
Sergey Lyubka committed
4821

4822 4823 4824
  /* None of the entries in the passwords file matched - return failure */
  return 0;
}
4825

4826 4827 4828 4829 4830 4831 4832 4833 4834 4835
static int is_authorized(struct http_message *hm, const char *path,
                         int is_directory, struct mg_serve_http_opts *opts) {
  FILE *fp;
  int authorized = 1;

  if (opts->auth_domain != NULL && (opts->per_directory_auth_file != NULL ||
                                    opts->global_auth_file != NULL) &&
      (fp = open_auth_file(path, is_directory, opts)) != NULL) {
    authorized = mg_http_check_digest_auth(hm, opts->auth_domain, fp);
    fclose(fp);
4836 4837
  }

4838
  return authorized;
4839
}
4840 4841 4842 4843 4844 4845 4846 4847 4848 4849
#else
static int is_authorized(struct http_message *hm, const char *path,
                         int is_directory, struct mg_serve_http_opts *opts) {
  (void) hm;
  (void) path;
  (void) is_directory;
  (void) opts;
  return 1;
}
#endif
4850

4851
#ifndef MG_DISABLE_DIRECTORY_LISTING
4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871
static size_t mg_url_encode(const char *src, size_t s_len, char *dst,
                            size_t dst_len) {
  static const char *dont_escape = "._-$,;~()";
  static const char *hex = "0123456789abcdef";
  size_t i = 0, j = 0;

  for (i = j = 0; dst_len > 0 && i < s_len && j + 2 < dst_len - 1; i++, j++) {
    if (isalnum(*(const unsigned char *) (src + i)) ||
        strchr(dont_escape, *(const unsigned char *) (src + i)) != NULL) {
      dst[j] = src[i];
    } else if (j + 3 < dst_len) {
      dst[j] = '%';
      dst[j + 1] = hex[(*(const unsigned char *) (src + i)) >> 4];
      dst[j + 2] = hex[(*(const unsigned char *) (src + i)) & 0xf];
      j += 2;
    }
  }

  dst[j] = '\0';
  return j;
4872 4873
}

4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884
static void escape(const char *src, char *dst, size_t dst_len) {
  size_t n = 0;
  while (*src != '\0' && n + 5 < dst_len) {
    unsigned char ch = *(unsigned char *) src++;
    if (ch == '<') {
      n += snprintf(dst + n, dst_len - n, "%s", "&lt;");
    } else {
      dst[n++] = ch;
    }
  }
  dst[n] = '\0';
4885
}
Sergey Lyubka's avatar
Sergey Lyubka committed
4886

4887 4888 4889 4890 4891 4892 4893 4894 4895
static void print_dir_entry(struct mg_connection *nc, const char *file_name,
                            cs_stat_t *stp) {
  char size[64], mod[64], href[MAX_PATH_SIZE * 3], path[MAX_PATH_SIZE];
  int64_t fsize = stp->st_size;
  int is_dir = S_ISDIR(stp->st_mode);
  const char *slash = is_dir ? "/" : "";

  if (is_dir) {
    snprintf(size, sizeof(size), "%s", "[DIRECTORY]");
4896
  } else {
4897 4898 4899 4900 4901 4902 4903 4904 4905 4906
    /*
     * We use (double) cast below because MSVC 6 compiler cannot
     * convert unsigned __int64 to double.
     */
    if (fsize < 1024) {
      snprintf(size, sizeof(size), "%d", (int) fsize);
    } else if (fsize < 0x100000) {
      snprintf(size, sizeof(size), "%.1fk", (double) fsize / 1024.0);
    } else if (fsize < 0x40000000) {
      snprintf(size, sizeof(size), "%.1fM", (double) fsize / 1048576);
4907
    } else {
4908
      snprintf(size, sizeof(size), "%.1fG", (double) fsize / 1073741824);
4909
    }
4910 4911 4912 4913 4914 4915 4916 4917 4918 4919
  }
  strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", localtime(&stp->st_mtime));
  escape(file_name, path, sizeof(path));
  mg_url_encode(file_name, strlen(file_name), href, sizeof(href));
  mg_printf_http_chunk(nc,
                       "<tr><td><a href=\"%s%s\">%s%s</a></td>"
                       "<td>%s</td><td name=%" INT64_FMT ">%s</td></tr>\n",
                       href, slash, path, slash, mod, is_dir ? -1 : fsize,
                       size);
}
4920

4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938
static void scan_directory(struct mg_connection *nc, const char *dir,
                           const struct mg_serve_http_opts *opts,
                           void (*func)(struct mg_connection *, const char *,
                                        cs_stat_t *)) {
  char path[MAX_PATH_SIZE];
  cs_stat_t st;
  struct dirent *dp;
  DIR *dirp;

  if ((dirp = (opendir(dir))) != NULL) {
    while ((dp = readdir(dirp)) != NULL) {
      /* Do not show current dir and hidden files */
      if (is_file_hidden(dp->d_name, opts)) {
        continue;
      }
      snprintf(path, sizeof(path), "%s/%s", dir, dp->d_name);
      if (mg_stat(path, &st) == 0) {
        func(nc, dp->d_name, &st);
4939 4940
      }
    }
4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983
    closedir(dirp);
  }
}

static void send_directory_listing(struct mg_connection *nc, const char *dir,
                                   struct http_message *hm,
                                   struct mg_serve_http_opts *opts) {
  static const char *sort_js_code =
      "<script>function srt(tb, col) {"
      "var tr = Array.prototype.slice.call(tb.rows, 0),"
      "tr = tr.sort(function (a, b) { var c1 = a.cells[col], c2 = b.cells[col],"
      "n1 = c1.getAttribute('name'), n2 = c2.getAttribute('name'), "
      "t1 = a.cells[2].getAttribute('name'), "
      "t2 = b.cells[2].getAttribute('name'); "
      "return t1 < 0 && t2 >= 0 ? -1 : t2 < 0 && t1 >= 0 ? 1 : "
      "n1 ? parseInt(n2) - parseInt(n1) : "
      "c1.textContent.trim().localeCompare(c2.textContent.trim()); });";
  static const char *sort_js_code2 =
      "for (var i = 0; i < tr.length; i++) tb.appendChild(tr[i]);}"
      "window.onload = function() { "
      "var tb = document.getElementById('tb');"
      "document.onclick = function(ev){ "
      "var c = ev.target.rel; if (c) srt(tb, c)}; srt(tb, 2); };</script>";

  mg_printf(nc, "%s\r\n%s: %s\r\n%s: %s\r\n\r\n", "HTTP/1.1 200 OK",
            "Transfer-Encoding", "chunked", "Content-Type",
            "text/html; charset=utf-8");

  mg_printf_http_chunk(
      nc,
      "<html><head><title>Index of %.*s</title>%s%s"
      "<style>th,td {text-align: left; padding-right: 1em; }</style></head>"
      "<body><h1>Index of %.*s</h1><pre><table cellpadding=\"0\"><thead>"
      "<tr><th><a href=# rel=0>Name</a></th><th>"
      "<a href=# rel=1>Modified</a</th>"
      "<th><a href=# rel=2>Size</a></th></tr>"
      "<tr><td colspan=\"3\"><hr></td></tr></thead><tbody id=tb>",
      (int) hm->uri.len, hm->uri.p, sort_js_code, sort_js_code2,
      (int) hm->uri.len, hm->uri.p);
  scan_directory(nc, dir, opts, print_dir_entry);
  mg_printf_http_chunk(nc, "%s", "</tbody></body></html>");
  mg_send_http_chunk(nc, "", 0);
  /* TODO(rojer): Remove when cesanta/dev/issues/197 is fixed. */
4984
  nc->flags |= MG_F_SEND_AND_CLOSE;
4985
}
4986
#endif /* MG_DISABLE_DIRECTORY_LISTING */
4987

4988
#ifndef MG_DISABLE_DAV
4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036
static void print_props(struct mg_connection *nc, const char *name,
                        cs_stat_t *stp) {
  char mtime[64], buf[MAX_PATH_SIZE * 3];
  time_t t = stp->st_mtime; /* store in local variable for NDK compile */
  gmt_time_string(mtime, sizeof(mtime), &t);
  mg_url_encode(name, strlen(name), buf, sizeof(buf));
  mg_printf(nc,
            "<d:response>"
            "<d:href>%s</d:href>"
            "<d:propstat>"
            "<d:prop>"
            "<d:resourcetype>%s</d:resourcetype>"
            "<d:getcontentlength>%" INT64_FMT
            "</d:getcontentlength>"
            "<d:getlastmodified>%s</d:getlastmodified>"
            "</d:prop>"
            "<d:status>HTTP/1.1 200 OK</d:status>"
            "</d:propstat>"
            "</d:response>\n",
            buf, S_ISDIR(stp->st_mode) ? "<d:collection/>" : "",
            (int64_t) stp->st_size, mtime);
}

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

  /* Print properties for the requested resource itself */
  if (S_ISDIR(stp->st_mode) &&
      strcmp(opts->enable_directory_listing, "yes") != 0) {
    mg_printf(nc, "%s", "HTTP/1.1 403 Directory Listing Denied\r\n\r\n");
  } else {
    char uri[MAX_PATH_SIZE];
    mg_send(nc, header, sizeof(header) - 1);
    snprintf(uri, sizeof(uri), "%.*s", (int) hm->uri.len, hm->uri.p);
    print_props(nc, uri, stp);
    if (S_ISDIR(stp->st_mode) && (depth == NULL || mg_vcmp(depth, "0") != 0)) {
      scan_directory(nc, path, opts, print_props);
    }
    mg_send(nc, footer, sizeof(footer) - 1);
5037
    nc->flags |= MG_F_SEND_AND_CLOSE;
5038 5039 5040
  }
}

5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055
static void handle_mkcol(struct mg_connection *nc, const char *path,
                         struct http_message *hm) {
  int status_code = 500;
  if (mg_get_http_header(hm, "Content-Length") != NULL) {
    status_code = 415;
  } else if (!mg_mkdir(path, 0755)) {
    status_code = 201;
  } else if (errno == EEXIST) {
    status_code = 405;
  } else if (errno == EACCES) {
    status_code = 403;
  } else if (errno == ENOENT) {
    status_code = 409;
  }
  send_http_error(nc, status_code, NULL);
5056 5057
}

5058 5059 5060 5061 5062
static int remove_directory(const char *dir) {
  char path[MAX_PATH_SIZE];
  struct dirent *dp;
  cs_stat_t st;
  DIR *dirp;
5063

5064
  if ((dirp = opendir(dir)) == NULL) return 0;
5065

5066 5067 5068 5069 5070 5071 5072 5073
  while ((dp = readdir(dirp)) != NULL) {
    if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) continue;
    snprintf(path, sizeof(path), "%s%c%s", dir, '/', dp->d_name);
    mg_stat(path, &st);
    if (S_ISDIR(st.st_mode)) {
      remove_directory(path);
    } else {
      remove(path);
5074 5075
    }
  }
5076 5077
  closedir(dirp);
  rmdir(dir);
5078

5079
  return 1;
5080 5081
}

5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094
static void handle_delete(struct mg_connection *nc, const char *path) {
  cs_stat_t st;
  if (mg_stat(path, &st) != 0) {
    send_http_error(nc, 404, NULL);
  } else if (S_ISDIR(st.st_mode)) {
    remove_directory(path);
    send_http_error(nc, 204, NULL);
  } else if (remove(path) == 0) {
    send_http_error(nc, 204, NULL);
  } else {
    send_http_error(nc, 423, NULL);
  }
}
5095

5096 5097 5098
/* Return -1 on error, 1 on success. */
static int create_itermediate_directories(const char *path) {
  const char *s = path;
5099

5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111
  /* Create intermediate directories if they do not exist */
  while (*s) {
    if (*s == '/') {
      char buf[MAX_PATH_SIZE];
      cs_stat_t st;
      snprintf(buf, sizeof(buf), "%.*s", (int) (s - path), path);
      buf[sizeof(buf) - 1] = '\0';
      if (mg_stat(buf, &st) != 0 && mg_mkdir(buf, 0755) != 0) {
        return -1;
      }
    }
    s++;
5112 5113
  }

5114
  return 1;
5115 5116
}

5117 5118 5119 5120 5121 5122
static void handle_put(struct mg_connection *nc, const char *path,
                       struct http_message *hm) {
  cs_stat_t st;
  const struct mg_str *cl_hdr = mg_get_http_header(hm, "Content-Length");
  int rc, status_code = mg_stat(path, &st) == 0 ? 200 : 201;
  struct proto_data_http *dp = (struct proto_data_http *) nc->proto_data;
5123

5124 5125 5126 5127 5128 5129 5130
  free_http_proto_data(nc);
  if ((rc = create_itermediate_directories(path)) == 0) {
    mg_printf(nc, "HTTP/1.1 %d OK\r\nContent-Length: 0\r\n\r\n", status_code);
  } else if (rc == -1) {
    send_http_error(nc, 500, NULL);
  } else if (cl_hdr == NULL) {
    send_http_error(nc, 411, NULL);
5131
  } else if ((dp = (struct proto_data_http *) MG_CALLOC(1, sizeof(*dp))) ==
5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154
             NULL) {
    send_http_error(nc, 500, NULL); /* LCOV_EXCL_LINE */
  } else if ((dp->fp = fopen(path, "w+b")) == NULL) {
    send_http_error(nc, 500, NULL);
    free_http_proto_data(nc);
  } else {
    const struct mg_str *range_hdr = mg_get_http_header(hm, "Content-Range");
    int64_t r1 = 0, r2 = 0;
    dp->type = DATA_PUT;
    mg_set_close_on_exec(fileno(dp->fp));
    dp->cl = to64(cl_hdr->p);
    if (range_hdr != NULL && parse_range_header(range_hdr, &r1, &r2) > 0) {
      status_code = 206;
      fseeko(dp->fp, r1, SEEK_SET);
      dp->cl = r2 > r1 ? r2 - r1 + 1 : dp->cl - r1;
    }
    mg_printf(nc, "HTTP/1.1 %d OK\r\nContent-Length: 0\r\n\r\n", status_code);
    nc->proto_data = dp;
    /* Remove HTTP request from the mbuf, leave only payload */
    mbuf_remove(&nc->recv_mbuf, hm->message.len - hm->body.len);
    transfer_file_data(nc);
  }
}
5155
#endif /* MG_DISABLE_DAV */
5156 5157 5158 5159 5160

static int is_dav_request(const struct mg_str *s) {
  return !mg_vcmp(s, "PUT") || !mg_vcmp(s, "DELETE") || !mg_vcmp(s, "MKCOL") ||
         !mg_vcmp(s, "PROPFIND");
}
5161

5162 5163 5164 5165 5166 5167 5168
/*
 * Given a directory path, find one of the files specified in the
 * comma-separated list of index files `list`.
 * First found index file wins. If an index file is found, then gets
 * appended to the `path`, stat-ed, and result of `stat()` passed to `stp`.
 * If index file is not found, then `path` and `stp` remain unchanged.
 */
5169
MG_INTERNAL int find_index_file(char *path, size_t path_len, const char *list,
5170 5171 5172 5173 5174
                                cs_stat_t *stp) {
  cs_stat_t st;
  size_t n = strlen(path);
  struct mg_str vec;
  int found = 0;
5175

5176 5177 5178 5179 5180
  /* The 'path' given to us points to the directory. Remove all trailing */
  /* directory separator characters from the end of the path, and */
  /* then append single directory separator character. */
  while (n > 0 && (path[n - 1] == '/' || path[n - 1] == '\\')) {
    n--;
5181 5182
  }

5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195
  /* Traverse index files list. For each entry, append it to the given */
  /* path and see if the file exists. If it exists, break the loop */
  while ((list = mg_next_comma_list_entry(list, &vec, NULL)) != NULL) {
    /* Prepare full path to the index file */
    snprintf(path + n, path_len - n, "/%.*s", (int) vec.len, vec.p);
    path[path_len - 1] = '\0';

    /* Does it exist? */
    if (!mg_stat(path, &st)) {
      /* Yes it does, break the loop */
      *stp = st;
      found = 1;
      break;
5196 5197
    }
  }
5198

5199 5200 5201 5202
  /* If no index file exists, restore directory path, keep trailing slash. */
  if (!found) {
    path[n] = '\0';
    strncat(path + n, "/", path_len - n);
5203
  }
Sergey Lyubka's avatar
Sergey Lyubka committed
5204

5205
  return found;
5206 5207
}

5208 5209
static void uri_to_path(struct http_message *hm, char *buf, size_t buf_len,
                        const struct mg_serve_http_opts *opts) {
5210
  char uri[MG_MAX_PATH];
5211 5212
  struct mg_str a, b, *host_hdr = mg_get_http_header(hm, "Host");
  const char *rewrites = opts->url_rewrites;
5213

5214 5215 5216
  mg_url_decode(hm->uri.p, hm->uri.len, uri, sizeof(uri), 0);
  remove_double_dots(uri);
  snprintf(buf, buf_len, "%s%s", opts->document_root, uri);
5217

5218
#ifndef MG_DISABLE_DAV
5219 5220 5221 5222
  if (is_dav_request(&hm->method) && opts->dav_document_root != NULL) {
    snprintf(buf, buf_len, "%s%s", opts->dav_document_root, uri);
  }
#endif
5223

5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240
  /* Handle URL rewrites */
  while ((rewrites = mg_next_comma_list_entry(rewrites, &a, &b)) != NULL) {
    if (a.len > 1 && a.p[0] == '@' && host_hdr != NULL &&
        host_hdr->len == a.len - 1 &&
        mg_ncasecmp(a.p + 1, host_hdr->p, a.len - 1) == 0) {
      /* This is a virtual host rewrite: @domain.name=document_root_dir */
      snprintf(buf, buf_len, "%.*s%s", (int) b.len, b.p, uri);
      break;
    } else {
      /* This is a usual rewrite, URI=directory */
      int match_len = mg_match_prefix(a.p, a.len, uri);
      if (match_len > 0) {
        snprintf(buf, buf_len, "%.*s%s", (int) b.len, b.p, uri + match_len);
        break;
      }
    }
  }
5241 5242
}

5243
#ifndef MG_DISABLE_CGI
5244
#ifdef _WIN32
Sergey Lyubka's avatar
Sergey Lyubka committed
5245 5246 5247 5248 5249 5250 5251 5252 5253
struct threadparam {
  sock_t s;
  HANDLE hPipe;
};

static int wait_until_ready(sock_t sock, int for_read) {
  fd_set set;
  FD_ZERO(&set);
  FD_SET(sock, &set);
5254
  return select(sock + 1, for_read ? &set : 0, for_read ? 0 : &set, 0, 0) == 1;
Sergey Lyubka's avatar
Sergey Lyubka committed
5255 5256 5257
}

static void *push_to_stdin(void *arg) {
5258
  struct threadparam *tp = (struct threadparam *) arg;
Sergey Lyubka's avatar
Sergey Lyubka committed
5259 5260
  int n, sent, stop = 0;
  DWORD k;
5261
  char buf[BUFSIZ];
Sergey Lyubka's avatar
Sergey Lyubka committed
5262 5263 5264 5265 5266 5267 5268 5269

  while (!stop && wait_until_ready(tp->s, 1) &&
         (n = recv(tp->s, buf, sizeof(buf), 0)) > 0) {
    if (n == -1 && GetLastError() == WSAEWOULDBLOCK) continue;
    for (sent = 0; !stop && sent < n; sent += k) {
      if (!WriteFile(tp->hPipe, buf + sent, n - sent, &k, 0)) stop = 1;
    }
  }
5270
  DBG(("%s", "FORWARED EVERYTHING TO CGI"));
Sergey Lyubka's avatar
Sergey Lyubka committed
5271
  CloseHandle(tp->hPipe);
5272
  MG_FREE(tp);
Sergey Lyubka's avatar
Sergey Lyubka committed
5273 5274 5275 5276 5277
  _endthread();
  return NULL;
}

static void *pull_from_stdout(void *arg) {
5278
  struct threadparam *tp = (struct threadparam *) arg;
5279
  int k = 0, stop = 0;
Sergey Lyubka's avatar
Sergey Lyubka committed
5280
  DWORD n, sent;
5281
  char buf[BUFSIZ];
Sergey Lyubka's avatar
Sergey Lyubka committed
5282 5283 5284 5285

  while (!stop && ReadFile(tp->hPipe, buf, sizeof(buf), &n, NULL)) {
    for (sent = 0; !stop && sent < n; sent += k) {
      if (wait_until_ready(tp->s, 0) &&
5286 5287
          (k = send(tp->s, buf + sent, n - sent, 0)) <= 0)
        stop = 1;
Sergey Lyubka's avatar
Sergey Lyubka committed
5288 5289 5290 5291 5292 5293
    }
  }
  DBG(("%s", "EOF FROM CGI"));
  CloseHandle(tp->hPipe);
  shutdown(tp->s, 2);  // Without this, IO thread may get truncated data
  closesocket(tp->s);
5294
  MG_FREE(tp);
Sergey Lyubka's avatar
Sergey Lyubka committed
5295 5296 5297 5298
  _endthread();
  return NULL;
}

Sergey Lyubka's avatar
Sergey Lyubka committed
5299 5300
static void spawn_stdio_thread(sock_t sock, HANDLE hPipe,
                               void *(*func)(void *)) {
5301
  struct threadparam *tp = (struct threadparam *) MG_MALLOC(sizeof(*tp));
Sergey Lyubka's avatar
Sergey Lyubka committed
5302 5303 5304 5305 5306 5307 5308
  if (tp != NULL) {
    tp->s = sock;
    tp->hPipe = hPipe;
    mg_start_thread(func, tp);
  }
}

5309 5310 5311 5312 5313 5314 5315
static void abs_path(const char *utf8_path, char *abs_path, size_t len) {
  wchar_t buf[MAX_PATH_SIZE], buf2[MAX_PATH_SIZE];
  to_wchar(utf8_path, buf, ARRAY_SIZE(buf));
  GetFullPathNameW(buf, ARRAY_SIZE(buf2), buf2, NULL);
  WideCharToMultiByte(CP_UTF8, 0, buf2, wcslen(buf2) + 1, abs_path, len, 0, 0);
}

5316 5317
static pid_t start_process(const char *interp, const char *cmd, const char *env,
                           const char *envp[], const char *dir, sock_t sock) {
5318 5319
  STARTUPINFOW si;
  PROCESS_INFORMATION pi;
Sergey Lyubka's avatar
Sergey Lyubka committed
5320
  HANDLE a[2], b[2], me = GetCurrentProcess();
5321
  wchar_t wcmd[MAX_PATH_SIZE], full_dir[MAX_PATH_SIZE];
5322 5323
  char buf[MAX_PATH_SIZE], buf2[MAX_PATH_SIZE], buf5[MAX_PATH_SIZE],
      buf4[MAX_PATH_SIZE], cmdline[MAX_PATH_SIZE];
Sergey Lyubka's avatar
Sergey Lyubka committed
5324
  DWORD flags = DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS;
5325
  FILE *fp;
5326

5327 5328 5329
  memset(&si, 0, sizeof(si));
  memset(&pi, 0, sizeof(pi));

5330 5331 5332 5333
  si.cb = sizeof(si);
  si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  si.wShowWindow = SW_HIDE;
  si.hStdError = GetStdHandle(STD_ERROR_HANDLE);
Sergey Lyubka's avatar
Sergey Lyubka committed
5334 5335 5336 5337 5338

  CreatePipe(&a[0], &a[1], NULL, 0);
  CreatePipe(&b[0], &b[1], NULL, 0);
  DuplicateHandle(me, a[0], me, &si.hStdInput, 0, TRUE, flags);
  DuplicateHandle(me, b[1], me, &si.hStdOutput, 0, TRUE, flags);
5339

5340 5341 5342 5343 5344 5345
  if (interp == NULL && (fp = fopen(cmd, "r")) != NULL) {
    buf[0] = buf[1] = '\0';
    fgets(buf, sizeof(buf), fp);
    buf[sizeof(buf) - 1] = '\0';
    if (buf[0] == '#' && buf[1] == '!') {
      interp = buf + 2;
5346 5347 5348 5349
      /* Trim leading spaces: https://github.com/cesanta/mongoose/issues/489 */
      while (*interp != '\0' && isspace(*(unsigned char *) interp)) {
        interp++;
      }
5350
    }
5351
    fclose(fp);
5352 5353
  }

5354 5355 5356 5357 5358 5359
  snprintf(buf, sizeof(buf), "%s/%s", dir, cmd);
  abs_path(buf, buf2, ARRAY_SIZE(buf2));

  abs_path(dir, buf5, ARRAY_SIZE(buf5));
  to_wchar(dir, full_dir, ARRAY_SIZE(full_dir));

5360
  if (interp != NULL) {
5361
    abs_path(interp, buf4, ARRAY_SIZE(buf4));
5362 5363 5364
    snprintf(cmdline, sizeof(cmdline), "%s \"%s\"", buf4, buf2);
  } else {
    snprintf(cmdline, sizeof(cmdline), "\"%s\"", buf2);
5365
  }
5366
  to_wchar(cmdline, wcmd, ARRAY_SIZE(wcmd));
5367

5368 5369 5370 5371
#if 0
  printf("[%ls] [%ls]\n", full_dir, wcmd);
#endif

5372 5373
  if (CreateProcessW(NULL, wcmd, NULL, NULL, TRUE, CREATE_NEW_PROCESS_GROUP,
                     (void *) env, full_dir, &si, &pi) != 0) {
Sergey Lyubka's avatar
Sergey Lyubka committed
5374 5375 5376 5377 5378 5379 5380
    spawn_stdio_thread(sock, a[1], push_to_stdin);
    spawn_stdio_thread(sock, b[0], pull_from_stdout);
  } else {
    CloseHandle(a[1]);
    CloseHandle(b[0]);
    closesocket(sock);
  }
5381
  DBG(("CGI command: [%ls] -> %p", wcmd, pi.hProcess));
5382

5383
  /* Not closing a[0] and b[1] because we've used DUPLICATE_CLOSE_SOURCE */
5384 5385
  CloseHandle(si.hStdOutput);
  CloseHandle(si.hStdInput);
5386 5387 5388
  /* TODO(lsm): check if we need close process and thread handles too */
  /* CloseHandle(pi.hThread); */
  /* CloseHandle(pi.hProcess); */
5389

5390
  return pi.hProcess;
5391
}
5392
#else
5393 5394
static pid_t start_process(const char *interp, const char *cmd, const char *env,
                           const char *envp[], const char *dir, sock_t sock) {
5395
  char buf[500];
5396
  pid_t pid = fork();
5397 5398 5399
  (void) env;

  if (pid == 0) {
5400 5401 5402 5403 5404 5405
    /*
     * In Linux `chdir` declared with `warn_unused_result` attribute
     * To shutup compiler we have yo use result in some way
     */
    int tmp = chdir(dir);
    (void) tmp;
5406 5407
    (void) dup2(sock, 0);
    (void) dup2(sock, 1);
5408
    closesocket(sock);
5409

5410 5411 5412 5413 5414 5415
    /*
     * After exec, all signal handlers are restored to their default values,
     * with one exception of SIGCHLD. According to POSIX.1-2001 and Linux's
     * implementation, SIGCHLD's handler will leave unchanged after exec
     * if it was set to be ignored. Restore it to default action.
     */
5416
    signal(SIGCHLD, SIG_DFL);
5417

5418
    if (interp == NULL) {
5419
      execle(cmd, cmd, (char *) 0, envp); /* (char *) 0 to squash warning */
5420
    } else {
5421
      execle(interp, interp, cmd, (char *) 0, envp);
5422
    }
5423 5424 5425 5426 5427
    snprintf(buf, sizeof(buf),
             "Status: 500\r\n\r\n"
             "500 Server Error: %s%s%s: %s",
             interp == NULL ? "" : interp, interp == NULL ? "" : " ", cmd,
             strerror(errno));
5428
    send(1, buf, strlen(buf), 0);
5429
    exit(EXIT_FAILURE); /* exec call failed */
5430 5431
  }

5432
  return pid;
5433
}
5434
#endif /* _WIN32 */
5435

5436 5437 5438 5439
/*
 * Append VARIABLE=VALUE\0 string to the buffer, and add a respective
 * pointer into the vars array.
 */
5440 5441
static char *addenv(struct cgi_env_block *block, const char *fmt, ...) {
  int n, space;
5442
  char *added = block->buf + block->len;
5443
  va_list ap;
5444

5445 5446 5447 5448 5449 5450 5451
  /* Calculate how much space is left in the buffer */
  space = sizeof(block->buf) - (block->len + 2);
  if (space > 0) {
    /* Copy VARIABLE=VALUE\0 string into the free space */
    va_start(ap, fmt);
    n = vsnprintf(added, (size_t) space, fmt, ap);
    va_end(ap);
5452

5453 5454 5455 5456 5457 5458 5459 5460
    /* Make sure we do not overflow buffer and the envp array */
    if (n > 0 && n + 1 < space &&
        block->nvars < (int) ARRAY_SIZE(block->vars) - 2) {
      /* Append a pointer to the added string into the envp array */
      block->vars[block->nvars++] = added;
      /* Bump up used length counter. Include \0 terminator */
      block->len += n + 1;
    }
5461 5462
  }

5463
  return added;
5464 5465
}

5466 5467 5468
static void addenv2(struct cgi_env_block *blk, const char *name) {
  const char *s;
  if ((s = getenv(name)) != NULL) addenv(blk, "%s=%s", name, s);
5469 5470
}

5471 5472 5473
static void prepare_cgi_environment(struct mg_connection *nc, const char *prog,
                                    const struct http_message *hm,
                                    const struct mg_serve_http_opts *opts,
5474 5475
                                    struct cgi_env_block *blk) {
  const char *s, *slash;
5476 5477 5478
  struct mg_str *h;
  char *p;
  size_t i;
5479

5480
  blk->len = blk->nvars = 0;
5481
  blk->nc = nc;
5482

5483 5484 5485
  if ((s = getenv("SERVER_NAME")) != NULL) {
    addenv(blk, "SERVER_NAME=%s", s);
  } else {
5486 5487 5488
    char buf[100];
    mg_sock_to_str(nc->sock, buf, sizeof(buf), 3);
    addenv(blk, "SERVER_NAME=%s", buf);
5489
  }
5490 5491
  addenv(blk, "SERVER_ROOT=%s", opts->document_root);
  addenv(blk, "DOCUMENT_ROOT=%s", opts->document_root);
5492
  addenv(blk, "SERVER_SOFTWARE=%s/%s", "Mongoose", MG_VERSION);
5493

5494
  /* Prepare the environment block */
5495 5496
  addenv(blk, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  addenv(blk, "%s", "SERVER_PROTOCOL=HTTP/1.1");
5497
  addenv(blk, "%s", "REDIRECT_STATUS=200"); /* For PHP */
5498

5499 5500
  /* TODO(lsm): fix this for IPv6 case */
  /*addenv(blk, "SERVER_PORT=%d", ri->remote_port); */
5501

5502 5503
  addenv(blk, "REQUEST_METHOD=%.*s", (int) hm->method.len, hm->method.p);
#if 0
5504 5505
  addenv(blk, "REMOTE_ADDR=%s", ri->remote_ip);
  addenv(blk, "REMOTE_PORT=%d", ri->remote_port);
5506 5507 5508 5509
#endif
  addenv(blk, "REQUEST_URI=%.*s%s%.*s", (int) hm->uri.len, hm->uri.p,
         hm->query_string.len == 0 ? "" : "?", (int) hm->query_string.len,
         hm->query_string.p);
5510

5511 5512 5513
/* SCRIPT_NAME */
#if 0
  if (nc->path_info != NULL) {
5514
    addenv(blk, "SCRIPT_NAME=%.*s",
5515 5516
           (int) (strlen(ri->uri) - strlen(nc->path_info)), ri->uri);
    addenv(blk, "PATH_INFO=%s", nc->path_info);
5517
  } else {
5518 5519 5520 5521 5522
#endif
  s = strrchr(prog, '/');
  slash = hm->uri.p + hm->uri.len;
  while (slash > hm->uri.p && *slash != '/') {
    slash--;
5523
  }
5524 5525 5526 5527 5528
  addenv(blk, "SCRIPT_NAME=%.*s%s", (int) (slash - hm->uri.p), hm->uri.p,
         s == NULL ? prog : s);
#if 0
  }
#endif
5529

5530 5531
  addenv(blk, "SCRIPT_FILENAME=%s", prog);
  addenv(blk, "PATH_TRANSLATED=%s", prog);
5532
  addenv(blk, "HTTPS=%s", nc->ssl != NULL ? "on" : "off");
5533

5534 5535 5536 5537
  if ((h = mg_get_http_header((struct http_message *) hm, "Content-Type")) !=
      NULL) {
    addenv(blk, "CONTENT_TYPE=%.*s", (int) h->len, h->p);
  }
5538

5539 5540 5541 5542
  if (hm->query_string.len > 0) {
    addenv(blk, "QUERY_STRING=%.*s", (int) hm->query_string.len,
           hm->query_string.p);
  }
5543

5544 5545 5546 5547
  if ((h = mg_get_http_header((struct http_message *) hm, "Content-Length")) !=
      NULL) {
    addenv(blk, "CONTENT_LENGTH=%.*s", (int) h->len, h->p);
  }
5548

5549
  addenv2(blk, "PATH");
5550 5551
  addenv2(blk, "TMP");
  addenv2(blk, "TEMP");
5552
  addenv2(blk, "TMPDIR");
5553
  addenv2(blk, "PERLLIB");
5554
  addenv2(blk, MG_ENV_EXPORT_TO_CGI);
5555

5556 5557 5558 5559 5560 5561 5562 5563 5564
#if defined(_WIN32)
  addenv2(blk, "COMSPEC");
  addenv2(blk, "SYSTEMROOT");
  addenv2(blk, "SystemDrive");
  addenv2(blk, "ProgramFiles");
  addenv2(blk, "ProgramFiles(x86)");
  addenv2(blk, "CommonProgramFiles(x86)");
#else
  addenv2(blk, "LD_LIBRARY_PATH");
5565
#endif /* _WIN32 */
5566

5567 5568 5569 5570 5571
  /* Add all headers as HTTP_* variables */
  for (i = 0; hm->header_names[i].len > 0; i++) {
    p = addenv(blk, "HTTP_%.*s=%.*s", (int) hm->header_names[i].len,
               hm->header_names[i].p, (int) hm->header_values[i].len,
               hm->header_values[i].p);
5572

5573
    /* Convert variable name into uppercase, and change - to _ */
5574
    for (; *p != '=' && *p != '\0'; p++) {
5575 5576
      if (*p == '-') *p = '_';
      *p = (char) toupper(*(unsigned char *) p);
5577 5578 5579
    }
  }

5580 5581
  blk->vars[blk->nvars++] = NULL;
  blk->buf[blk->len++] = '\0';
5582 5583
}

5584 5585 5586 5587 5588 5589 5590 5591
static void cgi_ev_handler(struct mg_connection *cgi_nc, int ev,
                           void *ev_data) {
  struct mg_connection *nc = (struct mg_connection *) cgi_nc->user_data;
  (void) ev_data;

  if (nc == NULL) return;

  switch (ev) {
5592
    case MG_EV_RECV:
5593 5594 5595 5596 5597 5598 5599
      /*
       * CGI script does not output reply line, like "HTTP/1.1 CODE XXXXX\n"
       * It outputs headers, then body. Headers might include "Status"
       * header, which changes CODE, and it might include "Location" header
       * which changes CODE to 302.
       *
       * Therefore we do not send the output from the CGI script to the user
5600
       * until all CGI headers are parsed (by setting MG_F_DONT_SEND flag).
5601 5602
       *
       * Here we parse the output from the CGI script, and if all headers has
5603
       * been received, amend the reply line, and clear MG_F_DONT_SEND flag,
5604 5605
       * which makes data to be sent to the user.
       */
5606
      if (nc->flags & MG_F_USER_1) {
5607 5608 5609 5610
        struct mbuf *io = &cgi_nc->recv_mbuf;
        int len = get_request_len(io->buf, io->len);

        if (len == 0) break;
5611 5612
        if (len < 0 || io->len > MG_MAX_HTTP_REQUEST_SIZE) {
          cgi_nc->flags |= MG_F_CLOSE_IMMEDIATELY;
5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626
          send_http_error(nc, 500, "Bad headers");
        } else {
          struct http_message hm;
          struct mg_str *h;
          parse_http_headers(io->buf, io->buf + io->len, io->len, &hm);
          /*printf("=== %d [%.*s]\n", k, k, io->buf);*/
          if (mg_get_http_header(&hm, "Location") != NULL) {
            mg_printf(nc, "%s", "HTTP/1.1 302 Moved\r\n");
          } else if ((h = mg_get_http_header(&hm, "Status")) != NULL) {
            mg_printf(nc, "HTTP/1.1 %.*s\r\n", (int) h->len, h->p);
          } else {
            mg_printf(nc, "%s", "HTTP/1.1 200 OK\r\n");
          }
        }
5627
        nc->flags &= ~MG_F_USER_1;
5628
      }
5629
      if (!(nc->flags & MG_F_USER_1)) {
5630 5631 5632
        mg_forward(cgi_nc, nc);
      }
      break;
5633
    case MG_EV_CLOSE:
5634
      free_http_proto_data(nc);
5635
      nc->flags |= MG_F_SEND_AND_CLOSE;
5636 5637 5638 5639
      nc->user_data = NULL;
      break;
  }
}
Sergey Lyubka's avatar
Sergey Lyubka committed
5640

5641 5642 5643 5644
static void handle_cgi(struct mg_connection *nc, const char *prog,
                       const struct http_message *hm,
                       const struct mg_serve_http_opts *opts) {
  struct proto_data_http *dp;
5645
  struct cgi_env_block blk;
5646 5647
  char dir[MAX_PATH_SIZE];
  const char *p;
5648 5649
  sock_t fds[2];

5650 5651 5652 5653 5654 5655
  prepare_cgi_environment(nc, prog, hm, opts, &blk);
  /*
   * CGI must be executed in its own directory. 'dir' must point to the
   * directory containing executable program, 'p' must point to the
   * executable program name relative to 'dir'.
   */
5656
  if ((p = strrchr(prog, '/')) == NULL) {
5657
    snprintf(dir, sizeof(dir), "%s", ".");
5658
  } else {
5659 5660
    snprintf(dir, sizeof(dir), "%.*s", (int) (p - prog), prog);
    prog = p + 1;
5661 5662
  }

5663 5664 5665 5666 5667 5668 5669 5670 5671 5672
  /*
   * Try to create socketpair in a loop until success. mg_socketpair()
   * can be interrupted by a signal and fail.
   * TODO(lsm): use sigaction to restart interrupted syscall
   */
  do {
    mg_socketpair(fds, SOCK_STREAM);
  } while (fds[0] == INVALID_SOCKET);

  free_http_proto_data(nc);
5673
  if ((dp = (struct proto_data_http *) MG_CALLOC(1, sizeof(*dp))) == NULL) {
5674 5675 5676 5677 5678 5679 5680
    send_http_error(nc, 500, "OOM"); /* LCOV_EXCL_LINE */
  } else if (start_process(opts->cgi_interpreter, prog, blk.buf, blk.vars, dir,
                           fds[1]) != 0) {
    size_t n = nc->recv_mbuf.len - (hm->message.len - hm->body.len);
    dp->type = DATA_CGI;
    dp->cgi_nc = mg_add_sock(nc->mgr, fds[0], cgi_ev_handler);
    dp->cgi_nc->user_data = nc;
5681
    nc->flags |= MG_F_USER_1;
5682 5683 5684 5685 5686
    /* Push POST data to the CGI */
    if (n > 0 && n < nc->recv_mbuf.len) {
      mg_send(dp->cgi_nc, hm->body.p, n);
    }
    mbuf_remove(&nc->recv_mbuf, nc->recv_mbuf.len);
5687 5688
  } else {
    closesocket(fds[0]);
5689
    send_http_error(nc, 500, "CGI failure");
5690
  }
5691

Sergey Lyubka's avatar
Sergey Lyubka committed
5692
#ifndef _WIN32
5693
  closesocket(fds[1]); /* On Windows, CGI stdio thread closes that socket */
Sergey Lyubka's avatar
Sergey Lyubka committed
5694
#endif
5695
}
5696
#endif
5697

5698 5699 5700 5701 5702 5703
void mg_send_http_file(struct mg_connection *nc, char *path,
                       size_t path_buf_len, struct http_message *hm,
                       struct mg_serve_http_opts *opts) {
  int stat_result, is_directory, is_dav = is_dav_request(&hm->method);
  uint32_t remote_ip = ntohl(*(uint32_t *) &nc->sa.sin.sin_addr);
  cs_stat_t st;
Sergey Lyubka's avatar
Sergey Lyubka committed
5704

5705 5706
  stat_result = mg_stat(path, &st);
  is_directory = !stat_result && S_ISDIR(st.st_mode);
Sergey Lyubka's avatar
Sergey Lyubka committed
5707

5708 5709
  if (mg_check_ip_acl(opts->ip_acl, remote_ip) != 1) {
    /* Not allowed to connect */
5710
    nc->flags |= MG_F_CLOSE_IMMEDIATELY;
5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726
  } else if (is_dav && opts->dav_document_root == NULL) {
    send_http_error(nc, 501, NULL);
  } else if (!is_authorized(hm, path, is_directory, opts)) {
    mg_printf(nc,
              "HTTP/1.1 401 Unauthorized\r\n"
              "WWW-Authenticate: Digest qop=\"auth\", "
              "realm=\"%s\", nonce=\"%lu\"\r\n"
              "Content-Length: 0\r\n\r\n",
              opts->auth_domain, (unsigned long) time(NULL));
  } else if ((stat_result != 0 || is_file_hidden(path, opts)) && !is_dav) {
    mg_printf(nc, "%s", "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n");
  } else if (is_directory && path[strlen(path) - 1] != '/' && !is_dav) {
    mg_printf(nc,
              "HTTP/1.1 301 Moved\r\nLocation: %.*s/\r\n"
              "Content-Length: 0\r\n\r\n",
              (int) hm->uri.len, hm->uri.p);
5727
#ifndef MG_DISABLE_DAV
5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739
  } else if (!mg_vcmp(&hm->method, "PROPFIND")) {
    handle_propfind(nc, path, &st, hm, opts);
  } else if (!mg_vcmp(&hm->method, "MKCOL")) {
    handle_mkcol(nc, path, hm);
  } else if (!mg_vcmp(&hm->method, "DELETE")) {
    handle_delete(nc, path);
  } else if (!mg_vcmp(&hm->method, "PUT")) {
    handle_put(nc, path, hm);
#endif
  } else if (S_ISDIR(st.st_mode) &&
             !find_index_file(path, path_buf_len, opts->index_files, &st)) {
    if (strcmp(opts->enable_directory_listing, "yes") == 0) {
5740
#ifndef MG_DISABLE_DIRECTORY_LISTING
5741 5742 5743 5744
      send_directory_listing(nc, path, hm, opts);
#else
      send_http_error(nc, 501, NULL);
#endif
Sergey Lyubka's avatar
Sergey Lyubka committed
5745
    } else {
5746
      send_http_error(nc, 403, NULL);
5747
    }
5748 5749
  } else if (mg_match_prefix(opts->cgi_file_pattern,
                             strlen(opts->cgi_file_pattern), path) > 0) {
5750
#if !defined(MG_DISABLE_CGI)
5751 5752 5753
    handle_cgi(nc, path, hm, opts);
#else
    send_http_error(nc, 501, NULL);
5754
#endif /* MG_DISABLE_CGI */
5755 5756
  } else {
    mg_send_http_file2(nc, path, &st, hm, opts);
5757 5758
  }
}
5759

5760 5761
void mg_serve_http(struct mg_connection *nc, struct http_message *hm,
                   struct mg_serve_http_opts opts) {
5762
  char path[MG_MAX_PATH];
5763 5764 5765
  uri_to_path(hm, path, sizeof(path), &opts);
  if (opts.per_directory_auth_file == NULL) {
    opts.per_directory_auth_file = ".htpasswd";
5766
  }
5767 5768
  if (opts.enable_directory_listing == NULL) {
    opts.enable_directory_listing = "yes";
5769
  }
5770 5771
  if (opts.cgi_file_pattern == NULL) {
    opts.cgi_file_pattern = "**.cgi$|**.php$";
5772
  }
5773 5774
  if (opts.ssi_pattern == NULL) {
    opts.ssi_pattern = "**.shtml$|**.shtm$";
5775
  }
5776 5777
  if (opts.index_files == NULL) {
    opts.index_files = "index.html,index.htm,index.shtml,index.cgi,index.php";
5778
  }
5779
  mg_send_http_file(nc, path, sizeof(path), hm, &opts);
5780
}
5781

5782
#endif /* MG_DISABLE_FILESYSTEM */
5783

5784 5785 5786 5787 5788 5789 5790 5791
struct mg_connection *mg_connect_http(struct mg_mgr *mgr,
                                      mg_event_handler_t ev_handler,
                                      const char *url,
                                      const char *extra_headers,
                                      const char *post_data) {
  struct mg_connection *nc;
  char addr[1100], path[4096]; /* NOTE: keep sizes in sync with sscanf below */
  int use_ssl = 0, addr_len = 0;
5792

5793 5794 5795 5796 5797
  if (memcmp(url, "http://", 7) == 0) {
    url += 7;
  } else if (memcmp(url, "https://", 8) == 0) {
    url += 8;
    use_ssl = 1;
5798
#ifndef MG_ENABLE_SSL
5799 5800 5801
    return NULL; /* SSL is not enabled, cannot do HTTPS URLs */
#endif
  }
5802

5803
  addr[0] = path[0] = '\0';
5804

5805 5806 5807 5808 5809
  /* addr buffer size made smaller to allow for port to be prepended */
  sscanf(url, "%1095[^/]/%4095s", addr, path);
  if (strchr(addr, ':') == NULL) {
    addr_len = strlen(addr);
    strncat(addr, use_ssl ? ":443" : ":80", sizeof(addr) - (addr_len + 1));
5810 5811
  }

5812 5813
  if ((nc = mg_connect(mgr, addr, ev_handler)) != NULL) {
    mg_set_protocol_http_websocket(nc);
5814

5815
    if (use_ssl) {
5816
#ifdef MG_ENABLE_SSL
5817 5818
      mg_set_ssl(nc, NULL, NULL);
#endif
5819
    }
5820 5821 5822 5823

    if (addr_len) {
      /* Do not add port. See https://github.com/cesanta/mongoose/pull/304 */
      addr[addr_len] = '\0';
5824
    }
5825 5826
    mg_printf(nc, "%s /%s HTTP/1.1\r\nHost: %s\r\nContent-Length: %" SIZE_T_FMT
                  "\r\n%s\r\n%s",
5827 5828 5829 5830
              post_data == NULL ? "GET" : "POST", path, addr,
              post_data == NULL ? 0 : strlen(post_data),
              extra_headers == NULL ? "" : extra_headers,
              post_data == NULL ? "" : post_data);
5831 5832
  }

5833
  return nc;
Sergey Lyubka's avatar
Sergey Lyubka committed
5834 5835
}

5836 5837 5838 5839
static size_t get_line_len(const char *buf, size_t buf_len) {
  size_t len = 0;
  while (len < buf_len && buf[len] != '\n') len++;
  return buf[len] == '\n' ? len + 1 : 0;
5840
}
5841

5842 5843 5844 5845 5846 5847
size_t mg_parse_multipart(const char *buf, size_t buf_len, char *var_name,
                          size_t var_name_len, char *file_name,
                          size_t file_name_len, const char **data,
                          size_t *data_len) {
  static const char cd[] = "Content-Disposition: ";
  size_t hl, bl, n, ll, pos, cdl = sizeof(cd) - 1;
5848

5849 5850 5851
  if (buf == NULL || buf_len <= 0) return 0;
  if ((hl = get_request_len(buf, buf_len)) <= 0) return 0;
  if (buf[0] != '-' || buf[1] != '-' || buf[2] == '\n') return 0;
5852

5853 5854
  /* Get boundary length */
  bl = get_line_len(buf, buf_len);
5855

5856 5857 5858 5859 5860 5861 5862 5863 5864
  /* Loop through headers, fetch variable name and file name */
  var_name[0] = file_name[0] = '\0';
  for (n = bl; (ll = get_line_len(buf + n, hl - n)) > 0; n += ll) {
    if (mg_ncasecmp(cd, buf + n, cdl) == 0) {
      struct mg_str header;
      header.p = buf + n + cdl;
      header.len = ll - (cdl + 2);
      mg_http_parse_header(&header, "name", var_name, var_name_len);
      mg_http_parse_header(&header, "filename", file_name, file_name_len);
5865 5866
    }
  }
5867

5868 5869 5870 5871 5872 5873
  /* Scan through the body, search for terminating boundary */
  for (pos = hl; pos + (bl - 2) < buf_len; pos++) {
    if (buf[pos] == '-' && !memcmp(buf, &buf[pos], bl - 2)) {
      if (data_len != NULL) *data_len = (pos - 2) - hl;
      if (data != NULL) *data = buf + hl;
      return pos;
5874
    }
5875
  }
5876

5877 5878
  return 0;
}
5879

5880
#endif /* MG_DISABLE_HTTP */
5881 5882 5883
#ifdef NS_MODULE_LINES
#line 1 "src/util.c"
/**/
5884
#endif
5885 5886 5887 5888
/*
 * Copyright (c) 2014 Cesanta Software Limited
 * All rights reserved
 */
5889

5890 5891 5892 5893 5894 5895 5896 5897 5898
/* Amalgamated: #include "internal.h" */

const char *mg_skip(const char *s, const char *end, const char *delims,
                    struct mg_str *v) {
  v->p = s;
  while (s < end && strchr(delims, *(unsigned char *) s) == NULL) s++;
  v->len = s - v->p;
  while (s < end && strchr(delims, *(unsigned char *) s) != NULL) s++;
  return s;
5899 5900
}

5901 5902
static int lowercase(const char *s) {
  return tolower(*(const unsigned char *) s);
5903 5904
}

5905 5906 5907 5908 5909 5910 5911 5912
int mg_ncasecmp(const char *s1, const char *s2, size_t len) {
  int diff = 0;

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

  return diff;
5913
}
5914

5915 5916
int mg_casecmp(const char *s1, const char *s2) {
  return mg_ncasecmp(s1, s2, (size_t) ~0);
5917 5918
}

5919 5920 5921 5922 5923
int mg_vcasecmp(const struct mg_str *str1, const char *str2) {
  size_t n2 = strlen(str2), n1 = str1->len;
  int r = mg_ncasecmp(str1->p, str2, (n1 < n2) ? n1 : n2);
  if (r == 0) {
    return n1 - n2;
5924
  }
5925
  return r;
5926 5927
}

5928 5929 5930 5931 5932
int mg_vcmp(const struct mg_str *str1, const char *str2) {
  size_t n2 = strlen(str2), n1 = str1->len;
  int r = memcmp(str1->p, str2, (n1 < n2) ? n1 : n2);
  if (r == 0) {
    return n1 - n2;
5933
  }
5934
  return r;
5935 5936
}

5937
#ifndef MG_DISABLE_FILESYSTEM
5938 5939 5940 5941 5942 5943 5944 5945 5946
int mg_stat(const char *path, cs_stat_t *st) {
#ifdef _WIN32
  wchar_t wpath[MAX_PATH_SIZE];
  to_wchar(path, wpath, ARRAY_SIZE(wpath));
  DBG(("[%ls] -> %d", wpath, _wstati64(wpath, st)));
  return _wstati64(wpath, (struct _stati64 *) st);
#else
  return stat(path, st);
#endif
5947 5948
}

5949 5950 5951 5952 5953 5954 5955 5956 5957 5958
FILE *mg_fopen(const char *path, const char *mode) {
#ifdef _WIN32
  wchar_t wpath[MAX_PATH_SIZE], wmode[10];
  to_wchar(path, wpath, ARRAY_SIZE(wpath));
  to_wchar(mode, wmode, ARRAY_SIZE(wmode));
  return _wfopen(wpath, wmode);
#else
  return fopen(path, mode);
#endif
}
5959

5960 5961 5962 5963 5964 5965 5966 5967 5968 5969
int mg_open(const char *path, int flag, int mode) { /* LCOV_EXCL_LINE */
#ifdef _WIN32
  wchar_t wpath[MAX_PATH_SIZE];
  to_wchar(path, wpath, ARRAY_SIZE(wpath));
  return _wopen(wpath, flag, mode);
#else
  return open(path, flag, mode); /* LCOV_EXCL_LINE */
#endif
}
#endif
5970

5971 5972
void mg_base64_encode(const unsigned char *src, int src_len, char *dst) {
  cs_base64_encode(src, src_len, dst);
5973 5974
}

5975 5976 5977
int mg_base64_decode(const unsigned char *s, int len, char *dst) {
  return cs_base64_decode(s, len, dst);
}
5978

5979
#ifdef MG_ENABLE_THREADS
5980 5981 5982 5983 5984 5985
void *mg_start_thread(void *(*f)(void *), void *p) {
#ifdef _WIN32
  return (void *) _beginthread((void(__cdecl *) (void *) ) f, 0, p);
#else
  pthread_t thread_id = (pthread_t) 0;
  pthread_attr_t attr;
5986

5987 5988
  (void) pthread_attr_init(&attr);
  (void) pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
5989

5990 5991
#if defined(MG_STACK_SIZE) && MG_STACK_SIZE > 1
  (void) pthread_attr_setstacksize(&attr, MG_STACK_SIZE);
5992
#endif
5993

5994 5995 5996 5997
  pthread_create(&thread_id, &attr, f, p);
  pthread_attr_destroy(&attr);

  return (void *) thread_id;
5998
#endif
5999
}
6000
#endif /* MG_ENABLE_THREADS */
6001

6002 6003 6004 6005 6006 6007
/* Set close-on-exec bit for a given socket. */
void mg_set_close_on_exec(sock_t sock) {
#ifdef _WIN32
  (void) SetHandleInformation((HANDLE) sock, HANDLE_FLAG_INHERIT, 0);
#else
  fcntl(sock, F_SETFD, FD_CLOEXEC);
6008
#endif
6009
}
6010

6011 6012
void mg_sock_to_str(sock_t sock, char *buf, size_t len, int flags) {
  union socket_address sa;
6013
#ifndef MG_CC3200
6014 6015
  socklen_t slen = sizeof(sa);
#endif
6016

6017
  memset(&sa, 0, sizeof(sa));
6018 6019
#ifndef MG_CC3200
  if (flags & MG_SOCK_STRINGIFY_REMOTE) {
6020 6021 6022 6023 6024 6025 6026
    getpeername(sock, &sa.sa, &slen);
  } else {
    getsockname(sock, &sa.sa, &slen);
  }
#endif
  mg_sock_addr_to_str(&sa, buf, len, flags);
}
6027

6028 6029 6030 6031 6032
void mg_sock_addr_to_str(const union socket_address *sa, char *buf, size_t len,
                         int flags) {
  int is_v6;
  if (buf == NULL || len <= 0) return;
  buf[0] = '\0';
6033
#if defined(MG_ENABLE_IPV6)
6034 6035 6036 6037
  is_v6 = sa->sa.sa_family == AF_INET6;
#else
  is_v6 = 0;
#endif
6038 6039
  if (flags & MG_SOCK_STRINGIFY_IP) {
#if defined(MG_ENABLE_IPV6)
6040 6041 6042 6043 6044 6045 6046
    const void *addr = NULL;
    char *start = buf;
    socklen_t capacity = len;
    if (!is_v6) {
      addr = &sa->sin.sin_addr;
    } else {
      addr = (void *) &sa->sin6.sin6_addr;
6047
      if (flags & MG_SOCK_STRINGIFY_PORT) {
6048 6049 6050 6051 6052 6053 6054 6055
        *buf = '[';
        start++;
        capacity--;
      }
    }
    if (inet_ntop(sa->sa.sa_family, addr, start, capacity) == NULL) {
      *buf = '\0';
    }
6056
#elif defined(_WIN32) || defined(MG_ESP8266)
6057 6058 6059 6060 6061 6062
    /* Only Windoze Vista (and newer) have inet_ntop() */
    strncpy(buf, inet_ntoa(sa->sin.sin_addr), len);
#else
    inet_ntop(AF_INET, (void *) &sa->sin.sin_addr, buf, len);
#endif
  }
6063
  if (flags & MG_SOCK_STRINGIFY_PORT) {
6064
    int port = ntohs(sa->sin.sin_port);
6065
    if (flags & MG_SOCK_STRINGIFY_IP) {
6066 6067 6068 6069 6070
      snprintf(buf + strlen(buf), len - (strlen(buf) + 1), "%s:%d",
               (is_v6 ? "]" : ""), port);
    } else {
      snprintf(buf, len, "%d", port);
    }
6071 6072
  }
}
6073

6074 6075 6076 6077
int mg_hexdump(const void *buf, int len, char *dst, int dst_len) {
  const unsigned char *p = (const unsigned char *) buf;
  char ascii[17] = "";
  int i, idx, n = 0;
Sergey Lyubka's avatar
Sergey Lyubka committed
6078

6079 6080 6081 6082 6083 6084 6085 6086 6087 6088
  for (i = 0; i < len; i++) {
    idx = i % 16;
    if (idx == 0) {
      if (i > 0) n += snprintf(dst + n, dst_len - n, "  %s\n", ascii);
      n += snprintf(dst + n, dst_len - n, "%04x ", i);
    }
    n += snprintf(dst + n, dst_len - n, " %02x", p[i]);
    ascii[idx] = p[i] < 0x20 || p[i] > 0x7e ? '.' : p[i];
    ascii[idx + 1] = '\0';
  }
6089

6090 6091
  while (i++ % 16) n += snprintf(dst + n, dst_len - n, "%s", "   ");
  n += snprintf(dst + n, dst_len - n, "  %s\n\n", ascii);
6092

6093
  return n;
6094 6095
}

6096 6097 6098
int mg_avprintf(char **buf, size_t size, const char *fmt, va_list ap) {
  va_list ap_copy;
  int len;
6099

6100 6101 6102 6103 6104 6105 6106 6107 6108 6109
  va_copy(ap_copy, ap);
  len = vsnprintf(*buf, size, fmt, ap_copy);
  va_end(ap_copy);

  if (len < 0) {
    /* eCos and Windows are not standard-compliant and return -1 when
     * the buffer is too small. Keep allocating larger buffers until we
     * succeed or out of memory. */
    *buf = NULL; /* LCOV_EXCL_START */
    while (len < 0) {
6110
      MG_FREE(*buf);
6111
      size *= 2;
6112
      if ((*buf = (char *) MG_MALLOC(size)) == NULL) break;
6113 6114 6115 6116 6117 6118 6119
      va_copy(ap_copy, ap);
      len = vsnprintf(*buf, size, fmt, ap_copy);
      va_end(ap_copy);
    }
    /* LCOV_EXCL_STOP */
  } else if (len > (int) size) {
    /* Standard-compliant code path. Allocate a buffer that is large enough. */
6120
    if ((*buf = (char *) MG_MALLOC(len + 1)) == NULL) {
6121 6122 6123 6124 6125
      len = -1; /* LCOV_EXCL_LINE */
    } else {    /* LCOV_EXCL_LINE */
      va_copy(ap_copy, ap);
      len = vsnprintf(*buf, len + 1, fmt, ap_copy);
      va_end(ap_copy);
6126 6127
    }
  }
6128 6129

  return len;
6130 6131
}

6132
#ifndef MG_DISABLE_FILESYSTEM
6133 6134
void mg_hexdump_connection(struct mg_connection *nc, const char *path,
                           int num_bytes, int ev) {
6135
  const struct mbuf *io = ev == MG_EV_SEND ? &nc->send_mbuf : &nc->recv_mbuf;
6136 6137 6138
  FILE *fp;
  char *buf, src[60], dst[60];
  int buf_size = num_bytes * 5 + 100;
6139

6140 6141 6142
  if ((fp = fopen(path, "a")) != NULL) {
    mg_sock_to_str(nc->sock, src, sizeof(src), 3);
    mg_sock_to_str(nc->sock, dst, sizeof(dst), 7);
6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153
    fprintf(
        fp, "%lu %p %s %s %s %d\n", (unsigned long) time(NULL), nc, src,
        ev == MG_EV_RECV ? "<-" : ev == MG_EV_SEND
                                      ? "->"
                                      : ev == MG_EV_ACCEPT
                                            ? "<A"
                                            : ev == MG_EV_CONNECT ? "C>" : "XX",
        dst, num_bytes);
    if (num_bytes > 0 && (buf = (char *) MG_MALLOC(buf_size)) != NULL) {
      mg_hexdump(io->buf + (ev == MG_EV_SEND ? 0 : io->len) -
                     (ev == MG_EV_SEND ? 0 : num_bytes),
6154 6155
                 num_bytes, buf, buf_size);
      fprintf(fp, "%s", buf);
6156
      MG_FREE(buf);
6157 6158
    }
    fclose(fp);
6159 6160
  }
}
6161
#endif
6162

6163 6164 6165 6166 6167
int mg_is_big_endian(void) {
  static const int n = 1;
  /* TODO(mkm) use compiletime check with 4-byte char literal */
  return ((char *) &n)[0] == 0;
}
6168

6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183
const char *mg_next_comma_list_entry(const char *list, struct mg_str *val,
                                     struct mg_str *eq_val) {
  if (list == NULL || *list == '\0') {
    /* End of the list */
    list = NULL;
  } else {
    val->p = list;
    if ((list = strchr(val->p, ',')) != NULL) {
      /* Comma found. Store length and shift the list ptr */
      val->len = list - val->p;
      list++;
    } else {
      /* This value is the last one */
      list = val->p + strlen(val->p);
      val->len = list - val->p;
6184
    }
6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195

    if (eq_val != NULL) {
      /* Value has form "x=y", adjust pointers and lengths */
      /* so that val points to "x", and eq_val points to "y". */
      eq_val->len = 0;
      eq_val->p = (const char *) memchr(val->p, '=', val->len);
      if (eq_val->p != NULL) {
        eq_val->p++; /* Skip over '=' character */
        eq_val->len = val->p + val->len - eq_val->p;
        val->len = (eq_val->p - val->p) - 1;
      }
6196 6197
    }
  }
6198

6199
  return list;
6200 6201
}

6202 6203 6204
int mg_match_prefix(const char *pattern, int pattern_len, const char *str) {
  const char *or_str;
  int len, res, i = 0, j = 0;
6205

6206 6207 6208 6209 6210 6211
  if ((or_str = (const char *) memchr(pattern, '|', pattern_len)) != NULL) {
    res = mg_match_prefix(pattern, or_str - pattern, str);
    return res > 0 ? res : mg_match_prefix(
                               or_str + 1,
                               (pattern + pattern_len) - (or_str + 1), str);
  }
6212

6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234
  for (; i < pattern_len; i++, j++) {
    if (pattern[i] == '?' && str[j] != '\0') {
      continue;
    } else if (pattern[i] == '$') {
      return str[j] == '\0' ? j : -1;
    } else if (pattern[i] == '*') {
      i++;
      if (pattern[i] == '*') {
        i++;
        len = (int) strlen(str + j);
      } else {
        len = (int) strcspn(str + j, "/");
      }
      if (i == pattern_len) {
        return j + len;
      }
      do {
        res = mg_match_prefix(pattern + i, pattern_len - i, str + j + len);
      } while (res == -1 && len-- > 0);
      return res == -1 ? -1 : j + res + len;
    } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
      return -1;
6235 6236
    }
  }
6237 6238 6239 6240 6241 6242 6243 6244
  return j;
}
#ifdef NS_MODULE_LINES
#line 1 "src/json-rpc.c"
/**/
#endif
/* Copyright (c) 2014 Cesanta Software Limited */
/* All rights reserved */
6245

6246
#ifndef MG_DISABLE_JSON_RPC
6247

6248
/* Amalgamated: #include "internal.h" */
6249

6250 6251 6252 6253 6254 6255
int mg_rpc_create_reply(char *buf, int len, const struct mg_rpc_request *req,
                        const char *result_fmt, ...) {
  static const struct json_token null_tok = {"null", 4, 0, JSON_TYPE_NULL};
  const struct json_token *id = req->id == NULL ? &null_tok : req->id;
  va_list ap;
  int n = 0;
6256

6257 6258 6259 6260 6261
  n += json_emit(buf + n, len - n, "{s:s,s:", "jsonrpc", "2.0", "id");
  if (id->type == JSON_TYPE_STRING) {
    n += json_emit_quoted_str(buf + n, len - n, id->ptr, id->len);
  } else {
    n += json_emit_unquoted_str(buf + n, len - n, id->ptr, id->len);
6262
  }
6263
  n += json_emit(buf + n, len - n, ",s:", "result");
6264

6265 6266 6267
  va_start(ap, result_fmt);
  n += json_emit_va(buf + n, len - n, result_fmt, ap);
  va_end(ap);
6268

6269
  n += json_emit(buf + n, len - n, "}");
Sergey Lyubka's avatar
Sergey Lyubka committed
6270

6271 6272
  return n;
}
6273

6274 6275 6276 6277
int mg_rpc_create_request(char *buf, int len, const char *method,
                          const char *id, const char *params_fmt, ...) {
  va_list ap;
  int n = 0;
6278

6279 6280 6281 6282 6283
  n += json_emit(buf + n, len - n, "{s:s,s:s,s:s,s:", "jsonrpc", "2.0", "id",
                 id, "method", method, "params");
  va_start(ap, params_fmt);
  n += json_emit_va(buf + n, len - n, params_fmt, ap);
  va_end(ap);
6284

6285
  n += json_emit(buf + n, len - n, "}");
Sergey Lyubka's avatar
Sergey Lyubka committed
6286

6287
  return n;
6288 6289
}

6290 6291
int mg_rpc_create_error(char *buf, int len, struct mg_rpc_request *req,
                        int code, const char *message, const char *fmt, ...) {
6292
  va_list ap;
6293
  int n = 0;
6294

6295 6296 6297 6298
  n += json_emit(buf + n, len - n, "{s:s,s:V,s:{s:i,s:s,s:", "jsonrpc", "2.0",
                 "id", req->id == NULL ? "null" : req->id->ptr,
                 req->id == NULL ? 4 : req->id->len, "error", "code", code,
                 "message", message, "data");
6299
  va_start(ap, fmt);
6300
  n += json_emit_va(buf + n, len - n, fmt, ap);
6301 6302
  va_end(ap);

6303
  n += json_emit(buf + n, len - n, "}}");
6304

6305
  return n;
6306 6307
}

6308 6309 6310
int mg_rpc_create_std_error(char *buf, int len, struct mg_rpc_request *req,
                            int code) {
  const char *message = NULL;
6311

6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330
  switch (code) {
    case JSON_RPC_PARSE_ERROR:
      message = "parse error";
      break;
    case JSON_RPC_INVALID_REQUEST_ERROR:
      message = "invalid request";
      break;
    case JSON_RPC_METHOD_NOT_FOUND_ERROR:
      message = "method not found";
      break;
    case JSON_RPC_INVALID_PARAMS_ERROR:
      message = "invalid parameters";
      break;
    case JSON_RPC_SERVER_ERROR:
      message = "server error";
      break;
    default:
      message = "unspecified error";
      break;
6331
  }
6332

6333
  return mg_rpc_create_error(buf, len, req, code, message, "N");
6334 6335
}

6336 6337 6338 6339 6340
int mg_rpc_dispatch(const char *buf, int len, char *dst, int dst_len,
                    const char **methods, mg_rpc_handler_t *handlers) {
  struct json_token tokens[200];
  struct mg_rpc_request req;
  int i, n;
6341

6342 6343 6344 6345 6346 6347 6348
  memset(&req, 0, sizeof(req));
  n = parse_json(buf, len, tokens, sizeof(tokens) / sizeof(tokens[0]));
  if (n <= 0) {
    int err_code = (n == JSON_STRING_INVALID) ? JSON_RPC_PARSE_ERROR
                                              : JSON_RPC_SERVER_ERROR;
    return mg_rpc_create_std_error(dst, dst_len, &req, err_code);
  }
6349

6350 6351 6352 6353
  req.message = tokens;
  req.id = find_json_token(tokens, "id");
  req.method = find_json_token(tokens, "method");
  req.params = find_json_token(tokens, "params");
6354

6355 6356 6357
  if (req.id == NULL || req.method == NULL) {
    return mg_rpc_create_std_error(dst, dst_len, &req,
                                   JSON_RPC_INVALID_REQUEST_ERROR);
6358 6359
  }

6360 6361 6362 6363 6364 6365
  for (i = 0; methods[i] != NULL; i++) {
    int mlen = strlen(methods[i]);
    if (mlen == req.method->len &&
        memcmp(methods[i], req.method->ptr, mlen) == 0)
      break;
  }
6366

6367 6368 6369 6370
  if (methods[i] == NULL) {
    return mg_rpc_create_std_error(dst, dst_len, &req,
                                   JSON_RPC_METHOD_NOT_FOUND_ERROR);
  }
6371

6372
  return handlers[i](dst, dst_len, &req);
6373 6374
}

6375 6376 6377 6378
int mg_rpc_parse_reply(const char *buf, int len, struct json_token *toks,
                       int max_toks, struct mg_rpc_reply *rep,
                       struct mg_rpc_error *er) {
  int n = parse_json(buf, len, toks, max_toks);
6379

6380 6381
  memset(rep, 0, sizeof(*rep));
  memset(er, 0, sizeof(*er));
6382

6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395
  if (n > 0) {
    if ((rep->result = find_json_token(toks, "result")) != NULL) {
      rep->message = toks;
      rep->id = find_json_token(toks, "id");
    } else {
      er->message = toks;
      er->id = find_json_token(toks, "id");
      er->error_code = find_json_token(toks, "error.code");
      er->error_message = find_json_token(toks, "error.message");
      er->error_data = find_json_token(toks, "error.data");
    }
  }
  return n;
6396
}
6397

6398
#endif /* MG_DISABLE_JSON_RPC */
6399 6400 6401 6402 6403 6404 6405 6406
#ifdef NS_MODULE_LINES
#line 1 "src/mqtt.c"
/**/
#endif
/*
 * Copyright (c) 2014 Cesanta Software Limited
 * All rights reserved
 */
Sergey Lyubka's avatar
Sergey Lyubka committed
6407

6408
#ifndef MG_DISABLE_MQTT
Sergey Lyubka's avatar
Sergey Lyubka committed
6409

6410
/* Amalgamated: #include "internal.h" */
Sergey Lyubka's avatar
Sergey Lyubka committed
6411

6412 6413 6414 6415 6416 6417
static int parse_mqtt(struct mbuf *io, struct mg_mqtt_message *mm) {
  uint8_t header;
  int cmd;
  size_t len = 0;
  int var_len = 0;
  char *vlen = &io->buf[1];
Sergey Lyubka's avatar
Sergey Lyubka committed
6418

6419
  if (io->len < 2) return -1;
Sergey Lyubka's avatar
Sergey Lyubka committed
6420

6421 6422
  header = io->buf[0];
  cmd = header >> 4;
Sergey Lyubka's avatar
Sergey Lyubka committed
6423

6424 6425 6426 6427
  /* decode mqtt variable length */
  do {
    len += (*vlen & 127) << 7 * (vlen - &io->buf[1]);
  } while ((*vlen++ & 128) != 0 && ((size_t)(vlen - io->buf) <= io->len));
6428

6429
  if (io->len < (size_t)(len - 1)) return -1;
6430

6431 6432
  mbuf_remove(io, 1 + (vlen - &io->buf[1]));
  mm->cmd = cmd;
6433
  mm->qos = MG_MQTT_GET_QOS(header);
6434 6435

  switch (cmd) {
6436
    case MG_MQTT_CMD_CONNECT:
6437 6438
      /* TODO(mkm): parse keepalive and will */
      break;
6439
    case MG_MQTT_CMD_CONNACK:
6440 6441 6442
      mm->connack_ret_code = io->buf[1];
      var_len = 2;
      break;
6443 6444 6445 6446 6447
    case MG_MQTT_CMD_PUBACK:
    case MG_MQTT_CMD_PUBREC:
    case MG_MQTT_CMD_PUBREL:
    case MG_MQTT_CMD_PUBCOMP:
    case MG_MQTT_CMD_SUBACK:
6448 6449 6450
      mm->message_id = ntohs(*(uint16_t *) io->buf);
      var_len = 2;
      break;
6451
    case MG_MQTT_CMD_PUBLISH: {
6452
      uint16_t topic_len = ntohs(*(uint16_t *) io->buf);
6453
      mm->topic = (char *) MG_MALLOC(topic_len + 1);
6454 6455 6456 6457
      mm->topic[topic_len] = 0;
      strncpy(mm->topic, io->buf + 2, topic_len);
      var_len = topic_len + 2;

6458
      if (MG_MQTT_GET_QOS(header) > 0) {
6459 6460 6461 6462
        mm->message_id = ntohs(*(uint16_t *) io->buf);
        var_len += 2;
      }
    } break;
6463
    case MG_MQTT_CMD_SUBSCRIBE:
6464 6465 6466 6467 6468 6469 6470 6471 6472 6473
      /*
       * topic expressions are left in the payload and can be parsed with
       * `mg_mqtt_next_subscribe_topic`
       */
      mm->message_id = ntohs(*(uint16_t *) io->buf);
      var_len = 2;
      break;
    default:
      printf("TODO: UNHANDLED COMMAND %d\n", cmd);
      break;
6474
  }
6475

6476 6477 6478
  mbuf_remove(io, var_len);
  return len - var_len;
}
6479

6480 6481 6482 6483 6484
static void mqtt_handler(struct mg_connection *nc, int ev, void *ev_data) {
  int len;
  struct mbuf *io = &nc->recv_mbuf;
  struct mg_mqtt_message mm;
  memset(&mm, 0, sizeof(mm));
6485

6486
  nc->handler(nc, ev, ev_data);
6487

6488
  switch (ev) {
6489
    case MG_EV_RECV:
6490 6491 6492 6493
      len = parse_mqtt(io, &mm);
      if (len == -1) break; /* not fully buffered */
      mm.payload.p = io->buf;
      mm.payload.len = len;
6494

6495
      nc->handler(nc, MG_MQTT_EVENT_BASE + mm.cmd, &mm);
6496

6497
      if (mm.topic) {
6498
        MG_FREE(mm.topic);
6499 6500
      }
      mbuf_remove(io, mm.payload.len);
6501 6502
      break;
  }
6503 6504
}

6505 6506
void mg_set_protocol_mqtt(struct mg_connection *nc) {
  nc->proto_handler = mqtt_handler;
Sergey Lyubka's avatar
Sergey Lyubka committed
6507 6508
}

6509 6510 6511
void mg_send_mqtt_handshake(struct mg_connection *nc, const char *client_id) {
  static struct mg_send_mqtt_handshake_opts opts;
  mg_send_mqtt_handshake_opt(nc, client_id, opts);
Sergey Lyubka's avatar
Sergey Lyubka committed
6512 6513
}

6514 6515
void mg_send_mqtt_handshake_opt(struct mg_connection *nc, const char *client_id,
                                struct mg_send_mqtt_handshake_opts opts) {
6516
  uint8_t header = MG_MQTT_CMD_CONNECT << 4;
6517 6518 6519
  uint8_t rem_len;
  uint16_t keep_alive;
  uint16_t client_id_len;
Sergey Lyubka's avatar
Sergey Lyubka committed
6520

6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534
  /*
   * 9: version_header(len, magic_string, version_number), 1: flags, 2:
   * keep-alive timer,
   * 2: client_identifier_len, n: client_id
   */
  rem_len = 9 + 1 + 2 + 2 + strlen(client_id);

  mg_send(nc, &header, 1);
  mg_send(nc, &rem_len, 1);
  mg_send(nc, "\00\06MQIsdp\03", 9);
  mg_send(nc, &opts.flags, 1);

  if (opts.keep_alive == 0) {
    opts.keep_alive = 60;
6535
  }
6536 6537 6538 6539 6540 6541
  keep_alive = htons(opts.keep_alive);
  mg_send(nc, &keep_alive, 2);

  client_id_len = htons(strlen(client_id));
  mg_send(nc, &client_id_len, 2);
  mg_send(nc, client_id, strlen(client_id));
6542 6543
}

6544 6545 6546 6547
static void mg_mqtt_prepend_header(struct mg_connection *nc, uint8_t cmd,
                                   uint8_t flags, size_t len) {
  size_t off = nc->send_mbuf.len - len;
  uint8_t header = cmd << 4 | (uint8_t) flags;
6548

6549 6550
  uint8_t buf[1 + sizeof(size_t)];
  uint8_t *vlen = &buf[1];
6551

6552
  assert(nc->send_mbuf.len >= len);
6553

6554
  buf[0] = header;
6555

6556 6557 6558 6559 6560 6561 6562
  /* mqtt variable length encoding */
  do {
    *vlen = len % 0x80;
    len /= 0x80;
    if (len > 0) *vlen |= 0x80;
    vlen++;
  } while (len > 0);
6563

6564
  mbuf_insert(&nc->send_mbuf, off, buf, vlen - buf);
6565 6566
}

6567 6568 6569 6570
void mg_mqtt_publish(struct mg_connection *nc, const char *topic,
                     uint16_t message_id, int flags, const void *data,
                     size_t len) {
  size_t old_len = nc->send_mbuf.len;
6571

6572 6573
  uint16_t topic_len = htons(strlen(topic));
  uint16_t message_id_net = htons(message_id);
6574

6575 6576
  mg_send(nc, &topic_len, 2);
  mg_send(nc, topic, strlen(topic));
6577
  if (MG_MQTT_GET_QOS(flags) > 0) {
6578
    mg_send(nc, &message_id_net, 2);
6579
  }
6580
  mg_send(nc, data, len);
6581

6582
  mg_mqtt_prepend_header(nc, MG_MQTT_CMD_PUBLISH, flags,
6583
                         nc->send_mbuf.len - old_len);
6584 6585
}

6586 6587 6588 6589
void mg_mqtt_subscribe(struct mg_connection *nc,
                       const struct mg_mqtt_topic_expression *topics,
                       size_t topics_len, uint16_t message_id) {
  size_t old_len = nc->send_mbuf.len;
6590

6591 6592
  uint16_t message_id_n = htons(message_id);
  size_t i;
6593

6594 6595 6596 6597 6598 6599
  mg_send(nc, (char *) &message_id_n, 2);
  for (i = 0; i < topics_len; i++) {
    uint16_t topic_len_n = htons(strlen(topics[i].topic));
    mg_send(nc, &topic_len_n, 2);
    mg_send(nc, topics[i].topic, strlen(topics[i].topic));
    mg_send(nc, &topics[i].qos, 1);
6600 6601
  }

6602
  mg_mqtt_prepend_header(nc, MG_MQTT_CMD_SUBSCRIBE, MG_MQTT_QOS(1),
6603
                         nc->send_mbuf.len - old_len);
6604 6605
}

6606 6607 6608 6609 6610 6611
int mg_mqtt_next_subscribe_topic(struct mg_mqtt_message *msg,
                                 struct mg_str *topic, uint8_t *qos, int pos) {
  unsigned char *buf = (unsigned char *) msg->payload.p + pos;
  if ((size_t) pos >= msg->payload.len) {
    return -1;
  }
6612

6613 6614 6615 6616 6617
  topic->len = buf[0] << 8 | buf[1];
  topic->p = (char *) buf + 2;
  *qos = buf[2 + topic->len];
  return pos + 2 + topic->len + 1;
}
6618

6619 6620 6621
void mg_mqtt_unsubscribe(struct mg_connection *nc, char **topics,
                         size_t topics_len, uint16_t message_id) {
  size_t old_len = nc->send_mbuf.len;
6622

6623 6624
  uint16_t message_id_n = htons(message_id);
  size_t i;
6625

6626 6627 6628 6629 6630
  mg_send(nc, (char *) &message_id_n, 2);
  for (i = 0; i < topics_len; i++) {
    uint16_t topic_len_n = htons(strlen(topics[i]));
    mg_send(nc, &topic_len_n, 2);
    mg_send(nc, topics[i], strlen(topics[i]));
6631 6632
  }

6633
  mg_mqtt_prepend_header(nc, MG_MQTT_CMD_UNSUBSCRIBE, MG_MQTT_QOS(1),
6634
                         nc->send_mbuf.len - old_len);
6635 6636
}

6637 6638 6639 6640
void mg_mqtt_connack(struct mg_connection *nc, uint8_t return_code) {
  uint8_t unused = 0;
  mg_send(nc, &unused, 1);
  mg_send(nc, &return_code, 1);
6641
  mg_mqtt_prepend_header(nc, MG_MQTT_CMD_CONNACK, 0, 2);
6642
}
6643

6644 6645 6646 6647 6648 6649 6650 6651 6652
/*
 * Sends a command which contains only a `message_id` and a QoS level of 1.
 *
 * Helper function.
 */
static void mg_send_mqtt_short_command(struct mg_connection *nc, uint8_t cmd,
                                       uint16_t message_id) {
  uint16_t message_id_net = htons(message_id);
  mg_send(nc, &message_id_net, 2);
6653
  mg_mqtt_prepend_header(nc, cmd, MG_MQTT_QOS(1), 2);
6654
}
6655

6656
void mg_mqtt_puback(struct mg_connection *nc, uint16_t message_id) {
6657
  mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBACK, message_id);
6658 6659
}

6660
void mg_mqtt_pubrec(struct mg_connection *nc, uint16_t message_id) {
6661
  mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBREC, message_id);
6662
}
6663

6664
void mg_mqtt_pubrel(struct mg_connection *nc, uint16_t message_id) {
6665
  mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBREL, message_id);
6666
}
6667

6668
void mg_mqtt_pubcomp(struct mg_connection *nc, uint16_t message_id) {
6669
  mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBCOMP, message_id);
6670
}
6671

6672 6673 6674 6675 6676 6677 6678 6679
void mg_mqtt_suback(struct mg_connection *nc, uint8_t *qoss, size_t qoss_len,
                    uint16_t message_id) {
  size_t i;
  uint16_t message_id_net = htons(message_id);
  mg_send(nc, &message_id_net, 2);
  for (i = 0; i < qoss_len; i++) {
    mg_send(nc, &qoss[i], 1);
  }
6680
  mg_mqtt_prepend_header(nc, MG_MQTT_CMD_SUBACK, MG_MQTT_QOS(1), 2 + qoss_len);
6681 6682
}

6683
void mg_mqtt_unsuback(struct mg_connection *nc, uint16_t message_id) {
6684
  mg_send_mqtt_short_command(nc, MG_MQTT_CMD_UNSUBACK, message_id);
6685
}
6686

6687
void mg_mqtt_ping(struct mg_connection *nc) {
6688
  mg_mqtt_prepend_header(nc, MG_MQTT_CMD_PINGREQ, 0, 0);
6689
}
6690

6691
void mg_mqtt_pong(struct mg_connection *nc) {
6692
  mg_mqtt_prepend_header(nc, MG_MQTT_CMD_PINGRESP, 0, 0);
6693
}
6694

6695
void mg_mqtt_disconnect(struct mg_connection *nc) {
6696
  mg_mqtt_prepend_header(nc, MG_MQTT_CMD_DISCONNECT, 0, 0);
6697 6698
}

6699
#endif /* MG_DISABLE_MQTT */
6700 6701 6702 6703 6704 6705 6706 6707
#ifdef NS_MODULE_LINES
#line 1 "src/mqtt-broker.c"
/**/
#endif
/*
 * Copyright (c) 2014 Cesanta Software Limited
 * All rights reserved
 */
6708

6709 6710
/* Amalgamated: #include "internal.h" */

6711
#ifdef MG_ENABLE_MQTT_BROKER
6712 6713 6714 6715 6716 6717 6718 6719

static void mg_mqtt_session_init(struct mg_mqtt_broker *brk,
                                 struct mg_mqtt_session *s,
                                 struct mg_connection *nc) {
  s->brk = brk;
  s->subscriptions = NULL;
  s->num_subscriptions = 0;
  s->nc = nc;
6720 6721
}

6722 6723 6724 6725 6726 6727
static void mg_mqtt_add_session(struct mg_mqtt_session *s) {
  s->next = s->brk->sessions;
  s->brk->sessions = s;
  s->prev = NULL;
  if (s->next != NULL) s->next->prev = s;
}
6728

6729 6730 6731 6732 6733
static void mg_mqtt_remove_session(struct mg_mqtt_session *s) {
  if (s->prev == NULL) s->brk->sessions = s->next;
  if (s->prev) s->prev->next = s->next;
  if (s->next) s->next->prev = s->prev;
}
6734

6735 6736 6737
static void mg_mqtt_destroy_session(struct mg_mqtt_session *s) {
  size_t i;
  for (i = 0; i < s->num_subscriptions; i++) {
6738
    MG_FREE((void *) s->subscriptions[i].topic);
6739
  }
6740
  MG_FREE(s);
6741
}
6742

6743 6744 6745
static void mg_mqtt_close_session(struct mg_mqtt_session *s) {
  mg_mqtt_remove_session(s);
  mg_mqtt_destroy_session(s);
6746 6747
}

6748 6749 6750 6751
void mg_mqtt_broker_init(struct mg_mqtt_broker *brk, void *user_data) {
  brk->sessions = NULL;
  brk->user_data = user_data;
}
6752

6753 6754 6755 6756 6757
static void mg_mqtt_broker_handle_connect(struct mg_mqtt_broker *brk,
                                          struct mg_connection *nc) {
  struct mg_mqtt_session *s = (struct mg_mqtt_session *) malloc(sizeof *s);
  if (s == NULL) {
    /* LCOV_EXCL_START */
6758
    mg_mqtt_connack(nc, MG_EV_MQTT_CONNACK_SERVER_UNAVAILABLE);
6759 6760
    return;
    /* LCOV_EXCL_STOP */
6761 6762
  }

6763
  /* TODO(mkm): check header (magic and version) */
6764

6765 6766 6767 6768
  mg_mqtt_session_init(brk, s, nc);
  s->user_data = nc->user_data;
  nc->user_data = s;
  mg_mqtt_add_session(s);
6769

6770
  mg_mqtt_connack(nc, MG_EV_MQTT_CONNACK_ACCEPTED);
6771 6772
}

6773 6774 6775 6776 6777 6778 6779 6780 6781
static void mg_mqtt_broker_handle_subscribe(struct mg_connection *nc,
                                            struct mg_mqtt_message *msg) {
  struct mg_mqtt_session *ss = (struct mg_mqtt_session *) nc->user_data;
  uint8_t qoss[512];
  size_t qoss_len = 0;
  struct mg_str topic;
  uint8_t qos;
  int pos;
  struct mg_mqtt_topic_expression *te;
6782

6783 6784 6785
  for (pos = 0;
       (pos = mg_mqtt_next_subscribe_topic(msg, &topic, &qos, pos)) != -1;) {
    qoss[qoss_len++] = qos;
6786
  }
6787

6788 6789 6790 6791 6792 6793 6794 6795 6796
  ss->subscriptions = (struct mg_mqtt_topic_expression *) realloc(
      ss->subscriptions, sizeof(*ss->subscriptions) * qoss_len);
  for (pos = 0;
       (pos = mg_mqtt_next_subscribe_topic(msg, &topic, &qos, pos)) != -1;
       ss->num_subscriptions++) {
    te = &ss->subscriptions[ss->num_subscriptions];
    te->topic = (char *) malloc(topic.len + 1);
    te->qos = qos;
    strncpy((char *) te->topic, topic.p, topic.len + 1);
6797 6798
  }

6799
  mg_mqtt_suback(nc, qoss, qoss_len, msg->message_id);
6800
}
6801

Sergey Lyubka's avatar
Sergey Lyubka committed
6802
/*
6803
 * Matches a topic against a topic expression
Sergey Lyubka's avatar
Sergey Lyubka committed
6804
 *
6805
 * See http://goo.gl/iWk21X
Sergey Lyubka's avatar
Sergey Lyubka committed
6806
 *
6807
 * Returns 1 if it matches; 0 otherwise.
Sergey Lyubka's avatar
Sergey Lyubka committed
6808
 */
6809 6810 6811 6812 6813
static int mg_mqtt_match_topic_expression(const char *exp, const char *topic) {
  /* TODO(mkm): implement real matching */
  int len = strlen(exp);
  if (strchr(exp, '#')) {
    len -= 2;
6814
  }
6815
  return strncmp(exp, topic, len) == 0;
6816 6817
}

6818 6819 6820 6821
static void mg_mqtt_broker_handle_publish(struct mg_mqtt_broker *brk,
                                          struct mg_mqtt_message *msg) {
  struct mg_mqtt_session *s;
  size_t i;
6822

6823 6824 6825 6826 6827 6828 6829 6830 6831 6832
  for (s = mg_mqtt_next(brk, NULL); s != NULL; s = mg_mqtt_next(brk, s)) {
    for (i = 0; i < s->num_subscriptions; i++) {
      if (mg_mqtt_match_topic_expression(s->subscriptions[i].topic,
                                         msg->topic)) {
        mg_mqtt_publish(s->nc, msg->topic, 0, 0, msg->payload.p,
                        msg->payload.len);
        break;
      }
    }
  }
6833 6834
}

6835 6836 6837
void mg_mqtt_broker(struct mg_connection *nc, int ev, void *data) {
  struct mg_mqtt_message *msg = (struct mg_mqtt_message *) data;
  struct mg_mqtt_broker *brk;
6838

6839 6840 6841 6842 6843
  if (nc->listener) {
    brk = (struct mg_mqtt_broker *) nc->listener->user_data;
  } else {
    brk = (struct mg_mqtt_broker *) nc->user_data;
  }
6844

6845
  switch (ev) {
6846
    case MG_EV_ACCEPT:
6847 6848
      mg_set_protocol_mqtt(nc);
      break;
6849
    case MG_EV_MQTT_CONNECT:
6850 6851
      mg_mqtt_broker_handle_connect(brk, nc);
      break;
6852
    case MG_EV_MQTT_SUBSCRIBE:
6853 6854
      mg_mqtt_broker_handle_subscribe(nc, msg);
      break;
6855
    case MG_EV_MQTT_PUBLISH:
6856 6857
      mg_mqtt_broker_handle_publish(brk, msg);
      break;
6858
    case MG_EV_CLOSE:
6859 6860 6861 6862 6863 6864
      if (nc->listener) {
        mg_mqtt_close_session((struct mg_mqtt_session *) nc->user_data);
      }
      break;
  }
}
6865

6866 6867 6868 6869
struct mg_mqtt_session *mg_mqtt_next(struct mg_mqtt_broker *brk,
                                     struct mg_mqtt_session *s) {
  return s == NULL ? brk->sessions : s->next;
}
6870

6871
#endif /* MG_ENABLE_MQTT_BROKER */
6872 6873 6874 6875 6876 6877 6878 6879
#ifdef NS_MODULE_LINES
#line 1 "src/dns.c"
/**/
#endif
/*
 * Copyright (c) 2014 Cesanta Software Limited
 * All rights reserved
 */
6880

6881
#ifndef MG_DISABLE_DNS
6882

6883
/* Amalgamated: #include "internal.h" */
6884

6885
#define MAX_DNS_PACKET_LEN 2048
6886

6887
static int mg_dmg_tid = 0xa0;
6888

6889 6890 6891 6892 6893 6894 6895 6896
struct mg_dmg_header {
  uint16_t transaction_id;
  uint16_t flags;
  uint16_t num_questions;
  uint16_t num_answers;
  uint16_t num_authority_prs;
  uint16_t num_other_prs;
};
6897

6898 6899 6900 6901
struct mg_dmg_resource_record *mg_dmg_next_record(
    struct mg_dmg_message *msg, int query,
    struct mg_dmg_resource_record *prev) {
  struct mg_dmg_resource_record *rr;
6902

6903 6904 6905 6906
  for (rr = (prev == NULL ? msg->answers : prev + 1);
       rr - msg->answers < msg->num_answers; rr++) {
    if (rr->rtype == query) {
      return rr;
6907 6908
    }
  }
6909 6910
  return NULL;
}
6911

6912 6913 6914 6915
int mg_dmg_parse_record_data(struct mg_dmg_message *msg,
                             struct mg_dmg_resource_record *rr, void *data,
                             size_t data_len) {
  switch (rr->rtype) {
6916
    case MG_DNS_A_RECORD:
6917 6918 6919 6920 6921 6922 6923 6924
      if (data_len < sizeof(struct in_addr)) {
        return -1;
      }
      if (rr->rdata.p + data_len > msg->pkt.p + msg->pkt.len) {
        return -1;
      }
      memcpy(data, rr->rdata.p, data_len);
      return 0;
6925 6926
#ifdef MG_ENABLE_IPV6
    case MG_DNS_AAAA_RECORD:
6927 6928 6929 6930 6931 6932
      if (data_len < sizeof(struct in6_addr)) {
        return -1; /* LCOV_EXCL_LINE */
      }
      memcpy(data, rr->rdata.p, data_len);
      return 0;
#endif
6933
    case MG_DNS_CNAME_RECORD:
6934 6935
      mg_dmg_uncompress_name(msg, &rr->rdata, (char *) data, data_len);
      return 0;
6936 6937
  }

6938
  return -1;
6939 6940
}

6941 6942 6943
int mg_dmg_insert_header(struct mbuf *io, size_t pos,
                         struct mg_dmg_message *msg) {
  struct mg_dmg_header header;
6944

6945 6946 6947 6948 6949
  memset(&header, 0, sizeof(header));
  header.transaction_id = msg->transaction_id;
  header.flags = htons(msg->flags);
  header.num_questions = htons(msg->num_questions);
  header.num_answers = htons(msg->num_answers);
6950

6951 6952
  return mbuf_insert(io, pos, &header, sizeof(header));
}
6953

6954 6955 6956
int mg_dmg_copy_body(struct mbuf *io, struct mg_dmg_message *msg) {
  return mbuf_append(io, msg->pkt.p + sizeof(struct mg_dmg_header),
                     msg->pkt.len - sizeof(struct mg_dmg_header));
6957 6958
}

6959 6960 6961 6962 6963 6964 6965 6966 6967
static int mg_dmg_encode_name(struct mbuf *io, const char *name, size_t len) {
  const char *s;
  unsigned char n;
  size_t pos = io->len;

  do {
    if ((s = strchr(name, '.')) == NULL) {
      s = name + len;
    }
6968

6969 6970 6971 6972 6973 6974
    if (s - name > 127) {
      return -1; /* TODO(mkm) cover */
    }
    n = s - name;           /* chunk length */
    mbuf_append(io, &n, 1); /* send length */
    mbuf_append(io, name, n);
6975

6976 6977 6978
    if (*s == '.') {
      n++;
    }
6979

6980 6981 6982 6983
    name += n;
    len -= n;
  } while (*s != '\0');
  mbuf_append(io, "\0", 1); /* Mark end of host name */
6984

6985 6986
  return io->len - pos;
}
6987

6988 6989 6990 6991 6992 6993
int mg_dmg_encode_record(struct mbuf *io, struct mg_dmg_resource_record *rr,
                         const char *name, size_t nlen, const void *rdata,
                         size_t rlen) {
  size_t pos = io->len;
  uint16_t u16;
  uint32_t u32;
6994

6995
  if (rr->kind == MG_DNS_INVALID_RECORD) {
6996
    return -1; /* LCOV_EXCL_LINE */
6997 6998
  }

6999 7000 7001
  if (mg_dmg_encode_name(io, name, nlen) == -1) {
    return -1;
  }
7002

7003 7004 7005 7006
  u16 = htons(rr->rtype);
  mbuf_append(io, &u16, 2);
  u16 = htons(rr->rclass);
  mbuf_append(io, &u16, 2);
7007

7008
  if (rr->kind == MG_DNS_ANSWER) {
7009 7010
    u32 = htonl(rr->ttl);
    mbuf_append(io, &u32, 4);
7011

7012
    if (rr->rtype == MG_DNS_CNAME_RECORD) {
7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028
      int clen;
      /* fill size after encoding */
      size_t off = io->len;
      mbuf_append(io, &u16, 2);
      if ((clen = mg_dmg_encode_name(io, (const char *) rdata, rlen)) == -1) {
        return -1;
      }
      u16 = clen;
      io->buf[off] = u16 >> 8;
      io->buf[off + 1] = u16 & 0xff;
    } else {
      u16 = htons(rlen);
      mbuf_append(io, &u16, 2);
      mbuf_append(io, rdata, rlen);
    }
  }
7029

7030
  return io->len - pos;
7031 7032
}

7033 7034 7035
void mg_send_dmg_query(struct mg_connection *nc, const char *name,
                       int query_type) {
  struct mg_dmg_message *msg =
7036
      (struct mg_dmg_message *) MG_CALLOC(1, sizeof(*msg));
7037 7038
  struct mbuf pkt;
  struct mg_dmg_resource_record *rr = &msg->questions[0];
7039

7040
  DBG(("%s %d", name, query_type));
7041

7042
  mbuf_init(&pkt, MAX_DNS_PACKET_LEN);
7043

7044 7045 7046
  msg->transaction_id = ++mg_dmg_tid;
  msg->flags = 0x100;
  msg->num_questions = 1;
7047

7048
  mg_dmg_insert_header(&pkt, 0, msg);
7049

7050 7051
  rr->rtype = query_type;
  rr->rclass = 1; /* Class: inet */
7052
  rr->kind = MG_DNS_QUESTION;
7053

7054 7055 7056
  if (mg_dmg_encode_record(&pkt, rr, name, strlen(name), NULL, 0) == -1) {
    /* TODO(mkm): return an error code */
    goto cleanup; /* LCOV_EXCL_LINE */
7057
  }
7058

7059
  /* TCP DNS requires messages to be prefixed with len */
7060
  if (!(nc->flags & MG_F_UDP)) {
7061 7062 7063 7064 7065 7066 7067 7068
    uint16_t len = htons(pkt.len);
    mbuf_insert(&pkt, 0, &len, 2);
  }

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

cleanup:
7069
  MG_FREE(msg);
7070 7071
}

7072 7073 7074 7075 7076
static unsigned char *mg_parse_dmg_resource_record(
    unsigned char *data, unsigned char *end, struct mg_dmg_resource_record *rr,
    int reply) {
  unsigned char *name = data;
  int chunk_len, data_len;
7077

7078 7079 7080 7081 7082 7083
  while (data < end && (chunk_len = *data)) {
    if (((unsigned char *) data)[0] & 0xc0) {
      data += 1;
      break;
    }
    data += chunk_len + 1;
7084
  }
7085

7086 7087
  rr->name.p = (char *) name;
  rr->name.len = data - name + 1;
7088

7089 7090 7091 7092
  data++;
  if (data > end - 4) {
    return data;
  }
7093

7094 7095
  rr->rtype = data[0] << 8 | data[1];
  data += 2;
7096

7097 7098
  rr->rclass = data[0] << 8 | data[1];
  data += 2;
7099

7100
  rr->kind = reply ? MG_DNS_ANSWER : MG_DNS_QUESTION;
7101 7102 7103
  if (reply) {
    if (data >= end - 6) {
      return data;
7104
    }
7105

7106 7107 7108
    rr->ttl = (uint32_t) data[0] << 24 | (uint32_t) data[1] << 16 |
              data[2] << 8 | data[3];
    data += 4;
Sergey Lyubka's avatar
Sergey Lyubka committed
7109

7110 7111
    data_len = *data << 8 | *(data + 1);
    data += 2;
7112

7113 7114 7115
    rr->rdata.p = (char *) data;
    rr->rdata.len = data_len;
    data += data_len;
7116
  }
7117
  return data;
7118 7119
}

7120 7121 7122 7123 7124 7125 7126
int mg_parse_dns(const char *buf, int len, struct mg_dmg_message *msg) {
  struct mg_dmg_header *header = (struct mg_dmg_header *) buf;
  unsigned char *data = (unsigned char *) buf + sizeof(*header);
  unsigned char *end = (unsigned char *) buf + len;
  int i;
  msg->pkt.p = buf;
  msg->pkt.len = len;
7127

7128 7129
  if (len < (int) sizeof(*header)) {
    return -1; /* LCOV_EXCL_LINE */
7130 7131
  }

7132 7133 7134 7135
  msg->transaction_id = header->transaction_id;
  msg->flags = ntohs(header->flags);
  msg->num_questions = ntohs(header->num_questions);
  msg->num_answers = ntohs(header->num_answers);
7136

7137 7138 7139 7140
  for (i = 0; i < msg->num_questions && i < (int) ARRAY_SIZE(msg->questions);
       i++) {
    data = mg_parse_dmg_resource_record(data, end, &msg->questions[i], 0);
  }
7141

7142 7143
  for (i = 0; i < msg->num_answers && i < (int) ARRAY_SIZE(msg->answers); i++) {
    data = mg_parse_dmg_resource_record(data, end, &msg->answers[i], 1);
7144
  }
7145 7146

  return 0;
7147 7148
}

7149 7150 7151 7152 7153 7154
size_t mg_dmg_uncompress_name(struct mg_dmg_message *msg, struct mg_str *name,
                              char *dst, int dst_len) {
  int chunk_len;
  char *old_dst = dst;
  const unsigned char *data = (unsigned char *) name->p;
  const unsigned char *end = (unsigned char *) msg->pkt.p + msg->pkt.len;
7155

7156 7157
  if (data >= end) {
    return 0;
7158 7159
  }

7160 7161 7162 7163 7164 7165 7166 7167 7168 7169
  while ((chunk_len = *data++)) {
    int leeway = dst_len - (dst - old_dst);
    if (data >= end) {
      return 0;
    }

    if (chunk_len & 0xc0) {
      uint16_t off = (data[-1] & (~0xc0)) << 8 | data[0];
      if (off >= msg->pkt.len) {
        return 0;
7170
      }
7171 7172
      data = (unsigned char *) msg->pkt.p + off;
      continue;
7173
    }
7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189
    if (chunk_len > leeway) {
      chunk_len = leeway;
    }

    if (data + chunk_len >= end) {
      return 0;
    }

    memcpy(dst, data, chunk_len);
    data += chunk_len;
    dst += chunk_len;
    leeway -= chunk_len;
    if (leeway == 0) {
      return dst - old_dst;
    }
    *dst++ = '.';
7190 7191
  }

7192 7193
  if (dst != old_dst) {
    *--dst = 0;
7194
  }
7195
  return dst - old_dst;
7196 7197
}

7198 7199 7200
static void dmg_handler(struct mg_connection *nc, int ev, void *ev_data) {
  struct mbuf *io = &nc->recv_mbuf;
  struct mg_dmg_message msg;
7201

7202 7203
  /* Pass low-level events to the user handler */
  nc->handler(nc, ev, ev_data);
7204

7205
  switch (ev) {
7206 7207
    case MG_EV_RECV:
      if (!(nc->flags & MG_F_UDP)) {
7208 7209 7210 7211 7212 7213 7214
        mbuf_remove(&nc->recv_mbuf, 2);
      }
      if (mg_parse_dns(nc->recv_mbuf.buf, nc->recv_mbuf.len, &msg) == -1) {
        /* reply + recursion allowed + format error */
        memset(&msg, 0, sizeof(msg));
        msg.flags = 0x8081;
        mg_dmg_insert_header(io, 0, &msg);
7215
        if (!(nc->flags & MG_F_UDP)) {
7216 7217 7218 7219 7220 7221
          uint16_t len = htons(io->len);
          mbuf_insert(io, 0, &len, 2);
        }
        mg_send(nc, io->buf, io->len);
      } else {
        /* Call user handler with parsed message */
7222
        nc->handler(nc, MG_DNS_MESSAGE, &msg);
7223 7224 7225
      }
      mbuf_remove(io, io->len);
      break;
Daniel O'Connell's avatar
Daniel O'Connell committed
7226 7227 7228
  }
}

7229 7230
void mg_set_protocol_dns(struct mg_connection *nc) {
  nc->proto_handler = dmg_handler;
7231
}
7232

7233
#endif /* MG_DISABLE_DNS */
7234 7235 7236
#ifdef NS_MODULE_LINES
#line 1 "src/dns-server.c"
/**/
7237
#endif
7238 7239 7240 7241
/*
 * Copyright (c) 2014 Cesanta Software Limited
 * All rights reserved
 */
7242

7243
#ifdef MG_ENABLE_DNS_SERVER
Sergey Lyubka's avatar
Sergey Lyubka committed
7244

7245
/* Amalgamated: #include "internal.h" */
Sergey Lyubka's avatar
Sergey Lyubka committed
7246

7247 7248 7249 7250 7251 7252
struct mg_dmg_reply mg_dmg_create_reply(struct mbuf *io,
                                        struct mg_dmg_message *msg) {
  struct mg_dmg_reply rep;
  rep.msg = msg;
  rep.io = io;
  rep.start = io->len;
Sergey Lyubka's avatar
Sergey Lyubka committed
7253

7254 7255 7256
  /* reply + recursion allowed */
  msg->flags |= 0x8080;
  mg_dmg_copy_body(io, msg);
Sergey Lyubka's avatar
Sergey Lyubka committed
7257

7258 7259 7260
  msg->num_answers = 0;
  return rep;
}
7261

7262 7263 7264
int mg_dmg_send_reply(struct mg_connection *nc, struct mg_dmg_reply *r) {
  size_t sent = r->io->len - r->start;
  mg_dmg_insert_header(r->io, r->start, r->msg);
7265
  if (!(nc->flags & MG_F_UDP)) {
7266 7267
    uint16_t len = htons(sent);
    mbuf_insert(r->io, r->start, &len, 2);
Sergey Lyubka's avatar
Sergey Lyubka committed
7268
  }
7269

7270
  if (&nc->send_mbuf != r->io || nc->flags & MG_F_UDP) {
7271 7272
    sent = mg_send(nc, r->io->buf + r->start, r->io->len - r->start);
    r->io->len = r->start;
7273
  }
7274
  return sent;
7275 7276
}

7277 7278 7279 7280 7281 7282 7283
int mg_dmg_reply_record(struct mg_dmg_reply *reply,
                        struct mg_dmg_resource_record *question,
                        const char *name, int rtype, int ttl, const void *rdata,
                        size_t rdata_len) {
  struct mg_dmg_message *msg = (struct mg_dmg_message *) reply->msg;
  char rname[512];
  struct mg_dmg_resource_record *ans = &msg->answers[msg->num_answers];
7284
  if (msg->num_answers >= MG_MAX_DNS_ANSWERS) {
7285 7286
    return -1; /* LCOV_EXCL_LINE */
  }
7287

7288 7289 7290 7291
  if (name == NULL) {
    name = rname;
    rname[511] = 0;
    mg_dmg_uncompress_name(msg, &question->name, rname, sizeof(rname) - 1);
7292 7293
  }

7294
  *ans = *question;
7295
  ans->kind = MG_DNS_ANSWER;
7296 7297
  ans->rtype = rtype;
  ans->ttl = ttl;
7298

7299 7300 7301 7302
  if (mg_dmg_encode_record(reply->io, ans, name, strlen(name), rdata,
                           rdata_len) == -1) {
    return -1; /* LCOV_EXCL_LINE */
  };
7303

7304 7305 7306
  msg->num_answers++;
  return 0;
}
7307

7308
#endif /* MG_ENABLE_DNS_SERVER */
7309 7310 7311
#ifdef NS_MODULE_LINES
#line 1 "src/resolv.c"
/**/
7312
#endif
7313 7314 7315 7316
/*
 * Copyright (c) 2014 Cesanta Software Limited
 * All rights reserved
 */
7317

7318
#ifndef MG_DISABLE_RESOLVER
7319

7320
/* Amalgamated: #include "internal.h" */
7321

7322 7323
#ifndef MG_DEFAULT_NAMESERVER
#define MG_DEFAULT_NAMESERVER "8.8.8.8"
7324 7325
#endif

7326
static const char *mg_default_dmg_server = "udp://" MG_DEFAULT_NAMESERVER ":53";
7327

7328
MG_INTERNAL char mg_dmg_server[256];
7329

7330 7331 7332 7333 7334 7335 7336
struct mg_resolve_async_request {
  char name[1024];
  int query;
  mg_resolve_callback_t callback;
  void *data;
  time_t timeout;
  int max_retries;
7337

7338 7339 7340 7341
  /* state */
  time_t last_time;
  int retries;
};
7342

7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388
/*
 * Find what nameserver to use.
 *
 * Return 0 if OK, -1 if error
 */
static int mg_get_ip_address_of_nameserver(char *name, size_t name_len) {
  int ret = -1;

#ifdef _WIN32
  int i;
  LONG err;
  HKEY hKey, hSub;
  char subkey[512], value[128],
      *key = "SYSTEM\\ControlSet001\\Services\\Tcpip\\Parameters\\Interfaces";

  if ((err = RegOpenKey(HKEY_LOCAL_MACHINE, key, &hKey)) != ERROR_SUCCESS) {
    fprintf(stderr, "cannot open reg key %s: %d\n", key, err);
    ret = -1;
  } else {
    for (ret = -1, i = 0;
         RegEnumKey(hKey, i, subkey, sizeof(subkey)) == ERROR_SUCCESS; i++) {
      DWORD type, len = sizeof(value);
      if (RegOpenKey(hKey, subkey, &hSub) == ERROR_SUCCESS &&
          (RegQueryValueEx(hSub, "NameServer", 0, &type, (void *) value,
                           &len) == ERROR_SUCCESS ||
           RegQueryValueEx(hSub, "DhcpNameServer", 0, &type, (void *) value,
                           &len) == ERROR_SUCCESS)) {
        /*
         * See https://github.com/cesanta/mongoose/issues/176
         * The value taken from the registry can be empty, a single
         * IP address, or multiple IP addresses separated by comma.
         * If it's empty, check the next interface.
         * If it's multiple IP addresses, take the first one.
         */
        char *comma = strchr(value, ',');
        if (value[0] == '\0') {
          continue;
        }
        if (comma != NULL) {
          *comma = '\0';
        }
        snprintf(name, name_len, "udp://%s:53", value);
        ret = 0;
        RegCloseKey(hSub);
        break;
      }
7389
    }
7390
    RegCloseKey(hKey);
7391
  }
7392
#elif !defined(MG_DISABLE_FILESYSTEM)
7393 7394
  FILE *fp;
  char line[512];
7395

7396 7397
  if ((fp = fopen("/etc/resolv.conf", "r")) == NULL) {
    ret = -1;
Daniel O'Connell's avatar
Daniel O'Connell committed
7398
  } else {
7399 7400 7401 7402 7403 7404 7405 7406 7407 7408
    /* Try to figure out what nameserver to use */
    for (ret = -1; fgets(line, sizeof(line), fp) != NULL;) {
      char buf[256];
      if (sscanf(line, "nameserver %255[^\n\t #]s", buf) == 1) {
        snprintf(name, name_len, "udp://%s:53", buf);
        ret = 0;
        break;
      }
    }
    (void) fclose(fp);
Daniel O'Connell's avatar
Daniel O'Connell committed
7409
  }
7410 7411 7412 7413 7414
#else
  snprintf(name, name_len, "%s", mg_default_dmg_server);
#endif /* _WIN32 */

  return ret;
Sergey Lyubka's avatar
Sergey Lyubka committed
7415 7416
}

7417
int mg_resolve_from_hosts_file(const char *name, union socket_address *usa) {
7418
#ifndef MG_DISABLE_FILESYSTEM
7419 7420 7421 7422 7423 7424 7425
  /* TODO(mkm) cache /etc/hosts */
  FILE *fp;
  char line[1024];
  char *p;
  char alias[256];
  unsigned int a, b, c, d;
  int len = 0;
7426

7427 7428
  if ((fp = fopen("/etc/hosts", "r")) == NULL) {
    return -1;
Daniel O'Connell's avatar
Daniel O'Connell committed
7429 7430
  }

7431 7432 7433 7434 7435 7436
  for (; fgets(line, sizeof(line), fp) != NULL;) {
    if (line[0] == '#') continue;

    if (sscanf(line, "%u.%u.%u.%u%n", &a, &b, &c, &d, &len) == 0) {
      /* TODO(mkm): handle ipv6 */
      continue;
7437
    }
7438 7439 7440 7441 7442 7443
    for (p = line + len; sscanf(p, "%s%n", alias, &len) == 1; p += len) {
      if (strcmp(alias, name) == 0) {
        usa->sin.sin_addr.s_addr = htonl(a << 24 | b << 16 | c << 8 | d);
        fclose(fp);
        return 0;
      }
7444 7445 7446
    }
  }

7447
  fclose(fp);
7448
#endif
7449

7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462
  return -1;
}

static void mg_resolve_async_eh(struct mg_connection *nc, int ev, void *data) {
  time_t now = time(NULL);
  struct mg_resolve_async_request *req;
  struct mg_dmg_message *msg;

  DBG(("ev=%d", ev));

  req = (struct mg_resolve_async_request *) nc->user_data;

  switch (ev) {
7463 7464
    case MG_EV_CONNECT:
    case MG_EV_POLL:
7465 7466
      if (req->retries > req->max_retries) {
        req->callback(NULL, req->data);
7467 7468
        MG_FREE(req);
        nc->flags |= MG_F_CLOSE_IMMEDIATELY;
7469 7470 7471 7472 7473 7474 7475 7476
        break;
      }
      if (now - req->last_time > req->timeout) {
        mg_send_dmg_query(nc, req->name, req->query);
        req->last_time = now;
        req->retries++;
      }
      break;
7477 7478
    case MG_EV_RECV:
      msg = (struct mg_dmg_message *) MG_MALLOC(sizeof(*msg));
7479 7480 7481 7482 7483 7484
      if (mg_parse_dns(nc->recv_mbuf.buf, *(int *) data, msg) == 0 &&
          msg->num_answers > 0) {
        req->callback(msg, req->data);
      } else {
        req->callback(NULL, req->data);
      }
7485 7486 7487
      MG_FREE(req);
      nc->flags |= MG_F_CLOSE_IMMEDIATELY;
      MG_FREE(msg);
7488
      break;
7489 7490 7491
  }
}

7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507
int mg_resolve_async(struct mg_mgr *mgr, const char *name, int query,
                     mg_resolve_callback_t cb, void *data) {
  static struct mg_resolve_async_opts opts;
  return mg_resolve_async_opt(mgr, name, query, cb, data, opts);
}

int mg_resolve_async_opt(struct mg_mgr *mgr, const char *name, int query,
                         mg_resolve_callback_t cb, void *data,
                         struct mg_resolve_async_opts opts) {
  struct mg_resolve_async_request *req;
  struct mg_connection *dmg_nc;
  const char *nameserver = opts.nameserver_url;

  DBG(("%s %d", name, query));

  /* resolve with DNS */
7508
  req = (struct mg_resolve_async_request *) MG_CALLOC(1, sizeof(*req));
7509 7510
  if (req == NULL) {
    return -1;
7511
  }
7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525

  strncpy(req->name, name, sizeof(req->name));
  req->query = query;
  req->callback = cb;
  req->data = data;
  /* TODO(mkm): parse defaults out of resolve.conf */
  req->max_retries = opts.max_retries ? opts.max_retries : 2;
  req->timeout = opts.timeout ? opts.timeout : 5;

  /* Lazily initialize dns server */
  if (nameserver == NULL && mg_dmg_server[0] == '\0' &&
      mg_get_ip_address_of_nameserver(mg_dmg_server, sizeof(mg_dmg_server)) ==
          -1) {
    strncpy(mg_dmg_server, mg_default_dmg_server, sizeof(mg_dmg_server));
7526 7527
  }

7528 7529 7530
  if (nameserver == NULL) {
    nameserver = mg_dmg_server;
  }
7531

7532 7533 7534 7535
  dmg_nc = mg_connect(mgr, nameserver, mg_resolve_async_eh);
  if (dmg_nc == NULL) {
    free(req);
    return -1;
7536
  }
7537 7538 7539
  dmg_nc->user_data = req;

  return 0;
7540 7541
}

7542
#endif /* MG_DISABLE_RESOLVE */
7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564
#ifdef NS_MODULE_LINES
#line 1 "src/coap.c"
/**/
#endif
/*
 * Copyright (c) 2015 Cesanta Software Limited
 * All rights reserved
 * This software is dual-licensed: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation. For the terms of this
 * license, see <http://www.gnu.org/licenses/>.
 *
 * You are free to use this software under the terms of the GNU General
 * Public License, but WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * Alternatively, you can license this software under a commercial
 * license, as set out in <https://www.cesanta.com/license>.
 */

/* Amalgamated: #include "internal.h" */
Sergey Lyubka's avatar
Sergey Lyubka committed
7565

7566
#ifdef MG_ENABLE_COAP
Sergey Lyubka's avatar
Sergey Lyubka committed
7567

7568 7569 7570
void mg_coap_free_options(struct mg_coap_message *cm) {
  while (cm->options != NULL) {
    struct mg_coap_option *next = cm->options->next;
7571
    MG_FREE(cm->options);
7572
    cm->options = next;
Sergey Lyubka's avatar
Sergey Lyubka committed
7573
  }
7574
}
Sergey Lyubka's avatar
Sergey Lyubka committed
7575

7576 7577 7578 7579
struct mg_coap_option *mg_coap_add_option(struct mg_coap_message *cm,
                                          uint32_t number, char *value,
                                          size_t len) {
  struct mg_coap_option *new_option =
7580
      (struct mg_coap_option *) MG_CALLOC(1, sizeof(*new_option));
Sergey Lyubka's avatar
Sergey Lyubka committed
7581

7582 7583 7584
  new_option->number = number;
  new_option->value.p = value;
  new_option->value.len = len;
Sergey Lyubka's avatar
Sergey Lyubka committed
7585

7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600
  if (cm->options == NULL) {
    cm->options = cm->optiomg_tail = new_option;
  } else {
    /*
     * A very simple attention to help clients to compose options:
     * CoAP wants to see options ASC ordered.
     * Could be change by using sort in coap_compose
     */
    if (cm->optiomg_tail->number <= new_option->number) {
      /* if option is already ordered just add it */
      cm->optiomg_tail = cm->optiomg_tail->next = new_option;
    } else {
      /* looking for appropriate position */
      struct mg_coap_option *current_opt = cm->options;
      struct mg_coap_option *prev_opt = 0;
Sergey Lyubka's avatar
Sergey Lyubka committed
7601

7602 7603 7604 7605 7606 7607 7608
      while (current_opt != NULL) {
        if (current_opt->number > new_option->number) {
          break;
        }
        prev_opt = current_opt;
        current_opt = current_opt->next;
      }
7609

7610 7611 7612 7613 7614 7615 7616 7617 7618
      if (prev_opt != NULL) {
        prev_opt->next = new_option;
        new_option->next = current_opt;
      } else {
        /* insert new_option to the beginning */
        new_option->next = cm->options;
        cm->options = new_option;
      }
    }
7619 7620
  }

7621
  return new_option;
7622 7623
}

7624 7625 7626 7627 7628 7629 7630 7631
/*
 * Fills CoAP header in mg_coap_message.
 *
 * Helper function.
 */
static char *coap_parse_header(char *ptr, struct mbuf *io,
                               struct mg_coap_message *cm) {
  if (io->len < sizeof(uint32_t)) {
7632
    cm->flags |= MG_COAP_NOT_ENOUGH_DATA;
7633
    return NULL;
7634
  }
7635

7636 7637 7638 7639 7640 7641 7642
  /*
   * Version (Ver):  2-bit unsigned integer.  Indicates the CoAP version
   * number.  Implementations of this specification MUST set this field
   * to 1 (01 binary).  Other values are reserved for future versions.
   * Messages with unknown version numbers MUST be silently ignored.
   */
  if (((uint8_t) *ptr >> 6) != 1) {
7643
    cm->flags |= MG_COAP_IGNORE;
7644
    return NULL;
7645
  }
7646

7647 7648 7649 7650 7651 7652
  /*
   * Type (T):  2-bit unsigned integer.  Indicates if this message is of
   * type Confirmable (0), Non-confirmable (1), Acknowledgement (2), or
   * Reset (3).
   */
  cm->msg_type = ((uint8_t) *ptr & 0x30) >> 4;
7653
  cm->flags |= MG_COAP_MSG_TYPE_FIELD;
7654 7655 7656 7657 7658 7659 7660 7661 7662

  /*
   * Token Length (TKL):  4-bit unsigned integer.  Indicates the length of
   * the variable-length Token field (0-8 bytes).  Lengths 9-15 are
   * reserved, MUST NOT be sent, and MUST be processed as a message
   * format error.
   */
  cm->token.len = *ptr & 0x0F;
  if (cm->token.len > 8) {
7663
    cm->flags |= MG_COAP_FORMAT_ERROR;
7664
    return NULL;
7665 7666
  }

7667
  ptr++;
7668

7669 7670 7671 7672 7673 7674
  /*
   * Code:  8-bit unsigned integer, split into a 3-bit class (most
   * significant bits) and a 5-bit detail (least significant bits)
   */
  cm->code_class = (uint8_t) *ptr >> 5;
  cm->code_detail = *ptr & 0x1F;
7675
  cm->flags |= (MG_COAP_CODE_CLASS_FIELD | MG_COAP_CODE_DETAIL_FIELD);
7676

7677
  ptr++;
7678

7679 7680
  /* Message ID:  16-bit unsigned integer in network byte order. */
  cm->msg_id = (uint8_t) *ptr << 8 | (uint8_t) * (ptr + 1);
7681
  cm->flags |= MG_COAP_MSG_ID_FIELD;
7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696

  ptr += 2;

  return ptr;
}

/*
 * Fills token information in mg_coap_message.
 *
 * Helper function.
 */
static char *coap_get_token(char *ptr, struct mbuf *io,
                            struct mg_coap_message *cm) {
  if (cm->token.len != 0) {
    if (ptr + cm->token.len > io->buf + io->len) {
7697
      cm->flags |= MG_COAP_NOT_ENOUGH_DATA;
7698 7699 7700 7701
      return NULL;
    } else {
      cm->token.p = ptr;
      ptr += cm->token.len;
7702
      cm->flags |= MG_COAP_TOKEN_FIELD;
7703 7704 7705
    }
  }

7706
  return ptr;
7707 7708
}

7709 7710 7711 7712 7713 7714 7715
/*
 * Returns Option Delta or Length.
 *
 * Helper function.
 */
static int coap_get_ext_opt(char *ptr, struct mbuf *io, uint16_t *opt_info) {
  int ret = 0;
Sergey Lyubka's avatar
Sergey Lyubka committed
7716

7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737
  if (*opt_info == 13) {
    /*
     * 13:  An 8-bit unsigned integer follows the initial byte and
     * indicates the Option Delta/Length minus 13.
     */
    if (ptr < io->buf + io->len) {
      *opt_info = (uint8_t) *ptr + 13;
      ret = sizeof(uint8_t);
    } else {
      ret = -1; /* LCOV_EXCL_LINE */
    }
  } else if (*opt_info == 14) {
    /*
     * 14:  A 16-bit unsigned integer in network byte order follows the
     * initial byte and indicates the Option Delta/Length minus 269.
     */
    if (ptr + sizeof(uint8_t) < io->buf + io->len) {
      *opt_info = ((uint8_t) *ptr << 8 | (uint8_t) * (ptr + 1)) + 269;
      ret = sizeof(uint16_t);
    } else {
      ret = -1; /* LCOV_EXCL_LINE */
7738
    }
7739
  }
7740 7741

  return ret;
7742 7743
}

7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765
/*
 * Fills options in mg_coap_message.
 *
 * Helper function.
 *
 * General options format:
 * +---------------+---------------+
 * | Option Delta  | Option Length |  1 byte
 * +---------------+---------------+
 * \    Option Delta (extended)    \  0-2 bytes
 * +-------------------------------+
 * / Option Length  (extended)     \  0-2 bytes
 * +-------------------------------+
 * \         Option Value          \  0 or more bytes
 * +-------------------------------+
 */
static char *coap_get_options(char *ptr, struct mbuf *io,
                              struct mg_coap_message *cm) {
  uint16_t prev_opt = 0;

  if (ptr == io->buf + io->len) {
    /* end of packet, ok */
7766 7767
    return NULL;
  }
7768

7769 7770 7771 7772
  /* 0xFF is payload marker */
  while (ptr < io->buf + io->len && (uint8_t) *ptr != 0xFF) {
    uint16_t option_delta, option_lenght;
    int optinfo_len;
7773

7774 7775 7776 7777
    /* Option Delta:  4-bit unsigned integer */
    option_delta = ((uint8_t) *ptr & 0xF0) >> 4;
    /* Option Length:  4-bit unsigned integer */
    option_lenght = *ptr & 0x0F;
7778

7779 7780 7781 7782 7783
    if (option_delta == 15 || option_lenght == 15) {
      /*
       * 15:  Reserved for future use.  If the field is set to this value,
       * it MUST be processed as a message format error
       */
7784
      cm->flags |= MG_COAP_FORMAT_ERROR;
7785 7786
      break;
    }
7787

7788
    ptr++;
NickCis's avatar
NickCis committed
7789

7790 7791 7792
    /* check for extended option delta */
    optinfo_len = coap_get_ext_opt(ptr, io, &option_delta);
    if (optinfo_len == -1) {
7793
      cm->flags |= MG_COAP_NOT_ENOUGH_DATA; /* LCOV_EXCL_LINE */
7794 7795
      break;                                /* LCOV_EXCL_LINE */
    }
7796

7797
    ptr += optinfo_len;
7798

7799 7800 7801
    /* check or extended option lenght */
    optinfo_len = coap_get_ext_opt(ptr, io, &option_lenght);
    if (optinfo_len == -1) {
7802
      cm->flags |= MG_COAP_NOT_ENOUGH_DATA; /* LCOV_EXCL_LINE */
7803 7804
      break;                                /* LCOV_EXCL_LINE */
    }
7805

7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819
    ptr += optinfo_len;

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

    mg_coap_add_option(cm, option_delta, ptr, option_lenght);

    prev_opt = option_delta;

    if (ptr + option_lenght > io->buf + io->len) {
7820
      cm->flags |= MG_COAP_NOT_ENOUGH_DATA; /* LCOV_EXCL_LINE */
7821
      break;                                /* LCOV_EXCL_LINE */
7822
    }
7823 7824

    ptr += option_lenght;
7825
  }
7826

7827
  if ((cm->flags & MG_COAP_ERROR) != 0) {
7828 7829 7830 7831
    mg_coap_free_options(cm);
    return NULL;
  }

7832
  cm->flags |= MG_COAP_OPTIOMG_FIELD;
7833

7834 7835 7836
  if (ptr == io->buf + io->len) {
    /* end of packet, ok */
    return NULL;
7837 7838
  }

7839
  ptr++;
Sergey Lyubka's avatar
Sergey Lyubka committed
7840

7841
  return ptr;
Sergey Lyubka's avatar
Sergey Lyubka committed
7842 7843
}

7844 7845
uint32_t mg_coap_parse(struct mbuf *io, struct mg_coap_message *cm) {
  char *ptr;
Sergey Lyubka's avatar
Sergey Lyubka committed
7846

7847
  memset(cm, 0, sizeof(*cm));
Sergey Lyubka's avatar
Sergey Lyubka committed
7848

7849 7850 7851
  if ((ptr = coap_parse_header(io->buf, io, cm)) == NULL) {
    return cm->flags;
  }
Sergey Lyubka's avatar
Sergey Lyubka committed
7852

7853 7854
  if ((ptr = coap_get_token(ptr, io, cm)) == NULL) {
    return cm->flags;
Sergey Lyubka's avatar
Sergey Lyubka committed
7855 7856
  }

7857 7858
  if ((ptr = coap_get_options(ptr, io, cm)) == NULL) {
    return cm->flags;
Sergey Lyubka's avatar
Sergey Lyubka committed
7859 7860
  }

7861 7862 7863 7864
  /* the rest is payload */
  cm->payload.len = io->len - (ptr - io->buf);
  if (cm->payload.len != 0) {
    cm->payload.p = ptr;
7865
    cm->flags |= MG_COAP_PAYLOAD_FIELD;
7866
  }
Sergey Lyubka's avatar
Sergey Lyubka committed
7867

7868
  return cm->flags;
7869 7870
}

7871 7872 7873 7874 7875 7876 7877
/*
 * Calculates extended size of given Opt Number/Length in coap message.
 *
 * Helper function.
 */
static size_t coap_get_ext_opt_size(uint32_t value) {
  int ret = 0;
Sergey Lyubka's avatar
Sergey Lyubka committed
7878

7879 7880 7881 7882
  if (value >= 13 && value <= 0xFF + 13) {
    ret = sizeof(uint8_t);
  } else if (value > 0xFF + 13 && value <= 0xFFFF + 269) {
    ret = sizeof(uint16_t);
7883
  }
7884 7885

  return ret;
7886 7887
}

7888 7889 7890 7891 7892 7893 7894
/*
 * Splits given Opt Number/Length into base and ext values.
 *
 * Helper function.
 */
static int coap_split_opt(uint32_t value, uint8_t *base, uint16_t *ext) {
  int ret = 0;
7895

7896 7897 7898 7899 7900 7901 7902 7903 7904 7905
  if (value < 13) {
    *base = value;
  } else if (value >= 13 && value <= 0xFF + 13) {
    *base = 13;
    *ext = value - 13;
    ret = sizeof(uint8_t);
  } else if (value > 0xFF + 13 && value <= 0xFFFF + 269) {
    *base = 14;
    *ext = value - 269;
    ret = sizeof(uint16_t);
7906
  }
7907 7908

  return ret;
7909 7910
}

7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922
/*
 * Puts uint16_t (in network order) into given char stream.
 *
 * Helper function.
 */
static char *coap_add_uint16(char *ptr, uint16_t val) {
  *ptr = val >> 8;
  ptr++;
  *ptr = val & 0x00FF;
  ptr++;
  return ptr;
}
7923

7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934
/*
 * Puts extended value of Opt Number/Length into given char stream.
 *
 * Helper function.
 */
static char *coap_add_opt_info(char *ptr, uint16_t val, size_t len) {
  if (len == sizeof(uint8_t)) {
    *ptr = val;
    ptr++;
  } else if (len == sizeof(uint16_t)) {
    ptr = coap_add_uint16(ptr, val);
7935 7936
  }

7937 7938
  return ptr;
}
7939

7940 7941 7942 7943 7944 7945 7946 7947 7948
/*
 * Verifies given mg_coap_message and calculates message size for it.
 *
 * Helper function.
 */
static uint32_t coap_calculate_packet_size(struct mg_coap_message *cm,
                                           size_t *len) {
  struct mg_coap_option *opt;
  uint32_t prev_opt_number;
7949

7950
  *len = 4; /* header */
7951 7952
  if (cm->msg_type > MG_COAP_MSG_MAX) {
    return MG_COAP_ERROR | MG_COAP_MSG_TYPE_FIELD;
7953
  }
7954
  if (cm->token.len > 8) {
7955
    return MG_COAP_ERROR | MG_COAP_TOKEN_FIELD;
7956 7957
  }
  if (cm->code_class > 7) {
7958
    return MG_COAP_ERROR | MG_COAP_CODE_CLASS_FIELD;
7959 7960
  }
  if (cm->code_detail > 31) {
7961
    return MG_COAP_ERROR | MG_COAP_CODE_DETAIL_FIELD;
7962 7963
  }

7964 7965 7966 7967
  *len += cm->token.len;
  if (cm->payload.len != 0) {
    *len += cm->payload.len + 1; /* ... + 1; add payload marker */
  }
Sergey Lyubka's avatar
Sergey Lyubka committed
7968

7969 7970 7971 7972 7973 7974
  opt = cm->options;
  prev_opt_number = 0;
  while (opt != NULL) {
    *len += 1; /* basic delta/length */
    *len += coap_get_ext_opt_size(opt->number);
    *len += coap_get_ext_opt_size((uint32_t) opt->value.len);
Sergey Lyubka's avatar
Sergey Lyubka committed
7975
    /*
7976 7977 7978 7979
     * Current implementation performs check if
     * option_number > previous option_number and produces an error
     * TODO(alashkin): write design doc with limitations
     * May be resorting is more suitable solution.
Sergey Lyubka's avatar
Sergey Lyubka committed
7980
     */
7981 7982 7983
    if ((opt->next != NULL && opt->number > opt->next->number) ||
        opt->value.len > 0xFFFF + 269 ||
        opt->number - prev_opt_number > 0xFFFF + 269) {
7984
      return MG_COAP_ERROR | MG_COAP_OPTIOMG_FIELD;
7985
    }
7986 7987
    *len += opt->value.len;
    opt = opt->next;
7988 7989
  }

7990
  return 0;
7991 7992
}

7993 7994 7995 7996 7997
uint32_t mg_coap_compose(struct mg_coap_message *cm, struct mbuf *io) {
  struct mg_coap_option *opt;
  uint32_t res, prev_opt_number;
  size_t prev_io_len, packet_size;
  char *ptr;
7998

7999 8000 8001 8002
  res = coap_calculate_packet_size(cm, &packet_size);
  if (res != 0) {
    return res;
  }
8003

8004 8005 8006 8007
  /* saving previous lenght to handle non-empty mbuf */
  prev_io_len = io->len;
  mbuf_append(io, NULL, packet_size);
  ptr = io->buf + prev_io_len;
Sergey Lyubka's avatar
Sergey Lyubka committed
8008

8009 8010 8011 8012
  /*
   * since cm is verified, it is possible to use bits shift operator
   * without additional zeroing of unused bits
   */
8013

8014 8015 8016
  /* ver: 2 bits, msg_type: 2 bits, toklen: 4 bits */
  *ptr = (1 << 6) | (cm->msg_type << 4) | (cm->token.len);
  ptr++;
Sergey Lyubka's avatar
Sergey Lyubka committed
8017

8018 8019 8020
  /* code class: 3 bits, code detail: 5 bits */
  *ptr = (cm->code_class << 5) | (cm->code_detail);
  ptr++;
Sergey Lyubka's avatar
Sergey Lyubka committed
8021

8022
  ptr = coap_add_uint16(ptr, cm->msg_id);
Sergey Lyubka's avatar
Sergey Lyubka committed
8023

8024 8025 8026
  if (cm->token.len != 0) {
    memcpy(ptr, cm->token.p, cm->token.len);
    ptr += cm->token.len;
8027 8028
  }

8029 8030 8031 8032 8033
  opt = cm->options;
  prev_opt_number = 0;
  while (opt != NULL) {
    uint8_t delta_base = 0, length_base = 0;
    uint16_t delta_ext, length_ext;
8034

8035 8036 8037 8038
    size_t opt_delta_len =
        coap_split_opt(opt->number - prev_opt_number, &delta_base, &delta_ext);
    size_t opt_lenght_len =
        coap_split_opt((uint32_t) opt->value.len, &length_base, &length_ext);
8039

8040 8041
    *ptr = (delta_base << 4) | length_base;
    ptr++;
Sergey Lyubka's avatar
Sergey Lyubka committed
8042

8043 8044
    ptr = coap_add_opt_info(ptr, delta_ext, opt_delta_len);
    ptr = coap_add_opt_info(ptr, length_ext, opt_lenght_len);
Sergey Lyubka's avatar
Sergey Lyubka committed
8045

8046 8047 8048 8049
    if (opt->value.len != 0) {
      memcpy(ptr, opt->value.p, opt->value.len);
      ptr += opt->value.len;
    }
Sergey Lyubka's avatar
Sergey Lyubka committed
8050

8051 8052 8053
    prev_opt_number = opt->number;
    opt = opt->next;
  }
Sergey Lyubka's avatar
Sergey Lyubka committed
8054

8055 8056 8057 8058 8059
  if (cm->payload.len != 0) {
    *ptr = 0xFF;
    ptr++;
    memcpy(ptr, cm->payload.p, cm->payload.len);
  }
Sergey Lyubka's avatar
Sergey Lyubka committed
8060

8061 8062
  return 0;
}
Sergey Lyubka's avatar
Sergey Lyubka committed
8063

8064 8065 8066 8067 8068
uint32_t mg_coap_send_message(struct mg_connection *nc,
                              struct mg_coap_message *cm) {
  struct mbuf packet_out;
  int send_res;
  uint32_t compose_res;
Sergey Lyubka's avatar
Sergey Lyubka committed
8069

8070 8071 8072 8073 8074
  mbuf_init(&packet_out, 0);
  compose_res = mg_coap_compose(cm, &packet_out);
  if (compose_res != 0) {
    return compose_res; /* LCOV_EXCL_LINE */
  }
Sergey Lyubka's avatar
Sergey Lyubka committed
8075

8076 8077
  send_res = mg_send(nc, packet_out.buf, (int) packet_out.len);
  mbuf_free(&packet_out);
Sergey Lyubka's avatar
Sergey Lyubka committed
8078

8079 8080 8081 8082 8083
  if (send_res == 0) {
    /*
     * in case of UDP mg_send tries to send immediately
     * and could return an error.
     */
8084
    return MG_COAP_NETWORK_ERROR; /* LCOV_EXCL_LINE */
8085
  }
Sergey Lyubka's avatar
Sergey Lyubka committed
8086

8087 8088
  return 0;
}
Sergey Lyubka's avatar
Sergey Lyubka committed
8089

8090 8091 8092
uint32_t mg_coap_send_ack(struct mg_connection *nc, uint16_t msg_id) {
  struct mg_coap_message cm;
  memset(&cm, 0, sizeof(cm));
8093
  cm.msg_type = MG_COAP_MSG_ACK;
8094
  cm.msg_id = msg_id;
Sergey Lyubka's avatar
Sergey Lyubka committed
8095

8096
  return mg_coap_send_message(nc, &cm);
Sergey Lyubka's avatar
Sergey Lyubka committed
8097 8098
}

8099 8100 8101 8102
static void coap_handler(struct mg_connection *nc, int ev, void *ev_data) {
  struct mbuf *io = &nc->recv_mbuf;
  struct mg_coap_message cm;
  uint32_t parse_res;
8103

8104
  memset(&cm, 0, sizeof(cm));
8105

8106
  nc->handler(nc, ev, ev_data);
8107

8108
  switch (ev) {
8109
    case MG_EV_RECV:
8110
      parse_res = mg_coap_parse(io, &cm);
8111 8112
      if ((parse_res & MG_COAP_IGNORE) == 0) {
        if ((cm.flags & MG_COAP_NOT_ENOUGH_DATA) != 0) {
8113 8114
          /*
           * Since we support UDP only
8115
           * MG_COAP_NOT_ENOUGH_DATA == MG_COAP_FORMAT_ERROR
8116
           */
8117
          cm.flags |= MG_COAP_FORMAT_ERROR; /* LCOV_EXCL_LINE */
8118
        }                                   /* LCOV_EXCL_LINE */
8119
        nc->handler(nc, MG_COAP_EVENT_BASE + cm.msg_type, &cm);
8120
      }
8121

8122 8123 8124 8125
      mg_coap_free_options(&cm);
      mbuf_remove(io, io->len);
      break;
  }
8126
}
8127 8128 8129 8130 8131
/*
 * Attach built-in CoAP event handler to the given connection.
 *
 * The user-defined event handler will receive following extra events:
 *
8132 8133 8134 8135
 * - MG_EV_COAP_CON
 * - MG_EV_COAP_NOC
 * - MG_EV_COAP_ACK
 * - MG_EV_COAP_RST
8136 8137 8138
 */
int mg_set_protocol_coap(struct mg_connection *nc) {
  /* supports UDP only */
8139
  if ((nc->flags & MG_F_UDP) == 0) {
8140 8141
    return -1;
  }
8142

8143
  nc->proto_handler = coap_handler;
Sergey Lyubka's avatar
Sergey Lyubka committed
8144

8145
  return 0;
8146 8147
}

8148
#endif /* MG_DISABLE_COAP */