MIDAS
Loading...
Searching...
No Matches
mongoose6.cxx
Go to the documentation of this file.
1#include "mongoose6.h"
2#ifdef MG_MODULE_LINES
3#line 1 "./src/internal.h"
4#endif
5/*
6 * Copyright (c) 2014 Cesanta Software Limited
7 * All rights reserved
8 */
9
10#ifndef CS_MONGOOSE_SRC_INTERNAL_H_
11#define CS_MONGOOSE_SRC_INTERNAL_H_
12
13#ifndef MG_MALLOC
14#define MG_MALLOC malloc
15#endif
16
17#ifndef MG_CALLOC
18#define MG_CALLOC calloc
19#endif
20
21#ifndef MG_REALLOC
22#define MG_REALLOC realloc
23#endif
24
25#ifndef MG_FREE
26#define MG_FREE free
27#endif
28
29#ifndef MBUF_REALLOC
30#define MBUF_REALLOC MG_REALLOC
31#endif
32
33#ifndef MBUF_FREE
34#define MBUF_FREE MG_FREE
35#endif
36
37#define MG_SET_PTRPTR(_ptr, _v) \
38 do { \
39 if (_ptr) *(_ptr) = _v; \
40 } while (0)
41
42#ifndef MG_INTERNAL
43#define MG_INTERNAL static
44#endif
45
46#ifdef PICOTCP
47#define NO_LIBC
48#define MG_DISABLE_FILESYSTEM
49#define MG_DISABLE_POPEN
50#define MG_DISABLE_CGI
51#define MG_DISABLE_DIRECTORY_LISTING
52#define MG_DISABLE_SOCKETPAIR
53#define MG_DISABLE_PFS
54#endif
55
56/* Amalgamated: #include "mongoose/src/net.h" */
57/* Amalgamated: #include "mongoose/src/http.h" */
58
59#define MG_CTL_MSG_MESSAGE_SIZE 8192
60
61/* internals that need to be accessible in unit tests */
63 int proto,
64 union socket_address *sa);
65
66MG_INTERNAL int mg_parse_address(const char *str, union socket_address *sa,
67 int *proto, char *host, size_t host_len);
68MG_INTERNAL void mg_call(struct mg_connection *nc,
70void mg_forward(struct mg_connection *from, struct mg_connection *to);
71MG_INTERNAL void mg_add_conn(struct mg_mgr *mgr, struct mg_connection *c);
75 struct mg_add_sock_opts opts);
76#ifndef MG_DISABLE_FILESYSTEM
78 const struct mg_serve_http_opts *opts,
79 char **local_path,
80 struct mg_str *remainder);
81#endif
82#ifdef _WIN32
83/* Retur value is the same as for MultiByteToWideChar. */
84int to_wchar(const char *path, wchar_t *wbuf, size_t wbuf_len);
85#endif
86
87/*
88 * Reassemble the content of the buffer (buf, blen) which should be
89 * in the HTTP chunked encoding, by collapsing data chunks to the
90 * beginning of the buffer.
91 *
92 * If chunks get reassembled, modify hm->body to point to the reassembled
93 * body and fire MG_EV_HTTP_CHUNK event. If handler sets MG_F_DELETE_CHUNK
94 * in nc->flags, delete reassembled body from the mbuf.
95 *
96 * Return reassembled body size.
97 */
99 struct http_message *hm, char *buf,
100 size_t blen);
101
102#ifndef MG_DISABLE_FILESYSTEM
105#endif
106
111
112#ifndef MG_DISABLE_MQTT
113struct mg_mqtt_message;
114MG_INTERNAL int parse_mqtt(struct mbuf *io, struct mg_mqtt_message *mm);
115#endif
116
117/* Forward declarations for testing. */
118extern void *(*test_malloc)(size_t size);
119extern void *(*test_calloc)(size_t count, size_t size);
120
121#endif /* CS_MONGOOSE_SRC_INTERNAL_H_ */
122#ifdef MG_MODULE_LINES
123#line 1 "./src/../../common/base64.c"
124#endif
125/*
126 * Copyright (c) 2014 Cesanta Software Limited
127 * All rights reserved
128 */
129
130#ifndef EXCLUDE_COMMON
131
132/* Amalgamated: #include "common/base64.h" */
133#include <string.h>
134
135/* ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/ */
136
137#define NUM_UPPERCASES ('Z' - 'A' + 1)
138#define NUM_LETTERS (NUM_UPPERCASES * 2)
139#define NUM_DIGITS ('9' - '0' + 1)
140
141/*
142 * Emit a base64 code char.
143 *
144 * Doesn't use memory, thus it's safe to use to safely dump memory in crashdumps
145 */
146static void cs_base64_emit_code(struct cs_base64_ctx *ctx, int v) {
147 if (v < NUM_UPPERCASES) {
148 ctx->b64_putc(v + 'A', ctx->user_data);
149 } else if (v < (NUM_LETTERS)) {
150 ctx->b64_putc(v - NUM_UPPERCASES + 'a', ctx->user_data);
151 } else if (v < (NUM_LETTERS + NUM_DIGITS)) {
152 ctx->b64_putc(v - NUM_LETTERS + '0', ctx->user_data);
153 } else {
154 ctx->b64_putc(v - NUM_LETTERS - NUM_DIGITS == 0 ? '+' : '/',
155 ctx->user_data);
156 }
157}
158
159static void cs_base64_emit_chunk(struct cs_base64_ctx *ctx) {
160 int a, b, c;
161
162 a = ctx->chunk[0];
163 b = ctx->chunk[1];
164 c = ctx->chunk[2];
165
166 cs_base64_emit_code(ctx, a >> 2);
167 cs_base64_emit_code(ctx, ((a & 3) << 4) | (b >> 4));
168 if (ctx->chunk_size > 1) {
169 cs_base64_emit_code(ctx, (b & 15) << 2 | (c >> 6));
170 }
171 if (ctx->chunk_size > 2) {
172 cs_base64_emit_code(ctx, c & 63);
173 }
174}
175
177 void *user_data) {
178 ctx->chunk_size = 0;
179 ctx->b64_putc = b64_putc;
180 ctx->user_data = user_data;
181}
182
183void cs_base64_update(struct cs_base64_ctx *ctx, const char *str, size_t len) {
184 const unsigned char *src = (const unsigned char *) str;
185 size_t i;
186 for (i = 0; i < len; i++) {
187 ctx->chunk[ctx->chunk_size++] = src[i];
188 if (ctx->chunk_size == 3) {
190 ctx->chunk_size = 0;
191 }
192 }
193}
194
196 if (ctx->chunk_size > 0) {
197 int i;
198 memset(&ctx->chunk[ctx->chunk_size], 0, 3 - ctx->chunk_size);
200 for (i = 0; i < (3 - ctx->chunk_size); i++) {
201 ctx->b64_putc('=', ctx->user_data);
202 }
203 }
204}
205
206#define BASE64_ENCODE_BODY \
207 static const char *b64 = \
208 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; \
209 int i, j, a, b, c; \
210 \
211 for (i = j = 0; i < src_len; i += 3) { \
212 a = src[i]; \
213 b = i + 1 >= src_len ? 0 : src[i + 1]; \
214 c = i + 2 >= src_len ? 0 : src[i + 2]; \
215 \
216 BASE64_OUT(b64[a >> 2]); \
217 BASE64_OUT(b64[((a & 3) << 4) | (b >> 4)]); \
218 if (i + 1 < src_len) { \
219 BASE64_OUT(b64[(b & 15) << 2 | (c >> 6)]); \
220 } \
221 if (i + 2 < src_len) { \
222 BASE64_OUT(b64[c & 63]); \
223 } \
224 } \
225 \
226 while (j % 4 != 0) { \
227 BASE64_OUT('='); \
228 } \
229 BASE64_FLUSH()
230
231#define BASE64_OUT(ch) \
232 do { \
233 dst[j++] = (ch); \
234 } while (0)
235
236#define BASE64_FLUSH() \
237 do { \
238 dst[j++] = '\0'; \
239 } while (0)
240
241void cs_base64_encode(const unsigned char *src, int src_len, char *dst) {
243}
244
245#undef BASE64_OUT
246#undef BASE64_FLUSH
247
248#ifndef CS_DISABLE_STDIO
249#define BASE64_OUT(ch) \
250 do { \
251 fprintf(f, "%c", (ch)); \
252 j++; \
253 } while (0)
254
255#define BASE64_FLUSH()
256
257void cs_fprint_base64(FILE *f, const unsigned char *src, int src_len) {
259}
260
261#undef BASE64_OUT
262#undef BASE64_FLUSH
263#endif /* !CS_DISABLE_STDIO */
264
265/* Convert one byte of encoded base64 input stream to 6-bit chunk */
266static unsigned char from_b64(unsigned char ch) {
267 /* Inverse lookup map */
268 static const unsigned char tab[128] = {
269 255, 255, 255, 255,
270 255, 255, 255, 255, /* 0 */
271 255, 255, 255, 255,
272 255, 255, 255, 255, /* 8 */
273 255, 255, 255, 255,
274 255, 255, 255, 255, /* 16 */
275 255, 255, 255, 255,
276 255, 255, 255, 255, /* 24 */
277 255, 255, 255, 255,
278 255, 255, 255, 255, /* 32 */
279 255, 255, 255, 62,
280 255, 255, 255, 63, /* 40 */
281 52, 53, 54, 55,
282 56, 57, 58, 59, /* 48 */
283 60, 61, 255, 255,
284 255, 200, 255, 255, /* 56 '=' is 200, on index 61 */
285 255, 0, 1, 2,
286 3, 4, 5, 6, /* 64 */
287 7, 8, 9, 10,
288 11, 12, 13, 14, /* 72 */
289 15, 16, 17, 18,
290 19, 20, 21, 22, /* 80 */
291 23, 24, 25, 255,
292 255, 255, 255, 255, /* 88 */
293 255, 26, 27, 28,
294 29, 30, 31, 32, /* 96 */
295 33, 34, 35, 36,
296 37, 38, 39, 40, /* 104 */
297 41, 42, 43, 44,
298 45, 46, 47, 48, /* 112 */
299 49, 50, 51, 255,
300 255, 255, 255, 255, /* 120 */
301 };
302 return tab[ch & 127];
303}
304
305int cs_base64_decode(const unsigned char *s, int len, char *dst) {
306 unsigned char a, b, c, d;
307 int orig_len = len;
308 while (len >= 4 && (a = from_b64(s[0])) != 255 &&
309 (b = from_b64(s[1])) != 255 && (c = from_b64(s[2])) != 255 &&
310 (d = from_b64(s[3])) != 255) {
311 s += 4;
312 len -= 4;
313 if (a == 200 || b == 200) break; /* '=' can't be there */
314 *dst++ = a << 2 | b >> 4;
315 if (c == 200) break;
316 *dst++ = b << 4 | c >> 2;
317 if (d == 200) break;
318 *dst++ = c << 6 | d;
319 }
320 *dst = 0;
321 return orig_len - len;
322}
323
324#endif /* EXCLUDE_COMMON */
325#ifdef MG_MODULE_LINES
326#line 1 "./src/../../common/cs_dbg.c"
327#endif
328/*
329 * Copyright (c) 2014-2016 Cesanta Software Limited
330 * All rights reserved
331 */
332
333/* Amalgamated: #include "common/cs_dbg.h" */
334
335#include <stdarg.h>
336#include <stdio.h>
337
338/* Amalgamated: #include "common/cs_time.h" */
339
341#ifdef CS_ENABLE_DEBUG
343#else
344 LL_ERROR;
345#endif
346
347#ifndef CS_DISABLE_STDIO
348
350
351#ifdef CS_LOG_TS_DIFF
352double cs_log_ts;
353#endif
354
355void cs_log_print_prefix(const char *func) {
357 fprintf(cs_log_file, "%-20s ", func);
358#ifdef CS_LOG_TS_DIFF
359 {
360 double now = cs_time();
361 fprintf(cs_log_file, "%7u ", (unsigned int) ((now - cs_log_ts) * 1000000));
362 cs_log_ts = now;
363 }
364#endif
365}
366
367void cs_log_printf(const char *fmt, ...) {
368 va_list ap;
369 va_start(ap, fmt);
370 vfprintf(cs_log_file, fmt, ap);
371 va_end(ap);
372 fputc('\n', cs_log_file);
374}
375
379
380#endif /* !CS_DISABLE_STDIO */
381
384#if defined(CS_LOG_TS_DIFF) && !defined(CS_DISABLE_STDIO)
385 cs_log_ts = cs_time();
386#endif
387}
388#ifdef MG_MODULE_LINES
389#line 1 "./src/../../common/cs_dirent.c"
390#endif
391/*
392 * Copyright (c) 2015 Cesanta Software Limited
393 * All rights reserved
394 */
395
396#ifndef EXCLUDE_COMMON
397
398/* Amalgamated: #include "common/cs_dirent.h" */
399
400/*
401 * This file contains POSIX opendir/closedir/readdir API implementation
402 * for systems which do not natively support it (e.g. Windows).
403 */
404
405#ifndef MG_FREE
406#define MG_FREE free
407#endif
408
409#ifndef MG_MALLOC
410#define MG_MALLOC malloc
411#endif
412
413#ifdef _WIN32
414DIR *opendir(const char *name) {
415 DIR *dir = NULL;
416 wchar_t wpath[MAX_PATH];
417 DWORD attrs;
418
419 if (name == NULL) {
421 } else if ((dir = (DIR *) MG_MALLOC(sizeof(*dir))) == NULL) {
423 } else {
426 if (attrs != 0xFFFFFFFF && (attrs & FILE_ATTRIBUTE_DIRECTORY)) {
427 (void) wcscat(wpath, L"\\*");
428 dir->handle = FindFirstFileW(wpath, &dir->info);
429 dir->result.d_name[0] = '\0';
430 } else {
431 MG_FREE(dir);
432 dir = NULL;
433 }
434 }
435
436 return dir;
437}
438
439int closedir(DIR *dir) {
440 int result = 0;
441
442 if (dir != NULL) {
443 if (dir->handle != INVALID_HANDLE_VALUE)
444 result = FindClose(dir->handle) ? 0 : -1;
445 MG_FREE(dir);
446 } else {
447 result = -1;
449 }
450
451 return result;
452}
453
454struct dirent *readdir(DIR *dir) {
455 struct dirent *result = NULL;
456
457 if (dir) {
458 if (dir->handle != INVALID_HANDLE_VALUE) {
459 result = &dir->result;
460 (void) WideCharToMultiByte(CP_UTF8, 0, dir->info.cFileName, -1,
461 result->d_name, sizeof(result->d_name), NULL,
462 NULL);
463
464 if (!FindNextFileW(dir->handle, &dir->info)) {
465 (void) FindClose(dir->handle);
466 dir->handle = INVALID_HANDLE_VALUE;
467 }
468
469 } else {
471 }
472 } else {
474 }
475
476 return result;
477}
478#endif
479
480#ifdef CS_ENABLE_SPIFFS
481
482DIR *opendir(const char *dir_name) {
483 DIR *dir = NULL;
484 extern spiffs fs;
485
486 if (dir_name != NULL && (dir = (DIR *) malloc(sizeof(*dir))) != NULL &&
487 SPIFFS_opendir(&fs, (char *) dir_name, &dir->dh) == NULL) {
488 free(dir);
489 dir = NULL;
490 }
491
492 return dir;
493}
494
495int closedir(DIR *dir) {
496 if (dir != NULL) {
497 SPIFFS_closedir(&dir->dh);
498 free(dir);
499 }
500 return 0;
501}
502
503struct dirent *readdir(DIR *dir) {
504 return SPIFFS_readdir(&dir->dh, &dir->de);
505}
506
507/* SPIFFs doesn't support directory operations */
508int rmdir(const char *path) {
509 (void) path;
510 return ENOTDIR;
511}
512
513int mkdir(const char *path, mode_t mode) {
514 (void) path;
515 (void) mode;
516 /* for spiffs supports only root dir, which comes from mongoose as '.' */
517 return (strlen(path) == 1 && *path == '.') ? 0 : ENOTDIR;
518}
519
520#endif /* CS_ENABLE_SPIFFS */
521
522#endif /* EXCLUDE_COMMON */
523
524/* ISO C requires a translation unit to contain at least one declaration */
525typedef int cs_dirent_dummy;
526#ifdef MG_MODULE_LINES
527#line 1 "./src/../../common/cs_time.c"
528#endif
529/*
530 * Copyright (c) 2014-2016 Cesanta Software Limited
531 * All rights reserved
532 */
533
534#ifndef _WIN32
535#include <stddef.h>
536#if !defined(CS_PLATFORM) || \
537 (CS_PLATFORM != CS_P_CC3200 && CS_PLATFORM != CS_P_MSP432)
538#include <sys/time.h>
539#endif
540#else
541#include <windows.h>
542#endif
543
544double cs_time() {
545 double now;
546#ifndef _WIN32
547 struct timeval tv;
548 if (gettimeofday(&tv, NULL /* tz */) != 0) return 0;
549 now = (double) tv.tv_sec + (((double) tv.tv_usec) / 1000000.0);
550#else
551 now = GetTickCount() / 1000.0;
552#endif
553 return now;
554}
555#ifdef MG_MODULE_LINES
556#line 1 "./src/../deps/frozen/frozen.c"
557#endif
558/*
559 * Copyright (c) 2004-2013 Sergey Lyubka <valenok@gmail.com>
560 * Copyright (c) 2013 Cesanta Software Limited
561 * All rights reserved
562 *
563 * This library is dual-licensed: you can redistribute it and/or modify
564 * it under the terms of the GNU General Public License version 2 as
565 * published by the Free Software Foundation. For the terms of this
566 * license, see <http: *www.gnu.org/licenses/>.
567 *
568 * You are free to use this library under the terms of the GNU General
569 * Public License, but WITHOUT ANY WARRANTY; without even the implied
570 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
571 * See the GNU General Public License for more details.
572 *
573 * Alternatively, you can license this library under a commercial
574 * license, as set out in <http://cesanta.com/products.html>.
575 */
576
577#ifndef _CRT_SECURE_NO_WARNINGS
578#define _CRT_SECURE_NO_WARNINGS /* Disable deprecation warning in VS2005+ */
579#endif
580
581#include <stdio.h>
582#include <stdlib.h>
583#include <string.h>
584#include <stdarg.h>
585/* Amalgamated: #include "frozen.h" */
586
587#ifdef _WIN32
588#define snprintf _snprintf
589#endif
590
591#ifndef FROZEN_REALLOC
592#define FROZEN_REALLOC realloc
593#endif
594
595#ifndef FROZEN_FREE
596#define FROZEN_FREE free
597#endif
598
599struct frozen {
600 const char *end;
601 const char *cur;
606};
607
608static int parse_object(struct frozen *f);
609static int parse_value(struct frozen *f);
610
611#define EXPECT(cond, err_code) \
612 do { \
613 if (!(cond)) return (err_code); \
614 } while (0)
615#define TRY(expr) \
616 do { \
617 int _n = expr; \
618 if (_n < 0) return _n; \
619 } while (0)
620#define END_OF_STRING (-1)
621
622static int left(const struct frozen *f) {
623 return f->end - f->cur;
624}
625
626static int is_space(int ch) {
627 return ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n';
628}
629
630static void skip_whitespaces(struct frozen *f) {
631 while (f->cur < f->end && is_space(*f->cur)) f->cur++;
632}
633
634static int cur(struct frozen *f) {
636 return f->cur >= f->end ? END_OF_STRING : *(unsigned char *) f->cur;
637}
638
639static int test_and_skip(struct frozen *f, int expected) {
640 int ch = cur(f);
641 if (ch == expected) {
642 f->cur++;
643 return 0;
644 }
646}
647
648static int test_no_skip(struct frozen *f, int expected) {
649 int ch = cur(f);
650 if (ch == expected) {
651 return 0;
652 }
654}
655
656static int is_alpha(int ch) {
657 return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z');
658}
659
660static int is_digit(int ch) {
661 return ch >= '0' && ch <= '9';
662}
663
664static int is_hex_digit(int ch) {
665 return is_digit(ch) || (ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F');
666}
667
668static int get_escape_len(const char *s, int len) {
669 switch (*s) {
670 case 'u':
671 return len < 6 ? JSON_STRING_INCOMPLETE
672 : is_hex_digit(s[1]) && is_hex_digit(s[2]) &&
673 is_hex_digit(s[3]) && is_hex_digit(s[4])
674 ? 5
676 case '"':
677 case '\\':
678 case '/':
679 case 'b':
680 case 'f':
681 case 'n':
682 case 'r':
683 case 't':
684 return len < 2 ? JSON_STRING_INCOMPLETE : 1;
685 default:
686 return JSON_STRING_INVALID;
687 }
688}
689
690static int capture_ptr(struct frozen *f, const char *ptr, enum json_type type) {
691 if (f->do_realloc && f->num_tokens >= f->max_tokens) {
692 int new_size = f->max_tokens == 0 ? 100 : f->max_tokens * 2;
693 void *p = FROZEN_REALLOC(f->tokens, new_size * sizeof(f->tokens[0]));
694 if (p == NULL) return JSON_TOKEN_ARRAY_TOO_SMALL;
695 f->max_tokens = new_size;
696 f->tokens = (struct json_token *) p;
697 }
698 if (f->tokens == NULL || f->max_tokens == 0) return 0;
700 f->tokens[f->num_tokens].ptr = ptr;
701 f->tokens[f->num_tokens].type = type;
702 f->num_tokens++;
703 return 0;
704}
705
706static int capture_len(struct frozen *f, int token_index, const char *ptr) {
707 if (f->tokens == 0 || f->max_tokens == 0) return 0;
711 return 0;
712}
713
714/* identifier = letter { letter | digit | '_' } */
715static int parse_identifier(struct frozen *f) {
718 while (f->cur < f->end &&
719 (*f->cur == '_' || is_alpha(*f->cur) || is_digit(*f->cur))) {
720 f->cur++;
721 }
722 capture_len(f, f->num_tokens - 1, f->cur);
723 return 0;
724}
725
726static int get_utf8_char_len(unsigned char ch) {
727 if ((ch & 0x80) == 0) return 1;
728 switch (ch & 0xf0) {
729 case 0xf0:
730 return 4;
731 case 0xe0:
732 return 3;
733 default:
734 return 2;
735 }
736}
737
738/* string = '"' { quoted_printable_chars } '"' */
739static int parse_string(struct frozen *f) {
740 int n, ch = 0, len = 0;
741 TRY(test_and_skip(f, '"'));
743 for (; f->cur < f->end; f->cur += len) {
744 ch = *(unsigned char *) f->cur;
745 len = get_utf8_char_len((unsigned char) ch);
746 EXPECT(ch >= 32 && len > 0, JSON_STRING_INVALID); /* No control chars */
748 if (ch == '\\') {
749 EXPECT((n = get_escape_len(f->cur + 1, left(f))) > 0, n);
750 len += n;
751 } else if (ch == '"') {
752 capture_len(f, f->num_tokens - 1, f->cur);
753 f->cur++;
754 break;
755 };
756 }
757 return ch == '"' ? 0 : JSON_STRING_INCOMPLETE;
758}
759
760/* number = [ '-' ] digit+ [ '.' digit+ ] [ ['e'|'E'] ['+'|'-'] digit+ ] */
761static int parse_number(struct frozen *f) {
762 int ch = cur(f);
764 if (ch == '-') f->cur++;
767 while (f->cur < f->end && is_digit(f->cur[0])) f->cur++;
768 if (f->cur < f->end && f->cur[0] == '.') {
769 f->cur++;
772 while (f->cur < f->end && is_digit(f->cur[0])) f->cur++;
773 }
774 if (f->cur < f->end && (f->cur[0] == 'e' || f->cur[0] == 'E')) {
775 f->cur++;
777 if ((f->cur[0] == '+' || f->cur[0] == '-')) f->cur++;
780 while (f->cur < f->end && is_digit(f->cur[0])) f->cur++;
781 }
782 capture_len(f, f->num_tokens - 1, f->cur);
783 return 0;
784}
785
786/* array = '[' [ value { ',' value } ] ']' */
787static int parse_array(struct frozen *f) {
788 int ind;
789 TRY(test_and_skip(f, '['));
790 TRY(capture_ptr(f, f->cur - 1, JSON_TYPE_ARRAY));
791 ind = f->num_tokens - 1;
792 while (cur(f) != ']') {
793 TRY(parse_value(f));
794 if (cur(f) == ',') f->cur++;
795 }
796 TRY(test_and_skip(f, ']'));
797 capture_len(f, ind, f->cur);
798 return 0;
799}
800
801static int compare(const char *s, const char *str, int len) {
802 int i = 0;
803 while (i < len && s[i] == str[i]) i++;
804 return i == len ? 1 : 0;
805}
806
807static int expect(struct frozen *f, const char *s, int len, enum json_type t) {
808 int i, n = left(f);
809
810 TRY(capture_ptr(f, f->cur, t));
811 for (i = 0; i < len; i++) {
812 if (i >= n) return JSON_STRING_INCOMPLETE;
813 if (f->cur[i] != s[i]) return JSON_STRING_INVALID;
814 }
815 f->cur += len;
816 TRY(capture_len(f, f->num_tokens - 1, f->cur));
817
818 return 0;
819}
820
821/* value = 'null' | 'true' | 'false' | number | string | array | object */
822static int parse_value(struct frozen *f) {
823 int ch = cur(f);
824
825 switch (ch) {
826 case '"':
827 TRY(parse_string(f));
828 break;
829 case '{':
830 TRY(parse_object(f));
831 break;
832 case '[':
833 TRY(parse_array(f));
834 break;
835 case 'n':
836 TRY(expect(f, "null", 4, JSON_TYPE_NULL));
837 break;
838 case 't':
839 TRY(expect(f, "true", 4, JSON_TYPE_TRUE));
840 break;
841 case 'f':
842 TRY(expect(f, "false", 5, JSON_TYPE_FALSE));
843 break;
844 case '-':
845 case '0':
846 case '1':
847 case '2':
848 case '3':
849 case '4':
850 case '5':
851 case '6':
852 case '7':
853 case '8':
854 case '9':
855 TRY(parse_number(f));
856 break;
857 default:
859 }
860
861 return 0;
862}
863
864/* key = identifier | string */
865static int parse_key(struct frozen *f) {
866 int ch = cur(f);
867#if 0
868 printf("%s 1 [%.*s]\n", __func__, (int) (f->end - f->cur), f->cur);
869#endif
870 if (is_alpha(ch)) {
872 } else if (ch == '"') {
873 TRY(parse_string(f));
874 } else {
876 }
877 return 0;
878}
879
880/* pair = key ':' value */
881static int parse_pair(struct frozen *f) {
882 TRY(parse_key(f));
883 TRY(test_and_skip(f, ':'));
884 TRY(parse_value(f));
885 return 0;
886}
887
888/* object = '{' pair { ',' pair } '}' */
889static int parse_object(struct frozen *f) {
890 int ind;
891 TRY(test_and_skip(f, '{'));
892 TRY(capture_ptr(f, f->cur - 1, JSON_TYPE_OBJECT));
893 ind = f->num_tokens - 1;
894 while (cur(f) != '}') {
895 TRY(parse_pair(f));
896 if (cur(f) == ',') f->cur++;
897 }
898 TRY(test_and_skip(f, '}'));
899 capture_len(f, ind, f->cur);
900 return 0;
901}
902
903static int doit(struct frozen *f) {
904 int ret = 0;
905
906 if (f->cur == 0 || f->end < f->cur) return JSON_STRING_INVALID;
907 if (f->end == f->cur) return JSON_STRING_INCOMPLETE;
908
909 if (0 == (ret = test_no_skip(f, '{'))) {
910 TRY(parse_object(f));
911 } else if (0 == (ret = test_no_skip(f, '['))) {
912 TRY(parse_array(f));
913 } else {
914 return ret;
915 }
916
918 capture_len(f, f->num_tokens, f->cur);
919 return 0;
920}
921
922/* json = object */
923int parse_json(const char *s, int s_len, struct json_token *arr, int arr_len) {
924 struct frozen frozen;
925
926 memset(&frozen, 0, sizeof(frozen));
927 frozen.end = s + s_len;
928 frozen.cur = s;
929 frozen.tokens = arr;
931
932 TRY(doit(&frozen));
933
934 return frozen.cur - s;
935}
936
937struct json_token *parse_json2(const char *s, int s_len) {
938 struct frozen frozen;
939
940 memset(&frozen, 0, sizeof(frozen));
941 frozen.end = s + s_len;
942 frozen.cur = s;
943 frozen.do_realloc = 1;
944
945 if (doit(&frozen) < 0) {
946 FROZEN_FREE((void *) frozen.tokens);
948 }
949 return frozen.tokens;
950}
951
952static int path_part_len(const char *p) {
953 int i = 0;
954 while (p[i] != '\0' && p[i] != '[' && p[i] != '.') i++;
955 return i;
956}
957
958struct json_token *find_json_token(struct json_token *toks, const char *path) {
959 while (path != 0 && path[0] != '\0') {
960 int i, ind2 = 0, ind = -1, skip = 2, n = path_part_len(path);
961 if (path[0] == '[') {
962 if (toks->type != JSON_TYPE_ARRAY || !is_digit(path[1])) return 0;
963 for (ind = 0, n = 1; path[n] != ']' && path[n] != '\0'; n++) {
964 if (!is_digit(path[n])) return 0;
965 ind *= 10;
966 ind += path[n] - '0';
967 }
968 if (path[n++] != ']') return 0;
969 skip = 1; /* In objects, we skip 2 elems while iterating, in arrays 1. */
970 } else if (toks->type != JSON_TYPE_OBJECT)
971 return 0;
972 toks++;
973 for (i = 0; i < toks[-1].num_desc; i += skip, ind2++) {
974 /* ind == -1 indicated that we're iterating an array, not object */
975 if (ind == -1 && toks[i].type != JSON_TYPE_STRING) return 0;
976 if (ind2 == ind ||
977 (ind == -1 && toks[i].len == n && compare(path, toks[i].ptr, n))) {
978 i += skip - 1;
979 break;
980 };
981 if (toks[i - 1 + skip].type == JSON_TYPE_ARRAY ||
982 toks[i - 1 + skip].type == JSON_TYPE_OBJECT) {
983 i += toks[i - 1 + skip].num_desc;
984 }
985 }
986 if (i == toks[-1].num_desc) return 0;
987 path += n;
988 if (path[0] == '.') path++;
989 if (path[0] == '\0') return &toks[i];
990 toks += i;
991 }
992 return 0;
993}
994
995int json_emit_long(char *buf, int buf_len, long int value) {
996 char tmp[20];
997 int n = snprintf(tmp, sizeof(tmp), "%ld", value);
998 strncpy(buf, tmp, buf_len > 0 ? buf_len : 0);
999 return n;
1000}
1001
1002int json_emit_double(char *buf, int buf_len, double value) {
1003 char tmp[20];
1004 int n = snprintf(tmp, sizeof(tmp), "%g", value);
1005 strncpy(buf, tmp, buf_len > 0 ? buf_len : 0);
1006 return n;
1007}
1008
1009int json_emit_quoted_str(char *s, int s_len, const char *str, int len) {
1010 const char *begin = s, *end = s + s_len, *str_end = str + len;
1011 char ch;
1012
1013#define EMIT(x) \
1014 do { \
1015 if (s < end) *s = x; \
1016 s++; \
1017 } while (0)
1018
1019 EMIT('"');
1020 while (str < str_end) {
1021 ch = *str++;
1022 switch (ch) {
1023 case '"':
1024 EMIT('\\');
1025 EMIT('"');
1026 break;
1027 case '\\':
1028 EMIT('\\');
1029 EMIT('\\');
1030 break;
1031 case '\b':
1032 EMIT('\\');
1033 EMIT('b');
1034 break;
1035 case '\f':
1036 EMIT('\\');
1037 EMIT('f');
1038 break;
1039 case '\n':
1040 EMIT('\\');
1041 EMIT('n');
1042 break;
1043 case '\r':
1044 EMIT('\\');
1045 EMIT('r');
1046 break;
1047 case '\t':
1048 EMIT('\\');
1049 EMIT('t');
1050 break;
1051 default:
1052 EMIT(ch);
1053 }
1054 }
1055 EMIT('"');
1056 if (s < end) {
1057 *s = '\0';
1058 }
1059
1060 return s - begin;
1061}
1062
1063int json_emit_unquoted_str(char *buf, int buf_len, const char *str, int len) {
1064 if (buf_len > 0 && len > 0) {
1065 int n = len < buf_len ? len : buf_len;
1066 memcpy(buf, str, n);
1067 if (n < buf_len) {
1068 buf[n] = '\0';
1069 }
1070 }
1071 return len;
1072}
1073
1074int json_emit_va(char *s, int s_len, const char *fmt, va_list ap) {
1075 const char *end = s + s_len, *str, *orig = s;
1076 size_t len;
1077
1078 while (*fmt != '\0') {
1079 switch (*fmt) {
1080 case '[':
1081 case ']':
1082 case '{':
1083 case '}':
1084 case ',':
1085 case ':':
1086 case ' ':
1087 case '\r':
1088 case '\n':
1089 case '\t':
1090 if (s < end) {
1091 *s = *fmt;
1092 }
1093 s++;
1094 break;
1095 case 'i':
1096 s += json_emit_long(s, end - s, va_arg(ap, long) );
1097 break;
1098 case 'f':
1099 s += json_emit_double(s, end - s, va_arg(ap, double) );
1100 break;
1101 case 'v':
1102 str = va_arg(ap, char *);
1103 len = va_arg(ap, size_t);
1104 s += json_emit_quoted_str(s, end - s, str, len);
1105 break;
1106 case 'V':
1107 str = va_arg(ap, char *);
1108 len = va_arg(ap, size_t);
1109 s += json_emit_unquoted_str(s, end - s, str, len);
1110 break;
1111 case 's':
1112 str = va_arg(ap, char *);
1113 s += json_emit_quoted_str(s, end - s, str, strlen(str));
1114 break;
1115 case 'S':
1116 str = va_arg(ap, char *);
1117 s += json_emit_unquoted_str(s, end - s, str, strlen(str));
1118 break;
1119 case 'T':
1120 s += json_emit_unquoted_str(s, end - s, "true", 4);
1121 break;
1122 case 'F':
1123 s += json_emit_unquoted_str(s, end - s, "false", 5);
1124 break;
1125 case 'N':
1126 s += json_emit_unquoted_str(s, end - s, "null", 4);
1127 break;
1128 default:
1129 return 0;
1130 }
1131 fmt++;
1132 }
1133
1134 /* Best-effort to 0-terminate generated string */
1135 if (s < end) {
1136 *s = '\0';
1137 }
1138
1139 return s - orig;
1140}
1141
1142int json_emit(char *buf, int buf_len, const char *fmt, ...) {
1143 int len;
1144 va_list ap;
1145
1146 va_start(ap, fmt);
1147 len = json_emit_va(buf, buf_len, fmt, ap);
1148 va_end(ap);
1149
1150 return len;
1151}
1152#ifdef MG_MODULE_LINES
1153#line 1 "./src/../../common/md5.c"
1154#endif
1155/*
1156 * This code implements the MD5 message-digest algorithm.
1157 * The algorithm is due to Ron Rivest. This code was
1158 * written by Colin Plumb in 1993, no copyright is claimed.
1159 * This code is in the public domain; do with it what you wish.
1160 *
1161 * Equivalent code is available from RSA Data Security, Inc.
1162 * This code has been tested against that, and is equivalent,
1163 * except that you don't need to include two pages of legalese
1164 * with every copy.
1165 *
1166 * To compute the message digest of a chunk of bytes, declare an
1167 * MD5Context structure, pass it to MD5Init, call MD5Update as
1168 * needed on buffers full of bytes, and then call MD5Final, which
1169 * will fill a supplied 16-byte array with the digest.
1170 */
1171
1172#if !defined(DISABLE_MD5) && !defined(EXCLUDE_COMMON)
1173
1174/* Amalgamated: #include "common/md5.h" */
1175
1176#ifndef CS_ENABLE_NATIVE_MD5
1177static void byteReverse(unsigned char *buf, unsigned longs) {
1178/* Forrest: MD5 expect LITTLE_ENDIAN, swap if BIG_ENDIAN */
1179#if BYTE_ORDER == BIG_ENDIAN
1180 do {
1181 uint32_t t = (uint32_t)((unsigned) buf[3] << 8 | buf[2]) << 16 |
1182 ((unsigned) buf[1] << 8 | buf[0]);
1183 *(uint32_t *) buf = t;
1184 buf += 4;
1185 } while (--longs);
1186#else
1187 (void) buf;
1188 (void) longs;
1189#endif
1190}
1191
1192#define F1(x, y, z) (z ^ (x & (y ^ z)))
1193#define F2(x, y, z) F1(z, x, y)
1194#define F3(x, y, z) (x ^ y ^ z)
1195#define F4(x, y, z) (y ^ (x | ~z))
1196
1197#define MD5STEP(f, w, x, y, z, data, s) \
1198 (w += f(x, y, z) + data, w = w << s | w >> (32 - s), w += x)
1199
1200/*
1201 * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
1202 * initialization constants.
1203 */
1204void MD5_Init(MD5_CTX *ctx) {
1205 ctx->buf[0] = 0x67452301;
1206 ctx->buf[1] = 0xefcdab89;
1207 ctx->buf[2] = 0x98badcfe;
1208 ctx->buf[3] = 0x10325476;
1209
1210 ctx->bits[0] = 0;
1211 ctx->bits[1] = 0;
1212}
1213
1214static void MD5Transform(uint32_t buf[4], uint32_t const in[16]) {
1215 uint32_t a, b, c, d;
1216
1217 a = buf[0];
1218 b = buf[1];
1219 c = buf[2];
1220 d = buf[3];
1221
1222 MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
1223 MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
1224 MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
1225 MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
1226 MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
1227 MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
1228 MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
1229 MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
1230 MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
1231 MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
1232 MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
1233 MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
1234 MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
1235 MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
1236 MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
1237 MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
1238
1239 MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
1240 MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
1241 MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
1242 MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
1243 MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
1244 MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
1245 MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
1246 MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
1247 MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
1248 MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
1249 MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
1250 MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
1251 MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
1252 MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
1253 MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
1254 MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
1255
1256 MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
1257 MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
1258 MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
1259 MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
1260 MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
1261 MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
1262 MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
1263 MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
1264 MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
1265 MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
1266 MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
1267 MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
1268 MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
1269 MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
1270 MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
1271 MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
1272
1273 MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
1274 MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
1275 MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
1276 MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
1277 MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
1278 MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
1279 MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
1280 MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
1281 MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
1282 MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
1283 MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
1284 MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
1285 MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
1286 MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
1287 MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
1288 MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
1289
1290 buf[0] += a;
1291 buf[1] += b;
1292 buf[2] += c;
1293 buf[3] += d;
1294}
1295
1296void MD5_Update(MD5_CTX *ctx, const unsigned char *buf, size_t len) {
1297 uint32_t t;
1298
1299 t = ctx->bits[0];
1300 if ((ctx->bits[0] = t + ((uint32_t) len << 3)) < t) ctx->bits[1]++;
1301 ctx->bits[1] += (uint32_t) len >> 29;
1302
1303 t = (t >> 3) & 0x3f;
1304
1305 if (t) {
1306 unsigned char *p = (unsigned char *) ctx->in + t;
1307
1308 t = 64 - t;
1309 if (len < t) {
1310 memcpy(p, buf, len);
1311 return;
1312 }
1313 memcpy(p, buf, t);
1314 byteReverse(ctx->in, 16);
1315 MD5Transform(ctx->buf, (uint32_t *) ctx->in);
1316 buf += t;
1317 len -= t;
1318 }
1319
1320 while (len >= 64) {
1321 memcpy(ctx->in, buf, 64);
1322 byteReverse(ctx->in, 16);
1323 MD5Transform(ctx->buf, (uint32_t *) ctx->in);
1324 buf += 64;
1325 len -= 64;
1326 }
1327
1328 memcpy(ctx->in, buf, len);
1329}
1330
1331void MD5_Final(unsigned char digest[16], MD5_CTX *ctx) {
1332 unsigned count;
1333 unsigned char *p;
1334 uint32_t *a;
1335
1336 count = (ctx->bits[0] >> 3) & 0x3F;
1337
1338 p = ctx->in + count;
1339 *p++ = 0x80;
1340 count = 64 - 1 - count;
1341 if (count < 8) {
1342 memset(p, 0, count);
1343 byteReverse(ctx->in, 16);
1344 MD5Transform(ctx->buf, (uint32_t *) ctx->in);
1345 memset(ctx->in, 0, 56);
1346 } else {
1347 memset(p, 0, count - 8);
1348 }
1349 byteReverse(ctx->in, 14);
1350
1351 a = (uint32_t *) ctx->in;
1352 a[14] = ctx->bits[0];
1353 a[15] = ctx->bits[1];
1354
1355 MD5Transform(ctx->buf, (uint32_t *) ctx->in);
1356 byteReverse((unsigned char *) ctx->buf, 4);
1357 memcpy(digest, ctx->buf, 16);
1358 memset((char *) ctx, 0, sizeof(*ctx));
1359}
1360#endif /* CS_ENABLE_NATIVE_MD5 */
1361
1362/*
1363 * Stringify binary data. Output buffer size must be 2 * size_of_input + 1
1364 * because each byte of input takes 2 bytes in string representation
1365 * plus 1 byte for the terminating \0 character.
1366 */
1367void cs_to_hex(char *to, const unsigned char *p, size_t len) {
1368 static const char *hex = "0123456789abcdef";
1369
1370 for (; len--; p++) {
1371 *to++ = hex[p[0] >> 4];
1372 *to++ = hex[p[0] & 0x0f];
1373 }
1374 *to = '\0';
1375}
1376
1377char *cs_md5(char buf[33], ...) {
1378 unsigned char hash[16];
1379 const unsigned char *p;
1380 va_list ap;
1381 MD5_CTX ctx;
1382
1383 MD5_Init(&ctx);
1384
1385 va_start(ap, buf);
1386 while ((p = va_arg(ap, const unsigned char *) ) != NULL) {
1387 size_t len = va_arg(ap, size_t);
1388 MD5_Update(&ctx, p, len);
1389 }
1390 va_end(ap);
1391
1392 MD5_Final(hash, &ctx);
1393 cs_to_hex(buf, hash, sizeof(hash));
1394
1395 return buf;
1396}
1397
1398#endif /* EXCLUDE_COMMON */
1399#ifdef MG_MODULE_LINES
1400#line 1 "./src/../../common/mbuf.c"
1401#endif
1402/*
1403 * Copyright (c) 2014 Cesanta Software Limited
1404 * All rights reserved
1405 */
1406
1407#ifndef EXCLUDE_COMMON
1408
1409#include <assert.h>
1410#include <string.h>
1411/* Amalgamated: #include "common/mbuf.h" */
1412
1413#ifndef MBUF_REALLOC
1414#define MBUF_REALLOC realloc
1415#endif
1416
1417#ifndef MBUF_FREE
1418#define MBUF_FREE free
1419#endif
1420
1421void mbuf_init(struct mbuf *mbuf, size_t initial_size) {
1422 mbuf->len = mbuf->size = 0;
1423 mbuf->buf = NULL;
1425}
1426
1427void mbuf_free(struct mbuf *mbuf) {
1428 if (mbuf->buf != NULL) {
1429 MBUF_FREE(mbuf->buf);
1430 mbuf_init(mbuf, 0);
1431 }
1432}
1433
1434void mbuf_resize(struct mbuf *a, size_t new_size) {
1435 if (new_size > a->size || (new_size < a->size && new_size >= a->len)) {
1436 char *buf = (char *) MBUF_REALLOC(a->buf, new_size);
1437 /*
1438 * In case realloc fails, there's not much we can do, except keep things as
1439 * they are. Note that NULL is a valid return value from realloc when
1440 * size == 0, but that is covered too.
1441 */
1442 if (buf == NULL && new_size != 0) return;
1443 a->buf = buf;
1444 a->size = new_size;
1445 }
1446}
1447
1448void mbuf_trim(struct mbuf *mbuf) {
1450}
1451
1452size_t mbuf_insert(struct mbuf *a, size_t off, const void *buf, size_t len) {
1453 char *p = NULL;
1454
1455 assert(a != NULL);
1456 assert(a->len <= a->size);
1457 assert(off <= a->len);
1458
1459 /* check overflow */
1460 if (~(size_t) 0 - (size_t) a->buf < len) return 0;
1461
1462 if (a->len + len <= a->size) {
1463 memmove(a->buf + off + len, a->buf + off, a->len - off);
1464 if (buf != NULL) {
1465 memcpy(a->buf + off, buf, len);
1466 }
1467 a->len += len;
1468 } else {
1469 size_t new_size = (a->len + len) * MBUF_SIZE_MULTIPLIER;
1470 if ((p = (char *) MBUF_REALLOC(a->buf, new_size)) != NULL) {
1471 a->buf = p;
1472 memmove(a->buf + off + len, a->buf + off, a->len - off);
1473 if (buf != NULL) memcpy(a->buf + off, buf, len);
1474 a->len += len;
1475 a->size = new_size;
1476 } else {
1477 len = 0;
1478 }
1479 }
1480
1481 return len;
1482}
1483
1484size_t mbuf_append(struct mbuf *a, const void *buf, size_t len) {
1485 return mbuf_insert(a, a->len, buf, len);
1486}
1487
1488void mbuf_remove(struct mbuf *mb, size_t n) {
1489 if (n > 0 && n <= mb->len) {
1490 memmove(mb->buf, mb->buf + n, mb->len - n);
1491 mb->len -= n;
1492 }
1493}
1494
1495#endif /* EXCLUDE_COMMON */
1496#ifdef MG_MODULE_LINES
1497#line 1 "./src/../../common/sha1.c"
1498#endif
1499/* Copyright(c) By Steve Reid <steve@edmweb.com> */
1500/* 100% Public Domain */
1501
1502#if !defined(DISABLE_SHA1) && !defined(EXCLUDE_COMMON)
1503
1504/* Amalgamated: #include "common/sha1.h" */
1505
1506#define SHA1HANDSOFF
1507#if defined(__sun)
1508/* Amalgamated: #include "common/solarisfixes.h" */
1509#endif
1510
1512 unsigned char c[64];
1514};
1515
1516#define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
1517
1518static uint32_t blk0(union char64long16 *block, int i) {
1519/* Forrest: SHA expect BIG_ENDIAN, swap if LITTLE_ENDIAN */
1520#if BYTE_ORDER == LITTLE_ENDIAN
1521 block->l[i] =
1522 (rol(block->l[i], 24) & 0xFF00FF00) | (rol(block->l[i], 8) & 0x00FF00FF);
1523#endif
1524 return block->l[i];
1525}
1526
1527/* Avoid redefine warning (ARM /usr/include/sys/ucontext.h define R0~R4) */
1528#undef blk
1529#undef R0
1530#undef R1
1531#undef R2
1532#undef R3
1533#undef R4
1534
1535#define blk(i) \
1536 (block->l[i & 15] = rol(block->l[(i + 13) & 15] ^ block->l[(i + 8) & 15] ^ \
1537 block->l[(i + 2) & 15] ^ block->l[i & 15], \
1538 1))
1539#define R0(v, w, x, y, z, i) \
1540 z += ((w & (x ^ y)) ^ y) + blk0(block, i) + 0x5A827999 + rol(v, 5); \
1541 w = rol(w, 30);
1542#define R1(v, w, x, y, z, i) \
1543 z += ((w & (x ^ y)) ^ y) + blk(i) + 0x5A827999 + rol(v, 5); \
1544 w = rol(w, 30);
1545#define R2(v, w, x, y, z, i) \
1546 z += (w ^ x ^ y) + blk(i) + 0x6ED9EBA1 + rol(v, 5); \
1547 w = rol(w, 30);
1548#define R3(v, w, x, y, z, i) \
1549 z += (((w | x) & y) | (w & x)) + blk(i) + 0x8F1BBCDC + rol(v, 5); \
1550 w = rol(w, 30);
1551#define R4(v, w, x, y, z, i) \
1552 z += (w ^ x ^ y) + blk(i) + 0xCA62C1D6 + rol(v, 5); \
1553 w = rol(w, 30);
1554
1555void cs_sha1_transform(uint32_t state[5], const unsigned char buffer[64]) {
1556 uint32_t a, b, c, d, e;
1557 union char64long16 block[1];
1558
1559 memcpy(block, buffer, 64);
1560 a = state[0];
1561 b = state[1];
1562 c = state[2];
1563 d = state[3];
1564 e = state[4];
1565 R0(a, b, c, d, e, 0);
1566 R0(e, a, b, c, d, 1);
1567 R0(d, e, a, b, c, 2);
1568 R0(c, d, e, a, b, 3);
1569 R0(b, c, d, e, a, 4);
1570 R0(a, b, c, d, e, 5);
1571 R0(e, a, b, c, d, 6);
1572 R0(d, e, a, b, c, 7);
1573 R0(c, d, e, a, b, 8);
1574 R0(b, c, d, e, a, 9);
1575 R0(a, b, c, d, e, 10);
1576 R0(e, a, b, c, d, 11);
1577 R0(d, e, a, b, c, 12);
1578 R0(c, d, e, a, b, 13);
1579 R0(b, c, d, e, a, 14);
1580 R0(a, b, c, d, e, 15);
1581 R1(e, a, b, c, d, 16);
1582 R1(d, e, a, b, c, 17);
1583 R1(c, d, e, a, b, 18);
1584 R1(b, c, d, e, a, 19);
1585 R2(a, b, c, d, e, 20);
1586 R2(e, a, b, c, d, 21);
1587 R2(d, e, a, b, c, 22);
1588 R2(c, d, e, a, b, 23);
1589 R2(b, c, d, e, a, 24);
1590 R2(a, b, c, d, e, 25);
1591 R2(e, a, b, c, d, 26);
1592 R2(d, e, a, b, c, 27);
1593 R2(c, d, e, a, b, 28);
1594 R2(b, c, d, e, a, 29);
1595 R2(a, b, c, d, e, 30);
1596 R2(e, a, b, c, d, 31);
1597 R2(d, e, a, b, c, 32);
1598 R2(c, d, e, a, b, 33);
1599 R2(b, c, d, e, a, 34);
1600 R2(a, b, c, d, e, 35);
1601 R2(e, a, b, c, d, 36);
1602 R2(d, e, a, b, c, 37);
1603 R2(c, d, e, a, b, 38);
1604 R2(b, c, d, e, a, 39);
1605 R3(a, b, c, d, e, 40);
1606 R3(e, a, b, c, d, 41);
1607 R3(d, e, a, b, c, 42);
1608 R3(c, d, e, a, b, 43);
1609 R3(b, c, d, e, a, 44);
1610 R3(a, b, c, d, e, 45);
1611 R3(e, a, b, c, d, 46);
1612 R3(d, e, a, b, c, 47);
1613 R3(c, d, e, a, b, 48);
1614 R3(b, c, d, e, a, 49);
1615 R3(a, b, c, d, e, 50);
1616 R3(e, a, b, c, d, 51);
1617 R3(d, e, a, b, c, 52);
1618 R3(c, d, e, a, b, 53);
1619 R3(b, c, d, e, a, 54);
1620 R3(a, b, c, d, e, 55);
1621 R3(e, a, b, c, d, 56);
1622 R3(d, e, a, b, c, 57);
1623 R3(c, d, e, a, b, 58);
1624 R3(b, c, d, e, a, 59);
1625 R4(a, b, c, d, e, 60);
1626 R4(e, a, b, c, d, 61);
1627 R4(d, e, a, b, c, 62);
1628 R4(c, d, e, a, b, 63);
1629 R4(b, c, d, e, a, 64);
1630 R4(a, b, c, d, e, 65);
1631 R4(e, a, b, c, d, 66);
1632 R4(d, e, a, b, c, 67);
1633 R4(c, d, e, a, b, 68);
1634 R4(b, c, d, e, a, 69);
1635 R4(a, b, c, d, e, 70);
1636 R4(e, a, b, c, d, 71);
1637 R4(d, e, a, b, c, 72);
1638 R4(c, d, e, a, b, 73);
1639 R4(b, c, d, e, a, 74);
1640 R4(a, b, c, d, e, 75);
1641 R4(e, a, b, c, d, 76);
1642 R4(d, e, a, b, c, 77);
1643 R4(c, d, e, a, b, 78);
1644 R4(b, c, d, e, a, 79);
1645 state[0] += a;
1646 state[1] += b;
1647 state[2] += c;
1648 state[3] += d;
1649 state[4] += e;
1650 /* Erase working structures. The order of operations is important,
1651 * used to ensure that compiler doesn't optimize those out. */
1652 memset(block, 0, sizeof(block));
1653 a = b = c = d = e = 0;
1654 (void) a;
1655 (void) b;
1656 (void) c;
1657 (void) d;
1658 (void) e;
1659}
1660
1662 context->state[0] = 0x67452301;
1663 context->state[1] = 0xEFCDAB89;
1664 context->state[2] = 0x98BADCFE;
1665 context->state[3] = 0x10325476;
1666 context->state[4] = 0xC3D2E1F0;
1667 context->count[0] = context->count[1] = 0;
1668}
1669
1670void cs_sha1_update(cs_sha1_ctx *context, const unsigned char *data,
1671 uint32_t len) {
1672 uint32_t i, j;
1673
1674 j = context->count[0];
1675 if ((context->count[0] += len << 3) < j) context->count[1]++;
1676 context->count[1] += (len >> 29);
1677 j = (j >> 3) & 63;
1678 if ((j + len) > 63) {
1679 memcpy(&context->buffer[j], data, (i = 64 - j));
1680 cs_sha1_transform(context->state, context->buffer);
1681 for (; i + 63 < len; i += 64) {
1682 cs_sha1_transform(context->state, &data[i]);
1683 }
1684 j = 0;
1685 } else
1686 i = 0;
1687 memcpy(&context->buffer[j], &data[i], len - i);
1688}
1689
1690void cs_sha1_final(unsigned char digest[20], cs_sha1_ctx *context) {
1691 unsigned i;
1692 unsigned char finalcount[8], c;
1693
1694 for (i = 0; i < 8; i++) {
1695 finalcount[i] = (unsigned char) ((context->count[(i >= 4 ? 0 : 1)] >>
1696 ((3 - (i & 3)) * 8)) &
1697 255);
1698 }
1699 c = 0200;
1700 cs_sha1_update(context, &c, 1);
1701 while ((context->count[0] & 504) != 448) {
1702 c = 0000;
1703 cs_sha1_update(context, &c, 1);
1704 }
1705 cs_sha1_update(context, finalcount, 8);
1706 for (i = 0; i < 20; i++) {
1707 digest[i] =
1708 (unsigned char) ((context->state[i >> 2] >> ((3 - (i & 3)) * 8)) & 255);
1709 }
1710 memset(context, '\0', sizeof(*context));
1711 memset(&finalcount, '\0', sizeof(finalcount));
1712}
1713
1714void cs_hmac_sha1(const unsigned char *key, size_t keylen,
1715 const unsigned char *data, size_t datalen,
1716 unsigned char out[20]) {
1717 cs_sha1_ctx ctx;
1718 unsigned char buf1[64], buf2[64], tmp_key[20], i;
1719
1720 if (keylen > sizeof(buf1)) {
1721 cs_sha1_init(&ctx);
1722 cs_sha1_update(&ctx, key, keylen);
1723 cs_sha1_final(tmp_key, &ctx);
1724 key = tmp_key;
1725 keylen = sizeof(tmp_key);
1726 }
1727
1728 memset(buf1, 0, sizeof(buf1));
1729 memset(buf2, 0, sizeof(buf2));
1730 memcpy(buf1, key, keylen);
1731 memcpy(buf2, key, keylen);
1732
1733 for (i = 0; i < sizeof(buf1); i++) {
1734 buf1[i] ^= 0x36;
1735 buf2[i] ^= 0x5c;
1736 }
1737
1738 cs_sha1_init(&ctx);
1739 cs_sha1_update(&ctx, buf1, sizeof(buf1));
1740 cs_sha1_update(&ctx, data, datalen);
1741 cs_sha1_final(out, &ctx);
1742
1743 cs_sha1_init(&ctx);
1744 cs_sha1_update(&ctx, buf2, sizeof(buf2));
1745 cs_sha1_update(&ctx, out, 20);
1746 cs_sha1_final(out, &ctx);
1747}
1748
1749#endif /* EXCLUDE_COMMON */
1750#ifdef MG_MODULE_LINES
1751#line 1 "./src/../../common/str_util.c"
1752#endif
1753/*
1754 * Copyright (c) 2015 Cesanta Software Limited
1755 * All rights reserved
1756 */
1757
1758#ifndef EXCLUDE_COMMON
1759
1760/* Amalgamated: #include "common/platform.h" */
1761/* Amalgamated: #include "common/str_util.h" */
1762
1763size_t c_strnlen(const char *s, size_t maxlen) {
1764 size_t l = 0;
1765 for (; l < maxlen && s[l] != '\0'; l++) {
1766 }
1767 return l;
1768}
1769
1770#define C_SNPRINTF_APPEND_CHAR(ch) \
1771 do { \
1772 if (i < (int) buf_size) buf[i] = ch; \
1773 i++; \
1774 } while (0)
1775
1776#define C_SNPRINTF_FLAG_ZERO 1
1777
1778#ifdef C_DISABLE_BUILTIN_SNPRINTF
1779int c_vsnprintf(char *buf, size_t buf_size, const char *fmt, va_list ap) {
1780 return vsnprintf(buf, buf_size, fmt, ap);
1781}
1782#else
1783static int c_itoa(char *buf, size_t buf_size, int64_t num, int base, int flags,
1784 int field_width) {
1785 char tmp[40];
1786 int i = 0, k = 0, neg = 0;
1787
1788 if (num < 0) {
1789 neg++;
1790 num = -num;
1791 }
1792
1793 /* Print into temporary buffer - in reverse order */
1794 do {
1795 int rem = num % base;
1796 if (rem < 10) {
1797 tmp[k++] = '0' + rem;
1798 } else {
1799 tmp[k++] = 'a' + (rem - 10);
1800 }
1801 num /= base;
1802 } while (num > 0);
1803
1804 /* Zero padding */
1805 if (flags && C_SNPRINTF_FLAG_ZERO) {
1806 while (k < field_width && k < (int) sizeof(tmp) - 1) {
1807 tmp[k++] = '0';
1808 }
1809 }
1810
1811 /* And sign */
1812 if (neg) {
1813 tmp[k++] = '-';
1814 }
1815
1816 /* Now output */
1817 while (--k >= 0) {
1819 }
1820
1821 return i;
1822}
1823
1824int c_vsnprintf(char *buf, size_t buf_size, const char *fmt, va_list ap) {
1825 int ch, i = 0, len_mod, flags, precision, field_width;
1826
1827 while ((ch = *fmt++) != '\0') {
1828 if (ch != '%') {
1830 } else {
1831 /*
1832 * Conversion specification:
1833 * zero or more flags (one of: # 0 - <space> + ')
1834 * an optional minimum field width (digits)
1835 * an optional precision (. followed by digits, or *)
1836 * an optional length modifier (one of: hh h l ll L q j z t)
1837 * conversion specifier (one of: d i o u x X e E f F g G a A c s p n)
1838 */
1839 flags = field_width = precision = len_mod = 0;
1840
1841 /* Flags. only zero-pad flag is supported. */
1842 if (*fmt == '0') {
1843 flags |= C_SNPRINTF_FLAG_ZERO;
1844 }
1845
1846 /* Field width */
1847 while (*fmt >= '0' && *fmt <= '9') {
1848 field_width *= 10;
1849 field_width += *fmt++ - '0';
1850 }
1851 /* Dynamic field width */
1852 if (*fmt == '*') {
1853 field_width = va_arg(ap, int);
1854 fmt++;
1855 }
1856
1857 /* Precision */
1858 if (*fmt == '.') {
1859 fmt++;
1860 if (*fmt == '*') {
1861 precision = va_arg(ap, int);
1862 fmt++;
1863 } else {
1864 while (*fmt >= '0' && *fmt <= '9') {
1865 precision *= 10;
1866 precision += *fmt++ - '0';
1867 }
1868 }
1869 }
1870
1871 /* Length modifier */
1872 switch (*fmt) {
1873 case 'h':
1874 case 'l':
1875 case 'L':
1876 case 'I':
1877 case 'q':
1878 case 'j':
1879 case 'z':
1880 case 't':
1881 len_mod = *fmt++;
1882 if (*fmt == 'h') {
1883 len_mod = 'H';
1884 fmt++;
1885 }
1886 if (*fmt == 'l') {
1887 len_mod = 'q';
1888 fmt++;
1889 }
1890 break;
1891 }
1892
1893 ch = *fmt++;
1894 if (ch == 's') {
1895 const char *s = va_arg(ap, const char *); /* Always fetch parameter */
1896 int j;
1897 int pad = field_width - (precision >= 0 ? c_strnlen(s, precision) : 0);
1898 for (j = 0; j < pad; j++) {
1900 }
1901
1902 /* `s` may be NULL in case of %.*s */
1903 if (s != NULL) {
1904 /* Ignore negative and 0 precisions */
1905 for (j = 0; (precision <= 0 || j < precision) && s[j] != '\0'; j++) {
1907 }
1908 }
1909 } else if (ch == 'c') {
1910 ch = va_arg(ap, int); /* Always fetch parameter */
1912 } else if (ch == 'd' && len_mod == 0) {
1913 i += c_itoa(buf + i, buf_size - i, va_arg(ap, int), 10, flags,
1914 field_width);
1915 } else if (ch == 'd' && len_mod == 'l') {
1916 i += c_itoa(buf + i, buf_size - i, va_arg(ap, long), 10, flags,
1917 field_width);
1918#ifdef SSIZE_MAX
1919 } else if (ch == 'd' && len_mod == 'z') {
1920 i += c_itoa(buf + i, buf_size - i, va_arg(ap, ssize_t), 10, flags,
1921 field_width);
1922#endif
1923 } else if (ch == 'd' && len_mod == 'q') {
1924 i += c_itoa(buf + i, buf_size - i, va_arg(ap, int64_t), 10, flags,
1925 field_width);
1926 } else if ((ch == 'x' || ch == 'u') && len_mod == 0) {
1927 i += c_itoa(buf + i, buf_size - i, va_arg(ap, unsigned),
1928 ch == 'x' ? 16 : 10, flags, field_width);
1929 } else if ((ch == 'x' || ch == 'u') && len_mod == 'l') {
1930 i += c_itoa(buf + i, buf_size - i, va_arg(ap, unsigned long),
1931 ch == 'x' ? 16 : 10, flags, field_width);
1932 } else if ((ch == 'x' || ch == 'u') && len_mod == 'z') {
1933 i += c_itoa(buf + i, buf_size - i, va_arg(ap, size_t),
1934 ch == 'x' ? 16 : 10, flags, field_width);
1935 } else if (ch == 'p') {
1936 unsigned long num = (unsigned long) va_arg(ap, void *);
1939 i += c_itoa(buf + i, buf_size - i, num, 16, flags, 0);
1940 } else {
1941#ifndef NO_LIBC
1942 /*
1943 * TODO(lsm): abort is not nice in a library, remove it
1944 * Also, ESP8266 SDK doesn't have it
1945 */
1946 abort();
1947#endif
1948 }
1949 }
1950 }
1951
1952 /* Zero-terminate the result */
1953 if (buf_size > 0) {
1954 buf[i < (int) buf_size ? i : (int) buf_size - 1] = '\0';
1955 }
1956
1957 return i;
1958}
1959#endif
1960
1961int c_snprintf(char *buf, size_t buf_size, const char *fmt, ...) {
1962 int result;
1963 va_list ap;
1964 va_start(ap, fmt);
1965 result = c_vsnprintf(buf, buf_size, fmt, ap);
1966 va_end(ap);
1967 return result;
1968}
1969
1970#ifdef _WIN32
1971int to_wchar(const char *path, wchar_t *wbuf, size_t wbuf_len) {
1972 int ret;
1973 char buf[MAX_PATH * 2], buf2[MAX_PATH * 2], *p;
1974
1975 strncpy(buf, path, sizeof(buf));
1976 buf[sizeof(buf) - 1] = '\0';
1977
1978 /* Trim trailing slashes. Leave backslash for paths like "X:\" */
1979 p = buf + strlen(buf) - 1;
1980 while (p > buf && p[-1] != ':' && (p[0] == '\\' || p[0] == '/')) *p-- = '\0';
1981
1982 memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
1983 ret = MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int) wbuf_len);
1984
1985 /*
1986 * Convert back to Unicode. If doubly-converted string does not match the
1987 * original, something is fishy, reject.
1988 */
1989 WideCharToMultiByte(CP_UTF8, 0, wbuf, (int) wbuf_len, buf2, sizeof(buf2),
1990 NULL, NULL);
1991 if (strcmp(buf, buf2) != 0) {
1992 wbuf[0] = L'\0';
1993 ret = 0;
1994 }
1995
1996 return ret;
1997}
1998#endif /* _WIN32 */
1999
2000/* The simplest O(mn) algorithm. Better implementation are GPLed */
2001const char *c_strnstr(const char *s, const char *find, size_t slen) {
2002 size_t find_length = strlen(find);
2003 size_t i;
2004
2005 for (i = 0; i < slen; i++) {
2006 if (i + find_length > slen) {
2007 return NULL;
2008 }
2009
2010 if (strncmp(&s[i], find, find_length) == 0) {
2011 return &s[i];
2012 }
2013 }
2014
2015 return NULL;
2016}
2017
2018#endif /* EXCLUDE_COMMON */
2019#ifdef MG_MODULE_LINES
2020#line 1 "./src/net.c"
2021#endif
2022/*
2023 * Copyright (c) 2014 Cesanta Software Limited
2024 * All rights reserved
2025 *
2026 * This software is dual-licensed: you can redistribute it and/or modify
2027 * it under the terms of the GNU General Public License version 2 as
2028 * published by the Free Software Foundation. For the terms of this
2029 * license, see <http://www.gnu.org/licenses/>.
2030 *
2031 * You are free to use this software under the terms of the GNU General
2032 * Public License, but WITHOUT ANY WARRANTY; without even the implied
2033 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
2034 * See the GNU General Public License for more details.
2035 *
2036 * Alternatively, you can license this software under a commercial
2037 * license, as set out in <https://www.cesanta.com/license>.
2038 */
2039
2040/* Amalgamated: #include "mongoose/src/internal.h" */
2041/* Amalgamated: #include "mongoose/src/util.h" */
2042/* Amalgamated: #include "mongoose/src/dns.h" */
2043/* Amalgamated: #include "mongoose/src/resolv.h" */
2044/* Amalgamated: #include "common/cs_time.h" */
2045
2046#define MG_MAX_HOST_LEN 200
2047
2048#define MG_COPY_COMMON_CONNECTION_OPTIONS(dst, src) \
2049 memcpy(dst, src, sizeof(*dst));
2050
2051/* Which flags can be pre-set by the user at connection creation time. */
2052#define _MG_ALLOWED_CONNECT_FLAGS_MASK \
2053 (MG_F_USER_1 | MG_F_USER_2 | MG_F_USER_3 | MG_F_USER_4 | MG_F_USER_5 | \
2054 MG_F_USER_6 | MG_F_WEBSOCKET_NO_DEFRAG)
2055/* Which flags should be modifiable by user's callbacks. */
2056#define _MG_CALLBACK_MODIFIABLE_FLAGS_MASK \
2057 (MG_F_USER_1 | MG_F_USER_2 | MG_F_USER_3 | MG_F_USER_4 | MG_F_USER_5 | \
2058 MG_F_USER_6 | MG_F_WEBSOCKET_NO_DEFRAG | MG_F_SEND_AND_CLOSE | \
2059 MG_F_CLOSE_IMMEDIATELY | MG_F_IS_WEBSOCKET | MG_F_DELETE_CHUNK)
2060
2061#ifndef intptr_t
2062#define intptr_t long
2063#endif
2064
2065int mg_is_error(int n);
2067
2068extern void mg_ev_mgr_init(struct mg_mgr *mgr);
2069extern void mg_ev_mgr_free(struct mg_mgr *mgr);
2070extern void mg_ev_mgr_add_conn(struct mg_connection *nc);
2071extern void mg_ev_mgr_remove_conn(struct mg_connection *nc);
2072
2073MG_INTERNAL void mg_add_conn(struct mg_mgr *mgr, struct mg_connection *c) {
2074 DBG(("%p %p", mgr, c));
2075 //printf("nc %p -> mg_add_conn, mgr %p %p, pd %p, fp %p\n", c, c->mgr, mgr, c->proto_data, (c->proto_data?*(FILE**)c->proto_data:NULL));
2076 c->mgr = mgr;
2077 c->next = mgr->active_connections;
2078 mgr->active_connections = c;
2079 c->prev = NULL;
2080 if (c->next != NULL) c->next->prev = c;
2082}
2083
2085 if (conn->prev == NULL) conn->mgr->active_connections = conn->next;
2086 if (conn->prev) conn->prev->next = conn->next;
2087 if (conn->next) conn->next->prev = conn->prev;
2089}
2090
2093 if (ev_handler == NULL) {
2094 /*
2095 * If protocol handler is specified, call it. Otherwise, call user-specified
2096 * event handler.
2097 */
2099 }
2100 DBG(("%p %s ev=%d ev_data=%p flags=%lu rmbl=%d smbl=%d", nc,
2101 ev_handler == nc->handler ? "user" : "proto", ev, ev_data, nc->flags,
2102 (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len));
2103
2104#if !defined(NO_LIBC) && !defined(MG_DISABLE_HEXDUMP)
2105 /* LCOV_EXCL_START */
2106 if (nc->mgr->hexdump_file != NULL && ev != MG_EV_POLL &&
2107 ev != MG_EV_SEND /* handled separately */) {
2108 if (ev == MG_EV_RECV) {
2110 *(int *) ev_data, ev);
2111 } else {
2113 }
2114 }
2115/* LCOV_EXCL_STOP */
2116#endif
2117 if (ev_handler != NULL) {
2118 unsigned long flags_before = nc->flags;
2119 size_t recv_mbuf_before = nc->recv_mbuf.len, recved;
2120 ev_handler(nc, ev, ev_data);
2122 /* Prevent user handler from fiddling with system flags. */
2123 if (ev_handler == nc->handler && nc->flags != flags_before) {
2126 }
2127 if (recved > 0 && !(nc->flags & MG_F_UDP)) {
2128 mg_if_recved(nc, recved);
2129 }
2130 }
2131 DBG(("%p after %s flags=%lu rmbl=%d smbl=%d", nc,
2132 ev_handler == nc->handler ? "user" : "proto", nc->flags,
2133 (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len));
2134}
2135
2136void mg_if_timer(struct mg_connection *c, double now) {
2137 if (c->ev_timer_time > 0 && now >= c->ev_timer_time) {
2138 double old_value = c->ev_timer_time;
2140 /*
2141 * To prevent timer firing all the time, reset the timer after delivery.
2142 * However, in case user sets it to new value, do not reset.
2143 */
2144 if (c->ev_timer_time == old_value) {
2145 c->ev_timer_time = 0;
2146 }
2147 }
2148}
2149
2151 if (nc->ssl == NULL || (nc->flags & MG_F_SSL_HANDSHAKE_DONE)) {
2152 mg_call(nc, NULL, MG_EV_POLL, &now);
2153 }
2154}
2155
2156static void mg_destroy_conn(struct mg_connection *conn) {
2157 if (conn->proto_data != NULL && conn->proto_data_destructor != NULL) {
2158 conn->proto_data_destructor(conn->proto_data);
2159 }
2160 mg_if_destroy_conn(conn);
2161#ifdef MG_ENABLE_SSL
2162 if (conn->ssl != NULL) SSL_free(conn->ssl);
2163 if (conn->ssl_ctx != NULL) SSL_CTX_free(conn->ssl_ctx);
2164#endif
2165 mbuf_free(&conn->recv_mbuf);
2166 mbuf_free(&conn->send_mbuf);
2167
2168 memset(conn, 0, sizeof(*conn));
2169 MG_FREE(conn);
2170}
2171
2172void mg_close_conn(struct mg_connection *conn) {
2173 DBG(("%p %lu", conn, conn->flags));
2174 mg_call(conn, NULL, MG_EV_CLOSE, NULL);
2175 mg_remove_conn(conn);
2176 mg_destroy_conn(conn);
2177}
2178
2179void mg_mgr_init(struct mg_mgr *m, void *user_data) {
2180 memset(m, 0, sizeof(*m));
2181#ifndef MG_DISABLE_SOCKETPAIR
2182 m->ctl[0] = m->ctl[1] = INVALID_SOCKET;
2183#endif
2184 m->user_data = user_data;
2185
2186#ifdef _WIN32
2187 {
2188 WSADATA data;
2189 WSAStartup(MAKEWORD(2, 2), &data);
2190 }
2191#elif defined(__unix__)
2192 /* Ignore SIGPIPE signal, so if client cancels the request, it
2193 * won't kill the whole process. */
2195#endif
2196
2197#ifdef MG_ENABLE_SSL
2198 {
2199 static int init_done;
2200 if (!init_done) {
2202 init_done++;
2203 }
2204 }
2205#endif
2206
2207 mg_ev_mgr_init(m);
2208 DBG(("=================================="));
2209 DBG(("init mgr=%p", m));
2210}
2211
2212#ifdef MG_ENABLE_JAVASCRIPT
2213static enum v7_err mg_send_js(struct v7 *v7, v7_val_t *res) {
2214 v7_val_t arg0 = v7_arg(v7, 0);
2215 v7_val_t arg1 = v7_arg(v7, 1);
2216 struct mg_connection *c = (struct mg_connection *) v7_to_foreign(arg0);
2217 size_t len = 0;
2218
2219 if (v7_is_string(arg1)) {
2220 const char *data = v7_get_string_data(v7, &arg1, &len);
2221 mg_send(c, data, len);
2222 }
2223
2224 *res = v7_mk_number(len);
2225
2226 return V7_OK;
2227}
2228
2229enum v7_err mg_enable_javascript(struct mg_mgr *m, struct v7 *v7,
2230 const char *init_file_name) {
2231 v7_val_t v;
2232 m->v7 = v7;
2234 return v7_exec_file(v7, init_file_name, &v);
2235}
2236#endif
2237
2238void mg_mgr_free(struct mg_mgr *m) {
2239 struct mg_connection *conn, *tmp_conn;
2240
2241 DBG(("%p", m));
2242 if (m == NULL) return;
2243 /* Do one last poll, see https://github.com/cesanta/mongoose/issues/286 */
2244 mg_mgr_poll(m, 0);
2245
2246#ifndef MG_DISABLE_SOCKETPAIR
2247 if (m->ctl[0] != INVALID_SOCKET) closesocket(m->ctl[0]);
2248 if (m->ctl[1] != INVALID_SOCKET) closesocket(m->ctl[1]);
2249 m->ctl[0] = m->ctl[1] = INVALID_SOCKET;
2250#endif
2251
2252 for (conn = m->active_connections; conn != NULL; conn = tmp_conn) {
2253 tmp_conn = conn->next;
2254 mg_close_conn(conn);
2255 }
2256
2257 mg_ev_mgr_free(m);
2258}
2259
2260int mg_vprintf(struct mg_connection *nc, const char *fmt, va_list ap) {
2262 int len;
2263
2264 if ((len = mg_avprintf(&buf, sizeof(mem), fmt, ap)) > 0) {
2265 mg_send(nc, buf, len);
2266 }
2267 if (buf != mem && buf != NULL) {
2268 MG_FREE(buf); /* LCOV_EXCL_LINE */
2269 } /* LCOV_EXCL_LINE */
2270
2271 return len;
2272}
2273
2274int mg_printf(struct mg_connection *conn, const char *fmt, ...) {
2275 int len;
2276 va_list ap;
2277 va_start(ap, fmt);
2278 len = mg_vprintf(conn, fmt, ap);
2279 va_end(ap);
2280 return len;
2281}
2282
2283#ifndef MG_DISABLE_SYNC_RESOLVER
2284/* TODO(lsm): use non-blocking resolver */
2285static int mg_resolve2(const char *host, struct in_addr *ina) {
2286#ifdef MG_ENABLE_GETADDRINFO
2287 int rv = 0;
2288 struct addrinfo hints, *servinfo, *p;
2289 struct sockaddr_in *h = NULL;
2290 memset(&hints, 0, sizeof hints);
2291 hints.ai_family = AF_INET;
2292 hints.ai_socktype = SOCK_STREAM;
2293 if ((rv = getaddrinfo(host, NULL, NULL, &servinfo)) != 0) {
2294 DBG(("getaddrinfo(%s) failed: %s", host, strerror(errno)));
2295 return 0;
2296 }
2297 for (p = servinfo; p != NULL; p = p->ai_next) {
2298 memcpy(&h, &p->ai_addr, sizeof(struct sockaddr_in *));
2299 memcpy(ina, &h->sin_addr, sizeof(ina));
2300 }
2302 return 1;
2303#else
2304 struct hostent *he;
2305 if ((he = gethostbyname(host)) == NULL) {
2306 DBG(("gethostbyname(%s) failed: %s", host, strerror(errno)));
2307 } else {
2308 memcpy(ina, he->h_addr_list[0], sizeof(*ina));
2309 return 1;
2310 }
2311 return 0;
2312#endif /* MG_ENABLE_GETADDRINFO */
2313}
2314
2315int mg_resolve(const char *host, char *buf, size_t n) {
2316 struct in_addr ad;
2317 return mg_resolve2(host, &ad) ? snprintf(buf, n, "%s", inet_ntoa(ad)) : 0;
2318}
2319#endif /* MG_DISABLE_SYNC_RESOLVER */
2320
2323 struct mg_add_sock_opts opts) {
2324 struct mg_connection *conn;
2325
2326 if ((conn = (struct mg_connection *) MG_CALLOC(1, sizeof(*conn))) != NULL) {
2327 conn->sock = INVALID_SOCKET;
2328 conn->handler = callback;
2329 conn->mgr = mgr;
2330 conn->last_io_time = mg_time();
2332 conn->user_data = opts.user_data;
2333 /*
2334 * SIZE_MAX is defined as a long long constant in
2335 * system headers on some platforms and so it
2336 * doesn't compile with pedantic ansi flags.
2337 */
2338 conn->recv_mbuf_limit = ~0;
2339 } else {
2340 MG_SET_PTRPTR(opts.error_string, "failed to create connection");
2341 }
2342
2343 return conn;
2344}
2345
2348 struct mg_add_sock_opts opts) {
2350
2351 if (!mg_if_create_conn(conn)) {
2352 MG_FREE(conn);
2353 conn = NULL;
2354 MG_SET_PTRPTR(opts.error_string, "failed to init connection");
2355 }
2356
2357 return conn;
2358}
2359
2360/*
2361 * Address format: [PROTO://][HOST]:PORT
2362 *
2363 * HOST could be IPv4/IPv6 address or a host name.
2364 * `host` is a destination buffer to hold parsed HOST part. Shoud be at least
2365 * MG_MAX_HOST_LEN bytes long.
2366 * `proto` is a returned socket type, either SOCK_STREAM or SOCK_DGRAM
2367 *
2368 * Return:
2369 * -1 on parse error
2370 * 0 if HOST needs DNS lookup
2371 * >0 length of the address string
2372 */
2374 int *proto, char *host, size_t host_len) {
2375 unsigned int a, b, c, d, port = 0;
2376 int ch, len = 0;
2377#ifdef MG_ENABLE_IPV6
2378 char buf[100];
2379#endif
2380
2381 /*
2382 * MacOS needs that. If we do not zero it, subsequent bind() will fail.
2383 * Also, all-zeroes in the socket address means binding to all addresses
2384 * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT).
2385 */
2386 memset(sa, 0, sizeof(*sa));
2387 sa->sin.sin_family = AF_INET;
2388
2389 *proto = SOCK_STREAM;
2390
2391 if (strncmp(str, "udp://", 6) == 0) {
2392 str += 6;
2393 *proto = SOCK_DGRAM;
2394 } else if (strncmp(str, "tcp://", 6) == 0) {
2395 str += 6;
2396 }
2397
2398 if (sscanf(str, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len) == 5) {
2399 /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
2400 sa->sin.sin_addr.s_addr =
2401 htonl(((uint32_t) a << 24) | ((uint32_t) b << 16) | c << 8 | d);
2402 sa->sin.sin_port = htons((uint16_t) port);
2403#ifdef MG_ENABLE_IPV6
2404 } else if (sscanf(str, "[%99[^]]]:%u%n", buf, &port, &len) == 2 &&
2405 inet_pton(AF_INET6, buf, &sa->sin6.sin6_addr)) {
2406 /* IPv6 address, e.g. [3ffe:2a00:100:7031::1]:8080 */
2407 sa->sin6.sin6_family = AF_INET6;
2408 sa->sin.sin_port = htons((uint16_t) port);
2409#endif
2410#ifndef MG_DISABLE_RESOLVER
2411 } else if (strlen(str) < host_len &&
2412 sscanf(str, "%[^ :]:%u%n", host, &port, &len) == 2) {
2413 sa->sin.sin_port = htons((uint16_t) port);
2414 if (mg_resolve_from_hosts_file(host, sa) != 0) {
2415 return 0;
2416 }
2417#endif
2418 } else if (sscanf(str, ":%u%n", &port, &len) == 1 ||
2419 sscanf(str, "%u%n", &port, &len) == 1) {
2420 /* If only port is specified, bind to IPv4, INADDR_ANY */
2421 sa->sin.sin_port = htons((uint16_t) port);
2422 } else {
2423 return -1;
2424 }
2425
2426 ch = str[len]; /* Character that follows the address */
2427 return port < 0xffffUL && (ch == '\0' || ch == ',' || isspace(ch)) ? len : -1;
2428}
2429
2430#ifdef MG_ENABLE_SSL
2431/*
2432 * Certificate generation script is at
2433 * https://github.com/cesanta/mongoose/blob/master/scripts/generate_ssl_certificates.sh
2434 */
2435
2436#ifndef MG_DISABLE_PFS
2437/*
2438 * Cipher suite options used for TLS negotiation.
2439 * https://wiki.mozilla.org/Security/Server_Side_TLS#Recommended_configurations
2440 */
2441static const char mg_s_cipher_list[] =
2442#if defined(MG_SSL_CRYPTO_MODERN)
2443 "ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:"
2444 "ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:"
2445 "DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:"
2446 "ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:"
2447 "ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:"
2448 "ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:"
2449 "DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:"
2450 "DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:"
2451 "!aNULL:!eNULL:!EXPORT:!DES:!RC4:!3DES:!MD5:!PSK"
2452#elif defined(MG_SSL_CRYPTO_OLD)
2453 "ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:"
2454 "ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:"
2455 "DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:"
2456 "ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:"
2457 "ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:"
2458 "ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:"
2459 "DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:"
2460 "DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:ECDHE-RSA-DES-CBC3-SHA:"
2461 "ECDHE-ECDSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:"
2462 "AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:DES-CBC3-SHA:"
2463 "HIGH:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:"
2464 "!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA"
2465#else /* Default - intermediate. */
2466 "ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:"
2467 "ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:"
2468 "DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:"
2469 //"ECDHE-RSA-AES128-SHA256:"
2470 "ECDHE-ECDSA-AES128-SHA256:"
2471 //"ECDHE-RSA-AES128-SHA:"
2472 "ECDHE-ECDSA-AES128-SHA:"
2473 //"ECDHE-RSA-AES256-SHA384:"
2474 "ECDHE-ECDSA-AES256-SHA384:"
2475 //"ECDHE-RSA-AES256-SHA:"
2476 "ECDHE-ECDSA-AES256-SHA:"
2477 //"DHE-RSA-AES128-SHA256:"
2478 //"DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:"
2479 //"DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:"
2480 "AES128-GCM-SHA256:AES256-GCM-SHA384:"
2481 "AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:"
2482 "AES:"
2483 "!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:!RSA:!CBC-SHA:!CAMELLIA:"
2484 "!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA"
2485#endif
2486 ;
2487
2488/*
2489 * Default DH params for PFS cipher negotiation. This is a 2048-bit group.
2490 * Will be used if none are provided by the user in the certificate file.
2491 */
2492static const char mg_s_default_dh_params[] =
2493 "\
2494-----BEGIN DH PARAMETERS-----\n\
2495MIIBCAKCAQEAlvbgD/qh9znWIlGFcV0zdltD7rq8FeShIqIhkQ0C7hYFThrBvF2E\n\
2496Z9bmgaP+sfQwGpVlv9mtaWjvERbu6mEG7JTkgmVUJrUt/wiRzwTaCXBqZkdUO8Tq\n\
2497+E6VOEQAilstG90ikN1Tfo+K6+X68XkRUIlgawBTKuvKVwBhuvlqTGerOtnXWnrt\n\
2498ym//hd3cd5PBYGBix0i7oR4xdghvfR2WLVu0LgdThTBb6XP7gLd19cQ1JuBtAajZ\n\
2499wMuPn7qlUkEFDIkAZy59/Hue/H2Q2vU/JsvVhHWCQBL4F1ofEAt50il6ZxR1QfFK\n\
25009VGKDC4oOgm9DlxwwBoC2FjqmvQlqVV3kwIBAg==\n\
2501-----END DH PARAMETERS-----\n";
2502#endif
2503
2504static int mg_use_ca_cert(SSL_CTX *ctx, const char *cert) {
2505 if (ctx == NULL) {
2506 return -1;
2507 } else if (cert == NULL || cert[0] == '\0') {
2508 return 0;
2509 }
2511 return SSL_CTX_load_verify_locations(ctx, cert, NULL) == 1 ? 0 : -2;
2512}
2513
2514static int mg_use_cert(SSL_CTX *ctx, const char *pem_file) {
2515 if (ctx == NULL) {
2516 return -1;
2517 } else if (pem_file == NULL || pem_file[0] == '\0') {
2518 return 0;
2519 } else if (SSL_CTX_use_certificate_file(ctx, pem_file, 1) == 0 ||
2521 return -2;
2522 } else {
2523#ifndef MG_DISABLE_PFS
2524 BIO *bio = NULL;
2525 DH *dh = NULL;
2526
2527 /* Try to read DH parameters from the cert/key file. */
2528 bio = BIO_new_file(pem_file, "r");
2529 if (bio != NULL) {
2531 BIO_free(bio);
2532 }
2533 /*
2534 * If there are no DH params in the file, fall back to hard-coded ones.
2535 * Not ideal, but better than nothing.
2536 */
2537 if (dh == NULL) {
2540 BIO_free(bio);
2541 }
2542 if (dh != NULL) {
2545 DH_free(dh);
2546 }
2547#endif
2550 return 0;
2551 }
2552}
2553
2554/*
2555 * Turn the connection into SSL mode.
2556 * `cert` is the certificate file in PEM format. For listening connections,
2557 * certificate file must contain private key and server certificate,
2558 * concatenated. It may also contain DH params - these will be used for more
2559 * secure key exchange. `ca_cert` is a certificate authority (CA) PEM file, and
2560 * it is optional (can be set to NULL). If `ca_cert` is non-NULL, then
2561 * the connection is so-called two-way-SSL: other peer's certificate is
2562 * checked against the `ca_cert`.
2563 *
2564 * Handy OpenSSL command to generate test self-signed certificate:
2565 *
2566 * openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 999
2567 *
2568 * Return NULL on success, or error message on failure.
2569 */
2570const char *mg_set_ssl(struct mg_connection *nc, const char *cert,
2571 const char *ca_cert) {
2572 const char *result = NULL;
2573 DBG(("%p %s %s", nc, (cert ? cert : ""), (ca_cert ? ca_cert : "")));
2574
2575 if (nc->flags & MG_F_UDP) {
2576 return "SSL for UDP is not supported";
2577 }
2578
2579 if (nc->ssl != NULL) {
2580 SSL_free(nc->ssl);
2581 nc->ssl = NULL;
2582 }
2583 if (nc->ssl_ctx != NULL) {
2584 SSL_CTX_free(nc->ssl_ctx);
2585 nc->ssl_ctx = NULL;
2586 }
2587
2588 if ((nc->flags & MG_F_LISTENING) &&
2590 result = "SSL_CTX_new() failed";
2591 } else if (!(nc->flags & MG_F_LISTENING) &&
2593 result = "SSL_CTX_new() failed";
2594 } else if (mg_use_cert(nc->ssl_ctx, cert) != 0) {
2595 result = "Invalid ssl cert";
2596 } else if (mg_use_ca_cert(nc->ssl_ctx, ca_cert) != 0) {
2597 result = "Invalid CA cert";
2598 } else if (!(nc->flags & MG_F_LISTENING) &&
2599 (nc->ssl = SSL_new(nc->ssl_ctx)) == NULL) {
2600 result = "SSL_new() failed";
2601 } else if (!(nc->flags & MG_F_LISTENING) && nc->sock != INVALID_SOCKET) {
2602 /*
2603 * Socket is open here only if we are connecting to IP address
2604 * and does not open if we are connecting using async DNS resolver
2605 */
2606 SSL_set_fd(nc->ssl, nc->sock);
2607 }
2608
2611
2612#ifndef MG_DISABLE_PFS
2614#endif
2615 return result;
2616}
2617#endif /* MG_ENABLE_SSL */
2618
2620 struct mg_add_sock_opts opts;
2621 struct mg_connection *nc;
2622 memset(&opts, 0, sizeof(opts));
2623 nc = mg_create_connection(lc->mgr, lc->handler, opts);
2624 if (nc == NULL) return NULL;
2625 nc->listener = lc;
2626 nc->proto_handler = lc->proto_handler;
2627 nc->user_data = lc->user_data;
2629 mg_add_conn(nc->mgr, nc);
2630 DBG(("%p %p %d %d, %p %p", lc, nc, nc->sock, (int) nc->flags, lc->ssl_ctx,
2631 nc->ssl));
2632 return nc;
2633}
2634
2636 size_t sa_len) {
2637 (void) sa_len;
2638 nc->sa = *sa;
2639 mg_call(nc, NULL, MG_EV_ACCEPT, &nc->sa);
2640}
2641
2642void mg_send(struct mg_connection *nc, const void *buf, int len) {
2643 nc->last_io_time = mg_time();
2644 if (nc->flags & MG_F_UDP) {
2645 mg_if_udp_send(nc, buf, len);
2646 } else {
2647 mg_if_tcp_send(nc, buf, len);
2648 }
2649#if !defined(NO_LIBC) && !defined(MG_DISABLE_HEXDUMP)
2650 if (nc->mgr && nc->mgr->hexdump_file != NULL) {
2652 }
2653#endif
2654}
2655
2656void mg_if_sent_cb(struct mg_connection *nc, int num_sent) {
2657 if (num_sent < 0) {
2659 }
2660 mg_call(nc, NULL, MG_EV_SEND, &num_sent);
2661}
2662
2663static void mg_recv_common(struct mg_connection *nc, void *buf, int len) {
2664 DBG(("%p %d %u", nc, len, (unsigned int) nc->recv_mbuf.len));
2665 if (nc->flags & MG_F_CLOSE_IMMEDIATELY) {
2666 DBG(("%p discarded %d bytes", nc, len));
2667 /*
2668 * This connection will not survive next poll. Do not deliver events,
2669 * send data to /dev/null without acking.
2670 */
2671 MG_FREE(buf);
2672 return;
2673 }
2674 nc->last_io_time = mg_time();
2675 if (nc->recv_mbuf.len == 0) {
2676 /* Adopt buf as recv_mbuf's backing store. */
2677 mbuf_free(&nc->recv_mbuf);
2678 nc->recv_mbuf.buf = (char *) buf;
2679 nc->recv_mbuf.size = nc->recv_mbuf.len = len;
2680 } else {
2681 mbuf_append(&nc->recv_mbuf, buf, len);
2682 MG_FREE(buf);
2683 }
2684 mg_call(nc, NULL, MG_EV_RECV, &len);
2685}
2686
2687void mg_if_recv_tcp_cb(struct mg_connection *nc, void *buf, int len) {
2688 mg_recv_common(nc, buf, len);
2689}
2690
2691void mg_if_recv_udp_cb(struct mg_connection *nc, void *buf, int len,
2692 union socket_address *sa, size_t sa_len) {
2693 assert(nc->flags & MG_F_UDP);
2694 DBG(("%p %u", nc, (unsigned int) len));
2695 if (nc->flags & MG_F_LISTENING) {
2696 struct mg_connection *lc = nc;
2697 /*
2698 * Do we have an existing connection for this source?
2699 * This is very inefficient for long connection lists.
2700 */
2701 for (nc = mg_next(lc->mgr, NULL); nc != NULL; nc = mg_next(lc->mgr, nc)) {
2702 if (memcmp(&nc->sa.sa, &sa->sa, sa_len) == 0 && nc->listener == lc) {
2703 break;
2704 }
2705 }
2706 if (nc == NULL) {
2707 struct mg_add_sock_opts opts;
2708 memset(&opts, 0, sizeof(opts));
2709 /* Create fake connection w/out sock initialization */
2710 nc = mg_create_connection_base(lc->mgr, lc->handler, opts);
2711 if (nc != NULL) {
2712 nc->sock = lc->sock;
2713 nc->listener = lc;
2714 nc->sa = *sa;
2715 nc->proto_handler = lc->proto_handler;
2716 nc->user_data = lc->user_data;
2718 nc->flags = MG_F_UDP;
2719 mg_add_conn(lc->mgr, nc);
2720 mg_call(nc, NULL, MG_EV_ACCEPT, &nc->sa);
2721 } else {
2722 DBG(("OOM"));
2723 /* No return here, we still need to drop on the floor */
2724 }
2725 }
2726 }
2727 if (nc != NULL) {
2728 mg_recv_common(nc, buf, len);
2729 } else {
2730 /* Drop on the floor. */
2731 MG_FREE(buf);
2732 mg_if_recved(nc, len);
2733 }
2734}
2735
2736/*
2737 * Schedules an async connect for a resolved address and proto.
2738 * Called from two places: `mg_connect_opt()` and from async resolver.
2739 * When called from the async resolver, it must trigger `MG_EV_CONNECT` event
2740 * with a failure flag to indicate connection failure.
2741 */
2743 int proto,
2744 union socket_address *sa) {
2745 DBG(("%p %s://%s:%hu", nc, proto == SOCK_DGRAM ? "udp" : "tcp",
2746 inet_ntoa(sa->sin.sin_addr), ntohs(sa->sin.sin_port)));
2747
2748 nc->flags |= MG_F_CONNECTING;
2749 if (proto == SOCK_DGRAM) {
2751 } else {
2752 mg_if_connect_tcp(nc, sa);
2753 }
2754 mg_add_conn(nc->mgr, nc);
2755 return nc;
2756}
2757
2758void mg_if_connect_cb(struct mg_connection *nc, int err) {
2759 DBG(("%p connect, err=%d", nc, err));
2760 nc->flags &= ~MG_F_CONNECTING;
2761 if (err != 0) {
2763 }
2764 mg_call(nc, NULL, MG_EV_CONNECT, &err);
2765}
2766
2767#ifndef MG_DISABLE_RESOLVER
2768/*
2769 * Callback for the async resolver on mg_connect_opt() call.
2770 * Main task of this function is to trigger MG_EV_CONNECT event with
2771 * either failure (and dealloc the connection)
2772 * or success (and proceed with connect()
2773 */
2774static void resolve_cb(struct mg_dns_message *msg, void *data,
2775 enum mg_resolve_err e) {
2776 struct mg_connection *nc = (struct mg_connection *) data;
2777 int i;
2778 int failure = -1;
2779
2780 nc->flags &= ~MG_F_RESOLVING;
2781 if (msg != NULL) {
2782 /*
2783 * Take the first DNS A answer and run...
2784 */
2785 for (i = 0; i < msg->num_answers; i++) {
2786 if (msg->answers[i].rtype == MG_DNS_A_RECORD) {
2787 /*
2788 * Async resolver guarantees that there is at least one answer.
2789 * TODO(lsm): handle IPv6 answers too
2790 */
2791 mg_dns_parse_record_data(msg, &msg->answers[i], &nc->sa.sin.sin_addr,
2792 4);
2794 &nc->sa);
2795 return;
2796 }
2797 }
2798 }
2799
2800 if (e == MG_RESOLVE_TIMEOUT) {
2801 double now = mg_time();
2802 mg_call(nc, NULL, MG_EV_TIMER, &now);
2803 }
2804
2805 /*
2806 * If we get there was no MG_DNS_A_RECORD in the answer
2807 */
2808 mg_call(nc, NULL, MG_EV_CONNECT, &failure);
2810 mg_destroy_conn(nc);
2811}
2812#endif
2813
2814struct mg_connection *mg_connect(struct mg_mgr *mgr, const char *address,
2816 struct mg_connect_opts opts;
2817 memset(&opts, 0, sizeof(opts));
2818 return mg_connect_opt(mgr, address, callback, opts);
2819}
2820
2821struct mg_connection *mg_connect_opt(struct mg_mgr *mgr, const char *address,
2823 struct mg_connect_opts opts) {
2824 struct mg_connection *nc = NULL;
2825 int proto, rc;
2827 char host[MG_MAX_HOST_LEN];
2828
2830
2831 if ((nc = mg_create_connection(mgr, callback, add_sock_opts)) == NULL) {
2832 return NULL;
2833 } else if ((rc = mg_parse_address(address, &nc->sa, &proto, host,
2834 sizeof(host))) < 0) {
2835 /* Address is malformed */
2836 MG_SET_PTRPTR(opts.error_string, "cannot parse address");
2837 mg_destroy_conn(nc);
2838 return NULL;
2839 }
2841 nc->flags |= (proto == SOCK_DGRAM) ? MG_F_UDP : 0;
2842 nc->user_data = opts.user_data;
2843
2844#ifdef MG_ENABLE_SSL
2845 if (opts.ssl_cert != NULL || opts.ssl_ca_cert != NULL) {
2846 const char *err = mg_set_ssl(nc, opts.ssl_cert, opts.ssl_ca_cert);
2847 if (err != NULL) {
2848 MG_SET_PTRPTR(opts.error_string, err);
2849 mg_destroy_conn(nc);
2850 return NULL;
2851 }
2852 if (opts.ssl_ca_cert != NULL && (opts.ssl_server_name == NULL ||
2853 strcmp(opts.ssl_server_name, "*") != 0)) {
2854 if (opts.ssl_server_name == NULL) opts.ssl_server_name = host;
2855#ifdef SSL_KRYPTON
2856 SSL_CTX_kr_set_verify_name(nc->ssl_ctx, opts.ssl_server_name);
2857#else
2858 /* TODO(rojer): Implement server name verification on OpenSSL. */
2859 MG_SET_PTRPTR(opts.error_string,
2860 "Server name verification requested but is not supported");
2861 mg_destroy_conn(nc);
2862 return NULL;
2863#endif /* SSL_KRYPTON */
2864 }
2865 }
2866#endif /* MG_ENABLE_SSL */
2867
2868 if (rc == 0) {
2869#ifndef MG_DISABLE_RESOLVER
2870 /*
2871 * DNS resolution is required for host.
2872 * mg_parse_address() fills port in nc->sa, which we pass to resolve_cb()
2873 */
2874 struct mg_connection *dns_conn = NULL;
2875 struct mg_resolve_async_opts o;
2876 memset(&o, 0, sizeof(o));
2877 o.dns_conn = &dns_conn;
2879 o) != 0) {
2880 MG_SET_PTRPTR(opts.error_string, "cannot schedule DNS lookup");
2881 mg_destroy_conn(nc);
2882 return NULL;
2883 }
2884 nc->priv_2 = dns_conn;
2885 nc->flags |= MG_F_RESOLVING;
2886 return nc;
2887#else
2888 MG_SET_PTRPTR(opts.error_string, "Resolver is disabled");
2889 mg_destroy_conn(nc);
2890 return NULL;
2891#endif
2892 } else {
2893 /* Address is parsed and resolved to IP. proceed with connect() */
2894 return mg_do_connect(nc, proto, &nc->sa);
2895 }
2896}
2897
2898struct mg_connection *mg_bind(struct mg_mgr *srv, const char *address,
2899 mg_event_handler_t event_handler) {
2900 struct mg_bind_opts opts;
2901 memset(&opts, 0, sizeof(opts));
2902 return mg_bind_opt(srv, address, event_handler, opts);
2903}
2904
2905struct mg_connection *mg_bind_opt(struct mg_mgr *mgr, const char *address,
2907 struct mg_bind_opts opts) {
2908 union socket_address sa;
2909 struct mg_connection *nc = NULL;
2910 int proto, rc;
2912 char host[MG_MAX_HOST_LEN];
2913
2915
2916 if (mg_parse_address(address, &sa, &proto, host, sizeof(host)) <= 0) {
2917 MG_SET_PTRPTR(opts.error_string, "cannot parse address");
2918 return NULL;
2919 }
2920
2922 if (nc == NULL) {
2923 return NULL;
2924 }
2925
2926 nc->sa = sa;
2927 nc->flags |= MG_F_LISTENING;
2928 if (proto == SOCK_DGRAM) {
2929 nc->flags |= MG_F_UDP;
2930 rc = mg_if_listen_udp(nc, &nc->sa);
2931 } else {
2932 rc = mg_if_listen_tcp(nc, &nc->sa);
2933 }
2934 if (rc != 0) {
2935 DBG(("Failed to open listener: %d", rc));
2936 MG_SET_PTRPTR(opts.error_string, "failed to open listener");
2937 mg_destroy_conn(nc);
2938 return NULL;
2939 }
2940#ifdef MG_ENABLE_SSL
2941 if (opts.ssl_cert != NULL || opts.ssl_ca_cert != NULL) {
2942 const char *err = mg_set_ssl(nc, opts.ssl_cert, opts.ssl_ca_cert);
2943 if (err != NULL) {
2944 MG_SET_PTRPTR(opts.error_string, err);
2945 mg_destroy_conn(nc);
2946 return NULL;
2947 }
2948 }
2949#endif /* MG_ENABLE_SSL */
2950 mg_add_conn(nc->mgr, nc);
2951
2952 return nc;
2953}
2954
2955struct mg_connection *mg_next(struct mg_mgr *s, struct mg_connection *conn) {
2956 return conn == NULL ? s->active_connections : conn->next;
2957}
2958
2959#ifndef MG_DISABLE_SOCKETPAIR
2961 size_t len) {
2962 struct ctl_msg ctl_msg;
2963
2964 /*
2965 * Mongoose manager has a socketpair, `struct mg_mgr::ctl`,
2966 * where `mg_broadcast()` pushes the message.
2967 * `mg_mgr_poll()` wakes up, reads a message from the socket pair, and calls
2968 * specified callback for each connection. Thus the callback function executes
2969 * in event manager thread.
2970 */
2971 if (mgr->ctl[0] != INVALID_SOCKET && data != NULL &&
2972 len < sizeof(ctl_msg.message)) {
2973 size_t dummy;
2974
2975 ctl_msg.callback = cb;
2976 memcpy(ctl_msg.message, data, len);
2977 dummy = MG_SEND_FUNC(mgr->ctl[0], (char *) &ctl_msg,
2978 offsetof(struct ctl_msg, message) + len, 0);
2979 dummy = MG_RECV_FUNC(mgr->ctl[0], (char *) &len, 1, 0);
2980 (void) dummy; /* https://gcc.gnu.org/bugzilla/show_bug.cgi?id=25509 */
2981 }
2982}
2983#endif /* MG_DISABLE_SOCKETPAIR */
2984
2985static int isbyte(int n) {
2986 return n >= 0 && n <= 255;
2987}
2988
2989static int parse_net(const char *spec, uint32_t *net, uint32_t *mask) {
2990 int n, a, b, c, d, slash = 32, len = 0;
2991
2992 if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5 ||
2993 sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) &&
2994 isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) && slash >= 0 &&
2995 slash < 33) {
2996 len = n;
2997 *net =
2998 ((uint32_t) a << 24) | ((uint32_t) b << 16) | ((uint32_t) c << 8) | d;
2999 *mask = slash ? 0xffffffffU << (32 - slash) : 0;
3000 }
3001
3002 return len;
3003}
3004
3005int mg_check_ip_acl(const char *acl, uint32_t remote_ip) {
3006 int allowed, flag;
3007 uint32_t net, mask;
3008 struct mg_str vec;
3009
3010 /* If any ACL is set, deny by default */
3011 allowed = (acl == NULL || *acl == '\0') ? '+' : '-';
3012
3013 while ((acl = mg_next_comma_list_entry(acl, &vec, NULL)) != NULL) {
3014 flag = vec.p[0];
3015 if ((flag != '+' && flag != '-') ||
3016 parse_net(&vec.p[1], &net, &mask) == 0) {
3017 return -1;
3018 }
3019
3020 if (net == (remote_ip & mask)) {
3021 allowed = flag;
3022 }
3023 }
3024
3025 DBG(("%08x %c", remote_ip, allowed));
3026 return allowed == '+';
3027}
3028
3029/* Move data from one connection to another */
3031 mg_send(to, from->recv_mbuf.buf, from->recv_mbuf.len);
3032 mbuf_remove(&from->recv_mbuf, from->recv_mbuf.len);
3033}
3034
3035double mg_set_timer(struct mg_connection *c, double timestamp) {
3036 double result = c->ev_timer_time;
3037 c->ev_timer_time = timestamp;
3038 /*
3039 * If this connection is resolving, it's not in the list of active
3040 * connections, so not processed yet. It has a DNS resolver connection
3041 * linked to it. Set up a timer for the DNS connection.
3042 */
3043 DBG(("%p %p %d -> %lu", c, c->priv_2, c->flags & MG_F_RESOLVING,
3044 (unsigned long) timestamp));
3045 if ((c->flags & MG_F_RESOLVING) && c->priv_2 != NULL) {
3046 ((struct mg_connection *) c->priv_2)->ev_timer_time = timestamp;
3047 }
3048 return result;
3049}
3050
3053 struct mg_add_sock_opts opts) {
3055 if (nc != NULL) {
3056 mg_sock_set(nc, sock);
3057 mg_add_conn(nc->mgr, nc);
3058 }
3059 return nc;
3060}
3061
3064 struct mg_add_sock_opts opts;
3065 memset(&opts, 0, sizeof(opts));
3066 return mg_add_sock_opt(s, sock, callback, opts);
3067}
3068
3069double mg_time() {
3070 return cs_time();
3071}
3072#ifdef MG_MODULE_LINES
3073#line 1 "./src/net_if_socket.c"
3074#endif
3075/*
3076 * Copyright (c) 2014-2016 Cesanta Software Limited
3077 * All rights reserved
3078 */
3079
3080#ifndef MG_DISABLE_SOCKET_IF
3081
3082/* Amalgamated: #include "mongoose/src/internal.h" */
3083/* Amalgamated: #include "mongoose/src/util.h" */
3084
3085#define MG_TCP_RECV_BUFFER_SIZE 1024
3086#define MG_UDP_RECV_BUFFER_SIZE 1500
3087
3088static sock_t mg_open_listening_socket(union socket_address *sa, int proto);
3089#ifdef MG_ENABLE_SSL
3090static void mg_ssl_begin(struct mg_connection *nc);
3091static int mg_ssl_err(struct mg_connection *conn, int res);
3092#endif
3093
3095#ifdef _WIN32
3096 unsigned long on = 1;
3097 ioctlsocket(sock, FIONBIO, &on);
3098#elif defined(MG_SOCKET_SIMPLELINK)
3100 opt.NonblockingEnabled = 1;
3102#else
3103 int flags = fcntl(sock, F_GETFL, 0);
3104 fcntl(sock, F_SETFL, flags | O_NONBLOCK);
3105#endif
3106}
3107
3108int mg_is_error(int n) {
3109#ifdef MG_SOCKET_SIMPLELINK
3110 DBG(("n = %d, errno = %d", n, errno));
3111 if (n < 0) errno = n;
3112#endif
3113 return n == 0 || (n < 0 && errno != EINTR && errno != EINPROGRESS &&
3114 errno != EAGAIN && errno != EWOULDBLOCK
3115#ifdef MG_SOCKET_SIMPLELINK
3116 && errno != SL_EALREADY
3117#endif
3118#ifdef _WIN32
3119 && WSAGetLastError() != WSAEINTR &&
3121#endif
3122 );
3123}
3124
3126 const union socket_address *sa) {
3127 int rc;
3128 nc->sock = socket(AF_INET, SOCK_STREAM, 0);
3129 if (nc->sock < 0) {
3130 nc->sock = INVALID_SOCKET;
3131 nc->err = errno ? errno : 1;
3132 return;
3133 }
3134#if !defined(MG_SOCKET_SIMPLELINK) && !defined(MG_ESP8266)
3136#endif
3137 rc = connect(nc->sock, &sa->sa, sizeof(sa->sin));
3138 nc->err = mg_is_error(rc) ? errno : 0;
3139 DBG(("%p sock %d err %d", nc, nc->sock, nc->err));
3140}
3141
3143 nc->sock = socket(AF_INET, SOCK_DGRAM, 0);
3144 if (nc->sock < 0) {
3145 nc->sock = INVALID_SOCKET;
3146 nc->err = errno ? errno : 1;
3147 return;
3148 }
3149 nc->err = 0;
3150}
3151
3154 if (sock == INVALID_SOCKET) {
3155 return (errno ? errno : 1);
3156 }
3157 mg_sock_set(nc, sock);
3158 return 0;
3159}
3160
3163 if (sock < 0) return (errno ? errno : 1);
3164 mg_sock_set(nc, sock);
3165 return 0;
3166}
3167
3168void mg_if_tcp_send(struct mg_connection *nc, const void *buf, size_t len) {
3169 mbuf_append(&nc->send_mbuf, buf, len);
3170}
3171
3172void mg_if_udp_send(struct mg_connection *nc, const void *buf, size_t len) {
3173 mbuf_append(&nc->send_mbuf, buf, len);
3174}
3175
3176void mg_if_recved(struct mg_connection *nc, size_t len) {
3177 (void) nc;
3178 (void) len;
3179}
3180
3182 (void) nc;
3183 return 1;
3184}
3185
3187 if (nc->sock == INVALID_SOCKET) return;
3188 if (!(nc->flags & MG_F_UDP)) {
3189 closesocket(nc->sock);
3190 } else {
3191 /* Only close outgoing UDP sockets or listeners. */
3192 if (nc->listener == NULL) closesocket(nc->sock);
3193 }
3194 /*
3195 * avoid users accidentally double close a socket
3196 * because it can lead to difficult to debug situations.
3197 * It would happen only if reusing a destroyed mg_connection
3198 * but it's not always possible to run the code through an
3199 * address sanitizer.
3200 */
3201 nc->sock = INVALID_SOCKET;
3202}
3203
3204static void mg_accept_conn(struct mg_connection *lc) {
3205 struct mg_connection *nc;
3206 union socket_address sa;
3207 socklen_t sa_len = sizeof(sa);
3208 extern int check_midas_acl(const struct sockaddr *sa, int len);
3209 /* NOTE(lsm): on Windows, sock is always > FD_SETSIZE */
3210 sock_t sock = accept(lc->sock, &sa.sa, &sa_len);
3211 if (sock < 0) {
3212 DBG(("%p: failed to accept: %d", lc, errno));
3213 return;
3214 }
3215 if (!check_midas_acl(&sa.sa, sa_len)) {
3216 closesocket(sock);
3217 return;
3218 }
3219 nc = mg_if_accept_new_conn(lc);
3220 if (nc == NULL) {
3221 closesocket(sock);
3222 return;
3223 }
3224 mg_sock_set(nc, sock);
3225#ifdef MG_ENABLE_SSL
3226 if (lc->ssl_ctx != NULL) {
3227 nc->ssl = SSL_new(lc->ssl_ctx);
3228 if (nc->ssl == NULL || SSL_set_fd(nc->ssl, sock) != 1) {
3229 DBG(("SSL error"));
3230 mg_close_conn(nc);
3231 }
3232 } else
3233#endif
3234 {
3236 }
3237}
3238
3239/* 'sa' must be an initialized address to bind to */
3242 (sa->sa.sa_family == AF_INET) ? sizeof(sa->sin) : sizeof(sa->sin6);
3243 sock_t sock = INVALID_SOCKET;
3244#if !defined(MG_SOCKET_SIMPLELINK) && !defined(MG_LWIP)
3245 int on = 1;
3246#endif
3247
3248 if ((sock = socket(sa->sa.sa_family, proto, 0)) != INVALID_SOCKET &&
3250 !defined(MG_LWIP) /* SimpleLink and LWIP don't support either */
3251#if defined(_WIN32) && defined(SO_EXCLUSIVEADDRUSE)
3252 /* "Using SO_REUSEADDR and SO_EXCLUSIVEADDRUSE" http://goo.gl/RmrFTm */
3253 !setsockopt(sock, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (void *) &on,
3254 sizeof(on)) &&
3255#endif
3256
3257#if !defined(_WIN32) || !defined(SO_EXCLUSIVEADDRUSE)
3258 /*
3259 * SO_RESUSEADDR is not enabled on Windows because the semantics of
3260 * SO_REUSEADDR on UNIX and Windows is different. On Windows,
3261 * SO_REUSEADDR allows to bind a socket to a port without error even if
3262 * the port is already open by another program. This is not the behavior
3263 * SO_REUSEADDR was designed for, and leads to hard-to-track failure
3264 * scenarios. Therefore, SO_REUSEADDR was disabled on Windows unless
3265 * SO_EXCLUSIVEADDRUSE is supported and set on a socket.
3266 */
3267 !setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *) &on, sizeof(on)) &&
3268#endif
3269#endif /* !MG_SOCKET_SIMPLELINK && !MG_LWIP */
3270
3271 !bind(sock, &sa->sa, sa_len) &&
3272 (proto == SOCK_DGRAM || listen(sock, SOMAXCONN) == 0)) {
3273#if !defined(MG_SOCKET_SIMPLELINK) && \
3274 !defined(MG_LWIP) /* TODO(rojer): Fix this. */
3276 /* In case port was set to 0, get the real port number */
3277 (void) getsockname(sock, &sa->sa, &sa_len);
3278#endif
3279 } else if (sock != INVALID_SOCKET) {
3280 closesocket(sock);
3281 sock = INVALID_SOCKET;
3282 }
3283
3284 return sock;
3285}
3286
3287static void mg_write_to_socket(struct mg_connection *nc) {
3288 struct mbuf *io = &nc->send_mbuf;
3289 int n = 0;
3290
3291#ifdef MG_LWIP
3292 /* With LWIP we don't know if the socket is ready */
3293 if (io->len == 0) return;
3294#endif
3295
3296 assert(io->len > 0);
3297
3298 if (nc->flags & MG_F_UDP) {
3299 int n =
3300 sendto(nc->sock, io->buf, io->len, 0, &nc->sa.sa, sizeof(nc->sa.sin));
3301 DBG(("%p %d %d %d %s:%hu", nc, nc->sock, n, errno,
3302 inet_ntoa(nc->sa.sin.sin_addr), ntohs(nc->sa.sin.sin_port)));
3303 if (n > 0) {
3304 mbuf_remove(io, n);
3305 }
3306 mg_if_sent_cb(nc, n);
3307 return;
3308 }
3309
3310#ifdef MG_ENABLE_SSL
3311 if (nc->ssl != NULL) {
3312 if (nc->flags & MG_F_SSL_HANDSHAKE_DONE) {
3313 n = SSL_write(nc->ssl, io->buf, io->len);
3314 DBG(("%p %d bytes -> %d (SSL)", nc, n, nc->sock));
3315 if (n <= 0) {
3316 int ssl_err = mg_ssl_err(nc, n);
3318 return; /* Call us again */
3319 }
3320 } else {
3321 /* Successful SSL operation, clear off SSL wait flags */
3323 }
3324 } else {
3325 mg_ssl_begin(nc);
3326 return;
3327 }
3328 } else
3329#endif
3330 {
3331 n = (int) MG_SEND_FUNC(nc->sock, io->buf, io->len, 0);
3332 DBG(("%p %d bytes -> %d", nc, n, nc->sock));
3333 }
3334
3335 if (n > 0) {
3336 mbuf_remove(io, n);
3337 }
3338 mg_if_sent_cb(nc, n);
3339}
3340
3341MG_INTERNAL size_t recv_avail_size(struct mg_connection *conn, size_t max) {
3342 size_t avail;
3343 if (conn->recv_mbuf_limit < conn->recv_mbuf.len) return 0;
3344 avail = conn->recv_mbuf_limit - conn->recv_mbuf.len;
3345 return avail > max ? max : avail;
3346}
3347
3348static void mg_read_from_socket(struct mg_connection *conn) {
3349 int n = 0;
3350 char *buf = (char *) MG_MALLOC(MG_TCP_RECV_BUFFER_SIZE);
3351
3352 if (buf == NULL) {
3353 DBG(("OOM"));
3354 return;
3355 }
3356
3357#ifdef MG_ENABLE_SSL
3358 if (conn->ssl != NULL) {
3359 if (conn->flags & MG_F_SSL_HANDSHAKE_DONE) {
3360 /* SSL library may have more bytes ready to read then we ask to read.
3361 * Therefore, read in a loop until we read everything. Without the loop,
3362 * we skip to the next select() cycle which can just timeout. */
3363 while ((n = SSL_read(conn->ssl, buf, MG_TCP_RECV_BUFFER_SIZE)) > 0) {
3364 DBG(("%p %d bytes <- %d (SSL)", conn, n, conn->sock));
3365 mg_if_recv_tcp_cb(conn, buf, n);
3366 buf = NULL;
3367 if (conn->flags & MG_F_CLOSE_IMMEDIATELY) break;
3368 /* buf has been freed, we need a new one. */
3370 if (buf == NULL) break;
3371 }
3372 MG_FREE(buf);
3373 mg_ssl_err(conn, n);
3374 } else {
3375 MG_FREE(buf);
3376 mg_ssl_begin(conn);
3377 return;
3378 }
3379 } else
3380#endif
3381 {
3382 n = (int) MG_RECV_FUNC(conn->sock, buf,
3384 if (n > 0) {
3385 DBG(("%p %d bytes (PLAIN) <- %d", conn, n, conn->sock));
3386 mg_if_recv_tcp_cb(conn, buf, n);
3387 } else {
3388 MG_FREE(buf);
3389 }
3390 if (mg_is_error(n)) {
3392 }
3393 }
3394}
3395
3396static int mg_recvfrom(struct mg_connection *nc, union socket_address *sa,
3397 socklen_t *sa_len, char **buf) {
3398 int n;
3400 if (*buf == NULL) {
3401 DBG(("Out of memory"));
3402 return -ENOMEM;
3403 }
3404 n = recvfrom(nc->sock, *buf, MG_UDP_RECV_BUFFER_SIZE, 0, &sa->sa, sa_len);
3405 if (n <= 0) {
3406 DBG(("%p recvfrom: %s", nc, strerror(errno)));
3407 MG_FREE(*buf);
3408 }
3409 return n;
3410}
3411
3412static void mg_handle_udp_read(struct mg_connection *nc) {
3413 char *buf = NULL;
3414 union socket_address sa;
3415 socklen_t sa_len = sizeof(sa);
3416 int n = mg_recvfrom(nc, &sa, &sa_len, &buf);
3417 DBG(("%p %d bytes from %s:%d", nc, n, inet_ntoa(nc->sa.sin.sin_addr),
3418 ntohs(nc->sa.sin.sin_port)));
3419 mg_if_recv_udp_cb(nc, buf, n, &sa, sa_len);
3420}
3421
3422#ifdef MG_ENABLE_SSL
3423static int mg_ssl_err(struct mg_connection *conn, int res) {
3424 int ssl_err = SSL_get_error(conn->ssl, res);
3425 DBG(("%p %d -> %d", conn, res, ssl_err));
3427 conn->flags |= MG_F_WANT_READ;
3428 } else if (ssl_err == SSL_ERROR_WANT_WRITE) {
3429 conn->flags |= MG_F_WANT_WRITE;
3430 } else {
3431 /* There could be an alert to deliver. Try our best. */
3432 SSL_write(conn->ssl, "", 0);
3434 }
3435 return ssl_err;
3436}
3437
3438static void mg_ssl_begin(struct mg_connection *nc) {
3439 int server_side = (nc->listener != NULL);
3440 int res = server_side ? SSL_accept(nc->ssl) : SSL_connect(nc->ssl);
3441 DBG(("%p %d res %d %d", nc, server_side, res, errno));
3442
3443 if (res == 1) {
3446
3447 if (server_side) {
3448 union socket_address sa;
3449 socklen_t sa_len = sizeof(sa);
3450 (void) getpeername(nc->sock, &sa.sa, &sa_len);
3452 } else {
3453 mg_if_connect_cb(nc, 0);
3454 }
3455 } else {
3456 int ssl_err = mg_ssl_err(nc, res);
3458 if (!server_side) {
3460 }
3462 }
3463 }
3464}
3465#endif /* MG_ENABLE_SSL */
3466
3467#define _MG_F_FD_CAN_READ 1
3468#define _MG_F_FD_CAN_WRITE 1 << 1
3469#define _MG_F_FD_ERROR 1 << 2
3470
3471void mg_mgr_handle_conn(struct mg_connection *nc, int fd_flags, double now) {
3472 DBG(("%p fd=%d fd_flags=%d nc_flags=%lu rmbl=%d smbl=%d", nc, nc->sock,
3473 fd_flags, nc->flags, (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len));
3474
3475 if (nc->flags & MG_F_CONNECTING) {
3476 if (fd_flags != 0) {
3477 int err = 0;
3478#if !defined(MG_SOCKET_SIMPLELINK) && !defined(MG_ESP8266)
3479 if (!(nc->flags & MG_F_UDP)) {
3480 socklen_t len = sizeof(err);
3481 int ret =
3482 getsockopt(nc->sock, SOL_SOCKET, SO_ERROR, (char *) &err, &len);
3483 if (ret != 0) err = 1;
3484 }
3485#else
3486/* On SimpleLink and ESP8266 we use blocking connect. If we got as far as
3487 * this, it means connect() was successful.
3488 * TODO(rojer): Figure out why it fails where blocking succeeds.
3489 */
3490#endif
3491#ifdef MG_ENABLE_SSL
3492 if (nc->ssl != NULL && err == 0) {
3493 SSL_set_fd(nc->ssl, nc->sock);
3494 mg_ssl_begin(nc);
3495 } else {
3496 mg_if_connect_cb(nc, err);
3497 }
3498#else
3499 mg_if_connect_cb(nc, err);
3500#endif
3501 } else if (nc->err != 0) {
3502 mg_if_connect_cb(nc, nc->err);
3503 }
3504 }
3505
3507 if (nc->flags & MG_F_UDP) {
3509 } else {
3510 if (nc->flags & MG_F_LISTENING) {
3511 /*
3512 * We're not looping here, and accepting just one connection at
3513 * a time. The reason is that eCos does not respect non-blocking
3514 * flag on a listening socket and hangs in a loop.
3515 */
3517 return;
3518 } else {
3520 }
3521 }
3522 if (nc->flags & MG_F_CLOSE_IMMEDIATELY) return;
3523 }
3524
3525 if ((fd_flags & _MG_F_FD_CAN_WRITE) && nc->send_mbuf.len > 0) {
3527 }
3528
3530 mg_if_poll(nc, now);
3531 }
3532 mg_if_timer(nc, now);
3533
3534 DBG(("%p after fd=%d nc_flags=%lu rmbl=%d smbl=%d", nc, nc->sock, nc->flags,
3535 (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len));
3536}
3537
3538#ifndef MG_DISABLE_SOCKETPAIR
3539static void mg_mgr_handle_ctl_sock(struct mg_mgr *mgr) {
3540 struct ctl_msg ctl_msg;
3541 int len =
3542 (int) MG_RECV_FUNC(mgr->ctl[1], (char *) &ctl_msg, sizeof(ctl_msg), 0);
3543 size_t dummy = MG_SEND_FUNC(mgr->ctl[1], ctl_msg.message, 1, 0);
3544 DBG(("read %d from ctl socket", len));
3545 (void) dummy; /* https://gcc.gnu.org/bugzilla/show_bug.cgi?id=25509 */
3546 if (len >= (int) sizeof(ctl_msg.callback) && ctl_msg.callback != NULL) {
3547 struct mg_connection *nc;
3548 for (nc = mg_next(mgr, NULL); nc != NULL; nc = mg_next(mgr, nc)) {
3550 }
3551 }
3552}
3553#endif
3554
3555/* Associate a socket to a connection. */
3559 nc->sock = sock;
3560 DBG(("%p %d", nc, sock));
3561}
3562
3564 (void) mgr;
3565 DBG(("%p using select()", mgr));
3566#ifndef MG_DISABLE_SOCKETPAIR
3567 do {
3569 } while (mgr->ctl[0] == INVALID_SOCKET);
3570#endif
3571}
3572
3574 (void) mgr;
3575}
3576
3578 (void) nc;
3579}
3580
3582 (void) nc;
3583}
3584
3586 if (sock != INVALID_SOCKET) {
3587 FD_SET(sock, set);
3588 if (*max_fd == INVALID_SOCKET || sock > *max_fd) {
3589 *max_fd = sock;
3590 }
3591 }
3592}
3593
3595 double now = mg_time();
3596 double min_timer;
3597 struct mg_connection *nc, *tmp;
3598 struct timeval tv;
3601 int num_fds, num_ev, num_timers = 0;
3602
3603 FD_ZERO(&read_set);
3605 FD_ZERO(&err_set);
3606#ifndef MG_DISABLE_SOCKETPAIR
3607 mg_add_to_set(mgr->ctl[1], &read_set, &max_fd);
3608#endif
3609
3610 /*
3611 * Note: it is ok to have connections with sock == INVALID_SOCKET in the list,
3612 * e.g. timer-only "connections".
3613 */
3614 min_timer = 0;
3615 for (nc = mgr->active_connections, num_fds = 0; nc != NULL; nc = tmp) {
3616 tmp = nc->next;
3617
3618 //printf("nc %p -> mg_mgr_poll, mgr %p %p, pd %p, fp %p\n", nc, nc->mgr, mgr, nc->proto_data, (nc->proto_data?*(FILE**)nc->proto_data:NULL));
3619
3620 if (nc->sock != INVALID_SOCKET) {
3621 num_fds++;
3622
3623 if (!(nc->flags & MG_F_WANT_WRITE) &&
3624 nc->recv_mbuf.len < nc->recv_mbuf_limit &&
3625 (!(nc->flags & MG_F_UDP) || nc->listener == NULL)) {
3627 }
3628
3629 if (((nc->flags & MG_F_CONNECTING) && !(nc->flags & MG_F_WANT_READ)) ||
3630 (nc->send_mbuf.len > 0 && !(nc->flags & MG_F_CONNECTING))) {
3633 }
3634 }
3635
3636 if (nc->ev_timer_time > 0) {
3637 if (num_timers == 0 || nc->ev_timer_time < min_timer) {
3639 }
3640 num_timers++;
3641 }
3642 }
3643
3644 /*
3645 * If there is a timer to be fired earlier than the requested timeout,
3646 * adjust the timeout.
3647 */
3648 if (num_timers > 0) {
3649 double timer_timeout_ms = (min_timer - mg_time()) * 1000 + 1 /* rounding */;
3652 }
3653 }
3654 if (timeout_ms < 0) timeout_ms = 0;
3655
3656 tv.tv_sec = timeout_ms / 1000;
3657 tv.tv_usec = (timeout_ms % 1000) * 1000;
3658
3659 num_ev = select((int) max_fd + 1, &read_set, &write_set, &err_set, &tv);
3660 now = mg_time();
3661 DBG(("select @ %ld num_ev=%d of %d, timeout=%d", (long) now, num_ev, num_fds,
3662 timeout_ms));
3663
3664#ifndef MG_DISABLE_SOCKETPAIR
3665 if (num_ev > 0 && mgr->ctl[1] != INVALID_SOCKET &&
3666 FD_ISSET(mgr->ctl[1], &read_set)) {
3668 }
3669#endif
3670
3671 for (nc = mgr->active_connections; nc != NULL; nc = tmp) {
3672 int fd_flags = 0;
3673 if (nc->sock != INVALID_SOCKET) {
3674 if (num_ev > 0) {
3675 fd_flags = (FD_ISSET(nc->sock, &read_set) &&
3676 (!(nc->flags & MG_F_UDP) || nc->listener == NULL)
3678 : 0) |
3679 (FD_ISSET(nc->sock, &write_set) ? _MG_F_FD_CAN_WRITE : 0) |
3680 (FD_ISSET(nc->sock, &err_set) ? _MG_F_FD_ERROR : 0);
3681 }
3682#ifdef MG_SOCKET_SIMPLELINK
3683 /* SimpleLink does not report UDP sockets as writeable. */
3684 if (nc->flags & MG_F_UDP &&
3685 (nc->send_mbuf.len > 0 || nc->flags & MG_F_CONNECTING)) {
3687 }
3688#endif
3689#ifdef MG_LWIP
3690 /* With LWIP socket emulation layer, we don't get write events */
3692#endif
3693 }
3694 tmp = nc->next;
3696 }
3697
3698 for (nc = mgr->active_connections; nc != NULL; nc = tmp) {
3699 tmp = nc->next;
3700 if ((nc->flags & MG_F_CLOSE_IMMEDIATELY) ||
3701 (nc->send_mbuf.len == 0 && (nc->flags & MG_F_SEND_AND_CLOSE))) {
3702 //printf("nc %p -> mg_close_conn, mgr %p %p, pd %p, fp %p\n", nc, nc->mgr, mgr, nc->proto_data, (nc->proto_data?*(FILE**)nc->proto_data:NULL));
3703 mg_close_conn(nc);
3704 }
3705 }
3706
3707 return now;
3708}
3709
3710#ifndef MG_DISABLE_SOCKETPAIR
3712 union socket_address sa;
3713 sock_t sock;
3714 socklen_t len = sizeof(sa.sin);
3715 int ret = 0;
3716
3717 sock = sp[0] = sp[1] = INVALID_SOCKET;
3718
3719 (void) memset(&sa, 0, sizeof(sa));
3720 sa.sin.sin_family = AF_INET;
3721 sa.sin.sin_port = htons(0);
3722 sa.sin.sin_addr.s_addr = htonl(0x7f000001); /* 127.0.0.1 */
3723
3724 if ((sock = socket(AF_INET, sock_type, 0)) == INVALID_SOCKET) {
3725 } else if (bind(sock, &sa.sa, len) != 0) {
3726 } else if (sock_type == SOCK_STREAM && listen(sock, 1) != 0) {
3727 } else if (getsockname(sock, &sa.sa, &len) != 0) {
3728 } else if ((sp[0] = socket(AF_INET, sock_type, 0)) == INVALID_SOCKET) {
3729 } else if (connect(sp[0], &sa.sa, len) != 0) {
3730 } else if (sock_type == SOCK_DGRAM &&
3731 (getsockname(sp[0], &sa.sa, &len) != 0 ||
3732 connect(sock, &sa.sa, len) != 0)) {
3733 } else if ((sp[1] = (sock_type == SOCK_DGRAM ? sock
3734 : accept(sock, &sa.sa, &len))) ==
3736 } else {
3739 if (sock_type == SOCK_STREAM) closesocket(sock);
3740 ret = 1;
3741 }
3742
3743 if (!ret) {
3744 if (sp[0] != INVALID_SOCKET) closesocket(sp[0]);
3745 if (sp[1] != INVALID_SOCKET) closesocket(sp[1]);
3746 if (sock != INVALID_SOCKET) closesocket(sock);
3747 sock = sp[0] = sp[1] = INVALID_SOCKET;
3748 }
3749
3750 return ret;
3751}
3752#endif /* MG_DISABLE_SOCKETPAIR */
3753
3754#ifndef MG_SOCKET_SIMPLELINK
3755static void mg_sock_get_addr(sock_t sock, int remote,
3756 union socket_address *sa) {
3757 socklen_t slen = sizeof(*sa);
3758 memset(sa, 0, slen);
3759 if (remote) {
3760 getpeername(sock, &sa->sa, &slen);
3761 } else {
3762 getsockname(sock, &sa->sa, &slen);
3763 }
3764}
3765
3766void mg_sock_to_str(sock_t sock, char *buf, size_t len, int flags) {
3767 union socket_address sa;
3769 mg_sock_addr_to_str(&sa, buf, len, flags);
3770}
3771#endif
3772
3774 union socket_address *sa) {
3775#ifndef MG_SOCKET_SIMPLELINK
3777#else
3778 /* SimpleLink does not provide a way to get socket's peer address after
3779 * accept or connect. Address hould have been preserved in the connection,
3780 * so we do our best here by using it. */
3781 if (remote) memcpy(sa, &nc->sa, sizeof(*sa));
3782#endif
3783}
3784
3785#endif /* !MG_DISABLE_SOCKET_IF */
3786#ifdef MG_MODULE_LINES
3787#line 1 "./src/multithreading.c"
3788#endif
3789/*
3790 * Copyright (c) 2014 Cesanta Software Limited
3791 * All rights reserved
3792 */
3793
3794/* Amalgamated: #include "mongoose/src/internal.h" */
3795/* Amalgamated: #include "mongoose/src/util.h" */
3796
3797#ifdef MG_ENABLE_THREADS
3798
3799static void multithreaded_ev_handler(struct mg_connection *c, int ev, void *p);
3800
3801/*
3802 * This thread function executes user event handler.
3803 * It runs an event manager that has only one connection, until that
3804 * connection is alive.
3805 */
3806static void *per_connection_thread_function(void *param) {
3807 struct mg_connection *c = (struct mg_connection *) param;
3808 struct mg_mgr m;
3809
3810 mg_mgr_init(&m, NULL);
3811 mg_add_conn(&m, c);
3812 while (m.active_connections != NULL) {
3813 mg_mgr_poll(&m, 1000);
3814 }
3815 mg_mgr_free(&m);
3816
3817 return param;
3818}
3819
3820static void link_conns(struct mg_connection *c1, struct mg_connection *c2) {
3821 c1->priv_2 = c2;
3822 c2->priv_2 = c1;
3823}
3824
3825static void unlink_conns(struct mg_connection *c) {
3826 struct mg_connection *peer = (struct mg_connection *) c->priv_2;
3827 if (peer != NULL) {
3828 peer->flags |= MG_F_SEND_AND_CLOSE;
3829 peer->priv_2 = NULL;
3830 }
3831 c->priv_2 = NULL;
3832}
3833
3834static void forwarder_ev_handler(struct mg_connection *c, int ev, void *p) {
3835 (void) p;
3836 if (ev == MG_EV_RECV && c->priv_2) {
3837 mg_forward(c, (struct mg_connection *) c->priv_2);
3838 } else if (ev == MG_EV_CLOSE) {
3839 unlink_conns(c);
3840 }
3841}
3842
3843static void spawn_handling_thread(struct mg_connection *nc) {
3844 struct mg_mgr dummy;
3845 sock_t sp[2];
3846 struct mg_connection *c[2];
3847
3848 /*
3849 * Create a socket pair, and wrap each socket into the connection with
3850 * dummy event manager.
3851 * c[0] stays in this thread, c[1] goes to another thread.
3852 */
3854 memset(&dummy, 0, sizeof(dummy));
3856 c[1] = mg_add_sock(&dummy, sp[1], nc->listener->priv_1.f);
3857
3858 /* Interlink client connection with c[0] */
3859 link_conns(c[0], nc);
3860
3861 /*
3862 * Switch c[0] manager from the dummy one to the real one. c[1] manager
3863 * will be set in another thread, allocated on stack of that thread.
3864 */
3865 mg_add_conn(nc->mgr, c[0]);
3866
3867 /*
3868 * Dress c[1] as nc.
3869 * TODO(lsm): code in accept_conn() looks similar. Refactor.
3870 */
3871 c[1]->listener = nc->listener;
3872 c[1]->proto_handler = nc->proto_handler;
3873 c[1]->proto_data = nc->proto_data;
3874 c[1]->user_data = nc->user_data;
3875
3876 //printf("dup proto_data %p, nc %p\n", nc->proto_data, nc);
3877
3878 // fix https://github.com/cesanta/mongoose/issues/646
3879 nc->proto_data = NULL;
3880
3882}
3883
3884static void multithreaded_ev_handler(struct mg_connection *c, int ev, void *p) {
3885 (void) p;
3886 if (ev == MG_EV_ACCEPT) {
3888 c->handler = forwarder_ev_handler;
3889 }
3890}
3891
3892void mg_enable_multithreading(struct mg_connection *nc) {
3893 /* Wrap user event handler into our multithreaded_ev_handler */
3894 nc->priv_1.f = nc->handler;
3896}
3897#endif
3898#ifdef MG_MODULE_LINES
3899#line 1 "./src/uri.c"
3900#endif
3901/*
3902 * Copyright (c) 2014 Cesanta Software Limited
3903 * All rights reserved
3904 */
3905
3906/* Amalgamated: #include "mongoose/src/internal.h" */
3907/* Amalgamated: #include "mongoose/src/uri.h" */
3908
3909/*
3910 * scan string until `sep`, keeping track of component boundaries in `res`.
3911 *
3912 * `p` will point to the char after the separator or it will be `end`.
3913 */
3914static void parse_uri_component(const char **p, const char *end, char sep,
3915 struct mg_str *res) {
3916 res->p = *p;
3917 for (; *p < end; (*p)++) {
3918 if (**p == sep) {
3919 break;
3920 }
3921 }
3922 res->len = (*p) - res->p;
3923 if (*p < end) (*p)++;
3924}
3925
3926int mg_parse_uri(struct mg_str uri, struct mg_str *scheme,
3927 struct mg_str *user_info, struct mg_str *host,
3928 unsigned int *port, struct mg_str *path, struct mg_str *query,
3929 struct mg_str *fragment) {
3930 struct mg_str rscheme = {0, 0}, ruser_info = {0, 0}, rhost = {0, 0},
3931 rpath = {0, 0}, rquery = {0, 0}, rfragment = {0, 0};
3932 unsigned int rport = 0;
3933 enum {
3934 P_START,
3937 P_HOST,
3938 P_PORT,
3939 P_REST
3940 } state = P_START;
3941
3942 const char *p = uri.p, *end = p + uri.len;
3943 while (p < end) {
3944 switch (state) {
3945 case P_START:
3946 /*
3947 * expecting on of:
3948 * - `scheme://xxxx`
3949 * - `xxxx:port`
3950 * - `xxxx/path`
3951 */
3952 for (; p < end; p++) {
3953 if (*p == ':') {
3955 break;
3956 } else if (*p == '/') {
3957 state = P_REST;
3958 break;
3959 }
3960 }
3961 if (state == P_START || state == P_REST) {
3962 rhost.p = uri.p;
3963 rhost.len = p - uri.p;
3964 }
3965 break;
3966 case P_SCHEME_OR_PORT:
3967 if (end - p >= 3 && memcmp(p, "://", 3) == 0) {
3968 rscheme.p = uri.p;
3969 rscheme.len = p - uri.p;
3971 p += 2; /* point to last separator char */
3972 } else {
3973 rhost.p = uri.p;
3974 rhost.len = p - uri.p;
3975 state = P_PORT;
3976 }
3977 break;
3978 case P_USER_INFO:
3979 p++;
3980 ruser_info.p = p;
3981 for (; p < end; p++) {
3982 if (*p == '@') {
3983 state = P_HOST;
3984 break;
3985 } else if (*p == '/') {
3986 break;
3987 }
3988 }
3989 if (p == end || *p == '/') {
3990 /* backtrack and parse as host */
3991 state = P_HOST;
3992 p = ruser_info.p;
3993 }
3994 ruser_info.len = p - ruser_info.p;
3995 break;
3996 case P_HOST:
3997 if (*p == '@') p++;
3998 rhost.p = p;
3999 for (; p < end; p++) {
4000 if (*p == ':') {
4001 state = P_PORT;
4002 break;
4003 } else if (*p == '/') {
4004 state = P_REST;
4005 break;
4006 }
4007 }
4008 rhost.len = p - rhost.p;
4009 break;
4010 case P_PORT:
4011 p++;
4012 for (; p < end; p++) {
4013 if (*p == '/') {
4014 state = P_REST;
4015 break;
4016 }
4017 rport *= 10;
4018 rport += *p - '0';
4019 }
4020 break;
4021 case P_REST:
4022 /* `p` points to separator. `path` includes the separator */
4023 parse_uri_component(&p, end, '?', &rpath);
4024 parse_uri_component(&p, end, '#', &rquery);
4026 break;
4027 }
4028 }
4029
4030 if (scheme != 0) *scheme = rscheme;
4031 if (user_info != 0) *user_info = ruser_info;
4032 if (host != 0) *host = rhost;
4033 if (port != 0) *port = rport;
4034 if (path != 0) *path = rpath;
4035 if (query != 0) *query = rquery;
4036 if (fragment != 0) *fragment = rfragment;
4037
4038 return 0;
4039}
4040
4041/* Normalize the URI path. Remove/resolve "." and "..". */
4042int mg_normalize_uri_path(const struct mg_str *in, struct mg_str *out) {
4043 const char *s = in->p, *se = s + in->len;
4044 char *cp = (char *) out->p, *d;
4045
4046 if (in->len == 0 || *s != '/') {
4047 out->len = 0;
4048 return 0;
4049 }
4050
4051 d = cp;
4052
4053 while (s < se) {
4054 const char *next = s;
4055 struct mg_str component;
4056 parse_uri_component(&next, se, '/', &component);
4057 if (mg_vcmp(&component, ".") == 0) {
4058 /* Yum. */
4059 } else if (mg_vcmp(&component, "..") == 0) {
4060 /* Backtrack to previous slash. */
4061 if (d > cp + 1 && *(d - 1) == '/') d--;
4062 while (d > cp && *(d - 1) != '/') d--;
4063 } else {
4064 memmove(d, s, next - s);
4065 d += next - s;
4066 }
4067 s = next;
4068 }
4069 if (d == cp) *d++ = '/';
4070
4071 out->p = cp;
4072 out->len = d - cp;
4073 return 1;
4074}
4075#ifdef MG_MODULE_LINES
4076#line 1 "./src/http.c"
4077#endif
4078/*
4079 * Copyright (c) 2014 Cesanta Software Limited
4080 * All rights reserved
4081 */
4082
4083#ifndef MG_DISABLE_HTTP
4084
4085/* Amalgamated: #include "mongoose/src/internal.h" */
4086/* Amalgamated: #include "mongoose/src/util.h" */
4087/* Amalgamated: #include "common/sha1.h" */
4088/* Amalgamated: #include "common/md5.h" */
4089
4090#ifndef MG_DISABLE_HTTP_WEBSOCKET
4091#define MG_WS_NO_HOST_HEADER_MAGIC ((char *) 0x1)
4092#endif
4093
4095
4097 FILE *fp; /* Opened file. */
4098 int64_t cl; /* Content-Length. How many bytes to send. */
4099 int64_t sent; /* How many bytes have been already sent. */
4101};
4102
4106
4108 int64_t body_len; /* How many bytes of chunked body was reassembled. */
4109};
4110
4117
4127
4138
4140#ifndef MG_DISABLE_FILESYSTEM
4142#endif
4143#ifndef MG_DISABLE_CGI
4145#endif
4146#ifdef MG_ENABLE_HTTP_STREAMING_MULTIPART
4148#endif
4152};
4153
4154static void mg_http_conn_destructor(void *proto_data);
4155
4157 struct mg_connection *c) {
4158 if (c->proto_data == NULL) {
4159 c->proto_data = MG_CALLOC(1, sizeof(struct mg_http_proto_data));
4160 c->proto_data_destructor = mg_http_conn_destructor;
4161 //printf("conn_new, pd %p, fp %p\n", c->proto_data, (c->proto_data?*(FILE**)c->proto_data:NULL));
4162 }
4163
4164 //printf("nc %p -> get_proto_data, pd %p, fp %p\n", c, c->proto_data, (c->proto_data?*(FILE**)c->proto_data:NULL));
4165
4166 return (struct mg_http_proto_data *) c->proto_data;
4167}
4168
4169#ifdef MG_ENABLE_HTTP_STREAMING_MULTIPART
4171 struct mg_http_multipart_stream *mp) {
4172 free((void *) mp->boundary);
4173 mp->boundary = NULL;
4174 free((void *) mp->var_name);
4175 mp->var_name = NULL;
4176 free((void *) mp->file_name);
4177 mp->file_name = NULL;
4178}
4179#endif
4180
4181#ifndef MG_DISABLE_FILESYSTEM
4183 if (d != NULL) {
4184 if (d->fp != NULL) {
4185 fclose(d->fp);
4186 }
4187 memset(d, 0, sizeof(struct mg_http_proto_data_file));
4188 }
4189}
4190#endif
4191
4192#ifndef MG_DISABLE_CGI
4194 if (d != NULL) {
4195 if (d->cgi_nc != NULL) d->cgi_nc->flags |= MG_F_CLOSE_IMMEDIATELY;
4196 memset(d, 0, sizeof(struct mg_http_proto_data_cgi));
4197 }
4198}
4199#endif
4200
4202 struct mg_http_endpoint *current = *ep;
4203
4204 while (current != NULL) {
4205 struct mg_http_endpoint *tmp = current->next;
4206 free((void *) current->name);
4207 free(current);
4208 current = tmp;
4209 }
4210
4211 ep = NULL;
4212}
4213
4214static void mg_http_conn_destructor(void *proto_data) {
4215 struct mg_http_proto_data *pd = (struct mg_http_proto_data *) proto_data;
4216 //printf("conn_destructor, pd %p, fp %p\n", proto_data, (proto_data?*(FILE**)proto_data:NULL));
4217#ifndef MG_DISABLE_FILESYSTEM
4219#endif
4220#ifndef MG_DISABLE_CGI
4222#endif
4223#ifdef MG_ENABLE_HTTP_STREAMING_MULTIPART
4225#endif
4227 free(proto_data);
4228}
4229
4230/*
4231 * This structure helps to create an environment for the spawned CGI program.
4232 * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
4233 * last element must be NULL.
4234 * However, on Windows there is a requirement that all these VARIABLE=VALUE\0
4235 * strings must reside in a contiguous buffer. The end of the buffer is
4236 * marked by two '\0' characters.
4237 * We satisfy both worlds: we create an envp array (which is vars), all
4238 * entries are actually pointers inside buf.
4239 */
4242 char buf[MG_CGI_ENVIRONMENT_SIZE]; /* Environment buffer */
4243 const char *vars[MG_MAX_CGI_ENVIR_VARS]; /* char *envp[] */
4244 int len; /* Space taken */
4245 int nvars; /* Number of variables in envp[] */
4246};
4247
4248#define MIME_ENTRY(_ext, _type) \
4249 { _ext, sizeof(_ext) - 1, _type }
4250static const struct {
4251 const char *extension;
4252 size_t ext_len;
4253 const char *mime_type;
4255 MIME_ENTRY("html", "text/html"),
4256 MIME_ENTRY("html", "text/html"),
4257 MIME_ENTRY("htm", "text/html"),
4258 MIME_ENTRY("shtm", "text/html"),
4259 MIME_ENTRY("shtml", "text/html"),
4260 MIME_ENTRY("css", "text/css"),
4261 MIME_ENTRY("js", "application/x-javascript"),
4262 MIME_ENTRY("ico", "image/x-icon"),
4263 MIME_ENTRY("gif", "image/gif"),
4264 MIME_ENTRY("jpg", "image/jpeg"),
4265 MIME_ENTRY("jpeg", "image/jpeg"),
4266 MIME_ENTRY("png", "image/png"),
4267 MIME_ENTRY("svg", "image/svg+xml"),
4268 MIME_ENTRY("txt", "text/plain"),
4269 MIME_ENTRY("torrent", "application/x-bittorrent"),
4270 MIME_ENTRY("wav", "audio/x-wav"),
4271 MIME_ENTRY("mp3", "audio/x-mp3"),
4272 MIME_ENTRY("mid", "audio/mid"),
4273 MIME_ENTRY("m3u", "audio/x-mpegurl"),
4274 MIME_ENTRY("ogg", "application/ogg"),
4275 MIME_ENTRY("ram", "audio/x-pn-realaudio"),
4276 MIME_ENTRY("xml", "text/xml"),
4277 MIME_ENTRY("ttf", "application/x-font-ttf"),
4278 MIME_ENTRY("json", "application/json"),
4279 MIME_ENTRY("xslt", "application/xml"),
4280 MIME_ENTRY("xsl", "application/xml"),
4281 MIME_ENTRY("ra", "audio/x-pn-realaudio"),
4282 MIME_ENTRY("doc", "application/msword"),
4283 MIME_ENTRY("exe", "application/octet-stream"),
4284 MIME_ENTRY("zip", "application/x-zip-compressed"),
4285 MIME_ENTRY("xls", "application/excel"),
4286 MIME_ENTRY("tgz", "application/x-tar-gz"),
4287 MIME_ENTRY("tar", "application/x-tar"),
4288 MIME_ENTRY("gz", "application/x-gunzip"),
4289 MIME_ENTRY("arj", "application/x-arj-compressed"),
4290 MIME_ENTRY("rar", "application/x-rar-compressed"),
4291 MIME_ENTRY("rtf", "application/rtf"),
4292 MIME_ENTRY("pdf", "application/pdf"),
4293 MIME_ENTRY("swf", "application/x-shockwave-flash"),
4294 MIME_ENTRY("mpg", "video/mpeg"),
4295 MIME_ENTRY("webm", "video/webm"),
4296 MIME_ENTRY("mpeg", "video/mpeg"),
4297 MIME_ENTRY("mov", "video/quicktime"),
4298 MIME_ENTRY("mp4", "video/mp4"),
4299 MIME_ENTRY("m4v", "video/x-m4v"),
4300 MIME_ENTRY("asf", "video/x-ms-asf"),
4301 MIME_ENTRY("avi", "video/x-msvideo"),
4302 MIME_ENTRY("bmp", "image/bmp"),
4303 {NULL, 0, NULL}};
4304
4305#ifndef MG_DISABLE_FILESYSTEM
4306
4307#ifndef MG_DISABLE_DAV
4308static int mg_mkdir(const char *path, uint32_t mode) {
4309#ifndef _WIN32
4310 return mkdir(path, mode);
4311#else
4312 (void) mode;
4313 return _mkdir(path);
4314#endif
4315}
4316#endif
4317
4318static struct mg_str mg_get_mime_type(const char *path, const char *dflt,
4319 const struct mg_serve_http_opts *opts) {
4320 const char *ext, *overrides;
4321 size_t i, path_len;
4322 struct mg_str r, k, v;
4323
4324 path_len = strlen(path);
4325
4326 overrides = opts->custom_mime_types;
4327 while ((overrides = mg_next_comma_list_entry(overrides, &k, &v)) != NULL) {
4328 ext = path + (path_len - k.len);
4329 if (path_len > k.len && mg_vcasecmp(&k, ext) == 0) {
4330 return v;
4331 }
4332 }
4333
4334 for (i = 0; mg_static_builtin_mime_types[i].extension != NULL; i++) {
4335 ext = path + (path_len - mg_static_builtin_mime_types[i].ext_len);
4336 if (path_len > mg_static_builtin_mime_types[i].ext_len && ext[-1] == '.' &&
4338 r.p = mg_static_builtin_mime_types[i].mime_type;
4339 r.len = strlen(r.p);
4340 return r;
4341 }
4342 }
4343
4344 r.p = dflt;
4345 r.len = strlen(r.p);
4346 return r;
4347}
4348#endif
4349
4350/*
4351 * Check whether full request is buffered. Return:
4352 * -1 if request is malformed
4353 * 0 if request is not yet fully buffered
4354 * >0 actual request length, including last \r\n\r\n
4355 */
4356static int mg_http_get_request_len(const char *s, int buf_len) {
4357 const unsigned char *buf = (unsigned char *) s;
4358 int i;
4359
4360 for (i = 0; i < buf_len; i++) {
4361 if (!isprint(buf[i]) && buf[i] != '\r' && buf[i] != '\n' && buf[i] < 128) {
4362 return -1;
4363 } else if (buf[i] == '\n' && i + 1 < buf_len && buf[i + 1] == '\n') {
4364 return i + 2;
4365 } else if (buf[i] == '\n' && i + 2 < buf_len && buf[i + 1] == '\r' &&
4366 buf[i + 2] == '\n') {
4367 return i + 3;
4368 }
4369 }
4370
4371 return 0;
4372}
4373
4374static const char *mg_http_parse_headers(const char *s, const char *end,
4375 int len, struct http_message *req) {
4376 int i;
4377 for (i = 0; i < (int) ARRAY_SIZE(req->header_names) - 1; i++) {
4378 struct mg_str *k = &req->header_names[i], *v = &req->header_values[i];
4379
4380 s = mg_skip(s, end, ": ", k);
4381 s = mg_skip(s, end, "\r\n", v);
4382
4383 while (v->len > 0 && v->p[v->len - 1] == ' ') {
4384 v->len--; /* Trim trailing spaces in header value */
4385 }
4386
4387 if (k->len == 0 || v->len == 0) {
4388 k->p = v->p = NULL;
4389 k->len = v->len = 0;
4390 break;
4391 }
4392
4393 if (!mg_ncasecmp(k->p, "Content-Length", 14)) {
4394 req->body.len = to64(v->p);
4395 req->message.len = len + req->body.len;
4396 }
4397 }
4398
4399 return s;
4400}
4401
4402int mg_parse_http(const char *s, int n, struct http_message *hm, int is_req) {
4403 const char *end, *qs;
4404 int len = mg_http_get_request_len(s, n);
4405
4406 if (len <= 0) return len;
4407
4408 memset(hm, 0, sizeof(*hm));
4409 hm->message.p = s;
4410 hm->body.p = s + len;
4411 hm->message.len = hm->body.len = (size_t) ~0;
4412 end = s + len;
4413
4414 /* Request is fully buffered. Skip leading whitespaces. */
4415 while (s < end && isspace(*(unsigned char *) s)) s++;
4416
4417 if (is_req) {
4418 /* Parse request line: method, URI, proto */
4419 s = mg_skip(s, end, " ", &hm->method);
4420 s = mg_skip(s, end, " ", &hm->uri);
4421 s = mg_skip(s, end, "\r\n", &hm->proto);
4422 if (hm->uri.p <= hm->method.p || hm->proto.p <= hm->uri.p) return -1;
4423
4424 /* If URI contains '?' character, initialize query_string */
4425 if ((qs = (char *) memchr(hm->uri.p, '?', hm->uri.len)) != NULL) {
4426 hm->query_string.p = qs + 1;
4427 hm->query_string.len = &hm->uri.p[hm->uri.len] - (qs + 1);
4428 hm->uri.len = qs - hm->uri.p;
4429 }
4430 } else {
4431 s = mg_skip(s, end, " ", &hm->proto);
4432 if (end - s < 4 || s[3] != ' ') return -1;
4433 hm->resp_code = atoi(s);
4434 if (hm->resp_code < 100 || hm->resp_code >= 600) return -1;
4435 s += 4;
4436 s = mg_skip(s, end, "\r\n", &hm->resp_status_msg);
4437 }
4438
4439 s = mg_http_parse_headers(s, end, len, hm);
4440
4441 /*
4442 * mg_parse_http() is used to parse both HTTP requests and HTTP
4443 * responses. If HTTP response does not have Content-Length set, then
4444 * body is read until socket is closed, i.e. body.len is infinite (~0).
4445 *
4446 * For HTTP requests though, according to
4447 * http://tools.ietf.org/html/rfc7231#section-8.1.3,
4448 * only POST and PUT methods have defined body semantics.
4449 * Therefore, if Content-Length is not specified and methods are
4450 * not one of PUT or POST, set body length to 0.
4451 *
4452 * So,
4453 * if it is HTTP request, and Content-Length is not set,
4454 * and method is not (PUT or POST) then reset body length to zero.
4455 */
4456 if (hm->body.len == (size_t) ~0 && is_req &&
4457 mg_vcasecmp(&hm->method, "PUT") != 0 &&
4458 mg_vcasecmp(&hm->method, "POST") != 0) {
4459 hm->body.len = 0;
4460 hm->message.len = len;
4461 }
4462
4463 return len;
4464}
4465
4466struct mg_str *mg_get_http_header(struct http_message *hm, const char *name) {
4467 size_t i, len = strlen(name);
4468
4469 for (i = 0; hm->header_names[i].len > 0; i++) {
4470 struct mg_str *h = &hm->header_names[i], *v = &hm->header_values[i];
4471 if (h->p != NULL && h->len == len && !mg_ncasecmp(h->p, name, len))
4472 return v;
4473 }
4474
4475 return NULL;
4476}
4477
4478#ifndef MG_DISABLE_HTTP_WEBSOCKET
4479
4480static int mg_is_ws_fragment(unsigned char flags) {
4481 return (flags & 0x80) == 0 || (flags & 0x0f) == 0;
4482}
4483
4484static int mg_is_ws_first_fragment(unsigned char flags) {
4485 return (flags & 0x80) == 0 && (flags & 0x0f) != 0;
4486}
4487
4489 struct websocket_message *wsm) {
4490 if (wsm->flags & 0x8) {
4492 } else {
4494 }
4495}
4496
4498 /* Using unsigned char *, cause of integer arithmetic below */
4499 uint64_t i, data_len = 0, frame_len = 0, buf_len = nc->recv_mbuf.len, len,
4500 mask_len = 0, header_len = 0;
4501 unsigned char *p = (unsigned char *) nc->recv_mbuf.buf, *buf = p,
4502 *e = p + buf_len;
4503 unsigned *sizep = (unsigned *) &p[1]; /* Size ptr for defragmented frames */
4504 int ok, reass = buf_len > 0 && mg_is_ws_fragment(p[0]) &&
4506
4507 /* If that's a continuation frame that must be reassembled, handle it */
4508 if (reass && !mg_is_ws_first_fragment(p[0]) &&
4509 buf_len >= 1 + sizeof(*sizep) && buf_len >= 1 + sizeof(*sizep) + *sizep) {
4510 buf += 1 + sizeof(*sizep) + *sizep;
4511 buf_len -= 1 + sizeof(*sizep) + *sizep;
4512 }
4513
4514 if (buf_len >= 2) {
4515 len = buf[1] & 127;
4516 mask_len = buf[1] & 128 ? 4 : 0;
4518 data_len = len;
4519 header_len = 2 + mask_len;
4520 } else if (len == 126 && buf_len >= 4 + mask_len) {
4521 header_len = 4 + mask_len;
4522 data_len = ntohs(*(uint16_t *) &buf[2]);
4523 } else if (buf_len >= 10 + mask_len) {
4524 header_len = 10 + mask_len;
4525 data_len = (((uint64_t) ntohl(*(uint32_t *) &buf[2])) << 32) +
4526 ntohl(*(uint32_t *) &buf[6]);
4527 }
4528 }
4529
4530 frame_len = header_len + data_len;
4531 ok = frame_len > 0 && frame_len <= buf_len;
4532
4533 if (ok) {
4534 struct websocket_message wsm;
4535
4536 wsm.size = (size_t) data_len;
4537 wsm.data = buf + header_len;
4538 wsm.flags = buf[0];
4539
4540 /* Apply mask if necessary */
4541 if (mask_len > 0) {
4542 for (i = 0; i < data_len; i++) {
4543 buf[i + header_len] ^= (buf + header_len - mask_len)[i % 4];
4544 }
4545 }
4546
4547 if (reass) {
4548 /* On first fragmented frame, nullify size */
4549 if (mg_is_ws_first_fragment(wsm.flags)) {
4550 mbuf_resize(&nc->recv_mbuf, nc->recv_mbuf.size + sizeof(*sizep));
4551 p[0] &= ~0x0f; /* Next frames will be treated as continuation */
4552 buf = p + 1 + sizeof(*sizep);
4553 *sizep = 0; /* TODO(lsm): fix. this can stomp over frame data */
4554 }
4555
4556 /* Append this frame to the reassembled buffer */
4557 memmove(buf, wsm.data, e - wsm.data);
4558 (*sizep) += wsm.size;
4559 nc->recv_mbuf.len -= wsm.data - buf;
4560
4561 /* On last fragmented frame - call user handler and remove data */
4562 if (wsm.flags & 0x80) {
4563 wsm.data = p + 1 + sizeof(*sizep);
4564 wsm.size = *sizep;
4566 mbuf_remove(&nc->recv_mbuf, 1 + sizeof(*sizep) + *sizep);
4567 }
4568 } else {
4569 /* TODO(lsm): properly handle OOB control frames during defragmentation */
4571 mbuf_remove(&nc->recv_mbuf, (size_t) frame_len); /* Cleanup frame */
4572 }
4573
4574 /* If client closes, close too */
4575 if ((buf[0] & 0x0f) == WEBSOCKET_OP_CLOSE) {
4577 }
4578 }
4579
4580 return ok;
4581}
4582
4584 size_t pos; /* zero means unmasked */
4586};
4587
4589 uint32_t mask;
4590/*
4591 * The spec requires WS client to generate hard to
4592 * guess mask keys. From RFC6455, Section 5.3:
4593 *
4594 * The unpredictability of the masking key is essential to prevent
4595 * authors of malicious applications from selecting the bytes that appear on
4596 * the wire.
4597 *
4598 * Hence this feature is essential when the actual end user of this API
4599 * is untrusted code that wouldn't have access to a lower level net API
4600 * anyway (e.g. web browsers). Hence this feature is low prio for most
4601 * mongoose use cases and thus can be disabled, e.g. when porting to a platform
4602 * that lacks random().
4603 */
4604#ifdef MG_DISABLE_WS_RANDOM_MASK
4605 mask = 0xefbeadde; /* generated with a random number generator, I swear */
4606#else
4607 if (sizeof(long) >= 4) {
4608 mask = (uint32_t) random();
4609 } else if (sizeof(long) == 2) {
4610 mask = (uint32_t) random() << 16 | (uint32_t) random();
4611 }
4612#endif
4613 return mask;
4614}
4615
4616static void mg_send_ws_header(struct mg_connection *nc, int op, size_t len,
4617 struct ws_mask_ctx *ctx) {
4618 int header_len;
4619 unsigned char header[10];
4620
4621 header[0] = (op & WEBSOCKET_DONT_FIN ? 0x0 : 0x80) + (op & 0x0f);
4622 if (len < 126) {
4623 header[1] = len;
4624 header_len = 2;
4625 } else if (len < 65535) {
4626 uint16_t tmp = htons((uint16_t) len);
4627 header[1] = 126;
4628 memcpy(&header[2], &tmp, sizeof(tmp));
4629 header_len = 4;
4630 } else {
4631 uint32_t tmp;
4632 header[1] = 127;
4633 tmp = htonl((uint32_t)((uint64_t) len >> 32));
4634 memcpy(&header[2], &tmp, sizeof(tmp));
4635 tmp = htonl((uint32_t)(len & 0xffffffff));
4636 memcpy(&header[6], &tmp, sizeof(tmp));
4637 header_len = 10;
4638 }
4639
4640 /* client connections enable masking */
4641 if (nc->listener == NULL) {
4642 header[1] |= 1 << 7; /* set masking flag */
4643 mg_send(nc, header, header_len);
4644 ctx->mask = mg_ws_random_mask();
4645 mg_send(nc, &ctx->mask, sizeof(ctx->mask));
4646 ctx->pos = nc->send_mbuf.len;
4647 } else {
4648 mg_send(nc, header, header_len);
4649 ctx->pos = 0;
4650 }
4651}
4652
4653static void mg_ws_mask_frame(struct mbuf *mbuf, struct ws_mask_ctx *ctx) {
4654 size_t i;
4655 if (ctx->pos == 0) return;
4656 for (i = 0; i < (mbuf->len - ctx->pos); i++) {
4657 mbuf->buf[ctx->pos + i] ^= ((char *) &ctx->mask)[i % 4];
4658 }
4659}
4660
4661void mg_send_websocket_frame(struct mg_connection *nc, int op, const void *data,
4662 size_t len) {
4663 struct ws_mask_ctx ctx;
4664 DBG(("%p %d %d", nc, op, (int) len));
4665 mg_send_ws_header(nc, op, len, &ctx);
4666 mg_send(nc, data, len);
4667
4668 mg_ws_mask_frame(&nc->send_mbuf, &ctx);
4669
4670 if (op == WEBSOCKET_OP_CLOSE) {
4672 }
4673}
4674
4676 const struct mg_str *strv, int strvcnt) {
4677 struct ws_mask_ctx ctx;
4678 int i;
4679 int len = 0;
4680 for (i = 0; i < strvcnt; i++) {
4681 len += strv[i].len;
4682 }
4683
4684 mg_send_ws_header(nc, op, len, &ctx);
4685
4686 for (i = 0; i < strvcnt; i++) {
4687 mg_send(nc, strv[i].p, strv[i].len);
4688 }
4689
4690 mg_ws_mask_frame(&nc->send_mbuf, &ctx);
4691
4692 if (op == WEBSOCKET_OP_CLOSE) {
4694 }
4695}
4696
4698 const char *fmt, ...) {
4699 char mem[MG_VPRINTF_BUFFER_SIZE], *buf = mem;
4700 va_list ap;
4701 int len;
4702
4703 va_start(ap, fmt);
4704 if ((len = mg_avprintf(&buf, sizeof(mem), fmt, ap)) > 0) {
4705 mg_send_websocket_frame(nc, op, buf, len);
4706 }
4707 va_end(ap);
4708
4709 if (buf != mem && buf != NULL) {
4710 MG_FREE(buf);
4711 }
4712}
4713
4714static void mg_websocket_handler(struct mg_connection *nc, int ev,
4715 void *ev_data) {
4716 mg_call(nc, nc->handler, ev, ev_data);
4717
4718 switch (ev) {
4719 case MG_EV_RECV:
4720 do {
4721 } while (mg_deliver_websocket_data(nc));
4722 break;
4723 case MG_EV_POLL:
4724 /* Ping idle websocket connections */
4725 {
4726 time_t now = *(time_t *) ev_data;
4727 if (nc->flags & MG_F_IS_WEBSOCKET &&
4730 }
4731 }
4732 break;
4733 default:
4734 break;
4735 }
4736}
4737
4738static void mg_ws_handshake(struct mg_connection *nc,
4739 const struct mg_str *key) {
4740 static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
4741 char buf[MG_VPRINTF_BUFFER_SIZE], sha[20], b64_sha[sizeof(sha) * 2];
4743
4744 snprintf(buf, sizeof(buf), "%.*s%s", (int) key->len, key->p, magic);
4745
4747 cs_sha1_update(&sha_ctx, (unsigned char *) buf, strlen(buf));
4748 cs_sha1_final((unsigned char *) sha, &sha_ctx);
4749
4750 mg_base64_encode((unsigned char *) sha, sizeof(sha), b64_sha);
4751 mg_printf(nc, "%s%s%s",
4752 "HTTP/1.1 101 Switching Protocols\r\n"
4753 "Upgrade: websocket\r\n"
4754 "Connection: Upgrade\r\n"
4755 "Sec-WebSocket-Accept: ",
4756 b64_sha, "\r\n\r\n");
4757 DBG(("%p %.*s %s", nc, (int) key->len, key->p, b64_sha));
4758}
4759
4760#endif /* MG_DISABLE_HTTP_WEBSOCKET */
4761
4762#ifndef MG_DISABLE_FILESYSTEM
4765 char buf[MG_MAX_HTTP_SEND_MBUF];
4766 int64_t left = pd->file.cl - pd->file.sent;
4767 size_t n = 0, to_read = 0;
4768
4769 if (pd->file.type == DATA_FILE) {
4770 struct mbuf *io = &nc->send_mbuf;
4771 if (io->len < sizeof(buf)) {
4772 to_read = sizeof(buf) - io->len;
4773 }
4774
4775 if (left > 0 && to_read > (size_t) left) {
4776 to_read = left;
4777 }
4778
4779 if (to_read == 0) {
4780 /* Rate limiting. send_mbuf is too full, wait until it's drained. */
4781 } else if (pd->file.sent < pd->file.cl &&
4782 (n = fread(buf, 1, to_read, pd->file.fp)) > 0) {
4783 mg_send(nc, buf, n);
4784 pd->file.sent += n;
4785 } else {
4787#ifdef MG_DISABLE_HTTP_KEEP_ALIVE
4789#endif
4790 }
4791 } else if (pd->file.type == DATA_PUT) {
4792 struct mbuf *io = &nc->recv_mbuf;
4793 size_t to_write =
4794 left <= 0 ? 0 : left < (int64_t) io->len ? (size_t) left : io->len;
4795 size_t n = fwrite(io->buf, 1, to_write, pd->file.fp);
4796 if (n > 0) {
4797 mbuf_remove(io, n);
4798 pd->file.sent += n;
4799 }
4800 if (n == 0 || pd->file.sent >= pd->file.cl) {
4802#ifdef MG_DISABLE_HTTP_KEEP_ALIVE
4804#endif
4805 }
4806 }
4807#ifndef MG_DISABLE_CGI
4808 else if (pd->cgi.cgi_nc != NULL) {
4809 /* This is POST data that needs to be forwarded to the CGI process */
4810 if (pd->cgi.cgi_nc != NULL) {
4811 mg_forward(nc, pd->cgi.cgi_nc);
4812 } else {
4814 }
4815 }
4816#endif
4817}
4818#endif /* MG_DISABLE_FILESYSTEM */
4819
4820/*
4821 * Parse chunked-encoded buffer. Return 0 if the buffer is not encoded, or
4822 * if it's incomplete. If the chunk is fully buffered, return total number of
4823 * bytes in a chunk, and store data in `data`, `data_len`.
4824 */
4825static size_t mg_http_parse_chunk(char *buf, size_t len, char **chunk_data,
4826 size_t *chunk_len) {
4827 unsigned char *s = (unsigned char *) buf;
4828 size_t n = 0; /* scanned chunk length */
4829 size_t i = 0; /* index in s */
4830
4831 /* Scan chunk length. That should be a hexadecimal number. */
4832 while (i < len && isxdigit(s[i])) {
4833 n *= 16;
4834 n += (s[i] >= '0' && s[i] <= '9') ? s[i] - '0' : tolower(s[i]) - 'a' + 10;
4835 i++;
4836 }
4837
4838 /* Skip new line */
4839 if (i == 0 || i + 2 > len || s[i] != '\r' || s[i + 1] != '\n') {
4840 return 0;
4841 }
4842 i += 2;
4843
4844 /* Record where the data is */
4845 *chunk_data = (char *) s + i;
4846 *chunk_len = n;
4847
4848 /* Skip data */
4849 i += n;
4850
4851 /* Skip new line */
4852 if (i == 0 || i + 2 > len || s[i] != '\r' || s[i + 1] != '\n') {
4853 return 0;
4854 }
4855 return i + 2;
4856}
4857
4859 struct http_message *hm, char *buf,
4860 size_t blen) {
4862 char *data;
4863 size_t i, n, data_len, body_len, zero_chunk_received = 0;
4864
4865 /* Find out piece of received data that is not yet reassembled */
4866 body_len = pd->chunk.body_len;
4867 assert(blen >= body_len);
4868
4869 /* Traverse all fully buffered chunks */
4870 for (i = body_len;
4871 (n = mg_http_parse_chunk(buf + i, blen - i, &data, &data_len)) > 0;
4872 i += n) {
4873 /* Collapse chunk data to the rest of HTTP body */
4874 memmove(buf + body_len, data, data_len);
4875 body_len += data_len;
4876 hm->body.len = body_len;
4877
4878 if (data_len == 0) {
4880 i += n;
4881 break;
4882 }
4883 }
4884
4885 if (i > body_len) {
4886 /* Shift unparsed content to the parsed body */
4887 assert(i <= blen);
4888 memmove(buf + body_len, buf + i, blen - i);
4889 memset(buf + body_len + blen - i, 0, i - body_len);
4890 nc->recv_mbuf.len -= i - body_len;
4891 pd->chunk.body_len = body_len;
4892
4893 /* Send MG_EV_HTTP_CHUNK event */
4896
4897 /* Delete processed data if user set MG_F_DELETE_CHUNK flag */
4898 if (nc->flags & MG_F_DELETE_CHUNK) {
4899 memset(buf, 0, body_len);
4900 memmove(buf, buf + body_len, blen - i);
4901 nc->recv_mbuf.len -= body_len;
4902 hm->body.len = pd->chunk.body_len = 0;
4903 }
4904
4905 if (zero_chunk_received) {
4906 hm->message.len = pd->chunk.body_len + blen - i;
4907 }
4908 }
4909
4910 return body_len;
4911}
4912
4914 struct mg_connection *nc, struct mg_str *uri_path) {
4915 struct mg_http_proto_data *pd;
4917 int matched, matched_max = 0;
4918 struct mg_http_endpoint *ep;
4919
4920 if (nc == NULL) {
4921 return NULL;
4922 }
4923
4925
4926 ep = pd->endpoints;
4927 while (ep != NULL) {
4928 const struct mg_str name_s = {ep->name, ep->name_len};
4929 if ((matched = mg_match_prefix_n(name_s, *uri_path)) != -1) {
4930 if (matched > matched_max) {
4931 /* Looking for the longest suitable handler */
4932 ret = ep->handler;
4934 }
4935 }
4936
4937 ep = ep->next;
4938 }
4939
4940 return ret;
4941}
4942
4944 struct http_message *hm) {
4946
4947 if (pd->endpoint_handler == NULL || ev == MG_EV_HTTP_REQUEST) {
4948 pd->endpoint_handler =
4951 : NULL;
4952 }
4953 mg_call(nc, pd->endpoint_handler ? pd->endpoint_handler : nc->handler, ev,
4954 hm);
4955}
4956
4957#ifdef MG_ENABLE_HTTP_STREAMING_MULTIPART
4958static void mg_http_multipart_continue(struct mg_connection *nc);
4959
4960static void mg_http_multipart_begin(struct mg_connection *nc,
4961 struct http_message *hm, int req_len);
4962
4963#endif
4964
4965/*
4966 * lx106 compiler has a bug (TODO(mkm) report and insert tracking bug here)
4967 * If a big structure is declared in a big function, lx106 gcc will make it
4968 * even bigger (round up to 4k, from 700 bytes of actual size).
4969 */
4970#ifdef __xtensa__
4971static void mg_http_handler2(struct mg_connection *nc, int ev, void *ev_data,
4973
4974void mg_http_handler(struct mg_connection *nc, int ev, void *ev_data) {
4975 struct http_message hm;
4976 mg_http_handler2(nc, ev, ev_data, &hm);
4977}
4978
4979static void mg_http_handler2(struct mg_connection *nc, int ev, void *ev_data,
4980 struct http_message *hm) {
4981#else /* !__XTENSA__ */
4982void mg_http_handler(struct mg_connection *nc, int ev, void *ev_data) {
4983 struct http_message shm;
4984 struct http_message *hm = &shm;
4985#endif /* __XTENSA__ */
4987 struct mbuf *io = &nc->recv_mbuf;
4988 int req_len;
4989 const int is_req = (nc->listener != NULL);
4990#ifndef MG_DISABLE_HTTP_WEBSOCKET
4991 struct mg_str *vec;
4992#endif
4993 if (ev == MG_EV_CLOSE) {
4994#ifdef MG_ENABLE_HTTP_STREAMING_MULTIPART
4995 if (pd->mp_stream.boundary != NULL) {
4996 /*
4997 * Multipart message is in progress, but we get close
4998 * MG_EV_HTTP_PART_END with error flag
4999 */
5001 memset(&mp, 0, sizeof(mp));
5002
5003 mp.status = -1;
5004 mp.var_name = pd->mp_stream.var_name;
5005 mp.file_name = pd->mp_stream.file_name;
5006 mg_call(nc, (pd->endpoint_handler ? pd->endpoint_handler : nc->handler),
5008 } else
5009#endif
5010 if (io->len > 0 && mg_parse_http(io->buf, io->len, hm, is_req) > 0) {
5011 /*
5012 * For HTTP messages without Content-Length, always send HTTP message
5013 * before MG_EV_CLOSE message.
5014 */
5016 hm->message.len = io->len;
5017 hm->body.len = io->buf + io->len - hm->body.p;
5019 }
5020 }
5021
5022#ifndef MG_DISABLE_FILESYSTEM
5023 if (pd->file.fp)
5024 printf("nc %p, pd %p, file fp %p cl %d\n", nc, pd, pd->file.fp, (int)pd->file.cl);
5025 //printf("fp %p\n", pd->file.fp);
5026 assert(pd->file.fp == NULL);
5027 if (pd->file.fp != NULL) {
5029 }
5030#endif
5031
5032 mg_call(nc, nc->handler, ev, ev_data);
5033
5034 if (ev == MG_EV_RECV) {
5035 struct mg_str *s;
5036
5037#ifdef MG_ENABLE_HTTP_STREAMING_MULTIPART
5038 if (pd->mp_stream.boundary != NULL) {
5040 return;
5041 }
5042#endif /* MG_ENABLE_HTTP_STREAMING_MULTIPART */
5043
5044 req_len = mg_parse_http(io->buf, io->len, hm, is_req);
5045
5046 if (req_len > 0 &&
5047 (s = mg_get_http_header(hm, "Transfer-Encoding")) != NULL &&
5048 mg_vcasecmp(s, "chunked") == 0) {
5049 mg_handle_chunked(nc, hm, io->buf + req_len, io->len - req_len);
5050 }
5051
5052#ifdef MG_ENABLE_HTTP_STREAMING_MULTIPART
5053 if (req_len > 0 && (s = mg_get_http_header(hm, "Content-Type")) != NULL &&
5054 s->len >= 9 && strncmp(s->p, "multipart", 9) == 0) {
5057 return;
5058 }
5059#endif /* MG_ENABLE_HTTP_STREAMING_MULTIPART */
5060
5061 /* TODO(alashkin): refactor this ifelseifelseifelseifelse */
5062 if ((req_len < 0 ||
5063 (req_len == 0 && io->len >= MG_MAX_HTTP_REQUEST_SIZE))) {
5064 DBG(("invalid request"));
5066 } else if (req_len == 0) {
5067 /* Do nothing, request is not yet fully buffered */
5068 }
5069#ifndef MG_DISABLE_HTTP_WEBSOCKET
5070 else if (nc->listener == NULL &&
5071 mg_get_http_header(hm, "Sec-WebSocket-Accept")) {
5072 /* We're websocket client, got handshake response from server. */
5073 /* TODO(lsm): check the validity of accept Sec-WebSocket-Accept */
5076 nc->flags |= MG_F_IS_WEBSOCKET;
5079 } else if (nc->listener != NULL &&
5080 (vec = mg_get_http_header(hm, "Sec-WebSocket-Key")) != NULL) {
5081 /* This is a websocket request. Switch protocol handlers. */
5084 nc->flags |= MG_F_IS_WEBSOCKET;
5085
5086 /* Send handshake */
5088 if (!(nc->flags & MG_F_CLOSE_IMMEDIATELY)) {
5089 if (nc->send_mbuf.len == 0) {
5090 mg_ws_handshake(nc, vec);
5091 }
5094 }
5095#endif /* MG_DISABLE_HTTP_WEBSOCKET */
5096 } else if (hm->message.len <= io->len) {
5098
5099/* Whole HTTP message is fully buffered, call event handler */
5100
5101#ifdef MG_ENABLE_JAVASCRIPT
5102 v7_val_t v1, v2, headers, req, args, res;
5103 struct v7 *v7 = nc->mgr->v7;
5104 const char *ev_name = trigger_ev == MG_EV_HTTP_REPLY ? "onsnd" : "onrcv";
5106
5107 if (v7 != NULL) {
5108 /* Lookup JS callback */
5109 v1 = v7_get(v7, v7_get_global(v7), "Http", ~0);
5110 v2 = v7_get(v7, v1, ev_name, ~0);
5111
5112 /* Create callback params. TODO(lsm): own/disown those */
5113 args = v7_mk_array(v7);
5114 req = v7_mk_object(v7);
5116
5117 /* Populate request object */
5118 v7_set(v7, req, "method", ~0,
5119 v7_mk_string(v7, hm->method.p, hm->method.len, 1));
5120 v7_set(v7, req, "uri", ~0, v7_mk_string(v7, hm->uri.p, hm->uri.len, 1));
5121 v7_set(v7, req, "body", ~0,
5122 v7_mk_string(v7, hm->body.p, hm->body.len, 1));
5123 v7_set(v7, req, "headers", ~0, headers);
5124 for (i = 0; hm->header_names[i].len > 0; i++) {
5125 const struct mg_str *name = &hm->header_names[i];
5126 const struct mg_str *value = &hm->header_values[i];
5127 v7_set(v7, headers, name->p, name->len,
5128 v7_mk_string(v7, value->p, value->len, 1));
5129 }
5130
5131 /* Invoke callback. TODO(lsm): report errors */
5133 v7_array_push(v7, args, req);
5134 if (v7_apply(v7, v2, v7_mk_undefined(), args, &res) == V7_OK &&
5135 v7_is_truthy(v7, res)) {
5137 }
5138 }
5139
5140 /* If JS callback returns true, stop request processing */
5143 } else {
5145 }
5146#else
5148#endif
5149 mbuf_remove(io, hm->message.len);
5150 }
5151 }
5152 (void) pd;
5153}
5154
5155static size_t mg_get_line_len(const char *buf, size_t buf_len) {
5156 size_t len = 0;
5157 while (len < buf_len && buf[len] != '\n') len++;
5158 return len == buf_len ? 0 : len + 1;
5159}
5160
5161#ifdef MG_ENABLE_HTTP_STREAMING_MULTIPART
5162static void mg_http_multipart_begin(struct mg_connection *nc,
5163 struct http_message *hm, int req_len) {
5165 struct mg_str *ct;
5166 struct mbuf *io = &nc->recv_mbuf;
5167
5168 char boundary[100];
5169 int boundary_len;
5170
5171 if (nc->listener == NULL) {
5172 /* No streaming for replies now */
5173 goto exit_mp;
5174 }
5175
5176 ct = mg_get_http_header(hm, "Content-Type");
5177 if (ct == NULL) {
5178 /* We need more data - or it isn't multipart mesage */
5179 goto exit_mp;
5180 }
5181
5182 /* Content-type should start with "multipart" */
5183 if (ct->len < 9 || strncmp(ct->p, "multipart", 9) != 0) {
5184 goto exit_mp;
5185 }
5186
5187 boundary_len =
5188 mg_http_parse_header(ct, "boundary", boundary, sizeof(boundary));
5189 if (boundary_len == 0) {
5190 /*
5191 * Content type is multipart, but there is no boundary,
5192 * probably malformed request
5193 */
5195 DBG(("invalid request"));
5196 goto exit_mp;
5197 }
5198
5199 /* If we reach this place - that is multipart request */
5200
5201 if (pd->mp_stream.boundary != NULL) {
5202 /*
5203 * Another streaming request was in progress,
5204 * looks like protocol error
5205 */
5207 } else {
5208 pd->mp_stream.boundary = strdup(boundary);
5209 pd->mp_stream.boundary_len = strlen(boundary);
5210 pd->mp_stream.var_name = pd->mp_stream.file_name = NULL;
5211
5212 pd->endpoint_handler = mg_http_get_endpoint_handler(nc->listener, &hm->uri);
5213 if (pd->endpoint_handler == NULL) {
5214 pd->endpoint_handler = nc->handler;
5215 }
5216
5217 mg_call(nc, pd->endpoint_handler, MG_EV_HTTP_MULTIPART_REQUEST, hm);
5218
5220 }
5221exit_mp:
5222 ;
5223}
5224
5225#define CONTENT_DISPOSITION "Content-Disposition: "
5226
5227static void mg_http_multipart_call_handler(struct mg_connection *c, int ev,
5228 const char *data, size_t data_len) {
5231 memset(&mp, 0, sizeof(mp));
5232
5233 mp.var_name = pd->mp_stream.var_name;
5234 mp.file_name = pd->mp_stream.file_name;
5235 mp.user_data = pd->mp_stream.user_data;
5236 mp.data.p = data;
5237 mp.data.len = data_len;
5238 mg_call(c, pd->endpoint_handler, ev, &mp);
5239 pd->mp_stream.user_data = mp.user_data;
5240}
5241
5242static int mg_http_multipart_got_chunk(struct mg_connection *c) {
5244 struct mbuf *io = &c->recv_mbuf;
5245
5247 pd->mp_stream.prev_io_len);
5248 mbuf_remove(io, pd->mp_stream.prev_io_len);
5249 pd->mp_stream.prev_io_len = 0;
5250 pd->mp_stream.state = MPS_WAITING_FOR_CHUNK;
5251
5252 return 0;
5253}
5254
5255static int mg_http_multipart_finalize(struct mg_connection *c) {
5257
5260 pd->mp_stream.state = MPS_FINISHED;
5261
5262 return 1;
5263}
5264
5266 const char *boundary;
5267 struct mbuf *io = &c->recv_mbuf;
5269
5270 if ((int) io->len < pd->mp_stream.boundary_len + 2) {
5271 return 0;
5272 }
5273
5274 boundary = c_strnstr(io->buf, pd->mp_stream.boundary, io->len);
5275 if (boundary != NULL) {
5276 if (io->len - (boundary - io->buf) < 4) {
5277 return 0;
5278 }
5279 if (memcmp(boundary + pd->mp_stream.boundary_len, "--", 2) == 0) {
5280 pd->mp_stream.state = MPS_FINALIZE;
5281 } else {
5282 pd->mp_stream.state = MPS_GOT_BOUNDARY;
5283 }
5284 } else {
5285 return 0;
5286 }
5287
5288 return 1;
5289}
5290
5292 int data_size;
5293 const char *boundary, *block_begin;
5294 struct mbuf *io = &c->recv_mbuf;
5296 char file_name[100], var_name[100];
5297 int line_len;
5298 boundary = c_strnstr(io->buf, pd->mp_stream.boundary, io->len);
5299 block_begin = boundary + pd->mp_stream.boundary_len + 2;
5300 data_size = io->len - (block_begin - io->buf);
5301
5302 while (data_size > 0 &&
5303 (line_len = mg_get_line_len(block_begin, data_size)) != 0) {
5304 if (line_len > (int) sizeof(CONTENT_DISPOSITION) &&
5306 sizeof(CONTENT_DISPOSITION) - 1) == 0) {
5307 struct mg_str header;
5308
5309 header.p = block_begin + sizeof(CONTENT_DISPOSITION) - 1;
5310 header.len = line_len - sizeof(CONTENT_DISPOSITION) - 1;
5311 mg_http_parse_header(&header, "name", var_name, sizeof(var_name) - 2);
5312 mg_http_parse_header(&header, "filename", file_name,
5313 sizeof(file_name) - 2);
5315 data_size -= line_len;
5316 continue;
5317 }
5318
5319 if (line_len == 2 && mg_ncasecmp(block_begin, "\r\n", 2) == 0) {
5320 mbuf_remove(io, block_begin - io->buf + 2);
5321
5322 if (pd->mp_stream.processing_part != 0) {
5324 }
5325
5326 free((void *) pd->mp_stream.file_name);
5327 pd->mp_stream.file_name = strdup(file_name);
5328 free((void *) pd->mp_stream.var_name);
5329 pd->mp_stream.var_name = strdup(var_name);
5330
5332 pd->mp_stream.state = MPS_WAITING_FOR_CHUNK;
5333 pd->mp_stream.processing_part++;
5334 return 1;
5335 }
5336
5338 }
5339
5340 pd->mp_stream.state = MPS_WAITING_FOR_BOUNDARY;
5341
5342 return 0;
5343}
5344
5347 struct mbuf *io = &c->recv_mbuf;
5348
5349 const char *boundary;
5350 if ((int) io->len < pd->mp_stream.boundary_len + 6 /* \r\n, --, -- */) {
5351 return 0;
5352 }
5353
5354 boundary = c_strnstr(io->buf, pd->mp_stream.boundary, io->len);
5355 if (boundary == NULL && pd->mp_stream.prev_io_len == 0) {
5356 pd->mp_stream.prev_io_len = io->len;
5357 return 0;
5358 } else if (boundary == NULL &&
5359 (int) io->len >
5360 pd->mp_stream.prev_io_len + pd->mp_stream.boundary_len + 4) {
5361 pd->mp_stream.state = MPS_GOT_CHUNK;
5362 return 1;
5363 } else if (boundary != NULL) {
5364 int data_size = (boundary - io->buf - 4);
5366 mbuf_remove(io, (boundary - io->buf));
5367 pd->mp_stream.prev_io_len = 0;
5368 pd->mp_stream.state = MPS_WAITING_FOR_BOUNDARY;
5369 return 1;
5370 } else {
5371 return 0;
5372 }
5373}
5374
5375static void mg_http_multipart_continue(struct mg_connection *c) {
5377 while (1) {
5378 switch (pd->mp_stream.state) {
5379 case MPS_BEGIN: {
5380 pd->mp_stream.state = MPS_WAITING_FOR_BOUNDARY;
5381 break;
5382 }
5385 return;
5386 }
5387 break;
5388 }
5389 case MPS_GOT_BOUNDARY: {
5391 return;
5392 }
5393 break;
5394 }
5395 case MPS_WAITING_FOR_CHUNK: {
5397 return;
5398 }
5399 break;
5400 }
5401 case MPS_GOT_CHUNK: {
5402 if (mg_http_multipart_got_chunk(c) == 0) {
5403 return;
5404 }
5405 break;
5406 }
5407 case MPS_FINALIZE: {
5408 if (mg_http_multipart_finalize(c) == 0) {
5409 return;
5410 }
5411 break;
5412 }
5413 case MPS_FINISHED: {
5414 mbuf_remove(&c->recv_mbuf, c->recv_mbuf.len);
5415 return;
5416 }
5417 }
5418 }
5419}
5420
5421struct file_upload_state {
5422 char *lfn;
5423 size_t num_recd;
5424 FILE *fp;
5425};
5426
5427void mg_file_upload_handler(struct mg_connection *nc, int ev, void *ev_data,
5429 switch (ev) {
5430 case MG_EV_HTTP_PART_BEGIN: {
5431 struct mg_http_multipart_part *mp =
5433 struct file_upload_state *fus =
5434 (struct file_upload_state *) calloc(1, sizeof(*fus));
5435 mp->user_data = NULL;
5436
5437 struct mg_str lfn = local_name_fn(nc, mg_mk_str(mp->file_name));
5438 if (lfn.p == NULL || lfn.len == 0) {
5439 LOG(LL_ERROR, ("%p Not allowed to upload %s", nc, mp->file_name));
5440 mg_printf(nc,
5441 "HTTP/1.1 403 Not Allowed\r\n"
5442 "Content-Type: text/plain\r\n"
5443 "Connection: close\r\n\r\n"
5444 "Not allowed to upload %s\r\n",
5445 mp->file_name);
5447 return;
5448 }
5449 fus->lfn = (char *) malloc(lfn.len + 1);
5450 memcpy(fus->lfn, lfn.p, lfn.len);
5451 fus->lfn[lfn.len] = '\0';
5452 if (lfn.p != mp->file_name) free((char *) lfn.p);
5453 LOG(LL_DEBUG,
5454 ("%p Receiving file %s -> %s", nc, mp->file_name, fus->lfn));
5455 fus->fp = fopen(fus->lfn, "w");
5456 if (fus->fp == NULL) {
5457 mg_printf(nc,
5458 "HTTP/1.1 500 Internal Server Error\r\n"
5459 "Content-Type: text/plain\r\n"
5460 "Connection: close\r\n\r\n");
5461 LOG(LL_ERROR, ("Failed to open %s: %d\n", fus->lfn, errno));
5462 mg_printf(nc, "Failed to open %s: %d\n", fus->lfn, errno);
5463 /* Do not close the connection just yet, discard remainder of the data.
5464 * This is because at the time of writing some browsers (Chrome) fail to
5465 * render response before all the data is sent. */
5466 }
5467 mp->user_data = (void *) fus;
5468 break;
5469 }
5470 case MG_EV_HTTP_PART_DATA: {
5471 struct mg_http_multipart_part *mp =
5473 struct file_upload_state *fus =
5474 (struct file_upload_state *) mp->user_data;
5475 if (fus == NULL || fus->fp == NULL) break;
5476 if (fwrite(mp->data.p, 1, mp->data.len, fus->fp) != mp->data.len) {
5477 LOG(LL_ERROR, ("Failed to write to %s: %d, wrote %d", fus->lfn, errno,
5478 (int) fus->num_recd));
5479 if (errno == ENOSPC
5482#endif
5483 ) {
5484 mg_printf(nc,
5485 "HTTP/1.1 413 Payload Too Large\r\n"
5486 "Content-Type: text/plain\r\n"
5487 "Connection: close\r\n\r\n");
5488 mg_printf(nc, "Failed to write to %s: no space left; wrote %d\r\n",
5489 fus->lfn, (int) fus->num_recd);
5490 } else {
5491 mg_printf(nc,
5492 "HTTP/1.1 500 Internal Server Error\r\n"
5493 "Content-Type: text/plain\r\n"
5494 "Connection: close\r\n\r\n");
5495 mg_printf(nc, "Failed to write to %s: %d, wrote %d", mp->file_name,
5496 errno, (int) fus->num_recd);
5497 }
5498 fclose(fus->fp);
5499 remove(fus->lfn);
5500 fus->fp = NULL;
5501 /* Do not close the connection just yet, discard remainder of the data.
5502 * This is because at the time of writing some browsers (Chrome) fail to
5503 * render response before all the data is sent. */
5504 return;
5505 }
5506 fus->num_recd += mp->data.len;
5507 LOG(LL_DEBUG, ("%p rec'd %d bytes, %d total", nc, (int) mp->data.len,
5508 (int) fus->num_recd));
5509 break;
5510 }
5511 case MG_EV_HTTP_PART_END: {
5512 struct mg_http_multipart_part *mp =
5514 struct file_upload_state *fus =
5515 (struct file_upload_state *) mp->user_data;
5516 if (fus == NULL) break;
5517 if (mp->status >= 0 && fus->fp != NULL) {
5518 LOG(LL_DEBUG, ("%p Uploaded %s (%s), %d bytes", nc, mp->file_name,
5519 fus->lfn, (int) fus->num_recd));
5520 mg_printf(nc,
5521 "HTTP/1.1 200 OK\r\n"
5522 "Content-Type: text/plain\r\n"
5523 "Connection: close\r\n\r\n"
5524 "Ok, %s - %d bytes.\r\n",
5525 mp->file_name, (int) fus->num_recd);
5526 } else {
5527 LOG(LL_ERROR, ("Failed to store %s (%s)", mp->file_name, fus->lfn));
5528 /*
5529 * mp->status < 0 means connection was terminated, so no reason to send
5530 * HTTP reply
5531 */
5532 }
5533 if (fus->fp != NULL) fclose(fus->fp);
5534 free(fus->lfn);
5535 free(fus);
5536 mp->user_data = NULL;
5538 break;
5539 }
5540 }
5541}
5542
5543#endif /* MG_ENABLE_HTTP_STREAMING_MULTIPART */
5544
5548
5549#ifndef MG_DISABLE_HTTP_WEBSOCKET
5550
5551void mg_send_websocket_handshake2(struct mg_connection *nc, const char *path,
5552 const char *host, const char *protocol,
5553 const char *extra_headers) {
5554 /* pretty poor source of randomness, TODO fix */
5555 unsigned long random = (unsigned long) path;
5556 char key[sizeof(random) * 3];
5557
5558 mg_base64_encode((unsigned char *) &random, sizeof(random), key);
5559 mg_printf(nc,
5560 "GET %s HTTP/1.1\r\n"
5561 "Upgrade: websocket\r\n"
5562 "Connection: Upgrade\r\n"
5563 "Sec-WebSocket-Version: 13\r\n"
5564 "Sec-WebSocket-Key: %s\r\n",
5565 path, key);
5566
5567 /* TODO(mkm): take default hostname from http proto data if host == NULL */
5568 if (host != MG_WS_NO_HOST_HEADER_MAGIC) {
5569 mg_printf(nc, "Host: %s\r\n", host);
5570 }
5571 if (protocol != NULL) {
5572 mg_printf(nc, "Sec-WebSocket-Protocol: %s\r\n", protocol);
5573 }
5574 if (extra_headers != NULL) {
5575 mg_printf(nc, "%s", extra_headers);
5576 }
5577 mg_printf(nc, "\r\n");
5578}
5579
5580void mg_send_websocket_handshake(struct mg_connection *nc, const char *path,
5581 const char *extra_headers) {
5583 extra_headers);
5584}
5585
5586#endif /* MG_DISABLE_HTTP_WEBSOCKET */
5587
5588void mg_send_response_line(struct mg_connection *nc, int status_code,
5589 const char *extra_headers) {
5590 const char *status_message = "OK";
5591 switch (status_code) {
5592 case 206:
5593 status_message = "Partial Content";
5594 break;
5595 case 301:
5596 status_message = "Moved";
5597 break;
5598 case 302:
5599 status_message = "Found";
5600 break;
5601 case 401:
5602 status_message = "Unauthorized";
5603 break;
5604 case 403:
5605 status_message = "Forbidden";
5606 break;
5607 case 404:
5608 status_message = "Not Found";
5609 break;
5610 case 416:
5611 status_message = "Requested range not satisfiable";
5612 break;
5613 case 418:
5614 status_message = "I'm a teapot";
5615 break;
5616 case 500:
5617 status_message = "Internal Server Error";
5618 break;
5619 }
5620 mg_printf(nc, "HTTP/1.1 %d %s\r\n", status_code, status_message);
5621 if (extra_headers != NULL) {
5622 mg_printf(nc, "%s\r\n", extra_headers);
5623 }
5624}
5625
5626void mg_send_head(struct mg_connection *c, int status_code,
5627 int64_t content_length, const char *extra_headers) {
5628 mg_send_response_line(c, status_code, extra_headers);
5629 if (content_length < 0) {
5630 mg_printf(c, "%s", "Transfer-Encoding: chunked\r\n");
5631 } else {
5632 mg_printf(c, "Content-Length: %" INT64_FMT "\r\n", content_length);
5633 }
5634 mg_send(c, "\r\n", 2);
5635}
5636
5637#ifdef MG_DISABLE_FILESYSTEM
5638void mg_serve_http(struct mg_connection *nc, struct http_message *hm,
5639 struct mg_serve_http_opts opts) {
5640 mg_send_head(nc, 501, 0, NULL);
5641}
5642#else
5643static void mg_http_send_error(struct mg_connection *nc, int code,
5644 const char *reason) {
5645 if (!reason) reason = "";
5646 DBG(("%p %d %s", nc, code, reason));
5647 mg_send_head(nc, code, strlen(reason),
5648 "Content-Type: text/plain\r\nConnection: close");
5649 mg_send(nc, reason, strlen(reason));
5651}
5652#ifndef MG_DISABLE_SSI
5653static void mg_send_ssi_file(struct mg_connection *, const char *, FILE *, int,
5654 const struct mg_serve_http_opts *);
5655
5656static void mg_send_file_data(struct mg_connection *nc, FILE *fp) {
5657 char buf[BUFSIZ];
5658 size_t n;
5659 while ((n = fread(buf, 1, sizeof(buf), fp)) > 0) {
5660 mg_send(nc, buf, n);
5661 }
5662}
5663
5664#if 0
5665static void mg_do_ssi_include(struct mg_connection *nc, const char *ssi,
5666 char *tag, int include_level,
5667 const struct mg_serve_http_opts *opts) {
5668 char file_name[BUFSIZ], path[MAX_PATH_SIZE], *p;
5669 FILE *fp;
5670
5671 /*
5672 * sscanf() is safe here, since send_ssi_file() also uses buffer
5673 * of size MG_BUF_LEN to get the tag. So strlen(tag) is always < MG_BUF_LEN.
5674 */
5675 if (sscanf(tag, " virtual=\"%[^\"]\"", file_name) == 1) {
5676 /* File name is relative to the webserver root */
5677 snprintf(path, sizeof(path), "%s/%s", opts->document_root, file_name);
5678 } else if (sscanf(tag, " abspath=\"%[^\"]\"", file_name) == 1) {
5679 /*
5680 * File name is relative to the webserver working directory
5681 * or it is absolute system path
5682 */
5683 snprintf(path, sizeof(path), "%s", file_name);
5684 } else if (sscanf(tag, " file=\"%[^\"]\"", file_name) == 1 ||
5685 sscanf(tag, " \"%[^\"]\"", file_name) == 1) {
5686 /* File name is relative to the currect document */
5687 snprintf(path, sizeof(path), "%s", ssi);
5688 if ((p = strrchr(path, DIRSEP)) != NULL) {
5689 p[1] = '\0';
5690 }
5691 snprintf(path + strlen(path), sizeof(path) - strlen(path), "%s", file_name);
5692 } else {
5693 mg_printf(nc, "Bad SSI #include: [%s]", tag);
5694 return;
5695 }
5696
5697 if ((fp = fopen(path, "rb")) == NULL) {
5698 mg_printf(nc, "SSI include error: fopen(%s): %s", path, strerror(errno));
5699 } else {
5701 if (mg_match_prefix(opts->ssi_pattern, strlen(opts->ssi_pattern), path) >
5702 0) {
5703 mg_send_ssi_file(nc, path, fp, include_level + 1, opts);
5704 } else {
5705 mg_send_file_data(nc, fp);
5706 }
5707 fclose(fp);
5708 }
5709}
5710#endif
5711
5712#ifndef MG_DISABLE_POPEN
5713static void do_ssi_exec(struct mg_connection *nc, char *tag) {
5714 char cmd[BUFSIZ];
5715 FILE *fp;
5716
5717 if (sscanf(tag, " \"%[^\"]\"", cmd) != 1) {
5718 mg_printf(nc, "Bad SSI #exec: [%s]", tag);
5719 } else if ((fp = popen(cmd, "r")) == NULL) {
5720 mg_printf(nc, "Cannot SSI #exec: [%s]: %s", cmd, strerror(errno));
5721 } else {
5722 mg_send_file_data(nc, fp);
5723 pclose(fp);
5724 }
5725}
5726#endif /* !MG_DISABLE_POPEN */
5727
5728static void mg_do_ssi_call(struct mg_connection *nc, char *tag) {
5729 mg_call(nc, NULL, MG_EV_SSI_CALL, tag);
5730}
5731
5732/*
5733 * SSI directive has the following format:
5734 * <!--#directive parameter=value parameter=value -->
5735 */
5736static void mg_send_ssi_file(struct mg_connection *nc, const char *path,
5737 FILE *fp, int include_level,
5738 const struct mg_serve_http_opts *opts) {
5739 abort();
5740#if 0
5741 static const struct mg_str btag = MG_MK_STR("<!--#");
5742 static const struct mg_str d_include = MG_MK_STR("include");
5743 static const struct mg_str d_call = MG_MK_STR("call");
5744#ifndef MG_DISABLE_POPEN
5745 static const struct mg_str d_exec = MG_MK_STR("exec");
5746#endif
5747 char buf[BUFSIZ], *p = buf + btag.len; /* p points to SSI directive */
5748 int ch, len, in_ssi_tag;
5749
5750 if (include_level > 10) {
5751 mg_printf(nc, "SSI #include level is too deep (%s)", path);
5752 return;
5753 }
5754
5755 in_ssi_tag = len = 0;
5756 while ((ch = fgetc(fp)) != EOF) {
5757 if (in_ssi_tag && ch == '>' && buf[len - 1] == '-' && buf[len - 2] == '-') {
5758 size_t i = len - 2;
5759 in_ssi_tag = 0;
5760
5761 /* Trim closing --> */
5762 buf[i--] = '\0';
5763 while (i > 0 && buf[i] == ' ') {
5764 buf[i--] = '\0';
5765 }
5766
5767 /* Handle known SSI directives */
5768 if (memcmp(p, d_include.p, d_include.len) == 0) {
5769 mg_do_ssi_include(nc, path, p + d_include.len + 1, include_level, opts);
5770 } else if (memcmp(p, d_call.p, d_call.len) == 0) {
5771 mg_do_ssi_call(nc, p + d_call.len + 1);
5772#ifndef MG_DISABLE_POPEN
5773 } else if (memcmp(p, d_exec.p, d_exec.len) == 0) {
5774 do_ssi_exec(nc, p + d_exec.len + 1);
5775#endif
5776 } else {
5777 /* Silently ignore unknown SSI directive. */
5778 }
5779 len = 0;
5780 } else if (ch == '<') {
5781 in_ssi_tag = 1;
5782 if (len > 0) {
5783 mg_send(nc, buf, (size_t) len);
5784 }
5785 len = 0;
5786 buf[len++] = ch & 0xff;
5787 } else if (in_ssi_tag) {
5788 if (len == (int) btag.len && memcmp(buf, btag.p, btag.len) != 0) {
5789 /* Not an SSI tag */
5790 in_ssi_tag = 0;
5791 } else if (len == (int) sizeof(buf) - 2) {
5792 mg_printf(nc, "%s: SSI tag is too large", path);
5793 len = 0;
5794 }
5795 buf[len++] = ch & 0xff;
5796 } else {
5797 buf[len++] = ch & 0xff;
5798 if (len == (int) sizeof(buf)) {
5799 mg_send(nc, buf, (size_t) len);
5800 len = 0;
5801 }
5802 }
5803 }
5804
5805 /* Send the rest of buffered data */
5806 if (len > 0) {
5807 mg_send(nc, buf, (size_t) len);
5808 }
5809#endif
5810}
5811
5812static void mg_handle_ssi_request(struct mg_connection *nc, const char *path,
5813 const struct mg_serve_http_opts *opts) {
5814 FILE *fp;
5815 struct mg_str mime_type;
5816
5817 if ((fp = fopen(path, "rb")) == NULL) {
5818 mg_http_send_error(nc, 404, NULL);
5819 } else {
5821
5822 mime_type = mg_get_mime_type(path, "text/plain", opts);
5823 mg_send_response_line(nc, 200, opts->extra_headers);
5824 mg_printf(nc,
5825 "Content-Type: %.*s\r\n"
5826 "Connection: close\r\n\r\n",
5827 (int) mime_type.len, mime_type.p);
5828 mg_send_ssi_file(nc, path, fp, 0, opts);
5829 fclose(fp);
5831 }
5832}
5833#else
5834static void mg_handle_ssi_request(struct mg_connection *nc, const char *path,
5835 const struct mg_serve_http_opts *opts) {
5836 (void) path;
5837 (void) opts;
5838 mg_http_send_error(nc, 500, "SSI disabled");
5839}
5840#endif /* MG_DISABLE_SSI */
5841
5842static void mg_http_construct_etag(char *buf, size_t buf_len,
5843 const cs_stat_t *st) {
5844 snprintf(buf, buf_len, "\"%lx.%" INT64_FMT "\"", (unsigned long) st->st_mtime,
5845 (int64_t) st->st_size);
5846}
5847static void mg_gmt_time_string(char *buf, size_t buf_len, time_t *t) {
5848 strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", gmtime(t));
5849}
5850
5851static int mg_http_parse_range_header(const struct mg_str *header, int64_t *a,
5852 int64_t *b) {
5853 /*
5854 * There is no snscanf. Headers are not guaranteed to be NUL-terminated,
5855 * so we have this. Ugh.
5856 */
5857 int result;
5858 char *p = (char *) MG_MALLOC(header->len + 1);
5859 if (p == NULL) return 0;
5860 memcpy(p, header->p, header->len);
5861 p[header->len] = '\0';
5862 result = sscanf(p, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
5863 MG_FREE(p);
5864 return result;
5865}
5866
5867static void mg_http_send_file2(struct mg_connection *nc, const char *path,
5868 cs_stat_t *st, struct http_message *hm,
5869 struct mg_serve_http_opts *opts) {
5871 struct mg_str mime_type;
5872
5873 DBG(("%p [%s]", nc, path));
5875 if ((pd->file.fp = fopen(path, "rb")) == NULL) {
5876 int code;
5877 switch (errno) {
5878 case EACCES:
5879 code = 403;
5880 break;
5881 case ENOENT:
5882 code = 404;
5883 break;
5884 default:
5885 code = 500;
5886 };
5887 mg_http_send_error(nc, code, "Open failed");
5888 } else if (mg_match_prefix(opts->ssi_pattern, strlen(opts->ssi_pattern),
5889 path) > 0) {
5890 mg_handle_ssi_request(nc, path, opts);
5891 } else {
5892 char etag[50], current_time[50], last_modified[50], range[70];
5893 time_t t = time(NULL);
5894 int64_t r1 = 0, r2 = 0, cl = st->st_size;
5895 struct mg_str *range_hdr = mg_get_http_header(hm, "Range");
5896 int n, status_code = 200;
5897
5898 /* Handle Range header */
5899 range[0] = '\0';
5900 if (range_hdr != NULL &&
5901 (n = mg_http_parse_range_header(range_hdr, &r1, &r2)) > 0 && r1 >= 0 &&
5902 r2 >= 0) {
5903 /* If range is specified like "400-", set second limit to content len */
5904 if (n == 1) {
5905 r2 = cl - 1;
5906 }
5907 if (r1 > r2 || r2 >= cl) {
5908 status_code = 416;
5909 cl = 0;
5910 snprintf(range, sizeof(range),
5911 "Content-Range: bytes */%" INT64_FMT "\r\n",
5912 (int64_t) st->st_size);
5913 } else {
5914 status_code = 206;
5915 cl = r2 - r1 + 1;
5916 snprintf(range, sizeof(range), "Content-Range: bytes %" INT64_FMT
5917 "-%" INT64_FMT "/%" INT64_FMT "\r\n",
5918 r1, r1 + cl - 1, (int64_t) st->st_size);
5919#if _FILE_OFFSET_BITS == 64 || _POSIX_C_SOURCE >= 200112L || \
5920 _XOPEN_SOURCE >= 600
5921 fseeko(pd->file.fp, r1, SEEK_SET);
5922#else
5923 fseek(pd->file.fp, r1, SEEK_SET);
5924#endif
5925 }
5926 }
5927
5930 mg_gmt_time_string(last_modified, sizeof(last_modified), &st->st_mtime);
5931 mime_type = mg_get_mime_type(path, "text/plain", opts);
5932 /*
5933 * Content length casted to size_t because:
5934 * 1) that's the maximum buffer size anyway
5935 * 2) ESP8266 RTOS SDK newlib vprintf cannot contain a 64bit arg at non-last
5936 * position
5937 * TODO(mkm): fix ESP8266 RTOS SDK
5938 */
5939 mg_send_response_line(nc, status_code, opts->extra_headers);
5940 mg_printf(nc,
5941 "Date: %s\r\n"
5942 "Last-Modified: %s\r\n"
5943 "Accept-Ranges: bytes\r\n"
5944 "Content-Type: %.*s\r\n"
5946 "Connection: close\r\n"
5947#endif
5948 "Content-Length: %" SIZE_T_FMT
5949 "\r\n"
5950 "%sEtag: %s\r\n\r\n",
5952 (size_t) cl, range, etag);
5953
5954 pd->file.cl = cl;
5955 pd->file.type = DATA_FILE;
5957 }
5958}
5959
5960#endif
5961
5962int mg_url_decode(const char *src, int src_len, char *dst, int dst_len,
5963 int is_form_url_encoded) {
5964 int i, j, a, b;
5965#define HEXTOI(x) (isdigit(x) ? x - '0' : x - 'W')
5966
5967 for (i = j = 0; i < src_len && j < dst_len - 1; i++, j++) {
5968 if (src[i] == '%') {
5969 if (i < src_len - 2 && isxdigit(*(const unsigned char *) (src + i + 1)) &&
5970 isxdigit(*(const unsigned char *) (src + i + 2))) {
5971 a = tolower(*(const unsigned char *) (src + i + 1));
5972 b = tolower(*(const unsigned char *) (src + i + 2));
5973 dst[j] = (char) ((HEXTOI(a) << 4) | HEXTOI(b));
5974 i += 2;
5975 } else {
5976 return -1;
5977 }
5978 } else if (is_form_url_encoded && src[i] == '+') {
5979 dst[j] = ' ';
5980 } else {
5981 dst[j] = src[i];
5982 }
5983 }
5984
5985 dst[j] = '\0'; /* Null-terminate the destination */
5986
5987 return i >= src_len ? j : -1;
5988}
5989
5990int mg_get_http_var(const struct mg_str *buf, const char *name, char *dst,
5991 size_t dst_len) {
5992 const char *p, *e, *s;
5993 size_t name_len;
5994 int len;
5995
5996 if (dst == NULL || dst_len == 0) {
5997 len = -2;
5998 } else if (buf->p == NULL || name == NULL || buf->len == 0) {
5999 len = -1;
6000 dst[0] = '\0';
6001 } else {
6002 name_len = strlen(name);
6003 e = buf->p + buf->len;
6004 len = -1;
6005 dst[0] = '\0';
6006
6007 for (p = buf->p; p + name_len < e; p++) {
6008 if ((p == buf->p || p[-1] == '&') && p[name_len] == '=' &&
6009 !mg_ncasecmp(name, p, name_len)) {
6010 p += name_len + 1;
6011 s = (const char *) memchr(p, '&', (size_t)(e - p));
6012 if (s == NULL) {
6013 s = e;
6014 }
6015 len = mg_url_decode(p, (size_t)(s - p), dst, dst_len, 1);
6016 if (len == -1) {
6017 len = -2;
6018 }
6019 break;
6020 }
6021 }
6022 }
6023
6024 return len;
6025}
6026
6027void mg_send_http_chunk(struct mg_connection *nc, const char *buf, size_t len) {
6028 char chunk_size[50];
6029 int n;
6030
6031 n = snprintf(chunk_size, sizeof(chunk_size), "%lX\r\n", (unsigned long) len);
6032 mg_send(nc, chunk_size, n);
6033 mg_send(nc, buf, len);
6034 mg_send(nc, "\r\n", 2);
6035}
6036
6037void mg_printf_http_chunk(struct mg_connection *nc, const char *fmt, ...) {
6038 char mem[MG_VPRINTF_BUFFER_SIZE], *buf = mem;
6039 int len;
6040 va_list ap;
6041
6042 va_start(ap, fmt);
6043 len = mg_avprintf(&buf, sizeof(mem), fmt, ap);
6044 va_end(ap);
6045
6046 if (len >= 0) {
6047 mg_send_http_chunk(nc, buf, len);
6048 }
6049
6050 /* LCOV_EXCL_START */
6051 if (buf != mem && buf != NULL) {
6052 MG_FREE(buf);
6053 }
6054 /* LCOV_EXCL_STOP */
6055}
6056
6057void mg_printf_html_escape(struct mg_connection *nc, const char *fmt, ...) {
6058 char mem[MG_VPRINTF_BUFFER_SIZE], *buf = mem;
6059 int i, j, len;
6060 va_list ap;
6061
6062 va_start(ap, fmt);
6063 len = mg_avprintf(&buf, sizeof(mem), fmt, ap);
6064 va_end(ap);
6065
6066 if (len >= 0) {
6067 for (i = j = 0; i < len; i++) {
6068 if (buf[i] == '<' || buf[i] == '>') {
6069 mg_send(nc, buf + j, i - j);
6070 mg_send(nc, buf[i] == '<' ? "&lt;" : "&gt;", 4);
6071 j = i + 1;
6072 }
6073 }
6074 mg_send(nc, buf + j, i - j);
6075 }
6076
6077 /* LCOV_EXCL_START */
6078 if (buf != mem && buf != NULL) {
6079 MG_FREE(buf);
6080 }
6081 /* LCOV_EXCL_STOP */
6082}
6083
6084int mg_http_parse_header(struct mg_str *hdr, const char *var_name, char *buf,
6085 size_t buf_size) {
6086 int ch = ' ', ch1 = ',', len = 0, n = strlen(var_name);
6087 const char *p, *end = hdr ? hdr->p + hdr->len : NULL, *s = NULL;
6088
6089 if (buf != NULL && buf_size > 0) buf[0] = '\0';
6090 if (hdr == NULL) return 0;
6091
6092 /* Find where variable starts */
6093 for (s = hdr->p; s != NULL && s + n < end; s++) {
6094 if ((s == hdr->p || s[-1] == ch || s[-1] == ch1) && s[n] == '=' &&
6095 !memcmp(s, var_name, n))
6096 break;
6097 }
6098
6099 if (s != NULL && &s[n + 1] < end) {
6100 s += n + 1;
6101 if (*s == '"' || *s == '\'') {
6102 ch = ch1 = *s++;
6103 }
6104 p = s;
6105 while (p < end && p[0] != ch && p[0] != ch1 && len < (int) buf_size) {
6106 if (ch != ' ' && p[0] == '\\' && p[1] == ch) p++;
6107 buf[len++] = *p++;
6108 }
6109 if (len >= (int) buf_size || (ch != ' ' && *p != ch)) {
6110 len = 0;
6111 } else {
6112 if (len > 0 && s[len - 1] == ',') len--;
6113 if (len > 0 && s[len - 1] == ';') len--;
6114 buf[len] = '\0';
6115 }
6116 }
6117
6118 return len;
6119}
6120
6121#ifndef MG_DISABLE_FILESYSTEM
6122static int mg_is_file_hidden(const char *path,
6123 const struct mg_serve_http_opts *opts,
6124 int exclude_specials) {
6125 const char *p1 = opts->per_directory_auth_file;
6126 const char *p2 = opts->hidden_file_pattern;
6127
6128 /* Strip directory path from the file name */
6129 const char *pdir = strrchr(path, DIRSEP);
6130 if (pdir != NULL) {
6131 path = pdir + 1;
6132 }
6133
6134 return (exclude_specials && (!strcmp(path, ".") || !strcmp(path, ".."))) ||
6135 (p1 != NULL &&
6136 mg_match_prefix(p1, strlen(p1), path) == (int) strlen(p1)) ||
6137 (p2 != NULL && mg_match_prefix(p2, strlen(p2), path) > 0);
6138}
6139
6140#ifndef MG_DISABLE_HTTP_DIGEST_AUTH
6141static void mg_mkmd5resp(const char *method, size_t method_len, const char *uri,
6142 size_t uri_len, const char *ha1, size_t ha1_len,
6143 const char *nonce, size_t nonce_len, const char *nc,
6144 size_t nc_len, const char *cnonce, size_t cnonce_len,
6145 const char *qop, size_t qop_len, char *resp) {
6146 static const char colon[] = ":";
6147 static const size_t one = 1;
6148 char ha2[33];
6149
6150 cs_md5(ha2, method, method_len, colon, one, uri, uri_len, NULL);
6151 cs_md5(resp, ha1, ha1_len, colon, one, nonce, nonce_len, colon, one, nc,
6152 nc_len, colon, one, cnonce, cnonce_len, colon, one, qop, qop_len,
6153 colon, one, ha2, sizeof(ha2) - 1, NULL);
6154}
6155
6157 const char *method, const char *uri,
6158 const char *auth_domain, const char *user,
6159 const char *passwd) {
6160 static const char colon[] = ":", qop[] = "auth";
6161 static const size_t one = 1;
6162 char ha1[33], resp[33], cnonce[40];
6163
6164 snprintf(cnonce, sizeof(cnonce), "%x", (unsigned int) time(NULL));
6165 cs_md5(ha1, user, (size_t) strlen(user), colon, one, auth_domain,
6166 (size_t) strlen(auth_domain), colon, one, passwd,
6167 (size_t) strlen(passwd), NULL);
6168 mg_mkmd5resp(method, strlen(method), uri, strlen(uri), ha1, sizeof(ha1) - 1,
6169 cnonce, strlen(cnonce), "1", one, cnonce, strlen(cnonce), qop,
6170 sizeof(qop) - 1, resp);
6171 return snprintf(buf, buf_len,
6172 "Authorization: Digest username=\"%s\","
6173 "realm=\"%s\",uri=\"%s\",qop=%s,nc=1,cnonce=%s,"
6174 "nonce=%s,response=%s\r\n",
6175 user, auth_domain, uri, qop, cnonce, cnonce, resp);
6176}
6177
6178/*
6179 * Check for authentication timeout.
6180 * Clients send time stamp encoded in nonce. Make sure it is not too old,
6181 * to prevent replay attacks.
6182 * Assumption: nonce is a hexadecimal number of seconds since 1970.
6183 */
6184static int mg_check_nonce(const char *nonce) {
6185 unsigned long now = (unsigned long) time(NULL);
6186 unsigned long val = (unsigned long) strtoul(nonce, NULL, 16);
6187 return now < val || now - val < 3600;
6188}
6189
6190/*
6191 * Authenticate HTTP request against opened passwords file.
6192 * Returns 1 if authenticated, 0 otherwise.
6193 */
6195 const char *auth_domain, FILE *fp) {
6196 struct mg_str *hdr;
6197 char buf[128], f_user[sizeof(buf)], f_ha1[sizeof(buf)], f_domain[sizeof(buf)];
6198 char user[50], cnonce[33], response[40], uri[200], qop[20], nc[20], nonce[30];
6199 char expected_response[33];
6200
6201 /* Parse "Authorization:" header, fail fast on parse error */
6202 if (hm == NULL || fp == NULL ||
6203 (hdr = mg_get_http_header(hm, "Authorization")) == NULL ||
6204 mg_http_parse_header(hdr, "username", user, sizeof(user)) == 0 ||
6205 mg_http_parse_header(hdr, "cnonce", cnonce, sizeof(cnonce)) == 0 ||
6206 mg_http_parse_header(hdr, "response", response, sizeof(response)) == 0 ||
6207 mg_http_parse_header(hdr, "uri", uri, sizeof(uri)) == 0 ||
6208 mg_http_parse_header(hdr, "qop", qop, sizeof(qop)) == 0 ||
6209 mg_http_parse_header(hdr, "nc", nc, sizeof(nc)) == 0 ||
6210 mg_http_parse_header(hdr, "nonce", nonce, sizeof(nonce)) == 0 ||
6211 mg_check_nonce(nonce) == 0) {
6212 return 0;
6213 }
6214
6215 /*
6216 * Read passwords file line by line. If should have htdigest format,
6217 * i.e. each line should be a colon-separated sequence:
6218 * USER_NAME:DOMAIN_NAME:HA1_HASH_OF_USER_DOMAIN_AND_PASSWORD
6219 */
6220 while (fgets(buf, sizeof(buf), fp) != NULL) {
6221 if (sscanf(buf, "%[^:]:%[^:]:%s", f_user, f_domain, f_ha1) == 3 &&
6222 strcmp(user, f_user) == 0 &&
6223 /* NOTE(lsm): due to a bug in MSIE, we do not compare URIs */
6224 strcmp(auth_domain, f_domain) == 0) {
6225 /* User and domain matched, check the password */
6227 hm->method.p, hm->method.len, hm->uri.p,
6228 hm->uri.len + (hm->query_string.len ? hm->query_string.len + 1 : 0),
6229 f_ha1, strlen(f_ha1), nonce, strlen(nonce), nc, strlen(nc), cnonce,
6230 strlen(cnonce), qop, strlen(qop), expected_response);
6232 }
6233 }
6234
6235 /* None of the entries in the passwords file matched - return failure */
6236 return 0;
6237}
6238
6239static int mg_is_authorized(struct http_message *hm, const char *path,
6240 int is_directory, const char *domain,
6241 const char *passwords_file,
6242 int is_global_pass_file) {
6243 char buf[MG_MAX_PATH];
6244 const char *p;
6245 FILE *fp;
6246 int authorized = 1;
6247
6248 if (domain != NULL && passwords_file != NULL) {
6249 if (is_global_pass_file) {
6250 fp = fopen(passwords_file, "r");
6251 } else if (is_directory) {
6252 snprintf(buf, sizeof(buf), "%s%c%s", path, DIRSEP, passwords_file);
6253 fp = fopen(buf, "r");
6254 } else {
6255 p = strrchr(path, DIRSEP);
6256 if (p == NULL) p = path;
6257 snprintf(buf, sizeof(buf), "%.*s%c%s", (int) (p - path), path, DIRSEP,
6259 fp = fopen(buf, "r");
6260 }
6261
6262 if (fp != NULL) {
6264 fclose(fp);
6265 }
6266 }
6267
6268 DBG(("%s %s %d %d", path, passwords_file ? passwords_file : "",
6270 return authorized;
6271}
6272#else
6273static int mg_is_authorized(struct http_message *hm, const char *path,
6274 int is_directory, const char *domain,
6275 const char *passwords_file,
6276 int is_global_pass_file) {
6277 (void) hm;
6278 (void) path;
6279 (void) is_directory;
6280 (void) domain;
6283 return 1;
6284}
6285#endif
6286
6287#ifndef MG_DISABLE_DIRECTORY_LISTING
6288static size_t mg_url_encode(const char *src, size_t s_len, char *dst,
6289 size_t dst_len) {
6290 static const char *dont_escape = "._-$,;~()/";
6291 static const char *hex = "0123456789abcdef";
6292 size_t i = 0, j = 0;
6293
6294 for (i = j = 0; dst_len > 0 && i < s_len && j + 2 < dst_len - 1; i++, j++) {
6295 if (isalnum(*(const unsigned char *) (src + i)) ||
6296 strchr(dont_escape, *(const unsigned char *) (src + i)) != NULL) {
6297 dst[j] = src[i];
6298 } else if (j + 3 < dst_len) {
6299 dst[j] = '%';
6300 dst[j + 1] = hex[(*(const unsigned char *) (src + i)) >> 4];
6301 dst[j + 2] = hex[(*(const unsigned char *) (src + i)) & 0xf];
6302 j += 2;
6303 }
6304 }
6305
6306 dst[j] = '\0';
6307 return j;
6308}
6309
6310static void mg_escape(const char *src, char *dst, size_t dst_len) {
6311 size_t n = 0;
6312 while (*src != '\0' && n + 5 < dst_len) {
6313 unsigned char ch = *(unsigned char *) src++;
6314 if (ch == '<') {
6315 n += snprintf(dst + n, dst_len - n, "%s", "&lt;");
6316 } else {
6317 dst[n++] = ch;
6318 }
6319 }
6320 dst[n] = '\0';
6321}
6322
6323static void mg_print_dir_entry(struct mg_connection *nc, const char *file_name,
6324 cs_stat_t *stp) {
6325 char size[64], mod[64], href[MAX_PATH_SIZE * 3], path[MAX_PATH_SIZE];
6326 int64_t fsize = stp->st_size;
6327 int is_dir = S_ISDIR(stp->st_mode);
6328 const char *slash = is_dir ? "/" : "";
6329
6330 if (is_dir) {
6331 snprintf(size, sizeof(size), "%s", "[DIRECTORY]");
6332 } else {
6333 /*
6334 * We use (double) cast below because MSVC 6 compiler cannot
6335 * convert unsigned __int64 to double.
6336 */
6337 if (fsize < 1024) {
6338 snprintf(size, sizeof(size), "%d", (int) fsize);
6339 } else if (fsize < 0x100000) {
6340 snprintf(size, sizeof(size), "%.1fk", (double) fsize / 1024.0);
6341 } else if (fsize < 0x40000000) {
6342 snprintf(size, sizeof(size), "%.1fM", (double) fsize / 1048576);
6343 } else {
6344 snprintf(size, sizeof(size), "%.1fG", (double) fsize / 1073741824);
6345 }
6346 }
6347 strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", localtime(&stp->st_mtime));
6348 mg_escape(file_name, path, sizeof(path));
6351 "<tr><td><a href=\"%s%s\">%s%s</a></td>"
6352 "<td>%s</td><td name=%" INT64_FMT ">%s</td></tr>\n",
6353 href, slash, path, slash, mod, is_dir ? -1 : fsize,
6354 size);
6355}
6356
6357static void mg_scan_directory(struct mg_connection *nc, const char *dir,
6358 const struct mg_serve_http_opts *opts,
6359 void (*func)(struct mg_connection *, const char *,
6360 cs_stat_t *)) {
6361 char path[MAX_PATH_SIZE];
6362 cs_stat_t st;
6363 struct dirent *dp;
6364 DIR *dirp;
6365
6366 DBG(("%p [%s]", nc, dir));
6367 if ((dirp = (opendir(dir))) != NULL) {
6368 while ((dp = readdir(dirp)) != NULL) {
6369 /* Do not show current dir and hidden files */
6370 if (mg_is_file_hidden((const char *) dp->d_name, opts, 1)) {
6371 continue;
6372 }
6373 snprintf(path, sizeof(path), "%s/%s", dir, dp->d_name);
6374 if (mg_stat(path, &st) == 0) {
6375 func(nc, (const char *) dp->d_name, &st);
6376 }
6377 }
6378 closedir(dirp);
6379 } else {
6380 DBG(("%p opendir(%s) -> %d", nc, dir, errno));
6381 }
6382}
6383
6384static void mg_send_directory_listing(struct mg_connection *nc, const char *dir,
6385 struct http_message *hm,
6386 struct mg_serve_http_opts *opts) {
6387 static const char *sort_js_code =
6388 "<script>function srt(tb, col) {"
6389 "var tr = Array.prototype.slice.call(tb.rows, 0),"
6390 "tr = tr.sort(function (a, b) { var c1 = a.cells[col], c2 = b.cells[col],"
6391 "n1 = c1.getAttribute('name'), n2 = c2.getAttribute('name'), "
6392 "t1 = a.cells[2].getAttribute('name'), "
6393 "t2 = b.cells[2].getAttribute('name'); "
6394 "return t1 < 0 && t2 >= 0 ? -1 : t2 < 0 && t1 >= 0 ? 1 : "
6395 "n1 ? parseInt(n2) - parseInt(n1) : "
6396 "c1.textContent.trim().localeCompare(c2.textContent.trim()); });";
6397 static const char *sort_js_code2 =
6398 "for (var i = 0; i < tr.length; i++) tb.appendChild(tr[i]);}"
6399 "window.onload = function() { "
6400 "var tb = document.getElementById('tb');"
6401 "document.onclick = function(ev){ "
6402 "var c = ev.target.rel; if (c) srt(tb, c)}; srt(tb, 2); };</script>";
6403
6404 mg_send_response_line(nc, 200, opts->extra_headers);
6405 mg_printf(nc, "%s: %s\r\n%s: %s\r\n\r\n", "Transfer-Encoding", "chunked",
6406 "Content-Type", "text/html; charset=utf-8");
6407
6409 nc,
6410 "<html><head><title>Index of %.*s</title>%s%s"
6411 "<style>th,td {text-align: left; padding-right: 1em; }</style></head>"
6412 "<body><h1>Index of %.*s</h1><pre><table cellpadding=\"0\"><thead>"
6413 "<tr><th><a href=# rel=0>Name</a></th><th>"
6414 "<a href=# rel=1>Modified</a</th>"
6415 "<th><a href=# rel=2>Size</a></th></tr>"
6416 "<tr><td colspan=\"3\"><hr></td></tr></thead><tbody id=tb>",
6417 (int) hm->uri.len, hm->uri.p, sort_js_code, sort_js_code2,
6418 (int) hm->uri.len, hm->uri.p);
6420 mg_printf_http_chunk(nc, "%s", "</tbody></body></html>");
6421 mg_send_http_chunk(nc, "", 0);
6422 /* TODO(rojer): Remove when cesanta/dev/issues/197 is fixed. */
6424}
6425#endif /* MG_DISABLE_DIRECTORY_LISTING */
6426
6427#ifndef MG_DISABLE_DAV
6428static void mg_print_props(struct mg_connection *nc, const char *name,
6429 cs_stat_t *stp) {
6430 char mtime[64], buf[MAX_PATH_SIZE * 3];
6431 time_t t = stp->st_mtime; /* store in local variable for NDK compile */
6432 mg_gmt_time_string(mtime, sizeof(mtime), &t);
6433 mg_url_encode(name, strlen(name), buf, sizeof(buf));
6434 mg_printf(nc,
6435 "<d:response>"
6436 "<d:href>%s</d:href>"
6437 "<d:propstat>"
6438 "<d:prop>"
6439 "<d:resourcetype>%s</d:resourcetype>"
6440 "<d:getcontentlength>%" INT64_FMT
6441 "</d:getcontentlength>"
6442 "<d:getlastmodified>%s</d:getlastmodified>"
6443 "</d:prop>"
6444 "<d:status>HTTP/1.1 200 OK</d:status>"
6445 "</d:propstat>"
6446 "</d:response>\n",
6447 buf, S_ISDIR(stp->st_mode) ? "<d:collection/>" : "",
6448 (int64_t) stp->st_size, mtime);
6449}
6450
6451static void mg_handle_propfind(struct mg_connection *nc, const char *path,
6452 cs_stat_t *stp, struct http_message *hm,
6453 struct mg_serve_http_opts *opts) {
6454 static const char header[] =
6455 "HTTP/1.1 207 Multi-Status\r\n"
6456 "Connection: close\r\n"
6457 "Content-Type: text/xml; charset=utf-8\r\n\r\n"
6458 "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
6459 "<d:multistatus xmlns:d='DAV:'>\n";
6460 static const char footer[] = "</d:multistatus>\n";
6461 const struct mg_str *depth = mg_get_http_header(hm, "Depth");
6462
6463 /* Print properties for the requested resource itself */
6464 if (S_ISDIR(stp->st_mode) &&
6465 strcmp(opts->enable_directory_listing, "yes") != 0) {
6466 mg_printf(nc, "%s", "HTTP/1.1 403 Directory Listing Denied\r\n\r\n");
6467 } else {
6468 char uri[MAX_PATH_SIZE];
6469 mg_send(nc, header, sizeof(header) - 1);
6470 snprintf(uri, sizeof(uri), "%.*s", (int) hm->uri.len, hm->uri.p);
6471 mg_print_props(nc, uri, stp);
6472 if (S_ISDIR(stp->st_mode) && (depth == NULL || mg_vcmp(depth, "0") != 0)) {
6474 }
6475 mg_send(nc, footer, sizeof(footer) - 1);
6477 }
6478}
6479
6480#ifdef MG_ENABLE_FAKE_DAVLOCK
6481/*
6482 * Windows explorer (probably there are another WebDav clients like it)
6483 * requires LOCK support in webdav. W/out this, it still works, but fails
6484 * to save file: shows error message and offers "Save As".
6485 * "Save as" works, but this message is very annoying.
6486 * This is fake lock, which doesn't lock something, just returns LOCK token,
6487 * UNLOCK always answers "OK".
6488 * With this fake LOCK Windows Explorer looks happy and saves file.
6489 * NOTE: that is not DAV LOCK imlementation, it is just a way to shut up
6490 * Windows native DAV client. This is why FAKE LOCK is not enabed by default
6491 */
6492static void mg_handle_lock(struct mg_connection *nc, const char *path) {
6493 static const char *reply =
6494 "HTTP/1.1 207 Multi-Status\r\n"
6495 "Connection: close\r\n"
6496 "Content-Type: text/xml; charset=utf-8\r\n\r\n"
6497 "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
6498 "<d:multistatus xmlns:d='DAV:'>\n"
6499 "<D:lockdiscovery>\n"
6500 "<D:activelock>\n"
6501 "<D:locktoken>\n"
6502 "<D:href>\n"
6503 "opaquelocktoken:%s%u"
6504 "</D:href>"
6505 "</D:locktoken>"
6506 "</D:activelock>\n"
6507 "</D:lockdiscovery>"
6508 "</d:multistatus>\n";
6509 mg_printf(nc, reply, path, (unsigned int) time(NULL));
6511}
6512#endif
6513
6514static void mg_handle_mkcol(struct mg_connection *nc, const char *path,
6515 struct http_message *hm) {
6516 int status_code = 500;
6517 if (hm->body.len != (size_t) ~0 && hm->body.len > 0) {
6518 status_code = 415;
6519 } else if (!mg_mkdir(path, 0755)) {
6520 status_code = 201;
6521 } else if (errno == EEXIST) {
6522 status_code = 405;
6523 } else if (errno == EACCES) {
6524 status_code = 403;
6525 } else if (errno == ENOENT) {
6526 status_code = 409;
6527 } else {
6528 status_code = 500;
6529 }
6530 mg_http_send_error(nc, status_code, NULL);
6531}
6532
6534 const char *dir) {
6535 char path[MAX_PATH_SIZE];
6536 struct dirent *dp;
6537 cs_stat_t st;
6538 DIR *dirp;
6539
6540 if ((dirp = opendir(dir)) == NULL) return 0;
6541
6542 while ((dp = readdir(dirp)) != NULL) {
6543 if (mg_is_file_hidden((const char *) dp->d_name, opts, 1)) {
6544 continue;
6545 }
6546 snprintf(path, sizeof(path), "%s%c%s", dir, '/', dp->d_name);
6547 mg_stat(path, &st);
6548 if (S_ISDIR(st.st_mode)) {
6550 } else {
6551 remove(path);
6552 }
6553 }
6554 closedir(dirp);
6555 rmdir(dir);
6556
6557 return 1;
6558}
6559
6560static void mg_handle_move(struct mg_connection *c,
6561 const struct mg_serve_http_opts *opts,
6562 const char *path, struct http_message *hm) {
6563 const struct mg_str *dest = mg_get_http_header(hm, "Destination");
6564 if (dest == NULL) {
6565 mg_http_send_error(c, 411, NULL);
6566 } else {
6567 const char *p = (char *) memchr(dest->p, '/', dest->len);
6568 if (p != NULL && p[1] == '/' &&
6569 (p = (char *) memchr(p + 2, '/', dest->p + dest->len - p)) != NULL) {
6570 char buf[MAX_PATH_SIZE];
6571 snprintf(buf, sizeof(buf), "%s%.*s", opts->dav_document_root,
6572 (int) (dest->p + dest->len - p), p);
6573 if (rename(path, buf) == 0) {
6574 mg_http_send_error(c, 200, NULL);
6575 } else {
6576 mg_http_send_error(c, 418, NULL);
6577 }
6578 } else {
6579 mg_http_send_error(c, 500, NULL);
6580 }
6581 }
6582}
6583
6584static void mg_handle_delete(struct mg_connection *nc,
6585 const struct mg_serve_http_opts *opts,
6586 const char *path) {
6587 cs_stat_t st;
6588 if (mg_stat(path, &st) != 0) {
6589 mg_http_send_error(nc, 404, NULL);
6590 } else if (S_ISDIR(st.st_mode)) {
6592 mg_http_send_error(nc, 204, NULL);
6593 } else if (remove(path) == 0) {
6594 mg_http_send_error(nc, 204, NULL);
6595 } else {
6596 mg_http_send_error(nc, 423, NULL);
6597 }
6598}
6599
6600/* Return -1 on error, 1 on success. */
6601static int mg_create_itermediate_directories(const char *path) {
6602 const char *s;
6603
6604 /* Create intermediate directories if they do not exist */
6605 for (s = path + 1; *s != '\0'; s++) {
6606 if (*s == '/') {
6607 char buf[MAX_PATH_SIZE];
6608 cs_stat_t st;
6609 snprintf(buf, sizeof(buf), "%.*s", (int) (s - path), path);
6610 buf[sizeof(buf) - 1] = '\0';
6611 if (mg_stat(buf, &st) != 0 && mg_mkdir(buf, 0755) != 0) {
6612 return -1;
6613 }
6614 }
6615 }
6616
6617 return 1;
6618}
6619
6620static void mg_handle_put(struct mg_connection *nc, const char *path,
6621 struct http_message *hm) {
6623 cs_stat_t st;
6624 const struct mg_str *cl_hdr = mg_get_http_header(hm, "Content-Length");
6625 int rc, status_code = mg_stat(path, &st) == 0 ? 200 : 201;
6626
6628 if ((rc = mg_create_itermediate_directories(path)) == 0) {
6629 mg_printf(nc, "HTTP/1.1 %d OK\r\nContent-Length: 0\r\n\r\n", status_code);
6630 } else if (rc == -1) {
6631 mg_http_send_error(nc, 500, NULL);
6632 } else if (cl_hdr == NULL) {
6633 mg_http_send_error(nc, 411, NULL);
6634 } else if ((pd->file.fp = fopen(path, "w+b")) == NULL) {
6635 mg_http_send_error(nc, 500, NULL);
6636 } else {
6637 const struct mg_str *range_hdr = mg_get_http_header(hm, "Content-Range");
6638 int64_t r1 = 0, r2 = 0;
6639 pd->file.type = DATA_PUT;
6640 mg_set_close_on_exec(fileno(pd->file.fp));
6641 pd->file.cl = to64(cl_hdr->p);
6642 if (range_hdr != NULL &&
6644 status_code = 206;
6645 fseeko(pd->file.fp, r1, SEEK_SET);
6646 pd->file.cl = r2 > r1 ? r2 - r1 + 1 : pd->file.cl - r1;
6647 }
6648 mg_printf(nc, "HTTP/1.1 %d OK\r\nContent-Length: 0\r\n\r\n", status_code);
6649 /* Remove HTTP request from the mbuf, leave only payload */
6650 mbuf_remove(&nc->recv_mbuf, hm->message.len - hm->body.len);
6652 }
6653}
6654#endif /* MG_DISABLE_DAV */
6655
6656static int mg_is_dav_request(const struct mg_str *s) {
6657 static const char *methods[] = {"PUT", "DELETE", "MKCOL", "PROPFIND", "MOVE"
6658#ifdef MG_ENABLE_FAKE_DAVLOCK
6659 ,
6660 "LOCK", "UNLOCK"
6661#endif
6662 };
6663 size_t i;
6664
6665 for (i = 0; i < ARRAY_SIZE(methods); i++) {
6666 if (mg_vcmp(s, methods[i]) == 0) {
6667 return 1;
6668 }
6669 }
6670
6671 return 0;
6672}
6673
6674/*
6675 * Given a directory path, find one of the files specified in the
6676 * comma-separated list of index files `list`.
6677 * First found index file wins. If an index file is found, then gets
6678 * appended to the `path`, stat-ed, and result of `stat()` passed to `stp`.
6679 * If index file is not found, then `path` and `stp` remain unchanged.
6680 */
6681MG_INTERNAL void mg_find_index_file(const char *path, const char *list,
6682 char **index_file, cs_stat_t *stp) {
6683 struct mg_str vec;
6684 size_t path_len = strlen(path);
6685 int found = 0;
6686 *index_file = NULL;
6687
6688 /* Traverse index files list. For each entry, append it to the given */
6689 /* path and see if the file exists. If it exists, break the loop */
6690 while ((list = mg_next_comma_list_entry(list, &vec, NULL)) != NULL) {
6691 cs_stat_t st;
6692 size_t len = path_len + 1 + vec.len + 1;
6693 *index_file = (char *) MG_REALLOC(*index_file, len);
6694 if (*index_file == NULL) break;
6695 snprintf(*index_file, len, "%s%c%.*s", path, DIRSEP, (int) vec.len, vec.p);
6696
6697 /* Does it exist? Is it a file? */
6698 if (mg_stat(*index_file, &st) == 0 && S_ISREG(st.st_mode)) {
6699 /* Yes it does, break the loop */
6700 *stp = st;
6701 found = 1;
6702 break;
6703 }
6704 }
6705 if (!found) {
6707 *index_file = NULL;
6708 }
6709 DBG(("[%s] [%s]", path, (*index_file ? *index_file : "")));
6710}
6711
6713 struct mg_connection *c, struct http_message *hm,
6714 const struct mg_serve_http_opts *opts) {
6715 const char *rewrites = opts->url_rewrites;
6716 struct mg_str a, b;
6717 char local_port[20] = {'%'};
6718
6719 mg_conn_addr_to_str(c, local_port + 1, sizeof(local_port) - 1,
6721
6722 while ((rewrites = mg_next_comma_list_entry(rewrites, &a, &b)) != NULL) {
6723 if (mg_vcmp(&a, local_port) == 0) {
6725 mg_printf(c, "Content-Length: 0\r\nLocation: %.*s%.*s\r\n\r\n",
6726 (int) b.len, b.p, (int) (hm->proto.p - hm->uri.p - 1),
6727 hm->uri.p);
6728 return 1;
6729 }
6730 }
6731
6732 return 0;
6733}
6734
6736 const struct mg_serve_http_opts *opts,
6737 char **local_path,
6738 struct mg_str *remainder) {
6739 int ok = 1;
6740 const char *cp = hm->uri.p, *cp_end = hm->uri.p + hm->uri.len;
6741 struct mg_str root = {NULL, 0};
6742 const char *file_uri_start = cp;
6743 *local_path = NULL;
6744 remainder->p = NULL;
6745 remainder->len = 0;
6746
6747 { /* 1. Determine which root to use. */
6748 const char *rewrites = opts->url_rewrites;
6749 struct mg_str *hh = mg_get_http_header(hm, "Host");
6750 struct mg_str a, b;
6751 /* Check rewrites first. */
6752 while ((rewrites = mg_next_comma_list_entry(rewrites, &a, &b)) != NULL) {
6753 if (a.len > 1 && a.p[0] == '@') {
6754 /* Host rewrite. */
6755 if (hh != NULL && hh->len == a.len - 1 &&
6756 mg_ncasecmp(a.p + 1, hh->p, a.len - 1) == 0) {
6757 root = b;
6758 break;
6759 }
6760 } else {
6761 /* Regular rewrite, URI=directory */
6762 int match_len = mg_match_prefix_n(a, hm->uri);
6763 if (match_len > 0) {
6764 file_uri_start = hm->uri.p + match_len;
6765 if (*file_uri_start == '/' || file_uri_start == cp_end) {
6766 /* Match ended at component boundary, ok. */
6767 } else if (*(file_uri_start - 1) == '/') {
6768 /* Pattern ends with '/', backtrack. */
6770 } else {
6771 /* No match: must fall on the component boundary. */
6772 continue;
6773 }
6774 root = b;
6775 break;
6776 }
6777 }
6778 }
6779 /* If no rewrite rules matched, use DAV or regular document root. */
6780 if (root.p == NULL) {
6781#ifndef MG_DISABLE_DAV
6782 if (opts->dav_document_root != NULL && mg_is_dav_request(&hm->method)) {
6783 root.p = opts->dav_document_root;
6784 root.len = strlen(opts->dav_document_root);
6785 } else
6786#endif
6787 {
6788 root.p = opts->document_root;
6789 root.len = strlen(opts->document_root);
6790 }
6791 }
6792 assert(root.p != NULL && root.len > 0);
6793 }
6794
6795 { /* 2. Find where in the canonical URI path the local path ends. */
6796 const char *u = file_uri_start + 1;
6797 char *lp = (char *) MG_MALLOC(root.len + hm->uri.len + 1);
6798 char *lp_end = lp + root.len + hm->uri.len + 1;
6799 char *p = lp, *ps;
6800 int exists = 1;
6801 if (lp == NULL) {
6802 ok = 0;
6803 goto out;
6804 }
6805 memcpy(p, root.p, root.len);
6806 p += root.len;
6807 if (*(p - 1) == DIRSEP) p--;
6808 *p = '\0';
6809 ps = p;
6810
6811 /* Chop off URI path components one by one and build local path. */
6812 while (u <= cp_end) {
6813 const char *next = u;
6814 struct mg_str component;
6815 if (exists) {
6816 cs_stat_t st;
6817 exists = (mg_stat(lp, &st) == 0);
6818 if (exists && S_ISREG(st.st_mode)) {
6819 /* We found the terminal, the rest of the URI (if any) is path_info.
6820 */
6821 if (*(u - 1) == '/') u--;
6822 break;
6823 }
6824 }
6825 if (u >= cp_end) break;
6826 parse_uri_component((const char **) &next, cp_end, '/', &component);
6827 if (component.len > 0) {
6828 int len;
6829 memmove(p + 1, component.p, component.len);
6830 len = mg_url_decode(p + 1, component.len, p + 1, lp_end - p - 1, 0);
6831 if (len <= 0) {
6832 ok = 0;
6833 break;
6834 }
6835 component.p = p + 1;
6836 component.len = len;
6837 if (mg_vcmp(&component, ".") == 0) {
6838 /* Yum. */
6839 } else if (mg_vcmp(&component, "..") == 0) {
6840 while (p > ps && *p != DIRSEP) p--;
6841 *p = '\0';
6842 } else {
6843 size_t i;
6844#ifdef _WIN32
6845 /* On Windows, make sure it's valid Unicode (no funny stuff). */
6846 wchar_t buf[MG_MAX_PATH * 2];
6847 if (to_wchar(component.p, buf, MG_MAX_PATH) == 0) {
6848 DBG(("[%.*s] smells funny", (int) component.len, component.p));
6849 ok = 0;
6850 break;
6851 }
6852#endif
6853 *p++ = DIRSEP;
6854 /* No NULs and DIRSEPs in the component (percent-encoded). */
6855 for (i = 0; i < component.len; i++, p++) {
6856 if (*p == '\0' || *p == DIRSEP
6858 /* On Windows, "/" is also accepted, so check for that too. */
6859 ||
6860 *p == '/'
6861#endif
6862 ) {
6863 ok = 0;
6864 break;
6865 }
6866 }
6867 }
6868 }
6869 u = next;
6870 }
6871 if (ok) {
6872 *local_path = lp;
6873 remainder->p = u;
6874 remainder->len = cp_end - u;
6875 } else {
6876 MG_FREE(lp);
6877 }
6878 }
6879
6880out:
6881 DBG(("'%.*s' -> '%s' + '%.*s'", (int) hm->uri.len, hm->uri.p,
6882 *local_path ? *local_path : "", (int) remainder->len, remainder->p));
6883 return ok;
6884}
6885
6886#ifndef MG_DISABLE_CGI
6887#ifdef _WIN32
6888struct mg_threadparam {
6889 sock_t s;
6890 HANDLE hPipe;
6891};
6892
6893static int mg_wait_until_ready(sock_t sock, int for_read) {
6894 fd_set set;
6895 FD_ZERO(&set);
6896 FD_SET(sock, &set);
6897 return select(sock + 1, for_read ? &set : 0, for_read ? 0 : &set, 0, 0) == 1;
6898}
6899
6900static void *mg_push_to_stdin(void *arg) {
6901 struct mg_threadparam *tp = (struct mg_threadparam *) arg;
6902 int n, sent, stop = 0;
6903 DWORD k;
6904 char buf[BUFSIZ];
6905
6906 while (!stop && mg_wait_until_ready(tp->s, 1) &&
6907 (n = recv(tp->s, buf, sizeof(buf), 0)) > 0) {
6908 if (n == -1 && GetLastError() == WSAEWOULDBLOCK) continue;
6909 for (sent = 0; !stop && sent < n; sent += k) {
6910 if (!WriteFile(tp->hPipe, buf + sent, n - sent, &k, 0)) stop = 1;
6911 }
6912 }
6913 DBG(("%s", "FORWARED EVERYTHING TO CGI"));
6914 CloseHandle(tp->hPipe);
6915 MG_FREE(tp);
6916 _endthread();
6917 return NULL;
6918}
6919
6920static void *mg_pull_from_stdout(void *arg) {
6921 struct mg_threadparam *tp = (struct mg_threadparam *) arg;
6922 int k = 0, stop = 0;
6923 DWORD n, sent;
6924 char buf[BUFSIZ];
6925
6926 while (!stop && ReadFile(tp->hPipe, buf, sizeof(buf), &n, NULL)) {
6927 for (sent = 0; !stop && sent < n; sent += k) {
6928 if (mg_wait_until_ready(tp->s, 0) &&
6929 (k = send(tp->s, buf + sent, n - sent, 0)) <= 0)
6930 stop = 1;
6931 }
6932 }
6933 DBG(("%s", "EOF FROM CGI"));
6934 CloseHandle(tp->hPipe);
6935 shutdown(tp->s, 2); // Without this, IO thread may get truncated data
6936 closesocket(tp->s);
6937 MG_FREE(tp);
6938 _endthread();
6939 return NULL;
6940}
6941
6942static void mg_spawn_stdio_thread(sock_t sock, HANDLE hPipe,
6943 void *(*func)(void *)) {
6944 struct mg_threadparam *tp = (struct mg_threadparam *) MG_MALLOC(sizeof(*tp));
6945 if (tp != NULL) {
6946 tp->s = sock;
6947 tp->hPipe = hPipe;
6948 mg_start_thread(func, tp);
6949 }
6950}
6951
6952static void mg_abs_path(const char *utf8_path, char *abs_path, size_t len) {
6953 wchar_t buf[MAX_PATH_SIZE], buf2[MAX_PATH_SIZE];
6954 to_wchar(utf8_path, buf, ARRAY_SIZE(buf));
6956 WideCharToMultiByte(CP_UTF8, 0, buf2, wcslen(buf2) + 1, abs_path, len, 0, 0);
6957}
6958
6959static pid_t mg_start_process(const char *interp, const char *cmd,
6960 const char *env, const char *envp[],
6961 const char *dir, sock_t sock) {
6964 HANDLE a[2], b[2], me = GetCurrentProcess();
6969 FILE *fp;
6970
6971 memset(&si, 0, sizeof(si));
6972 memset(&pi, 0, sizeof(pi));
6973
6974 si.cb = sizeof(si);
6976 si.wShowWindow = SW_HIDE;
6977 si.hStdError = GetStdHandle(STD_ERROR_HANDLE);
6978
6979 CreatePipe(&a[0], &a[1], NULL, 0);
6980 CreatePipe(&b[0], &b[1], NULL, 0);
6981 DuplicateHandle(me, a[0], me, &si.hStdInput, 0, TRUE, flags);
6982 DuplicateHandle(me, b[1], me, &si.hStdOutput, 0, TRUE, flags);
6983
6984 if (interp == NULL && (fp = fopen(cmd, "r")) != NULL) {
6985 buf[0] = buf[1] = '\0';
6986 fgets(buf, sizeof(buf), fp);
6987 buf[sizeof(buf) - 1] = '\0';
6988 if (buf[0] == '#' && buf[1] == '!') {
6989 interp = buf + 2;
6990 /* Trim leading spaces: https://github.com/cesanta/mongoose/issues/489 */
6991 while (*interp != '\0' && isspace(*(unsigned char *) interp)) {
6992 interp++;
6993 }
6994 }
6995 fclose(fp);
6996 }
6997
6998 snprintf(buf, sizeof(buf), "%s/%s", dir, cmd);
7000
7003
7004 if (interp != NULL) {
7006 snprintf(cmdline, sizeof(cmdline), "%s \"%s\"", buf4, buf2);
7007 } else {
7008 snprintf(cmdline, sizeof(cmdline), "\"%s\"", buf2);
7009 }
7011
7013 (void *) env, full_dir, &si, &pi) != 0) {
7016 } else {
7017 CloseHandle(a[1]);
7018 CloseHandle(b[0]);
7019 closesocket(sock);
7020 }
7021 DBG(("CGI command: [%ls] -> %p", wcmd, pi.hProcess));
7022
7023 /* Not closing a[0] and b[1] because we've used DUPLICATE_CLOSE_SOURCE */
7024 CloseHandle(si.hStdOutput);
7025 CloseHandle(si.hStdInput);
7026 /* TODO(lsm): check if we need close process and thread handles too */
7027 /* CloseHandle(pi.hThread); */
7028 /* CloseHandle(pi.hProcess); */
7029
7030 return pi.hProcess;
7031}
7032#else
7033static pid_t mg_start_process(const char *interp, const char *cmd,
7034 const char *env, const char *envp[],
7035 const char *dir, sock_t sock) {
7036 char buf[500];
7037 pid_t pid = fork();
7038 (void) env;
7039
7040 if (pid == 0) {
7041 /*
7042 * In Linux `chdir` declared with `warn_unused_result` attribute
7043 * To shutup compiler we have yo use result in some way
7044 */
7045 int tmp = chdir(dir);
7046 (void) tmp;
7047 (void) dup2(sock, 0);
7048 (void) dup2(sock, 1);
7049 closesocket(sock);
7050
7051 /*
7052 * After exec, all signal handlers are restored to their default values,
7053 * with one exception of SIGCHLD. According to POSIX.1-2001 and Linux's
7054 * implementation, SIGCHLD's handler will leave unchanged after exec
7055 * if it was set to be ignored. Restore it to default action.
7056 */
7058
7059 if (interp == NULL) {
7060 execle(cmd, cmd, (char *) 0, envp); /* (char *) 0 to squash warning */
7061 } else {
7062 execle(interp, interp, cmd, (char *) 0, envp);
7063 }
7064 snprintf(buf, sizeof(buf),
7065 "Status: 500\r\n\r\n"
7066 "500 Server Error: %s%s%s: %s",
7067 interp == NULL ? "" : interp, interp == NULL ? "" : " ", cmd,
7068 strerror(errno));
7069 send(1, buf, strlen(buf), 0);
7070 exit(EXIT_FAILURE); /* exec call failed */
7071 }
7072
7073 return pid;
7074}
7075#endif /* _WIN32 */
7076
7077/*
7078 * Append VARIABLE=VALUE\0 string to the buffer, and add a respective
7079 * pointer into the vars array.
7080 */
7081static char *mg_addenv(struct mg_cgi_env_block *block, const char *fmt, ...) {
7082 int n, space;
7083 char *added = block->buf + block->len;
7084 va_list ap;
7085
7086 /* Calculate how much space is left in the buffer */
7087 space = sizeof(block->buf) - (block->len + 2);
7088 if (space > 0) {
7089 /* Copy VARIABLE=VALUE\0 string into the free space */
7090 va_start(ap, fmt);
7091 n = vsnprintf(added, (size_t) space, fmt, ap);
7092 va_end(ap);
7093
7094 /* Make sure we do not overflow buffer and the envp array */
7095 if (n > 0 && n + 1 < space &&
7096 block->nvars < (int) ARRAY_SIZE(block->vars) - 2) {
7097 /* Append a pointer to the added string into the envp array */
7098 block->vars[block->nvars++] = added;
7099 /* Bump up used length counter. Include \0 terminator */
7100 block->len += n + 1;
7101 }
7102 }
7103
7104 return added;
7105}
7106
7107static void mg_addenv2(struct mg_cgi_env_block *blk, const char *name) {
7108 const char *s;
7109 if ((s = getenv(name)) != NULL) mg_addenv(blk, "%s=%s", name, s);
7110}
7111
7113 const char *prog,
7114 const struct mg_str *path_info,
7115 const struct http_message *hm,
7116 const struct mg_serve_http_opts *opts,
7117 struct mg_cgi_env_block *blk) {
7118 const char *s;
7119 struct mg_str *h;
7120 char *p;
7121 size_t i;
7122
7123 blk->len = blk->nvars = 0;
7124 blk->nc = nc;
7125
7126 if ((s = getenv("SERVER_NAME")) != NULL) {
7127 mg_addenv(blk, "SERVER_NAME=%s", s);
7128 } else {
7129 char buf[100];
7130 mg_sock_to_str(nc->sock, buf, sizeof(buf), 3);
7131 mg_addenv(blk, "SERVER_NAME=%s", buf);
7132 }
7133 mg_addenv(blk, "SERVER_ROOT=%s", opts->document_root);
7134 mg_addenv(blk, "DOCUMENT_ROOT=%s", opts->document_root);
7135 mg_addenv(blk, "SERVER_SOFTWARE=%s/%s", "Mongoose", MG_VERSION);
7136
7137 /* Prepare the environment block */
7138 mg_addenv(blk, "%s", "GATEWAY_INTERFACE=CGI/1.1");
7139 mg_addenv(blk, "%s", "SERVER_PROTOCOL=HTTP/1.1");
7140 mg_addenv(blk, "%s", "REDIRECT_STATUS=200"); /* For PHP */
7141
7142 /* TODO(lsm): fix this for IPv6 case */
7143 /*addenv(blk, "SERVER_PORT=%d", ri->remote_port); */
7144
7145 mg_addenv(blk, "REQUEST_METHOD=%.*s", (int) hm->method.len, hm->method.p);
7146#if 0
7147 addenv(blk, "REMOTE_ADDR=%s", ri->remote_ip);
7148 addenv(blk, "REMOTE_PORT=%d", ri->remote_port);
7149#endif
7150 mg_addenv(blk, "REQUEST_URI=%.*s%s%.*s", (int) hm->uri.len, hm->uri.p,
7151 hm->query_string.len == 0 ? "" : "?", (int) hm->query_string.len,
7152 hm->query_string.p);
7153
7154 s = hm->uri.p + hm->uri.len - path_info->len - 1;
7155 if (*s == '/') {
7156 const char *base_name = strrchr(prog, DIRSEP);
7157 mg_addenv(blk, "SCRIPT_NAME=%.*s/%s", (int) (s - hm->uri.p), hm->uri.p,
7158 (base_name != NULL ? base_name + 1 : prog));
7159 } else {
7160 mg_addenv(blk, "SCRIPT_NAME=%.*s", (int) (s - hm->uri.p + 1), hm->uri.p);
7161 }
7162 mg_addenv(blk, "SCRIPT_FILENAME=%s", prog);
7163
7164 if (path_info != NULL && path_info->len > 0) {
7165 mg_addenv(blk, "PATH_INFO=%.*s", (int) path_info->len, path_info->p);
7166 /* Not really translated... */
7167 mg_addenv(blk, "PATH_TRANSLATED=%.*s", (int) path_info->len, path_info->p);
7168 }
7169
7170 mg_addenv(blk, "HTTPS=%s", nc->ssl != NULL ? "on" : "off");
7171
7172 if ((h = mg_get_http_header((struct http_message *) hm, "Content-Type")) !=
7173 NULL) {
7174 mg_addenv(blk, "CONTENT_TYPE=%.*s", (int) h->len, h->p);
7175 }
7176
7177 if (hm->query_string.len > 0) {
7178 mg_addenv(blk, "QUERY_STRING=%.*s", (int) hm->query_string.len,
7179 hm->query_string.p);
7180 }
7181
7182 if ((h = mg_get_http_header((struct http_message *) hm, "Content-Length")) !=
7183 NULL) {
7184 mg_addenv(blk, "CONTENT_LENGTH=%.*s", (int) h->len, h->p);
7185 }
7186
7187 mg_addenv2(blk, "PATH");
7188 mg_addenv2(blk, "TMP");
7189 mg_addenv2(blk, "TEMP");
7190 mg_addenv2(blk, "TMPDIR");
7191 mg_addenv2(blk, "PERLLIB");
7193
7194#if defined(_WIN32)
7195 mg_addenv2(blk, "COMSPEC");
7196 mg_addenv2(blk, "SYSTEMROOT");
7197 mg_addenv2(blk, "SystemDrive");
7198 mg_addenv2(blk, "ProgramFiles");
7199 mg_addenv2(blk, "ProgramFiles(x86)");
7200 mg_addenv2(blk, "CommonProgramFiles(x86)");
7201#else
7202 mg_addenv2(blk, "LD_LIBRARY_PATH");
7203#endif /* _WIN32 */
7204
7205 /* Add all headers as HTTP_* variables */
7206 for (i = 0; hm->header_names[i].len > 0; i++) {
7207 p = mg_addenv(blk, "HTTP_%.*s=%.*s", (int) hm->header_names[i].len,
7208 hm->header_names[i].p, (int) hm->header_values[i].len,
7209 hm->header_values[i].p);
7210
7211 /* Convert variable name into uppercase, and change - to _ */
7212 for (; *p != '=' && *p != '\0'; p++) {
7213 if (*p == '-') *p = '_';
7214 *p = (char) toupper(*(unsigned char *) p);
7215 }
7216 }
7217
7218 blk->vars[blk->nvars++] = NULL;
7219 blk->buf[blk->len++] = '\0';
7220}
7221
7222static void mg_cgi_ev_handler(struct mg_connection *cgi_nc, int ev,
7223 void *ev_data) {
7224 struct mg_connection *nc = (struct mg_connection *) cgi_nc->user_data;
7225 (void) ev_data;
7226
7227 if (nc == NULL) return;
7228
7229 switch (ev) {
7230 case MG_EV_RECV:
7231 /*
7232 * CGI script does not output reply line, like "HTTP/1.1 CODE XXXXX\n"
7233 * It outputs headers, then body. Headers might include "Status"
7234 * header, which changes CODE, and it might include "Location" header
7235 * which changes CODE to 302.
7236 *
7237 * Therefore we do not send the output from the CGI script to the user
7238 * until all CGI headers are received.
7239 *
7240 * Here we parse the output from the CGI script, and if all headers has
7241 * been received, send appropriate reply line, and forward all
7242 * received headers to the client.
7243 */
7244 if (nc->flags & MG_F_USER_1) {
7245 struct mbuf *io = &cgi_nc->recv_mbuf;
7246 int len = mg_http_get_request_len(io->buf, io->len);
7247
7248 if (len == 0) break;
7250 cgi_nc->flags |= MG_F_CLOSE_IMMEDIATELY;
7251 mg_http_send_error(nc, 500, "Bad headers");
7252 } else {
7253 struct http_message hm;
7254 struct mg_str *h;
7255 mg_http_parse_headers(io->buf, io->buf + io->len, io->len, &hm);
7256 if (mg_get_http_header(&hm, "Location") != NULL) {
7257 mg_printf(nc, "%s", "HTTP/1.1 302 Moved\r\n");
7258 } else if ((h = mg_get_http_header(&hm, "Status")) != NULL) {
7259 mg_printf(nc, "HTTP/1.1 %.*s\r\n", (int) h->len, h->p);
7260 } else {
7261 mg_printf(nc, "%s", "HTTP/1.1 200 OK\r\n");
7262 }
7263 }
7264 nc->flags &= ~MG_F_USER_1;
7265 }
7266 if (!(nc->flags & MG_F_USER_1)) {
7267 mg_forward(cgi_nc, nc);
7268 }
7269 break;
7270 case MG_EV_CLOSE:
7273 break;
7274 }
7275}
7276
7277static void mg_handle_cgi(struct mg_connection *nc, const char *prog,
7278 const struct mg_str *path_info,
7279 const struct http_message *hm,
7280 const struct mg_serve_http_opts *opts) {
7281 struct mg_cgi_env_block blk;
7282 char dir[MAX_PATH_SIZE];
7283 const char *p;
7284 sock_t fds[2];
7285
7286 DBG(("%p [%s]", nc, prog));
7287 mg_prepare_cgi_environment(nc, prog, path_info, hm, opts, &blk);
7288 /*
7289 * CGI must be executed in its own directory. 'dir' must point to the
7290 * directory containing executable program, 'p' must point to the
7291 * executable program name relative to 'dir'.
7292 */
7293 if ((p = strrchr(prog, DIRSEP)) == NULL) {
7294 snprintf(dir, sizeof(dir), "%s", ".");
7295 } else {
7296 snprintf(dir, sizeof(dir), "%.*s", (int) (p - prog), prog);
7297 prog = p + 1;
7298 }
7299
7300 /*
7301 * Try to create socketpair in a loop until success. mg_socketpair()
7302 * can be interrupted by a signal and fail.
7303 * TODO(lsm): use sigaction to restart interrupted syscall
7304 */
7305 do {
7307 } while (fds[0] == INVALID_SOCKET);
7308
7309 if (mg_start_process(opts->cgi_interpreter, prog, blk.buf, blk.vars, dir,
7310 fds[1]) != 0) {
7311 size_t n = nc->recv_mbuf.len - (hm->message.len - hm->body.len);
7312 struct mg_connection *cgi_nc =
7315 cgi_pd->cgi.cgi_nc = cgi_nc;
7316 cgi_pd->cgi.cgi_nc->user_data = nc;
7317 nc->flags |= MG_F_USER_1;
7318 /* Push POST data to the CGI */
7319 if (n > 0 && n < nc->recv_mbuf.len) {
7320 mg_send(cgi_pd->cgi.cgi_nc, hm->body.p, n);
7321 }
7323 } else {
7324 closesocket(fds[0]);
7325 mg_http_send_error(nc, 500, "CGI failure");
7326 }
7327
7328#ifndef _WIN32
7329 closesocket(fds[1]); /* On Windows, CGI stdio thread closes that socket */
7330#endif
7331}
7332#endif
7333
7334static int mg_get_month_index(const char *s) {
7335 static const char *month_names[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
7336 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
7337 size_t i;
7338
7339 for (i = 0; i < ARRAY_SIZE(month_names); i++)
7340 if (!strcmp(s, month_names[i])) return (int) i;
7341
7342 return -1;
7343}
7344
7345static int mg_num_leap_years(int year) {
7346 return year / 4 - year / 100 + year / 400;
7347}
7348
7349/* Parse UTC date-time string, and return the corresponding time_t value. */
7351 static const unsigned short days_before_month[] = {
7352 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};
7353 char month_str[32];
7355 time_t result = (time_t) 0;
7356
7357 if (((sscanf(datetime, "%d/%3s/%d %d:%d:%d", &day, month_str, &year, &hour,
7358 &minute, &second) == 6) ||
7359 (sscanf(datetime, "%d %3s %d %d:%d:%d", &day, month_str, &year, &hour,
7360 &minute, &second) == 6) ||
7361 (sscanf(datetime, "%*3s, %d %3s %d %d:%d:%d", &day, month_str, &year,
7362 &hour, &minute, &second) == 6) ||
7363 (sscanf(datetime, "%d-%3s-%d %d:%d:%d", &day, month_str, &year, &hour,
7364 &minute, &second) == 6)) &&
7365 year > 1970 && (month = mg_get_month_index(month_str)) != -1) {
7367 year -= 1970;
7368 days = year * 365 + days_before_month[month] + (day - 1) + leap_days;
7369 result = days * 24 * 3600 + hour * 3600 + minute * 60 + second;
7370 }
7371
7372 return result;
7373}
7374
7376 struct mg_str *hdr;
7377 if ((hdr = mg_get_http_header(hm, "If-None-Match")) != NULL) {
7378 char etag[64];
7380 return mg_vcasecmp(hdr, etag) == 0;
7381 } else if ((hdr = mg_get_http_header(hm, "If-Modified-Since")) != NULL) {
7382 return st->st_mtime <= mg_parse_date_string(hdr->p);
7383 } else {
7384 return 0;
7385 }
7386}
7387
7389 const char *domain) {
7390 mg_printf(c,
7391 "HTTP/1.1 401 Unauthorized\r\n"
7392 "WWW-Authenticate: Digest qop=\"auth\", "
7393 "realm=\"%s\", nonce=\"%lu\"\r\n"
7394 "Content-Length: 0\r\n\r\n",
7395 domain, (unsigned long) time(NULL));
7396}
7397
7398static void mg_http_send_options(struct mg_connection *nc) {
7399 mg_printf(nc, "%s",
7400 "HTTP/1.1 200 OK\r\nAllow: GET, POST, HEAD, CONNECT, OPTIONS"
7402 ", MKCOL, PUT, DELETE, PROPFIND, MOVE\r\nDAV: 1,2"
7403#endif
7404 "\r\n\r\n");
7406}
7407
7408static int mg_is_creation_request(const struct http_message *hm) {
7409 return mg_vcmp(&hm->method, "MKCOL") == 0 || mg_vcmp(&hm->method, "PUT") == 0;
7410}
7411
7412MG_INTERNAL void mg_send_http_file(struct mg_connection *nc, char *path,
7413 const struct mg_str *path_info,
7414 struct http_message *hm,
7415 struct mg_serve_http_opts *opts) {
7416 int exists, is_directory, is_dav = mg_is_dav_request(&hm->method);
7417 int is_cgi;
7418 char *index_file = NULL;
7419 cs_stat_t st;
7420
7421 exists = (mg_stat(path, &st) == 0);
7422 is_directory = exists && S_ISDIR(st.st_mode);
7423
7424 if (is_directory)
7425 mg_find_index_file(path, opts->index_files, &index_file, &st);
7426
7427 is_cgi =
7428 (mg_match_prefix(opts->cgi_file_pattern, strlen(opts->cgi_file_pattern),
7429 index_file ? index_file : path) > 0);
7430
7431 DBG(("%p %.*s [%s] exists=%d is_dir=%d is_dav=%d is_cgi=%d index=%s", nc,
7432 (int) hm->method.len, hm->method.p, path, exists, is_directory, is_dav,
7433 is_cgi, index_file ? index_file : ""));
7434
7435 if (is_directory && hm->uri.p[hm->uri.len - 1] != '/' && !is_dav) {
7436 mg_printf(nc,
7437 "HTTP/1.1 301 Moved\r\nLocation: %.*s/\r\n"
7438 "Content-Length: 0\r\n\r\n",
7439 (int) hm->uri.len, hm->uri.p);
7441 return;
7442 }
7443
7444 /* If we have path_info, the only way to handle it is CGI. */
7445 if (path_info->len > 0 && !is_cgi) {
7446 mg_http_send_error(nc, 501, NULL);
7448 return;
7449 }
7450
7451 if (is_dav && opts->dav_document_root == NULL) {
7452 mg_http_send_error(nc, 501, NULL);
7453 } else if (!mg_is_authorized(hm, path, is_directory, opts->auth_domain,
7454 opts->global_auth_file, 1) ||
7455 !mg_is_authorized(hm, path, is_directory, opts->auth_domain,
7456 opts->per_directory_auth_file, 0)) {
7457 mg_http_send_digest_auth_request(nc, opts->auth_domain);
7458 } else if (is_cgi) {
7459#if !defined(MG_DISABLE_CGI)
7460 mg_handle_cgi(nc, index_file ? index_file : path, path_info, hm, opts);
7461#else
7462 mg_http_send_error(nc, 501, NULL);
7463#endif /* MG_DISABLE_CGI */
7464 } else if ((!exists ||
7465 mg_is_file_hidden(path, opts, 0 /* specials are ok */)) &&
7467 mg_http_send_error(nc, 404, NULL);
7468#ifndef MG_DISABLE_DAV
7469 } else if (!mg_vcmp(&hm->method, "PROPFIND")) {
7470 mg_handle_propfind(nc, path, &st, hm, opts);
7471#ifndef MG_DISABLE_DAV_AUTH
7472 } else if (is_dav &&
7473 (opts->dav_auth_file == NULL ||
7474 (strcmp(opts->dav_auth_file, "-") != 0 &&
7475 !mg_is_authorized(hm, path, is_directory, opts->auth_domain,
7476 opts->dav_auth_file, 1)))) {
7477 mg_http_send_digest_auth_request(nc, opts->auth_domain);
7478#endif
7479 } else if (!mg_vcmp(&hm->method, "MKCOL")) {
7480 mg_handle_mkcol(nc, path, hm);
7481 } else if (!mg_vcmp(&hm->method, "DELETE")) {
7482 mg_handle_delete(nc, opts, path);
7483 } else if (!mg_vcmp(&hm->method, "PUT")) {
7484 mg_handle_put(nc, path, hm);
7485 } else if (!mg_vcmp(&hm->method, "MOVE")) {
7486 mg_handle_move(nc, opts, path, hm);
7487#ifdef MG_ENABLE_FAKE_DAVLOCK
7488 } else if (!mg_vcmp(&hm->method, "LOCK")) {
7489 mg_handle_lock(nc, path);
7490#endif
7491#endif
7492 } else if (!mg_vcmp(&hm->method, "OPTIONS")) {
7494 } else if (is_directory && index_file == NULL) {
7495#ifndef MG_DISABLE_DIRECTORY_LISTING
7496 if (strcmp(opts->enable_directory_listing, "yes") == 0) {
7497 mg_send_directory_listing(nc, path, hm, opts);
7498 } else {
7499 mg_http_send_error(nc, 403, NULL);
7500 }
7501#else
7502 mg_http_send_error(nc, 501, NULL);
7503#endif
7504 } else if (mg_is_not_modified(hm, &st)) {
7505 mg_http_send_error(nc, 304, "Not Modified");
7506 } else {
7508 }
7510}
7511
7513 struct mg_serve_http_opts opts) {
7514 char *path = NULL;
7515 struct mg_str *hdr, path_info;
7516 uint32_t remote_ip = ntohl(*(uint32_t *) &nc->sa.sin.sin_addr);
7517
7518 if (mg_check_ip_acl(opts.ip_acl, remote_ip) != 1) {
7519 /* Not allowed to connect */
7520 mg_http_send_error(nc, 403, NULL);
7522 return;
7523 }
7524
7526 return;
7527 }
7528
7529 if (opts.document_root == NULL) {
7530 opts.document_root = ".";
7531 }
7532 if (opts.per_directory_auth_file == NULL) {
7533 opts.per_directory_auth_file = ".htpasswd";
7534 }
7535 if (opts.enable_directory_listing == NULL) {
7536 opts.enable_directory_listing = "yes";
7537 }
7538 if (opts.cgi_file_pattern == NULL) {
7539 opts.cgi_file_pattern = "**.cgi$|**.php$";
7540 }
7541 if (opts.ssi_pattern == NULL) {
7542 opts.ssi_pattern = "**.shtml$|**.shtm$";
7543 }
7544 if (opts.index_files == NULL) {
7545 opts.index_files = "index.html,index.htm,index.shtml,index.cgi,index.php";
7546 }
7547 /* Normalize path - resolve "." and ".." (in-place). */
7548 if (!mg_normalize_uri_path(&hm->uri, &hm->uri)) {
7549 mg_http_send_error(nc, 400, NULL);
7550 return;
7551 }
7552 if (mg_uri_to_local_path(hm, &opts, &path, &path_info) == 0) {
7553 mg_http_send_error(nc, 404, NULL);
7554 return;
7555 }
7556 mg_send_http_file(nc, path, &path_info, hm, &opts);
7557
7558 MG_FREE(path);
7559 path = NULL;
7560
7561 /* Close connection for non-keep-alive requests */
7562 if (mg_vcmp(&hm->proto, "HTTP/1.1") != 0 ||
7563 ((hdr = mg_get_http_header(hm, "Connection")) != NULL &&
7564 mg_vcmp(hdr, "keep-alive") != 0)) {
7565#if 0
7567#endif
7568 }
7569}
7570
7571#endif /* MG_DISABLE_FILESYSTEM */
7572
7573/* returns 0 on success, -1 on error */
7574static int mg_http_common_url_parse(const char *url, const char *schema,
7575 const char *schema_tls, int *use_ssl,
7576 char **addr, int *port_i,
7577 const char **path) {
7578 int addr_len = 0;
7579
7580 if (memcmp(url, schema, strlen(schema)) == 0) {
7581 url += strlen(schema);
7582 } else if (memcmp(url, schema_tls, strlen(schema_tls)) == 0) {
7583 url += strlen(schema_tls);
7584 *use_ssl = 1;
7585#ifndef MG_ENABLE_SSL
7586 return -1; /* SSL is not enabled, cannot do HTTPS URLs */
7587#endif
7588 }
7589
7590 while (*url != '\0') {
7591 *addr = (char *) MG_REALLOC(*addr, addr_len + 5 /* space for port too. */);
7592 if (*addr == NULL) {
7593 DBG(("OOM"));
7594 return -1;
7595 }
7596 if (*url == '/') {
7597 break;
7598 }
7599 if (*url == ':') *port_i = addr_len;
7600 (*addr)[addr_len++] = *url;
7601 (*addr)[addr_len] = '\0';
7602 url++;
7603 }
7604 if (addr_len == 0) goto cleanup;
7605 if (*port_i < 0) {
7606 *port_i = addr_len;
7607 strcpy(*addr + *port_i, *use_ssl ? ":443" : ":80");
7608 } else {
7609 *port_i = -1;
7610 }
7611
7612 if (*path == NULL) *path = url;
7613
7614 if (**path == '\0') *path = "/";
7615
7616 DBG(("%s %s", *addr, *path));
7617
7618 return 0;
7619
7620cleanup:
7621 MG_FREE(*addr);
7622 return -1;
7623}
7624
7627 struct mg_connect_opts opts, const char *schema, const char *schema_ssl,
7628 const char *url, const char **path, char **addr) {
7629 struct mg_connection *nc = NULL;
7630 int port_i = -1;
7631 int use_ssl = 0;
7632
7634 path) < 0) {
7635 return NULL;
7636 }
7637
7638#ifndef MG_ENABLE_SSL
7639 if (use_ssl) {
7640 MG_SET_PTRPTR(opts.error_string, "ssl is disabled");
7641 MG_FREE(addr);
7642 return NULL;
7643 }
7644#endif
7645
7646 if ((nc = mg_connect_opt(mgr, *addr, ev_handler, opts)) != NULL) {
7647#ifdef MG_ENABLE_SSL
7648 if (use_ssl && nc->ssl_ctx == NULL) {
7649 /*
7650 * Schema requires SSL, but no SSL parameters were provided in
7651 * opts. In order to maintain backward compatibility, use
7652 * NULL, NULL
7653 */
7654 mg_set_ssl(nc, NULL, NULL);
7655 }
7656#endif
7658
7659 /* If the port was addred by us, restore the original host. */
7660 if (port_i >= 0) (*addr)[port_i] = '\0';
7661 }
7662
7663 return nc;
7664}
7665
7668 struct mg_connect_opts opts,
7669 const char *url,
7670 const char *extra_headers,
7671 const char *post_data) {
7672 char *addr = NULL;
7673 const char *path = NULL;
7675 mgr, ev_handler, opts, "http://", "https://", url, &path, &addr);
7676
7677 if (nc == NULL) {
7678 return NULL;
7679 }
7680
7681 mg_printf(nc, "%s %s HTTP/1.1\r\nHost: %s\r\nContent-Length: %" SIZE_T_FMT
7682 "\r\n%s\r\n%s",
7683 post_data == NULL ? "GET" : "POST", path, addr,
7684 post_data == NULL ? 0 : strlen(post_data),
7685 extra_headers == NULL ? "" : extra_headers,
7686 post_data == NULL ? "" : post_data);
7687
7688 MG_FREE(addr);
7689 return nc;
7690}
7691
7694 const char *url,
7695 const char *extra_headers,
7696 const char *post_data) {
7697 struct mg_connect_opts opts;
7698 memset(&opts, 0, sizeof(opts));
7699 return mg_connect_http_opt(mgr, ev_handler, opts, url, extra_headers,
7700 post_data);
7701}
7702
7705 struct mg_connect_opts opts,
7706 const char *url, const char *protocol,
7707 const char *extra_headers) {
7708 char *addr = NULL;
7709 const char *path = NULL;
7711 mgr, ev_handler, opts, "ws://", "wss://", url, &path, &addr);
7712
7713 if (nc == NULL) {
7714 return NULL;
7715 }
7716
7717 mg_send_websocket_handshake2(nc, path, addr, protocol, extra_headers);
7718
7719 MG_FREE(addr);
7720 return nc;
7721}
7722
7725 const char *url, const char *protocol,
7726 const char *extra_headers) {
7727 struct mg_connect_opts opts;
7728 memset(&opts, 0, sizeof(opts));
7729 return mg_connect_ws_opt(mgr, ev_handler, opts, url, protocol, extra_headers);
7730}
7731
7732size_t mg_parse_multipart(const char *buf, size_t buf_len, char *var_name,
7733 size_t var_name_len, char *file_name,
7734 size_t file_name_len, const char **data,
7735 size_t *data_len) {
7736 static const char cd[] = "Content-Disposition: ";
7737 size_t hl, bl, n, ll, pos, cdl = sizeof(cd) - 1;
7738
7739 if (buf == NULL || buf_len <= 0) return 0;
7740 if ((hl = mg_http_get_request_len(buf, buf_len)) <= 0) return 0;
7741 if (buf[0] != '-' || buf[1] != '-' || buf[2] == '\n') return 0;
7742
7743 /* Get boundary length */
7744 bl = mg_get_line_len(buf, buf_len);
7745
7746 /* Loop through headers, fetch variable name and file name */
7747 var_name[0] = file_name[0] = '\0';
7748 for (n = bl; (ll = mg_get_line_len(buf + n, hl - n)) > 0; n += ll) {
7749 if (mg_ncasecmp(cd, buf + n, cdl) == 0) {
7750 struct mg_str header;
7751 header.p = buf + n + cdl;
7752 header.len = ll - (cdl + 2);
7753 mg_http_parse_header(&header, "name", var_name, var_name_len);
7754 mg_http_parse_header(&header, "filename", file_name, file_name_len);
7755 }
7756 }
7757
7758 /* Scan through the body, search for terminating boundary */
7759 for (pos = hl; pos + (bl - 2) < buf_len; pos++) {
7760 if (buf[pos] == '-' && !memcmp(buf, &buf[pos], bl - 2)) {
7761 if (data_len != NULL) *data_len = (pos - 2) - hl;
7762 if (data != NULL) *data = buf + hl;
7763 return pos;
7764 }
7765 }
7766
7767 return 0;
7768}
7769
7771 mg_event_handler_t handler) {
7773 struct mg_http_endpoint *new_ep =
7774 (struct mg_http_endpoint *) calloc(1, sizeof(*new_ep));
7776 new_ep->name_len = strlen(new_ep->name);
7777 new_ep->handler = handler;
7778 new_ep->next = pd->endpoints;
7779 pd->endpoints = new_ep;
7780}
7781
7782#endif /* MG_DISABLE_HTTP */
7783#ifdef MG_MODULE_LINES
7784#line 1 "./src/util.c"
7785#endif
7786/*
7787 * Copyright (c) 2014 Cesanta Software Limited
7788 * All rights reserved
7789 */
7790
7791/* Amalgamated: #include "common/base64.h" */
7792/* Amalgamated: #include "mongoose/src/internal.h" */
7793/* Amalgamated: #include "mongoose/src/util.h" */
7794
7795const char *mg_skip(const char *s, const char *end, const char *delims,
7796 struct mg_str *v) {
7797 v->p = s;
7798 while (s < end && strchr(delims, *(unsigned char *) s) == NULL) s++;
7799 v->len = s - v->p;
7800 while (s < end && strchr(delims, *(unsigned char *) s) != NULL) s++;
7801 return s;
7802}
7803
7804static int lowercase(const char *s) {
7805 return tolower(*(const unsigned char *) s);
7806}
7807
7808int mg_ncasecmp(const char *s1, const char *s2, size_t len) {
7809 int diff = 0;
7810
7811 if (len > 0) do {
7812 diff = lowercase(s1++) - lowercase(s2++);
7813 } while (diff == 0 && s1[-1] != '\0' && --len > 0);
7814
7815 return diff;
7816}
7817
7818int mg_casecmp(const char *s1, const char *s2) {
7819 return mg_ncasecmp(s1, s2, (size_t) ~0);
7820}
7821
7822int mg_vcasecmp(const struct mg_str *str1, const char *str2) {
7823 size_t n2 = strlen(str2), n1 = str1->len;
7824 int r = mg_ncasecmp(str1->p, str2, (n1 < n2) ? n1 : n2);
7825 if (r == 0) {
7826 return n1 - n2;
7827 }
7828 return r;
7829}
7830
7831int mg_vcmp(const struct mg_str *str1, const char *str2) {
7832 size_t n2 = strlen(str2), n1 = str1->len;
7833 int r = memcmp(str1->p, str2, (n1 < n2) ? n1 : n2);
7834 if (r == 0) {
7835 return n1 - n2;
7836 }
7837 return r;
7838}
7839
7840#ifndef MG_DISABLE_FILESYSTEM
7841int mg_stat(const char *path, cs_stat_t *st) {
7842#ifdef _WIN32
7843 wchar_t wpath[MAX_PATH_SIZE];
7844 to_wchar(path, wpath, ARRAY_SIZE(wpath));
7845 DBG(("[%ls] -> %d", wpath, _wstati64(wpath, st)));
7846 return _wstati64(wpath, (struct _stati64 *) st);
7847#else
7848 return stat(path, st);
7849#endif
7850}
7851
7852FILE *mg_fopen(const char *path, const char *mode) {
7853#ifdef _WIN32
7854 wchar_t wpath[MAX_PATH_SIZE], wmode[10];
7855 to_wchar(path, wpath, ARRAY_SIZE(wpath));
7857 return _wfopen(wpath, wmode);
7858#else
7859 return fopen(path, mode);
7860#endif
7861}
7862
7863int mg_open(const char *path, int flag, int mode) { /* LCOV_EXCL_LINE */
7864#ifdef _WIN32
7865 wchar_t wpath[MAX_PATH_SIZE];
7866 to_wchar(path, wpath, ARRAY_SIZE(wpath));
7867 return _wopen(wpath, flag, mode);
7868#else
7869 return open(path, flag, mode); /* LCOV_EXCL_LINE */
7870#endif
7871}
7872#endif
7873
7874void mg_base64_encode(const unsigned char *src, int src_len, char *dst) {
7875 cs_base64_encode(src, src_len, dst);
7876}
7877
7878int mg_base64_decode(const unsigned char *s, int len, char *dst) {
7879 return cs_base64_decode(s, len, dst);
7880}
7881
7882#ifdef MG_ENABLE_THREADS
7883void *mg_start_thread(void *(*f)(void *), void *p) {
7884#ifdef _WIN32
7885 return (void *) _beginthread((void(__cdecl *) (void *) ) f, 0, p);
7886#else
7887 pthread_t thread_id = (pthread_t) 0;
7889
7892
7893#if defined(MG_STACK_SIZE) && MG_STACK_SIZE > 1
7895#endif
7896
7897 pthread_create(&thread_id, &attr, f, p);
7899
7900 return (void *) thread_id;
7901#endif
7902}
7903#endif /* MG_ENABLE_THREADS */
7904
7905/* Set close-on-exec bit for a given socket. */
7907#ifdef _WIN32
7909#elif defined(__unix__)
7910 fcntl(sock, F_SETFD, FD_CLOEXEC);
7911#else
7912 (void) sock;
7913#endif
7914}
7915
7916void mg_sock_addr_to_str(const union socket_address *sa, char *buf, size_t len,
7917 int flags) {
7918 int is_v6;
7919 if (buf == NULL || len <= 0) return;
7920 buf[0] = '\0';
7921#if defined(MG_ENABLE_IPV6)
7922 is_v6 = sa->sa.sa_family == AF_INET6;
7923#else
7924 is_v6 = 0;
7925#endif
7926 if (flags & MG_SOCK_STRINGIFY_IP) {
7927#if defined(MG_ENABLE_IPV6)
7928 const void *addr = NULL;
7929 char *start = buf;
7930 socklen_t capacity = len;
7931 if (!is_v6) {
7932 addr = &sa->sin.sin_addr;
7933 } else {
7934 addr = (void *) &sa->sin6.sin6_addr;
7935 if (flags & MG_SOCK_STRINGIFY_PORT) {
7936 *buf = '[';
7937 start++;
7938 capacity--;
7939 }
7940 }
7941 if (inet_ntop(sa->sa.sa_family, addr, start, capacity) == NULL) {
7942 *buf = '\0';
7943 }
7944#elif defined(_WIN32) || defined(MG_LWIP)
7945 /* Only Windoze Vista (and newer) have inet_ntop() */
7946 strncpy(buf, inet_ntoa(sa->sin.sin_addr), len);
7947#else
7948 inet_ntop(AF_INET, (void *) &sa->sin.sin_addr, buf, len);
7949#endif
7950 }
7951 if (flags & MG_SOCK_STRINGIFY_PORT) {
7952 int port = ntohs(sa->sin.sin_port);
7953 if (flags & MG_SOCK_STRINGIFY_IP) {
7954 snprintf(buf + strlen(buf), len - (strlen(buf) + 1), "%s:%d",
7955 (is_v6 ? "]" : ""), port);
7956 } else {
7957 snprintf(buf, len, "%d", port);
7958 }
7959 }
7960}
7961
7962void mg_conn_addr_to_str(struct mg_connection *nc, char *buf, size_t len,
7963 int flags) {
7964 union socket_address sa;
7965 memset(&sa, 0, sizeof(sa));
7967 mg_sock_addr_to_str(&sa, buf, len, flags);
7968}
7969
7970#ifndef MG_DISABLE_HEXDUMP
7971int mg_hexdump(const void *buf, int len, char *dst, int dst_len) {
7972 const unsigned char *p = (const unsigned char *) buf;
7973 char ascii[17] = "";
7974 int i, idx, n = 0;
7975
7976 for (i = 0; i < len; i++) {
7977 idx = i % 16;
7978 if (idx == 0) {
7979 if (i > 0) n += snprintf(dst + n, dst_len - n, " %s\n", ascii);
7980 n += snprintf(dst + n, dst_len - n, "%04x ", i);
7981 }
7982 n += snprintf(dst + n, dst_len - n, " %02x", p[i]);
7983 ascii[idx] = p[i] < 0x20 || p[i] > 0x7e ? '.' : p[i];
7984 ascii[idx + 1] = '\0';
7985 }
7986
7987 while (i++ % 16) n += snprintf(dst + n, dst_len - n, "%s", " ");
7988 n += snprintf(dst + n, dst_len - n, " %s\n\n", ascii);
7989
7990 return n;
7991}
7992#endif
7993
7994int mg_avprintf(char **buf, size_t size, const char *fmt, va_list ap) {
7996 int len;
7997
7998 va_copy(ap_copy, ap);
7999 len = vsnprintf(*buf, size, fmt, ap_copy);
8000 va_end(ap_copy);
8001
8002 if (len < 0) {
8003 /* eCos and Windows are not standard-compliant and return -1 when
8004 * the buffer is too small. Keep allocating larger buffers until we
8005 * succeed or out of memory. */
8006 *buf = NULL; /* LCOV_EXCL_START */
8007 while (len < 0) {
8008 MG_FREE(*buf);
8009 size *= 2;
8010 if ((*buf = (char *) MG_MALLOC(size)) == NULL) break;
8011 va_copy(ap_copy, ap);
8012 len = vsnprintf(*buf, size, fmt, ap_copy);
8013 va_end(ap_copy);
8014 }
8015 /* LCOV_EXCL_STOP */
8016 } else if (len >= (int) size) {
8017 /* Standard-compliant code path. Allocate a buffer that is large enough. */
8018 if ((*buf = (char *) MG_MALLOC(len + 1)) == NULL) {
8019 len = -1; /* LCOV_EXCL_LINE */
8020 } else { /* LCOV_EXCL_LINE */
8021 va_copy(ap_copy, ap);
8022 len = vsnprintf(*buf, len + 1, fmt, ap_copy);
8023 va_end(ap_copy);
8024 }
8025 }
8026
8027 return len;
8028}
8029
8030#if !defined(MG_DISABLE_HEXDUMP)
8031void mg_hexdump_connection(struct mg_connection *nc, const char *path,
8032 const void *buf, int num_bytes, int ev) {
8033#if !defined(NO_LIBC) && !defined(MG_DISABLE_STDIO)
8034 FILE *fp = NULL;
8035 char *hexbuf, src[60], dst[60];
8036 int buf_size = num_bytes * 5 + 100;
8037
8038 if (strcmp(path, "-") == 0) {
8039 fp = stdout;
8040 } else if (strcmp(path, "--") == 0) {
8041 fp = stderr;
8042#ifndef MG_DISABLE_FILESYSTEM
8043 } else {
8044 fp = fopen(path, "a");
8045#endif
8046 }
8047 if (fp == NULL) return;
8048
8049 mg_conn_addr_to_str(nc, src, sizeof(src),
8051 mg_conn_addr_to_str(nc, dst, sizeof(dst), MG_SOCK_STRINGIFY_IP |
8054 fprintf(
8055 fp, "%lu %p %s %s %s %d\n", (unsigned long) time(NULL), (void *) nc, src,
8056 ev == MG_EV_RECV ? "<-" : ev == MG_EV_SEND
8057 ? "->"
8058 : ev == MG_EV_ACCEPT
8059 ? "<A"
8060 : ev == MG_EV_CONNECT ? "C>" : "XX",
8061 dst, num_bytes);
8062 if (num_bytes > 0 && (hexbuf = (char *) MG_MALLOC(buf_size)) != NULL) {
8063 mg_hexdump(buf, num_bytes, hexbuf, buf_size);
8064 fprintf(fp, "%s", hexbuf);
8065 MG_FREE(hexbuf);
8066 }
8067 if (fp != stdin && fp != stdout) fclose(fp);
8068#endif
8069}
8070#endif
8071
8073 static const int n = 1;
8074 /* TODO(mkm) use compiletime check with 4-byte char literal */
8075 return ((char *) &n)[0] == 0;
8076}
8077
8078const char *mg_next_comma_list_entry(const char *list, struct mg_str *val,
8079 struct mg_str *eq_val) {
8080 if (list == NULL || *list == '\0') {
8081 /* End of the list */
8082 list = NULL;
8083 } else {
8084 val->p = list;
8085 if ((list = strchr(val->p, ',')) != NULL) {
8086 /* Comma found. Store length and shift the list ptr */
8087 val->len = list - val->p;
8088 list++;
8089 } else {
8090 /* This value is the last one */
8091 list = val->p + strlen(val->p);
8092 val->len = list - val->p;
8093 }
8094
8095 if (eq_val != NULL) {
8096 /* Value has form "x=y", adjust pointers and lengths */
8097 /* so that val points to "x", and eq_val points to "y". */
8098 eq_val->len = 0;
8099 eq_val->p = (const char *) memchr(val->p, '=', val->len);
8100 if (eq_val->p != NULL) {
8101 eq_val->p++; /* Skip over '=' character */
8102 eq_val->len = val->p + val->len - eq_val->p;
8103 val->len = (eq_val->p - val->p) - 1;
8104 }
8105 }
8106 }
8107
8108 return list;
8109}
8110
8111int mg_match_prefix_n(const struct mg_str pattern, const struct mg_str str) {
8112 const char *or_str;
8113 size_t len, i = 0, j = 0;
8114 int res;
8115
8116 if ((or_str = (const char *) memchr(pattern.p, '|', pattern.len)) != NULL) {
8117 struct mg_str pstr = {pattern.p, (size_t)(or_str - pattern.p)};
8119 if (res > 0) return res;
8120 pstr.p = or_str + 1;
8121 pstr.len = (pattern.p + pattern.len) - (or_str + 1);
8122 return mg_match_prefix_n(pstr, str);
8123 }
8124
8125 for (; i < pattern.len; i++, j++) {
8126 if (pattern.p[i] == '?' && j != str.len) {
8127 continue;
8128 } else if (pattern.p[i] == '$') {
8129 return j == str.len ? (int) j : -1;
8130 } else if (pattern.p[i] == '*') {
8131 i++;
8132 if (pattern.p[i] == '*') {
8133 i++;
8134 len = str.len - j;
8135 } else {
8136 len = 0;
8137 while (j + len != str.len && str.p[len] != '/') {
8138 len++;
8139 }
8140 }
8141 if (i == pattern.len) {
8142 return j + len;
8143 }
8144 do {
8145 const struct mg_str pstr = {pattern.p + i, pattern.len - i};
8146 const struct mg_str sstr = {str.p + j + len, str.len - j - len};
8148 } while (res == -1 && len-- > 0);
8149 return res == -1 ? -1 : (int) (j + res + len);
8150 } else if (lowercase(&pattern.p[i]) != lowercase(&str.p[j])) {
8151 return -1;
8152 }
8153 }
8154 return j;
8155}
8156
8157int mg_match_prefix(const char *pattern, int pattern_len, const char *str) {
8158 const struct mg_str pstr = {pattern, (size_t) pattern_len};
8160}
8161
8163 struct mg_str ret = {s, 0};
8164 if (s != NULL) ret.len = strlen(s);
8165 return ret;
8166}
8167#ifdef MG_MODULE_LINES
8168#line 1 "./src/json-rpc.c"
8169#endif
8170/* Copyright (c) 2014 Cesanta Software Limited */
8171/* All rights reserved */
8172
8173#ifndef MG_DISABLE_JSON_RPC
8174
8175/* Amalgamated: #include "mongoose/src/internal.h" */
8176/* Amalgamated: #include "mongoose/src/json-rpc.h" */
8177/* Amalgamated: #include "mongoose/deps/frozen/frozen.h" */
8178
8179int mg_rpc_create_reply(char *buf, int len, const struct mg_rpc_request *req,
8180 const char *result_fmt, ...) {
8181 static const struct json_token null_tok = {"null", 4, 0, JSON_TYPE_NULL};
8182 const struct json_token *id = req->id == NULL ? &null_tok : req->id;
8183 va_list ap;
8184 int n = 0;
8185
8186 n += json_emit(buf + n, len - n, "{s:s,s:", "jsonrpc", "2.0", "id");
8187 if (id->type == JSON_TYPE_STRING) {
8188 n += json_emit_quoted_str(buf + n, len - n, id->ptr, id->len);
8189 } else {
8190 n += json_emit_unquoted_str(buf + n, len - n, id->ptr, id->len);
8191 }
8192 n += json_emit(buf + n, len - n, ",s:", "result");
8193
8194 va_start(ap, result_fmt);
8195 n += json_emit_va(buf + n, len - n, result_fmt, ap);
8196 va_end(ap);
8197
8198 n += json_emit(buf + n, len - n, "}");
8199
8200 return n;
8201}
8202
8203int mg_rpc_create_request(char *buf, int len, const char *method,
8204 const char *id, const char *params_fmt, ...) {
8205 va_list ap;
8206 int n = 0;
8207
8208 n += json_emit(buf + n, len - n, "{s:s,s:s,s:s,s:", "jsonrpc", "2.0", "id",
8209 id, "method", method, "params");
8210 va_start(ap, params_fmt);
8211 n += json_emit_va(buf + n, len - n, params_fmt, ap);
8212 va_end(ap);
8213
8214 n += json_emit(buf + n, len - n, "}");
8215
8216 return n;
8217}
8218
8219int mg_rpc_create_error(char *buf, int len, struct mg_rpc_request *req,
8220 int code, const char *message, const char *fmt, ...) {
8221 va_list ap;
8222 int n = 0;
8223
8224 n += json_emit(buf + n, len - n, "{s:s,s:V,s:{s:i,s:s,s:", "jsonrpc", "2.0",
8225 "id", req->id == NULL ? "null" : req->id->ptr,
8226 req->id == NULL ? 4 : req->id->len, "error", "code",
8227 (long) code, "message", message, "data");
8228 va_start(ap, fmt);
8229 n += json_emit_va(buf + n, len - n, fmt, ap);
8230 va_end(ap);
8231
8232 n += json_emit(buf + n, len - n, "}}");
8233
8234 return n;
8235}
8236
8237int mg_rpc_create_std_error(char *buf, int len, struct mg_rpc_request *req,
8238 int code) {
8239 const char *message = NULL;
8240
8241 switch (code) {
8243 message = "parse error";
8244 break;
8246 message = "invalid request";
8247 break;
8249 message = "method not found";
8250 break;
8252 message = "invalid parameters";
8253 break;
8255 message = "server error";
8256 break;
8257 default:
8258 message = "unspecified error";
8259 break;
8260 }
8261
8262 return mg_rpc_create_error(buf, len, req, code, message, "N");
8263}
8264
8265int mg_rpc_dispatch(const char *buf, int len, char *dst, int dst_len,
8266 const char **methods, mg_rpc_handler_t *handlers) {
8267 struct json_token tokens[200];
8268 struct mg_rpc_request req;
8269 int i, n;
8270
8271 memset(&req, 0, sizeof(req));
8272 n = parse_json(buf, len, tokens, sizeof(tokens) / sizeof(tokens[0]));
8273 if (n <= 0) {
8276 return mg_rpc_create_std_error(dst, dst_len, &req, err_code);
8277 }
8278
8279 req.message = tokens;
8280 req.id = find_json_token(tokens, "id");
8281 req.method = find_json_token(tokens, "method");
8282 req.params = find_json_token(tokens, "params");
8283
8284 if (req.id == NULL || req.method == NULL) {
8285 return mg_rpc_create_std_error(dst, dst_len, &req,
8287 }
8288
8289 for (i = 0; methods[i] != NULL; i++) {
8290 int mlen = strlen(methods[i]);
8291 if (mlen == req.method->len &&
8292 memcmp(methods[i], req.method->ptr, mlen) == 0)
8293 break;
8294 }
8295
8296 if (methods[i] == NULL) {
8297 return mg_rpc_create_std_error(dst, dst_len, &req,
8299 }
8300
8301 return handlers[i](dst, dst_len, &req);
8302}
8303
8304int mg_rpc_parse_reply(const char *buf, int len, struct json_token *toks,
8305 int max_toks, struct mg_rpc_reply *rep,
8306 struct mg_rpc_error *er) {
8307 int n = parse_json(buf, len, toks, max_toks);
8308
8309 memset(rep, 0, sizeof(*rep));
8310 memset(er, 0, sizeof(*er));
8311
8312 if (n > 0) {
8313 if ((rep->result = find_json_token(toks, "result")) != NULL) {
8314 rep->message = toks;
8315 rep->id = find_json_token(toks, "id");
8316 } else {
8317 er->message = toks;
8318 er->id = find_json_token(toks, "id");
8319 er->error_code = find_json_token(toks, "error.code");
8320 er->error_message = find_json_token(toks, "error.message");
8321 er->error_data = find_json_token(toks, "error.data");
8322 }
8323 }
8324 return n;
8325}
8326
8327#endif /* MG_DISABLE_JSON_RPC */
8328#ifdef MG_MODULE_LINES
8329#line 1 "./src/mqtt.c"
8330#endif
8331/*
8332 * Copyright (c) 2014 Cesanta Software Limited
8333 * All rights reserved
8334 */
8335
8336#ifndef MG_DISABLE_MQTT
8337
8338/* Amalgamated: #include "mongoose/src/internal.h" */
8339/* Amalgamated: #include "mongoose/src/mqtt.h" */
8340
8342 uint8_t header;
8343 int cmd;
8344 size_t len = 0;
8345 int var_len = 0;
8346 char *vlen = &io->buf[1];
8347
8348 if (io->len < 2) return -1;
8349
8350 header = io->buf[0];
8351 cmd = header >> 4;
8352
8353 /* decode mqtt variable length */
8354 do {
8355 len += (*vlen & 127) << 7 * (vlen - &io->buf[1]);
8356 } while ((*vlen++ & 128) != 0 && ((size_t)(vlen - io->buf) <= io->len));
8357
8358 if (len != 0 && io->len < (size_t)(len - 1)) return -1;
8359
8360 mbuf_remove(io, 1 + (vlen - &io->buf[1]));
8361 mm->cmd = cmd;
8362 mm->qos = MG_MQTT_GET_QOS(header);
8363
8364 switch (cmd) {
8366 /* TODO(mkm): parse keepalive and will */
8367 break;
8369 mm->connack_ret_code = io->buf[1];
8370 var_len = 2;
8371 break;
8372 case MG_MQTT_CMD_PUBACK:
8373 case MG_MQTT_CMD_PUBREC:
8374 case MG_MQTT_CMD_PUBREL:
8376 case MG_MQTT_CMD_SUBACK:
8377 mm->message_id = ntohs(*(uint16_t *) io->buf);
8378 var_len = 2;
8379 break;
8380 case MG_MQTT_CMD_PUBLISH: {
8381 uint16_t topic_len = ntohs(*(uint16_t *) io->buf);
8382 mm->topic = (char *) MG_MALLOC(topic_len + 1);
8383 mm->topic[topic_len] = 0;
8384 strncpy(mm->topic, io->buf + 2, topic_len);
8385 var_len = topic_len + 2;
8386
8387 if (MG_MQTT_GET_QOS(header) > 0) {
8388 mm->message_id = ntohs(*(uint16_t *) io->buf);
8389 var_len += 2;
8390 }
8391 } break;
8393 /*
8394 * topic expressions are left in the payload and can be parsed with
8395 * `mg_mqtt_next_subscribe_topic`
8396 */
8397 mm->message_id = ntohs(*(uint16_t *) io->buf);
8398 var_len = 2;
8399 break;
8400 default:
8401 /* Unhandled command */
8402 break;
8403 }
8404
8406 return len - var_len;
8407}
8408
8409static void mqtt_handler(struct mg_connection *nc, int ev, void *ev_data) {
8410 int len;
8411 struct mbuf *io = &nc->recv_mbuf;
8412 struct mg_mqtt_message mm;
8413 memset(&mm, 0, sizeof(mm));
8414
8415 nc->handler(nc, ev, ev_data);
8416
8417 switch (ev) {
8418 case MG_EV_RECV:
8419 len = parse_mqtt(io, &mm);
8420 if (len == -1) break; /* not fully buffered */
8421 mm.payload.p = io->buf;
8422 mm.payload.len = len;
8423
8424 nc->handler(nc, MG_MQTT_EVENT_BASE + mm.cmd, &mm);
8425
8426 if (mm.topic) {
8427 MG_FREE(mm.topic);
8428 }
8429 mbuf_remove(io, mm.payload.len);
8430 break;
8431 }
8432}
8433
8437
8438void mg_send_mqtt_handshake(struct mg_connection *nc, const char *client_id) {
8439 static struct mg_send_mqtt_handshake_opts opts;
8440 mg_send_mqtt_handshake_opt(nc, client_id, opts);
8441}
8442
8443void mg_send_mqtt_handshake_opt(struct mg_connection *nc, const char *client_id,
8445 uint8_t header = MG_MQTT_CMD_CONNECT << 4;
8449
8450 /*
8451 * 9: version_header(len, magic_string, version_number), 1: flags, 2:
8452 * keep-alive timer,
8453 * 2: client_identifier_len, n: client_id
8454 */
8455 rem_len = 9 + 1 + 2 + 2 + strlen(client_id);
8456
8457 mg_send(nc, &header, 1);
8458 mg_send(nc, &rem_len, 1);
8459 mg_send(nc, "\00\06MQIsdp\03", 9);
8460 mg_send(nc, &opts.flags, 1);
8461
8462 if (opts.keep_alive == 0) {
8463 opts.keep_alive = 60;
8464 }
8465 keep_alive = htons(opts.keep_alive);
8466 mg_send(nc, &keep_alive, 2);
8467
8468 client_id_len = htons(strlen(client_id));
8469 mg_send(nc, &client_id_len, 2);
8470 mg_send(nc, client_id, strlen(client_id));
8471}
8472
8474 uint8_t flags, size_t len) {
8475 size_t off = nc->send_mbuf.len - len;
8476 uint8_t header = cmd << 4 | (uint8_t) flags;
8477
8478 uint8_t buf[1 + sizeof(size_t)];
8479 uint8_t *vlen = &buf[1];
8480
8481 assert(nc->send_mbuf.len >= len);
8482
8483 buf[0] = header;
8484
8485 /* mqtt variable length encoding */
8486 do {
8487 *vlen = len % 0x80;
8488 len /= 0x80;
8489 if (len > 0) *vlen |= 0x80;
8490 vlen++;
8491 } while (len > 0);
8492
8493 mbuf_insert(&nc->send_mbuf, off, buf, vlen - buf);
8494}
8495
8496void mg_mqtt_publish(struct mg_connection *nc, const char *topic,
8497 uint16_t message_id, int flags, const void *data,
8498 size_t len) {
8499 size_t old_len = nc->send_mbuf.len;
8500
8501 uint16_t topic_len = htons(strlen(topic));
8502 uint16_t message_id_net = htons(message_id);
8503
8504 mg_send(nc, &topic_len, 2);
8505 mg_send(nc, topic, strlen(topic));
8506 if (MG_MQTT_GET_QOS(flags) > 0) {
8507 mg_send(nc, &message_id_net, 2);
8508 }
8509 mg_send(nc, data, len);
8510
8512 nc->send_mbuf.len - old_len);
8513}
8514
8516 const struct mg_mqtt_topic_expression *topics,
8517 size_t topics_len, uint16_t message_id) {
8518 size_t old_len = nc->send_mbuf.len;
8519
8520 uint16_t message_id_n = htons(message_id);
8521 size_t i;
8522
8523 mg_send(nc, (char *) &message_id_n, 2);
8524 for (i = 0; i < topics_len; i++) {
8526 mg_send(nc, &topic_len_n, 2);
8527 mg_send(nc, topics[i].topic, strlen(topics[i].topic));
8528 mg_send(nc, &topics[i].qos, 1);
8529 }
8530
8532 nc->send_mbuf.len - old_len);
8533}
8534
8536 struct mg_str *topic, uint8_t *qos, int pos) {
8537 unsigned char *buf = (unsigned char *) msg->payload.p + pos;
8538 if ((size_t) pos >= msg->payload.len) {
8539 return -1;
8540 }
8541
8542 topic->len = buf[0] << 8 | buf[1];
8543 topic->p = (char *) buf + 2;
8544 *qos = buf[2 + topic->len];
8545 return pos + 2 + topic->len + 1;
8546}
8547
8549 size_t topics_len, uint16_t message_id) {
8550 size_t old_len = nc->send_mbuf.len;
8551
8552 uint16_t message_id_n = htons(message_id);
8553 size_t i;
8554
8555 mg_send(nc, (char *) &message_id_n, 2);
8556 for (i = 0; i < topics_len; i++) {
8558 mg_send(nc, &topic_len_n, 2);
8559 mg_send(nc, topics[i], strlen(topics[i]));
8560 }
8561
8563 nc->send_mbuf.len - old_len);
8564}
8565
8567 uint8_t unused = 0;
8568 mg_send(nc, &unused, 1);
8569 mg_send(nc, &return_code, 1);
8571}
8572
8573/*
8574 * Sends a command which contains only a `message_id` and a QoS level of 1.
8575 *
8576 * Helper function.
8577 */
8579 uint16_t message_id) {
8580 uint16_t message_id_net = htons(message_id);
8581 mg_send(nc, &message_id_net, 2);
8582 mg_mqtt_prepend_header(nc, cmd, MG_MQTT_QOS(1), 2);
8583}
8584
8585void mg_mqtt_puback(struct mg_connection *nc, uint16_t message_id) {
8587}
8588
8589void mg_mqtt_pubrec(struct mg_connection *nc, uint16_t message_id) {
8591}
8592
8593void mg_mqtt_pubrel(struct mg_connection *nc, uint16_t message_id) {
8595}
8596
8597void mg_mqtt_pubcomp(struct mg_connection *nc, uint16_t message_id) {
8599}
8600
8602 uint16_t message_id) {
8603 size_t i;
8604 uint16_t message_id_net = htons(message_id);
8605 mg_send(nc, &message_id_net, 2);
8606 for (i = 0; i < qoss_len; i++) {
8607 mg_send(nc, &qoss[i], 1);
8608 }
8610}
8611
8612void mg_mqtt_unsuback(struct mg_connection *nc, uint16_t message_id) {
8614}
8615
8619
8623
8627
8628#endif /* MG_DISABLE_MQTT */
8629#ifdef MG_MODULE_LINES
8630#line 1 "./src/mqtt-broker.c"
8631#endif
8632/*
8633 * Copyright (c) 2014 Cesanta Software Limited
8634 * All rights reserved
8635 */
8636
8637/* Amalgamated: #include "mongoose/src/internal.h" */
8638/* Amalgamated: #include "mongoose/src/mqtt-broker.h" */
8639
8640#ifdef MG_ENABLE_MQTT_BROKER
8641
8642static void mg_mqtt_session_init(struct mg_mqtt_broker *brk,
8643 struct mg_mqtt_session *s,
8644 struct mg_connection *nc) {
8645 s->brk = brk;
8646 s->subscriptions = NULL;
8647 s->num_subscriptions = 0;
8648 s->nc = nc;
8649}
8650
8651static void mg_mqtt_add_session(struct mg_mqtt_session *s) {
8652 s->next = s->brk->sessions;
8653 s->brk->sessions = s;
8654 s->prev = NULL;
8655 if (s->next != NULL) s->next->prev = s;
8656}
8657
8658static void mg_mqtt_remove_session(struct mg_mqtt_session *s) {
8659 if (s->prev == NULL) s->brk->sessions = s->next;
8660 if (s->prev) s->prev->next = s->next;
8661 if (s->next) s->next->prev = s->prev;
8662}
8663
8664static void mg_mqtt_destroy_session(struct mg_mqtt_session *s) {
8665 size_t i;
8666 for (i = 0; i < s->num_subscriptions; i++) {
8667 MG_FREE((void *) s->subscriptions[i].topic);
8668 }
8669 MG_FREE(s->subscriptions);
8670 MG_FREE(s);
8671}
8672
8673static void mg_mqtt_close_session(struct mg_mqtt_session *s) {
8676}
8677
8678void mg_mqtt_broker_init(struct mg_mqtt_broker *brk, void *user_data) {
8679 brk->sessions = NULL;
8680 brk->user_data = user_data;
8681}
8682
8684 struct mg_connection *nc) {
8685 struct mg_mqtt_session *s = (struct mg_mqtt_session *) malloc(sizeof *s);
8686 if (s == NULL) {
8687 /* LCOV_EXCL_START */
8689 return;
8690 /* LCOV_EXCL_STOP */
8691 }
8692
8693 /* TODO(mkm): check header (magic and version) */
8694
8695 mg_mqtt_session_init(brk, s, nc);
8696 s->user_data = nc->user_data;
8697 nc->user_data = s;
8699
8701}
8702
8703static void mg_mqtt_broker_handle_subscribe(struct mg_connection *nc,
8704 struct mg_mqtt_message *msg) {
8705 struct mg_mqtt_session *ss = (struct mg_mqtt_session *) nc->user_data;
8706 uint8_t qoss[512];
8707 size_t qoss_len = 0;
8708 struct mg_str topic;
8709 uint8_t qos;
8710 int pos;
8712
8713 for (pos = 0;
8714 (pos = mg_mqtt_next_subscribe_topic(msg, &topic, &qos, pos)) != -1;) {
8715 qoss[qoss_len++] = qos;
8716 }
8717
8718 ss->subscriptions = (struct mg_mqtt_topic_expression *) realloc(
8719 ss->subscriptions, sizeof(*ss->subscriptions) * qoss_len);
8720 for (pos = 0;
8721 (pos = mg_mqtt_next_subscribe_topic(msg, &topic, &qos, pos)) != -1;
8722 ss->num_subscriptions++) {
8723 te = &ss->subscriptions[ss->num_subscriptions];
8724 te->topic = (char *) malloc(topic.len + 1);
8725 te->qos = qos;
8726 strncpy((char *) te->topic, topic.p, topic.len + 1);
8727 }
8728
8729 mg_mqtt_suback(nc, qoss, qoss_len, msg->message_id);
8730}
8731
8732/*
8733 * Matches a topic against a topic expression
8734 *
8735 * See http://goo.gl/iWk21X
8736 *
8737 * Returns 1 if it matches; 0 otherwise.
8738 */
8739static int mg_mqtt_match_topic_expression(const char *exp, const char *topic) {
8740 /* TODO(mkm): implement real matching */
8741 int len = strlen(exp);
8742 if (strchr(exp, '#')) {
8743 len -= 2;
8744 }
8745 return strncmp(exp, topic, len) == 0;
8746}
8747
8749 struct mg_mqtt_message *msg) {
8750 struct mg_mqtt_session *s;
8751 size_t i;
8752
8753 for (s = mg_mqtt_next(brk, NULL); s != NULL; s = mg_mqtt_next(brk, s)) {
8754 for (i = 0; i < s->num_subscriptions; i++) {
8755 if (mg_mqtt_match_topic_expression(s->subscriptions[i].topic,
8756 msg->topic)) {
8757 mg_mqtt_publish(s->nc, msg->topic, 0, 0, msg->payload.p,
8758 msg->payload.len);
8759 break;
8760 }
8761 }
8762 }
8763}
8764
8765void mg_mqtt_broker(struct mg_connection *nc, int ev, void *data) {
8766 struct mg_mqtt_message *msg = (struct mg_mqtt_message *) data;
8767 struct mg_mqtt_broker *brk;
8768
8769 if (nc->listener) {
8770 brk = (struct mg_mqtt_broker *) nc->listener->user_data;
8771 } else {
8772 brk = (struct mg_mqtt_broker *) nc->user_data;
8773 }
8774
8775 switch (ev) {
8776 case MG_EV_ACCEPT:
8778 break;
8779 case MG_EV_MQTT_CONNECT:
8781 break;
8784 break;
8785 case MG_EV_MQTT_PUBLISH:
8787 break;
8788 case MG_EV_CLOSE:
8789 if (nc->listener) {
8791 }
8792 break;
8793 }
8794}
8795
8797 struct mg_mqtt_session *s) {
8798 return s == NULL ? brk->sessions : s->next;
8799}
8800
8801#endif /* MG_ENABLE_MQTT_BROKER */
8802#ifdef MG_MODULE_LINES
8803#line 1 "./src/dns.c"
8804#endif
8805/*
8806 * Copyright (c) 2014 Cesanta Software Limited
8807 * All rights reserved
8808 */
8809
8810#ifndef MG_DISABLE_DNS
8811
8812/* Amalgamated: #include "mongoose/src/internal.h" */
8813/* Amalgamated: #include "mongoose/src/dns.h" */
8814
8815static int mg_dns_tid = 0xa0;
8816
8825
8827 struct mg_dns_message *msg, int query,
8828 struct mg_dns_resource_record *prev) {
8829 struct mg_dns_resource_record *rr;
8830
8831 for (rr = (prev == NULL ? msg->answers : prev + 1);
8832 rr - msg->answers < msg->num_answers; rr++) {
8833 if (rr->rtype == query) {
8834 return rr;
8835 }
8836 }
8837 return NULL;
8838}
8839
8841 struct mg_dns_resource_record *rr, void *data,
8842 size_t data_len) {
8843 switch (rr->rtype) {
8844 case MG_DNS_A_RECORD:
8845 if (data_len < sizeof(struct in_addr)) {
8846 return -1;
8847 }
8848 if (rr->rdata.p + data_len > msg->pkt.p + msg->pkt.len) {
8849 return -1;
8850 }
8851 memcpy(data, rr->rdata.p, data_len);
8852 return 0;
8853#ifdef MG_ENABLE_IPV6
8854 case MG_DNS_AAAA_RECORD:
8855 if (data_len < sizeof(struct in6_addr)) {
8856 return -1; /* LCOV_EXCL_LINE */
8857 }
8858 memcpy(data, rr->rdata.p, data_len);
8859 return 0;
8860#endif
8862 mg_dns_uncompress_name(msg, &rr->rdata, (char *) data, data_len);
8863 return 0;
8864 }
8865
8866 return -1;
8867}
8868
8869int mg_dns_insert_header(struct mbuf *io, size_t pos,
8870 struct mg_dns_message *msg) {
8871 struct mg_dns_header header;
8872
8873 memset(&header, 0, sizeof(header));
8874 header.transaction_id = msg->transaction_id;
8875 header.flags = htons(msg->flags);
8876 header.num_questions = htons(msg->num_questions);
8877 header.num_answers = htons(msg->num_answers);
8878
8879 return mbuf_insert(io, pos, &header, sizeof(header));
8880}
8881
8882int mg_dns_copy_body(struct mbuf *io, struct mg_dns_message *msg) {
8883 return mbuf_append(io, msg->pkt.p + sizeof(struct mg_dns_header),
8884 msg->pkt.len - sizeof(struct mg_dns_header));
8885}
8886
8887static int mg_dns_encode_name(struct mbuf *io, const char *name, size_t len) {
8888 const char *s;
8889 unsigned char n;
8890 size_t pos = io->len;
8891
8892 do {
8893 if ((s = strchr(name, '.')) == NULL) {
8894 s = name + len;
8895 }
8896
8897 if (s - name > 127) {
8898 return -1; /* TODO(mkm) cover */
8899 }
8900 n = s - name; /* chunk length */
8901 mbuf_append(io, &n, 1); /* send length */
8902 mbuf_append(io, name, n);
8903
8904 if (*s == '.') {
8905 n++;
8906 }
8907
8908 name += n;
8909 len -= n;
8910 } while (*s != '\0');
8911 mbuf_append(io, "\0", 1); /* Mark end of host name */
8912
8913 return io->len - pos;
8914}
8915
8917 const char *name, size_t nlen, const void *rdata,
8918 size_t rlen) {
8919 size_t pos = io->len;
8920 uint16_t u16;
8921 uint32_t u32;
8922
8923 if (rr->kind == MG_DNS_INVALID_RECORD) {
8924 return -1; /* LCOV_EXCL_LINE */
8925 }
8926
8927 if (mg_dns_encode_name(io, name, nlen) == -1) {
8928 return -1;
8929 }
8930
8931 u16 = htons(rr->rtype);
8932 mbuf_append(io, &u16, 2);
8933 u16 = htons(rr->rclass);
8934 mbuf_append(io, &u16, 2);
8935
8936 if (rr->kind == MG_DNS_ANSWER) {
8937 u32 = htonl(rr->ttl);
8938 mbuf_append(io, &u32, 4);
8939
8940 if (rr->rtype == MG_DNS_CNAME_RECORD) {
8941 int clen;
8942 /* fill size after encoding */
8943 size_t off = io->len;
8944 mbuf_append(io, &u16, 2);
8945 if ((clen = mg_dns_encode_name(io, (const char *) rdata, rlen)) == -1) {
8946 return -1;
8947 }
8948 u16 = clen;
8949 io->buf[off] = u16 >> 8;
8950 io->buf[off + 1] = u16 & 0xff;
8951 } else {
8952 u16 = htons(rlen);
8953 mbuf_append(io, &u16, 2);
8954 mbuf_append(io, rdata, rlen);
8955 }
8956 }
8957
8958 return io->len - pos;
8959}
8960
8961void mg_send_dns_query(struct mg_connection *nc, const char *name,
8962 int query_type) {
8963 struct mg_dns_message *msg =
8964 (struct mg_dns_message *) MG_CALLOC(1, sizeof(*msg));
8965 struct mbuf pkt;
8966 struct mg_dns_resource_record *rr = &msg->questions[0];
8967
8968 DBG(("%s %d", name, query_type));
8969
8970 mbuf_init(&pkt, 64 /* Start small, it'll grow as needed. */);
8971
8972 msg->transaction_id = ++mg_dns_tid;
8973 msg->flags = 0x100;
8974 msg->num_questions = 1;
8975
8976 mg_dns_insert_header(&pkt, 0, msg);
8977
8978 rr->rtype = query_type;
8979 rr->rclass = 1; /* Class: inet */
8980 rr->kind = MG_DNS_QUESTION;
8981
8982 if (mg_dns_encode_record(&pkt, rr, name, strlen(name), NULL, 0) == -1) {
8983 /* TODO(mkm): return an error code */
8984 goto cleanup; /* LCOV_EXCL_LINE */
8985 }
8986
8987 /* TCP DNS requires messages to be prefixed with len */
8988 if (!(nc->flags & MG_F_UDP)) {
8989 uint16_t len = htons(pkt.len);
8990 mbuf_insert(&pkt, 0, &len, 2);
8991 }
8992
8993 mg_send(nc, pkt.buf, pkt.len);
8994 mbuf_free(&pkt);
8995
8996cleanup:
8997 MG_FREE(msg);
8998}
8999
9000static unsigned char *mg_parse_dns_resource_record(
9001 unsigned char *data, unsigned char *end, struct mg_dns_resource_record *rr,
9002 int reply) {
9003 unsigned char *name = data;
9004 int chunk_len, data_len;
9005
9006 while (data < end && (chunk_len = *data)) {
9007 if (((unsigned char *) data)[0] & 0xc0) {
9008 data += 1;
9009 break;
9010 }
9011 data += chunk_len + 1;
9012 }
9013
9014 if (data > end - 5) {
9015 return NULL;
9016 }
9017
9018 rr->name.p = (char *) name;
9019 rr->name.len = data - name + 1;
9020 data++;
9021
9022 rr->rtype = data[0] << 8 | data[1];
9023 data += 2;
9024
9025 rr->rclass = data[0] << 8 | data[1];
9026 data += 2;
9027
9029 if (reply) {
9030 if (data >= end - 6) {
9031 return NULL;
9032 }
9033
9034 rr->ttl = (uint32_t) data[0] << 24 | (uint32_t) data[1] << 16 |
9035 data[2] << 8 | data[3];
9036 data += 4;
9037
9038 data_len = *data << 8 | *(data + 1);
9039 data += 2;
9040
9041 rr->rdata.p = (char *) data;
9042 rr->rdata.len = data_len;
9043 data += data_len;
9044 }
9045 return data;
9046}
9047
9048int mg_parse_dns(const char *buf, int len, struct mg_dns_message *msg) {
9049 struct mg_dns_header *header = (struct mg_dns_header *) buf;
9050 unsigned char *data = (unsigned char *) buf + sizeof(*header);
9051 unsigned char *end = (unsigned char *) buf + len;
9052 int i;
9053
9054 memset(msg, 0, sizeof(*msg));
9055 msg->pkt.p = buf;
9056 msg->pkt.len = len;
9057
9058 if (len < (int) sizeof(*header)) return -1;
9059
9060 msg->transaction_id = header->transaction_id;
9061 msg->flags = ntohs(header->flags);
9062 msg->num_questions = ntohs(header->num_questions);
9063 if (msg->num_questions > (int) ARRAY_SIZE(msg->questions)) {
9064 msg->num_questions = (int) ARRAY_SIZE(msg->questions);
9065 }
9066 msg->num_answers = ntohs(header->num_answers);
9067 if (msg->num_answers > (int) ARRAY_SIZE(msg->answers)) {
9068 msg->num_answers = (int) ARRAY_SIZE(msg->answers);
9069 }
9070
9071 for (i = 0; i < msg->num_questions; i++) {
9073 if (data == NULL) return -1;
9074 }
9075
9076 for (i = 0; i < msg->num_answers; i++) {
9078 if (data == NULL) return -1;
9079 }
9080
9081 return 0;
9082}
9083
9085 char *dst, int dst_len) {
9086 int chunk_len;
9087 char *old_dst = dst;
9088 const unsigned char *data = (unsigned char *) name->p;
9089 const unsigned char *end = (unsigned char *) msg->pkt.p + msg->pkt.len;
9090
9091 if (data >= end) {
9092 return 0;
9093 }
9094
9095 while ((chunk_len = *data++)) {
9096 int leeway = dst_len - (dst - old_dst);
9097 if (data >= end) {
9098 return 0;
9099 }
9100
9101 if (chunk_len & 0xc0) {
9102 uint16_t off = (data[-1] & (~0xc0)) << 8 | data[0];
9103 if (off >= msg->pkt.len) {
9104 return 0;
9105 }
9106 data = (unsigned char *) msg->pkt.p + off;
9107 continue;
9108 }
9109 if (chunk_len > leeway) {
9110 chunk_len = leeway;
9111 }
9112
9113 if (data + chunk_len >= end) {
9114 return 0;
9115 }
9116
9117 memcpy(dst, data, chunk_len);
9118 data += chunk_len;
9119 dst += chunk_len;
9120 leeway -= chunk_len;
9121 if (leeway == 0) {
9122 return dst - old_dst;
9123 }
9124 *dst++ = '.';
9125 }
9126
9127 if (dst != old_dst) {
9128 *--dst = 0;
9129 }
9130 return dst - old_dst;
9131}
9132
9133static void dns_handler(struct mg_connection *nc, int ev, void *ev_data) {
9134 struct mbuf *io = &nc->recv_mbuf;
9135 struct mg_dns_message msg;
9136
9137 /* Pass low-level events to the user handler */
9138 nc->handler(nc, ev, ev_data);
9139
9140 switch (ev) {
9141 case MG_EV_RECV:
9142 if (!(nc->flags & MG_F_UDP)) {
9143 mbuf_remove(&nc->recv_mbuf, 2);
9144 }
9145 if (mg_parse_dns(nc->recv_mbuf.buf, nc->recv_mbuf.len, &msg) == -1) {
9146 /* reply + recursion allowed + format error */
9147 memset(&msg, 0, sizeof(msg));
9148 msg.flags = 0x8081;
9149 mg_dns_insert_header(io, 0, &msg);
9150 if (!(nc->flags & MG_F_UDP)) {
9151 uint16_t len = htons(io->len);
9152 mbuf_insert(io, 0, &len, 2);
9153 }
9154 mg_send(nc, io->buf, io->len);
9155 } else {
9156 /* Call user handler with parsed message */
9157 nc->handler(nc, MG_DNS_MESSAGE, &msg);
9158 }
9159 mbuf_remove(io, io->len);
9160 break;
9161 }
9162}
9163
9166}
9167
9168#endif /* MG_DISABLE_DNS */
9169#ifdef MG_MODULE_LINES
9170#line 1 "./src/dns-server.c"
9171#endif
9172/*
9173 * Copyright (c) 2014 Cesanta Software Limited
9174 * All rights reserved
9175 */
9176
9177#ifdef MG_ENABLE_DNS_SERVER
9178
9179/* Amalgamated: #include "mongoose/src/internal.h" */
9180/* Amalgamated: #include "mongoose/src/dns-server.h" */
9181
9183 struct mg_dns_message *msg) {
9184 struct mg_dns_reply rep;
9185 rep.msg = msg;
9186 rep.io = io;
9187 rep.start = io->len;
9188
9189 /* reply + recursion allowed */
9190 msg->flags |= 0x8080;
9191 mg_dns_copy_body(io, msg);
9192
9193 msg->num_answers = 0;
9194 return rep;
9195}
9196
9197void mg_dns_send_reply(struct mg_connection *nc, struct mg_dns_reply *r) {
9198 size_t sent = r->io->len - r->start;
9199 mg_dns_insert_header(r->io, r->start, r->msg);
9200 if (!(nc->flags & MG_F_UDP)) {
9201 uint16_t len = htons(sent);
9202 mbuf_insert(r->io, r->start, &len, 2);
9203 }
9204
9205 if (&nc->send_mbuf != r->io) {
9206 mg_send(nc, r->io->buf + r->start, r->io->len - r->start);
9207 r->io->len = r->start;
9208 }
9209}
9210
9213 const char *name, int rtype, int ttl, const void *rdata,
9214 size_t rdata_len) {
9215 struct mg_dns_message *msg = (struct mg_dns_message *) reply->msg;
9216 char rname[512];
9217 struct mg_dns_resource_record *ans = &msg->answers[msg->num_answers];
9218 if (msg->num_answers >= MG_MAX_DNS_ANSWERS) {
9219 return -1; /* LCOV_EXCL_LINE */
9220 }
9221
9222 if (name == NULL) {
9223 name = rname;
9224 rname[511] = 0;
9225 mg_dns_uncompress_name(msg, &question->name, rname, sizeof(rname) - 1);
9226 }
9227
9228 *ans = *question;
9229 ans->kind = MG_DNS_ANSWER;
9230 ans->rtype = rtype;
9231 ans->ttl = ttl;
9232
9234 rdata_len) == -1) {
9235 return -1; /* LCOV_EXCL_LINE */
9236 };
9237
9238 msg->num_answers++;
9239 return 0;
9240}
9241
9242#endif /* MG_ENABLE_DNS_SERVER */
9243#ifdef MG_MODULE_LINES
9244#line 1 "./src/resolv.c"
9245#endif
9246/*
9247 * Copyright (c) 2014 Cesanta Software Limited
9248 * All rights reserved
9249 */
9250
9251#ifndef MG_DISABLE_RESOLVER
9252
9253/* Amalgamated: #include "mongoose/src/internal.h" */
9254/* Amalgamated: #include "mongoose/src/resolv.h" */
9255
9256#ifndef MG_DEFAULT_NAMESERVER
9257#define MG_DEFAULT_NAMESERVER "8.8.8.8"
9258#endif
9259
9260static const char *mg_default_dns_server = "udp://" MG_DEFAULT_NAMESERVER ":53";
9261
9263
9277
9278/*
9279 * Find what nameserver to use.
9280 *
9281 * Return 0 if OK, -1 if error
9282 */
9283static int mg_get_ip_address_of_nameserver(char *name, size_t name_len) {
9284 int ret = -1;
9285
9286#ifdef _WIN32
9287 int i;
9288 LONG err;
9289 HKEY hKey, hSub;
9290 char subkey[512], value[128],
9291 *key = "SYSTEM\\ControlSet001\\Services\\Tcpip\\Parameters\\Interfaces";
9292
9294 fprintf(stderr, "cannot open reg key %s: %d\n", key, err);
9295 ret = -1;
9296 } else {
9297 for (ret = -1, i = 0;
9298 RegEnumKeyA(hKey, i, subkey, sizeof(subkey)) == ERROR_SUCCESS; i++) {
9299 DWORD type, len = sizeof(value);
9301 (RegQueryValueExA(hSub, "NameServer", 0, &type, (void *) value,
9302 &len) == ERROR_SUCCESS ||
9303 RegQueryValueExA(hSub, "DhcpNameServer", 0, &type, (void *) value,
9304 &len) == ERROR_SUCCESS)) {
9305 /*
9306 * See https://github.com/cesanta/mongoose/issues/176
9307 * The value taken from the registry can be empty, a single
9308 * IP address, or multiple IP addresses separated by comma.
9309 * If it's empty, check the next interface.
9310 * If it's multiple IP addresses, take the first one.
9311 */
9312 char *comma = strchr(value, ',');
9313 if (value[0] == '\0') {
9314 continue;
9315 }
9316 if (comma != NULL) {
9317 *comma = '\0';
9318 }
9319 snprintf(name, name_len, "udp://%s:53", value);
9320 ret = 0;
9322 break;
9323 }
9324 }
9326 }
9327#elif !defined(MG_DISABLE_FILESYSTEM)
9328 FILE *fp;
9329 char line[512];
9330
9331 if ((fp = fopen("/etc/resolv.conf", "r")) == NULL) {
9332 ret = -1;
9333 } else {
9334 /* Try to figure out what nameserver to use */
9335 for (ret = -1; fgets(line, sizeof(line), fp) != NULL;) {
9336 char buf[256];
9337 if (sscanf(line, "nameserver %255[^\n\t #]s", buf) == 1) {
9338 snprintf(name, name_len, "udp://%s:53", buf);
9339 ret = 0;
9340 break;
9341 }
9342 }
9343 (void) fclose(fp);
9344 }
9345#else
9346 snprintf(name, name_len, "%s", mg_default_dns_server);
9347#endif /* _WIN32 */
9348
9349 return ret;
9350}
9351
9353#ifndef MG_DISABLE_FILESYSTEM
9354 /* TODO(mkm) cache /etc/hosts */
9355 FILE *fp;
9356 char line[1024];
9357 char *p;
9358 char alias[256];
9359 unsigned int a, b, c, d;
9360 int len = 0;
9361
9362 if ((fp = fopen("/etc/hosts", "r")) == NULL) {
9363 return -1;
9364 }
9365
9366 for (; fgets(line, sizeof(line), fp) != NULL;) {
9367 if (line[0] == '#') continue;
9368
9369 if (sscanf(line, "%u.%u.%u.%u%n", &a, &b, &c, &d, &len) == 0) {
9370 /* TODO(mkm): handle ipv6 */
9371 continue;
9372 }
9373 for (p = line + len; sscanf(p, "%s%n", alias, &len) == 1; p += len) {
9374 if (strcmp(alias, name) == 0) {
9375 usa->sin.sin_addr.s_addr = htonl(a << 24 | b << 16 | c << 8 | d);
9376 fclose(fp);
9377 return 0;
9378 }
9379 }
9380 }
9381
9382 fclose(fp);
9383#endif
9384
9385 return -1;
9386}
9387
9388static void mg_resolve_async_eh(struct mg_connection *nc, int ev, void *data) {
9389 time_t now = time(NULL);
9390 struct mg_resolve_async_request *req;
9391 struct mg_dns_message *msg;
9392
9393 DBG(("ev=%d", ev));
9394
9395 req = (struct mg_resolve_async_request *) nc->user_data;
9396
9397 switch (ev) {
9398 case MG_EV_CONNECT:
9399 case MG_EV_POLL:
9400 if (req->retries > req->max_retries) {
9403 break;
9404 }
9405 if (now - req->last_time >= req->timeout) {
9406 mg_send_dns_query(nc, req->name, req->query);
9407 req->last_time = now;
9408 req->retries++;
9409 }
9410 break;
9411 case MG_EV_RECV:
9412 msg = (struct mg_dns_message *) MG_MALLOC(sizeof(*msg));
9413 if (mg_parse_dns(nc->recv_mbuf.buf, *(int *) data, msg) == 0 &&
9414 msg->num_answers > 0) {
9415 req->callback(msg, req->data, MG_RESOLVE_OK);
9416 nc->user_data = NULL;
9417 MG_FREE(req);
9418 } else {
9420 }
9421 MG_FREE(msg);
9423 break;
9424 case MG_EV_SEND:
9425 /*
9426 * If a send error occurs, prevent closing of the connection by the core.
9427 * We will retry after timeout.
9428 */
9431 break;
9432 case MG_EV_TIMER:
9433 req->err = MG_RESOLVE_TIMEOUT;
9435 break;
9436 case MG_EV_CLOSE:
9437 /* If we got here with request still not done, fire an error callback. */
9438 if (req != NULL) {
9439 req->callback(NULL, req->data, req->err);
9440 nc->user_data = NULL;
9441 MG_FREE(req);
9442 }
9443 break;
9444 }
9445}
9446
9447int mg_resolve_async(struct mg_mgr *mgr, const char *name, int query,
9448 mg_resolve_callback_t cb, void *data) {
9450 memset(&opts, 0, sizeof(opts));
9451 return mg_resolve_async_opt(mgr, name, query, cb, data, opts);
9452}
9453
9454int mg_resolve_async_opt(struct mg_mgr *mgr, const char *name, int query,
9455 mg_resolve_callback_t cb, void *data,
9456 struct mg_resolve_async_opts opts) {
9457 struct mg_resolve_async_request *req;
9458 struct mg_connection *dns_nc;
9459 const char *nameserver = opts.nameserver_url;
9460
9461 DBG(("%s %d %p", name, query, opts.dns_conn));
9462
9463 /* resolve with DNS */
9464 req = (struct mg_resolve_async_request *) MG_CALLOC(1, sizeof(*req));
9465 if (req == NULL) {
9466 return -1;
9467 }
9468
9469 memset(req->name, 0, sizeof(req->name));
9470 strncpy(req->name, name, sizeof(req->name)-1);
9471 req->query = query;
9472 req->callback = cb;
9473 req->data = data;
9474 /* TODO(mkm): parse defaults out of resolve.conf */
9475 req->max_retries = opts.max_retries ? opts.max_retries : 2;
9476 req->timeout = opts.timeout ? opts.timeout : 5;
9477
9478 /* Lazily initialize dns server */
9479 if (nameserver == NULL && mg_dns_server[0] == '\0' &&
9481 -1) {
9483 }
9484
9485 if (nameserver == NULL) {
9486 nameserver = mg_dns_server;
9487 }
9488
9489 dns_nc = mg_connect(mgr, nameserver, mg_resolve_async_eh);
9490 if (dns_nc == NULL) {
9491 free(req);
9492 return -1;
9493 }
9494 dns_nc->user_data = req;
9495 if (opts.dns_conn != NULL) {
9496 *opts.dns_conn = dns_nc;
9497 }
9498
9499 return 0;
9500}
9501
9502#endif /* MG_DISABLE_RESOLVE */
9503#ifdef MG_MODULE_LINES
9504#line 1 "./src/coap.c"
9505#endif
9506/*
9507 * Copyright (c) 2015 Cesanta Software Limited
9508 * All rights reserved
9509 * This software is dual-licensed: you can redistribute it and/or modify
9510 * it under the terms of the GNU General Public License version 2 as
9511 * published by the Free Software Foundation. For the terms of this
9512 * license, see <http://www.gnu.org/licenses/>.
9513 *
9514 * You are free to use this software under the terms of the GNU General
9515 * Public License, but WITHOUT ANY WARRANTY; without even the implied
9516 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
9517 * See the GNU General Public License for more details.
9518 *
9519 * Alternatively, you can license this software under a commercial
9520 * license, as set out in <https://www.cesanta.com/license>.
9521 */
9522
9523/* Amalgamated: #include "mongoose/src/internal.h" */
9524/* Amalgamated: #include "mongoose/src/coap.h" */
9525
9526#ifdef MG_ENABLE_COAP
9527
9529 while (cm->options != NULL) {
9530 struct mg_coap_option *next = cm->options->next;
9531 MG_FREE(cm->options);
9532 cm->options = next;
9533 }
9534}
9535
9537 uint32_t number, char *value,
9538 size_t len) {
9539 struct mg_coap_option *new_option =
9540 (struct mg_coap_option *) MG_CALLOC(1, sizeof(*new_option));
9541
9542 new_option->number = number;
9543 new_option->value.p = value;
9544 new_option->value.len = len;
9545
9546 if (cm->options == NULL) {
9547 cm->options = cm->optiomg_tail = new_option;
9548 } else {
9549 /*
9550 * A very simple attention to help clients to compose options:
9551 * CoAP wants to see options ASC ordered.
9552 * Could be change by using sort in coap_compose
9553 */
9554 if (cm->optiomg_tail->number <= new_option->number) {
9555 /* if option is already ordered just add it */
9556 cm->optiomg_tail = cm->optiomg_tail->next = new_option;
9557 } else {
9558 /* looking for appropriate position */
9559 struct mg_coap_option *current_opt = cm->options;
9560 struct mg_coap_option *prev_opt = 0;
9561
9562 while (current_opt != NULL) {
9563 if (current_opt->number > new_option->number) {
9564 break;
9565 }
9567 current_opt = current_opt->next;
9568 }
9569
9570 if (prev_opt != NULL) {
9571 prev_opt->next = new_option;
9572 new_option->next = current_opt;
9573 } else {
9574 /* insert new_option to the beginning */
9575 new_option->next = cm->options;
9576 cm->options = new_option;
9577 }
9578 }
9579 }
9580
9581 return new_option;
9582}
9583
9584/*
9585 * Fills CoAP header in mg_coap_message.
9586 *
9587 * Helper function.
9588 */
9589static char *coap_parse_header(char *ptr, struct mbuf *io,
9590 struct mg_coap_message *cm) {
9591 if (io->len < sizeof(uint32_t)) {
9592 cm->flags |= MG_COAP_NOT_ENOUGH_DATA;
9593 return NULL;
9594 }
9595
9596 /*
9597 * Version (Ver): 2-bit unsigned integer. Indicates the CoAP version
9598 * number. Implementations of this specification MUST set this field
9599 * to 1 (01 binary). Other values are reserved for future versions.
9600 * Messages with unknown version numbers MUST be silently ignored.
9601 */
9602 if (((uint8_t) *ptr >> 6) != 1) {
9603 cm->flags |= MG_COAP_IGNORE;
9604 return NULL;
9605 }
9606
9607 /*
9608 * Type (T): 2-bit unsigned integer. Indicates if this message is of
9609 * type Confirmable (0), Non-confirmable (1), Acknowledgement (2), or
9610 * Reset (3).
9611 */
9612 cm->msg_type = ((uint8_t) *ptr & 0x30) >> 4;
9613 cm->flags |= MG_COAP_MSG_TYPE_FIELD;
9614
9615 /*
9616 * Token Length (TKL): 4-bit unsigned integer. Indicates the length of
9617 * the variable-length Token field (0-8 bytes). Lengths 9-15 are
9618 * reserved, MUST NOT be sent, and MUST be processed as a message
9619 * format error.
9620 */
9621 cm->token.len = *ptr & 0x0F;
9622 if (cm->token.len > 8) {
9623 cm->flags |= MG_COAP_FORMAT_ERROR;
9624 return NULL;
9625 }
9626
9627 ptr++;
9628
9629 /*
9630 * Code: 8-bit unsigned integer, split into a 3-bit class (most
9631 * significant bits) and a 5-bit detail (least significant bits)
9632 */
9633 cm->code_class = (uint8_t) *ptr >> 5;
9634 cm->code_detail = *ptr & 0x1F;
9636
9637 ptr++;
9638
9639 /* Message ID: 16-bit unsigned integer in network byte order. */
9640 cm->msg_id = (uint8_t) *ptr << 8 | (uint8_t) * (ptr + 1);
9641 cm->flags |= MG_COAP_MSG_ID_FIELD;
9642
9643 ptr += 2;
9644
9645 return ptr;
9646}
9647
9648/*
9649 * Fills token information in mg_coap_message.
9650 *
9651 * Helper function.
9652 */
9653static char *coap_get_token(char *ptr, struct mbuf *io,
9654 struct mg_coap_message *cm) {
9655 if (cm->token.len != 0) {
9656 if (ptr + cm->token.len > io->buf + io->len) {
9657 cm->flags |= MG_COAP_NOT_ENOUGH_DATA;
9658 return NULL;
9659 } else {
9660 cm->token.p = ptr;
9661 ptr += cm->token.len;
9662 cm->flags |= MG_COAP_TOKEN_FIELD;
9663 }
9664 }
9665
9666 return ptr;
9667}
9668
9669/*
9670 * Returns Option Delta or Length.
9671 *
9672 * Helper function.
9673 */
9674static int coap_get_ext_opt(char *ptr, struct mbuf *io, uint16_t *opt_info) {
9675 int ret = 0;
9676
9677 if (*opt_info == 13) {
9678 /*
9679 * 13: An 8-bit unsigned integer follows the initial byte and
9680 * indicates the Option Delta/Length minus 13.
9681 */
9682 if (ptr < io->buf + io->len) {
9683 *opt_info = (uint8_t) *ptr + 13;
9684 ret = sizeof(uint8_t);
9685 } else {
9686 ret = -1; /* LCOV_EXCL_LINE */
9687 }
9688 } else if (*opt_info == 14) {
9689 /*
9690 * 14: A 16-bit unsigned integer in network byte order follows the
9691 * initial byte and indicates the Option Delta/Length minus 269.
9692 */
9693 if (ptr + sizeof(uint8_t) < io->buf + io->len) {
9694 *opt_info = ((uint8_t) *ptr << 8 | (uint8_t) * (ptr + 1)) + 269;
9695 ret = sizeof(uint16_t);
9696 } else {
9697 ret = -1; /* LCOV_EXCL_LINE */
9698 }
9699 }
9700
9701 return ret;
9702}
9703
9704/*
9705 * Fills options in mg_coap_message.
9706 *
9707 * Helper function.
9708 *
9709 * General options format:
9710 * +---------------+---------------+
9711 * | Option Delta | Option Length | 1 byte
9712 * +---------------+---------------+
9713 * \ Option Delta (extended) \ 0-2 bytes
9714 * +-------------------------------+
9715 * / Option Length (extended) \ 0-2 bytes
9716 * +-------------------------------+
9717 * \ Option Value \ 0 or more bytes
9718 * +-------------------------------+
9719 */
9720static char *coap_get_options(char *ptr, struct mbuf *io,
9721 struct mg_coap_message *cm) {
9722 uint16_t prev_opt = 0;
9723
9724 if (ptr == io->buf + io->len) {
9725 /* end of packet, ok */
9726 return NULL;
9727 }
9728
9729 /* 0xFF is payload marker */
9730 while (ptr < io->buf + io->len && (uint8_t) *ptr != 0xFF) {
9732 int optinfo_len;
9733
9734 /* Option Delta: 4-bit unsigned integer */
9735 option_delta = ((uint8_t) *ptr & 0xF0) >> 4;
9736 /* Option Length: 4-bit unsigned integer */
9737 option_lenght = *ptr & 0x0F;
9738
9739 if (option_delta == 15 || option_lenght == 15) {
9740 /*
9741 * 15: Reserved for future use. If the field is set to this value,
9742 * it MUST be processed as a message format error
9743 */
9744 cm->flags |= MG_COAP_FORMAT_ERROR;
9745 break;
9746 }
9747
9748 ptr++;
9749
9750 /* check for extended option delta */
9752 if (optinfo_len == -1) {
9753 cm->flags |= MG_COAP_NOT_ENOUGH_DATA; /* LCOV_EXCL_LINE */
9754 break; /* LCOV_EXCL_LINE */
9755 }
9756
9757 ptr += optinfo_len;
9758
9759 /* check or extended option lenght */
9761 if (optinfo_len == -1) {
9762 cm->flags |= MG_COAP_NOT_ENOUGH_DATA; /* LCOV_EXCL_LINE */
9763 break; /* LCOV_EXCL_LINE */
9764 }
9765
9766 ptr += optinfo_len;
9767
9768 /*
9769 * Instead of specifying the Option Number directly, the instances MUST
9770 * appear in order of their Option Numbers and a delta encoding is used
9771 * between them.
9772 */
9774
9776
9778
9779 if (ptr + option_lenght > io->buf + io->len) {
9780 cm->flags |= MG_COAP_NOT_ENOUGH_DATA; /* LCOV_EXCL_LINE */
9781 break; /* LCOV_EXCL_LINE */
9782 }
9783
9784 ptr += option_lenght;
9785 }
9786
9787 if ((cm->flags & MG_COAP_ERROR) != 0) {
9789 return NULL;
9790 }
9791
9792 cm->flags |= MG_COAP_OPTIOMG_FIELD;
9793
9794 if (ptr == io->buf + io->len) {
9795 /* end of packet, ok */
9796 return NULL;
9797 }
9798
9799 ptr++;
9800
9801 return ptr;
9802}
9803
9804uint32_t mg_coap_parse(struct mbuf *io, struct mg_coap_message *cm) {
9805 char *ptr;
9806
9807 memset(cm, 0, sizeof(*cm));
9808
9809 if ((ptr = coap_parse_header(io->buf, io, cm)) == NULL) {
9810 return cm->flags;
9811 }
9812
9813 if ((ptr = coap_get_token(ptr, io, cm)) == NULL) {
9814 return cm->flags;
9815 }
9816
9817 if ((ptr = coap_get_options(ptr, io, cm)) == NULL) {
9818 return cm->flags;
9819 }
9820
9821 /* the rest is payload */
9822 cm->payload.len = io->len - (ptr - io->buf);
9823 if (cm->payload.len != 0) {
9824 cm->payload.p = ptr;
9825 cm->flags |= MG_COAP_PAYLOAD_FIELD;
9826 }
9827
9828 return cm->flags;
9829}
9830
9831/*
9832 * Calculates extended size of given Opt Number/Length in coap message.
9833 *
9834 * Helper function.
9835 */
9836static size_t coap_get_ext_opt_size(uint32_t value) {
9837 int ret = 0;
9838
9839 if (value >= 13 && value <= 0xFF + 13) {
9840 ret = sizeof(uint8_t);
9841 } else if (value > 0xFF + 13 && value <= 0xFFFF + 269) {
9842 ret = sizeof(uint16_t);
9843 }
9844
9845 return ret;
9846}
9847
9848/*
9849 * Splits given Opt Number/Length into base and ext values.
9850 *
9851 * Helper function.
9852 */
9853static int coap_split_opt(uint32_t value, uint8_t *base, uint16_t *ext) {
9854 int ret = 0;
9855
9856 if (value < 13) {
9857 *base = value;
9858 } else if (value >= 13 && value <= 0xFF + 13) {
9859 *base = 13;
9860 *ext = value - 13;
9861 ret = sizeof(uint8_t);
9862 } else if (value > 0xFF + 13 && value <= 0xFFFF + 269) {
9863 *base = 14;
9864 *ext = value - 269;
9865 ret = sizeof(uint16_t);
9866 }
9867
9868 return ret;
9869}
9870
9871/*
9872 * Puts uint16_t (in network order) into given char stream.
9873 *
9874 * Helper function.
9875 */
9876static char *coap_add_uint16(char *ptr, uint16_t val) {
9877 *ptr = val >> 8;
9878 ptr++;
9879 *ptr = val & 0x00FF;
9880 ptr++;
9881 return ptr;
9882}
9883
9884/*
9885 * Puts extended value of Opt Number/Length into given char stream.
9886 *
9887 * Helper function.
9888 */
9889static char *coap_add_opt_info(char *ptr, uint16_t val, size_t len) {
9890 if (len == sizeof(uint8_t)) {
9891 *ptr = val;
9892 ptr++;
9893 } else if (len == sizeof(uint16_t)) {
9894 ptr = coap_add_uint16(ptr, val);
9895 }
9896
9897 return ptr;
9898}
9899
9900/*
9901 * Verifies given mg_coap_message and calculates message size for it.
9902 *
9903 * Helper function.
9904 */
9906 size_t *len) {
9907 struct mg_coap_option *opt;
9909
9910 *len = 4; /* header */
9911 if (cm->msg_type > MG_COAP_MSG_MAX) {
9913 }
9914 if (cm->token.len > 8) {
9916 }
9917 if (cm->code_class > 7) {
9919 }
9920 if (cm->code_detail > 31) {
9922 }
9923
9924 *len += cm->token.len;
9925 if (cm->payload.len != 0) {
9926 *len += cm->payload.len + 1; /* ... + 1; add payload marker */
9927 }
9928
9929 opt = cm->options;
9930 prev_opt_number = 0;
9931 while (opt != NULL) {
9932 *len += 1; /* basic delta/length */
9933 *len += coap_get_ext_opt_size(opt->number);
9934 *len += coap_get_ext_opt_size((uint32_t) opt->value.len);
9935 /*
9936 * Current implementation performs check if
9937 * option_number > previous option_number and produces an error
9938 * TODO(alashkin): write design doc with limitations
9939 * May be resorting is more suitable solution.
9940 */
9941 if ((opt->next != NULL && opt->number > opt->next->number) ||
9942 opt->value.len > 0xFFFF + 269 ||
9943 opt->number - prev_opt_number > 0xFFFF + 269) {
9945 }
9946 *len += opt->value.len;
9947 opt = opt->next;
9948 }
9949
9950 return 0;
9951}
9952
9954 struct mg_coap_option *opt;
9956 size_t prev_io_len, packet_size;
9957 char *ptr;
9958
9960 if (res != 0) {
9961 return res;
9962 }
9963
9964 /* saving previous lenght to handle non-empty mbuf */
9965 prev_io_len = io->len;
9967 ptr = io->buf + prev_io_len;
9968
9969 /*
9970 * since cm is verified, it is possible to use bits shift operator
9971 * without additional zeroing of unused bits
9972 */
9973
9974 /* ver: 2 bits, msg_type: 2 bits, toklen: 4 bits */
9975 *ptr = (1 << 6) | (cm->msg_type << 4) | (cm->token.len);
9976 ptr++;
9977
9978 /* code class: 3 bits, code detail: 5 bits */
9979 *ptr = (cm->code_class << 5) | (cm->code_detail);
9980 ptr++;
9981
9982 ptr = coap_add_uint16(ptr, cm->msg_id);
9983
9984 if (cm->token.len != 0) {
9985 memcpy(ptr, cm->token.p, cm->token.len);
9986 ptr += cm->token.len;
9987 }
9988
9989 opt = cm->options;
9990 prev_opt_number = 0;
9991 while (opt != NULL) {
9994
9995 size_t opt_delta_len =
9997 size_t opt_lenght_len =
9999
10000 *ptr = (delta_base << 4) | length_base;
10001 ptr++;
10002
10005
10006 if (opt->value.len != 0) {
10007 memcpy(ptr, opt->value.p, opt->value.len);
10008 ptr += opt->value.len;
10009 }
10010
10011 prev_opt_number = opt->number;
10012 opt = opt->next;
10013 }
10014
10015 if (cm->payload.len != 0) {
10016 *ptr = -1;
10017 ptr++;
10018 memcpy(ptr, cm->payload.p, cm->payload.len);
10019 }
10020
10021 return 0;
10022}
10023
10025 struct mg_coap_message *cm) {
10026 struct mbuf packet_out;
10028
10029 mbuf_init(&packet_out, 0);
10031 if (compose_res != 0) {
10032 return compose_res; /* LCOV_EXCL_LINE */
10033 }
10034
10035 mg_send(nc, packet_out.buf, (int) packet_out.len);
10037
10038 return 0;
10039}
10040
10042 struct mg_coap_message cm;
10043 memset(&cm, 0, sizeof(cm));
10044 cm.msg_type = MG_COAP_MSG_ACK;
10045 cm.msg_id = msg_id;
10046
10047 return mg_coap_send_message(nc, &cm);
10048}
10049
10050static void coap_handler(struct mg_connection *nc, int ev, void *ev_data) {
10051 struct mbuf *io = &nc->recv_mbuf;
10052 struct mg_coap_message cm;
10054
10055 memset(&cm, 0, sizeof(cm));
10056
10057 nc->handler(nc, ev, ev_data);
10058
10059 switch (ev) {
10060 case MG_EV_RECV:
10062 if ((parse_res & MG_COAP_IGNORE) == 0) {
10063 if ((cm.flags & MG_COAP_NOT_ENOUGH_DATA) != 0) {
10064 /*
10065 * Since we support UDP only
10066 * MG_COAP_NOT_ENOUGH_DATA == MG_COAP_FORMAT_ERROR
10067 */
10068 cm.flags |= MG_COAP_FORMAT_ERROR; /* LCOV_EXCL_LINE */
10069 } /* LCOV_EXCL_LINE */
10070 nc->handler(nc, MG_COAP_EVENT_BASE + cm.msg_type, &cm);
10071 }
10072
10074 mbuf_remove(io, io->len);
10075 break;
10076 }
10077}
10078/*
10079 * Attach built-in CoAP event handler to the given connection.
10080 *
10081 * The user-defined event handler will receive following extra events:
10082 *
10083 * - MG_EV_COAP_CON
10084 * - MG_EV_COAP_NOC
10085 * - MG_EV_COAP_ACK
10086 * - MG_EV_COAP_RST
10087 */
10088int mg_set_protocol_coap(struct mg_connection *nc) {
10089 /* supports UDP only */
10090 if ((nc->flags & MG_F_UDP) == 0) {
10091 return -1;
10092 }
10093
10095
10096 return 0;
10097}
10098
10099#endif /* MG_DISABLE_COAP */
10100#ifdef MG_MODULE_LINES
10101#line 1 "./src/../../common/platforms/cc3200/cc3200_libc.c"
10102#endif
10103/*
10104 * Copyright (c) 2014-2016 Cesanta Software Limited
10105 * All rights reserved
10106 */
10107
10108#if CS_PLATFORM == CS_P_CC3200
10109
10110#include <stdio.h>
10111#include <string.h>
10112
10113#ifndef __TI_COMPILER_VERSION__
10114#include <reent.h>
10115#include <sys/stat.h>
10116#include <sys/time.h>
10117#include <unistd.h>
10118#endif
10119
10120#include <inc/hw_types.h>
10121#include <inc/hw_memmap.h>
10122#include <driverlib/prcm.h>
10123#include <driverlib/rom.h>
10124#include <driverlib/rom_map.h>
10125#include <driverlib/uart.h>
10126#include <driverlib/utils.h>
10127
10128#define CONSOLE_UART UARTA0_BASE
10129
10130#ifndef __TI_COMPILER_VERSION__
10131int _gettimeofday_r(struct _reent *r, struct timeval *tp, void *tzp) {
10132#else
10133int gettimeofday(struct timeval *tp, void *tzp) {
10134#endif
10135 unsigned long long r1 = 0, r2;
10136 /* Achieve two consecutive reads of the same value. */
10137 do {
10138 r2 = r1;
10140 } while (r1 != r2);
10141 /* This is a 32768 Hz counter. */
10142 tp->tv_sec = (r1 >> 15);
10143 /* 1/32768-th of a second is 30.517578125 microseconds, approx. 31,
10144 * but we round down so it doesn't overflow at 32767 */
10145 tp->tv_usec = (r1 & 0x7FFF) * 30;
10146 return 0;
10147}
10148
10149long int random(void) {
10150 return 42; /* FIXME */
10151}
10152
10153void fprint_str(FILE *fp, const char *str) {
10154 while (*str != '\0') {
10155 if (*str == '\n') MAP_UARTCharPut(CONSOLE_UART, '\r');
10157 }
10158}
10159
10160void _exit(int status) {
10161 fprint_str(stderr, "_exit\n");
10162 /* cause an unaligned access exception, that will drop you into gdb */
10163 *(int *) 1 = status;
10164 while (1)
10165 ; /* avoid gcc warning because stdlib abort() has noreturn attribute */
10166}
10167
10168void _not_implemented(const char *what) {
10169 fprint_str(stderr, what);
10170 fprint_str(stderr, " is not implemented\n");
10171 _exit(42);
10172}
10173
10174int _kill(int pid, int sig) {
10175 (void) pid;
10176 (void) sig;
10177 _not_implemented("_kill");
10178 return -1;
10179}
10180
10181int _getpid() {
10182 fprint_str(stderr, "_getpid is not implemented\n");
10183 return 42;
10184}
10185
10186int _isatty(int fd) {
10187 /* 0, 1 and 2 are TTYs. */
10188 return fd < 2;
10189}
10190
10191#endif /* CS_PLATFORM == CS_P_CC3200 */
10192#ifdef MG_MODULE_LINES
10193#line 1 "./src/../../common/platforms/msp432/msp432_libc.c"
10194#endif
10195/*
10196 * Copyright (c) 2014-2016 Cesanta Software Limited
10197 * All rights reserved
10198 */
10199
10200#if CS_PLATFORM == CS_P_MSP432
10201
10202#include <ti/sysbios/BIOS.h>
10203#include <ti/sysbios/knl/Clock.h>
10204
10205int gettimeofday(struct timeval *tp, void *tzp) {
10207 tp->tv_sec = ticks / 1000;
10208 tp->tv_usec = (ticks % 1000) * 1000;
10209 return 0;
10210}
10211
10212long int random(void) {
10213 return 42; /* FIXME */
10214}
10215
10216#endif /* CS_PLATFORM == CS_P_MSP432 */
10217#ifdef MG_MODULE_LINES
10218#line 1 "./src/../../common/platforms/simplelink/sl_fs_slfs.h"
10219#endif
10220/*
10221 * Copyright (c) 2014-2016 Cesanta Software Limited
10222 * All rights reserved
10223 */
10224
10225#ifndef CS_COMMON_PLATFORMS_SIMPLELINK_SL_FS_SLFS_H_
10226#define CS_COMMON_PLATFORMS_SIMPLELINK_SL_FS_SLFS_H_
10227
10228#if defined(MG_FS_SLFS)
10229
10230#include <stdio.h>
10231#ifndef __TI_COMPILER_VERSION__
10232#include <unistd.h>
10233#include <sys/stat.h>
10234#endif
10235
10236#define MAX_OPEN_SLFS_FILES 8
10237
10238/* Indirect libc interface - same functions, different names. */
10239int fs_slfs_open(const char *pathname, int flags, mode_t mode);
10240int fs_slfs_close(int fd);
10241ssize_t fs_slfs_read(int fd, void *buf, size_t count);
10242ssize_t fs_slfs_write(int fd, const void *buf, size_t count);
10243int fs_slfs_stat(const char *pathname, struct stat *s);
10244int fs_slfs_fstat(int fd, struct stat *s);
10245off_t fs_slfs_lseek(int fd, off_t offset, int whence);
10246int fs_slfs_unlink(const char *filename);
10247int fs_slfs_rename(const char *from, const char *to);
10248
10249#endif /* defined(MG_FS_SLFS) */
10250
10251#endif /* CS_COMMON_PLATFORMS_SIMPLELINK_SL_FS_SLFS_H_ */
10252#ifdef MG_MODULE_LINES
10253#line 1 "./src/../../common/platforms/simplelink/sl_fs_slfs.c"
10254#endif
10255/*
10256 * Copyright (c) 2014-2016 Cesanta Software Limited
10257 * All rights reserved
10258 */
10259
10260/* Standard libc interface to TI SimpleLink FS. */
10261
10262#if defined(MG_FS_SLFS) || defined(CC3200_FS_SLFS)
10263
10264/* Amalgamated: #include "common/platforms/simplelink/sl_fs_slfs.h" */
10265
10266#include <errno.h>
10267
10268#if CS_PLATFORM == CS_P_CC3200
10269#include <inc/hw_types.h>
10270#endif
10271#include <simplelink/include/simplelink.h>
10272#include <simplelink/include/fs.h>
10273
10274/* Amalgamated: #include "common/cs_dbg.h" */
10275
10276extern int set_errno(int e); /* From sl_fs.c */
10277
10278/*
10279 * With SLFS, you have to pre-declare max file size. Yes. Really.
10280 * 64K should be enough for everyone. Right?
10281 */
10282#ifndef FS_SLFS_MAX_FILE_SIZE
10283#define FS_SLFS_MAX_FILE_SIZE (64 * 1024)
10284#endif
10285
10286struct sl_fd_info {
10287 _i32 fh;
10288 _off_t pos;
10289 size_t size;
10290};
10291
10293
10294static int sl_fs_to_errno(_i32 r) {
10295 DBG(("SL error: %d", (int) r));
10296 switch (r) {
10297 case SL_FS_OK:
10298 return 0;
10300 return EEXIST;
10302 return EINVAL;
10305 return ENOSPC;
10307 return ENOMEM;
10309 return ENOENT;
10311 return ENOTSUP;
10312 }
10313 return ENXIO;
10314}
10315
10316int fs_slfs_open(const char *pathname, int flags, mode_t mode) {
10317 int fd;
10318 for (fd = 0; fd < MAX_OPEN_SLFS_FILES; fd++) {
10319 if (s_sl_fds[fd].fh <= 0) break;
10320 }
10321 if (fd >= MAX_OPEN_SLFS_FILES) return set_errno(ENOMEM);
10322 struct sl_fd_info *fi = &s_sl_fds[fd];
10323
10324 _u32 am = 0;
10325 fi->size = (size_t) -1;
10326 if (pathname[0] == '/') pathname++;
10327 int rw = (flags & 3);
10328 if (rw == O_RDONLY) {
10330 _i32 r = sl_FsGetInfo((const _u8 *) pathname, 0, &sl_fi);
10331 if (r == SL_FS_OK) {
10332 fi->size = sl_fi.FileLen;
10333 }
10334 am = FS_MODE_OPEN_READ;
10335 } else {
10336 if (!(flags & O_TRUNC) || (flags & O_APPEND)) {
10337 // FailFS files cannot be opened for append and will be truncated
10338 // when opened for write.
10339 return set_errno(ENOTSUP);
10340 }
10341 if (flags & O_CREAT) {
10343 } else {
10344 am = FS_MODE_OPEN_WRITE;
10345 }
10346 }
10347 _i32 r = sl_FsOpen((_u8 *) pathname, am, NULL, &fi->fh);
10348 DBG(("sl_FsOpen(%s, 0x%x) = %d, %d", pathname, (int) am, (int) r,
10349 (int) fi->fh));
10350 if (r == SL_FS_OK) {
10351 fi->pos = 0;
10352 r = fd;
10353 } else {
10354 fi->fh = -1;
10355 r = set_errno(sl_fs_to_errno(r));
10356 }
10357 return r;
10358}
10359
10360int fs_slfs_close(int fd) {
10361 struct sl_fd_info *fi = &s_sl_fds[fd];
10362 if (fi->fh <= 0) return set_errno(EBADF);
10363 _i32 r = sl_FsClose(fi->fh, NULL, NULL, 0);
10364 DBG(("sl_FsClose(%d) = %d", (int) fi->fh, (int) r));
10365 s_sl_fds[fd].fh = -1;
10366 return set_errno(sl_fs_to_errno(r));
10367}
10368
10369ssize_t fs_slfs_read(int fd, void *buf, size_t count) {
10370 struct sl_fd_info *fi = &s_sl_fds[fd];
10371 if (fi->fh <= 0) return set_errno(EBADF);
10372 /* Simulate EOF. sl_FsRead @ file_size return SL_FS_ERR_OFFSET_OUT_OF_RANGE.
10373 */
10374 if (fi->pos == fi->size) return 0;
10375 _i32 r = sl_FsRead(fi->fh, fi->pos, buf, count);
10376 DBG(("sl_FsRead(%d, %d, %d) = %d", (int) fi->fh, (int) fi->pos, (int) count,
10377 (int) r));
10378 if (r >= 0) {
10379 fi->pos += r;
10380 return r;
10381 }
10382 return set_errno(sl_fs_to_errno(r));
10383}
10384
10385ssize_t fs_slfs_write(int fd, const void *buf, size_t count) {
10386 struct sl_fd_info *fi = &s_sl_fds[fd];
10387 if (fi->fh <= 0) return set_errno(EBADF);
10388 _i32 r = sl_FsWrite(fi->fh, fi->pos, (_u8 *) buf, count);
10389 DBG(("sl_FsWrite(%d, %d, %d) = %d", (int) fi->fh, (int) fi->pos, (int) count,
10390 (int) r));
10391 if (r >= 0) {
10392 fi->pos += r;
10393 return r;
10394 }
10395 return set_errno(sl_fs_to_errno(r));
10396}
10397
10398int fs_slfs_stat(const char *pathname, struct stat *s) {
10400 _i32 r = sl_FsGetInfo((const _u8 *) pathname, 0, &sl_fi);
10401 if (r == SL_FS_OK) {
10402 s->st_mode = S_IFREG | 0666;
10403 s->st_nlink = 1;
10404 s->st_size = sl_fi.FileLen;
10405 return 0;
10406 }
10407 return set_errno(sl_fs_to_errno(r));
10408}
10409
10410int fs_slfs_fstat(int fd, struct stat *s) {
10411 struct sl_fd_info *fi = &s_sl_fds[fd];
10412 if (fi->fh <= 0) return set_errno(EBADF);
10413 s->st_mode = 0666;
10414 s->st_mode = S_IFREG | 0666;
10415 s->st_nlink = 1;
10416 s->st_size = fi->size;
10417 return 0;
10418}
10419
10420off_t fs_slfs_lseek(int fd, off_t offset, int whence) {
10421 if (s_sl_fds[fd].fh <= 0) return set_errno(EBADF);
10422 switch (whence) {
10423 case SEEK_SET:
10424 s_sl_fds[fd].pos = offset;
10425 break;
10426 case SEEK_CUR:
10427 s_sl_fds[fd].pos += offset;
10428 break;
10429 case SEEK_END:
10430 return set_errno(ENOTSUP);
10431 }
10432 return 0;
10433}
10434
10435int fs_slfs_unlink(const char *filename) {
10436 return set_errno(sl_fs_to_errno(sl_FsDel((const _u8 *) filename, 0)));
10437}
10438
10439int fs_slfs_rename(const char *from, const char *to) {
10440 return set_errno(ENOTSUP);
10441}
10442
10443#endif /* defined(MG_FS_SLFS) || defined(CC3200_FS_SLFS) */
10444#ifdef MG_MODULE_LINES
10445#line 1 "./src/../../common/platforms/simplelink/sl_fs.c"
10446#endif
10447/*
10448 * Copyright (c) 2014-2016 Cesanta Software Limited
10449 * All rights reserved
10450 */
10451
10452#if defined(MG_SOCKET_SIMPLELINK) && \
10453 (defined(MG_FS_SLFS) || defined(MG_FS_SPIFFS))
10454
10455#include <errno.h>
10456#include <stdio.h>
10457#include <stdlib.h>
10458#include <string.h>
10459#ifdef __TI_COMPILER_VERSION__
10460#include <file.h>
10461#endif
10462
10463#if CS_PLATFORM == CS_P_CC3200
10464#include <inc/hw_types.h>
10465#include <inc/hw_memmap.h>
10466#include <driverlib/rom.h>
10467#include <driverlib/rom_map.h>
10468#include <driverlib/uart.h>
10469#endif
10470
10471/* Amalgamated: #include "common/cs_dbg.h" */
10472/* Amalgamated: #include "common/platform.h" */
10473
10474#ifdef CC3200_FS_SPIFFS
10475/* Amalgamated: #include "cc3200_fs_spiffs.h" */
10476#endif
10477
10478#ifdef MG_FS_SLFS
10479/* Amalgamated: #include "sl_fs_slfs.h" */
10480#endif
10481
10482#define NUM_SYS_FDS 3
10483#define SPIFFS_FD_BASE 10
10484#define SLFS_FD_BASE 100
10485
10486#define CONSOLE_UART UARTA0_BASE
10487
10488int set_errno(int e) {
10489 errno = e;
10490 return -e;
10491}
10492
10493static int is_sl_fname(const char *fname) {
10494 return strncmp(fname, "SL:", 3) == 0;
10495}
10496
10497static const char *sl_fname(const char *fname) {
10498 return fname + 3;
10499}
10500
10501static const char *drop_dir(const char *fname) {
10502 if (*fname == '.') fname++;
10503 if (*fname == '/') fname++;
10504 return fname;
10505}
10506
10507enum fd_type {
10508 FD_INVALID,
10509 FD_SYS,
10510#ifdef CC3200_FS_SPIFFS
10511 FD_SPIFFS,
10512#endif
10513#ifdef MG_FS_SLFS
10514 FD_SLFS
10515#endif
10516};
10517static int fd_type(int fd) {
10518 if (fd >= 0 && fd < NUM_SYS_FDS) return FD_SYS;
10519#ifdef CC3200_FS_SPIFFS
10521 return FD_SPIFFS;
10522 }
10523#endif
10524#ifdef MG_FS_SLFS
10525 if (fd >= SLFS_FD_BASE && fd < SLFS_FD_BASE + MAX_OPEN_SLFS_FILES) {
10526 return FD_SLFS;
10527 }
10528#endif
10529 return FD_INVALID;
10530}
10531
10532int _open(const char *pathname, int flags, mode_t mode) {
10533 int fd = -1;
10535 if (is_sl_fname(pathname)) {
10536#ifdef MG_FS_SLFS
10537 fd = fs_slfs_open(sl_fname(pathname), flags, mode);
10538 if (fd >= 0) fd += SLFS_FD_BASE;
10539#endif
10540 } else {
10541#ifdef CC3200_FS_SPIFFS
10542 fd = fs_spiffs_open(pathname, flags, mode);
10543 if (fd >= 0) fd += SPIFFS_FD_BASE;
10544#endif
10545 }
10546 DBG(("open(%s, 0x%x) = %d", pathname, flags, fd));
10547 return fd;
10548}
10549
10550int _stat(const char *pathname, struct stat *st) {
10551 int res = -1;
10552 const char *fname = pathname;
10553 int is_sl = is_sl_fname(pathname);
10554 if (is_sl) fname = sl_fname(pathname);
10555 fname = drop_dir(fname);
10556 memset(st, 0, sizeof(*st));
10557 /* Simulate statting the root directory. */
10558 if (strcmp(fname, "") == 0) {
10559 st->st_ino = 0;
10560 st->st_mode = S_IFDIR | 0777;
10561 st->st_nlink = 1;
10562 st->st_size = 0;
10563 return 0;
10564 }
10565 if (is_sl) {
10566#ifdef MG_FS_SLFS
10568#endif
10569 } else {
10570#ifdef CC3200_FS_SPIFFS
10572#endif
10573 }
10574 DBG(("stat(%s) = %d; fname = %s", pathname, res, fname));
10575 return res;
10576}
10577
10578int _close(int fd) {
10579 int r = -1;
10580 switch (fd_type(fd)) {
10581 case FD_INVALID:
10582 r = set_errno(EBADF);
10583 break;
10584 case FD_SYS:
10585 r = set_errno(EACCES);
10586 break;
10587#ifdef CC3200_FS_SPIFFS
10588 case FD_SPIFFS:
10590 break;
10591#endif
10592#ifdef MG_FS_SLFS
10593 case FD_SLFS:
10594 r = fs_slfs_close(fd - SLFS_FD_BASE);
10595 break;
10596#endif
10597 }
10598 DBG(("close(%d) = %d", fd, r));
10599 return r;
10600}
10601
10602off_t _lseek(int fd, off_t offset, int whence) {
10603 int r = -1;
10604 switch (fd_type(fd)) {
10605 case FD_INVALID:
10606 r = set_errno(EBADF);
10607 break;
10608 case FD_SYS:
10609 r = set_errno(ESPIPE);
10610 break;
10611#ifdef CC3200_FS_SPIFFS
10612 case FD_SPIFFS:
10614 break;
10615#endif
10616#ifdef MG_FS_SLFS
10617 case FD_SLFS:
10619 break;
10620#endif
10621 }
10622 DBG(("lseek(%d, %d, %d) = %d", fd, (int) offset, whence, r));
10623 return r;
10624}
10625
10626int _fstat(int fd, struct stat *s) {
10627 int r = -1;
10628 memset(s, 0, sizeof(*s));
10629 switch (fd_type(fd)) {
10630 case FD_INVALID:
10631 r = set_errno(EBADF);
10632 break;
10633 case FD_SYS: {
10634 /* Create barely passable stats for STD{IN,OUT,ERR}. */
10635 memset(s, 0, sizeof(*s));
10636 s->st_ino = fd;
10637 s->st_mode = S_IFCHR | 0666;
10638 r = 0;
10639 break;
10640 }
10641#ifdef CC3200_FS_SPIFFS
10642 case FD_SPIFFS:
10643 r = fs_spiffs_fstat(fd - SPIFFS_FD_BASE, s);
10644 break;
10645#endif
10646#ifdef MG_FS_SLFS
10647 case FD_SLFS:
10648 r = fs_slfs_fstat(fd - SLFS_FD_BASE, s);
10649 break;
10650#endif
10651 }
10652 DBG(("fstat(%d) = %d", fd, r));
10653 return r;
10654}
10655
10656ssize_t _read(int fd, void *buf, size_t count) {
10657 int r = -1;
10658 switch (fd_type(fd)) {
10659 case FD_INVALID:
10660 r = set_errno(EBADF);
10661 break;
10662 case FD_SYS: {
10663 if (fd != 0) {
10664 r = set_errno(EACCES);
10665 break;
10666 }
10667 /* Should we allow reading from stdin = uart? */
10668 r = set_errno(ENOTSUP);
10669 break;
10670 }
10671#ifdef CC3200_FS_SPIFFS
10672 case FD_SPIFFS:
10673 r = fs_spiffs_read(fd - SPIFFS_FD_BASE, buf, count);
10674 break;
10675#endif
10676#ifdef MG_FS_SLFS
10677 case FD_SLFS:
10678 r = fs_slfs_read(fd - SLFS_FD_BASE, buf, count);
10679 break;
10680#endif
10681 }
10682 DBG(("read(%d, %u) = %d", fd, count, r));
10683 return r;
10684}
10685
10686ssize_t _write(int fd, const void *buf, size_t count) {
10687 int r = -1;
10688 size_t i = 0;
10689 switch (fd_type(fd)) {
10690 case FD_INVALID:
10691 r = set_errno(EBADF);
10692 break;
10693 case FD_SYS: {
10694 if (fd == 0) {
10695 r = set_errno(EACCES);
10696 break;
10697 }
10698#if CS_PLATFORM == CS_P_CC3200
10699 for (i = 0; i < count; i++) {
10700 const char c = ((const char *) buf)[i];
10701 if (c == '\n') MAP_UARTCharPut(CONSOLE_UART, '\r');
10703 }
10704#else
10705 (void) i;
10706#endif
10707 r = count;
10708 break;
10709 }
10710#ifdef CC3200_FS_SPIFFS
10711 case FD_SPIFFS:
10712 r = fs_spiffs_write(fd - SPIFFS_FD_BASE, buf, count);
10713 break;
10714#endif
10715#ifdef MG_FS_SLFS
10716 case FD_SLFS:
10717 r = fs_slfs_write(fd - SLFS_FD_BASE, buf, count);
10718 break;
10719#endif
10720 }
10721 return r;
10722}
10723
10724int _rename(const char *from, const char *to) {
10725 int r = -1;
10726 from = drop_dir(from);
10727 to = drop_dir(to);
10728 if (is_sl_fname(from) || is_sl_fname(to)) {
10729#ifdef MG_FS_SLFS
10731#endif
10732 } else {
10733#ifdef CC3200_FS_SPIFFS
10734 r = fs_spiffs_rename(from, to);
10735#endif
10736 }
10737 DBG(("rename(%s, %s) = %d", from, to, r));
10738 return r;
10739}
10740
10741int _link(const char *from, const char *to) {
10742 DBG(("link(%s, %s)", from, to));
10743 return set_errno(ENOTSUP);
10744}
10745
10746int _unlink(const char *filename) {
10747 int r = -1;
10748 filename = drop_dir(filename);
10749 if (is_sl_fname(filename)) {
10750#ifdef MG_FS_SLFS
10751 r = fs_slfs_unlink(sl_fname(filename));
10752#endif
10753 } else {
10754#ifdef CC3200_FS_SPIFFS
10755 r = fs_spiffs_unlink(filename);
10756#endif
10757 }
10758 DBG(("unlink(%s) = %d", filename, r));
10759 return r;
10760}
10761
10762#ifdef CC3200_FS_SPIFFS /* FailFS does not support listing files. */
10763DIR *opendir(const char *dir_name) {
10764 DIR *r = NULL;
10765 if (is_sl_fname(dir_name)) {
10766 r = NULL;
10768 } else {
10770 }
10771 DBG(("opendir(%s) = %p", dir_name, r));
10772 return r;
10773}
10774
10775struct dirent *readdir(DIR *dir) {
10776 struct dirent *res = fs_spiffs_readdir(dir);
10777 DBG(("readdir(%p) = %p", dir, res));
10778 return res;
10779}
10780
10781int closedir(DIR *dir) {
10782 int res = fs_spiffs_closedir(dir);
10783 DBG(("closedir(%p) = %d", dir, res));
10784 return res;
10785}
10786
10787int rmdir(const char *path) {
10788 return fs_spiffs_rmdir(path);
10789}
10790
10791int mkdir(const char *path, mode_t mode) {
10792 (void) path;
10793 (void) mode;
10794 /* for spiffs supports only root dir, which comes from mongoose as '.' */
10795 return (strlen(path) == 1 && *path == '.') ? 0 : ENOTDIR;
10796}
10797#endif
10798
10799int sl_fs_init() {
10800 int ret = 1;
10801#ifdef __TI_COMPILER_VERSION__
10802#ifdef MG_FS_SLFS
10805 fs_slfs_rename) == 0);
10806#endif
10807#endif
10808 return ret;
10809}
10810
10811#endif /* defined(MG_SOCKET_SIMPLELINK) && (defined(MG_FS_SLFS) || \
10812 defined(MG_FS_SPIFFS)) */
10813#ifdef MG_MODULE_LINES
10814#line 1 "./src/../../common/platforms/simplelink/sl_socket.c"
10815#endif
10816/*
10817 * Copyright (c) 2014-2016 Cesanta Software Limited
10818 * All rights reserved
10819 */
10820
10821#ifdef MG_SOCKET_SIMPLELINK
10822
10823#include <errno.h>
10824#include <stdio.h>
10825
10826/* Amalgamated: #include "common/platform.h" */
10827
10828#include <simplelink/include/netapp.h>
10829
10830const char *inet_ntop(int af, const void *src, char *dst, socklen_t size) {
10831 int res;
10832 struct in_addr *in = (struct in_addr *) src;
10833 if (af != AF_INET) {
10835 return NULL;
10836 }
10837 res = snprintf(dst, size, "%lu.%lu.%lu.%lu", SL_IPV4_BYTE(in->s_addr, 0),
10838 SL_IPV4_BYTE(in->s_addr, 1), SL_IPV4_BYTE(in->s_addr, 2),
10839 SL_IPV4_BYTE(in->s_addr, 3));
10840 return res > 0 ? dst : NULL;
10841}
10842
10843char *inet_ntoa(struct in_addr n) {
10844 static char a[16];
10845 return (char *) inet_ntop(AF_INET, &n, a, sizeof(n));
10846}
10847
10848int inet_pton(int af, const char *src, void *dst) {
10849 uint32_t a0, a1, a2, a3;
10850 uint8_t *db = (uint8_t *) dst;
10851 if (af != AF_INET) {
10853 return 0;
10854 }
10855 if (sscanf(src, "%lu.%lu.%lu.%lu", &a0, &a1, &a2, &a3) != 4) {
10856 return 0;
10857 }
10858 *db = a3;
10859 *(db + 1) = a2;
10860 *(db + 2) = a1;
10861 *(db + 3) = a0;
10862 return 1;
10863}
10864
10865#endif /* CS_COMMON_PLATFORMS_SIMPLELINK_SL_SOCKET_C_ */
10866#ifdef MG_MODULE_LINES
10867#line 1 "./src/../../common/platforms/simplelink/sl_mg_task.c"
10868#endif
10869#if defined(MG_SOCKET_SIMPLELINK)
10870
10871/* Amalgamated: #include "mg_task.h" */
10872
10873#include <oslib/osi.h>
10874
10875enum mg_q_msg_type {
10877};
10878struct mg_q_msg {
10879 enum mg_q_msg_type type;
10880 void (*cb)(struct mg_mgr *mgr, void *arg);
10881 void *arg;
10882};
10883static OsiMsgQ_t s_mg_q;
10884static void mg_task(void *arg);
10885
10887 if (osi_MsgQCreate(&s_mg_q, "MG", sizeof(struct mg_q_msg), 16) != OSI_OK) {
10888 return false;
10889 }
10890 if (osi_TaskCreate(mg_task, (const signed char *) "MG", stack_size,
10891 (void *) mg_init, priority, NULL) != OSI_OK) {
10892 return false;
10893 }
10894 return true;
10895}
10896
10897static void mg_task(void *arg) {
10898 struct mg_mgr mgr;
10900 mg_mgr_init(&mgr, NULL);
10901 mg_init(&mgr);
10902 while (1) {
10903 struct mg_q_msg msg;
10904 mg_mgr_poll(&mgr, 1);
10905 if (osi_MsgQRead(&s_mg_q, &msg, 1) != OSI_OK) continue;
10906 switch (msg.type) {
10907 case MG_Q_MSG_CB: {
10908 msg.cb(&mgr, msg.arg);
10909 }
10910 }
10911 }
10912}
10913
10914void mg_run_in_task(void (*cb)(struct mg_mgr *mgr, void *arg), void *cb_arg) {
10915 struct mg_q_msg msg = {MG_Q_MSG_CB, cb, cb_arg};
10917}
10918
10919#endif /* defined(MG_SOCKET_SIMPLELINK) */
#define LONG
Definition crc32c.cxx:230
unsigned int DWORD
Definition mcstd.h:51
int mg_start_thread(mg_thread_func_t f, void *p)
int mg_url_decode(const char *src, int src_len, char *dst, int dst_len, int is_form_url_encoded)
int(* mg_event_handler_t)(struct mg_event *event)
Definition mongoose4.h:70
time_t mg_mgr_poll(struct mg_mgr *mgr, int timeout_ms)
struct mg_str message
Definition mongoose6.h:2068
void mg_mqtt_ping(struct mg_connection *nc)
void MD5_Init(MD5_CTX *ctx)
void mg_set_protocol_mqtt(struct mg_connection *nc)
#define JSON_STRING_INCOMPLETE
Definition mongoose6.h:1080
void mg_mgr_free(struct mg_mgr *m)
const char * hexdump_file
Definition mongoose6.h:1232
int mg_resolve_from_hosts_file(const char *name, union socket_address *usa)
void cs_base64_update(struct cs_base64_ctx *ctx, const char *str, size_t len)
#define LOG(l, x)
Definition mongoose6.h:765
void cs_to_hex(char *to, const unsigned char *p, size_t len)
#define WEBSOCKET_DONT_FIN
Definition mongoose6.h:2365
#define MG_MK_STR(str_literal)
Definition mongoose6.h:2006
void mg_send_dns_query(struct mg_connection *nc, const char *name, int query_type)
#define WEBSOCKET_OP_PING
Definition mongoose6.h:2350
char * cs_md5(char buf[33],...)
struct json_token * message
Definition mongoose6.h:2731
void mg_mqtt_disconnect(struct mg_connection *nc)
#define MG_MQTT_CMD_PUBREC
Definition mongoose6.h:2904
void mg_mqtt_publish(struct mg_connection *nc, const char *topic, uint16_t message_id, int flags, const void *data, size_t len)
void mg_if_get_conn_addr(struct mg_connection *nc, int remote, union socket_address *sa)
#define MG_MQTT_CMD_UNSUBACK
Definition mongoose6.h:2910
void * user_data
Definition mongoose6.h:1265
struct mg_str header_names[MG_MAX_HTTP_HEADERS]
Definition mongoose6.h:2090
int mg_avprintf(char **buf, size_t size, const char *fmt, va_list ap)
struct mg_str payload
Definition mongoose6.h:2878
int c_vsnprintf(char *buf, size_t buf_size, const char *fmt, va_list ap)
void mg_if_destroy_conn(struct mg_connection *nc)
#define MG_MAX_HTTP_SEND_MBUF
Definition mongoose6.h:2047
#define MG_MAX_DNS_ANSWERS
Definition mongoose6.h:3169
int mg_dns_copy_body(struct mbuf *io, struct mg_dns_message *msg)
#define MG_EV_WEBSOCKET_FRAME
Definition mongoose6.h:2121
int mg_stat(const char *path, cs_stat_t *st)
#define JSON_RPC_INVALID_PARAMS_ERROR
Definition mongoose6.h:2809
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)
#define MG_EV_WEBSOCKET_HANDSHAKE_DONE
Definition mongoose6.h:2120
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)
mg_event_handler_t handler
Definition mongoose6.h:1264
struct mg_connection * active_connections
Definition mongoose6.h:1231
void mg_mqtt_connack(struct mg_connection *nc, uint8_t return_code)
cs_log_level
Definition mongoose6.h:741
#define MG_MQTT_CMD_PUBACK
Definition mongoose6.h:2903
int mg_dns_encode_record(struct mbuf *io, struct mg_dns_resource_record *rr, const char *name, size_t nlen, const void *rdata, size_t rlen)
void mg_mqtt_pong(struct mg_connection *nc)
struct mg_connection ** dns_conn
Definition mongoose6.h:3426
int mg_is_big_endian(void)
#define MG_F_CLOSE_IMMEDIATELY
Definition mongoose6.h:1289
size_t mbuf_insert(struct mbuf *a, size_t off, const void *buf, size_t len)
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)
const char * ptr
Definition mongoose6.h:1072
#define MG_SOCK_STRINGIFY_PORT
Definition mongoose6.h:1905
void mbuf_remove(struct mbuf *mb, size_t n)
void mg_mgr_init(struct mg_mgr *m, void *user_data)
int mg_dns_insert_header(struct mbuf *io, size_t pos, struct mg_dns_message *msg)
void mg_send_head(struct mg_connection *c, int status_code, int64_t content_length, const char *extra_headers)
void mg_mqtt_pubcomp(struct mg_connection *nc, uint16_t message_id)
void mg_if_tcp_send(struct mg_connection *nc, const void *buf, size_t len)
void(* proto_data_destructor)(void *proto_data)
Definition mongoose6.h:1263
struct mg_connection * mg_next(struct mg_mgr *s, struct mg_connection *conn)
#define DBG(x)
Definition mongoose6.h:773
int mg_resolve_async(struct mg_mgr *mgr, const char *name, int query, mg_resolve_callback_t cb, void *data)
#define MG_EV_RECV
Definition mongoose6.h:1222
uint32_t state[5]
Definition mongoose6.h:899
void mg_if_connect_udp(struct mg_connection *nc)
void mg_if_accept_tcp_cb(struct mg_connection *nc, union socket_address *sa, size_t sa_len)
int mg_normalize_uri_path(const struct mg_str *in, struct mg_str *out)
#define WEBSOCKET_OP_CLOSE
Definition mongoose6.h:2349
const char * c_strnstr(const char *s, const char *find, size_t slen)
int mg_vprintf(struct mg_connection *nc, const char *fmt, va_list ap)
const char * mg_set_ssl(struct mg_connection *nc, const char *cert, const char *ca_cert)
void mg_broadcast(struct mg_mgr *mgr, mg_event_handler_t cb, void *data, size_t len)
#define MG_DNS_AAAA_RECORD
Definition mongoose6.h:3165
int json_emit_unquoted_str(char *buf, int buf_len, const char *str, int len)
void mg_send_response_line(struct mg_connection *nc, int status_code, const char *extra_headers)
#define MG_MQTT_CMD_CONNACK
Definition mongoose6.h:2901
void mg_send_mqtt_handshake(struct mg_connection *nc, const char *client_id)
#define MG_VPRINTF_BUFFER_SIZE
Definition mongoose6.h:1179
struct mg_str header_values[MG_MAX_HTTP_HEADERS]
Definition mongoose6.h:2091
void mg_if_recv_udp_cb(struct mg_connection *nc, void *buf, int len, union socket_address *sa, size_t sa_len)
void mbuf_free(struct mbuf *mbuf)
union socket_address sa
Definition mongoose6.h:1253
#define MG_EV_WEBSOCKET_CONTROL_FRAME
Definition mongoose6.h:2122
void mg_serve_http(struct mg_connection *nc, struct http_message *hm, struct mg_serve_http_opts opts)
#define MG_F_WANT_READ
Definition mongoose6.h:1283
#define MG_MAX_CGI_ENVIR_VARS
Definition mongoose6.h:2059
void * user_data
Definition mongoose6.h:984
#define MG_SOCK_STRINGIFY_REMOTE
Definition mongoose6.h:1906
void mg_if_poll(struct mg_connection *nc, time_t now)
int mg_open(const char *path, int flag, int mode)
struct json_token * method
Definition mongoose6.h:2733
double mg_set_timer(struct mg_connection *c, double timestamp)
struct mg_connection * mg_connect(struct mg_mgr *mgr, const char *address, mg_event_handler_t callback)
void mg_conn_addr_to_str(struct mg_connection *nc, char *buf, size_t len, int flags)
#define MAX_PATH_SIZE
Definition mongoose6.h:1804
#define MG_MQTT_GET_QOS(flags)
Definition mongoose6.h:2936
#define MG_EV_CONNECT
Definition mongoose6.h:1221
int mg_parse_http(const char *s, int n, struct http_message *hm, int is_req)
int mg_match_prefix_n(const struct mg_str pattern, const struct mg_str str)
#define MG_EV_SSI_CALL
Definition mongoose6.h:2117
mg_resolve_err
Definition mongoose6.h:3409
#define MG_SEND_FUNC(s, b, l, f)
Definition mongoose6.h:1187
size_t len
Definition mongoose6.h:835
void * proto_data
Definition mongoose6.h:1262
#define MG_MAX_PATH
Definition mongoose6.h:2042
union mg_connection::@11 priv_1
void mbuf_resize(struct mbuf *a, size_t new_size)
size_t len
Definition mongoose6.h:1207
void mg_if_recv_tcp_cb(struct mg_connection *nc, void *buf, int len)
void mg_printf_html_escape(struct mg_connection *nc, const char *fmt,...)
#define MG_F_LISTENING
Definition mongoose6.h:1278
unsigned char buffer[64]
Definition mongoose6.h:901
cs_base64_putc_t b64_putc
Definition mongoose6.h:981
void mg_if_sent_cb(struct mg_connection *nc, int num_sent)
#define MG_DNS_CNAME_RECORD
Definition mongoose6.h:3164
struct mg_connection * mg_if_accept_new_conn(struct mg_connection *lc)
#define MG_CGI_ENVIRONMENT_SIZE
Definition mongoose6.h:2055
int mg_casecmp(const char *s1, const char *s2)
int mg_if_create_conn(struct mg_connection *nc)
void mg_send(struct mg_connection *nc, const void *buf, int len)
int mg_socketpair(sock_t sp[2], int sock_type)
#define MG_MQTT_CMD_PUBREL
Definition mongoose6.h:2905
int mg_rpc_create_error(char *buf, int len, struct mg_rpc_request *req, int code, const char *message, const char *fmt,...)
struct mg_connection * next
Definition mongoose6.h:1247
void mg_send_http_chunk(struct mg_connection *nc, const char *buf, size_t len)
int json_emit_double(char *buf, int buf_len, double value)
#define MG_MQTT_CMD_PINGREQ
Definition mongoose6.h:2911
unsigned char in[64]
Definition mongoose6.h:933
#define MG_EV_MQTT_CONNACK_SERVER_UNAVAILABLE
Definition mongoose6.h:2953
#define MG_ENV_EXPORT_TO_CGI
Definition mongoose6.h:2063
void mg_hexdump_connection(struct mg_connection *nc, const char *path, const void *buf, int num_bytes, int ev)
struct mbuf send_mbuf
Definition mongoose6.h:1256
#define MG_F_WEBSOCKET_NO_DEFRAG
Definition mongoose6.h:1290
#define MG_DNS_A_RECORD
Definition mongoose6.h:3163
#define ARRAY_SIZE(array)
Definition mongoose6.h:119
struct mbuf recv_mbuf
Definition mongoose6.h:1255
void mg_if_connect_cb(struct mg_connection *nc, int err)
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)
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)
#define MG_EV_MQTT_CONNECT
Definition mongoose6.h:2917
#define MG_EV_POLL
Definition mongoose6.h:1219
int mg_if_listen_udp(struct mg_connection *nc, union socket_address *sa)
void mg_sock_set(struct mg_connection *nc, sock_t sock)
#define MG_MQTT_QOS(qos)
Definition mongoose6.h:2935
#define MG_F_UDP
Definition mongoose6.h:1279
void mg_send_websocket_handshake2(struct mg_connection *nc, const char *path, const char *host, const char *protocol, const char *extra_headers)
void mg_if_udp_send(struct mg_connection *nc, const void *buf, size_t len)
int(* mg_rpc_handler_t)(char *buf, int len, struct mg_rpc_request *req)
Definition mongoose6.h:2830
void cs_base64_finish(struct cs_base64_ctx *ctx)
sock_t ctl[2]
Definition mongoose6.h:1234
#define MG_F_USER_1
Definition mongoose6.h:1293
int mg_if_listen_tcp(struct mg_connection *nc, union socket_address *sa)
struct mg_connection * mg_connect_opt(struct mg_mgr *mgr, const char *address, mg_event_handler_t callback, struct mg_connect_opts opts)
double mg_time()
double ev_timer_time
Definition mongoose6.h:1260
void mg_register_http_endpoint(struct mg_connection *nc, const char *uri_path, mg_event_handler_t handler)
void mg_sock_to_str(sock_t sock, char *buf, size_t len, int flags)
#define MG_MQTT_CMD_PUBCOMP
Definition mongoose6.h:2906
void mg_mqtt_puback(struct mg_connection *nc, uint16_t message_id)
struct json_token * id
Definition mongoose6.h:2732
uint16_t flags
Definition mongoose6.h:3192
enum json_type type
Definition mongoose6.h:1075
void mg_printf_websocket_frame(struct mg_connection *nc, int op, const char *fmt,...)
void * SSL_CTX
Definition mongoose6.h:1175
#define MG_MQTT_EVENT_BASE
Definition mongoose6.h:2916
#define MG_MQTT_CMD_PUBLISH
Definition mongoose6.h:2902
#define MBUF_SIZE_MULTIPLIER
Definition mongoose6.h:829
struct mg_dns_resource_record questions[MG_MAX_DNS_QUESTIONS]
Definition mongoose6.h:3196
#define MG_EV_HTTP_CHUNK
Definition mongoose6.h:2116
void cs_log_set_level(enum cs_log_level level)
struct sockaddr sin6
Definition mongoose6.h:1200
void MD5_Update(MD5_CTX *ctx, const unsigned char *buf, size_t len)
#define JSON_RPC_SERVER_ERROR
Definition mongoose6.h:2811
int parse_json(const char *s, int s_len, struct json_token *arr, int arr_len)
int cs_base64_decode(const unsigned char *s, int len, char *dst)
#define MG_SOCK_STRINGIFY_IP
Definition mongoose6.h:1904
uint32_t count[2]
Definition mongoose6.h:900
size_t c_strnlen(const char *s, size_t maxlen)
int mg_match_prefix(const char *pattern, int pattern_len, const char *str)
mg_event_handler_t f
Definition mongoose6.h:1272
#define MG_MQTT_CMD_PINGRESP
Definition mongoose6.h:2912
#define MG_EV_TIMER
Definition mongoose6.h:1225
#define MG_MQTT_CMD_CONNECT
Definition mongoose6.h:2900
void cs_hmac_sha1(const unsigned char *key, size_t keylen, const unsigned char *data, size_t datalen, unsigned char out[20])
void mg_set_protocol_http_websocket(struct mg_connection *nc)
void mg_send_websocket_framev(struct mg_connection *nc, int op, const struct mg_str *strv, int strvcnt)
void cs_fprint_base64(FILE *f, const unsigned char *src, int src_len)
int mg_hexdump(const void *buf, int len, char *dst, int dst_len)
#define MG_DNS_MESSAGE
Definition mongoose6.h:3171
int mg_vcasecmp(const struct mg_str *str1, const char *str2)
#define MG_WEBSOCKET_PING_INTERVAL_SECONDS
Definition mongoose6.h:2051
#define MG_EV_SEND
Definition mongoose6.h:1223
unsigned long flags
Definition mongoose6.h:1276
int mg_base64_decode(const unsigned char *s, int len, char *dst)
struct mg_connection * mg_connect_ws(struct mg_mgr *mgr, mg_event_handler_t ev_handler, const char *url, const char *protocol, const char *extra_headers)
struct mg_connection * listener
Definition mongoose6.h:1248
struct mg_connection * prev
Definition mongoose6.h:1247
#define MG_VERSION
Definition mongoose6.h:26
void mg_mqtt_pubrec(struct mg_connection *nc, uint16_t message_id)
void * user_data
Definition mongoose6.h:1236
time_t last_io_time
Definition mongoose6.h:1259
void mg_set_close_on_exec(sock_t sock)
void cs_log_print_prefix(const char *func)
size_t recv_mbuf_limit
Definition mongoose6.h:1254
double cs_time()
void(* cs_base64_putc_t)(char, void *)
Definition mongoose6.h:977
struct mg_connection * mg_connect_ws_opt(struct mg_mgr *mgr, mg_event_handler_t ev_handler, struct mg_connect_opts opts, const char *url, const char *protocol, const char *extra_headers)
#define MG_F_DELETE_CHUNK
Definition mongoose6.h:1291
struct mg_str body
Definition mongoose6.h:2094
int mg_resolve(const char *host, char *buf, size_t n)
#define MG_EV_HTTP_REPLY
Definition mongoose6.h:2115
void mg_set_protocol_dns(struct mg_connection *nc)
const char * mg_skip(const char *s, const char *end, const char *delims, struct mg_str *v)
int json_emit(char *buf, int buf_len, const char *fmt,...)
void mg_mqtt_suback(struct mg_connection *nc, uint8_t *qoss, size_t qoss_len, uint16_t message_id)
int json_emit_va(char *s, int s_len, const char *fmt, va_list ap)
struct sockaddr sa
Definition mongoose6.h:1195
#define MG_MAX_HTTP_REQUEST_SIZE
Definition mongoose6.h:2035
#define MG_MQTT_CMD_UNSUBSCRIBE
Definition mongoose6.h:2909
struct mg_mgr * mgr
Definition mongoose6.h:1249
int mg_parse_dns(const char *buf, int len, struct mg_dns_message *msg)
int c_snprintf(char *buf, size_t buf_size, const char *fmt,...)
char * buf
Definition mongoose6.h:834
void mg_mqtt_unsuback(struct mg_connection *nc, uint16_t message_id)
void cs_base64_init(struct cs_base64_ctx *ctx, cs_base64_putc_t b64_putc, void *user_data)
struct mg_dns_resource_record * mg_dns_next_record(struct mg_dns_message *msg, int query, struct mg_dns_resource_record *prev)
#define MG_F_RESOLVING
Definition mongoose6.h:1280
void mbuf_init(struct mbuf *mbuf, size_t initial_size)
struct mg_str rdata
Definition mongoose6.h:3186
struct mg_connection * mg_bind_opt(struct mg_mgr *mgr, const char *address, mg_event_handler_t callback, struct mg_bind_opts opts)
void cs_log_printf(const char *fmt,...)
void mg_send_mqtt_handshake_opt(struct mg_connection *nc, const char *client_id, struct mg_send_mqtt_handshake_opts opts)
#define JSON_RPC_PARSE_ERROR
Definition mongoose6.h:2806
size_t mbuf_append(struct mbuf *a, const void *buf, size_t len)
int json_emit_quoted_str(char *s, int s_len, const char *str, int len)
json_type
Definition mongoose6.h:1060
unsigned int flags
Definition mongoose6.h:1367
#define MG_F_SSL_HANDSHAKE_DONE
Definition mongoose6.h:1282
void mg_sock_addr_to_str(const union socket_address *sa, char *buf, size_t len, int flags)
uint32_t bits[2]
Definition mongoose6.h:932
void mg_base64_encode(const unsigned char *src, int src_len, char *dst)
#define JSON_TOKEN_ARRAY_TOO_SMALL
Definition mongoose6.h:1081
void mg_send_websocket_frame(struct mg_connection *nc, int op, const void *data, size_t len)
#define MG_EV_MQTT_PUBLISH
Definition mongoose6.h:2919
struct mg_connection * mg_bind(struct mg_mgr *srv, const char *address, mg_event_handler_t event_handler)
void(* mg_resolve_callback_t)(struct mg_dns_message *dns_message, void *user_data, enum mg_resolve_err)
Definition mongoose6.h:3416
#define MG_F_IS_WEBSOCKET
Definition mongoose6.h:1285
#define MG_RECV_FUNC(s, b, l, f)
Definition mongoose6.h:1186
struct json_token * find_json_token(struct json_token *toks, const char *path)
struct json_token * parse_json2(const char *s, int s_len)
void cs_sha1_final(unsigned char digest[20], cs_sha1_ctx *context)
int mg_http_parse_header(struct mg_str *hdr, const char *var_name, char *buf, size_t buf_size)
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)
struct mg_str mg_mk_str(const char *s)
int mg_rpc_create_request(char *buf, int len, const char *method, const char *id, const char *params_fmt,...)
void cs_base64_encode(const unsigned char *src, int src_len, char *dst)
int mg_rpc_create_std_error(char *buf, int len, struct mg_rpc_request *req, int code)
int mg_get_http_var(const struct mg_str *buf, const char *name, char *dst, size_t dst_len)
void mg_send_websocket_handshake(struct mg_connection *nc, const char *path, const char *extra_headers)
#define JSON_RPC_METHOD_NOT_FOUND_ERROR
Definition mongoose6.h:2808
void mg_printf_http_chunk(struct mg_connection *nc, const char *fmt,...)
void mg_if_connect_tcp(struct mg_connection *nc, const union socket_address *sa)
#define MG_EV_MQTT_SUBSCRIBE
Definition mongoose6.h:2924
const char * mg_next_comma_list_entry(const char *list, struct mg_str *val, struct mg_str *eq_val)
struct json_token * params
Definition mongoose6.h:2734
#define MG_EV_CLOSE
Definition mongoose6.h:1224
size_t mg_dns_uncompress_name(struct mg_dns_message *msg, struct mg_str *name, char *dst, int dst_len)
struct mg_connection * mg_connect_http_opt(struct mg_mgr *mgr, mg_event_handler_t ev_handler, struct mg_connect_opts opts, const char *url, const char *extra_headers, const char *post_data)
SSL_CTX * ssl_ctx
Definition mongoose6.h:1258
void mbuf_trim(struct mbuf *mbuf)
#define MG_MQTT_CMD_DISCONNECT
Definition mongoose6.h:2913
#define JSON_STRING_INVALID
Definition mongoose6.h:1079
FILE * mg_fopen(const char *path, const char *mode)
uint32_t buf[4]
Definition mongoose6.h:931
void mg_enable_multithreading(struct mg_connection *nc)
struct mg_str * mg_get_http_header(struct http_message *hm, const char *name)
void cs_sha1_update(cs_sha1_ctx *context, const unsigned char *data, uint32_t len)
#define MG_MQTT_CMD_SUBSCRIBE
Definition mongoose6.h:2907
#define MG_MQTT_CMD_SUBACK
Definition mongoose6.h:2908
void mg_if_recved(struct mg_connection *nc, size_t len)
unsigned char chunk[3]
Definition mongoose6.h:982
int mg_vcmp(const struct mg_str *str1, const char *str2)
int mg_parse_uri(struct mg_str uri, struct mg_str *scheme, struct mg_str *user_info, struct mg_str *host, unsigned int *port, struct mg_str *path, struct mg_str *query, struct mg_str *fragment)
#define MG_F_WANT_WRITE
Definition mongoose6.h:1284
size_t size
Definition mongoose6.h:836
int mg_check_ip_acl(const char *acl, uint32_t remote_ip)
struct mg_dns_resource_record answers[MG_MAX_DNS_ANSWERS]
Definition mongoose6.h:3197
#define MG_F_CONNECTING
Definition mongoose6.h:1281
void mg_if_timer(struct mg_connection *c, double now)
mg_event_handler_t proto_handler
Definition mongoose6.h:1261
void mg_close_conn(struct mg_connection *conn)
struct mg_str pkt
Definition mongoose6.h:3191
const char * p
Definition mongoose6.h:1206
void cs_sha1_init(cs_sha1_ctx *context)
int mg_ncasecmp(const char *s1, const char *s2, size_t len)
int mg_dns_parse_record_data(struct mg_dns_message *msg, struct mg_dns_resource_record *rr, void *data, size_t data_len)
int mg_rpc_dispatch(const char *buf, int len, char *dst, int dst_len, const char **methods, mg_rpc_handler_t *handlers)
#define MG_EV_ACCEPT
Definition mongoose6.h:1220
struct mg_connection * mg_add_sock(struct mg_mgr *s, sock_t sock, mg_event_handler_t callback)
#define MG_EV_MQTT_CONNACK_ACCEPTED
Definition mongoose6.h:2950
void mg_mqtt_unsubscribe(struct mg_connection *nc, char **topics, size_t topics_len, uint16_t message_id)
#define MG_EV_WEBSOCKET_HANDSHAKE_REQUEST
Definition mongoose6.h:2119
#define JSON_RPC_INVALID_REQUEST_ERROR
Definition mongoose6.h:2807
struct sockaddr_in sin
Definition mongoose6.h:1196
int mg_printf(struct mg_connection *conn, const char *fmt,...)
void mg_mqtt_subscribe(struct mg_connection *nc, const struct mg_mqtt_topic_expression *topics, size_t topics_len, uint16_t message_id)
int mg_rpc_create_reply(char *buf, int len, const struct mg_rpc_request *req, const char *result_fmt,...)
void mg_mqtt_pubrel(struct mg_connection *nc, uint16_t message_id)
void cs_log_set_file(FILE *file)
int mg_mqtt_next_subscribe_topic(struct mg_mqtt_message *msg, struct mg_str *topic, uint8_t *qos, int pos)
#define MG_F_SEND_AND_CLOSE
Definition mongoose6.h:1288
uint16_t transaction_id
Definition mongoose6.h:3193
#define MG_EV_HTTP_REQUEST
Definition mongoose6.h:2114
@ LL_DEBUG
Definition mongoose6.h:746
@ LL_ERROR
Definition mongoose6.h:743
@ LL_VERBOSE_DEBUG
Definition mongoose6.h:747
@ MG_RESOLVE_TIMEOUT
Definition mongoose6.h:3413
@ MG_RESOLVE_EXCEEDED_RETRY_COUNT
Definition mongoose6.h:3412
@ MG_RESOLVE_OK
Definition mongoose6.h:3410
@ MG_RESOLVE_NO_ANSWERS
Definition mongoose6.h:3411
@ MG_DNS_INVALID_RECORD
Definition mongoose6.h:3174
@ MG_DNS_ANSWER
Definition mongoose6.h:3176
@ MG_DNS_QUESTION
Definition mongoose6.h:3175
@ JSON_TYPE_STRING
Definition mongoose6.h:1062
@ JSON_TYPE_TRUE
Definition mongoose6.h:1065
@ JSON_TYPE_OBJECT
Definition mongoose6.h:1064
@ JSON_TYPE_NUMBER
Definition mongoose6.h:1063
@ JSON_TYPE_ARRAY
Definition mongoose6.h:1068
@ JSON_TYPE_EOF
Definition mongoose6.h:1061
@ JSON_TYPE_FALSE
Definition mongoose6.h:1066
@ JSON_TYPE_NULL
Definition mongoose6.h:1067
HNDLE hKey
DWORD n[4]
Definition mana.cxx:247
char param[10][256]
Definition mana.cxx:250
void * data
Definition mana.cxx:268
INT type
Definition mana.cxx:269
char addr[128]
Definition mcnaf.cxx:104
double count
Definition mdump.cxx:33
KEY key
Definition mdump.cxx:34
INT i
Definition mdump.cxx:32
INT bl
Definition mdump.cxx:29
char response[10000]
Definition melog.cxx:90
#define closesocket(s)
Definition melog.cxx:29
static int offset
Definition mgd.cxx:1500
#define TRUE
Definition midas.h:182
#define end
#define message(type, str)
#define mask(slot)
Definition midas_macro.h:54
#define begin
#define name(x)
Definition midas_macro.h:24
#define set(var, value)
static std::string remove(const std::string s, char c)
Definition mjsonrpc.cxx:253
static FILE * fp
#define mg_mkdir(x, y)
#define SOMAXCONN
const char * mime_type
#define INVALID_SOCKET
size_t ext_len
const char * extension
#define INT64_FMT
static char * skip(char **buf, const char *delimiters)
static const char * month_names[]
static char * addenv(struct cgi_env_block *block, PRINTF_FORMAT_STRING(const char *fmt),...) PRINTF_ARGS(2
static OsiMsgQ_t s_mg_q
bool mg_start_task(int priority, int stack_size, mg_init_cb mg_init)
mg_q_msg_type
@ MG_Q_MSG_CB
char * inet_ntoa(struct in_addr n)
static void mg_task(void *arg)
const char * inet_ntop(int af, const void *src, char *dst, socklen_t size)
int inet_pton(int af, const char *src, void *dst)
static int mg_is_error(void)
void mg_run_in_task(void(*cb)(struct mg_mgr *mgr, void *arg), void *cb_arg)
#define MG_DISABLE_HTTP_KEEP_ALIVE
int mg_mqtt_match_topic_expression(struct mg_str exp, struct mg_str topic)
#define MG_LWIP
#define MG_CTL_MSG_MESSAGE_SIZE
#define MG_COPY_COMMON_CONNECTION_OPTIONS(dst, src)
static size_t mg_http_parse_chunk(char *buf, size_t len, char **chunk_data, size_t *chunk_len)
int cs_dirent_dummy
#define MD5STEP(f, w, x, y, z, data, s)
mg_http_multipart_stream_state
@ MPS_WAITING_FOR_CHUNK
@ MPS_FINISHED
@ MPS_FINALIZE
@ MPS_GOT_BOUNDARY
@ MPS_WAITING_FOR_BOUNDARY
@ MPS_BEGIN
@ MPS_GOT_CHUNK
int _kill(int pid, int sig)
MG_INTERNAL int parse_mqtt(struct mbuf *io, struct mg_mqtt_message *mm)
static void mg_send_directory_listing(struct mg_connection *nc, const char *dir, struct http_message *hm, struct mg_serve_http_opts *opts)
static void do_ssi_exec(struct mg_connection *nc, char *tag)
static int parse_key(struct frozen *f)
MG_INTERNAL int mg_uri_to_local_path(struct http_message *hm, const struct mg_serve_http_opts *opts, char **local_path, struct mg_str *remainder)
#define HEXTOI(x)
#define NUM_DIGITS
static int capture_ptr(struct frozen *f, const char *ptr, enum json_type type)
static void mg_http_free_proto_data_cgi(struct mg_http_proto_data_cgi *d)
static void mqtt_handler(struct mg_connection *nc, int ev, void *ev_data)
int _getpid()
static void mg_recv_common(struct mg_connection *nc, void *buf, int len)
const char * mime_type
#define MG_MALLOC
Definition mongoose6.cxx:14
static int path_part_len(const char *p)
static int is_alpha(int ch)
static int mg_resolve2(const char *host, struct in_addr *ina)
static void mg_handle_cgi(struct mg_connection *nc, const char *prog, const struct mg_str *path_info, const struct http_message *hm, const struct mg_serve_http_opts *opts)
static struct mg_http_proto_data * mg_http_get_proto_data(struct mg_connection *c)
static void mg_send_file_data(struct mg_connection *nc, FILE *fp)
void cs_sha1_transform(uint32_t state[5], const unsigned char buffer[64])
#define MG_WS_NO_HOST_HEADER_MAGIC
MG_INTERNAL void mg_remove_conn(struct mg_connection *c)
#define EMIT(x)
static void mg_resolve_async_eh(struct mg_connection *nc, int ev, void *data)
void mg_ev_mgr_add_conn(struct mg_connection *nc)
FILE * cs_log_file
static const struct @23 mg_static_builtin_mime_types[]
#define MIME_ENTRY(_ext, _type)
MG_INTERNAL struct mg_connection * mg_create_connection_base(struct mg_mgr *mgr, mg_event_handler_t callback, struct mg_add_sock_opts opts)
#define R1(v, w, x, y, z, i)
size_t ext_len
MG_INTERNAL struct mg_connection * mg_create_connection(struct mg_mgr *mgr, mg_event_handler_t callback, struct mg_add_sock_opts opts)
MG_INTERNAL void mg_call(struct mg_connection *nc, mg_event_handler_t ev_handler, int ev, void *ev_data)
static int mg_recvfrom(struct mg_connection *nc, union socket_address *sa, socklen_t *sa_len, char **buf)
static void mg_write_to_socket(struct mg_connection *nc)
static int parse_value(struct frozen *f)
#define _MG_CALLBACK_MODIFIABLE_FLAGS_MASK
static unsigned char from_b64(unsigned char ch)
static int mg_create_itermediate_directories(const char *path)
#define MBUF_REALLOC
Definition mongoose6.cxx:30
MG_INTERNAL void mg_send_http_file(struct mg_connection *nc, char *path, const struct mg_str *path_info, struct http_message *hm, struct mg_serve_http_opts *opts)
#define _MG_F_FD_ERROR
static void dns_handler(struct mg_connection *nc, int ev, void *ev_data)
long int random(void)
static void mg_websocket_handler(struct mg_connection *nc, int ev, void *ev_data)
static int c_itoa(char *buf, size_t buf_size, int64_t num, int base, int flags, int field_width)
#define MG_UDP_RECV_BUFFER_SIZE
static int parse_net(const char *spec, uint32_t *net, uint32_t *mask)
const char * extension
#define F1(x, y, z)
static int parse_object(struct frozen *f)
static int capture_len(struct frozen *f, int token_index, const char *ptr)
static void mg_http_construct_etag(char *buf, size_t buf_len, const cs_stat_t *st)
int _isatty(int fd)
MG_INTERNAL size_t recv_avail_size(struct mg_connection *conn, size_t max)
static void mg_http_conn_destructor(void *proto_data)
#define FROZEN_REALLOC
static int mg_dns_tid
static int parse_array(struct frozen *f)
MG_INTERNAL char mg_dns_server[300]
void _not_implemented(const char *what)
MG_INTERNAL time_t mg_parse_date_string(const char *datetime)
static void resolve_cb(struct mg_dns_message *msg, void *data, enum mg_resolve_err e)
static sock_t mg_open_listening_socket(union socket_address *sa, int proto)
static int parse_number(struct frozen *f)
static mg_event_handler_t mg_http_get_endpoint_handler(struct mg_connection *nc, struct mg_str *uri_path)
static int mg_dns_encode_name(struct mbuf *io, const char *name, size_t len)
static int mg_is_ws_first_fragment(unsigned char flags)
static int mg_remove_directory(const struct mg_serve_http_opts *opts, const char *dir)
static int mg_http_common_url_parse(const char *url, const char *schema, const char *schema_tls, int *use_ssl, char **addr, int *port_i, const char **path)
static int mg_check_nonce(const char *nonce)
static void mg_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 *))
static void mg_do_ssi_call(struct mg_connection *nc, char *tag)
static void MD5Transform(uint32_t buf[4], uint32_t const in[16])
static void mg_print_dir_entry(struct mg_connection *nc, const char *file_name, cs_stat_t *stp)
#define MG_CALLOC
Definition mongoose6.cxx:18
#define F4(x, y, z)
static void mg_destroy_conn(struct mg_connection *conn)
static void cs_base64_emit_chunk(struct cs_base64_ctx *ctx)
#define _MG_ALLOWED_CONNECT_FLAGS_MASK
struct mg_connection * mg_connect_http_base(struct mg_mgr *mgr, mg_event_handler_t ev_handler, struct mg_connect_opts opts, const char *schema, const char *schema_ssl, const char *url, const char **path, char **addr)
static void mg_http_send_error(struct mg_connection *nc, int code, const char *reason)
static void mg_handle_udp_read(struct mg_connection *nc)
static int left(const struct frozen *f)
static void mg_handle_put(struct mg_connection *nc, const char *path, struct http_message *hm)
static const char * mg_http_parse_headers(const char *s, const char *end, int len, struct http_message *req)
static size_t mg_url_encode(const char *src, size_t s_len, char *dst, size_t dst_len)
#define MG_MAX_HOST_LEN
static int is_space(int ch)
static int parse_string(struct frozen *f)
static int isbyte(int n)
static void mg_escape(const char *src, char *dst, size_t dst_len)
#define R2(v, w, x, y, z, i)
static void mg_send_ssi_file(struct mg_connection *, const char *, FILE *, int, const struct mg_serve_http_opts *)
MG_INTERNAL int mg_is_not_modified(struct http_message *hm, cs_stat_t *st)
static int parse_pair(struct frozen *f)
static int mg_get_month_index(const char *s)
static int get_utf8_char_len(unsigned char ch)
static uint32_t mg_ws_random_mask(void)
static void mg_sock_get_addr(sock_t sock, int remote, union socket_address *sa)
void mg_ev_mgr_remove_conn(struct mg_connection *nc)
static void skip_whitespaces(struct frozen *f)
static const char * mg_default_dns_server
MG_INTERNAL int mg_parse_address(const char *str, union socket_address *sa, int *proto, char *host, size_t host_len)
static void mg_http_free_proto_data_file(struct mg_http_proto_data_file *d)
static int parse_identifier(struct frozen *f)
#define _MG_F_FD_CAN_READ
static void byteReverse(unsigned char *buf, unsigned longs)
static int mg_get_ip_address_of_nameserver(char *name, size_t name_len)
static void parse_uri_component(const char **p, const char *end, char sep, struct mg_str *res)
static int mg_is_dav_request(const struct mg_str *s)
#define R0(v, w, x, y, z, i)
static unsigned char * mg_parse_dns_resource_record(unsigned char *data, unsigned char *end, struct mg_dns_resource_record *rr, int reply)
static int doit(struct frozen *f)
static void mg_mgr_handle_ctl_sock(struct mg_mgr *mgr)
#define NUM_UPPERCASES
#define F3(x, y, z)
#define MG_SET_PTRPTR(_ptr, _v)
Definition mongoose6.cxx:37
static char * mg_addenv(struct mg_cgi_env_block *block, const char *fmt,...)
static int lowercase(const char *s)
#define NUM_LETTERS
static int test_and_skip(struct frozen *f, int expected)
static void mg_read_from_socket(struct mg_connection *conn)
static void cs_base64_emit_code(struct cs_base64_ctx *ctx, int v)
#define CONSOLE_UART
static void mg_ws_mask_frame(struct mbuf *mbuf, struct ws_mask_ctx *ctx)
static void mg_prepare_cgi_environment(struct mg_connection *nc, const char *prog, const struct mg_str *path_info, const struct http_message *hm, const struct mg_serve_http_opts *opts, struct mg_cgi_env_block *blk)
void mg_ev_mgr_init(struct mg_mgr *mgr)
#define MBUF_FREE
Definition mongoose6.cxx:34
static void mg_handle_incoming_websocket_frame(struct mg_connection *nc, struct websocket_message *wsm)
void mg_forward(struct mg_connection *from, struct mg_connection *to)
static int mg_is_file_hidden(const char *path, const struct mg_serve_http_opts *opts, int exclude_specials)
static void mg_handle_ssi_request(struct mg_connection *nc, const char *path, const struct mg_serve_http_opts *opts)
static int mg_http_get_request_len(const char *s, int buf_len)
MG_INTERNAL size_t mg_handle_chunked(struct mg_connection *nc, struct http_message *hm, char *buf, size_t blen)
int _gettimeofday_r(struct _reent *r, struct timeval *tp, void *tzp)
static int expect(struct frozen *f, const char *s, int len, enum json_type t)
static void mg_addenv2(struct mg_cgi_env_block *blk, const char *name)
static int is_hex_digit(int ch)
void mg_set_non_blocking_mode(sock_t sock)
void _exit(int status)
#define blk(i)
static void mg_send_ws_header(struct mg_connection *nc, int op, size_t len, struct ws_mask_ctx *ctx)
#define C_SNPRINTF_FLAG_ZERO
static int mg_http_parse_range_header(const struct mg_str *header, int64_t *a, int64_t *b)
static void mg_print_props(struct mg_connection *nc, const char *name, cs_stat_t *stp)
#define MG_REALLOC
Definition mongoose6.cxx:22
#define BASE64_ENCODE_BODY
static pid_t mg_start_process(const char *interp, const char *cmd, const char *env, const char *envp[], const char *dir, sock_t sock)
#define R3(v, w, x, y, z, i)
#define END_OF_STRING
static void mg_accept_conn(struct mg_connection *lc)
#define MG_INTERNAL
Definition mongoose6.cxx:43
static int test_no_skip(struct frozen *f, int expected)
#define TRY(expr)
static void mg_http_send_file2(struct mg_connection *nc, const char *path, cs_stat_t *st, struct http_message *hm, struct mg_serve_http_opts *opts)
#define MG_TCP_RECV_BUFFER_SIZE
int gettimeofday(struct timeval *tp, void *tzp)
static int mg_is_ws_fragment(unsigned char flags)
MG_INTERNAL void mg_find_index_file(const char *path, const char *list, char **index_file, cs_stat_t *stp)
static int mg_deliver_websocket_data(struct mg_connection *nc)
MG_INTERNAL void mg_add_conn(struct mg_mgr *mgr, struct mg_connection *c)
static void mg_http_free_proto_data_endpoints(struct mg_http_endpoint **ep)
#define FROZEN_FREE
static void mg_cgi_ev_handler(struct mg_connection *cgi_nc, int ev, void *ev_data)
#define _MG_F_FD_CAN_WRITE
static int cur(struct frozen *f)
static void mg_http_send_digest_auth_request(struct mg_connection *c, const char *domain)
#define MG_FREE
Definition mongoose6.cxx:26
static size_t mg_get_line_len(const char *buf, size_t buf_len)
MG_INTERNAL struct mg_connection * mg_do_connect(struct mg_connection *nc, int proto, union socket_address *sa)
static void mg_http_call_endpoint_handler(struct mg_connection *nc, int ev, struct http_message *hm)
static void mg_handle_mkcol(struct mg_connection *nc, const char *path, struct http_message *hm)
static void mg_http_transfer_file_data(struct mg_connection *nc)
static void mg_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)
mg_http_proto_data_type
@ DATA_FILE
@ DATA_NONE
@ DATA_PUT
static int mg_is_authorized(struct http_message *hm, const char *path, int is_directory, const char *domain, const char *passwords_file, int is_global_pass_file)
#define F2(x, y, z)
void mg_http_handler(struct mg_connection *nc, int ev, void *ev_data)
#define EXPECT(cond, err_code)
static void mg_mqtt_prepend_header(struct mg_connection *nc, uint8_t cmd, uint8_t flags, size_t len)
static int mg_http_send_port_based_redirect(struct mg_connection *c, struct http_message *hm, const struct mg_serve_http_opts *opts)
static void mg_handle_delete(struct mg_connection *nc, const struct mg_serve_http_opts *opts, const char *path)
int json_emit_long(char *buf, int buf_len, long int value)
static int mg_http_check_digest_auth(struct http_message *hm, const char *auth_domain, FILE *fp)
void mg_add_to_set(sock_t sock, fd_set *set, sock_t *max_fd)
void fprint_str(FILE *fp, const char *str)
static void mg_handle_move(struct mg_connection *c, const struct mg_serve_http_opts *opts, const char *path, struct http_message *hm)
static int get_escape_len(const char *s, int len)
static void mg_handle_propfind(struct mg_connection *nc, const char *path, cs_stat_t *stp, struct http_message *hm, struct mg_serve_http_opts *opts)
void MD5_Final(unsigned char digest[16], MD5_CTX *ctx)
static void mg_gmt_time_string(char *buf, size_t buf_len, time_t *t)
static int compare(const char *s, const char *str, int len)
static void mg_http_send_options(struct mg_connection *nc)
#define rol(value, bits)
static uint32_t blk0(union char64long16 *block, int i)
#define MG_DEFAULT_NAMESERVER
#define C_SNPRINTF_APPEND_CHAR(ch)
static int is_digit(int ch)
static void mg_ws_handshake(struct mg_connection *nc, const struct mg_str *key)
static int mg_is_creation_request(const struct http_message *hm)
void mg_ev_mgr_free(struct mg_mgr *mgr)
static int mg_num_leap_years(int year)
#define R4(v, w, x, y, z, i)
void mg_mgr_handle_conn(struct mg_connection *nc, int fd_flags, double now)
static struct mg_str mg_get_mime_type(const char *path, const char *dflt, const struct mg_serve_http_opts *opts)
static void mg_send_mqtt_short_command(struct mg_connection *nc, uint8_t cmd, uint16_t message_id)
struct callback_addr callback
Definition mserver.cxx:22
timeval tv
Definition msysmon.cxx:1095
#define gmtime
Definition msystem.h:266
#define localtime
Definition msystem.h:265
INT j
Definition odbhist.cxx:40
double value[100]
Definition odbhist.cxx:42
INT k
Definition odbhist.cxx:40
char str[256]
Definition odbhist.cxx:33
char file_name[256]
Definition odbhist.cxx:41
DWORD status
Definition odbhist.cxx:39
char var_name[256]
Definition odbhist.cxx:41
TH1X EXPRT * h1_book(const char *name, const char *title, int bins, double min, double max)
Definition rmidas.h:24
char message[MG_CTL_MSG_MESSAGE_SIZE]
mg_event_handler_t callback
const char * end
const char * cur
int num_tokens
int do_realloc
int max_tokens
struct json_token * tokens
const char * vars[MG_MAX_CGI_ENVIR_VARS]
struct mg_connection * nc
char buf[MG_CGI_ENVIRONMENT_SIZE]
struct mg_context * ctx
uint16_t transaction_id
uint16_t num_questions
uint16_t num_answers
uint16_t num_authority_prs
uint16_t num_other_prs
const char * name
mg_event_handler_t handler
struct mg_http_endpoint * next
enum mg_http_multipart_stream_state state
struct mg_connection * cgi_nc
enum mg_http_proto_data_type type
struct mg_http_proto_data_chuncked chunk
struct mg_http_endpoint * endpoints
struct mg_http_proto_data_cgi cgi
mg_event_handler_t endpoint_handler
struct mg_str client_id
enum mg_q_msg_type type
void(* cb)(struct mg_mgr *mgr, void *arg)
enum mg_resolve_err err
mg_resolve_callback_t callback
size_t len
uint32_t mask
double d
Definition system.cxx:1311
char c
Definition system.cxx:1310
@ DIR
Definition test_init.cxx:7
static double comma(double a, double b)
Definition tinyexpr.c:248
static double e(void)
Definition tinyexpr.c:136
static te_expr * base(state *s)
Definition tinyexpr.c:357
static double pi(void)
Definition tinyexpr.c:135
static te_expr * list(state *s)
Definition tinyexpr.c:567
unsigned char c[64]
uint32_t l[16]
struct sockaddr_in sin