/
book_samples_server.c
2132 lines (1853 loc) · 66.3 KB
/
book_samples_server.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
// Mongoose is Copyright (c) 2004-2012 Sergey Lyubka
// Book Samples Server code is Copyright (c) 2012-2013 Ger Hobbelt
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
/*
Shows/tests how to completely restart the mongoose server:
when someone visits the '/restart' URL, the server is stopped and restarted after waiting
3 seconds.
*/
// Override ASSERT in debug mode
#ifndef NDEBUG
#define MG_ASSERT(expr) \
do { \
if (!(expr)) { \
srv_signal_assert(#expr, __FILE__, __LINE__); \
} \
} while (0)
void srv_signal_assert(const char *expr, const char *filepath, unsigned int lineno);
#endif
#include "mongoose_ex.h"
#ifdef _WIN32
#include "win32/examples/mongoose_book_samples_server.resource.h"
#define _RICHEDIT_VER 0x0800
#include <richedit.h>
#ifndef AURL_ENABLEURL
#define AURL_ENABLEURL 1
#endif
#ifndef AURL_ENABLEEAURLS
#define AURL_ENABLEEAURLS 0
#endif
#include <shlwapi.h>
#endif // _WIN32
#include <upskirt/src/markdown.h>
#include <upskirt/html/html.h>
#define MAX_OPTIONS (1 + 27 /* NUM_OPTIONS */ * 3 /* once as defaults, once from config file, once from command line */)
#define MAX_CONF_FILE_LINE_SIZE (8 * 1024)
static volatile int exit_flag = 0;
static volatile int should_restart = 0;
static char server_name[40]; // Set by init_server_name()
static char config_file[PATH_MAX]; // Set by process_command_line_arguments()
static struct mg_context *ctx = NULL; // Set by start_mongoose()
#if defined(_WIN32)
static HWND app_hwnd = NULL;
static int edit_control_version = 0;
#define WM_START_SERVER (WM_APP + 42)
#define WM_SERVER_IS_STOPPING (WM_APP + 43)
#define WM_RESTART_SERVER (WM_APP + 44)
#define WM_TRAY_ICON_HIT (WM_APP + 45)
#define WM_APPEND_LOG (WM_APP + 46)
static char server_url[256] = "";
#define _T(text) TEXT(text)
#endif
static char document_root_dir[PATH_MAX] = "./";
#if !defined(CONFIG_FILE)
#define CONFIG_FILE "mongoose.conf"
#endif /* !CONFIG_FILE */
static void WINCDECL signal_handler(int sig_num) {
exit_flag = sig_num;
}
static const char *default_options[] = {
"document_root", document_root_dir,
"listening_ports", "9999", // "8081,8082s"
//"ssl_certificate", "ssl_cert.pem",
"num_threads", "5",
"error_log_file", "./log/%Y/%m/tws_ib_if_srv-%Y%m%d.%H-IP-%[s]-%[p]-error.log",
"access_log_file", "./log/%Y/%m/tws_ib_if_srv-%Y%m%d.%H-IP-%[s]-%[p]-access.log",
"index_files", "index.html,index.htm,index.cgi,index.shtml,index.php,default.html",
"ssi_pattern", "**.html$|**.htm|**.shtml$|**.shtm$",
//"ssi_marker", "{!--#,}",
"keep_alive_timeout", "5",
NULL
};
#if defined(_WIN32)
void append_log(const char *msg, ...) {
va_list args;
char *buf = NULL;
const char *msgbuf = msg;
va_start(args, msg);
if (strchr(msg, '%')) {
mg_vasprintf(NULL, &buf, 0, msg, args);
msgbuf = buf;
}
va_end(args);
if (IsWindow(app_hwnd)) {
SendMessage(app_hwnd, WM_APPEND_LOG, 0, (LPARAM)msgbuf);
} else {
OutputDebugStringA(msgbuf);
}
free(buf);
}
static int error_dialog_shown_previously = 0;
#endif
void die(const char *fmt, ...) {
va_list ap;
char msg[1024];
va_start(ap, fmt);
vsnprintf(msg, sizeof(msg), fmt, ap);
va_end(ap);
#if defined(_WIN32)
if (!error_dialog_shown_previously)
{
MessageBoxA(NULL, msg, "Error", MB_OK);
error_dialog_shown_previously = 1;
}
#else
fprintf(stderr, "%s\n", msg);
#endif
exit(EXIT_FAILURE);
}
static void show_usage_and_exit(const struct mg_context *ctx) {
const char **names;
int i;
fprintf(stderr, "Mongoose version %s (c) Sergey Lyubka, built %s\n",
mg_version(), __DATE__);
fprintf(stderr, "Usage:\n");
fprintf(stderr, " mongoose -A <htpasswd_file> <realm> <user> <passwd>\n");
fprintf(stderr, " mongoose <config_file>\n");
fprintf(stderr, " mongoose [-option value ...]\n");
fprintf(stderr, "\nOPTIONS:\n");
names = mg_get_valid_option_names();
for (i = 0; names[i] != NULL; i += MG_ENTRIES_PER_CONFIG_OPTION) {
fprintf(stderr, " %s%s %s (default: \"%s\")\n",
(names[i][0] ? "-" : " "),
names[i], names[i + 1], names[i + 2] == NULL ? "" : names[i + 2]);
}
fprintf(stderr, "\nSee http://code.google.com/p/mongoose/wiki/MongooseManual"
" for more details.\n");
fprintf(stderr, "Example:\n mongoose -s cert.pem -p 80,443s -d no\n");
exit(EXIT_FAILURE);
}
static void verify_document_root(const char *root) {
struct mgstat st;
char buf[PATH_MAX];
getcwd(buf, sizeof(buf));
if (mg_stat(root, &st) != 0 || !st.is_directory) {
die("Invalid root directory: [%s]: %s; current directory = [%s]", root, mg_strerror(ERRNO), buf);
}
}
static void set_option(char **options, const char *name, const char *value) {
int i;
if (mg_get_option_long_name(name))
name = mg_get_option_long_name(name);
for (i = 0; i < MAX_OPTIONS * 2; i += 2) {
// replace option value when it was set before: command line overrules config file, which overrules global defaults.
if (options[i] == NULL) {
options[i] = mg_strdup(name);
options[i + 1] = mg_strdup(value);
break;
} else if (strcmp(options[i], name) == 0) {
free(options[i + 1]);
options[i + 1] = mg_strdup(value);
break;
}
}
if (i > MAX_OPTIONS * 2 - 2) {
die("Too many options specified");
}
}
static void process_command_line_arguments(char *argv[], char **options) {
char line[MAX_CONF_FILE_LINE_SIZE], opt[sizeof(line)], val[sizeof(line)], *p;
FILE *fp = NULL;
size_t i;
int line_no = 0;
options[0] = NULL;
// Should we use a config file ?
if (argv[1] != NULL && argv[2] == NULL) {
snprintf(config_file, sizeof(config_file), "%s", argv[1]);
} else if ((p = strrchr(argv[0], DIRSEP)) == NULL) {
// No command line flags specified. Look where binary lives
snprintf(config_file, sizeof(config_file), "%s", CONFIG_FILE);
} else {
snprintf(config_file, sizeof(config_file), "%.*s%c%s",
(int) (p - argv[0]), argv[0], DIRSEP, CONFIG_FILE);
}
fp = mg_fopen(config_file, "r");
// If config file was set in command line and open failed, exit
if (argv[1] != NULL && argv[2] == NULL && fp == NULL) {
die("Cannot open config file %s: %s", config_file, mg_strerror(ERRNO));
}
// use the default values for starters (so that all options have a known reasonable value):
for (i = 0; default_options[i]; i += 2) {
set_option(options, default_options[i], default_options[i+1]);
}
// Load config file settings first
if (fp != NULL) {
append_log("Loading config file %s\n", config_file);
// Loop over the lines in config file
while (fgets(line, sizeof(line), fp) != NULL) {
if (!line_no && !memcmp(line,"\xEF\xBB\xBF", 3)) {
// strip UTF-8 BOM
p = line+3;
} else {
p = line;
}
line_no++;
// Ignore empty lines (with optional, ignored, whitespace) and comments
if (line[0] == '#')
continue;
// MS sscanf() says: The return value is EOF for an error or if the end of the string is reached before the first conversion.
// Hence we make sure we don't feed it an empty line --> -1 will only have one meaning then.
if (line[strspn(line, " \t\r\n")] == 0)
continue;
if (2 == sscanf(line, "%s %[^\r\n#]", opt, val)) {
set_option(options, opt, val);
continue;
} else {
die("%s: line %d is invalid", config_file, line_no);
break;
}
}
(void) mg_fclose(fp);
}
// Now handle command line flags. They override config file / default settings.
for (i = 1; argv[i] != NULL; i += 2) {
if (argv[i][0] != '-' || argv[i + 1] == NULL) {
show_usage_and_exit(ctx);
}
set_option(options, &argv[i][1], argv[i + 1]);
}
}
static void init_server_name(void) {
snprintf(server_name, sizeof(server_name), "Mongoose web server v%s",
mg_version());
}
// example and test case for a callback
// this callback creates a statistics of request methods and the requested uris
// it is not meant as a feature but as a simple test case
struct t_stat {
const char * name;
unsigned long getCount;
unsigned long postCount;
struct t_stat * next;
};
struct t_user_arg {
pthread_mutex_t mutex;
struct t_stat * uris[0x10000];
};
unsigned short crc16(const void * data, size_t bitCount) {
unsigned short r = 0xFFFFu;
size_t i;
for (i = 0; i < bitCount; i++) {
unsigned short b = ((unsigned char*)data)[i>>3];
b >>= i & 0x7ul;
r = ((r & 1u) != (b & 1u)) ? ((r>>1) ^ 0xA001u) : (r>>1);
}
r ^= 0xFFFFu;
return r;
}
static int report_markdown_failure(struct mg_connection *conn, int is_inline_production, int response_code, const char *fmt, ...)
{
va_list args;
if (is_inline_production)
{
mg_printf(conn, "<h1 style=\"color: red;\">Error: %d - %s</h1>\n", response_code, mg_get_response_code_text(response_code));
va_start(args, fmt);
mg_vprintf(conn, fmt, args);
va_end(args);
}
else
{
va_start(args, fmt);
mg_vsend_http_error(conn, response_code, NULL, fmt, args);
va_end(args);
}
return -1;
}
static int serve_a_markdown_page(struct mg_connection *conn, const struct mgstat *st, int is_inline_production)
{
#define SD_READ_UNIT 1024
#define SD_OUTPUT_UNIT 64
const struct mg_request_info *ri = mg_get_request_info(conn);
struct sd_buf *ib, *ob;
int ret;
unsigned int enabled_extensions = MKDEXT_TABLES | MKDEXT_FENCED_CODE | MKDEXT_EMAIL_FRIENDLY;
unsigned int render_flags = 0; // HTML_SKIP_HTML | HTML_SKIP_STYLE | HTML_HARD_WRAP;
struct sd_callbacks callbacks;
struct html_renderopt options;
struct sd_markdown *markdown;
/* opening the file */
FILE *in;
MG_ASSERT(ri->phys_path);
/* opening the file */
in = mg_fopen(ri->phys_path, "r");
if (!in)
{
return report_markdown_failure(conn, is_inline_production, 404, "Unable to open input file: [%s] %s", ri->uri, mg_strerror(errno));
}
/* reading everything */
ib = sd_bufnew(SD_READ_UNIT);
if (SD_BUF_OK != sd_bufgrow(ib, (size_t)st->size))
{
mg_fclose(in);
sd_bufrelease(ib);
return report_markdown_failure(conn, is_inline_production, 500, "Out of memory while loading Markdown input file: [%s]", ri->uri);
}
ret = (int)fread(ib->data, 1, ib->asize, in);
if (ret > 0)
{
ib->size += ret;
mg_fclose(in);
}
else
{
mg_fclose(in);
sd_bufrelease(ib);
return report_markdown_failure(conn, is_inline_production, 500, "Cannot read from input file: [%s] %s", ri->uri, mg_strerror(errno));
}
/* performing markdown parsing */
ob = sd_bufnew(SD_OUTPUT_UNIT);
sdhtml_renderer(&callbacks, &options, render_flags);
markdown = sd_markdown_new(enabled_extensions, 16, &callbacks, &options);
if (!markdown)
{
sd_bufrelease(ib);
sd_bufrelease(ob);
return report_markdown_failure(conn, is_inline_production, 500, "Out of memory while processing Markdown input file: [%s]", ri->uri);
}
sd_markdown_render(ob, ib->data, ib->size, markdown);
sd_markdown_free(markdown);
if (!is_inline_production)
{
/* write the appropriate headers */
char date[64], lm[64], etag[64];
time_t curtime = time(NULL);
const char *hdr;
int64_t cl, r1, r2;
int n;
mg_set_response_code(conn, 200);
cl = ob->size;
#if 0
// If Range: header specified, act accordingly
r1 = r2 = 0;
hdr = mg_get_header(conn, "Range");
if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0) {
mg_set_response_code(conn, 206);
(void) fseeko(fp, (off_t) r1, SEEK_SET);
cl = n == 2 ? r2 - r1 + 1: cl - r1;
mg_add_response_header(conn, 0, "Content-Range",
"bytes "
"%" PRId64 "-%"
PRId64 "/%" PRId64 "\r\n",
r1, r1 + cl - 1, stp->size);
}
#endif
// Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to
// http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3
mg_gmt_time_string(date, sizeof(date), &curtime);
mg_gmt_time_string(lm, sizeof(lm), &st->mtime);
(void) mg_snprintf(conn, etag, sizeof(etag), "%lx.%lx", (unsigned long) st->mtime, (unsigned long) st->size);
mg_add_response_header(conn, 0, "Date", "%s", date);
mg_add_response_header(conn, 0, "Last-Modified", "%s", lm);
mg_add_response_header(conn, 0, "Etag", "\"%s\"", etag);
mg_add_response_header(conn, 0, "Content-Type", "text/html; charset=utf-8");
mg_add_response_header(conn, 0, "Content-Length", "%" PRId64, cl);
// Connection: close is automatically added by mg_write_http_response_head()
mg_write_http_response_head(conn, 0, NULL);
ret = (int)cl;
if (strcmp(ri->request_method, "HEAD") != 0) {
ret = mg_write(conn, ob->data, (size_t)cl);
}
}
else
{
ret = mg_write(conn, ob->data, ob->size);
}
/* cleanup */
sd_bufrelease(ib);
sd_bufrelease(ob);
return ret;
}
static int send_requested_resource(struct mg_context *ctx, struct mg_connection *conn,
const struct mg_request_info *request_info, struct t_user_arg * udata) {
// Send the resource matching the given name
struct res_def {
LPCTSTR id;
LPCTSTR category;
const char *path;
const char *mime;
};
static const struct res_def res_defs[] = {
{
MAKEINTRESOURCE(IDR_HTML_HELP_OVERVIEW),
RT_HTML,
"/_help/help_overview.html",
"text/html"
},
{
MAKEINTRESOURCE(IDR_HTML_DEVELOPER_INFO),
RT_HTML,
"/_help/developer_info.html",
"text/html"
},
{
MAKEINTRESOURCE(IDR_RC_BIOHAZARD_RED_BG_SVG),
RT_RCDATA,
"/_help/images/biohazard-red-bg.svg",
"image/svg+xml"
},
};
int i;
for (i = 0; i < ARRAY_SIZE(res_defs); i++) {
const struct res_def *def = &res_defs[i];
if (!strcmp(def->path, request_info->uri)) {
HMODULE module;
HRSRC icon;
DWORD len;
void *data;
module = GetModuleHandle(NULL);
icon = FindResource(module, def->id, def->category);
data = LockResource(LoadResource(module, icon));
len = SizeofResource(module, icon);
mg_add_response_header(conn, 0, "Content-Type", def->mime);
mg_add_response_header(conn, 0, "Cache-Control", "no-cache");
mg_add_response_header(conn, 0, "Content-Length", "%u", (unsigned int)len);
mg_write_http_response_head(conn, 200, NULL);
if ((int)len != mg_write(conn, data, len)) {
mg_send_http_error(conn, 580, NULL, "not all data was written to the socket (len: %u)", (unsigned int)len); // internal error in our custom handler or client closed connection prematurely
}
return 1;
}
}
return 0;
}
/*
Ths bit of code shows how one can go about providing something very much like
IP-based and/or Name-based Virtual Hosting.
When you have your local DNS (or hosts file for that matter) configured to
point the 'localhost-9.lan' domain name at IP address 127.0.0.9 and then run
mongoose on your localhost and visit
http://127.0.0.2/
for an example of IP-based Virtual Hosting, or
http://localhost-9.lan/
for an example of Host-based Virtual Hosting, you will see another website
located in ./documentation: the mongoose documentation pages.
If you visit
http://127.0.0.1/
or
http://127.0.0.9/
instead you will visit the website located in ./test/
---
Off Topic: one can override other options on a per-connection / request basis
as well. This applies to all options which' values are fetched by
mongoose through the internal get_conn_option() call - grep
mongoose.c for that one if you like.
*/
// typedef const char * (*mg_option_get_callback_t)(struct mg_context *ctx, struct mg_connection *conn, const char *name);
static const char *option_get_callback(struct mg_context *ctx, struct mg_connection *conn, const char *name)
{
// check local IP for IP-based Virtual Hosting & switch DocumentRoot for the connection accordingly:
if (conn && !strcmp("document_root", name))
{
const struct mg_request_info *request_info = mg_get_request_info(conn);
static char docu_site_docroot[PATH_MAX] = "";
/* IP-based Virtual Hosting */
if (!request_info->local_ip.is_ip6 &&
request_info->local_ip.ip_addr.v4[0] == 127 &&
request_info->local_ip.ip_addr.v4[1] == 0 &&
request_info->local_ip.ip_addr.v4[2] == 0 &&
request_info->local_ip.ip_addr.v4[3] >= 2 /* 127.0.0.x where x >= 2 */)
{
/* 127.0.0.x where x >= 2 */
// use the CTX-based get-option call so our recursive invocation
// skips this bit of code as 'conn == NULL' then:
mg_snprintf(NULL, docu_site_docroot, sizeof(docu_site_docroot), "%s/../localhost-%03u", mg_get_option(ctx, name), (unsigned int)request_info->local_ip.ip_addr.v4[3]);
return docu_site_docroot;
}
/* Name-based Virtual Hosting */
int prefix_len = mg_match_string("*.gov|*.lan", -1, mg_get_header(conn, "Host")); /* e.g. 'nameless.gov:8081' or 'fifi.lan:8081' */
if (0 < prefix_len)
{
// use the CTX-based get-option call so our recursive invocation
// skips this bit of code as 'conn == NULL' then:
mg_snprintf(NULL, docu_site_docroot, sizeof(docu_site_docroot), "%s/../%.*s", mg_get_option(ctx, name), prefix_len, mg_get_header(conn, "Host"));
return docu_site_docroot;
}
}
return NULL; // let mongoose handle it by himself
}
static void *mongoose_callback(enum mg_event event, struct mg_connection *conn) {
struct mg_context *ctx = mg_get_context(conn);
const struct mg_request_info *request_info = mg_get_request_info(conn);
int i;
struct t_user_arg * udata = (struct t_user_arg *)mg_get_user_data(ctx)->user_data;
const char * uri;
unsigned short crc;
struct t_stat ** st;
char content[1024];
int content_length;
if (event == MG_INIT0)
{
verify_document_root(mg_get_conn_option(conn, "document_root"));
return (void *)1;
}
if (event == MG_EXIT_MASTER && mg_get_stop_flag(ctx))
{
/*
master thread stopped due to STOP signal given by somebody;
this is a sure-fire way to detect if the STOP signal was issued,
but it has the 'drawback' that by now, the master thread and
probably quite a few of the client threads have terminated as
well.
If you don't mind about that, it's a fine way to detect the STOP
with a minimum of fuss in an event-driven environment such as the
Windows message loop.
*/
PostMessage(app_hwnd, WM_SERVER_IS_STOPPING, 0, 0);
return (void *)1;
}
#if defined(_WIN32)
if (event == MG_EVENT_LOG &&
strstr(request_info->log_message, "cannot bind to") &&
!strcmp(request_info->log_severity, "error"))
{
if (!error_dialog_shown_previously)
{
MessageBoxA(NULL, request_info->log_message, "Error", MB_OK);
error_dialog_shown_previously = 1;
}
}
#endif
if (event == MG_EVENT_LOG)
{
DEBUG_TRACE(0x00010000, ("[%s] %s", request_info->log_severity, request_info->log_message));
// we do not log 'HTTP RESPONSE 304' 'error' lines as those are very valid responses (304 = Not Modified) which should not pollute the log window.
switch (request_info->status_code)
{
case 304:
// do not log 'Not Modified' messages.
break;
default:
append_log("[%s] %s\n", request_info->log_severity, request_info->log_message);
break;
}
return (void *)1;
}
if (event == MG_SSI_INCLUDE_REQUEST || event == MG_NEW_REQUEST) {
struct mgstat st;
int file_found;
MG_ASSERT(request_info->phys_path);
file_found = (0 == mg_stat(request_info->phys_path, &st) && !st.is_directory);
if (file_found) {
// are we looking for HTML output of MarkDown file?
if (mg_match_string("**.md$|**.mkd$|**.markdown$|**.wiki$", -1, request_info->phys_path) > 0) {
serve_a_markdown_page(conn, &st, (event == MG_SSI_INCLUDE_REQUEST));
return "";
}
return NULL; // let mongoose handle the default of 'file exists'...
}
}
if (event != MG_NEW_REQUEST) {
// This callback currently only handles new requests
return NULL;
}
// This callback adds the request method and the uri to a list.
uri = request_info->uri;
// In C++ one could use a STL-map. However, this is just a test case here.
crc = crc16(uri, (strlen(uri)+1)<<3);
// This is a multithreaded system, so a mutex is required
pthread_mutex_lock(&udata->mutex);
st = &udata->uris[crc];
while (*st) {
if (!strcmp((*st)->name, uri)) {
break;
} else {
st = &((*st)->next);
}
}
if (*st == NULL) {
uri = mg_strdup(uri);
*st = (struct t_stat*) calloc(1, sizeof(struct t_stat));
if (!st || !uri) {
pthread_mutex_unlock(&udata->mutex);
die("out of memory");
}
(*st)->name = uri;
(*st)->next = 0;
}
if (!strcmp(request_info->request_method, "GET")) {
(*st)->getCount++;
} else if (!strcmp(request_info->request_method, "POST")) {
(*st)->postCount++;
}
pthread_mutex_unlock(&udata->mutex);
if (!strcmp(uri, "/_stat")) {
mg_connection_must_close(conn);
// Connection: close is automatically added by mg_write_http_response_head()
mg_add_response_header(conn, 0, "Cache-Control", "no-cache");
mg_add_response_header(conn, 0, "Content-Type", "text/html; charset=utf-8");
mg_write_http_response_head(conn, 200, NULL);
mg_printf(conn,
"<html><head><title>HTTP server statistics</title>"
"<style>th {text-align: left;}</style></head>"
"<body><h1>HTTP server statistics</h1>\r\n");
mg_printf(conn,
"<p><pre><table border=\"1\" rules=\"all\">"
"<tr><th>Resource</th>"
"<th>GET</th><th>POST</th></tr>\r\n");
pthread_mutex_lock(&udata->mutex);
for (i = 0; i < sizeof(udata->uris) / sizeof(udata->uris[0]); i++) {
st = &udata->uris[i];
while (*st) {
mg_printf(conn, "<tr><td>%s</td><td>%8u</td><td>%8u</td></tr>\r\n",
(*st)->name, (*st)->getCount, (*st)->postCount);
st = &((*st)->next);
}
}
pthread_mutex_unlock(&udata->mutex);
mg_printf(conn, "</table></pre></p></body></html>\r\n");
return (void *)1;
} else if (!strcmp(uri, "/_echo")) {
const char * contentLength = mg_get_header(conn, "Content-Length");
mg_connection_must_close(conn);
// Connection: close is automatically added by mg_write_http_response_head()
mg_add_response_header(conn, 0, "Cache-Control", "no-cache");
mg_add_response_header(conn, 0, "Content-Type", "text/plain; charset=utf-8");
mg_write_http_response_head(conn, 200, NULL);
mg_printf(conn, "Received headers:\r\n");
for (i = 0; i < request_info->num_headers; i++)
{
mg_printf(conn, "Header[%d]: '%s' = '%s'\r\n",
i, request_info->http_headers[i].name, request_info->http_headers[i].value);
}
mg_printf(conn, "----- info bits ------\r\n");
mg_printf(conn, "URL: [%s]\r\n", request_info->uri);
mg_printf(conn, "Query: [%s]\r\n", request_info->query_string);
mg_printf(conn, "Phys.Path: [%s]\r\n", request_info->phys_path);
mg_printf(conn, "----- data? ------\r\n");
if (!strcmp(request_info->request_method, "POST")) {
long int dataSize = atol(contentLength);
#if 0
int bufferSize = (dataSize > 1024 * 1024 ? 1024 * 1024 : (int)dataSize);
#else
int bufferSize = (int)dataSize;
#endif
long int gotSize = 0;
int bufferFill = 0;
char * data = (char*) ((dataSize > 0) ? malloc(bufferSize) : 0);
if (data) {
mg_set_non_blocking_mode(conn, 1);
{
const int tcpbuflen = 1 * 1024 * 1024;
mg_setsockopt(conn, SOL_SOCKET, SO_RCVBUF, (const void *)&tcpbuflen, sizeof(tcpbuflen));
mg_setsockopt(conn, SOL_SOCKET, SO_SNDBUF, (const void *)&tcpbuflen, sizeof(tcpbuflen));
}
while (gotSize < dataSize && !mg_get_stop_flag(ctx)) {
int gotNow = 0;
// check whether there's anything available:
fd_set read_set;
struct timeval tv;
int max_fd;
FD_ZERO(&read_set);
max_fd = -1;
tv.tv_sec = 1;
tv.tv_usec = 0;
while (mg_get_stop_flag(ctx) == 0)
{
struct timeval tv2 = tv;
FD_ZERO(&read_set);
max_fd = -1;
// Add listening sockets to the read set
mg_FD_SET(conn, &read_set, &max_fd);
if (select(max_fd + 1, &read_set, NULL, NULL, &tv2) < 0)
{
// signal a fatal failure:
// clear the handles sets to prevent 'surprises' from processing these a second time (below):
FD_ZERO(&read_set);
max_fd = -1;
MG_ASSERT(!"Should never get here");
mg_send_http_error(conn, 579, NULL, "select() failure"); // internal error in our custom handler
break;
}
else
{
if (mg_FD_ISSET(conn, &read_set))
{
break;
}
max_fd = -1;
}
}
if (max_fd >= 0)
{
long int len = dataSize - gotSize;
if (len > bufferSize - bufferFill)
len = bufferSize - bufferFill;
gotNow = mg_read(conn, data + bufferFill, len);
if (gotNow > 0)
{
bufferFill += gotNow;
if (bufferFill == bufferSize && bufferSize != dataSize)
{
bufferFill = mg_write(conn, data, bufferSize);
if (bufferFill < 0)
{
mg_send_http_error(conn, 579, NULL, "POST /_echo: write error at dataSize=%lu, gotNow=%u, gotSize=%lu\n", dataSize, gotNow, gotSize);
break;
}
bufferFill = bufferSize - bufferFill;
}
}
}
if (gotNow == 0)
{
DEBUG_TRACE(0x00020000,
("POST /_echo: ***CLOSE*** at dataSize=%lu, gotNow=%u, gotSize=%lu\n",
dataSize, gotNow, gotSize));
break;
}
gotSize += gotNow;
}
mg_set_non_blocking_mode(conn, 0);
//mg_write(conn, data, gotSize);
if (bufferFill > 0 && mg_get_stop_flag(ctx) == 0)
{
int wlen = mg_write(conn, data, bufferFill);
if (bufferFill != wlen)
{
mg_send_http_error(conn, 580, NULL, "POST /_echo: ***ERR*** at dataSize=%lu, gotSize=%lu, wlen=%d\n", dataSize, gotSize, wlen); // internal error in our custom handler
}
}
free(data);
}
} else {
mg_printf(conn, "%s", request_info->request_method);
}
return (void *)1;
} else {
struct mgstat fst;
MG_ASSERT(request_info->phys_path);
if (0 == mg_stat(request_info->phys_path, &fst)) {
return NULL; // let mongoose handle the default of 'file exists/directory listing'...
}
if (strstr(uri, "/restart")) {
// send an info page
content_length = mg_snprintf(conn, content, sizeof(content),
"<html><body><h1>Restart in progress</h1>"
"<p><a href=\"/\">Click here</a> to view "
"the hello page again.");
mg_connection_must_close(conn);
//mg_set_response_code(conn, 200);
mg_add_response_header(conn, 0, "Content-Length", "%d", content_length);
mg_add_response_header(conn, 0, "Content-Type", "text/html");
//mg_add_response_header(conn, 0, "Connection", "%s", mg_suggest_connection_header(conn)); -- not needed any longer
mg_write_http_response_head(conn, 200, 0);
mg_write(conn, content, content_length);
// signal the server to stop & restart
should_restart = 1;
mg_signal_stop(mg_get_context(conn));
// Mark as processed
return "";
} else if (strstr(request_info->uri, "/quit")) {
// send an info page
content_length = mg_snprintf(conn, content, sizeof(content),
"<html><body><h1>Server shut down in progress</h1>");
mg_connection_must_close(conn);
//mg_set_response_code(conn, 200);
mg_add_response_header(conn, 0, "Content-Length", "%d", content_length);
mg_add_response_header(conn, 0, "Content-Type", "text/html");
//mg_add_response_header(conn, 0, "Connection", "%s", mg_suggest_connection_header(conn)); -- not needed any longer
mg_write_http_response_head(conn, 200, 0);
mg_write(conn, content, content_length);
// signal the server to stop
should_restart = 0;
mg_signal_stop(mg_get_context(conn));
// Mark as processed
return "";
} else
#ifdef _WIN32
// Send the systray icon as favicon
if (!strcmp("/favicon.ico", request_info->uri)) {
HMODULE module;
HRSRC icon;
DWORD len;
void *data;
module = GetModuleHandle(NULL);
icon = FindResource(module, MAKEINTRESOURCE(IDR_FAVICON), RT_RCDATA);
data = LockResource(LoadResource(module, icon));
len = SizeofResource(module, icon);
mg_add_response_header(conn, 0, "Content-Type", "image/x-icon");
mg_add_response_header(conn, 0, "Cache-Control", "no-cache");
mg_add_response_header(conn, 0, "Content-Length", "%u", (unsigned int)len);
mg_write_http_response_head(conn, 200, NULL);
if ((int)len != mg_write(conn, data, len)) {
mg_send_http_error(conn, 580, NULL, "not all data was written to the socket (len: %u)", (unsigned int)len); // internal error in our custom handler or client closed connection prematurely
}
return (void *)1;
}
else if (send_requested_resource(ctx, conn, request_info, udata)) {
return (void *)1;
} else
#endif
{
struct mg_mime_vec mime_vec;
char ip_addr_strbuf[128];
// allow default error processing chain:
if (!strncmp(uri, "/error/", 7)) {
return 0;
}
// default error processing chain for JS/CSS/JSON/LESS/MD/TXT/COFFEE/COFFEESCRIPT/FONT/SVG/PDF/AI/PS/JPG/PNG/GIF/AVI/MKV/MOV/etc. files,
// i.e. handle all file requests which have a MIME type as 'standard' UNLESS the requested file is a HTML file.
mg_get_mime_type(ctx, uri, NULL, &mime_vec);
if (mime_vec.ptr && mime_vec.len && !mg_vec_matches_string(&mime_vec, "text/html")) {
return 0; // let mongoose handle the default of 'file exists'...
}
content_length = mg_snprintf(conn, content, sizeof(content),
"<html><body>"
"<h1>404 - File not found!</h1>"
"<p>Hello from mongoose! Your browser's IP address & port: %s : %d. You requested the file: '<code>%s</code>'."
"<p><a href=\"/restart\">Click here</a> to restart "
"the server."
"<p><a href=\"/quit\">Click here</a> to stop "
"the server.",
mg_sockaddr_to_string(ip_addr_strbuf, ARRAY_SIZE(ip_addr_strbuf), conn, TRUE),
request_info->remote_port,
request_info->uri); // <-- known issue: we echo user data back to them without sanitizing it first; we don't mind in this sample/test server!
//mg_set_response_code(conn, 200); -- not needed any longer
mg_add_response_header(conn, 0, "Content-Length", "%d", content_length);
mg_add_response_header(conn, 0, "Content-Type", "text/html");
//mg_add_response_header(conn, 0, "Connection", "%s", mg_suggest_connection_header(conn)); -- not needed any longer
mg_write_http_response_head(conn, 200, 0);
mg_write(conn, content, content_length);
// Mark as processed
return "";
}
}
return NULL;
}
#if defined(_WIN32)
static void report_possible_vhosts(void)
{
char hosts_path[PATH_MAX];
char line[512];
unsigned int ip_lsb;
char domainname[128];
const char *sysdir = getenv("WINDIR");