This repository has been archived by the owner on Apr 12, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mongoose.c
4646 lines (4202 loc) · 144 KB
/
mongoose.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2004-2013 Sergey Lyubka
// Copyright (c) 2013-2021 Cesanta Software Limited
// All rights reserved
//
// This software is dual-licensed: you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2 as
// published by the Free Software Foundation. For the terms of this
// license, see <http://www.gnu.org/licenses/>.
//
// You are free to use this software under the terms of the GNU General
// Public License, but WITHOUT ANY WARRANTY; without even the implied
// warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU General Public License for more details.
//
// Alternatively, you can license this software under a commercial
// license, as set out in <https://www.cesanta.com/license>.
#include "mongoose.h"
#ifdef MG_ENABLE_LINES
#line 1 "src/private.h"
#endif
void mg_connect_resolved(struct mg_connection*);
#if MG_ARCH == MG_ARCH_FREERTOS
static inline void* mg_calloc(int cnt, size_t size) {
void* p = pvPortMalloc(size);
if (p != NULL) memset(p, 0, size);
return p;
}
#define calloc(a, b) mg_calloc((a), (b))
#define malloc(a) pvPortMalloc(a)
#define free(a) vPortFree(a)
#endif
#ifdef MG_ENABLE_LINES
#line 1 "src/base64.c"
#endif
#include <string.h>
static int mg_b64idx(int c) {
if (c < 26) {
return c + 'A';
}
else if (c < 52) {
return c - 26 + 'a';
}
else if (c < 62) {
return c - 52 + '0';
}
else {
return c == 62 ? '+' : '/';
}
}
static int mg_b64rev(int c) {
if (c >= 'A' && c <= 'Z') {
return c - 'A';
}
else if (c >= 'a' && c <= 'z') {
return c + 26 - 'a';
}
else if (c >= '0' && c <= '9') {
return c + 52 - '0';
}
else if (c == '+') {
return 62;
}
else if (c == '/') {
return 63;
}
else if (c == '=') {
return 64;
}
else {
return -1;
}
}
int mg_base64_update(unsigned char ch, char* to, int n) {
unsigned char rem = (n & 3) % 3;
if (rem == 0) {
to[n] = mg_b64idx(ch >> 2);
to[++n] = (ch & 3) << 4;
}
else if (rem == 1) {
to[n] = mg_b64idx(to[n] | (ch >> 4));
to[++n] = (ch & 15) << 2;
}
else {
to[n] = mg_b64idx(to[n] | (ch >> 6));
to[++n] = mg_b64idx(ch & 63);
n++;
}
return n;
}
int mg_base64_final(char* to, int n) {
int saved = n;
// printf("---[%.*s]\n", n, to);
if (n & 3) n = mg_base64_update(0, to, n);
if ((saved & 3) == 2) n--;
// printf(" %d[%.*s]\n", n, n, to);
while (n & 3) to[n++] = '=';
to[n] = '\0';
return n;
}
int mg_base64_encode(const unsigned char* p, int n, char* to) {
int i, len = 0;
for (i = 0; i < n; i++) len = mg_base64_update(p[i], to, len);
len = mg_base64_final(to, len);
return len;
}
int mg_base64_decode(const char* src, int n, char* dst) {
const char* end = src + n;
int len = 0;
while (src + 3 < end) {
int a = mg_b64rev(src[0]), b = mg_b64rev(src[1]), c = mg_b64rev(src[2]),
d = mg_b64rev(src[3]);
if (a == 64 || a < 0 || b == 64 || b < 0 || c < 0 || d < 0) return 0;
dst[len++] = (a << 2) | (b >> 4);
if (src[2] != '=') {
dst[len++] = (b << 4) | (c >> 2);
if (src[3] != '=') dst[len++] = (c << 6) | d;
}
src += 4;
}
dst[len] = '\0';
return len;
}
#ifdef MG_ENABLE_LINES
#line 1 "src/dns.c"
#endif
struct dns_data {
struct dns_data* next;
struct mg_connection* c;
unsigned long expire;
uint16_t txnid;
};
static struct dns_data* s_reqs; // Active DNS requests
static void mg_sendnsreq(struct mg_connection*, struct mg_str*, int,
struct mg_dns*, bool);
static void mg_dns_free(struct dns_data* d) {
LIST_DELETE(struct dns_data, &s_reqs, d);
free(d);
}
void mg_resolve_cancel(struct mg_connection* c) {
struct dns_data* tmp, * d;
for (d = s_reqs; d != NULL; d = tmp) {
tmp = d->next;
if (d->c == c) mg_dns_free(d);
}
}
static size_t mg_dns_parse_name_depth(const uint8_t* s, size_t len, size_t ofs,
char* to, size_t tolen, int depth) {
size_t i = 0, j = 0;
if (tolen > 0) to[0] = '\0';
if (depth > 5) return 0;
while (ofs + i + 1 < len) {
size_t n = s[ofs + i];
if (n == 0) {
i++;
break;
}
if (n & 0xc0) {
size_t ptr = (((n & 0x3f) << 8) | s[ofs + i + 1]); // 12 is hdr len
if (ptr + 1 < len && (s[ptr] & 0xc0) == 0 &&
mg_dns_parse_name_depth(s, len, ptr, to, tolen, depth + 1) == 0)
return 0;
i += 2;
break;
}
if (ofs + i + n + 1 >= len) return 0;
if (j > 0) {
if (j < tolen) to[j] = '.';
j++;
}
if (j + n < tolen) memcpy(&to[j], &s[ofs + i + 1], n);
j += n;
i += n + 1;
if (j < tolen) to[j] = '\0'; // Zero-terminate this chunk
}
if (tolen > 0) to[tolen - 1] = '\0'; // Make sure make sure it is nul-term
return i;
}
size_t mg_dns_parse_name(const uint8_t* s, size_t n, size_t ofs, char* dst,
size_t dstlen) {
return mg_dns_parse_name_depth(s, n, ofs, dst, dstlen, 0);
}
size_t mg_dns_parse_rr(const uint8_t* buf, size_t len, size_t ofs,
bool is_question, struct mg_dns_rr* rr) {
const struct mg_dns_header* h = (struct mg_dns_header*)buf;
const uint8_t* s = buf + ofs, * e = &buf[len];
memset(rr, 0, sizeof(*rr));
if (len < sizeof(*h)) return 0; // Too small, headers dont fit
if (len > 512) return 0; // Too large, we don't expect that
if (s >= e) return 0; // Overflow
if ((rr->nlen = (uint16_t)mg_dns_parse_name(buf, len, ofs, NULL, 0)) == 0)
return 0;
s += rr->nlen + 4;
if (s > e) return 0;
rr->atype = ((uint16_t)s[-4] << 8) | s[-3];
rr->aclass = ((uint16_t)s[-2] << 8) | s[-1];
if (is_question) return rr->nlen + 4;
s += 6;
if (s > e) return 0;
rr->alen = ((uint16_t)s[-2] << 8) | s[-1];
if (s + rr->alen > e) return 0;
return rr->nlen + rr->alen + 10;
}
bool mg_dns_parse(const uint8_t* buf, size_t len, struct mg_dns_message* dm) {
const struct mg_dns_header* h = (struct mg_dns_header*)buf;
struct mg_dns_rr rr;
size_t i, n, ofs = sizeof(*h);
memset(dm, 0, sizeof(*dm));
if (len < sizeof(*h)) return 0; // Too small, headers dont fit
if (mg_ntohs(h->num_questions) > 1) return 0; // Sanity
if (mg_ntohs(h->num_answers) > 10) return 0; // Sanity
dm->txnid = mg_ntohs(h->txnid);
for (i = 0; i < mg_ntohs(h->num_questions); i++) {
if ((n = mg_dns_parse_rr(buf, len, ofs, true, &rr)) == 0) return false;
// LOG(LL_INFO, ("Q %zu %zu", ofs, n));
ofs += n;
}
for (i = 0; i < mg_ntohs(h->num_answers); i++) {
// LOG(LL_INFO, ("A -- %zu %zu %s", ofs, n, dm->name));
if ((n = mg_dns_parse_rr(buf, len, ofs, false, &rr)) == 0) return false;
mg_dns_parse_name(buf, len, ofs, dm->name, sizeof(dm->name));
ofs += n;
if (rr.alen == 4 && rr.atype == 1 && rr.aclass == 1) {
dm->addr.is_ip6 = false;
memcpy(&dm->addr.ip, &buf[ofs - 4], 4);
dm->resolved = true;
break; // Return success
}
else if (rr.alen == 16 && rr.atype == 28 && rr.aclass == 1) {
dm->addr.is_ip6 = true;
memcpy(&dm->addr.ip6, &buf[ofs - 16], 16);
dm->resolved = true;
break; // Return success
}
}
return true;
}
static void dns_cb(struct mg_connection* c, int ev, void* ev_data,
void* fn_data) {
struct dns_data* d, * tmp;
if (ev == MG_EV_POLL) {
unsigned long now = *(unsigned long*)ev_data;
for (d = s_reqs; d != NULL; d = tmp) {
tmp = d->next;
// LOG(LL_DEBUG, ("%lu %lu dns poll", d->expire, now));
if (now > d->expire) mg_error(d->c, "DNS timeout");
}
}
else if (ev == MG_EV_READ) {
struct mg_dns_message dm;
int resolved = 0;
if (mg_dns_parse(c->recv.buf, c->recv.len, &dm) == false) {
char* s = mg_hexdump(c->recv.buf, c->recv.len);
LOG(LL_ERROR, ("Unexpected DNS response:\n%s\n", s));
free(s);
}
else {
LOG(LL_VERBOSE_DEBUG, ("%s %d", dm.name, dm.resolved));
for (d = s_reqs; d != NULL; d = tmp) {
tmp = d->next;
// LOG(LL_INFO, ("d %p %hu %hu", d, d->txnid, dm.txnid));
if (dm.txnid != d->txnid) continue;
if (d->c->is_resolving) {
d->c->is_resolving = 0;
if (dm.resolved) {
#if MG_ENABLE_LOG
char buf[100];
#endif
dm.addr.port = d->c->peer.port; // Save port
d->c->peer = dm.addr; // Copy resolved address
LOG(LL_DEBUG, ("%lu %s resolved to %s", d->c->id, dm.name,
mg_ntoa(&d->c->peer, buf, sizeof(buf))));
mg_connect_resolved(d->c);
#if MG_ENABLE_IPV6
}
else if (dm.addr.is_ip6 == false && dm.name[0] != '\0') {
struct mg_str x = mg_str(dm.name);
mg_sendnsreq(d->c, &x, c->mgr->dnstimeout, &c->mgr->dns6, true);
#endif
}
else {
mg_error(d->c, "%s DNS lookup failed", dm.name);
}
}
else {
LOG(LL_ERROR, ("%lu already resolved", d->c->id));
}
mg_dns_free(d);
resolved = 1;
}
}
if (!resolved) LOG(LL_ERROR, ("stray DNS reply"));
c->recv.len = 0;
}
else if (ev == MG_EV_CLOSE) {
for (d = s_reqs; d != NULL; d = tmp) {
tmp = d->next;
mg_dns_free(d);
}
}
(void)fn_data;
}
void mg_dns_send(struct mg_connection* c, const struct mg_str* name,
uint16_t txnid, bool ipv6) {
struct {
struct mg_dns_header header;
uint8_t data[256];
} pkt;
size_t i, n;
memset(&pkt, 0, sizeof(pkt));
pkt.header.txnid = mg_htons(txnid);
pkt.header.flags = mg_htons(0x100);
pkt.header.num_questions = mg_htons(1);
for (i = n = 0; i < sizeof(pkt.data) - 5; i++) {
if (name->ptr[i] == '.' || i >= name->len) {
pkt.data[n] = (uint8_t)(i - n);
memcpy(&pkt.data[n + 1], name->ptr + n, i - n);
n = i + 1;
}
if (i >= name->len) break;
}
memcpy(&pkt.data[n], "\x00\x00\x01\x00\x01", 5); // A query
n += 5;
if (ipv6) pkt.data[n - 3] = 0x1c; // AAAA query
// memcpy(&pkt.data[n], "\xc0\x0c\x00\x1c\x00\x01", 6); // AAAA query
// n += 6;
mg_send(c, &pkt, sizeof(pkt.header) + n);
#if 0
// Immediately after A query, send AAAA query. Whatever reply comes first,
// we'll use it. Note: we cannot send two queries in a single packet.
// https://stackoverflow.com/questions/4082081/requesting-a-and-aaaa-records-in-single-dns-query
pkt.data[n - 3] = 0x1c; // AAAA query
mg_send(c, &pkt, sizeof(pkt.header) + n);
#endif
}
static void mg_sendnsreq(struct mg_connection* c, struct mg_str* name, int ms,
struct mg_dns* dnsc, bool ipv6) {
struct dns_data* d = NULL;
if (dnsc->url == NULL) {
mg_error(c, "DNS server URL is NULL. Call mg_mgr_init()");
}
else if (dnsc->c == NULL) {
dnsc->c = mg_connect(c->mgr, dnsc->url, NULL, NULL);
if (dnsc->c != NULL) {
dnsc->c->pfn = dns_cb;
snprintf(dnsc->c->label, sizeof(dnsc->c->label), "%s", "DNS");
// dnsc->c->is_hexdumping = 1;
}
}
if (dnsc->c == NULL) {
mg_error(c, "resolver");
}
else if ((d = (struct dns_data*)calloc(1, sizeof(*d))) == NULL) {
mg_error(c, "resolve OOM");
}
else {
d->txnid = s_reqs ? s_reqs->txnid + 1 : 1;
d->next = s_reqs;
s_reqs = d;
d->expire = mg_millis() + ms;
d->c = c;
c->is_resolving = 1;
LOG(LL_VERBOSE_DEBUG, ("%lu resolving %.*s, txnid %hu", c->id,
(int)name->len, name->ptr, d->txnid));
mg_dns_send(dnsc->c, name, d->txnid, ipv6);
}
}
void mg_resolve(struct mg_connection* c, struct mg_str* name, int ms) {
if (mg_aton(*name, &c->peer)) {
// name is an IP address, do not fire name resolution
mg_connect_resolved(c);
}
else {
// name is not an IP, send DNS resolution request
mg_sendnsreq(c, name, ms, &c->mgr->dns4, false);
}
}
#ifdef MG_ENABLE_LINES
#line 1 "src/event.c"
#endif
void mg_call(struct mg_connection* c, int ev, void* ev_data) {
if (c->pfn != NULL) c->pfn(c, ev, ev_data, c->pfn_data);
if (c->fn != NULL) c->fn(c, ev, ev_data, c->fn_data);
}
void mg_error(struct mg_connection* c, const char* fmt, ...) {
char mem[256], * buf = mem;
va_list ap;
va_start(ap, fmt);
mg_vasprintf(&buf, sizeof(mem), fmt, ap);
va_end(ap);
LOG(LL_ERROR, ("%lu %s", c->id, buf));
mg_call(c, MG_EV_ERROR, buf);
if (buf != mem) free(buf);
c->is_closing = 1;
}
#ifdef MG_ENABLE_LINES
#line 1 "src/http.c"
#endif
// Multipart POST example:
// --xyz
// Content-Disposition: form-data; name="val"
//
// abcdef
// --xyz
// Content-Disposition: form-data; name="foo"; filename="a.txt"
// Content-Type: text/plain
//
// hello world
//
// --xyz--
size_t mg_http_next_multipart(struct mg_str body, size_t ofs,
struct mg_http_part* part) {
struct mg_str cd = mg_str_n("Content-Disposition", 19);
const char* s = body.ptr;
size_t b = ofs, h1, h2, b1, b2, max = body.len;
// Init part params
if (part != NULL) part->name = part->filename = part->body = mg_str_n(0, 0);
// Skip boundary
while (b + 2 < max && s[b] != '\r' && s[b + 1] != '\n') b++;
if (b <= ofs || b + 2 >= max) return 0;
// LOG(LL_INFO, ("B: %zu %zu [%.*s]", ofs, b - ofs, (int) (b - ofs), s));
// Skip headers
h1 = h2 = b + 2;
for (;;) {
while (h2 + 2 < max && s[h2] != '\r' && s[h2 + 1] != '\n') h2++;
if (h2 == h1) break;
if (h2 + 2 >= max) return 0;
// LOG(LL_INFO, ("Header: [%.*s]", (int) (h2 - h1), &s[h1]));
if (part != NULL && h1 + cd.len + 2 < h2 && s[h1 + cd.len] == ':' &&
mg_ncasecmp(&s[h1], cd.ptr, cd.len) == 0) {
struct mg_str v = mg_str_n(&s[h1 + cd.len + 2], h2 - (h1 + cd.len + 2));
part->name = mg_http_get_header_var(v, mg_str_n("name", 4));
part->filename = mg_http_get_header_var(v, mg_str_n("filename", 8));
}
h1 = h2 = h2 + 2;
}
b1 = b2 = h2 + 2;
while (b2 + 2 + (b - ofs) + 2 < max && !(s[b2] == '\r' && s[b2 + 1] == '\n' &&
memcmp(&s[b2 + 2], s, b - ofs) == 0))
b2++;
if (b2 + 2 >= max) return 0;
if (part != NULL) part->body = mg_str_n(&s[b1], b2 - b1);
// LOG(LL_INFO, ("Body: [%.*s]", (int) (b2 - b1), &s[b1]));
return b2 + 2;
}
void mg_http_bauth(struct mg_connection* c, const char* user,
const char* pass) {
struct mg_str u = mg_str(user), p = mg_str(pass);
size_t need = c->send.len + 36 + (u.len + p.len) * 2;
if (c->send.size < need) mg_iobuf_resize(&c->send, need);
if (c->send.size >= need) {
size_t i, n = 0;
char* buf = (char*)&c->send.buf[c->send.len + 21];
memcpy(&buf[-21], "Authorization: Basic ", 21); // DON'T use mg_send!
for (i = 0; i < u.len; i++) n = mg_base64_update(u.ptr[i], buf, n);
if (p.len > 0) {
n = mg_base64_update(':', buf, n);
for (i = 0; i < p.len; i++) n = mg_base64_update(p.ptr[i], buf, n);
}
n = mg_base64_final(buf, n);
c->send.len += 21 + n + 2;
memcpy(&c->send.buf[c->send.len - 2], "\r\n", 2);
}
else {
LOG(LL_ERROR, ("%lu %s cannot resize iobuf %d->%d ", c->id, c->label,
(int)c->send.size, (int)need));
}
}
int mg_http_get_var(const struct mg_str* buf, const char* name, char* dst,
int dst_len) {
const char* p, * e, * s;
size_t name_len;
int len;
if (dst == NULL || dst_len == 0) {
len = -2; // Bad destination
}
else if (buf->ptr == NULL || name == NULL || buf->len == 0) {
len = -1; // Bad source
dst[0] = '\0';
}
else {
name_len = strlen(name);
e = buf->ptr + buf->len;
len = -4; // Name does not exist
dst[0] = '\0';
for (p = buf->ptr; p + name_len < e; p++) {
if ((p == buf->ptr || p[-1] == '&') && p[name_len] == '=' &&
!mg_ncasecmp(name, p, name_len)) {
p += name_len + 1;
s = (const char*)memchr(p, '&', (size_t)(e - p));
if (s == NULL) s = e;
len = mg_url_decode(p, (size_t)(s - p), dst, dst_len, 1);
if (len < 0) len = -3; // Failed to decode
break;
}
}
}
return len;
}
int mg_url_decode(const char* src, size_t src_len, char* dst, size_t dst_len,
int is_form_url_encoded) {
size_t i, j;
for (i = j = 0; i < src_len && j + 1 < dst_len; i++, j++) {
if (src[i] == '%') {
// Use `i + 2 < src_len`, not `i < src_len - 2`, note small src_len
if (i + 2 < src_len && isxdigit(*(const unsigned char*)(src + i + 1)) &&
isxdigit(*(const unsigned char*)(src + i + 2))) {
mg_unhex(src + i + 1, 2, (uint8_t*)&dst[j]);
i += 2;
}
else {
return -1;
}
}
else if (is_form_url_encoded && src[i] == '+') {
dst[j] = ' ';
}
else {
dst[j] = src[i];
}
}
if (j < dst_len) dst[j] = '\0'; // Null-terminate the destination
return i >= src_len && j < dst_len ? (int)j : -1;
}
int mg_http_get_request_len(const unsigned char* buf, size_t buf_len) {
size_t i;
for (i = 0; i < buf_len; i++) {
if (!isprint(buf[i]) && buf[i] != '\r' && buf[i] != '\n' && buf[i] < 128)
return -1;
if ((i > 0 && buf[i] == '\n' && buf[i - 1] == '\n') ||
(i > 3 && buf[i] == '\n' && buf[i - 1] == '\r' && buf[i - 2] == '\n'))
return (int)i + 1;
}
return 0;
}
static const char* skip(const char* s, const char* e, const char* d,
struct mg_str* v) {
v->ptr = s;
while (s < e && *s != '\n' && strchr(d, *s) == NULL) s++;
v->len = s - v->ptr;
while (s < e && strchr(d, *s) != NULL) s++;
return s;
}
struct mg_str* mg_http_get_header(struct mg_http_message* h, const char* name) {
size_t i, n = strlen(name), max = sizeof(h->headers) / sizeof(h->headers[0]);
for (i = 0; i < max && h->headers[i].name.len > 0; i++) {
struct mg_str* k = &h->headers[i].name, * v = &h->headers[i].value;
if (n == k->len && mg_ncasecmp(k->ptr, name, n) == 0) return v;
}
return NULL;
}
void mg_http_parse_headers(const char* s, const char* end,
struct mg_http_header* h, int max_headers) {
int i;
for (i = 0; i < max_headers; i++) {
struct mg_str k, v, tmp;
const char* he = skip(s, end, "\n", &tmp);
s = skip(s, he, ": \r\n", &k);
s = skip(s, he, "\r\n", &v);
if (k.len == tmp.len) continue;
while (v.len > 0 && v.ptr[v.len - 1] == ' ') v.len--; // Trim spaces
if (k.len == 0) break;
// LOG(LL_INFO, ("--HH [%.*s] [%.*s] [%.*s]", (int) tmp.len - 1, tmp.ptr,
//(int) k.len, k.ptr, (int) v.len, v.ptr));
h[i].name = k;
h[i].value = v;
}
}
int mg_http_parse(const char* s, size_t len, struct mg_http_message* hm) {
int is_response, req_len = mg_http_get_request_len((unsigned char*)s, len);
const char* end = s + req_len, * qs;
struct mg_str* cl;
memset(hm, 0, sizeof(*hm));
if (req_len <= 0) return req_len;
hm->message.ptr = hm->head.ptr = s;
hm->body.ptr = end;
hm->head.len = req_len;
hm->chunk.ptr = end;
hm->message.len = hm->body.len = (size_t)~0; // Set body length to infinite
// Parse request line
s = skip(s, end, " ", &hm->method);
s = skip(s, end, " ", &hm->uri);
s = skip(s, end, "\r\n", &hm->proto);
// Sanity check
if (hm->method.len == 0 || hm->uri.len == 0 || hm->proto.len == 0) return -1;
// If URI contains '?' character, setup query string
if ((qs = (const char*)memchr(hm->uri.ptr, '?', hm->uri.len)) != NULL) {
hm->query.ptr = qs + 1;
hm->query.len = &hm->uri.ptr[hm->uri.len] - (qs + 1);
hm->uri.len = qs - hm->uri.ptr;
}
mg_http_parse_headers(s, end, hm->headers,
sizeof(hm->headers) / sizeof(hm->headers[0]));
if ((cl = mg_http_get_header(hm, "Content-Length")) != NULL) {
hm->body.len = (size_t)mg_to64(*cl);
hm->message.len = req_len + hm->body.len;
}
// mg_http_parse() is used to parse both HTTP requests and HTTP
// responses. If HTTP response does not have Content-Length set, then
// body is read until socket is closed, i.e. body.len is infinite (~0).
//
// For HTTP requests though, according to
// http://tools.ietf.org/html/rfc7231#section-8.1.3,
// only POST and PUT methods have defined body semantics.
// Therefore, if Content-Length is not specified and methods are
// not one of PUT or POST, set body length to 0.
//
// So, if it is HTTP request, and Content-Length is not set,
// and method is not (PUT or POST) then reset body length to zero.
is_response = mg_ncasecmp(hm->method.ptr, "HTTP/", 5) == 0;
if (hm->body.len == (size_t)~0 && !is_response &&
mg_vcasecmp(&hm->method, "PUT") != 0 &&
mg_vcasecmp(&hm->method, "POST") != 0) {
hm->body.len = 0;
hm->message.len = req_len;
}
// The 204 (No content) responses also have 0 body length
if (hm->body.len == (size_t)~0 && is_response &&
mg_vcasecmp(&hm->uri, "204") == 0) {
hm->body.len = 0;
hm->message.len = req_len;
}
return req_len;
}
static void mg_http_vprintf_chunk(struct mg_connection* c, const char* fmt,
va_list ap) {
char mem[256], * buf = mem;
int len = mg_vasprintf(&buf, sizeof(mem), fmt, ap);
mg_printf(c, "%X\r\n", len);
mg_send(c, buf, len);
mg_send(c, "\r\n", 2);
if (buf != mem) free(buf);
}
void mg_http_printf_chunk(struct mg_connection* c, const char* fmt, ...) {
va_list ap;
va_start(ap, fmt);
mg_http_vprintf_chunk(c, fmt, ap);
va_end(ap);
}
void mg_http_write_chunk(struct mg_connection* c, const char* buf, size_t len) {
mg_printf(c, "%X\r\n", len);
mg_send(c, buf, len);
mg_send(c, "\r\n", 2);
}
void mg_http_reply(struct mg_connection* c, int code, const char* headers,
const char* fmt, ...) {
char mem[100], * buf = mem;
va_list ap;
int len;
va_start(ap, fmt);
len = mg_vasprintf(&buf, sizeof(mem), fmt, ap);
va_end(ap);
mg_printf(c, "HTTP/1.1 %d OK\r\n%sContent-Length: %d\r\n\r\n", code,
headers == NULL ? "" : headers, len);
mg_send(c, buf, len);
if (buf != mem) free(buf);
}
#if MG_ENABLE_FS
static void http_cb(struct mg_connection*, int, void*, void*);
static void restore_http_cb(struct mg_connection* c) {
if (c->pfn_data != NULL) fclose((FILE*)c->pfn_data);
c->pfn_data = NULL;
c->pfn = http_cb;
}
char* mg_http_etag(char* buf, size_t len, mg_stat_t* st) {
snprintf(buf, len, "\"%lx." MG_INT64_FMT "\"", (unsigned long)st->st_mtime,
(int64_t)st->st_size);
return buf;
}
int mg_http_upload(struct mg_connection* c, struct mg_http_message* hm,
const char* dir) {
char offset[40] = "", name[200] = "", path[256];
mg_http_get_var(&hm->query, "offset", offset, sizeof(offset));
mg_http_get_var(&hm->query, "name", name, sizeof(name));
if (name[0] == '\0') {
mg_http_reply(c, 400, "", "%s", "name required");
return -1;
}
else {
FILE* fp;
size_t oft = strtoul(offset, NULL, 0);
snprintf(path, sizeof(path), "%s%c%s", dir, MG_DIRSEP, name);
LOG(LL_DEBUG,
("%p %d bytes @ %d [%s]", c->fd, (int)hm->body.len, (int)oft, name));
if ((fp = mg_fopen(path, oft == 0 ? "wb" : "ab")) == NULL) {
mg_http_reply(c, 400, "", "fopen(%s): %d", name, errno);
return -2;
}
else {
fwrite(hm->body.ptr, 1, hm->body.len, fp);
fclose(fp);
mg_http_reply(c, 200, "", "");
return hm->body.len;
}
}
}
static void static_cb(struct mg_connection* c, int ev, void* ev_data,
void* fn_data) {
if (ev == MG_EV_WRITE || ev == MG_EV_POLL) {
FILE* fp = (FILE*)fn_data;
// Read to send IO buffer directly, avoid extra on-stack buffer
size_t n, max = 2 * MG_IO_SIZE;
if (c->send.size < max) mg_iobuf_resize(&c->send, max);
if (c->send.len >= c->send.size) return; // Rate limit
n = fread(c->send.buf + c->send.len, 1, c->send.size - c->send.len, fp);
if (n > 0) c->send.len += n;
if (c->send.len < c->send.size) restore_http_cb(c);
}
else if (ev == MG_EV_CLOSE) {
restore_http_cb(c);
}
(void)ev_data;
}
static const char* guess_content_type(const char* filename) {
size_t n = strlen(filename);
#define MIME_ENTRY(_ext, _type) \
{ _ext, sizeof(_ext) - 1, _type }
const struct {
const char* ext;
size_t ext_len;
const char* type;
} *t, types[] = {
MIME_ENTRY("html", "text/html; charset=utf-8"),
MIME_ENTRY("htm", "text/html; charset=utf-8"),
MIME_ENTRY("shtml", "text/html; charset=utf-8"),
MIME_ENTRY("css", "text/css"),
MIME_ENTRY("js", "text/javascript"),
MIME_ENTRY("mjs", "text/javascript"),
MIME_ENTRY("json", "application/json"),
MIME_ENTRY("ico", "image/x-icon"),
MIME_ENTRY("gif", "image/gif"),
MIME_ENTRY("jpg", "image/jpeg"),
MIME_ENTRY("jpeg", "image/jpeg"),
MIME_ENTRY("png", "image/png"),
MIME_ENTRY("svg", "image/svg+xml"),
MIME_ENTRY("txt", "text/plain; charset=utf-8"),
MIME_ENTRY("wav", "audio/wav"),
MIME_ENTRY("mp3", "audio/mpeg"),
MIME_ENTRY("mid", "audio/mid"),
MIME_ENTRY("ogg", "application/ogg"),
MIME_ENTRY("xml", "application/xml"),
MIME_ENTRY("ttf", "font/ttf"),
MIME_ENTRY("json", "application/json"),
MIME_ENTRY("xsl", "application/xml"),
MIME_ENTRY("doc", "application/msword"),
MIME_ENTRY("exe", "application/octet-stream"),
MIME_ENTRY("zip", "application/zip"),
MIME_ENTRY("xls", "application/excel"),
MIME_ENTRY("tgz", "application/tar-gz"),
MIME_ENTRY("tar", "application/tar"),
MIME_ENTRY("gz", "application/gzip"),
MIME_ENTRY("rar", "application/rar"),
MIME_ENTRY("rtf", "application/rtf"),
MIME_ENTRY("pdf", "application/pdf"),
MIME_ENTRY("mpg", "video/mpeg"),
MIME_ENTRY("webm", "video/webm"),
MIME_ENTRY("mpeg", "video/mpeg"),
MIME_ENTRY("mov", "video/quicktime"),
MIME_ENTRY("mp4", "video/mp4"),
MIME_ENTRY("avi", "video/x-msvideo"),
MIME_ENTRY("csv", "text/csv"),
MIME_ENTRY("bmp", "image/bmp"),
MIME_ENTRY("bin", "application/octet-stream"),
MIME_ENTRY("wasm", "application/wasm"),
{NULL, 0, NULL},
};
for (t = types; t->ext != NULL; t++) {
if (n < t->ext_len + 2) continue;
if (mg_ncasecmp(t->ext, &filename[n - t->ext_len], t->ext_len)) continue;
return t->type;
}
return "text/plain; charset=utf-8";
}
void mg_http_serve_file(struct mg_connection* c, struct mg_http_message* hm,
const char* path, const char* mime, const char* hdrs) {
struct mg_str* inm = mg_http_get_header(hm, "If-None-Match");
mg_stat_t st;
char etag[64];
FILE* fp = mg_fopen(path, "rb");
if (fp == NULL || mg_stat(path, &st) != 0 ||
mg_http_etag(etag, sizeof(etag), &st) != etag) {
LOG(LL_DEBUG,
("404 [%.*s] [%s] %p", (int)hm->uri.len, hm->uri.ptr, path, fp));
mg_http_reply(c, 404, "", "%s", "Not found\n");
if (fp != NULL) fclose(fp);
}
else if (inm != NULL && mg_vcasecmp(inm, etag) == 0) {
fclose(fp);
mg_printf(c, "HTTP/1.1 304 Not Modified\r\nContent-Length: 0\r\n\r\n");
}
else {
mg_printf(c,
"HTTP/1.1 200 OK\r\nContent-Type: %s\r\n"
"Etag: %s\r\nContent-Length: " MG_INT64_FMT "\r\n%s\r\n",
mime, etag, (int64_t)st.st_size, hdrs ? hdrs : "");
if (mg_vcasecmp(&hm->method, "HEAD") == 0) {
fclose(fp);
}
else {
c->pfn = static_cb;
c->pfn_data = fp;
}
}
}
#if MG_ARCH == MG_ARCH_ESP32 || MG_ARCH == MG_ARCH_ESP8266 || \
MG_ARCH == MG_ARCH_FREERTOS
char* realpath(const char* src, char* dst) {
int len = strlen(src);
if (len > MG_PATH_MAX - 1) len = MG_PATH_MAX - 1;
strncpy(dst, src, len);
dst[len] = '\0';
LOG(LL_DEBUG, ("[%s] -> [%s]", src, dst));
return dst;
}
#endif
// Allow user to override this function
bool mg_is_dir(const char* path) WEAK;
bool mg_is_dir(const char* path) {
#if MG_ARCH == MG_ARCH_FREERTOS
struct FF_STAT st;
return (ff_stat(path, &st) == 0) && (st.st_mode & FF_IFDIR);
#else
mg_stat_t st;
return mg_stat(path, &st) == 0 && S_ISDIR(st.st_mode);
#endif
}
#if MG_ENABLE_DIRECTORY_LISTING
#ifdef _WIN32
struct dirent {
char d_name[MAX_PATH];
};
typedef struct win32_dir {
HANDLE handle;
WIN32_FIND_DATAW info;
struct dirent result;
} DIR;
int gettimeofday(struct timeval* tv, void* tz) {
FILETIME ft;
unsigned __int64 tmpres = 0;
if (tv != NULL) {
GetSystemTimeAsFileTime(&ft);
tmpres |= ft.dwHighDateTime;
tmpres <<= 32;
tmpres |= ft.dwLowDateTime;
tmpres /= 10; // convert into microseconds
tmpres -= (int64_t)11644473600000000;
tv->tv_sec = (long)(tmpres / 1000000UL);
tv->tv_usec = (long)(tmpres % 1000000UL);
}
(void)tz;
return 0;
}
static int to_wchar(const char* path, wchar_t* wbuf, size_t wbuf_len) {
int ret;
char buf[MAX_PATH * 2], buf2[MAX_PATH * 2], * p;
strncpy(buf, path, sizeof(buf));
buf[sizeof(buf) - 1] = '\0';
// Trim trailing slashes. Leave backslash for paths like "X:\"
p = buf + strlen(buf) - 1;
while (p > buf && p[-1] != ':' && (p[0] == '\\' || p[0] == '/')) *p-- = '\0';
memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
ret = MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
// Convert back to Unicode. If doubly-converted string does not match the
// original, something is fishy, reject.
WideCharToMultiByte(CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2),
NULL, NULL);
if (strcmp(buf, buf2) != 0) {
wbuf[0] = L'\0';
ret = 0;
}
return ret;
}
DIR* opendir(const char* name) {
DIR* d = NULL;
wchar_t wpath[MAX_PATH];
DWORD attrs;
if (name == NULL) {
SetLastError(ERROR_BAD_ARGUMENTS);
}
else if ((d = (DIR*)malloc(sizeof(*d))) == NULL) {
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
}
else {
to_wchar(name, wpath, sizeof(wpath) / sizeof(wpath[0]));
attrs = GetFileAttributesW(wpath);
if (attrs != 0Xffffffff && (attrs & FILE_ATTRIBUTE_DIRECTORY)) {
(void)wcscat(wpath, L"\\*");
d->handle = FindFirstFileW(wpath, &d->info);
d->result.d_name[0] = '\0';
}
else {
free(d);
d = NULL;
}
}
return d;
}
int closedir(DIR* d) {
int result = 0;
if (d != NULL) {
if (d->handle != INVALID_HANDLE_VALUE)
result = FindClose(d->handle) ? 0 : -1;