1 #include "mongoose.h"
2 #ifdef MG_MODULE_LINES
3 #line 1 "mongoose/src/mg_internal.h"
4 #endif
5 /*
6 * Copyright (c) 2014 Cesanta Software Limited
7 * All rights reserved
8 */
9
10 #ifndef CS_MONGOOSE_SRC_INTERNAL_H_
11 #define CS_MONGOOSE_SRC_INTERNAL_H_
12
13 /* Amalgamated: #include "common/mg_mem.h" */
14
15 #ifndef MBUF_REALLOC
16 #define MBUF_REALLOC MG_REALLOC
17 #endif
18
19 #ifndef MBUF_FREE
20 #define MBUF_FREE MG_FREE
21 #endif
22
23 #define MG_SET_PTRPTR(_ptr, _v) \
24 do { \
25 if (_ptr) *(_ptr) = _v; \
26 } while (0)
27
28 #ifndef MG_INTERNAL
29 #define MG_INTERNAL static
30 #endif
31
32 #ifdef PICOTCP
33 #define NO_LIBC
34 #define MG_DISABLE_PFS
35 #endif
36
37 /* Amalgamated: #include "common/cs_dbg.h" */
38 /* Amalgamated: #include "mg_http.h" */
39 /* Amalgamated: #include "mg_net.h" */
40
41 #ifndef MG_CTL_MSG_MESSAGE_SIZE
42 #define MG_CTL_MSG_MESSAGE_SIZE 8192
43 #endif
44
45 /* internals that need to be accessible in unit tests */
46 MG_INTERNAL struct mg_connection *mg_do_connect(struct mg_connection *nc,
47 int proto,
48 union socket_address *sa);
49
50 MG_INTERNAL int mg_parse_address(const char *str, union socket_address *sa,
51 int *proto, char *host, size_t host_len);
52 MG_INTERNAL void mg_call(struct mg_connection *nc,
53 mg_event_handler_t ev_handler, void *user_data, int ev,
54 void *ev_data);
55 void mg_forward(struct mg_connection *from, struct mg_connection *to);
56 MG_INTERNAL void mg_add_conn(struct mg_mgr *mgr, struct mg_connection *c);
57 MG_INTERNAL void mg_remove_conn(struct mg_connection *c);
58 MG_INTERNAL struct mg_connection *mg_create_connection(
59 struct mg_mgr *mgr, mg_event_handler_t callback,
60 struct mg_add_sock_opts opts);
61 #ifdef _WIN32
62 /* Retur value is the same as for MultiByteToWideChar. */
63 int to_wchar(const char *path, wchar_t *wbuf, size_t wbuf_len);
64 #endif
65
66 struct ctl_msg {
67 mg_event_handler_t callback;
68 char message[MG_CTL_MSG_MESSAGE_SIZE];
69 };
70
71 #if MG_ENABLE_MQTT
72 struct mg_mqtt_message;
73
74 #define MG_MQTT_ERROR_INCOMPLETE_MSG -1
75 #define MG_MQTT_ERROR_MALFORMED_MSG -2
76
77 MG_INTERNAL int parse_mqtt(struct mbuf *io, struct mg_mqtt_message *mm);
78 #endif
79
80 /* Forward declarations for testing. */
81 extern void *(*test_malloc)(size_t size);
82 extern void *(*test_calloc)(size_t count, size_t size);
83
84 #ifndef MIN
85 #define MIN(a, b) ((a) < (b) ? (a) : (b))
86 #endif
87
88 #if MG_ENABLE_HTTP
89 struct mg_serve_http_opts;
90
91 MG_INTERNAL struct mg_http_proto_data *mg_http_create_proto_data(
92 struct mg_connection *c);
93
94 /*
95 * Reassemble the content of the buffer (buf, blen) which should be
96 * in the HTTP chunked encoding, by collapsing data chunks to the
97 * beginning of the buffer.
98 *
99 * If chunks get reassembled, modify hm->body to point to the reassembled
100 * body and fire MG_EV_HTTP_CHUNK event. If handler sets MG_F_DELETE_CHUNK
101 * in nc->flags, delete reassembled body from the mbuf.
102 *
103 * Return reassembled body size.
104 */
105 MG_INTERNAL size_t mg_handle_chunked(struct mg_connection *nc,
106 struct http_message *hm, char *buf,
107 size_t blen);
108
109 #if MG_ENABLE_FILESYSTEM
110 MG_INTERNAL int mg_uri_to_local_path(struct http_message *hm,
111 const struct mg_serve_http_opts *opts,
112 char **local_path,
113 struct mg_str *remainder);
114 MG_INTERNAL time_t mg_parse_date_string(const char *datetime);
115 MG_INTERNAL int mg_is_not_modified(struct http_message *hm, cs_stat_t *st);
116 #endif
117 #if MG_ENABLE_HTTP_CGI
118 MG_INTERNAL void mg_handle_cgi(struct mg_connection *nc, const char *prog,
119 const struct mg_str *path_info,
120 const struct http_message *hm,
121 const struct mg_serve_http_opts *opts);
122 struct mg_http_proto_data_cgi;
123 MG_INTERNAL void mg_http_free_proto_data_cgi(struct mg_http_proto_data_cgi *d);
124 #endif
125 #if MG_ENABLE_HTTP_SSI
126 MG_INTERNAL void mg_handle_ssi_request(struct mg_connection *nc,
127 struct http_message *hm,
128 const char *path,
129 const struct mg_serve_http_opts *opts);
130 #endif
131 #if MG_ENABLE_HTTP_WEBDAV
132 MG_INTERNAL int mg_is_dav_request(const struct mg_str *s);
133 MG_INTERNAL void mg_handle_propfind(struct mg_connection *nc, const char *path,
134 cs_stat_t *stp, struct http_message *hm,
135 struct mg_serve_http_opts *opts);
136 MG_INTERNAL void mg_handle_lock(struct mg_connection *nc, const char *path);
137 MG_INTERNAL void mg_handle_mkcol(struct mg_connection *nc, const char *path,
138 struct http_message *hm);
139 MG_INTERNAL void mg_handle_move(struct mg_connection *c,
140 const struct mg_serve_http_opts *opts,
141 const char *path, struct http_message *hm);
142 MG_INTERNAL void mg_handle_delete(struct mg_connection *nc,
143 const struct mg_serve_http_opts *opts,
144 const char *path);
145 MG_INTERNAL void mg_handle_put(struct mg_connection *nc, const char *path,
146 struct http_message *hm);
147 #endif
148 #if MG_ENABLE_HTTP_WEBSOCKET
149 MG_INTERNAL void mg_ws_handler(struct mg_connection *nc, int ev,
150 void *ev_data MG_UD_ARG(void *user_data));
151 MG_INTERNAL void mg_ws_handshake(struct mg_connection *nc,
152 const struct mg_str *key,
153 struct http_message *);
154 #endif
155 #endif /* MG_ENABLE_HTTP */
156
157 MG_INTERNAL int mg_get_errno(void);
158
159 MG_INTERNAL void mg_close_conn(struct mg_connection *conn);
160
161 #if MG_ENABLE_SNTP
162 MG_INTERNAL int mg_sntp_parse_reply(const char *buf, int len,
163 struct mg_sntp_message *msg);
164 #endif
165
166 #endif /* CS_MONGOOSE_SRC_INTERNAL_H_ */
167 #ifdef MG_MODULE_LINES
168 #line 1 "common/mg_mem.h"
169 #endif
170 /*
171 * Copyright (c) 2014-2018 Cesanta Software Limited
172 * All rights reserved
173 *
174 * Licensed under the Apache License, Version 2.0 (the ""License"");
175 * you may not use this file except in compliance with the License.
176 * You may obtain a copy of the License at
177 *
178 * http://www.apache.org/licenses/LICENSE-2.0
179 *
180 * Unless required by applicable law or agreed to in writing, software
181 * distributed under the License is distributed on an ""AS IS"" BASIS,
182 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
183 * See the License for the specific language governing permissions and
184 * limitations under the License.
185 */
186
187 #ifndef CS_COMMON_MG_MEM_H_
188 #define CS_COMMON_MG_MEM_H_
189
190 #ifdef __cplusplus
191 extern "C" {
192 #endif
193
194 #ifndef MG_MALLOC
195 #define MG_MALLOC malloc
196 #endif
197
198 #ifndef MG_CALLOC
199 #define MG_CALLOC calloc
200 #endif
201
202 #ifndef MG_REALLOC
203 #define MG_REALLOC realloc
204 #endif
205
206 #ifndef MG_FREE
207 #define MG_FREE free
208 #endif
209
210 #ifdef __cplusplus
211 }
212 #endif
213
214 #endif /* CS_COMMON_MG_MEM_H_ */
215 #ifdef MG_MODULE_LINES
216 #line 1 "common/cs_base64.c"
217 #endif
218 /*
219 * Copyright (c) 2014-2018 Cesanta Software Limited
220 * All rights reserved
221 *
222 * Licensed under the Apache License, Version 2.0 (the ""License"");
223 * you may not use this file except in compliance with the License.
224 * You may obtain a copy of the License at
225 *
226 * http://www.apache.org/licenses/LICENSE-2.0
227 *
228 * Unless required by applicable law or agreed to in writing, software
229 * distributed under the License is distributed on an ""AS IS"" BASIS,
230 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
231 * See the License for the specific language governing permissions and
232 * limitations under the License.
233 */
234
235 #ifndef EXCLUDE_COMMON
236
237 /* Amalgamated: #include "common/cs_base64.h" */
238
239 #include <string.h>
240
241 /* Amalgamated: #include "common/cs_dbg.h" */
242
243 /* ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/ */
244
245 #define NUM_UPPERCASES ('Z' - 'A' + 1)
246 #define NUM_LETTERS (NUM_UPPERCASES * 2)
247 #define NUM_DIGITS ('9' - '0' + 1)
248
249 /*
250 * Emit a base64 code char.
251 *
252 * Doesn't use memory, thus it's safe to use to safely dump memory in crashdumps
253 */
cs_base64_emit_code(struct cs_base64_ctx * ctx,int v)254 static void cs_base64_emit_code(struct cs_base64_ctx *ctx, int v) {
255 if (v < NUM_UPPERCASES) {
256 ctx->b64_putc(v + 'A', ctx->user_data);
257 } else if (v < (NUM_LETTERS)) {
258 ctx->b64_putc(v - NUM_UPPERCASES + 'a', ctx->user_data);
259 } else if (v < (NUM_LETTERS + NUM_DIGITS)) {
260 ctx->b64_putc(v - NUM_LETTERS + '0', ctx->user_data);
261 } else {
262 ctx->b64_putc(v - NUM_LETTERS - NUM_DIGITS == 0 ? '+' : '/',
263 ctx->user_data);
264 }
265 }
266
cs_base64_emit_chunk(struct cs_base64_ctx * ctx)267 static void cs_base64_emit_chunk(struct cs_base64_ctx *ctx) {
268 int a, b, c;
269
270 a = ctx->chunk[0];
271 b = ctx->chunk[1];
272 c = ctx->chunk[2];
273
274 cs_base64_emit_code(ctx, a >> 2);
275 cs_base64_emit_code(ctx, ((a & 3) << 4) | (b >> 4));
276 if (ctx->chunk_size > 1) {
277 cs_base64_emit_code(ctx, (b & 15) << 2 | (c >> 6));
278 }
279 if (ctx->chunk_size > 2) {
280 cs_base64_emit_code(ctx, c & 63);
281 }
282 }
283
cs_base64_init(struct cs_base64_ctx * ctx,cs_base64_putc_t b64_putc,void * user_data)284 void cs_base64_init(struct cs_base64_ctx *ctx, cs_base64_putc_t b64_putc,
285 void *user_data) {
286 ctx->chunk_size = 0;
287 ctx->b64_putc = b64_putc;
288 ctx->user_data = user_data;
289 }
290
cs_base64_update(struct cs_base64_ctx * ctx,const char * str,size_t len)291 void cs_base64_update(struct cs_base64_ctx *ctx, const char *str, size_t len) {
292 const unsigned char *src = (const unsigned char *) str;
293 size_t i;
294 for (i = 0; i < len; i++) {
295 ctx->chunk[ctx->chunk_size++] = src[i];
296 if (ctx->chunk_size == 3) {
297 cs_base64_emit_chunk(ctx);
298 ctx->chunk_size = 0;
299 }
300 }
301 }
302
cs_base64_finish(struct cs_base64_ctx * ctx)303 void cs_base64_finish(struct cs_base64_ctx *ctx) {
304 if (ctx->chunk_size > 0) {
305 int i;
306 memset(&ctx->chunk[ctx->chunk_size], 0, 3 - ctx->chunk_size);
307 cs_base64_emit_chunk(ctx);
308 for (i = 0; i < (3 - ctx->chunk_size); i++) {
309 ctx->b64_putc('=', ctx->user_data);
310 }
311 }
312 }
313
314 #define BASE64_ENCODE_BODY \
315 static const char *b64 = \
316 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; \
317 int i, j, a, b, c; \
318 \
319 for (i = j = 0; i < src_len; i += 3) { \
320 a = src[i]; \
321 b = i + 1 >= src_len ? 0 : src[i + 1]; \
322 c = i + 2 >= src_len ? 0 : src[i + 2]; \
323 \
324 BASE64_OUT(b64[a >> 2]); \
325 BASE64_OUT(b64[((a & 3) << 4) | (b >> 4)]); \
326 if (i + 1 < src_len) { \
327 BASE64_OUT(b64[(b & 15) << 2 | (c >> 6)]); \
328 } \
329 if (i + 2 < src_len) { \
330 BASE64_OUT(b64[c & 63]); \
331 } \
332 } \
333 \
334 while (j % 4 != 0) { \
335 BASE64_OUT('='); \
336 } \
337 BASE64_FLUSH()
338
339 #define BASE64_OUT(ch) \
340 do { \
341 dst[j++] = (ch); \
342 } while (0)
343
344 #define BASE64_FLUSH() \
345 do { \
346 dst[j++] = '\0'; \
347 } while (0)
348
cs_base64_encode(const unsigned char * src,int src_len,char * dst)349 void cs_base64_encode(const unsigned char *src, int src_len, char *dst) {
350 BASE64_ENCODE_BODY;
351 }
352
353 #undef BASE64_OUT
354 #undef BASE64_FLUSH
355
356 #if CS_ENABLE_STDIO
357 #define BASE64_OUT(ch) \
358 do { \
359 fprintf(f, "%c", (ch)); \
360 j++; \
361 } while (0)
362
363 #define BASE64_FLUSH()
364
cs_fprint_base64(FILE * f,const unsigned char * src,int src_len)365 void cs_fprint_base64(FILE *f, const unsigned char *src, int src_len) {
366 BASE64_ENCODE_BODY;
367 }
368
369 #undef BASE64_OUT
370 #undef BASE64_FLUSH
371 #endif /* CS_ENABLE_STDIO */
372
373 /* Convert one byte of encoded base64 input stream to 6-bit chunk */
from_b64(unsigned char ch)374 static unsigned char from_b64(unsigned char ch) {
375 /* Inverse lookup map */
376 static const unsigned char tab[128] = {
377 255, 255, 255, 255,
378 255, 255, 255, 255, /* 0 */
379 255, 255, 255, 255,
380 255, 255, 255, 255, /* 8 */
381 255, 255, 255, 255,
382 255, 255, 255, 255, /* 16 */
383 255, 255, 255, 255,
384 255, 255, 255, 255, /* 24 */
385 255, 255, 255, 255,
386 255, 255, 255, 255, /* 32 */
387 255, 255, 255, 62,
388 255, 255, 255, 63, /* 40 */
389 52, 53, 54, 55,
390 56, 57, 58, 59, /* 48 */
391 60, 61, 255, 255,
392 255, 200, 255, 255, /* 56 '=' is 200, on index 61 */
393 255, 0, 1, 2,
394 3, 4, 5, 6, /* 64 */
395 7, 8, 9, 10,
396 11, 12, 13, 14, /* 72 */
397 15, 16, 17, 18,
398 19, 20, 21, 22, /* 80 */
399 23, 24, 25, 255,
400 255, 255, 255, 255, /* 88 */
401 255, 26, 27, 28,
402 29, 30, 31, 32, /* 96 */
403 33, 34, 35, 36,
404 37, 38, 39, 40, /* 104 */
405 41, 42, 43, 44,
406 45, 46, 47, 48, /* 112 */
407 49, 50, 51, 255,
408 255, 255, 255, 255, /* 120 */
409 };
410 return tab[ch & 127];
411 }
412
cs_base64_decode(const unsigned char * s,int len,char * dst,int * dec_len)413 int cs_base64_decode(const unsigned char *s, int len, char *dst, int *dec_len) {
414 unsigned char a, b, c, d;
415 int orig_len = len;
416 char *orig_dst = dst;
417 while (len >= 4 && (a = from_b64(s[0])) != 255 &&
418 (b = from_b64(s[1])) != 255 && (c = from_b64(s[2])) != 255 &&
419 (d = from_b64(s[3])) != 255) {
420 s += 4;
421 len -= 4;
422 if (a == 200 || b == 200) break; /* '=' can't be there */
423 *dst++ = a << 2 | b >> 4;
424 if (c == 200) break;
425 *dst++ = b << 4 | c >> 2;
426 if (d == 200) break;
427 *dst++ = c << 6 | d;
428 }
429 *dst = 0;
430 if (dec_len != NULL) *dec_len = (dst - orig_dst);
431 return orig_len - len;
432 }
433
434 #endif /* EXCLUDE_COMMON */
435 #ifdef MG_MODULE_LINES
436 #line 1 "common/cs_dbg.h"
437 #endif
438 /*
439 * Copyright (c) 2014-2018 Cesanta Software Limited
440 * All rights reserved
441 *
442 * Licensed under the Apache License, Version 2.0 (the ""License"");
443 * you may not use this file except in compliance with the License.
444 * You may obtain a copy of the License at
445 *
446 * http://www.apache.org/licenses/LICENSE-2.0
447 *
448 * Unless required by applicable law or agreed to in writing, software
449 * distributed under the License is distributed on an ""AS IS"" BASIS,
450 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
451 * See the License for the specific language governing permissions and
452 * limitations under the License.
453 */
454
455 #ifndef CS_COMMON_CS_DBG_H_
456 #define CS_COMMON_CS_DBG_H_
457
458 /* Amalgamated: #include "common/platform.h" */
459
460 #if CS_ENABLE_STDIO
461 #include <stdio.h>
462 #endif
463
464 #ifndef CS_ENABLE_DEBUG
465 #define CS_ENABLE_DEBUG 0
466 #endif
467
468 #ifndef CS_LOG_PREFIX_LEN
469 #define CS_LOG_PREFIX_LEN 24
470 #endif
471
472 #ifndef CS_LOG_ENABLE_TS_DIFF
473 #define CS_LOG_ENABLE_TS_DIFF 0
474 #endif
475
476 #ifdef __cplusplus
477 extern "C" {
478 #endif /* __cplusplus */
479
480 /*
481 * Log level; `LL_INFO` is the default. Use `cs_log_set_level()` to change it.
482 */
483 enum cs_log_level {
484 LL_NONE = -1,
485 LL_ERROR = 0,
486 LL_WARN = 1,
487 LL_INFO = 2,
488 LL_DEBUG = 3,
489 LL_VERBOSE_DEBUG = 4,
490
491 _LL_MIN = -2,
492 _LL_MAX = 5,
493 };
494
495 /*
496 * Set max log level to print; messages with the level above the given one will
497 * not be printed.
498 */
499 void cs_log_set_level(enum cs_log_level level);
500
501 /*
502 * A comma-separated set of prefix=level.
503 * prefix is matched against the log prefix exactly as printed, including line
504 * number, but partial match is ok. Check stops on first matching entry.
505 * If nothing matches, default level is used.
506 *
507 * Examples:
508 * main.c:=4 - everything from main C at verbose debug level.
509 * mongoose.c=1,mjs.c=1,=4 - everything at verbose debug except mg_* and mjs_*
510 *
511 */
512 void cs_log_set_file_level(const char *file_level);
513
514 /*
515 * Helper function which prints message prefix with the given `level`.
516 * If message should be printed (according to the current log level
517 * and filter), prints the prefix and returns 1, otherwise returns 0.
518 *
519 * Clients should typically just use `LOG()` macro.
520 */
521 int cs_log_print_prefix(enum cs_log_level level, const char *fname, int line);
522
523 extern enum cs_log_level cs_log_level;
524
525 #if CS_ENABLE_STDIO
526
527 /*
528 * Set file to write logs into. If `NULL`, logs go to `stderr`.
529 */
530 void cs_log_set_file(FILE *file);
531
532 /*
533 * Prints log to the current log file, appends "\n" in the end and flushes the
534 * stream.
535 */
536 void cs_log_printf(const char *fmt, ...) PRINTF_LIKE(1, 2);
537
538 #if CS_ENABLE_STDIO
539
540 /*
541 * Format and print message `x` with the given level `l`. Example:
542 *
543 * ```c
544 * LOG(LL_INFO, ("my info message: %d", 123));
545 * LOG(LL_DEBUG, ("my debug message: %d", 123));
546 * ```
547 */
548 #define LOG(l, x) \
549 do { \
550 if (cs_log_print_prefix(l, __FILE__, __LINE__)) { \
551 cs_log_printf x; \
552 } \
553 } while (0)
554
555 #else
556
557 #define LOG(l, x) ((void) l)
558
559 #endif
560
561 #ifndef CS_NDEBUG
562
563 /*
564 * Shortcut for `LOG(LL_VERBOSE_DEBUG, (...))`
565 */
566 #define DBG(x) LOG(LL_VERBOSE_DEBUG, x)
567
568 #else /* NDEBUG */
569
570 #define DBG(x)
571
572 #endif
573
574 #else /* CS_ENABLE_STDIO */
575
576 #define LOG(l, x)
577 #define DBG(x)
578
579 #endif
580
581 #ifdef __cplusplus
582 }
583 #endif /* __cplusplus */
584
585 #endif /* CS_COMMON_CS_DBG_H_ */
586 #ifdef MG_MODULE_LINES
587 #line 1 "common/cs_dbg.c"
588 #endif
589 /*
590 * Copyright (c) 2014-2018 Cesanta Software Limited
591 * All rights reserved
592 *
593 * Licensed under the Apache License, Version 2.0 (the ""License"");
594 * you may not use this file except in compliance with the License.
595 * You may obtain a copy of the License at
596 *
597 * http://www.apache.org/licenses/LICENSE-2.0
598 *
599 * Unless required by applicable law or agreed to in writing, software
600 * distributed under the License is distributed on an ""AS IS"" BASIS,
601 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
602 * See the License for the specific language governing permissions and
603 * limitations under the License.
604 */
605
606 /* Amalgamated: #include "common/cs_dbg.h" */
607
608 #include <stdarg.h>
609 #include <stdio.h>
610 #include <string.h>
611
612 /* Amalgamated: #include "common/cs_time.h" */
613 /* Amalgamated: #include "common/str_util.h" */
614
615 enum cs_log_level cs_log_level WEAK =
616 #if CS_ENABLE_DEBUG
617 LL_VERBOSE_DEBUG;
618 #else
619 LL_ERROR;
620 #endif
621
622 #if CS_ENABLE_STDIO
623 static char *s_file_level = NULL;
624
625 void cs_log_set_file_level(const char *file_level) WEAK;
626
627 FILE *cs_log_file WEAK = NULL;
628
629 #if CS_LOG_ENABLE_TS_DIFF
630 double cs_log_ts WEAK;
631 #endif
632
633 enum cs_log_level cs_log_cur_msg_level WEAK = LL_NONE;
634
cs_log_set_file_level(const char * file_level)635 void cs_log_set_file_level(const char *file_level) {
636 char *fl = s_file_level;
637 if (file_level != NULL) {
638 s_file_level = strdup(file_level);
639 } else {
640 s_file_level = NULL;
641 }
642 free(fl);
643 }
644
645 int cs_log_print_prefix(enum cs_log_level level, const char *file, int ln) WEAK;
cs_log_print_prefix(enum cs_log_level level,const char * file,int ln)646 int cs_log_print_prefix(enum cs_log_level level, const char *file, int ln) {
647 char prefix[CS_LOG_PREFIX_LEN], *q;
648 const char *p;
649 size_t fl = 0, ll = 0, pl = 0;
650
651 if (level > cs_log_level && s_file_level == NULL) return 0;
652
653 p = file + strlen(file);
654
655 while (p != file) {
656 const char c = *(p - 1);
657 if (c == '/' || c == '\\') break;
658 p--;
659 fl++;
660 }
661
662 ll = (ln < 10000 ? (ln < 1000 ? (ln < 100 ? (ln < 10 ? 1 : 2) : 3) : 4) : 5);
663 if (fl > (sizeof(prefix) - ll - 2)) fl = (sizeof(prefix) - ll - 2);
664
665 pl = fl + 1 + ll;
666 memcpy(prefix, p, fl);
667 q = prefix + pl;
668 memset(q, ' ', sizeof(prefix) - pl);
669 do {
670 *(--q) = '0' + (ln % 10);
671 ln /= 10;
672 } while (ln > 0);
673 *(--q) = ':';
674
675 if (s_file_level != NULL) {
676 enum cs_log_level pll = cs_log_level;
677 struct mg_str fl = mg_mk_str(s_file_level), ps = MG_MK_STR_N(prefix, pl);
678 struct mg_str k, v;
679 while ((fl = mg_next_comma_list_entry_n(fl, &k, &v)).p != NULL) {
680 bool yes = !(!mg_str_starts_with(ps, k) || v.len == 0);
681 if (!yes) continue;
682 pll = (enum cs_log_level)(*v.p - '0');
683 break;
684 }
685 if (level > pll) return 0;
686 }
687
688 if (cs_log_file == NULL) cs_log_file = stderr;
689 cs_log_cur_msg_level = level;
690 fwrite(prefix, 1, sizeof(prefix), cs_log_file);
691 #if CS_LOG_ENABLE_TS_DIFF
692 {
693 double now = cs_time();
694 fprintf(cs_log_file, "%7u ", (unsigned int) ((now - cs_log_ts) * 1000000));
695 cs_log_ts = now;
696 }
697 #endif
698 return 1;
699 }
700
701 void cs_log_printf(const char *fmt, ...) WEAK;
cs_log_printf(const char * fmt,...)702 void cs_log_printf(const char *fmt, ...) {
703 va_list ap;
704 va_start(ap, fmt);
705 vfprintf(cs_log_file, fmt, ap);
706 va_end(ap);
707 fputc('\n', cs_log_file);
708 fflush(cs_log_file);
709 cs_log_cur_msg_level = LL_NONE;
710 }
711
712 void cs_log_set_file(FILE *file) WEAK;
cs_log_set_file(FILE * file)713 void cs_log_set_file(FILE *file) {
714 cs_log_file = file;
715 }
716
717 #else
718
cs_log_set_file_level(const char * file_level)719 void cs_log_set_file_level(const char *file_level) {
720 (void) file_level;
721 }
722
723 #endif /* CS_ENABLE_STDIO */
724
725 void cs_log_set_level(enum cs_log_level level) WEAK;
cs_log_set_level(enum cs_log_level level)726 void cs_log_set_level(enum cs_log_level level) {
727 cs_log_level = level;
728 #if CS_LOG_ENABLE_TS_DIFF && CS_ENABLE_STDIO
729 cs_log_ts = cs_time();
730 #endif
731 }
732 #ifdef MG_MODULE_LINES
733 #line 1 "common/cs_dirent.h"
734 #endif
735 /*
736 * Copyright (c) 2014-2018 Cesanta Software Limited
737 * All rights reserved
738 *
739 * Licensed under the Apache License, Version 2.0 (the ""License"");
740 * you may not use this file except in compliance with the License.
741 * You may obtain a copy of the License at
742 *
743 * http://www.apache.org/licenses/LICENSE-2.0
744 *
745 * Unless required by applicable law or agreed to in writing, software
746 * distributed under the License is distributed on an ""AS IS"" BASIS,
747 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
748 * See the License for the specific language governing permissions and
749 * limitations under the License.
750 */
751
752 #ifndef CS_COMMON_CS_DIRENT_H_
753 #define CS_COMMON_CS_DIRENT_H_
754
755 #include <limits.h>
756
757 /* Amalgamated: #include "common/platform.h" */
758
759 #ifdef __cplusplus
760 extern "C" {
761 #endif /* __cplusplus */
762
763 #ifdef CS_DEFINE_DIRENT
764 typedef struct { int dummy; } DIR;
765
766 struct dirent {
767 int d_ino;
768 #ifdef _WIN32
769 char d_name[MAX_PATH];
770 #else
771 /* TODO(rojer): Use PATH_MAX but make sure it's sane on every platform */
772 char d_name[256];
773 #endif
774 };
775
776 DIR *opendir(const char *dir_name);
777 int closedir(DIR *dir);
778 struct dirent *readdir(DIR *dir);
779 #endif /* CS_DEFINE_DIRENT */
780
781 #ifdef __cplusplus
782 }
783 #endif /* __cplusplus */
784
785 #endif /* CS_COMMON_CS_DIRENT_H_ */
786 #ifdef MG_MODULE_LINES
787 #line 1 "common/cs_dirent.c"
788 #endif
789 /*
790 * Copyright (c) 2014-2018 Cesanta Software Limited
791 * All rights reserved
792 *
793 * Licensed under the Apache License, Version 2.0 (the ""License"");
794 * you may not use this file except in compliance with the License.
795 * You may obtain a copy of the License at
796 *
797 * http://www.apache.org/licenses/LICENSE-2.0
798 *
799 * Unless required by applicable law or agreed to in writing, software
800 * distributed under the License is distributed on an ""AS IS"" BASIS,
801 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
802 * See the License for the specific language governing permissions and
803 * limitations under the License.
804 */
805
806 #ifndef EXCLUDE_COMMON
807
808 /* Amalgamated: #include "common/mg_mem.h" */
809 /* Amalgamated: #include "common/cs_dirent.h" */
810
811 /*
812 * This file contains POSIX opendir/closedir/readdir API implementation
813 * for systems which do not natively support it (e.g. Windows).
814 */
815
816 #ifdef _WIN32
817 struct win32_dir {
818 DIR d;
819 HANDLE handle;
820 WIN32_FIND_DATAW info;
821 struct dirent result;
822 };
823
opendir(const char * name)824 DIR *opendir(const char *name) {
825 struct win32_dir *dir = NULL;
826 wchar_t wpath[MAX_PATH];
827 DWORD attrs;
828
829 if (name == NULL) {
830 SetLastError(ERROR_BAD_ARGUMENTS);
831 } else if ((dir = (struct win32_dir *) MG_MALLOC(sizeof(*dir))) == NULL) {
832 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
833 } else {
834 to_wchar(name, wpath, ARRAY_SIZE(wpath));
835 attrs = GetFileAttributesW(wpath);
836 if (attrs != 0xFFFFFFFF && (attrs & FILE_ATTRIBUTE_DIRECTORY)) {
837 (void) wcscat(wpath, L"\\*");
838 dir->handle = FindFirstFileW(wpath, &dir->info);
839 dir->result.d_name[0] = '\0';
840 } else {
841 MG_FREE(dir);
842 dir = NULL;
843 }
844 }
845
846 return (DIR *) dir;
847 }
848
closedir(DIR * d)849 int closedir(DIR *d) {
850 struct win32_dir *dir = (struct win32_dir *) d;
851 int result = 0;
852
853 if (dir != NULL) {
854 if (dir->handle != INVALID_HANDLE_VALUE)
855 result = FindClose(dir->handle) ? 0 : -1;
856 MG_FREE(dir);
857 } else {
858 result = -1;
859 SetLastError(ERROR_BAD_ARGUMENTS);
860 }
861
862 return result;
863 }
864
readdir(DIR * d)865 struct dirent *readdir(DIR *d) {
866 struct win32_dir *dir = (struct win32_dir *) d;
867 struct dirent *result = NULL;
868
869 if (dir) {
870 memset(&dir->result, 0, sizeof(dir->result));
871 if (dir->handle != INVALID_HANDLE_VALUE) {
872 result = &dir->result;
873 (void) WideCharToMultiByte(CP_UTF8, 0, dir->info.cFileName, -1,
874 result->d_name, sizeof(result->d_name), NULL,
875 NULL);
876
877 if (!FindNextFileW(dir->handle, &dir->info)) {
878 (void) FindClose(dir->handle);
879 dir->handle = INVALID_HANDLE_VALUE;
880 }
881
882 } else {
883 SetLastError(ERROR_FILE_NOT_FOUND);
884 }
885 } else {
886 SetLastError(ERROR_BAD_ARGUMENTS);
887 }
888
889 return result;
890 }
891 #endif
892
893 #endif /* EXCLUDE_COMMON */
894
895 /* ISO C requires a translation unit to contain at least one declaration */
896 typedef int cs_dirent_dummy;
897 #ifdef MG_MODULE_LINES
898 #line 1 "common/cs_time.c"
899 #endif
900 /*
901 * Copyright (c) 2014-2018 Cesanta Software Limited
902 * All rights reserved
903 *
904 * Licensed under the Apache License, Version 2.0 (the ""License"");
905 * you may not use this file except in compliance with the License.
906 * You may obtain a copy of the License at
907 *
908 * http://www.apache.org/licenses/LICENSE-2.0
909 *
910 * Unless required by applicable law or agreed to in writing, software
911 * distributed under the License is distributed on an ""AS IS"" BASIS,
912 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
913 * See the License for the specific language governing permissions and
914 * limitations under the License.
915 */
916
917 /* Amalgamated: #include "common/cs_time.h" */
918
919 #ifndef _WIN32
920 #include <stddef.h>
921 /*
922 * There is no sys/time.h on ARMCC.
923 */
924 #if !(defined(__ARMCC_VERSION) || defined(__ICCARM__)) && \
925 !defined(__TI_COMPILER_VERSION__) && \
926 (!defined(CS_PLATFORM) || CS_PLATFORM != CS_P_NXP_LPC)
927 #include <sys/time.h>
928 #endif
929 #else
930 #include <windows.h>
931 #endif
932
933 double cs_time(void) WEAK;
cs_time(void)934 double cs_time(void) {
935 double now;
936 #ifndef _WIN32
937 struct timeval tv;
938 if (gettimeofday(&tv, NULL /* tz */) != 0) return 0;
939 now = (double) tv.tv_sec + (((double) tv.tv_usec) / 1000000.0);
940 #else
941 SYSTEMTIME sysnow;
942 FILETIME ftime;
943 GetLocalTime(&sysnow);
944 SystemTimeToFileTime(&sysnow, &ftime);
945 /*
946 * 1. VC 6.0 doesn't support conversion uint64 -> double, so, using int64
947 * This should not cause a problems in this (21th) century
948 * 2. Windows FILETIME is a number of 100-nanosecond intervals since January
949 * 1, 1601 while time_t is a number of _seconds_ since January 1, 1970 UTC,
950 * thus, we need to convert to seconds and adjust amount (subtract 11644473600
951 * seconds)
952 */
953 now = (double) (((int64_t) ftime.dwLowDateTime +
954 ((int64_t) ftime.dwHighDateTime << 32)) /
955 10000000.0) -
956 11644473600;
957 #endif /* _WIN32 */
958 return now;
959 }
960
cs_timegm(const struct tm * tm)961 double cs_timegm(const struct tm *tm) {
962 /* Month-to-day offset for non-leap-years. */
963 static const int month_day[12] = {0, 31, 59, 90, 120, 151,
964 181, 212, 243, 273, 304, 334};
965
966 /* Most of the calculation is easy; leap years are the main difficulty. */
967 int month = tm->tm_mon % 12;
968 int year = tm->tm_year + tm->tm_mon / 12;
969 int year_for_leap;
970 int64_t rt;
971
972 if (month < 0) { /* Negative values % 12 are still negative. */
973 month += 12;
974 --year;
975 }
976
977 /* This is the number of Februaries since 1900. */
978 year_for_leap = (month > 1) ? year + 1 : year;
979
980 rt =
981 tm->tm_sec /* Seconds */
982 +
983 60 *
984 (tm->tm_min /* Minute = 60 seconds */
985 +
986 60 * (tm->tm_hour /* Hour = 60 minutes */
987 +
988 24 * (month_day[month] + tm->tm_mday - 1 /* Day = 24 hours */
989 + 365 * (year - 70) /* Year = 365 days */
990 + (year_for_leap - 69) / 4 /* Every 4 years is leap... */
991 - (year_for_leap - 1) / 100 /* Except centuries... */
992 + (year_for_leap + 299) / 400))); /* Except 400s. */
993 return rt < 0 ? -1 : (double) rt;
994 }
995 #ifdef MG_MODULE_LINES
996 #line 1 "common/cs_endian.h"
997 #endif
998 /*
999 * Copyright (c) 2014-2018 Cesanta Software Limited
1000 * All rights reserved
1001 *
1002 * Licensed under the Apache License, Version 2.0 (the ""License"");
1003 * you may not use this file except in compliance with the License.
1004 * You may obtain a copy of the License at
1005 *
1006 * http://www.apache.org/licenses/LICENSE-2.0
1007 *
1008 * Unless required by applicable law or agreed to in writing, software
1009 * distributed under the License is distributed on an ""AS IS"" BASIS,
1010 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1011 * See the License for the specific language governing permissions and
1012 * limitations under the License.
1013 */
1014
1015 #ifndef CS_COMMON_CS_ENDIAN_H_
1016 #define CS_COMMON_CS_ENDIAN_H_
1017
1018 #ifdef __cplusplus
1019 extern "C" {
1020 #endif
1021
1022 /*
1023 * clang with std=-c99 uses __LITTLE_ENDIAN, by default
1024 * while for ex, RTOS gcc - LITTLE_ENDIAN, by default
1025 * it depends on __USE_BSD, but let's have everything
1026 */
1027 #if !defined(BYTE_ORDER) && defined(__BYTE_ORDER)
1028 #define BYTE_ORDER __BYTE_ORDER
1029 #ifndef LITTLE_ENDIAN
1030 #define LITTLE_ENDIAN __LITTLE_ENDIAN
1031 #endif /* LITTLE_ENDIAN */
1032 #ifndef BIG_ENDIAN
1033 #define BIG_ENDIAN __LITTLE_ENDIAN
1034 #endif /* BIG_ENDIAN */
1035 #endif /* BYTE_ORDER */
1036
1037 #ifdef __cplusplus
1038 }
1039 #endif
1040
1041 #endif /* CS_COMMON_CS_ENDIAN_H_ */
1042 #ifdef MG_MODULE_LINES
1043 #line 1 "common/cs_md5.c"
1044 #endif
1045 /*
1046 * This code implements the MD5 message-digest algorithm.
1047 * The algorithm is due to Ron Rivest. This code was
1048 * written by Colin Plumb in 1993, no copyright is claimed.
1049 * This code is in the public domain; do with it what you wish.
1050 *
1051 * Equivalent code is available from RSA Data Security, Inc.
1052 * This code has been tested against that, and is equivalent,
1053 * except that you don't need to include two pages of legalese
1054 * with every copy.
1055 *
1056 * To compute the message digest of a chunk of bytes, declare an
1057 * MD5Context structure, pass it to MD5Init, call MD5Update as
1058 * needed on buffers full of bytes, and then call MD5Final, which
1059 * will fill a supplied 16-byte array with the digest.
1060 */
1061
1062 /* Amalgamated: #include "common/cs_md5.h" */
1063 /* Amalgamated: #include "common/str_util.h" */
1064
1065 #if !defined(EXCLUDE_COMMON)
1066 #if !CS_DISABLE_MD5
1067
1068 /* Amalgamated: #include "common/cs_endian.h" */
1069
byteReverse(unsigned char * buf,unsigned longs)1070 static void byteReverse(unsigned char *buf, unsigned longs) {
1071 /* Forrest: MD5 expect LITTLE_ENDIAN, swap if BIG_ENDIAN */
1072 #if BYTE_ORDER == BIG_ENDIAN
1073 do {
1074 uint32_t t = (uint32_t)((unsigned) buf[3] << 8 | buf[2]) << 16 |
1075 ((unsigned) buf[1] << 8 | buf[0]);
1076 *(uint32_t *) buf = t;
1077 buf += 4;
1078 } while (--longs);
1079 #else
1080 (void) buf;
1081 (void) longs;
1082 #endif
1083 }
1084
1085 #define F1(x, y, z) (z ^ (x & (y ^ z)))
1086 #define F2(x, y, z) F1(z, x, y)
1087 #define F3(x, y, z) (x ^ y ^ z)
1088 #define F4(x, y, z) (y ^ (x | ~z))
1089
1090 #define MD5STEP(f, w, x, y, z, data, s) \
1091 (w += f(x, y, z) + data, w = w << s | w >> (32 - s), w += x)
1092
1093 /*
1094 * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
1095 * initialization constants.
1096 */
cs_md5_init(cs_md5_ctx * ctx)1097 void cs_md5_init(cs_md5_ctx *ctx) {
1098 ctx->buf[0] = 0x67452301;
1099 ctx->buf[1] = 0xefcdab89;
1100 ctx->buf[2] = 0x98badcfe;
1101 ctx->buf[3] = 0x10325476;
1102
1103 ctx->bits[0] = 0;
1104 ctx->bits[1] = 0;
1105 }
1106
cs_md5_transform(uint32_t buf[4],uint32_t const in[16])1107 static void cs_md5_transform(uint32_t buf[4], uint32_t const in[16]) {
1108 register uint32_t a, b, c, d;
1109
1110 a = buf[0];
1111 b = buf[1];
1112 c = buf[2];
1113 d = buf[3];
1114
1115 MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
1116 MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
1117 MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
1118 MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
1119 MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
1120 MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
1121 MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
1122 MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
1123 MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
1124 MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
1125 MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
1126 MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
1127 MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
1128 MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
1129 MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
1130 MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
1131
1132 MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
1133 MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
1134 MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
1135 MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
1136 MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
1137 MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
1138 MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
1139 MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
1140 MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
1141 MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
1142 MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
1143 MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
1144 MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
1145 MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
1146 MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
1147 MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
1148
1149 MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
1150 MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
1151 MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
1152 MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
1153 MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
1154 MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
1155 MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
1156 MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
1157 MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
1158 MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
1159 MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
1160 MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
1161 MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
1162 MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
1163 MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
1164 MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
1165
1166 MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
1167 MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
1168 MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
1169 MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
1170 MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
1171 MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
1172 MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
1173 MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
1174 MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
1175 MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
1176 MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
1177 MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
1178 MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
1179 MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
1180 MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
1181 MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
1182
1183 buf[0] += a;
1184 buf[1] += b;
1185 buf[2] += c;
1186 buf[3] += d;
1187 }
1188
cs_md5_update(cs_md5_ctx * ctx,const unsigned char * buf,size_t len)1189 void cs_md5_update(cs_md5_ctx *ctx, const unsigned char *buf, size_t len) {
1190 uint32_t t;
1191
1192 t = ctx->bits[0];
1193 if ((ctx->bits[0] = t + ((uint32_t) len << 3)) < t) ctx->bits[1]++;
1194 ctx->bits[1] += (uint32_t) len >> 29;
1195
1196 t = (t >> 3) & 0x3f;
1197
1198 if (t) {
1199 unsigned char *p = (unsigned char *) ctx->in + t;
1200
1201 t = 64 - t;
1202 if (len < t) {
1203 memcpy(p, buf, len);
1204 return;
1205 }
1206 memcpy(p, buf, t);
1207 byteReverse(ctx->in, 16);
1208 cs_md5_transform(ctx->buf, (uint32_t *) ctx->in);
1209 buf += t;
1210 len -= t;
1211 }
1212
1213 while (len >= 64) {
1214 memcpy(ctx->in, buf, 64);
1215 byteReverse(ctx->in, 16);
1216 cs_md5_transform(ctx->buf, (uint32_t *) ctx->in);
1217 buf += 64;
1218 len -= 64;
1219 }
1220
1221 memcpy(ctx->in, buf, len);
1222 }
1223
cs_md5_final(unsigned char * digest,cs_md5_ctx * ctx)1224 void cs_md5_final(unsigned char *digest, cs_md5_ctx *ctx) {
1225 unsigned count;
1226 unsigned char *p;
1227 uint32_t *a;
1228
1229 count = (ctx->bits[0] >> 3) & 0x3F;
1230
1231 p = ctx->in + count;
1232 *p++ = 0x80;
1233 count = 64 - 1 - count;
1234 if (count < 8) {
1235 memset(p, 0, count);
1236 byteReverse(ctx->in, 16);
1237 cs_md5_transform(ctx->buf, (uint32_t *) ctx->in);
1238 memset(ctx->in, 0, 56);
1239 } else {
1240 memset(p, 0, count - 8);
1241 }
1242 byteReverse(ctx->in, 14);
1243
1244 a = (uint32_t *) ctx->in;
1245 a[14] = ctx->bits[0];
1246 a[15] = ctx->bits[1];
1247
1248 cs_md5_transform(ctx->buf, (uint32_t *) ctx->in);
1249 byteReverse((unsigned char *) ctx->buf, 4);
1250 memcpy(digest, ctx->buf, 16);
1251 memset((char *) ctx, 0, sizeof(*ctx));
1252 }
1253
1254 #endif /* CS_DISABLE_MD5 */
1255 #endif /* EXCLUDE_COMMON */
1256 #ifdef MG_MODULE_LINES
1257 #line 1 "common/cs_sha1.c"
1258 #endif
1259 /* Copyright(c) By Steve Reid <steve@edmweb.com> */
1260 /* 100% Public Domain */
1261
1262 /* Amalgamated: #include "common/cs_sha1.h" */
1263
1264 #if !CS_DISABLE_SHA1 && !defined(EXCLUDE_COMMON)
1265
1266 /* Amalgamated: #include "common/cs_endian.h" */
1267
1268 #define SHA1HANDSOFF
1269 #if defined(__sun)
1270 /* Amalgamated: #include "common/solarisfixes.h" */
1271 #endif
1272
1273 union char64long16 {
1274 unsigned char c[64];
1275 uint32_t l[16];
1276 };
1277
1278 #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
1279
blk0(union char64long16 * block,int i)1280 static uint32_t blk0(union char64long16 *block, int i) {
1281 /* Forrest: SHA expect BIG_ENDIAN, swap if LITTLE_ENDIAN */
1282 #if BYTE_ORDER == LITTLE_ENDIAN
1283 block->l[i] =
1284 (rol(block->l[i], 24) & 0xFF00FF00) | (rol(block->l[i], 8) & 0x00FF00FF);
1285 #endif
1286 return block->l[i];
1287 }
1288
1289 /* Avoid redefine warning (ARM /usr/include/sys/ucontext.h define R0~R4) */
1290 #undef blk
1291 #undef R0
1292 #undef R1
1293 #undef R2
1294 #undef R3
1295 #undef R4
1296
1297 #define blk(i) \
1298 (block->l[i & 15] = rol(block->l[(i + 13) & 15] ^ block->l[(i + 8) & 15] ^ \
1299 block->l[(i + 2) & 15] ^ block->l[i & 15], \
1300 1))
1301 #define R0(v, w, x, y, z, i) \
1302 z += ((w & (x ^ y)) ^ y) + blk0(block, i) + 0x5A827999 + rol(v, 5); \
1303 w = rol(w, 30);
1304 #define R1(v, w, x, y, z, i) \
1305 z += ((w & (x ^ y)) ^ y) + blk(i) + 0x5A827999 + rol(v, 5); \
1306 w = rol(w, 30);
1307 #define R2(v, w, x, y, z, i) \
1308 z += (w ^ x ^ y) + blk(i) + 0x6ED9EBA1 + rol(v, 5); \
1309 w = rol(w, 30);
1310 #define R3(v, w, x, y, z, i) \
1311 z += (((w | x) & y) | (w & x)) + blk(i) + 0x8F1BBCDC + rol(v, 5); \
1312 w = rol(w, 30);
1313 #define R4(v, w, x, y, z, i) \
1314 z += (w ^ x ^ y) + blk(i) + 0xCA62C1D6 + rol(v, 5); \
1315 w = rol(w, 30);
1316
cs_sha1_transform(uint32_t state[5],const unsigned char buffer[64])1317 void cs_sha1_transform(uint32_t state[5], const unsigned char buffer[64]) {
1318 uint32_t a, b, c, d, e;
1319 union char64long16 block[1];
1320
1321 memcpy(block, buffer, 64);
1322 a = state[0];
1323 b = state[1];
1324 c = state[2];
1325 d = state[3];
1326 e = state[4];
1327 R0(a, b, c, d, e, 0);
1328 R0(e, a, b, c, d, 1);
1329 R0(d, e, a, b, c, 2);
1330 R0(c, d, e, a, b, 3);
1331 R0(b, c, d, e, a, 4);
1332 R0(a, b, c, d, e, 5);
1333 R0(e, a, b, c, d, 6);
1334 R0(d, e, a, b, c, 7);
1335 R0(c, d, e, a, b, 8);
1336 R0(b, c, d, e, a, 9);
1337 R0(a, b, c, d, e, 10);
1338 R0(e, a, b, c, d, 11);
1339 R0(d, e, a, b, c, 12);
1340 R0(c, d, e, a, b, 13);
1341 R0(b, c, d, e, a, 14);
1342 R0(a, b, c, d, e, 15);
1343 R1(e, a, b, c, d, 16);
1344 R1(d, e, a, b, c, 17);
1345 R1(c, d, e, a, b, 18);
1346 R1(b, c, d, e, a, 19);
1347 R2(a, b, c, d, e, 20);
1348 R2(e, a, b, c, d, 21);
1349 R2(d, e, a, b, c, 22);
1350 R2(c, d, e, a, b, 23);
1351 R2(b, c, d, e, a, 24);
1352 R2(a, b, c, d, e, 25);
1353 R2(e, a, b, c, d, 26);
1354 R2(d, e, a, b, c, 27);
1355 R2(c, d, e, a, b, 28);
1356 R2(b, c, d, e, a, 29);
1357 R2(a, b, c, d, e, 30);
1358 R2(e, a, b, c, d, 31);
1359 R2(d, e, a, b, c, 32);
1360 R2(c, d, e, a, b, 33);
1361 R2(b, c, d, e, a, 34);
1362 R2(a, b, c, d, e, 35);
1363 R2(e, a, b, c, d, 36);
1364 R2(d, e, a, b, c, 37);
1365 R2(c, d, e, a, b, 38);
1366 R2(b, c, d, e, a, 39);
1367 R3(a, b, c, d, e, 40);
1368 R3(e, a, b, c, d, 41);
1369 R3(d, e, a, b, c, 42);
1370 R3(c, d, e, a, b, 43);
1371 R3(b, c, d, e, a, 44);
1372 R3(a, b, c, d, e, 45);
1373 R3(e, a, b, c, d, 46);
1374 R3(d, e, a, b, c, 47);
1375 R3(c, d, e, a, b, 48);
1376 R3(b, c, d, e, a, 49);
1377 R3(a, b, c, d, e, 50);
1378 R3(e, a, b, c, d, 51);
1379 R3(d, e, a, b, c, 52);
1380 R3(c, d, e, a, b, 53);
1381 R3(b, c, d, e, a, 54);
1382 R3(a, b, c, d, e, 55);
1383 R3(e, a, b, c, d, 56);
1384 R3(d, e, a, b, c, 57);
1385 R3(c, d, e, a, b, 58);
1386 R3(b, c, d, e, a, 59);
1387 R4(a, b, c, d, e, 60);
1388 R4(e, a, b, c, d, 61);
1389 R4(d, e, a, b, c, 62);
1390 R4(c, d, e, a, b, 63);
1391 R4(b, c, d, e, a, 64);
1392 R4(a, b, c, d, e, 65);
1393 R4(e, a, b, c, d, 66);
1394 R4(d, e, a, b, c, 67);
1395 R4(c, d, e, a, b, 68);
1396 R4(b, c, d, e, a, 69);
1397 R4(a, b, c, d, e, 70);
1398 R4(e, a, b, c, d, 71);
1399 R4(d, e, a, b, c, 72);
1400 R4(c, d, e, a, b, 73);
1401 R4(b, c, d, e, a, 74);
1402 R4(a, b, c, d, e, 75);
1403 R4(e, a, b, c, d, 76);
1404 R4(d, e, a, b, c, 77);
1405 R4(c, d, e, a, b, 78);
1406 R4(b, c, d, e, a, 79);
1407 state[0] += a;
1408 state[1] += b;
1409 state[2] += c;
1410 state[3] += d;
1411 state[4] += e;
1412 /* Erase working structures. The order of operations is important,
1413 * used to ensure that compiler doesn't optimize those out. */
1414 memset(block, 0, sizeof(block));
1415 a = b = c = d = e = 0;
1416 (void) a;
1417 (void) b;
1418 (void) c;
1419 (void) d;
1420 (void) e;
1421 }
1422
cs_sha1_init(cs_sha1_ctx * context)1423 void cs_sha1_init(cs_sha1_ctx *context) {
1424 context->state[0] = 0x67452301;
1425 context->state[1] = 0xEFCDAB89;
1426 context->state[2] = 0x98BADCFE;
1427 context->state[3] = 0x10325476;
1428 context->state[4] = 0xC3D2E1F0;
1429 context->count[0] = context->count[1] = 0;
1430 }
1431
cs_sha1_update(cs_sha1_ctx * context,const unsigned char * data,uint32_t len)1432 void cs_sha1_update(cs_sha1_ctx *context, const unsigned char *data,
1433 uint32_t len) {
1434 uint32_t i, j;
1435
1436 j = context->count[0];
1437 if ((context->count[0] += len << 3) < j) context->count[1]++;
1438 context->count[1] += (len >> 29);
1439 j = (j >> 3) & 63;
1440 if ((j + len) > 63) {
1441 memcpy(&context->buffer[j], data, (i = 64 - j));
1442 cs_sha1_transform(context->state, context->buffer);
1443 for (; i + 63 < len; i += 64) {
1444 cs_sha1_transform(context->state, &data[i]);
1445 }
1446 j = 0;
1447 } else
1448 i = 0;
1449 memcpy(&context->buffer[j], &data[i], len - i);
1450 }
1451
cs_sha1_final(unsigned char digest[20],cs_sha1_ctx * context)1452 void cs_sha1_final(unsigned char digest[20], cs_sha1_ctx *context) {
1453 unsigned i;
1454 unsigned char finalcount[8], c;
1455
1456 for (i = 0; i < 8; i++) {
1457 finalcount[i] = (unsigned char) ((context->count[(i >= 4 ? 0 : 1)] >>
1458 ((3 - (i & 3)) * 8)) &
1459 255);
1460 }
1461 c = 0200;
1462 cs_sha1_update(context, &c, 1);
1463 while ((context->count[0] & 504) != 448) {
1464 c = 0000;
1465 cs_sha1_update(context, &c, 1);
1466 }
1467 cs_sha1_update(context, finalcount, 8);
1468 for (i = 0; i < 20; i++) {
1469 digest[i] =
1470 (unsigned char) ((context->state[i >> 2] >> ((3 - (i & 3)) * 8)) & 255);
1471 }
1472 memset(context, '\0', sizeof(*context));
1473 memset(&finalcount, '\0', sizeof(finalcount));
1474 }
1475
cs_hmac_sha1(const unsigned char * key,size_t keylen,const unsigned char * data,size_t datalen,unsigned char out[20])1476 void cs_hmac_sha1(const unsigned char *key, size_t keylen,
1477 const unsigned char *data, size_t datalen,
1478 unsigned char out[20]) {
1479 cs_sha1_ctx ctx;
1480 unsigned char buf1[64], buf2[64], tmp_key[20], i;
1481
1482 if (keylen > sizeof(buf1)) {
1483 cs_sha1_init(&ctx);
1484 cs_sha1_update(&ctx, key, keylen);
1485 cs_sha1_final(tmp_key, &ctx);
1486 key = tmp_key;
1487 keylen = sizeof(tmp_key);
1488 }
1489
1490 memset(buf1, 0, sizeof(buf1));
1491 memset(buf2, 0, sizeof(buf2));
1492 memcpy(buf1, key, keylen);
1493 memcpy(buf2, key, keylen);
1494
1495 for (i = 0; i < sizeof(buf1); i++) {
1496 buf1[i] ^= 0x36;
1497 buf2[i] ^= 0x5c;
1498 }
1499
1500 cs_sha1_init(&ctx);
1501 cs_sha1_update(&ctx, buf1, sizeof(buf1));
1502 cs_sha1_update(&ctx, data, datalen);
1503 cs_sha1_final(out, &ctx);
1504
1505 cs_sha1_init(&ctx);
1506 cs_sha1_update(&ctx, buf2, sizeof(buf2));
1507 cs_sha1_update(&ctx, out, 20);
1508 cs_sha1_final(out, &ctx);
1509 }
1510
1511 #endif /* EXCLUDE_COMMON */
1512 #ifdef MG_MODULE_LINES
1513 #line 1 "common/mbuf.c"
1514 #endif
1515 /*
1516 * Copyright (c) 2014-2018 Cesanta Software Limited
1517 * All rights reserved
1518 *
1519 * Licensed under the Apache License, Version 2.0 (the ""License"");
1520 * you may not use this file except in compliance with the License.
1521 * You may obtain a copy of the License at
1522 *
1523 * http://www.apache.org/licenses/LICENSE-2.0
1524 *
1525 * Unless required by applicable law or agreed to in writing, software
1526 * distributed under the License is distributed on an ""AS IS"" BASIS,
1527 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1528 * See the License for the specific language governing permissions and
1529 * limitations under the License.
1530 */
1531
1532 #ifndef EXCLUDE_COMMON
1533
1534 #include <assert.h>
1535 #include <string.h>
1536 /* Amalgamated: #include "common/mbuf.h" */
1537
1538 #ifndef MBUF_REALLOC
1539 #define MBUF_REALLOC realloc
1540 #endif
1541
1542 #ifndef MBUF_FREE
1543 #define MBUF_FREE free
1544 #endif
1545
1546 void mbuf_init(struct mbuf *mbuf, size_t initial_size) WEAK;
mbuf_init(struct mbuf * mbuf,size_t initial_size)1547 void mbuf_init(struct mbuf *mbuf, size_t initial_size) {
1548 mbuf->len = mbuf->size = 0;
1549 mbuf->buf = NULL;
1550 mbuf_resize(mbuf, initial_size);
1551 }
1552
1553 void mbuf_free(struct mbuf *mbuf) WEAK;
mbuf_free(struct mbuf * mbuf)1554 void mbuf_free(struct mbuf *mbuf) {
1555 if (mbuf->buf != NULL) {
1556 MBUF_FREE(mbuf->buf);
1557 mbuf_init(mbuf, 0);
1558 }
1559 }
1560
1561 void mbuf_resize(struct mbuf *a, size_t new_size) WEAK;
mbuf_resize(struct mbuf * a,size_t new_size)1562 void mbuf_resize(struct mbuf *a, size_t new_size) {
1563 if (new_size > a->size || (new_size < a->size && new_size >= a->len)) {
1564 char *buf = (char *) MBUF_REALLOC(a->buf, new_size);
1565 /*
1566 * In case realloc fails, there's not much we can do, except keep things as
1567 * they are. Note that NULL is a valid return value from realloc when
1568 * size == 0, but that is covered too.
1569 */
1570 if (buf == NULL && new_size != 0) return;
1571 a->buf = buf;
1572 a->size = new_size;
1573 }
1574 }
1575
1576 void mbuf_trim(struct mbuf *mbuf) WEAK;
mbuf_trim(struct mbuf * mbuf)1577 void mbuf_trim(struct mbuf *mbuf) {
1578 mbuf_resize(mbuf, mbuf->len);
1579 }
1580
1581 size_t mbuf_insert(struct mbuf *a, size_t off, const void *buf, size_t) WEAK;
mbuf_insert(struct mbuf * a,size_t off,const void * buf,size_t len)1582 size_t mbuf_insert(struct mbuf *a, size_t off, const void *buf, size_t len) {
1583 char *p = NULL;
1584
1585 assert(a != NULL);
1586 assert(a->len <= a->size);
1587 assert(off <= a->len);
1588
1589 /* check overflow */
1590 if (~(size_t) 0 - (size_t) a->buf < len) return 0;
1591
1592 if (a->len + len <= a->size) {
1593 memmove(a->buf + off + len, a->buf + off, a->len - off);
1594 if (buf != NULL) {
1595 memcpy(a->buf + off, buf, len);
1596 }
1597 a->len += len;
1598 } else {
1599 size_t min_size = (a->len + len);
1600 size_t new_size = (size_t)(min_size * MBUF_SIZE_MULTIPLIER);
1601 if (new_size - min_size > MBUF_SIZE_MAX_HEADROOM) {
1602 new_size = min_size + MBUF_SIZE_MAX_HEADROOM;
1603 }
1604 p = (char *) MBUF_REALLOC(a->buf, new_size);
1605 if (p == NULL && new_size != min_size) {
1606 new_size = min_size;
1607 p = (char *) MBUF_REALLOC(a->buf, new_size);
1608 }
1609 if (p != NULL) {
1610 a->buf = p;
1611 if (off != a->len) {
1612 memmove(a->buf + off + len, a->buf + off, a->len - off);
1613 }
1614 if (buf != NULL) memcpy(a->buf + off, buf, len);
1615 a->len += len;
1616 a->size = new_size;
1617 } else {
1618 len = 0;
1619 }
1620 }
1621
1622 return len;
1623 }
1624
1625 size_t mbuf_append(struct mbuf *a, const void *buf, size_t len) WEAK;
mbuf_append(struct mbuf * a,const void * buf,size_t len)1626 size_t mbuf_append(struct mbuf *a, const void *buf, size_t len) {
1627 return mbuf_insert(a, a->len, buf, len);
1628 }
1629
1630 size_t mbuf_append_and_free(struct mbuf *a, void *buf, size_t len) WEAK;
mbuf_append_and_free(struct mbuf * a,void * data,size_t len)1631 size_t mbuf_append_and_free(struct mbuf *a, void *data, size_t len) {
1632 size_t ret;
1633 /* Optimization: if the buffer is currently empty,
1634 * take over the user-provided buffer. */
1635 if (a->len == 0) {
1636 if (a->buf != NULL) free(a->buf);
1637 a->buf = (char *) data;
1638 a->len = a->size = len;
1639 return len;
1640 }
1641 ret = mbuf_insert(a, a->len, data, len);
1642 free(data);
1643 return ret;
1644 }
1645
1646 void mbuf_remove(struct mbuf *mb, size_t n) WEAK;
mbuf_remove(struct mbuf * mb,size_t n)1647 void mbuf_remove(struct mbuf *mb, size_t n) {
1648 if (n > 0 && n <= mb->len) {
1649 memmove(mb->buf, mb->buf + n, mb->len - n);
1650 mb->len -= n;
1651 }
1652 }
1653
1654 void mbuf_clear(struct mbuf *mb) WEAK;
mbuf_clear(struct mbuf * mb)1655 void mbuf_clear(struct mbuf *mb) {
1656 mb->len = 0;
1657 }
1658
1659 void mbuf_move(struct mbuf *from, struct mbuf *to) WEAK;
mbuf_move(struct mbuf * from,struct mbuf * to)1660 void mbuf_move(struct mbuf *from, struct mbuf *to) {
1661 memcpy(to, from, sizeof(*to));
1662 memset(from, 0, sizeof(*from));
1663 }
1664
1665 #endif /* EXCLUDE_COMMON */
1666 #ifdef MG_MODULE_LINES
1667 #line 1 "common/mg_str.c"
1668 #endif
1669 /*
1670 * Copyright (c) 2014-2018 Cesanta Software Limited
1671 * All rights reserved
1672 *
1673 * Licensed under the Apache License, Version 2.0 (the ""License"");
1674 * you may not use this file except in compliance with the License.
1675 * You may obtain a copy of the License at
1676 *
1677 * http://www.apache.org/licenses/LICENSE-2.0
1678 *
1679 * Unless required by applicable law or agreed to in writing, software
1680 * distributed under the License is distributed on an ""AS IS"" BASIS,
1681 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1682 * See the License for the specific language governing permissions and
1683 * limitations under the License.
1684 */
1685
1686 /* Amalgamated: #include "common/mg_mem.h" */
1687 /* Amalgamated: #include "common/mg_str.h" */
1688 /* Amalgamated: #include "common/platform.h" */
1689
1690 #include <ctype.h>
1691 #include <stdlib.h>
1692 #include <string.h>
1693
1694 int mg_ncasecmp(const char *s1, const char *s2, size_t len) WEAK;
1695
1696 struct mg_str mg_mk_str(const char *s) WEAK;
mg_mk_str(const char * s)1697 struct mg_str mg_mk_str(const char *s) {
1698 struct mg_str ret = {s, 0};
1699 if (s != NULL) ret.len = strlen(s);
1700 return ret;
1701 }
1702
1703 struct mg_str mg_mk_str_n(const char *s, size_t len) WEAK;
mg_mk_str_n(const char * s,size_t len)1704 struct mg_str mg_mk_str_n(const char *s, size_t len) {
1705 struct mg_str ret = {s, len};
1706 return ret;
1707 }
1708
1709 int mg_vcmp(const struct mg_str *str1, const char *str2) WEAK;
mg_vcmp(const struct mg_str * str1,const char * str2)1710 int mg_vcmp(const struct mg_str *str1, const char *str2) {
1711 size_t n2 = strlen(str2), n1 = str1->len;
1712 int r = strncmp(str1->p, str2, (n1 < n2) ? n1 : n2);
1713 if (r == 0) {
1714 return n1 - n2;
1715 }
1716 return r;
1717 }
1718
1719 int mg_vcasecmp(const struct mg_str *str1, const char *str2) WEAK;
mg_vcasecmp(const struct mg_str * str1,const char * str2)1720 int mg_vcasecmp(const struct mg_str *str1, const char *str2) {
1721 size_t n2 = strlen(str2), n1 = str1->len;
1722 int r = mg_ncasecmp(str1->p, str2, (n1 < n2) ? n1 : n2);
1723 if (r == 0) {
1724 return n1 - n2;
1725 }
1726 return r;
1727 }
1728
mg_strdup_common(const struct mg_str s,int nul_terminate)1729 static struct mg_str mg_strdup_common(const struct mg_str s,
1730 int nul_terminate) {
1731 struct mg_str r = {NULL, 0};
1732 if (s.len > 0 && s.p != NULL) {
1733 char *sc = (char *) MG_MALLOC(s.len + (nul_terminate ? 1 : 0));
1734 if (sc != NULL) {
1735 memcpy(sc, s.p, s.len);
1736 if (nul_terminate) sc[s.len] = '\0';
1737 r.p = sc;
1738 r.len = s.len;
1739 }
1740 }
1741 return r;
1742 }
1743
1744 struct mg_str mg_strdup(const struct mg_str s) WEAK;
mg_strdup(const struct mg_str s)1745 struct mg_str mg_strdup(const struct mg_str s) {
1746 return mg_strdup_common(s, 0 /* NUL-terminate */);
1747 }
1748
1749 struct mg_str mg_strdup_nul(const struct mg_str s) WEAK;
mg_strdup_nul(const struct mg_str s)1750 struct mg_str mg_strdup_nul(const struct mg_str s) {
1751 return mg_strdup_common(s, 1 /* NUL-terminate */);
1752 }
1753
1754 const char *mg_strchr(const struct mg_str s, int c) WEAK;
mg_strchr(const struct mg_str s,int c)1755 const char *mg_strchr(const struct mg_str s, int c) {
1756 size_t i;
1757 for (i = 0; i < s.len; i++) {
1758 if (s.p[i] == c) return &s.p[i];
1759 }
1760 return NULL;
1761 }
1762
1763 int mg_strcmp(const struct mg_str str1, const struct mg_str str2) WEAK;
mg_strcmp(const struct mg_str str1,const struct mg_str str2)1764 int mg_strcmp(const struct mg_str str1, const struct mg_str str2) {
1765 size_t i = 0;
1766 while (i < str1.len && i < str2.len) {
1767 if (str1.p[i] < str2.p[i]) return -1;
1768 if (str1.p[i] > str2.p[i]) return 1;
1769 i++;
1770 }
1771 if (i < str1.len) return 1;
1772 if (i < str2.len) return -1;
1773 return 0;
1774 }
1775
1776 int mg_strncmp(const struct mg_str, const struct mg_str, size_t n) WEAK;
mg_strncmp(const struct mg_str str1,const struct mg_str str2,size_t n)1777 int mg_strncmp(const struct mg_str str1, const struct mg_str str2, size_t n) {
1778 struct mg_str s1 = str1;
1779 struct mg_str s2 = str2;
1780
1781 if (s1.len > n) {
1782 s1.len = n;
1783 }
1784 if (s2.len > n) {
1785 s2.len = n;
1786 }
1787 return mg_strcmp(s1, s2);
1788 }
1789
1790 void mg_strfree(struct mg_str *s) WEAK;
mg_strfree(struct mg_str * s)1791 void mg_strfree(struct mg_str *s) {
1792 char *sp = (char *) s->p;
1793 s->p = NULL;
1794 s->len = 0;
1795 if (sp != NULL) free(sp);
1796 }
1797
1798 const char *mg_strstr(const struct mg_str haystack,
1799 const struct mg_str needle) WEAK;
mg_strstr(const struct mg_str haystack,const struct mg_str needle)1800 const char *mg_strstr(const struct mg_str haystack,
1801 const struct mg_str needle) {
1802 size_t i;
1803 if (needle.len > haystack.len) return NULL;
1804 for (i = 0; i <= haystack.len - needle.len; i++) {
1805 if (memcmp(haystack.p + i, needle.p, needle.len) == 0) {
1806 return haystack.p + i;
1807 }
1808 }
1809 return NULL;
1810 }
1811
1812 struct mg_str mg_strstrip(struct mg_str s) WEAK;
mg_strstrip(struct mg_str s)1813 struct mg_str mg_strstrip(struct mg_str s) {
1814 while (s.len > 0 && isspace((int) *s.p)) {
1815 s.p++;
1816 s.len--;
1817 }
1818 while (s.len > 0 && isspace((int) *(s.p + s.len - 1))) {
1819 s.len--;
1820 }
1821 return s;
1822 }
1823
1824 int mg_str_starts_with(struct mg_str s, struct mg_str prefix) WEAK;
mg_str_starts_with(struct mg_str s,struct mg_str prefix)1825 int mg_str_starts_with(struct mg_str s, struct mg_str prefix) {
1826 const struct mg_str sp = MG_MK_STR_N(s.p, prefix.len);
1827 if (s.len < prefix.len) return 0;
1828 return (mg_strcmp(sp, prefix) == 0);
1829 }
1830 #ifdef MG_MODULE_LINES
1831 #line 1 "common/str_util.c"
1832 #endif
1833 /*
1834 * Copyright (c) 2014-2018 Cesanta Software Limited
1835 * All rights reserved
1836 *
1837 * Licensed under the Apache License, Version 2.0 (the ""License"");
1838 * you may not use this file except in compliance with the License.
1839 * You may obtain a copy of the License at
1840 *
1841 * http://www.apache.org/licenses/LICENSE-2.0
1842 *
1843 * Unless required by applicable law or agreed to in writing, software
1844 * distributed under the License is distributed on an ""AS IS"" BASIS,
1845 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1846 * See the License for the specific language governing permissions and
1847 * limitations under the License.
1848 */
1849
1850 #ifndef EXCLUDE_COMMON
1851
1852 /* Amalgamated: #include "common/str_util.h" */
1853 /* Amalgamated: #include "common/mg_mem.h" */
1854 /* Amalgamated: #include "common/platform.h" */
1855
1856 #ifndef C_DISABLE_BUILTIN_SNPRINTF
1857 #define C_DISABLE_BUILTIN_SNPRINTF 0
1858 #endif
1859
1860 /* Amalgamated: #include "common/mg_mem.h" */
1861
1862 size_t c_strnlen(const char *s, size_t maxlen) WEAK;
c_strnlen(const char * s,size_t maxlen)1863 size_t c_strnlen(const char *s, size_t maxlen) {
1864 size_t l = 0;
1865 for (; l < maxlen && s[l] != '\0'; l++) {
1866 }
1867 return l;
1868 }
1869
1870 #define C_SNPRINTF_APPEND_CHAR(ch) \
1871 do { \
1872 if (i < (int) buf_size) buf[i] = ch; \
1873 i++; \
1874 } while (0)
1875
1876 #define C_SNPRINTF_FLAG_ZERO 1
1877
1878 #if C_DISABLE_BUILTIN_SNPRINTF
1879 int c_vsnprintf(char *buf, size_t buf_size, const char *fmt, va_list ap) WEAK;
c_vsnprintf(char * buf,size_t buf_size,const char * fmt,va_list ap)1880 int c_vsnprintf(char *buf, size_t buf_size, const char *fmt, va_list ap) {
1881 return vsnprintf(buf, buf_size, fmt, ap);
1882 }
1883 #else
c_itoa(char * buf,size_t buf_size,int64_t num,int base,int flags,int field_width)1884 static int c_itoa(char *buf, size_t buf_size, int64_t num, int base, int flags,
1885 int field_width) {
1886 char tmp[40];
1887 int i = 0, k = 0, neg = 0;
1888
1889 if (num < 0) {
1890 neg++;
1891 num = -num;
1892 }
1893
1894 /* Print into temporary buffer - in reverse order */
1895 do {
1896 int rem = num % base;
1897 if (rem < 10) {
1898 tmp[k++] = '0' + rem;
1899 } else {
1900 tmp[k++] = 'a' + (rem - 10);
1901 }
1902 num /= base;
1903 } while (num > 0);
1904
1905 /* Zero padding */
1906 if (flags && C_SNPRINTF_FLAG_ZERO) {
1907 while (k < field_width && k < (int) sizeof(tmp) - 1) {
1908 tmp[k++] = '0';
1909 }
1910 }
1911
1912 /* And sign */
1913 if (neg) {
1914 tmp[k++] = '-';
1915 }
1916
1917 /* Now output */
1918 while (--k >= 0) {
1919 C_SNPRINTF_APPEND_CHAR(tmp[k]);
1920 }
1921
1922 return i;
1923 }
1924
1925 int c_vsnprintf(char *buf, size_t buf_size, const char *fmt, va_list ap) WEAK;
c_vsnprintf(char * buf,size_t buf_size,const char * fmt,va_list ap)1926 int c_vsnprintf(char *buf, size_t buf_size, const char *fmt, va_list ap) {
1927 int ch, i = 0, len_mod, flags, precision, field_width;
1928
1929 while ((ch = *fmt++) != '\0') {
1930 if (ch != '%') {
1931 C_SNPRINTF_APPEND_CHAR(ch);
1932 } else {
1933 /*
1934 * Conversion specification:
1935 * zero or more flags (one of: # 0 - <space> + ')
1936 * an optional minimum field width (digits)
1937 * an optional precision (. followed by digits, or *)
1938 * an optional length modifier (one of: hh h l ll L q j z t)
1939 * conversion specifier (one of: d i o u x X e E f F g G a A c s p n)
1940 */
1941 flags = field_width = precision = len_mod = 0;
1942
1943 /* Flags. only zero-pad flag is supported. */
1944 if (*fmt == '0') {
1945 flags |= C_SNPRINTF_FLAG_ZERO;
1946 }
1947
1948 /* Field width */
1949 while (*fmt >= '0' && *fmt <= '9') {
1950 field_width *= 10;
1951 field_width += *fmt++ - '0';
1952 }
1953 /* Dynamic field width */
1954 if (*fmt == '*') {
1955 field_width = va_arg(ap, int);
1956 fmt++;
1957 }
1958
1959 /* Precision */
1960 if (*fmt == '.') {
1961 fmt++;
1962 if (*fmt == '*') {
1963 precision = va_arg(ap, int);
1964 fmt++;
1965 } else {
1966 while (*fmt >= '0' && *fmt <= '9') {
1967 precision *= 10;
1968 precision += *fmt++ - '0';
1969 }
1970 }
1971 }
1972
1973 /* Length modifier */
1974 switch (*fmt) {
1975 case 'h':
1976 case 'l':
1977 case 'L':
1978 case 'I':
1979 case 'q':
1980 case 'j':
1981 case 'z':
1982 case 't':
1983 len_mod = *fmt++;
1984 if (*fmt == 'h') {
1985 len_mod = 'H';
1986 fmt++;
1987 }
1988 if (*fmt == 'l') {
1989 len_mod = 'q';
1990 fmt++;
1991 }
1992 break;
1993 }
1994
1995 ch = *fmt++;
1996 if (ch == 's') {
1997 const char *s = va_arg(ap, const char *); /* Always fetch parameter */
1998 int j;
1999 int pad = field_width - (precision >= 0 ? c_strnlen(s, precision) : 0);
2000 for (j = 0; j < pad; j++) {
2001 C_SNPRINTF_APPEND_CHAR(' ');
2002 }
2003
2004 /* `s` may be NULL in case of %.*s */
2005 if (s != NULL) {
2006 /* Ignore negative and 0 precisions */
2007 for (j = 0; (precision <= 0 || j < precision) && s[j] != '\0'; j++) {
2008 C_SNPRINTF_APPEND_CHAR(s[j]);
2009 }
2010 }
2011 } else if (ch == 'c') {
2012 ch = va_arg(ap, int); /* Always fetch parameter */
2013 C_SNPRINTF_APPEND_CHAR(ch);
2014 } else if (ch == 'd' && len_mod == 0) {
2015 i += c_itoa(buf + i, buf_size - i, va_arg(ap, int), 10, flags,
2016 field_width);
2017 } else if (ch == 'd' && len_mod == 'l') {
2018 i += c_itoa(buf + i, buf_size - i, va_arg(ap, long), 10, flags,
2019 field_width);
2020 #ifdef SSIZE_MAX
2021 } else if (ch == 'd' && len_mod == 'z') {
2022 i += c_itoa(buf + i, buf_size - i, va_arg(ap, ssize_t), 10, flags,
2023 field_width);
2024 #endif
2025 } else if (ch == 'd' && len_mod == 'q') {
2026 i += c_itoa(buf + i, buf_size - i, va_arg(ap, int64_t), 10, flags,
2027 field_width);
2028 } else if ((ch == 'x' || ch == 'u') && len_mod == 0) {
2029 i += c_itoa(buf + i, buf_size - i, va_arg(ap, unsigned),
2030 ch == 'x' ? 16 : 10, flags, field_width);
2031 } else if ((ch == 'x' || ch == 'u') && len_mod == 'l') {
2032 i += c_itoa(buf + i, buf_size - i, va_arg(ap, unsigned long),
2033 ch == 'x' ? 16 : 10, flags, field_width);
2034 } else if ((ch == 'x' || ch == 'u') && len_mod == 'z') {
2035 i += c_itoa(buf + i, buf_size - i, va_arg(ap, size_t),
2036 ch == 'x' ? 16 : 10, flags, field_width);
2037 } else if (ch == 'p') {
2038 unsigned long num = (unsigned long) (uintptr_t) va_arg(ap, void *);
2039 C_SNPRINTF_APPEND_CHAR('0');
2040 C_SNPRINTF_APPEND_CHAR('x');
2041 i += c_itoa(buf + i, buf_size - i, num, 16, flags, 0);
2042 } else {
2043 #ifndef NO_LIBC
2044 /*
2045 * TODO(lsm): abort is not nice in a library, remove it
2046 * Also, ESP8266 SDK doesn't have it
2047 */
2048 abort();
2049 #endif
2050 }
2051 }
2052 }
2053
2054 /* Zero-terminate the result */
2055 if (buf_size > 0) {
2056 buf[i < (int) buf_size ? i : (int) buf_size - 1] = '\0';
2057 }
2058
2059 return i;
2060 }
2061 #endif
2062
2063 int c_snprintf(char *buf, size_t buf_size, const char *fmt, ...) WEAK;
c_snprintf(char * buf,size_t buf_size,const char * fmt,...)2064 int c_snprintf(char *buf, size_t buf_size, const char *fmt, ...) {
2065 int result;
2066 va_list ap;
2067 va_start(ap, fmt);
2068 result = c_vsnprintf(buf, buf_size, fmt, ap);
2069 va_end(ap);
2070 return result;
2071 }
2072
2073 #ifdef _WIN32
to_wchar(const char * path,wchar_t * wbuf,size_t wbuf_len)2074 int to_wchar(const char *path, wchar_t *wbuf, size_t wbuf_len) {
2075 int ret;
2076 char buf[MAX_PATH * 2], buf2[MAX_PATH * 2], *p;
2077
2078 strncpy(buf, path, sizeof(buf));
2079 buf[sizeof(buf) - 1] = '\0';
2080
2081 /* Trim trailing slashes. Leave backslash for paths like "X:\" */
2082 p = buf + strlen(buf) - 1;
2083 while (p > buf && p[-1] != ':' && (p[0] == '\\' || p[0] == '/')) *p-- = '\0';
2084
2085 memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
2086 ret = MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int) wbuf_len);
2087
2088 /*
2089 * Convert back to Unicode. If doubly-converted string does not match the
2090 * original, something is fishy, reject.
2091 */
2092 WideCharToMultiByte(CP_UTF8, 0, wbuf, (int) wbuf_len, buf2, sizeof(buf2),
2093 NULL, NULL);
2094 if (strcmp(buf, buf2) != 0) {
2095 wbuf[0] = L'\0';
2096 ret = 0;
2097 }
2098
2099 return ret;
2100 }
2101 #endif /* _WIN32 */
2102
2103 /* The simplest O(mn) algorithm. Better implementation are GPLed */
2104 const char *c_strnstr(const char *s, const char *find, size_t slen) WEAK;
c_strnstr(const char * s,const char * find,size_t slen)2105 const char *c_strnstr(const char *s, const char *find, size_t slen) {
2106 size_t find_length = strlen(find);
2107 size_t i;
2108
2109 for (i = 0; i < slen; i++) {
2110 if (i + find_length > slen) {
2111 return NULL;
2112 }
2113
2114 if (strncmp(&s[i], find, find_length) == 0) {
2115 return &s[i];
2116 }
2117 }
2118
2119 return NULL;
2120 }
2121
2122 #if CS_ENABLE_STRDUP
2123 char *strdup(const char *src) WEAK;
strdup(const char * src)2124 char *strdup(const char *src) {
2125 size_t len = strlen(src) + 1;
2126 char *ret = MG_MALLOC(len);
2127 if (ret != NULL) {
2128 strcpy(ret, src);
2129 }
2130 return ret;
2131 }
2132 #endif
2133
2134 void cs_to_hex(char *to, const unsigned char *p, size_t len) WEAK;
cs_to_hex(char * to,const unsigned char * p,size_t len)2135 void cs_to_hex(char *to, const unsigned char *p, size_t len) {
2136 static const char *hex = "0123456789abcdef";
2137
2138 for (; len--; p++) {
2139 *to++ = hex[p[0] >> 4];
2140 *to++ = hex[p[0] & 0x0f];
2141 }
2142 *to = '\0';
2143 }
2144
fourbit(int ch)2145 static int fourbit(int ch) {
2146 if (ch >= '0' && ch <= '9') {
2147 return ch - '0';
2148 } else if (ch >= 'a' && ch <= 'f') {
2149 return ch - 'a' + 10;
2150 } else if (ch >= 'A' && ch <= 'F') {
2151 return ch - 'A' + 10;
2152 }
2153 return 0;
2154 }
2155
2156 void cs_from_hex(char *to, const char *p, size_t len) WEAK;
cs_from_hex(char * to,const char * p,size_t len)2157 void cs_from_hex(char *to, const char *p, size_t len) {
2158 size_t i;
2159
2160 for (i = 0; i < len; i += 2) {
2161 *to++ = (fourbit(p[i]) << 4) + fourbit(p[i + 1]);
2162 }
2163 *to = '\0';
2164 }
2165
2166 #if CS_ENABLE_TO64
2167 int64_t cs_to64(const char *s) WEAK;
cs_to64(const char * s)2168 int64_t cs_to64(const char *s) {
2169 int64_t result = 0;
2170 int64_t neg = 1;
2171 while (*s && isspace((unsigned char) *s)) s++;
2172 if (*s == '-') {
2173 neg = -1;
2174 s++;
2175 }
2176 while (isdigit((unsigned char) *s)) {
2177 result *= 10;
2178 result += (*s - '0');
2179 s++;
2180 }
2181 return result * neg;
2182 }
2183 #endif
2184
str_util_lowercase(const char * s)2185 static int str_util_lowercase(const char *s) {
2186 return tolower(*(const unsigned char *) s);
2187 }
2188
2189 int mg_ncasecmp(const char *s1, const char *s2, size_t len) WEAK;
mg_ncasecmp(const char * s1,const char * s2,size_t len)2190 int mg_ncasecmp(const char *s1, const char *s2, size_t len) {
2191 int diff = 0;
2192
2193 if (len > 0) do {
2194 diff = str_util_lowercase(s1++) - str_util_lowercase(s2++);
2195 } while (diff == 0 && s1[-1] != '\0' && --len > 0);
2196
2197 return diff;
2198 }
2199
2200 int mg_casecmp(const char *s1, const char *s2) WEAK;
mg_casecmp(const char * s1,const char * s2)2201 int mg_casecmp(const char *s1, const char *s2) {
2202 return mg_ncasecmp(s1, s2, (size_t) ~0);
2203 }
2204
2205 int mg_asprintf(char **buf, size_t size, const char *fmt, ...) WEAK;
mg_asprintf(char ** buf,size_t size,const char * fmt,...)2206 int mg_asprintf(char **buf, size_t size, const char *fmt, ...) {
2207 int ret;
2208 va_list ap;
2209 va_start(ap, fmt);
2210 ret = mg_avprintf(buf, size, fmt, ap);
2211 va_end(ap);
2212 return ret;
2213 }
2214
2215 int mg_avprintf(char **buf, size_t size, const char *fmt, va_list ap) WEAK;
mg_avprintf(char ** buf,size_t size,const char * fmt,va_list ap)2216 int mg_avprintf(char **buf, size_t size, const char *fmt, va_list ap) {
2217 va_list ap_copy;
2218 int len;
2219
2220 va_copy(ap_copy, ap);
2221 len = vsnprintf(*buf, size, fmt, ap_copy);
2222 va_end(ap_copy);
2223
2224 if (len < 0) {
2225 /* eCos and Windows are not standard-compliant and return -1 when
2226 * the buffer is too small. Keep allocating larger buffers until we
2227 * succeed or out of memory. */
2228 *buf = NULL; /* LCOV_EXCL_START */
2229 while (len < 0) {
2230 MG_FREE(*buf);
2231 if (size == 0) {
2232 size = 5;
2233 }
2234 size *= 2;
2235 if ((*buf = (char *) MG_MALLOC(size)) == NULL) {
2236 len = -1;
2237 break;
2238 }
2239 va_copy(ap_copy, ap);
2240 len = vsnprintf(*buf, size - 1, fmt, ap_copy);
2241 va_end(ap_copy);
2242 }
2243
2244 /*
2245 * Microsoft version of vsnprintf() is not always null-terminated, so put
2246 * the terminator manually
2247 */
2248 (*buf)[len] = 0;
2249 /* LCOV_EXCL_STOP */
2250 } else if (len >= (int) size) {
2251 /* Standard-compliant code path. Allocate a buffer that is large enough. */
2252 if ((*buf = (char *) MG_MALLOC(len + 1)) == NULL) {
2253 len = -1; /* LCOV_EXCL_LINE */
2254 } else { /* LCOV_EXCL_LINE */
2255 va_copy(ap_copy, ap);
2256 len = vsnprintf(*buf, len + 1, fmt, ap_copy);
2257 va_end(ap_copy);
2258 }
2259 }
2260
2261 return len;
2262 }
2263
2264 const char *mg_next_comma_list_entry(const char *, struct mg_str *,
2265 struct mg_str *) WEAK;
mg_next_comma_list_entry(const char * list,struct mg_str * val,struct mg_str * eq_val)2266 const char *mg_next_comma_list_entry(const char *list, struct mg_str *val,
2267 struct mg_str *eq_val) {
2268 struct mg_str ret = mg_next_comma_list_entry_n(mg_mk_str(list), val, eq_val);
2269 return ret.p;
2270 }
2271
2272 struct mg_str mg_next_comma_list_entry_n(struct mg_str list, struct mg_str *val,
2273 struct mg_str *eq_val) WEAK;
mg_next_comma_list_entry_n(struct mg_str list,struct mg_str * val,struct mg_str * eq_val)2274 struct mg_str mg_next_comma_list_entry_n(struct mg_str list, struct mg_str *val,
2275 struct mg_str *eq_val) {
2276 if (list.len == 0) {
2277 /* End of the list */
2278 list = mg_mk_str(NULL);
2279 } else {
2280 const char *chr = NULL;
2281 *val = list;
2282
2283 if ((chr = mg_strchr(*val, ',')) != NULL) {
2284 /* Comma found. Store length and shift the list ptr */
2285 val->len = chr - val->p;
2286 chr++;
2287 list.len -= (chr - list.p);
2288 list.p = chr;
2289 } else {
2290 /* This value is the last one */
2291 list = mg_mk_str_n(list.p + list.len, 0);
2292 }
2293
2294 if (eq_val != NULL) {
2295 /* Value has form "x=y", adjust pointers and lengths */
2296 /* so that val points to "x", and eq_val points to "y". */
2297 eq_val->len = 0;
2298 eq_val->p = (const char *) memchr(val->p, '=', val->len);
2299 if (eq_val->p != NULL) {
2300 eq_val->p++; /* Skip over '=' character */
2301 eq_val->len = val->p + val->len - eq_val->p;
2302 val->len = (eq_val->p - val->p) - 1;
2303 }
2304 }
2305 }
2306
2307 return list;
2308 }
2309
2310 size_t mg_match_prefix_n(const struct mg_str, const struct mg_str) WEAK;
mg_match_prefix_n(const struct mg_str pattern,const struct mg_str str)2311 size_t mg_match_prefix_n(const struct mg_str pattern, const struct mg_str str) {
2312 const char *or_str;
2313 size_t res = 0, len = 0, i = 0, j = 0;
2314
2315 if ((or_str = (const char *) memchr(pattern.p, '|', pattern.len)) != NULL ||
2316 (or_str = (const char *) memchr(pattern.p, ',', pattern.len)) != NULL) {
2317 struct mg_str pstr = {pattern.p, (size_t)(or_str - pattern.p)};
2318 res = mg_match_prefix_n(pstr, str);
2319 if (res > 0) return res;
2320 pstr.p = or_str + 1;
2321 pstr.len = (pattern.p + pattern.len) - (or_str + 1);
2322 return mg_match_prefix_n(pstr, str);
2323 }
2324
2325 for (; i < pattern.len && j < str.len; i++, j++) {
2326 if (pattern.p[i] == '?') {
2327 continue;
2328 } else if (pattern.p[i] == '*') {
2329 i++;
2330 if (i < pattern.len && pattern.p[i] == '*') {
2331 i++;
2332 len = str.len - j;
2333 } else {
2334 len = 0;
2335 while (j + len < str.len && str.p[j + len] != '/') len++;
2336 }
2337 if (i == pattern.len || (pattern.p[i] == '$' && i == pattern.len - 1))
2338 return j + len;
2339 do {
2340 const struct mg_str pstr = {pattern.p + i, pattern.len - i};
2341 const struct mg_str sstr = {str.p + j + len, str.len - j - len};
2342 res = mg_match_prefix_n(pstr, sstr);
2343 } while (res == 0 && len != 0 && --len > 0);
2344 return res == 0 ? 0 : j + res + len;
2345 } else if (str_util_lowercase(&pattern.p[i]) !=
2346 str_util_lowercase(&str.p[j])) {
2347 break;
2348 }
2349 }
2350 if (i < pattern.len && pattern.p[i] == '$') {
2351 return j == str.len ? str.len : 0;
2352 }
2353 return i == pattern.len ? j : 0;
2354 }
2355
2356 size_t mg_match_prefix(const char *, int, const char *) WEAK;
mg_match_prefix(const char * pattern,int pattern_len,const char * str)2357 size_t mg_match_prefix(const char *pattern, int pattern_len, const char *str) {
2358 const struct mg_str pstr = {pattern, (size_t) pattern_len};
2359 struct mg_str s = {str, 0};
2360 if (str != NULL) s.len = strlen(str);
2361 return mg_match_prefix_n(pstr, s);
2362 }
2363
2364 #endif /* EXCLUDE_COMMON */
2365 #ifdef MG_MODULE_LINES
2366 #line 1 "mongoose/src/mg_net.c"
2367 #endif
2368 /*
2369 * Copyright (c) 2014 Cesanta Software Limited
2370 * All rights reserved
2371 *
2372 * This software is dual-licensed: you can redistribute it and/or modify
2373 * it under the terms of the GNU General Public License version 2 as
2374 * published by the Free Software Foundation. For the terms of this
2375 * license, see <http://www.gnu.org/licenses/>.
2376 *
2377 * You are free to use this software under the terms of the GNU General
2378 * Public License, but WITHOUT ANY WARRANTY; without even the implied
2379 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
2380 * See the GNU General Public License for more details.
2381 *
2382 * Alternatively, you can license this software under a commercial
2383 * license, as set out in <https://www.cesanta.com/license>.
2384 */
2385
2386 /* Amalgamated: #include "common/cs_time.h" */
2387 /* Amalgamated: #include "mg_dns.h" */
2388 /* Amalgamated: #include "mg_internal.h" */
2389 /* Amalgamated: #include "mg_resolv.h" */
2390 /* Amalgamated: #include "mg_util.h" */
2391
2392 #define MG_MAX_HOST_LEN 200
2393
2394 #ifndef MG_TCP_IO_SIZE
2395 #define MG_TCP_IO_SIZE 1460
2396 #endif
2397 #ifndef MG_UDP_IO_SIZE
2398 #define MG_UDP_IO_SIZE 1460
2399 #endif
2400
2401 #define MG_COPY_COMMON_CONNECTION_OPTIONS(dst, src) \
2402 memcpy(dst, src, sizeof(*dst));
2403
2404 /* Which flags can be pre-set by the user at connection creation time. */
2405 #define _MG_ALLOWED_CONNECT_FLAGS_MASK \
2406 (MG_F_USER_1 | MG_F_USER_2 | MG_F_USER_3 | MG_F_USER_4 | MG_F_USER_5 | \
2407 MG_F_USER_6 | MG_F_WEBSOCKET_NO_DEFRAG | MG_F_ENABLE_BROADCAST)
2408 /* Which flags should be modifiable by user's callbacks. */
2409 #define _MG_CALLBACK_MODIFIABLE_FLAGS_MASK \
2410 (MG_F_USER_1 | MG_F_USER_2 | MG_F_USER_3 | MG_F_USER_4 | MG_F_USER_5 | \
2411 MG_F_USER_6 | MG_F_WEBSOCKET_NO_DEFRAG | MG_F_SEND_AND_CLOSE | \
2412 MG_F_CLOSE_IMMEDIATELY | MG_F_IS_WEBSOCKET | MG_F_DELETE_CHUNK)
2413
2414 #ifndef intptr_t
2415 #define intptr_t long
2416 #endif
2417
mg_add_conn(struct mg_mgr * mgr,struct mg_connection * c)2418 MG_INTERNAL void mg_add_conn(struct mg_mgr *mgr, struct mg_connection *c) {
2419 DBG(("%p %p", mgr, c));
2420 c->mgr = mgr;
2421 c->next = mgr->active_connections;
2422 mgr->active_connections = c;
2423 c->prev = NULL;
2424 if (c->next != NULL) c->next->prev = c;
2425 if (c->sock != INVALID_SOCKET) {
2426 c->iface->vtable->add_conn(c);
2427 }
2428 }
2429
mg_remove_conn(struct mg_connection * conn)2430 MG_INTERNAL void mg_remove_conn(struct mg_connection *conn) {
2431 if (conn->prev == NULL) conn->mgr->active_connections = conn->next;
2432 if (conn->prev) conn->prev->next = conn->next;
2433 if (conn->next) conn->next->prev = conn->prev;
2434 conn->prev = conn->next = NULL;
2435 conn->iface->vtable->remove_conn(conn);
2436 }
2437
mg_call(struct mg_connection * nc,mg_event_handler_t ev_handler,void * user_data,int ev,void * ev_data)2438 MG_INTERNAL void mg_call(struct mg_connection *nc,
2439 mg_event_handler_t ev_handler, void *user_data, int ev,
2440 void *ev_data) {
2441 if (ev_handler == NULL) {
2442 /*
2443 * If protocol handler is specified, call it. Otherwise, call user-specified
2444 * event handler.
2445 */
2446 ev_handler = nc->proto_handler ? nc->proto_handler : nc->handler;
2447 }
2448 if (ev != MG_EV_POLL) {
2449 DBG(("%p %s ev=%d ev_data=%p flags=0x%lx rmbl=%d smbl=%d", nc,
2450 ev_handler == nc->handler ? "user" : "proto", ev, ev_data, nc->flags,
2451 (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len));
2452 }
2453
2454 #if !defined(NO_LIBC) && MG_ENABLE_HEXDUMP
2455 if (nc->mgr->hexdump_file != NULL && ev != MG_EV_POLL && ev != MG_EV_RECV &&
2456 ev != MG_EV_SEND /* handled separately */) {
2457 mg_hexdump_connection(nc, nc->mgr->hexdump_file, NULL, 0, ev);
2458 }
2459 #endif
2460 if (ev_handler != NULL) {
2461 unsigned long flags_before = nc->flags;
2462 ev_handler(nc, ev, ev_data MG_UD_ARG(user_data));
2463 /* Prevent user handler from fiddling with system flags. */
2464 if (ev_handler == nc->handler && nc->flags != flags_before) {
2465 nc->flags = (flags_before & ~_MG_CALLBACK_MODIFIABLE_FLAGS_MASK) |
2466 (nc->flags & _MG_CALLBACK_MODIFIABLE_FLAGS_MASK);
2467 }
2468 }
2469 if (ev != MG_EV_POLL) nc->mgr->num_calls++;
2470 if (ev != MG_EV_POLL) {
2471 DBG(("%p after %s flags=0x%lx rmbl=%d smbl=%d", nc,
2472 ev_handler == nc->handler ? "user" : "proto", nc->flags,
2473 (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len));
2474 }
2475 #if !MG_ENABLE_CALLBACK_USERDATA
2476 (void) user_data;
2477 #endif
2478 }
2479
mg_timer(struct mg_connection * c,double now)2480 MG_INTERNAL void mg_timer(struct mg_connection *c, double now) {
2481 if (c->ev_timer_time > 0 && now >= c->ev_timer_time) {
2482 double old_value = c->ev_timer_time;
2483 c->ev_timer_time = 0;
2484 mg_call(c, NULL, c->user_data, MG_EV_TIMER, &old_value);
2485 }
2486 }
2487
recv_avail_size(struct mg_connection * conn,size_t max)2488 MG_INTERNAL size_t recv_avail_size(struct mg_connection *conn, size_t max) {
2489 size_t avail;
2490 if (conn->recv_mbuf_limit < conn->recv_mbuf.len) return 0;
2491 avail = conn->recv_mbuf_limit - conn->recv_mbuf.len;
2492 return avail > max ? max : avail;
2493 }
2494
2495 static int mg_do_recv(struct mg_connection *nc);
2496
mg_if_poll(struct mg_connection * nc,double now)2497 int mg_if_poll(struct mg_connection *nc, double now) {
2498 if (nc->flags & MG_F_CLOSE_IMMEDIATELY) {
2499 mg_close_conn(nc);
2500 return 0;
2501 } else if (nc->flags & MG_F_SEND_AND_CLOSE) {
2502 if (nc->send_mbuf.len == 0) {
2503 nc->flags |= MG_F_CLOSE_IMMEDIATELY;
2504 mg_close_conn(nc);
2505 return 0;
2506 }
2507 } else if (nc->flags & MG_F_RECV_AND_CLOSE) {
2508 mg_close_conn(nc);
2509 return 0;
2510 }
2511 #if MG_ENABLE_SSL
2512 if ((nc->flags & (MG_F_SSL | MG_F_LISTENING | MG_F_CONNECTING)) == MG_F_SSL) {
2513 /* SSL library may have data to be delivered to the app in its buffers,
2514 * drain them. */
2515 int recved = 0;
2516 do {
2517 if (nc->flags & (MG_F_WANT_READ | MG_F_WANT_WRITE)) break;
2518 if (recv_avail_size(nc, MG_TCP_IO_SIZE) <= 0) break;
2519 recved = mg_do_recv(nc);
2520 } while (recved > 0);
2521 }
2522 #endif /* MG_ENABLE_SSL */
2523 mg_timer(nc, now);
2524 {
2525 time_t now_t = (time_t) now;
2526 mg_call(nc, NULL, nc->user_data, MG_EV_POLL, &now_t);
2527 }
2528 return 1;
2529 }
2530
mg_destroy_conn(struct mg_connection * conn,int destroy_if)2531 void mg_destroy_conn(struct mg_connection *conn, int destroy_if) {
2532 if (conn->sock != INVALID_SOCKET) { /* Don't print timer-only conns */
2533 LOG(LL_DEBUG, ("%p 0x%lx %d", conn, conn->flags, destroy_if));
2534 }
2535 if (destroy_if) conn->iface->vtable->destroy_conn(conn);
2536 if (conn->proto_data != NULL && conn->proto_data_destructor != NULL) {
2537 conn->proto_data_destructor(conn->proto_data);
2538 }
2539 #if MG_ENABLE_SSL
2540 mg_ssl_if_conn_free(conn);
2541 #endif
2542 mbuf_free(&conn->recv_mbuf);
2543 mbuf_free(&conn->send_mbuf);
2544
2545 memset(conn, 0, sizeof(*conn));
2546 MG_FREE(conn);
2547 }
2548
mg_close_conn(struct mg_connection * conn)2549 void mg_close_conn(struct mg_connection *conn) {
2550 /* See if there's any remaining data to deliver. Skip if user completely
2551 * throttled the connection there will be no progress anyway. */
2552 if (conn->sock != INVALID_SOCKET && mg_do_recv(conn) == -2) {
2553 /* Receive is throttled, wait. */
2554 conn->flags |= MG_F_RECV_AND_CLOSE;
2555 return;
2556 }
2557 #if MG_ENABLE_SSL
2558 if (conn->flags & MG_F_SSL_HANDSHAKE_DONE) {
2559 mg_ssl_if_conn_close_notify(conn);
2560 }
2561 #endif
2562 /*
2563 * Clearly mark the connection as going away (if not already).
2564 * Some net_if impls (LwIP) need this for cleanly handling half-dead conns.
2565 */
2566 conn->flags |= MG_F_CLOSE_IMMEDIATELY;
2567 mg_remove_conn(conn);
2568 conn->iface->vtable->destroy_conn(conn);
2569 mg_call(conn, NULL, conn->user_data, MG_EV_CLOSE, NULL);
2570 mg_destroy_conn(conn, 0 /* destroy_if */);
2571 }
2572
mg_mgr_init(struct mg_mgr * m,void * user_data)2573 void mg_mgr_init(struct mg_mgr *m, void *user_data) {
2574 struct mg_mgr_init_opts opts;
2575 memset(&opts, 0, sizeof(opts));
2576 mg_mgr_init_opt(m, user_data, opts);
2577 }
2578
mg_mgr_init_opt(struct mg_mgr * m,void * user_data,struct mg_mgr_init_opts opts)2579 void mg_mgr_init_opt(struct mg_mgr *m, void *user_data,
2580 struct mg_mgr_init_opts opts) {
2581 memset(m, 0, sizeof(*m));
2582 #if MG_ENABLE_BROADCAST
2583 m->ctl[0] = m->ctl[1] = INVALID_SOCKET;
2584 #endif
2585 m->user_data = user_data;
2586
2587 #ifdef _WIN32
2588 {
2589 WSADATA data;
2590 WSAStartup(MAKEWORD(2, 2), &data);
2591 }
2592 #elif defined(__unix__)
2593 /* Ignore SIGPIPE signal, so if client cancels the request, it
2594 * won't kill the whole process. */
2595 signal(SIGPIPE, SIG_IGN);
2596 #endif
2597
2598 {
2599 int i;
2600 if (opts.num_ifaces == 0) {
2601 opts.num_ifaces = mg_num_ifaces;
2602 opts.ifaces = mg_ifaces;
2603 }
2604 if (opts.main_iface != NULL) {
2605 opts.ifaces[MG_MAIN_IFACE] = opts.main_iface;
2606 }
2607 m->num_ifaces = opts.num_ifaces;
2608 m->ifaces =
2609 (struct mg_iface **) MG_MALLOC(sizeof(*m->ifaces) * opts.num_ifaces);
2610 for (i = 0; i < opts.num_ifaces; i++) {
2611 m->ifaces[i] = mg_if_create_iface(opts.ifaces[i], m);
2612 m->ifaces[i]->vtable->init(m->ifaces[i]);
2613 }
2614 }
2615 if (opts.nameserver != NULL) {
2616 m->nameserver = strdup(opts.nameserver);
2617 }
2618 DBG(("=================================="));
2619 DBG(("init mgr=%p", m));
2620 #if MG_ENABLE_SSL
2621 {
2622 static int init_done;
2623 if (!init_done) {
2624 mg_ssl_if_init();
2625 init_done++;
2626 }
2627 }
2628 #endif
2629 }
2630
mg_mgr_free(struct mg_mgr * m)2631 void mg_mgr_free(struct mg_mgr *m) {
2632 struct mg_connection *conn, *tmp_conn;
2633
2634 DBG(("%p", m));
2635 if (m == NULL) return;
2636 /* Do one last poll, see https://github.com/cesanta/mongoose/issues/286 */
2637 mg_mgr_poll(m, 0);
2638
2639 #if MG_ENABLE_BROADCAST
2640 if (m->ctl[0] != INVALID_SOCKET) closesocket(m->ctl[0]);
2641 if (m->ctl[1] != INVALID_SOCKET) closesocket(m->ctl[1]);
2642 m->ctl[0] = m->ctl[1] = INVALID_SOCKET;
2643 #endif
2644
2645 for (conn = m->active_connections; conn != NULL; conn = tmp_conn) {
2646 tmp_conn = conn->next;
2647 conn->flags |= MG_F_CLOSE_IMMEDIATELY;
2648 mg_close_conn(conn);
2649 }
2650
2651 {
2652 int i;
2653 for (i = 0; i < m->num_ifaces; i++) {
2654 m->ifaces[i]->vtable->_free(m->ifaces[i]);
2655 MG_FREE(m->ifaces[i]);
2656 }
2657 MG_FREE(m->ifaces);
2658 }
2659
2660 MG_FREE((char *) m->nameserver);
2661 }
2662
mg_mgr_poll(struct mg_mgr * m,int timeout_ms)2663 int mg_mgr_poll(struct mg_mgr *m, int timeout_ms) {
2664 int i, num_calls_before = m->num_calls;
2665
2666 for (i = 0; i < m->num_ifaces; i++) {
2667 m->ifaces[i]->vtable->poll(m->ifaces[i], timeout_ms);
2668 }
2669
2670 return (m->num_calls - num_calls_before);
2671 }
2672
mg_vprintf(struct mg_connection * nc,const char * fmt,va_list ap)2673 int mg_vprintf(struct mg_connection *nc, const char *fmt, va_list ap) {
2674 char mem[MG_VPRINTF_BUFFER_SIZE], *buf = mem;
2675 int len;
2676
2677 if ((len = mg_avprintf(&buf, sizeof(mem), fmt, ap)) > 0) {
2678 mg_send(nc, buf, len);
2679 }
2680 if (buf != mem && buf != NULL) {
2681 MG_FREE(buf); /* LCOV_EXCL_LINE */
2682 } /* LCOV_EXCL_LINE */
2683
2684 return len;
2685 }
2686
mg_printf(struct mg_connection * conn,const char * fmt,...)2687 int mg_printf(struct mg_connection *conn, const char *fmt, ...) {
2688 int len;
2689 va_list ap;
2690 va_start(ap, fmt);
2691 len = mg_vprintf(conn, fmt, ap);
2692 va_end(ap);
2693 return len;
2694 }
2695
2696 #if MG_ENABLE_SYNC_RESOLVER
2697 /* TODO(lsm): use non-blocking resolver */
mg_resolve2(const char * host,struct in_addr * ina)2698 static int mg_resolve2(const char *host, struct in_addr *ina) {
2699 #if MG_ENABLE_GETADDRINFO
2700 int rv = 0;
2701 struct addrinfo hints, *servinfo, *p;
2702 struct sockaddr_in *h = NULL;
2703 memset(&hints, 0, sizeof hints);
2704 hints.ai_family = AF_INET;
2705 hints.ai_socktype = SOCK_STREAM;
2706 if ((rv = getaddrinfo(host, NULL, NULL, &servinfo)) != 0) {
2707 DBG(("getaddrinfo(%s) failed: %s", host, strerror(mg_get_errno())));
2708 return 0;
2709 }
2710 for (p = servinfo; p != NULL; p = p->ai_next) {
2711 memcpy(&h, &p->ai_addr, sizeof(h));
2712 memcpy(ina, &h->sin_addr, sizeof(*ina));
2713 }
2714 freeaddrinfo(servinfo);
2715 return 1;
2716 #else
2717 struct hostent *he;
2718 if ((he = gethostbyname(host)) == NULL) {
2719 DBG(("gethostbyname(%s) failed: %s", host, strerror(mg_get_errno())));
2720 } else {
2721 memcpy(ina, he->h_addr_list[0], sizeof(*ina));
2722 return 1;
2723 }
2724 return 0;
2725 #endif /* MG_ENABLE_GETADDRINFO */
2726 }
2727
mg_resolve(const char * host,char * buf,size_t n)2728 int mg_resolve(const char *host, char *buf, size_t n) {
2729 struct in_addr ad;
2730 return mg_resolve2(host, &ad) ? snprintf(buf, n, "%s", inet_ntoa(ad)) : 0;
2731 }
2732 #endif /* MG_ENABLE_SYNC_RESOLVER */
2733
mg_create_connection_base(struct mg_mgr * mgr,mg_event_handler_t callback,struct mg_add_sock_opts opts)2734 MG_INTERNAL struct mg_connection *mg_create_connection_base(
2735 struct mg_mgr *mgr, mg_event_handler_t callback,
2736 struct mg_add_sock_opts opts) {
2737 struct mg_connection *conn;
2738
2739 if ((conn = (struct mg_connection *) MG_CALLOC(1, sizeof(*conn))) != NULL) {
2740 conn->sock = INVALID_SOCKET;
2741 conn->handler = callback;
2742 conn->mgr = mgr;
2743 conn->last_io_time = (time_t) mg_time();
2744 conn->iface =
2745 (opts.iface != NULL ? opts.iface : mgr->ifaces[MG_MAIN_IFACE]);
2746 conn->flags = opts.flags & _MG_ALLOWED_CONNECT_FLAGS_MASK;
2747 conn->user_data = opts.user_data;
2748 /*
2749 * SIZE_MAX is defined as a long long constant in
2750 * system headers on some platforms and so it
2751 * doesn't compile with pedantic ansi flags.
2752 */
2753 conn->recv_mbuf_limit = ~0;
2754 } else {
2755 MG_SET_PTRPTR(opts.error_string, "failed to create connection");
2756 }
2757
2758 return conn;
2759 }
2760
mg_create_connection(struct mg_mgr * mgr,mg_event_handler_t callback,struct mg_add_sock_opts opts)2761 MG_INTERNAL struct mg_connection *mg_create_connection(
2762 struct mg_mgr *mgr, mg_event_handler_t callback,
2763 struct mg_add_sock_opts opts) {
2764 struct mg_connection *conn = mg_create_connection_base(mgr, callback, opts);
2765
2766 if (conn != NULL && !conn->iface->vtable->create_conn(conn)) {
2767 MG_FREE(conn);
2768 conn = NULL;
2769 }
2770 if (conn == NULL) {
2771 MG_SET_PTRPTR(opts.error_string, "failed to init connection");
2772 }
2773
2774 return conn;
2775 }
2776
2777 /*
2778 * Address format: [PROTO://][HOST]:PORT
2779 *
2780 * HOST could be IPv4/IPv6 address or a host name.
2781 * `host` is a destination buffer to hold parsed HOST part. Should be at least
2782 * MG_MAX_HOST_LEN bytes long.
2783 * `proto` is a returned socket type, either SOCK_STREAM or SOCK_DGRAM
2784 *
2785 * Return:
2786 * -1 on parse error
2787 * 0 if HOST needs DNS lookup
2788 * >0 length of the address string
2789 */
mg_parse_address(const char * str,union socket_address * sa,int * proto,char * host,size_t host_len)2790 MG_INTERNAL int mg_parse_address(const char *str, union socket_address *sa,
2791 int *proto, char *host, size_t host_len) {
2792 unsigned int a, b, c, d, port = 0;
2793 int ch, len = 0;
2794 #if MG_ENABLE_IPV6
2795 char buf[100];
2796 #endif
2797
2798 /*
2799 * MacOS needs that. If we do not zero it, subsequent bind() will fail.
2800 * Also, all-zeroes in the socket address means binding to all addresses
2801 * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT).
2802 */
2803 memset(sa, 0, sizeof(*sa));
2804 sa->sin.sin_family = AF_INET;
2805
2806 *proto = SOCK_STREAM;
2807
2808 if (strncmp(str, "udp://", 6) == 0) {
2809 str += 6;
2810 *proto = SOCK_DGRAM;
2811 } else if (strncmp(str, "tcp://", 6) == 0) {
2812 str += 6;
2813 }
2814
2815 if (sscanf(str, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len) == 5) {
2816 /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
2817 sa->sin.sin_addr.s_addr =
2818 htonl(((uint32_t) a << 24) | ((uint32_t) b << 16) | c << 8 | d);
2819 sa->sin.sin_port = htons((uint16_t) port);
2820 #if MG_ENABLE_IPV6
2821 } else if (sscanf(str, "[%99[^]]]:%u%n", buf, &port, &len) == 2 &&
2822 inet_pton(AF_INET6, buf, &sa->sin6.sin6_addr)) {
2823 /* IPv6 address, e.g. [3ffe:2a00:100:7031::1]:8080 */
2824 sa->sin6.sin6_family = AF_INET6;
2825 sa->sin.sin_port = htons((uint16_t) port);
2826 #endif
2827 #if MG_ENABLE_ASYNC_RESOLVER
2828 } else if (strlen(str) < host_len &&
2829 sscanf(str, "%[^ :]:%u%n", host, &port, &len) == 2) {
2830 sa->sin.sin_port = htons((uint16_t) port);
2831 if (mg_resolve_from_hosts_file(host, sa) != 0) {
2832 /*
2833 * if resolving from hosts file failed and the host
2834 * we are trying to resolve is `localhost` - we should
2835 * try to resolve it using `gethostbyname` and do not try
2836 * to resolve it via DNS server if gethostbyname has failed too
2837 */
2838 if (mg_ncasecmp(host, "localhost", 9) != 0) {
2839 return 0;
2840 }
2841
2842 #if MG_ENABLE_SYNC_RESOLVER
2843 if (!mg_resolve2(host, &sa->sin.sin_addr)) {
2844 return -1;
2845 }
2846 #else
2847 return -1;
2848 #endif
2849 }
2850 #endif
2851 } else if (sscanf(str, ":%u%n", &port, &len) == 1 ||
2852 sscanf(str, "%u%n", &port, &len) == 1) {
2853 /* If only port is specified, bind to IPv4, INADDR_ANY */
2854 sa->sin.sin_port = htons((uint16_t) port);
2855 } else {
2856 return -1;
2857 }
2858
2859 /* Required for MG_ENABLE_ASYNC_RESOLVER=0 */
2860 (void) host;
2861 (void) host_len;
2862
2863 ch = str[len]; /* Character that follows the address */
2864 return port < 0xffffUL && (ch == '\0' || ch == ',' || isspace(ch)) ? len : -1;
2865 }
2866
2867 #if MG_ENABLE_SSL
mg_ssl_handshake(struct mg_connection * nc)2868 MG_INTERNAL void mg_ssl_handshake(struct mg_connection *nc) {
2869 int err = 0;
2870 int server_side = (nc->listener != NULL);
2871 enum mg_ssl_if_result res;
2872 if (nc->flags & MG_F_SSL_HANDSHAKE_DONE) return;
2873 res = mg_ssl_if_handshake(nc);
2874
2875 if (res == MG_SSL_OK) {
2876 nc->flags |= MG_F_SSL_HANDSHAKE_DONE;
2877 nc->flags &= ~(MG_F_WANT_READ | MG_F_WANT_WRITE);
2878 if (server_side) {
2879 mg_call(nc, NULL, nc->user_data, MG_EV_ACCEPT, &nc->sa);
2880 } else {
2881 mg_call(nc, NULL, nc->user_data, MG_EV_CONNECT, &err);
2882 }
2883 } else if (res == MG_SSL_WANT_READ) {
2884 nc->flags |= MG_F_WANT_READ;
2885 } else if (res == MG_SSL_WANT_WRITE) {
2886 nc->flags |= MG_F_WANT_WRITE;
2887 } else {
2888 if (!server_side) {
2889 err = res;
2890 mg_call(nc, NULL, nc->user_data, MG_EV_CONNECT, &err);
2891 }
2892 nc->flags |= MG_F_CLOSE_IMMEDIATELY;
2893 }
2894 }
2895 #endif /* MG_ENABLE_SSL */
2896
mg_if_accept_new_conn(struct mg_connection * lc)2897 struct mg_connection *mg_if_accept_new_conn(struct mg_connection *lc) {
2898 struct mg_add_sock_opts opts;
2899 struct mg_connection *nc;
2900 memset(&opts, 0, sizeof(opts));
2901 nc = mg_create_connection(lc->mgr, lc->handler, opts);
2902 if (nc == NULL) return NULL;
2903 nc->listener = lc;
2904 nc->proto_handler = lc->proto_handler;
2905 nc->user_data = lc->user_data;
2906 nc->recv_mbuf_limit = lc->recv_mbuf_limit;
2907 nc->iface = lc->iface;
2908 if (lc->flags & MG_F_SSL) nc->flags |= MG_F_SSL;
2909 mg_add_conn(nc->mgr, nc);
2910 LOG(LL_DEBUG, ("%p %p %d %d", lc, nc, nc->sock, (int) nc->flags));
2911 return nc;
2912 }
2913
mg_if_accept_tcp_cb(struct mg_connection * nc,union socket_address * sa,size_t sa_len)2914 void mg_if_accept_tcp_cb(struct mg_connection *nc, union socket_address *sa,
2915 size_t sa_len) {
2916 LOG(LL_DEBUG, ("%p %s://%s:%hu", nc, (nc->flags & MG_F_UDP ? "udp" : "tcp"),
2917 inet_ntoa(sa->sin.sin_addr), ntohs(sa->sin.sin_port)));
2918 nc->sa = *sa;
2919 #if MG_ENABLE_SSL
2920 if (nc->listener->flags & MG_F_SSL) {
2921 nc->flags |= MG_F_SSL;
2922 if (mg_ssl_if_conn_accept(nc, nc->listener) == MG_SSL_OK) {
2923 mg_ssl_handshake(nc);
2924 } else {
2925 mg_close_conn(nc);
2926 }
2927 } else
2928 #endif
2929 {
2930 mg_call(nc, NULL, nc->user_data, MG_EV_ACCEPT, &nc->sa);
2931 }
2932 (void) sa_len;
2933 }
2934
mg_send(struct mg_connection * nc,const void * buf,int len)2935 void mg_send(struct mg_connection *nc, const void *buf, int len) {
2936 nc->last_io_time = (time_t) mg_time();
2937 mbuf_append(&nc->send_mbuf, buf, len);
2938 }
2939
2940 static int mg_recv_tcp(struct mg_connection *nc, char *buf, size_t len);
2941 static int mg_recv_udp(struct mg_connection *nc, char *buf, size_t len);
2942
mg_do_recv(struct mg_connection * nc)2943 static int mg_do_recv(struct mg_connection *nc) {
2944 int res = 0;
2945 char *buf = NULL;
2946 size_t len = (nc->flags & MG_F_UDP ? MG_UDP_IO_SIZE : MG_TCP_IO_SIZE);
2947 if ((nc->flags & (MG_F_CLOSE_IMMEDIATELY | MG_F_CONNECTING)) ||
2948 ((nc->flags & MG_F_LISTENING) && !(nc->flags & MG_F_UDP))) {
2949 return -1;
2950 }
2951 do {
2952 len = recv_avail_size(nc, len);
2953 if (len == 0) {
2954 res = -2;
2955 break;
2956 }
2957 if (nc->recv_mbuf.size < nc->recv_mbuf.len + len) {
2958 mbuf_resize(&nc->recv_mbuf, nc->recv_mbuf.len + len);
2959 }
2960 buf = nc->recv_mbuf.buf + nc->recv_mbuf.len;
2961 len = nc->recv_mbuf.size - nc->recv_mbuf.len;
2962 if (nc->flags & MG_F_UDP) {
2963 res = mg_recv_udp(nc, buf, len);
2964 } else {
2965 res = mg_recv_tcp(nc, buf, len);
2966 }
2967 } while (res > 0 && !(nc->flags & (MG_F_CLOSE_IMMEDIATELY | MG_F_UDP)));
2968 return res;
2969 }
2970
mg_if_can_recv_cb(struct mg_connection * nc)2971 void mg_if_can_recv_cb(struct mg_connection *nc) {
2972 mg_do_recv(nc);
2973 }
2974
mg_recv_tcp(struct mg_connection * nc,char * buf,size_t len)2975 static int mg_recv_tcp(struct mg_connection *nc, char *buf, size_t len) {
2976 int n = 0;
2977 #if MG_ENABLE_SSL
2978 if (nc->flags & MG_F_SSL) {
2979 if (nc->flags & MG_F_SSL_HANDSHAKE_DONE) {
2980 n = mg_ssl_if_read(nc, buf, len);
2981 DBG(("%p <- %d bytes (SSL)", nc, n));
2982 if (n < 0) {
2983 if (n == MG_SSL_WANT_READ) {
2984 nc->flags |= MG_F_WANT_READ;
2985 n = 0;
2986 } else {
2987 nc->flags |= MG_F_CLOSE_IMMEDIATELY;
2988 }
2989 } else if (n > 0) {
2990 nc->flags &= ~MG_F_WANT_READ;
2991 }
2992 } else {
2993 mg_ssl_handshake(nc);
2994 }
2995 } else
2996 #endif
2997 {
2998 n = nc->iface->vtable->tcp_recv(nc, buf, len);
2999 DBG(("%p <- %d bytes", nc, n));
3000 }
3001 if (n > 0) {
3002 nc->recv_mbuf.len += n;
3003 nc->last_io_time = (time_t) mg_time();
3004 #if !defined(NO_LIBC) && MG_ENABLE_HEXDUMP
3005 if (nc->mgr && nc->mgr->hexdump_file != NULL) {
3006 mg_hexdump_connection(nc, nc->mgr->hexdump_file, buf, n, MG_EV_RECV);
3007 }
3008 #endif
3009 mbuf_trim(&nc->recv_mbuf);
3010 mg_call(nc, NULL, nc->user_data, MG_EV_RECV, &n);
3011 } else if (n < 0) {
3012 nc->flags |= MG_F_CLOSE_IMMEDIATELY;
3013 }
3014 mbuf_trim(&nc->recv_mbuf);
3015 return n;
3016 }
3017
mg_recv_udp(struct mg_connection * nc,char * buf,size_t len)3018 static int mg_recv_udp(struct mg_connection *nc, char *buf, size_t len) {
3019 int n = 0;
3020 struct mg_connection *lc = nc;
3021 union socket_address sa;
3022 size_t sa_len = sizeof(sa);
3023 n = nc->iface->vtable->udp_recv(lc, buf, len, &sa, &sa_len);
3024 if (n < 0) {
3025 lc->flags |= MG_F_CLOSE_IMMEDIATELY;
3026 goto out;
3027 }
3028 if (nc->flags & MG_F_LISTENING) {
3029 /*
3030 * Do we have an existing connection for this source?
3031 * This is very inefficient for long connection lists.
3032 */
3033 lc = nc;
3034 for (nc = mg_next(lc->mgr, NULL); nc != NULL; nc = mg_next(lc->mgr, nc)) {
3035 if (memcmp(&nc->sa.sa, &sa.sa, sa_len) == 0 && nc->listener == lc) {
3036 break;
3037 }
3038 }
3039 if (nc == NULL) {
3040 struct mg_add_sock_opts opts;
3041 memset(&opts, 0, sizeof(opts));
3042 /* Create fake connection w/out sock initialization */
3043 nc = mg_create_connection_base(lc->mgr, lc->handler, opts);
3044 if (nc != NULL) {
3045 nc->sock = lc->sock;
3046 nc->listener = lc;
3047 nc->sa = sa;
3048 nc->proto_handler = lc->proto_handler;
3049 nc->user_data = lc->user_data;
3050 nc->recv_mbuf_limit = lc->recv_mbuf_limit;
3051 nc->flags = MG_F_UDP;
3052 /*
3053 * Long-lived UDP "connections" i.e. interactions that involve more
3054 * than one request and response are rare, most are transactional:
3055 * response is sent and the "connection" is closed. Or - should be.
3056 * But users (including ourselves) tend to forget about that part,
3057 * because UDP is connectionless and one does not think about
3058 * processing a UDP request as handling a connection that needs to be
3059 * closed. Thus, we begin with SEND_AND_CLOSE flag set, which should
3060 * be a reasonable default for most use cases, but it is possible to
3061 * turn it off the connection should be kept alive after processing.
3062 */
3063 nc->flags |= MG_F_SEND_AND_CLOSE;
3064 mg_add_conn(lc->mgr, nc);
3065 mg_call(nc, NULL, nc->user_data, MG_EV_ACCEPT, &nc->sa);
3066 }
3067 }
3068 }
3069 if (nc != NULL) {
3070 DBG(("%p <- %d bytes from %s:%d", nc, n, inet_ntoa(nc->sa.sin.sin_addr),
3071 ntohs(nc->sa.sin.sin_port)));
3072 if (nc == lc) {
3073 nc->recv_mbuf.len += n;
3074 } else {
3075 mbuf_append(&nc->recv_mbuf, buf, n);
3076 }
3077 mbuf_trim(&lc->recv_mbuf);
3078 lc->last_io_time = nc->last_io_time = (time_t) mg_time();
3079 #if !defined(NO_LIBC) && MG_ENABLE_HEXDUMP
3080 if (nc->mgr && nc->mgr->hexdump_file != NULL) {
3081 mg_hexdump_connection(nc, nc->mgr->hexdump_file, buf, n, MG_EV_RECV);
3082 }
3083 #endif
3084 if (n != 0) {
3085 mg_call(nc, NULL, nc->user_data, MG_EV_RECV, &n);
3086 }
3087 }
3088
3089 out:
3090 mbuf_free(&lc->recv_mbuf);
3091 return n;
3092 }
3093
mg_if_can_send_cb(struct mg_connection * nc)3094 void mg_if_can_send_cb(struct mg_connection *nc) {
3095 int n = 0;
3096 const char *buf = nc->send_mbuf.buf;
3097 size_t len = nc->send_mbuf.len;
3098
3099 if (nc->flags & (MG_F_CLOSE_IMMEDIATELY | MG_F_CONNECTING)) {
3100 return;
3101 }
3102 if (!(nc->flags & MG_F_UDP)) {
3103 if (nc->flags & MG_F_LISTENING) return;
3104 if (len > MG_TCP_IO_SIZE) len = MG_TCP_IO_SIZE;
3105 }
3106 #if MG_ENABLE_SSL
3107 if (nc->flags & MG_F_SSL) {
3108 if (nc->flags & MG_F_SSL_HANDSHAKE_DONE) {
3109 if (len > 0) {
3110 n = mg_ssl_if_write(nc, buf, len);
3111 DBG(("%p -> %d bytes (SSL)", nc, n));
3112 }
3113 if (n < 0) {
3114 if (n == MG_SSL_WANT_WRITE) {
3115 nc->flags |= MG_F_WANT_WRITE;
3116 n = 0;
3117 } else {
3118 nc->flags |= MG_F_CLOSE_IMMEDIATELY;
3119 }
3120 } else {
3121 nc->flags &= ~MG_F_WANT_WRITE;
3122 }
3123 } else {
3124 mg_ssl_handshake(nc);
3125 }
3126 } else
3127 #endif
3128 if (len > 0) {
3129 if (nc->flags & MG_F_UDP) {
3130 n = nc->iface->vtable->udp_send(nc, buf, len);
3131 } else {
3132 n = nc->iface->vtable->tcp_send(nc, buf, len);
3133 }
3134 DBG(("%p -> %d bytes", nc, n));
3135 }
3136
3137 #if !defined(NO_LIBC) && MG_ENABLE_HEXDUMP
3138 if (n > 0 && nc->mgr && nc->mgr->hexdump_file != NULL) {
3139 mg_hexdump_connection(nc, nc->mgr->hexdump_file, buf, n, MG_EV_SEND);
3140 }
3141 #endif
3142 if (n < 0) {
3143 nc->flags |= MG_F_CLOSE_IMMEDIATELY;
3144 } else if (n > 0) {
3145 nc->last_io_time = (time_t) mg_time();
3146 mbuf_remove(&nc->send_mbuf, n);
3147 mbuf_trim(&nc->send_mbuf);
3148 }
3149 if (n != 0) mg_call(nc, NULL, nc->user_data, MG_EV_SEND, &n);
3150 }
3151
3152 /*
3153 * Schedules an async connect for a resolved address and proto.
3154 * Called from two places: `mg_connect_opt()` and from async resolver.
3155 * When called from the async resolver, it must trigger `MG_EV_CONNECT` event
3156 * with a failure flag to indicate connection failure.
3157 */
mg_do_connect(struct mg_connection * nc,int proto,union socket_address * sa)3158 MG_INTERNAL struct mg_connection *mg_do_connect(struct mg_connection *nc,
3159 int proto,
3160 union socket_address *sa) {
3161 LOG(LL_DEBUG, ("%p %s://%s:%hu", nc, proto == SOCK_DGRAM ? "udp" : "tcp",
3162 inet_ntoa(sa->sin.sin_addr), ntohs(sa->sin.sin_port)));
3163
3164 nc->flags |= MG_F_CONNECTING;
3165 if (proto == SOCK_DGRAM) {
3166 nc->iface->vtable->connect_udp(nc);
3167 } else {
3168 nc->iface->vtable->connect_tcp(nc, sa);
3169 }
3170 mg_add_conn(nc->mgr, nc);
3171 return nc;
3172 }
3173
mg_if_connect_cb(struct mg_connection * nc,int err)3174 void mg_if_connect_cb(struct mg_connection *nc, int err) {
3175 LOG(LL_DEBUG,
3176 ("%p %s://%s:%hu -> %d", nc, (nc->flags & MG_F_UDP ? "udp" : "tcp"),
3177 inet_ntoa(nc->sa.sin.sin_addr), ntohs(nc->sa.sin.sin_port), err));
3178 nc->flags &= ~MG_F_CONNECTING;
3179 if (err != 0) {
3180 nc->flags |= MG_F_CLOSE_IMMEDIATELY;
3181 }
3182 #if MG_ENABLE_SSL
3183 if (err == 0 && (nc->flags & MG_F_SSL)) {
3184 mg_ssl_handshake(nc);
3185 } else
3186 #endif
3187 {
3188 mg_call(nc, NULL, nc->user_data, MG_EV_CONNECT, &err);
3189 }
3190 }
3191
3192 #if MG_ENABLE_ASYNC_RESOLVER
3193 /*
3194 * Callback for the async resolver on mg_connect_opt() call.
3195 * Main task of this function is to trigger MG_EV_CONNECT event with
3196 * either failure (and dealloc the connection)
3197 * or success (and proceed with connect()
3198 */
resolve_cb(struct mg_dns_message * msg,void * data,enum mg_resolve_err e)3199 static void resolve_cb(struct mg_dns_message *msg, void *data,
3200 enum mg_resolve_err e) {
3201 struct mg_connection *nc = (struct mg_connection *) data;
3202 int i;
3203 int failure = -1;
3204
3205 nc->flags &= ~MG_F_RESOLVING;
3206 if (msg != NULL) {
3207 /*
3208 * Take the first DNS A answer and run...
3209 */
3210 for (i = 0; i < msg->num_answers; i++) {
3211 if (msg->answers[i].rtype == MG_DNS_A_RECORD) {
3212 /*
3213 * Async resolver guarantees that there is at least one answer.
3214 * TODO(lsm): handle IPv6 answers too
3215 */
3216 mg_dns_parse_record_data(msg, &msg->answers[i], &nc->sa.sin.sin_addr,
3217 4);
3218 mg_do_connect(nc, nc->flags & MG_F_UDP ? SOCK_DGRAM : SOCK_STREAM,
3219 &nc->sa);
3220 return;
3221 }
3222 }
3223 }
3224
3225 if (e == MG_RESOLVE_TIMEOUT) {
3226 double now = mg_time();
3227 mg_call(nc, NULL, nc->user_data, MG_EV_TIMER, &now);
3228 }
3229
3230 /*
3231 * If we get there was no MG_DNS_A_RECORD in the answer
3232 */
3233 mg_call(nc, NULL, nc->user_data, MG_EV_CONNECT, &failure);
3234 mg_call(nc, NULL, nc->user_data, MG_EV_CLOSE, NULL);
3235 mg_destroy_conn(nc, 1 /* destroy_if */);
3236 }
3237 #endif
3238
mg_connect(struct mg_mgr * mgr,const char * address,MG_CB (mg_event_handler_t callback,void * user_data))3239 struct mg_connection *mg_connect(struct mg_mgr *mgr, const char *address,
3240 MG_CB(mg_event_handler_t callback,
3241 void *user_data)) {
3242 struct mg_connect_opts opts;
3243 memset(&opts, 0, sizeof(opts));
3244 return mg_connect_opt(mgr, address, MG_CB(callback, user_data), opts);
3245 }
3246
mg_ev_handler_empty(struct mg_connection * c,int ev,void * ev_data MG_UD_ARG (void * user_data))3247 void mg_ev_handler_empty(struct mg_connection *c, int ev,
3248 void *ev_data MG_UD_ARG(void *user_data)) {
3249 (void) c;
3250 (void) ev;
3251 (void) ev_data;
3252 #if MG_ENABLE_CALLBACK_USERDATA
3253 (void) user_data;
3254 #endif
3255 }
3256
mg_connect_opt(struct mg_mgr * mgr,const char * address,MG_CB (mg_event_handler_t callback,void * user_data),struct mg_connect_opts opts)3257 struct mg_connection *mg_connect_opt(struct mg_mgr *mgr, const char *address,
3258 MG_CB(mg_event_handler_t callback,
3259 void *user_data),
3260 struct mg_connect_opts opts) {
3261 struct mg_connection *nc = NULL;
3262 int proto, rc;
3263 struct mg_add_sock_opts add_sock_opts;
3264 char host[MG_MAX_HOST_LEN];
3265
3266 MG_COPY_COMMON_CONNECTION_OPTIONS(&add_sock_opts, &opts);
3267
3268 if (callback == NULL) callback = mg_ev_handler_empty;
3269
3270 if ((nc = mg_create_connection(mgr, callback, add_sock_opts)) == NULL) {
3271 return NULL;
3272 }
3273
3274 if ((rc = mg_parse_address(address, &nc->sa, &proto, host, sizeof(host))) <
3275 0) {
3276 /* Address is malformed */
3277 MG_SET_PTRPTR(opts.error_string, "cannot parse address");
3278 mg_destroy_conn(nc, 1 /* destroy_if */);
3279 return NULL;
3280 }
3281
3282 nc->flags |= opts.flags & _MG_ALLOWED_CONNECT_FLAGS_MASK;
3283 nc->flags |= (proto == SOCK_DGRAM) ? MG_F_UDP : 0;
3284 #if MG_ENABLE_CALLBACK_USERDATA
3285 nc->user_data = user_data;
3286 #else
3287 nc->user_data = opts.user_data;
3288 #endif
3289
3290 #if MG_ENABLE_SSL
3291 LOG(LL_DEBUG,
3292 ("%p %s %s,%s,%s", nc, address, (opts.ssl_cert ? opts.ssl_cert : "-"),
3293 (opts.ssl_key ? opts.ssl_key : "-"),
3294 (opts.ssl_ca_cert ? opts.ssl_ca_cert : "-")));
3295
3296 if (opts.ssl_cert != NULL || opts.ssl_ca_cert != NULL ||
3297 opts.ssl_psk_identity != NULL) {
3298 const char *err_msg = NULL;
3299 struct mg_ssl_if_conn_params params;
3300 if (nc->flags & MG_F_UDP) {
3301 MG_SET_PTRPTR(opts.error_string, "SSL for UDP is not supported");
3302 mg_destroy_conn(nc, 1 /* destroy_if */);
3303 return NULL;
3304 }
3305 memset(¶ms, 0, sizeof(params));
3306 params.cert = opts.ssl_cert;
3307 params.key = opts.ssl_key;
3308 params.ca_cert = opts.ssl_ca_cert;
3309 params.cipher_suites = opts.ssl_cipher_suites;
3310 params.psk_identity = opts.ssl_psk_identity;
3311 params.psk_key = opts.ssl_psk_key;
3312 if (opts.ssl_ca_cert != NULL) {
3313 if (opts.ssl_server_name != NULL) {
3314 if (strcmp(opts.ssl_server_name, "*") != 0) {
3315 params.server_name = opts.ssl_server_name;
3316 }
3317 } else if (rc == 0) { /* If it's a DNS name, use host. */
3318 params.server_name = host;
3319 }
3320 }
3321 if (mg_ssl_if_conn_init(nc, ¶ms, &err_msg) != MG_SSL_OK) {
3322 MG_SET_PTRPTR(opts.error_string, err_msg);
3323 mg_destroy_conn(nc, 1 /* destroy_if */);
3324 return NULL;
3325 }
3326 nc->flags |= MG_F_SSL;
3327 }
3328 #endif /* MG_ENABLE_SSL */
3329
3330 if (rc == 0) {
3331 #if MG_ENABLE_ASYNC_RESOLVER
3332 /*
3333 * DNS resolution is required for host.
3334 * mg_parse_address() fills port in nc->sa, which we pass to resolve_cb()
3335 */
3336 struct mg_connection *dns_conn = NULL;
3337 struct mg_resolve_async_opts o;
3338 memset(&o, 0, sizeof(o));
3339 o.dns_conn = &dns_conn;
3340 o.nameserver = opts.nameserver;
3341 if (mg_resolve_async_opt(nc->mgr, host, MG_DNS_A_RECORD, resolve_cb, nc,
3342 o) != 0) {
3343 MG_SET_PTRPTR(opts.error_string, "cannot schedule DNS lookup");
3344 mg_destroy_conn(nc, 1 /* destroy_if */);
3345 return NULL;
3346 }
3347 nc->priv_2 = dns_conn;
3348 nc->flags |= MG_F_RESOLVING;
3349 return nc;
3350 #else
3351 MG_SET_PTRPTR(opts.error_string, "Resolver is disabled");
3352 mg_destroy_conn(nc, 1 /* destroy_if */);
3353 return NULL;
3354 #endif
3355 } else {
3356 /* Address is parsed and resolved to IP. proceed with connect() */
3357 return mg_do_connect(nc, proto, &nc->sa);
3358 }
3359 }
3360
mg_bind(struct mg_mgr * srv,const char * address,MG_CB (mg_event_handler_t event_handler,void * user_data))3361 struct mg_connection *mg_bind(struct mg_mgr *srv, const char *address,
3362 MG_CB(mg_event_handler_t event_handler,
3363 void *user_data)) {
3364 struct mg_bind_opts opts;
3365 memset(&opts, 0, sizeof(opts));
3366 return mg_bind_opt(srv, address, MG_CB(event_handler, user_data), opts);
3367 }
3368
mg_bind_opt(struct mg_mgr * mgr,const char * address,MG_CB (mg_event_handler_t callback,void * user_data),struct mg_bind_opts opts)3369 struct mg_connection *mg_bind_opt(struct mg_mgr *mgr, const char *address,
3370 MG_CB(mg_event_handler_t callback,
3371 void *user_data),
3372 struct mg_bind_opts opts) {
3373 union socket_address sa;
3374 struct mg_connection *nc = NULL;
3375 int proto, rc;
3376 struct mg_add_sock_opts add_sock_opts;
3377 char host[MG_MAX_HOST_LEN];
3378
3379 #if MG_ENABLE_CALLBACK_USERDATA
3380 opts.user_data = user_data;
3381 #endif
3382
3383 if (callback == NULL) callback = mg_ev_handler_empty;
3384
3385 MG_COPY_COMMON_CONNECTION_OPTIONS(&add_sock_opts, &opts);
3386
3387 if (mg_parse_address(address, &sa, &proto, host, sizeof(host)) <= 0) {
3388 MG_SET_PTRPTR(opts.error_string, "cannot parse address");
3389 return NULL;
3390 }
3391
3392 nc = mg_create_connection(mgr, callback, add_sock_opts);
3393 if (nc == NULL) {
3394 return NULL;
3395 }
3396
3397 nc->sa = sa;
3398 nc->flags |= MG_F_LISTENING;
3399 if (proto == SOCK_DGRAM) nc->flags |= MG_F_UDP;
3400
3401 #if MG_ENABLE_SSL
3402 DBG(("%p %s %s,%s,%s", nc, address, (opts.ssl_cert ? opts.ssl_cert : "-"),
3403 (opts.ssl_key ? opts.ssl_key : "-"),
3404 (opts.ssl_ca_cert ? opts.ssl_ca_cert : "-")));
3405
3406 if (opts.ssl_cert != NULL || opts.ssl_ca_cert != NULL) {
3407 const char *err_msg = NULL;
3408 struct mg_ssl_if_conn_params params;
3409 if (nc->flags & MG_F_UDP) {
3410 MG_SET_PTRPTR(opts.error_string, "SSL for UDP is not supported");
3411 mg_destroy_conn(nc, 1 /* destroy_if */);
3412 return NULL;
3413 }
3414 memset(¶ms, 0, sizeof(params));
3415 params.cert = opts.ssl_cert;
3416 params.key = opts.ssl_key;
3417 params.ca_cert = opts.ssl_ca_cert;
3418 params.cipher_suites = opts.ssl_cipher_suites;
3419 if (mg_ssl_if_conn_init(nc, ¶ms, &err_msg) != MG_SSL_OK) {
3420 MG_SET_PTRPTR(opts.error_string, err_msg);
3421 mg_destroy_conn(nc, 1 /* destroy_if */);
3422 return NULL;
3423 }
3424 nc->flags |= MG_F_SSL;
3425 }
3426 #endif /* MG_ENABLE_SSL */
3427
3428 if (nc->flags & MG_F_UDP) {
3429 rc = nc->iface->vtable->listen_udp(nc, &nc->sa);
3430 } else {
3431 rc = nc->iface->vtable->listen_tcp(nc, &nc->sa);
3432 }
3433 if (rc != 0) {
3434 DBG(("Failed to open listener: %d", rc));
3435 MG_SET_PTRPTR(opts.error_string, "failed to open listener");
3436 mg_destroy_conn(nc, 1 /* destroy_if */);
3437 return NULL;
3438 }
3439 mg_add_conn(nc->mgr, nc);
3440
3441 return nc;
3442 }
3443
mg_next(struct mg_mgr * s,struct mg_connection * conn)3444 struct mg_connection *mg_next(struct mg_mgr *s, struct mg_connection *conn) {
3445 return conn == NULL ? s->active_connections : conn->next;
3446 }
3447
3448 #if MG_ENABLE_BROADCAST
mg_broadcast(struct mg_mgr * mgr,mg_event_handler_t cb,void * data,size_t len)3449 void mg_broadcast(struct mg_mgr *mgr, mg_event_handler_t cb, void *data,
3450 size_t len) {
3451 struct ctl_msg ctl_msg;
3452
3453 /*
3454 * Mongoose manager has a socketpair, `struct mg_mgr::ctl`,
3455 * where `mg_broadcast()` pushes the message.
3456 * `mg_mgr_poll()` wakes up, reads a message from the socket pair, and calls
3457 * specified callback for each connection. Thus the callback function executes
3458 * in event manager thread.
3459 */
3460 if (mgr->ctl[0] != INVALID_SOCKET && data != NULL &&
3461 len < sizeof(ctl_msg.message)) {
3462 size_t dummy;
3463
3464 ctl_msg.callback = cb;
3465 memcpy(ctl_msg.message, data, len);
3466 dummy = MG_SEND_FUNC(mgr->ctl[0], (char *) &ctl_msg,
3467 offsetof(struct ctl_msg, message) + len, 0);
3468 dummy = MG_RECV_FUNC(mgr->ctl[0], (char *) &len, 1, 0);
3469 (void) dummy; /* https://gcc.gnu.org/bugzilla/show_bug.cgi?id=25509 */
3470 }
3471 }
3472 #endif /* MG_ENABLE_BROADCAST */
3473
isbyte(int n)3474 static int isbyte(int n) {
3475 return n >= 0 && n <= 255;
3476 }
3477
parse_net(const char * spec,uint32_t * net,uint32_t * mask)3478 static int parse_net(const char *spec, uint32_t *net, uint32_t *mask) {
3479 int n, a, b, c, d, slash = 32, len = 0;
3480
3481 if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5 ||
3482 sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) &&
3483 isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) && slash >= 0 &&
3484 slash < 33) {
3485 len = n;
3486 *net =
3487 ((uint32_t) a << 24) | ((uint32_t) b << 16) | ((uint32_t) c << 8) | d;
3488 *mask = slash ? 0xffffffffU << (32 - slash) : 0;
3489 }
3490
3491 return len;
3492 }
3493
mg_check_ip_acl(const char * acl,uint32_t remote_ip)3494 int mg_check_ip_acl(const char *acl, uint32_t remote_ip) {
3495 int allowed, flag;
3496 uint32_t net, mask;
3497 struct mg_str vec;
3498
3499 /* If any ACL is set, deny by default */
3500 allowed = (acl == NULL || *acl == '\0') ? '+' : '-';
3501
3502 while ((acl = mg_next_comma_list_entry(acl, &vec, NULL)) != NULL) {
3503 flag = vec.p[0];
3504 if ((flag != '+' && flag != '-') ||
3505 parse_net(&vec.p[1], &net, &mask) == 0) {
3506 return -1;
3507 }
3508
3509 if (net == (remote_ip & mask)) {
3510 allowed = flag;
3511 }
3512 }
3513
3514 DBG(("%08x %c", (unsigned int) remote_ip, allowed));
3515 return allowed == '+';
3516 }
3517
3518 /* Move data from one connection to another */
mg_forward(struct mg_connection * from,struct mg_connection * to)3519 void mg_forward(struct mg_connection *from, struct mg_connection *to) {
3520 mg_send(to, from->recv_mbuf.buf, from->recv_mbuf.len);
3521 mbuf_remove(&from->recv_mbuf, from->recv_mbuf.len);
3522 }
3523
mg_set_timer(struct mg_connection * c,double timestamp)3524 double mg_set_timer(struct mg_connection *c, double timestamp) {
3525 double result = c->ev_timer_time;
3526 c->ev_timer_time = timestamp;
3527 /*
3528 * If this connection is resolving, it's not in the list of active
3529 * connections, so not processed yet. It has a DNS resolver connection
3530 * linked to it. Set up a timer for the DNS connection.
3531 */
3532 DBG(("%p %p %d -> %lu", c, c->priv_2, (c->flags & MG_F_RESOLVING ? 1 : 0),
3533 (unsigned long) timestamp));
3534 if ((c->flags & MG_F_RESOLVING) && c->priv_2 != NULL) {
3535 mg_set_timer((struct mg_connection *) c->priv_2, timestamp);
3536 }
3537 return result;
3538 }
3539
mg_sock_set(struct mg_connection * nc,sock_t sock)3540 void mg_sock_set(struct mg_connection *nc, sock_t sock) {
3541 if (sock != INVALID_SOCKET) {
3542 nc->iface->vtable->sock_set(nc, sock);
3543 }
3544 }
3545
mg_if_get_conn_addr(struct mg_connection * nc,int remote,union socket_address * sa)3546 void mg_if_get_conn_addr(struct mg_connection *nc, int remote,
3547 union socket_address *sa) {
3548 nc->iface->vtable->get_conn_addr(nc, remote, sa);
3549 }
3550
mg_add_sock_opt(struct mg_mgr * s,sock_t sock,MG_CB (mg_event_handler_t callback,void * user_data),struct mg_add_sock_opts opts)3551 struct mg_connection *mg_add_sock_opt(struct mg_mgr *s, sock_t sock,
3552 MG_CB(mg_event_handler_t callback,
3553 void *user_data),
3554 struct mg_add_sock_opts opts) {
3555 #if MG_ENABLE_CALLBACK_USERDATA
3556 opts.user_data = user_data;
3557 #endif
3558
3559 struct mg_connection *nc = mg_create_connection_base(s, callback, opts);
3560 if (nc != NULL) {
3561 mg_sock_set(nc, sock);
3562 mg_add_conn(nc->mgr, nc);
3563 }
3564 return nc;
3565 }
3566
mg_add_sock(struct mg_mgr * s,sock_t sock,MG_CB (mg_event_handler_t callback,void * user_data))3567 struct mg_connection *mg_add_sock(struct mg_mgr *s, sock_t sock,
3568 MG_CB(mg_event_handler_t callback,
3569 void *user_data)) {
3570 struct mg_add_sock_opts opts;
3571 memset(&opts, 0, sizeof(opts));
3572 return mg_add_sock_opt(s, sock, MG_CB(callback, user_data), opts);
3573 }
3574
mg_time(void)3575 double mg_time(void) {
3576 return cs_time();
3577 }
3578 #ifdef MG_MODULE_LINES
3579 #line 1 "mongoose/src/mg_net_if_socket.h"
3580 #endif
3581 /*
3582 * Copyright (c) 2014-2016 Cesanta Software Limited
3583 * All rights reserved
3584 */
3585
3586 #ifndef CS_MONGOOSE_SRC_NET_IF_SOCKET_H_
3587 #define CS_MONGOOSE_SRC_NET_IF_SOCKET_H_
3588
3589 /* Amalgamated: #include "mg_net_if.h" */
3590
3591 #ifdef __cplusplus
3592 extern "C" {
3593 #endif /* __cplusplus */
3594
3595 #ifndef MG_ENABLE_NET_IF_SOCKET
3596 #define MG_ENABLE_NET_IF_SOCKET MG_NET_IF == MG_NET_IF_SOCKET
3597 #endif
3598
3599 extern const struct mg_iface_vtable mg_socket_iface_vtable;
3600
3601 #ifdef __cplusplus
3602 }
3603 #endif /* __cplusplus */
3604
3605 #endif /* CS_MONGOOSE_SRC_NET_IF_SOCKET_H_ */
3606 #ifdef MG_MODULE_LINES
3607 #line 1 "mongoose/src/mg_net_if_socks.h"
3608 #endif
3609 /*
3610 * Copyright (c) 2014-2017 Cesanta Software Limited
3611 * All rights reserved
3612 */
3613
3614 #ifndef CS_MONGOOSE_SRC_NET_IF_SOCKS_H_
3615 #define CS_MONGOOSE_SRC_NET_IF_SOCKS_H_
3616
3617 #if MG_ENABLE_SOCKS
3618 /* Amalgamated: #include "mg_net_if.h" */
3619
3620 #ifdef __cplusplus
3621 extern "C" {
3622 #endif /* __cplusplus */
3623
3624 extern const struct mg_iface_vtable mg_socks_iface_vtable;
3625
3626 #ifdef __cplusplus
3627 }
3628 #endif /* __cplusplus */
3629 #endif /* MG_ENABLE_SOCKS */
3630 #endif /* CS_MONGOOSE_SRC_NET_IF_SOCKS_H_ */
3631 #ifdef MG_MODULE_LINES
3632 #line 1 "mongoose/src/mg_net_if.c"
3633 #endif
3634 /* Amalgamated: #include "mg_net_if.h" */
3635 /* Amalgamated: #include "mg_internal.h" */
3636 /* Amalgamated: #include "mg_net_if_socket.h" */
3637
3638 extern const struct mg_iface_vtable mg_default_iface_vtable;
3639
3640 const struct mg_iface_vtable *mg_ifaces[] = {
3641 &mg_default_iface_vtable,
3642 };
3643
3644 int mg_num_ifaces = (int) (sizeof(mg_ifaces) / sizeof(mg_ifaces[0]));
3645
mg_if_create_iface(const struct mg_iface_vtable * vtable,struct mg_mgr * mgr)3646 struct mg_iface *mg_if_create_iface(const struct mg_iface_vtable *vtable,
3647 struct mg_mgr *mgr) {
3648 struct mg_iface *iface = (struct mg_iface *) MG_CALLOC(1, sizeof(*iface));
3649 iface->mgr = mgr;
3650 iface->data = NULL;
3651 iface->vtable = vtable;
3652 return iface;
3653 }
3654
mg_find_iface(struct mg_mgr * mgr,const struct mg_iface_vtable * vtable,struct mg_iface * from)3655 struct mg_iface *mg_find_iface(struct mg_mgr *mgr,
3656 const struct mg_iface_vtable *vtable,
3657 struct mg_iface *from) {
3658 int i = 0;
3659 if (from != NULL) {
3660 for (i = 0; i < mgr->num_ifaces; i++) {
3661 if (mgr->ifaces[i] == from) {
3662 i++;
3663 break;
3664 }
3665 }
3666 }
3667
3668 for (; i < mgr->num_ifaces; i++) {
3669 if (mgr->ifaces[i]->vtable == vtable) {
3670 return mgr->ifaces[i];
3671 }
3672 }
3673 return NULL;
3674 }
3675
mg_mgr_min_timer(const struct mg_mgr * mgr)3676 double mg_mgr_min_timer(const struct mg_mgr *mgr) {
3677 double min_timer = 0;
3678 struct mg_connection *nc;
3679 for (nc = mgr->active_connections; nc != NULL; nc = nc->next) {
3680 if (nc->ev_timer_time <= 0) continue;
3681 if (min_timer == 0 || nc->ev_timer_time < min_timer) {
3682 min_timer = nc->ev_timer_time;
3683 }
3684 }
3685 return min_timer;
3686 }
3687 #ifdef MG_MODULE_LINES
3688 #line 1 "mongoose/src/mg_net_if_null.c"
3689 #endif
3690 /*
3691 * Copyright (c) 2018 Cesanta Software Limited
3692 * All rights reserved
3693 *
3694 * This software is dual-licensed: you can redistribute it and/or modify
3695 * it under the terms of the GNU General Public License version 2 as
3696 * published by the Free Software Foundation. For the terms of this
3697 * license, see <http://www.gnu.org/licenses/>.
3698 *
3699 * You are free to use this software under the terms of the GNU General
3700 * Public License, but WITHOUT ANY WARRANTY; without even the implied
3701 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
3702 * See the GNU General Public License for more details.
3703 *
3704 * Alternatively, you can license this software under a commercial
3705 * license, as set out in <https://www.cesanta.com/license>.
3706 */
3707
mg_null_if_connect_tcp(struct mg_connection * c,const union socket_address * sa)3708 static void mg_null_if_connect_tcp(struct mg_connection *c,
3709 const union socket_address *sa) {
3710 c->flags |= MG_F_CLOSE_IMMEDIATELY;
3711 (void) sa;
3712 }
3713
mg_null_if_connect_udp(struct mg_connection * c)3714 static void mg_null_if_connect_udp(struct mg_connection *c) {
3715 c->flags |= MG_F_CLOSE_IMMEDIATELY;
3716 }
3717
mg_null_if_listen_tcp(struct mg_connection * c,union socket_address * sa)3718 static int mg_null_if_listen_tcp(struct mg_connection *c,
3719 union socket_address *sa) {
3720 (void) c;
3721 (void) sa;
3722 return -1;
3723 }
3724
mg_null_if_listen_udp(struct mg_connection * c,union socket_address * sa)3725 static int mg_null_if_listen_udp(struct mg_connection *c,
3726 union socket_address *sa) {
3727 (void) c;
3728 (void) sa;
3729 return -1;
3730 }
3731
mg_null_if_tcp_send(struct mg_connection * c,const void * buf,size_t len)3732 static int mg_null_if_tcp_send(struct mg_connection *c, const void *buf,
3733 size_t len) {
3734 (void) c;
3735 (void) buf;
3736 (void) len;
3737 return -1;
3738 }
3739
mg_null_if_udp_send(struct mg_connection * c,const void * buf,size_t len)3740 static int mg_null_if_udp_send(struct mg_connection *c, const void *buf,
3741 size_t len) {
3742 (void) c;
3743 (void) buf;
3744 (void) len;
3745 return -1;
3746 }
3747
mg_null_if_tcp_recv(struct mg_connection * c,void * buf,size_t len)3748 int mg_null_if_tcp_recv(struct mg_connection *c, void *buf, size_t len) {
3749 (void) c;
3750 (void) buf;
3751 (void) len;
3752 return -1;
3753 }
3754
mg_null_if_udp_recv(struct mg_connection * c,void * buf,size_t len,union socket_address * sa,size_t * sa_len)3755 int mg_null_if_udp_recv(struct mg_connection *c, void *buf, size_t len,
3756 union socket_address *sa, size_t *sa_len) {
3757 (void) c;
3758 (void) buf;
3759 (void) len;
3760 (void) sa;
3761 (void) sa_len;
3762 return -1;
3763 }
3764
mg_null_if_create_conn(struct mg_connection * c)3765 static int mg_null_if_create_conn(struct mg_connection *c) {
3766 (void) c;
3767 return 1;
3768 }
3769
mg_null_if_destroy_conn(struct mg_connection * c)3770 static void mg_null_if_destroy_conn(struct mg_connection *c) {
3771 (void) c;
3772 }
3773
mg_null_if_sock_set(struct mg_connection * c,sock_t sock)3774 static void mg_null_if_sock_set(struct mg_connection *c, sock_t sock) {
3775 (void) c;
3776 (void) sock;
3777 }
3778
mg_null_if_init(struct mg_iface * iface)3779 static void mg_null_if_init(struct mg_iface *iface) {
3780 (void) iface;
3781 }
3782
mg_null_if_free(struct mg_iface * iface)3783 static void mg_null_if_free(struct mg_iface *iface) {
3784 (void) iface;
3785 }
3786
mg_null_if_add_conn(struct mg_connection * c)3787 static void mg_null_if_add_conn(struct mg_connection *c) {
3788 c->sock = INVALID_SOCKET;
3789 c->flags |= MG_F_CLOSE_IMMEDIATELY;
3790 }
3791
mg_null_if_remove_conn(struct mg_connection * c)3792 static void mg_null_if_remove_conn(struct mg_connection *c) {
3793 (void) c;
3794 }
3795
mg_null_if_poll(struct mg_iface * iface,int timeout_ms)3796 static time_t mg_null_if_poll(struct mg_iface *iface, int timeout_ms) {
3797 struct mg_mgr *mgr = iface->mgr;
3798 struct mg_connection *nc, *tmp;
3799 double now = mg_time();
3800 /* We basically just run timers and poll. */
3801 for (nc = mgr->active_connections; nc != NULL; nc = tmp) {
3802 tmp = nc->next;
3803 mg_if_poll(nc, now);
3804 }
3805 (void) timeout_ms;
3806 return (time_t) now;
3807 }
3808
mg_null_if_get_conn_addr(struct mg_connection * c,int remote,union socket_address * sa)3809 static void mg_null_if_get_conn_addr(struct mg_connection *c, int remote,
3810 union socket_address *sa) {
3811 (void) c;
3812 (void) remote;
3813 (void) sa;
3814 }
3815
3816 #define MG_NULL_IFACE_VTABLE \
3817 { \
3818 mg_null_if_init, mg_null_if_free, mg_null_if_add_conn, \
3819 mg_null_if_remove_conn, mg_null_if_poll, mg_null_if_listen_tcp, \
3820 mg_null_if_listen_udp, mg_null_if_connect_tcp, mg_null_if_connect_udp, \
3821 mg_null_if_tcp_send, mg_null_if_udp_send, mg_null_if_tcp_recv, \
3822 mg_null_if_udp_recv, mg_null_if_create_conn, mg_null_if_destroy_conn, \
3823 mg_null_if_sock_set, mg_null_if_get_conn_addr, \
3824 }
3825
3826 const struct mg_iface_vtable mg_null_iface_vtable = MG_NULL_IFACE_VTABLE;
3827
3828 #if MG_NET_IF == MG_NET_IF_NULL
3829 const struct mg_iface_vtable mg_default_iface_vtable = MG_NULL_IFACE_VTABLE;
3830 #endif /* MG_NET_IF == MG_NET_IF_NULL */
3831 #ifdef MG_MODULE_LINES
3832 #line 1 "mongoose/src/mg_net_if_socket.c"
3833 #endif
3834 /*
3835 * Copyright (c) 2014-2016 Cesanta Software Limited
3836 * All rights reserved
3837 */
3838
3839 #if MG_ENABLE_NET_IF_SOCKET
3840
3841 /* Amalgamated: #include "mg_net_if_socket.h" */
3842 /* Amalgamated: #include "mg_internal.h" */
3843 /* Amalgamated: #include "mg_util.h" */
3844
3845 static sock_t mg_open_listening_socket(union socket_address *sa, int type,
3846 int proto);
3847
mg_set_non_blocking_mode(sock_t sock)3848 void mg_set_non_blocking_mode(sock_t sock) {
3849 #ifdef _WIN32
3850 unsigned long on = 1;
3851 ioctlsocket(sock, FIONBIO, &on);
3852 #else
3853 int flags = fcntl(sock, F_GETFL, 0);
3854 fcntl(sock, F_SETFL, flags | O_NONBLOCK);
3855 #endif
3856 }
3857
mg_is_error(void)3858 static int mg_is_error(void) {
3859 int err = mg_get_errno();
3860 return err != EINPROGRESS && err != EWOULDBLOCK
3861 #ifndef WINCE
3862 && err != EAGAIN && err != EINTR
3863 #endif
3864 #ifdef _WIN32
3865 && WSAGetLastError() != WSAEINTR && WSAGetLastError() != WSAEWOULDBLOCK
3866 #endif
3867 ;
3868 }
3869
mg_socket_if_connect_tcp(struct mg_connection * nc,const union socket_address * sa)3870 void mg_socket_if_connect_tcp(struct mg_connection *nc,
3871 const union socket_address *sa) {
3872 int rc, proto = 0;
3873 nc->sock = socket(sa->sa.sa_family, SOCK_STREAM, proto);
3874 if (nc->sock == INVALID_SOCKET) {
3875 nc->err = mg_get_errno() ? mg_get_errno() : 1;
3876 return;
3877 }
3878 #if !defined(MG_ESP8266)
3879 mg_set_non_blocking_mode(nc->sock);
3880 #endif
3881 socklen_t sa_len =
3882 (sa->sa.sa_family == AF_INET) ? sizeof(sa->sin) : sizeof(sa->sin6);
3883 rc = connect(nc->sock, &sa->sa, sa_len);
3884 nc->err = rc < 0 && mg_is_error() ? mg_get_errno() : 0;
3885 DBG(("%p sock %d rc %d errno %d err %d", nc, nc->sock, rc, mg_get_errno(),
3886 nc->err));
3887 }
3888
mg_socket_if_connect_udp(struct mg_connection * nc)3889 void mg_socket_if_connect_udp(struct mg_connection *nc) {
3890 nc->sock = socket(AF_INET, SOCK_DGRAM, 0);
3891 if (nc->sock == INVALID_SOCKET) {
3892 nc->err = mg_get_errno() ? mg_get_errno() : 1;
3893 return;
3894 }
3895 if (nc->flags & MG_F_ENABLE_BROADCAST) {
3896 int optval = 1;
3897 if (setsockopt(nc->sock, SOL_SOCKET, SO_BROADCAST, (const char *) &optval,
3898 sizeof(optval)) < 0) {
3899 nc->err = mg_get_errno() ? mg_get_errno() : 1;
3900 return;
3901 }
3902 }
3903 nc->err = 0;
3904 }
3905
mg_socket_if_listen_tcp(struct mg_connection * nc,union socket_address * sa)3906 int mg_socket_if_listen_tcp(struct mg_connection *nc,
3907 union socket_address *sa) {
3908 int proto = 0;
3909 sock_t sock = mg_open_listening_socket(sa, SOCK_STREAM, proto);
3910 if (sock == INVALID_SOCKET) {
3911 return (mg_get_errno() ? mg_get_errno() : 1);
3912 }
3913 mg_sock_set(nc, sock);
3914 return 0;
3915 }
3916
mg_socket_if_listen_udp(struct mg_connection * nc,union socket_address * sa)3917 static int mg_socket_if_listen_udp(struct mg_connection *nc,
3918 union socket_address *sa) {
3919 sock_t sock = mg_open_listening_socket(sa, SOCK_DGRAM, 0);
3920 if (sock == INVALID_SOCKET) return (mg_get_errno() ? mg_get_errno() : 1);
3921 mg_sock_set(nc, sock);
3922 return 0;
3923 }
3924
mg_socket_if_tcp_send(struct mg_connection * nc,const void * buf,size_t len)3925 static int mg_socket_if_tcp_send(struct mg_connection *nc, const void *buf,
3926 size_t len) {
3927 int n = (int) MG_SEND_FUNC(nc->sock, buf, len, 0);
3928 if (n < 0 && !mg_is_error()) n = 0;
3929 return n;
3930 }
3931
mg_socket_if_udp_send(struct mg_connection * nc,const void * buf,size_t len)3932 static int mg_socket_if_udp_send(struct mg_connection *nc, const void *buf,
3933 size_t len) {
3934 int n = sendto(nc->sock, buf, len, 0, &nc->sa.sa, sizeof(nc->sa.sin));
3935 if (n < 0 && !mg_is_error()) n = 0;
3936 return n;
3937 }
3938
mg_socket_if_tcp_recv(struct mg_connection * nc,void * buf,size_t len)3939 static int mg_socket_if_tcp_recv(struct mg_connection *nc, void *buf,
3940 size_t len) {
3941 int n = (int) MG_RECV_FUNC(nc->sock, buf, len, 0);
3942 if (n == 0) {
3943 /* Orderly shutdown of the socket, try flushing output. */
3944 nc->flags |= MG_F_SEND_AND_CLOSE;
3945 } else if (n < 0 && !mg_is_error()) {
3946 n = 0;
3947 }
3948 return n;
3949 }
3950
mg_socket_if_udp_recv(struct mg_connection * nc,void * buf,size_t len,union socket_address * sa,size_t * sa_len)3951 static int mg_socket_if_udp_recv(struct mg_connection *nc, void *buf,
3952 size_t len, union socket_address *sa,
3953 size_t *sa_len) {
3954 socklen_t sa_len_st = *sa_len;
3955 int n = recvfrom(nc->sock, buf, len, 0, &sa->sa, &sa_len_st);
3956 *sa_len = sa_len_st;
3957 if (n < 0 && !mg_is_error()) n = 0;
3958 return n;
3959 }
3960
mg_socket_if_create_conn(struct mg_connection * nc)3961 int mg_socket_if_create_conn(struct mg_connection *nc) {
3962 (void) nc;
3963 return 1;
3964 }
3965
mg_socket_if_destroy_conn(struct mg_connection * nc)3966 void mg_socket_if_destroy_conn(struct mg_connection *nc) {
3967 if (nc->sock == INVALID_SOCKET) return;
3968 if (!(nc->flags & MG_F_UDP)) {
3969 closesocket(nc->sock);
3970 } else {
3971 /* Only close outgoing UDP sockets or listeners. */
3972 if (nc->listener == NULL) closesocket(nc->sock);
3973 }
3974 nc->sock = INVALID_SOCKET;
3975 }
3976
mg_accept_conn(struct mg_connection * lc)3977 static int mg_accept_conn(struct mg_connection *lc) {
3978 struct mg_connection *nc;
3979 union socket_address sa;
3980 socklen_t sa_len = sizeof(sa);
3981 /* NOTE(lsm): on Windows, sock is always > FD_SETSIZE */
3982 sock_t sock = accept(lc->sock, &sa.sa, &sa_len);
3983 if (sock == INVALID_SOCKET) {
3984 if (mg_is_error()) {
3985 DBG(("%p: failed to accept: %d", lc, mg_get_errno()));
3986 }
3987 return 0;
3988 }
3989 nc = mg_if_accept_new_conn(lc);
3990 if (nc == NULL) {
3991 closesocket(sock);
3992 return 0;
3993 }
3994 DBG(("%p conn from %s:%d", nc, inet_ntoa(sa.sin.sin_addr),
3995 ntohs(sa.sin.sin_port)));
3996 mg_sock_set(nc, sock);
3997 mg_if_accept_tcp_cb(nc, &sa, sa_len);
3998 return 1;
3999 }
4000
4001 /* 'sa' must be an initialized address to bind to */
mg_open_listening_socket(union socket_address * sa,int type,int proto)4002 static sock_t mg_open_listening_socket(union socket_address *sa, int type,
4003 int proto) {
4004 socklen_t sa_len =
4005 (sa->sa.sa_family == AF_INET) ? sizeof(sa->sin) : sizeof(sa->sin6);
4006 sock_t sock = INVALID_SOCKET;
4007 #if !MG_LWIP
4008 int on = 1;
4009 #endif
4010
4011 if ((sock = socket(sa->sa.sa_family, type, proto)) != INVALID_SOCKET &&
4012 #if !MG_LWIP /* LWIP doesn't support either */
4013 #if defined(_WIN32) && defined(SO_EXCLUSIVEADDRUSE) && !defined(WINCE)
4014 /* "Using SO_REUSEADDR and SO_EXCLUSIVEADDRUSE" http://goo.gl/RmrFTm */
4015 !setsockopt(sock, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (void *) &on,
4016 sizeof(on)) &&
4017 #endif
4018
4019 #if !defined(_WIN32) || !defined(SO_EXCLUSIVEADDRUSE)
4020 /*
4021 * SO_RESUSEADDR is not enabled on Windows because the semantics of
4022 * SO_REUSEADDR on UNIX and Windows is different. On Windows,
4023 * SO_REUSEADDR allows to bind a socket to a port without error even if
4024 * the port is already open by another program. This is not the behavior
4025 * SO_REUSEADDR was designed for, and leads to hard-to-track failure
4026 * scenarios. Therefore, SO_REUSEADDR was disabled on Windows unless
4027 * SO_EXCLUSIVEADDRUSE is supported and set on a socket.
4028 */
4029 !setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *) &on, sizeof(on)) &&
4030 #endif
4031 #endif /* !MG_LWIP */
4032
4033 !bind(sock, &sa->sa, sa_len) &&
4034 (type == SOCK_DGRAM || listen(sock, SOMAXCONN) == 0)) {
4035 #if !MG_LWIP
4036 mg_set_non_blocking_mode(sock);
4037 /* In case port was set to 0, get the real port number */
4038 (void) getsockname(sock, &sa->sa, &sa_len);
4039 #endif
4040 } else if (sock != INVALID_SOCKET) {
4041 closesocket(sock);
4042 sock = INVALID_SOCKET;
4043 }
4044
4045 return sock;
4046 }
4047
4048 #define _MG_F_FD_CAN_READ 1
4049 #define _MG_F_FD_CAN_WRITE 1 << 1
4050 #define _MG_F_FD_ERROR 1 << 2
4051
mg_mgr_handle_conn(struct mg_connection * nc,int fd_flags,double now)4052 void mg_mgr_handle_conn(struct mg_connection *nc, int fd_flags, double now) {
4053 int worth_logging =
4054 fd_flags != 0 || (nc->flags & (MG_F_WANT_READ | MG_F_WANT_WRITE));
4055 if (worth_logging) {
4056 DBG(("%p fd=%d fd_flags=%d nc_flags=0x%lx rmbl=%d smbl=%d", nc, nc->sock,
4057 fd_flags, nc->flags, (int) nc->recv_mbuf.len,
4058 (int) nc->send_mbuf.len));
4059 }
4060
4061 if (!mg_if_poll(nc, now)) return;
4062
4063 if (nc->flags & MG_F_CONNECTING) {
4064 if (fd_flags != 0) {
4065 int err = 0;
4066 #if !defined(MG_ESP8266)
4067 if (!(nc->flags & MG_F_UDP)) {
4068 socklen_t len = sizeof(err);
4069 int ret =
4070 getsockopt(nc->sock, SOL_SOCKET, SO_ERROR, (char *) &err, &len);
4071 if (ret != 0) {
4072 err = 1;
4073 } else if (err == EAGAIN || err == EWOULDBLOCK) {
4074 err = 0;
4075 }
4076 }
4077 #else
4078 /*
4079 * On ESP8266 we use blocking connect.
4080 */
4081 err = nc->err;
4082 #endif
4083 mg_if_connect_cb(nc, err);
4084 } else if (nc->err != 0) {
4085 mg_if_connect_cb(nc, nc->err);
4086 }
4087 }
4088
4089 if (fd_flags & _MG_F_FD_CAN_READ) {
4090 if (nc->flags & MG_F_UDP) {
4091 mg_if_can_recv_cb(nc);
4092 } else {
4093 if (nc->flags & MG_F_LISTENING) {
4094 /*
4095 * We're not looping here, and accepting just one connection at
4096 * a time. The reason is that eCos does not respect non-blocking
4097 * flag on a listening socket and hangs in a loop.
4098 */
4099 mg_accept_conn(nc);
4100 } else {
4101 mg_if_can_recv_cb(nc);
4102 }
4103 }
4104 }
4105
4106 if (fd_flags & _MG_F_FD_CAN_WRITE) mg_if_can_send_cb(nc);
4107
4108 if (worth_logging) {
4109 DBG(("%p after fd=%d nc_flags=0x%lx rmbl=%d smbl=%d", nc, nc->sock,
4110 nc->flags, (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len));
4111 }
4112 }
4113
4114 #if MG_ENABLE_BROADCAST
mg_mgr_handle_ctl_sock(struct mg_mgr * mgr)4115 static void mg_mgr_handle_ctl_sock(struct mg_mgr *mgr) {
4116 struct ctl_msg ctl_msg;
4117 int len =
4118 (int) MG_RECV_FUNC(mgr->ctl[1], (char *) &ctl_msg, sizeof(ctl_msg), 0);
4119 size_t dummy = MG_SEND_FUNC(mgr->ctl[1], ctl_msg.message, 1, 0);
4120 DBG(("read %d from ctl socket", len));
4121 (void) dummy; /* https://gcc.gnu.org/bugzilla/show_bug.cgi?id=25509 */
4122 if (len >= (int) sizeof(ctl_msg.callback) && ctl_msg.callback != NULL) {
4123 struct mg_connection *nc;
4124 for (nc = mg_next(mgr, NULL); nc != NULL; nc = mg_next(mgr, nc)) {
4125 ctl_msg.callback(nc, MG_EV_POLL,
4126 ctl_msg.message MG_UD_ARG(nc->user_data));
4127 }
4128 }
4129 }
4130 #endif
4131
4132 /* Associate a socket to a connection. */
mg_socket_if_sock_set(struct mg_connection * nc,sock_t sock)4133 void mg_socket_if_sock_set(struct mg_connection *nc, sock_t sock) {
4134 mg_set_non_blocking_mode(sock);
4135 mg_set_close_on_exec(sock);
4136 nc->sock = sock;
4137 DBG(("%p %d", nc, sock));
4138 }
4139
mg_socket_if_init(struct mg_iface * iface)4140 void mg_socket_if_init(struct mg_iface *iface) {
4141 (void) iface;
4142 DBG(("%p using select()", iface->mgr));
4143 #if MG_ENABLE_BROADCAST
4144 mg_socketpair(iface->mgr->ctl, SOCK_DGRAM);
4145 #endif
4146 }
4147
mg_socket_if_free(struct mg_iface * iface)4148 void mg_socket_if_free(struct mg_iface *iface) {
4149 (void) iface;
4150 }
4151
mg_socket_if_add_conn(struct mg_connection * nc)4152 void mg_socket_if_add_conn(struct mg_connection *nc) {
4153 (void) nc;
4154 }
4155
mg_socket_if_remove_conn(struct mg_connection * nc)4156 void mg_socket_if_remove_conn(struct mg_connection *nc) {
4157 (void) nc;
4158 }
4159
mg_add_to_set(sock_t sock,fd_set * set,sock_t * max_fd)4160 void mg_add_to_set(sock_t sock, fd_set *set, sock_t *max_fd) {
4161 if (sock != INVALID_SOCKET
4162 #ifdef __unix__
4163 && sock < (sock_t) FD_SETSIZE
4164 #endif
4165 ) {
4166 FD_SET(sock, set);
4167 if (*max_fd == INVALID_SOCKET || sock > *max_fd) {
4168 *max_fd = sock;
4169 }
4170 }
4171 }
4172
mg_socket_if_poll(struct mg_iface * iface,int timeout_ms)4173 time_t mg_socket_if_poll(struct mg_iface *iface, int timeout_ms) {
4174 struct mg_mgr *mgr = iface->mgr;
4175 double now = mg_time();
4176 double min_timer;
4177 struct mg_connection *nc, *tmp;
4178 struct timeval tv;
4179 fd_set read_set, write_set, err_set;
4180 sock_t max_fd = INVALID_SOCKET;
4181 int num_fds, num_ev, num_timers = 0;
4182 #ifdef __unix__
4183 int try_dup = 1;
4184 #endif
4185
4186 FD_ZERO(&read_set);
4187 FD_ZERO(&write_set);
4188 FD_ZERO(&err_set);
4189 #if MG_ENABLE_BROADCAST
4190 mg_add_to_set(mgr->ctl[1], &read_set, &max_fd);
4191 #endif
4192
4193 /*
4194 * Note: it is ok to have connections with sock == INVALID_SOCKET in the list,
4195 * e.g. timer-only "connections".
4196 */
4197 min_timer = 0;
4198 for (nc = mgr->active_connections, num_fds = 0; nc != NULL; nc = tmp) {
4199 tmp = nc->next;
4200
4201 if (nc->sock != INVALID_SOCKET) {
4202 num_fds++;
4203
4204 #ifdef __unix__
4205 /* A hack to make sure all our file descriptos fit into FD_SETSIZE. */
4206 if (nc->sock >= (sock_t) FD_SETSIZE && try_dup) {
4207 int new_sock = dup(nc->sock);
4208 if (new_sock >= 0) {
4209 if (new_sock < (sock_t) FD_SETSIZE) {
4210 closesocket(nc->sock);
4211 DBG(("new sock %d -> %d", nc->sock, new_sock));
4212 nc->sock = new_sock;
4213 } else {
4214 closesocket(new_sock);
4215 DBG(("new sock is still larger than FD_SETSIZE, disregard"));
4216 try_dup = 0;
4217 }
4218 } else {
4219 try_dup = 0;
4220 }
4221 }
4222 #endif
4223
4224 if (nc->recv_mbuf.len < nc->recv_mbuf_limit &&
4225 (!(nc->flags & MG_F_UDP) || nc->listener == NULL)) {
4226 mg_add_to_set(nc->sock, &read_set, &max_fd);
4227 }
4228
4229 if (((nc->flags & MG_F_CONNECTING) && !(nc->flags & MG_F_WANT_READ)) ||
4230 (nc->send_mbuf.len > 0 && !(nc->flags & MG_F_CONNECTING))) {
4231 mg_add_to_set(nc->sock, &write_set, &max_fd);
4232 mg_add_to_set(nc->sock, &err_set, &max_fd);
4233 }
4234 }
4235
4236 if (nc->ev_timer_time > 0) {
4237 if (num_timers == 0 || nc->ev_timer_time < min_timer) {
4238 min_timer = nc->ev_timer_time;
4239 }
4240 num_timers++;
4241 }
4242 }
4243
4244 /*
4245 * If there is a timer to be fired earlier than the requested timeout,
4246 * adjust the timeout.
4247 */
4248 if (num_timers > 0) {
4249 double timer_timeout_ms = (min_timer - mg_time()) * 1000 + 1 /* rounding */;
4250 if (timer_timeout_ms < timeout_ms) {
4251 timeout_ms = (int) timer_timeout_ms;
4252 }
4253 }
4254 if (timeout_ms < 0) timeout_ms = 0;
4255
4256 tv.tv_sec = timeout_ms / 1000;
4257 tv.tv_usec = (timeout_ms % 1000) * 1000;
4258
4259 num_ev = select((int) max_fd + 1, &read_set, &write_set, &err_set, &tv);
4260 now = mg_time();
4261 #if 0
4262 DBG(("select @ %ld num_ev=%d of %d, timeout=%d", (long) now, num_ev, num_fds,
4263 timeout_ms));
4264 #endif
4265
4266 #if MG_ENABLE_BROADCAST
4267 if (num_ev > 0 && mgr->ctl[1] != INVALID_SOCKET &&
4268 FD_ISSET(mgr->ctl[1], &read_set)) {
4269 mg_mgr_handle_ctl_sock(mgr);
4270 }
4271 #endif
4272
4273 for (nc = mgr->active_connections; nc != NULL; nc = tmp) {
4274 int fd_flags = 0;
4275 if (nc->sock != INVALID_SOCKET) {
4276 if (num_ev > 0) {
4277 fd_flags = (FD_ISSET(nc->sock, &read_set) &&
4278 (!(nc->flags & MG_F_UDP) || nc->listener == NULL)
4279 ? _MG_F_FD_CAN_READ
4280 : 0) |
4281 (FD_ISSET(nc->sock, &write_set) ? _MG_F_FD_CAN_WRITE : 0) |
4282 (FD_ISSET(nc->sock, &err_set) ? _MG_F_FD_ERROR : 0);
4283 }
4284 #if MG_LWIP
4285 /* With LWIP socket emulation layer, we don't get write events for UDP */
4286 if ((nc->flags & MG_F_UDP) && nc->listener == NULL) {
4287 fd_flags |= _MG_F_FD_CAN_WRITE;
4288 }
4289 #endif
4290 }
4291 tmp = nc->next;
4292 mg_mgr_handle_conn(nc, fd_flags, now);
4293 }
4294
4295 return (time_t) now;
4296 }
4297
4298 #if MG_ENABLE_BROADCAST
mg_socketpair_close(sock_t * sock)4299 MG_INTERNAL void mg_socketpair_close(sock_t *sock) {
4300 while (1) {
4301 if (closesocket(*sock) == -1 && errno == EINTR) continue;
4302 break;
4303 }
4304 *sock = INVALID_SOCKET;
4305 }
4306
4307 MG_INTERNAL sock_t
mg_socketpair_accept(sock_t sock,union socket_address * sa,socklen_t sa_len)4308 mg_socketpair_accept(sock_t sock, union socket_address *sa, socklen_t sa_len) {
4309 sock_t rc;
4310 while (1) {
4311 if ((rc = accept(sock, &sa->sa, &sa_len)) == INVALID_SOCKET &&
4312 errno == EINTR)
4313 continue;
4314 break;
4315 }
4316 return rc;
4317 }
4318
mg_socketpair(sock_t sp[2],int sock_type)4319 int mg_socketpair(sock_t sp[2], int sock_type) {
4320 union socket_address sa, sa2;
4321 sock_t sock;
4322 socklen_t len = sizeof(sa.sin);
4323 int ret = 0;
4324
4325 sock = sp[0] = sp[1] = INVALID_SOCKET;
4326
4327 (void) memset(&sa, 0, sizeof(sa));
4328 sa.sin.sin_family = AF_INET;
4329 sa.sin.sin_addr.s_addr = htonl(0x7f000001); /* 127.0.0.1 */
4330 sa2 = sa;
4331
4332 if ((sock = socket(AF_INET, sock_type, 0)) == INVALID_SOCKET) {
4333 // abort
4334 } else if (bind(sock, &sa.sa, len) != 0) {
4335 // abort
4336 } else if (sock_type == SOCK_STREAM && listen(sock, 1) != 0) {
4337 // abort
4338 } else if (getsockname(sock, &sa.sa, &len) != 0) {
4339 // abort
4340 } else if ((sp[0] = socket(AF_INET, sock_type, 0)) == INVALID_SOCKET) {
4341 // abort
4342 } else if (sock_type == SOCK_STREAM && connect(sp[0], &sa.sa, len) != 0) {
4343 // abort
4344 } else if (sock_type == SOCK_DGRAM &&
4345 (bind(sp[0], &sa2.sa, len) != 0 ||
4346 getsockname(sp[0], &sa2.sa, &len) != 0 ||
4347 connect(sp[0], &sa.sa, len) != 0 ||
4348 connect(sock, &sa2.sa, len) != 0)) {
4349 // abort
4350 } else if ((sp[1] = (sock_type == SOCK_DGRAM ? sock : mg_socketpair_accept(
4351 sock, &sa, len))) ==
4352 INVALID_SOCKET) {
4353 // abort
4354 } else {
4355 mg_set_close_on_exec(sp[0]);
4356 mg_set_close_on_exec(sp[1]);
4357 if (sock_type == SOCK_STREAM) mg_socketpair_close(&sock);
4358 ret = 1;
4359 }
4360
4361 if (!ret) {
4362 if (sp[0] != INVALID_SOCKET) mg_socketpair_close(&sp[0]);
4363 if (sp[1] != INVALID_SOCKET) mg_socketpair_close(&sp[1]);
4364 if (sock != INVALID_SOCKET) mg_socketpair_close(&sock);
4365 }
4366
4367 return ret;
4368 }
4369 #endif /* MG_ENABLE_BROADCAST */
4370
mg_sock_get_addr(sock_t sock,int remote,union socket_address * sa)4371 static void mg_sock_get_addr(sock_t sock, int remote,
4372 union socket_address *sa) {
4373 socklen_t slen = sizeof(*sa);
4374 memset(sa, 0, slen);
4375 if (remote) {
4376 getpeername(sock, &sa->sa, &slen);
4377 } else {
4378 getsockname(sock, &sa->sa, &slen);
4379 }
4380 }
4381
mg_sock_to_str(sock_t sock,char * buf,size_t len,int flags)4382 void mg_sock_to_str(sock_t sock, char *buf, size_t len, int flags) {
4383 union socket_address sa;
4384 mg_sock_get_addr(sock, flags & MG_SOCK_STRINGIFY_REMOTE, &sa);
4385 mg_sock_addr_to_str(&sa, buf, len, flags);
4386 }
4387
mg_socket_if_get_conn_addr(struct mg_connection * nc,int remote,union socket_address * sa)4388 void mg_socket_if_get_conn_addr(struct mg_connection *nc, int remote,
4389 union socket_address *sa) {
4390 if ((nc->flags & MG_F_UDP) && remote) {
4391 memcpy(sa, &nc->sa, sizeof(*sa));
4392 return;
4393 }
4394 mg_sock_get_addr(nc->sock, remote, sa);
4395 }
4396
4397 /* clang-format off */
4398 #define MG_SOCKET_IFACE_VTABLE \
4399 { \
4400 mg_socket_if_init, \
4401 mg_socket_if_free, \
4402 mg_socket_if_add_conn, \
4403 mg_socket_if_remove_conn, \
4404 mg_socket_if_poll, \
4405 mg_socket_if_listen_tcp, \
4406 mg_socket_if_listen_udp, \
4407 mg_socket_if_connect_tcp, \
4408 mg_socket_if_connect_udp, \
4409 mg_socket_if_tcp_send, \
4410 mg_socket_if_udp_send, \
4411 mg_socket_if_tcp_recv, \
4412 mg_socket_if_udp_recv, \
4413 mg_socket_if_create_conn, \
4414 mg_socket_if_destroy_conn, \
4415 mg_socket_if_sock_set, \
4416 mg_socket_if_get_conn_addr, \
4417 }
4418 /* clang-format on */
4419
4420 const struct mg_iface_vtable mg_socket_iface_vtable = MG_SOCKET_IFACE_VTABLE;
4421 #if MG_NET_IF == MG_NET_IF_SOCKET
4422 const struct mg_iface_vtable mg_default_iface_vtable = MG_SOCKET_IFACE_VTABLE;
4423 #endif
4424
4425 #endif /* MG_ENABLE_NET_IF_SOCKET */
4426 #ifdef MG_MODULE_LINES
4427 #line 1 "mongoose/src/mg_net_if_socks.c"
4428 #endif
4429 /*
4430 * Copyright (c) 2014-2016 Cesanta Software Limited
4431 * All rights reserved
4432 */
4433
4434 #if MG_ENABLE_SOCKS
4435
4436 struct socksdata {
4437 char *proxy_addr; /* HOST:PORT of the socks5 proxy server */
4438 struct mg_connection *s; /* Respective connection to the server */
4439 struct mg_connection *c; /* Connection to the client */
4440 };
4441
socks_if_disband(struct socksdata * d)4442 static void socks_if_disband(struct socksdata *d) {
4443 LOG(LL_DEBUG, ("disbanding proxy %p %p", d->c, d->s));
4444 if (d->c) {
4445 d->c->flags |= MG_F_SEND_AND_CLOSE;
4446 d->c->user_data = NULL;
4447 d->c = NULL;
4448 }
4449 if (d->s) {
4450 d->s->flags |= MG_F_SEND_AND_CLOSE;
4451 d->s->user_data = NULL;
4452 d->s = NULL;
4453 }
4454 }
4455
socks_if_relay(struct mg_connection * s)4456 static void socks_if_relay(struct mg_connection *s) {
4457 struct socksdata *d = (struct socksdata *) s->user_data;
4458 if (d == NULL || d->c == NULL || !(s->flags & MG_SOCKS_CONNECT_DONE) ||
4459 d->s == NULL) {
4460 return;
4461 }
4462 if (s->recv_mbuf.len > 0) mg_if_can_recv_cb(d->c);
4463 if (d->c->send_mbuf.len > 0 && s->send_mbuf.len == 0) mg_if_can_send_cb(d->c);
4464 }
4465
socks_if_handler(struct mg_connection * c,int ev,void * ev_data)4466 static void socks_if_handler(struct mg_connection *c, int ev, void *ev_data) {
4467 struct socksdata *d = (struct socksdata *) c->user_data;
4468 if (d == NULL) return;
4469 if (ev == MG_EV_CONNECT) {
4470 int res = *(int *) ev_data;
4471 if (res == 0) {
4472 /* Send handshake to the proxy server */
4473 unsigned char buf[] = {MG_SOCKS_VERSION, 1, MG_SOCKS_HANDSHAKE_NOAUTH};
4474 mg_send(d->s, buf, sizeof(buf));
4475 LOG(LL_DEBUG, ("Sent handshake to %s", d->proxy_addr));
4476 } else {
4477 LOG(LL_ERROR, ("Cannot connect to %s: %d", d->proxy_addr, res));
4478 d->c->flags |= MG_F_CLOSE_IMMEDIATELY;
4479 }
4480 } else if (ev == MG_EV_CLOSE) {
4481 socks_if_disband(d);
4482 } else if (ev == MG_EV_RECV) {
4483 /* Handle handshake reply */
4484 if (!(c->flags & MG_SOCKS_HANDSHAKE_DONE)) {
4485 /* TODO(lsm): process IPv6 too */
4486 unsigned char buf[10] = {MG_SOCKS_VERSION, MG_SOCKS_CMD_CONNECT, 0,
4487 MG_SOCKS_ADDR_IPV4};
4488 if (c->recv_mbuf.len < 2) return;
4489 if ((unsigned char) c->recv_mbuf.buf[1] == MG_SOCKS_HANDSHAKE_FAILURE) {
4490 LOG(LL_ERROR, ("Server kicked us out"));
4491 socks_if_disband(d);
4492 return;
4493 }
4494 mbuf_remove(&c->recv_mbuf, 2);
4495 c->flags |= MG_SOCKS_HANDSHAKE_DONE;
4496
4497 /* Send connect request */
4498 memcpy(buf + 4, &d->c->sa.sin.sin_addr, 4);
4499 memcpy(buf + 8, &d->c->sa.sin.sin_port, 2);
4500 mg_send(c, buf, sizeof(buf));
4501 LOG(LL_DEBUG, ("%p Sent connect request", c));
4502 }
4503 /* Process connect request */
4504 if ((c->flags & MG_SOCKS_HANDSHAKE_DONE) &&
4505 !(c->flags & MG_SOCKS_CONNECT_DONE)) {
4506 if (c->recv_mbuf.len < 10) return;
4507 if (c->recv_mbuf.buf[1] != MG_SOCKS_SUCCESS) {
4508 LOG(LL_ERROR, ("Socks connection error: %d", c->recv_mbuf.buf[1]));
4509 socks_if_disband(d);
4510 return;
4511 }
4512 mbuf_remove(&c->recv_mbuf, 10);
4513 c->flags |= MG_SOCKS_CONNECT_DONE;
4514 LOG(LL_DEBUG, ("%p Connect done %p", c, d->c));
4515 mg_if_connect_cb(d->c, 0);
4516 }
4517 socks_if_relay(c);
4518 } else if (ev == MG_EV_SEND || ev == MG_EV_POLL) {
4519 socks_if_relay(c);
4520 }
4521 }
4522
mg_socks_if_connect_tcp(struct mg_connection * c,const union socket_address * sa)4523 static void mg_socks_if_connect_tcp(struct mg_connection *c,
4524 const union socket_address *sa) {
4525 struct socksdata *d = (struct socksdata *) c->iface->data;
4526 d->c = c;
4527 d->s = mg_connect(c->mgr, d->proxy_addr, socks_if_handler);
4528 d->s->user_data = d;
4529 LOG(LL_DEBUG, ("%p %s %p %p", c, d->proxy_addr, d, d->s));
4530 (void) sa;
4531 }
4532
mg_socks_if_connect_udp(struct mg_connection * c)4533 static void mg_socks_if_connect_udp(struct mg_connection *c) {
4534 (void) c;
4535 }
4536
mg_socks_if_listen_tcp(struct mg_connection * c,union socket_address * sa)4537 static int mg_socks_if_listen_tcp(struct mg_connection *c,
4538 union socket_address *sa) {
4539 (void) c;
4540 (void) sa;
4541 return 0;
4542 }
4543
mg_socks_if_listen_udp(struct mg_connection * c,union socket_address * sa)4544 static int mg_socks_if_listen_udp(struct mg_connection *c,
4545 union socket_address *sa) {
4546 (void) c;
4547 (void) sa;
4548 return -1;
4549 }
4550
mg_socks_if_tcp_send(struct mg_connection * c,const void * buf,size_t len)4551 static int mg_socks_if_tcp_send(struct mg_connection *c, const void *buf,
4552 size_t len) {
4553 int res;
4554 struct socksdata *d = (struct socksdata *) c->iface->data;
4555 if (d->s == NULL) return -1;
4556 res = (int) mbuf_append(&d->s->send_mbuf, buf, len);
4557 DBG(("%p -> %d -> %p", c, res, d->s));
4558 return res;
4559 }
4560
mg_socks_if_udp_send(struct mg_connection * c,const void * buf,size_t len)4561 static int mg_socks_if_udp_send(struct mg_connection *c, const void *buf,
4562 size_t len) {
4563 (void) c;
4564 (void) buf;
4565 (void) len;
4566 return -1;
4567 }
4568
mg_socks_if_tcp_recv(struct mg_connection * c,void * buf,size_t len)4569 int mg_socks_if_tcp_recv(struct mg_connection *c, void *buf, size_t len) {
4570 struct socksdata *d = (struct socksdata *) c->iface->data;
4571 if (d->s == NULL) return -1;
4572 if (len > d->s->recv_mbuf.len) len = d->s->recv_mbuf.len;
4573 if (len > 0) {
4574 memcpy(buf, d->s->recv_mbuf.buf, len);
4575 mbuf_remove(&d->s->recv_mbuf, len);
4576 }
4577 DBG(("%p <- %d <- %p", c, (int) len, d->s));
4578 return len;
4579 }
4580
mg_socks_if_udp_recv(struct mg_connection * c,void * buf,size_t len,union socket_address * sa,size_t * sa_len)4581 int mg_socks_if_udp_recv(struct mg_connection *c, void *buf, size_t len,
4582 union socket_address *sa, size_t *sa_len) {
4583 (void) c;
4584 (void) buf;
4585 (void) len;
4586 (void) sa;
4587 (void) sa_len;
4588 return -1;
4589 }
4590
mg_socks_if_create_conn(struct mg_connection * c)4591 static int mg_socks_if_create_conn(struct mg_connection *c) {
4592 (void) c;
4593 return 1;
4594 }
4595
mg_socks_if_destroy_conn(struct mg_connection * c)4596 static void mg_socks_if_destroy_conn(struct mg_connection *c) {
4597 c->iface->vtable->_free(c->iface);
4598 MG_FREE(c->iface);
4599 c->iface = NULL;
4600 LOG(LL_DEBUG, ("%p", c));
4601 }
4602
mg_socks_if_sock_set(struct mg_connection * c,sock_t sock)4603 static void mg_socks_if_sock_set(struct mg_connection *c, sock_t sock) {
4604 (void) c;
4605 (void) sock;
4606 }
4607
mg_socks_if_init(struct mg_iface * iface)4608 static void mg_socks_if_init(struct mg_iface *iface) {
4609 (void) iface;
4610 }
4611
mg_socks_if_free(struct mg_iface * iface)4612 static void mg_socks_if_free(struct mg_iface *iface) {
4613 struct socksdata *d = (struct socksdata *) iface->data;
4614 LOG(LL_DEBUG, ("%p", iface));
4615 if (d != NULL) {
4616 socks_if_disband(d);
4617 MG_FREE(d->proxy_addr);
4618 MG_FREE(d);
4619 iface->data = NULL;
4620 }
4621 }
4622
mg_socks_if_add_conn(struct mg_connection * c)4623 static void mg_socks_if_add_conn(struct mg_connection *c) {
4624 c->sock = INVALID_SOCKET;
4625 }
4626
mg_socks_if_remove_conn(struct mg_connection * c)4627 static void mg_socks_if_remove_conn(struct mg_connection *c) {
4628 (void) c;
4629 }
4630
mg_socks_if_poll(struct mg_iface * iface,int timeout_ms)4631 static time_t mg_socks_if_poll(struct mg_iface *iface, int timeout_ms) {
4632 LOG(LL_DEBUG, ("%p", iface));
4633 (void) iface;
4634 (void) timeout_ms;
4635 return (time_t) cs_time();
4636 }
4637
mg_socks_if_get_conn_addr(struct mg_connection * c,int remote,union socket_address * sa)4638 static void mg_socks_if_get_conn_addr(struct mg_connection *c, int remote,
4639 union socket_address *sa) {
4640 LOG(LL_DEBUG, ("%p", c));
4641 (void) c;
4642 (void) remote;
4643 (void) sa;
4644 }
4645
4646 const struct mg_iface_vtable mg_socks_iface_vtable = {
4647 mg_socks_if_init, mg_socks_if_free,
4648 mg_socks_if_add_conn, mg_socks_if_remove_conn,
4649 mg_socks_if_poll, mg_socks_if_listen_tcp,
4650 mg_socks_if_listen_udp, mg_socks_if_connect_tcp,
4651 mg_socks_if_connect_udp, mg_socks_if_tcp_send,
4652 mg_socks_if_udp_send, mg_socks_if_tcp_recv,
4653 mg_socks_if_udp_recv, mg_socks_if_create_conn,
4654 mg_socks_if_destroy_conn, mg_socks_if_sock_set,
4655 mg_socks_if_get_conn_addr,
4656 };
4657
mg_socks_mk_iface(struct mg_mgr * mgr,const char * proxy_addr)4658 struct mg_iface *mg_socks_mk_iface(struct mg_mgr *mgr, const char *proxy_addr) {
4659 struct mg_iface *iface = mg_if_create_iface(&mg_socks_iface_vtable, mgr);
4660 iface->data = MG_CALLOC(1, sizeof(struct socksdata));
4661 ((struct socksdata *) iface->data)->proxy_addr = strdup(proxy_addr);
4662 return iface;
4663 }
4664
4665 #endif
4666 #ifdef MG_MODULE_LINES
4667 #line 1 "mongoose/src/mg_ssl_if_openssl.c"
4668 #endif
4669 /*
4670 * Copyright (c) 2014-2016 Cesanta Software Limited
4671 * All rights reserved
4672 */
4673
4674 #if MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_OPENSSL
4675
4676 #ifdef __APPLE__
4677 #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
4678 #endif
4679
4680 #include <openssl/ssl.h>
4681 #ifndef KR_VERSION
4682 #include <openssl/tls1.h>
4683 #endif
4684
4685 struct mg_ssl_if_ctx {
4686 SSL *ssl;
4687 SSL_CTX *ssl_ctx;
4688 struct mbuf psk;
4689 size_t identity_len;
4690 };
4691
mg_ssl_if_init()4692 void mg_ssl_if_init() {
4693 SSL_library_init();
4694 }
4695
mg_ssl_if_conn_accept(struct mg_connection * nc,struct mg_connection * lc)4696 enum mg_ssl_if_result mg_ssl_if_conn_accept(struct mg_connection *nc,
4697 struct mg_connection *lc) {
4698 struct mg_ssl_if_ctx *ctx =
4699 (struct mg_ssl_if_ctx *) MG_CALLOC(1, sizeof(*ctx));
4700 struct mg_ssl_if_ctx *lc_ctx = (struct mg_ssl_if_ctx *) lc->ssl_if_data;
4701 nc->ssl_if_data = ctx;
4702 if (ctx == NULL || lc_ctx == NULL) return MG_SSL_ERROR;
4703 ctx->ssl_ctx = lc_ctx->ssl_ctx;
4704 if ((ctx->ssl = SSL_new(ctx->ssl_ctx)) == NULL) {
4705 return MG_SSL_ERROR;
4706 }
4707 return MG_SSL_OK;
4708 }
4709
4710 static enum mg_ssl_if_result mg_use_cert(SSL_CTX *ctx, const char *cert,
4711 const char *key, const char **err_msg);
4712 static enum mg_ssl_if_result mg_use_ca_cert(SSL_CTX *ctx, const char *cert);
4713 static enum mg_ssl_if_result mg_set_cipher_list(SSL_CTX *ctx, const char *cl);
4714 static enum mg_ssl_if_result mg_ssl_if_ossl_set_psk(struct mg_ssl_if_ctx *ctx,
4715 const char *identity,
4716 const char *key_str);
4717
mg_ssl_if_conn_init(struct mg_connection * nc,const struct mg_ssl_if_conn_params * params,const char ** err_msg)4718 enum mg_ssl_if_result mg_ssl_if_conn_init(
4719 struct mg_connection *nc, const struct mg_ssl_if_conn_params *params,
4720 const char **err_msg) {
4721 struct mg_ssl_if_ctx *ctx =
4722 (struct mg_ssl_if_ctx *) MG_CALLOC(1, sizeof(*ctx));
4723 DBG(("%p %s,%s,%s", nc, (params->cert ? params->cert : ""),
4724 (params->key ? params->key : ""),
4725 (params->ca_cert ? params->ca_cert : "")));
4726 if (ctx == NULL) {
4727 MG_SET_PTRPTR(err_msg, "Out of memory");
4728 return MG_SSL_ERROR;
4729 }
4730 nc->ssl_if_data = ctx;
4731 if (nc->flags & MG_F_LISTENING) {
4732 ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method());
4733 } else {
4734 ctx->ssl_ctx = SSL_CTX_new(SSLv23_client_method());
4735 }
4736 if (ctx->ssl_ctx == NULL) {
4737 MG_SET_PTRPTR(err_msg, "Failed to create SSL context");
4738 return MG_SSL_ERROR;
4739 }
4740
4741 #ifndef KR_VERSION
4742 /* Disable deprecated protocols. */
4743 SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_NO_SSLv2);
4744 SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_NO_SSLv3);
4745 SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_NO_TLSv1);
4746 #ifdef MG_SSL_OPENSSL_NO_COMPRESSION
4747 SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
4748 #endif
4749 #ifdef MG_SSL_OPENSSL_CIPHER_SERVER_PREFERENCE
4750 SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
4751 #endif
4752 #else
4753 /* Krypton only supports TLSv1.2 anyway. */
4754 #endif
4755
4756 if (params->cert != NULL &&
4757 mg_use_cert(ctx->ssl_ctx, params->cert, params->key, err_msg) !=
4758 MG_SSL_OK) {
4759 return MG_SSL_ERROR;
4760 }
4761
4762 if (params->ca_cert != NULL &&
4763 mg_use_ca_cert(ctx->ssl_ctx, params->ca_cert) != MG_SSL_OK) {
4764 MG_SET_PTRPTR(err_msg, "Invalid SSL CA cert");
4765 return MG_SSL_ERROR;
4766 }
4767
4768 if (mg_set_cipher_list(ctx->ssl_ctx, params->cipher_suites) != MG_SSL_OK) {
4769 MG_SET_PTRPTR(err_msg, "Invalid cipher suite list");
4770 return MG_SSL_ERROR;
4771 }
4772
4773 mbuf_init(&ctx->psk, 0);
4774 if (mg_ssl_if_ossl_set_psk(ctx, params->psk_identity, params->psk_key) !=
4775 MG_SSL_OK) {
4776 MG_SET_PTRPTR(err_msg, "Invalid PSK settings");
4777 return MG_SSL_ERROR;
4778 }
4779
4780 if (!(nc->flags & MG_F_LISTENING) &&
4781 (ctx->ssl = SSL_new(ctx->ssl_ctx)) == NULL) {
4782 MG_SET_PTRPTR(err_msg, "Failed to create SSL session");
4783 return MG_SSL_ERROR;
4784 }
4785
4786 if (params->server_name != NULL) {
4787 #ifdef KR_VERSION
4788 SSL_CTX_kr_set_verify_name(ctx->ssl_ctx, params->server_name);
4789 #else
4790 SSL_set_tlsext_host_name(ctx->ssl, params->server_name);
4791 #endif
4792 }
4793
4794 nc->flags |= MG_F_SSL;
4795
4796 return MG_SSL_OK;
4797 }
4798
mg_ssl_if_ssl_err(struct mg_connection * nc,int res)4799 static enum mg_ssl_if_result mg_ssl_if_ssl_err(struct mg_connection *nc,
4800 int res) {
4801 struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
4802 int err = SSL_get_error(ctx->ssl, res);
4803 if (err == SSL_ERROR_WANT_READ) return MG_SSL_WANT_READ;
4804 if (err == SSL_ERROR_WANT_WRITE) return MG_SSL_WANT_WRITE;
4805 DBG(("%p %p SSL error: %d %d", nc, ctx->ssl_ctx, res, err));
4806 nc->err = err;
4807 return MG_SSL_ERROR;
4808 }
4809
mg_ssl_if_handshake(struct mg_connection * nc)4810 enum mg_ssl_if_result mg_ssl_if_handshake(struct mg_connection *nc) {
4811 struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
4812 int server_side = (nc->listener != NULL);
4813 int res;
4814 /* If descriptor is not yet set, do it now. */
4815 if (SSL_get_fd(ctx->ssl) < 0) {
4816 if (SSL_set_fd(ctx->ssl, nc->sock) != 1) return MG_SSL_ERROR;
4817 }
4818 res = server_side ? SSL_accept(ctx->ssl) : SSL_connect(ctx->ssl);
4819 if (res != 1) return mg_ssl_if_ssl_err(nc, res);
4820 return MG_SSL_OK;
4821 }
4822
mg_ssl_if_read(struct mg_connection * nc,void * buf,size_t buf_size)4823 int mg_ssl_if_read(struct mg_connection *nc, void *buf, size_t buf_size) {
4824 struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
4825 int n = SSL_read(ctx->ssl, buf, buf_size);
4826 DBG(("%p %d -> %d", nc, (int) buf_size, n));
4827 if (n < 0) return mg_ssl_if_ssl_err(nc, n);
4828 if (n == 0) nc->flags |= MG_F_CLOSE_IMMEDIATELY;
4829 return n;
4830 }
4831
mg_ssl_if_write(struct mg_connection * nc,const void * data,size_t len)4832 int mg_ssl_if_write(struct mg_connection *nc, const void *data, size_t len) {
4833 struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
4834 int n = SSL_write(ctx->ssl, data, len);
4835 DBG(("%p %d -> %d", nc, (int) len, n));
4836 if (n <= 0) return mg_ssl_if_ssl_err(nc, n);
4837 return n;
4838 }
4839
mg_ssl_if_conn_close_notify(struct mg_connection * nc)4840 void mg_ssl_if_conn_close_notify(struct mg_connection *nc) {
4841 struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
4842 if (ctx == NULL) return;
4843 SSL_shutdown(ctx->ssl);
4844 }
4845
mg_ssl_if_conn_free(struct mg_connection * nc)4846 void mg_ssl_if_conn_free(struct mg_connection *nc) {
4847 struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
4848 if (ctx == NULL) return;
4849 nc->ssl_if_data = NULL;
4850 if (ctx->ssl != NULL) SSL_free(ctx->ssl);
4851 if (ctx->ssl_ctx != NULL && nc->listener == NULL) SSL_CTX_free(ctx->ssl_ctx);
4852 mbuf_free(&ctx->psk);
4853 memset(ctx, 0, sizeof(*ctx));
4854 MG_FREE(ctx);
4855 }
4856
4857 /*
4858 * Cipher suite options used for TLS negotiation.
4859 * https://wiki.mozilla.org/Security/Server_Side_TLS#Recommended_configurations
4860 */
4861 static const char mg_s_cipher_list[] =
4862 #if defined(MG_SSL_CRYPTO_MODERN)
4863 "ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:"
4864 "ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:"
4865 "DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:"
4866 "ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:"
4867 "ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:"
4868 "ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:"
4869 "DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:"
4870 "DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:"
4871 "!aNULL:!eNULL:!EXPORT:!DES:!RC4:!3DES:!MD5:!PSK"
4872 #elif defined(MG_SSL_CRYPTO_OLD)
4873 "ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:"
4874 "ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:"
4875 "DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:"
4876 "ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:"
4877 "ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:"
4878 "ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:"
4879 "DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:"
4880 "DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:ECDHE-RSA-DES-CBC3-SHA:"
4881 "ECDHE-ECDSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:"
4882 "AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:DES-CBC3-SHA:"
4883 "HIGH:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:"
4884 "!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA"
4885 #else /* Default - intermediate. */
4886 "ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:"
4887 "ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:"
4888 "DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:"
4889 "ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:"
4890 "ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:"
4891 "ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:"
4892 "DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:"
4893 "DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:"
4894 "AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:CAMELLIA:"
4895 "DES-CBC3-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:"
4896 "!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA"
4897 #endif
4898 ;
4899
4900 /*
4901 * Default DH params for PFS cipher negotiation. This is a 2048-bit group.
4902 * Will be used if none are provided by the user in the certificate file.
4903 */
4904 #if !MG_DISABLE_PFS && !defined(KR_VERSION)
4905 static const char mg_s_default_dh_params[] =
4906 "\
4907 -----BEGIN DH PARAMETERS-----\n\
4908 MIIBCAKCAQEAlvbgD/qh9znWIlGFcV0zdltD7rq8FeShIqIhkQ0C7hYFThrBvF2E\n\
4909 Z9bmgaP+sfQwGpVlv9mtaWjvERbu6mEG7JTkgmVUJrUt/wiRzwTaCXBqZkdUO8Tq\n\
4910 +E6VOEQAilstG90ikN1Tfo+K6+X68XkRUIlgawBTKuvKVwBhuvlqTGerOtnXWnrt\n\
4911 ym//hd3cd5PBYGBix0i7oR4xdghvfR2WLVu0LgdThTBb6XP7gLd19cQ1JuBtAajZ\n\
4912 wMuPn7qlUkEFDIkAZy59/Hue/H2Q2vU/JsvVhHWCQBL4F1ofEAt50il6ZxR1QfFK\n\
4913 9VGKDC4oOgm9DlxwwBoC2FjqmvQlqVV3kwIBAg==\n\
4914 -----END DH PARAMETERS-----\n";
4915 #endif
4916
mg_use_ca_cert(SSL_CTX * ctx,const char * cert)4917 static enum mg_ssl_if_result mg_use_ca_cert(SSL_CTX *ctx, const char *cert) {
4918 if (cert == NULL || strcmp(cert, "*") == 0) {
4919 return MG_SSL_OK;
4920 }
4921 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, 0);
4922 return SSL_CTX_load_verify_locations(ctx, cert, NULL) == 1 ? MG_SSL_OK
4923 : MG_SSL_ERROR;
4924 }
4925
mg_use_cert(SSL_CTX * ctx,const char * cert,const char * key,const char ** err_msg)4926 static enum mg_ssl_if_result mg_use_cert(SSL_CTX *ctx, const char *cert,
4927 const char *key,
4928 const char **err_msg) {
4929 if (key == NULL) key = cert;
4930 if (cert == NULL || cert[0] == '\0' || key == NULL || key[0] == '\0') {
4931 return MG_SSL_OK;
4932 } else if (SSL_CTX_use_certificate_file(ctx, cert, 1) == 0) {
4933 MG_SET_PTRPTR(err_msg, "Invalid SSL cert");
4934 return MG_SSL_ERROR;
4935 } else if (SSL_CTX_use_PrivateKey_file(ctx, key, 1) == 0) {
4936 MG_SET_PTRPTR(err_msg, "Invalid SSL key");
4937 return MG_SSL_ERROR;
4938 } else if (SSL_CTX_use_certificate_chain_file(ctx, cert) == 0) {
4939 MG_SET_PTRPTR(err_msg, "Invalid CA bundle");
4940 return MG_SSL_ERROR;
4941 } else {
4942 SSL_CTX_set_mode(ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
4943 #if !MG_DISABLE_PFS && !defined(KR_VERSION)
4944 BIO *bio = NULL;
4945 DH *dh = NULL;
4946
4947 /* Try to read DH parameters from the cert/key file. */
4948 bio = BIO_new_file(cert, "r");
4949 if (bio != NULL) {
4950 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
4951 BIO_free(bio);
4952 }
4953 /*
4954 * If there are no DH params in the file, fall back to hard-coded ones.
4955 * Not ideal, but better than nothing.
4956 */
4957 if (dh == NULL) {
4958 bio = BIO_new_mem_buf((void *) mg_s_default_dh_params, -1);
4959 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
4960 BIO_free(bio);
4961 }
4962 if (dh != NULL) {
4963 SSL_CTX_set_tmp_dh(ctx, dh);
4964 SSL_CTX_set_options(ctx, SSL_OP_SINGLE_DH_USE);
4965 DH_free(dh);
4966 }
4967 #if OPENSSL_VERSION_NUMBER > 0x10002000L
4968 (void) SSL_CTX_set_ecdh_auto(ctx, 1);
4969 #endif
4970 #endif
4971 }
4972 return MG_SSL_OK;
4973 }
4974
mg_set_cipher_list(SSL_CTX * ctx,const char * cl)4975 static enum mg_ssl_if_result mg_set_cipher_list(SSL_CTX *ctx, const char *cl) {
4976 return (SSL_CTX_set_cipher_list(ctx, cl ? cl : mg_s_cipher_list) == 1
4977 ? MG_SSL_OK
4978 : MG_SSL_ERROR);
4979 }
4980
4981 #if !defined(KR_VERSION) && !defined(LIBRESSL_VERSION_NUMBER)
mg_ssl_if_ossl_psk_cb(SSL * ssl,const char * hint,char * identity,unsigned int max_identity_len,unsigned char * psk,unsigned int max_psk_len)4982 static unsigned int mg_ssl_if_ossl_psk_cb(SSL *ssl, const char *hint,
4983 char *identity,
4984 unsigned int max_identity_len,
4985 unsigned char *psk,
4986 unsigned int max_psk_len) {
4987 struct mg_ssl_if_ctx *ctx =
4988 (struct mg_ssl_if_ctx *) SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl));
4989 size_t key_len = ctx->psk.len - ctx->identity_len - 1;
4990 DBG(("hint: '%s'", (hint ? hint : "")));
4991 if (ctx->identity_len + 1 > max_identity_len) {
4992 DBG(("identity too long"));
4993 return 0;
4994 }
4995 if (key_len > max_psk_len) {
4996 DBG(("key too long"));
4997 return 0;
4998 }
4999 memcpy(identity, ctx->psk.buf, ctx->identity_len + 1);
5000 memcpy(psk, ctx->psk.buf + ctx->identity_len + 1, key_len);
5001 (void) ssl;
5002 return key_len;
5003 }
5004
mg_ssl_if_ossl_set_psk(struct mg_ssl_if_ctx * ctx,const char * identity,const char * key_str)5005 static enum mg_ssl_if_result mg_ssl_if_ossl_set_psk(struct mg_ssl_if_ctx *ctx,
5006 const char *identity,
5007 const char *key_str) {
5008 unsigned char key[32];
5009 size_t key_len;
5010 size_t i = 0;
5011 if (identity == NULL && key_str == NULL) return MG_SSL_OK;
5012 if (identity == NULL || key_str == NULL) return MG_SSL_ERROR;
5013 key_len = strlen(key_str);
5014 if (key_len != 32 && key_len != 64) return MG_SSL_ERROR;
5015 memset(key, 0, sizeof(key));
5016 key_len = 0;
5017 for (i = 0; key_str[i] != '\0'; i++) {
5018 unsigned char c;
5019 char hc = tolower((int) key_str[i]);
5020 if (hc >= '0' && hc <= '9') {
5021 c = hc - '0';
5022 } else if (hc >= 'a' && hc <= 'f') {
5023 c = hc - 'a' + 0xa;
5024 } else {
5025 return MG_SSL_ERROR;
5026 }
5027 key_len = i / 2;
5028 key[key_len] <<= 4;
5029 key[key_len] |= c;
5030 }
5031 key_len++;
5032 DBG(("identity = '%s', key = (%u)", identity, (unsigned int) key_len));
5033 ctx->identity_len = strlen(identity);
5034 mbuf_append(&ctx->psk, identity, ctx->identity_len + 1);
5035 mbuf_append(&ctx->psk, key, key_len);
5036 SSL_CTX_set_psk_client_callback(ctx->ssl_ctx, mg_ssl_if_ossl_psk_cb);
5037 SSL_CTX_set_app_data(ctx->ssl_ctx, ctx);
5038 return MG_SSL_OK;
5039 }
5040 #else
mg_ssl_if_ossl_set_psk(struct mg_ssl_if_ctx * ctx,const char * identity,const char * key_str)5041 static enum mg_ssl_if_result mg_ssl_if_ossl_set_psk(struct mg_ssl_if_ctx *ctx,
5042 const char *identity,
5043 const char *key_str) {
5044 (void) ctx;
5045 (void) identity;
5046 (void) key_str;
5047 /* Krypton / LibreSSL does not support PSK. */
5048 return MG_SSL_ERROR;
5049 }
5050 #endif /* !defined(KR_VERSION) && !defined(LIBRESSL_VERSION_NUMBER) */
5051
mg_set_ssl(struct mg_connection * nc,const char * cert,const char * ca_cert)5052 const char *mg_set_ssl(struct mg_connection *nc, const char *cert,
5053 const char *ca_cert) {
5054 const char *err_msg = NULL;
5055 struct mg_ssl_if_conn_params params;
5056 memset(¶ms, 0, sizeof(params));
5057 params.cert = cert;
5058 params.ca_cert = ca_cert;
5059 if (mg_ssl_if_conn_init(nc, ¶ms, &err_msg) != MG_SSL_OK) {
5060 return err_msg;
5061 }
5062 return NULL;
5063 }
5064
5065 #endif /* MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_OPENSSL */
5066 #ifdef MG_MODULE_LINES
5067 #line 1 "mongoose/src/mg_ssl_if_mbedtls.c"
5068 #endif
5069 /*
5070 * Copyright (c) 2014-2016 Cesanta Software Limited
5071 * All rights reserved
5072 */
5073
5074 #if MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_MBEDTLS
5075
5076 #include <mbedtls/debug.h>
5077 #include <mbedtls/ecp.h>
5078 #include <mbedtls/net.h>
5079 #include <mbedtls/platform.h>
5080 #include <mbedtls/ssl.h>
5081 #include <mbedtls/ssl_internal.h>
5082 #include <mbedtls/x509_crt.h>
5083 #include <mbedtls/version.h>
5084
mg_ssl_mbed_log(void * ctx,int level,const char * file,int line,const char * str)5085 static void mg_ssl_mbed_log(void *ctx, int level, const char *file, int line,
5086 const char *str) {
5087 enum cs_log_level cs_level;
5088 switch (level) {
5089 case 1:
5090 cs_level = LL_ERROR;
5091 break;
5092 case 2:
5093 cs_level = LL_INFO;
5094 break;
5095 case 3:
5096 cs_level = LL_DEBUG;
5097 break;
5098 default:
5099 cs_level = LL_VERBOSE_DEBUG;
5100 }
5101 /* mbedTLS passes strings with \n at the end, strip it. */
5102 LOG(cs_level, ("%p %.*s", ctx, (int) (strlen(str) - 1), str));
5103 (void) ctx;
5104 (void) str;
5105 (void) file;
5106 (void) line;
5107 (void) cs_level;
5108 }
5109
5110 struct mg_ssl_if_ctx {
5111 mbedtls_ssl_config *conf;
5112 mbedtls_ssl_context *ssl;
5113 mbedtls_x509_crt *cert;
5114 mbedtls_pk_context *key;
5115 mbedtls_x509_crt *ca_cert;
5116 struct mbuf cipher_suites;
5117 size_t saved_len;
5118 };
5119
5120 /* Must be provided by the platform. ctx is struct mg_connection. */
5121 extern int mg_ssl_if_mbed_random(void *ctx, unsigned char *buf, size_t len);
5122
mg_ssl_if_init()5123 void mg_ssl_if_init() {
5124 LOG(LL_INFO, ("%s", MBEDTLS_VERSION_STRING_FULL));
5125 }
5126
mg_ssl_if_conn_accept(struct mg_connection * nc,struct mg_connection * lc)5127 enum mg_ssl_if_result mg_ssl_if_conn_accept(struct mg_connection *nc,
5128 struct mg_connection *lc) {
5129 struct mg_ssl_if_ctx *ctx =
5130 (struct mg_ssl_if_ctx *) MG_CALLOC(1, sizeof(*ctx));
5131 struct mg_ssl_if_ctx *lc_ctx = (struct mg_ssl_if_ctx *) lc->ssl_if_data;
5132 nc->ssl_if_data = ctx;
5133 if (ctx == NULL || lc_ctx == NULL) return MG_SSL_ERROR;
5134 ctx->ssl = (mbedtls_ssl_context *) MG_CALLOC(1, sizeof(*ctx->ssl));
5135 if (mbedtls_ssl_setup(ctx->ssl, lc_ctx->conf) != 0) {
5136 return MG_SSL_ERROR;
5137 }
5138 return MG_SSL_OK;
5139 }
5140
5141 static enum mg_ssl_if_result mg_use_cert(struct mg_ssl_if_ctx *ctx,
5142 const char *cert, const char *key,
5143 const char **err_msg);
5144 static enum mg_ssl_if_result mg_use_ca_cert(struct mg_ssl_if_ctx *ctx,
5145 const char *cert);
5146 static enum mg_ssl_if_result mg_set_cipher_list(struct mg_ssl_if_ctx *ctx,
5147 const char *ciphers);
5148 #ifdef MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED
5149 static enum mg_ssl_if_result mg_ssl_if_mbed_set_psk(struct mg_ssl_if_ctx *ctx,
5150 const char *identity,
5151 const char *key);
5152 #endif
5153
mg_ssl_if_conn_init(struct mg_connection * nc,const struct mg_ssl_if_conn_params * params,const char ** err_msg)5154 enum mg_ssl_if_result mg_ssl_if_conn_init(
5155 struct mg_connection *nc, const struct mg_ssl_if_conn_params *params,
5156 const char **err_msg) {
5157 struct mg_ssl_if_ctx *ctx =
5158 (struct mg_ssl_if_ctx *) MG_CALLOC(1, sizeof(*ctx));
5159 DBG(("%p %s,%s,%s", nc, (params->cert ? params->cert : ""),
5160 (params->key ? params->key : ""),
5161 (params->ca_cert ? params->ca_cert : "")));
5162
5163 if (ctx == NULL) {
5164 MG_SET_PTRPTR(err_msg, "Out of memory");
5165 return MG_SSL_ERROR;
5166 }
5167 nc->ssl_if_data = ctx;
5168 ctx->conf = (mbedtls_ssl_config *) MG_CALLOC(1, sizeof(*ctx->conf));
5169 mbuf_init(&ctx->cipher_suites, 0);
5170 mbedtls_ssl_config_init(ctx->conf);
5171 mbedtls_ssl_conf_dbg(ctx->conf, mg_ssl_mbed_log, nc);
5172 if (mbedtls_ssl_config_defaults(
5173 ctx->conf, (nc->flags & MG_F_LISTENING ? MBEDTLS_SSL_IS_SERVER
5174 : MBEDTLS_SSL_IS_CLIENT),
5175 MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_PRESET_DEFAULT) != 0) {
5176 MG_SET_PTRPTR(err_msg, "Failed to init SSL config");
5177 return MG_SSL_ERROR;
5178 }
5179
5180 /* TLS 1.2 and up */
5181 mbedtls_ssl_conf_min_version(ctx->conf, MBEDTLS_SSL_MAJOR_VERSION_3,
5182 MBEDTLS_SSL_MINOR_VERSION_3);
5183 mbedtls_ssl_conf_rng(ctx->conf, mg_ssl_if_mbed_random, nc);
5184
5185 if (params->cert != NULL &&
5186 mg_use_cert(ctx, params->cert, params->key, err_msg) != MG_SSL_OK) {
5187 return MG_SSL_ERROR;
5188 }
5189
5190 if (params->ca_cert != NULL &&
5191 mg_use_ca_cert(ctx, params->ca_cert) != MG_SSL_OK) {
5192 MG_SET_PTRPTR(err_msg, "Invalid SSL CA cert");
5193 return MG_SSL_ERROR;
5194 }
5195
5196 if (mg_set_cipher_list(ctx, params->cipher_suites) != MG_SSL_OK) {
5197 MG_SET_PTRPTR(err_msg, "Invalid cipher suite list");
5198 return MG_SSL_ERROR;
5199 }
5200
5201 #ifdef MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED
5202 if (mg_ssl_if_mbed_set_psk(ctx, params->psk_identity, params->psk_key) !=
5203 MG_SSL_OK) {
5204 MG_SET_PTRPTR(err_msg, "Invalid PSK settings");
5205 return MG_SSL_ERROR;
5206 }
5207 #endif
5208
5209 if (!(nc->flags & MG_F_LISTENING)) {
5210 ctx->ssl = (mbedtls_ssl_context *) MG_CALLOC(1, sizeof(*ctx->ssl));
5211 mbedtls_ssl_init(ctx->ssl);
5212 if (mbedtls_ssl_setup(ctx->ssl, ctx->conf) != 0) {
5213 MG_SET_PTRPTR(err_msg, "Failed to create SSL session");
5214 return MG_SSL_ERROR;
5215 }
5216 if (params->server_name != NULL &&
5217 mbedtls_ssl_set_hostname(ctx->ssl, params->server_name) != 0) {
5218 return MG_SSL_ERROR;
5219 }
5220 }
5221
5222 #ifdef MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN
5223 if (mbedtls_ssl_conf_max_frag_len(ctx->conf,
5224 #if MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN == 512
5225 MBEDTLS_SSL_MAX_FRAG_LEN_512
5226 #elif MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN == 1024
5227 MBEDTLS_SSL_MAX_FRAG_LEN_1024
5228 #elif MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN == 2048
5229 MBEDTLS_SSL_MAX_FRAG_LEN_2048
5230 #elif MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN == 4096
5231 MBEDTLS_SSL_MAX_FRAG_LEN_4096
5232 #else
5233 #error Invalid MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN
5234 #endif
5235 ) != 0) {
5236 return MG_SSL_ERROR;
5237 }
5238 #endif
5239
5240 nc->flags |= MG_F_SSL;
5241
5242 return MG_SSL_OK;
5243 }
5244
mg_ssl_if_mbed_send(void * ctx,const unsigned char * buf,size_t len)5245 static int mg_ssl_if_mbed_send(void *ctx, const unsigned char *buf,
5246 size_t len) {
5247 struct mg_connection *nc = (struct mg_connection *) ctx;
5248 int n = nc->iface->vtable->tcp_send(nc, buf, len);
5249 if (n > 0) return n;
5250 if (n == 0) return MBEDTLS_ERR_SSL_WANT_WRITE;
5251 return MBEDTLS_ERR_NET_SEND_FAILED;
5252 }
5253
mg_ssl_if_mbed_recv(void * ctx,unsigned char * buf,size_t len)5254 static int mg_ssl_if_mbed_recv(void *ctx, unsigned char *buf, size_t len) {
5255 struct mg_connection *nc = (struct mg_connection *) ctx;
5256 int n = nc->iface->vtable->tcp_recv(nc, buf, len);
5257 if (n > 0) return n;
5258 if (n == 0) return MBEDTLS_ERR_SSL_WANT_READ;
5259 return MBEDTLS_ERR_NET_RECV_FAILED;
5260 }
5261
mg_ssl_if_mbed_err(struct mg_connection * nc,int ret)5262 static enum mg_ssl_if_result mg_ssl_if_mbed_err(struct mg_connection *nc,
5263 int ret) {
5264 enum mg_ssl_if_result res = MG_SSL_OK;
5265 if (ret == MBEDTLS_ERR_SSL_WANT_READ) {
5266 res = MG_SSL_WANT_READ;
5267 } else if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) {
5268 res = MG_SSL_WANT_WRITE;
5269 } else if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) {
5270 LOG(LL_DEBUG, ("%p TLS connection closed by peer", nc));
5271 nc->flags |= MG_F_CLOSE_IMMEDIATELY;
5272 res = MG_SSL_OK;
5273 } else {
5274 LOG(LL_ERROR, ("%p mbedTLS error: -0x%04x", nc, -ret));
5275 nc->flags |= MG_F_CLOSE_IMMEDIATELY;
5276 res = MG_SSL_ERROR;
5277 }
5278 nc->err = ret;
5279 return res;
5280 }
5281
mg_ssl_if_mbed_free_certs_and_keys(struct mg_ssl_if_ctx * ctx)5282 static void mg_ssl_if_mbed_free_certs_and_keys(struct mg_ssl_if_ctx *ctx) {
5283 if (ctx->cert != NULL) {
5284 mbedtls_x509_crt_free(ctx->cert);
5285 MG_FREE(ctx->cert);
5286 ctx->cert = NULL;
5287 mbedtls_pk_free(ctx->key);
5288 MG_FREE(ctx->key);
5289 ctx->key = NULL;
5290 }
5291 if (ctx->ca_cert != NULL) {
5292 mbedtls_ssl_conf_ca_chain(ctx->conf, NULL, NULL);
5293 #ifdef MBEDTLS_X509_CA_CHAIN_ON_DISK
5294 if (ctx->conf->ca_chain_file != NULL) {
5295 MG_FREE((void *) ctx->conf->ca_chain_file);
5296 ctx->conf->ca_chain_file = NULL;
5297 }
5298 #endif
5299 mbedtls_x509_crt_free(ctx->ca_cert);
5300 MG_FREE(ctx->ca_cert);
5301 ctx->ca_cert = NULL;
5302 }
5303 }
5304
mg_ssl_if_handshake(struct mg_connection * nc)5305 enum mg_ssl_if_result mg_ssl_if_handshake(struct mg_connection *nc) {
5306 struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
5307 int err;
5308 /* If bio is not yet set, do it now. */
5309 if (ctx->ssl->p_bio == NULL) {
5310 mbedtls_ssl_set_bio(ctx->ssl, nc, mg_ssl_if_mbed_send, mg_ssl_if_mbed_recv,
5311 NULL);
5312 }
5313 err = mbedtls_ssl_handshake(ctx->ssl);
5314 if (err != 0) return mg_ssl_if_mbed_err(nc, err);
5315 #ifdef MG_SSL_IF_MBEDTLS_FREE_CERTS
5316 /*
5317 * Free the peer certificate, we don't need it after handshake.
5318 * Note that this effectively disables renegotiation.
5319 */
5320 mbedtls_x509_crt_free(ctx->ssl->session->peer_cert);
5321 mbedtls_free(ctx->ssl->session->peer_cert);
5322 ctx->ssl->session->peer_cert = NULL;
5323 /* On a client connection we can also free our own and CA certs. */
5324 if (nc->listener == NULL) {
5325 if (ctx->conf->key_cert != NULL) {
5326 /* Note that this assumes one key_cert entry, which matches our init. */
5327 MG_FREE(ctx->conf->key_cert);
5328 ctx->conf->key_cert = NULL;
5329 }
5330 mbedtls_ssl_conf_ca_chain(ctx->conf, NULL, NULL);
5331 mg_ssl_if_mbed_free_certs_and_keys(ctx);
5332 }
5333 #endif
5334 return MG_SSL_OK;
5335 }
5336
mg_ssl_if_read(struct mg_connection * nc,void * buf,size_t len)5337 int mg_ssl_if_read(struct mg_connection *nc, void *buf, size_t len) {
5338 struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
5339 int n = mbedtls_ssl_read(ctx->ssl, (unsigned char *) buf, len);
5340 DBG(("%p %d -> %d", nc, (int) len, n));
5341 if (n < 0) return mg_ssl_if_mbed_err(nc, n);
5342 if (n == 0) nc->flags |= MG_F_CLOSE_IMMEDIATELY;
5343 return n;
5344 }
5345
mg_ssl_if_write(struct mg_connection * nc,const void * buf,size_t len)5346 int mg_ssl_if_write(struct mg_connection *nc, const void *buf, size_t len) {
5347 struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
5348 /* Per mbedTLS docs, if write returns WANT_READ or WANT_WRITE, the operation
5349 * should be retried with the same data and length.
5350 * Here we assume that the data being pushed will remain the same but the
5351 * amount may grow between calls so we save the length that was used and
5352 * retry. The assumption being that the data itself won't change and won't
5353 * be removed. */
5354 size_t l = len;
5355 if (ctx->saved_len > 0 && ctx->saved_len < l) l = ctx->saved_len;
5356 int n = mbedtls_ssl_write(ctx->ssl, (const unsigned char *) buf, l);
5357 DBG(("%p %d,%d,%d -> %d", nc, (int) len, (int) ctx->saved_len, (int) l, n));
5358 if (n < 0) {
5359 if (n == MBEDTLS_ERR_SSL_WANT_READ || n == MBEDTLS_ERR_SSL_WANT_WRITE) {
5360 ctx->saved_len = len;
5361 }
5362 return mg_ssl_if_mbed_err(nc, n);
5363 } else if (n > 0) {
5364 ctx->saved_len = 0;
5365 }
5366 return n;
5367 }
5368
mg_ssl_if_conn_close_notify(struct mg_connection * nc)5369 void mg_ssl_if_conn_close_notify(struct mg_connection *nc) {
5370 struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
5371 if (ctx == NULL) return;
5372 mbedtls_ssl_close_notify(ctx->ssl);
5373 }
5374
mg_ssl_if_conn_free(struct mg_connection * nc)5375 void mg_ssl_if_conn_free(struct mg_connection *nc) {
5376 struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
5377 if (ctx == NULL) return;
5378 nc->ssl_if_data = NULL;
5379 if (ctx->ssl != NULL) {
5380 mbedtls_ssl_free(ctx->ssl);
5381 MG_FREE(ctx->ssl);
5382 }
5383 mg_ssl_if_mbed_free_certs_and_keys(ctx);
5384 if (ctx->conf != NULL) {
5385 mbedtls_ssl_config_free(ctx->conf);
5386 MG_FREE(ctx->conf);
5387 }
5388 mbuf_free(&ctx->cipher_suites);
5389 memset(ctx, 0, sizeof(*ctx));
5390 MG_FREE(ctx);
5391 }
5392
mg_use_ca_cert(struct mg_ssl_if_ctx * ctx,const char * ca_cert)5393 static enum mg_ssl_if_result mg_use_ca_cert(struct mg_ssl_if_ctx *ctx,
5394 const char *ca_cert) {
5395 if (ca_cert == NULL || strcmp(ca_cert, "*") == 0) {
5396 mbedtls_ssl_conf_authmode(ctx->conf, MBEDTLS_SSL_VERIFY_NONE);
5397 return MG_SSL_OK;
5398 }
5399 ctx->ca_cert = (mbedtls_x509_crt *) MG_CALLOC(1, sizeof(*ctx->ca_cert));
5400 mbedtls_x509_crt_init(ctx->ca_cert);
5401 #ifdef MBEDTLS_X509_CA_CHAIN_ON_DISK
5402 ca_cert = strdup(ca_cert);
5403 mbedtls_ssl_conf_ca_chain_file(ctx->conf, ca_cert, NULL);
5404 #else
5405 if (mbedtls_x509_crt_parse_file(ctx->ca_cert, ca_cert) != 0) {
5406 return MG_SSL_ERROR;
5407 }
5408 mbedtls_ssl_conf_ca_chain(ctx->conf, ctx->ca_cert, NULL);
5409 #endif
5410 mbedtls_ssl_conf_authmode(ctx->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
5411 return MG_SSL_OK;
5412 }
5413
mg_use_cert(struct mg_ssl_if_ctx * ctx,const char * cert,const char * key,const char ** err_msg)5414 static enum mg_ssl_if_result mg_use_cert(struct mg_ssl_if_ctx *ctx,
5415 const char *cert, const char *key,
5416 const char **err_msg) {
5417 if (key == NULL) key = cert;
5418 if (cert == NULL || cert[0] == '\0' || key == NULL || key[0] == '\0') {
5419 return MG_SSL_OK;
5420 }
5421 ctx->cert = (mbedtls_x509_crt *) MG_CALLOC(1, sizeof(*ctx->cert));
5422 mbedtls_x509_crt_init(ctx->cert);
5423 ctx->key = (mbedtls_pk_context *) MG_CALLOC(1, sizeof(*ctx->key));
5424 mbedtls_pk_init(ctx->key);
5425 if (mbedtls_x509_crt_parse_file(ctx->cert, cert) != 0) {
5426 MG_SET_PTRPTR(err_msg, "Invalid SSL cert");
5427 return MG_SSL_ERROR;
5428 }
5429 if (mbedtls_pk_parse_keyfile(ctx->key, key, NULL) != 0) {
5430 MG_SET_PTRPTR(err_msg, "Invalid SSL key");
5431 return MG_SSL_ERROR;
5432 }
5433 if (mbedtls_ssl_conf_own_cert(ctx->conf, ctx->cert, ctx->key) != 0) {
5434 MG_SET_PTRPTR(err_msg, "Invalid SSL key or cert");
5435 return MG_SSL_ERROR;
5436 }
5437 return MG_SSL_OK;
5438 }
5439
5440 static const int mg_s_cipher_list[] = {
5441 #if CS_PLATFORM != CS_P_ESP8266
5442 MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
5443 MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,
5444 MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
5445 MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,
5446 MBEDTLS_TLS_DHE_RSA_WITH_AES_128_GCM_SHA256,
5447 MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256,
5448 MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256,
5449 MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256,
5450 MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA,
5451 MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256,
5452 MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256,
5453 MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA,
5454 MBEDTLS_TLS_RSA_WITH_AES_128_GCM_SHA256,
5455 MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA256,
5456 MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA,
5457 #else
5458 /*
5459 * ECDHE is way too slow on ESP8266 w/o cryptochip, this sometimes results
5460 * in WiFi STA deauths. Use weaker but faster cipher suites. Sad but true.
5461 * Disable DHE completely because it's just hopelessly slow.
5462 */
5463 MBEDTLS_TLS_RSA_WITH_AES_128_GCM_SHA256,
5464 MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA256,
5465 MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
5466 MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,
5467 MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
5468 MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,
5469 MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256,
5470 MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256,
5471 MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA,
5472 MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256,
5473 MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256,
5474 MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA,
5475 MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA,
5476 #endif /* CS_PLATFORM != CS_P_ESP8266 */
5477 0,
5478 };
5479
5480 /*
5481 * Ciphers can be specified as a colon-separated list of cipher suite names.
5482 * These can be found in
5483 * https://github.com/ARMmbed/mbedtls/blob/development/library/ssl_ciphersuites.c#L267
5484 * E.g.: TLS-ECDHE-ECDSA-WITH-AES-128-GCM-SHA256:TLS-DHE-RSA-WITH-AES-256-CCM
5485 */
mg_set_cipher_list(struct mg_ssl_if_ctx * ctx,const char * ciphers)5486 static enum mg_ssl_if_result mg_set_cipher_list(struct mg_ssl_if_ctx *ctx,
5487 const char *ciphers) {
5488 if (ciphers != NULL) {
5489 int l, id;
5490 const char *s = ciphers, *e;
5491 char tmp[50];
5492 while (s != NULL) {
5493 e = strchr(s, ':');
5494 l = (e != NULL ? (e - s) : (int) strlen(s));
5495 strncpy(tmp, s, l);
5496 tmp[l] = '\0';
5497 id = mbedtls_ssl_get_ciphersuite_id(tmp);
5498 DBG(("%s -> %04x", tmp, id));
5499 if (id != 0) {
5500 mbuf_append(&ctx->cipher_suites, &id, sizeof(id));
5501 }
5502 s = (e != NULL ? e + 1 : NULL);
5503 }
5504 if (ctx->cipher_suites.len == 0) return MG_SSL_ERROR;
5505 id = 0;
5506 mbuf_append(&ctx->cipher_suites, &id, sizeof(id));
5507 mbuf_trim(&ctx->cipher_suites);
5508 mbedtls_ssl_conf_ciphersuites(ctx->conf,
5509 (const int *) ctx->cipher_suites.buf);
5510 } else {
5511 mbedtls_ssl_conf_ciphersuites(ctx->conf, mg_s_cipher_list);
5512 }
5513 return MG_SSL_OK;
5514 }
5515
5516 #ifdef MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED
mg_ssl_if_mbed_set_psk(struct mg_ssl_if_ctx * ctx,const char * identity,const char * key_str)5517 static enum mg_ssl_if_result mg_ssl_if_mbed_set_psk(struct mg_ssl_if_ctx *ctx,
5518 const char *identity,
5519 const char *key_str) {
5520 unsigned char key[32];
5521 size_t key_len;
5522 if (identity == NULL && key_str == NULL) return MG_SSL_OK;
5523 if (identity == NULL || key_str == NULL) return MG_SSL_ERROR;
5524 key_len = strlen(key_str);
5525 if (key_len != 32 && key_len != 64) return MG_SSL_ERROR;
5526 size_t i = 0;
5527 memset(key, 0, sizeof(key));
5528 key_len = 0;
5529 for (i = 0; key_str[i] != '\0'; i++) {
5530 unsigned char c;
5531 char hc = tolower((int) key_str[i]);
5532 if (hc >= '0' && hc <= '9') {
5533 c = hc - '0';
5534 } else if (hc >= 'a' && hc <= 'f') {
5535 c = hc - 'a' + 0xa;
5536 } else {
5537 return MG_SSL_ERROR;
5538 }
5539 key_len = i / 2;
5540 key[key_len] <<= 4;
5541 key[key_len] |= c;
5542 }
5543 key_len++;
5544 DBG(("identity = '%s', key = (%u)", identity, (unsigned int) key_len));
5545 /* mbedTLS makes copies of psk and identity. */
5546 if (mbedtls_ssl_conf_psk(ctx->conf, (const unsigned char *) key, key_len,
5547 (const unsigned char *) identity,
5548 strlen(identity)) != 0) {
5549 return MG_SSL_ERROR;
5550 }
5551 return MG_SSL_OK;
5552 }
5553 #endif
5554
mg_set_ssl(struct mg_connection * nc,const char * cert,const char * ca_cert)5555 const char *mg_set_ssl(struct mg_connection *nc, const char *cert,
5556 const char *ca_cert) {
5557 const char *err_msg = NULL;
5558 struct mg_ssl_if_conn_params params;
5559 memset(¶ms, 0, sizeof(params));
5560 params.cert = cert;
5561 params.ca_cert = ca_cert;
5562 if (mg_ssl_if_conn_init(nc, ¶ms, &err_msg) != MG_SSL_OK) {
5563 return err_msg;
5564 }
5565 return NULL;
5566 }
5567
5568 /* Lazy RNG. Warning: it would be a bad idea to do this in production! */
5569 #ifdef MG_SSL_MBED_DUMMY_RANDOM
mg_ssl_if_mbed_random(void * ctx,unsigned char * buf,size_t len)5570 int mg_ssl_if_mbed_random(void *ctx, unsigned char *buf, size_t len) {
5571 (void) ctx;
5572 while (len--) *buf++ = rand();
5573 return 0;
5574 }
5575 #endif
5576
5577 #endif /* MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_MBEDTLS */
5578 #ifdef MG_MODULE_LINES
5579 #line 1 "mongoose/src/mg_uri.c"
5580 #endif
5581 /*
5582 * Copyright (c) 2014 Cesanta Software Limited
5583 * All rights reserved
5584 */
5585
5586 /* Amalgamated: #include "mg_internal.h" */
5587 /* Amalgamated: #include "mg_uri.h" */
5588
5589 /*
5590 * scan string until encountering one of `seps`, keeping track of component
5591 * boundaries in `res`.
5592 *
5593 * `p` will point to the char after the separator or it will be `end`.
5594 */
parse_uri_component(const char ** p,const char * end,const char * seps,struct mg_str * res)5595 static void parse_uri_component(const char **p, const char *end,
5596 const char *seps, struct mg_str *res) {
5597 const char *q;
5598 res->p = *p;
5599 for (; *p < end; (*p)++) {
5600 for (q = seps; *q != '\0'; q++) {
5601 if (**p == *q) break;
5602 }
5603 if (*q != '\0') break;
5604 }
5605 res->len = (*p) - res->p;
5606 if (*p < end) (*p)++;
5607 }
5608
mg_parse_uri(const 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)5609 int mg_parse_uri(const struct mg_str uri, struct mg_str *scheme,
5610 struct mg_str *user_info, struct mg_str *host,
5611 unsigned int *port, struct mg_str *path, struct mg_str *query,
5612 struct mg_str *fragment) {
5613 struct mg_str rscheme = {0, 0}, ruser_info = {0, 0}, rhost = {0, 0},
5614 rpath = {0, 0}, rquery = {0, 0}, rfragment = {0, 0};
5615 unsigned int rport = 0;
5616 enum {
5617 P_START,
5618 P_SCHEME_OR_PORT,
5619 P_USER_INFO,
5620 P_HOST,
5621 P_PORT,
5622 P_REST
5623 } state = P_START;
5624
5625 const char *p = uri.p, *end = p + uri.len;
5626 while (p < end) {
5627 switch (state) {
5628 case P_START:
5629 /*
5630 * expecting on of:
5631 * - `scheme://xxxx`
5632 * - `xxxx:port`
5633 * - `[a:b:c]:port`
5634 * - `xxxx/path`
5635 */
5636 if (*p == '[') {
5637 state = P_HOST;
5638 break;
5639 }
5640 for (; p < end; p++) {
5641 if (*p == ':') {
5642 state = P_SCHEME_OR_PORT;
5643 break;
5644 } else if (*p == '/') {
5645 state = P_REST;
5646 break;
5647 }
5648 }
5649 if (state == P_START || state == P_REST) {
5650 rhost.p = uri.p;
5651 rhost.len = p - uri.p;
5652 }
5653 break;
5654 case P_SCHEME_OR_PORT:
5655 if (end - p >= 3 && strncmp(p, "://", 3) == 0) {
5656 rscheme.p = uri.p;
5657 rscheme.len = p - uri.p;
5658 state = P_USER_INFO;
5659 p += 3;
5660 } else {
5661 rhost.p = uri.p;
5662 rhost.len = p - uri.p;
5663 state = P_PORT;
5664 }
5665 break;
5666 case P_USER_INFO:
5667 ruser_info.p = p;
5668 for (; p < end; p++) {
5669 if (*p == '@' || *p == '[' || *p == '/') {
5670 break;
5671 }
5672 }
5673 if (p == end || *p == '/' || *p == '[') {
5674 /* backtrack and parse as host */
5675 p = ruser_info.p;
5676 }
5677 ruser_info.len = p - ruser_info.p;
5678 state = P_HOST;
5679 break;
5680 case P_HOST:
5681 if (*p == '@') p++;
5682 rhost.p = p;
5683 if (*p == '[') {
5684 int found = 0;
5685 for (; !found && p < end; p++) {
5686 found = (*p == ']');
5687 }
5688 if (!found) return -1;
5689 } else {
5690 for (; p < end; p++) {
5691 if (*p == ':' || *p == '/') break;
5692 }
5693 }
5694 rhost.len = p - rhost.p;
5695 if (p < end) {
5696 if (*p == ':') {
5697 state = P_PORT;
5698 break;
5699 } else if (*p == '/') {
5700 state = P_REST;
5701 break;
5702 }
5703 }
5704 break;
5705 case P_PORT:
5706 p++;
5707 for (; p < end; p++) {
5708 if (*p == '/') {
5709 state = P_REST;
5710 break;
5711 }
5712 rport *= 10;
5713 rport += *p - '0';
5714 }
5715 break;
5716 case P_REST:
5717 /* `p` points to separator. `path` includes the separator */
5718 parse_uri_component(&p, end, "?#", &rpath);
5719 if (p < end && *(p - 1) == '?') {
5720 parse_uri_component(&p, end, "#", &rquery);
5721 }
5722 parse_uri_component(&p, end, "", &rfragment);
5723 break;
5724 }
5725 }
5726
5727 if (scheme != 0) *scheme = rscheme;
5728 if (user_info != 0) *user_info = ruser_info;
5729 if (host != 0) *host = rhost;
5730 if (port != 0) *port = rport;
5731 if (path != 0) *path = rpath;
5732 if (query != 0) *query = rquery;
5733 if (fragment != 0) *fragment = rfragment;
5734
5735 return 0;
5736 }
5737
5738 /* Normalize the URI path. Remove/resolve "." and "..". */
mg_normalize_uri_path(const struct mg_str * in,struct mg_str * out)5739 int mg_normalize_uri_path(const struct mg_str *in, struct mg_str *out) {
5740 const char *s = in->p, *se = s + in->len;
5741 char *cp = (char *) out->p, *d;
5742
5743 if (in->len == 0 || *s != '/') {
5744 out->len = 0;
5745 return 0;
5746 }
5747
5748 d = cp;
5749
5750 while (s < se) {
5751 const char *next = s;
5752 struct mg_str component;
5753 parse_uri_component(&next, se, "/", &component);
5754 if (mg_vcmp(&component, ".") == 0) {
5755 /* Yum. */
5756 } else if (mg_vcmp(&component, "..") == 0) {
5757 /* Backtrack to previous slash. */
5758 if (d > cp + 1 && *(d - 1) == '/') d--;
5759 while (d > cp && *(d - 1) != '/') d--;
5760 } else {
5761 memmove(d, s, next - s);
5762 d += next - s;
5763 }
5764 s = next;
5765 }
5766 if (d == cp) *d++ = '/';
5767
5768 out->p = cp;
5769 out->len = d - cp;
5770 return 1;
5771 }
5772
mg_assemble_uri(const struct mg_str * scheme,const struct mg_str * user_info,const struct mg_str * host,unsigned int port,const struct mg_str * path,const struct mg_str * query,const struct mg_str * fragment,int normalize_path,struct mg_str * uri)5773 int mg_assemble_uri(const struct mg_str *scheme, const struct mg_str *user_info,
5774 const struct mg_str *host, unsigned int port,
5775 const struct mg_str *path, const struct mg_str *query,
5776 const struct mg_str *fragment, int normalize_path,
5777 struct mg_str *uri) {
5778 int result = -1;
5779 struct mbuf out;
5780 mbuf_init(&out, 0);
5781
5782 if (scheme != NULL && scheme->len > 0) {
5783 mbuf_append(&out, scheme->p, scheme->len);
5784 mbuf_append(&out, "://", 3);
5785 }
5786
5787 if (user_info != NULL && user_info->len > 0) {
5788 mbuf_append(&out, user_info->p, user_info->len);
5789 mbuf_append(&out, "@", 1);
5790 }
5791
5792 if (host != NULL && host->len > 0) {
5793 mbuf_append(&out, host->p, host->len);
5794 }
5795
5796 if (port != 0) {
5797 char port_str[20];
5798 int port_str_len = sprintf(port_str, ":%u", port);
5799 mbuf_append(&out, port_str, port_str_len);
5800 }
5801
5802 if (path != NULL && path->len > 0) {
5803 if (normalize_path) {
5804 struct mg_str npath = mg_strdup(*path);
5805 if (npath.len != path->len) goto out;
5806 if (!mg_normalize_uri_path(path, &npath)) {
5807 free((void *) npath.p);
5808 goto out;
5809 }
5810 mbuf_append(&out, npath.p, npath.len);
5811 free((void *) npath.p);
5812 } else {
5813 mbuf_append(&out, path->p, path->len);
5814 }
5815 } else if (normalize_path) {
5816 mbuf_append(&out, "/", 1);
5817 }
5818
5819 if (query != NULL && query->len > 0) {
5820 mbuf_append(&out, "?", 1);
5821 mbuf_append(&out, query->p, query->len);
5822 }
5823
5824 if (fragment != NULL && fragment->len > 0) {
5825 mbuf_append(&out, "#", 1);
5826 mbuf_append(&out, fragment->p, fragment->len);
5827 }
5828
5829 result = 0;
5830
5831 out:
5832 if (result == 0) {
5833 uri->p = out.buf;
5834 uri->len = out.len;
5835 } else {
5836 mbuf_free(&out);
5837 uri->p = NULL;
5838 uri->len = 0;
5839 }
5840 return result;
5841 }
5842 #ifdef MG_MODULE_LINES
5843 #line 1 "mongoose/src/mg_http.c"
5844 #endif
5845 /*
5846 * Copyright (c) 2014 Cesanta Software Limited
5847 * All rights reserved
5848 */
5849
5850 #if MG_ENABLE_HTTP
5851
5852 /* Amalgamated: #include "common/cs_md5.h" */
5853 /* Amalgamated: #include "mg_internal.h" */
5854 /* Amalgamated: #include "mg_util.h" */
5855
5856 /* altbuf {{{ */
5857
5858 /*
5859 * Alternate buffer: fills the client-provided buffer with data; and if it's
5860 * not large enough, allocates another buffer (via mbuf), similar to asprintf.
5861 */
5862 struct altbuf {
5863 struct mbuf m;
5864 char *user_buf;
5865 size_t len;
5866 size_t user_buf_size;
5867 };
5868
5869 /*
5870 * Initializes altbuf; `buf`, `buf_size` is the client-provided buffer.
5871 */
altbuf_init(struct altbuf * ab,char * buf,size_t buf_size)5872 MG_INTERNAL void altbuf_init(struct altbuf *ab, char *buf, size_t buf_size) {
5873 mbuf_init(&ab->m, 0);
5874 ab->user_buf = buf;
5875 ab->user_buf_size = buf_size;
5876 ab->len = 0;
5877 }
5878
5879 /*
5880 * Appends a single char to the altbuf.
5881 */
altbuf_append(struct altbuf * ab,char c)5882 MG_INTERNAL void altbuf_append(struct altbuf *ab, char c) {
5883 if (ab->len < ab->user_buf_size) {
5884 /* The data fits into the original buffer */
5885 ab->user_buf[ab->len++] = c;
5886 } else {
5887 /* The data can't fit into the original buffer, so write it to mbuf. */
5888
5889 /*
5890 * First of all, see if that's the first byte which overflows the original
5891 * buffer: if so, copy the existing data from there to a newly allocated
5892 * mbuf.
5893 */
5894 if (ab->len > 0 && ab->m.len == 0) {
5895 mbuf_append(&ab->m, ab->user_buf, ab->len);
5896 }
5897
5898 mbuf_append(&ab->m, &c, 1);
5899 ab->len = ab->m.len;
5900 }
5901 }
5902
5903 /*
5904 * Resets any data previously appended to altbuf.
5905 */
altbuf_reset(struct altbuf * ab)5906 MG_INTERNAL void altbuf_reset(struct altbuf *ab) {
5907 mbuf_free(&ab->m);
5908 ab->len = 0;
5909 }
5910
5911 /*
5912 * Returns whether the additional buffer was allocated (and thus the data
5913 * is in the mbuf, not the client-provided buffer)
5914 */
altbuf_reallocated(struct altbuf * ab)5915 MG_INTERNAL int altbuf_reallocated(struct altbuf *ab) {
5916 return ab->len > ab->user_buf_size;
5917 }
5918
5919 /*
5920 * Returns the actual buffer with data, either the client-provided or a newly
5921 * allocated one. If `trim` is non-zero, mbuf-backed buffer is trimmed first.
5922 */
altbuf_get_buf(struct altbuf * ab,int trim)5923 MG_INTERNAL char *altbuf_get_buf(struct altbuf *ab, int trim) {
5924 if (altbuf_reallocated(ab)) {
5925 if (trim) {
5926 mbuf_trim(&ab->m);
5927 }
5928 return ab->m.buf;
5929 } else {
5930 return ab->user_buf;
5931 }
5932 }
5933
5934 /* }}} */
5935
5936 static const char *mg_version_header = "Mongoose/" MG_VERSION;
5937
5938 enum mg_http_proto_data_type { DATA_NONE, DATA_FILE, DATA_PUT };
5939
5940 struct mg_http_proto_data_file {
5941 FILE *fp; /* Opened file. */
5942 int64_t cl; /* Content-Length. How many bytes to send. */
5943 int64_t sent; /* How many bytes have been already sent. */
5944 int keepalive; /* Keep connection open after sending. */
5945 enum mg_http_proto_data_type type;
5946 };
5947
5948 #if MG_ENABLE_HTTP_CGI
5949 struct mg_http_proto_data_cgi {
5950 struct mg_connection *cgi_nc;
5951 };
5952 #endif
5953
5954 struct mg_http_proto_data_chuncked {
5955 int64_t body_len; /* How many bytes of chunked body was reassembled. */
5956 };
5957
5958 struct mg_http_endpoint {
5959 struct mg_http_endpoint *next;
5960 struct mg_str uri_pattern; /* owned */
5961 char *auth_domain; /* owned */
5962 char *auth_file; /* owned */
5963
5964 mg_event_handler_t handler;
5965 #if MG_ENABLE_CALLBACK_USERDATA
5966 void *user_data;
5967 #endif
5968 };
5969
5970 enum mg_http_multipart_stream_state {
5971 MPS_BEGIN,
5972 MPS_WAITING_FOR_BOUNDARY,
5973 MPS_WAITING_FOR_CHUNK,
5974 MPS_GOT_BOUNDARY,
5975 MPS_FINALIZE,
5976 MPS_FINISHED
5977 };
5978
5979 struct mg_http_multipart_stream {
5980 const char *boundary;
5981 int boundary_len;
5982 const char *var_name;
5983 const char *file_name;
5984 void *user_data;
5985 enum mg_http_multipart_stream_state state;
5986 int processing_part;
5987 int data_avail;
5988 };
5989
5990 struct mg_reverse_proxy_data {
5991 struct mg_connection *linked_conn;
5992 };
5993
5994 struct mg_ws_proto_data {
5995 /*
5996 * Defragmented size of the frame so far.
5997 *
5998 * First byte of nc->recv_mbuf.buf is an op, the rest of the data is
5999 * defragmented data.
6000 */
6001 size_t reass_len;
6002 };
6003
6004 struct mg_http_proto_data {
6005 #if MG_ENABLE_FILESYSTEM
6006 struct mg_http_proto_data_file file;
6007 #endif
6008 #if MG_ENABLE_HTTP_CGI
6009 struct mg_http_proto_data_cgi cgi;
6010 #endif
6011 #if MG_ENABLE_HTTP_STREAMING_MULTIPART
6012 struct mg_http_multipart_stream mp_stream;
6013 #endif
6014 #if MG_ENABLE_HTTP_WEBSOCKET
6015 struct mg_ws_proto_data ws_data;
6016 #endif
6017 struct mg_http_proto_data_chuncked chunk;
6018 struct mg_http_endpoint *endpoints;
6019 mg_event_handler_t endpoint_handler;
6020 struct mg_reverse_proxy_data reverse_proxy_data;
6021 size_t rcvd; /* How many bytes we have received. */
6022 };
6023
6024 static void mg_http_proto_data_destructor(void *proto_data);
6025
6026 struct mg_connection *mg_connect_http_base(
6027 struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data),
6028 struct mg_connect_opts opts, const char *scheme1, const char *scheme2,
6029 const char *scheme_ssl1, const char *scheme_ssl2, const char *url,
6030 struct mg_str *path, struct mg_str *user_info, struct mg_str *host);
6031
mg_http_create_proto_data(struct mg_connection * c)6032 MG_INTERNAL struct mg_http_proto_data *mg_http_create_proto_data(
6033 struct mg_connection *c) {
6034 /* If we have proto data from previous connection, flush it. */
6035 if (c->proto_data != NULL) {
6036 void *pd = c->proto_data;
6037 c->proto_data = NULL;
6038 mg_http_proto_data_destructor(pd);
6039 }
6040 c->proto_data = MG_CALLOC(1, sizeof(struct mg_http_proto_data));
6041 c->proto_data_destructor = mg_http_proto_data_destructor;
6042 return (struct mg_http_proto_data *) c->proto_data;
6043 }
6044
mg_http_get_proto_data(struct mg_connection * c)6045 static struct mg_http_proto_data *mg_http_get_proto_data(
6046 struct mg_connection *c) {
6047 return (struct mg_http_proto_data *) c->proto_data;
6048 }
6049
6050 #if MG_ENABLE_HTTP_STREAMING_MULTIPART
mg_http_free_proto_data_mp_stream(struct mg_http_multipart_stream * mp)6051 static void mg_http_free_proto_data_mp_stream(
6052 struct mg_http_multipart_stream *mp) {
6053 MG_FREE((void *) mp->boundary);
6054 MG_FREE((void *) mp->var_name);
6055 MG_FREE((void *) mp->file_name);
6056 memset(mp, 0, sizeof(*mp));
6057 }
6058 #endif
6059
6060 #if MG_ENABLE_FILESYSTEM
mg_http_free_proto_data_file(struct mg_http_proto_data_file * d)6061 static void mg_http_free_proto_data_file(struct mg_http_proto_data_file *d) {
6062 if (d != NULL) {
6063 if (d->fp != NULL) {
6064 fclose(d->fp);
6065 }
6066 memset(d, 0, sizeof(struct mg_http_proto_data_file));
6067 }
6068 }
6069 #endif
6070
mg_http_free_proto_data_endpoints(struct mg_http_endpoint ** ep)6071 static void mg_http_free_proto_data_endpoints(struct mg_http_endpoint **ep) {
6072 struct mg_http_endpoint *current = *ep;
6073
6074 while (current != NULL) {
6075 struct mg_http_endpoint *tmp = current->next;
6076 MG_FREE((void *) current->uri_pattern.p);
6077 MG_FREE((void *) current->auth_domain);
6078 MG_FREE((void *) current->auth_file);
6079 MG_FREE(current);
6080 current = tmp;
6081 }
6082
6083 ep = NULL;
6084 }
6085
mg_http_free_reverse_proxy_data(struct mg_reverse_proxy_data * rpd)6086 static void mg_http_free_reverse_proxy_data(struct mg_reverse_proxy_data *rpd) {
6087 if (rpd->linked_conn != NULL) {
6088 /*
6089 * Connection has linked one, we have to unlink & close it
6090 * since _this_ connection is going to die and
6091 * it doesn't make sense to keep another one
6092 */
6093 struct mg_http_proto_data *pd = mg_http_get_proto_data(rpd->linked_conn);
6094 if (pd->reverse_proxy_data.linked_conn != NULL) {
6095 pd->reverse_proxy_data.linked_conn->flags |= MG_F_SEND_AND_CLOSE;
6096 pd->reverse_proxy_data.linked_conn = NULL;
6097 }
6098 rpd->linked_conn = NULL;
6099 }
6100 }
6101
mg_http_proto_data_destructor(void * proto_data)6102 static void mg_http_proto_data_destructor(void *proto_data) {
6103 struct mg_http_proto_data *pd = (struct mg_http_proto_data *) proto_data;
6104 #if MG_ENABLE_FILESYSTEM
6105 mg_http_free_proto_data_file(&pd->file);
6106 #endif
6107 #if MG_ENABLE_HTTP_CGI
6108 mg_http_free_proto_data_cgi(&pd->cgi);
6109 #endif
6110 #if MG_ENABLE_HTTP_STREAMING_MULTIPART
6111 mg_http_free_proto_data_mp_stream(&pd->mp_stream);
6112 #endif
6113 mg_http_free_proto_data_endpoints(&pd->endpoints);
6114 mg_http_free_reverse_proxy_data(&pd->reverse_proxy_data);
6115 MG_FREE(proto_data);
6116 }
6117
6118 #if MG_ENABLE_FILESYSTEM
6119
6120 #define MIME_ENTRY(_ext, _type) \
6121 { _ext, sizeof(_ext) - 1, _type }
6122 static const struct {
6123 const char *extension;
6124 size_t ext_len;
6125 const char *mime_type;
6126 } mg_static_builtin_mime_types[] = {
6127 MIME_ENTRY("html", "text/html"),
6128 MIME_ENTRY("html", "text/html"),
6129 MIME_ENTRY("htm", "text/html"),
6130 MIME_ENTRY("shtm", "text/html"),
6131 MIME_ENTRY("shtml", "text/html"),
6132 MIME_ENTRY("css", "text/css"),
6133 MIME_ENTRY("js", "application/x-javascript"),
6134 MIME_ENTRY("ico", "image/x-icon"),
6135 MIME_ENTRY("gif", "image/gif"),
6136 MIME_ENTRY("jpg", "image/jpeg"),
6137 MIME_ENTRY("jpeg", "image/jpeg"),
6138 MIME_ENTRY("png", "image/png"),
6139 MIME_ENTRY("svg", "image/svg+xml"),
6140 MIME_ENTRY("txt", "text/plain"),
6141 MIME_ENTRY("torrent", "application/x-bittorrent"),
6142 MIME_ENTRY("wav", "audio/x-wav"),
6143 MIME_ENTRY("mp3", "audio/x-mp3"),
6144 MIME_ENTRY("mid", "audio/mid"),
6145 MIME_ENTRY("m3u", "audio/x-mpegurl"),
6146 MIME_ENTRY("ogg", "application/ogg"),
6147 MIME_ENTRY("ram", "audio/x-pn-realaudio"),
6148 MIME_ENTRY("xml", "text/xml"),
6149 MIME_ENTRY("ttf", "application/x-font-ttf"),
6150 MIME_ENTRY("json", "application/json"),
6151 MIME_ENTRY("xslt", "application/xml"),
6152 MIME_ENTRY("xsl", "application/xml"),
6153 MIME_ENTRY("ra", "audio/x-pn-realaudio"),
6154 MIME_ENTRY("doc", "application/msword"),
6155 MIME_ENTRY("exe", "application/octet-stream"),
6156 MIME_ENTRY("zip", "application/x-zip-compressed"),
6157 MIME_ENTRY("xls", "application/excel"),
6158 MIME_ENTRY("tgz", "application/x-tar-gz"),
6159 MIME_ENTRY("tar", "application/x-tar"),
6160 MIME_ENTRY("gz", "application/x-gunzip"),
6161 MIME_ENTRY("arj", "application/x-arj-compressed"),
6162 MIME_ENTRY("rar", "application/x-rar-compressed"),
6163 MIME_ENTRY("rtf", "application/rtf"),
6164 MIME_ENTRY("pdf", "application/pdf"),
6165 MIME_ENTRY("swf", "application/x-shockwave-flash"),
6166 MIME_ENTRY("mpg", "video/mpeg"),
6167 MIME_ENTRY("webm", "video/webm"),
6168 MIME_ENTRY("mpeg", "video/mpeg"),
6169 MIME_ENTRY("mov", "video/quicktime"),
6170 MIME_ENTRY("mp4", "video/mp4"),
6171 MIME_ENTRY("m4v", "video/x-m4v"),
6172 MIME_ENTRY("asf", "video/x-ms-asf"),
6173 MIME_ENTRY("avi", "video/x-msvideo"),
6174 MIME_ENTRY("bmp", "image/bmp"),
6175 {NULL, 0, NULL}};
6176
mg_get_mime_type(const char * path,const char * dflt,const struct mg_serve_http_opts * opts)6177 static struct mg_str mg_get_mime_type(const char *path, const char *dflt,
6178 const struct mg_serve_http_opts *opts) {
6179 const char *ext, *overrides;
6180 size_t i, path_len;
6181 struct mg_str r, k, v;
6182
6183 path_len = strlen(path);
6184
6185 overrides = opts->custom_mime_types;
6186 while ((overrides = mg_next_comma_list_entry(overrides, &k, &v)) != NULL) {
6187 ext = path + (path_len - k.len);
6188 if (path_len > k.len && mg_vcasecmp(&k, ext) == 0) {
6189 return v;
6190 }
6191 }
6192
6193 for (i = 0; mg_static_builtin_mime_types[i].extension != NULL; i++) {
6194 ext = path + (path_len - mg_static_builtin_mime_types[i].ext_len);
6195 if (path_len > mg_static_builtin_mime_types[i].ext_len && ext[-1] == '.' &&
6196 mg_casecmp(ext, mg_static_builtin_mime_types[i].extension) == 0) {
6197 r.p = mg_static_builtin_mime_types[i].mime_type;
6198 r.len = strlen(r.p);
6199 return r;
6200 }
6201 }
6202
6203 r.p = dflt;
6204 r.len = strlen(r.p);
6205 return r;
6206 }
6207 #endif
6208
6209 /*
6210 * Check whether full request is buffered. Return:
6211 * -1 if request is malformed
6212 * 0 if request is not yet fully buffered
6213 * >0 actual request length, including last \r\n\r\n
6214 */
mg_http_get_request_len(const char * s,int buf_len)6215 static int mg_http_get_request_len(const char *s, int buf_len) {
6216 const unsigned char *buf = (unsigned char *) s;
6217 int i;
6218
6219 for (i = 0; i < buf_len; i++) {
6220 if (!isprint(buf[i]) && buf[i] != '\r' && buf[i] != '\n' && buf[i] < 128) {
6221 return -1;
6222 } else if (buf[i] == '\n' && i + 1 < buf_len && buf[i + 1] == '\n') {
6223 return i + 2;
6224 } else if (buf[i] == '\n' && i + 2 < buf_len && buf[i + 1] == '\r' &&
6225 buf[i + 2] == '\n') {
6226 return i + 3;
6227 }
6228 }
6229
6230 return 0;
6231 }
6232
mg_http_parse_headers(const char * s,const char * end,int len,struct http_message * req)6233 static const char *mg_http_parse_headers(const char *s, const char *end,
6234 int len, struct http_message *req) {
6235 int i = 0;
6236 while (i < (int) ARRAY_SIZE(req->header_names) - 1) {
6237 struct mg_str *k = &req->header_names[i], *v = &req->header_values[i];
6238
6239 s = mg_skip(s, end, ": ", k);
6240 s = mg_skip(s, end, "\r\n", v);
6241
6242 while (v->len > 0 && v->p[v->len - 1] == ' ') {
6243 v->len--; /* Trim trailing spaces in header value */
6244 }
6245
6246 /*
6247 * If header value is empty - skip it and go to next (if any).
6248 * NOTE: Do not add it to headers_values because such addition changes API
6249 * behaviour
6250 */
6251 if (k->len != 0 && v->len == 0) {
6252 continue;
6253 }
6254
6255 if (k->len == 0 || v->len == 0) {
6256 k->p = v->p = NULL;
6257 k->len = v->len = 0;
6258 break;
6259 }
6260
6261 if (!mg_ncasecmp(k->p, "Content-Length", 14)) {
6262 req->body.len = (size_t) to64(v->p);
6263 req->message.len = len + req->body.len;
6264 }
6265
6266 i++;
6267 }
6268
6269 return s;
6270 }
6271
mg_parse_http(const char * s,int n,struct http_message * hm,int is_req)6272 int mg_parse_http(const char *s, int n, struct http_message *hm, int is_req) {
6273 const char *end, *qs;
6274 int len = mg_http_get_request_len(s, n);
6275
6276 if (len <= 0) return len;
6277
6278 memset(hm, 0, sizeof(*hm));
6279 hm->message.p = s;
6280 hm->body.p = s + len;
6281 hm->message.len = hm->body.len = (size_t) ~0;
6282 end = s + len;
6283
6284 /* Request is fully buffered. Skip leading whitespaces. */
6285 while (s < end && isspace(*(unsigned char *) s)) s++;
6286
6287 if (is_req) {
6288 /* Parse request line: method, URI, proto */
6289 s = mg_skip(s, end, " ", &hm->method);
6290 s = mg_skip(s, end, " ", &hm->uri);
6291 s = mg_skip(s, end, "\r\n", &hm->proto);
6292 if (hm->uri.p <= hm->method.p || hm->proto.p <= hm->uri.p) return -1;
6293
6294 /* If URI contains '?' character, initialize query_string */
6295 if ((qs = (char *) memchr(hm->uri.p, '?', hm->uri.len)) != NULL) {
6296 hm->query_string.p = qs + 1;
6297 hm->query_string.len = &hm->uri.p[hm->uri.len] - (qs + 1);
6298 hm->uri.len = qs - hm->uri.p;
6299 }
6300 } else {
6301 s = mg_skip(s, end, " ", &hm->proto);
6302 if (end - s < 4 || s[0] < '0' || s[0] > '9' || s[3] != ' ') return -1;
6303 hm->resp_code = atoi(s);
6304 if (hm->resp_code < 100 || hm->resp_code >= 600) return -1;
6305 s += 4;
6306 s = mg_skip(s, end, "\r\n", &hm->resp_status_msg);
6307 }
6308
6309 s = mg_http_parse_headers(s, end, len, hm);
6310
6311 /*
6312 * mg_parse_http() is used to parse both HTTP requests and HTTP
6313 * responses. If HTTP response does not have Content-Length set, then
6314 * body is read until socket is closed, i.e. body.len is infinite (~0).
6315 *
6316 * For HTTP requests though, according to
6317 * http://tools.ietf.org/html/rfc7231#section-8.1.3,
6318 * only POST and PUT methods have defined body semantics.
6319 * Therefore, if Content-Length is not specified and methods are
6320 * not one of PUT or POST, set body length to 0.
6321 *
6322 * So,
6323 * if it is HTTP request, and Content-Length is not set,
6324 * and method is not (PUT or POST) then reset body length to zero.
6325 */
6326 if (hm->body.len == (size_t) ~0 && is_req &&
6327 mg_vcasecmp(&hm->method, "PUT") != 0 &&
6328 mg_vcasecmp(&hm->method, "POST") != 0) {
6329 hm->body.len = 0;
6330 hm->message.len = len;
6331 }
6332
6333 return len;
6334 }
6335
mg_get_http_header(struct http_message * hm,const char * name)6336 struct mg_str *mg_get_http_header(struct http_message *hm, const char *name) {
6337 size_t i, len = strlen(name);
6338
6339 for (i = 0; hm->header_names[i].len > 0; i++) {
6340 struct mg_str *h = &hm->header_names[i], *v = &hm->header_values[i];
6341 if (h->p != NULL && h->len == len && !mg_ncasecmp(h->p, name, len))
6342 return v;
6343 }
6344
6345 return NULL;
6346 }
6347
6348 #if MG_ENABLE_FILESYSTEM
mg_http_transfer_file_data(struct mg_connection * nc)6349 static void mg_http_transfer_file_data(struct mg_connection *nc) {
6350 struct mg_http_proto_data *pd = mg_http_get_proto_data(nc);
6351 char buf[MG_MAX_HTTP_SEND_MBUF];
6352 size_t n = 0, to_read = 0, left = (size_t)(pd->file.cl - pd->file.sent);
6353
6354 if (pd->file.type == DATA_FILE) {
6355 struct mbuf *io = &nc->send_mbuf;
6356 if (io->len >= MG_MAX_HTTP_SEND_MBUF) {
6357 to_read = 0;
6358 } else {
6359 to_read = MG_MAX_HTTP_SEND_MBUF - io->len;
6360 }
6361 if (to_read > left) {
6362 to_read = left;
6363 }
6364 if (to_read > 0) {
6365 n = mg_fread(buf, 1, to_read, pd->file.fp);
6366 if (n > 0) {
6367 mg_send(nc, buf, n);
6368 pd->file.sent += n;
6369 DBG(("%p sent %d (total %d)", nc, (int) n, (int) pd->file.sent));
6370 }
6371 } else {
6372 /* Rate-limited */
6373 }
6374 if (pd->file.sent >= pd->file.cl) {
6375 LOG(LL_DEBUG, ("%p done, %d bytes, ka %d", nc, (int) pd->file.sent,
6376 pd->file.keepalive));
6377 if (!pd->file.keepalive) nc->flags |= MG_F_SEND_AND_CLOSE;
6378 mg_http_free_proto_data_file(&pd->file);
6379 }
6380 } else if (pd->file.type == DATA_PUT) {
6381 struct mbuf *io = &nc->recv_mbuf;
6382 size_t to_write = left <= 0 ? 0 : left < io->len ? (size_t) left : io->len;
6383 size_t n = mg_fwrite(io->buf, 1, to_write, pd->file.fp);
6384 if (n > 0) {
6385 mbuf_remove(io, n);
6386 pd->file.sent += n;
6387 }
6388 if (n == 0 || pd->file.sent >= pd->file.cl) {
6389 if (!pd->file.keepalive) nc->flags |= MG_F_SEND_AND_CLOSE;
6390 mg_http_free_proto_data_file(&pd->file);
6391 }
6392 }
6393 #if MG_ENABLE_HTTP_CGI
6394 else if (pd->cgi.cgi_nc != NULL) {
6395 /* This is POST data that needs to be forwarded to the CGI process */
6396 if (pd->cgi.cgi_nc != NULL) {
6397 mg_forward(nc, pd->cgi.cgi_nc);
6398 } else {
6399 nc->flags |= MG_F_SEND_AND_CLOSE;
6400 }
6401 }
6402 #endif
6403 }
6404 #endif /* MG_ENABLE_FILESYSTEM */
6405
6406 /*
6407 * Parse chunked-encoded buffer. Return 0 if the buffer is not encoded, or
6408 * if it's incomplete. If the chunk is fully buffered, return total number of
6409 * bytes in a chunk, and store data in `data`, `data_len`.
6410 */
mg_http_parse_chunk(char * buf,size_t len,char ** chunk_data,size_t * chunk_len)6411 static size_t mg_http_parse_chunk(char *buf, size_t len, char **chunk_data,
6412 size_t *chunk_len) {
6413 unsigned char *s = (unsigned char *) buf;
6414 size_t n = 0; /* scanned chunk length */
6415 size_t i = 0; /* index in s */
6416
6417 /* Scan chunk length. That should be a hexadecimal number. */
6418 while (i < len && isxdigit(s[i])) {
6419 n *= 16;
6420 n += (s[i] >= '0' && s[i] <= '9') ? s[i] - '0' : tolower(s[i]) - 'a' + 10;
6421 i++;
6422 if (i > 6) {
6423 /* Chunk size is unreasonable. */
6424 return 0;
6425 }
6426 }
6427
6428 /* Skip new line */
6429 if (i == 0 || i + 2 > len || s[i] != '\r' || s[i + 1] != '\n') {
6430 return 0;
6431 }
6432 i += 2;
6433
6434 /* Record where the data is */
6435 *chunk_data = (char *) s + i;
6436 *chunk_len = n;
6437
6438 /* Skip data */
6439 i += n;
6440
6441 /* Skip new line */
6442 if (i == 0 || i + 2 > len || s[i] != '\r' || s[i + 1] != '\n') {
6443 return 0;
6444 }
6445 return i + 2;
6446 }
6447
mg_handle_chunked(struct mg_connection * nc,struct http_message * hm,char * buf,size_t blen)6448 MG_INTERNAL size_t mg_handle_chunked(struct mg_connection *nc,
6449 struct http_message *hm, char *buf,
6450 size_t blen) {
6451 struct mg_http_proto_data *pd = mg_http_get_proto_data(nc);
6452 char *data;
6453 size_t i, n, data_len, body_len, zero_chunk_received = 0;
6454 /* Find out piece of received data that is not yet reassembled */
6455 body_len = (size_t) pd->chunk.body_len;
6456 assert(blen >= body_len);
6457
6458 /* Traverse all fully buffered chunks */
6459 for (i = body_len;
6460 (n = mg_http_parse_chunk(buf + i, blen - i, &data, &data_len)) > 0;
6461 i += n) {
6462 /* Collapse chunk data to the rest of HTTP body */
6463 memmove(buf + body_len, data, data_len);
6464 body_len += data_len;
6465 hm->body.len = body_len;
6466
6467 if (data_len == 0) {
6468 zero_chunk_received = 1;
6469 i += n;
6470 break;
6471 }
6472 }
6473
6474 if (i > body_len) {
6475 /* Shift unparsed content to the parsed body */
6476 assert(i <= blen);
6477 memmove(buf + body_len, buf + i, blen - i);
6478 memset(buf + body_len + blen - i, 0, i - body_len);
6479 nc->recv_mbuf.len -= i - body_len;
6480 pd->chunk.body_len = body_len;
6481
6482 /* Send MG_EV_HTTP_CHUNK event */
6483 nc->flags &= ~MG_F_DELETE_CHUNK;
6484 mg_call(nc, nc->handler, nc->user_data, MG_EV_HTTP_CHUNK, hm);
6485
6486 /* Delete processed data if user set MG_F_DELETE_CHUNK flag */
6487 if (nc->flags & MG_F_DELETE_CHUNK) {
6488 memset(buf, 0, body_len);
6489 memmove(buf, buf + body_len, blen - i);
6490 nc->recv_mbuf.len -= body_len;
6491 hm->body.len = 0;
6492 pd->chunk.body_len = 0;
6493 }
6494
6495 if (zero_chunk_received) {
6496 /* Total message size is len(body) + len(headers) */
6497 hm->message.len =
6498 (size_t) pd->chunk.body_len + blen - i + (hm->body.p - hm->message.p);
6499 }
6500 }
6501
6502 return body_len;
6503 }
6504
mg_http_get_endpoint_handler(struct mg_connection * nc,struct mg_str * uri_path)6505 struct mg_http_endpoint *mg_http_get_endpoint_handler(struct mg_connection *nc,
6506 struct mg_str *uri_path) {
6507 struct mg_http_proto_data *pd;
6508 struct mg_http_endpoint *ret = NULL;
6509 int matched, matched_max = 0;
6510 struct mg_http_endpoint *ep;
6511
6512 if (nc == NULL) return NULL;
6513
6514 pd = mg_http_get_proto_data(nc);
6515
6516 if (pd == NULL) return NULL;
6517
6518 ep = pd->endpoints;
6519 while (ep != NULL) {
6520 if ((matched = mg_match_prefix_n(ep->uri_pattern, *uri_path)) > 0) {
6521 if (matched > matched_max) {
6522 /* Looking for the longest suitable handler */
6523 ret = ep;
6524 matched_max = matched;
6525 }
6526 }
6527
6528 ep = ep->next;
6529 }
6530
6531 return ret;
6532 }
6533
6534 #if MG_ENABLE_HTTP_STREAMING_MULTIPART
6535 static void mg_http_multipart_continue(struct mg_connection *nc);
6536
6537 static void mg_http_multipart_begin(struct mg_connection *nc,
6538 struct http_message *hm, int req_len);
6539
6540 #endif
6541
6542 static void mg_http_call_endpoint_handler(struct mg_connection *nc, int ev,
6543 struct http_message *hm);
6544
deliver_chunk(struct mg_connection * c,struct http_message * hm,int req_len)6545 static void deliver_chunk(struct mg_connection *c, struct http_message *hm,
6546 int req_len) {
6547 /* Incomplete message received. Send MG_EV_HTTP_CHUNK event */
6548 hm->body.len = c->recv_mbuf.len - req_len;
6549 c->flags &= ~MG_F_DELETE_CHUNK;
6550 mg_call(c, c->handler, c->user_data, MG_EV_HTTP_CHUNK, hm);
6551 /* Delete processed data if user set MG_F_DELETE_CHUNK flag */
6552 if (c->flags & MG_F_DELETE_CHUNK) c->recv_mbuf.len = req_len;
6553 }
6554
6555 /*
6556 * lx106 compiler has a bug (TODO(mkm) report and insert tracking bug here)
6557 * If a big structure is declared in a big function, lx106 gcc will make it
6558 * even bigger (round up to 4k, from 700 bytes of actual size).
6559 */
6560 #ifdef __xtensa__
6561 static void mg_http_handler2(struct mg_connection *nc, int ev,
6562 void *ev_data MG_UD_ARG(void *user_data),
6563 struct http_message *hm) __attribute__((noinline));
6564
mg_http_handler(struct mg_connection * nc,int ev,void * ev_data MG_UD_ARG (void * user_data))6565 void mg_http_handler(struct mg_connection *nc, int ev,
6566 void *ev_data MG_UD_ARG(void *user_data)) {
6567 struct http_message hm;
6568 mg_http_handler2(nc, ev, ev_data MG_UD_ARG(user_data), &hm);
6569 }
6570
mg_http_handler2(struct mg_connection * nc,int ev,void * ev_data MG_UD_ARG (void * user_data),struct http_message * hm)6571 static void mg_http_handler2(struct mg_connection *nc, int ev,
6572 void *ev_data MG_UD_ARG(void *user_data),
6573 struct http_message *hm) {
6574 #else /* !__XTENSA__ */
6575 void mg_http_handler(struct mg_connection *nc, int ev,
6576 void *ev_data MG_UD_ARG(void *user_data)) {
6577 struct http_message shm, *hm = &shm;
6578 #endif /* __XTENSA__ */
6579 struct mg_http_proto_data *pd = mg_http_get_proto_data(nc);
6580 struct mbuf *io = &nc->recv_mbuf;
6581 int req_len;
6582 const int is_req = (nc->listener != NULL);
6583 #if MG_ENABLE_HTTP_WEBSOCKET
6584 struct mg_str *vec;
6585 #endif
6586 if (ev == MG_EV_CLOSE) {
6587 #if MG_ENABLE_HTTP_CGI
6588 /* Close associated CGI forwarder connection */
6589 if (pd != NULL && pd->cgi.cgi_nc != NULL) {
6590 pd->cgi.cgi_nc->user_data = NULL;
6591 pd->cgi.cgi_nc->flags |= MG_F_CLOSE_IMMEDIATELY;
6592 }
6593 #endif
6594 #if MG_ENABLE_HTTP_STREAMING_MULTIPART
6595 if (pd != NULL && pd->mp_stream.boundary != NULL) {
6596 /*
6597 * Multipart message is in progress, but connection is closed.
6598 * Finish part and request with an error flag.
6599 */
6600 struct mg_http_multipart_part mp;
6601 memset(&mp, 0, sizeof(mp));
6602 mp.status = -1;
6603 mp.user_data = pd->mp_stream.user_data;
6604 mp.var_name = pd->mp_stream.var_name;
6605 mp.file_name = pd->mp_stream.file_name;
6606 mg_call(nc, (pd->endpoint_handler ? pd->endpoint_handler : nc->handler),
6607 nc->user_data, MG_EV_HTTP_PART_END, &mp);
6608 mp.var_name = NULL;
6609 mp.file_name = NULL;
6610 mg_call(nc, (pd->endpoint_handler ? pd->endpoint_handler : nc->handler),
6611 nc->user_data, MG_EV_HTTP_MULTIPART_REQUEST_END, &mp);
6612 } else
6613 #endif
6614 if (io->len > 0 &&
6615 (req_len = mg_parse_http(io->buf, io->len, hm, is_req)) > 0) {
6616 /*
6617 * For HTTP messages without Content-Length, always send HTTP message
6618 * before MG_EV_CLOSE message.
6619 */
6620 int ev2 = is_req ? MG_EV_HTTP_REQUEST : MG_EV_HTTP_REPLY;
6621 hm->message.len = io->len;
6622 hm->body.len = io->buf + io->len - hm->body.p;
6623 deliver_chunk(nc, hm, req_len);
6624 mg_http_call_endpoint_handler(nc, ev2, hm);
6625 }
6626 if (pd != NULL && pd->endpoint_handler != NULL &&
6627 pd->endpoint_handler != nc->handler) {
6628 mg_call(nc, pd->endpoint_handler, nc->user_data, ev, NULL);
6629 }
6630 }
6631
6632 #if MG_ENABLE_FILESYSTEM
6633 if (pd != NULL && pd->file.fp != NULL) {
6634 mg_http_transfer_file_data(nc);
6635 }
6636 #endif
6637
6638 mg_call(nc, nc->handler, nc->user_data, ev, ev_data);
6639
6640 #if MG_ENABLE_HTTP_STREAMING_MULTIPART
6641 if (pd != NULL && pd->mp_stream.boundary != NULL &&
6642 (ev == MG_EV_RECV || ev == MG_EV_POLL)) {
6643 if (ev == MG_EV_RECV) {
6644 pd->rcvd += *(int *) ev_data;
6645 mg_http_multipart_continue(nc);
6646 } else if (pd->mp_stream.data_avail) {
6647 /* Try re-delivering the data. */
6648 mg_http_multipart_continue(nc);
6649 }
6650 return;
6651 }
6652 #endif /* MG_ENABLE_HTTP_STREAMING_MULTIPART */
6653
6654 if (ev == MG_EV_RECV) {
6655 struct mg_str *s;
6656
6657 again:
6658 req_len = mg_parse_http(io->buf, io->len, hm, is_req);
6659
6660 if (req_len > 0) {
6661 /* New request - new proto data */
6662 pd = mg_http_create_proto_data(nc);
6663 pd->rcvd = io->len;
6664 }
6665
6666 if (req_len > 0 &&
6667 (s = mg_get_http_header(hm, "Transfer-Encoding")) != NULL &&
6668 mg_vcasecmp(s, "chunked") == 0) {
6669 mg_handle_chunked(nc, hm, io->buf + req_len, io->len - req_len);
6670 }
6671
6672 #if MG_ENABLE_HTTP_STREAMING_MULTIPART
6673 if (req_len > 0 && (s = mg_get_http_header(hm, "Content-Type")) != NULL &&
6674 s->len >= 9 && strncmp(s->p, "multipart", 9) == 0) {
6675 mg_http_multipart_begin(nc, hm, req_len);
6676 mg_http_multipart_continue(nc);
6677 return;
6678 }
6679 #endif /* MG_ENABLE_HTTP_STREAMING_MULTIPART */
6680
6681 /* TODO(alashkin): refactor this ifelseifelseifelseifelse */
6682 if ((req_len < 0 ||
6683 (req_len == 0 && io->len >= MG_MAX_HTTP_REQUEST_SIZE))) {
6684 DBG(("invalid request"));
6685 nc->flags |= MG_F_CLOSE_IMMEDIATELY;
6686 } else if (req_len == 0) {
6687 /* Do nothing, request is not yet fully buffered */
6688 }
6689 #if MG_ENABLE_HTTP_WEBSOCKET
6690 else if (nc->listener == NULL && (nc->flags & MG_F_IS_WEBSOCKET)) {
6691 /* We're websocket client, got handshake response from server. */
6692 DBG(("%p WebSocket upgrade code %d", nc, hm->resp_code));
6693 if (hm->resp_code == 101 &&
6694 mg_get_http_header(hm, "Sec-WebSocket-Accept")) {
6695 /* TODO(lsm): check the validity of accept Sec-WebSocket-Accept */
6696 mg_call(nc, nc->handler, nc->user_data, MG_EV_WEBSOCKET_HANDSHAKE_DONE,
6697 hm);
6698 mbuf_remove(io, req_len);
6699 nc->proto_handler = mg_ws_handler;
6700 mg_ws_handler(nc, MG_EV_RECV, ev_data MG_UD_ARG(user_data));
6701 } else {
6702 mg_call(nc, nc->handler, nc->user_data, MG_EV_WEBSOCKET_HANDSHAKE_DONE,
6703 hm);
6704 nc->flags |= MG_F_CLOSE_IMMEDIATELY;
6705 mbuf_remove(io, req_len);
6706 }
6707 } else if (nc->listener != NULL &&
6708 (vec = mg_get_http_header(hm, "Sec-WebSocket-Key")) != NULL) {
6709 struct mg_http_endpoint *ep;
6710
6711 /* This is a websocket request. Switch protocol handlers. */
6712 mbuf_remove(io, req_len);
6713 nc->proto_handler = mg_ws_handler;
6714 nc->flags |= MG_F_IS_WEBSOCKET;
6715
6716 /*
6717 * If we have a handler set up with mg_register_http_endpoint(),
6718 * deliver subsequent websocket events to this handler after the
6719 * protocol switch.
6720 */
6721 ep = mg_http_get_endpoint_handler(nc->listener, &hm->uri);
6722 if (ep != NULL) {
6723 nc->handler = ep->handler;
6724 #if MG_ENABLE_CALLBACK_USERDATA
6725 nc->user_data = ep->user_data;
6726 #endif
6727 }
6728
6729 /* Send handshake */
6730 mg_call(nc, nc->handler, nc->user_data, MG_EV_WEBSOCKET_HANDSHAKE_REQUEST,
6731 hm);
6732 if (!(nc->flags & (MG_F_CLOSE_IMMEDIATELY | MG_F_SEND_AND_CLOSE))) {
6733 if (nc->send_mbuf.len == 0) {
6734 mg_ws_handshake(nc, vec, hm);
6735 }
6736 mg_call(nc, nc->handler, nc->user_data, MG_EV_WEBSOCKET_HANDSHAKE_DONE,
6737 hm);
6738 mg_ws_handler(nc, MG_EV_RECV, ev_data MG_UD_ARG(user_data));
6739 }
6740 }
6741 #endif /* MG_ENABLE_HTTP_WEBSOCKET */
6742 else if (hm->message.len > pd->rcvd) {
6743 /* Not yet received all HTTP body, deliver MG_EV_HTTP_CHUNK */
6744 deliver_chunk(nc, hm, req_len);
6745 if (nc->recv_mbuf_limit > 0 && nc->recv_mbuf.len >= nc->recv_mbuf_limit) {
6746 LOG(LL_ERROR, ("%p recv buffer (%lu bytes) exceeds the limit "
6747 "%lu bytes, and not drained, closing",
6748 nc, (unsigned long) nc->recv_mbuf.len,
6749 (unsigned long) nc->recv_mbuf_limit));
6750 nc->flags |= MG_F_CLOSE_IMMEDIATELY;
6751 }
6752 } else {
6753 /* We did receive all HTTP body. */
6754 int request_done = 1;
6755 int trigger_ev = nc->listener ? MG_EV_HTTP_REQUEST : MG_EV_HTTP_REPLY;
6756 char addr[32];
6757 mg_sock_addr_to_str(&nc->sa, addr, sizeof(addr),
6758 MG_SOCK_STRINGIFY_IP | MG_SOCK_STRINGIFY_PORT);
6759 DBG(("%p %s %.*s %.*s", nc, addr, (int) hm->method.len, hm->method.p,
6760 (int) hm->uri.len, hm->uri.p));
6761 deliver_chunk(nc, hm, req_len);
6762 /* Whole HTTP message is fully buffered, call event handler */
6763 mg_http_call_endpoint_handler(nc, trigger_ev, hm);
6764 mbuf_remove(io, hm->message.len);
6765 pd->rcvd -= hm->message.len;
6766 #if MG_ENABLE_FILESYSTEM
6767 /* We don't have a generic mechanism of communicating that we are done
6768 * responding to a request (should probably add one). But if we are
6769 * serving
6770 * a file, we are definitely not done. */
6771 if (pd->file.fp != NULL) request_done = 0;
6772 #endif
6773 #if MG_ENABLE_HTTP_CGI
6774 /* If this is a CGI request, we are not done either. */
6775 if (pd->cgi.cgi_nc != NULL) request_done = 0;
6776 #endif
6777 if (request_done && io->len > 0) goto again;
6778 }
6779 }
6780 }
6781
6782 static size_t mg_get_line_len(const char *buf, size_t buf_len) {
6783 size_t len = 0;
6784 while (len < buf_len && buf[len] != '\n') len++;
6785 return len == buf_len ? 0 : len + 1;
6786 }
6787
6788 #if MG_ENABLE_HTTP_STREAMING_MULTIPART
6789 static void mg_http_multipart_begin(struct mg_connection *nc,
6790 struct http_message *hm, int req_len) {
6791 struct mg_http_proto_data *pd = mg_http_get_proto_data(nc);
6792 struct mg_str *ct;
6793 struct mbuf *io = &nc->recv_mbuf;
6794
6795 char boundary_buf[100];
6796 char *boundary = boundary_buf;
6797 int boundary_len;
6798
6799 ct = mg_get_http_header(hm, "Content-Type");
6800 if (ct == NULL) {
6801 /* We need more data - or it isn't multipart message */
6802 goto exit_mp;
6803 }
6804
6805 /* Content-type should start with "multipart" */
6806 if (ct->len < 9 || strncmp(ct->p, "multipart", 9) != 0) {
6807 goto exit_mp;
6808 }
6809
6810 boundary_len =
6811 mg_http_parse_header2(ct, "boundary", &boundary, sizeof(boundary_buf));
6812 if (boundary_len == 0) {
6813 /*
6814 * Content type is multipart, but there is no boundary,
6815 * probably malformed request
6816 */
6817 nc->flags = MG_F_CLOSE_IMMEDIATELY;
6818 DBG(("invalid request"));
6819 goto exit_mp;
6820 }
6821
6822 /* If we reach this place - that is multipart request */
6823
6824 if (pd->mp_stream.boundary != NULL) {
6825 /*
6826 * Another streaming request was in progress,
6827 * looks like protocol error
6828 */
6829 nc->flags |= MG_F_CLOSE_IMMEDIATELY;
6830 } else {
6831 struct mg_http_endpoint *ep = NULL;
6832 pd->mp_stream.state = MPS_BEGIN;
6833 pd->mp_stream.boundary = strdup(boundary);
6834 pd->mp_stream.boundary_len = strlen(boundary);
6835 pd->mp_stream.var_name = pd->mp_stream.file_name = NULL;
6836 pd->endpoint_handler = nc->handler;
6837
6838 ep = mg_http_get_endpoint_handler(nc->listener, &hm->uri);
6839 if (ep != NULL) {
6840 pd->endpoint_handler = ep->handler;
6841 }
6842
6843 mg_http_call_endpoint_handler(nc, MG_EV_HTTP_MULTIPART_REQUEST, hm);
6844
6845 mbuf_remove(io, req_len);
6846 }
6847 exit_mp:
6848 if (boundary != boundary_buf) MG_FREE(boundary);
6849 }
6850
6851 #define CONTENT_DISPOSITION "Content-Disposition: "
6852
6853 static size_t mg_http_multipart_call_handler(struct mg_connection *c, int ev,
6854 const char *data,
6855 size_t data_len) {
6856 struct mg_http_multipart_part mp;
6857 struct mg_http_proto_data *pd = mg_http_get_proto_data(c);
6858 memset(&mp, 0, sizeof(mp));
6859
6860 mp.var_name = pd->mp_stream.var_name;
6861 mp.file_name = pd->mp_stream.file_name;
6862 mp.user_data = pd->mp_stream.user_data;
6863 mp.data.p = data;
6864 mp.data.len = data_len;
6865 mp.num_data_consumed = data_len;
6866 mg_call(c, pd->endpoint_handler, c->user_data, ev, &mp);
6867 pd->mp_stream.user_data = mp.user_data;
6868 pd->mp_stream.data_avail = (mp.num_data_consumed != data_len);
6869 return mp.num_data_consumed;
6870 }
6871
6872 static int mg_http_multipart_finalize(struct mg_connection *c) {
6873 struct mg_http_proto_data *pd = mg_http_get_proto_data(c);
6874
6875 mg_http_multipart_call_handler(c, MG_EV_HTTP_PART_END, NULL, 0);
6876 MG_FREE((void *) pd->mp_stream.file_name);
6877 pd->mp_stream.file_name = NULL;
6878 MG_FREE((void *) pd->mp_stream.var_name);
6879 pd->mp_stream.var_name = NULL;
6880 mg_http_multipart_call_handler(c, MG_EV_HTTP_MULTIPART_REQUEST_END, NULL, 0);
6881 mg_http_free_proto_data_mp_stream(&pd->mp_stream);
6882 pd->mp_stream.state = MPS_FINISHED;
6883
6884 return 1;
6885 }
6886
6887 static int mg_http_multipart_wait_for_boundary(struct mg_connection *c) {
6888 const char *boundary;
6889 struct mbuf *io = &c->recv_mbuf;
6890 struct mg_http_proto_data *pd = mg_http_get_proto_data(c);
6891
6892 if (pd->mp_stream.boundary == NULL) {
6893 pd->mp_stream.state = MPS_FINALIZE;
6894 DBG(("Invalid request: boundary not initialized"));
6895 return 0;
6896 }
6897
6898 if ((int) io->len < pd->mp_stream.boundary_len + 2) {
6899 return 0;
6900 }
6901
6902 boundary = c_strnstr(io->buf, pd->mp_stream.boundary, io->len);
6903 if (boundary != NULL) {
6904 const char *boundary_end = (boundary + pd->mp_stream.boundary_len);
6905 if (io->len - (boundary_end - io->buf) < 4) {
6906 return 0;
6907 }
6908 if (strncmp(boundary_end, "--\r\n", 4) == 0) {
6909 pd->mp_stream.state = MPS_FINALIZE;
6910 mbuf_remove(io, (boundary_end - io->buf) + 4);
6911 } else {
6912 pd->mp_stream.state = MPS_GOT_BOUNDARY;
6913 }
6914 } else {
6915 return 0;
6916 }
6917
6918 return 1;
6919 }
6920
6921 static void mg_http_parse_header_internal(struct mg_str *hdr,
6922 const char *var_name,
6923 struct altbuf *ab);
6924
6925 static int mg_http_multipart_process_boundary(struct mg_connection *c) {
6926 int data_size;
6927 const char *boundary, *block_begin;
6928 struct mbuf *io = &c->recv_mbuf;
6929 struct mg_http_proto_data *pd = mg_http_get_proto_data(c);
6930 struct altbuf ab_file_name, ab_var_name;
6931 int line_len;
6932 boundary = c_strnstr(io->buf, pd->mp_stream.boundary, io->len);
6933 block_begin = boundary + pd->mp_stream.boundary_len + 2;
6934 data_size = io->len - (block_begin - io->buf);
6935
6936 altbuf_init(&ab_file_name, NULL, 0);
6937 altbuf_init(&ab_var_name, NULL, 0);
6938
6939 while (data_size > 0 &&
6940 (line_len = mg_get_line_len(block_begin, data_size)) != 0) {
6941 if (line_len > (int) sizeof(CONTENT_DISPOSITION) &&
6942 mg_ncasecmp(block_begin, CONTENT_DISPOSITION,
6943 sizeof(CONTENT_DISPOSITION) - 1) == 0) {
6944 struct mg_str header;
6945
6946 header.p = block_begin + sizeof(CONTENT_DISPOSITION) - 1;
6947 header.len = line_len - sizeof(CONTENT_DISPOSITION) - 1;
6948
6949 altbuf_reset(&ab_var_name);
6950 mg_http_parse_header_internal(&header, "name", &ab_var_name);
6951
6952 altbuf_reset(&ab_file_name);
6953 mg_http_parse_header_internal(&header, "filename", &ab_file_name);
6954
6955 block_begin += line_len;
6956 data_size -= line_len;
6957
6958 continue;
6959 }
6960
6961 if (line_len == 2 && mg_ncasecmp(block_begin, "\r\n", 2) == 0) {
6962 mbuf_remove(io, block_begin - io->buf + 2);
6963
6964 if (pd->mp_stream.processing_part != 0) {
6965 mg_http_multipart_call_handler(c, MG_EV_HTTP_PART_END, NULL, 0);
6966 }
6967
6968 /* Reserve 2 bytes for "\r\n" in file_name and var_name */
6969 altbuf_append(&ab_file_name, '\0');
6970 altbuf_append(&ab_file_name, '\0');
6971 altbuf_append(&ab_var_name, '\0');
6972 altbuf_append(&ab_var_name, '\0');
6973
6974 MG_FREE((void *) pd->mp_stream.file_name);
6975 pd->mp_stream.file_name = altbuf_get_buf(&ab_file_name, 1 /* trim */);
6976 MG_FREE((void *) pd->mp_stream.var_name);
6977 pd->mp_stream.var_name = altbuf_get_buf(&ab_var_name, 1 /* trim */);
6978
6979 mg_http_multipart_call_handler(c, MG_EV_HTTP_PART_BEGIN, NULL, 0);
6980 pd->mp_stream.state = MPS_WAITING_FOR_CHUNK;
6981 pd->mp_stream.processing_part++;
6982 return 1;
6983 }
6984
6985 block_begin += line_len;
6986 }
6987
6988 pd->mp_stream.state = MPS_WAITING_FOR_BOUNDARY;
6989
6990 altbuf_reset(&ab_var_name);
6991 altbuf_reset(&ab_file_name);
6992
6993 return 0;
6994 }
6995
6996 static int mg_http_multipart_continue_wait_for_chunk(struct mg_connection *c) {
6997 struct mg_http_proto_data *pd = mg_http_get_proto_data(c);
6998 struct mbuf *io = &c->recv_mbuf;
6999
7000 const char *boundary;
7001 if ((int) io->len < pd->mp_stream.boundary_len + 6 /* \r\n, --, -- */) {
7002 return 0;
7003 }
7004
7005 boundary = c_strnstr(io->buf, pd->mp_stream.boundary, io->len);
7006 if (boundary == NULL) {
7007 int data_len = (io->len - (pd->mp_stream.boundary_len + 6));
7008 if (data_len > 0) {
7009 size_t consumed = mg_http_multipart_call_handler(
7010 c, MG_EV_HTTP_PART_DATA, io->buf, (size_t) data_len);
7011 mbuf_remove(io, consumed);
7012 }
7013 return 0;
7014 } else if (boundary != NULL) {
7015 size_t data_len = ((size_t)(boundary - io->buf) - 4);
7016 size_t consumed = mg_http_multipart_call_handler(c, MG_EV_HTTP_PART_DATA,
7017 io->buf, data_len);
7018 mbuf_remove(io, consumed);
7019 if (consumed == data_len) {
7020 mbuf_remove(io, 4);
7021 pd->mp_stream.state = MPS_WAITING_FOR_BOUNDARY;
7022 return 1;
7023 } else {
7024 return 0;
7025 }
7026 } else {
7027 return 0;
7028 }
7029 }
7030
7031 static void mg_http_multipart_continue(struct mg_connection *c) {
7032 struct mg_http_proto_data *pd = mg_http_get_proto_data(c);
7033 while (1) {
7034 switch (pd->mp_stream.state) {
7035 case MPS_BEGIN: {
7036 pd->mp_stream.state = MPS_WAITING_FOR_BOUNDARY;
7037 break;
7038 }
7039 case MPS_WAITING_FOR_BOUNDARY: {
7040 if (mg_http_multipart_wait_for_boundary(c) == 0) {
7041 return;
7042 }
7043 break;
7044 }
7045 case MPS_GOT_BOUNDARY: {
7046 if (mg_http_multipart_process_boundary(c) == 0) {
7047 return;
7048 }
7049 break;
7050 }
7051 case MPS_WAITING_FOR_CHUNK: {
7052 if (mg_http_multipart_continue_wait_for_chunk(c) == 0) {
7053 return;
7054 }
7055 break;
7056 }
7057 case MPS_FINALIZE: {
7058 if (mg_http_multipart_finalize(c) == 0) {
7059 return;
7060 }
7061 break;
7062 }
7063 case MPS_FINISHED: {
7064 return;
7065 }
7066 }
7067 }
7068 }
7069
7070 struct file_upload_state {
7071 char *lfn;
7072 size_t num_recd;
7073 FILE *fp;
7074 };
7075
7076 #endif /* MG_ENABLE_HTTP_STREAMING_MULTIPART */
7077
7078 void mg_set_protocol_http_websocket(struct mg_connection *nc) {
7079 nc->proto_handler = mg_http_handler;
7080 }
7081
7082 const char *mg_status_message(int status_code) {
7083 switch (status_code) {
7084 case 206:
7085 return "Partial Content";
7086 case 301:
7087 return "Moved";
7088 case 302:
7089 return "Found";
7090 case 400:
7091 return "Bad Request";
7092 case 401:
7093 return "Unauthorized";
7094 case 403:
7095 return "Forbidden";
7096 case 404:
7097 return "Not Found";
7098 case 416:
7099 return "Requested Range Not Satisfiable";
7100 case 418:
7101 return "I'm a teapot";
7102 case 500:
7103 return "Internal Server Error";
7104 case 502:
7105 return "Bad Gateway";
7106 case 503:
7107 return "Service Unavailable";
7108
7109 #if MG_ENABLE_EXTRA_ERRORS_DESC
7110 case 100:
7111 return "Continue";
7112 case 101:
7113 return "Switching Protocols";
7114 case 102:
7115 return "Processing";
7116 case 200:
7117 return "OK";
7118 case 201:
7119 return "Created";
7120 case 202:
7121 return "Accepted";
7122 case 203:
7123 return "Non-Authoritative Information";
7124 case 204:
7125 return "No Content";
7126 case 205:
7127 return "Reset Content";
7128 case 207:
7129 return "Multi-Status";
7130 case 208:
7131 return "Already Reported";
7132 case 226:
7133 return "IM Used";
7134 case 300:
7135 return "Multiple Choices";
7136 case 303:
7137 return "See Other";
7138 case 304:
7139 return "Not Modified";
7140 case 305:
7141 return "Use Proxy";
7142 case 306:
7143 return "Switch Proxy";
7144 case 307:
7145 return "Temporary Redirect";
7146 case 308:
7147 return "Permanent Redirect";
7148 case 402:
7149 return "Payment Required";
7150 case 405:
7151 return "Method Not Allowed";
7152 case 406:
7153 return "Not Acceptable";
7154 case 407:
7155 return "Proxy Authentication Required";
7156 case 408:
7157 return "Request Timeout";
7158 case 409:
7159 return "Conflict";
7160 case 410:
7161 return "Gone";
7162 case 411:
7163 return "Length Required";
7164 case 412:
7165 return "Precondition Failed";
7166 case 413:
7167 return "Payload Too Large";
7168 case 414:
7169 return "URI Too Long";
7170 case 415:
7171 return "Unsupported Media Type";
7172 case 417:
7173 return "Expectation Failed";
7174 case 422:
7175 return "Unprocessable Entity";
7176 case 423:
7177 return "Locked";
7178 case 424:
7179 return "Failed Dependency";
7180 case 426:
7181 return "Upgrade Required";
7182 case 428:
7183 return "Precondition Required";
7184 case 429:
7185 return "Too Many Requests";
7186 case 431:
7187 return "Request Header Fields Too Large";
7188 case 451:
7189 return "Unavailable For Legal Reasons";
7190 case 501:
7191 return "Not Implemented";
7192 case 504:
7193 return "Gateway Timeout";
7194 case 505:
7195 return "HTTP Version Not Supported";
7196 case 506:
7197 return "Variant Also Negotiates";
7198 case 507:
7199 return "Insufficient Storage";
7200 case 508:
7201 return "Loop Detected";
7202 case 510:
7203 return "Not Extended";
7204 case 511:
7205 return "Network Authentication Required";
7206 #endif /* MG_ENABLE_EXTRA_ERRORS_DESC */
7207
7208 default:
7209 return "OK";
7210 }
7211 }
7212
7213 void mg_send_response_line_s(struct mg_connection *nc, int status_code,
7214 const struct mg_str extra_headers) {
7215 mg_printf(nc, "HTTP/1.1 %d %s\r\n", status_code,
7216 mg_status_message(status_code));
7217 #ifndef MG_HIDE_SERVER_INFO
7218 mg_printf(nc, "Server: %s\r\n", mg_version_header);
7219 #endif
7220 if (extra_headers.len > 0) {
7221 mg_printf(nc, "%.*s\r\n", (int) extra_headers.len, extra_headers.p);
7222 }
7223 }
7224
7225 void mg_send_response_line(struct mg_connection *nc, int status_code,
7226 const char *extra_headers) {
7227 mg_send_response_line_s(nc, status_code, mg_mk_str(extra_headers));
7228 }
7229
7230 void mg_http_send_redirect(struct mg_connection *nc, int status_code,
7231 const struct mg_str location,
7232 const struct mg_str extra_headers) {
7233 char bbody[100], *pbody = bbody;
7234 int bl = mg_asprintf(&pbody, sizeof(bbody),
7235 "<p>Moved <a href='%.*s'>here</a>.\r\n",
7236 (int) location.len, location.p);
7237 char bhead[150], *phead = bhead;
7238 mg_asprintf(&phead, sizeof(bhead),
7239 "Location: %.*s\r\n"
7240 "Content-Type: text/html\r\n"
7241 "Content-Length: %d\r\n"
7242 "Cache-Control: no-cache\r\n"
7243 "%.*s%s",
7244 (int) location.len, location.p, bl, (int) extra_headers.len,
7245 extra_headers.p, (extra_headers.len > 0 ? "\r\n" : ""));
7246 mg_send_response_line(nc, status_code, phead);
7247 if (phead != bhead) MG_FREE(phead);
7248 mg_send(nc, pbody, bl);
7249 if (pbody != bbody) MG_FREE(pbody);
7250 }
7251
7252 void mg_send_head(struct mg_connection *c, int status_code,
7253 int64_t content_length, const char *extra_headers) {
7254 mg_send_response_line(c, status_code, extra_headers);
7255 if (content_length < 0) {
7256 mg_printf(c, "%s", "Transfer-Encoding: chunked\r\n");
7257 } else {
7258 mg_printf(c, "Content-Length: %" INT64_FMT "\r\n", content_length);
7259 }
7260 mg_send(c, "\r\n", 2);
7261 }
7262
7263 void mg_http_send_error(struct mg_connection *nc, int code,
7264 const char *reason) {
7265 if (!reason) reason = mg_status_message(code);
7266 LOG(LL_DEBUG, ("%p %d %s", nc, code, reason));
7267 mg_send_head(nc, code, strlen(reason),
7268 "Content-Type: text/plain\r\nConnection: close");
7269 mg_send(nc, reason, strlen(reason));
7270 nc->flags |= MG_F_SEND_AND_CLOSE;
7271 }
7272
7273 #if MG_ENABLE_FILESYSTEM
7274 static void mg_http_construct_etag(char *buf, size_t buf_len,
7275 const cs_stat_t *st) {
7276 snprintf(buf, buf_len, "\"%lx.%" INT64_FMT "\"", (unsigned long) st->st_mtime,
7277 (int64_t) st->st_size);
7278 }
7279
7280 #ifndef WINCE
7281 static void mg_gmt_time_string(char *buf, size_t buf_len, time_t *t) {
7282 struct tm tm;
7283 strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", gmtime_r(t, &tm));
7284 }
7285 #else
7286 /* Look wince_lib.c for WindowsCE implementation */
7287 static void mg_gmt_time_string(char *buf, size_t buf_len, time_t *t);
7288 #endif
7289
7290 static int mg_http_parse_range_header(const struct mg_str *header, int64_t *a,
7291 int64_t *b) {
7292 /*
7293 * There is no snscanf. Headers are not guaranteed to be NUL-terminated,
7294 * so we have this. Ugh.
7295 */
7296 int result;
7297 char *p = (char *) MG_MALLOC(header->len + 1);
7298 if (p == NULL) return 0;
7299 memcpy(p, header->p, header->len);
7300 p[header->len] = '\0';
7301 result = sscanf(p, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
7302 MG_FREE(p);
7303 return result;
7304 }
7305
7306 void mg_http_serve_file(struct mg_connection *nc, struct http_message *hm,
7307 const char *path, const struct mg_str mime_type,
7308 const struct mg_str extra_headers) {
7309 struct mg_http_proto_data *pd = mg_http_get_proto_data(nc);
7310 cs_stat_t st;
7311 LOG(LL_DEBUG, ("%p [%s] %.*s", nc, path, (int) mime_type.len, mime_type.p));
7312 if (mg_stat(path, &st) != 0 || (pd->file.fp = mg_fopen(path, "rb")) == NULL) {
7313 int code, err = mg_get_errno();
7314 switch (err) {
7315 case EACCES:
7316 code = 403;
7317 break;
7318 case ENOENT:
7319 code = 404;
7320 break;
7321 default:
7322 code = 500;
7323 };
7324 mg_http_send_error(nc, code, "Open failed");
7325 } else {
7326 char etag[50], current_time[50], last_modified[50], range[70];
7327 time_t t = (time_t) mg_time();
7328 int64_t r1 = 0, r2 = 0, cl = st.st_size;
7329 struct mg_str *range_hdr = mg_get_http_header(hm, "Range");
7330 int n, status_code = 200;
7331
7332 /* Handle Range header */
7333 range[0] = '\0';
7334 if (range_hdr != NULL &&
7335 (n = mg_http_parse_range_header(range_hdr, &r1, &r2)) > 0 && r1 >= 0 &&
7336 r2 >= 0) {
7337 /* If range is specified like "400-", set second limit to content len */
7338 if (n == 1) {
7339 r2 = cl - 1;
7340 }
7341 if (r1 > r2 || r2 >= cl) {
7342 status_code = 416;
7343 cl = 0;
7344 snprintf(range, sizeof(range),
7345 "Content-Range: bytes */%" INT64_FMT "\r\n",
7346 (int64_t) st.st_size);
7347 } else {
7348 status_code = 206;
7349 cl = r2 - r1 + 1;
7350 snprintf(range, sizeof(range), "Content-Range: bytes %" INT64_FMT
7351 "-%" INT64_FMT "/%" INT64_FMT "\r\n",
7352 r1, r1 + cl - 1, (int64_t) st.st_size);
7353 #if _FILE_OFFSET_BITS == 64 || _POSIX_C_SOURCE >= 200112L || \
7354 _XOPEN_SOURCE >= 600
7355 fseeko(pd->file.fp, r1, SEEK_SET);
7356 #else
7357 fseek(pd->file.fp, (long) r1, SEEK_SET);
7358 #endif
7359 }
7360 }
7361
7362 #if !MG_DISABLE_HTTP_KEEP_ALIVE
7363 {
7364 struct mg_str *conn_hdr = mg_get_http_header(hm, "Connection");
7365 if (conn_hdr != NULL) {
7366 pd->file.keepalive = (mg_vcasecmp(conn_hdr, "keep-alive") == 0);
7367 } else {
7368 pd->file.keepalive = (mg_vcmp(&hm->proto, "HTTP/1.1") == 0);
7369 }
7370 }
7371 #endif
7372
7373 mg_http_construct_etag(etag, sizeof(etag), &st);
7374 mg_gmt_time_string(current_time, sizeof(current_time), &t);
7375 mg_gmt_time_string(last_modified, sizeof(last_modified), &st.st_mtime);
7376 /*
7377 * Content length casted to size_t because:
7378 * 1) that's the maximum buffer size anyway
7379 * 2) ESP8266 RTOS SDK newlib vprintf cannot contain a 64bit arg at non-last
7380 * position
7381 * TODO(mkm): fix ESP8266 RTOS SDK
7382 */
7383 mg_send_response_line_s(nc, status_code, extra_headers);
7384 mg_printf(nc,
7385 "Date: %s\r\n"
7386 "Last-Modified: %s\r\n"
7387 "Accept-Ranges: bytes\r\n"
7388 "Content-Type: %.*s\r\n"
7389 "Connection: %s\r\n"
7390 "Content-Length: %" SIZE_T_FMT
7391 "\r\n"
7392 "%sEtag: %s\r\n\r\n",
7393 current_time, last_modified, (int) mime_type.len, mime_type.p,
7394 (pd->file.keepalive ? "keep-alive" : "close"), (size_t) cl, range,
7395 etag);
7396
7397 pd->file.cl = cl;
7398 pd->file.type = DATA_FILE;
7399 mg_http_transfer_file_data(nc);
7400 }
7401 }
7402
7403 static void mg_http_serve_file2(struct mg_connection *nc, const char *path,
7404 struct http_message *hm,
7405 struct mg_serve_http_opts *opts) {
7406 #if MG_ENABLE_HTTP_SSI
7407 if (mg_match_prefix(opts->ssi_pattern, strlen(opts->ssi_pattern), path) > 0) {
7408 mg_handle_ssi_request(nc, hm, path, opts);
7409 return;
7410 }
7411 #endif
7412 mg_http_serve_file(nc, hm, path, mg_get_mime_type(path, "text/plain", opts),
7413 mg_mk_str(opts->extra_headers));
7414 }
7415
7416 #endif
7417
7418 int mg_url_decode(const char *src, int src_len, char *dst, int dst_len,
7419 int is_form_url_encoded) {
7420 int i, j, a, b;
7421 #define HEXTOI(x) (isdigit(x) ? x - '0' : x - 'W')
7422
7423 for (i = j = 0; i < src_len && j < dst_len - 1; i++, j++) {
7424 if (src[i] == '%') {
7425 if (i < src_len - 2 && isxdigit(*(const unsigned char *) (src + i + 1)) &&
7426 isxdigit(*(const unsigned char *) (src + i + 2))) {
7427 a = tolower(*(const unsigned char *) (src + i + 1));
7428 b = tolower(*(const unsigned char *) (src + i + 2));
7429 dst[j] = (char) ((HEXTOI(a) << 4) | HEXTOI(b));
7430 i += 2;
7431 } else {
7432 return -1;
7433 }
7434 } else if (is_form_url_encoded && src[i] == '+') {
7435 dst[j] = ' ';
7436 } else {
7437 dst[j] = src[i];
7438 }
7439 }
7440
7441 dst[j] = '\0'; /* Null-terminate the destination */
7442
7443 return i >= src_len ? j : -1;
7444 }
7445
7446 int mg_get_http_var(const struct mg_str *buf, const char *name, char *dst,
7447 size_t dst_len) {
7448 const char *p, *e, *s;
7449 size_t name_len;
7450 int len;
7451
7452 /*
7453 * According to the documentation function returns negative
7454 * value in case of error. For debug purposes it returns:
7455 * -1 - src is wrong (NUUL)
7456 * -2 - dst is wrong (NULL)
7457 * -3 - failed to decode url or dst is to small
7458 * -4 - name does not exist
7459 */
7460 if (dst == NULL || dst_len == 0) {
7461 len = -2;
7462 } else if (buf->p == NULL || name == NULL || buf->len == 0) {
7463 len = -1;
7464 dst[0] = '\0';
7465 } else {
7466 name_len = strlen(name);
7467 e = buf->p + buf->len;
7468 len = -4;
7469 dst[0] = '\0';
7470
7471 for (p = buf->p; p + name_len < e; p++) {
7472 if ((p == buf->p || p[-1] == '&') && p[name_len] == '=' &&
7473 !mg_ncasecmp(name, p, name_len)) {
7474 p += name_len + 1;
7475 s = (const char *) memchr(p, '&', (size_t)(e - p));
7476 if (s == NULL) {
7477 s = e;
7478 }
7479 len = mg_url_decode(p, (size_t)(s - p), dst, dst_len, 1);
7480 /* -1 means: failed to decode or dst is too small */
7481 if (len == -1) {
7482 len = -3;
7483 }
7484 break;
7485 }
7486 }
7487 }
7488
7489 return len;
7490 }
7491
7492 void mg_send_http_chunk(struct mg_connection *nc, const char *buf, size_t len) {
7493 char chunk_size[50];
7494 int n;
7495
7496 n = snprintf(chunk_size, sizeof(chunk_size), "%lX\r\n", (unsigned long) len);
7497 mg_send(nc, chunk_size, n);
7498 mg_send(nc, buf, len);
7499 mg_send(nc, "\r\n", 2);
7500 }
7501
7502 void mg_printf_http_chunk(struct mg_connection *nc, const char *fmt, ...) {
7503 char mem[MG_VPRINTF_BUFFER_SIZE], *buf = mem;
7504 int len;
7505 va_list ap;
7506
7507 va_start(ap, fmt);
7508 len = mg_avprintf(&buf, sizeof(mem), fmt, ap);
7509 va_end(ap);
7510
7511 if (len >= 0) {
7512 mg_send_http_chunk(nc, buf, len);
7513 }
7514
7515 /* LCOV_EXCL_START */
7516 if (buf != mem && buf != NULL) {
7517 MG_FREE(buf);
7518 }
7519 /* LCOV_EXCL_STOP */
7520 }
7521
7522 void mg_printf_html_escape(struct mg_connection *nc, const char *fmt, ...) {
7523 char mem[MG_VPRINTF_BUFFER_SIZE], *buf = mem;
7524 int i, j, len;
7525 va_list ap;
7526
7527 va_start(ap, fmt);
7528 len = mg_avprintf(&buf, sizeof(mem), fmt, ap);
7529 va_end(ap);
7530
7531 if (len >= 0) {
7532 for (i = j = 0; i < len; i++) {
7533 if (buf[i] == '<' || buf[i] == '>') {
7534 mg_send(nc, buf + j, i - j);
7535 mg_send(nc, buf[i] == '<' ? "<" : ">", 4);
7536 j = i + 1;
7537 }
7538 }
7539 mg_send(nc, buf + j, i - j);
7540 }
7541
7542 /* LCOV_EXCL_START */
7543 if (buf != mem && buf != NULL) {
7544 MG_FREE(buf);
7545 }
7546 /* LCOV_EXCL_STOP */
7547 }
7548
7549 static void mg_http_parse_header_internal(struct mg_str *hdr,
7550 const char *var_name,
7551 struct altbuf *ab) {
7552 int ch = ' ', ch1 = ',', ch2 = ';', n = strlen(var_name);
7553 const char *p, *end = hdr ? hdr->p + hdr->len : NULL, *s = NULL;
7554
7555 /* Find where variable starts */
7556 for (s = hdr->p; s != NULL && s + n < end; s++) {
7557 if ((s == hdr->p || s[-1] == ch || s[-1] == ch1 || s[-1] == ';') &&
7558 s[n] == '=' && !strncmp(s, var_name, n))
7559 break;
7560 }
7561
7562 if (s != NULL && &s[n + 1] < end) {
7563 s += n + 1;
7564 if (*s == '"' || *s == '\'') {
7565 ch = ch1 = ch2 = *s++;
7566 }
7567 p = s;
7568 while (p < end && p[0] != ch && p[0] != ch1 && p[0] != ch2) {
7569 if (ch != ' ' && p[0] == '\\' && p[1] == ch) p++;
7570 altbuf_append(ab, *p++);
7571 }
7572
7573 if (ch != ' ' && *p != ch) {
7574 altbuf_reset(ab);
7575 }
7576 }
7577
7578 /* If there is some data, append a NUL. */
7579 if (ab->len > 0) {
7580 altbuf_append(ab, '\0');
7581 }
7582 }
7583
7584 int mg_http_parse_header2(struct mg_str *hdr, const char *var_name, char **buf,
7585 size_t buf_size) {
7586 struct altbuf ab;
7587 altbuf_init(&ab, *buf, buf_size);
7588 if (hdr == NULL) return 0;
7589 if (*buf != NULL && buf_size > 0) *buf[0] = '\0';
7590
7591 mg_http_parse_header_internal(hdr, var_name, &ab);
7592
7593 /*
7594 * Get a (trimmed) buffer, and return a len without a NUL byte which might
7595 * have been added.
7596 */
7597 *buf = altbuf_get_buf(&ab, 1 /* trim */);
7598 return ab.len > 0 ? ab.len - 1 : 0;
7599 }
7600
7601 int mg_http_parse_header(struct mg_str *hdr, const char *var_name, char *buf,
7602 size_t buf_size) {
7603 char *buf2 = buf;
7604
7605 int len = mg_http_parse_header2(hdr, var_name, &buf2, buf_size);
7606
7607 if (buf2 != buf) {
7608 /* Buffer was not enough and was reallocated: free it and just return 0 */
7609 MG_FREE(buf2);
7610 return 0;
7611 }
7612
7613 return len;
7614 }
7615
7616 int mg_get_http_basic_auth(struct http_message *hm, char *user, size_t user_len,
7617 char *pass, size_t pass_len) {
7618 struct mg_str *hdr = mg_get_http_header(hm, "Authorization");
7619 if (hdr == NULL) return -1;
7620 return mg_parse_http_basic_auth(hdr, user, user_len, pass, pass_len);
7621 }
7622
7623 int mg_parse_http_basic_auth(struct mg_str *hdr, char *user, size_t user_len,
7624 char *pass, size_t pass_len) {
7625 char *buf = NULL;
7626 char fmt[64];
7627 int res = 0;
7628
7629 if (mg_strncmp(*hdr, mg_mk_str("Basic "), 6) != 0) return -1;
7630
7631 buf = (char *) MG_MALLOC(hdr->len);
7632 cs_base64_decode((unsigned char *) hdr->p + 6, hdr->len, buf, NULL);
7633
7634 /* e.g. "%123[^:]:%321[^\n]" */
7635 snprintf(fmt, sizeof(fmt), "%%%" SIZE_T_FMT "[^:]:%%%" SIZE_T_FMT "[^\n]",
7636 user_len - 1, pass_len - 1);
7637 if (sscanf(buf, fmt, user, pass) == 0) {
7638 res = -1;
7639 }
7640
7641 MG_FREE(buf);
7642 return res;
7643 }
7644
7645 #if MG_ENABLE_FILESYSTEM
7646 static int mg_is_file_hidden(const char *path,
7647 const struct mg_serve_http_opts *opts,
7648 int exclude_specials) {
7649 const char *p1 = opts->per_directory_auth_file;
7650 const char *p2 = opts->hidden_file_pattern;
7651
7652 /* Strip directory path from the file name */
7653 const char *pdir = strrchr(path, DIRSEP);
7654 if (pdir != NULL) {
7655 path = pdir + 1;
7656 }
7657
7658 return (exclude_specials && (!strcmp(path, ".") || !strcmp(path, ".."))) ||
7659 (p1 != NULL && mg_match_prefix(p1, strlen(p1), path) == strlen(p1)) ||
7660 (p2 != NULL && mg_match_prefix(p2, strlen(p2), path) > 0);
7661 }
7662
7663 #if !MG_DISABLE_HTTP_DIGEST_AUTH
7664
7665 #ifndef MG_EXT_MD5
7666 void mg_hash_md5_v(size_t num_msgs, const uint8_t *msgs[],
7667 const size_t *msg_lens, uint8_t *digest) {
7668 size_t i;
7669 cs_md5_ctx md5_ctx;
7670 cs_md5_init(&md5_ctx);
7671 for (i = 0; i < num_msgs; i++) {
7672 cs_md5_update(&md5_ctx, msgs[i], msg_lens[i]);
7673 }
7674 cs_md5_final(digest, &md5_ctx);
7675 }
7676 #else
7677 extern void mg_hash_md5_v(size_t num_msgs, const uint8_t *msgs[],
7678 const size_t *msg_lens, uint8_t *digest);
7679 #endif
7680
7681 void cs_md5(char buf[33], ...) {
7682 unsigned char hash[16];
7683 const uint8_t *msgs[20], *p;
7684 size_t msg_lens[20];
7685 size_t num_msgs = 0;
7686 va_list ap;
7687
7688 va_start(ap, buf);
7689 while ((p = va_arg(ap, const unsigned char *) ) != NULL) {
7690 msgs[num_msgs] = p;
7691 msg_lens[num_msgs] = va_arg(ap, size_t);
7692 num_msgs++;
7693 }
7694 va_end(ap);
7695
7696 mg_hash_md5_v(num_msgs, msgs, msg_lens, hash);
7697 cs_to_hex(buf, hash, sizeof(hash));
7698 }
7699
7700 static void mg_mkmd5resp(const char *method, size_t method_len, const char *uri,
7701 size_t uri_len, const char *ha1, size_t ha1_len,
7702 const char *nonce, size_t nonce_len, const char *nc,
7703 size_t nc_len, const char *cnonce, size_t cnonce_len,
7704 const char *qop, size_t qop_len, char *resp) {
7705 static const char colon[] = ":";
7706 static const size_t one = 1;
7707 char ha2[33];
7708 cs_md5(ha2, method, method_len, colon, one, uri, uri_len, NULL);
7709 cs_md5(resp, ha1, ha1_len, colon, one, nonce, nonce_len, colon, one, nc,
7710 nc_len, colon, one, cnonce, cnonce_len, colon, one, qop, qop_len,
7711 colon, one, ha2, sizeof(ha2) - 1, NULL);
7712 }
7713
7714 int mg_http_create_digest_auth_header(char *buf, size_t buf_len,
7715 const char *method, const char *uri,
7716 const char *auth_domain, const char *user,
7717 const char *passwd, const char *nonce) {
7718 static const char colon[] = ":", qop[] = "auth";
7719 static const size_t one = 1;
7720 char ha1[33], resp[33], cnonce[40];
7721
7722 snprintf(cnonce, sizeof(cnonce), "%lx", (unsigned long) mg_time());
7723 cs_md5(ha1, user, (size_t) strlen(user), colon, one, auth_domain,
7724 (size_t) strlen(auth_domain), colon, one, passwd,
7725 (size_t) strlen(passwd), NULL);
7726 mg_mkmd5resp(method, strlen(method), uri, strlen(uri), ha1, sizeof(ha1) - 1,
7727 nonce, strlen(nonce), "1", one, cnonce, strlen(cnonce), qop,
7728 sizeof(qop) - 1, resp);
7729 return snprintf(buf, buf_len,
7730 "Authorization: Digest username=\"%s\","
7731 "realm=\"%s\",uri=\"%s\",qop=%s,nc=1,cnonce=%s,"
7732 "nonce=%s,response=%s\r\n",
7733 user, auth_domain, uri, qop, cnonce, nonce, resp);
7734 }
7735
7736 /*
7737 * Check for authentication timeout.
7738 * Clients send time stamp encoded in nonce. Make sure it is not too old,
7739 * to prevent replay attacks.
7740 * Assumption: nonce is a hexadecimal number of seconds since 1970.
7741 */
7742 static int mg_check_nonce(const char *nonce) {
7743 unsigned long now = (unsigned long) mg_time();
7744 unsigned long val = (unsigned long) strtoul(nonce, NULL, 16);
7745 return (now >= val) && (now - val < 60 * 60);
7746 }
7747
7748 int mg_http_check_digest_auth(struct http_message *hm, const char *auth_domain,
7749 FILE *fp) {
7750 int ret = 0;
7751 struct mg_str *hdr;
7752 char username_buf[50], cnonce_buf[64], response_buf[40], uri_buf[200],
7753 qop_buf[20], nc_buf[20], nonce_buf[16];
7754
7755 char *username = username_buf, *cnonce = cnonce_buf, *response = response_buf,
7756 *uri = uri_buf, *qop = qop_buf, *nc = nc_buf, *nonce = nonce_buf;
7757
7758 /* Parse "Authorization:" header, fail fast on parse error */
7759 if (hm == NULL || fp == NULL ||
7760 (hdr = mg_get_http_header(hm, "Authorization")) == NULL ||
7761 mg_http_parse_header2(hdr, "username", &username, sizeof(username_buf)) ==
7762 0 ||
7763 mg_http_parse_header2(hdr, "cnonce", &cnonce, sizeof(cnonce_buf)) == 0 ||
7764 mg_http_parse_header2(hdr, "response", &response, sizeof(response_buf)) ==
7765 0 ||
7766 mg_http_parse_header2(hdr, "uri", &uri, sizeof(uri_buf)) == 0 ||
7767 mg_http_parse_header2(hdr, "qop", &qop, sizeof(qop_buf)) == 0 ||
7768 mg_http_parse_header2(hdr, "nc", &nc, sizeof(nc_buf)) == 0 ||
7769 mg_http_parse_header2(hdr, "nonce", &nonce, sizeof(nonce_buf)) == 0 ||
7770 mg_check_nonce(nonce) == 0) {
7771 ret = 0;
7772 goto clean;
7773 }
7774
7775 /* NOTE(lsm): due to a bug in MSIE, we do not compare URIs */
7776
7777 ret = mg_check_digest_auth(
7778 hm->method,
7779 mg_mk_str_n(
7780 hm->uri.p,
7781 hm->uri.len + (hm->query_string.len ? hm->query_string.len + 1 : 0)),
7782 mg_mk_str(username), mg_mk_str(cnonce), mg_mk_str(response),
7783 mg_mk_str(qop), mg_mk_str(nc), mg_mk_str(nonce), mg_mk_str(auth_domain),
7784 fp);
7785
7786 clean:
7787 if (username != username_buf) MG_FREE(username);
7788 if (cnonce != cnonce_buf) MG_FREE(cnonce);
7789 if (response != response_buf) MG_FREE(response);
7790 if (uri != uri_buf) MG_FREE(uri);
7791 if (qop != qop_buf) MG_FREE(qop);
7792 if (nc != nc_buf) MG_FREE(nc);
7793 if (nonce != nonce_buf) MG_FREE(nonce);
7794
7795 return ret;
7796 }
7797
7798 int mg_check_digest_auth(struct mg_str method, struct mg_str uri,
7799 struct mg_str username, struct mg_str cnonce,
7800 struct mg_str response, struct mg_str qop,
7801 struct mg_str nc, struct mg_str nonce,
7802 struct mg_str auth_domain, FILE *fp) {
7803 char buf[128], f_user[sizeof(buf)], f_ha1[sizeof(buf)], f_domain[sizeof(buf)];
7804 char exp_resp[33];
7805
7806 /*
7807 * Read passwords file line by line. If should have htdigest format,
7808 * i.e. each line should be a colon-separated sequence:
7809 * USER_NAME:DOMAIN_NAME:HA1_HASH_OF_USER_DOMAIN_AND_PASSWORD
7810 */
7811 while (fgets(buf, sizeof(buf), fp) != NULL) {
7812 if (sscanf(buf, "%[^:]:%[^:]:%s", f_user, f_domain, f_ha1) == 3 &&
7813 mg_vcmp(&username, f_user) == 0 &&
7814 mg_vcmp(&auth_domain, f_domain) == 0) {
7815 /* Username and domain matched, check the password */
7816 mg_mkmd5resp(method.p, method.len, uri.p, uri.len, f_ha1, strlen(f_ha1),
7817 nonce.p, nonce.len, nc.p, nc.len, cnonce.p, cnonce.len,
7818 qop.p, qop.len, exp_resp);
7819 LOG(LL_DEBUG, ("%.*s %s %.*s %s", (int) username.len, username.p,
7820 f_domain, (int) response.len, response.p, exp_resp));
7821 return mg_ncasecmp(response.p, exp_resp, strlen(exp_resp)) == 0;
7822 }
7823 }
7824
7825 /* None of the entries in the passwords file matched - return failure */
7826 return 0;
7827 }
7828
7829 int mg_http_is_authorized(struct http_message *hm, struct mg_str path,
7830 const char *domain, const char *passwords_file,
7831 int flags) {
7832 char buf[MG_MAX_PATH];
7833 const char *p;
7834 FILE *fp;
7835 int authorized = 1;
7836
7837 if (domain != NULL && passwords_file != NULL) {
7838 if (flags & MG_AUTH_FLAG_IS_GLOBAL_PASS_FILE) {
7839 fp = mg_fopen(passwords_file, "r");
7840 } else if (flags & MG_AUTH_FLAG_IS_DIRECTORY) {
7841 snprintf(buf, sizeof(buf), "%.*s%c%s", (int) path.len, path.p, DIRSEP,
7842 passwords_file);
7843 fp = mg_fopen(buf, "r");
7844 } else {
7845 p = strrchr(path.p, DIRSEP);
7846 if (p == NULL) p = path.p;
7847 snprintf(buf, sizeof(buf), "%.*s%c%s", (int) (p - path.p), path.p, DIRSEP,
7848 passwords_file);
7849 fp = mg_fopen(buf, "r");
7850 }
7851
7852 if (fp != NULL) {
7853 authorized = mg_http_check_digest_auth(hm, domain, fp);
7854 fclose(fp);
7855 } else if (!(flags & MG_AUTH_FLAG_ALLOW_MISSING_FILE)) {
7856 authorized = 0;
7857 }
7858 }
7859
7860 LOG(LL_DEBUG, ("%.*s %s %x %d", (int) path.len, path.p,
7861 passwords_file ? passwords_file : "", flags, authorized));
7862 return authorized;
7863 }
7864 #else
7865 int mg_http_is_authorized(struct http_message *hm, const struct mg_str path,
7866 const char *domain, const char *passwords_file,
7867 int flags) {
7868 (void) hm;
7869 (void) path;
7870 (void) domain;
7871 (void) passwords_file;
7872 (void) flags;
7873 return 1;
7874 }
7875 #endif
7876
7877 #if MG_ENABLE_DIRECTORY_LISTING
7878 static void mg_escape(const char *src, char *dst, size_t dst_len) {
7879 size_t n = 0;
7880 while (*src != '\0' && n + 5 < dst_len) {
7881 unsigned char ch = *(unsigned char *) src++;
7882 if (ch == '<') {
7883 n += snprintf(dst + n, dst_len - n, "%s", "<");
7884 } else {
7885 dst[n++] = ch;
7886 }
7887 }
7888 dst[n] = '\0';
7889 }
7890
7891 static void mg_print_dir_entry(struct mg_connection *nc, const char *file_name,
7892 cs_stat_t *stp) {
7893 char size[64], mod[64], path[MG_MAX_PATH];
7894 int64_t fsize = stp->st_size;
7895 int is_dir = S_ISDIR(stp->st_mode);
7896 const char *slash = is_dir ? "/" : "";
7897 struct mg_str href;
7898 struct tm tm;
7899
7900 if (is_dir) {
7901 snprintf(size, sizeof(size), "%s", "[DIRECTORY]");
7902 } else {
7903 /*
7904 * We use (double) cast below because MSVC 6 compiler cannot
7905 * convert unsigned __int64 to double.
7906 */
7907 if (fsize < 1024) {
7908 snprintf(size, sizeof(size), "%d", (int) fsize);
7909 } else if (fsize < 0x100000) {
7910 snprintf(size, sizeof(size), "%.1fk", (double) fsize / 1024.0);
7911 } else if (fsize < 0x40000000) {
7912 snprintf(size, sizeof(size), "%.1fM", (double) fsize / 1048576);
7913 } else {
7914 snprintf(size, sizeof(size), "%.1fG", (double) fsize / 1073741824);
7915 }
7916 }
7917 strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", localtime_r(&stp->st_mtime, &tm));
7918 mg_escape(file_name, path, sizeof(path));
7919 href = mg_url_encode(mg_mk_str(file_name));
7920 mg_printf_http_chunk(nc,
7921 "<tr><td><a href=\"%s%s\">%s%s</a></td>"
7922 "<td>%s</td><td name=%" INT64_FMT ">%s</td></tr>\n",
7923 href.p, slash, path, slash, mod, is_dir ? -1 : fsize,
7924 size);
7925 free((void *) href.p);
7926 }
7927
7928 static void mg_scan_directory(struct mg_connection *nc, const char *dir,
7929 const struct mg_serve_http_opts *opts,
7930 void (*func)(struct mg_connection *, const char *,
7931 cs_stat_t *)) {
7932 char path[MG_MAX_PATH + 1];
7933 cs_stat_t st;
7934 struct dirent *dp;
7935 DIR *dirp;
7936
7937 LOG(LL_DEBUG, ("%p [%s]", nc, dir));
7938 if ((dirp = (opendir(dir))) != NULL) {
7939 while ((dp = readdir(dirp)) != NULL) {
7940 /* Do not show current dir and hidden files */
7941 if (mg_is_file_hidden((const char *) dp->d_name, opts, 1)) {
7942 continue;
7943 }
7944 snprintf(path, sizeof(path), "%s/%s", dir, dp->d_name);
7945 if (mg_stat(path, &st) == 0) {
7946 func(nc, (const char *) dp->d_name, &st);
7947 }
7948 }
7949 closedir(dirp);
7950 } else {
7951 LOG(LL_DEBUG, ("%p opendir(%s) -> %d", nc, dir, mg_get_errno()));
7952 }
7953 }
7954
7955 static void mg_send_directory_listing(struct mg_connection *nc, const char *dir,
7956 struct http_message *hm,
7957 struct mg_serve_http_opts *opts) {
7958 static const char *sort_js_code =
7959 "<script>function srt(tb, sc, so, d) {"
7960 "var tr = Array.prototype.slice.call(tb.rows, 0),"
7961 "tr = tr.sort(function (a, b) { var c1 = a.cells[sc], c2 = b.cells[sc],"
7962 "n1 = c1.getAttribute('name'), n2 = c2.getAttribute('name'), "
7963 "t1 = a.cells[2].getAttribute('name'), "
7964 "t2 = b.cells[2].getAttribute('name'); "
7965 "return so * (t1 < 0 && t2 >= 0 ? -1 : t2 < 0 && t1 >= 0 ? 1 : "
7966 "n1 ? parseInt(n2) - parseInt(n1) : "
7967 "c1.textContent.trim().localeCompare(c2.textContent.trim())); });";
7968 static const char *sort_js_code2 =
7969 "for (var i = 0; i < tr.length; i++) tb.appendChild(tr[i]); "
7970 "if (!d) window.location.hash = ('sc=' + sc + '&so=' + so); "
7971 "};"
7972 "window.onload = function() {"
7973 "var tb = document.getElementById('tb');"
7974 "var m = /sc=([012]).so=(1|-1)/.exec(window.location.hash) || [0, 2, 1];"
7975 "var sc = m[1], so = m[2]; document.onclick = function(ev) { "
7976 "var c = ev.target.rel; if (c) {if (c == sc) so *= -1; srt(tb, c, so); "
7977 "sc = c; ev.preventDefault();}};"
7978 "srt(tb, sc, so, true);"
7979 "}"
7980 "</script>";
7981
7982 mg_send_response_line(nc, 200, opts->extra_headers);
7983 mg_printf(nc, "%s: %s\r\n%s: %s\r\n\r\n", "Transfer-Encoding", "chunked",
7984 "Content-Type", "text/html; charset=utf-8");
7985
7986 mg_printf_http_chunk(
7987 nc,
7988 "<html><head><title>Index of %.*s</title>%s%s"
7989 "<style>th,td {text-align: left; padding-right: 1em; "
7990 "font-family: monospace; }</style></head>\n"
7991 "<body><h1>Index of %.*s</h1>\n<table cellpadding=0><thead>"
7992 "<tr><th><a href=# rel=0>Name</a></th><th>"
7993 "<a href=# rel=1>Modified</a</th>"
7994 "<th><a href=# rel=2>Size</a></th></tr>"
7995 "<tr><td colspan=3><hr></td></tr>\n"
7996 "</thead>\n"
7997 "<tbody id=tb>",
7998 (int) hm->uri.len, hm->uri.p, sort_js_code, sort_js_code2,
7999 (int) hm->uri.len, hm->uri.p);
8000 mg_scan_directory(nc, dir, opts, mg_print_dir_entry);
8001 mg_printf_http_chunk(nc,
8002 "</tbody><tr><td colspan=3><hr></td></tr>\n"
8003 "</table>\n"
8004 "<address>%s</address>\n"
8005 "</body></html>",
8006 mg_version_header);
8007 mg_send_http_chunk(nc, "", 0);
8008 /* TODO(rojer): Remove when cesanta/dev/issues/197 is fixed. */
8009 nc->flags |= MG_F_SEND_AND_CLOSE;
8010 }
8011 #endif /* MG_ENABLE_DIRECTORY_LISTING */
8012
8013 /*
8014 * Given a directory path, find one of the files specified in the
8015 * comma-separated list of index files `list`.
8016 * First found index file wins. If an index file is found, then gets
8017 * appended to the `path`, stat-ed, and result of `stat()` passed to `stp`.
8018 * If index file is not found, then `path` and `stp` remain unchanged.
8019 */
8020 MG_INTERNAL void mg_find_index_file(const char *path, const char *list,
8021 char **index_file, cs_stat_t *stp) {
8022 struct mg_str vec;
8023 size_t path_len = strlen(path);
8024 int found = 0;
8025 *index_file = NULL;
8026
8027 /* Traverse index files list. For each entry, append it to the given */
8028 /* path and see if the file exists. If it exists, break the loop */
8029 while ((list = mg_next_comma_list_entry(list, &vec, NULL)) != NULL) {
8030 cs_stat_t st;
8031 size_t len = path_len + 1 + vec.len + 1;
8032 *index_file = (char *) MG_REALLOC(*index_file, len);
8033 if (*index_file == NULL) break;
8034 snprintf(*index_file, len, "%s%c%.*s", path, DIRSEP, (int) vec.len, vec.p);
8035
8036 /* Does it exist? Is it a file? */
8037 if (mg_stat(*index_file, &st) == 0 && S_ISREG(st.st_mode)) {
8038 /* Yes it does, break the loop */
8039 *stp = st;
8040 found = 1;
8041 break;
8042 }
8043 }
8044 if (!found) {
8045 MG_FREE(*index_file);
8046 *index_file = NULL;
8047 }
8048 LOG(LL_DEBUG, ("[%s] [%s]", path, (*index_file ? *index_file : "")));
8049 }
8050
8051 #if MG_ENABLE_HTTP_URL_REWRITES
8052 static int mg_http_send_port_based_redirect(
8053 struct mg_connection *c, struct http_message *hm,
8054 const struct mg_serve_http_opts *opts) {
8055 const char *rewrites = opts->url_rewrites;
8056 struct mg_str a, b;
8057 char local_port[20] = {'%'};
8058
8059 mg_conn_addr_to_str(c, local_port + 1, sizeof(local_port) - 1,
8060 MG_SOCK_STRINGIFY_PORT);
8061
8062 while ((rewrites = mg_next_comma_list_entry(rewrites, &a, &b)) != NULL) {
8063 if (mg_vcmp(&a, local_port) == 0) {
8064 mg_send_response_line(c, 301, NULL);
8065 mg_printf(c, "Content-Length: 0\r\nLocation: %.*s%.*s\r\n\r\n",
8066 (int) b.len, b.p, (int) (hm->proto.p - hm->uri.p - 1),
8067 hm->uri.p);
8068 return 1;
8069 }
8070 }
8071
8072 return 0;
8073 }
8074
8075 static void mg_reverse_proxy_handler(struct mg_connection *nc, int ev,
8076 void *ev_data MG_UD_ARG(void *user_data)) {
8077 struct http_message *hm = (struct http_message *) ev_data;
8078 struct mg_http_proto_data *pd = mg_http_get_proto_data(nc);
8079
8080 if (pd == NULL || pd->reverse_proxy_data.linked_conn == NULL) {
8081 DBG(("%p: upstream closed", nc));
8082 return;
8083 }
8084
8085 switch (ev) {
8086 case MG_EV_CONNECT:
8087 if (*(int *) ev_data != 0) {
8088 mg_http_send_error(pd->reverse_proxy_data.linked_conn, 502, NULL);
8089 }
8090 break;
8091 /* TODO(mkm): handle streaming */
8092 case MG_EV_HTTP_REPLY:
8093 mg_send(pd->reverse_proxy_data.linked_conn, hm->message.p,
8094 hm->message.len);
8095 pd->reverse_proxy_data.linked_conn->flags |= MG_F_SEND_AND_CLOSE;
8096 nc->flags |= MG_F_CLOSE_IMMEDIATELY;
8097 break;
8098 case MG_EV_CLOSE:
8099 pd->reverse_proxy_data.linked_conn->flags |= MG_F_SEND_AND_CLOSE;
8100 break;
8101 }
8102
8103 #if MG_ENABLE_CALLBACK_USERDATA
8104 (void) user_data;
8105 #endif
8106 }
8107
8108 void mg_http_reverse_proxy(struct mg_connection *nc,
8109 const struct http_message *hm, struct mg_str mount,
8110 struct mg_str upstream) {
8111 struct mg_connection *be;
8112 char burl[256], *purl = burl;
8113 int i;
8114 const char *error;
8115 struct mg_connect_opts opts;
8116 struct mg_str path = MG_NULL_STR, user_info = MG_NULL_STR, host = MG_NULL_STR;
8117 memset(&opts, 0, sizeof(opts));
8118 opts.error_string = &error;
8119
8120 mg_asprintf(&purl, sizeof(burl), "%.*s%.*s", (int) upstream.len, upstream.p,
8121 (int) (hm->uri.len - mount.len), hm->uri.p + mount.len);
8122
8123 be = mg_connect_http_base(nc->mgr, MG_CB(mg_reverse_proxy_handler, NULL),
8124 opts, "http", NULL, "https", NULL, purl, &path,
8125 &user_info, &host);
8126 LOG(LL_DEBUG, ("Proxying %.*s to %s (rule: %.*s)", (int) hm->uri.len,
8127 hm->uri.p, purl, (int) mount.len, mount.p));
8128
8129 if (be == NULL) {
8130 LOG(LL_ERROR, ("Error connecting to %s: %s", purl, error));
8131 mg_http_send_error(nc, 502, NULL);
8132 goto cleanup;
8133 }
8134
8135 /* link connections to each other, they must live and die together */
8136 mg_http_get_proto_data(be)->reverse_proxy_data.linked_conn = nc;
8137 mg_http_get_proto_data(nc)->reverse_proxy_data.linked_conn = be;
8138
8139 /* send request upstream */
8140 mg_printf(be, "%.*s %.*s HTTP/1.1\r\n", (int) hm->method.len, hm->method.p,
8141 (int) path.len, path.p);
8142
8143 mg_printf(be, "Host: %.*s\r\n", (int) host.len, host.p);
8144 for (i = 0; i < MG_MAX_HTTP_HEADERS && hm->header_names[i].len > 0; i++) {
8145 struct mg_str hn = hm->header_names[i];
8146 struct mg_str hv = hm->header_values[i];
8147
8148 /* we rewrite the host header */
8149 if (mg_vcasecmp(&hn, "Host") == 0) continue;
8150 /*
8151 * Don't pass chunked transfer encoding to the client because hm->body is
8152 * already dechunked when we arrive here.
8153 */
8154 if (mg_vcasecmp(&hn, "Transfer-encoding") == 0 &&
8155 mg_vcasecmp(&hv, "chunked") == 0) {
8156 mg_printf(be, "Content-Length: %" SIZE_T_FMT "\r\n", hm->body.len);
8157 continue;
8158 }
8159 /* We don't support proxying Expect: 100-continue. */
8160 if (mg_vcasecmp(&hn, "Expect") == 0 &&
8161 mg_vcasecmp(&hv, "100-continue") == 0) {
8162 continue;
8163 }
8164
8165 mg_printf(be, "%.*s: %.*s\r\n", (int) hn.len, hn.p, (int) hv.len, hv.p);
8166 }
8167
8168 mg_send(be, "\r\n", 2);
8169 mg_send(be, hm->body.p, hm->body.len);
8170
8171 cleanup:
8172 if (purl != burl) MG_FREE(purl);
8173 }
8174
8175 static int mg_http_handle_forwarding(struct mg_connection *nc,
8176 struct http_message *hm,
8177 const struct mg_serve_http_opts *opts) {
8178 const char *rewrites = opts->url_rewrites;
8179 struct mg_str a, b;
8180 struct mg_str p1 = MG_MK_STR("http://"), p2 = MG_MK_STR("https://");
8181
8182 while ((rewrites = mg_next_comma_list_entry(rewrites, &a, &b)) != NULL) {
8183 if (mg_strncmp(a, hm->uri, a.len) == 0) {
8184 if (mg_strncmp(b, p1, p1.len) == 0 || mg_strncmp(b, p2, p2.len) == 0) {
8185 mg_http_reverse_proxy(nc, hm, a, b);
8186 return 1;
8187 }
8188 }
8189 }
8190
8191 return 0;
8192 }
8193 #endif /* MG_ENABLE_FILESYSTEM */
8194
8195 MG_INTERNAL int mg_uri_to_local_path(struct http_message *hm,
8196 const struct mg_serve_http_opts *opts,
8197 char **local_path,
8198 struct mg_str *remainder) {
8199 int ok = 1;
8200 const char *cp = hm->uri.p, *cp_end = hm->uri.p + hm->uri.len;
8201 struct mg_str root = {NULL, 0};
8202 const char *file_uri_start = cp;
8203 *local_path = NULL;
8204 remainder->p = NULL;
8205 remainder->len = 0;
8206
8207 { /* 1. Determine which root to use. */
8208
8209 #if MG_ENABLE_HTTP_URL_REWRITES
8210 const char *rewrites = opts->url_rewrites;
8211 #else
8212 const char *rewrites = "";
8213 #endif
8214 struct mg_str *hh = mg_get_http_header(hm, "Host");
8215 struct mg_str a, b;
8216 /* Check rewrites first. */
8217 while ((rewrites = mg_next_comma_list_entry(rewrites, &a, &b)) != NULL) {
8218 if (a.len > 1 && a.p[0] == '@') {
8219 /* Host rewrite. */
8220 if (hh != NULL && hh->len == a.len - 1 &&
8221 mg_ncasecmp(a.p + 1, hh->p, a.len - 1) == 0) {
8222 root = b;
8223 break;
8224 }
8225 } else {
8226 /* Regular rewrite, URI=directory */
8227 size_t match_len = mg_match_prefix_n(a, hm->uri);
8228 if (match_len > 0) {
8229 file_uri_start = hm->uri.p + match_len;
8230 if (*file_uri_start == '/' || file_uri_start == cp_end) {
8231 /* Match ended at component boundary, ok. */
8232 } else if (*(file_uri_start - 1) == '/') {
8233 /* Pattern ends with '/', backtrack. */
8234 file_uri_start--;
8235 } else {
8236 /* No match: must fall on the component boundary. */
8237 continue;
8238 }
8239 root = b;
8240 break;
8241 }
8242 }
8243 }
8244 /* If no rewrite rules matched, use DAV or regular document root. */
8245 if (root.p == NULL) {
8246 #if MG_ENABLE_HTTP_WEBDAV
8247 if (opts->dav_document_root != NULL && mg_is_dav_request(&hm->method)) {
8248 root.p = opts->dav_document_root;
8249 root.len = strlen(opts->dav_document_root);
8250 } else
8251 #endif
8252 {
8253 root.p = opts->document_root;
8254 root.len = strlen(opts->document_root);
8255 }
8256 }
8257 assert(root.p != NULL && root.len > 0);
8258 }
8259
8260 { /* 2. Find where in the canonical URI path the local path ends. */
8261 const char *u = file_uri_start + 1;
8262 char *lp = (char *) MG_MALLOC(root.len + hm->uri.len + 1);
8263 char *lp_end = lp + root.len + hm->uri.len + 1;
8264 char *p = lp, *ps;
8265 int exists = 1;
8266 if (lp == NULL) {
8267 ok = 0;
8268 goto out;
8269 }
8270 memcpy(p, root.p, root.len);
8271 p += root.len;
8272 if (*(p - 1) == DIRSEP) p--;
8273 *p = '\0';
8274 ps = p;
8275
8276 /* Chop off URI path components one by one and build local path. */
8277 while (u <= cp_end) {
8278 const char *next = u;
8279 struct mg_str component;
8280 if (exists) {
8281 cs_stat_t st;
8282 exists = (mg_stat(lp, &st) == 0);
8283 if (exists && S_ISREG(st.st_mode)) {
8284 /* We found the terminal, the rest of the URI (if any) is path_info.
8285 */
8286 if (*(u - 1) == '/') u--;
8287 break;
8288 }
8289 }
8290 if (u >= cp_end) break;
8291 parse_uri_component((const char **) &next, cp_end, "/", &component);
8292 if (component.len > 0) {
8293 int len;
8294 memmove(p + 1, component.p, component.len);
8295 len = mg_url_decode(p + 1, component.len, p + 1, lp_end - p - 1, 0);
8296 if (len <= 0) {
8297 ok = 0;
8298 break;
8299 }
8300 component.p = p + 1;
8301 component.len = len;
8302 if (mg_vcmp(&component, ".") == 0) {
8303 /* Yum. */
8304 } else if (mg_vcmp(&component, "..") == 0) {
8305 while (p > ps && *p != DIRSEP) p--;
8306 *p = '\0';
8307 } else {
8308 size_t i;
8309 #ifdef _WIN32
8310 /* On Windows, make sure it's valid Unicode (no funny stuff). */
8311 wchar_t buf[MG_MAX_PATH * 2];
8312 if (to_wchar(component.p, buf, MG_MAX_PATH) == 0) {
8313 DBG(("[%.*s] smells funny", (int) component.len, component.p));
8314 ok = 0;
8315 break;
8316 }
8317 #endif
8318 *p++ = DIRSEP;
8319 /* No NULs and DIRSEPs in the component (percent-encoded). */
8320 for (i = 0; i < component.len; i++, p++) {
8321 if (*p == '\0' || *p == DIRSEP
8322 #ifdef _WIN32
8323 /* On Windows, "/" is also accepted, so check for that too. */
8324 ||
8325 *p == '/'
8326 #endif
8327 ) {
8328 ok = 0;
8329 break;
8330 }
8331 }
8332 }
8333 }
8334 u = next;
8335 }
8336 if (ok) {
8337 *local_path = lp;
8338 if (u > cp_end) u = cp_end;
8339 remainder->p = u;
8340 remainder->len = cp_end - u;
8341 } else {
8342 MG_FREE(lp);
8343 }
8344 }
8345
8346 out:
8347 LOG(LL_DEBUG,
8348 ("'%.*s' -> '%s' + '%.*s'", (int) hm->uri.len, hm->uri.p,
8349 *local_path ? *local_path : "", (int) remainder->len, remainder->p));
8350 return ok;
8351 }
8352
8353 static int mg_get_month_index(const char *s) {
8354 static const char *month_names[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
8355 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
8356 size_t i;
8357
8358 for (i = 0; i < ARRAY_SIZE(month_names); i++)
8359 if (!strcmp(s, month_names[i])) return (int) i;
8360
8361 return -1;
8362 }
8363
8364 static int mg_num_leap_years(int year) {
8365 return year / 4 - year / 100 + year / 400;
8366 }
8367
8368 /* Parse UTC date-time string, and return the corresponding time_t value. */
8369 MG_INTERNAL time_t mg_parse_date_string(const char *datetime) {
8370 static const unsigned short days_before_month[] = {
8371 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};
8372 char month_str[32];
8373 int second, minute, hour, day, month, year, leap_days, days;
8374 time_t result = (time_t) 0;
8375
8376 if (((sscanf(datetime, "%d/%3s/%d %d:%d:%d", &day, month_str, &year, &hour,
8377 &minute, &second) == 6) ||
8378 (sscanf(datetime, "%d %3s %d %d:%d:%d", &day, month_str, &year, &hour,
8379 &minute, &second) == 6) ||
8380 (sscanf(datetime, "%*3s, %d %3s %d %d:%d:%d", &day, month_str, &year,
8381 &hour, &minute, &second) == 6) ||
8382 (sscanf(datetime, "%d-%3s-%d %d:%d:%d", &day, month_str, &year, &hour,
8383 &minute, &second) == 6)) &&
8384 year > 1970 && (month = mg_get_month_index(month_str)) != -1) {
8385 leap_days = mg_num_leap_years(year) - mg_num_leap_years(1970);
8386 year -= 1970;
8387 days = year * 365 + days_before_month[month] + (day - 1) + leap_days;
8388 result = days * 24 * 3600 + hour * 3600 + minute * 60 + second;
8389 }
8390
8391 return result;
8392 }
8393
8394 MG_INTERNAL int mg_is_not_modified(struct http_message *hm, cs_stat_t *st) {
8395 struct mg_str *hdr;
8396 if ((hdr = mg_get_http_header(hm, "If-None-Match")) != NULL) {
8397 char etag[64];
8398 mg_http_construct_etag(etag, sizeof(etag), st);
8399 return mg_vcasecmp(hdr, etag) == 0;
8400 } else if ((hdr = mg_get_http_header(hm, "If-Modified-Since")) != NULL) {
8401 return st->st_mtime <= mg_parse_date_string(hdr->p);
8402 } else {
8403 return 0;
8404 }
8405 }
8406
8407 void mg_http_send_digest_auth_request(struct mg_connection *c,
8408 const char *domain) {
8409 mg_printf(c,
8410 "HTTP/1.1 401 Unauthorized\r\n"
8411 "WWW-Authenticate: Digest qop=\"auth\", "
8412 "realm=\"%s\", nonce=\"%lx\"\r\n"
8413 "Content-Length: 0\r\n\r\n",
8414 domain, (unsigned long) mg_time());
8415 }
8416
8417 static void mg_http_send_options(struct mg_connection *nc,
8418 struct mg_serve_http_opts *opts) {
8419 mg_send_response_line(nc, 200, opts->extra_headers);
8420 mg_printf(nc, "%s",
8421 "Allow: GET, POST, HEAD, CONNECT, OPTIONS"
8422 #if MG_ENABLE_HTTP_WEBDAV
8423 ", MKCOL, PUT, DELETE, PROPFIND, MOVE\r\nDAV: 1,2"
8424 #endif
8425 "\r\n\r\n");
8426 nc->flags |= MG_F_SEND_AND_CLOSE;
8427 }
8428
8429 static int mg_is_creation_request(const struct http_message *hm) {
8430 return mg_vcmp(&hm->method, "MKCOL") == 0 || mg_vcmp(&hm->method, "PUT") == 0;
8431 }
8432
8433 MG_INTERNAL void mg_send_http_file(struct mg_connection *nc, char *path,
8434 const struct mg_str *path_info,
8435 struct http_message *hm,
8436 struct mg_serve_http_opts *opts) {
8437 int exists, is_directory, is_cgi;
8438 #if MG_ENABLE_HTTP_WEBDAV
8439 int is_dav = mg_is_dav_request(&hm->method);
8440 #else
8441 int is_dav = 0;
8442 #endif
8443 char *index_file = NULL;
8444 cs_stat_t st;
8445
8446 exists = (mg_stat(path, &st) == 0);
8447 is_directory = exists && S_ISDIR(st.st_mode);
8448
8449 if (is_directory)
8450 mg_find_index_file(path, opts->index_files, &index_file, &st);
8451
8452 is_cgi =
8453 (mg_match_prefix(opts->cgi_file_pattern, strlen(opts->cgi_file_pattern),
8454 index_file ? index_file : path) > 0);
8455
8456 LOG(LL_DEBUG,
8457 ("%p %.*s [%s] exists=%d is_dir=%d is_dav=%d is_cgi=%d index=%s", nc,
8458 (int) hm->method.len, hm->method.p, path, exists, is_directory, is_dav,
8459 is_cgi, index_file ? index_file : ""));
8460
8461 if (is_directory && hm->uri.p[hm->uri.len - 1] != '/' && !is_dav) {
8462 mg_printf(nc,
8463 "HTTP/1.1 301 Moved\r\nLocation: %.*s/\r\n"
8464 "Content-Length: 0\r\n\r\n",
8465 (int) hm->uri.len, hm->uri.p);
8466 MG_FREE(index_file);
8467 return;
8468 }
8469
8470 /* If we have path_info, the only way to handle it is CGI. */
8471 if (path_info->len > 0 && !is_cgi) {
8472 mg_http_send_error(nc, 501, NULL);
8473 MG_FREE(index_file);
8474 return;
8475 }
8476
8477 if (is_dav && opts->dav_document_root == NULL) {
8478 mg_http_send_error(nc, 501, NULL);
8479 } else if (!mg_http_is_authorized(
8480 hm, mg_mk_str(path), opts->auth_domain, opts->global_auth_file,
8481 ((is_directory ? MG_AUTH_FLAG_IS_DIRECTORY : 0) |
8482 MG_AUTH_FLAG_IS_GLOBAL_PASS_FILE |
8483 MG_AUTH_FLAG_ALLOW_MISSING_FILE)) ||
8484 !mg_http_is_authorized(
8485 hm, mg_mk_str(path), opts->auth_domain,
8486 opts->per_directory_auth_file,
8487 ((is_directory ? MG_AUTH_FLAG_IS_DIRECTORY : 0) |
8488 MG_AUTH_FLAG_ALLOW_MISSING_FILE))) {
8489 mg_http_send_digest_auth_request(nc, opts->auth_domain);
8490 } else if (is_cgi) {
8491 #if MG_ENABLE_HTTP_CGI
8492 mg_handle_cgi(nc, index_file ? index_file : path, path_info, hm, opts);
8493 #else
8494 mg_http_send_error(nc, 501, NULL);
8495 #endif /* MG_ENABLE_HTTP_CGI */
8496 } else if ((!exists ||
8497 mg_is_file_hidden(path, opts, 0 /* specials are ok */)) &&
8498 !mg_is_creation_request(hm)) {
8499 mg_http_send_error(nc, 404, NULL);
8500 #if MG_ENABLE_HTTP_WEBDAV
8501 } else if (!mg_vcmp(&hm->method, "PROPFIND")) {
8502 mg_handle_propfind(nc, path, &st, hm, opts);
8503 #if !MG_DISABLE_DAV_AUTH
8504 } else if (is_dav &&
8505 (opts->dav_auth_file == NULL ||
8506 (strcmp(opts->dav_auth_file, "-") != 0 &&
8507 !mg_http_is_authorized(
8508 hm, mg_mk_str(path), opts->auth_domain, opts->dav_auth_file,
8509 ((is_directory ? MG_AUTH_FLAG_IS_DIRECTORY : 0) |
8510 MG_AUTH_FLAG_IS_GLOBAL_PASS_FILE |
8511 MG_AUTH_FLAG_ALLOW_MISSING_FILE))))) {
8512 mg_http_send_digest_auth_request(nc, opts->auth_domain);
8513 #endif
8514 } else if (!mg_vcmp(&hm->method, "MKCOL")) {
8515 mg_handle_mkcol(nc, path, hm);
8516 } else if (!mg_vcmp(&hm->method, "DELETE")) {
8517 mg_handle_delete(nc, opts, path);
8518 } else if (!mg_vcmp(&hm->method, "PUT")) {
8519 mg_handle_put(nc, path, hm);
8520 } else if (!mg_vcmp(&hm->method, "MOVE")) {
8521 mg_handle_move(nc, opts, path, hm);
8522 #if MG_ENABLE_FAKE_DAVLOCK
8523 } else if (!mg_vcmp(&hm->method, "LOCK")) {
8524 mg_handle_lock(nc, path);
8525 #endif
8526 #endif /* MG_ENABLE_HTTP_WEBDAV */
8527 } else if (!mg_vcmp(&hm->method, "OPTIONS")) {
8528 mg_http_send_options(nc, opts);
8529 } else if (is_directory && index_file == NULL) {
8530 #if MG_ENABLE_DIRECTORY_LISTING
8531 if (strcmp(opts->enable_directory_listing, "yes") == 0) {
8532 mg_send_directory_listing(nc, path, hm, opts);
8533 } else {
8534 mg_http_send_error(nc, 403, NULL);
8535 }
8536 #else
8537 mg_http_send_error(nc, 501, NULL);
8538 #endif
8539 } else if (mg_is_not_modified(hm, &st)) {
8540 mg_http_send_error(nc, 304, "Not Modified");
8541 } else {
8542 mg_http_serve_file2(nc, index_file ? index_file : path, hm, opts);
8543 }
8544 MG_FREE(index_file);
8545 }
8546
8547 void mg_serve_http(struct mg_connection *nc, struct http_message *hm,
8548 struct mg_serve_http_opts opts) {
8549 char *path = NULL;
8550 struct mg_str *hdr, path_info;
8551 uint32_t remote_ip = ntohl(*(uint32_t *) &nc->sa.sin.sin_addr);
8552
8553 if (mg_check_ip_acl(opts.ip_acl, remote_ip) != 1) {
8554 /* Not allowed to connect */
8555 mg_http_send_error(nc, 403, NULL);
8556 nc->flags |= MG_F_SEND_AND_CLOSE;
8557 return;
8558 }
8559
8560 #if MG_ENABLE_HTTP_URL_REWRITES
8561 if (mg_http_handle_forwarding(nc, hm, &opts)) {
8562 return;
8563 }
8564
8565 if (mg_http_send_port_based_redirect(nc, hm, &opts)) {
8566 return;
8567 }
8568 #endif
8569
8570 if (opts.document_root == NULL) {
8571 opts.document_root = ".";
8572 }
8573 if (opts.per_directory_auth_file == NULL) {
8574 opts.per_directory_auth_file = ".htpasswd";
8575 }
8576 if (opts.enable_directory_listing == NULL) {
8577 opts.enable_directory_listing = "yes";
8578 }
8579 if (opts.cgi_file_pattern == NULL) {
8580 opts.cgi_file_pattern = "**.cgi$|**.php$";
8581 }
8582 if (opts.ssi_pattern == NULL) {
8583 opts.ssi_pattern = "**.shtml$|**.shtm$";
8584 }
8585 if (opts.index_files == NULL) {
8586 opts.index_files = "index.html,index.htm,index.shtml,index.cgi,index.php";
8587 }
8588 /* Normalize path - resolve "." and ".." (in-place). */
8589 if (!mg_normalize_uri_path(&hm->uri, &hm->uri)) {
8590 mg_http_send_error(nc, 400, NULL);
8591 return;
8592 }
8593 if (mg_uri_to_local_path(hm, &opts, &path, &path_info) == 0) {
8594 mg_http_send_error(nc, 404, NULL);
8595 return;
8596 }
8597 mg_send_http_file(nc, path, &path_info, hm, &opts);
8598
8599 MG_FREE(path);
8600 path = NULL;
8601
8602 /* Close connection for non-keep-alive requests */
8603 if (mg_vcmp(&hm->proto, "HTTP/1.1") != 0 ||
8604 ((hdr = mg_get_http_header(hm, "Connection")) != NULL &&
8605 mg_vcmp(hdr, "keep-alive") != 0)) {
8606 #if 0
8607 nc->flags |= MG_F_SEND_AND_CLOSE;
8608 #endif
8609 }
8610 }
8611
8612 #if MG_ENABLE_HTTP_STREAMING_MULTIPART
8613 void mg_file_upload_handler(struct mg_connection *nc, int ev, void *ev_data,
8614 mg_fu_fname_fn local_name_fn
8615 MG_UD_ARG(void *user_data)) {
8616 switch (ev) {
8617 case MG_EV_HTTP_PART_BEGIN: {
8618 struct mg_http_multipart_part *mp =
8619 (struct mg_http_multipart_part *) ev_data;
8620 struct file_upload_state *fus;
8621 struct mg_str lfn = local_name_fn(nc, mg_mk_str(mp->file_name));
8622 mp->user_data = NULL;
8623 if (lfn.p == NULL || lfn.len == 0) {
8624 LOG(LL_ERROR, ("%p Not allowed to upload %s", nc, mp->file_name));
8625 mg_printf(nc,
8626 "HTTP/1.1 403 Not Allowed\r\n"
8627 "Content-Type: text/plain\r\n"
8628 "Connection: close\r\n\r\n"
8629 "Not allowed to upload %s\r\n",
8630 mp->file_name);
8631 nc->flags |= MG_F_SEND_AND_CLOSE;
8632 return;
8633 }
8634 fus = (struct file_upload_state *) MG_CALLOC(1, sizeof(*fus));
8635 if (fus == NULL) {
8636 nc->flags |= MG_F_CLOSE_IMMEDIATELY;
8637 return;
8638 }
8639 fus->lfn = (char *) MG_MALLOC(lfn.len + 1);
8640 memcpy(fus->lfn, lfn.p, lfn.len);
8641 fus->lfn[lfn.len] = '\0';
8642 if (lfn.p != mp->file_name) MG_FREE((char *) lfn.p);
8643 LOG(LL_DEBUG,
8644 ("%p Receiving file %s -> %s", nc, mp->file_name, fus->lfn));
8645 fus->fp = mg_fopen(fus->lfn, "wb");
8646 if (fus->fp == NULL) {
8647 mg_printf(nc,
8648 "HTTP/1.1 500 Internal Server Error\r\n"
8649 "Content-Type: text/plain\r\n"
8650 "Connection: close\r\n\r\n");
8651 LOG(LL_ERROR, ("Failed to open %s: %d\n", fus->lfn, mg_get_errno()));
8652 mg_printf(nc, "Failed to open %s: %d\n", fus->lfn, mg_get_errno());
8653 /* Do not close the connection just yet, discard remainder of the data.
8654 * This is because at the time of writing some browsers (Chrome) fail to
8655 * render response before all the data is sent. */
8656 }
8657 mp->user_data = (void *) fus;
8658 break;
8659 }
8660 case MG_EV_HTTP_PART_DATA: {
8661 struct mg_http_multipart_part *mp =
8662 (struct mg_http_multipart_part *) ev_data;
8663 struct file_upload_state *fus =
8664 (struct file_upload_state *) mp->user_data;
8665 if (fus == NULL || fus->fp == NULL) break;
8666 if (mg_fwrite(mp->data.p, 1, mp->data.len, fus->fp) != mp->data.len) {
8667 LOG(LL_ERROR, ("Failed to write to %s: %d, wrote %d", fus->lfn,
8668 mg_get_errno(), (int) fus->num_recd));
8669 if (mg_get_errno() == ENOSPC
8670 #ifdef SPIFFS_ERR_FULL
8671 || mg_get_errno() == SPIFFS_ERR_FULL
8672 #endif
8673 ) {
8674 mg_printf(nc,
8675 "HTTP/1.1 413 Payload Too Large\r\n"
8676 "Content-Type: text/plain\r\n"
8677 "Connection: close\r\n\r\n");
8678 mg_printf(nc, "Failed to write to %s: no space left; wrote %d\r\n",
8679 fus->lfn, (int) fus->num_recd);
8680 } else {
8681 mg_printf(nc,
8682 "HTTP/1.1 500 Internal Server Error\r\n"
8683 "Content-Type: text/plain\r\n"
8684 "Connection: close\r\n\r\n");
8685 mg_printf(nc, "Failed to write to %s: %d, wrote %d", mp->file_name,
8686 mg_get_errno(), (int) fus->num_recd);
8687 }
8688 fclose(fus->fp);
8689 remove(fus->lfn);
8690 fus->fp = NULL;
8691 /* Do not close the connection just yet, discard remainder of the data.
8692 * This is because at the time of writing some browsers (Chrome) fail to
8693 * render response before all the data is sent. */
8694 return;
8695 }
8696 fus->num_recd += mp->data.len;
8697 LOG(LL_DEBUG, ("%p rec'd %d bytes, %d total", nc, (int) mp->data.len,
8698 (int) fus->num_recd));
8699 break;
8700 }
8701 case MG_EV_HTTP_PART_END: {
8702 struct mg_http_multipart_part *mp =
8703 (struct mg_http_multipart_part *) ev_data;
8704 struct file_upload_state *fus =
8705 (struct file_upload_state *) mp->user_data;
8706 if (fus == NULL) break;
8707 if (mp->status >= 0 && fus->fp != NULL) {
8708 LOG(LL_DEBUG, ("%p Uploaded %s (%s), %d bytes", nc, mp->file_name,
8709 fus->lfn, (int) fus->num_recd));
8710 } else {
8711 LOG(LL_ERROR, ("Failed to store %s (%s)", mp->file_name, fus->lfn));
8712 /*
8713 * mp->status < 0 means connection was terminated, so no reason to send
8714 * HTTP reply
8715 */
8716 }
8717 if (fus->fp != NULL) fclose(fus->fp);
8718 MG_FREE(fus->lfn);
8719 MG_FREE(fus);
8720 mp->user_data = NULL;
8721 /* Don't close the connection yet, there may be more files to come. */
8722 break;
8723 }
8724 case MG_EV_HTTP_MULTIPART_REQUEST_END: {
8725 mg_printf(nc,
8726 "HTTP/1.1 200 OK\r\n"
8727 "Content-Type: text/plain\r\n"
8728 "Connection: close\r\n\r\n"
8729 "Ok.\r\n");
8730 nc->flags |= MG_F_SEND_AND_CLOSE;
8731 break;
8732 }
8733 }
8734
8735 #if MG_ENABLE_CALLBACK_USERDATA
8736 (void) user_data;
8737 #endif
8738 }
8739
8740 #endif /* MG_ENABLE_HTTP_STREAMING_MULTIPART */
8741 #endif /* MG_ENABLE_FILESYSTEM */
8742
8743 struct mg_connection *mg_connect_http_base(
8744 struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data),
8745 struct mg_connect_opts opts, const char *scheme1, const char *scheme2,
8746 const char *scheme_ssl1, const char *scheme_ssl2, const char *url,
8747 struct mg_str *path, struct mg_str *user_info, struct mg_str *host) {
8748 struct mg_connection *nc = NULL;
8749 unsigned int port_i = 0;
8750 int use_ssl = 0;
8751 struct mg_str scheme, query, fragment;
8752 char conn_addr_buf[2];
8753 char *conn_addr = conn_addr_buf;
8754
8755 if (mg_parse_uri(mg_mk_str(url), &scheme, user_info, host, &port_i, path,
8756 &query, &fragment) != 0) {
8757 MG_SET_PTRPTR(opts.error_string, "cannot parse url");
8758 goto out;
8759 }
8760
8761 /* If query is present, do not strip it. Pass to the caller. */
8762 if (query.len > 0) path->len += query.len + 1;
8763
8764 if (scheme.len == 0 || mg_vcmp(&scheme, scheme1) == 0 ||
8765 (scheme2 != NULL && mg_vcmp(&scheme, scheme2) == 0)) {
8766 use_ssl = 0;
8767 if (port_i == 0) port_i = 80;
8768 } else if (mg_vcmp(&scheme, scheme_ssl1) == 0 ||
8769 (scheme2 != NULL && mg_vcmp(&scheme, scheme_ssl2) == 0)) {
8770 use_ssl = 1;
8771 if (port_i == 0) port_i = 443;
8772 } else {
8773 goto out;
8774 }
8775
8776 mg_asprintf(&conn_addr, sizeof(conn_addr_buf), "tcp://%.*s:%u",
8777 (int) host->len, host->p, port_i);
8778 if (conn_addr == NULL) goto out;
8779
8780 LOG(LL_DEBUG, ("%s use_ssl? %d %s", url, use_ssl, conn_addr));
8781 if (use_ssl) {
8782 #if MG_ENABLE_SSL
8783 /*
8784 * Schema requires SSL, but no SSL parameters were provided in opts.
8785 * In order to maintain backward compatibility, use a faux-SSL with no
8786 * verification.
8787 */
8788 if (opts.ssl_ca_cert == NULL) {
8789 opts.ssl_ca_cert = "*";
8790 }
8791 #else
8792 MG_SET_PTRPTR(opts.error_string, "ssl is disabled");
8793 goto out;
8794 #endif
8795 }
8796
8797 if ((nc = mg_connect_opt(mgr, conn_addr, MG_CB(ev_handler, user_data),
8798 opts)) != NULL) {
8799 mg_set_protocol_http_websocket(nc);
8800 }
8801
8802 out:
8803 if (conn_addr != NULL && conn_addr != conn_addr_buf) MG_FREE(conn_addr);
8804 return nc;
8805 }
8806
8807 struct mg_connection *mg_connect_http_opt(
8808 struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data),
8809 struct mg_connect_opts opts, const char *url, const char *extra_headers,
8810 const char *post_data) {
8811 struct mg_str user = MG_NULL_STR, null_str = MG_NULL_STR;
8812 struct mg_str host = MG_NULL_STR, path = MG_NULL_STR;
8813 struct mbuf auth;
8814 struct mg_connection *nc =
8815 mg_connect_http_base(mgr, MG_CB(ev_handler, user_data), opts, "http",
8816 NULL, "https", NULL, url, &path, &user, &host);
8817
8818 if (nc == NULL) {
8819 return NULL;
8820 }
8821
8822 mbuf_init(&auth, 0);
8823 if (user.len > 0) {
8824 mg_basic_auth_header(user, null_str, &auth);
8825 }
8826
8827 if (post_data == NULL) post_data = "";
8828 if (extra_headers == NULL) extra_headers = "";
8829 if (path.len == 0) path = mg_mk_str("/");
8830 if (host.len == 0) host = mg_mk_str("");
8831
8832 mg_printf(nc, "%s %.*s HTTP/1.1\r\nHost: %.*s\r\nContent-Length: %" SIZE_T_FMT
8833 "\r\n%.*s%s\r\n%s",
8834 (post_data[0] == '\0' ? "GET" : "POST"), (int) path.len, path.p,
8835 (int) (path.p - host.p), host.p, strlen(post_data), (int) auth.len,
8836 (auth.buf == NULL ? "" : auth.buf), extra_headers, post_data);
8837
8838 mbuf_free(&auth);
8839 return nc;
8840 }
8841
8842 struct mg_connection *mg_connect_http(
8843 struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data),
8844 const char *url, const char *extra_headers, const char *post_data) {
8845 struct mg_connect_opts opts;
8846 memset(&opts, 0, sizeof(opts));
8847 return mg_connect_http_opt(mgr, MG_CB(ev_handler, user_data), opts, url,
8848 extra_headers, post_data);
8849 }
8850
8851 size_t mg_parse_multipart(const char *buf, size_t buf_len, char *var_name,
8852 size_t var_name_len, char *file_name,
8853 size_t file_name_len, const char **data,
8854 size_t *data_len) {
8855 static const char cd[] = "Content-Disposition: ";
8856 size_t hl, bl, n, ll, pos, cdl = sizeof(cd) - 1;
8857 int shl;
8858
8859 if (buf == NULL || buf_len <= 0) return 0;
8860 if ((shl = mg_http_get_request_len(buf, buf_len)) <= 0) return 0;
8861 hl = shl;
8862 if (buf[0] != '-' || buf[1] != '-' || buf[2] == '\n') return 0;
8863
8864 /* Get boundary length */
8865 bl = mg_get_line_len(buf, buf_len);
8866
8867 /* Loop through headers, fetch variable name and file name */
8868 var_name[0] = file_name[0] = '\0';
8869 for (n = bl; (ll = mg_get_line_len(buf + n, hl - n)) > 0; n += ll) {
8870 if (mg_ncasecmp(cd, buf + n, cdl) == 0) {
8871 struct mg_str header;
8872 header.p = buf + n + cdl;
8873 header.len = ll - (cdl + 2);
8874 {
8875 char *var_name2 = var_name;
8876 mg_http_parse_header2(&header, "name", &var_name2, var_name_len);
8877 /* TODO: handle reallocated buffer correctly */
8878 if (var_name2 != var_name) {
8879 MG_FREE(var_name2);
8880 var_name[0] = '\0';
8881 }
8882 }
8883 {
8884 char *file_name2 = file_name;
8885 mg_http_parse_header2(&header, "filename", &file_name2, file_name_len);
8886 /* TODO: handle reallocated buffer correctly */
8887 if (file_name2 != file_name) {
8888 MG_FREE(file_name2);
8889 file_name[0] = '\0';
8890 }
8891 }
8892 }
8893 }
8894
8895 /* Scan through the body, search for terminating boundary */
8896 for (pos = hl; pos + (bl - 2) < buf_len; pos++) {
8897 if (buf[pos] == '-' && !strncmp(buf, &buf[pos], bl - 2)) {
8898 if (data_len != NULL) *data_len = (pos - 2) - hl;
8899 if (data != NULL) *data = buf + hl;
8900 return pos;
8901 }
8902 }
8903
8904 return 0;
8905 }
8906
8907 void mg_register_http_endpoint_opt(struct mg_connection *nc,
8908 const char *uri_path,
8909 mg_event_handler_t handler,
8910 struct mg_http_endpoint_opts opts) {
8911 struct mg_http_proto_data *pd = NULL;
8912 struct mg_http_endpoint *new_ep = NULL;
8913
8914 if (nc == NULL) return;
8915 new_ep = (struct mg_http_endpoint *) MG_CALLOC(1, sizeof(*new_ep));
8916 if (new_ep == NULL) return;
8917
8918 pd = mg_http_get_proto_data(nc);
8919 if (pd == NULL) pd = mg_http_create_proto_data(nc);
8920 new_ep->uri_pattern = mg_strdup(mg_mk_str(uri_path));
8921 if (opts.auth_domain != NULL && opts.auth_file != NULL) {
8922 new_ep->auth_domain = strdup(opts.auth_domain);
8923 new_ep->auth_file = strdup(opts.auth_file);
8924 }
8925 new_ep->handler = handler;
8926 #if MG_ENABLE_CALLBACK_USERDATA
8927 new_ep->user_data = opts.user_data;
8928 #endif
8929 new_ep->next = pd->endpoints;
8930 pd->endpoints = new_ep;
8931 }
8932
8933 static void mg_http_call_endpoint_handler(struct mg_connection *nc, int ev,
8934 struct http_message *hm) {
8935 struct mg_http_proto_data *pd = mg_http_get_proto_data(nc);
8936 void *user_data = nc->user_data;
8937
8938 if (ev == MG_EV_HTTP_REQUEST
8939 #if MG_ENABLE_HTTP_STREAMING_MULTIPART
8940 || ev == MG_EV_HTTP_MULTIPART_REQUEST
8941 #endif
8942 ) {
8943 struct mg_http_endpoint *ep =
8944 mg_http_get_endpoint_handler(nc->listener, &hm->uri);
8945 if (ep != NULL) {
8946 #if MG_ENABLE_FILESYSTEM && !MG_DISABLE_HTTP_DIGEST_AUTH
8947 if (!mg_http_is_authorized(hm, hm->uri, ep->auth_domain, ep->auth_file,
8948 MG_AUTH_FLAG_IS_GLOBAL_PASS_FILE)) {
8949 mg_http_send_digest_auth_request(nc, ep->auth_domain);
8950 return;
8951 }
8952 #endif
8953 pd->endpoint_handler = ep->handler;
8954 #if MG_ENABLE_CALLBACK_USERDATA
8955 user_data = ep->user_data;
8956 #endif
8957 }
8958 }
8959 mg_call(nc, pd->endpoint_handler ? pd->endpoint_handler : nc->handler,
8960 user_data, ev, hm);
8961 }
8962
8963 void mg_register_http_endpoint(struct mg_connection *nc, const char *uri_path,
8964 MG_CB(mg_event_handler_t handler,
8965 void *user_data)) {
8966 struct mg_http_endpoint_opts opts;
8967 memset(&opts, 0, sizeof(opts));
8968 #if MG_ENABLE_CALLBACK_USERDATA
8969 opts.user_data = user_data;
8970 #endif
8971 mg_register_http_endpoint_opt(nc, uri_path, handler, opts);
8972 }
8973
8974 #endif /* MG_ENABLE_HTTP */
8975 #ifdef MG_MODULE_LINES
8976 #line 1 "mongoose/src/mg_http_cgi.c"
8977 #endif
8978 /*
8979 * Copyright (c) 2014-2016 Cesanta Software Limited
8980 * All rights reserved
8981 */
8982
8983 #ifndef _WIN32
8984 #include <signal.h>
8985 #endif
8986
8987 #if MG_ENABLE_HTTP && MG_ENABLE_HTTP_CGI
8988
8989 #ifndef MG_MAX_CGI_ENVIR_VARS
8990 #define MG_MAX_CGI_ENVIR_VARS 64
8991 #endif
8992
8993 #ifndef MG_ENV_EXPORT_TO_CGI
8994 #define MG_ENV_EXPORT_TO_CGI "MONGOOSE_CGI"
8995 #endif
8996
8997 #define MG_F_HTTP_CGI_PARSE_HEADERS MG_F_USER_1
8998
8999 /*
9000 * This structure helps to create an environment for the spawned CGI program.
9001 * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
9002 * last element must be NULL.
9003 * However, on Windows there is a requirement that all these VARIABLE=VALUE\0
9004 * strings must reside in a contiguous buffer. The end of the buffer is
9005 * marked by two '\0' characters.
9006 * We satisfy both worlds: we create an envp array (which is vars), all
9007 * entries are actually pointers inside buf.
9008 */
9009 struct mg_cgi_env_block {
9010 struct mg_connection *nc;
9011 char buf[MG_CGI_ENVIRONMENT_SIZE]; /* Environment buffer */
9012 const char *vars[MG_MAX_CGI_ENVIR_VARS]; /* char *envp[] */
9013 int len; /* Space taken */
9014 int nvars; /* Number of variables in envp[] */
9015 };
9016
9017 #ifdef _WIN32
9018 struct mg_threadparam {
9019 sock_t s;
9020 HANDLE hPipe;
9021 };
9022
9023 static int mg_wait_until_ready(sock_t sock, int for_read) {
9024 fd_set set;
9025 FD_ZERO(&set);
9026 FD_SET(sock, &set);
9027 return select(sock + 1, for_read ? &set : 0, for_read ? 0 : &set, 0, 0) == 1;
9028 }
9029
9030 static void *mg_push_to_stdin(void *arg) {
9031 struct mg_threadparam *tp = (struct mg_threadparam *) arg;
9032 int n, sent, stop = 0;
9033 DWORD k;
9034 char buf[BUFSIZ];
9035
9036 while (!stop && mg_wait_until_ready(tp->s, 1) &&
9037 (n = recv(tp->s, buf, sizeof(buf), 0)) > 0) {
9038 if (n == -1 && GetLastError() == WSAEWOULDBLOCK) continue;
9039 for (sent = 0; !stop && sent < n; sent += k) {
9040 if (!WriteFile(tp->hPipe, buf + sent, n - sent, &k, 0)) stop = 1;
9041 }
9042 }
9043 DBG(("%s", "FORWARED EVERYTHING TO CGI"));
9044 CloseHandle(tp->hPipe);
9045 MG_FREE(tp);
9046 return NULL;
9047 }
9048
9049 static void *mg_pull_from_stdout(void *arg) {
9050 struct mg_threadparam *tp = (struct mg_threadparam *) arg;
9051 int k = 0, stop = 0;
9052 DWORD n, sent;
9053 char buf[BUFSIZ];
9054
9055 while (!stop && ReadFile(tp->hPipe, buf, sizeof(buf), &n, NULL)) {
9056 for (sent = 0; !stop && sent < n; sent += k) {
9057 if (mg_wait_until_ready(tp->s, 0) &&
9058 (k = send(tp->s, buf + sent, n - sent, 0)) <= 0)
9059 stop = 1;
9060 }
9061 }
9062 DBG(("%s", "EOF FROM CGI"));
9063 CloseHandle(tp->hPipe);
9064 shutdown(tp->s, 2); // Without this, IO thread may get truncated data
9065 closesocket(tp->s);
9066 MG_FREE(tp);
9067 return NULL;
9068 }
9069
9070 static void mg_spawn_stdio_thread(sock_t sock, HANDLE hPipe,
9071 void *(*func)(void *)) {
9072 struct mg_threadparam *tp = (struct mg_threadparam *) MG_MALLOC(sizeof(*tp));
9073 if (tp != NULL) {
9074 tp->s = sock;
9075 tp->hPipe = hPipe;
9076 mg_start_thread(func, tp);
9077 }
9078 }
9079
9080 static void mg_abs_path(const char *utf8_path, char *abs_path, size_t len) {
9081 wchar_t buf[MG_MAX_PATH], buf2[MG_MAX_PATH];
9082 to_wchar(utf8_path, buf, ARRAY_SIZE(buf));
9083 GetFullPathNameW(buf, ARRAY_SIZE(buf2), buf2, NULL);
9084 WideCharToMultiByte(CP_UTF8, 0, buf2, wcslen(buf2) + 1, abs_path, len, 0, 0);
9085 }
9086
9087 static int mg_start_process(const char *interp, const char *cmd,
9088 const char *env, const char *envp[],
9089 const char *dir, sock_t sock) {
9090 STARTUPINFOW si;
9091 PROCESS_INFORMATION pi;
9092 HANDLE a[2], b[2], me = GetCurrentProcess();
9093 wchar_t wcmd[MG_MAX_PATH], full_dir[MG_MAX_PATH];
9094 char buf[MG_MAX_PATH], buf2[MG_MAX_PATH], buf5[MG_MAX_PATH],
9095 buf4[MG_MAX_PATH], cmdline[MG_MAX_PATH];
9096 DWORD flags = DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS;
9097 FILE *fp;
9098
9099 memset(&si, 0, sizeof(si));
9100 memset(&pi, 0, sizeof(pi));
9101
9102 si.cb = sizeof(si);
9103 si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
9104 si.wShowWindow = SW_HIDE;
9105 si.hStdError = GetStdHandle(STD_ERROR_HANDLE);
9106
9107 CreatePipe(&a[0], &a[1], NULL, 0);
9108 CreatePipe(&b[0], &b[1], NULL, 0);
9109 DuplicateHandle(me, a[0], me, &si.hStdInput, 0, TRUE, flags);
9110 DuplicateHandle(me, b[1], me, &si.hStdOutput, 0, TRUE, flags);
9111
9112 if (interp == NULL && (fp = mg_fopen(cmd, "r")) != NULL) {
9113 buf[0] = buf[1] = '\0';
9114 fgets(buf, sizeof(buf), fp);
9115 buf[sizeof(buf) - 1] = '\0';
9116 if (buf[0] == '#' && buf[1] == '!') {
9117 interp = buf + 2;
9118 /* Trim leading spaces: https://github.com/cesanta/mongoose/issues/489 */
9119 while (*interp != '\0' && isspace(*(unsigned char *) interp)) {
9120 interp++;
9121 }
9122 }
9123 fclose(fp);
9124 }
9125
9126 snprintf(buf, sizeof(buf), "%s/%s", dir, cmd);
9127 mg_abs_path(buf, buf2, ARRAY_SIZE(buf2));
9128
9129 mg_abs_path(dir, buf5, ARRAY_SIZE(buf5));
9130 to_wchar(dir, full_dir, ARRAY_SIZE(full_dir));
9131
9132 if (interp != NULL) {
9133 mg_abs_path(interp, buf4, ARRAY_SIZE(buf4));
9134 snprintf(cmdline, sizeof(cmdline), "%s \"%s\"", buf4, buf2);
9135 } else {
9136 snprintf(cmdline, sizeof(cmdline), "\"%s\"", buf2);
9137 }
9138 to_wchar(cmdline, wcmd, ARRAY_SIZE(wcmd));
9139
9140 if (CreateProcessW(NULL, wcmd, NULL, NULL, TRUE, CREATE_NEW_PROCESS_GROUP,
9141 (void *) env, full_dir, &si, &pi) != 0) {
9142 mg_spawn_stdio_thread(sock, a[1], mg_push_to_stdin);
9143 mg_spawn_stdio_thread(sock, b[0], mg_pull_from_stdout);
9144
9145 CloseHandle(si.hStdOutput);
9146 CloseHandle(si.hStdInput);
9147
9148 CloseHandle(pi.hThread);
9149 CloseHandle(pi.hProcess);
9150 } else {
9151 CloseHandle(a[1]);
9152 CloseHandle(b[0]);
9153 closesocket(sock);
9154 }
9155 DBG(("CGI command: [%ls] -> %p", wcmd, pi.hProcess));
9156
9157 /* Not closing a[0] and b[1] because we've used DUPLICATE_CLOSE_SOURCE */
9158 (void) envp;
9159 return (pi.hProcess != NULL);
9160 }
9161 #else
9162 static int mg_start_process(const char *interp, const char *cmd,
9163 const char *env, const char *envp[],
9164 const char *dir, sock_t sock) {
9165 char buf[500];
9166 pid_t pid = fork();
9167 (void) env;
9168
9169 if (pid == 0) {
9170 /*
9171 * In Linux `chdir` declared with `warn_unused_result` attribute
9172 * To shutup compiler we have yo use result in some way
9173 */
9174 int tmp = chdir(dir);
9175 (void) tmp;
9176 (void) dup2(sock, 0);
9177 (void) dup2(sock, 1);
9178 closesocket(sock);
9179
9180 /*
9181 * After exec, all signal handlers are restored to their default values,
9182 * with one exception of SIGCHLD. According to POSIX.1-2001 and Linux's
9183 * implementation, SIGCHLD's handler will leave unchanged after exec
9184 * if it was set to be ignored. Restore it to default action.
9185 */
9186 signal(SIGCHLD, SIG_DFL);
9187
9188 if (interp == NULL) {
9189 execle(cmd, cmd, (char *) 0, envp); /* (char *) 0 to squash warning */
9190 } else {
9191 execle(interp, interp, cmd, (char *) 0, envp);
9192 }
9193 snprintf(buf, sizeof(buf),
9194 "Status: 500\r\n\r\n"
9195 "500 Server Error: %s%s%s: %s",
9196 interp == NULL ? "" : interp, interp == NULL ? "" : " ", cmd,
9197 strerror(errno));
9198 send(1, buf, strlen(buf), 0);
9199 _exit(EXIT_FAILURE); /* exec call failed */
9200 }
9201
9202 return (pid != 0);
9203 }
9204 #endif /* _WIN32 */
9205
9206 /*
9207 * Append VARIABLE=VALUE\0 string to the buffer, and add a respective
9208 * pointer into the vars array.
9209 */
9210 static char *mg_addenv(struct mg_cgi_env_block *block, const char *fmt, ...) {
9211 int n, space;
9212 char *added = block->buf + block->len;
9213 va_list ap;
9214
9215 /* Calculate how much space is left in the buffer */
9216 space = sizeof(block->buf) - (block->len + 2);
9217 if (space > 0) {
9218 /* Copy VARIABLE=VALUE\0 string into the free space */
9219 va_start(ap, fmt);
9220 n = vsnprintf(added, (size_t) space, fmt, ap);
9221 va_end(ap);
9222
9223 /* Make sure we do not overflow buffer and the envp array */
9224 if (n > 0 && n + 1 < space &&
9225 block->nvars < (int) ARRAY_SIZE(block->vars) - 2) {
9226 /* Append a pointer to the added string into the envp array */
9227 block->vars[block->nvars++] = added;
9228 /* Bump up used length counter. Include \0 terminator */
9229 block->len += n + 1;
9230 }
9231 }
9232
9233 return added;
9234 }
9235
9236 static void mg_addenv2(struct mg_cgi_env_block *blk, const char *name) {
9237 const char *s;
9238 if ((s = getenv(name)) != NULL) mg_addenv(blk, "%s=%s", name, s);
9239 }
9240
9241 static void mg_prepare_cgi_environment(struct mg_connection *nc,
9242 const char *prog,
9243 const struct mg_str *path_info,
9244 const struct http_message *hm,
9245 const struct mg_serve_http_opts *opts,
9246 struct mg_cgi_env_block *blk) {
9247 const char *s;
9248 struct mg_str *h;
9249 char *p;
9250 size_t i;
9251 char buf[100];
9252 size_t path_info_len = path_info != NULL ? path_info->len : 0;
9253
9254 blk->len = blk->nvars = 0;
9255 blk->nc = nc;
9256
9257 if ((s = getenv("SERVER_NAME")) != NULL) {
9258 mg_addenv(blk, "SERVER_NAME=%s", s);
9259 } else {
9260 mg_sock_to_str(nc->sock, buf, sizeof(buf), 3);
9261 mg_addenv(blk, "SERVER_NAME=%s", buf);
9262 }
9263 mg_addenv(blk, "SERVER_ROOT=%s", opts->document_root);
9264 mg_addenv(blk, "DOCUMENT_ROOT=%s", opts->document_root);
9265 mg_addenv(blk, "SERVER_SOFTWARE=%s/%s", "Mongoose", MG_VERSION);
9266
9267 /* Prepare the environment block */
9268 mg_addenv(blk, "%s", "GATEWAY_INTERFACE=CGI/1.1");
9269 mg_addenv(blk, "%s", "SERVER_PROTOCOL=HTTP/1.1");
9270 mg_addenv(blk, "%s", "REDIRECT_STATUS=200"); /* For PHP */
9271
9272 mg_addenv(blk, "REQUEST_METHOD=%.*s", (int) hm->method.len, hm->method.p);
9273
9274 mg_addenv(blk, "REQUEST_URI=%.*s%s%.*s", (int) hm->uri.len, hm->uri.p,
9275 hm->query_string.len == 0 ? "" : "?", (int) hm->query_string.len,
9276 hm->query_string.p);
9277
9278 mg_conn_addr_to_str(nc, buf, sizeof(buf),
9279 MG_SOCK_STRINGIFY_REMOTE | MG_SOCK_STRINGIFY_IP);
9280 mg_addenv(blk, "REMOTE_ADDR=%s", buf);
9281 mg_conn_addr_to_str(nc, buf, sizeof(buf), MG_SOCK_STRINGIFY_PORT);
9282 mg_addenv(blk, "SERVER_PORT=%s", buf);
9283
9284 s = hm->uri.p + hm->uri.len - path_info_len - 1;
9285 if (*s == '/') {
9286 const char *base_name = strrchr(prog, DIRSEP);
9287 mg_addenv(blk, "SCRIPT_NAME=%.*s/%s", (int) (s - hm->uri.p), hm->uri.p,
9288 (base_name != NULL ? base_name + 1 : prog));
9289 } else {
9290 mg_addenv(blk, "SCRIPT_NAME=%.*s", (int) (s - hm->uri.p + 1), hm->uri.p);
9291 }
9292 mg_addenv(blk, "SCRIPT_FILENAME=%s", prog);
9293
9294 if (path_info != NULL && path_info->len > 0) {
9295 mg_addenv(blk, "PATH_INFO=%.*s", (int) path_info->len, path_info->p);
9296 /* Not really translated... */
9297 mg_addenv(blk, "PATH_TRANSLATED=%.*s", (int) path_info->len, path_info->p);
9298 }
9299
9300 #if MG_ENABLE_SSL
9301 mg_addenv(blk, "HTTPS=%s", (nc->flags & MG_F_SSL ? "on" : "off"));
9302 #else
9303 mg_addenv(blk, "HTTPS=off");
9304 #endif
9305
9306 if ((h = mg_get_http_header((struct http_message *) hm, "Content-Type")) !=
9307 NULL) {
9308 mg_addenv(blk, "CONTENT_TYPE=%.*s", (int) h->len, h->p);
9309 }
9310
9311 if (hm->query_string.len > 0) {
9312 mg_addenv(blk, "QUERY_STRING=%.*s", (int) hm->query_string.len,
9313 hm->query_string.p);
9314 }
9315
9316 if ((h = mg_get_http_header((struct http_message *) hm, "Content-Length")) !=
9317 NULL) {
9318 mg_addenv(blk, "CONTENT_LENGTH=%.*s", (int) h->len, h->p);
9319 }
9320
9321 mg_addenv2(blk, "PATH");
9322 mg_addenv2(blk, "TMP");
9323 mg_addenv2(blk, "TEMP");
9324 mg_addenv2(blk, "TMPDIR");
9325 mg_addenv2(blk, "PERLLIB");
9326 mg_addenv2(blk, MG_ENV_EXPORT_TO_CGI);
9327
9328 #ifdef _WIN32
9329 mg_addenv2(blk, "COMSPEC");
9330 mg_addenv2(blk, "SYSTEMROOT");
9331 mg_addenv2(blk, "SystemDrive");
9332 mg_addenv2(blk, "ProgramFiles");
9333 mg_addenv2(blk, "ProgramFiles(x86)");
9334 mg_addenv2(blk, "CommonProgramFiles(x86)");
9335 #else
9336 mg_addenv2(blk, "LD_LIBRARY_PATH");
9337 #endif /* _WIN32 */
9338
9339 /* Add all headers as HTTP_* variables */
9340 for (i = 0; hm->header_names[i].len > 0; i++) {
9341 p = mg_addenv(blk, "HTTP_%.*s=%.*s", (int) hm->header_names[i].len,
9342 hm->header_names[i].p, (int) hm->header_values[i].len,
9343 hm->header_values[i].p);
9344
9345 /* Convert variable name into uppercase, and change - to _ */
9346 for (; *p != '=' && *p != '\0'; p++) {
9347 if (*p == '-') *p = '_';
9348 *p = (char) toupper(*(unsigned char *) p);
9349 }
9350 }
9351
9352 blk->vars[blk->nvars++] = NULL;
9353 blk->buf[blk->len++] = '\0';
9354 }
9355
9356 static void mg_cgi_ev_handler(struct mg_connection *cgi_nc, int ev,
9357 void *ev_data MG_UD_ARG(void *user_data)) {
9358 #if !MG_ENABLE_CALLBACK_USERDATA
9359 void *user_data = cgi_nc->user_data;
9360 #endif
9361 struct mg_connection *nc = (struct mg_connection *) user_data;
9362 (void) ev_data;
9363
9364 if (nc == NULL) {
9365 /* The corresponding network connection was closed. */
9366 cgi_nc->flags |= MG_F_CLOSE_IMMEDIATELY;
9367 return;
9368 }
9369
9370 switch (ev) {
9371 case MG_EV_RECV:
9372 /*
9373 * CGI script does not output reply line, like "HTTP/1.1 CODE XXXXX\n"
9374 * It outputs headers, then body. Headers might include "Status"
9375 * header, which changes CODE, and it might include "Location" header
9376 * which changes CODE to 302.
9377 *
9378 * Therefore we do not send the output from the CGI script to the user
9379 * until all CGI headers are received.
9380 *
9381 * Here we parse the output from the CGI script, and if all headers has
9382 * been received, send appropriate reply line, and forward all
9383 * received headers to the client.
9384 */
9385 if (nc->flags & MG_F_HTTP_CGI_PARSE_HEADERS) {
9386 struct mbuf *io = &cgi_nc->recv_mbuf;
9387 int len = mg_http_get_request_len(io->buf, io->len);
9388
9389 if (len == 0) break;
9390 if (len < 0 || io->len > MG_MAX_HTTP_REQUEST_SIZE) {
9391 cgi_nc->flags |= MG_F_CLOSE_IMMEDIATELY;
9392 mg_http_send_error(nc, 500, "Bad headers");
9393 } else {
9394 struct http_message hm;
9395 struct mg_str *h;
9396 mg_http_parse_headers(io->buf, io->buf + io->len, io->len, &hm);
9397 if (mg_get_http_header(&hm, "Location") != NULL) {
9398 mg_printf(nc, "%s", "HTTP/1.1 302 Moved\r\n");
9399 } else if ((h = mg_get_http_header(&hm, "Status")) != NULL) {
9400 mg_printf(nc, "HTTP/1.1 %.*s\r\n", (int) h->len, h->p);
9401 } else {
9402 mg_printf(nc, "%s", "HTTP/1.1 200 OK\r\n");
9403 }
9404 }
9405 nc->flags &= ~MG_F_HTTP_CGI_PARSE_HEADERS;
9406 }
9407 if (!(nc->flags & MG_F_HTTP_CGI_PARSE_HEADERS)) {
9408 mg_forward(cgi_nc, nc);
9409 }
9410 break;
9411 case MG_EV_CLOSE:
9412 DBG(("%p CLOSE", cgi_nc));
9413 mg_http_free_proto_data_cgi(&mg_http_get_proto_data(nc)->cgi);
9414 nc->flags |= MG_F_SEND_AND_CLOSE;
9415 break;
9416 }
9417 }
9418
9419 MG_INTERNAL void mg_handle_cgi(struct mg_connection *nc, const char *prog,
9420 const struct mg_str *path_info,
9421 const struct http_message *hm,
9422 const struct mg_serve_http_opts *opts) {
9423 struct mg_cgi_env_block blk;
9424 char dir[MG_MAX_PATH];
9425 const char *p;
9426 sock_t fds[2];
9427
9428 DBG(("%p [%s]", nc, prog));
9429 mg_prepare_cgi_environment(nc, prog, path_info, hm, opts, &blk);
9430 /*
9431 * CGI must be executed in its own directory. 'dir' must point to the
9432 * directory containing executable program, 'p' must point to the
9433 * executable program name relative to 'dir'.
9434 */
9435 if ((p = strrchr(prog, DIRSEP)) == NULL) {
9436 snprintf(dir, sizeof(dir), "%s", ".");
9437 } else {
9438 snprintf(dir, sizeof(dir), "%.*s", (int) (p - prog), prog);
9439 prog = p + 1;
9440 }
9441
9442 if (!mg_socketpair(fds, SOCK_STREAM)) {
9443 nc->flags |= MG_F_CLOSE_IMMEDIATELY;
9444 return;
9445 }
9446
9447 #ifndef _WIN32
9448 struct sigaction sa;
9449
9450 sigemptyset(&sa.sa_mask);
9451 sa.sa_handler = SIG_IGN;
9452 sa.sa_flags = 0;
9453 sigaction(SIGCHLD, &sa, NULL);
9454 #endif
9455
9456 if (mg_start_process(opts->cgi_interpreter, prog, blk.buf, blk.vars, dir,
9457 fds[1]) != 0) {
9458 struct mg_connection *cgi_nc =
9459 mg_add_sock(nc->mgr, fds[0], mg_cgi_ev_handler MG_UD_ARG(nc));
9460 struct mg_http_proto_data *cgi_pd = mg_http_get_proto_data(nc);
9461 cgi_pd->cgi.cgi_nc = cgi_nc;
9462 #if !MG_ENABLE_CALLBACK_USERDATA
9463 cgi_pd->cgi.cgi_nc->user_data = nc;
9464 #endif
9465 nc->flags |= MG_F_HTTP_CGI_PARSE_HEADERS;
9466 /* Push POST data to the CGI */
9467 if (hm->body.len > 0) {
9468 mg_send(cgi_pd->cgi.cgi_nc, hm->body.p, hm->body.len);
9469 }
9470 mbuf_remove(&nc->recv_mbuf, nc->recv_mbuf.len);
9471 } else {
9472 closesocket(fds[0]);
9473 mg_http_send_error(nc, 500, "CGI failure");
9474 }
9475
9476 #ifndef _WIN32
9477 closesocket(fds[1]); /* On Windows, CGI stdio thread closes that socket */
9478 #endif
9479 }
9480
9481 MG_INTERNAL void mg_http_free_proto_data_cgi(struct mg_http_proto_data_cgi *d) {
9482 if (d == NULL) return;
9483 if (d->cgi_nc != NULL) {
9484 d->cgi_nc->flags |= MG_F_CLOSE_IMMEDIATELY;
9485 d->cgi_nc->user_data = NULL;
9486 }
9487 memset(d, 0, sizeof(*d));
9488 }
9489
9490 #endif /* MG_ENABLE_HTTP && MG_ENABLE_HTTP_CGI */
9491 #ifdef MG_MODULE_LINES
9492 #line 1 "mongoose/src/mg_http_ssi.c"
9493 #endif
9494 /*
9495 * Copyright (c) 2014-2016 Cesanta Software Limited
9496 * All rights reserved
9497 */
9498
9499 #if MG_ENABLE_HTTP && MG_ENABLE_HTTP_SSI && MG_ENABLE_FILESYSTEM
9500
9501 static void mg_send_ssi_file(struct mg_connection *nc, struct http_message *hm,
9502 const char *path, FILE *fp, int include_level,
9503 const struct mg_serve_http_opts *opts);
9504
9505 static void mg_send_file_data(struct mg_connection *nc, FILE *fp) {
9506 char buf[BUFSIZ];
9507 size_t n;
9508 while ((n = mg_fread(buf, 1, sizeof(buf), fp)) > 0) {
9509 mg_send(nc, buf, n);
9510 }
9511 }
9512
9513 static void mg_do_ssi_include(struct mg_connection *nc, struct http_message *hm,
9514 const char *ssi, char *tag, int include_level,
9515 const struct mg_serve_http_opts *opts) {
9516 char file_name[MG_MAX_PATH], path[MG_MAX_PATH], *p;
9517 FILE *fp;
9518
9519 /*
9520 * sscanf() is safe here, since send_ssi_file() also uses buffer
9521 * of size MG_BUF_LEN to get the tag. So strlen(tag) is always < MG_BUF_LEN.
9522 */
9523 if (sscanf(tag, " virtual=\"%[^\"]\"", file_name) == 1) {
9524 /* File name is relative to the webserver root */
9525 snprintf(path, sizeof(path), "%s/%s", opts->document_root, file_name);
9526 } else if (sscanf(tag, " abspath=\"%[^\"]\"", file_name) == 1) {
9527 /*
9528 * File name is relative to the webserver working directory
9529 * or it is absolute system path
9530 */
9531 snprintf(path, sizeof(path), "%s", file_name);
9532 } else if (sscanf(tag, " file=\"%[^\"]\"", file_name) == 1 ||
9533 sscanf(tag, " \"%[^\"]\"", file_name) == 1) {
9534 /* File name is relative to the currect document */
9535 snprintf(path, sizeof(path), "%s", ssi);
9536 if ((p = strrchr(path, DIRSEP)) != NULL) {
9537 p[1] = '\0';
9538 }
9539 snprintf(path + strlen(path), sizeof(path) - strlen(path), "%s", file_name);
9540 } else {
9541 mg_printf(nc, "Bad SSI #include: [%s]", tag);
9542 return;
9543 }
9544
9545 if ((fp = mg_fopen(path, "rb")) == NULL) {
9546 mg_printf(nc, "SSI include error: mg_fopen(%s): %s", path,
9547 strerror(mg_get_errno()));
9548 } else {
9549 mg_set_close_on_exec((sock_t) fileno(fp));
9550 if (mg_match_prefix(opts->ssi_pattern, strlen(opts->ssi_pattern), path) >
9551 0) {
9552 mg_send_ssi_file(nc, hm, path, fp, include_level + 1, opts);
9553 } else {
9554 mg_send_file_data(nc, fp);
9555 }
9556 fclose(fp);
9557 }
9558 }
9559
9560 #if MG_ENABLE_HTTP_SSI_EXEC
9561 static void do_ssi_exec(struct mg_connection *nc, char *tag) {
9562 char cmd[BUFSIZ];
9563 FILE *fp;
9564
9565 if (sscanf(tag, " \"%[^\"]\"", cmd) != 1) {
9566 mg_printf(nc, "Bad SSI #exec: [%s]", tag);
9567 } else if ((fp = popen(cmd, "r")) == NULL) {
9568 mg_printf(nc, "Cannot SSI #exec: [%s]: %s", cmd, strerror(mg_get_errno()));
9569 } else {
9570 mg_send_file_data(nc, fp);
9571 pclose(fp);
9572 }
9573 }
9574 #endif /* MG_ENABLE_HTTP_SSI_EXEC */
9575
9576 /*
9577 * SSI directive has the following format:
9578 * <!--#directive parameter=value parameter=value -->
9579 */
9580 static void mg_send_ssi_file(struct mg_connection *nc, struct http_message *hm,
9581 const char *path, FILE *fp, int include_level,
9582 const struct mg_serve_http_opts *opts) {
9583 static const struct mg_str btag = MG_MK_STR("<!--#");
9584 static const struct mg_str d_include = MG_MK_STR("include");
9585 static const struct mg_str d_call = MG_MK_STR("call");
9586 #if MG_ENABLE_HTTP_SSI_EXEC
9587 static const struct mg_str d_exec = MG_MK_STR("exec");
9588 #endif
9589 char buf[BUFSIZ], *p = buf + btag.len; /* p points to SSI directive */
9590 int ch, len, in_ssi_tag;
9591
9592 if (include_level > 10) {
9593 mg_printf(nc, "SSI #include level is too deep (%s)", path);
9594 return;
9595 }
9596
9597 in_ssi_tag = len = 0;
9598 while ((ch = fgetc(fp)) != EOF) {
9599 if (in_ssi_tag && ch == '>' && buf[len - 1] == '-' && buf[len - 2] == '-') {
9600 size_t i = len - 2;
9601 in_ssi_tag = 0;
9602
9603 /* Trim closing --> */
9604 buf[i--] = '\0';
9605 while (i > 0 && buf[i] == ' ') {
9606 buf[i--] = '\0';
9607 }
9608
9609 /* Handle known SSI directives */
9610 if (strncmp(p, d_include.p, d_include.len) == 0) {
9611 mg_do_ssi_include(nc, hm, path, p + d_include.len + 1, include_level,
9612 opts);
9613 } else if (strncmp(p, d_call.p, d_call.len) == 0) {
9614 struct mg_ssi_call_ctx cctx;
9615 memset(&cctx, 0, sizeof(cctx));
9616 cctx.req = hm;
9617 cctx.file = mg_mk_str(path);
9618 cctx.arg = mg_mk_str(p + d_call.len + 1);
9619 mg_call(nc, NULL, nc->user_data, MG_EV_SSI_CALL,
9620 (void *) cctx.arg.p); /* NUL added above */
9621 mg_call(nc, NULL, nc->user_data, MG_EV_SSI_CALL_CTX, &cctx);
9622 #if MG_ENABLE_HTTP_SSI_EXEC
9623 } else if (strncmp(p, d_exec.p, d_exec.len) == 0) {
9624 do_ssi_exec(nc, p + d_exec.len + 1);
9625 #endif
9626 } else {
9627 /* Silently ignore unknown SSI directive. */
9628 }
9629 len = 0;
9630 } else if (ch == '<') {
9631 in_ssi_tag = 1;
9632 if (len > 0) {
9633 mg_send(nc, buf, (size_t) len);
9634 }
9635 len = 0;
9636 buf[len++] = ch & 0xff;
9637 } else if (in_ssi_tag) {
9638 if (len == (int) btag.len && strncmp(buf, btag.p, btag.len) != 0) {
9639 /* Not an SSI tag */
9640 in_ssi_tag = 0;
9641 } else if (len == (int) sizeof(buf) - 2) {
9642 mg_printf(nc, "%s: SSI tag is too large", path);
9643 len = 0;
9644 }
9645 buf[len++] = ch & 0xff;
9646 } else {
9647 buf[len++] = ch & 0xff;
9648 if (len == (int) sizeof(buf)) {
9649 mg_send(nc, buf, (size_t) len);
9650 len = 0;
9651 }
9652 }
9653 }
9654
9655 /* Send the rest of buffered data */
9656 if (len > 0) {
9657 mg_send(nc, buf, (size_t) len);
9658 }
9659 }
9660
9661 MG_INTERNAL void mg_handle_ssi_request(struct mg_connection *nc,
9662 struct http_message *hm,
9663 const char *path,
9664 const struct mg_serve_http_opts *opts) {
9665 FILE *fp;
9666 struct mg_str mime_type;
9667 DBG(("%p %s", nc, path));
9668
9669 if ((fp = mg_fopen(path, "rb")) == NULL) {
9670 mg_http_send_error(nc, 404, NULL);
9671 } else {
9672 mg_set_close_on_exec((sock_t) fileno(fp));
9673
9674 mime_type = mg_get_mime_type(path, "text/plain", opts);
9675 mg_send_response_line(nc, 200, opts->extra_headers);
9676 mg_printf(nc,
9677 "Content-Type: %.*s\r\n"
9678 "Connection: close\r\n\r\n",
9679 (int) mime_type.len, mime_type.p);
9680 mg_send_ssi_file(nc, hm, path, fp, 0, opts);
9681 fclose(fp);
9682 nc->flags |= MG_F_SEND_AND_CLOSE;
9683 }
9684 }
9685
9686 #endif /* MG_ENABLE_HTTP_SSI && MG_ENABLE_HTTP && MG_ENABLE_FILESYSTEM */
9687 #ifdef MG_MODULE_LINES
9688 #line 1 "mongoose/src/mg_http_webdav.c"
9689 #endif
9690 /*
9691 * Copyright (c) 2014-2016 Cesanta Software Limited
9692 * All rights reserved
9693 */
9694
9695 #if MG_ENABLE_HTTP && MG_ENABLE_HTTP_WEBDAV
9696
9697 MG_INTERNAL int mg_is_dav_request(const struct mg_str *s) {
9698 static const char *methods[] = {
9699 "PUT",
9700 "DELETE",
9701 "MKCOL",
9702 "PROPFIND",
9703 "MOVE"
9704 #if MG_ENABLE_FAKE_DAVLOCK
9705 ,
9706 "LOCK",
9707 "UNLOCK"
9708 #endif
9709 };
9710 size_t i;
9711
9712 for (i = 0; i < ARRAY_SIZE(methods); i++) {
9713 if (mg_vcmp(s, methods[i]) == 0) {
9714 return 1;
9715 }
9716 }
9717
9718 return 0;
9719 }
9720
9721 static int mg_mkdir(const char *path, uint32_t mode) {
9722 #ifndef _WIN32
9723 return mkdir(path, mode);
9724 #else
9725 (void) mode;
9726 return _mkdir(path);
9727 #endif
9728 }
9729
9730 static void mg_print_props(struct mg_connection *nc, const char *name,
9731 cs_stat_t *stp) {
9732 char mtime[64];
9733 time_t t = stp->st_mtime; /* store in local variable for NDK compile */
9734 struct mg_str name_esc = mg_url_encode(mg_mk_str(name));
9735 mg_gmt_time_string(mtime, sizeof(mtime), &t);
9736 mg_printf(nc,
9737 "<d:response>"
9738 "<d:href>%s</d:href>"
9739 "<d:propstat>"
9740 "<d:prop>"
9741 "<d:resourcetype>%s</d:resourcetype>"
9742 "<d:getcontentlength>%" INT64_FMT
9743 "</d:getcontentlength>"
9744 "<d:getlastmodified>%s</d:getlastmodified>"
9745 "</d:prop>"
9746 "<d:status>HTTP/1.1 200 OK</d:status>"
9747 "</d:propstat>"
9748 "</d:response>\n",
9749 name_esc.p, S_ISDIR(stp->st_mode) ? "<d:collection/>" : "",
9750 (int64_t) stp->st_size, mtime);
9751 free((void *) name_esc.p);
9752 }
9753
9754 MG_INTERNAL void mg_handle_propfind(struct mg_connection *nc, const char *path,
9755 cs_stat_t *stp, struct http_message *hm,
9756 struct mg_serve_http_opts *opts) {
9757 static const char header[] =
9758 "HTTP/1.1 207 Multi-Status\r\n"
9759 "Connection: close\r\n"
9760 "Content-Type: text/xml; charset=utf-8\r\n\r\n"
9761 "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
9762 "<d:multistatus xmlns:d='DAV:'>\n";
9763 static const char footer[] = "</d:multistatus>\n";
9764 const struct mg_str *depth = mg_get_http_header(hm, "Depth");
9765
9766 /* Print properties for the requested resource itself */
9767 if (S_ISDIR(stp->st_mode) &&
9768 strcmp(opts->enable_directory_listing, "yes") != 0) {
9769 mg_printf(nc, "%s", "HTTP/1.1 403 Directory Listing Denied\r\n\r\n");
9770 } else {
9771 char uri[MG_MAX_PATH];
9772 mg_send(nc, header, sizeof(header) - 1);
9773 snprintf(uri, sizeof(uri), "%.*s", (int) hm->uri.len, hm->uri.p);
9774 mg_print_props(nc, uri, stp);
9775 if (S_ISDIR(stp->st_mode) && (depth == NULL || mg_vcmp(depth, "0") != 0)) {
9776 mg_scan_directory(nc, path, opts, mg_print_props);
9777 }
9778 mg_send(nc, footer, sizeof(footer) - 1);
9779 nc->flags |= MG_F_SEND_AND_CLOSE;
9780 }
9781 }
9782
9783 #if MG_ENABLE_FAKE_DAVLOCK
9784 /*
9785 * Windows explorer (probably there are another WebDav clients like it)
9786 * requires LOCK support in webdav. W/out this, it still works, but fails
9787 * to save file: shows error message and offers "Save As".
9788 * "Save as" works, but this message is very annoying.
9789 * This is fake lock, which doesn't lock something, just returns LOCK token,
9790 * UNLOCK always answers "OK".
9791 * With this fake LOCK Windows Explorer looks happy and saves file.
9792 * NOTE: that is not DAV LOCK imlementation, it is just a way to shut up
9793 * Windows native DAV client. This is why FAKE LOCK is not enabed by default
9794 */
9795 MG_INTERNAL void mg_handle_lock(struct mg_connection *nc, const char *path) {
9796 static const char *reply =
9797 "HTTP/1.1 207 Multi-Status\r\n"
9798 "Connection: close\r\n"
9799 "Content-Type: text/xml; charset=utf-8\r\n\r\n"
9800 "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
9801 "<d:multistatus xmlns:d='DAV:'>\n"
9802 "<D:lockdiscovery>\n"
9803 "<D:activelock>\n"
9804 "<D:locktoken>\n"
9805 "<D:href>\n"
9806 "opaquelocktoken:%s%u"
9807 "</D:href>"
9808 "</D:locktoken>"
9809 "</D:activelock>\n"
9810 "</D:lockdiscovery>"
9811 "</d:multistatus>\n";
9812 mg_printf(nc, reply, path, (unsigned int) mg_time());
9813 nc->flags |= MG_F_SEND_AND_CLOSE;
9814 }
9815 #endif
9816
9817 MG_INTERNAL void mg_handle_mkcol(struct mg_connection *nc, const char *path,
9818 struct http_message *hm) {
9819 int status_code = 500;
9820 if (hm->body.len != (size_t) ~0 && hm->body.len > 0) {
9821 status_code = 415;
9822 } else if (!mg_mkdir(path, 0755)) {
9823 status_code = 201;
9824 } else if (errno == EEXIST) {
9825 status_code = 405;
9826 } else if (errno == EACCES) {
9827 status_code = 403;
9828 } else if (errno == ENOENT) {
9829 status_code = 409;
9830 } else {
9831 status_code = 500;
9832 }
9833 mg_http_send_error(nc, status_code, NULL);
9834 }
9835
9836 static int mg_remove_directory(const struct mg_serve_http_opts *opts,
9837 const char *dir) {
9838 char path[MG_MAX_PATH];
9839 struct dirent *dp;
9840 cs_stat_t st;
9841 DIR *dirp;
9842
9843 if ((dirp = opendir(dir)) == NULL) return 0;
9844
9845 while ((dp = readdir(dirp)) != NULL) {
9846 if (mg_is_file_hidden((const char *) dp->d_name, opts, 1)) {
9847 continue;
9848 }
9849 snprintf(path, sizeof(path), "%s%c%s", dir, '/', dp->d_name);
9850 mg_stat(path, &st);
9851 if (S_ISDIR(st.st_mode)) {
9852 mg_remove_directory(opts, path);
9853 } else {
9854 remove(path);
9855 }
9856 }
9857 closedir(dirp);
9858 rmdir(dir);
9859
9860 return 1;
9861 }
9862
9863 MG_INTERNAL void mg_handle_move(struct mg_connection *c,
9864 const struct mg_serve_http_opts *opts,
9865 const char *path, struct http_message *hm) {
9866 const struct mg_str *dest = mg_get_http_header(hm, "Destination");
9867 if (dest == NULL) {
9868 mg_http_send_error(c, 411, NULL);
9869 } else {
9870 const char *p = (char *) memchr(dest->p, '/', dest->len);
9871 if (p != NULL && p[1] == '/' &&
9872 (p = (char *) memchr(p + 2, '/', dest->p + dest->len - p)) != NULL) {
9873 char buf[MG_MAX_PATH];
9874 snprintf(buf, sizeof(buf), "%s%.*s", opts->dav_document_root,
9875 (int) (dest->p + dest->len - p), p);
9876 if (rename(path, buf) == 0) {
9877 mg_http_send_error(c, 200, NULL);
9878 } else {
9879 mg_http_send_error(c, 418, NULL);
9880 }
9881 } else {
9882 mg_http_send_error(c, 500, NULL);
9883 }
9884 }
9885 }
9886
9887 MG_INTERNAL void mg_handle_delete(struct mg_connection *nc,
9888 const struct mg_serve_http_opts *opts,
9889 const char *path) {
9890 cs_stat_t st;
9891 if (mg_stat(path, &st) != 0) {
9892 mg_http_send_error(nc, 404, NULL);
9893 } else if (S_ISDIR(st.st_mode)) {
9894 mg_remove_directory(opts, path);
9895 mg_http_send_error(nc, 204, NULL);
9896 } else if (remove(path) == 0) {
9897 mg_http_send_error(nc, 204, NULL);
9898 } else {
9899 mg_http_send_error(nc, 423, NULL);
9900 }
9901 }
9902
9903 /* Return -1 on error, 1 on success. */
9904 static int mg_create_itermediate_directories(const char *path) {
9905 const char *s;
9906
9907 /* Create intermediate directories if they do not exist */
9908 for (s = path + 1; *s != '\0'; s++) {
9909 if (*s == '/') {
9910 char buf[MG_MAX_PATH];
9911 cs_stat_t st;
9912 snprintf(buf, sizeof(buf), "%.*s", (int) (s - path), path);
9913 buf[sizeof(buf) - 1] = '\0';
9914 if (mg_stat(buf, &st) != 0 && mg_mkdir(buf, 0755) != 0) {
9915 return -1;
9916 }
9917 }
9918 }
9919
9920 return 1;
9921 }
9922
9923 MG_INTERNAL void mg_handle_put(struct mg_connection *nc, const char *path,
9924 struct http_message *hm) {
9925 struct mg_http_proto_data *pd = mg_http_get_proto_data(nc);
9926 cs_stat_t st;
9927 const struct mg_str *cl_hdr = mg_get_http_header(hm, "Content-Length");
9928 int rc, status_code = mg_stat(path, &st) == 0 ? 200 : 201;
9929
9930 mg_http_free_proto_data_file(&pd->file);
9931 if ((rc = mg_create_itermediate_directories(path)) == 0) {
9932 mg_printf(nc, "HTTP/1.1 %d OK\r\nContent-Length: 0\r\n\r\n", status_code);
9933 } else if (rc == -1) {
9934 mg_http_send_error(nc, 500, NULL);
9935 } else if (cl_hdr == NULL) {
9936 mg_http_send_error(nc, 411, NULL);
9937 } else if ((pd->file.fp = mg_fopen(path, "w+b")) == NULL) {
9938 mg_http_send_error(nc, 500, NULL);
9939 } else {
9940 const struct mg_str *range_hdr = mg_get_http_header(hm, "Content-Range");
9941 int64_t r1 = 0, r2 = 0;
9942 pd->file.type = DATA_PUT;
9943 mg_set_close_on_exec((sock_t) fileno(pd->file.fp));
9944 pd->file.cl = to64(cl_hdr->p);
9945 if (range_hdr != NULL &&
9946 mg_http_parse_range_header(range_hdr, &r1, &r2) > 0) {
9947 status_code = 206;
9948 fseeko(pd->file.fp, r1, SEEK_SET);
9949 pd->file.cl = r2 > r1 ? r2 - r1 + 1 : pd->file.cl - r1;
9950 }
9951 mg_printf(nc, "HTTP/1.1 %d OK\r\nContent-Length: 0\r\n\r\n", status_code);
9952 /* Remove HTTP request from the mbuf, leave only payload */
9953 mbuf_remove(&nc->recv_mbuf, hm->message.len - hm->body.len);
9954 mg_http_transfer_file_data(nc);
9955 }
9956 }
9957
9958 #endif /* MG_ENABLE_HTTP && MG_ENABLE_HTTP_WEBDAV */
9959 #ifdef MG_MODULE_LINES
9960 #line 1 "mongoose/src/mg_http_websocket.c"
9961 #endif
9962 /*
9963 * Copyright (c) 2014 Cesanta Software Limited
9964 * All rights reserved
9965 */
9966
9967 #if MG_ENABLE_HTTP && MG_ENABLE_HTTP_WEBSOCKET
9968
9969 /* Amalgamated: #include "common/cs_sha1.h" */
9970
9971 #ifndef MG_WEBSOCKET_PING_INTERVAL_SECONDS
9972 #define MG_WEBSOCKET_PING_INTERVAL_SECONDS 5
9973 #endif
9974
9975 #define FLAGS_MASK_FIN (1 << 7)
9976 #define FLAGS_MASK_OP 0x0f
9977
9978 static int mg_is_ws_fragment(unsigned char flags) {
9979 return (flags & FLAGS_MASK_FIN) == 0 ||
9980 (flags & FLAGS_MASK_OP) == WEBSOCKET_OP_CONTINUE;
9981 }
9982
9983 static int mg_is_ws_first_fragment(unsigned char flags) {
9984 return (flags & FLAGS_MASK_FIN) == 0 &&
9985 (flags & FLAGS_MASK_OP) != WEBSOCKET_OP_CONTINUE;
9986 }
9987
9988 static int mg_is_ws_control_frame(unsigned char flags) {
9989 unsigned char op = (flags & FLAGS_MASK_OP);
9990 return op == WEBSOCKET_OP_CLOSE || op == WEBSOCKET_OP_PING ||
9991 op == WEBSOCKET_OP_PONG;
9992 }
9993
9994 static void mg_handle_incoming_websocket_frame(struct mg_connection *nc,
9995 struct websocket_message *wsm) {
9996 if (wsm->flags & 0x8) {
9997 mg_call(nc, nc->handler, nc->user_data, MG_EV_WEBSOCKET_CONTROL_FRAME, wsm);
9998 } else {
9999 mg_call(nc, nc->handler, nc->user_data, MG_EV_WEBSOCKET_FRAME, wsm);
10000 }
10001 }
10002
10003 static struct mg_ws_proto_data *mg_ws_get_proto_data(struct mg_connection *nc) {
10004 struct mg_http_proto_data *htd = mg_http_get_proto_data(nc);
10005 return (htd != NULL ? &htd->ws_data : NULL);
10006 }
10007
10008 /*
10009 * Sends a Close websocket frame with the given data, and closes the underlying
10010 * connection. If `len` is ~0, strlen(data) is used.
10011 */
10012 static void mg_ws_close(struct mg_connection *nc, const void *data,
10013 size_t len) {
10014 if ((int) len == ~0) {
10015 len = strlen((const char *) data);
10016 }
10017 mg_send_websocket_frame(nc, WEBSOCKET_OP_CLOSE, data, len);
10018 nc->flags |= MG_F_SEND_AND_CLOSE;
10019 }
10020
10021 static int mg_deliver_websocket_data(struct mg_connection *nc) {
10022 /* Using unsigned char *, cause of integer arithmetic below */
10023 uint64_t i, data_len = 0, frame_len = 0, new_data_len = nc->recv_mbuf.len,
10024 len, mask_len = 0, header_len = 0;
10025 struct mg_ws_proto_data *wsd = mg_ws_get_proto_data(nc);
10026 unsigned char *new_data = (unsigned char *) nc->recv_mbuf.buf,
10027 *e = (unsigned char *) nc->recv_mbuf.buf + nc->recv_mbuf.len;
10028 uint8_t flags;
10029 int ok, reass;
10030
10031 if (wsd->reass_len > 0) {
10032 /*
10033 * We already have some previously received data which we need to
10034 * reassemble and deliver to the client code when we get the final
10035 * fragment.
10036 *
10037 * NOTE: it doesn't mean that the current message must be a continuation:
10038 * it might be a control frame (Close, Ping or Pong), which should be
10039 * handled without breaking the fragmented message.
10040 */
10041
10042 size_t existing_len = wsd->reass_len;
10043 assert(new_data_len >= existing_len);
10044
10045 new_data += existing_len;
10046 new_data_len -= existing_len;
10047 }
10048
10049 flags = new_data[0];
10050
10051 reass = new_data_len > 0 && mg_is_ws_fragment(flags) &&
10052 !(nc->flags & MG_F_WEBSOCKET_NO_DEFRAG);
10053
10054 if (reass && mg_is_ws_control_frame(flags)) {
10055 /*
10056 * Control frames can't be fragmented, so if we encounter fragmented
10057 * control frame, close connection immediately.
10058 */
10059 mg_ws_close(nc, "fragmented control frames are illegal", ~0);
10060 return 0;
10061 } else if (new_data_len > 0 && !reass && !mg_is_ws_control_frame(flags) &&
10062 wsd->reass_len > 0) {
10063 /*
10064 * When in the middle of a fragmented message, only the continuations
10065 * and control frames are allowed.
10066 */
10067 mg_ws_close(nc, "non-continuation in the middle of a fragmented message",
10068 ~0);
10069 return 0;
10070 }
10071
10072 if (new_data_len >= 2) {
10073 len = new_data[1] & 0x7f;
10074 mask_len = new_data[1] & FLAGS_MASK_FIN ? 4 : 0;
10075 if (len < 126 && new_data_len >= mask_len) {
10076 data_len = len;
10077 header_len = 2 + mask_len;
10078 } else if (len == 126 && new_data_len >= 4 + mask_len) {
10079 header_len = 4 + mask_len;
10080 data_len = ntohs(*(uint16_t *) &new_data[2]);
10081 } else if (new_data_len >= 10 + mask_len) {
10082 header_len = 10 + mask_len;
10083 data_len = (((uint64_t) ntohl(*(uint32_t *) &new_data[2])) << 32) +
10084 ntohl(*(uint32_t *) &new_data[6]);
10085 }
10086 }
10087
10088 frame_len = header_len + data_len;
10089 ok = (frame_len > 0 && frame_len <= new_data_len);
10090
10091 /* Check for overflow */
10092 if (frame_len < header_len || frame_len < data_len) {
10093 ok = 0;
10094 mg_ws_close(nc, "overflowed message", ~0);
10095 }
10096
10097 if (ok) {
10098 size_t cleanup_len = 0;
10099 struct websocket_message wsm;
10100
10101 wsm.size = (size_t) data_len;
10102 wsm.data = new_data + header_len;
10103 wsm.flags = flags;
10104
10105 /* Apply mask if necessary */
10106 if (mask_len > 0) {
10107 for (i = 0; i < data_len; i++) {
10108 new_data[i + header_len] ^= (new_data + header_len - mask_len)[i % 4];
10109 }
10110 }
10111
10112 if (reass) {
10113 /* This is a message fragment */
10114
10115 if (mg_is_ws_first_fragment(flags)) {
10116 /*
10117 * On the first fragmented frame, skip the first byte (op) and also
10118 * reset size to 1 (op), it'll be incremented with the data len below.
10119 */
10120 new_data += 1;
10121 wsd->reass_len = 1 /* op */;
10122 }
10123
10124 /* Append this frame to the reassembled buffer */
10125 memmove(new_data, wsm.data, e - wsm.data);
10126 wsd->reass_len += wsm.size;
10127 nc->recv_mbuf.len -= wsm.data - new_data;
10128
10129 if (flags & FLAGS_MASK_FIN) {
10130 /* On last fragmented frame - call user handler and remove data */
10131 wsm.flags = FLAGS_MASK_FIN | nc->recv_mbuf.buf[0];
10132 wsm.data = (unsigned char *) nc->recv_mbuf.buf + 1 /* op */;
10133 wsm.size = wsd->reass_len - 1 /* op */;
10134 cleanup_len = wsd->reass_len;
10135 wsd->reass_len = 0;
10136
10137 /* Pass reassembled message to the client code. */
10138 mg_handle_incoming_websocket_frame(nc, &wsm);
10139 mbuf_remove(&nc->recv_mbuf, cleanup_len); /* Cleanup frame */
10140 }
10141 } else {
10142 /*
10143 * This is a complete message, not a fragment. It might happen in between
10144 * of a fragmented message (in this case, WebSocket protocol requires
10145 * current message to be a control frame).
10146 */
10147 cleanup_len = (size_t) frame_len;
10148
10149 /* First of all, check if we need to react on a control frame. */
10150 switch (flags & FLAGS_MASK_OP) {
10151 case WEBSOCKET_OP_PING:
10152 mg_send_websocket_frame(nc, WEBSOCKET_OP_PONG, wsm.data, wsm.size);
10153 break;
10154
10155 case WEBSOCKET_OP_CLOSE:
10156 mg_ws_close(nc, wsm.data, wsm.size);
10157 break;
10158 }
10159
10160 /* Pass received message to the client code. */
10161 mg_handle_incoming_websocket_frame(nc, &wsm);
10162
10163 /* Cleanup frame */
10164 memmove(nc->recv_mbuf.buf + wsd->reass_len,
10165 nc->recv_mbuf.buf + wsd->reass_len + cleanup_len,
10166 nc->recv_mbuf.len - wsd->reass_len - cleanup_len);
10167 nc->recv_mbuf.len -= cleanup_len;
10168 }
10169 }
10170
10171 return ok;
10172 }
10173
10174 struct ws_mask_ctx {
10175 size_t pos; /* zero means unmasked */
10176 uint32_t mask;
10177 };
10178
10179 static uint32_t mg_ws_random_mask(void) {
10180 uint32_t mask;
10181 /*
10182 * The spec requires WS client to generate hard to
10183 * guess mask keys. From RFC6455, Section 5.3:
10184 *
10185 * The unpredictability of the masking key is essential to prevent
10186 * authors of malicious applications from selecting the bytes that appear on
10187 * the wire.
10188 *
10189 * Hence this feature is essential when the actual end user of this API
10190 * is untrusted code that wouldn't have access to a lower level net API
10191 * anyway (e.g. web browsers). Hence this feature is low prio for most
10192 * mongoose use cases and thus can be disabled, e.g. when porting to a platform
10193 * that lacks rand().
10194 */
10195 #if MG_DISABLE_WS_RANDOM_MASK
10196 mask = 0xefbeadde; /* generated with a random number generator, I swear */
10197 #else
10198 if (sizeof(long) >= 4) {
10199 mask = (uint32_t) rand();
10200 } else if (sizeof(long) == 2) {
10201 mask = (uint32_t) rand() << 16 | (uint32_t) rand();
10202 }
10203 #endif
10204 return mask;
10205 }
10206
10207 static void mg_send_ws_header(struct mg_connection *nc, int op, size_t len,
10208 struct ws_mask_ctx *ctx) {
10209 int header_len;
10210 unsigned char header[10];
10211
10212 header[0] =
10213 (op & WEBSOCKET_DONT_FIN ? 0x0 : FLAGS_MASK_FIN) | (op & FLAGS_MASK_OP);
10214 if (len < 126) {
10215 header[1] = (unsigned char) len;
10216 header_len = 2;
10217 } else if (len < 65535) {
10218 uint16_t tmp = htons((uint16_t) len);
10219 header[1] = 126;
10220 memcpy(&header[2], &tmp, sizeof(tmp));
10221 header_len = 4;
10222 } else {
10223 uint32_t tmp;
10224 header[1] = 127;
10225 tmp = htonl((uint32_t)((uint64_t) len >> 32));
10226 memcpy(&header[2], &tmp, sizeof(tmp));
10227 tmp = htonl((uint32_t)(len & 0xffffffff));
10228 memcpy(&header[6], &tmp, sizeof(tmp));
10229 header_len = 10;
10230 }
10231
10232 /* client connections enable masking */
10233 if (nc->listener == NULL) {
10234 header[1] |= 1 << 7; /* set masking flag */
10235 mg_send(nc, header, header_len);
10236 ctx->mask = mg_ws_random_mask();
10237 mg_send(nc, &ctx->mask, sizeof(ctx->mask));
10238 ctx->pos = nc->send_mbuf.len;
10239 } else {
10240 mg_send(nc, header, header_len);
10241 ctx->pos = 0;
10242 }
10243 }
10244
10245 static void mg_ws_mask_frame(struct mbuf *mbuf, struct ws_mask_ctx *ctx) {
10246 size_t i;
10247 if (ctx->pos == 0) return;
10248 for (i = 0; i < (mbuf->len - ctx->pos); i++) {
10249 mbuf->buf[ctx->pos + i] ^= ((char *) &ctx->mask)[i % 4];
10250 }
10251 }
10252
10253 void mg_send_websocket_frame(struct mg_connection *nc, int op, const void *data,
10254 size_t len) {
10255 struct ws_mask_ctx ctx;
10256 DBG(("%p %d %d", nc, op, (int) len));
10257 mg_send_ws_header(nc, op, len, &ctx);
10258 mg_send(nc, data, len);
10259
10260 mg_ws_mask_frame(&nc->send_mbuf, &ctx);
10261
10262 if (op == WEBSOCKET_OP_CLOSE) {
10263 nc->flags |= MG_F_SEND_AND_CLOSE;
10264 }
10265 }
10266
10267 void mg_send_websocket_framev(struct mg_connection *nc, int op,
10268 const struct mg_str *strv, int strvcnt) {
10269 struct ws_mask_ctx ctx;
10270 int i;
10271 int len = 0;
10272 for (i = 0; i < strvcnt; i++) {
10273 len += strv[i].len;
10274 }
10275
10276 mg_send_ws_header(nc, op, len, &ctx);
10277
10278 for (i = 0; i < strvcnt; i++) {
10279 mg_send(nc, strv[i].p, strv[i].len);
10280 }
10281
10282 mg_ws_mask_frame(&nc->send_mbuf, &ctx);
10283
10284 if (op == WEBSOCKET_OP_CLOSE) {
10285 nc->flags |= MG_F_SEND_AND_CLOSE;
10286 }
10287 }
10288
10289 void mg_printf_websocket_frame(struct mg_connection *nc, int op,
10290 const char *fmt, ...) {
10291 char mem[MG_VPRINTF_BUFFER_SIZE], *buf = mem;
10292 va_list ap;
10293 int len;
10294
10295 va_start(ap, fmt);
10296 if ((len = mg_avprintf(&buf, sizeof(mem), fmt, ap)) > 0) {
10297 mg_send_websocket_frame(nc, op, buf, len);
10298 }
10299 va_end(ap);
10300
10301 if (buf != mem && buf != NULL) {
10302 MG_FREE(buf);
10303 }
10304 }
10305
10306 MG_INTERNAL void mg_ws_handler(struct mg_connection *nc, int ev,
10307 void *ev_data MG_UD_ARG(void *user_data)) {
10308 mg_call(nc, nc->handler, nc->user_data, ev, ev_data);
10309
10310 switch (ev) {
10311 case MG_EV_RECV:
10312 do {
10313 } while (mg_deliver_websocket_data(nc));
10314 break;
10315 case MG_EV_POLL:
10316 /* Ping idle websocket connections */
10317 {
10318 time_t now = *(time_t *) ev_data;
10319 if (nc->flags & MG_F_IS_WEBSOCKET &&
10320 now > nc->last_io_time + MG_WEBSOCKET_PING_INTERVAL_SECONDS) {
10321 mg_send_websocket_frame(nc, WEBSOCKET_OP_PING, "", 0);
10322 }
10323 }
10324 break;
10325 default:
10326 break;
10327 }
10328 #if MG_ENABLE_CALLBACK_USERDATA
10329 (void) user_data;
10330 #endif
10331 }
10332
10333 #ifndef MG_EXT_SHA1
10334 void mg_hash_sha1_v(size_t num_msgs, const uint8_t *msgs[],
10335 const size_t *msg_lens, uint8_t *digest) {
10336 size_t i;
10337 cs_sha1_ctx sha_ctx;
10338 cs_sha1_init(&sha_ctx);
10339 for (i = 0; i < num_msgs; i++) {
10340 cs_sha1_update(&sha_ctx, msgs[i], msg_lens[i]);
10341 }
10342 cs_sha1_final(digest, &sha_ctx);
10343 }
10344 #else
10345 extern void mg_hash_sha1_v(size_t num_msgs, const uint8_t *msgs[],
10346 const size_t *msg_lens, uint8_t *digest);
10347 #endif
10348
10349 MG_INTERNAL void mg_ws_handshake(struct mg_connection *nc,
10350 const struct mg_str *key,
10351 struct http_message *hm) {
10352 static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
10353 const uint8_t *msgs[2] = {(const uint8_t *) key->p, (const uint8_t *) magic};
10354 const size_t msg_lens[2] = {key->len, 36};
10355 unsigned char sha[20];
10356 char b64_sha[30];
10357 struct mg_str *s;
10358
10359 mg_hash_sha1_v(2, msgs, msg_lens, sha);
10360 mg_base64_encode(sha, sizeof(sha), b64_sha);
10361 mg_printf(nc, "%s",
10362 "HTTP/1.1 101 Switching Protocols\r\n"
10363 "Upgrade: websocket\r\n"
10364 "Connection: Upgrade\r\n");
10365
10366 s = mg_get_http_header(hm, "Sec-WebSocket-Protocol");
10367 if (s != NULL) {
10368 mg_printf(nc, "Sec-WebSocket-Protocol: %.*s\r\n", (int) s->len, s->p);
10369 }
10370 mg_printf(nc, "Sec-WebSocket-Accept: %s%s", b64_sha, "\r\n\r\n");
10371
10372 DBG(("%p %.*s %s", nc, (int) key->len, key->p, b64_sha));
10373 }
10374
10375 void mg_send_websocket_handshake2(struct mg_connection *nc, const char *path,
10376 const char *host, const char *protocol,
10377 const char *extra_headers) {
10378 mg_send_websocket_handshake3(nc, path, host, protocol, extra_headers, NULL,
10379 NULL);
10380 }
10381
10382 void mg_send_websocket_handshake3(struct mg_connection *nc, const char *path,
10383 const char *host, const char *protocol,
10384 const char *extra_headers, const char *user,
10385 const char *pass) {
10386 mg_send_websocket_handshake3v(nc, mg_mk_str(path), mg_mk_str(host),
10387 mg_mk_str(protocol), mg_mk_str(extra_headers),
10388 mg_mk_str(user), mg_mk_str(pass));
10389 }
10390
10391 void mg_send_websocket_handshake3v(struct mg_connection *nc,
10392 const struct mg_str path,
10393 const struct mg_str host,
10394 const struct mg_str protocol,
10395 const struct mg_str extra_headers,
10396 const struct mg_str user,
10397 const struct mg_str pass) {
10398 struct mbuf auth;
10399 char key[25];
10400 uint32_t nonce[4];
10401 nonce[0] = mg_ws_random_mask();
10402 nonce[1] = mg_ws_random_mask();
10403 nonce[2] = mg_ws_random_mask();
10404 nonce[3] = mg_ws_random_mask();
10405 mg_base64_encode((unsigned char *) &nonce, sizeof(nonce), key);
10406
10407 mbuf_init(&auth, 0);
10408 if (user.len > 0) {
10409 mg_basic_auth_header(user, pass, &auth);
10410 }
10411
10412 /*
10413 * NOTE: the (auth.buf == NULL ? "" : auth.buf) is because cc3200 libc is
10414 * broken: it doesn't like zero length to be passed to %.*s
10415 * i.e. sprintf("f%.*so", (int)0, NULL), yields `f\0o`.
10416 * because it handles NULL specially (and incorrectly).
10417 */
10418 mg_printf(nc,
10419 "GET %.*s HTTP/1.1\r\n"
10420 "Upgrade: websocket\r\n"
10421 "Connection: Upgrade\r\n"
10422 "%.*s"
10423 "Sec-WebSocket-Version: 13\r\n"
10424 "Sec-WebSocket-Key: %s\r\n",
10425 (int) path.len, path.p, (int) auth.len,
10426 (auth.buf == NULL ? "" : auth.buf), key);
10427
10428 /* TODO(mkm): take default hostname from http proto data if host == NULL */
10429 if (host.len > 0) {
10430 int host_len = (int) (path.p - host.p); /* Account for possible :PORT */
10431 mg_printf(nc, "Host: %.*s\r\n", host_len, host.p);
10432 }
10433 if (protocol.len > 0) {
10434 mg_printf(nc, "Sec-WebSocket-Protocol: %.*s\r\n", (int) protocol.len,
10435 protocol.p);
10436 }
10437 if (extra_headers.len > 0) {
10438 mg_printf(nc, "%.*s", (int) extra_headers.len, extra_headers.p);
10439 }
10440 mg_printf(nc, "\r\n");
10441
10442 nc->flags |= MG_F_IS_WEBSOCKET;
10443
10444 mbuf_free(&auth);
10445 }
10446
10447 void mg_send_websocket_handshake(struct mg_connection *nc, const char *path,
10448 const char *extra_headers) {
10449 struct mg_str null_str = MG_NULL_STR;
10450 mg_send_websocket_handshake3v(
10451 nc, mg_mk_str(path), null_str /* host */, null_str /* protocol */,
10452 mg_mk_str(extra_headers), null_str /* user */, null_str /* pass */);
10453 }
10454
10455 struct mg_connection *mg_connect_ws_opt(
10456 struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data),
10457 struct mg_connect_opts opts, const char *url, const char *protocol,
10458 const char *extra_headers) {
10459 struct mg_str null_str = MG_NULL_STR;
10460 struct mg_str host = MG_NULL_STR, path = MG_NULL_STR, user_info = MG_NULL_STR;
10461 struct mg_connection *nc =
10462 mg_connect_http_base(mgr, MG_CB(ev_handler, user_data), opts, "http",
10463 "ws", "https", "wss", url, &path, &user_info, &host);
10464 if (nc != NULL) {
10465 mg_send_websocket_handshake3v(nc, path, host, mg_mk_str(protocol),
10466 mg_mk_str(extra_headers), user_info,
10467 null_str);
10468 }
10469 return nc;
10470 }
10471
10472 struct mg_connection *mg_connect_ws(
10473 struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data),
10474 const char *url, const char *protocol, const char *extra_headers) {
10475 struct mg_connect_opts opts;
10476 memset(&opts, 0, sizeof(opts));
10477 return mg_connect_ws_opt(mgr, MG_CB(ev_handler, user_data), opts, url,
10478 protocol, extra_headers);
10479 }
10480 #endif /* MG_ENABLE_HTTP && MG_ENABLE_HTTP_WEBSOCKET */
10481 #ifdef MG_MODULE_LINES
10482 #line 1 "mongoose/src/mg_util.c"
10483 #endif
10484 /*
10485 * Copyright (c) 2014 Cesanta Software Limited
10486 * All rights reserved
10487 */
10488
10489 /* Amalgamated: #include "common/cs_base64.h" */
10490 /* Amalgamated: #include "mg_internal.h" */
10491 /* Amalgamated: #include "mg_util.h" */
10492
10493 /* For platforms with limited libc */
10494 #ifndef MAX
10495 #define MAX(a, b) ((a) > (b) ? (a) : (b))
10496 #endif
10497
10498 const char *mg_skip(const char *s, const char *end, const char *delims,
10499 struct mg_str *v) {
10500 v->p = s;
10501 while (s < end && strchr(delims, *(unsigned char *) s) == NULL) s++;
10502 v->len = s - v->p;
10503 while (s < end && strchr(delims, *(unsigned char *) s) != NULL) s++;
10504 return s;
10505 }
10506
10507 #if MG_ENABLE_FILESYSTEM && !defined(MG_USER_FILE_FUNCTIONS)
10508 int mg_stat(const char *path, cs_stat_t *st) {
10509 #ifdef _WIN32
10510 wchar_t wpath[MG_MAX_PATH];
10511 to_wchar(path, wpath, ARRAY_SIZE(wpath));
10512 DBG(("[%ls] -> %d", wpath, _wstati64(wpath, st)));
10513 return _wstati64(wpath, st);
10514 #else
10515 return stat(path, st);
10516 #endif
10517 }
10518
10519 FILE *mg_fopen(const char *path, const char *mode) {
10520 #ifdef _WIN32
10521 wchar_t wpath[MG_MAX_PATH], wmode[10];
10522 to_wchar(path, wpath, ARRAY_SIZE(wpath));
10523 to_wchar(mode, wmode, ARRAY_SIZE(wmode));
10524 return _wfopen(wpath, wmode);
10525 #else
10526 return fopen(path, mode);
10527 #endif
10528 }
10529
10530 int mg_open(const char *path, int flag, int mode) { /* LCOV_EXCL_LINE */
10531 #if defined(_WIN32) && !defined(WINCE)
10532 wchar_t wpath[MG_MAX_PATH];
10533 to_wchar(path, wpath, ARRAY_SIZE(wpath));
10534 return _wopen(wpath, flag, mode);
10535 #else
10536 return open(path, flag, mode); /* LCOV_EXCL_LINE */
10537 #endif
10538 }
10539
10540 size_t mg_fread(void *ptr, size_t size, size_t count, FILE *f) {
10541 return fread(ptr, size, count, f);
10542 }
10543
10544 size_t mg_fwrite(const void *ptr, size_t size, size_t count, FILE *f) {
10545 return fwrite(ptr, size, count, f);
10546 }
10547 #endif
10548
10549 void mg_base64_encode(const unsigned char *src, int src_len, char *dst) {
10550 cs_base64_encode(src, src_len, dst);
10551 }
10552
10553 int mg_base64_decode(const unsigned char *s, int len, char *dst) {
10554 return cs_base64_decode(s, len, dst, NULL);
10555 }
10556
10557 #if MG_ENABLE_THREADS
10558 void *mg_start_thread(void *(*f)(void *), void *p) {
10559 #ifdef WINCE
10560 return (void *) CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) f, p, 0, NULL);
10561 #elif defined(_WIN32)
10562 return (void *) _beginthread((void(__cdecl *) (void *) ) f, 0, p);
10563 #else
10564 pthread_t thread_id = (pthread_t) 0;
10565 pthread_attr_t attr;
10566
10567 (void) pthread_attr_init(&attr);
10568 (void) pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
10569
10570 #if defined(MG_STACK_SIZE) && MG_STACK_SIZE > 1
10571 (void) pthread_attr_setstacksize(&attr, MG_STACK_SIZE);
10572 #endif
10573
10574 pthread_create(&thread_id, &attr, f, p);
10575 pthread_attr_destroy(&attr);
10576
10577 return (void *) thread_id;
10578 #endif
10579 }
10580 #endif /* MG_ENABLE_THREADS */
10581
10582 /* Set close-on-exec bit for a given socket. */
10583 void mg_set_close_on_exec(sock_t sock) {
10584 #if defined(_WIN32) && !defined(WINCE)
10585 (void) SetHandleInformation((HANDLE) sock, HANDLE_FLAG_INHERIT, 0);
10586 #elif defined(__unix__)
10587 fcntl(sock, F_SETFD, FD_CLOEXEC);
10588 #else
10589 (void) sock;
10590 #endif
10591 }
10592
10593 int mg_sock_addr_to_str(const union socket_address *sa, char *buf, size_t len,
10594 int flags) {
10595 int is_v6;
10596 if (buf == NULL || len <= 0) return 0;
10597 memset(buf, 0, len);
10598 #if MG_ENABLE_IPV6
10599 is_v6 = sa->sa.sa_family == AF_INET6;
10600 #else
10601 is_v6 = 0;
10602 #endif
10603 if (flags & MG_SOCK_STRINGIFY_IP) {
10604 #if MG_ENABLE_IPV6
10605 const void *addr = NULL;
10606 char *start = buf;
10607 socklen_t capacity = len;
10608 if (!is_v6) {
10609 addr = &sa->sin.sin_addr;
10610 } else {
10611 addr = (void *) &sa->sin6.sin6_addr;
10612 if (flags & MG_SOCK_STRINGIFY_PORT) {
10613 *buf = '[';
10614 start++;
10615 capacity--;
10616 }
10617 }
10618 if (inet_ntop(sa->sa.sa_family, addr, start, capacity) == NULL) {
10619 goto cleanup;
10620 }
10621 #elif defined(_WIN32) || MG_LWIP || (MG_NET_IF == MG_NET_IF_PIC32)
10622 /* Only Windoze Vista (and newer) have inet_ntop() */
10623 char *addr_str = inet_ntoa(sa->sin.sin_addr);
10624 if (addr_str != NULL) {
10625 strncpy(buf, inet_ntoa(sa->sin.sin_addr), len - 1);
10626 } else {
10627 goto cleanup;
10628 }
10629 #else
10630 if (inet_ntop(AF_INET, (void *) &sa->sin.sin_addr, buf, len) == NULL) {
10631 goto cleanup;
10632 }
10633 #endif
10634 }
10635 if (flags & MG_SOCK_STRINGIFY_PORT) {
10636 int port = ntohs(sa->sin.sin_port);
10637 if (flags & MG_SOCK_STRINGIFY_IP) {
10638 int buf_len = strlen(buf);
10639 snprintf(buf + buf_len, len - (buf_len + 1), "%s:%d", (is_v6 ? "]" : ""),
10640 port);
10641 } else {
10642 snprintf(buf, len, "%d", port);
10643 }
10644 }
10645
10646 return strlen(buf);
10647
10648 cleanup:
10649 *buf = '\0';
10650 return 0;
10651 }
10652
10653 int mg_conn_addr_to_str(struct mg_connection *nc, char *buf, size_t len,
10654 int flags) {
10655 union socket_address sa;
10656 memset(&sa, 0, sizeof(sa));
10657 mg_if_get_conn_addr(nc, flags & MG_SOCK_STRINGIFY_REMOTE, &sa);
10658 return mg_sock_addr_to_str(&sa, buf, len, flags);
10659 }
10660
10661 #if MG_ENABLE_HEXDUMP
10662 static int mg_hexdump_n(const void *buf, int len, char *dst, int dst_len,
10663 int offset) {
10664 const unsigned char *p = (const unsigned char *) buf;
10665 char ascii[17] = "";
10666 int i, idx, n = 0;
10667
10668 for (i = 0; i < len; i++) {
10669 idx = i % 16;
10670 if (idx == 0) {
10671 if (i > 0) n += snprintf(dst + n, MAX(dst_len - n, 0), " %s\n", ascii);
10672 n += snprintf(dst + n, MAX(dst_len - n, 0), "%04x ", i + offset);
10673 }
10674 if (dst_len - n < 0) {
10675 return n;
10676 }
10677 n += snprintf(dst + n, MAX(dst_len - n, 0), " %02x", p[i]);
10678 ascii[idx] = p[i] < 0x20 || p[i] > 0x7e ? '.' : p[i];
10679 ascii[idx + 1] = '\0';
10680 }
10681
10682 while (i++ % 16) n += snprintf(dst + n, MAX(dst_len - n, 0), "%s", " ");
10683 n += snprintf(dst + n, MAX(dst_len - n, 0), " %s\n", ascii);
10684
10685 return n;
10686 }
10687
10688 int mg_hexdump(const void *buf, int len, char *dst, int dst_len) {
10689 return mg_hexdump_n(buf, len, dst, dst_len, 0);
10690 }
10691
10692 void mg_hexdumpf(FILE *fp, const void *buf, int len) {
10693 char tmp[80];
10694 int offset = 0, n;
10695 while (len > 0) {
10696 n = (len < 16 ? len : 16);
10697 mg_hexdump_n(((const char *) buf) + offset, n, tmp, sizeof(tmp), offset);
10698 fputs(tmp, fp);
10699 offset += n;
10700 len -= n;
10701 }
10702 }
10703
10704 void mg_hexdump_connection(struct mg_connection *nc, const char *path,
10705 const void *buf, int num_bytes, int ev) {
10706 FILE *fp = NULL;
10707 char src[60], dst[60];
10708 const char *tag = NULL;
10709 switch (ev) {
10710 case MG_EV_RECV:
10711 tag = "<-";
10712 break;
10713 case MG_EV_SEND:
10714 tag = "->";
10715 break;
10716 case MG_EV_ACCEPT:
10717 tag = "<A";
10718 break;
10719 case MG_EV_CONNECT:
10720 tag = "C>";
10721 break;
10722 case MG_EV_CLOSE:
10723 tag = "XX";
10724 break;
10725 }
10726 if (tag == NULL) return; /* Don't log MG_EV_TIMER, etc */
10727
10728 if (strcmp(path, "-") == 0) {
10729 fp = stdout;
10730 } else if (strcmp(path, "--") == 0) {
10731 fp = stderr;
10732 #if MG_ENABLE_FILESYSTEM
10733 } else {
10734 fp = mg_fopen(path, "a");
10735 #endif
10736 }
10737 if (fp == NULL) return;
10738
10739 mg_conn_addr_to_str(nc, src, sizeof(src),
10740 MG_SOCK_STRINGIFY_IP | MG_SOCK_STRINGIFY_PORT);
10741 mg_conn_addr_to_str(nc, dst, sizeof(dst), MG_SOCK_STRINGIFY_IP |
10742 MG_SOCK_STRINGIFY_PORT |
10743 MG_SOCK_STRINGIFY_REMOTE);
10744 fprintf(fp, "%lu %p %s %s %s %d\n", (unsigned long) mg_time(), (void *) nc,
10745 src, tag, dst, (int) num_bytes);
10746 if (num_bytes > 0) {
10747 mg_hexdumpf(fp, buf, num_bytes);
10748 }
10749 if (fp != stdout && fp != stderr) fclose(fp);
10750 }
10751 #endif
10752
10753 int mg_is_big_endian(void) {
10754 static const int n = 1;
10755 /* TODO(mkm) use compiletime check with 4-byte char literal */
10756 return ((char *) &n)[0] == 0;
10757 }
10758
10759 DO_NOT_WARN_UNUSED MG_INTERNAL int mg_get_errno(void) {
10760 #ifndef WINCE
10761 return errno;
10762 #else
10763 /* TODO(alashkin): translate error codes? */
10764 return GetLastError();
10765 #endif
10766 }
10767
10768 void mg_mbuf_append_base64_putc(char ch, void *user_data) {
10769 struct mbuf *mbuf = (struct mbuf *) user_data;
10770 mbuf_append(mbuf, &ch, sizeof(ch));
10771 }
10772
10773 void mg_mbuf_append_base64(struct mbuf *mbuf, const void *data, size_t len) {
10774 struct cs_base64_ctx ctx;
10775 cs_base64_init(&ctx, mg_mbuf_append_base64_putc, mbuf);
10776 cs_base64_update(&ctx, (const char *) data, len);
10777 cs_base64_finish(&ctx);
10778 }
10779
10780 void mg_basic_auth_header(const struct mg_str user, const struct mg_str pass,
10781 struct mbuf *buf) {
10782 const char *header_prefix = "Authorization: Basic ";
10783 const char *header_suffix = "\r\n";
10784
10785 struct cs_base64_ctx ctx;
10786 cs_base64_init(&ctx, mg_mbuf_append_base64_putc, buf);
10787
10788 mbuf_append(buf, header_prefix, strlen(header_prefix));
10789
10790 cs_base64_update(&ctx, user.p, user.len);
10791 if (pass.len > 0) {
10792 cs_base64_update(&ctx, ":", 1);
10793 cs_base64_update(&ctx, pass.p, pass.len);
10794 }
10795 cs_base64_finish(&ctx);
10796 mbuf_append(buf, header_suffix, strlen(header_suffix));
10797 }
10798
10799 struct mg_str mg_url_encode_opt(const struct mg_str src,
10800 const struct mg_str safe, unsigned int flags) {
10801 const char *hex =
10802 (flags & MG_URL_ENCODE_F_UPPERCASE_HEX ? "0123456789ABCDEF"
10803 : "0123456789abcdef");
10804 size_t i = 0;
10805 struct mbuf mb;
10806 mbuf_init(&mb, src.len);
10807
10808 for (i = 0; i < src.len; i++) {
10809 const unsigned char c = *((const unsigned char *) src.p + i);
10810 if (isalnum(c) || mg_strchr(safe, c) != NULL) {
10811 mbuf_append(&mb, &c, 1);
10812 } else if (c == ' ' && (flags & MG_URL_ENCODE_F_SPACE_AS_PLUS)) {
10813 mbuf_append(&mb, "+", 1);
10814 } else {
10815 mbuf_append(&mb, "%", 1);
10816 mbuf_append(&mb, &hex[c >> 4], 1);
10817 mbuf_append(&mb, &hex[c & 15], 1);
10818 }
10819 }
10820 mbuf_append(&mb, "", 1);
10821 mbuf_trim(&mb);
10822 return mg_mk_str_n(mb.buf, mb.len - 1);
10823 }
10824
10825 struct mg_str mg_url_encode(const struct mg_str src) {
10826 return mg_url_encode_opt(src, mg_mk_str("._-$,;~()/"), 0);
10827 }
10828 #ifdef MG_MODULE_LINES
10829 #line 1 "mongoose/src/mg_mqtt.c"
10830 #endif
10831 /*
10832 * Copyright (c) 2014 Cesanta Software Limited
10833 * All rights reserved
10834 */
10835
10836 #if MG_ENABLE_MQTT
10837
10838 #include <string.h>
10839
10840 /* Amalgamated: #include "mg_internal.h" */
10841 /* Amalgamated: #include "mg_mqtt.h" */
10842
10843 static uint16_t getu16(const char *p) {
10844 const uint8_t *up = (const uint8_t *) p;
10845 return (up[0] << 8) + up[1];
10846 }
10847
10848 static const char *scanto(const char *p, struct mg_str *s) {
10849 s->len = getu16(p);
10850 s->p = p + 2;
10851 return s->p + s->len;
10852 }
10853
10854 MG_INTERNAL int parse_mqtt(struct mbuf *io, struct mg_mqtt_message *mm) {
10855 uint8_t header;
10856 size_t len = 0, len_len = 0;
10857 const char *p, *end, *eop = &io->buf[io->len];
10858 unsigned char lc = 0;
10859 int cmd;
10860
10861 if (io->len < 2) return MG_MQTT_ERROR_INCOMPLETE_MSG;
10862 header = io->buf[0];
10863 cmd = header >> 4;
10864
10865 /* decode mqtt variable length */
10866 len = len_len = 0;
10867 p = io->buf + 1;
10868 while (p < eop) {
10869 lc = *((const unsigned char *) p++);
10870 len += (lc & 0x7f) << 7 * len_len;
10871 len_len++;
10872 if (!(lc & 0x80)) break;
10873 if (len_len > 4) return MG_MQTT_ERROR_MALFORMED_MSG;
10874 }
10875
10876 end = p + len;
10877 if (lc & 0x80 || end > eop) return MG_MQTT_ERROR_INCOMPLETE_MSG;
10878
10879 mm->cmd = cmd;
10880 mm->qos = MG_MQTT_GET_QOS(header);
10881
10882 switch (cmd) {
10883 case MG_MQTT_CMD_CONNECT: {
10884 p = scanto(p, &mm->protocol_name);
10885 if (p > end - 4) return MG_MQTT_ERROR_MALFORMED_MSG;
10886 mm->protocol_version = *(uint8_t *) p++;
10887 mm->connect_flags = *(uint8_t *) p++;
10888 mm->keep_alive_timer = getu16(p);
10889 p += 2;
10890 if (p >= end) return MG_MQTT_ERROR_MALFORMED_MSG;
10891 p = scanto(p, &mm->client_id);
10892 if (p > end) return MG_MQTT_ERROR_MALFORMED_MSG;
10893 if (mm->connect_flags & MG_MQTT_HAS_WILL) {
10894 if (p >= end) return MG_MQTT_ERROR_MALFORMED_MSG;
10895 p = scanto(p, &mm->will_topic);
10896 }
10897 if (mm->connect_flags & MG_MQTT_HAS_WILL) {
10898 if (p >= end) return MG_MQTT_ERROR_MALFORMED_MSG;
10899 p = scanto(p, &mm->will_message);
10900 }
10901 if (mm->connect_flags & MG_MQTT_HAS_USER_NAME) {
10902 if (p >= end) return MG_MQTT_ERROR_MALFORMED_MSG;
10903 p = scanto(p, &mm->user_name);
10904 }
10905 if (mm->connect_flags & MG_MQTT_HAS_PASSWORD) {
10906 if (p >= end) return MG_MQTT_ERROR_MALFORMED_MSG;
10907 p = scanto(p, &mm->password);
10908 }
10909 if (p != end) return MG_MQTT_ERROR_MALFORMED_MSG;
10910
10911 LOG(LL_DEBUG,
10912 ("%d %2x %d proto [%.*s] client_id [%.*s] will_topic [%.*s] "
10913 "will_msg [%.*s] user_name [%.*s] password [%.*s]",
10914 (int) len, (int) mm->connect_flags, (int) mm->keep_alive_timer,
10915 (int) mm->protocol_name.len, mm->protocol_name.p,
10916 (int) mm->client_id.len, mm->client_id.p, (int) mm->will_topic.len,
10917 mm->will_topic.p, (int) mm->will_message.len, mm->will_message.p,
10918 (int) mm->user_name.len, mm->user_name.p, (int) mm->password.len,
10919 mm->password.p));
10920 break;
10921 }
10922 case MG_MQTT_CMD_CONNACK:
10923 if (end - p < 2) return MG_MQTT_ERROR_MALFORMED_MSG;
10924 mm->connack_ret_code = p[1];
10925 break;
10926 case MG_MQTT_CMD_PUBACK:
10927 case MG_MQTT_CMD_PUBREC:
10928 case MG_MQTT_CMD_PUBREL:
10929 case MG_MQTT_CMD_PUBCOMP:
10930 case MG_MQTT_CMD_SUBACK:
10931 if (end - p < 2) return MG_MQTT_ERROR_MALFORMED_MSG;
10932 mm->message_id = getu16(p);
10933 p += 2;
10934 break;
10935 case MG_MQTT_CMD_PUBLISH: {
10936 p = scanto(p, &mm->topic);
10937 if (p > end) return MG_MQTT_ERROR_MALFORMED_MSG;
10938 if (mm->qos > 0) {
10939 if (end - p < 2) return MG_MQTT_ERROR_MALFORMED_MSG;
10940 mm->message_id = getu16(p);
10941 p += 2;
10942 }
10943 mm->payload.p = p;
10944 mm->payload.len = end - p;
10945 break;
10946 }
10947 case MG_MQTT_CMD_SUBSCRIBE:
10948 if (end - p < 2) return MG_MQTT_ERROR_MALFORMED_MSG;
10949 mm->message_id = getu16(p);
10950 p += 2;
10951 /*
10952 * topic expressions are left in the payload and can be parsed with
10953 * `mg_mqtt_next_subscribe_topic`
10954 */
10955 mm->payload.p = p;
10956 mm->payload.len = end - p;
10957 break;
10958 default:
10959 /* Unhandled command */
10960 break;
10961 }
10962
10963 mm->len = end - io->buf;
10964 return mm->len;
10965 }
10966
10967 static void mqtt_handler(struct mg_connection *nc, int ev,
10968 void *ev_data MG_UD_ARG(void *user_data)) {
10969 struct mbuf *io = &nc->recv_mbuf;
10970 struct mg_mqtt_message mm;
10971 memset(&mm, 0, sizeof(mm));
10972
10973 nc->handler(nc, ev, ev_data MG_UD_ARG(user_data));
10974
10975 switch (ev) {
10976 case MG_EV_ACCEPT:
10977 if (nc->proto_data == NULL) mg_set_protocol_mqtt(nc);
10978 break;
10979 case MG_EV_RECV: {
10980 /* There can be multiple messages in the buffer, process them all. */
10981 while (1) {
10982 int len = parse_mqtt(io, &mm);
10983 if (len < 0) {
10984 if (len == MG_MQTT_ERROR_MALFORMED_MSG) {
10985 /* Protocol error. */
10986 nc->flags |= MG_F_CLOSE_IMMEDIATELY;
10987 } else if (len == MG_MQTT_ERROR_INCOMPLETE_MSG) {
10988 /* Not fully buffered, let's check if we have a chance to get more
10989 * data later */
10990 if (nc->recv_mbuf_limit > 0 &&
10991 nc->recv_mbuf.len >= nc->recv_mbuf_limit) {
10992 LOG(LL_ERROR, ("%p recv buffer (%lu bytes) exceeds the limit "
10993 "%lu bytes, and not drained, closing",
10994 nc, (unsigned long) nc->recv_mbuf.len,
10995 (unsigned long) nc->recv_mbuf_limit));
10996 nc->flags |= MG_F_CLOSE_IMMEDIATELY;
10997 }
10998 } else {
10999 /* Should never be here */
11000 LOG(LL_ERROR, ("%p invalid len: %d, closing", nc, len));
11001 nc->flags |= MG_F_CLOSE_IMMEDIATELY;
11002 }
11003 break;
11004 }
11005
11006 nc->handler(nc, MG_MQTT_EVENT_BASE + mm.cmd, &mm MG_UD_ARG(user_data));
11007 mbuf_remove(io, len);
11008 }
11009 break;
11010 }
11011 case MG_EV_POLL: {
11012 struct mg_mqtt_proto_data *pd =
11013 (struct mg_mqtt_proto_data *) nc->proto_data;
11014 double now = mg_time();
11015 if (pd->keep_alive > 0 && pd->last_control_time > 0 &&
11016 (now - pd->last_control_time) > pd->keep_alive) {
11017 LOG(LL_DEBUG, ("Send PINGREQ"));
11018 mg_mqtt_ping(nc);
11019 }
11020 break;
11021 }
11022 }
11023 }
11024
11025 static void mg_mqtt_proto_data_destructor(void *proto_data) {
11026 MG_FREE(proto_data);
11027 }
11028
11029 static struct mg_str mg_mqtt_next_topic_component(struct mg_str *topic) {
11030 struct mg_str res = *topic;
11031 const char *c = mg_strchr(*topic, '/');
11032 if (c != NULL) {
11033 res.len = (c - topic->p);
11034 topic->len -= (res.len + 1);
11035 topic->p += (res.len + 1);
11036 } else {
11037 topic->len = 0;
11038 }
11039 return res;
11040 }
11041
11042 /* Reference: https://mosquitto.org/man/mqtt-7.html */
11043 int mg_mqtt_match_topic_expression(struct mg_str exp, struct mg_str topic) {
11044 struct mg_str ec, tc;
11045 if (exp.len == 0) return 0;
11046 while (1) {
11047 ec = mg_mqtt_next_topic_component(&exp);
11048 tc = mg_mqtt_next_topic_component(&topic);
11049 if (ec.len == 0) {
11050 if (tc.len != 0) return 0;
11051 if (exp.len == 0) break;
11052 continue;
11053 }
11054 if (mg_vcmp(&ec, "+") == 0) {
11055 if (tc.len == 0 && topic.len == 0) return 0;
11056 continue;
11057 }
11058 if (mg_vcmp(&ec, "#") == 0) {
11059 /* Must be the last component in the expression or it's invalid. */
11060 return (exp.len == 0);
11061 }
11062 if (mg_strcmp(ec, tc) != 0) {
11063 return 0;
11064 }
11065 }
11066 return (tc.len == 0 && topic.len == 0);
11067 }
11068
11069 int mg_mqtt_vmatch_topic_expression(const char *exp, struct mg_str topic) {
11070 return mg_mqtt_match_topic_expression(mg_mk_str(exp), topic);
11071 }
11072
11073 void mg_set_protocol_mqtt(struct mg_connection *nc) {
11074 nc->proto_handler = mqtt_handler;
11075 nc->proto_data = MG_CALLOC(1, sizeof(struct mg_mqtt_proto_data));
11076 nc->proto_data_destructor = mg_mqtt_proto_data_destructor;
11077 }
11078
11079 static void mg_send_mqtt_header(struct mg_connection *nc, uint8_t cmd,
11080 uint8_t flags, size_t len) {
11081 struct mg_mqtt_proto_data *pd = (struct mg_mqtt_proto_data *) nc->proto_data;
11082 uint8_t buf[1 + sizeof(size_t)];
11083 uint8_t *vlen = &buf[1];
11084
11085 buf[0] = (cmd << 4) | flags;
11086
11087 /* mqtt variable length encoding */
11088 do {
11089 *vlen = len % 0x80;
11090 len /= 0x80;
11091 if (len > 0) *vlen |= 0x80;
11092 vlen++;
11093 } while (len > 0);
11094
11095 mg_send(nc, buf, vlen - buf);
11096 pd->last_control_time = mg_time();
11097 }
11098
11099 void mg_send_mqtt_handshake(struct mg_connection *nc, const char *client_id) {
11100 static struct mg_send_mqtt_handshake_opts opts;
11101 mg_send_mqtt_handshake_opt(nc, client_id, opts);
11102 }
11103
11104 void mg_send_mqtt_handshake_opt(struct mg_connection *nc, const char *client_id,
11105 struct mg_send_mqtt_handshake_opts opts) {
11106 struct mg_mqtt_proto_data *pd = (struct mg_mqtt_proto_data *) nc->proto_data;
11107 uint16_t id_len = 0, wt_len = 0, wm_len = 0, user_len = 0, pw_len = 0;
11108 uint16_t netbytes;
11109 size_t total_len;
11110
11111 if (client_id != NULL) {
11112 id_len = strlen(client_id);
11113 }
11114
11115 total_len = 7 + 1 + 2 + 2 + id_len;
11116
11117 if (opts.user_name != NULL) {
11118 opts.flags |= MG_MQTT_HAS_USER_NAME;
11119 }
11120 if (opts.password != NULL) {
11121 opts.flags |= MG_MQTT_HAS_PASSWORD;
11122 }
11123 if (opts.will_topic != NULL && opts.will_message != NULL) {
11124 wt_len = strlen(opts.will_topic);
11125 wm_len = strlen(opts.will_message);
11126 opts.flags |= MG_MQTT_HAS_WILL;
11127 }
11128 if (opts.keep_alive == 0) {
11129 opts.keep_alive = 60;
11130 }
11131
11132 if (opts.flags & MG_MQTT_HAS_WILL) {
11133 total_len += 2 + wt_len + 2 + wm_len;
11134 }
11135 if (opts.flags & MG_MQTT_HAS_USER_NAME) {
11136 user_len = strlen(opts.user_name);
11137 total_len += 2 + user_len;
11138 }
11139 if (opts.flags & MG_MQTT_HAS_PASSWORD) {
11140 pw_len = strlen(opts.password);
11141 total_len += 2 + pw_len;
11142 }
11143
11144 mg_send_mqtt_header(nc, MG_MQTT_CMD_CONNECT, 0, total_len);
11145 mg_send(nc, "\00\04MQTT\04", 7);
11146 mg_send(nc, &opts.flags, 1);
11147
11148 netbytes = htons(opts.keep_alive);
11149 mg_send(nc, &netbytes, 2);
11150
11151 netbytes = htons(id_len);
11152 mg_send(nc, &netbytes, 2);
11153 mg_send(nc, client_id, id_len);
11154
11155 if (opts.flags & MG_MQTT_HAS_WILL) {
11156 netbytes = htons(wt_len);
11157 mg_send(nc, &netbytes, 2);
11158 mg_send(nc, opts.will_topic, wt_len);
11159
11160 netbytes = htons(wm_len);
11161 mg_send(nc, &netbytes, 2);
11162 mg_send(nc, opts.will_message, wm_len);
11163 }
11164
11165 if (opts.flags & MG_MQTT_HAS_USER_NAME) {
11166 netbytes = htons(user_len);
11167 mg_send(nc, &netbytes, 2);
11168 mg_send(nc, opts.user_name, user_len);
11169 }
11170 if (opts.flags & MG_MQTT_HAS_PASSWORD) {
11171 netbytes = htons(pw_len);
11172 mg_send(nc, &netbytes, 2);
11173 mg_send(nc, opts.password, pw_len);
11174 }
11175
11176 if (pd != NULL) {
11177 pd->keep_alive = opts.keep_alive;
11178 }
11179 }
11180
11181 void mg_mqtt_publish(struct mg_connection *nc, const char *topic,
11182 uint16_t message_id, int flags, const void *data,
11183 size_t len) {
11184 uint16_t netbytes;
11185 uint16_t topic_len = strlen(topic);
11186
11187 size_t total_len = 2 + topic_len + len;
11188 if (MG_MQTT_GET_QOS(flags) > 0) {
11189 total_len += 2;
11190 }
11191
11192 mg_send_mqtt_header(nc, MG_MQTT_CMD_PUBLISH, flags, total_len);
11193
11194 netbytes = htons(topic_len);
11195 mg_send(nc, &netbytes, 2);
11196 mg_send(nc, topic, topic_len);
11197
11198 if (MG_MQTT_GET_QOS(flags) > 0) {
11199 netbytes = htons(message_id);
11200 mg_send(nc, &netbytes, 2);
11201 }
11202
11203 mg_send(nc, data, len);
11204 }
11205
11206 void mg_mqtt_subscribe(struct mg_connection *nc,
11207 const struct mg_mqtt_topic_expression *topics,
11208 size_t topics_len, uint16_t message_id) {
11209 uint16_t netbytes;
11210 size_t i;
11211 uint16_t topic_len;
11212 size_t total_len = 2;
11213
11214 for (i = 0; i < topics_len; i++) {
11215 total_len += 2 + strlen(topics[i].topic) + 1;
11216 }
11217
11218 mg_send_mqtt_header(nc, MG_MQTT_CMD_SUBSCRIBE, MG_MQTT_QOS(1), total_len);
11219
11220 netbytes = htons(message_id);
11221 mg_send(nc, (char *) &netbytes, 2);
11222
11223 for (i = 0; i < topics_len; i++) {
11224 topic_len = strlen(topics[i].topic);
11225 netbytes = htons(topic_len);
11226 mg_send(nc, &netbytes, 2);
11227 mg_send(nc, topics[i].topic, topic_len);
11228 mg_send(nc, &topics[i].qos, 1);
11229 }
11230 }
11231
11232 int mg_mqtt_next_subscribe_topic(struct mg_mqtt_message *msg,
11233 struct mg_str *topic, uint8_t *qos, int pos) {
11234 unsigned char *buf = (unsigned char *) msg->payload.p + pos;
11235 int new_pos;
11236
11237 if ((size_t) pos >= msg->payload.len) return -1;
11238
11239 topic->len = buf[0] << 8 | buf[1];
11240 topic->p = (char *) buf + 2;
11241 new_pos = pos + 2 + topic->len + 1;
11242 if ((size_t) new_pos > msg->payload.len) return -1;
11243 *qos = buf[2 + topic->len];
11244 return new_pos;
11245 }
11246
11247 void mg_mqtt_unsubscribe(struct mg_connection *nc, char **topics,
11248 size_t topics_len, uint16_t message_id) {
11249 uint16_t netbytes;
11250 size_t i;
11251 uint16_t topic_len;
11252 size_t total_len = 2;
11253
11254 for (i = 0; i < topics_len; i++) {
11255 total_len += 2 + strlen(topics[i]);
11256 }
11257
11258 mg_send_mqtt_header(nc, MG_MQTT_CMD_UNSUBSCRIBE, MG_MQTT_QOS(1), total_len);
11259
11260 netbytes = htons(message_id);
11261 mg_send(nc, (char *) &netbytes, 2);
11262
11263 for (i = 0; i < topics_len; i++) {
11264 topic_len = strlen(topics[i]);
11265 netbytes = htons(topic_len);
11266 mg_send(nc, &netbytes, 2);
11267 mg_send(nc, topics[i], topic_len);
11268 }
11269 }
11270
11271 void mg_mqtt_connack(struct mg_connection *nc, uint8_t return_code) {
11272 uint8_t unused = 0;
11273 mg_send_mqtt_header(nc, MG_MQTT_CMD_CONNACK, 0, 2);
11274 mg_send(nc, &unused, 1);
11275 mg_send(nc, &return_code, 1);
11276 }
11277
11278 /*
11279 * Sends a command which contains only a `message_id` and a QoS level of 1.
11280 *
11281 * Helper function.
11282 */
11283 static void mg_send_mqtt_short_command(struct mg_connection *nc, uint8_t cmd,
11284 uint16_t message_id) {
11285 uint16_t netbytes;
11286 uint8_t flags = (cmd == MG_MQTT_CMD_PUBREL ? 2 : 0);
11287
11288 mg_send_mqtt_header(nc, cmd, flags, 2 /* len */);
11289
11290 netbytes = htons(message_id);
11291 mg_send(nc, &netbytes, 2);
11292 }
11293
11294 void mg_mqtt_puback(struct mg_connection *nc, uint16_t message_id) {
11295 mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBACK, message_id);
11296 }
11297
11298 void mg_mqtt_pubrec(struct mg_connection *nc, uint16_t message_id) {
11299 mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBREC, message_id);
11300 }
11301
11302 void mg_mqtt_pubrel(struct mg_connection *nc, uint16_t message_id) {
11303 mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBREL, message_id);
11304 }
11305
11306 void mg_mqtt_pubcomp(struct mg_connection *nc, uint16_t message_id) {
11307 mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBCOMP, message_id);
11308 }
11309
11310 void mg_mqtt_suback(struct mg_connection *nc, uint8_t *qoss, size_t qoss_len,
11311 uint16_t message_id) {
11312 size_t i;
11313 uint16_t netbytes;
11314
11315 mg_send_mqtt_header(nc, MG_MQTT_CMD_SUBACK, MG_MQTT_QOS(1), 2 + qoss_len);
11316
11317 netbytes = htons(message_id);
11318 mg_send(nc, &netbytes, 2);
11319
11320 for (i = 0; i < qoss_len; i++) {
11321 mg_send(nc, &qoss[i], 1);
11322 }
11323 }
11324
11325 void mg_mqtt_unsuback(struct mg_connection *nc, uint16_t message_id) {
11326 mg_send_mqtt_short_command(nc, MG_MQTT_CMD_UNSUBACK, message_id);
11327 }
11328
11329 void mg_mqtt_ping(struct mg_connection *nc) {
11330 mg_send_mqtt_header(nc, MG_MQTT_CMD_PINGREQ, 0, 0);
11331 }
11332
11333 void mg_mqtt_pong(struct mg_connection *nc) {
11334 mg_send_mqtt_header(nc, MG_MQTT_CMD_PINGRESP, 0, 0);
11335 }
11336
11337 void mg_mqtt_disconnect(struct mg_connection *nc) {
11338 mg_send_mqtt_header(nc, MG_MQTT_CMD_DISCONNECT, 0, 0);
11339 }
11340
11341 #endif /* MG_ENABLE_MQTT */
11342 #ifdef MG_MODULE_LINES
11343 #line 1 "mongoose/src/mg_mqtt_server.c"
11344 #endif
11345 /*
11346 * Copyright (c) 2014 Cesanta Software Limited
11347 * All rights reserved
11348 */
11349
11350 /* Amalgamated: #include "mg_internal.h" */
11351 /* Amalgamated: #include "mg_mqtt_server.h" */
11352
11353 #if MG_ENABLE_MQTT_BROKER
11354
11355 static void mg_mqtt_session_init(struct mg_mqtt_broker *brk,
11356 struct mg_mqtt_session *s,
11357 struct mg_connection *nc) {
11358 s->brk = brk;
11359 s->subscriptions = NULL;
11360 s->num_subscriptions = 0;
11361 s->nc = nc;
11362 }
11363
11364 static void mg_mqtt_add_session(struct mg_mqtt_session *s) {
11365 LIST_INSERT_HEAD(&s->brk->sessions, s, link);
11366 }
11367
11368 static void mg_mqtt_remove_session(struct mg_mqtt_session *s) {
11369 LIST_REMOVE(s, link);
11370 }
11371
11372 static void mg_mqtt_destroy_session(struct mg_mqtt_session *s) {
11373 size_t i;
11374 for (i = 0; i < s->num_subscriptions; i++) {
11375 MG_FREE((void *) s->subscriptions[i].topic);
11376 }
11377 MG_FREE(s->subscriptions);
11378 MG_FREE(s);
11379 }
11380
11381 static void mg_mqtt_close_session(struct mg_mqtt_session *s) {
11382 mg_mqtt_remove_session(s);
11383 mg_mqtt_destroy_session(s);
11384 }
11385
11386 void mg_mqtt_broker_init(struct mg_mqtt_broker *brk, void *user_data) {
11387 LIST_INIT(&brk->sessions);
11388 brk->user_data = user_data;
11389 }
11390
11391 static void mg_mqtt_broker_handle_connect(struct mg_mqtt_broker *brk,
11392 struct mg_connection *nc) {
11393 struct mg_mqtt_session *s =
11394 (struct mg_mqtt_session *) MG_CALLOC(1, sizeof *s);
11395 if (s == NULL) {
11396 /* LCOV_EXCL_START */
11397 mg_mqtt_connack(nc, MG_EV_MQTT_CONNACK_SERVER_UNAVAILABLE);
11398 return;
11399 /* LCOV_EXCL_STOP */
11400 }
11401
11402 /* TODO(mkm): check header (magic and version) */
11403
11404 mg_mqtt_session_init(brk, s, nc);
11405 nc->priv_2 = s;
11406 mg_mqtt_add_session(s);
11407
11408 mg_mqtt_connack(nc, MG_EV_MQTT_CONNACK_ACCEPTED);
11409 }
11410
11411 static void mg_mqtt_broker_handle_subscribe(struct mg_connection *nc,
11412 struct mg_mqtt_message *msg) {
11413 struct mg_mqtt_session *ss = (struct mg_mqtt_session *) nc->priv_2;
11414 uint8_t qoss[MG_MQTT_MAX_SESSION_SUBSCRIPTIONS];
11415 size_t num_subs = 0;
11416 struct mg_str topic;
11417 uint8_t qos;
11418 int pos;
11419 struct mg_mqtt_topic_expression *te;
11420
11421 for (pos = 0;
11422 (pos = mg_mqtt_next_subscribe_topic(msg, &topic, &qos, pos)) != -1;) {
11423 if (num_subs >= sizeof(MG_MQTT_MAX_SESSION_SUBSCRIPTIONS) ||
11424 (ss->num_subscriptions + num_subs >=
11425 MG_MQTT_MAX_SESSION_SUBSCRIPTIONS)) {
11426 nc->flags |= MG_F_CLOSE_IMMEDIATELY;
11427 return;
11428 }
11429 qoss[num_subs++] = qos;
11430 }
11431
11432 if (num_subs > 0) {
11433 te = (struct mg_mqtt_topic_expression *) MG_REALLOC(
11434 ss->subscriptions,
11435 sizeof(*ss->subscriptions) * (ss->num_subscriptions + num_subs));
11436 if (te == NULL) {
11437 nc->flags |= MG_F_CLOSE_IMMEDIATELY;
11438 return;
11439 }
11440 ss->subscriptions = te;
11441 for (pos = 0;
11442 pos < (int) msg->payload.len &&
11443 (pos = mg_mqtt_next_subscribe_topic(msg, &topic, &qos, pos)) != -1;
11444 ss->num_subscriptions++) {
11445 te = &ss->subscriptions[ss->num_subscriptions];
11446 te->topic = (char *) MG_MALLOC(topic.len + 1);
11447 te->qos = qos;
11448 memcpy((char *) te->topic, topic.p, topic.len);
11449 ((char *) te->topic)[topic.len] = '\0';
11450 }
11451 }
11452
11453 if (pos == (int) msg->payload.len) {
11454 mg_mqtt_suback(nc, qoss, num_subs, msg->message_id);
11455 } else {
11456 /* We did not fully parse the payload, something must be wrong. */
11457 nc->flags |= MG_F_CLOSE_IMMEDIATELY;
11458 }
11459 }
11460
11461 static void mg_mqtt_broker_handle_publish(struct mg_mqtt_broker *brk,
11462 struct mg_mqtt_message *msg) {
11463 struct mg_mqtt_session *s;
11464 size_t i;
11465
11466 for (s = mg_mqtt_next(brk, NULL); s != NULL; s = mg_mqtt_next(brk, s)) {
11467 for (i = 0; i < s->num_subscriptions; i++) {
11468 if (mg_mqtt_vmatch_topic_expression(s->subscriptions[i].topic,
11469 msg->topic)) {
11470 char buf[100], *p = buf;
11471 mg_asprintf(&p, sizeof(buf), "%.*s", (int) msg->topic.len,
11472 msg->topic.p);
11473 if (p == NULL) {
11474 return;
11475 }
11476 mg_mqtt_publish(s->nc, p, 0, 0, msg->payload.p, msg->payload.len);
11477 if (p != buf) {
11478 MG_FREE(p);
11479 }
11480 break;
11481 }
11482 }
11483 }
11484 }
11485
11486 void mg_mqtt_broker(struct mg_connection *nc, int ev, void *data) {
11487 struct mg_mqtt_message *msg = (struct mg_mqtt_message *) data;
11488 struct mg_mqtt_broker *brk;
11489
11490 if (nc->listener) {
11491 brk = (struct mg_mqtt_broker *) nc->listener->priv_2;
11492 } else {
11493 brk = (struct mg_mqtt_broker *) nc->priv_2;
11494 }
11495
11496 switch (ev) {
11497 case MG_EV_ACCEPT:
11498 if (nc->proto_data == NULL) mg_set_protocol_mqtt(nc);
11499 nc->priv_2 = NULL; /* Clear up the inherited pointer to broker */
11500 break;
11501 case MG_EV_MQTT_CONNECT:
11502 if (nc->priv_2 == NULL) {
11503 mg_mqtt_broker_handle_connect(brk, nc);
11504 } else {
11505 /* Repeated CONNECT */
11506 nc->flags |= MG_F_CLOSE_IMMEDIATELY;
11507 }
11508 break;
11509 case MG_EV_MQTT_SUBSCRIBE:
11510 if (nc->priv_2 != NULL) {
11511 mg_mqtt_broker_handle_subscribe(nc, msg);
11512 } else {
11513 /* Subscribe before CONNECT */
11514 nc->flags |= MG_F_CLOSE_IMMEDIATELY;
11515 }
11516 break;
11517 case MG_EV_MQTT_PUBLISH:
11518 if (nc->priv_2 != NULL) {
11519 mg_mqtt_broker_handle_publish(brk, msg);
11520 } else {
11521 /* Publish before CONNECT */
11522 nc->flags |= MG_F_CLOSE_IMMEDIATELY;
11523 }
11524 break;
11525 case MG_EV_CLOSE:
11526 if (nc->listener && nc->priv_2 != NULL) {
11527 mg_mqtt_close_session((struct mg_mqtt_session *) nc->priv_2);
11528 }
11529 break;
11530 }
11531 }
11532
11533 struct mg_mqtt_session *mg_mqtt_next(struct mg_mqtt_broker *brk,
11534 struct mg_mqtt_session *s) {
11535 return s == NULL ? LIST_FIRST(&brk->sessions) : LIST_NEXT(s, link);
11536 }
11537
11538 #endif /* MG_ENABLE_MQTT_BROKER */
11539 #ifdef MG_MODULE_LINES
11540 #line 1 "mongoose/src/mg_dns.c"
11541 #endif
11542 /*
11543 * Copyright (c) 2014 Cesanta Software Limited
11544 * All rights reserved
11545 */
11546
11547 #if MG_ENABLE_DNS
11548
11549 /* Amalgamated: #include "mg_internal.h" */
11550 /* Amalgamated: #include "mg_dns.h" */
11551
11552 static int mg_dns_tid = 0xa0;
11553
11554 struct mg_dns_header {
11555 uint16_t transaction_id;
11556 uint16_t flags;
11557 uint16_t num_questions;
11558 uint16_t num_answers;
11559 uint16_t num_authority_prs;
11560 uint16_t num_other_prs;
11561 };
11562
11563 struct mg_dns_resource_record *mg_dns_next_record(
11564 struct mg_dns_message *msg, int query,
11565 struct mg_dns_resource_record *prev) {
11566 struct mg_dns_resource_record *rr;
11567
11568 for (rr = (prev == NULL ? msg->answers : prev + 1);
11569 rr - msg->answers < msg->num_answers; rr++) {
11570 if (rr->rtype == query) {
11571 return rr;
11572 }
11573 }
11574 return NULL;
11575 }
11576
11577 int mg_dns_parse_record_data(struct mg_dns_message *msg,
11578 struct mg_dns_resource_record *rr, void *data,
11579 size_t data_len) {
11580 switch (rr->rtype) {
11581 case MG_DNS_A_RECORD:
11582 if (data_len < sizeof(struct in_addr)) {
11583 return -1;
11584 }
11585 if (rr->rdata.p + data_len > msg->pkt.p + msg->pkt.len) {
11586 return -1;
11587 }
11588 memcpy(data, rr->rdata.p, data_len);
11589 return 0;
11590 #if MG_ENABLE_IPV6
11591 case MG_DNS_AAAA_RECORD:
11592 if (data_len < sizeof(struct in6_addr)) {
11593 return -1; /* LCOV_EXCL_LINE */
11594 }
11595 memcpy(data, rr->rdata.p, data_len);
11596 return 0;
11597 #endif
11598 case MG_DNS_CNAME_RECORD:
11599 mg_dns_uncompress_name(msg, &rr->rdata, (char *) data, data_len);
11600 return 0;
11601 }
11602
11603 return -1;
11604 }
11605
11606 int mg_dns_insert_header(struct mbuf *io, size_t pos,
11607 struct mg_dns_message *msg) {
11608 struct mg_dns_header header;
11609
11610 memset(&header, 0, sizeof(header));
11611 header.transaction_id = msg->transaction_id;
11612 header.flags = htons(msg->flags);
11613 header.num_questions = htons(msg->num_questions);
11614 header.num_answers = htons(msg->num_answers);
11615
11616 return mbuf_insert(io, pos, &header, sizeof(header));
11617 }
11618
11619 int mg_dns_copy_questions(struct mbuf *io, struct mg_dns_message *msg) {
11620 unsigned char *begin, *end;
11621 struct mg_dns_resource_record *last_q;
11622 if (msg->num_questions <= 0) return 0;
11623 begin = (unsigned char *) msg->pkt.p + sizeof(struct mg_dns_header);
11624 last_q = &msg->questions[msg->num_questions - 1];
11625 end = (unsigned char *) last_q->name.p + last_q->name.len + 4;
11626 return mbuf_append(io, begin, end - begin);
11627 }
11628
11629 int mg_dns_encode_name(struct mbuf *io, const char *name, size_t len) {
11630 const char *s;
11631 unsigned char n;
11632 size_t pos = io->len;
11633
11634 do {
11635 if ((s = strchr(name, '.')) == NULL) {
11636 s = name + len;
11637 }
11638
11639 if (s - name > 127) {
11640 return -1; /* TODO(mkm) cover */
11641 }
11642 n = s - name; /* chunk length */
11643 mbuf_append(io, &n, 1); /* send length */
11644 mbuf_append(io, name, n);
11645
11646 if (*s == '.') {
11647 n++;
11648 }
11649
11650 name += n;
11651 len -= n;
11652 } while (*s != '\0');
11653 mbuf_append(io, "\0", 1); /* Mark end of host name */
11654
11655 return io->len - pos;
11656 }
11657
11658 int mg_dns_encode_record(struct mbuf *io, struct mg_dns_resource_record *rr,
11659 const char *name, size_t nlen, const void *rdata,
11660 size_t rlen) {
11661 size_t pos = io->len;
11662 uint16_t u16;
11663 uint32_t u32;
11664
11665 if (rr->kind == MG_DNS_INVALID_RECORD) {
11666 return -1; /* LCOV_EXCL_LINE */
11667 }
11668
11669 if (mg_dns_encode_name(io, name, nlen) == -1) {
11670 return -1;
11671 }
11672
11673 u16 = htons(rr->rtype);
11674 mbuf_append(io, &u16, 2);
11675 u16 = htons(rr->rclass);
11676 mbuf_append(io, &u16, 2);
11677
11678 if (rr->kind == MG_DNS_ANSWER) {
11679 u32 = htonl(rr->ttl);
11680 mbuf_append(io, &u32, 4);
11681
11682 if (rr->rtype == MG_DNS_CNAME_RECORD) {
11683 int clen;
11684 /* fill size after encoding */
11685 size_t off = io->len;
11686 mbuf_append(io, &u16, 2);
11687 if ((clen = mg_dns_encode_name(io, (const char *) rdata, rlen)) == -1) {
11688 return -1;
11689 }
11690 u16 = clen;
11691 io->buf[off] = u16 >> 8;
11692 io->buf[off + 1] = u16 & 0xff;
11693 } else {
11694 u16 = htons((uint16_t) rlen);
11695 mbuf_append(io, &u16, 2);
11696 mbuf_append(io, rdata, rlen);
11697 }
11698 }
11699
11700 return io->len - pos;
11701 }
11702
11703 void mg_send_dns_query(struct mg_connection *nc, const char *name,
11704 int query_type) {
11705 struct mg_dns_message *msg =
11706 (struct mg_dns_message *) MG_CALLOC(1, sizeof(*msg));
11707 struct mbuf pkt;
11708 struct mg_dns_resource_record *rr = &msg->questions[0];
11709
11710 DBG(("%s %d", name, query_type));
11711
11712 mbuf_init(&pkt, 64 /* Start small, it'll grow as needed. */);
11713
11714 msg->transaction_id = ++mg_dns_tid;
11715 msg->flags = 0x100;
11716 msg->num_questions = 1;
11717
11718 mg_dns_insert_header(&pkt, 0, msg);
11719
11720 rr->rtype = query_type;
11721 rr->rclass = 1; /* Class: inet */
11722 rr->kind = MG_DNS_QUESTION;
11723
11724 if (mg_dns_encode_record(&pkt, rr, name, strlen(name), NULL, 0) == -1) {
11725 /* TODO(mkm): return an error code */
11726 goto cleanup; /* LCOV_EXCL_LINE */
11727 }
11728
11729 /* TCP DNS requires messages to be prefixed with len */
11730 if (!(nc->flags & MG_F_UDP)) {
11731 uint16_t len = htons((uint16_t) pkt.len);
11732 mbuf_insert(&pkt, 0, &len, 2);
11733 }
11734
11735 mg_send(nc, pkt.buf, pkt.len);
11736 mbuf_free(&pkt);
11737
11738 cleanup:
11739 MG_FREE(msg);
11740 }
11741
11742 static unsigned char *mg_parse_dns_resource_record(
11743 unsigned char *data, unsigned char *end, struct mg_dns_resource_record *rr,
11744 int reply) {
11745 unsigned char *name = data;
11746 int chunk_len, data_len;
11747
11748 while (data < end && (chunk_len = *data)) {
11749 if (((unsigned char *) data)[0] & 0xc0) {
11750 data += 1;
11751 break;
11752 }
11753 data += chunk_len + 1;
11754 }
11755
11756 if (data > end - 5) {
11757 return NULL;
11758 }
11759
11760 rr->name.p = (char *) name;
11761 rr->name.len = data - name + 1;
11762 data++;
11763
11764 rr->rtype = data[0] << 8 | data[1];
11765 data += 2;
11766
11767 rr->rclass = data[0] << 8 | data[1];
11768 data += 2;
11769
11770 rr->kind = reply ? MG_DNS_ANSWER : MG_DNS_QUESTION;
11771 if (reply) {
11772 if (data >= end - 6) {
11773 return NULL;
11774 }
11775
11776 rr->ttl = (uint32_t) data[0] << 24 | (uint32_t) data[1] << 16 |
11777 data[2] << 8 | data[3];
11778 data += 4;
11779
11780 data_len = *data << 8 | *(data + 1);
11781 data += 2;
11782
11783 rr->rdata.p = (char *) data;
11784 rr->rdata.len = data_len;
11785 data += data_len;
11786 }
11787 return data;
11788 }
11789
11790 int mg_parse_dns(const char *buf, int len, struct mg_dns_message *msg) {
11791 struct mg_dns_header *header = (struct mg_dns_header *) buf;
11792 unsigned char *data = (unsigned char *) buf + sizeof(*header);
11793 unsigned char *end = (unsigned char *) buf + len;
11794 int i;
11795
11796 memset(msg, 0, sizeof(*msg));
11797 msg->pkt.p = buf;
11798 msg->pkt.len = len;
11799
11800 if (len < (int) sizeof(*header)) return -1;
11801
11802 msg->transaction_id = header->transaction_id;
11803 msg->flags = ntohs(header->flags);
11804 msg->num_questions = ntohs(header->num_questions);
11805 if (msg->num_questions > (int) ARRAY_SIZE(msg->questions)) {
11806 msg->num_questions = (int) ARRAY_SIZE(msg->questions);
11807 }
11808 msg->num_answers = ntohs(header->num_answers);
11809 if (msg->num_answers > (int) ARRAY_SIZE(msg->answers)) {
11810 msg->num_answers = (int) ARRAY_SIZE(msg->answers);
11811 }
11812
11813 for (i = 0; i < msg->num_questions; i++) {
11814 data = mg_parse_dns_resource_record(data, end, &msg->questions[i], 0);
11815 if (data == NULL) return -1;
11816 }
11817
11818 for (i = 0; i < msg->num_answers; i++) {
11819 data = mg_parse_dns_resource_record(data, end, &msg->answers[i], 1);
11820 if (data == NULL) return -1;
11821 }
11822
11823 return 0;
11824 }
11825
11826 size_t mg_dns_uncompress_name(struct mg_dns_message *msg, struct mg_str *name,
11827 char *dst, int dst_len) {
11828 int chunk_len, num_ptrs = 0;
11829 char *old_dst = dst;
11830 const unsigned char *data = (unsigned char *) name->p;
11831 const unsigned char *end = (unsigned char *) msg->pkt.p + msg->pkt.len;
11832
11833 if (data >= end) {
11834 return 0;
11835 }
11836
11837 while ((chunk_len = *data++)) {
11838 int leeway = dst_len - (dst - old_dst);
11839 if (data >= end) {
11840 return 0;
11841 }
11842
11843 if ((chunk_len & 0xc0) == 0xc0) {
11844 uint16_t off = (data[-1] & (~0xc0)) << 8 | data[0];
11845 if (off >= msg->pkt.len) {
11846 return 0;
11847 }
11848 /* Basic circular loop avoidance: allow up to 16 pointer hops. */
11849 if (++num_ptrs > 15) {
11850 return 0;
11851 }
11852 data = (unsigned char *) msg->pkt.p + off;
11853 continue;
11854 }
11855 if (chunk_len > 63) {
11856 return 0;
11857 }
11858 if (chunk_len > leeway) {
11859 chunk_len = leeway;
11860 }
11861
11862 if (data + chunk_len >= end) {
11863 return 0;
11864 }
11865
11866 memcpy(dst, data, chunk_len);
11867 data += chunk_len;
11868 dst += chunk_len;
11869 leeway -= chunk_len;
11870 if (leeway == 0) {
11871 return dst - old_dst;
11872 }
11873 *dst++ = '.';
11874 }
11875
11876 if (dst != old_dst) {
11877 *--dst = 0;
11878 }
11879 return dst - old_dst;
11880 }
11881
11882 static void dns_handler(struct mg_connection *nc, int ev,
11883 void *ev_data MG_UD_ARG(void *user_data)) {
11884 struct mbuf *io = &nc->recv_mbuf;
11885 struct mg_dns_message msg;
11886
11887 /* Pass low-level events to the user handler */
11888 nc->handler(nc, ev, ev_data MG_UD_ARG(user_data));
11889
11890 switch (ev) {
11891 case MG_EV_RECV:
11892 if (!(nc->flags & MG_F_UDP)) {
11893 mbuf_remove(&nc->recv_mbuf, 2);
11894 }
11895 if (mg_parse_dns(nc->recv_mbuf.buf, nc->recv_mbuf.len, &msg) == -1) {
11896 /* reply + recursion allowed + format error */
11897 memset(&msg, 0, sizeof(msg));
11898 msg.flags = 0x8081;
11899 mg_dns_insert_header(io, 0, &msg);
11900 if (!(nc->flags & MG_F_UDP)) {
11901 uint16_t len = htons((uint16_t) io->len);
11902 mbuf_insert(io, 0, &len, 2);
11903 }
11904 mg_send(nc, io->buf, io->len);
11905 } else {
11906 /* Call user handler with parsed message */
11907 nc->handler(nc, MG_DNS_MESSAGE, &msg MG_UD_ARG(user_data));
11908 }
11909 mbuf_remove(io, io->len);
11910 break;
11911 }
11912 }
11913
11914 void mg_set_protocol_dns(struct mg_connection *nc) {
11915 nc->proto_handler = dns_handler;
11916 }
11917
11918 #endif /* MG_ENABLE_DNS */
11919 #ifdef MG_MODULE_LINES
11920 #line 1 "mongoose/src/mg_dns_server.c"
11921 #endif
11922 /*
11923 * Copyright (c) 2014 Cesanta Software Limited
11924 * All rights reserved
11925 */
11926
11927 #if MG_ENABLE_DNS_SERVER
11928
11929 /* Amalgamated: #include "mg_internal.h" */
11930 /* Amalgamated: #include "dns-server.h" */
11931
11932 struct mg_dns_reply mg_dns_create_reply(struct mbuf *io,
11933 struct mg_dns_message *msg) {
11934 struct mg_dns_reply rep;
11935 rep.msg = msg;
11936 rep.io = io;
11937 rep.start = io->len;
11938
11939 /* reply + recursion allowed */
11940 msg->flags |= 0x8080;
11941 mg_dns_copy_questions(io, msg);
11942
11943 msg->num_answers = 0;
11944 return rep;
11945 }
11946
11947 void mg_dns_send_reply(struct mg_connection *nc, struct mg_dns_reply *r) {
11948 size_t sent = r->io->len - r->start;
11949 mg_dns_insert_header(r->io, r->start, r->msg);
11950 if (!(nc->flags & MG_F_UDP)) {
11951 uint16_t len = htons((uint16_t) sent);
11952 mbuf_insert(r->io, r->start, &len, 2);
11953 }
11954
11955 if (&nc->send_mbuf != r->io) {
11956 mg_send(nc, r->io->buf + r->start, r->io->len - r->start);
11957 r->io->len = r->start;
11958 }
11959 }
11960
11961 int mg_dns_reply_record(struct mg_dns_reply *reply,
11962 struct mg_dns_resource_record *question,
11963 const char *name, int rtype, int ttl, const void *rdata,
11964 size_t rdata_len) {
11965 struct mg_dns_message *msg = (struct mg_dns_message *) reply->msg;
11966 char rname[512];
11967 struct mg_dns_resource_record *ans = &msg->answers[msg->num_answers];
11968 if (msg->num_answers >= MG_MAX_DNS_ANSWERS) {
11969 return -1; /* LCOV_EXCL_LINE */
11970 }
11971
11972 if (name == NULL) {
11973 name = rname;
11974 rname[511] = 0;
11975 mg_dns_uncompress_name(msg, &question->name, rname, sizeof(rname) - 1);
11976 }
11977
11978 *ans = *question;
11979 ans->kind = MG_DNS_ANSWER;
11980 ans->rtype = rtype;
11981 ans->ttl = ttl;
11982
11983 if (mg_dns_encode_record(reply->io, ans, name, strlen(name), rdata,
11984 rdata_len) == -1) {
11985 return -1; /* LCOV_EXCL_LINE */
11986 };
11987
11988 msg->num_answers++;
11989 return 0;
11990 }
11991
11992 #endif /* MG_ENABLE_DNS_SERVER */
11993 #ifdef MG_MODULE_LINES
11994 #line 1 "mongoose/src/mg_resolv.c"
11995 #endif
11996 /*
11997 * Copyright (c) 2014 Cesanta Software Limited
11998 * All rights reserved
11999 */
12000
12001 #if MG_ENABLE_ASYNC_RESOLVER
12002
12003 /* Amalgamated: #include "mg_internal.h" */
12004 /* Amalgamated: #include "mg_resolv.h" */
12005
12006 #ifndef MG_DEFAULT_NAMESERVER
12007 #define MG_DEFAULT_NAMESERVER "8.8.8.8"
12008 #endif
12009
12010 struct mg_resolve_async_request {
12011 char name[1024];
12012 int query;
12013 mg_resolve_callback_t callback;
12014 void *data;
12015 time_t timeout;
12016 int max_retries;
12017 enum mg_resolve_err err;
12018
12019 /* state */
12020 time_t last_time;
12021 int retries;
12022 };
12023
12024 /*
12025 * Find what nameserver to use.
12026 *
12027 * Return 0 if OK, -1 if error
12028 */
12029 static int mg_get_ip_address_of_nameserver(char *name, size_t name_len) {
12030 int ret = -1;
12031
12032 #ifdef _WIN32
12033 int i;
12034 LONG err;
12035 HKEY hKey, hSub;
12036 wchar_t subkey[512], value[128],
12037 *key = L"SYSTEM\\ControlSet001\\Services\\Tcpip\\Parameters\\Interfaces";
12038
12039 if ((err = RegOpenKeyExW(HKEY_LOCAL_MACHINE, key, 0, KEY_READ, &hKey)) !=
12040 ERROR_SUCCESS) {
12041 fprintf(stderr, "cannot open reg key %S: %ld\n", key, err);
12042 ret = -1;
12043 } else {
12044 for (ret = -1, i = 0; 1; i++) {
12045 DWORD subkey_size = sizeof(subkey), type, len = sizeof(value);
12046 if (RegEnumKeyExW(hKey, i, subkey, &subkey_size, NULL, NULL, NULL,
12047 NULL) != ERROR_SUCCESS) {
12048 break;
12049 }
12050 if (RegOpenKeyExW(hKey, subkey, 0, KEY_READ, &hSub) == ERROR_SUCCESS &&
12051 ((RegQueryValueExW(hSub, L"NameServer", 0, &type, (void *) value,
12052 &len) == ERROR_SUCCESS &&
12053 value[0] != '\0') ||
12054 (RegQueryValueExW(hSub, L"DhcpNameServer", 0, &type, (void *) value,
12055 &len) == ERROR_SUCCESS &&
12056 value[0] != '\0'))) {
12057 /*
12058 * See https://github.com/cesanta/mongoose/issues/176
12059 * The value taken from the registry can be empty, a single
12060 * IP address, or multiple IP addresses separated by comma.
12061 * If it's empty, check the next interface.
12062 * If it's multiple IP addresses, take the first one.
12063 */
12064 wchar_t *comma = wcschr(value, ',');
12065 if (comma != NULL) {
12066 *comma = '\0';
12067 }
12068 /* %S will convert wchar_t -> char */
12069 snprintf(name, name_len, "%S", value);
12070 ret = 0;
12071 RegCloseKey(hSub);
12072 break;
12073 }
12074 }
12075 RegCloseKey(hKey);
12076 }
12077 #elif MG_ENABLE_FILESYSTEM && defined(MG_RESOLV_CONF_FILE_NAME)
12078 FILE *fp;
12079 char line[512];
12080
12081 if ((fp = mg_fopen(MG_RESOLV_CONF_FILE_NAME, "r")) == NULL) {
12082 ret = -1;
12083 } else {
12084 /* Try to figure out what nameserver to use */
12085 for (ret = -1; fgets(line, sizeof(line), fp) != NULL;) {
12086 unsigned int a, b, c, d;
12087 if (sscanf(line, "nameserver %u.%u.%u.%u", &a, &b, &c, &d) == 4) {
12088 snprintf(name, name_len, "%u.%u.%u.%u", a, b, c, d);
12089 ret = 0;
12090 break;
12091 }
12092 }
12093 (void) fclose(fp);
12094 }
12095 #else
12096 snprintf(name, name_len, "%s", MG_DEFAULT_NAMESERVER);
12097 #endif /* _WIN32 */
12098
12099 return ret;
12100 }
12101
12102 int mg_resolve_from_hosts_file(const char *name, union socket_address *usa) {
12103 #if MG_ENABLE_FILESYSTEM && defined(MG_HOSTS_FILE_NAME)
12104 /* TODO(mkm) cache /etc/hosts */
12105 FILE *fp;
12106 char line[1024];
12107 char *p;
12108 char alias[256];
12109 unsigned int a, b, c, d;
12110 int len = 0;
12111
12112 if ((fp = mg_fopen(MG_HOSTS_FILE_NAME, "r")) == NULL) {
12113 return -1;
12114 }
12115
12116 for (; fgets(line, sizeof(line), fp) != NULL;) {
12117 if (line[0] == '#') continue;
12118
12119 if (sscanf(line, "%u.%u.%u.%u%n", &a, &b, &c, &d, &len) == 0) {
12120 /* TODO(mkm): handle ipv6 */
12121 continue;
12122 }
12123 for (p = line + len; sscanf(p, "%s%n", alias, &len) == 1; p += len) {
12124 if (strcmp(alias, name) == 0) {
12125 usa->sin.sin_addr.s_addr = htonl(a << 24 | b << 16 | c << 8 | d);
12126 fclose(fp);
12127 return 0;
12128 }
12129 }
12130 }
12131
12132 fclose(fp);
12133 #else
12134 (void) name;
12135 (void) usa;
12136 #endif
12137
12138 return -1;
12139 }
12140
12141 static void mg_resolve_async_eh(struct mg_connection *nc, int ev,
12142 void *data MG_UD_ARG(void *user_data)) {
12143 time_t now = (time_t) mg_time();
12144 struct mg_resolve_async_request *req;
12145 struct mg_dns_message *msg;
12146 #if !MG_ENABLE_CALLBACK_USERDATA
12147 void *user_data = nc->user_data;
12148 #endif
12149
12150 if (ev != MG_EV_POLL) {
12151 DBG(("ev=%d user_data=%p", ev, user_data));
12152 }
12153
12154 req = (struct mg_resolve_async_request *) user_data;
12155
12156 if (req == NULL) {
12157 return;
12158 }
12159
12160 switch (ev) {
12161 case MG_EV_POLL:
12162 if (req->retries > req->max_retries) {
12163 req->err = MG_RESOLVE_EXCEEDED_RETRY_COUNT;
12164 nc->flags |= MG_F_CLOSE_IMMEDIATELY;
12165 break;
12166 }
12167 if (nc->flags & MG_F_CONNECTING) break;
12168 /* fallthrough */
12169 case MG_EV_CONNECT:
12170 if (req->retries == 0 || now - req->last_time >= req->timeout) {
12171 mg_send_dns_query(nc, req->name, req->query);
12172 req->last_time = now;
12173 req->retries++;
12174 }
12175 break;
12176 case MG_EV_RECV:
12177 msg = (struct mg_dns_message *) MG_MALLOC(sizeof(*msg));
12178 if (mg_parse_dns(nc->recv_mbuf.buf, *(int *) data, msg) == 0 &&
12179 msg->num_answers > 0) {
12180 req->callback(msg, req->data, MG_RESOLVE_OK);
12181 nc->user_data = NULL;
12182 MG_FREE(req);
12183 } else {
12184 req->err = MG_RESOLVE_NO_ANSWERS;
12185 }
12186 MG_FREE(msg);
12187 nc->flags |= MG_F_CLOSE_IMMEDIATELY;
12188 break;
12189 case MG_EV_SEND:
12190 /*
12191 * If a send error occurs, prevent closing of the connection by the core.
12192 * We will retry after timeout.
12193 */
12194 nc->flags &= ~MG_F_CLOSE_IMMEDIATELY;
12195 mbuf_remove(&nc->send_mbuf, nc->send_mbuf.len);
12196 break;
12197 case MG_EV_TIMER:
12198 req->err = MG_RESOLVE_TIMEOUT;
12199 nc->flags |= MG_F_CLOSE_IMMEDIATELY;
12200 break;
12201 case MG_EV_CLOSE:
12202 /* If we got here with request still not done, fire an error callback. */
12203 if (req != NULL) {
12204 char addr[32];
12205 mg_sock_addr_to_str(&nc->sa, addr, sizeof(addr), MG_SOCK_STRINGIFY_IP);
12206 #ifdef MG_LOG_DNS_FAILURES
12207 LOG(LL_ERROR, ("Failed to resolve '%s', server %s", req->name, addr));
12208 #endif
12209 req->callback(NULL, req->data, req->err);
12210 nc->user_data = NULL;
12211 MG_FREE(req);
12212 }
12213 break;
12214 }
12215 }
12216
12217 int mg_resolve_async(struct mg_mgr *mgr, const char *name, int query,
12218 mg_resolve_callback_t cb, void *data) {
12219 struct mg_resolve_async_opts opts;
12220 memset(&opts, 0, sizeof(opts));
12221 return mg_resolve_async_opt(mgr, name, query, cb, data, opts);
12222 }
12223
12224 int mg_resolve_async_opt(struct mg_mgr *mgr, const char *name, int query,
12225 mg_resolve_callback_t cb, void *data,
12226 struct mg_resolve_async_opts opts) {
12227 struct mg_resolve_async_request *req;
12228 struct mg_connection *dns_nc;
12229 const char *nameserver = opts.nameserver;
12230 char dns_server_buff[17], nameserver_url[26];
12231
12232 if (nameserver == NULL) {
12233 nameserver = mgr->nameserver;
12234 }
12235
12236 DBG(("%s %d %p", name, query, opts.dns_conn));
12237
12238 /* resolve with DNS */
12239 req = (struct mg_resolve_async_request *) MG_CALLOC(1, sizeof(*req));
12240 if (req == NULL) {
12241 return -1;
12242 }
12243
12244 strncpy(req->name, name, sizeof(req->name));
12245 req->name[sizeof(req->name) - 1] = '\0';
12246
12247 req->query = query;
12248 req->callback = cb;
12249 req->data = data;
12250 /* TODO(mkm): parse defaults out of resolve.conf */
12251 req->max_retries = opts.max_retries ? opts.max_retries : 2;
12252 req->timeout = opts.timeout ? opts.timeout : 5;
12253
12254 /* Lazily initialize dns server */
12255 if (nameserver == NULL) {
12256 if (mg_get_ip_address_of_nameserver(dns_server_buff,
12257 sizeof(dns_server_buff)) != -1) {
12258 nameserver = dns_server_buff;
12259 } else {
12260 nameserver = MG_DEFAULT_NAMESERVER;
12261 }
12262 }
12263
12264 snprintf(nameserver_url, sizeof(nameserver_url), "udp://%s:53", nameserver);
12265
12266 dns_nc = mg_connect(mgr, nameserver_url, MG_CB(mg_resolve_async_eh, NULL));
12267 if (dns_nc == NULL) {
12268 MG_FREE(req);
12269 return -1;
12270 }
12271 dns_nc->user_data = req;
12272 if (opts.dns_conn != NULL) {
12273 *opts.dns_conn = dns_nc;
12274 }
12275
12276 return 0;
12277 }
12278
12279 void mg_set_nameserver(struct mg_mgr *mgr, const char *nameserver) {
12280 MG_FREE((char *) mgr->nameserver);
12281 mgr->nameserver = NULL;
12282 if (nameserver != NULL) {
12283 mgr->nameserver = strdup(nameserver);
12284 }
12285 }
12286
12287 #endif /* MG_ENABLE_ASYNC_RESOLVER */
12288 #ifdef MG_MODULE_LINES
12289 #line 1 "mongoose/src/mg_coap.c"
12290 #endif
12291 /*
12292 * Copyright (c) 2015 Cesanta Software Limited
12293 * All rights reserved
12294 * This software is dual-licensed: you can redistribute it and/or modify
12295 * it under the terms of the GNU General Public License version 2 as
12296 * published by the Free Software Foundation. For the terms of this
12297 * license, see <http://www.gnu.org/licenses/>.
12298 *
12299 * You are free to use this software under the terms of the GNU General
12300 * Public License, but WITHOUT ANY WARRANTY; without even the implied
12301 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12302 * See the GNU General Public License for more details.
12303 *
12304 * Alternatively, you can license this software under a commercial
12305 * license, as set out in <https://www.cesanta.com/license>.
12306 */
12307
12308 /* Amalgamated: #include "mg_internal.h" */
12309 /* Amalgamated: #include "mg_coap.h" */
12310
12311 #if MG_ENABLE_COAP
12312
12313 void mg_coap_free_options(struct mg_coap_message *cm) {
12314 while (cm->options != NULL) {
12315 struct mg_coap_option *next = cm->options->next;
12316 MG_FREE(cm->options);
12317 cm->options = next;
12318 }
12319 }
12320
12321 struct mg_coap_option *mg_coap_add_option(struct mg_coap_message *cm,
12322 uint32_t number, char *value,
12323 size_t len) {
12324 struct mg_coap_option *new_option =
12325 (struct mg_coap_option *) MG_CALLOC(1, sizeof(*new_option));
12326
12327 new_option->number = number;
12328 new_option->value.p = value;
12329 new_option->value.len = len;
12330
12331 if (cm->options == NULL) {
12332 cm->options = cm->optiomg_tail = new_option;
12333 } else {
12334 /*
12335 * A very simple attention to help clients to compose options:
12336 * CoAP wants to see options ASC ordered.
12337 * Could be change by using sort in coap_compose
12338 */
12339 if (cm->optiomg_tail->number <= new_option->number) {
12340 /* if option is already ordered just add it */
12341 cm->optiomg_tail = cm->optiomg_tail->next = new_option;
12342 } else {
12343 /* looking for appropriate position */
12344 struct mg_coap_option *current_opt = cm->options;
12345 struct mg_coap_option *prev_opt = 0;
12346
12347 while (current_opt != NULL) {
12348 if (current_opt->number > new_option->number) {
12349 break;
12350 }
12351 prev_opt = current_opt;
12352 current_opt = current_opt->next;
12353 }
12354
12355 if (prev_opt != NULL) {
12356 prev_opt->next = new_option;
12357 new_option->next = current_opt;
12358 } else {
12359 /* insert new_option to the beginning */
12360 new_option->next = cm->options;
12361 cm->options = new_option;
12362 }
12363 }
12364 }
12365
12366 return new_option;
12367 }
12368
12369 /*
12370 * Fills CoAP header in mg_coap_message.
12371 *
12372 * Helper function.
12373 */
12374 static char *coap_parse_header(char *ptr, struct mbuf *io,
12375 struct mg_coap_message *cm) {
12376 if (io->len < sizeof(uint32_t)) {
12377 cm->flags |= MG_COAP_NOT_ENOUGH_DATA;
12378 return NULL;
12379 }
12380
12381 /*
12382 * Version (Ver): 2-bit unsigned integer. Indicates the CoAP version
12383 * number. Implementations of this specification MUST set this field
12384 * to 1 (01 binary). Other values are reserved for future versions.
12385 * Messages with unknown version numbers MUST be silently ignored.
12386 */
12387 if (((uint8_t) *ptr >> 6) != 1) {
12388 cm->flags |= MG_COAP_IGNORE;
12389 return NULL;
12390 }
12391
12392 /*
12393 * Type (T): 2-bit unsigned integer. Indicates if this message is of
12394 * type Confirmable (0), Non-confirmable (1), Acknowledgement (2), or
12395 * Reset (3).
12396 */
12397 cm->msg_type = ((uint8_t) *ptr & 0x30) >> 4;
12398 cm->flags |= MG_COAP_MSG_TYPE_FIELD;
12399
12400 /*
12401 * Token Length (TKL): 4-bit unsigned integer. Indicates the length of
12402 * the variable-length Token field (0-8 bytes). Lengths 9-15 are
12403 * reserved, MUST NOT be sent, and MUST be processed as a message
12404 * format error.
12405 */
12406 cm->token.len = *ptr & 0x0F;
12407 if (cm->token.len > 8) {
12408 cm->flags |= MG_COAP_FORMAT_ERROR;
12409 return NULL;
12410 }
12411
12412 ptr++;
12413
12414 /*
12415 * Code: 8-bit unsigned integer, split into a 3-bit class (most
12416 * significant bits) and a 5-bit detail (least significant bits)
12417 */
12418 cm->code_class = (uint8_t) *ptr >> 5;
12419 cm->code_detail = *ptr & 0x1F;
12420 cm->flags |= (MG_COAP_CODE_CLASS_FIELD | MG_COAP_CODE_DETAIL_FIELD);
12421
12422 ptr++;
12423
12424 /* Message ID: 16-bit unsigned integer in network byte order. */
12425 cm->msg_id = (uint8_t) *ptr << 8 | (uint8_t) * (ptr + 1);
12426 cm->flags |= MG_COAP_MSG_ID_FIELD;
12427
12428 ptr += 2;
12429
12430 return ptr;
12431 }
12432
12433 /*
12434 * Fills token information in mg_coap_message.
12435 *
12436 * Helper function.
12437 */
12438 static char *coap_get_token(char *ptr, struct mbuf *io,
12439 struct mg_coap_message *cm) {
12440 if (cm->token.len != 0) {
12441 if (ptr + cm->token.len > io->buf + io->len) {
12442 cm->flags |= MG_COAP_NOT_ENOUGH_DATA;
12443 return NULL;
12444 } else {
12445 cm->token.p = ptr;
12446 ptr += cm->token.len;
12447 cm->flags |= MG_COAP_TOKEN_FIELD;
12448 }
12449 }
12450
12451 return ptr;
12452 }
12453
12454 /*
12455 * Returns Option Delta or Length.
12456 *
12457 * Helper function.
12458 */
12459 static int coap_get_ext_opt(char *ptr, struct mbuf *io, uint16_t *opt_info) {
12460 int ret = 0;
12461
12462 if (*opt_info == 13) {
12463 /*
12464 * 13: An 8-bit unsigned integer follows the initial byte and
12465 * indicates the Option Delta/Length minus 13.
12466 */
12467 if (ptr < io->buf + io->len) {
12468 *opt_info = (uint8_t) *ptr + 13;
12469 ret = sizeof(uint8_t);
12470 } else {
12471 ret = -1; /* LCOV_EXCL_LINE */
12472 }
12473 } else if (*opt_info == 14) {
12474 /*
12475 * 14: A 16-bit unsigned integer in network byte order follows the
12476 * initial byte and indicates the Option Delta/Length minus 269.
12477 */
12478 if (ptr + sizeof(uint8_t) < io->buf + io->len) {
12479 *opt_info = ((uint8_t) *ptr << 8 | (uint8_t) * (ptr + 1)) + 269;
12480 ret = sizeof(uint16_t);
12481 } else {
12482 ret = -1; /* LCOV_EXCL_LINE */
12483 }
12484 }
12485
12486 return ret;
12487 }
12488
12489 /*
12490 * Fills options in mg_coap_message.
12491 *
12492 * Helper function.
12493 *
12494 * General options format:
12495 * +---------------+---------------+
12496 * | Option Delta | Option Length | 1 byte
12497 * +---------------+---------------+
12498 * \ Option Delta (extended) \ 0-2 bytes
12499 * +-------------------------------+
12500 * / Option Length (extended) \ 0-2 bytes
12501 * +-------------------------------+
12502 * \ Option Value \ 0 or more bytes
12503 * +-------------------------------+
12504 */
12505 static char *coap_get_options(char *ptr, struct mbuf *io,
12506 struct mg_coap_message *cm) {
12507 uint16_t prev_opt = 0;
12508
12509 if (ptr == io->buf + io->len) {
12510 /* end of packet, ok */
12511 return NULL;
12512 }
12513
12514 /* 0xFF is payload marker */
12515 while (ptr < io->buf + io->len && (uint8_t) *ptr != 0xFF) {
12516 uint16_t option_delta, option_lenght;
12517 int optinfo_len;
12518
12519 /* Option Delta: 4-bit unsigned integer */
12520 option_delta = ((uint8_t) *ptr & 0xF0) >> 4;
12521 /* Option Length: 4-bit unsigned integer */
12522 option_lenght = *ptr & 0x0F;
12523
12524 if (option_delta == 15 || option_lenght == 15) {
12525 /*
12526 * 15: Reserved for future use. If the field is set to this value,
12527 * it MUST be processed as a message format error
12528 */
12529 cm->flags |= MG_COAP_FORMAT_ERROR;
12530 break;
12531 }
12532
12533 ptr++;
12534
12535 /* check for extended option delta */
12536 optinfo_len = coap_get_ext_opt(ptr, io, &option_delta);
12537 if (optinfo_len == -1) {
12538 cm->flags |= MG_COAP_NOT_ENOUGH_DATA; /* LCOV_EXCL_LINE */
12539 break; /* LCOV_EXCL_LINE */
12540 }
12541
12542 ptr += optinfo_len;
12543
12544 /* check or extended option lenght */
12545 optinfo_len = coap_get_ext_opt(ptr, io, &option_lenght);
12546 if (optinfo_len == -1) {
12547 cm->flags |= MG_COAP_NOT_ENOUGH_DATA; /* LCOV_EXCL_LINE */
12548 break; /* LCOV_EXCL_LINE */
12549 }
12550
12551 ptr += optinfo_len;
12552
12553 /*
12554 * Instead of specifying the Option Number directly, the instances MUST
12555 * appear in order of their Option Numbers and a delta encoding is used
12556 * between them.
12557 */
12558 option_delta += prev_opt;
12559
12560 mg_coap_add_option(cm, option_delta, ptr, option_lenght);
12561
12562 prev_opt = option_delta;
12563
12564 if (ptr + option_lenght > io->buf + io->len) {
12565 cm->flags |= MG_COAP_NOT_ENOUGH_DATA; /* LCOV_EXCL_LINE */
12566 break; /* LCOV_EXCL_LINE */
12567 }
12568
12569 ptr += option_lenght;
12570 }
12571
12572 if ((cm->flags & MG_COAP_ERROR) != 0) {
12573 mg_coap_free_options(cm);
12574 return NULL;
12575 }
12576
12577 cm->flags |= MG_COAP_OPTIOMG_FIELD;
12578
12579 if (ptr == io->buf + io->len) {
12580 /* end of packet, ok */
12581 return NULL;
12582 }
12583
12584 ptr++;
12585
12586 return ptr;
12587 }
12588
12589 uint32_t mg_coap_parse(struct mbuf *io, struct mg_coap_message *cm) {
12590 char *ptr;
12591
12592 memset(cm, 0, sizeof(*cm));
12593
12594 if ((ptr = coap_parse_header(io->buf, io, cm)) == NULL) {
12595 return cm->flags;
12596 }
12597
12598 if ((ptr = coap_get_token(ptr, io, cm)) == NULL) {
12599 return cm->flags;
12600 }
12601
12602 if ((ptr = coap_get_options(ptr, io, cm)) == NULL) {
12603 return cm->flags;
12604 }
12605
12606 /* the rest is payload */
12607 cm->payload.len = io->len - (ptr - io->buf);
12608 if (cm->payload.len != 0) {
12609 cm->payload.p = ptr;
12610 cm->flags |= MG_COAP_PAYLOAD_FIELD;
12611 }
12612
12613 return cm->flags;
12614 }
12615
12616 /*
12617 * Calculates extended size of given Opt Number/Length in coap message.
12618 *
12619 * Helper function.
12620 */
12621 static size_t coap_get_ext_opt_size(uint32_t value) {
12622 int ret = 0;
12623
12624 if (value >= 13 && value <= 0xFF + 13) {
12625 ret = sizeof(uint8_t);
12626 } else if (value > 0xFF + 13 && value <= 0xFFFF + 269) {
12627 ret = sizeof(uint16_t);
12628 }
12629
12630 return ret;
12631 }
12632
12633 /*
12634 * Splits given Opt Number/Length into base and ext values.
12635 *
12636 * Helper function.
12637 */
12638 static int coap_split_opt(uint32_t value, uint8_t *base, uint16_t *ext) {
12639 int ret = 0;
12640
12641 if (value < 13) {
12642 *base = value;
12643 } else if (value >= 13 && value <= 0xFF + 13) {
12644 *base = 13;
12645 *ext = value - 13;
12646 ret = sizeof(uint8_t);
12647 } else if (value > 0xFF + 13 && value <= 0xFFFF + 269) {
12648 *base = 14;
12649 *ext = value - 269;
12650 ret = sizeof(uint16_t);
12651 }
12652
12653 return ret;
12654 }
12655
12656 /*
12657 * Puts uint16_t (in network order) into given char stream.
12658 *
12659 * Helper function.
12660 */
12661 static char *coap_add_uint16(char *ptr, uint16_t val) {
12662 *ptr = val >> 8;
12663 ptr++;
12664 *ptr = val & 0x00FF;
12665 ptr++;
12666 return ptr;
12667 }
12668
12669 /*
12670 * Puts extended value of Opt Number/Length into given char stream.
12671 *
12672 * Helper function.
12673 */
12674 static char *coap_add_opt_info(char *ptr, uint16_t val, size_t len) {
12675 if (len == sizeof(uint8_t)) {
12676 *ptr = (char) val;
12677 ptr++;
12678 } else if (len == sizeof(uint16_t)) {
12679 ptr = coap_add_uint16(ptr, val);
12680 }
12681
12682 return ptr;
12683 }
12684
12685 /*
12686 * Verifies given mg_coap_message and calculates message size for it.
12687 *
12688 * Helper function.
12689 */
12690 static uint32_t coap_calculate_packet_size(struct mg_coap_message *cm,
12691 size_t *len) {
12692 struct mg_coap_option *opt;
12693 uint32_t prev_opt_number;
12694
12695 *len = 4; /* header */
12696 if (cm->msg_type > MG_COAP_MSG_MAX) {
12697 return MG_COAP_ERROR | MG_COAP_MSG_TYPE_FIELD;
12698 }
12699 if (cm->token.len > 8) {
12700 return MG_COAP_ERROR | MG_COAP_TOKEN_FIELD;
12701 }
12702 if (cm->code_class > 7) {
12703 return MG_COAP_ERROR | MG_COAP_CODE_CLASS_FIELD;
12704 }
12705 if (cm->code_detail > 31) {
12706 return MG_COAP_ERROR | MG_COAP_CODE_DETAIL_FIELD;
12707 }
12708
12709 *len += cm->token.len;
12710 if (cm->payload.len != 0) {
12711 *len += cm->payload.len + 1; /* ... + 1; add payload marker */
12712 }
12713
12714 opt = cm->options;
12715 prev_opt_number = 0;
12716 while (opt != NULL) {
12717 *len += 1; /* basic delta/length */
12718 *len += coap_get_ext_opt_size(opt->number - prev_opt_number);
12719 *len += coap_get_ext_opt_size((uint32_t) opt->value.len);
12720 /*
12721 * Current implementation performs check if
12722 * option_number > previous option_number and produces an error
12723 * TODO(alashkin): write design doc with limitations
12724 * May be resorting is more suitable solution.
12725 */
12726 if ((opt->next != NULL && opt->number > opt->next->number) ||
12727 opt->value.len > 0xFFFF + 269 ||
12728 opt->number - prev_opt_number > 0xFFFF + 269) {
12729 return MG_COAP_ERROR | MG_COAP_OPTIOMG_FIELD;
12730 }
12731 *len += opt->value.len;
12732 prev_opt_number = opt->number;
12733 opt = opt->next;
12734 }
12735
12736 return 0;
12737 }
12738
12739 uint32_t mg_coap_compose(struct mg_coap_message *cm, struct mbuf *io) {
12740 struct mg_coap_option *opt;
12741 uint32_t res, prev_opt_number;
12742 size_t prev_io_len, packet_size;
12743 char *ptr;
12744
12745 res = coap_calculate_packet_size(cm, &packet_size);
12746 if (res != 0) {
12747 return res;
12748 }
12749
12750 /* saving previous lenght to handle non-empty mbuf */
12751 prev_io_len = io->len;
12752 if (mbuf_append(io, NULL, packet_size) == 0) return MG_COAP_ERROR;
12753 ptr = io->buf + prev_io_len;
12754
12755 /*
12756 * since cm is verified, it is possible to use bits shift operator
12757 * without additional zeroing of unused bits
12758 */
12759
12760 /* ver: 2 bits, msg_type: 2 bits, toklen: 4 bits */
12761 *ptr = (1 << 6) | (cm->msg_type << 4) | (uint8_t)(cm->token.len);
12762 ptr++;
12763
12764 /* code class: 3 bits, code detail: 5 bits */
12765 *ptr = (cm->code_class << 5) | (cm->code_detail);
12766 ptr++;
12767
12768 ptr = coap_add_uint16(ptr, cm->msg_id);
12769
12770 if (cm->token.len != 0) {
12771 memcpy(ptr, cm->token.p, cm->token.len);
12772 ptr += cm->token.len;
12773 }
12774
12775 opt = cm->options;
12776 prev_opt_number = 0;
12777 while (opt != NULL) {
12778 uint8_t delta_base = 0, length_base = 0;
12779 uint16_t delta_ext = 0, length_ext = 0;
12780
12781 size_t opt_delta_len =
12782 coap_split_opt(opt->number - prev_opt_number, &delta_base, &delta_ext);
12783 size_t opt_lenght_len =
12784 coap_split_opt((uint32_t) opt->value.len, &length_base, &length_ext);
12785
12786 *ptr = (delta_base << 4) | length_base;
12787 ptr++;
12788
12789 ptr = coap_add_opt_info(ptr, delta_ext, opt_delta_len);
12790 ptr = coap_add_opt_info(ptr, length_ext, opt_lenght_len);
12791
12792 if (opt->value.len != 0) {
12793 memcpy(ptr, opt->value.p, opt->value.len);
12794 ptr += opt->value.len;
12795 }
12796
12797 prev_opt_number = opt->number;
12798 opt = opt->next;
12799 }
12800
12801 if (cm->payload.len != 0) {
12802 *ptr = (char) -1;
12803 ptr++;
12804 memcpy(ptr, cm->payload.p, cm->payload.len);
12805 }
12806
12807 return 0;
12808 }
12809
12810 uint32_t mg_coap_send_message(struct mg_connection *nc,
12811 struct mg_coap_message *cm) {
12812 struct mbuf packet_out;
12813 uint32_t compose_res;
12814
12815 mbuf_init(&packet_out, 0);
12816 compose_res = mg_coap_compose(cm, &packet_out);
12817 if (compose_res != 0) {
12818 return compose_res; /* LCOV_EXCL_LINE */
12819 }
12820
12821 mg_send(nc, packet_out.buf, (int) packet_out.len);
12822 mbuf_free(&packet_out);
12823
12824 return 0;
12825 }
12826
12827 uint32_t mg_coap_send_ack(struct mg_connection *nc, uint16_t msg_id) {
12828 struct mg_coap_message cm;
12829 memset(&cm, 0, sizeof(cm));
12830 cm.msg_type = MG_COAP_MSG_ACK;
12831 cm.msg_id = msg_id;
12832
12833 return mg_coap_send_message(nc, &cm);
12834 }
12835
12836 static void coap_handler(struct mg_connection *nc, int ev,
12837 void *ev_data MG_UD_ARG(void *user_data)) {
12838 struct mbuf *io = &nc->recv_mbuf;
12839 struct mg_coap_message cm;
12840 uint32_t parse_res;
12841
12842 memset(&cm, 0, sizeof(cm));
12843
12844 nc->handler(nc, ev, ev_data MG_UD_ARG(user_data));
12845
12846 switch (ev) {
12847 case MG_EV_RECV:
12848 parse_res = mg_coap_parse(io, &cm);
12849 if ((parse_res & MG_COAP_IGNORE) == 0) {
12850 if ((cm.flags & MG_COAP_NOT_ENOUGH_DATA) != 0) {
12851 /*
12852 * Since we support UDP only
12853 * MG_COAP_NOT_ENOUGH_DATA == MG_COAP_FORMAT_ERROR
12854 */
12855 cm.flags |= MG_COAP_FORMAT_ERROR; /* LCOV_EXCL_LINE */
12856 } /* LCOV_EXCL_LINE */
12857 nc->handler(nc, MG_COAP_EVENT_BASE + cm.msg_type,
12858 &cm MG_UD_ARG(user_data));
12859 }
12860
12861 mg_coap_free_options(&cm);
12862 mbuf_remove(io, io->len);
12863 break;
12864 }
12865 }
12866 /*
12867 * Attach built-in CoAP event handler to the given connection.
12868 *
12869 * The user-defined event handler will receive following extra events:
12870 *
12871 * - MG_EV_COAP_CON
12872 * - MG_EV_COAP_NOC
12873 * - MG_EV_COAP_ACK
12874 * - MG_EV_COAP_RST
12875 */
12876 int mg_set_protocol_coap(struct mg_connection *nc) {
12877 /* supports UDP only */
12878 if ((nc->flags & MG_F_UDP) == 0) {
12879 return -1;
12880 }
12881
12882 nc->proto_handler = coap_handler;
12883
12884 return 0;
12885 }
12886
12887 #endif /* MG_ENABLE_COAP */
12888 #ifdef MG_MODULE_LINES
12889 #line 1 "mongoose/src/mg_sntp.c"
12890 #endif
12891 /*
12892 * Copyright (c) 2016 Cesanta Software Limited
12893 * All rights reserved
12894 */
12895
12896 /* Amalgamated: #include "mg_internal.h" */
12897 /* Amalgamated: #include "mg_sntp.h" */
12898 /* Amalgamated: #include "mg_util.h" */
12899
12900 #if MG_ENABLE_SNTP
12901
12902 #define SNTP_TIME_OFFSET 2208988800
12903
12904 #ifndef SNTP_TIMEOUT
12905 #define SNTP_TIMEOUT 10
12906 #endif
12907
12908 #ifndef SNTP_ATTEMPTS
12909 #define SNTP_ATTEMPTS 3
12910 #endif
12911
12912 static uint64_t mg_get_sec(uint64_t val) {
12913 return (val & 0xFFFFFFFF00000000) >> 32;
12914 }
12915
12916 static uint64_t mg_get_usec(uint64_t val) {
12917 uint64_t tmp = (val & 0x00000000FFFFFFFF);
12918 tmp *= 1000000;
12919 tmp >>= 32;
12920 return tmp;
12921 }
12922
12923 static void mg_ntp_to_tv(uint64_t val, struct timeval *tv) {
12924 uint64_t tmp;
12925 tmp = mg_get_sec(val);
12926 tmp -= SNTP_TIME_OFFSET;
12927 tv->tv_sec = tmp;
12928 tv->tv_usec = mg_get_usec(val);
12929 }
12930
12931 static void mg_get_ntp_ts(const char *ntp, uint64_t *val) {
12932 uint32_t tmp;
12933 memcpy(&tmp, ntp, sizeof(tmp));
12934 tmp = ntohl(tmp);
12935 *val = (uint64_t) tmp << 32;
12936 memcpy(&tmp, ntp + 4, sizeof(tmp));
12937 tmp = ntohl(tmp);
12938 *val |= tmp;
12939 }
12940
12941 void mg_sntp_send_request(struct mg_connection *c) {
12942 uint8_t buf[48] = {0};
12943 /*
12944 * header - 8 bit:
12945 * LI (2 bit) - 3 (not in sync), VN (3 bit) - 4 (version),
12946 * mode (3 bit) - 3 (client)
12947 */
12948 buf[0] = (3 << 6) | (4 << 3) | 3;
12949
12950 /*
12951 * Next fields should be empty in client request
12952 * stratum, 8 bit
12953 * poll interval, 8 bit
12954 * rrecision, 8 bit
12955 * root delay, 32 bit
12956 * root dispersion, 32 bit
12957 * ref id, 32 bit
12958 * ref timestamp, 64 bit
12959 * originate Timestamp, 64 bit
12960 * receive Timestamp, 64 bit
12961 */
12962
12963 /*
12964 * convert time to sntp format (sntp starts from 00:00:00 01.01.1900)
12965 * according to rfc868 it is 2208988800L sec
12966 * this information is used to correct roundtrip delay
12967 * but if local clock is absolutely broken (and doesn't work even
12968 * as simple timer), it is better to disable it
12969 */
12970 #ifndef MG_SNTP_NO_DELAY_CORRECTION
12971 uint32_t sec;
12972 sec = htonl((uint32_t)(mg_time() + SNTP_TIME_OFFSET));
12973 memcpy(&buf[40], &sec, sizeof(sec));
12974 #endif
12975
12976 mg_send(c, buf, sizeof(buf));
12977 }
12978
12979 #ifndef MG_SNTP_NO_DELAY_CORRECTION
12980 static uint64_t mg_calculate_delay(uint64_t t1, uint64_t t2, uint64_t t3) {
12981 /* roundloop delay = (T4 - T1) - (T3 - T2) */
12982 uint64_t d1 = ((mg_time() + SNTP_TIME_OFFSET) * 1000000) -
12983 (mg_get_sec(t1) * 1000000 + mg_get_usec(t1));
12984 uint64_t d2 = (mg_get_sec(t3) * 1000000 + mg_get_usec(t3)) -
12985 (mg_get_sec(t2) * 1000000 + mg_get_usec(t2));
12986
12987 return (d1 > d2) ? d1 - d2 : 0;
12988 }
12989 #endif
12990
12991 MG_INTERNAL int mg_sntp_parse_reply(const char *buf, int len,
12992 struct mg_sntp_message *msg) {
12993 uint8_t hdr;
12994 uint64_t trsm_ts_T3, delay = 0;
12995 int mode;
12996 struct timeval tv;
12997
12998 if (len < 48) {
12999 return -1;
13000 }
13001
13002 hdr = buf[0];
13003
13004 if ((hdr & 0x38) >> 3 != 4) {
13005 /* Wrong version */
13006 return -1;
13007 }
13008
13009 mode = hdr & 0x7;
13010 if (mode != 4 && mode != 5) {
13011 /* Not a server reply */
13012 return -1;
13013 }
13014
13015 memset(msg, 0, sizeof(*msg));
13016
13017 msg->kiss_of_death = (buf[1] == 0); /* Server asks to not send requests */
13018
13019 mg_get_ntp_ts(&buf[40], &trsm_ts_T3);
13020
13021 #ifndef MG_SNTP_NO_DELAY_CORRECTION
13022 {
13023 uint64_t orig_ts_T1, recv_ts_T2;
13024 mg_get_ntp_ts(&buf[24], &orig_ts_T1);
13025 mg_get_ntp_ts(&buf[32], &recv_ts_T2);
13026 delay = mg_calculate_delay(orig_ts_T1, recv_ts_T2, trsm_ts_T3);
13027 }
13028 #endif
13029
13030 mg_ntp_to_tv(trsm_ts_T3, &tv);
13031
13032 msg->time = (double) tv.tv_sec + (((double) tv.tv_usec + delay) / 1000000.0);
13033
13034 return 0;
13035 }
13036
13037 static void mg_sntp_handler(struct mg_connection *c, int ev,
13038 void *ev_data MG_UD_ARG(void *user_data)) {
13039 struct mbuf *io = &c->recv_mbuf;
13040 struct mg_sntp_message msg;
13041
13042 c->handler(c, ev, ev_data MG_UD_ARG(user_data));
13043
13044 switch (ev) {
13045 case MG_EV_RECV: {
13046 if (mg_sntp_parse_reply(io->buf, io->len, &msg) < 0) {
13047 DBG(("Invalid SNTP packet received (%d)", (int) io->len));
13048 c->handler(c, MG_SNTP_MALFORMED_REPLY, NULL MG_UD_ARG(user_data));
13049 } else {
13050 c->handler(c, MG_SNTP_REPLY, (void *) &msg MG_UD_ARG(user_data));
13051 }
13052
13053 mbuf_remove(io, io->len);
13054 break;
13055 }
13056 }
13057 }
13058
13059 int mg_set_protocol_sntp(struct mg_connection *c) {
13060 if ((c->flags & MG_F_UDP) == 0) {
13061 return -1;
13062 }
13063
13064 c->proto_handler = mg_sntp_handler;
13065
13066 return 0;
13067 }
13068
13069 struct mg_connection *mg_sntp_connect(struct mg_mgr *mgr,
13070 MG_CB(mg_event_handler_t event_handler,
13071 void *user_data),
13072 const char *sntp_server_name) {
13073 struct mg_connection *c = NULL;
13074 char url[100], *p_url = url;
13075 const char *proto = "", *port = "", *tmp;
13076
13077 /* If port is not specified, use default (123) */
13078 tmp = strchr(sntp_server_name, ':');
13079 if (tmp != NULL && *(tmp + 1) == '/') {
13080 tmp = strchr(tmp + 1, ':');
13081 }
13082
13083 if (tmp == NULL) {
13084 port = ":123";
13085 }
13086
13087 /* Add udp:// if needed */
13088 if (strncmp(sntp_server_name, "udp://", 6) != 0) {
13089 proto = "udp://";
13090 }
13091
13092 mg_asprintf(&p_url, sizeof(url), "%s%s%s", proto, sntp_server_name, port);
13093
13094 c = mg_connect(mgr, p_url, event_handler MG_UD_ARG(user_data));
13095
13096 if (c == NULL) {
13097 goto cleanup;
13098 }
13099
13100 mg_set_protocol_sntp(c);
13101
13102 cleanup:
13103 if (p_url != url) {
13104 MG_FREE(p_url);
13105 }
13106
13107 return c;
13108 }
13109
13110 struct sntp_data {
13111 mg_event_handler_t hander;
13112 int count;
13113 };
13114
13115 static void mg_sntp_util_ev_handler(struct mg_connection *c, int ev,
13116 void *ev_data MG_UD_ARG(void *user_data)) {
13117 #if !MG_ENABLE_CALLBACK_USERDATA
13118 void *user_data = c->user_data;
13119 #endif
13120 struct sntp_data *sd = (struct sntp_data *) user_data;
13121
13122 switch (ev) {
13123 case MG_EV_CONNECT:
13124 if (*(int *) ev_data != 0) {
13125 mg_call(c, sd->hander, c->user_data, MG_SNTP_FAILED, NULL);
13126 break;
13127 }
13128 /* fallthrough */
13129 case MG_EV_TIMER:
13130 if (sd->count <= SNTP_ATTEMPTS) {
13131 mg_sntp_send_request(c);
13132 mg_set_timer(c, mg_time() + 10);
13133 sd->count++;
13134 } else {
13135 mg_call(c, sd->hander, c->user_data, MG_SNTP_FAILED, NULL);
13136 c->flags |= MG_F_CLOSE_IMMEDIATELY;
13137 }
13138 break;
13139 case MG_SNTP_MALFORMED_REPLY:
13140 mg_call(c, sd->hander, c->user_data, MG_SNTP_FAILED, NULL);
13141 c->flags |= MG_F_CLOSE_IMMEDIATELY;
13142 break;
13143 case MG_SNTP_REPLY:
13144 mg_call(c, sd->hander, c->user_data, MG_SNTP_REPLY, ev_data);
13145 c->flags |= MG_F_CLOSE_IMMEDIATELY;
13146 break;
13147 case MG_EV_CLOSE:
13148 MG_FREE(user_data);
13149 c->user_data = NULL;
13150 break;
13151 }
13152 }
13153
13154 struct mg_connection *mg_sntp_get_time(struct mg_mgr *mgr,
13155 mg_event_handler_t event_handler,
13156 const char *sntp_server_name) {
13157 struct mg_connection *c;
13158 struct sntp_data *sd = (struct sntp_data *) MG_CALLOC(1, sizeof(*sd));
13159 if (sd == NULL) {
13160 return NULL;
13161 }
13162
13163 c = mg_sntp_connect(mgr, MG_CB(mg_sntp_util_ev_handler, sd),
13164 sntp_server_name);
13165 if (c == NULL) {
13166 MG_FREE(sd);
13167 return NULL;
13168 }
13169
13170 sd->hander = event_handler;
13171 #if !MG_ENABLE_CALLBACK_USERDATA
13172 c->user_data = sd;
13173 #endif
13174
13175 return c;
13176 }
13177
13178 #endif /* MG_ENABLE_SNTP */
13179 #ifdef MG_MODULE_LINES
13180 #line 1 "mongoose/src/mg_socks.c"
13181 #endif
13182 /*
13183 * Copyright (c) 2017 Cesanta Software Limited
13184 * All rights reserved
13185 */
13186
13187 #if MG_ENABLE_SOCKS
13188
13189 /* Amalgamated: #include "mg_socks.h" */
13190 /* Amalgamated: #include "mg_internal.h" */
13191
13192 /*
13193 * https://www.ietf.org/rfc/rfc1928.txt paragraph 3, handle client handshake
13194 *
13195 * +----+----------+----------+
13196 * |VER | NMETHODS | METHODS |
13197 * +----+----------+----------+
13198 * | 1 | 1 | 1 to 255 |
13199 * +----+----------+----------+
13200 */
13201 static void mg_socks5_handshake(struct mg_connection *c) {
13202 struct mbuf *r = &c->recv_mbuf;
13203 if (r->buf[0] != MG_SOCKS_VERSION) {
13204 c->flags |= MG_F_CLOSE_IMMEDIATELY;
13205 } else if (r->len > 2 && (size_t) r->buf[1] + 2 <= r->len) {
13206 /* https://www.ietf.org/rfc/rfc1928.txt paragraph 3 */
13207 unsigned char reply[2] = {MG_SOCKS_VERSION, MG_SOCKS_HANDSHAKE_FAILURE};
13208 int i;
13209 for (i = 2; i < r->buf[1] + 2; i++) {
13210 /* TODO(lsm): support other auth methods */
13211 if (r->buf[i] == MG_SOCKS_HANDSHAKE_NOAUTH) reply[1] = r->buf[i];
13212 }
13213 mbuf_remove(r, 2 + r->buf[1]);
13214 mg_send(c, reply, sizeof(reply));
13215 c->flags |= MG_SOCKS_HANDSHAKE_DONE; /* Mark handshake done */
13216 }
13217 }
13218
13219 static void disband(struct mg_connection *c) {
13220 struct mg_connection *c2 = (struct mg_connection *) c->user_data;
13221 if (c2 != NULL) {
13222 c2->flags |= MG_F_SEND_AND_CLOSE;
13223 c2->user_data = NULL;
13224 }
13225 c->flags |= MG_F_SEND_AND_CLOSE;
13226 c->user_data = NULL;
13227 }
13228
13229 static void relay_data(struct mg_connection *c) {
13230 struct mg_connection *c2 = (struct mg_connection *) c->user_data;
13231 if (c2 != NULL) {
13232 mg_send(c2, c->recv_mbuf.buf, c->recv_mbuf.len);
13233 mbuf_remove(&c->recv_mbuf, c->recv_mbuf.len);
13234 } else {
13235 c->flags |= MG_F_SEND_AND_CLOSE;
13236 }
13237 }
13238
13239 static void serv_ev_handler(struct mg_connection *c, int ev, void *ev_data) {
13240 if (ev == MG_EV_CLOSE) {
13241 disband(c);
13242 } else if (ev == MG_EV_RECV) {
13243 relay_data(c);
13244 } else if (ev == MG_EV_CONNECT) {
13245 int res = *(int *) ev_data;
13246 if (res != 0) LOG(LL_ERROR, ("connect error: %d", res));
13247 }
13248 }
13249
13250 static void mg_socks5_connect(struct mg_connection *c, const char *addr) {
13251 struct mg_connection *serv = mg_connect(c->mgr, addr, serv_ev_handler);
13252 serv->user_data = c;
13253 c->user_data = serv;
13254 }
13255
13256 /*
13257 * Request, https://www.ietf.org/rfc/rfc1928.txt paragraph 4
13258 *
13259 * +----+-----+-------+------+----------+----------+
13260 * |VER | CMD | RSV | ATYP | DST.ADDR | DST.PORT |
13261 * +----+-----+-------+------+----------+----------+
13262 * | 1 | 1 | X'00' | 1 | Variable | 2 |
13263 * +----+-----+-------+------+----------+----------+
13264 */
13265 static void mg_socks5_handle_request(struct mg_connection *c) {
13266 struct mbuf *r = &c->recv_mbuf;
13267 unsigned char *p = (unsigned char *) r->buf;
13268 unsigned char addr_len = 4, reply = MG_SOCKS_SUCCESS;
13269 int ver, cmd, atyp;
13270 char addr[300];
13271
13272 if (r->len < 8) return; /* return if not fully buffered. min DST.ADDR is 2 */
13273 ver = p[0];
13274 cmd = p[1];
13275 atyp = p[3];
13276
13277 /* TODO(lsm): support other commands */
13278 if (ver != MG_SOCKS_VERSION || cmd != MG_SOCKS_CMD_CONNECT) {
13279 reply = MG_SOCKS_CMD_NOT_SUPPORTED;
13280 } else if (atyp == MG_SOCKS_ADDR_IPV4) {
13281 addr_len = 4;
13282 if (r->len < (size_t) addr_len + 6) return; /* return if not buffered */
13283 snprintf(addr, sizeof(addr), "%d.%d.%d.%d:%d", p[4], p[5], p[6], p[7],
13284 p[8] << 8 | p[9]);
13285 mg_socks5_connect(c, addr);
13286 } else if (atyp == MG_SOCKS_ADDR_IPV6) {
13287 addr_len = 16;
13288 if (r->len < (size_t) addr_len + 6) return; /* return if not buffered */
13289 snprintf(addr, sizeof(addr), "[%x:%x:%x:%x:%x:%x:%x:%x]:%d",
13290 p[4] << 8 | p[5], p[6] << 8 | p[7], p[8] << 8 | p[9],
13291 p[10] << 8 | p[11], p[12] << 8 | p[13], p[14] << 8 | p[15],
13292 p[16] << 8 | p[17], p[18] << 8 | p[19], p[20] << 8 | p[21]);
13293 mg_socks5_connect(c, addr);
13294 } else if (atyp == MG_SOCKS_ADDR_DOMAIN) {
13295 addr_len = p[4] + 1;
13296 if (r->len < (size_t) addr_len + 6) return; /* return if not buffered */
13297 snprintf(addr, sizeof(addr), "%.*s:%d", p[4], p + 5,
13298 p[4 + addr_len] << 8 | p[4 + addr_len + 1]);
13299 mg_socks5_connect(c, addr);
13300 } else {
13301 reply = MG_SOCKS_ADDR_NOT_SUPPORTED;
13302 }
13303
13304 /*
13305 * Reply, https://www.ietf.org/rfc/rfc1928.txt paragraph 5
13306 *
13307 * +----+-----+-------+------+----------+----------+
13308 * |VER | REP | RSV | ATYP | BND.ADDR | BND.PORT |
13309 * +----+-----+-------+------+----------+----------+
13310 * | 1 | 1 | X'00' | 1 | Variable | 2 |
13311 * +----+-----+-------+------+----------+----------+
13312 */
13313 {
13314 unsigned char buf[] = {MG_SOCKS_VERSION, reply, 0};
13315 mg_send(c, buf, sizeof(buf));
13316 }
13317 mg_send(c, r->buf + 3, addr_len + 1 + 2);
13318
13319 mbuf_remove(r, 6 + addr_len); /* Remove request from the input stream */
13320 c->flags |= MG_SOCKS_CONNECT_DONE; /* Mark ourselves as connected */
13321 }
13322
13323 static void socks_handler(struct mg_connection *c, int ev, void *ev_data) {
13324 if (ev == MG_EV_RECV) {
13325 if (!(c->flags & MG_SOCKS_HANDSHAKE_DONE)) mg_socks5_handshake(c);
13326 if (c->flags & MG_SOCKS_HANDSHAKE_DONE &&
13327 !(c->flags & MG_SOCKS_CONNECT_DONE)) {
13328 mg_socks5_handle_request(c);
13329 }
13330 if (c->flags & MG_SOCKS_CONNECT_DONE) relay_data(c);
13331 } else if (ev == MG_EV_CLOSE) {
13332 disband(c);
13333 }
13334 (void) ev_data;
13335 }
13336
13337 void mg_set_protocol_socks(struct mg_connection *c) {
13338 c->proto_handler = socks_handler;
13339 }
13340 #endif
13341 #ifdef MG_MODULE_LINES
13342 #line 1 "common/platforms/cc3200/cc3200_libc.c"
13343 #endif
13344 /*
13345 * Copyright (c) 2014-2018 Cesanta Software Limited
13346 * All rights reserved
13347 *
13348 * Licensed under the Apache License, Version 2.0 (the ""License"");
13349 * you may not use this file except in compliance with the License.
13350 * You may obtain a copy of the License at
13351 *
13352 * http://www.apache.org/licenses/LICENSE-2.0
13353 *
13354 * Unless required by applicable law or agreed to in writing, software
13355 * distributed under the License is distributed on an ""AS IS"" BASIS,
13356 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13357 * See the License for the specific language governing permissions and
13358 * limitations under the License.
13359 */
13360
13361 #if CS_PLATFORM == CS_P_CC3200
13362
13363 /* Amalgamated: #include "common/mg_mem.h" */
13364 #include <stdio.h>
13365 #include <string.h>
13366
13367 #ifndef __TI_COMPILER_VERSION__
13368 #include <reent.h>
13369 #include <sys/stat.h>
13370 #include <sys/time.h>
13371 #include <unistd.h>
13372 #endif
13373
13374 #include <inc/hw_types.h>
13375 #include <inc/hw_memmap.h>
13376 #include <driverlib/prcm.h>
13377 #include <driverlib/rom.h>
13378 #include <driverlib/rom_map.h>
13379 #include <driverlib/uart.h>
13380 #include <driverlib/utils.h>
13381
13382 #define CONSOLE_UART UARTA0_BASE
13383
13384 #ifdef __TI_COMPILER_VERSION__
13385 int asprintf(char **strp, const char *fmt, ...) {
13386 va_list ap;
13387 int len;
13388
13389 *strp = MG_MALLOC(BUFSIZ);
13390 if (*strp == NULL) return -1;
13391
13392 va_start(ap, fmt);
13393 len = vsnprintf(*strp, BUFSIZ, fmt, ap);
13394 va_end(ap);
13395
13396 if (len > 0) {
13397 *strp = MG_REALLOC(*strp, len + 1);
13398 if (*strp == NULL) return -1;
13399 }
13400
13401 if (len >= BUFSIZ) {
13402 va_start(ap, fmt);
13403 len = vsnprintf(*strp, len + 1, fmt, ap);
13404 va_end(ap);
13405 }
13406
13407 return len;
13408 }
13409
13410 #if MG_TI_NO_HOST_INTERFACE
13411 time_t HOSTtime() {
13412 struct timeval tp;
13413 gettimeofday(&tp, NULL);
13414 return tp.tv_sec;
13415 }
13416 #endif
13417
13418 #endif /* __TI_COMPILER_VERSION__ */
13419
13420 void fprint_str(FILE *fp, const char *str) {
13421 while (*str != '\0') {
13422 if (*str == '\n') MAP_UARTCharPut(CONSOLE_UART, '\r');
13423 MAP_UARTCharPut(CONSOLE_UART, *str++);
13424 }
13425 }
13426
13427 void _exit(int status) {
13428 fprint_str(stderr, "_exit\n");
13429 /* cause an unaligned access exception, that will drop you into gdb */
13430 *(int *) 1 = status;
13431 while (1)
13432 ; /* avoid gcc warning because stdlib abort() has noreturn attribute */
13433 }
13434
13435 void _not_implemented(const char *what) {
13436 fprint_str(stderr, what);
13437 fprint_str(stderr, " is not implemented\n");
13438 _exit(42);
13439 }
13440
13441 int _kill(int pid, int sig) {
13442 (void) pid;
13443 (void) sig;
13444 _not_implemented("_kill");
13445 return -1;
13446 }
13447
13448 int _getpid() {
13449 fprint_str(stderr, "_getpid is not implemented\n");
13450 return 42;
13451 }
13452
13453 int _isatty(int fd) {
13454 /* 0, 1 and 2 are TTYs. */
13455 return fd < 2;
13456 }
13457
13458 #endif /* CS_PLATFORM == CS_P_CC3200 */
13459 #ifdef MG_MODULE_LINES
13460 #line 1 "common/platforms/msp432/msp432_libc.c"
13461 #endif
13462 /*
13463 * Copyright (c) 2014-2018 Cesanta Software Limited
13464 * All rights reserved
13465 *
13466 * Licensed under the Apache License, Version 2.0 (the ""License"");
13467 * you may not use this file except in compliance with the License.
13468 * You may obtain a copy of the License at
13469 *
13470 * http://www.apache.org/licenses/LICENSE-2.0
13471 *
13472 * Unless required by applicable law or agreed to in writing, software
13473 * distributed under the License is distributed on an ""AS IS"" BASIS,
13474 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13475 * See the License for the specific language governing permissions and
13476 * limitations under the License.
13477 */
13478
13479 #if CS_PLATFORM == CS_P_MSP432
13480
13481 #include <ti/sysbios/BIOS.h>
13482 #include <ti/sysbios/knl/Clock.h>
13483
13484 int gettimeofday(struct timeval *tp, void *tzp) {
13485 uint32_t ticks = Clock_getTicks();
13486 tp->tv_sec = ticks / 1000;
13487 tp->tv_usec = (ticks % 1000) * 1000;
13488 return 0;
13489 }
13490
13491 #endif /* CS_PLATFORM == CS_P_MSP432 */
13492 #ifdef MG_MODULE_LINES
13493 #line 1 "common/platforms/nrf5/nrf5_libc.c"
13494 #endif
13495 /*
13496 * Copyright (c) 2014-2018 Cesanta Software Limited
13497 * All rights reserved
13498 *
13499 * Licensed under the Apache License, Version 2.0 (the ""License"");
13500 * you may not use this file except in compliance with the License.
13501 * You may obtain a copy of the License at
13502 *
13503 * http://www.apache.org/licenses/LICENSE-2.0
13504 *
13505 * Unless required by applicable law or agreed to in writing, software
13506 * distributed under the License is distributed on an ""AS IS"" BASIS,
13507 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13508 * See the License for the specific language governing permissions and
13509 * limitations under the License.
13510 */
13511
13512 #if (CS_PLATFORM == CS_P_NRF51 || CS_PLATFORM == CS_P_NRF52) && \
13513 defined(__ARMCC_VERSION)
13514 int gettimeofday(struct timeval *tp, void *tzp) {
13515 /* TODO */
13516 tp->tv_sec = 0;
13517 tp->tv_usec = 0;
13518 return 0;
13519 }
13520 #endif
13521 #ifdef MG_MODULE_LINES
13522 #line 1 "common/platforms/simplelink/sl_fs_slfs.h"
13523 #endif
13524 /*
13525 * Copyright (c) 2014-2018 Cesanta Software Limited
13526 * All rights reserved
13527 *
13528 * Licensed under the Apache License, Version 2.0 (the ""License"");
13529 * you may not use this file except in compliance with the License.
13530 * You may obtain a copy of the License at
13531 *
13532 * http://www.apache.org/licenses/LICENSE-2.0
13533 *
13534 * Unless required by applicable law or agreed to in writing, software
13535 * distributed under the License is distributed on an ""AS IS"" BASIS,
13536 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13537 * See the License for the specific language governing permissions and
13538 * limitations under the License.
13539 */
13540
13541 #ifndef CS_COMMON_PLATFORMS_SIMPLELINK_SL_FS_SLFS_H_
13542 #define CS_COMMON_PLATFORMS_SIMPLELINK_SL_FS_SLFS_H_
13543
13544 #if defined(MG_FS_SLFS)
13545
13546 #include <stdio.h>
13547 #ifndef __TI_COMPILER_VERSION__
13548 #include <unistd.h>
13549 #include <sys/stat.h>
13550 #endif
13551
13552 #define MAX_OPEN_SLFS_FILES 8
13553
13554 /* Indirect libc interface - same functions, different names. */
13555 int fs_slfs_open(const char *pathname, int flags, mode_t mode);
13556 int fs_slfs_close(int fd);
13557 ssize_t fs_slfs_read(int fd, void *buf, size_t count);
13558 ssize_t fs_slfs_write(int fd, const void *buf, size_t count);
13559 int fs_slfs_stat(const char *pathname, struct stat *s);
13560 int fs_slfs_fstat(int fd, struct stat *s);
13561 off_t fs_slfs_lseek(int fd, off_t offset, int whence);
13562 int fs_slfs_unlink(const char *filename);
13563 int fs_slfs_rename(const char *from, const char *to);
13564
13565 void fs_slfs_set_file_size(const char *name, size_t size);
13566 void fs_slfs_set_file_flags(const char *name, uint32_t flags, uint32_t *token);
13567 void fs_slfs_unset_file_flags(const char *name);
13568
13569 #endif /* defined(MG_FS_SLFS) */
13570
13571 #endif /* CS_COMMON_PLATFORMS_SIMPLELINK_SL_FS_SLFS_H_ */
13572 #ifdef MG_MODULE_LINES
13573 #line 1 "common/platforms/simplelink/sl_fs_slfs.c"
13574 #endif
13575 /*
13576 * Copyright (c) 2014-2018 Cesanta Software Limited
13577 * All rights reserved
13578 *
13579 * Licensed under the Apache License, Version 2.0 (the ""License"");
13580 * you may not use this file except in compliance with the License.
13581 * You may obtain a copy of the License at
13582 *
13583 * http://www.apache.org/licenses/LICENSE-2.0
13584 *
13585 * Unless required by applicable law or agreed to in writing, software
13586 * distributed under the License is distributed on an ""AS IS"" BASIS,
13587 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13588 * See the License for the specific language governing permissions and
13589 * limitations under the License.
13590 */
13591
13592 /* Standard libc interface to TI SimpleLink FS. */
13593
13594 #if defined(MG_FS_SLFS) || defined(CC3200_FS_SLFS)
13595
13596 /* Amalgamated: #include "common/platforms/simplelink/sl_fs_slfs.h" */
13597
13598 #include <errno.h>
13599
13600 #if CS_PLATFORM == CS_P_CC3200
13601 #include <inc/hw_types.h>
13602 #endif
13603
13604 /* Amalgamated: #include "common/cs_dbg.h" */
13605 /* Amalgamated: #include "common/mg_mem.h" */
13606
13607 #if SL_MAJOR_VERSION_NUM < 2
13608 int slfs_open(const unsigned char *fname, uint32_t flags, uint32_t *token) {
13609 _i32 fh;
13610 _i32 r = sl_FsOpen(fname, flags, (unsigned long *) token, &fh);
13611 return (r < 0 ? r : fh);
13612 }
13613 #else /* SL_MAJOR_VERSION_NUM >= 2 */
13614 int slfs_open(const unsigned char *fname, uint32_t flags, uint32_t *token) {
13615 return sl_FsOpen(fname, flags, (unsigned long *) token);
13616 }
13617 #endif
13618
13619 /* From sl_fs.c */
13620 int set_errno(int e);
13621 const char *drop_dir(const char *fname, bool *is_slfs);
13622
13623 /*
13624 * With SLFS, you have to pre-declare max file size. Yes. Really.
13625 * 64K should be enough for everyone. Right?
13626 */
13627 #ifndef FS_SLFS_MAX_FILE_SIZE
13628 #define FS_SLFS_MAX_FILE_SIZE (64 * 1024)
13629 #endif
13630
13631 struct sl_file_open_info {
13632 char *name;
13633 size_t size;
13634 uint32_t flags;
13635 uint32_t *token;
13636 };
13637
13638 struct sl_fd_info {
13639 _i32 fh;
13640 _off_t pos;
13641 size_t size;
13642 };
13643
13644 static struct sl_fd_info s_sl_fds[MAX_OPEN_SLFS_FILES];
13645 static struct sl_file_open_info s_sl_file_open_infos[MAX_OPEN_SLFS_FILES];
13646
13647 static struct sl_file_open_info *fs_slfs_find_foi(const char *name,
13648 bool create);
13649
13650 static int sl_fs_to_errno(_i32 r) {
13651 DBG(("SL error: %d", (int) r));
13652 switch (r) {
13653 case SL_FS_OK:
13654 return 0;
13655 case SL_ERROR_FS_FILE_NAME_EXIST:
13656 return EEXIST;
13657 case SL_ERROR_FS_WRONG_FILE_NAME:
13658 return EINVAL;
13659 case SL_ERROR_FS_NO_AVAILABLE_NV_INDEX:
13660 case SL_ERROR_FS_NOT_ENOUGH_STORAGE_SPACE:
13661 return ENOSPC;
13662 case SL_ERROR_FS_FAILED_TO_ALLOCATE_MEM:
13663 return ENOMEM;
13664 case SL_ERROR_FS_FILE_NOT_EXISTS:
13665 return ENOENT;
13666 case SL_ERROR_FS_NOT_SUPPORTED:
13667 return ENOTSUP;
13668 }
13669 return ENXIO;
13670 }
13671
13672 int fs_slfs_open(const char *pathname, int flags, mode_t mode) {
13673 int fd;
13674 for (fd = 0; fd < MAX_OPEN_SLFS_FILES; fd++) {
13675 if (s_sl_fds[fd].fh <= 0) break;
13676 }
13677 if (fd >= MAX_OPEN_SLFS_FILES) return set_errno(ENOMEM);
13678 struct sl_fd_info *fi = &s_sl_fds[fd];
13679
13680 /*
13681 * Apply path manipulations again, in case we got here directly
13682 * (via TI libc's "add_device").
13683 */
13684 pathname = drop_dir(pathname, NULL);
13685
13686 _u32 am = 0;
13687 fi->size = (size_t) -1;
13688 int rw = (flags & 3);
13689 size_t new_size = 0;
13690 struct sl_file_open_info *foi =
13691 fs_slfs_find_foi(pathname, false /* create */);
13692 if (foi != NULL) {
13693 LOG(LL_DEBUG, ("FOI for %s: %d 0x%x %p", pathname, (int) foi->size,
13694 (unsigned int) foi->flags, foi->token));
13695 }
13696 if (rw == O_RDONLY) {
13697 SlFsFileInfo_t sl_fi;
13698 _i32 r = sl_FsGetInfo((const _u8 *) pathname, 0, &sl_fi);
13699 if (r == SL_FS_OK) {
13700 fi->size = SL_FI_FILE_SIZE(sl_fi);
13701 }
13702 am = SL_FS_READ;
13703 } else {
13704 if (!(flags & O_TRUNC) || (flags & O_APPEND)) {
13705 // FailFS files cannot be opened for append and will be truncated
13706 // when opened for write.
13707 return set_errno(ENOTSUP);
13708 }
13709 if (flags & O_CREAT) {
13710 if (foi->size > 0) {
13711 new_size = foi->size;
13712 } else {
13713 new_size = FS_SLFS_MAX_FILE_SIZE;
13714 }
13715 am = FS_MODE_OPEN_CREATE(new_size, 0);
13716 } else {
13717 am = SL_FS_WRITE;
13718 }
13719 #if SL_MAJOR_VERSION_NUM >= 2
13720 am |= SL_FS_OVERWRITE;
13721 #endif
13722 }
13723 uint32_t *token = NULL;
13724 if (foi != NULL) {
13725 am |= foi->flags;
13726 token = foi->token;
13727 }
13728 fi->fh = slfs_open((_u8 *) pathname, am, token);
13729 LOG(LL_DEBUG, ("sl_FsOpen(%s, 0x%x, %p) sz %u = %d", pathname, (int) am,
13730 token, (unsigned int) new_size, (int) fi->fh));
13731 int r;
13732 if (fi->fh >= 0) {
13733 fi->pos = 0;
13734 r = fd;
13735 } else {
13736 r = set_errno(sl_fs_to_errno(fi->fh));
13737 }
13738 return r;
13739 }
13740
13741 int fs_slfs_close(int fd) {
13742 struct sl_fd_info *fi = &s_sl_fds[fd];
13743 if (fi->fh <= 0) return set_errno(EBADF);
13744 _i32 r = sl_FsClose(fi->fh, NULL, NULL, 0);
13745 LOG(LL_DEBUG, ("sl_FsClose(%d) = %d", (int) fi->fh, (int) r));
13746 s_sl_fds[fd].fh = -1;
13747 return set_errno(sl_fs_to_errno(r));
13748 }
13749
13750 ssize_t fs_slfs_read(int fd, void *buf, size_t count) {
13751 struct sl_fd_info *fi = &s_sl_fds[fd];
13752 if (fi->fh <= 0) return set_errno(EBADF);
13753 /* Simulate EOF. sl_FsRead @ file_size return SL_FS_ERR_OFFSET_OUT_OF_RANGE.
13754 */
13755 if (fi->pos == fi->size) return 0;
13756 _i32 r = sl_FsRead(fi->fh, fi->pos, buf, count);
13757 DBG(("sl_FsRead(%d, %d, %d) = %d", (int) fi->fh, (int) fi->pos, (int) count,
13758 (int) r));
13759 if (r >= 0) {
13760 fi->pos += r;
13761 return r;
13762 }
13763 return set_errno(sl_fs_to_errno(r));
13764 }
13765
13766 ssize_t fs_slfs_write(int fd, const void *buf, size_t count) {
13767 struct sl_fd_info *fi = &s_sl_fds[fd];
13768 if (fi->fh <= 0) return set_errno(EBADF);
13769 _i32 r = sl_FsWrite(fi->fh, fi->pos, (_u8 *) buf, count);
13770 DBG(("sl_FsWrite(%d, %d, %d) = %d", (int) fi->fh, (int) fi->pos, (int) count,
13771 (int) r));
13772 if (r >= 0) {
13773 fi->pos += r;
13774 return r;
13775 }
13776 return set_errno(sl_fs_to_errno(r));
13777 }
13778
13779 int fs_slfs_stat(const char *pathname, struct stat *s) {
13780 SlFsFileInfo_t sl_fi;
13781 /*
13782 * Apply path manipulations again, in case we got here directly
13783 * (via TI libc's "add_device").
13784 */
13785 pathname = drop_dir(pathname, NULL);
13786 _i32 r = sl_FsGetInfo((const _u8 *) pathname, 0, &sl_fi);
13787 if (r == SL_FS_OK) {
13788 s->st_mode = S_IFREG | 0666;
13789 s->st_nlink = 1;
13790 s->st_size = SL_FI_FILE_SIZE(sl_fi);
13791 return 0;
13792 }
13793 return set_errno(sl_fs_to_errno(r));
13794 }
13795
13796 int fs_slfs_fstat(int fd, struct stat *s) {
13797 struct sl_fd_info *fi = &s_sl_fds[fd];
13798 if (fi->fh <= 0) return set_errno(EBADF);
13799 s->st_mode = 0666;
13800 s->st_mode = S_IFREG | 0666;
13801 s->st_nlink = 1;
13802 s->st_size = fi->size;
13803 return 0;
13804 }
13805
13806 off_t fs_slfs_lseek(int fd, off_t offset, int whence) {
13807 if (s_sl_fds[fd].fh <= 0) return set_errno(EBADF);
13808 switch (whence) {
13809 case SEEK_SET:
13810 s_sl_fds[fd].pos = offset;
13811 break;
13812 case SEEK_CUR:
13813 s_sl_fds[fd].pos += offset;
13814 break;
13815 case SEEK_END:
13816 return set_errno(ENOTSUP);
13817 }
13818 return 0;
13819 }
13820
13821 int fs_slfs_unlink(const char *pathname) {
13822 /*
13823 * Apply path manipulations again, in case we got here directly
13824 * (via TI libc's "add_device").
13825 */
13826 pathname = drop_dir(pathname, NULL);
13827 return set_errno(sl_fs_to_errno(sl_FsDel((const _u8 *) pathname, 0)));
13828 }
13829
13830 int fs_slfs_rename(const char *from, const char *to) {
13831 return set_errno(ENOTSUP);
13832 }
13833
13834 static struct sl_file_open_info *fs_slfs_find_foi(const char *name,
13835 bool create) {
13836 int i = 0;
13837 for (i = 0; i < MAX_OPEN_SLFS_FILES; i++) {
13838 if (s_sl_file_open_infos[i].name != NULL &&
13839 strcmp(drop_dir(s_sl_file_open_infos[i].name, NULL), name) == 0) {
13840 break;
13841 }
13842 }
13843 if (i != MAX_OPEN_SLFS_FILES) return &s_sl_file_open_infos[i];
13844 if (!create) return NULL;
13845 for (i = 0; i < MAX_OPEN_SLFS_FILES; i++) {
13846 if (s_sl_file_open_infos[i].name == NULL) break;
13847 }
13848 if (i == MAX_OPEN_SLFS_FILES) {
13849 i = 0; /* Evict a random slot. */
13850 }
13851 if (s_sl_file_open_infos[i].name != NULL) {
13852 free(s_sl_file_open_infos[i].name);
13853 }
13854 s_sl_file_open_infos[i].name = strdup(name);
13855 return &s_sl_file_open_infos[i];
13856 }
13857
13858 void fs_slfs_set_file_size(const char *name, size_t size) {
13859 struct sl_file_open_info *foi = fs_slfs_find_foi(name, true /* create */);
13860 foi->size = size;
13861 }
13862
13863 void fs_slfs_set_file_flags(const char *name, uint32_t flags, uint32_t *token) {
13864 struct sl_file_open_info *foi = fs_slfs_find_foi(name, true /* create */);
13865 foi->flags = flags;
13866 foi->token = token;
13867 }
13868
13869 void fs_slfs_unset_file_flags(const char *name) {
13870 struct sl_file_open_info *foi = fs_slfs_find_foi(name, false /* create */);
13871 if (foi == NULL) return;
13872 free(foi->name);
13873 memset(foi, 0, sizeof(*foi));
13874 }
13875
13876 #endif /* defined(MG_FS_SLFS) || defined(CC3200_FS_SLFS) */
13877 #ifdef MG_MODULE_LINES
13878 #line 1 "common/platforms/simplelink/sl_fs.c"
13879 #endif
13880 /*
13881 * Copyright (c) 2014-2018 Cesanta Software Limited
13882 * All rights reserved
13883 *
13884 * Licensed under the Apache License, Version 2.0 (the ""License"");
13885 * you may not use this file except in compliance with the License.
13886 * You may obtain a copy of the License at
13887 *
13888 * http://www.apache.org/licenses/LICENSE-2.0
13889 *
13890 * Unless required by applicable law or agreed to in writing, software
13891 * distributed under the License is distributed on an ""AS IS"" BASIS,
13892 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13893 * See the License for the specific language governing permissions and
13894 * limitations under the License.
13895 */
13896
13897 #if MG_NET_IF == MG_NET_IF_SIMPLELINK && \
13898 (defined(MG_FS_SLFS) || defined(MG_FS_SPIFFS))
13899
13900 int set_errno(int e) {
13901 errno = e;
13902 return (e == 0 ? 0 : -1);
13903 }
13904
13905 const char *drop_dir(const char *fname, bool *is_slfs) {
13906 if (is_slfs != NULL) {
13907 *is_slfs = (strncmp(fname, "SL:", 3) == 0);
13908 if (*is_slfs) fname += 3;
13909 }
13910 /* Drop "./", if any */
13911 if (fname[0] == '.' && fname[1] == '/') {
13912 fname += 2;
13913 }
13914 /*
13915 * Drop / if it is the only one in the path.
13916 * This allows use of /pretend/directories but serves /file.txt as normal.
13917 */
13918 if (fname[0] == '/' && strchr(fname + 1, '/') == NULL) {
13919 fname++;
13920 }
13921 return fname;
13922 }
13923
13924 #if !defined(MG_FS_NO_VFS)
13925
13926 #include <errno.h>
13927 #include <stdbool.h>
13928 #include <stdio.h>
13929 #include <stdlib.h>
13930 #include <string.h>
13931 #ifdef __TI_COMPILER_VERSION__
13932 #include <file.h>
13933 #endif
13934
13935 /* Amalgamated: #include "common/cs_dbg.h" */
13936 /* Amalgamated: #include "common/platform.h" */
13937
13938 #ifdef CC3200_FS_SPIFFS
13939 /* Amalgamated: #include "cc3200_fs_spiffs.h" */
13940 #endif
13941
13942 #ifdef MG_FS_SLFS
13943 /* Amalgamated: #include "sl_fs_slfs.h" */
13944 #endif
13945
13946 #define NUM_SYS_FDS 3
13947 #define SPIFFS_FD_BASE 10
13948 #define SLFS_FD_BASE 100
13949
13950 #if !defined(MG_UART_CHAR_PUT) && !defined(MG_UART_WRITE)
13951 #if CS_PLATFORM == CS_P_CC3200
13952 #include <inc/hw_types.h>
13953 #include <inc/hw_memmap.h>
13954 #include <driverlib/rom.h>
13955 #include <driverlib/rom_map.h>
13956 #include <driverlib/uart.h>
13957 #define MG_UART_CHAR_PUT(fd, c) MAP_UARTCharPut(UARTA0_BASE, c);
13958 #else
13959 #define MG_UART_WRITE(fd, buf, len)
13960 #endif /* CS_PLATFORM == CS_P_CC3200 */
13961 #endif /* !MG_UART_CHAR_PUT */
13962
13963 enum fd_type {
13964 FD_INVALID,
13965 FD_SYS,
13966 #ifdef CC3200_FS_SPIFFS
13967 FD_SPIFFS,
13968 #endif
13969 #ifdef MG_FS_SLFS
13970 FD_SLFS
13971 #endif
13972 };
13973 static int fd_type(int fd) {
13974 if (fd >= 0 && fd < NUM_SYS_FDS) return FD_SYS;
13975 #ifdef CC3200_FS_SPIFFS
13976 if (fd >= SPIFFS_FD_BASE && fd < SPIFFS_FD_BASE + MAX_OPEN_SPIFFS_FILES) {
13977 return FD_SPIFFS;
13978 }
13979 #endif
13980 #ifdef MG_FS_SLFS
13981 if (fd >= SLFS_FD_BASE && fd < SLFS_FD_BASE + MAX_OPEN_SLFS_FILES) {
13982 return FD_SLFS;
13983 }
13984 #endif
13985 return FD_INVALID;
13986 }
13987
13988 #if MG_TI_NO_HOST_INTERFACE
13989 int open(const char *pathname, unsigned flags, int mode) {
13990 #else
13991 int _open(const char *pathname, int flags, mode_t mode) {
13992 #endif
13993 int fd = -1;
13994 bool is_sl;
13995 const char *fname = drop_dir(pathname, &is_sl);
13996 if (is_sl) {
13997 #ifdef MG_FS_SLFS
13998 fd = fs_slfs_open(fname, flags, mode);
13999 if (fd >= 0) fd += SLFS_FD_BASE;
14000 #endif
14001 } else {
14002 #ifdef CC3200_FS_SPIFFS
14003 fd = fs_spiffs_open(fname, flags, mode);
14004 if (fd >= 0) fd += SPIFFS_FD_BASE;
14005 #endif
14006 }
14007 LOG(LL_DEBUG,
14008 ("open(%s, 0x%x) = %d, fname = %s", pathname, flags, fd, fname));
14009 return fd;
14010 }
14011
14012 int _stat(const char *pathname, struct stat *st) {
14013 int res = -1;
14014 bool is_sl;
14015 const char *fname = drop_dir(pathname, &is_sl);
14016 memset(st, 0, sizeof(*st));
14017 /* Simulate statting the root directory. */
14018 if (fname[0] == '\0' || strcmp(fname, ".") == 0) {
14019 st->st_ino = 0;
14020 st->st_mode = S_IFDIR | 0777;
14021 st->st_nlink = 1;
14022 st->st_size = 0;
14023 return 0;
14024 }
14025 if (is_sl) {
14026 #ifdef MG_FS_SLFS
14027 res = fs_slfs_stat(fname, st);
14028 #endif
14029 } else {
14030 #ifdef CC3200_FS_SPIFFS
14031 res = fs_spiffs_stat(fname, st);
14032 #endif
14033 }
14034 LOG(LL_DEBUG, ("stat(%s) = %d; fname = %s", pathname, res, fname));
14035 return res;
14036 }
14037
14038 #if MG_TI_NO_HOST_INTERFACE
14039 int close(int fd) {
14040 #else
14041 int _close(int fd) {
14042 #endif
14043 int r = -1;
14044 switch (fd_type(fd)) {
14045 case FD_INVALID:
14046 r = set_errno(EBADF);
14047 break;
14048 case FD_SYS:
14049 r = set_errno(EACCES);
14050 break;
14051 #ifdef CC3200_FS_SPIFFS
14052 case FD_SPIFFS:
14053 r = fs_spiffs_close(fd - SPIFFS_FD_BASE);
14054 break;
14055 #endif
14056 #ifdef MG_FS_SLFS
14057 case FD_SLFS:
14058 r = fs_slfs_close(fd - SLFS_FD_BASE);
14059 break;
14060 #endif
14061 }
14062 DBG(("close(%d) = %d", fd, r));
14063 return r;
14064 }
14065
14066 #if MG_TI_NO_HOST_INTERFACE
14067 off_t lseek(int fd, off_t offset, int whence) {
14068 #else
14069 off_t _lseek(int fd, off_t offset, int whence) {
14070 #endif
14071 int r = -1;
14072 switch (fd_type(fd)) {
14073 case FD_INVALID:
14074 r = set_errno(EBADF);
14075 break;
14076 case FD_SYS:
14077 r = set_errno(ESPIPE);
14078 break;
14079 #ifdef CC3200_FS_SPIFFS
14080 case FD_SPIFFS:
14081 r = fs_spiffs_lseek(fd - SPIFFS_FD_BASE, offset, whence);
14082 break;
14083 #endif
14084 #ifdef MG_FS_SLFS
14085 case FD_SLFS:
14086 r = fs_slfs_lseek(fd - SLFS_FD_BASE, offset, whence);
14087 break;
14088 #endif
14089 }
14090 DBG(("lseek(%d, %d, %d) = %d", fd, (int) offset, whence, r));
14091 return r;
14092 }
14093
14094 int _fstat(int fd, struct stat *s) {
14095 int r = -1;
14096 memset(s, 0, sizeof(*s));
14097 switch (fd_type(fd)) {
14098 case FD_INVALID:
14099 r = set_errno(EBADF);
14100 break;
14101 case FD_SYS: {
14102 /* Create barely passable stats for STD{IN,OUT,ERR}. */
14103 memset(s, 0, sizeof(*s));
14104 s->st_ino = fd;
14105 s->st_mode = S_IFCHR | 0666;
14106 r = 0;
14107 break;
14108 }
14109 #ifdef CC3200_FS_SPIFFS
14110 case FD_SPIFFS:
14111 r = fs_spiffs_fstat(fd - SPIFFS_FD_BASE, s);
14112 break;
14113 #endif
14114 #ifdef MG_FS_SLFS
14115 case FD_SLFS:
14116 r = fs_slfs_fstat(fd - SLFS_FD_BASE, s);
14117 break;
14118 #endif
14119 }
14120 DBG(("fstat(%d) = %d", fd, r));
14121 return r;
14122 }
14123
14124 #if MG_TI_NO_HOST_INTERFACE
14125 int read(int fd, char *buf, unsigned count) {
14126 #else
14127 ssize_t _read(int fd, void *buf, size_t count) {
14128 #endif
14129 int r = -1;
14130 switch (fd_type(fd)) {
14131 case FD_INVALID:
14132 r = set_errno(EBADF);
14133 break;
14134 case FD_SYS: {
14135 if (fd != 0) {
14136 r = set_errno(EACCES);
14137 break;
14138 }
14139 /* Should we allow reading from stdin = uart? */
14140 r = set_errno(ENOTSUP);
14141 break;
14142 }
14143 #ifdef CC3200_FS_SPIFFS
14144 case FD_SPIFFS:
14145 r = fs_spiffs_read(fd - SPIFFS_FD_BASE, buf, count);
14146 break;
14147 #endif
14148 #ifdef MG_FS_SLFS
14149 case FD_SLFS:
14150 r = fs_slfs_read(fd - SLFS_FD_BASE, buf, count);
14151 break;
14152 #endif
14153 }
14154 DBG(("read(%d, %u) = %d", fd, count, r));
14155 return r;
14156 }
14157
14158 #if MG_TI_NO_HOST_INTERFACE
14159 int write(int fd, const char *buf, unsigned count) {
14160 #else
14161 ssize_t _write(int fd, const void *buf, size_t count) {
14162 #endif
14163 int r = -1;
14164 switch (fd_type(fd)) {
14165 case FD_INVALID:
14166 r = set_errno(EBADF);
14167 break;
14168 case FD_SYS: {
14169 if (fd == 0) {
14170 r = set_errno(EACCES);
14171 break;
14172 }
14173 #ifdef MG_UART_WRITE
14174 MG_UART_WRITE(fd, buf, count);
14175 #elif defined(MG_UART_CHAR_PUT)
14176 {
14177 size_t i;
14178 for (i = 0; i < count; i++) {
14179 const char c = ((const char *) buf)[i];
14180 if (c == '\n') MG_UART_CHAR_PUT(fd, '\r');
14181 MG_UART_CHAR_PUT(fd, c);
14182 }
14183 }
14184 #endif
14185 r = count;
14186 break;
14187 }
14188 #ifdef CC3200_FS_SPIFFS
14189 case FD_SPIFFS:
14190 r = fs_spiffs_write(fd - SPIFFS_FD_BASE, buf, count);
14191 break;
14192 #endif
14193 #ifdef MG_FS_SLFS
14194 case FD_SLFS:
14195 r = fs_slfs_write(fd - SLFS_FD_BASE, buf, count);
14196 break;
14197 #endif
14198 }
14199 return r;
14200 }
14201
14202 /*
14203 * On Newlib we override rename directly too, because the default
14204 * implementation using _link and _unlink doesn't work for us.
14205 */
14206 #if MG_TI_NO_HOST_INTERFACE || defined(_NEWLIB_VERSION)
14207 int rename(const char *frompath, const char *topath) {
14208 int r = -1;
14209 bool is_sl_from, is_sl_to;
14210 const char *from = drop_dir(frompath, &is_sl_from);
14211 const char *to = drop_dir(topath, &is_sl_to);
14212 if (is_sl_from || is_sl_to) {
14213 set_errno(ENOTSUP);
14214 } else {
14215 #ifdef CC3200_FS_SPIFFS
14216 r = fs_spiffs_rename(from, to);
14217 #endif
14218 }
14219 DBG(("rename(%s, %s) = %d", from, to, r));
14220 return r;
14221 }
14222 #endif /* MG_TI_NO_HOST_INTERFACE || defined(_NEWLIB_VERSION) */
14223
14224 #if MG_TI_NO_HOST_INTERFACE
14225 int unlink(const char *pathname) {
14226 #else
14227 int _unlink(const char *pathname) {
14228 #endif
14229 int r = -1;
14230 bool is_sl;
14231 const char *fname = drop_dir(pathname, &is_sl);
14232 if (is_sl) {
14233 #ifdef MG_FS_SLFS
14234 r = fs_slfs_unlink(fname);
14235 #endif
14236 } else {
14237 #ifdef CC3200_FS_SPIFFS
14238 r = fs_spiffs_unlink(fname);
14239 #endif
14240 }
14241 DBG(("unlink(%s) = %d, fname = %s", pathname, r, fname));
14242 return r;
14243 }
14244
14245 #ifdef CC3200_FS_SPIFFS /* FailFS does not support listing files. */
14246 DIR *opendir(const char *dir_name) {
14247 DIR *r = NULL;
14248 bool is_sl;
14249 drop_dir(dir_name, &is_sl);
14250 if (is_sl) {
14251 r = NULL;
14252 set_errno(ENOTSUP);
14253 } else {
14254 r = fs_spiffs_opendir(dir_name);
14255 }
14256 DBG(("opendir(%s) = %p", dir_name, r));
14257 return r;
14258 }
14259
14260 struct dirent *readdir(DIR *dir) {
14261 struct dirent *res = fs_spiffs_readdir(dir);
14262 DBG(("readdir(%p) = %p", dir, res));
14263 return res;
14264 }
14265
14266 int closedir(DIR *dir) {
14267 int res = fs_spiffs_closedir(dir);
14268 DBG(("closedir(%p) = %d", dir, res));
14269 return res;
14270 }
14271
14272 int rmdir(const char *path) {
14273 return fs_spiffs_rmdir(path);
14274 }
14275
14276 int mkdir(const char *path, mode_t mode) {
14277 (void) path;
14278 (void) mode;
14279 /* for spiffs supports only root dir, which comes from mongoose as '.' */
14280 return (strlen(path) == 1 && *path == '.') ? 0 : ENOTDIR;
14281 }
14282 #endif
14283
14284 int sl_fs_init(void) {
14285 int ret = 1;
14286 #ifdef __TI_COMPILER_VERSION__
14287 #ifdef MG_FS_SLFS
14288 #pragma diag_push
14289 #pragma diag_suppress 169 /* Nothing we can do about the prototype mismatch. \
14290 */
14291 ret = (add_device("SL", _MSA, fs_slfs_open, fs_slfs_close, fs_slfs_read,
14292 fs_slfs_write, fs_slfs_lseek, fs_slfs_unlink,
14293 fs_slfs_rename) == 0);
14294 #pragma diag_pop
14295 #endif
14296 #endif
14297 return ret;
14298 }
14299
14300 #endif /* !defined(MG_FS_NO_VFS) */
14301 #endif /* MG_NET_IF == MG_NET_IF_SIMPLELINK && (defined(MG_FS_SLFS) || \
14302 defined(MG_FS_SPIFFS)) */
14303 #ifdef MG_MODULE_LINES
14304 #line 1 "common/platforms/simplelink/sl_socket.c"
14305 #endif
14306 /*
14307 * Copyright (c) 2014-2018 Cesanta Software Limited
14308 * All rights reserved
14309 *
14310 * Licensed under the Apache License, Version 2.0 (the ""License"");
14311 * you may not use this file except in compliance with the License.
14312 * You may obtain a copy of the License at
14313 *
14314 * http://www.apache.org/licenses/LICENSE-2.0
14315 *
14316 * Unless required by applicable law or agreed to in writing, software
14317 * distributed under the License is distributed on an ""AS IS"" BASIS,
14318 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14319 * See the License for the specific language governing permissions and
14320 * limitations under the License.
14321 */
14322
14323 #if MG_NET_IF == MG_NET_IF_SIMPLELINK
14324
14325 #include <errno.h>
14326 #include <stdio.h>
14327
14328 /* Amalgamated: #include "common/platform.h" */
14329
14330 const char *inet_ntop(int af, const void *src, char *dst, socklen_t size) {
14331 int res;
14332 struct in_addr *in = (struct in_addr *) src;
14333 if (af != AF_INET) {
14334 errno = ENOTSUP;
14335 return NULL;
14336 }
14337 res = snprintf(dst, size, "%lu.%lu.%lu.%lu", SL_IPV4_BYTE(in->s_addr, 0),
14338 SL_IPV4_BYTE(in->s_addr, 1), SL_IPV4_BYTE(in->s_addr, 2),
14339 SL_IPV4_BYTE(in->s_addr, 3));
14340 return res > 0 ? dst : NULL;
14341 }
14342
14343 char *inet_ntoa(struct in_addr n) {
14344 static char a[16];
14345 return (char *) inet_ntop(AF_INET, &n, a, sizeof(a));
14346 }
14347
14348 int inet_pton(int af, const char *src, void *dst) {
14349 uint32_t a0, a1, a2, a3;
14350 uint8_t *db = (uint8_t *) dst;
14351 if (af != AF_INET) {
14352 errno = ENOTSUP;
14353 return 0;
14354 }
14355 if (sscanf(src, "%lu.%lu.%lu.%lu", &a0, &a1, &a2, &a3) != 4) {
14356 return 0;
14357 }
14358 *db = a3;
14359 *(db + 1) = a2;
14360 *(db + 2) = a1;
14361 *(db + 3) = a0;
14362 return 1;
14363 }
14364
14365 #endif /* MG_NET_IF == MG_NET_IF_SIMPLELINK */
14366 #ifdef MG_MODULE_LINES
14367 #line 1 "common/platforms/simplelink/sl_mg_task.c"
14368 #endif
14369 #if MG_NET_IF == MG_NET_IF_SIMPLELINK && !defined(MG_SIMPLELINK_NO_OSI)
14370
14371 /* Amalgamated: #include "mg_task.h" */
14372
14373 #include <oslib/osi.h>
14374
14375 enum mg_q_msg_type {
14376 MG_Q_MSG_CB,
14377 };
14378 struct mg_q_msg {
14379 enum mg_q_msg_type type;
14380 void (*cb)(struct mg_mgr *mgr, void *arg);
14381 void *arg;
14382 };
14383 static OsiMsgQ_t s_mg_q;
14384 static void mg_task(void *arg);
14385
14386 bool mg_start_task(int priority, int stack_size, mg_init_cb mg_init) {
14387 if (osi_MsgQCreate(&s_mg_q, "MG", sizeof(struct mg_q_msg), 16) != OSI_OK) {
14388 return false;
14389 }
14390 if (osi_TaskCreate(mg_task, (const signed char *) "MG", stack_size,
14391 (void *) mg_init, priority, NULL) != OSI_OK) {
14392 return false;
14393 }
14394 return true;
14395 }
14396
14397 static void mg_task(void *arg) {
14398 struct mg_mgr mgr;
14399 mg_init_cb mg_init = (mg_init_cb) arg;
14400 mg_mgr_init(&mgr, NULL);
14401 mg_init(&mgr);
14402 while (1) {
14403 struct mg_q_msg msg;
14404 mg_mgr_poll(&mgr, 1);
14405 if (osi_MsgQRead(&s_mg_q, &msg, 1) != OSI_OK) continue;
14406 switch (msg.type) {
14407 case MG_Q_MSG_CB: {
14408 msg.cb(&mgr, msg.arg);
14409 }
14410 }
14411 }
14412 }
14413
14414 void mg_run_in_task(void (*cb)(struct mg_mgr *mgr, void *arg), void *cb_arg) {
14415 struct mg_q_msg msg = {MG_Q_MSG_CB, cb, cb_arg};
14416 osi_MsgQWrite(&s_mg_q, &msg, OSI_NO_WAIT);
14417 }
14418
14419 #endif /* MG_NET_IF == MG_NET_IF_SIMPLELINK && !defined(MG_SIMPLELINK_NO_OSI) \
14420 */
14421 #ifdef MG_MODULE_LINES
14422 #line 1 "common/platforms/simplelink/sl_net_if.h"
14423 #endif
14424 /*
14425 * Copyright (c) 2014-2018 Cesanta Software Limited
14426 * All rights reserved
14427 *
14428 * Licensed under the Apache License, Version 2.0 (the ""License"");
14429 * you may not use this file except in compliance with the License.
14430 * You may obtain a copy of the License at
14431 *
14432 * http://www.apache.org/licenses/LICENSE-2.0
14433 *
14434 * Unless required by applicable law or agreed to in writing, software
14435 * distributed under the License is distributed on an ""AS IS"" BASIS,
14436 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14437 * See the License for the specific language governing permissions and
14438 * limitations under the License.
14439 */
14440
14441 #ifndef CS_COMMON_PLATFORMS_SIMPLELINK_SL_NET_IF_H_
14442 #define CS_COMMON_PLATFORMS_SIMPLELINK_SL_NET_IF_H_
14443
14444 /* Amalgamated: #include "mongoose/src/net_if.h" */
14445
14446 #ifdef __cplusplus
14447 extern "C" {
14448 #endif /* __cplusplus */
14449
14450 #ifndef MG_ENABLE_NET_IF_SIMPLELINK
14451 #define MG_ENABLE_NET_IF_SIMPLELINK MG_NET_IF == MG_NET_IF_SIMPLELINK
14452 #endif
14453
14454 extern const struct mg_iface_vtable mg_simplelink_iface_vtable;
14455
14456 #ifdef __cplusplus
14457 }
14458 #endif /* __cplusplus */
14459
14460 #endif /* CS_COMMON_PLATFORMS_SIMPLELINK_SL_NET_IF_H_ */
14461 #ifdef MG_MODULE_LINES
14462 #line 1 "common/platforms/simplelink/sl_net_if.c"
14463 #endif
14464 /*
14465 * Copyright (c) 2014-2018 Cesanta Software Limited
14466 * All rights reserved
14467 *
14468 * Licensed under the Apache License, Version 2.0 (the ""License"");
14469 * you may not use this file except in compliance with the License.
14470 * You may obtain a copy of the License at
14471 *
14472 * http://www.apache.org/licenses/LICENSE-2.0
14473 *
14474 * Unless required by applicable law or agreed to in writing, software
14475 * distributed under the License is distributed on an ""AS IS"" BASIS,
14476 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14477 * See the License for the specific language governing permissions and
14478 * limitations under the License.
14479 */
14480
14481 /* Amalgamated: #include "common/platforms/simplelink/sl_net_if.h" */
14482
14483 #if MG_ENABLE_NET_IF_SIMPLELINK
14484
14485 /* Amalgamated: #include "mongoose/src/internal.h" */
14486 /* Amalgamated: #include "mongoose/src/util.h" */
14487
14488 #define MG_TCP_RECV_BUFFER_SIZE 1024
14489 #define MG_UDP_RECV_BUFFER_SIZE 1500
14490
14491 static sock_t mg_open_listening_socket(struct mg_connection *nc,
14492 union socket_address *sa, int type,
14493 int proto);
14494
14495 static void mg_set_non_blocking_mode(sock_t sock) {
14496 SlSockNonblocking_t opt;
14497 #if SL_MAJOR_VERSION_NUM < 2
14498 opt.NonblockingEnabled = 1;
14499 #else
14500 opt.NonBlockingEnabled = 1;
14501 #endif
14502 sl_SetSockOpt(sock, SL_SOL_SOCKET, SL_SO_NONBLOCKING, &opt, sizeof(opt));
14503 }
14504
14505 static int mg_is_error(int n) {
14506 return (n < 0 && n != SL_ERROR_BSD_EALREADY && n != SL_ERROR_BSD_EAGAIN);
14507 }
14508
14509 static void mg_sl_if_connect_tcp(struct mg_connection *nc,
14510 const union socket_address *sa) {
14511 int proto = 0;
14512 #if MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_SIMPLELINK
14513 if (nc->flags & MG_F_SSL) proto = SL_SEC_SOCKET;
14514 #endif
14515 sock_t sock = sl_Socket(AF_INET, SOCK_STREAM, proto);
14516 if (sock < 0) {
14517 nc->err = sock;
14518 goto out;
14519 }
14520 mg_sock_set(nc, sock);
14521 #if MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_SIMPLELINK
14522 nc->err = sl_set_ssl_opts(sock, nc);
14523 if (nc->err != 0) goto out;
14524 #endif
14525 nc->err = sl_Connect(sock, &sa->sa, sizeof(sa->sin));
14526 out:
14527 DBG(("%p to %s:%d sock %d %d err %d", nc, inet_ntoa(sa->sin.sin_addr),
14528 ntohs(sa->sin.sin_port), nc->sock, proto, nc->err));
14529 }
14530
14531 static void mg_sl_if_connect_udp(struct mg_connection *nc) {
14532 sock_t sock = sl_Socket(AF_INET, SOCK_DGRAM, 0);
14533 if (sock < 0) {
14534 nc->err = sock;
14535 return;
14536 }
14537 mg_sock_set(nc, sock);
14538 nc->err = 0;
14539 }
14540
14541 static int mg_sl_if_listen_tcp(struct mg_connection *nc,
14542 union socket_address *sa) {
14543 int proto = 0;
14544 if (nc->flags & MG_F_SSL) proto = SL_SEC_SOCKET;
14545 sock_t sock = mg_open_listening_socket(nc, sa, SOCK_STREAM, proto);
14546 if (sock < 0) return sock;
14547 mg_sock_set(nc, sock);
14548 return 0;
14549 }
14550
14551 static int mg_sl_if_listen_udp(struct mg_connection *nc,
14552 union socket_address *sa) {
14553 sock_t sock = mg_open_listening_socket(nc, sa, SOCK_DGRAM, 0);
14554 if (sock == INVALID_SOCKET) return (errno ? errno : 1);
14555 mg_sock_set(nc, sock);
14556 return 0;
14557 }
14558
14559 static int mg_sl_if_tcp_send(struct mg_connection *nc, const void *buf,
14560 size_t len) {
14561 int n = (int) sl_Send(nc->sock, buf, len, 0);
14562 if (n < 0 && !mg_is_error(n)) n = 0;
14563 return n;
14564 }
14565
14566 static int mg_sl_if_udp_send(struct mg_connection *nc, const void *buf,
14567 size_t len) {
14568 int n = sl_SendTo(nc->sock, buf, len, 0, &nc->sa.sa, sizeof(nc->sa.sin));
14569 if (n < 0 && !mg_is_error(n)) n = 0;
14570 return n;
14571 }
14572
14573 static int mg_sl_if_tcp_recv(struct mg_connection *nc, void *buf, size_t len) {
14574 int n = sl_Recv(nc->sock, buf, len, 0);
14575 if (n == 0) {
14576 /* Orderly shutdown of the socket, try flushing output. */
14577 nc->flags |= MG_F_SEND_AND_CLOSE;
14578 } else if (n < 0 && !mg_is_error(n)) {
14579 n = 0;
14580 }
14581 return n;
14582 }
14583
14584 static int mg_sl_if_udp_recv(struct mg_connection *nc, void *buf, size_t len,
14585 union socket_address *sa, size_t *sa_len) {
14586 SlSocklen_t sa_len_t = *sa_len;
14587 int n = sl_RecvFrom(nc->sock, buf, MG_UDP_RECV_BUFFER_SIZE, 0,
14588 (SlSockAddr_t *) sa, &sa_len_t);
14589 *sa_len = sa_len_t;
14590 if (n < 0 && !mg_is_error(n)) n = 0;
14591 return n;
14592 }
14593
14594 static int mg_sl_if_create_conn(struct mg_connection *nc) {
14595 (void) nc;
14596 return 1;
14597 }
14598
14599 void mg_sl_if_destroy_conn(struct mg_connection *nc) {
14600 if (nc->sock == INVALID_SOCKET) return;
14601 /* For UDP, only close outgoing sockets or listeners. */
14602 if (!(nc->flags & MG_F_UDP) || nc->listener == NULL) {
14603 sl_Close(nc->sock);
14604 }
14605 nc->sock = INVALID_SOCKET;
14606 }
14607
14608 static int mg_accept_conn(struct mg_connection *lc) {
14609 struct mg_connection *nc;
14610 union socket_address sa;
14611 socklen_t sa_len = sizeof(sa);
14612 sock_t sock = sl_Accept(lc->sock, &sa.sa, &sa_len);
14613 if (sock < 0) {
14614 DBG(("%p: failed to accept: %d", lc, sock));
14615 return 0;
14616 }
14617 nc = mg_if_accept_new_conn(lc);
14618 if (nc == NULL) {
14619 sl_Close(sock);
14620 return 0;
14621 }
14622 DBG(("%p conn from %s:%d", nc, inet_ntoa(sa.sin.sin_addr),
14623 ntohs(sa.sin.sin_port)));
14624 mg_sock_set(nc, sock);
14625 mg_if_accept_tcp_cb(nc, &sa, sa_len);
14626 return 1;
14627 }
14628
14629 /* 'sa' must be an initialized address to bind to */
14630 static sock_t mg_open_listening_socket(struct mg_connection *nc,
14631 union socket_address *sa, int type,
14632 int proto) {
14633 int r;
14634 socklen_t sa_len =
14635 (sa->sa.sa_family == AF_INET) ? sizeof(sa->sin) : sizeof(sa->sin6);
14636 sock_t sock = sl_Socket(sa->sa.sa_family, type, proto);
14637 if (sock < 0) return sock;
14638 #if MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_SIMPLELINK
14639 if ((r = sl_set_ssl_opts(sock, nc)) < 0) goto clean;
14640 #endif
14641 if ((r = sl_Bind(sock, &sa->sa, sa_len)) < 0) goto clean;
14642 if (type != SOCK_DGRAM) {
14643 if ((r = sl_Listen(sock, SOMAXCONN)) < 0) goto clean;
14644 }
14645 mg_set_non_blocking_mode(sock);
14646 clean:
14647 if (r < 0) {
14648 sl_Close(sock);
14649 sock = r;
14650 }
14651 return sock;
14652 }
14653
14654 #define _MG_F_FD_CAN_READ 1
14655 #define _MG_F_FD_CAN_WRITE 1 << 1
14656 #define _MG_F_FD_ERROR 1 << 2
14657
14658 void mg_mgr_handle_conn(struct mg_connection *nc, int fd_flags, double now) {
14659 DBG(("%p fd=%d fd_flags=%d nc_flags=0x%lx rmbl=%d smbl=%d", nc, nc->sock,
14660 fd_flags, nc->flags, (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len));
14661
14662 if (!mg_if_poll(nc, now)) return;
14663
14664 if (nc->flags & MG_F_CONNECTING) {
14665 if ((nc->flags & MG_F_UDP) || nc->err != SL_ERROR_BSD_EALREADY) {
14666 mg_if_connect_cb(nc, nc->err);
14667 } else {
14668 /* In SimpleLink, to get status of non-blocking connect() we need to wait
14669 * until socket is writable and repeat the call to sl_Connect again,
14670 * which will now return the real status. */
14671 if (fd_flags & _MG_F_FD_CAN_WRITE) {
14672 nc->err = sl_Connect(nc->sock, &nc->sa.sa, sizeof(nc->sa.sin));
14673 DBG(("%p conn res=%d", nc, nc->err));
14674 if (nc->err == SL_ERROR_BSD_ESECSNOVERIFY ||
14675 /* TODO(rojer): Provide API to set the date for verification. */
14676 nc->err == SL_ERROR_BSD_ESECDATEERROR
14677 #if SL_MAJOR_VERSION_NUM >= 2
14678 /* Per SWRU455, this error does not mean verification failed,
14679 * it only means that the cert used is not present in the trusted
14680 * root CA catalog. Which is perfectly fine. */
14681 ||
14682 nc->err == SL_ERROR_BSD_ESECUNKNOWNROOTCA
14683 #endif
14684 ) {
14685 nc->err = 0;
14686 }
14687 mg_if_connect_cb(nc, nc->err);
14688 }
14689 }
14690 /* Ignore read/write in further processing, we've handled it. */
14691 fd_flags &= ~(_MG_F_FD_CAN_READ | _MG_F_FD_CAN_WRITE);
14692 }
14693
14694 if (fd_flags & _MG_F_FD_CAN_READ) {
14695 if (nc->flags & MG_F_UDP) {
14696 mg_if_can_recv_cb(nc);
14697 } else {
14698 if (nc->flags & MG_F_LISTENING) {
14699 mg_accept_conn(nc);
14700 } else {
14701 mg_if_can_recv_cb(nc);
14702 }
14703 }
14704 }
14705
14706 if (fd_flags & _MG_F_FD_CAN_WRITE) {
14707 mg_if_can_send_cb(nc);
14708 }
14709
14710 DBG(("%p after fd=%d nc_flags=0x%lx rmbl=%d smbl=%d", nc, nc->sock, nc->flags,
14711 (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len));
14712 }
14713
14714 /* Associate a socket to a connection. */
14715 void mg_sl_if_sock_set(struct mg_connection *nc, sock_t sock) {
14716 mg_set_non_blocking_mode(sock);
14717 nc->sock = sock;
14718 DBG(("%p %d", nc, sock));
14719 }
14720
14721 void mg_sl_if_init(struct mg_iface *iface) {
14722 (void) iface;
14723 DBG(("%p using sl_Select()", iface->mgr));
14724 }
14725
14726 void mg_sl_if_free(struct mg_iface *iface) {
14727 (void) iface;
14728 }
14729
14730 void mg_sl_if_add_conn(struct mg_connection *nc) {
14731 (void) nc;
14732 }
14733
14734 void mg_sl_if_remove_conn(struct mg_connection *nc) {
14735 (void) nc;
14736 }
14737
14738 time_t mg_sl_if_poll(struct mg_iface *iface, int timeout_ms) {
14739 struct mg_mgr *mgr = iface->mgr;
14740 double now = mg_time();
14741 double min_timer;
14742 struct mg_connection *nc, *tmp;
14743 struct SlTimeval_t tv;
14744 SlFdSet_t read_set, write_set, err_set;
14745 sock_t max_fd = INVALID_SOCKET;
14746 int num_fds, num_ev = 0, num_timers = 0;
14747
14748 SL_SOCKET_FD_ZERO(&read_set);
14749 SL_SOCKET_FD_ZERO(&write_set);
14750 SL_SOCKET_FD_ZERO(&err_set);
14751
14752 /*
14753 * Note: it is ok to have connections with sock == INVALID_SOCKET in the list,
14754 * e.g. timer-only "connections".
14755 */
14756 min_timer = 0;
14757 for (nc = mgr->active_connections, num_fds = 0; nc != NULL; nc = tmp) {
14758 tmp = nc->next;
14759
14760 if (nc->sock != INVALID_SOCKET) {
14761 num_fds++;
14762
14763 if (!(nc->flags & MG_F_WANT_WRITE) &&
14764 nc->recv_mbuf.len < nc->recv_mbuf_limit &&
14765 (!(nc->flags & MG_F_UDP) || nc->listener == NULL)) {
14766 SL_SOCKET_FD_SET(nc->sock, &read_set);
14767 if (max_fd == INVALID_SOCKET || nc->sock > max_fd) max_fd = nc->sock;
14768 }
14769
14770 if (((nc->flags & MG_F_CONNECTING) && !(nc->flags & MG_F_WANT_READ)) ||
14771 (nc->send_mbuf.len > 0 && !(nc->flags & MG_F_CONNECTING))) {
14772 SL_SOCKET_FD_SET(nc->sock, &write_set);
14773 SL_SOCKET_FD_SET(nc->sock, &err_set);
14774 if (max_fd == INVALID_SOCKET || nc->sock > max_fd) max_fd = nc->sock;
14775 }
14776 }
14777
14778 if (nc->ev_timer_time > 0) {
14779 if (num_timers == 0 || nc->ev_timer_time < min_timer) {
14780 min_timer = nc->ev_timer_time;
14781 }
14782 num_timers++;
14783 }
14784 }
14785
14786 /*
14787 * If there is a timer to be fired earlier than the requested timeout,
14788 * adjust the timeout.
14789 */
14790 if (num_timers > 0) {
14791 double timer_timeout_ms = (min_timer - mg_time()) * 1000 + 1 /* rounding */;
14792 if (timer_timeout_ms < timeout_ms) {
14793 timeout_ms = timer_timeout_ms;
14794 }
14795 }
14796 if (timeout_ms < 0) timeout_ms = 0;
14797
14798 tv.tv_sec = timeout_ms / 1000;
14799 tv.tv_usec = (timeout_ms % 1000) * 1000;
14800
14801 if (num_fds > 0) {
14802 num_ev = sl_Select((int) max_fd + 1, &read_set, &write_set, &err_set, &tv);
14803 }
14804
14805 now = mg_time();
14806 DBG(("sl_Select @ %ld num_ev=%d of %d, timeout=%d", (long) now, num_ev,
14807 num_fds, timeout_ms));
14808
14809 for (nc = mgr->active_connections; nc != NULL; nc = tmp) {
14810 int fd_flags = 0;
14811 if (nc->sock != INVALID_SOCKET) {
14812 if (num_ev > 0) {
14813 fd_flags =
14814 (SL_SOCKET_FD_ISSET(nc->sock, &read_set) &&
14815 (!(nc->flags & MG_F_UDP) || nc->listener == NULL)
14816 ? _MG_F_FD_CAN_READ
14817 : 0) |
14818 (SL_SOCKET_FD_ISSET(nc->sock, &write_set) ? _MG_F_FD_CAN_WRITE
14819 : 0) |
14820 (SL_SOCKET_FD_ISSET(nc->sock, &err_set) ? _MG_F_FD_ERROR : 0);
14821 }
14822 /* SimpleLink does not report UDP sockets as writable. */
14823 if (nc->flags & MG_F_UDP && nc->send_mbuf.len > 0) {
14824 fd_flags |= _MG_F_FD_CAN_WRITE;
14825 }
14826 }
14827 tmp = nc->next;
14828 mg_mgr_handle_conn(nc, fd_flags, now);
14829 }
14830
14831 return now;
14832 }
14833
14834 void mg_sl_if_get_conn_addr(struct mg_connection *nc, int remote,
14835 union socket_address *sa) {
14836 /* SimpleLink does not provide a way to get socket's peer address after
14837 * accept or connect. Address should have been preserved in the connection,
14838 * so we do our best here by using it. */
14839 if (remote) memcpy(sa, &nc->sa, sizeof(*sa));
14840 }
14841
14842 void sl_restart_cb(struct mg_mgr *mgr) {
14843 /*
14844 * SimpleLink has been restarted, meaning all sockets have been invalidated.
14845 * We try our best - we'll restart the listeners, but for outgoing
14846 * connections we have no option but to terminate.
14847 */
14848 struct mg_connection *nc;
14849 for (nc = mg_next(mgr, NULL); nc != NULL; nc = mg_next(mgr, nc)) {
14850 if (nc->sock == INVALID_SOCKET) continue; /* Could be a timer */
14851 if (nc->flags & MG_F_LISTENING) {
14852 DBG(("restarting %p %s:%d", nc, inet_ntoa(nc->sa.sin.sin_addr),
14853 ntohs(nc->sa.sin.sin_port)));
14854 int res = (nc->flags & MG_F_UDP ? mg_sl_if_listen_udp(nc, &nc->sa)
14855 : mg_sl_if_listen_tcp(nc, &nc->sa));
14856 if (res == 0) continue;
14857 /* Well, we tried and failed. Fall through to closing. */
14858 }
14859 nc->sock = INVALID_SOCKET;
14860 DBG(("terminating %p %s:%d", nc, inet_ntoa(nc->sa.sin.sin_addr),
14861 ntohs(nc->sa.sin.sin_port)));
14862 /* TODO(rojer): Outgoing UDP? */
14863 nc->flags |= MG_F_CLOSE_IMMEDIATELY;
14864 }
14865 }
14866
14867 /* clang-format off */
14868 #define MG_SL_IFACE_VTABLE \
14869 { \
14870 mg_sl_if_init, \
14871 mg_sl_if_free, \
14872 mg_sl_if_add_conn, \
14873 mg_sl_if_remove_conn, \
14874 mg_sl_if_poll, \
14875 mg_sl_if_listen_tcp, \
14876 mg_sl_if_listen_udp, \
14877 mg_sl_if_connect_tcp, \
14878 mg_sl_if_connect_udp, \
14879 mg_sl_if_tcp_send, \
14880 mg_sl_if_udp_send, \
14881 mg_sl_if_tcp_recv, \
14882 mg_sl_if_udp_recv, \
14883 mg_sl_if_create_conn, \
14884 mg_sl_if_destroy_conn, \
14885 mg_sl_if_sock_set, \
14886 mg_sl_if_get_conn_addr, \
14887 }
14888 /* clang-format on */
14889
14890 const struct mg_iface_vtable mg_simplelink_iface_vtable = MG_SL_IFACE_VTABLE;
14891 #if MG_NET_IF == MG_NET_IF_SIMPLELINK
14892 const struct mg_iface_vtable mg_default_iface_vtable = MG_SL_IFACE_VTABLE;
14893 #endif
14894
14895 #endif /* MG_ENABLE_NET_IF_SIMPLELINK */
14896 #ifdef MG_MODULE_LINES
14897 #line 1 "common/platforms/simplelink/sl_ssl_if.c"
14898 #endif
14899 /*
14900 * Copyright (c) 2014-2018 Cesanta Software Limited
14901 * All rights reserved
14902 *
14903 * Licensed under the Apache License, Version 2.0 (the ""License"");
14904 * you may not use this file except in compliance with the License.
14905 * You may obtain a copy of the License at
14906 *
14907 * http://www.apache.org/licenses/LICENSE-2.0
14908 *
14909 * Unless required by applicable law or agreed to in writing, software
14910 * distributed under the License is distributed on an ""AS IS"" BASIS,
14911 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14912 * See the License for the specific language governing permissions and
14913 * limitations under the License.
14914 */
14915
14916 #if MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_SIMPLELINK
14917
14918 /* Amalgamated: #include "common/mg_mem.h" */
14919
14920 #ifndef MG_SSL_IF_SIMPLELINK_SLFS_PREFIX
14921 #define MG_SSL_IF_SIMPLELINK_SLFS_PREFIX "SL:"
14922 #endif
14923
14924 #define MG_SSL_IF_SIMPLELINK_SLFS_PREFIX_LEN \
14925 (sizeof(MG_SSL_IF_SIMPLELINK_SLFS_PREFIX) - 1)
14926
14927 struct mg_ssl_if_ctx {
14928 char *ssl_cert;
14929 char *ssl_key;
14930 char *ssl_ca_cert;
14931 char *ssl_server_name;
14932 };
14933
14934 void mg_ssl_if_init() {
14935 }
14936
14937 enum mg_ssl_if_result mg_ssl_if_conn_init(
14938 struct mg_connection *nc, const struct mg_ssl_if_conn_params *params,
14939 const char **err_msg) {
14940 struct mg_ssl_if_ctx *ctx =
14941 (struct mg_ssl_if_ctx *) MG_CALLOC(1, sizeof(*ctx));
14942 if (ctx == NULL) {
14943 MG_SET_PTRPTR(err_msg, "Out of memory");
14944 return MG_SSL_ERROR;
14945 }
14946 nc->ssl_if_data = ctx;
14947
14948 if (params->cert != NULL || params->key != NULL) {
14949 if (params->cert != NULL && params->key != NULL) {
14950 ctx->ssl_cert = strdup(params->cert);
14951 ctx->ssl_key = strdup(params->key);
14952 } else {
14953 MG_SET_PTRPTR(err_msg, "Both cert and key are required.");
14954 return MG_SSL_ERROR;
14955 }
14956 }
14957 if (params->ca_cert != NULL && strcmp(params->ca_cert, "*") != 0) {
14958 ctx->ssl_ca_cert = strdup(params->ca_cert);
14959 }
14960 /* TODO(rojer): cipher_suites. */
14961 if (params->server_name != NULL) {
14962 ctx->ssl_server_name = strdup(params->server_name);
14963 }
14964 return MG_SSL_OK;
14965 }
14966
14967 enum mg_ssl_if_result mg_ssl_if_conn_accept(struct mg_connection *nc,
14968 struct mg_connection *lc) {
14969 /* SimpleLink does everything for us, nothing for us to do. */
14970 (void) nc;
14971 (void) lc;
14972 return MG_SSL_OK;
14973 }
14974
14975 enum mg_ssl_if_result mg_ssl_if_handshake(struct mg_connection *nc) {
14976 /* SimpleLink has already performed the handshake, nothing to do. */
14977 return MG_SSL_OK;
14978 }
14979
14980 int mg_ssl_if_read(struct mg_connection *nc, void *buf, size_t len) {
14981 /* SimpelLink handles TLS, so this is just a pass-through. */
14982 int n = nc->iface->vtable->tcp_recv(nc, buf, len);
14983 if (n == 0) nc->flags |= MG_F_WANT_READ;
14984 return n;
14985 }
14986
14987 int mg_ssl_if_write(struct mg_connection *nc, const void *buf, size_t len) {
14988 /* SimpelLink handles TLS, so this is just a pass-through. */
14989 return nc->iface->vtable->tcp_send(nc, buf, len);
14990 }
14991
14992 void mg_ssl_if_conn_close_notify(struct mg_connection *nc) {
14993 /* Nothing to do */
14994 (void) nc;
14995 }
14996
14997 void mg_ssl_if_conn_free(struct mg_connection *nc) {
14998 struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
14999 if (ctx == NULL) return;
15000 nc->ssl_if_data = NULL;
15001 MG_FREE(ctx->ssl_cert);
15002 MG_FREE(ctx->ssl_key);
15003 MG_FREE(ctx->ssl_ca_cert);
15004 MG_FREE(ctx->ssl_server_name);
15005 memset(ctx, 0, sizeof(*ctx));
15006 MG_FREE(ctx);
15007 }
15008
15009 bool pem_to_der(const char *pem_file, const char *der_file) {
15010 bool ret = false;
15011 FILE *pf = NULL, *df = NULL;
15012 bool writing = false;
15013 pf = fopen(pem_file, "r");
15014 if (pf == NULL) goto clean;
15015 remove(der_file);
15016 fs_slfs_set_file_size(der_file + MG_SSL_IF_SIMPLELINK_SLFS_PREFIX_LEN, 2048);
15017 df = fopen(der_file, "w");
15018 fs_slfs_unset_file_flags(der_file + MG_SSL_IF_SIMPLELINK_SLFS_PREFIX_LEN);
15019 if (df == NULL) goto clean;
15020 while (1) {
15021 char pem_buf[70];
15022 char der_buf[48];
15023 if (!fgets(pem_buf, sizeof(pem_buf), pf)) break;
15024 if (writing) {
15025 if (strstr(pem_buf, "-----END ") != NULL) {
15026 ret = true;
15027 break;
15028 }
15029 int l = 0;
15030 while (!isspace((unsigned int) pem_buf[l])) l++;
15031 int der_len = 0;
15032 cs_base64_decode((const unsigned char *) pem_buf, sizeof(pem_buf),
15033 der_buf, &der_len);
15034 if (der_len <= 0) break;
15035 if (fwrite(der_buf, 1, der_len, df) != der_len) break;
15036 } else if (strstr(pem_buf, "-----BEGIN ") != NULL) {
15037 writing = true;
15038 }
15039 }
15040
15041 clean:
15042 if (pf != NULL) fclose(pf);
15043 if (df != NULL) {
15044 fclose(df);
15045 if (!ret) remove(der_file);
15046 }
15047 return ret;
15048 }
15049
15050 #if MG_ENABLE_FILESYSTEM && defined(MG_FS_SLFS)
15051 /* If the file's extension is .pem, convert it to DER format and put on SLFS. */
15052 static char *sl_pem2der(const char *pem_file) {
15053 const char *pem_ext = strstr(pem_file, ".pem");
15054 if (pem_ext == NULL || *(pem_ext + 4) != '\0') {
15055 return strdup(pem_file);
15056 }
15057 char *der_file = NULL;
15058 /* DER file must be located on SLFS, add prefix. */
15059 int l = mg_asprintf(&der_file, 0, MG_SSL_IF_SIMPLELINK_SLFS_PREFIX "%.*s.der",
15060 (int) (pem_ext - pem_file), pem_file);
15061 if (der_file == NULL) return NULL;
15062 bool result = false;
15063 cs_stat_t st;
15064 if (mg_stat(der_file, &st) != 0) {
15065 result = pem_to_der(pem_file, der_file);
15066 LOG(LL_DEBUG, ("%s -> %s = %d", pem_file, der_file, result));
15067 } else {
15068 /* File exists, assume it's already been converted. */
15069 result = true;
15070 }
15071 if (result) {
15072 /* Strip the SL: prefix we added since NWP does not expect it. */
15073 memmove(der_file, der_file + MG_SSL_IF_SIMPLELINK_SLFS_PREFIX_LEN,
15074 l - 2 /* including \0 */);
15075 } else {
15076 MG_FREE(der_file);
15077 der_file = NULL;
15078 }
15079 return der_file;
15080 }
15081 #else
15082 static char *sl_pem2der(const char *pem_file) {
15083 return strdup(pem_file);
15084 }
15085 #endif
15086
15087 int sl_set_ssl_opts(int sock, struct mg_connection *nc) {
15088 int err;
15089 const struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
15090 DBG(("%p ssl ctx: %p", nc, ctx));
15091
15092 if (ctx == NULL) return 0;
15093 DBG(("%p %s,%s,%s,%s", nc, (ctx->ssl_cert ? ctx->ssl_cert : "-"),
15094 (ctx->ssl_key ? ctx->ssl_cert : "-"),
15095 (ctx->ssl_ca_cert ? ctx->ssl_ca_cert : "-"),
15096 (ctx->ssl_server_name ? ctx->ssl_server_name : "-")));
15097 if (ctx->ssl_cert != NULL && ctx->ssl_key != NULL) {
15098 char *ssl_cert = sl_pem2der(ctx->ssl_cert), *ssl_key = NULL;
15099 if (ssl_cert != NULL) {
15100 err = sl_SetSockOpt(sock, SL_SOL_SOCKET,
15101 SL_SO_SECURE_FILES_CERTIFICATE_FILE_NAME, ssl_cert,
15102 strlen(ssl_cert));
15103 MG_FREE(ssl_cert);
15104 LOG(LL_DEBUG, ("CERTIFICATE_FILE_NAME %s -> %d", ssl_cert, err));
15105 ssl_key = sl_pem2der(ctx->ssl_key);
15106 if (ssl_key != NULL) {
15107 err = sl_SetSockOpt(sock, SL_SOL_SOCKET,
15108 SL_SO_SECURE_FILES_PRIVATE_KEY_FILE_NAME, ssl_key,
15109 strlen(ssl_key));
15110 MG_FREE(ssl_key);
15111 LOG(LL_DEBUG, ("PRIVATE_KEY_FILE_NAME %s -> %d", ssl_key, err));
15112 } else {
15113 err = -1;
15114 }
15115 } else {
15116 err = -1;
15117 }
15118 if (err != 0) return err;
15119 }
15120 if (ctx->ssl_ca_cert != NULL) {
15121 if (ctx->ssl_ca_cert[0] != '\0') {
15122 char *ssl_ca_cert = sl_pem2der(ctx->ssl_ca_cert);
15123 if (ssl_ca_cert != NULL) {
15124 err =
15125 sl_SetSockOpt(sock, SL_SOL_SOCKET, SL_SO_SECURE_FILES_CA_FILE_NAME,
15126 ssl_ca_cert, strlen(ssl_ca_cert));
15127 LOG(LL_DEBUG, ("CA_FILE_NAME %s -> %d", ssl_ca_cert, err));
15128 } else {
15129 err = -1;
15130 }
15131 MG_FREE(ssl_ca_cert);
15132 if (err != 0) return err;
15133 }
15134 }
15135 if (ctx->ssl_server_name != NULL) {
15136 err = sl_SetSockOpt(sock, SL_SOL_SOCKET,
15137 SL_SO_SECURE_DOMAIN_NAME_VERIFICATION,
15138 ctx->ssl_server_name, strlen(ctx->ssl_server_name));
15139 DBG(("DOMAIN_NAME_VERIFICATION %s -> %d", ctx->ssl_server_name, err));
15140 /* Domain name verificationw as added in a NWP service pack, older
15141 * versions return SL_ERROR_BSD_ENOPROTOOPT. There isn't much we can do
15142 * about it,
15143 * so we ignore the error. */
15144 if (err != 0 && err != SL_ERROR_BSD_ENOPROTOOPT) return err;
15145 }
15146 return 0;
15147 }
15148
15149 #endif /* MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_SIMPLELINK */
15150 #ifdef MG_MODULE_LINES
15151 #line 1 "common/platforms/lwip/mg_lwip_net_if.h"
15152 #endif
15153 /*
15154 * Copyright (c) 2014-2018 Cesanta Software Limited
15155 * All rights reserved
15156 *
15157 * Licensed under the Apache License, Version 2.0 (the ""License"");
15158 * you may not use this file except in compliance with the License.
15159 * You may obtain a copy of the License at
15160 *
15161 * http://www.apache.org/licenses/LICENSE-2.0
15162 *
15163 * Unless required by applicable law or agreed to in writing, software
15164 * distributed under the License is distributed on an ""AS IS"" BASIS,
15165 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15166 * See the License for the specific language governing permissions and
15167 * limitations under the License.
15168 */
15169
15170 #ifndef CS_COMMON_PLATFORMS_LWIP_MG_NET_IF_LWIP_H_
15171 #define CS_COMMON_PLATFORMS_LWIP_MG_NET_IF_LWIP_H_
15172
15173 #ifndef MG_ENABLE_NET_IF_LWIP_LOW_LEVEL
15174 #define MG_ENABLE_NET_IF_LWIP_LOW_LEVEL MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL
15175 #endif
15176
15177 #if MG_ENABLE_NET_IF_LWIP_LOW_LEVEL
15178
15179 #include <stdint.h>
15180
15181 extern const struct mg_iface_vtable mg_lwip_iface_vtable;
15182
15183 struct mg_lwip_conn_state {
15184 struct mg_connection *nc;
15185 struct mg_connection *lc;
15186 union {
15187 struct tcp_pcb *tcp;
15188 struct udp_pcb *udp;
15189 } pcb;
15190 err_t err;
15191 size_t num_sent; /* Number of acknowledged bytes to be reported to the core */
15192 struct pbuf *rx_chain; /* Chain of incoming data segments. */
15193 size_t rx_offset; /* Offset within the first pbuf (if partially consumed) */
15194 /* Last SSL write size, for retries. */
15195 int last_ssl_write_size;
15196 /* Whether MG_SIG_RECV is already pending for this connection */
15197 int recv_pending;
15198 /* Whether the connection is about to close, just `rx_chain` needs to drain */
15199 int draining_rx_chain;
15200 };
15201
15202 enum mg_sig_type {
15203 MG_SIG_CONNECT_RESULT = 1,
15204 MG_SIG_RECV = 2,
15205 MG_SIG_CLOSE_CONN = 3,
15206 MG_SIG_TOMBSTONE = 4,
15207 MG_SIG_ACCEPT = 5,
15208 };
15209
15210 void mg_lwip_post_signal(enum mg_sig_type sig, struct mg_connection *nc);
15211
15212 /* To be implemented by the platform. */
15213 void mg_lwip_mgr_schedule_poll(struct mg_mgr *mgr);
15214
15215 #endif /* MG_ENABLE_NET_IF_LWIP_LOW_LEVEL */
15216
15217 #endif /* CS_COMMON_PLATFORMS_LWIP_MG_NET_IF_LWIP_H_ */
15218 #ifdef MG_MODULE_LINES
15219 #line 1 "common/platforms/lwip/mg_lwip_net_if.c"
15220 #endif
15221 /*
15222 * Copyright (c) 2014-2018 Cesanta Software Limited
15223 * All rights reserved
15224 *
15225 * Licensed under the Apache License, Version 2.0 (the ""License"");
15226 * you may not use this file except in compliance with the License.
15227 * You may obtain a copy of the License at
15228 *
15229 * http://www.apache.org/licenses/LICENSE-2.0
15230 *
15231 * Unless required by applicable law or agreed to in writing, software
15232 * distributed under the License is distributed on an ""AS IS"" BASIS,
15233 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15234 * See the License for the specific language governing permissions and
15235 * limitations under the License.
15236 */
15237
15238 #if MG_ENABLE_NET_IF_LWIP_LOW_LEVEL
15239
15240 /* Amalgamated: #include "common/mg_mem.h" */
15241
15242 #include <lwip/init.h>
15243 #include <lwip/pbuf.h>
15244 #include <lwip/tcp.h>
15245 #include <lwip/tcpip.h>
15246 #if ((LWIP_VERSION_MAJOR << 8) | LWIP_VERSION_MINOR) >= 0x0105
15247 #include <lwip/priv/tcp_priv.h> /* For tcp_seg */
15248 #include <lwip/priv/tcpip_priv.h> /* For tcpip_api_call */
15249 #else
15250 #include <lwip/tcp_impl.h>
15251 #endif
15252 #include <lwip/udp.h>
15253
15254 /* Amalgamated: #include "common/cs_dbg.h" */
15255
15256 /*
15257 * Newest versions of LWIP have ip_2_ip4, older have ipX_2_ip,
15258 * even older have nothing.
15259 */
15260 #ifndef ip_2_ip4
15261 #ifdef ipX_2_ip
15262 #define ip_2_ip4(addr) ipX_2_ip(addr)
15263 #else
15264 #define ip_2_ip4(addr) (addr)
15265 #endif
15266 #endif
15267
15268 /*
15269 * Depending on whether Mongoose is compiled with ipv6 support, use right
15270 * lwip functions
15271 */
15272 #if MG_ENABLE_IPV6
15273 #define TCP_NEW tcp_new_ip6
15274 #define TCP_BIND tcp_bind_ip6
15275 #define UDP_BIND udp_bind_ip6
15276 #define IPADDR_NTOA(x) ip6addr_ntoa((const ip6_addr_t *)(x))
15277 #define SET_ADDR(dst, src) \
15278 memcpy((dst)->sin6.sin6_addr.s6_addr, (src)->ip6.addr, \
15279 sizeof((dst)->sin6.sin6_addr.s6_addr))
15280 #else
15281 #define TCP_NEW tcp_new
15282 #define TCP_BIND tcp_bind
15283 #define UDP_BIND udp_bind
15284 #define IPADDR_NTOA ipaddr_ntoa
15285 #define SET_ADDR(dst, src) (dst)->sin.sin_addr.s_addr = ip_2_ip4(src)->addr
15286 #endif
15287
15288 #if !NO_SYS
15289 #if LWIP_TCPIP_CORE_LOCKING
15290 /* With locking tcpip_api_call is just a function call wrapped in lock/unlock,
15291 * so we can get away with just casting. */
15292 void mg_lwip_netif_run_on_tcpip(void (*fn)(void *), void *arg) {
15293 tcpip_api_call((tcpip_api_call_fn) fn, (struct tcpip_api_call_data *) arg);
15294 }
15295 #else
15296 static sys_sem_t s_tcpip_call_lock_sem = NULL;
15297 static sys_sem_t s_tcpip_call_sync_sem = NULL;
15298 struct mg_lwip_netif_tcpip_call_ctx {
15299 void (*fn)(void *);
15300 void *arg;
15301 };
15302 static void xxx_tcpip(void *arg) {
15303 struct mg_lwip_netif_tcpip_call_ctx *ctx =
15304 (struct mg_lwip_netif_tcpip_call_ctx *) arg;
15305 ctx->fn(ctx->arg);
15306 sys_sem_signal(&s_tcpip_call_sync_sem);
15307 }
15308 void mg_lwip_netif_run_on_tcpip(void (*fn)(void *), void *arg) {
15309 struct mg_lwip_netif_tcpip_call_ctx ctx = {.fn = fn, .arg = arg};
15310 sys_arch_sem_wait(&s_tcpip_call_lock_sem, 0);
15311 tcpip_send_msg_wait_sem(xxx_tcpip, &ctx, &s_tcpip_call_sync_sem);
15312 sys_sem_signal(&s_tcpip_call_lock_sem);
15313 }
15314 #endif
15315 #else
15316 #define mg_lwip_netif_run_on_tcpip(fn, arg) (fn)(arg)
15317 #endif
15318
15319 void mg_lwip_if_init(struct mg_iface *iface);
15320 void mg_lwip_if_free(struct mg_iface *iface);
15321 void mg_lwip_if_add_conn(struct mg_connection *nc);
15322 void mg_lwip_if_remove_conn(struct mg_connection *nc);
15323 time_t mg_lwip_if_poll(struct mg_iface *iface, int timeout_ms);
15324
15325 // If compiling for Mongoose OS.
15326 #ifdef MGOS
15327 extern void mgos_lock();
15328 extern void mgos_unlock();
15329 #else
15330 #define mgos_lock()
15331 #define mgos_unlock()
15332 #endif
15333
15334 static void mg_lwip_recv_common(struct mg_connection *nc, struct pbuf *p);
15335
15336 #if LWIP_TCP_KEEPALIVE
15337 void mg_lwip_set_keepalive_params(struct mg_connection *nc, int idle,
15338 int interval, int count) {
15339 if (nc->sock == INVALID_SOCKET || nc->flags & MG_F_UDP) {
15340 return;
15341 }
15342 struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
15343 struct tcp_pcb *tpcb = cs->pcb.tcp;
15344 if (idle > 0 && interval > 0 && count > 0) {
15345 tpcb->keep_idle = idle * 1000;
15346 tpcb->keep_intvl = interval * 1000;
15347 tpcb->keep_cnt = count;
15348 tpcb->so_options |= SOF_KEEPALIVE;
15349 } else {
15350 tpcb->so_options &= ~SOF_KEEPALIVE;
15351 }
15352 }
15353 #elif !defined(MG_NO_LWIP_TCP_KEEPALIVE)
15354 #warning LWIP TCP keepalive is disabled. Please consider enabling it.
15355 #endif /* LWIP_TCP_KEEPALIVE */
15356
15357 static err_t mg_lwip_tcp_conn_cb(void *arg, struct tcp_pcb *tpcb, err_t err) {
15358 struct mg_connection *nc = (struct mg_connection *) arg;
15359 DBG(("%p connect to %s:%u = %d", nc, IPADDR_NTOA(ipX_2_ip(&tpcb->remote_ip)),
15360 tpcb->remote_port, err));
15361 if (nc == NULL) {
15362 tcp_abort(tpcb);
15363 return ERR_ARG;
15364 }
15365 struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
15366 cs->err = err;
15367 #if LWIP_TCP_KEEPALIVE
15368 if (err == 0) mg_lwip_set_keepalive_params(nc, 60, 10, 6);
15369 #endif
15370 mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc);
15371 return ERR_OK;
15372 }
15373
15374 static void mg_lwip_tcp_error_cb(void *arg, err_t err) {
15375 struct mg_connection *nc = (struct mg_connection *) arg;
15376 DBG(("%p conn error %d", nc, err));
15377 if (nc == NULL || (nc->flags & MG_F_CLOSE_IMMEDIATELY)) return;
15378 struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
15379 cs->pcb.tcp = NULL; /* Has already been deallocated */
15380 if (nc->flags & MG_F_CONNECTING) {
15381 cs->err = err;
15382 mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc);
15383 } else {
15384 mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc);
15385 }
15386 }
15387
15388 static err_t mg_lwip_tcp_recv_cb(void *arg, struct tcp_pcb *tpcb,
15389 struct pbuf *p, err_t err) {
15390 struct mg_connection *nc = (struct mg_connection *) arg;
15391 struct mg_lwip_conn_state *cs =
15392 (nc ? (struct mg_lwip_conn_state *) nc->sock : NULL);
15393 DBG(("%p %p %p %p %u %d", nc, cs, tpcb, p, (p != NULL ? p->tot_len : 0),
15394 err));
15395 if (p == NULL) {
15396 if (nc != NULL && !(nc->flags & MG_F_CLOSE_IMMEDIATELY)) {
15397 if (cs->rx_chain != NULL) {
15398 /*
15399 * rx_chain still contains non-consumed data, don't close the
15400 * connection
15401 */
15402 cs->draining_rx_chain = 1;
15403 } else {
15404 mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc);
15405 }
15406 } else {
15407 /* Tombstoned connection, do nothing. */
15408 }
15409 return ERR_OK;
15410 } else if (nc == NULL) {
15411 tcp_abort(tpcb);
15412 return ERR_ARG;
15413 }
15414 /*
15415 * If we get a chain of more than one segment at once, we need to bump
15416 * refcount on the subsequent bufs to make them independent.
15417 */
15418 if (p->next != NULL) {
15419 struct pbuf *q = p->next;
15420 for (; q != NULL; q = q->next) pbuf_ref(q);
15421 }
15422 mgos_lock();
15423 if (cs->rx_chain == NULL) {
15424 cs->rx_offset = 0;
15425 } else if (pbuf_clen(cs->rx_chain) >= 4) {
15426 /* ESP SDK has a limited pool of 5 pbufs. We must not hog them all or RX
15427 * will be completely blocked. We already have at least 4 in the chain,
15428 * this one is the last, so we have to make a copy and release this one. */
15429 struct pbuf *np = pbuf_alloc(PBUF_RAW, p->tot_len, PBUF_RAM);
15430 if (np != NULL) {
15431 pbuf_copy(np, p);
15432 pbuf_free(p);
15433 p = np;
15434 }
15435 }
15436 mg_lwip_recv_common(nc, p);
15437 mgos_unlock();
15438 (void) err;
15439 return ERR_OK;
15440 }
15441
15442 static err_t mg_lwip_tcp_sent_cb(void *arg, struct tcp_pcb *tpcb,
15443 u16_t num_sent) {
15444 struct mg_connection *nc = (struct mg_connection *) arg;
15445 DBG(("%p %p %u %p %p", nc, tpcb, num_sent, tpcb->unsent, tpcb->unacked));
15446 if (nc == NULL) return ERR_OK;
15447 if ((nc->flags & MG_F_SEND_AND_CLOSE) && !(nc->flags & MG_F_WANT_WRITE) &&
15448 nc->send_mbuf.len == 0 && tpcb->unsent == NULL && tpcb->unacked == NULL) {
15449 mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc);
15450 }
15451 if (nc->send_mbuf.len > 0 || (nc->flags & MG_F_WANT_WRITE)) {
15452 mg_lwip_mgr_schedule_poll(nc->mgr);
15453 }
15454 (void) num_sent;
15455 return ERR_OK;
15456 }
15457
15458 struct mg_lwip_if_connect_tcp_ctx {
15459 struct mg_connection *nc;
15460 const union socket_address *sa;
15461 };
15462
15463 static void mg_lwip_if_connect_tcp_tcpip(void *arg) {
15464 struct mg_lwip_if_connect_tcp_ctx *ctx =
15465 (struct mg_lwip_if_connect_tcp_ctx *) arg;
15466 struct mg_connection *nc = ctx->nc;
15467 const union socket_address *sa = ctx->sa;
15468
15469 struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
15470 struct tcp_pcb *tpcb = TCP_NEW();
15471 cs->pcb.tcp = tpcb;
15472 ip_addr_t *ip = (ip_addr_t *) &sa->sin.sin_addr.s_addr;
15473 u16_t port = ntohs(sa->sin.sin_port);
15474 tcp_arg(tpcb, nc);
15475 tcp_err(tpcb, mg_lwip_tcp_error_cb);
15476 tcp_sent(tpcb, mg_lwip_tcp_sent_cb);
15477 tcp_recv(tpcb, mg_lwip_tcp_recv_cb);
15478 cs->err = TCP_BIND(tpcb, IP_ADDR_ANY, 0 /* any port */);
15479 DBG(("%p tcp_bind = %d", nc, cs->err));
15480 if (cs->err != ERR_OK) {
15481 mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc);
15482 return;
15483 }
15484 cs->err = tcp_connect(tpcb, ip, port, mg_lwip_tcp_conn_cb);
15485 DBG(("%p tcp_connect %p = %d", nc, tpcb, cs->err));
15486 if (cs->err != ERR_OK) {
15487 mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc);
15488 return;
15489 }
15490 }
15491
15492 void mg_lwip_if_connect_tcp(struct mg_connection *nc,
15493 const union socket_address *sa) {
15494 struct mg_lwip_if_connect_tcp_ctx ctx = {.nc = nc, .sa = sa};
15495 mg_lwip_netif_run_on_tcpip(mg_lwip_if_connect_tcp_tcpip, &ctx);
15496 }
15497
15498 /*
15499 * Lwip included in the SDKs for nRF5x chips has different type for the
15500 * callback of `udp_recv()`
15501 */
15502 #if ((LWIP_VERSION_MAJOR << 8) | LWIP_VERSION_MINOR) >= 0x0105
15503 static void mg_lwip_udp_recv_cb(void *arg, struct udp_pcb *pcb, struct pbuf *p,
15504 const ip_addr_t *addr, u16_t port)
15505 #else
15506 static void mg_lwip_udp_recv_cb(void *arg, struct udp_pcb *pcb, struct pbuf *p,
15507 ip_addr_t *addr, u16_t port)
15508 #endif
15509 {
15510 struct mg_connection *nc = (struct mg_connection *) arg;
15511 DBG(("%p %s:%u %p %u %u", nc, IPADDR_NTOA(addr), port, p, p->ref, p->len));
15512 /* Put address in a separate pbuf and tack it onto the packet. */
15513 struct pbuf *sap =
15514 pbuf_alloc(PBUF_RAW, sizeof(union socket_address), PBUF_RAM);
15515 if (sap == NULL) {
15516 pbuf_free(p);
15517 return;
15518 }
15519 union socket_address *sa = (union socket_address *) sap->payload;
15520 #if ((LWIP_VERSION_MAJOR << 8) | LWIP_VERSION_MINOR) >= 0x0105
15521 sa->sin.sin_addr.s_addr = ip_2_ip4(addr)->addr;
15522 #else
15523 sa->sin.sin_addr.s_addr = addr->addr;
15524 #endif
15525 sa->sin.sin_port = htons(port);
15526 /* Logic in the recv handler requires that there be exactly one data pbuf. */
15527 p = pbuf_coalesce(p, PBUF_RAW);
15528 pbuf_chain(sap, p);
15529 mgos_lock();
15530 mg_lwip_recv_common(nc, sap);
15531 mgos_unlock();
15532 (void) pcb;
15533 }
15534
15535 static void mg_lwip_recv_common(struct mg_connection *nc, struct pbuf *p) {
15536 struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
15537 if (cs->rx_chain == NULL) {
15538 cs->rx_chain = p;
15539 } else {
15540 pbuf_chain(cs->rx_chain, p);
15541 }
15542 if (!cs->recv_pending) {
15543 cs->recv_pending = 1;
15544 mg_lwip_post_signal(MG_SIG_RECV, nc);
15545 }
15546 }
15547
15548 static int mg_lwip_if_udp_recv(struct mg_connection *nc, void *buf, size_t len,
15549 union socket_address *sa, size_t *sa_len) {
15550 /*
15551 * For UDP, RX chain consists of interleaved address and packet bufs:
15552 * Address pbuf followed by exactly one data pbuf (recv_cb took care of that).
15553 */
15554 int res = 0;
15555 struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
15556 if (nc->sock == INVALID_SOCKET) return -1;
15557 mgos_lock();
15558 if (cs->rx_chain != NULL) {
15559 struct pbuf *ap = cs->rx_chain;
15560 struct pbuf *dp = ap->next;
15561 cs->rx_chain = pbuf_dechain(dp);
15562 res = MIN(dp->len, len);
15563 pbuf_copy_partial(dp, buf, res, 0);
15564 pbuf_free(dp);
15565 pbuf_copy_partial(ap, sa, MIN(*sa_len, ap->len), 0);
15566 pbuf_free(ap);
15567 }
15568 mgos_unlock();
15569 return res;
15570 }
15571
15572 static void mg_lwip_if_connect_udp_tcpip(void *arg) {
15573 struct mg_connection *nc = (struct mg_connection *) arg;
15574 struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
15575 struct udp_pcb *upcb = udp_new();
15576 cs->err = UDP_BIND(upcb, IP_ADDR_ANY, 0 /* any port */);
15577 DBG(("%p udp_bind %p = %d", nc, upcb, cs->err));
15578 if (cs->err == ERR_OK) {
15579 udp_recv(upcb, mg_lwip_udp_recv_cb, nc);
15580 cs->pcb.udp = upcb;
15581 } else {
15582 udp_remove(upcb);
15583 }
15584 mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc);
15585 }
15586
15587 void mg_lwip_if_connect_udp(struct mg_connection *nc) {
15588 mg_lwip_netif_run_on_tcpip(mg_lwip_if_connect_udp_tcpip, nc);
15589 }
15590
15591 static void tcp_close_tcpip(void *arg) {
15592 tcp_close((struct tcp_pcb *) arg);
15593 }
15594
15595 void mg_lwip_handle_accept(struct mg_connection *nc) {
15596 struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
15597 if (cs->pcb.tcp == NULL) return;
15598 union socket_address sa;
15599 struct tcp_pcb *tpcb = cs->pcb.tcp;
15600 SET_ADDR(&sa, &tpcb->remote_ip);
15601 sa.sin.sin_port = htons(tpcb->remote_port);
15602 mg_if_accept_tcp_cb(nc, &sa, sizeof(sa.sin));
15603 }
15604
15605 static err_t mg_lwip_accept_cb(void *arg, struct tcp_pcb *newtpcb, err_t err) {
15606 struct mg_connection *lc = (struct mg_connection *) arg, *nc;
15607 struct mg_lwip_conn_state *lcs, *cs;
15608 struct tcp_pcb_listen *lpcb;
15609 LOG(LL_DEBUG,
15610 ("%p conn %p from %s:%u", lc, newtpcb,
15611 IPADDR_NTOA(ipX_2_ip(&newtpcb->remote_ip)), newtpcb->remote_port));
15612 if (lc == NULL) {
15613 tcp_abort(newtpcb);
15614 return ERR_ABRT;
15615 }
15616 lcs = (struct mg_lwip_conn_state *) lc->sock;
15617 lpcb = (struct tcp_pcb_listen *) lcs->pcb.tcp;
15618 #if TCP_LISTEN_BACKLOG
15619 tcp_accepted(lpcb);
15620 #endif
15621 nc = mg_if_accept_new_conn(lc);
15622 if (nc == NULL) {
15623 tcp_abort(newtpcb);
15624 return ERR_ABRT;
15625 }
15626 cs = (struct mg_lwip_conn_state *) nc->sock;
15627 cs->lc = lc;
15628 cs->pcb.tcp = newtpcb;
15629 /* We need to set up callbacks before returning because data may start
15630 * arriving immediately. */
15631 tcp_arg(newtpcb, nc);
15632 tcp_err(newtpcb, mg_lwip_tcp_error_cb);
15633 tcp_sent(newtpcb, mg_lwip_tcp_sent_cb);
15634 tcp_recv(newtpcb, mg_lwip_tcp_recv_cb);
15635 #if LWIP_TCP_KEEPALIVE
15636 mg_lwip_set_keepalive_params(nc, 60, 10, 6);
15637 #endif
15638 mg_lwip_post_signal(MG_SIG_ACCEPT, nc);
15639 (void) err;
15640 (void) lpcb;
15641 return ERR_OK;
15642 }
15643
15644 struct mg_lwip_if_listen_ctx {
15645 struct mg_connection *nc;
15646 union socket_address *sa;
15647 int ret;
15648 };
15649
15650 static void mg_lwip_if_listen_tcp_tcpip(void *arg) {
15651 struct mg_lwip_if_listen_ctx *ctx = (struct mg_lwip_if_listen_ctx *) arg;
15652 struct mg_connection *nc = ctx->nc;
15653 union socket_address *sa = ctx->sa;
15654 struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
15655 struct tcp_pcb *tpcb = TCP_NEW();
15656 ip_addr_t *ip = (ip_addr_t *) &sa->sin.sin_addr.s_addr;
15657 u16_t port = ntohs(sa->sin.sin_port);
15658 cs->err = TCP_BIND(tpcb, ip, port);
15659 DBG(("%p tcp_bind(%s:%u) = %d", nc, IPADDR_NTOA(ip), port, cs->err));
15660 if (cs->err != ERR_OK) {
15661 tcp_close(tpcb);
15662 ctx->ret = -1;
15663 return;
15664 }
15665 tcp_arg(tpcb, nc);
15666 tpcb = tcp_listen(tpcb);
15667 cs->pcb.tcp = tpcb;
15668 tcp_accept(tpcb, mg_lwip_accept_cb);
15669 ctx->ret = 0;
15670 }
15671
15672 int mg_lwip_if_listen_tcp(struct mg_connection *nc, union socket_address *sa) {
15673 struct mg_lwip_if_listen_ctx ctx = {.nc = nc, .sa = sa};
15674 mg_lwip_netif_run_on_tcpip(mg_lwip_if_listen_tcp_tcpip, &ctx);
15675 return ctx.ret;
15676 }
15677
15678 static void mg_lwip_if_listen_udp_tcpip(void *arg) {
15679 struct mg_lwip_if_listen_ctx *ctx = (struct mg_lwip_if_listen_ctx *) arg;
15680 struct mg_connection *nc = ctx->nc;
15681 union socket_address *sa = ctx->sa;
15682 struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
15683 struct udp_pcb *upcb = udp_new();
15684 ip_addr_t *ip = (ip_addr_t *) &sa->sin.sin_addr.s_addr;
15685 u16_t port = ntohs(sa->sin.sin_port);
15686 cs->err = UDP_BIND(upcb, ip, port);
15687 DBG(("%p udb_bind(%s:%u) = %d", nc, IPADDR_NTOA(ip), port, cs->err));
15688 if (cs->err != ERR_OK) {
15689 udp_remove(upcb);
15690 ctx->ret = -1;
15691 } else {
15692 udp_recv(upcb, mg_lwip_udp_recv_cb, nc);
15693 cs->pcb.udp = upcb;
15694 ctx->ret = 0;
15695 }
15696 }
15697
15698 int mg_lwip_if_listen_udp(struct mg_connection *nc, union socket_address *sa) {
15699 struct mg_lwip_if_listen_ctx ctx = {.nc = nc, .sa = sa};
15700 mg_lwip_netif_run_on_tcpip(mg_lwip_if_listen_udp_tcpip, &ctx);
15701 return ctx.ret;
15702 }
15703
15704 struct mg_lwip_tcp_write_ctx {
15705 struct mg_connection *nc;
15706 const void *data;
15707 uint16_t len;
15708 int ret;
15709 };
15710
15711 static void tcp_output_tcpip(void *arg) {
15712 tcp_output((struct tcp_pcb *) arg);
15713 }
15714
15715 static void mg_lwip_tcp_write_tcpip(void *arg) {
15716 struct mg_lwip_tcp_write_ctx *ctx = (struct mg_lwip_tcp_write_ctx *) arg;
15717 struct mg_connection *nc = ctx->nc;
15718 struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
15719 struct tcp_pcb *tpcb = cs->pcb.tcp;
15720 size_t len = MIN(tpcb->mss, MIN(ctx->len, tpcb->snd_buf));
15721 size_t unsent, unacked;
15722 if (len == 0) {
15723 DBG(("%p no buf avail %u %u %p %p", tpcb, tpcb->snd_buf, tpcb->snd_queuelen,
15724 tpcb->unsent, tpcb->unacked));
15725 mg_lwip_netif_run_on_tcpip(tcp_output_tcpip, tpcb);
15726 ctx->ret = 0;
15727 return;
15728 }
15729 unsent = (tpcb->unsent != NULL ? tpcb->unsent->len : 0);
15730 unacked = (tpcb->unacked != NULL ? tpcb->unacked->len : 0);
15731 /*
15732 * On ESP8266 we only allow one TCP segment in flight at any given time.
15733 * This may increase latency and reduce efficiency of tcp windowing,
15734 * but memory is scarce and precious on that platform so we do this to
15735 * reduce footprint.
15736 */
15737 #if CS_PLATFORM == CS_P_ESP8266
15738 if (unacked > 0) {
15739 ctx->ret = 0;
15740 return;
15741 }
15742 len = MIN(len, (TCP_MSS - unsent));
15743 #endif
15744 cs->err = tcp_write(tpcb, ctx->data, len, TCP_WRITE_FLAG_COPY);
15745 unsent = (tpcb->unsent != NULL ? tpcb->unsent->len : 0);
15746 unacked = (tpcb->unacked != NULL ? tpcb->unacked->len : 0);
15747 DBG(("%p tcp_write %u = %d, %u %u", tpcb, len, cs->err, unsent, unacked));
15748 if (cs->err != ERR_OK) {
15749 /*
15750 * We ignore ERR_MEM because memory will be freed up when the data is sent
15751 * and we'll retry.
15752 */
15753 ctx->ret = (cs->err == ERR_MEM ? 0 : -1);
15754 return;
15755 }
15756 ctx->ret = len;
15757 (void) unsent;
15758 (void) unacked;
15759 }
15760
15761 int mg_lwip_if_tcp_send(struct mg_connection *nc, const void *buf, size_t len) {
15762 struct mg_lwip_tcp_write_ctx ctx = {.nc = nc, .data = buf, .len = len};
15763 struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
15764 if (nc->sock == INVALID_SOCKET) return -1;
15765 struct tcp_pcb *tpcb = cs->pcb.tcp;
15766 if (tpcb == NULL) return -1;
15767 if (tpcb->snd_buf <= 0) return 0;
15768 mg_lwip_netif_run_on_tcpip(mg_lwip_tcp_write_tcpip, &ctx);
15769 return ctx.ret;
15770 }
15771
15772 struct udp_sendto_ctx {
15773 struct udp_pcb *upcb;
15774 struct pbuf *p;
15775 ip_addr_t *ip;
15776 uint16_t port;
15777 int ret;
15778 };
15779
15780 static void udp_sendto_tcpip(void *arg) {
15781 struct udp_sendto_ctx *ctx = (struct udp_sendto_ctx *) arg;
15782 ctx->ret = udp_sendto(ctx->upcb, ctx->p, ctx->ip, ctx->port);
15783 }
15784
15785 static int mg_lwip_if_udp_send(struct mg_connection *nc, const void *data,
15786 size_t len) {
15787 struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
15788 if (nc->sock == INVALID_SOCKET || cs->pcb.udp == NULL) return -1;
15789 struct udp_pcb *upcb = cs->pcb.udp;
15790 struct pbuf *p = pbuf_alloc(PBUF_TRANSPORT, len, PBUF_RAM);
15791 #if defined(LWIP_IPV4) && LWIP_IPV4 && defined(LWIP_IPV6) && LWIP_IPV6
15792 ip_addr_t ip = {.u_addr.ip4.addr = nc->sa.sin.sin_addr.s_addr, .type = 0};
15793 #else
15794 ip_addr_t ip = {.addr = nc->sa.sin.sin_addr.s_addr};
15795 #endif
15796 u16_t port = ntohs(nc->sa.sin.sin_port);
15797 if (p == NULL) return 0;
15798 memcpy(p->payload, data, len);
15799 struct udp_sendto_ctx ctx = {.upcb = upcb, .p = p, .ip = &ip, .port = port};
15800 mg_lwip_netif_run_on_tcpip(udp_sendto_tcpip, &ctx);
15801 cs->err = ctx.ret;
15802 pbuf_free(p);
15803 return (cs->err == ERR_OK ? (int) len : -2);
15804 }
15805
15806 static int mg_lwip_if_can_send(struct mg_connection *nc,
15807 struct mg_lwip_conn_state *cs) {
15808 int can_send = 0;
15809 if (nc->send_mbuf.len > 0 || (nc->flags & MG_F_WANT_WRITE)) {
15810 /* We have stuff to send, but can we? */
15811 if (nc->flags & MG_F_UDP) {
15812 /* UDP is always ready for sending. */
15813 can_send = (cs->pcb.udp != NULL);
15814 } else {
15815 can_send = (cs->pcb.tcp != NULL && cs->pcb.tcp->snd_buf > 0);
15816 /* See comment above. */
15817 #if CS_PLATFORM == CS_P_ESP8266
15818 if (cs->pcb.tcp->unacked != NULL) can_send = 0;
15819 #endif
15820 }
15821 }
15822 return can_send;
15823 }
15824
15825 struct tcp_recved_ctx {
15826 struct tcp_pcb *tpcb;
15827 size_t len;
15828 };
15829
15830 void tcp_recved_tcpip(void *arg) {
15831 struct tcp_recved_ctx *ctx = (struct tcp_recved_ctx *) arg;
15832 if (ctx->tpcb != NULL) tcp_recved(ctx->tpcb, ctx->len);
15833 }
15834
15835 static int mg_lwip_if_tcp_recv(struct mg_connection *nc, void *buf,
15836 size_t len) {
15837 int res = 0;
15838 char *bufp = buf;
15839 struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
15840 if (nc->sock == INVALID_SOCKET) return -1;
15841 mgos_lock();
15842 while (cs->rx_chain != NULL && len > 0) {
15843 struct pbuf *seg = cs->rx_chain;
15844 size_t seg_len = (seg->len - cs->rx_offset);
15845 size_t copy_len = MIN(len, seg_len);
15846
15847 pbuf_copy_partial(seg, bufp, copy_len, cs->rx_offset);
15848 len -= copy_len;
15849 res += copy_len;
15850 bufp += copy_len;
15851 cs->rx_offset += copy_len;
15852 if (cs->rx_offset == cs->rx_chain->len) {
15853 cs->rx_chain = pbuf_dechain(cs->rx_chain);
15854 pbuf_free(seg);
15855 cs->rx_offset = 0;
15856 }
15857 }
15858 mgos_unlock();
15859 if (res > 0) {
15860 struct tcp_recved_ctx ctx = {.tpcb = cs->pcb.tcp, .len = res};
15861 mg_lwip_netif_run_on_tcpip(tcp_recved_tcpip, &ctx);
15862 }
15863 return res;
15864 }
15865
15866 int mg_lwip_if_create_conn(struct mg_connection *nc) {
15867 struct mg_lwip_conn_state *cs =
15868 (struct mg_lwip_conn_state *) MG_CALLOC(1, sizeof(*cs));
15869 if (cs == NULL) return 0;
15870 cs->nc = nc;
15871 nc->sock = (intptr_t) cs;
15872 return 1;
15873 }
15874
15875 static void udp_remove_tcpip(void *arg) {
15876 udp_remove((struct udp_pcb *) arg);
15877 }
15878
15879 void mg_lwip_if_destroy_conn(struct mg_connection *nc) {
15880 if (nc->sock == INVALID_SOCKET) return;
15881 struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
15882 if (!(nc->flags & MG_F_UDP)) {
15883 struct tcp_pcb *tpcb = cs->pcb.tcp;
15884 if (tpcb != NULL) {
15885 tcp_arg(tpcb, NULL);
15886 DBG(("%p tcp_close %p", nc, tpcb));
15887 tcp_arg(tpcb, NULL);
15888 mg_lwip_netif_run_on_tcpip(tcp_close_tcpip, tpcb);
15889 }
15890 while (cs->rx_chain != NULL) {
15891 struct pbuf *seg = cs->rx_chain;
15892 cs->rx_chain = pbuf_dechain(cs->rx_chain);
15893 pbuf_free(seg);
15894 }
15895 memset(cs, 0, sizeof(*cs));
15896 MG_FREE(cs);
15897 } else if (nc->listener == NULL) {
15898 /* Only close outgoing UDP pcb or listeners. */
15899 struct udp_pcb *upcb = cs->pcb.udp;
15900 if (upcb != NULL) {
15901 DBG(("%p udp_remove %p", nc, upcb));
15902 mg_lwip_netif_run_on_tcpip(udp_remove_tcpip, upcb);
15903 }
15904 memset(cs, 0, sizeof(*cs));
15905 MG_FREE(cs);
15906 }
15907 nc->sock = INVALID_SOCKET;
15908 }
15909
15910 void mg_lwip_if_get_conn_addr(struct mg_connection *nc, int remote,
15911 union socket_address *sa) {
15912 memset(sa, 0, sizeof(*sa));
15913 if (nc == NULL || nc->sock == INVALID_SOCKET) return;
15914 struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
15915 if (nc->flags & MG_F_UDP) {
15916 struct udp_pcb *upcb = cs->pcb.udp;
15917 if (remote) {
15918 memcpy(sa, &nc->sa, sizeof(*sa));
15919 } else if (upcb != NULL) {
15920 sa->sin.sin_port = htons(upcb->local_port);
15921 SET_ADDR(sa, &upcb->local_ip);
15922 }
15923 } else {
15924 struct tcp_pcb *tpcb = cs->pcb.tcp;
15925 if (remote) {
15926 memcpy(sa, &nc->sa, sizeof(*sa));
15927 } else if (tpcb != NULL) {
15928 sa->sin.sin_port = htons(tpcb->local_port);
15929 SET_ADDR(sa, &tpcb->local_ip);
15930 }
15931 }
15932 }
15933
15934 void mg_lwip_if_sock_set(struct mg_connection *nc, sock_t sock) {
15935 nc->sock = sock;
15936 }
15937
15938 /* clang-format off */
15939 #define MG_LWIP_IFACE_VTABLE \
15940 { \
15941 mg_lwip_if_init, \
15942 mg_lwip_if_free, \
15943 mg_lwip_if_add_conn, \
15944 mg_lwip_if_remove_conn, \
15945 mg_lwip_if_poll, \
15946 mg_lwip_if_listen_tcp, \
15947 mg_lwip_if_listen_udp, \
15948 mg_lwip_if_connect_tcp, \
15949 mg_lwip_if_connect_udp, \
15950 mg_lwip_if_tcp_send, \
15951 mg_lwip_if_udp_send, \
15952 mg_lwip_if_tcp_recv, \
15953 mg_lwip_if_udp_recv, \
15954 mg_lwip_if_create_conn, \
15955 mg_lwip_if_destroy_conn, \
15956 mg_lwip_if_sock_set, \
15957 mg_lwip_if_get_conn_addr, \
15958 }
15959 /* clang-format on */
15960
15961 const struct mg_iface_vtable mg_lwip_iface_vtable = MG_LWIP_IFACE_VTABLE;
15962 #if MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL
15963 const struct mg_iface_vtable mg_default_iface_vtable = MG_LWIP_IFACE_VTABLE;
15964 #endif
15965
15966 #endif /* MG_ENABLE_NET_IF_LWIP_LOW_LEVEL */
15967 #ifdef MG_MODULE_LINES
15968 #line 1 "common/platforms/lwip/mg_lwip_ev_mgr.c"
15969 #endif
15970 /*
15971 * Copyright (c) 2014-2018 Cesanta Software Limited
15972 * All rights reserved
15973 *
15974 * Licensed under the Apache License, Version 2.0 (the ""License"");
15975 * you may not use this file except in compliance with the License.
15976 * You may obtain a copy of the License at
15977 *
15978 * http://www.apache.org/licenses/LICENSE-2.0
15979 *
15980 * Unless required by applicable law or agreed to in writing, software
15981 * distributed under the License is distributed on an ""AS IS"" BASIS,
15982 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15983 * See the License for the specific language governing permissions and
15984 * limitations under the License.
15985 */
15986
15987 #if MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL
15988
15989 #ifndef MG_SIG_QUEUE_LEN
15990 #define MG_SIG_QUEUE_LEN 32
15991 #endif
15992
15993 struct mg_ev_mgr_lwip_signal {
15994 int sig;
15995 struct mg_connection *nc;
15996 };
15997
15998 struct mg_ev_mgr_lwip_data {
15999 struct mg_ev_mgr_lwip_signal sig_queue[MG_SIG_QUEUE_LEN];
16000 int sig_queue_len;
16001 int start_index;
16002 };
16003
16004 void mg_lwip_post_signal(enum mg_sig_type sig, struct mg_connection *nc) {
16005 struct mg_ev_mgr_lwip_data *md =
16006 (struct mg_ev_mgr_lwip_data *) nc->iface->data;
16007 mgos_lock();
16008 if (md->sig_queue_len >= MG_SIG_QUEUE_LEN) {
16009 mgos_unlock();
16010 return;
16011 }
16012 int end_index = (md->start_index + md->sig_queue_len) % MG_SIG_QUEUE_LEN;
16013 md->sig_queue[end_index].sig = sig;
16014 md->sig_queue[end_index].nc = nc;
16015 md->sig_queue_len++;
16016 mg_lwip_mgr_schedule_poll(nc->mgr);
16017 mgos_unlock();
16018 }
16019
16020 void mg_ev_mgr_lwip_process_signals(struct mg_mgr *mgr) {
16021 struct mg_ev_mgr_lwip_data *md =
16022 (struct mg_ev_mgr_lwip_data *) mgr->ifaces[MG_MAIN_IFACE]->data;
16023 while (md->sig_queue_len > 0) {
16024 mgos_lock();
16025 int i = md->start_index;
16026 int sig = md->sig_queue[i].sig;
16027 struct mg_connection *nc = md->sig_queue[i].nc;
16028 struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
16029 md->start_index = (i + 1) % MG_SIG_QUEUE_LEN;
16030 md->sig_queue_len--;
16031 mgos_unlock();
16032 if (nc->iface == NULL || nc->mgr == NULL) continue;
16033 switch (sig) {
16034 case MG_SIG_CONNECT_RESULT: {
16035 mg_if_connect_cb(nc, cs->err);
16036 break;
16037 }
16038 case MG_SIG_CLOSE_CONN: {
16039 mg_close_conn(nc);
16040 break;
16041 }
16042 case MG_SIG_RECV: {
16043 cs->recv_pending = 0;
16044 mg_if_can_recv_cb(nc);
16045 mbuf_trim(&nc->recv_mbuf);
16046 break;
16047 }
16048 case MG_SIG_TOMBSTONE: {
16049 break;
16050 }
16051 case MG_SIG_ACCEPT: {
16052 mg_lwip_handle_accept(nc);
16053 break;
16054 }
16055 }
16056 }
16057 }
16058
16059 void mg_lwip_if_init(struct mg_iface *iface) {
16060 LOG(LL_INFO, ("Mongoose %s, LwIP %u.%u.%u", MG_VERSION, LWIP_VERSION_MAJOR,
16061 LWIP_VERSION_MINOR, LWIP_VERSION_REVISION));
16062 iface->data = MG_CALLOC(1, sizeof(struct mg_ev_mgr_lwip_data));
16063 #if !NO_SYS && !LWIP_TCPIP_CORE_LOCKING
16064 sys_sem_new(&s_tcpip_call_lock_sem, 1);
16065 sys_sem_new(&s_tcpip_call_sync_sem, 0);
16066 #endif
16067 }
16068
16069 void mg_lwip_if_free(struct mg_iface *iface) {
16070 MG_FREE(iface->data);
16071 iface->data = NULL;
16072 }
16073
16074 void mg_lwip_if_add_conn(struct mg_connection *nc) {
16075 (void) nc;
16076 }
16077
16078 void mg_lwip_if_remove_conn(struct mg_connection *nc) {
16079 struct mg_ev_mgr_lwip_data *md =
16080 (struct mg_ev_mgr_lwip_data *) nc->iface->data;
16081 /* Walk the queue and null-out further signals for this conn. */
16082 for (int i = 0; i < MG_SIG_QUEUE_LEN; i++) {
16083 if (md->sig_queue[i].nc == nc) {
16084 md->sig_queue[i].sig = MG_SIG_TOMBSTONE;
16085 }
16086 }
16087 }
16088
16089 time_t mg_lwip_if_poll(struct mg_iface *iface, int timeout_ms) {
16090 struct mg_mgr *mgr = iface->mgr;
16091 int n = 0;
16092 double now = mg_time();
16093 struct mg_connection *nc, *tmp;
16094 double min_timer = 0;
16095 int num_timers = 0;
16096 #if 0
16097 DBG(("begin poll @%u", (unsigned int) (now * 1000)));
16098 #endif
16099 mg_ev_mgr_lwip_process_signals(mgr);
16100 for (nc = mgr->active_connections; nc != NULL; nc = tmp) {
16101 struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
16102 tmp = nc->next;
16103 n++;
16104 if (!mg_if_poll(nc, now)) continue;
16105 if (nc->sock != INVALID_SOCKET &&
16106 !(nc->flags & (MG_F_UDP | MG_F_LISTENING)) && cs->pcb.tcp != NULL &&
16107 cs->pcb.tcp->unsent != NULL) {
16108 mg_lwip_netif_run_on_tcpip(tcp_output_tcpip, cs->pcb.tcp);
16109 }
16110 if (nc->ev_timer_time > 0) {
16111 if (num_timers == 0 || nc->ev_timer_time < min_timer) {
16112 min_timer = nc->ev_timer_time;
16113 }
16114 num_timers++;
16115 }
16116
16117 if (nc->sock != INVALID_SOCKET) {
16118 if (mg_lwip_if_can_send(nc, cs)) {
16119 mg_if_can_send_cb(nc);
16120 mbuf_trim(&nc->send_mbuf);
16121 }
16122 if (cs->rx_chain != NULL) {
16123 mg_if_can_recv_cb(nc);
16124 } else if (cs->draining_rx_chain) {
16125 /*
16126 * If the connection is about to close, and rx_chain is finally empty,
16127 * send the MG_SIG_CLOSE_CONN signal
16128 */
16129 mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc);
16130 }
16131 }
16132 }
16133 #if 0
16134 DBG(("end poll @%u, %d conns, %d timers (min %u), next in %d ms",
16135 (unsigned int) (now * 1000), n, num_timers,
16136 (unsigned int) (min_timer * 1000), timeout_ms));
16137 #endif
16138 (void) timeout_ms;
16139 return now;
16140 }
16141
16142 #endif /* MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL */
16143 #ifdef MG_MODULE_LINES
16144 #line 1 "common/platforms/wince/wince_libc.c"
16145 #endif
16146 /*
16147 * Copyright (c) 2014-2018 Cesanta Software Limited
16148 * All rights reserved
16149 *
16150 * Licensed under the Apache License, Version 2.0 (the ""License"");
16151 * you may not use this file except in compliance with the License.
16152 * You may obtain a copy of the License at
16153 *
16154 * http://www.apache.org/licenses/LICENSE-2.0
16155 *
16156 * Unless required by applicable law or agreed to in writing, software
16157 * distributed under the License is distributed on an ""AS IS"" BASIS,
16158 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16159 * See the License for the specific language governing permissions and
16160 * limitations under the License.
16161 */
16162
16163 #ifdef WINCE
16164
16165 const char *strerror(int err) {
16166 /*
16167 * TODO(alashkin): there is no strerror on WinCE;
16168 * look for similar wce_xxxx function
16169 */
16170 static char buf[10];
16171 snprintf(buf, sizeof(buf), "%d", err);
16172 return buf;
16173 }
16174
16175 int open(const char *filename, int oflag, int pmode) {
16176 /*
16177 * TODO(alashkin): mg_open function is not used in mongoose
16178 * but exists in documentation as utility function
16179 * Shall we delete it at all or implement for WinCE as well?
16180 */
16181 DebugBreak();
16182 return 0; /* for compiler */
16183 }
16184
16185 int _wstati64(const wchar_t *path, cs_stat_t *st) {
16186 DWORD fa = GetFileAttributesW(path);
16187 if (fa == INVALID_FILE_ATTRIBUTES) {
16188 return -1;
16189 }
16190 memset(st, 0, sizeof(*st));
16191 if ((fa & FILE_ATTRIBUTE_DIRECTORY) == 0) {
16192 HANDLE h;
16193 FILETIME ftime;
16194 st->st_mode |= _S_IFREG;
16195 h = CreateFileW(path, GENERIC_READ, 0, NULL, OPEN_EXISTING,
16196 FILE_ATTRIBUTE_NORMAL, NULL);
16197 if (h == INVALID_HANDLE_VALUE) {
16198 return -1;
16199 }
16200 st->st_size = GetFileSize(h, NULL);
16201 GetFileTime(h, NULL, NULL, &ftime);
16202 st->st_mtime = (uint32_t)((((uint64_t) ftime.dwLowDateTime +
16203 ((uint64_t) ftime.dwHighDateTime << 32)) /
16204 10000000.0) -
16205 11644473600);
16206 CloseHandle(h);
16207 } else {
16208 st->st_mode |= _S_IFDIR;
16209 }
16210 return 0;
16211 }
16212
16213 /* Windows CE doesn't have neither gmtime nor strftime */
16214 static void mg_gmt_time_string(char *buf, size_t buf_len, time_t *t) {
16215 FILETIME ft;
16216 SYSTEMTIME systime;
16217 if (t != NULL) {
16218 uint64_t filetime = (*t + 11644473600) * 10000000;
16219 ft.dwLowDateTime = filetime & 0xFFFFFFFF;
16220 ft.dwHighDateTime = (filetime & 0xFFFFFFFF00000000) >> 32;
16221 FileTimeToSystemTime(&ft, &systime);
16222 } else {
16223 GetSystemTime(&systime);
16224 }
16225 /* There is no PRIu16 in WinCE SDK */
16226 snprintf(buf, buf_len, "%d.%d.%d %d:%d:%d GMT", (int) systime.wYear,
16227 (int) systime.wMonth, (int) systime.wDay, (int) systime.wHour,
16228 (int) systime.wMinute, (int) systime.wSecond);
16229 }
16230
16231 #endif
16232 #ifdef MG_MODULE_LINES
16233 #line 1 "common/platforms/pic32/pic32_net_if.h"
16234 #endif
16235 /*
16236 * Copyright (c) 2014-2018 Cesanta Software Limited
16237 * All rights reserved
16238 *
16239 * Licensed under the Apache License, Version 2.0 (the ""License"");
16240 * you may not use this file except in compliance with the License.
16241 * You may obtain a copy of the License at
16242 *
16243 * http://www.apache.org/licenses/LICENSE-2.0
16244 *
16245 * Unless required by applicable law or agreed to in writing, software
16246 * distributed under the License is distributed on an ""AS IS"" BASIS,
16247 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16248 * See the License for the specific language governing permissions and
16249 * limitations under the License.
16250 */
16251
16252 #ifndef CS_COMMON_PLATFORMS_PIC32_NET_IF_H_
16253 #define CS_COMMON_PLATFORMS_PIC32_NET_IF_H_
16254
16255 /* Amalgamated: #include "mongoose/src/net_if.h" */
16256
16257 #ifdef __cplusplus
16258 extern "C" {
16259 #endif /* __cplusplus */
16260
16261 #ifndef MG_ENABLE_NET_IF_PIC32
16262 #define MG_ENABLE_NET_IF_PIC32 MG_NET_IF == MG_NET_IF_PIC32
16263 #endif
16264
16265 extern const struct mg_iface_vtable mg_pic32_iface_vtable;
16266
16267 #ifdef __cplusplus
16268 }
16269 #endif /* __cplusplus */
16270
16271 #endif /* CS_COMMON_PLATFORMS_PIC32_NET_IF_H_ */
16272 #ifdef MG_MODULE_LINES
16273 #line 1 "common/platforms/pic32/pic32_net_if.c"
16274 #endif
16275 /*
16276 * Copyright (c) 2014-2018 Cesanta Software Limited
16277 * All rights reserved
16278 *
16279 * Licensed under the Apache License, Version 2.0 (the ""License"");
16280 * you may not use this file except in compliance with the License.
16281 * You may obtain a copy of the License at
16282 *
16283 * http://www.apache.org/licenses/LICENSE-2.0
16284 *
16285 * Unless required by applicable law or agreed to in writing, software
16286 * distributed under the License is distributed on an ""AS IS"" BASIS,
16287 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16288 * See the License for the specific language governing permissions and
16289 * limitations under the License.
16290 */
16291
16292 #if MG_ENABLE_NET_IF_PIC32
16293
16294 int mg_pic32_if_create_conn(struct mg_connection *nc) {
16295 (void) nc;
16296 return 1;
16297 }
16298
16299 void mg_pic32_if_recved(struct mg_connection *nc, size_t len) {
16300 (void) nc;
16301 (void) len;
16302 }
16303
16304 void mg_pic32_if_add_conn(struct mg_connection *nc) {
16305 (void) nc;
16306 }
16307
16308 void mg_pic32_if_init(struct mg_iface *iface) {
16309 (void) iface;
16310 (void) mg_get_errno(); /* Shutup compiler */
16311 }
16312
16313 void mg_pic32_if_free(struct mg_iface *iface) {
16314 (void) iface;
16315 }
16316
16317 void mg_pic32_if_remove_conn(struct mg_connection *nc) {
16318 (void) nc;
16319 }
16320
16321 void mg_pic32_if_destroy_conn(struct mg_connection *nc) {
16322 if (nc->sock == INVALID_SOCKET) return;
16323 /* For UDP, only close outgoing sockets or listeners. */
16324 if (!(nc->flags & MG_F_UDP)) {
16325 /* Close TCP */
16326 TCPIP_TCP_Close((TCP_SOCKET) nc->sock);
16327 } else if (nc->listener == NULL) {
16328 /* Only close outgoing UDP or listeners. */
16329 TCPIP_UDP_Close((UDP_SOCKET) nc->sock);
16330 }
16331
16332 nc->sock = INVALID_SOCKET;
16333 }
16334
16335 int mg_pic32_if_listen_udp(struct mg_connection *nc, union socket_address *sa) {
16336 nc->sock = TCPIP_UDP_ServerOpen(
16337 sa->sin.sin_family == AF_INET ? IP_ADDRESS_TYPE_IPV4
16338 : IP_ADDRESS_TYPE_IPV6,
16339 ntohs(sa->sin.sin_port),
16340 sa->sin.sin_addr.s_addr == 0 ? 0 : (IP_MULTI_ADDRESS *) &sa->sin);
16341 if (nc->sock == INVALID_SOCKET) {
16342 return -1;
16343 }
16344 return 0;
16345 }
16346
16347 void mg_pic32_if_udp_send(struct mg_connection *nc, const void *buf,
16348 size_t len) {
16349 mbuf_append(&nc->send_mbuf, buf, len);
16350 }
16351
16352 void mg_pic32_if_tcp_send(struct mg_connection *nc, const void *buf,
16353 size_t len) {
16354 mbuf_append(&nc->send_mbuf, buf, len);
16355 }
16356
16357 int mg_pic32_if_listen_tcp(struct mg_connection *nc, union socket_address *sa) {
16358 nc->sock = TCPIP_TCP_ServerOpen(
16359 sa->sin.sin_family == AF_INET ? IP_ADDRESS_TYPE_IPV4
16360 : IP_ADDRESS_TYPE_IPV6,
16361 ntohs(sa->sin.sin_port),
16362 sa->sin.sin_addr.s_addr == 0 ? 0 : (IP_MULTI_ADDRESS *) &sa->sin);
16363 memcpy(&nc->sa, sa, sizeof(*sa));
16364 if (nc->sock == INVALID_SOCKET) {
16365 return -1;
16366 }
16367 return 0;
16368 }
16369
16370 static int mg_accept_conn(struct mg_connection *lc) {
16371 struct mg_connection *nc;
16372 TCP_SOCKET_INFO si;
16373 union socket_address sa;
16374
16375 nc = mg_if_accept_new_conn(lc);
16376
16377 if (nc == NULL) {
16378 return 0;
16379 }
16380
16381 nc->sock = lc->sock;
16382 nc->flags &= ~MG_F_LISTENING;
16383
16384 if (!TCPIP_TCP_SocketInfoGet((TCP_SOCKET) nc->sock, &si)) {
16385 return 0;
16386 }
16387
16388 if (si.addressType == IP_ADDRESS_TYPE_IPV4) {
16389 sa.sin.sin_family = AF_INET;
16390 sa.sin.sin_port = htons(si.remotePort);
16391 sa.sin.sin_addr.s_addr = si.remoteIPaddress.v4Add.Val;
16392 } else {
16393 /* TODO(alashkin): do something with _potential_ IPv6 */
16394 memset(&sa, 0, sizeof(sa));
16395 }
16396
16397 mg_if_accept_tcp_cb(nc, (union socket_address *) &sa, sizeof(sa));
16398
16399 return mg_pic32_if_listen_tcp(lc, &lc->sa) >= 0;
16400 }
16401
16402 char *inet_ntoa(struct in_addr in) {
16403 static char addr[17];
16404 snprintf(addr, sizeof(addr), "%d.%d.%d.%d", (int) in.S_un.S_un_b.s_b1,
16405 (int) in.S_un.S_un_b.s_b2, (int) in.S_un.S_un_b.s_b3,
16406 (int) in.S_un.S_un_b.s_b4);
16407 return addr;
16408 }
16409
16410 static void mg_handle_send(struct mg_connection *nc) {
16411 uint16_t bytes_written = 0;
16412 if (nc->flags & MG_F_UDP) {
16413 if (!TCPIP_UDP_RemoteBind(
16414 (UDP_SOCKET) nc->sock,
16415 nc->sa.sin.sin_family == AF_INET ? IP_ADDRESS_TYPE_IPV4
16416 : IP_ADDRESS_TYPE_IPV6,
16417 ntohs(nc->sa.sin.sin_port), (IP_MULTI_ADDRESS *) &nc->sa.sin)) {
16418 nc->flags |= MG_F_CLOSE_IMMEDIATELY;
16419 return;
16420 }
16421 bytes_written = TCPIP_UDP_TxPutIsReady((UDP_SOCKET) nc->sock, 0);
16422 if (bytes_written >= nc->send_mbuf.len) {
16423 if (TCPIP_UDP_ArrayPut((UDP_SOCKET) nc->sock,
16424 (uint8_t *) nc->send_mbuf.buf,
16425 nc->send_mbuf.len) != nc->send_mbuf.len) {
16426 nc->flags |= MG_F_CLOSE_IMMEDIATELY;
16427 bytes_written = 0;
16428 }
16429 }
16430 } else {
16431 bytes_written = TCPIP_TCP_FifoTxFreeGet((TCP_SOCKET) nc->sock);
16432 if (bytes_written != 0) {
16433 if (bytes_written > nc->send_mbuf.len) {
16434 bytes_written = nc->send_mbuf.len;
16435 }
16436 if (TCPIP_TCP_ArrayPut((TCP_SOCKET) nc->sock,
16437 (uint8_t *) nc->send_mbuf.buf,
16438 bytes_written) != bytes_written) {
16439 nc->flags |= MG_F_CLOSE_IMMEDIATELY;
16440 bytes_written = 0;
16441 }
16442 }
16443 }
16444
16445 mg_if_sent_cb(nc, bytes_written);
16446 }
16447
16448 static void mg_handle_recv(struct mg_connection *nc) {
16449 uint16_t bytes_read = 0;
16450 uint8_t *buf = NULL;
16451 if (nc->flags & MG_F_UDP) {
16452 bytes_read = TCPIP_UDP_GetIsReady((UDP_SOCKET) nc->sock);
16453 if (bytes_read != 0 &&
16454 (nc->recv_mbuf_limit == -1 ||
16455 nc->recv_mbuf.len + bytes_read < nc->recv_mbuf_limit)) {
16456 buf = (uint8_t *) MG_MALLOC(bytes_read);
16457 if (TCPIP_UDP_ArrayGet((UDP_SOCKET) nc->sock, buf, bytes_read) !=
16458 bytes_read) {
16459 nc->flags |= MG_F_CLOSE_IMMEDIATELY;
16460 bytes_read = 0;
16461 MG_FREE(buf);
16462 }
16463 }
16464 } else {
16465 bytes_read = TCPIP_TCP_GetIsReady((TCP_SOCKET) nc->sock);
16466 if (bytes_read != 0) {
16467 if (nc->recv_mbuf_limit != -1 &&
16468 nc->recv_mbuf_limit - nc->recv_mbuf.len > bytes_read) {
16469 bytes_read = nc->recv_mbuf_limit - nc->recv_mbuf.len;
16470 }
16471 buf = (uint8_t *) MG_MALLOC(bytes_read);
16472 if (TCPIP_TCP_ArrayGet((TCP_SOCKET) nc->sock, buf, bytes_read) !=
16473 bytes_read) {
16474 nc->flags |= MG_F_CLOSE_IMMEDIATELY;
16475 MG_FREE(buf);
16476 bytes_read = 0;
16477 }
16478 }
16479 }
16480
16481 if (bytes_read != 0) {
16482 mg_if_recv_tcp_cb(nc, buf, bytes_read, 1 /* own */);
16483 }
16484 }
16485
16486 time_t mg_pic32_if_poll(struct mg_iface *iface, int timeout_ms) {
16487 struct mg_mgr *mgr = iface->mgr;
16488 double now = mg_time();
16489 struct mg_connection *nc, *tmp;
16490
16491 for (nc = mgr->active_connections; nc != NULL; nc = tmp) {
16492 tmp = nc->next;
16493
16494 if (nc->flags & MG_F_CONNECTING) {
16495 /* processing connections */
16496 if (nc->flags & MG_F_UDP ||
16497 TCPIP_TCP_IsConnected((TCP_SOCKET) nc->sock)) {
16498 mg_if_connect_cb(nc, 0);
16499 }
16500 } else if (nc->flags & MG_F_LISTENING) {
16501 if (TCPIP_TCP_IsConnected((TCP_SOCKET) nc->sock)) {
16502 /* accept new connections */
16503 mg_accept_conn(nc);
16504 }
16505 } else {
16506 if (nc->send_mbuf.len != 0) {
16507 mg_handle_send(nc);
16508 }
16509
16510 if (nc->recv_mbuf_limit == -1 ||
16511 nc->recv_mbuf.len < nc->recv_mbuf_limit) {
16512 mg_handle_recv(nc);
16513 }
16514 }
16515 }
16516
16517 for (nc = mgr->active_connections; nc != NULL; nc = tmp) {
16518 tmp = nc->next;
16519 if ((nc->flags & MG_F_CLOSE_IMMEDIATELY) ||
16520 (nc->send_mbuf.len == 0 && (nc->flags & MG_F_SEND_AND_CLOSE))) {
16521 mg_close_conn(nc);
16522 }
16523 }
16524
16525 return now;
16526 }
16527
16528 void mg_pic32_if_sock_set(struct mg_connection *nc, sock_t sock) {
16529 nc->sock = sock;
16530 }
16531
16532 void mg_pic32_if_get_conn_addr(struct mg_connection *nc, int remote,
16533 union socket_address *sa) {
16534 /* TODO(alaskin): not implemented yet */
16535 }
16536
16537 void mg_pic32_if_connect_tcp(struct mg_connection *nc,
16538 const union socket_address *sa) {
16539 nc->sock = TCPIP_TCP_ClientOpen(
16540 sa->sin.sin_family == AF_INET ? IP_ADDRESS_TYPE_IPV4
16541 : IP_ADDRESS_TYPE_IPV6,
16542 ntohs(sa->sin.sin_port), (IP_MULTI_ADDRESS *) &sa->sin);
16543 nc->err = (nc->sock == INVALID_SOCKET) ? -1 : 0;
16544 }
16545
16546 void mg_pic32_if_connect_udp(struct mg_connection *nc) {
16547 nc->sock = TCPIP_UDP_ClientOpen(IP_ADDRESS_TYPE_ANY, 0, NULL);
16548 nc->err = (nc->sock == INVALID_SOCKET) ? -1 : 0;
16549 }
16550
16551 /* clang-format off */
16552 #define MG_PIC32_IFACE_VTABLE \
16553 { \
16554 mg_pic32_if_init, \
16555 mg_pic32_if_free, \
16556 mg_pic32_if_add_conn, \
16557 mg_pic32_if_remove_conn, \
16558 mg_pic32_if_poll, \
16559 mg_pic32_if_listen_tcp, \
16560 mg_pic32_if_listen_udp, \
16561 mg_pic32_if_connect_tcp, \
16562 mg_pic32_if_connect_udp, \
16563 mg_pic32_if_tcp_send, \
16564 mg_pic32_if_udp_send, \
16565 mg_pic32_if_recved, \
16566 mg_pic32_if_create_conn, \
16567 mg_pic32_if_destroy_conn, \
16568 mg_pic32_if_sock_set, \
16569 mg_pic32_if_get_conn_addr, \
16570 }
16571 /* clang-format on */
16572
16573 const struct mg_iface_vtable mg_pic32_iface_vtable = MG_PIC32_IFACE_VTABLE;
16574 #if MG_NET_IF == MG_NET_IF_PIC32
16575 const struct mg_iface_vtable mg_default_iface_vtable = MG_PIC32_IFACE_VTABLE;
16576 #endif
16577
16578 #endif /* MG_ENABLE_NET_IF_PIC32 */
16579 #ifdef MG_MODULE_LINES
16580 #line 1 "common/platforms/windows/windows_direct.c"
16581 #endif
16582 /*
16583 * Copyright (c) 2014-2018 Cesanta Software Limited
16584 * All rights reserved
16585 *
16586 * Licensed under the Apache License, Version 2.0 (the ""License"");
16587 * you may not use this file except in compliance with the License.
16588 * You may obtain a copy of the License at
16589 *
16590 * http://www.apache.org/licenses/LICENSE-2.0
16591 *
16592 * Unless required by applicable law or agreed to in writing, software
16593 * distributed under the License is distributed on an ""AS IS"" BASIS,
16594 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16595 * See the License for the specific language governing permissions and
16596 * limitations under the License.
16597 */
16598
16599 #ifdef _WIN32
16600
16601 int rmdir(const char *dirname) {
16602 return _rmdir(dirname);
16603 }
16604
16605 unsigned int sleep(unsigned int seconds) {
16606 Sleep(seconds * 1000);
16607 return 0;
16608 }
16609
16610 #endif /* _WIN32 */
16611