forked from cesanta/mongoose
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmongoose.c
3704 lines (3212 loc) · 113 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 <[email protected]>
// Copyright (c) 2013-2014 Cesanta Software Limited
// All rights reserved
//
// This library is dual-licensed: you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2 as
// published by the Free Software Foundation. For the terms of this
// license, see <http://www.gnu.org/licenses/>.
//
// You are free to use this library under the terms of the GNU General
// Public License, but WITHOUT ANY WARRANTY; without even the implied
// warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU General Public License for more details.
//
// Alternatively, you can license this library under a commercial
// license, as set out in <http://cesanta.com/>.
// net_skeleton start
#include "net_skeleton.h"
// net_skeleton end
#include <ctype.h>
#ifdef _WIN32
#ifndef S_ISDIR
#define S_ISDIR(x) ((x) & _S_IFDIR)
#endif
#define sleep(x) Sleep((x) * 1000)
#define stat(x, y) mg_stat((x), (y))
#define fopen(x, y) mg_fopen((x), (y))
#define open(x, y) mg_open((x), (y))
#define lseek(x, y, z) _lseeki64((x), (y), (z))
#define mkdir(x, y) _mkdir(x)
#define to64(x) _atoi64(x)
#ifndef __func__
#define STRX(x) #x
#define STR(x) STRX(x)
#define __func__ __FILE__ ":" STR(__LINE__)
#endif
typedef struct _stati64 file_stat_t;
#else
#include <dirent.h>
#include <inttypes.h>
#include <pwd.h>
#define O_BINARY 0
#define INT64_FMT PRId64
typedef struct stat file_stat_t;
#endif
#include "mongoose.h"
#define MAX_REQUEST_SIZE 16384
#define IOBUF_SIZE 8192
#define MAX_PATH_SIZE 8192
#define LUA_SCRIPT_PATTERN "**.lp$"
#define DEFAULT_CGI_PATTERN "**.cgi$|**.pl$|**.php$"
#define CGI_ENVIRONMENT_SIZE 8192
#define MAX_CGI_ENVIR_VARS 64
#define ENV_EXPORT_TO_CGI "MONGOOSE_CGI"
#define PASSWORDS_FILE_NAME ".htpasswd"
#ifndef MONGOOSE_USE_WEBSOCKET_PING_INTERVAL
#define MONGOOSE_USE_WEBSOCKET_PING_INTERVAL 5
#endif
// Extra HTTP headers to send in every static file reply
#if !defined(MONGOOSE_USE_EXTRA_HTTP_HEADERS)
#define MONGOOSE_USE_EXTRA_HTTP_HEADERS ""
#endif
#ifndef MONGOOSE_POST_SIZE_LIMIT
#define MONGOOSE_POST_SIZE_LIMIT 0
#endif
#ifndef MONGOOSE_IDLE_TIMEOUT_SECONDS
#define MONGOOSE_IDLE_TIMEOUT_SECONDS 30
#endif
#ifdef MONGOOSE_NO_SOCKETPAIR
#define MONGOOSE_NO_CGI
#endif
#ifdef MONGOOSE_NO_FILESYSTEM
#define MONGOOSE_NO_AUTH
#define MONGOOSE_NO_CGI
#define MONGOOSE_NO_DAV
#define MONGOOSE_NO_DIRECTORY_LISTING
#define MONGOOSE_NO_LOGGING
#endif
struct vec {
const char *ptr;
int len;
};
// For directory listing and WevDAV support
struct dir_entry {
struct connection *conn;
char *file_name;
file_stat_t st;
};
// NOTE(lsm): this enum shoulds be in sync with the config_options.
enum {
ACCESS_CONTROL_LIST,
#ifndef MONGOOSE_NO_FILESYSTEM
ACCESS_LOG_FILE,
#ifndef MONGOOSE_NO_AUTH
AUTH_DOMAIN,
#endif
#ifndef MONGOOSE_NO_CGI
CGI_INTERPRETER,
CGI_PATTERN,
#endif
#ifndef MONGOOSE_NO_DAV
DAV_AUTH_FILE,
#endif
DOCUMENT_ROOT,
#ifndef MONGOOSE_NO_DIRECTORY_LISTING
ENABLE_DIRECTORY_LISTING,
#endif
#endif
EXTRA_MIME_TYPES,
#if !defined(MONGOOSE_NO_FILESYSTEM) && !defined(MONGOOSE_NO_AUTH)
GLOBAL_AUTH_FILE,
#endif
HIDE_FILES_PATTERN,
#ifndef MONGOOSE_NO_FILESYSTEM
INDEX_FILES,
#endif
LISTENING_PORT,
#ifndef _WIN32
RUN_AS_USER,
#endif
#ifdef NS_ENABLE_SSL
SSL_CERTIFICATE,
#endif
URL_REWRITES,
NUM_OPTIONS
};
static const char *static_config_options[] = {
"access_control_list", NULL,
#ifndef MONGOOSE_NO_FILESYSTEM
"access_log_file", NULL,
#ifndef MONGOOSE_NO_AUTH
"auth_domain", "mydomain.com",
#endif
#ifndef MONGOOSE_NO_CGI
"cgi_interpreter", NULL,
"cgi_pattern", DEFAULT_CGI_PATTERN,
#endif
#ifndef MONGOOSE_NO_DAV
"dav_auth_file", NULL,
#endif
"document_root", NULL,
#ifndef MONGOOSE_NO_DIRECTORY_LISTING
"enable_directory_listing", "yes",
#endif
#endif
"extra_mime_types", NULL,
#if !defined(MONGOOSE_NO_FILESYSTEM) && !defined(MONGOOSE_NO_AUTH)
"global_auth_file", NULL,
#endif
"hide_files_patterns", NULL,
#ifndef MONGOOSE_NO_FILESYSTEM
"index_files","index.html,index.htm,index.cgi,index.php,index.lp",
#endif
"listening_port", NULL,
#ifndef _WIN32
"run_as_user", NULL,
#endif
#ifdef NS_ENABLE_SSL
"ssl_certificate", NULL,
#endif
"url_rewrites", NULL,
NULL
};
struct mg_server {
struct ns_server ns_server;
union socket_address lsa; // Listening socket address
mg_handler_t request_handler;
mg_handler_t http_close_handler;
mg_handler_t error_handler;
mg_handler_t auth_handler;
char *config_options[NUM_OPTIONS];
char local_ip[48];
};
// Local endpoint representation
union endpoint {
int fd; // Opened regular local file
struct ns_connection *cgi_conn; // CGI socket
};
enum endpoint_type { EP_NONE, EP_FILE, EP_CGI, EP_USER, EP_PUT, EP_CLIENT };
#define MG_HEADERS_SENT NSF_USER_1
#define MG_LONG_RUNNING NSF_USER_2
#define MG_CGI_CONN NSF_USER_3
struct connection {
struct ns_connection *ns_conn;
struct mg_connection mg_conn;
struct mg_server *server;
union endpoint endpoint;
enum endpoint_type endpoint_type;
time_t birth_time;
char *path_info;
char *request;
int64_t num_bytes_sent; // Total number of bytes sent
int64_t cl; // Reply content length, for Range support
int request_len; // Request length, including last \r\n after last header
//int flags; // CONN_* flags: CONN_CLOSE, CONN_SPOOL_DONE, etc
mg_handler_t handler; // Callback for HTTP client
};
#define MG_CONN_2_CONN(c) ((struct connection *) ((char *) (c) - \
offsetof(struct connection, mg_conn)))
static void open_local_endpoint(struct connection *conn, int skip_user);
static void close_local_endpoint(struct connection *conn);
static const struct {
const char *extension;
size_t ext_len;
const char *mime_type;
} static_builtin_mime_types[] = {
{".html", 5, "text/html"},
{".htm", 4, "text/html"},
{".shtm", 5, "text/html"},
{".shtml", 6, "text/html"},
{".css", 4, "text/css"},
{".js", 3, "application/x-javascript"},
{".ico", 4, "image/x-icon"},
{".gif", 4, "image/gif"},
{".jpg", 4, "image/jpeg"},
{".jpeg", 5, "image/jpeg"},
{".png", 4, "image/png"},
{".svg", 4, "image/svg+xml"},
{".txt", 4, "text/plain"},
{".torrent", 8, "application/x-bittorrent"},
{".wav", 4, "audio/x-wav"},
{".mp3", 4, "audio/x-mp3"},
{".mid", 4, "audio/mid"},
{".m3u", 4, "audio/x-mpegurl"},
{".ogg", 4, "application/ogg"},
{".ram", 4, "audio/x-pn-realaudio"},
{".xml", 4, "text/xml"},
{".json", 5, "text/json"},
{".xslt", 5, "application/xml"},
{".xsl", 4, "application/xml"},
{".ra", 3, "audio/x-pn-realaudio"},
{".doc", 4, "application/msword"},
{".exe", 4, "application/octet-stream"},
{".zip", 4, "application/x-zip-compressed"},
{".xls", 4, "application/excel"},
{".tgz", 4, "application/x-tar-gz"},
{".tar", 4, "application/x-tar"},
{".gz", 3, "application/x-gunzip"},
{".arj", 4, "application/x-arj-compressed"},
{".rar", 4, "application/x-arj-compressed"},
{".rtf", 4, "application/rtf"},
{".pdf", 4, "application/pdf"},
{".swf", 4, "application/x-shockwave-flash"},
{".mpg", 4, "video/mpeg"},
{".webm", 5, "video/webm"},
{".mpeg", 5, "video/mpeg"},
{".mov", 4, "video/quicktime"},
{".mp4", 4, "video/mp4"},
{".m4v", 4, "video/x-m4v"},
{".asf", 4, "video/x-ms-asf"},
{".avi", 4, "video/x-msvideo"},
{".bmp", 4, "image/bmp"},
{".ttf", 4, "application/x-font-ttf"},
{NULL, 0, NULL}
};
#ifndef MONGOOSE_NO_THREADS
void *mg_start_thread(void *(*f)(void *), void *p) {
#ifdef _WIN32
return (void *) _beginthread((void (__cdecl *)(void *)) f, 0, p);
#else
pthread_t thread_id = (pthread_t) 0;
pthread_attr_t attr;
(void) pthread_attr_init(&attr);
(void) pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
#if MONGOOSE_USE_STACK_SIZE > 1
(void) pthread_attr_setstacksize(&attr, MONGOOSE_USE_STACK_SIZE);
#endif
pthread_create(&thread_id, &attr, f, p);
pthread_attr_destroy(&attr);
return (void *) thread_id;
#endif
}
#endif // MONGOOSE_NO_THREADS
#ifdef _WIN32
#ifndef MONGOOSE_NO_FILESYSTEM
// Encode 'path' which is assumed UTF-8 string, into UNICODE string.
// wbuf and wbuf_len is a target buffer and its length.
static void to_wchar(const char *path, wchar_t *wbuf, size_t wbuf_len) {
char buf[MAX_PATH_SIZE * 2], buf2[MAX_PATH_SIZE * 2], *p;
strncpy(buf, path, sizeof(buf));
buf[sizeof(buf) - 1] = '\0';
// Trim trailing slashes
p = buf + strlen(buf) - 1;
while (p > buf && p[0] == '\\' || p[0] == '/') *p-- = '\0';
//change_slashes_to_backslashes(buf);
// Convert to Unicode and back. If doubly-converted string does not
// match the original, something is fishy, reject.
memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int) wbuf_len);
WideCharToMultiByte(CP_UTF8, 0, wbuf, (int) wbuf_len, buf2, sizeof(buf2),
NULL, NULL);
if (strcmp(buf, buf2) != 0) {
wbuf[0] = L'\0';
}
}
static int mg_stat(const char *path, file_stat_t *st) {
wchar_t wpath[MAX_PATH_SIZE];
to_wchar(path, wpath, ARRAY_SIZE(wpath));
DBG(("[%ls] -> %d", wpath, _wstati64(wpath, st)));
return _wstati64(wpath, st);
}
static FILE *mg_fopen(const char *path, const char *mode) {
wchar_t wpath[MAX_PATH_SIZE], wmode[10];
to_wchar(path, wpath, ARRAY_SIZE(wpath));
to_wchar(mode, wmode, ARRAY_SIZE(wmode));
return _wfopen(wpath, wmode);
}
static int mg_open(const char *path, int flag) {
wchar_t wpath[MAX_PATH_SIZE];
to_wchar(path, wpath, ARRAY_SIZE(wpath));
return _wopen(wpath, flag);
}
#endif
#endif // MONGOOSE_NO_FILESYSTEM
// A helper function for traversing a comma separated list of values.
// It returns a list pointer shifted to the next value, or NULL if the end
// of the list found.
// Value is stored in val vector. If value has form "x=y", then eq_val
// vector is initialized to point to the "y" part, and val vector length
// is adjusted to point only to "x".
static const char *next_option(const char *list, struct vec *val,
struct vec *eq_val) {
if (list == NULL || *list == '\0') {
// End of the list
list = NULL;
} else {
val->ptr = list;
if ((list = strchr(val->ptr, ',')) != NULL) {
// Comma found. Store length and shift the list ptr
val->len = list - val->ptr;
list++;
} else {
// This value is the last one
list = val->ptr + strlen(val->ptr);
val->len = list - val->ptr;
}
if (eq_val != NULL) {
// Value has form "x=y", adjust pointers and lengths
// so that val points to "x", and eq_val points to "y".
eq_val->len = 0;
eq_val->ptr = (const char *) memchr(val->ptr, '=', val->len);
if (eq_val->ptr != NULL) {
eq_val->ptr++; // Skip over '=' character
eq_val->len = val->ptr + val->len - eq_val->ptr;
val->len = (eq_val->ptr - val->ptr) - 1;
}
}
}
return list;
}
// Like snprintf(), but never returns negative value, or a value
// that is larger than a supplied buffer.
static int mg_vsnprintf(char *buf, size_t buflen, const char *fmt, va_list ap) {
int n;
if (buflen < 1) return 0;
n = vsnprintf(buf, buflen, fmt, ap);
if (n < 0) {
n = 0;
} else if (n >= (int) buflen) {
n = (int) buflen - 1;
}
buf[n] = '\0';
return n;
}
static int mg_snprintf(char *buf, size_t buflen, const char *fmt, ...) {
va_list ap;
int n;
va_start(ap, fmt);
n = mg_vsnprintf(buf, buflen, fmt, ap);
va_end(ap);
return n;
}
// Check whether full request is buffered. Return:
// -1 if request is malformed
// 0 if request is not yet fully buffered
// >0 actual request length, including last \r\n\r\n
static int get_request_len(const char *s, int buf_len) {
const unsigned char *buf = (unsigned char *) s;
int i;
for (i = 0; i < buf_len; i++) {
// Control characters are not allowed but >=128 are.
// Abort scan as soon as one malformed character is found.
if (!isprint(buf[i]) && buf[i] != '\r' && buf[i] != '\n' && buf[i] < 128) {
return -1;
} else if (buf[i] == '\n' && i + 1 < buf_len && buf[i + 1] == '\n') {
return i + 2;
} else if (buf[i] == '\n' && i + 2 < buf_len && buf[i + 1] == '\r' &&
buf[i + 2] == '\n') {
return i + 3;
}
}
return 0;
}
// Skip the characters until one of the delimiters characters found.
// 0-terminate resulting word. Skip the rest of the delimiters if any.
// Advance pointer to buffer to the next word. Return found 0-terminated word.
static char *skip(char **buf, const char *delimiters) {
char *p, *begin_word, *end_word, *end_delimiters;
begin_word = *buf;
end_word = begin_word + strcspn(begin_word, delimiters);
end_delimiters = end_word + strspn(end_word, delimiters);
for (p = end_word; p < end_delimiters; p++) {
*p = '\0';
}
*buf = end_delimiters;
return begin_word;
}
// Parse HTTP headers from the given buffer, advance buffer to the point
// where parsing stopped.
static void parse_http_headers(char **buf, struct mg_connection *ri) {
size_t i;
for (i = 0; i < ARRAY_SIZE(ri->http_headers); i++) {
ri->http_headers[i].name = skip(buf, ": ");
ri->http_headers[i].value = skip(buf, "\r\n");
if (ri->http_headers[i].name[0] == '\0')
break;
ri->num_headers = i + 1;
}
}
static const char *status_code_to_str(int status_code) {
switch (status_code) {
case 200: return "OK";
case 201: return "Created";
case 204: return "No Content";
case 301: return "Moved Permanently";
case 302: return "Found";
case 304: return "Not Modified";
case 400: return "Bad Request";
case 403: return "Forbidden";
case 404: return "Not Found";
case 405: return "Method Not Allowed";
case 409: return "Conflict";
case 411: return "Length Required";
case 413: return "Request Entity Too Large";
case 415: return "Unsupported Media Type";
case 423: return "Locked";
case 500: return "Server Error";
case 501: return "Not Implemented";
default: return "Server Error";
}
}
static void send_http_error(struct connection *conn, int code,
const char *fmt, ...) {
const char *message = status_code_to_str(code);
const char *rewrites = conn->server->config_options[URL_REWRITES];
char headers[200], body[200];
struct vec a, b;
va_list ap;
int body_len, headers_len, match_code;
conn->mg_conn.status_code = code;
// Invoke error handler if it is set
if (conn->server->error_handler != NULL &&
conn->server->error_handler(&conn->mg_conn) == MG_ERROR_PROCESSED) {
close_local_endpoint(conn);
return;
}
// Handle error code rewrites
while ((rewrites = next_option(rewrites, &a, &b)) != NULL) {
if ((match_code = atoi(a.ptr)) > 0 && match_code == code) {
conn->mg_conn.status_code = 302;
mg_printf(&conn->mg_conn, "HTTP/1.1 %d Moved\r\n"
"Location: %.*s?code=%d&orig_uri=%s\r\n\r\n",
conn->mg_conn.status_code, b.len, b.ptr, code,
conn->mg_conn.uri);
close_local_endpoint(conn);
return;
}
}
body_len = mg_snprintf(body, sizeof(body), "%d %s\n", code, message);
if (fmt != NULL) {
va_start(ap, fmt);
body_len += mg_vsnprintf(body + body_len, sizeof(body) - body_len, fmt, ap);
va_end(ap);
}
if (code >= 300 && code <= 399) {
// 3xx errors do not have body
body_len = 0;
}
headers_len = mg_snprintf(headers, sizeof(headers),
"HTTP/1.1 %d %s\r\nContent-Length: %d\r\n"
"Content-Type: text/plain\r\n\r\n",
code, message, body_len);
ns_send(conn->ns_conn, headers, headers_len);
ns_send(conn->ns_conn, body, body_len);
close_local_endpoint(conn); // This will write to the log file
}
static void write_chunk(struct connection *conn, const char *buf, int len) {
char chunk_size[50];
int n = mg_snprintf(chunk_size, sizeof(chunk_size), "%X\r\n", len);
ns_send(conn->ns_conn, chunk_size, n);
ns_send(conn->ns_conn, buf, len);
ns_send(conn->ns_conn, "\r\n", 2);
}
int mg_printf(struct mg_connection *conn, const char *fmt, ...) {
struct connection *c = MG_CONN_2_CONN(conn);
int len;
va_list ap;
va_start(ap, fmt);
len = ns_vprintf(c->ns_conn, fmt, ap);
va_end(ap);
return len;
}
#ifndef MONGOOSE_NO_CGI
#ifdef _WIN32
struct threadparam {
sock_t s;
HANDLE hPipe;
};
static int wait_until_ready(sock_t sock, int for_read) {
fd_set set;
FD_ZERO(&set);
FD_SET(sock, &set);
select(sock + 1, for_read ? &set : 0, for_read ? 0 : &set, 0, 0);
return 1;
}
static void *push_to_stdin(void *arg) {
struct threadparam *tp = arg;
int n, sent, stop = 0;
DWORD k;
char buf[IOBUF_SIZE];
while (!stop && wait_until_ready(tp->s, 1) &&
(n = recv(tp->s, buf, sizeof(buf), 0)) > 0) {
if (n == -1 && GetLastError() == WSAEWOULDBLOCK) continue;
for (sent = 0; !stop && sent < n; sent += k) {
if (!WriteFile(tp->hPipe, buf + sent, n - sent, &k, 0)) stop = 1;
}
}
DBG(("%s", "FORWARED EVERYTHING TO CGI"));
CloseHandle(tp->hPipe);
free(tp);
_endthread();
return NULL;
}
static void *pull_from_stdout(void *arg) {
struct threadparam *tp = arg;
int k, stop = 0;
DWORD n, sent;
char buf[IOBUF_SIZE];
while (!stop && ReadFile(tp->hPipe, buf, sizeof(buf), &n, NULL)) {
for (sent = 0; !stop && sent < n; sent += k) {
if (wait_until_ready(tp->s, 0) &&
(k = send(tp->s, buf + sent, n - sent, 0)) <= 0) stop = 1;
}
}
DBG(("%s", "EOF FROM CGI"));
CloseHandle(tp->hPipe);
shutdown(tp->s, 2); // Without this, IO thread may get truncated data
closesocket(tp->s);
free(tp);
_endthread();
return NULL;
}
static void spawn_stdio_thread(sock_t sock, HANDLE hPipe,
void *(*func)(void *)) {
struct threadparam *tp = malloc(sizeof(*tp));
if (tp != NULL) {
tp->s = sock;
tp->hPipe = hPipe;
mg_start_thread(func, tp);
}
}
static void abs_path(const char *utf8_path, char *abs_path, size_t len) {
wchar_t buf[MAX_PATH_SIZE], buf2[MAX_PATH_SIZE];
to_wchar(utf8_path, buf, ARRAY_SIZE(buf));
GetFullPathNameW(buf, ARRAY_SIZE(buf2), buf2, NULL);
WideCharToMultiByte(CP_UTF8, 0, buf2, wcslen(buf2) + 1, abs_path, len, 0, 0);
}
static pid_t start_process(char *interp, const char *cmd, const char *env,
const char *envp[], const char *dir, sock_t sock) {
STARTUPINFOW si = {0};
PROCESS_INFORMATION pi = {0};
HANDLE a[2], b[2], me = GetCurrentProcess();
wchar_t wcmd[MAX_PATH_SIZE], full_dir[MAX_PATH_SIZE];
char buf[MAX_PATH_SIZE], buf4[MAX_PATH_SIZE], buf5[MAX_PATH_SIZE],
cmdline[MAX_PATH_SIZE], *p;
DWORD flags = DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS;
FILE *fp;
si.cb = sizeof(si);
si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
si.wShowWindow = SW_HIDE;
si.hStdError = GetStdHandle(STD_ERROR_HANDLE);
CreatePipe(&a[0], &a[1], NULL, 0);
CreatePipe(&b[0], &b[1], NULL, 0);
DuplicateHandle(me, a[0], me, &si.hStdInput, 0, TRUE, flags);
DuplicateHandle(me, b[1], me, &si.hStdOutput, 0, TRUE, flags);
if (interp == NULL && (fp = fopen(cmd, "r")) != NULL) {
buf[0] = buf[1] = '\0';
fgets(buf, sizeof(buf), fp);
buf[sizeof(buf) - 1] = '\0';
if (buf[0] == '#' && buf[1] == '!') {
interp = buf + 2;
for (p = interp + strlen(interp);
isspace(* (uint8_t *) p) && p > interp; p--) *p = '\0';
}
fclose(fp);
}
if (interp != NULL) {
abs_path(interp, buf4, ARRAY_SIZE(buf4));
interp = buf4;
}
abs_path(dir, buf5, ARRAY_SIZE(buf5));
to_wchar(dir, full_dir, ARRAY_SIZE(full_dir));
mg_snprintf(cmdline, sizeof(cmdline), "%s%s\"%s\"",
interp ? interp : "", interp ? " " : "", cmd);
to_wchar(cmdline, wcmd, ARRAY_SIZE(wcmd));
if (CreateProcessW(NULL, wcmd, NULL, NULL, TRUE, CREATE_NEW_PROCESS_GROUP,
(void *) env, full_dir, &si, &pi) != 0) {
spawn_stdio_thread(sock, a[1], push_to_stdin);
spawn_stdio_thread(sock, b[0], pull_from_stdout);
} else {
CloseHandle(a[1]);
CloseHandle(b[0]);
closesocket(sock);
}
DBG(("CGI command: [%ls] -> %p", wcmd, pi.hProcess));
CloseHandle(si.hStdOutput);
CloseHandle(si.hStdInput);
CloseHandle(a[0]);
CloseHandle(b[1]);
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
return pi.hProcess;
}
#else
static pid_t start_process(const char *interp, const char *cmd, const char *env,
const char *envp[], const char *dir, sock_t sock) {
char buf[500];
pid_t pid = fork();
(void) env;
if (pid == 0) {
(void) chdir(dir);
(void) dup2(sock, 0);
(void) dup2(sock, 1);
closesocket(sock);
// After exec, all signal handlers are restored to their default values,
// with one exception of SIGCHLD. According to POSIX.1-2001 and Linux's
// implementation, SIGCHLD's handler will leave unchanged after exec
// if it was set to be ignored. Restore it to default action.
signal(SIGCHLD, SIG_DFL);
if (interp == NULL) {
execle(cmd, cmd, NULL, envp);
} else {
execle(interp, interp, cmd, NULL, envp);
}
snprintf(buf, sizeof(buf), "Status: 500\r\n\r\n"
"500 Server Error: %s%s%s: %s", interp == NULL ? "" : interp,
interp == NULL ? "" : " ", cmd, strerror(errno));
send(1, buf, strlen(buf), 0);
exit(EXIT_FAILURE); // exec call failed
}
return pid;
}
#endif // _WIN32
// This structure helps to create an environment for the spawned CGI program.
// Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
// last element must be NULL.
// However, on Windows there is a requirement that all these VARIABLE=VALUE\0
// strings must reside in a contiguous buffer. The end of the buffer is
// marked by two '\0' characters.
// We satisfy both worlds: we create an envp array (which is vars), all
// entries are actually pointers inside buf.
struct cgi_env_block {
struct mg_connection *conn;
char buf[CGI_ENVIRONMENT_SIZE]; // Environment buffer
const char *vars[MAX_CGI_ENVIR_VARS]; // char *envp[]
int len; // Space taken
int nvars; // Number of variables in envp[]
};
// Append VARIABLE=VALUE\0 string to the buffer, and add a respective
// pointer into the vars array.
static char *addenv(struct cgi_env_block *block, const char *fmt, ...) {
int n, space;
char *added;
va_list ap;
// Calculate how much space is left in the buffer
space = sizeof(block->buf) - block->len - 2;
assert(space >= 0);
// Make a pointer to the free space int the buffer
added = block->buf + block->len;
// Copy VARIABLE=VALUE\0 string into the free space
va_start(ap, fmt);
n = mg_vsnprintf(added, (size_t) space, fmt, ap);
va_end(ap);
// Make sure we do not overflow buffer and the envp array
if (n > 0 && n + 1 < space &&
block->nvars < (int) ARRAY_SIZE(block->vars) - 2) {
// Append a pointer to the added string into the envp array
block->vars[block->nvars++] = added;
// Bump up used length counter. Include \0 terminator
block->len += n + 1;
}
return added;
}
static void addenv2(struct cgi_env_block *blk, const char *name) {
const char *s;
if ((s = getenv(name)) != NULL) addenv(blk, "%s=%s", name, s);
}
static void prepare_cgi_environment(struct connection *conn,
const char *prog,
struct cgi_env_block *blk) {
struct mg_connection *ri = &conn->mg_conn;
const char *s, *slash;
char *p, **opts = conn->server->config_options;
int i;
blk->len = blk->nvars = 0;
blk->conn = ri;
if ((s = getenv("SERVER_NAME")) != NULL) {
addenv(blk, "SERVER_NAME=%s", s);
} else {
addenv(blk, "SERVER_NAME=%s", conn->server->local_ip);
}
addenv(blk, "SERVER_ROOT=%s", opts[DOCUMENT_ROOT]);
addenv(blk, "DOCUMENT_ROOT=%s", opts[DOCUMENT_ROOT]);
addenv(blk, "SERVER_SOFTWARE=%s/%s", "Mongoose", MONGOOSE_VERSION);
// Prepare the environment block
addenv(blk, "%s", "GATEWAY_INTERFACE=CGI/1.1");
addenv(blk, "%s", "SERVER_PROTOCOL=HTTP/1.1");
addenv(blk, "%s", "REDIRECT_STATUS=200"); // For PHP
// TODO(lsm): fix this for IPv6 case
//addenv(blk, "SERVER_PORT=%d", ri->remote_port);
addenv(blk, "REQUEST_METHOD=%s", ri->request_method);
addenv(blk, "REMOTE_ADDR=%s", ri->remote_ip);
addenv(blk, "REMOTE_PORT=%d", ri->remote_port);
addenv(blk, "REQUEST_URI=%s%s%s", ri->uri,
ri->query_string == NULL ? "" : "?",
ri->query_string == NULL ? "" : ri->query_string);
// SCRIPT_NAME
if (conn->path_info != NULL) {
addenv(blk, "SCRIPT_NAME=%.*s",
(int) (strlen(ri->uri) - strlen(conn->path_info)), ri->uri);
addenv(blk, "PATH_INFO=%s", conn->path_info);
} else {
s = strrchr(prog, '/');
slash = strrchr(ri->uri, '/');
addenv(blk, "SCRIPT_NAME=%.*s%s",
slash == NULL ? 0 : (int) (slash - ri->uri), ri->uri,
s == NULL ? prog : s);
}
addenv(blk, "SCRIPT_FILENAME=%s", prog);
addenv(blk, "PATH_TRANSLATED=%s", prog);
addenv(blk, "HTTPS=%s", conn->ns_conn->ssl != NULL ? "on" : "off");
if ((s = mg_get_header(ri, "Content-Type")) != NULL)
addenv(blk, "CONTENT_TYPE=%s", s);
if (ri->query_string != NULL)
addenv(blk, "QUERY_STRING=%s", ri->query_string);
if ((s = mg_get_header(ri, "Content-Length")) != NULL)
addenv(blk, "CONTENT_LENGTH=%s", s);
addenv2(blk, "PATH");
addenv2(blk, "TMP");
addenv2(blk, "TEMP");
addenv2(blk, "TMPDIR");
addenv2(blk, "PERLLIB");
addenv2(blk, ENV_EXPORT_TO_CGI);
#if defined(_WIN32)
addenv2(blk, "COMSPEC");
addenv2(blk, "SYSTEMROOT");
addenv2(blk, "SystemDrive");
addenv2(blk, "ProgramFiles");
addenv2(blk, "ProgramFiles(x86)");
addenv2(blk, "CommonProgramFiles(x86)");
#else
addenv2(blk, "LD_LIBRARY_PATH");
#endif // _WIN32
// Add all headers as HTTP_* variables
for (i = 0; i < ri->num_headers; i++) {
p = addenv(blk, "HTTP_%s=%s",
ri->http_headers[i].name, ri->http_headers[i].value);
// Convert variable name into uppercase, and change - to _
for (; *p != '=' && *p != '\0'; p++) {
if (*p == '-')
*p = '_';
*p = (char) toupper(* (unsigned char *) p);
}
}
blk->vars[blk->nvars++] = NULL;
blk->buf[blk->len++] = '\0';
assert(blk->nvars < (int) ARRAY_SIZE(blk->vars));
assert(blk->len > 0);
assert(blk->len < (int) sizeof(blk->buf));
}
static const char cgi_status[] = "HTTP/1.1 200 OK\r\n";
static void open_cgi_endpoint(struct connection *conn, const char *prog) {
struct cgi_env_block blk;
char dir[MAX_PATH_SIZE], *p;
sock_t fds[2];
prepare_cgi_environment(conn, prog, &blk);
// CGI must be executed in its own directory. 'dir' must point to the
// directory containing executable program, 'p' must point to the
// executable program name relative to 'dir'.
if ((p = strrchr(prog, '/')) == NULL) {
mg_snprintf(dir, sizeof(dir), "%s", ".");
} else {
mg_snprintf(dir, sizeof(dir), "%.*s", (int) (p - prog), prog);
}
// Try to create socketpair in a loop until success. ns_socketpair()
// can be interrupted by a signal and fail.
// TODO(lsm): use sigaction to restart interrupted syscall
do {
ns_socketpair(fds);
} while (fds[0] == INVALID_SOCKET);
if (start_process(conn->server->config_options[CGI_INTERPRETER],
prog, blk.buf, blk.vars, dir, fds[1]) > 0) {
conn->endpoint_type = EP_CGI;
conn->endpoint.cgi_conn = ns_add_sock(&conn->server->ns_server,
fds[0], conn);
conn->endpoint.cgi_conn->flags |= MG_CGI_CONN;
ns_send(conn->ns_conn, cgi_status, sizeof(cgi_status) - 1);
conn->mg_conn.status_code = 200;
conn->ns_conn->flags |= NSF_BUFFER_BUT_DONT_SEND;
} else {
closesocket(fds[0]);
send_http_error(conn, 500, "start_process(%s) failed", prog);
}
#ifndef _WIN32
closesocket(fds[1]); // On Windows, CGI stdio thread closes that socket
#endif
}
static void on_cgi_data(struct ns_connection *nc) {
struct connection *conn = (struct connection *) nc->connection_data;
const char *status = "500";
struct mg_connection c;
if (!conn) return;
// Copy CGI data from CGI socket to the client send buffer
ns_send(conn->ns_conn, nc->recv_iobuf.buf, nc->recv_iobuf.len);
iobuf_remove(&nc->recv_iobuf, nc->recv_iobuf.len);
// If reply has not been parsed yet, parse it
if (conn->ns_conn->flags & NSF_BUFFER_BUT_DONT_SEND) {
struct iobuf *io = &conn->ns_conn->send_iobuf;
int s_len = sizeof(cgi_status) - 1;
int len = get_request_len(io->buf + s_len, io->len - s_len);
char buf[MAX_REQUEST_SIZE], *s = buf;
if (len == 0) return;
if (len < 0 || len > (int) sizeof(buf)) {
iobuf_remove(io, io->len);
send_http_error(conn, 500, "%s", "CGI program sent malformed headers");
} else {
memset(&c, 0, sizeof(c));
memcpy(buf, io->buf + s_len, len);
buf[len - 1] = '\0';
parse_http_headers(&s, &c);
if (mg_get_header(&c, "Location") != NULL) {
status = "302";
} else if ((status = (char *) mg_get_header(&c, "Status")) == NULL) {
status = "200";
}
memcpy(io->buf + 9, status, 3);
conn->mg_conn.status_code = atoi(status);
}
conn->ns_conn->flags &= ~NSF_BUFFER_BUT_DONT_SEND;
}
}
static void forward_post_data(struct connection *conn) {
struct iobuf *io = &conn->ns_conn->recv_iobuf;
if (conn->endpoint.cgi_conn != NULL) {
ns_send(conn->endpoint.cgi_conn, io->buf, io->len);
iobuf_remove(io, io->len);
}
}
#endif // !MONGOOSE_NO_CGI
static char *mg_strdup(const char *str) {
char *copy = (char *) malloc(strlen(str) + 1);
if (copy != NULL) {
strcpy(copy, str);
}
return copy;
}
static int isbyte(int n) {
return n >= 0 && n <= 255;
}
static int parse_net(const char *spec, uint32_t *net, uint32_t *mask) {
int n, a, b, c, d, slash = 32, len = 0;
if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5 ||
sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) &&
isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) &&
slash >= 0 && slash < 33) {
len = n;
*net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8) | d;
*mask = slash ? 0xffffffffU << (32 - slash) : 0;