1 /* Copyright (c) 2015-2020 the Civetweb developers
2 *
3 * Permission is hereby granted, free of charge, to any person obtaining a copy
4 * of this software and associated documentation files (the "Software"), to deal
5 * in the Software without restriction, including without limitation the rights
6 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7 * copies of the Software, and to permit persons to whom the Software is
8 * furnished to do so, subject to the following conditions:
9 *
10 * The above copyright notice and this permission notice shall be included in
11 * all copies or substantial portions of the Software.
12 *
13 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19 * THE SOFTWARE.
20 */
21
22 #ifdef _MSC_VER
23 #ifndef _CRT_SECURE_NO_WARNINGS
24 #define _CRT_SECURE_NO_WARNINGS
25 #endif
26 #endif
27
28 #include <stdarg.h>
29 #include <stdint.h>
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <sys/stat.h>
34 #include <sys/types.h>
35 #include <time.h>
36
37 #include "public_server.h"
38 #include <civetweb.h>
39
40 #if defined(_WIN32)
41 #include <windows.h>
42 #define test_sleep(x) (Sleep((x)*1000))
43 #else
44 #include <arpa/inet.h>
45 #include <netdb.h>
46 #include <netinet/in.h>
47 #include <sys/socket.h>
48 #include <unistd.h>
49 #define test_sleep(x) (sleep(x))
50 #endif
51
52
53 /* Some environment configuration for the unit test */
54 #define SLEEP_BEFORE_MG_START (1)
55 #define SLEEP_AFTER_MG_START (3)
56 #define SLEEP_BEFORE_MG_STOP (1)
57 #define SLEEP_AFTER_MG_STOP (5)
58
59
60 /* Try to communicate with an external http server. */
61 static const char *
get_external_server_ip(void)62 get_external_server_ip(void)
63 {
64 #define no_of_testhosts (4)
65 const char *testhost[no_of_testhosts] = {"github.com",
66 "google.com",
67 "sourceforge.net",
68 "microsoft.com"};
69 static char external_ip[64] = {0};
70 int testhostidx;
71
72 if (external_ip[0]) {
73 /* Get IP of external server only once, then reuse it */
74 return external_ip;
75 }
76 mark_point();
77
78 for (testhostidx = 0; testhostidx < no_of_testhosts; testhostidx++) {
79 struct hostent *hostentry;
80 struct in_addr **in_addr_list;
81 const char *ip;
82
83 hostentry = gethostbyname(testhost[testhostidx]);
84
85 if (hostentry != NULL) {
86 in_addr_list = (struct in_addr **)hostentry->h_addr_list;
87 if (in_addr_list[0] != NULL) {
88 ip = inet_ntoa(*in_addr_list[0]);
89 if (ip != NULL) {
90 mark_point();
91 strcpy(external_ip, ip);
92 return external_ip;
93 }
94 }
95 }
96 }
97
98 ck_abort_msg("Could not determine IP of any external server");
99 return "0.0.0.0";
100 }
101
102
103 /* This unit test file uses the excellent Check unit testing library.
104 * The API documentation is available here:
105 * http://check.sourceforge.net/doc/check_html/index.html
106 */
107
108 #if defined(__MINGW32__) || defined(__GNUC__)
109 /* Return codes of the tested functions are evaluated. Checking all other
110 * functions, used only to prepare the test environment seems redundant.
111 * If they fail, the test fails anyway. */
112 #pragma GCC diagnostic ignored "-Wunused-result"
113 #endif
114
115 static const char *
locate_path(const char * a_path)116 locate_path(const char *a_path)
117 {
118 static char r_path[256];
119
120 #ifdef _WIN32
121 #ifdef LOCAL_TEST
122 sprintf(r_path, "%s\\", a_path);
123 #else
124 /* Appveyor */
125 sprintf(r_path, "..\\..\\..\\%s\\", a_path);
126 /* TODO: the different paths
127 * used in the different test
128 * system is an unsolved
129 * problem. */
130 #endif
131 #else
132 #ifdef LOCAL_TEST
133 sprintf(r_path, "%s/", a_path);
134 #else
135 /* Travis */
136 sprintf(r_path,
137 "../../%s/",
138 a_path); // TODO: fix path in CI test environment
139 #endif
140 #endif
141
142 return r_path;
143 }
144
145
146 #define locate_resources() locate_path("resources")
147 #define locate_test_exes() locate_path("output")
148
149
150 static const char *
locate_ssl_cert(void)151 locate_ssl_cert(void)
152 {
153 static char cert_path[256];
154 const char *res = locate_resources();
155 size_t l;
156
157 ck_assert(res != NULL);
158 l = strlen(res);
159 ck_assert_uint_gt(l, 0);
160 ck_assert_uint_lt(l, 100); /* assume there is enough space left in our
161 typical 255 character string buffers */
162
163 strcpy(cert_path, res);
164 strcat(cert_path, "ssl_cert.pem");
165 return cert_path;
166 }
167
168
169 static int
wait_not_null(void * volatile * data)170 wait_not_null(void *volatile *data)
171 {
172 int i;
173 for (i = 0; i < 100; i++) {
174 mark_point();
175 test_sleep(1);
176
177 if (*data != NULL) {
178 mark_point();
179 return 1;
180 }
181 }
182
183 #if defined(__MINGW32__) || defined(__GNUC__)
184 #pragma GCC diagnostic push
185 #pragma GCC diagnostic ignored "-Wunreachable-code"
186 #pragma GCC diagnostic ignored "-Wunreachable-code-return"
187 #endif
188
189 ck_abort_msg("wait_not_null failed (%i sec)", i);
190
191 return 0;
192
193 #if defined(__MINGW32__) || defined(__GNUC__)
194 #pragma GCC diagnostic pop
195 #endif
196 }
197
198
START_TEST(test_the_test_environment)199 START_TEST(test_the_test_environment)
200 {
201 char wd[300];
202 char buf[500];
203 FILE *f;
204 const char *ssl_cert = locate_ssl_cert();
205
206 memset(wd, 0, sizeof(wd));
207 memset(buf, 0, sizeof(buf));
208
209 /* Get the current working directory */
210 #ifdef _WIN32
211 (void)GetCurrentDirectoryA(sizeof(wd), wd);
212 wd[sizeof(wd) - 1] = 0;
213 #else
214 (void)getcwd(wd, sizeof(wd));
215 wd[sizeof(wd) - 1] = 0;
216 #endif
217
218 /* Check the pem file */
219 #ifdef _WIN32
220 strcpy(buf, wd);
221 strcat(buf, "\\");
222 strcat(buf, ssl_cert);
223 f = fopen(buf, "rb");
224 #else
225 strcpy(buf, wd);
226 strcat(buf, "/");
227 strcat(buf, ssl_cert);
228 f = fopen(buf, "r");
229 #endif
230
231 if (f) {
232 fclose(f);
233 } else {
234 fprintf(stderr, "Certificate %s not found\n", buf);
235 exit(1); /* some path is not correct --> test will not work */
236 }
237
238
239 #ifdef _WIN32
240 /* Try to copy the files required for AppVeyor */
241 #if defined(_WIN64) || defined(__MINGW64__)
242 (void)system("cmd /c copy C:\\OpenSSL-Win64\\libeay32.dll libeay32.dll");
243 (void)system("cmd /c copy C:\\OpenSSL-Win64\\libssl32.dll libssl32.dll");
244 (void)system("cmd /c copy C:\\OpenSSL-Win64\\ssleay32.dll ssleay32.dll");
245 (void)system("cmd /c copy C:\\OpenSSL-Win64\\libeay32.dll libeay64.dll");
246 (void)system("cmd /c copy C:\\OpenSSL-Win64\\libssl32.dll libssl64.dll");
247 (void)system("cmd /c copy C:\\OpenSSL-Win64\\ssleay32.dll ssleay64.dll");
248 #else
249 (void)system("cmd /c copy C:\\OpenSSL-Win32\\libeay32.dll libeay32.dll");
250 (void)system("cmd /c copy C:\\OpenSSL-Win32\\libssl32.dll libssl32.dll");
251 (void)system("cmd /c copy C:\\OpenSSL-Win32\\ssleay32.dll ssleay32.dll");
252 #endif
253 #endif
254 }
255 END_TEST
256
257
258 static void *threading_data = 0;
259
260 static void *
test_thread_func_t(void * param)261 test_thread_func_t(void *param)
262 {
263 ck_assert_ptr_eq(param, &threading_data);
264 ck_assert_ptr_eq(threading_data, NULL);
265 threading_data = &threading_data;
266 return NULL;
267 }
268
269
START_TEST(test_threading)270 START_TEST(test_threading)
271 {
272 int ok;
273
274 threading_data = NULL;
275 mark_point();
276
277 ok = mg_start_thread(test_thread_func_t, &threading_data);
278 ck_assert_int_eq(ok, 0);
279
280 wait_not_null(&threading_data);
281 ck_assert_ptr_eq(threading_data, &threading_data);
282 }
283 END_TEST
284
285 static const char *lastMessage = NULL;
286
287 static int
log_msg_func(const struct mg_connection * conn,const char * message)288 log_msg_func(const struct mg_connection *conn, const char *message)
289 {
290 struct mg_context *ctx;
291 char *ud;
292
293 ck_assert(conn != NULL);
294 ctx = mg_get_context(conn);
295 ck_assert(ctx != NULL);
296 ud = (char *)mg_get_user_data(ctx);
297
298 strncpy(ud, message, 255);
299 ud[255] = 0;
300 mark_point();
301
302 printf("LOG_MSG_FUNC: %s\n", message);
303 mark_point();
304 lastMessage = message;
305
306 return 1; /* Return 1 means "already handled" */
307 }
308
309
310 static int
test_log_message(const struct mg_connection * conn,const char * message)311 test_log_message(const struct mg_connection *conn, const char *message)
312 {
313 (void)conn;
314
315 printf("LOG_MESSAGE: %s\n", message);
316 mark_point();
317 lastMessage = message;
318
319 return 0; /* Return 0 means "not yet handled" */
320 }
321
322
323 static struct mg_context *
test_mg_start(const struct mg_callbacks * callbacks,void * user_data,const char ** configuration_options,unsigned line)324 test_mg_start(const struct mg_callbacks *callbacks,
325 void *user_data,
326 const char **configuration_options,
327 unsigned line)
328 {
329 struct mg_context *ctx;
330 struct mg_callbacks cb;
331 struct mg_init_data init;
332 struct mg_error_data error;
333 char error_buffer[256];
334
335 memset(&init, 0, sizeof(init));
336 memset(&error, 0, sizeof(error));
337
338 if (callbacks) {
339 memcpy(&cb, callbacks, sizeof(cb));
340 } else {
341 memset(&cb, 0, sizeof(cb));
342 }
343
344 if (cb.log_message == NULL) {
345 cb.log_message = test_log_message;
346 }
347
348 init.callbacks = &cb;
349 init.user_data = user_data;
350 init.configuration_options = configuration_options;
351
352 error.text = error_buffer;
353 error.text_buffer_size = sizeof(error_buffer);
354
355 mark_point();
356 test_sleep(SLEEP_BEFORE_MG_START);
357 mark_point();
358 ctx = mg_start2(&init, &error);
359 mark_point();
360 if (ctx) {
361 /* Give the server some time to start in the test VM. */
362 /* Don't need to do this if mg_start failed. */
363 test_sleep(SLEEP_AFTER_MG_START);
364 ck_assert_int_eq(error.code, 0);
365 ck_assert_str_eq(error.text, "");
366 } else if (line > 0) {
367 /* mg_start is not supposed to fail anywhere, except for
368 * special tests (for them, line is 0). */
369 ck_abort_msg(
370 "mg_start failed in line %u\nerror %u: %s\nlast message %s\n",
371 line,
372 error.code,
373 error.text,
374 (lastMessage ? lastMessage : "<NULL>"));
375 }
376 mark_point();
377
378 return ctx;
379 }
380
381
382 static void
test_mg_stop(struct mg_context * ctx,unsigned line)383 test_mg_stop(struct mg_context *ctx, unsigned line)
384 {
385 (void)line;
386 #ifdef __MACH__
387 /* For unknown reasons, there are sporadic hangs
388 * for OSX if mark_point is called here */
389 test_sleep(SLEEP_BEFORE_MG_STOP);
390 mg_stop(ctx);
391 test_sleep(SLEEP_AFTER_MG_STOP);
392 #else
393 mark_point();
394 test_sleep(SLEEP_BEFORE_MG_STOP);
395 mark_point();
396 mg_stop(ctx);
397 mark_point();
398 test_sleep(SLEEP_AFTER_MG_STOP);
399 mark_point();
400 #endif
401 }
402
403
404 static void
test_mg_start_stop_http_server_impl(int ipv6,int bound)405 test_mg_start_stop_http_server_impl(int ipv6, int bound)
406 {
407 struct mg_context *ctx;
408 const char *OPTIONS[16];
409 int optcnt = 0;
410 const char *localhost_name = ((ipv6) ? "[::1]" : "127.0.0.1");
411
412 struct mg_callbacks callbacks;
413 char errmsg[256];
414
415 struct mg_connection *client_conn;
416 char client_err[256];
417 const struct mg_response_info *client_ri;
418 int client_res, ret;
419 struct mg_server_port portinfo[8];
420
421 mark_point();
422
423 #if !defined(NO_FILES)
424 OPTIONS[optcnt++] = "document_root";
425 OPTIONS[optcnt++] = ".";
426 #endif
427 OPTIONS[optcnt++] = "listening_ports";
428 if (bound) {
429 OPTIONS[optcnt++] = ((ipv6) ? "[::1]:+8080" : "127.0.0.1:8080");
430 } else {
431 OPTIONS[optcnt++] = ((ipv6) ? "+8080" : "8080");
432 /* Test also tcp_nodelay - this option is not related
433 * to interface binding, it's just tested here in this
434 * combination to keep the number of tests smaller and
435 * the test duration shorter.
436 */
437 OPTIONS[optcnt++] = "tcp_nodelay";
438 OPTIONS[optcnt++] = "1";
439 }
440
441 OPTIONS[optcnt] = 0;
442
443 memset(portinfo, 0, sizeof(portinfo));
444 memset(&callbacks, 0, sizeof(callbacks));
445 memset(errmsg, 0, sizeof(errmsg));
446
447 callbacks.log_message = log_msg_func;
448
449 ctx = test_mg_start(&callbacks, (void *)errmsg, OPTIONS, __LINE__);
450
451 ck_assert_str_eq(errmsg, "");
452 ck_assert(ctx != NULL);
453
454 ret = mg_get_server_ports(ctx, 0, portinfo);
455 ck_assert_int_lt(ret, 0);
456 ck_assert_int_eq(portinfo[0].protocol, 0);
457 ck_assert_int_eq(portinfo[0].port, 0);
458 ck_assert_int_eq(portinfo[0].is_ssl, 0);
459 ck_assert_int_eq(portinfo[0].is_redirect, 0);
460 ck_assert_int_eq(portinfo[1].protocol, 0);
461 ck_assert_int_eq(portinfo[1].port, 0);
462 ck_assert_int_eq(portinfo[1].is_ssl, 0);
463 ck_assert_int_eq(portinfo[1].is_redirect, 0);
464
465 ret = mg_get_server_ports(ctx, 4, portinfo);
466 ck_assert_int_eq(ret, 1);
467 if (ipv6) {
468 ck_assert_int_eq(portinfo[0].protocol, 3);
469 } else {
470 ck_assert_int_eq(portinfo[0].protocol, 1);
471 }
472 ck_assert_int_eq(portinfo[0].port, 8080);
473 ck_assert_int_eq(portinfo[0].is_ssl, 0);
474 ck_assert_int_eq(portinfo[0].is_redirect, 0);
475 ck_assert_int_eq(portinfo[1].protocol, 0);
476 ck_assert_int_eq(portinfo[1].port, 0);
477 ck_assert_int_eq(portinfo[1].is_ssl, 0);
478 ck_assert_int_eq(portinfo[1].is_redirect, 0);
479
480 test_sleep(1);
481
482 /* HTTP 1.0 GET request */
483 memset(client_err, 0, sizeof(client_err));
484 client_conn = mg_connect_client(
485 localhost_name, 8080, 0, client_err, sizeof(client_err));
486
487 ck_assert_str_eq(client_err, "");
488 ck_assert(client_conn != NULL);
489
490 mg_printf(client_conn, "GET / HTTP/1.0\r\n\r\n");
491 client_res =
492 mg_get_response(client_conn, client_err, sizeof(client_err), 10000);
493 ck_assert_int_ge(client_res, 0);
494 ck_assert_str_eq(client_err, "");
495 client_ri = mg_get_response_info(client_conn);
496 ck_assert(client_ri != NULL);
497
498 #if defined(NO_FILES)
499 ck_assert_int_eq(client_ri->status_code, 404);
500 #else
501 ck_assert_int_eq(client_ri->status_code, 200);
502 /* TODO: ck_assert_str_eq(client_ri->request_method, "HTTP/1.0"); */
503 client_res = (int)mg_read(client_conn, client_err, sizeof(client_err));
504 ck_assert_int_gt(client_res, 0);
505 ck_assert_int_le(client_res, sizeof(client_err));
506 #endif
507 mg_close_connection(client_conn);
508
509 test_sleep(1);
510
511 /* HTTP 1.1 GET request */
512 memset(client_err, 0, sizeof(client_err));
513 client_conn = mg_connect_client(
514 localhost_name, 8080, 0, client_err, sizeof(client_err));
515
516 ck_assert_str_eq(client_err, "");
517 ck_assert(client_conn != NULL);
518
519 mg_printf(client_conn, "GET / HTTP/1.1\r\n");
520 mg_printf(client_conn, "Host: localhost:8080\r\n");
521 mg_printf(client_conn, "Connection: close\r\n\r\n");
522 client_res =
523 mg_get_response(client_conn, client_err, sizeof(client_err), 10000);
524 ck_assert_int_ge(client_res, 0);
525 ck_assert_str_eq(client_err, "");
526 client_ri = mg_get_response_info(client_conn);
527 ck_assert(client_ri != NULL);
528
529 #if defined(NO_FILES)
530 ck_assert_int_eq(client_ri->status_code, 404);
531 #else
532 ck_assert_int_eq(client_ri->status_code, 200);
533 /* TODO: ck_assert_str_eq(client_ri->request_method, "HTTP/1.0"); */
534 client_res = (int)mg_read(client_conn, client_err, sizeof(client_err));
535 ck_assert_int_gt(client_res, 0);
536 ck_assert_int_le(client_res, sizeof(client_err));
537 #endif
538 mg_close_connection(client_conn);
539
540 test_sleep(1);
541
542
543 /* HTTP 1.7 GET request - this HTTP version does not exist */
544 memset(client_err, 0, sizeof(client_err));
545 client_conn = mg_connect_client(
546 localhost_name, 8080, 0, client_err, sizeof(client_err));
547
548 ck_assert_str_eq(client_err, "");
549 ck_assert(client_conn != NULL);
550
551 mg_printf(client_conn, "GET / HTTP/1.7\r\n");
552 mg_printf(client_conn, "Host: localhost:8080\r\n");
553 mg_printf(client_conn, "Connection: close\r\n\r\n");
554 client_res =
555 mg_get_response(client_conn, client_err, sizeof(client_err), 10000);
556 ck_assert_int_ge(client_res, 0);
557 ck_assert_str_eq(client_err, "");
558 client_ri = mg_get_response_info(client_conn);
559 ck_assert(client_ri != NULL);
560
561 /* Response must be 505 HTTP Version not supported */
562 ck_assert_int_eq(client_ri->status_code, 505);
563 mg_close_connection(client_conn);
564
565 test_sleep(1);
566
567
568 /* HTTP request with multiline header.
569 * Multiline header are obsolete with RFC 7230 section-3.2.4
570 * and must return "400 Bad Request" */
571 memset(client_err, 0, sizeof(client_err));
572 client_conn = mg_connect_client(
573 localhost_name, 8080, 0, client_err, sizeof(client_err));
574
575 ck_assert_str_eq(client_err, "");
576 ck_assert(client_conn != NULL);
577
578 mg_printf(client_conn, "GET / HTTP/1.1\r\n");
579 mg_printf(client_conn, "Host: localhost:8080\r\n");
580 mg_printf(client_conn, "X-Obsolete-Header: something\r\nfor nothing\r\n");
581 mg_printf(client_conn, "Connection: close\r\n\r\n");
582 client_res =
583 mg_get_response(client_conn, client_err, sizeof(client_err), 10000);
584 ck_assert_int_ge(client_res, 0);
585 ck_assert_str_eq(client_err, "");
586 client_ri = mg_get_response_info(client_conn);
587 ck_assert(client_ri != NULL);
588
589 /* Response must be 400 Bad Request */
590 ck_assert_int_eq(client_ri->status_code, 400);
591 mg_close_connection(client_conn);
592
593 test_sleep(1);
594
595 /* End test */
596 test_mg_stop(ctx, __LINE__);
597 mark_point();
598 }
599
600
START_TEST(test_mg_start_stop_http_server)601 START_TEST(test_mg_start_stop_http_server)
602 {
603 mark_point();
604 test_mg_start_stop_http_server_impl(0, 0);
605 mark_point();
606 test_mg_start_stop_http_server_impl(0, 1);
607 mark_point();
608 }
609 END_TEST
610
611
START_TEST(test_mg_start_stop_http_server_ipv6)612 START_TEST(test_mg_start_stop_http_server_ipv6)
613 {
614 mark_point();
615 #if defined(USE_IPV6)
616 test_mg_start_stop_http_server_impl(1, 0);
617 mark_point();
618 test_mg_start_stop_http_server_impl(1, 1);
619 #endif
620 mark_point();
621 }
622 END_TEST
623
624
START_TEST(test_mg_start_stop_https_server)625 START_TEST(test_mg_start_stop_https_server)
626 {
627 #ifndef NO_SSL
628
629 struct mg_context *ctx;
630
631 struct mg_callbacks callbacks;
632 char errmsg[256];
633
634 const char *OPTIONS[8]; /* initializer list here is rejected by CI test */
635 int opt_idx = 0;
636 const char *ssl_cert = locate_ssl_cert();
637
638 struct mg_connection *client_conn;
639 char client_err[256];
640 const struct mg_response_info *client_ri;
641 int client_res, ret;
642 struct mg_server_port portinfo[8];
643
644 ck_assert(ssl_cert != NULL);
645
646 memset((void *)OPTIONS, 0, sizeof(OPTIONS));
647 #if !defined(NO_FILES)
648 OPTIONS[opt_idx++] = "document_root";
649 OPTIONS[opt_idx++] = ".";
650 #endif
651 OPTIONS[opt_idx++] = "listening_ports";
652 OPTIONS[opt_idx++] = "8080r,8443s";
653 OPTIONS[opt_idx++] = "ssl_certificate";
654 OPTIONS[opt_idx++] = ssl_cert;
655
656 ck_assert_int_le(opt_idx, (int)(sizeof(OPTIONS) / sizeof(OPTIONS[0])));
657 ck_assert(OPTIONS[sizeof(OPTIONS) / sizeof(OPTIONS[0]) - 1] == NULL);
658 ck_assert(OPTIONS[sizeof(OPTIONS) / sizeof(OPTIONS[0]) - 2] == NULL);
659
660 memset(portinfo, 0, sizeof(portinfo));
661 memset(&callbacks, 0, sizeof(callbacks));
662 memset(errmsg, 0, sizeof(errmsg));
663
664 callbacks.log_message = log_msg_func;
665
666 ctx = test_mg_start(&callbacks, (void *)errmsg, OPTIONS, __LINE__);
667
668 ck_assert_str_eq(errmsg, "");
669 ck_assert(ctx != NULL);
670
671 ret = mg_get_server_ports(ctx, 0, portinfo);
672 ck_assert_int_lt(ret, 0);
673 ck_assert_int_eq(portinfo[0].protocol, 0);
674 ck_assert_int_eq(portinfo[0].port, 0);
675 ck_assert_int_eq(portinfo[0].is_ssl, 0);
676 ck_assert_int_eq(portinfo[0].is_redirect, 0);
677 ck_assert_int_eq(portinfo[1].protocol, 0);
678 ck_assert_int_eq(portinfo[1].port, 0);
679 ck_assert_int_eq(portinfo[1].is_ssl, 0);
680 ck_assert_int_eq(portinfo[1].is_redirect, 0);
681
682 ret = mg_get_server_ports(ctx, 4, portinfo);
683 ck_assert_int_eq(ret, 2);
684 ck_assert_int_eq(portinfo[0].protocol, 1);
685 ck_assert_int_eq(portinfo[0].port, 8080);
686 ck_assert_int_eq(portinfo[0].is_ssl, 0);
687 ck_assert_int_eq(portinfo[0].is_redirect, 1);
688 ck_assert_int_eq(portinfo[1].protocol, 1);
689 ck_assert_int_eq(portinfo[1].port, 8443);
690 ck_assert_int_eq(portinfo[1].is_ssl, 1);
691 ck_assert_int_eq(portinfo[1].is_redirect, 0);
692 ck_assert_int_eq(portinfo[2].protocol, 0);
693 ck_assert_int_eq(portinfo[2].port, 0);
694 ck_assert_int_eq(portinfo[2].is_ssl, 0);
695 ck_assert_int_eq(portinfo[2].is_redirect, 0);
696
697 test_sleep(1);
698
699 memset(client_err, 0, sizeof(client_err));
700 client_conn =
701 mg_connect_client("127.0.0.1", 8443, 1, client_err, sizeof(client_err));
702
703 ck_assert_str_eq(client_err, "");
704 ck_assert(client_conn != NULL);
705
706 mg_printf(client_conn, "GET / HTTP/1.0\r\n\r\n");
707 client_res =
708 mg_get_response(client_conn, client_err, sizeof(client_err), 10000);
709 ck_assert_int_ge(client_res, 0);
710 ck_assert_str_eq(client_err, "");
711 client_ri = mg_get_response_info(client_conn);
712 ck_assert(client_ri != NULL);
713
714 #if defined(NO_FILES)
715 ck_assert_int_eq(client_ri->status_code, 404);
716 #else
717 ck_assert_int_eq(client_ri->status_code, 200);
718 /* TODO: ck_assert_str_eq(client_ri->request_method, "HTTP/1.0"); */
719 client_res = (int)mg_read(client_conn, client_err, sizeof(client_err));
720 ck_assert_int_gt(client_res, 0);
721 ck_assert_int_le(client_res, sizeof(client_err));
722 #endif
723 mg_close_connection(client_conn);
724
725 test_sleep(1);
726
727 test_mg_stop(ctx, __LINE__);
728 mark_point();
729 #endif
730 }
731 END_TEST
732
733
START_TEST(test_mg_server_and_client_tls)734 START_TEST(test_mg_server_and_client_tls)
735 {
736 #ifndef NO_SSL
737
738 struct mg_context *ctx;
739
740 int ports_cnt;
741 struct mg_server_port ports[16];
742 struct mg_callbacks callbacks;
743 char errmsg[256];
744
745 struct mg_connection *client_conn;
746 char client_err[256];
747 const struct mg_response_info *client_ri;
748 int client_res;
749 struct mg_client_options client_options;
750
751 const char *OPTIONS[32]; /* initializer list here is rejected by CI test */
752 int opt_idx = 0;
753 char server_cert[256];
754 char client_cert[256];
755 const char *res_dir = locate_resources();
756
757 ck_assert(res_dir != NULL);
758 strcpy(server_cert, res_dir);
759 strcpy(client_cert, res_dir);
760 #ifdef _WIN32
761 strcat(server_cert, "cert\\server.pem");
762 strcat(client_cert, "cert\\client.pem");
763 #else
764 strcat(server_cert, "cert/server.pem");
765 strcat(client_cert, "cert/client.pem");
766 #endif
767
768 memset((void *)OPTIONS, 0, sizeof(OPTIONS));
769 #if !defined(NO_FILES)
770 OPTIONS[opt_idx++] = "document_root";
771 OPTIONS[opt_idx++] = ".";
772 #endif
773 OPTIONS[opt_idx++] = "listening_ports";
774 OPTIONS[opt_idx++] = "8080r,8443s";
775 OPTIONS[opt_idx++] = "ssl_certificate";
776 OPTIONS[opt_idx++] = server_cert;
777 OPTIONS[opt_idx++] = "ssl_verify_peer";
778 OPTIONS[opt_idx++] = "yes";
779 OPTIONS[opt_idx++] = "ssl_ca_file";
780 OPTIONS[opt_idx++] = client_cert;
781
782 ck_assert_int_le(opt_idx, (int)(sizeof(OPTIONS) / sizeof(OPTIONS[0])));
783 ck_assert(OPTIONS[sizeof(OPTIONS) / sizeof(OPTIONS[0]) - 1] == NULL);
784 ck_assert(OPTIONS[sizeof(OPTIONS) / sizeof(OPTIONS[0]) - 2] == NULL);
785
786 memset(ports, 0, sizeof(ports));
787 memset(&callbacks, 0, sizeof(callbacks));
788 memset(errmsg, 0, sizeof(errmsg));
789
790 callbacks.log_message = log_msg_func;
791
792 ctx = test_mg_start(&callbacks, (void *)errmsg, OPTIONS, __LINE__);
793
794 ck_assert_str_eq(errmsg, "");
795 ck_assert(ctx != NULL);
796
797 ports_cnt = mg_get_server_ports(ctx, 16, ports);
798 ck_assert_int_eq(ports_cnt, 2);
799 ck_assert_int_eq(ports[0].protocol, 1);
800 ck_assert_int_eq(ports[0].port, 8080);
801 ck_assert_int_eq(ports[0].is_ssl, 0);
802 ck_assert_int_eq(ports[0].is_redirect, 1);
803 ck_assert_int_eq(ports[1].protocol, 1);
804 ck_assert_int_eq(ports[1].port, 8443);
805 ck_assert_int_eq(ports[1].is_ssl, 1);
806 ck_assert_int_eq(ports[1].is_redirect, 0);
807 ck_assert_int_eq(ports[2].protocol, 0);
808 ck_assert_int_eq(ports[2].port, 0);
809 ck_assert_int_eq(ports[2].is_ssl, 0);
810 ck_assert_int_eq(ports[2].is_redirect, 0);
811
812 test_sleep(1);
813
814 memset(client_err, 0, sizeof(client_err));
815 client_conn =
816 mg_connect_client("127.0.0.1", 8443, 1, client_err, sizeof(client_err));
817
818 /* We tried to connect without client certificate:
819 * Depending on ???, either mg_conn_client failed entirely, returning NULL.
820 * or we do get a connection but get an error when we try to use it.
821 *
822 * MacOS (Version ?), Ubuntu Bionic and Ububtu Eoan allow to connect,
823 * while Ubuntu Xenial, Ubuntu Trusty and Windows test containers at
824 * Travis CI do not. Maybe it is OpenSSL version specific.
825 */
826 #if defined(OPENSSL_API_1_1)
827 if (client_conn) {
828 /* Connect succeeds, but the connection is unusable. */
829 mg_printf(client_conn, "GET / HTTP/1.0\r\n\r\n");
830 client_res =
831 mg_get_response(client_conn, client_err, sizeof(client_err), 10000);
832 ck_assert_int_lt(client_res, 0); /* response is "error" (-1) */
833 ck_assert_str_ne(client_err, "");
834 client_ri = mg_get_response_info(client_conn);
835 if (client_ri) {
836 /* client_ri == NULL is allowed. However, some versions seem to
837 * return non-null, but all elements are NULL. */
838 ck_assert_int_eq(client_ri->status_code, 0);
839 ck_assert_int_eq(client_ri->num_headers, 0);
840 ck_assert_ptr_eq(client_ri->http_version, NULL);
841 client_ri = NULL;
842 }
843 ck_assert(client_ri == NULL);
844
845 mg_close_connection(client_conn);
846 client_conn = NULL;
847 strcpy(client_err,
848 "OpenSSL on MacOS allows to connect without a mandatory client "
849 "certificate, but not data exchange");
850 }
851 #endif
852 ck_assert(client_conn == NULL);
853 ck_assert_str_ne(client_err, "");
854
855 memset(client_err, 0, sizeof(client_err));
856 memset(&client_options, 0, sizeof(client_options));
857 client_options.host = "127.0.0.1";
858 client_options.port = 8443;
859 client_options.client_cert = client_cert;
860 client_options.server_cert = server_cert;
861
862 client_conn = mg_connect_client_secure(&client_options,
863 client_err,
864 sizeof(client_err));
865
866 ck_assert_str_eq(client_err, "");
867 ck_assert(client_conn != NULL);
868
869 mg_printf(client_conn, "GET / HTTP/1.0\r\n\r\n");
870 client_res =
871 mg_get_response(client_conn, client_err, sizeof(client_err), 10000);
872 ck_assert_int_ge(client_res, 0);
873 ck_assert_str_eq(client_err, "");
874 client_ri = mg_get_response_info(client_conn);
875 ck_assert(client_ri != NULL);
876
877 #if defined(NO_FILES)
878 ck_assert_int_eq(client_ri->status_code, 404);
879 #else
880 ck_assert_int_eq(client_ri->status_code, 200);
881 /* TODO: ck_assert_str_eq(client_ri->request_method, "HTTP/1.0"); */
882 client_res = (int)mg_read(client_conn, client_err, sizeof(client_err));
883 ck_assert_int_gt(client_res, 0);
884 ck_assert_int_le(client_res, sizeof(client_err));
885 #endif
886 mg_close_connection(client_conn);
887
888 /* TODO: A client API using a client certificate is missing */
889
890 test_sleep(1);
891
892 test_mg_stop(ctx, __LINE__);
893 #endif
894 mark_point();
895 }
896 END_TEST
897
898
899 static struct mg_context *g_ctx;
900
901 static int
request_test_handler(struct mg_connection * conn,void * cbdata)902 request_test_handler(struct mg_connection *conn, void *cbdata)
903 {
904 int i;
905 char chunk_data[32];
906 const struct mg_request_info *ri;
907 struct mg_context *ctx;
908 void *ud, *cud, *ud2;
909 void *dummy = malloc(1);
910
911 ctx = mg_get_context(conn);
912 ud = mg_get_user_data(ctx);
913 ud2 = mg_get_user_context_data(conn);
914 ri = mg_get_request_info(conn);
915
916 ck_assert(ri != NULL);
917 ck_assert(ctx == g_ctx);
918 ck_assert(ud == &g_ctx);
919 ck_assert(ud == ud2);
920
921 ck_assert(dummy != NULL);
922
923 mg_set_user_connection_data(conn, (void *)&dummy);
924 cud = mg_get_user_connection_data(conn);
925 ck_assert_ptr_eq((void *)cud, (void *)&dummy);
926
927 mg_set_user_connection_data(conn, (void *)NULL);
928 cud = mg_get_user_connection_data(conn);
929 ck_assert_ptr_eq((void *)cud, (void *)NULL);
930
931 free(dummy);
932
933 ck_assert_ptr_eq((void *)cbdata, (void *)(ptrdiff_t)7);
934 strcpy(chunk_data, "123456789A123456789B123456789C");
935
936 mg_printf(conn,
937 "HTTP/1.1 200 OK\r\n"
938 "Transfer-Encoding: chunked\r\n"
939 "Content-Type: text/plain\r\n\r\n");
940
941 for (i = 1; i <= 10; i++) {
942 mg_printf(conn, "%x\r\n", i);
943 mg_write(conn, chunk_data, (unsigned)i);
944 mg_printf(conn, "\r\n");
945 }
946
947 mg_printf(conn, "0\r\n\r\n");
948 mark_point();
949
950 return 1;
951 }
952
953 static char request_handler2_url_expected[128] = {0};
954
955 /* Return the same as request_test_handler using new interfaces */
956 static int
request_test_handler2(struct mg_connection * conn,void * cbdata)957 request_test_handler2(struct mg_connection *conn, void *cbdata)
958 {
959 int i;
960 const char *chunk_data = "123456789A123456789B123456789C";
961 const struct mg_request_info *ri;
962 struct mg_context *ctx;
963 void *ud, *ud2;
964 int err_ret;
965 char url_buffer[128];
966
967 (void)cbdata; /* unused */
968
969 ctx = mg_get_context(conn);
970 ud = mg_get_user_data(ctx);
971 ud2 = mg_get_user_context_data(conn);
972 ri = mg_get_request_info(conn);
973
974 ck_assert(ri != NULL);
975 ck_assert(ctx == g_ctx);
976 ck_assert(ud == &g_ctx);
977 ck_assert(ud == ud2);
978
979 err_ret = mg_get_request_link(NULL,
980 url_buffer,
981 sizeof(url_buffer)); /* param error */
982 ck_assert(err_ret < 0);
983 err_ret =
984 mg_get_request_link(conn, NULL, sizeof(url_buffer)); /* param error */
985 ck_assert(err_ret < 0);
986 err_ret = mg_get_request_link(conn, url_buffer, 0); /* param error */
987 ck_assert(err_ret < 0);
988 err_ret = mg_get_request_link(conn, url_buffer, 5); /* buffer too small */
989 ck_assert(err_ret < 0);
990 err_ret = mg_get_request_link(conn, url_buffer, sizeof(url_buffer));
991 ck_assert(err_ret == 0);
992 ck_assert_str_eq(url_buffer, request_handler2_url_expected);
993
994 mg_send_http_ok(conn, "text/plain", -1);
995
996 for (i = 1; i <= 10; i++) {
997 mg_send_chunk(conn, chunk_data, (unsigned)i);
998 }
999
1000 mg_send_chunk(conn, 0, 0);
1001 mark_point();
1002
1003 return 200;
1004 }
1005
1006
1007 #if defined(USE_WEBSOCKET)
1008 /****************************************************************************/
1009 /* WEBSOCKET SERVER */
1010 /****************************************************************************/
1011 static const char *websocket_welcome_msg = "websocket welcome\n";
1012 static const size_t websocket_welcome_msg_len =
1013 18 /* strlen(websocket_welcome_msg) */;
1014 static const char *websocket_goodbye_msg = "websocket bye\n";
1015 static const size_t websocket_goodbye_msg_len =
1016 14 /* strlen(websocket_goodbye_msg) */;
1017
1018
1019 #if defined(WS_DEBUG_TRACE)
1020 static void
WS_TEST_TRACE(const char * f,...)1021 WS_TEST_TRACE(const char *f, ...)
1022 {
1023 va_list l;
1024 va_start(l, f);
1025 vprintf(f, l);
1026 va_end(l);
1027 }
1028 #else
1029 #define WS_TEST_TRACE(...)
1030 #endif
1031
1032
1033 static int
websock_server_connect(const struct mg_connection * conn,void * udata)1034 websock_server_connect(const struct mg_connection *conn, void *udata)
1035 {
1036 (void)conn;
1037
1038 ck_assert_ptr_eq((void *)udata, (void *)(ptrdiff_t)7531);
1039 WS_TEST_TRACE("Server: Websocket connected\n");
1040 mark_point();
1041
1042 return 0; /* return 0 to accept every connection */
1043 }
1044
1045
1046 static void
websock_server_ready(struct mg_connection * conn,void * udata)1047 websock_server_ready(struct mg_connection *conn, void *udata)
1048 {
1049 ck_assert_ptr_eq((void *)udata, (void *)(ptrdiff_t)7531);
1050 ck_assert_ptr_ne((void *)conn, (void *)NULL);
1051 WS_TEST_TRACE("Server: Websocket ready\n");
1052
1053 /* Send websocket welcome message */
1054 mg_lock_connection(conn);
1055 mg_websocket_write(conn,
1056 MG_WEBSOCKET_OPCODE_TEXT,
1057 websocket_welcome_msg,
1058 websocket_welcome_msg_len);
1059 mg_unlock_connection(conn);
1060
1061 WS_TEST_TRACE("Server: Websocket ready X\n");
1062 mark_point();
1063 }
1064
1065
1066 #define long_ws_buf_len_16 (500)
1067 #define long_ws_buf_len_64 (70000)
1068 static char long_ws_buf[long_ws_buf_len_64];
1069
1070
1071 static int
websock_server_data(struct mg_connection * conn,int bits,char * data,size_t data_len,void * udata)1072 websock_server_data(struct mg_connection *conn,
1073 int bits,
1074 char *data,
1075 size_t data_len,
1076 void *udata)
1077 {
1078 (void)bits;
1079
1080 ck_assert_ptr_eq((void *)udata, (void *)(ptrdiff_t)7531);
1081 WS_TEST_TRACE("Server: Got %u bytes from the client\n", (unsigned)data_len);
1082
1083 if (data_len == 3 && !memcmp(data, "bye", 3)) {
1084 /* Send websocket goodbye message */
1085 mg_lock_connection(conn);
1086 mg_websocket_write(conn,
1087 MG_WEBSOCKET_OPCODE_TEXT,
1088 websocket_goodbye_msg,
1089 websocket_goodbye_msg_len);
1090 mg_unlock_connection(conn);
1091 } else if (data_len == 5 && !memcmp(data, "data1", 5)) {
1092 mg_lock_connection(conn);
1093 mg_websocket_write(conn, MG_WEBSOCKET_OPCODE_TEXT, "ok1", 3);
1094 mg_unlock_connection(conn);
1095 } else if (data_len == 5 && !memcmp(data, "data2", 5)) {
1096 mg_lock_connection(conn);
1097 mg_websocket_write(conn, MG_WEBSOCKET_OPCODE_TEXT, "ok 2", 4);
1098 mg_unlock_connection(conn);
1099 } else if (data_len == 5 && !memcmp(data, "data3", 5)) {
1100 mg_lock_connection(conn);
1101 mg_websocket_write(conn, MG_WEBSOCKET_OPCODE_TEXT, "ok - 3", 6);
1102 mg_unlock_connection(conn);
1103 } else if (data_len == long_ws_buf_len_16) {
1104 ck_assert(memcmp(data, long_ws_buf, long_ws_buf_len_16) == 0);
1105 mg_lock_connection(conn);
1106 mg_websocket_write(conn,
1107 MG_WEBSOCKET_OPCODE_BINARY,
1108 long_ws_buf,
1109 long_ws_buf_len_16);
1110 mg_unlock_connection(conn);
1111 } else if (data_len == long_ws_buf_len_64) {
1112 ck_assert(memcmp(data, long_ws_buf, long_ws_buf_len_64) == 0);
1113 mg_lock_connection(conn);
1114 mg_websocket_write(conn,
1115 MG_WEBSOCKET_OPCODE_BINARY,
1116 long_ws_buf,
1117 long_ws_buf_len_64);
1118 mg_unlock_connection(conn);
1119 } else {
1120
1121 #if defined(__MINGW32__) || defined(__GNUC__)
1122 #pragma GCC diagnostic push
1123 #pragma GCC diagnostic ignored "-Wunreachable-code"
1124 #endif
1125 #ifdef __clang__
1126 #pragma clang diagnostic push
1127 #pragma clang diagnostic ignored "-Wunreachable-code"
1128 #endif
1129
1130 ck_abort_msg("Got unexpected message from websocket client");
1131
1132
1133 return 0;
1134
1135 #ifdef __clang__
1136 #pragma clang diagnostic pop
1137 #endif
1138 #if defined(__MINGW32__) || defined(__GNUC__)
1139 #pragma GCC diagnostic pop
1140 #endif
1141 }
1142 mark_point();
1143
1144 return 1; /* return 1 to keep the connetion open */
1145 }
1146
1147
1148 static void
websock_server_close(const struct mg_connection * conn,void * udata)1149 websock_server_close(const struct mg_connection *conn, void *udata)
1150 {
1151 #ifndef __MACH__
1152 ck_assert_ptr_eq((void *)udata, (void *)(ptrdiff_t)7531);
1153 WS_TEST_TRACE("Server: Close connection\n");
1154
1155 /* Can not send a websocket goodbye message here -
1156 * the connection is already closed */
1157
1158 mark_point();
1159 #endif
1160
1161 (void)conn;
1162 (void)udata;
1163 }
1164
1165
1166 /****************************************************************************/
1167 /* WEBSOCKET CLIENT */
1168 /****************************************************************************/
1169 struct tclient_data {
1170 void *data;
1171 size_t len;
1172 int closed;
1173 int clientId;
1174 };
1175
1176
1177 static int
websocket_client_data_handler(struct mg_connection * conn,int flags,char * data,size_t data_len,void * user_data)1178 websocket_client_data_handler(struct mg_connection *conn,
1179 int flags,
1180 char *data,
1181 size_t data_len,
1182 void *user_data)
1183 {
1184 struct mg_context *ctx = mg_get_context(conn);
1185 struct tclient_data *pclient_data =
1186 (struct tclient_data *)mg_get_user_data(ctx);
1187
1188 ck_assert_ptr_eq(user_data, (void *)pclient_data);
1189
1190 ck_assert(pclient_data != NULL);
1191 ck_assert_int_gt(flags, 128);
1192 ck_assert_int_lt(flags, 128 + 16);
1193 ck_assert((flags == (int)(128 | MG_WEBSOCKET_OPCODE_BINARY))
1194 || (flags == (int)(128 | MG_WEBSOCKET_OPCODE_TEXT)));
1195
1196 if (flags == (int)(128 | MG_WEBSOCKET_OPCODE_TEXT)) {
1197 WS_TEST_TRACE(
1198 "Client %i received %lu bytes text data from server: %.*s\n",
1199 pclient_data->clientId,
1200 (unsigned long)data_len,
1201 (int)data_len,
1202 data);
1203 } else {
1204 WS_TEST_TRACE("Client %i received %lu bytes binary data from\n",
1205 pclient_data->clientId,
1206 (unsigned long)data_len);
1207 }
1208
1209 pclient_data->data = malloc(data_len);
1210 ck_assert(pclient_data->data != NULL);
1211 memcpy(pclient_data->data, data, data_len);
1212 pclient_data->len = data_len;
1213
1214 mark_point();
1215
1216 return 1;
1217 }
1218
1219
1220 static void
websocket_client_close_handler(const struct mg_connection * conn,void * user_data)1221 websocket_client_close_handler(const struct mg_connection *conn,
1222 void *user_data)
1223 {
1224 struct mg_context *ctx = mg_get_context(conn);
1225 struct tclient_data *pclient_data =
1226 (struct tclient_data *)mg_get_user_data(ctx);
1227
1228 #ifndef __MACH__
1229 ck_assert_ptr_eq(user_data, (void *)pclient_data);
1230
1231 ck_assert(pclient_data != NULL);
1232
1233 WS_TEST_TRACE("Client %i: Close handler\n", pclient_data->clientId);
1234 pclient_data->closed++;
1235
1236 mark_point();
1237 #else
1238
1239 (void)user_data;
1240 pclient_data->closed++;
1241
1242 #endif /* __MACH__ */
1243 }
1244
1245 #endif /* USE_WEBSOCKET */
1246
1247
START_TEST(test_request_handlers)1248 START_TEST(test_request_handlers)
1249 {
1250 char ebuf[1024];
1251 struct mg_context *ctx;
1252 struct mg_connection *client_conn;
1253 const struct mg_response_info *client_ri;
1254 char uri[64];
1255 char buf[1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 8];
1256 const char *expected =
1257 "112123123412345123456123456712345678123456789123456789A";
1258 int i;
1259 const char *request = "GET /U7 HTTP/1.0\r\n\r\n";
1260 #if defined(USE_IPV6) && defined(NO_SSL)
1261 const char *HTTP_PORT = "8084,[::]:8086";
1262 short ipv4_port = 8084;
1263 short ipv6_port = 8086;
1264 #elif !defined(USE_IPV6) && defined(NO_SSL)
1265 const char *HTTP_PORT = "8084";
1266 short ipv4_port = 8084;
1267 #elif defined(USE_IPV6) && !defined(NO_SSL)
1268 const char *HTTP_PORT = "8084,[::]:8086,8194r,[::]:8196r,8094s,[::]:8096s";
1269 short ipv4_port = 8084;
1270 short ipv4s_port = 8094;
1271 short ipv4r_port = 8194;
1272 short ipv6_port = 8086;
1273 short ipv6s_port = 8096;
1274 short ipv6r_port = 8196;
1275 #elif !defined(USE_IPV6) && !defined(NO_SSL)
1276 const char *HTTP_PORT = "8084,8194r,8094s";
1277 short ipv4_port = 8084;
1278 short ipv4s_port = 8094;
1279 short ipv4r_port = 8194;
1280 #endif
1281
1282 const char *OPTIONS[16];
1283 const char *opt;
1284 FILE *f;
1285 const char *plain_file_content;
1286 const char *cgi_script_content;
1287 const char *expected_cgi_result;
1288 int opt_idx = 0;
1289 struct stat st;
1290
1291 const char encoded_file_content[] = "\x1f\x8b\x08\x08\xf8"
1292 "\x9d\xcb\x55\x00\x00"
1293 "test_gz.txt"
1294 "\x00\x01\x11\x00\xee\xff"
1295 "zipped text file"
1296 "\x0a\x34\x5f\xcc\x49"
1297 "\x11\x00\x00\x00";
1298 size_t encoded_file_content_len = sizeof(encoded_file_content);
1299
1300
1301 #if !defined(NO_SSL)
1302 const char *ssl_cert = locate_ssl_cert();
1303 #endif
1304
1305 #if defined(USE_WEBSOCKET)
1306 struct tclient_data ws_client1_data = {NULL, 0, 0, 1};
1307 struct tclient_data ws_client2_data = {NULL, 0, 0, 2};
1308 struct tclient_data ws_client3_data = {NULL, 0, 0, 3};
1309 struct tclient_data ws_client4_data = {NULL, 0, 0, 4};
1310 struct mg_connection *ws_client1_conn = NULL;
1311 struct mg_connection *ws_client2_conn = NULL;
1312 struct mg_connection *ws_client3_conn = NULL;
1313 struct mg_connection *ws_client4_conn = NULL;
1314 #endif
1315
1316 char cmd_buf[1024];
1317 char *cgi_env_opt;
1318
1319 const char *server_host = "test.domain";
1320
1321 mark_point();
1322
1323 memset((void *)OPTIONS, 0, sizeof(OPTIONS));
1324 OPTIONS[opt_idx++] = "listening_ports";
1325 OPTIONS[opt_idx++] = HTTP_PORT;
1326 OPTIONS[opt_idx++] = "authentication_domain";
1327 OPTIONS[opt_idx++] = server_host;
1328 #if !defined(NO_FILES)
1329 OPTIONS[opt_idx++] = "document_root";
1330 OPTIONS[opt_idx++] = ".";
1331 #endif
1332 #ifndef NO_SSL
1333 ck_assert(ssl_cert != NULL);
1334 OPTIONS[opt_idx++] = "ssl_certificate";
1335 OPTIONS[opt_idx++] = ssl_cert;
1336 #endif
1337 OPTIONS[opt_idx++] = "cgi_environment";
1338 cgi_env_opt = (char *)calloc(1, 4096 /* CGI_ENVIRONMENT_SIZE */);
1339 ck_assert(cgi_env_opt != NULL);
1340 cgi_env_opt[0] = 'x';
1341 cgi_env_opt[1] = '=';
1342 memset(cgi_env_opt + 2, 'y', 4090); /* Add large env field, so the server
1343 * must reallocate buffers. */
1344 OPTIONS[opt_idx++] = cgi_env_opt;
1345
1346 OPTIONS[opt_idx++] = "num_threads";
1347 OPTIONS[opt_idx++] = "2";
1348
1349
1350 ck_assert_int_le(opt_idx, (int)(sizeof(OPTIONS) / sizeof(OPTIONS[0])));
1351 ck_assert(OPTIONS[sizeof(OPTIONS) / sizeof(OPTIONS[0]) - 1] == NULL);
1352 ck_assert(OPTIONS[sizeof(OPTIONS) / sizeof(OPTIONS[0]) - 2] == NULL);
1353
1354 ctx = test_mg_start(NULL, &g_ctx, OPTIONS, __LINE__);
1355
1356 ck_assert(ctx != NULL);
1357 g_ctx = ctx;
1358
1359 opt = mg_get_option(ctx, "listening_ports");
1360 ck_assert_str_eq(opt, HTTP_PORT);
1361
1362 opt = mg_get_option(ctx, "cgi_environment");
1363 ck_assert_ptr_ne(opt, cgi_env_opt);
1364 ck_assert_int_eq((int)opt[0], (int)cgi_env_opt[0]);
1365 ck_assert_int_eq((int)opt[1], (int)cgi_env_opt[1]);
1366 ck_assert_int_eq((int)opt[2], (int)cgi_env_opt[2]);
1367 ck_assert_int_eq((int)opt[3], (int)cgi_env_opt[3]);
1368 /* full length string compare will reach limit in the implementation
1369 * of the check unit test framework */
1370 {
1371 size_t len_check_1 = strlen(opt);
1372 size_t len_check_2 = strlen(cgi_env_opt);
1373 ck_assert_uint_eq(len_check_1, len_check_2);
1374 }
1375
1376 /* We don't need the original anymore, the server has a private copy */
1377 free(cgi_env_opt);
1378
1379 opt = mg_get_option(ctx, "throttle");
1380 ck_assert_str_eq(opt, "");
1381
1382 opt = mg_get_option(ctx, "unknown_option_name");
1383 ck_assert(opt == NULL);
1384
1385 for (i = 0; i < 1000; i++) {
1386 sprintf(uri, "/U%u", i);
1387 mg_set_request_handler(ctx, uri, request_test_handler, NULL);
1388 }
1389 for (i = 500; i < 800; i++) {
1390 sprintf(uri, "/U%u", i);
1391 mg_set_request_handler(ctx, uri, NULL, (void *)(ptrdiff_t)1);
1392 }
1393 for (i = 600; i >= 0; i--) {
1394 sprintf(uri, "/U%u", i);
1395 mg_set_request_handler(ctx, uri, NULL, (void *)(ptrdiff_t)2);
1396 }
1397 for (i = 750; i <= 1000; i++) {
1398 sprintf(uri, "/U%u", i);
1399 mg_set_request_handler(ctx, uri, NULL, (void *)(ptrdiff_t)3);
1400 }
1401 for (i = 5; i < 9; i++) {
1402 sprintf(uri, "/U%u", i);
1403 mg_set_request_handler(ctx,
1404 uri,
1405 request_test_handler,
1406 (void *)(ptrdiff_t)i);
1407 }
1408
1409 sprintf(request_handler2_url_expected,
1410 "http://%s:%u/handler2",
1411 server_host,
1412 ipv4_port);
1413 mg_set_request_handler(ctx, "/handler2", request_test_handler2, NULL);
1414
1415 #if defined(USE_WEBSOCKET)
1416 mg_set_websocket_handler(ctx,
1417 "/websocket",
1418 websock_server_connect,
1419 websock_server_ready,
1420 websock_server_data,
1421 websock_server_close,
1422 (void *)(ptrdiff_t)7531);
1423 #endif
1424
1425 /* Try to load non existing file */
1426 client_conn = mg_download("localhost",
1427 ipv4_port,
1428 0,
1429 ebuf,
1430 sizeof(ebuf),
1431 "%s",
1432 "GET /file/not/found HTTP/1.0\r\n\r\n");
1433 ck_assert(client_conn != NULL);
1434 client_ri = mg_get_response_info(client_conn);
1435
1436 ck_assert(client_ri != NULL);
1437 ck_assert_int_eq(client_ri->status_code, 404);
1438 mg_close_connection(client_conn);
1439
1440 /* Get data from callback */
1441 client_conn = mg_download(
1442 "localhost", ipv4_port, 0, ebuf, sizeof(ebuf), "%s", request);
1443 ck_assert(client_conn != NULL);
1444 client_ri = mg_get_response_info(client_conn);
1445
1446 ck_assert(client_ri != NULL);
1447 ck_assert_int_eq(client_ri->status_code, 200);
1448 i = mg_read(client_conn, buf, sizeof(buf));
1449 ck_assert_int_eq(i, (int)strlen(expected));
1450 buf[i] = 0;
1451 ck_assert_str_eq(buf, expected);
1452 mg_close_connection(client_conn);
1453
1454 /* Get data from callback using http://127.0.0.1 */
1455 client_conn = mg_download(
1456 "127.0.0.1", ipv4_port, 0, ebuf, sizeof(ebuf), "%s", request);
1457 ck_assert(client_conn != NULL);
1458 client_ri = mg_get_response_info(client_conn);
1459
1460 ck_assert(client_ri != NULL);
1461 ck_assert_int_eq(client_ri->status_code, 200);
1462 i = mg_read(client_conn, buf, sizeof(buf));
1463 if ((i >= 0) && ((size_t)i < sizeof(buf))) {
1464 buf[i] = 0;
1465 } else {
1466 ck_abort_msg(
1467 "ERROR: test_request_handlers: read returned %i (>=0, <%i)",
1468 (int)i,
1469 (int)sizeof(buf));
1470 }
1471 ck_assert((int)i < (int)sizeof(buf));
1472 ck_assert(i > 0);
1473 ck_assert_int_eq(i, (int)strlen(expected));
1474 buf[i] = 0;
1475 ck_assert_str_eq(buf, expected);
1476 mg_close_connection(client_conn);
1477
1478 #if defined(USE_IPV6)
1479 /* Get data from callback using http://[::1] */
1480 client_conn =
1481 mg_download("[::1]", ipv6_port, 0, ebuf, sizeof(ebuf), "%s", request);
1482 ck_assert(client_conn != NULL);
1483 client_ri = mg_get_response_info(client_conn);
1484
1485 ck_assert(client_ri != NULL);
1486 ck_assert_int_eq(client_ri->status_code, 200);
1487 i = mg_read(client_conn, buf, sizeof(buf));
1488 ck_assert_int_eq(i, (int)strlen(expected));
1489 buf[i] = 0;
1490 ck_assert_str_eq(buf, expected);
1491 mg_close_connection(client_conn);
1492 #endif
1493
1494 #if !defined(NO_SSL)
1495 /* Get data from callback using https://127.0.0.1 */
1496 client_conn = mg_download(
1497 "127.0.0.1", ipv4s_port, 1, ebuf, sizeof(ebuf), "%s", request);
1498 ck_assert(client_conn != NULL);
1499 client_ri = mg_get_response_info(client_conn);
1500
1501 ck_assert(client_ri != NULL);
1502 ck_assert_int_eq(client_ri->status_code, 200);
1503 i = mg_read(client_conn, buf, sizeof(buf));
1504 ck_assert_int_eq(i, (int)strlen(expected));
1505 buf[i] = 0;
1506 ck_assert_str_eq(buf, expected);
1507 mg_close_connection(client_conn);
1508
1509 /* Get redirect from callback using http://127.0.0.1 */
1510 client_conn = mg_download(
1511 "127.0.0.1", ipv4r_port, 0, ebuf, sizeof(ebuf), "%s", request);
1512 ck_assert(client_conn != NULL);
1513 client_ri = mg_get_response_info(client_conn);
1514
1515 ck_assert(client_ri != NULL);
1516 if ((client_ri->status_code != 301) && (client_ri->status_code != 302)
1517 && (client_ri->status_code != 303) && (client_ri->status_code != 307)
1518 && (client_ri->status_code != 308)) {
1519 /* expect a 30x redirect code */
1520 ck_abort_msg("Expected a redirect code, got %i",
1521 client_ri->status_code);
1522 }
1523 /*
1524 // A redirect may have a body, or not
1525 i = mg_read(client_conn, buf, sizeof(buf));
1526 ck_assert_int_eq(i, -1);
1527 */
1528 mg_close_connection(client_conn);
1529 #endif
1530
1531 #if defined(USE_IPV6) && !defined(NO_SSL)
1532 /* Get data from callback using https://[::1] */
1533 client_conn =
1534 mg_download("[::1]", ipv6s_port, 1, ebuf, sizeof(ebuf), "%s", request);
1535 ck_assert(client_conn != NULL);
1536 client_ri = mg_get_response_info(client_conn);
1537
1538 ck_assert(client_ri != NULL);
1539 ck_assert_int_eq(client_ri->status_code, 200);
1540 i = mg_read(client_conn, buf, sizeof(buf));
1541 ck_assert_int_eq(i, (int)strlen(expected));
1542 buf[i] = 0;
1543 ck_assert_str_eq(buf, expected);
1544 mg_close_connection(client_conn);
1545
1546 /* Get redirect from callback using http://127.0.0.1 */
1547 client_conn =
1548 mg_download("[::1]", ipv6r_port, 0, ebuf, sizeof(ebuf), "%s", request);
1549 ck_assert(client_conn != NULL);
1550 client_ri = mg_get_response_info(client_conn);
1551
1552 ck_assert(client_ri != NULL);
1553 ck_assert((client_ri->status_code == 301) || (client_ri->status_code == 302)
1554 || (client_ri->status_code == 303)
1555 || (client_ri->status_code == 307)
1556 || (client_ri->status_code == 308)); /* is a redirect code */
1557 /*
1558 // A redirect may have a body, or not
1559 i = mg_read(client_conn, buf, sizeof(buf));
1560 ck_assert_int_eq(i, -1);
1561 */
1562 mg_close_connection(client_conn);
1563 #endif
1564
1565 /* It seems to be impossible to find out what the actual working
1566 * directory of the CI test environment is. Before breaking another
1567 * dozen of builds by trying blindly with different paths, just
1568 * create the file here */
1569 #ifdef _WIN32
1570 f = fopen("test.txt", "wb");
1571 #else
1572 f = fopen("test.txt", "w");
1573 #endif
1574 ck_assert(f != NULL);
1575 plain_file_content = "simple text file\n";
1576 i = (int)strlen(plain_file_content);
1577 ck_assert_int_eq(i, 17);
1578
1579 fwrite(plain_file_content, (size_t)i, 1, f);
1580 fclose(f);
1581
1582 #ifdef _WIN32
1583 f = fopen("test_gz.txt.gz", "wb");
1584 #else
1585 f = fopen("test_gz.txt.gz", "w");
1586 #endif
1587 ck_assert(f != NULL);
1588 ck_assert_uint_ge(encoded_file_content_len, 52);
1589 encoded_file_content_len = 52;
1590 fwrite(encoded_file_content, 1, encoded_file_content_len, f);
1591 fclose(f);
1592
1593 #ifdef _WIN32
1594 f = fopen("test.cgi", "wb");
1595 ck_assert(f != NULL);
1596 cgi_script_content = "#!test.cgi.cmd\r\n";
1597 fwrite(cgi_script_content, strlen(cgi_script_content), 1, f);
1598 fclose(f);
1599 f = fopen("test.cgi.cmd", "w");
1600 cgi_script_content = "@echo off\r\n"
1601 "echo Connection: close\r\n"
1602 "echo Content-Type: text/plain\r\n"
1603 "echo.\r\n"
1604 "echo CGI test\r\n"
1605 "\r\n";
1606 fwrite(cgi_script_content, strlen(cgi_script_content), 1, f);
1607 fclose(f);
1608 #else
1609 f = fopen("test.cgi", "w");
1610 ck_assert(f != NULL);
1611 cgi_script_content = "#!/bin/sh\n\n"
1612 "printf \"Connection: close\\r\\n\"\n"
1613 "printf \"Content-Type: text/plain\\r\\n\"\n"
1614 "printf \"\\r\\n\"\n"
1615 "printf \"CGI test\\r\\n\"\n"
1616 "\n";
1617 (void)fwrite(cgi_script_content, strlen(cgi_script_content), 1, f);
1618 (void)fclose(f);
1619 (void)system("chmod a+x test.cgi");
1620 #endif
1621 expected_cgi_result = "CGI test";
1622
1623 /* Get static data */
1624 client_conn = mg_download("localhost",
1625 ipv4_port,
1626 0,
1627 ebuf,
1628 sizeof(ebuf),
1629 "%s",
1630 "GET /test.txt HTTP/1.0\r\n\r\n");
1631 ck_assert(client_conn != NULL);
1632 client_ri = mg_get_response_info(client_conn);
1633
1634 ck_assert(client_ri != NULL);
1635
1636 #if defined(NO_FILES)
1637 ck_assert_int_eq(client_ri->status_code, 404);
1638 #else
1639 ck_assert_int_eq(client_ri->status_code, 200);
1640 i = mg_read(client_conn, buf, sizeof(buf));
1641 ck_assert_int_eq(i, 17);
1642 if ((i >= 0) && (i < (int)sizeof(buf))) {
1643 buf[i] = 0;
1644 }
1645 ck_assert_str_eq(buf, plain_file_content);
1646 #endif
1647 mg_close_connection(client_conn);
1648
1649
1650 /* Check if CGI test executable exists */
1651 memset(&st, 0, sizeof(st));
1652
1653 #if defined(_WIN32)
1654 /* TODO: not yet available */
1655 sprintf(ebuf, "%scgi_test.cgi", locate_test_exes());
1656 #else
1657 sprintf(ebuf, "%scgi_test.cgi", locate_test_exes());
1658
1659 if (stat(ebuf, &st) != 0) {
1660 char cwd[512];
1661 getcwd(cwd, sizeof(cwd));
1662
1663 fprintf(stderr, "\nFile %s not found\n", ebuf);
1664 fprintf(stderr, "Working directory is %s\n", cwd);
1665 fprintf(stderr,
1666 "This file needs to be compiled manually before "
1667 "starting the test\n");
1668 fprintf(stderr,
1669 "e.g. by gcc unittest/cgi_test.c -o output/cgi_test.cgi\n\n");
1670
1671 /* Abort test with diagnostic message */
1672 ck_abort_msg("Mandatory file %s must be built before starting the test "
1673 "(cwd: %s)",
1674 ebuf,
1675 cwd);
1676 }
1677 #endif
1678
1679
1680 /* Test with CGI test executable */
1681 #if defined(_WIN32)
1682 sprintf(cmd_buf, "copy %s\\cgi_test.cgi cgi_test.exe", locate_test_exes());
1683 #else
1684 sprintf(cmd_buf, "cp %s/cgi_test.cgi cgi_test.cgi", locate_test_exes());
1685 #endif
1686 (void)system(cmd_buf);
1687
1688 #if !defined(NO_CGI) && !defined(NO_FILES) && !defined(_WIN32)
1689 /* TODO: add test for windows, check with POST */
1690 client_conn = mg_download(
1691 "localhost",
1692 ipv4_port,
1693 0,
1694 ebuf,
1695 sizeof(ebuf),
1696 "%s",
1697 "POST /cgi_test.cgi/x/y.z HTTP/1.0\r\nContent-Length: 3\r\n\r\nABC");
1698 ck_assert(client_conn != NULL);
1699 client_ri = mg_get_response_info(client_conn);
1700
1701 ck_assert(client_ri != NULL);
1702 ck_assert_int_eq(client_ri->status_code, 200);
1703 mg_close_connection(client_conn);
1704 #endif
1705
1706 /* Get zipped static data - will not work if Accept-Encoding is not set */
1707 client_conn = mg_download("localhost",
1708 ipv4_port,
1709 0,
1710 ebuf,
1711 sizeof(ebuf),
1712 "%s",
1713 "GET /test_gz.txt HTTP/1.0\r\n\r\n");
1714 ck_assert(client_conn != NULL);
1715 client_ri = mg_get_response_info(client_conn);
1716
1717 ck_assert(client_ri != NULL);
1718 ck_assert_int_eq(client_ri->status_code, 404);
1719 mg_close_connection(client_conn);
1720
1721 /* Get zipped static data - with Accept-Encoding */
1722 client_conn = mg_download(
1723 "localhost",
1724 ipv4_port,
1725 0,
1726 ebuf,
1727 sizeof(ebuf),
1728 "%s",
1729 "GET /test_gz.txt HTTP/1.0\r\nAccept-Encoding: gzip\r\n\r\n");
1730 ck_assert(client_conn != NULL);
1731 client_ri = mg_get_response_info(client_conn);
1732
1733 ck_assert(client_ri != NULL);
1734
1735 #if defined(NO_FILES)
1736 ck_assert_int_eq(client_ri->status_code, 404);
1737 #else
1738 ck_assert_int_eq(client_ri->status_code, 200);
1739 i = mg_read(client_conn, buf, sizeof(buf));
1740 ck_assert_int_eq(i, 52);
1741 if ((i >= 0) && (i < (int)sizeof(buf))) {
1742 buf[i] = 0;
1743 }
1744 ck_assert_int_eq(client_ri->content_length, 52);
1745 ck_assert_str_eq(buf, encoded_file_content);
1746 #endif
1747 mg_close_connection(client_conn);
1748
1749 /* Get CGI generated data */
1750 #if !defined(NO_CGI)
1751 client_conn = mg_download("localhost",
1752 ipv4_port,
1753 0,
1754 ebuf,
1755 sizeof(ebuf),
1756 "%s",
1757 "GET /test.cgi HTTP/1.0\r\n\r\n");
1758 ck_assert(client_conn != NULL);
1759 client_ri = mg_get_response_info(client_conn);
1760
1761 ck_assert(client_ri != NULL);
1762
1763 #if defined(NO_FILES)
1764 ck_assert_int_eq(client_ri->status_code, 404);
1765
1766 (void)expected_cgi_result;
1767 (void)cgi_script_content;
1768 #else
1769 i = mg_read(client_conn, buf, sizeof(buf));
1770 if ((i >= 0) && (i < (int)sizeof(buf))) {
1771 while ((i > 0) && ((buf[i - 1] == '\r') || (buf[i - 1] == '\n'))) {
1772 i--;
1773 }
1774 buf[i] = 0;
1775 }
1776 /* ck_assert_int_eq(i, (int)strlen(expected_cgi_result)); */
1777 ck_assert_str_eq(buf, expected_cgi_result);
1778 ck_assert_int_eq(client_ri->status_code, 200);
1779 mg_close_connection(client_conn);
1780 #endif
1781
1782 #else
1783 (void)expected_cgi_result;
1784 (void)cgi_script_content;
1785 #endif
1786
1787 /* Get directory listing */
1788 client_conn = mg_download("localhost",
1789 ipv4_port,
1790 0,
1791 ebuf,
1792 sizeof(ebuf),
1793 "%s",
1794 "GET / HTTP/1.0\r\n\r\n");
1795 ck_assert(client_conn != NULL);
1796 client_ri = mg_get_response_info(client_conn);
1797
1798 ck_assert(client_ri != NULL);
1799 #if defined(NO_FILES)
1800 ck_assert_int_eq(client_ri->status_code, 404);
1801 #else
1802 ck_assert_int_eq(client_ri->status_code, 200);
1803 i = mg_read(client_conn, buf, sizeof(buf));
1804 ck_assert(i > 6);
1805 buf[6] = 0;
1806 ck_assert_str_eq(buf, "<html>");
1807 #endif
1808 mg_close_connection(client_conn);
1809
1810 /* POST to static file (will not work) */
1811 client_conn = mg_download("localhost",
1812 ipv4_port,
1813 0,
1814 ebuf,
1815 sizeof(ebuf),
1816 "%s",
1817 "POST /test.txt HTTP/1.0\r\n\r\n");
1818 ck_assert(client_conn != NULL);
1819 client_ri = mg_get_response_info(client_conn);
1820
1821 ck_assert(client_ri != NULL);
1822 #if defined(NO_FILES)
1823 ck_assert_int_eq(client_ri->status_code, 404);
1824 #else
1825 ck_assert_int_eq(client_ri->status_code, 405);
1826 i = mg_read(client_conn, buf, sizeof(buf));
1827 ck_assert(i >= 29);
1828 buf[29] = 0;
1829 ck_assert_str_eq(buf, "Error 405: Method Not Allowed");
1830 #endif
1831 mg_close_connection(client_conn);
1832
1833 /* PUT to static file (will not work) */
1834 client_conn = mg_download("localhost",
1835 ipv4_port,
1836 0,
1837 ebuf,
1838 sizeof(ebuf),
1839 "%s",
1840 "PUT /test.txt HTTP/1.0\r\n\r\n");
1841 ck_assert(client_conn != NULL);
1842 client_ri = mg_get_response_info(client_conn);
1843
1844 ck_assert(client_ri != NULL);
1845 #if defined(NO_FILES)
1846 ck_assert_int_eq(client_ri->status_code, 405); /* method not allowed */
1847 #else
1848 ck_assert_int_eq(client_ri->status_code, 401); /* not authorized */
1849 #endif
1850 mg_close_connection(client_conn);
1851
1852
1853 /* Get data from callback using mg_connect_client instead of mg_download */
1854 memset(ebuf, 0, sizeof(ebuf));
1855 client_conn =
1856 mg_connect_client("127.0.0.1", ipv4_port, 0, ebuf, sizeof(ebuf));
1857
1858 ck_assert_str_eq(ebuf, "");
1859 ck_assert(client_conn != NULL);
1860
1861 mg_printf(client_conn, "%s", request);
1862
1863 i = mg_get_response(client_conn, ebuf, sizeof(ebuf), 10000);
1864 ck_assert_int_ge(i, 0);
1865 ck_assert_str_eq(ebuf, "");
1866
1867 client_ri = mg_get_response_info(client_conn);
1868
1869 ck_assert(client_ri != NULL);
1870 ck_assert_int_eq(client_ri->status_code, 200);
1871 i = mg_read(client_conn, buf, sizeof(buf));
1872 ck_assert_int_eq(i, (int)strlen(expected));
1873 buf[i] = 0;
1874 ck_assert_str_eq(buf, expected);
1875 mg_close_connection(client_conn);
1876
1877 /* Get data from callback using mg_connect_client and absolute URI */
1878 memset(ebuf, 0, sizeof(ebuf));
1879 client_conn =
1880 mg_connect_client("localhost", ipv4_port, 0, ebuf, sizeof(ebuf));
1881
1882 ck_assert_str_eq(ebuf, "");
1883 ck_assert(client_conn != NULL);
1884
1885 mg_printf(client_conn,
1886 "GET http://test.domain:%d/U7 HTTP/1.0\r\n\r\n",
1887 ipv4_port);
1888
1889 i = mg_get_response(client_conn, ebuf, sizeof(ebuf), 10000);
1890 ck_assert_int_ge(i, 0);
1891 ck_assert_str_eq(ebuf, "");
1892
1893 client_ri = mg_get_response_info(client_conn);
1894
1895 ck_assert(client_ri != NULL);
1896 ck_assert_int_eq(client_ri->status_code, 200);
1897 i = mg_read(client_conn, buf, sizeof(buf));
1898 ck_assert_int_eq(i, (int)strlen(expected));
1899 buf[i] = 0;
1900 ck_assert_str_eq(buf, expected);
1901 mg_close_connection(client_conn);
1902
1903 /* Get data from callback using mg_connect_client and absolute URI with a
1904 * sub-domain */
1905 memset(ebuf, 0, sizeof(ebuf));
1906 client_conn =
1907 mg_connect_client("localhost", ipv4_port, 0, ebuf, sizeof(ebuf));
1908
1909 ck_assert_str_eq(ebuf, "");
1910 ck_assert(client_conn != NULL);
1911
1912 mg_printf(client_conn,
1913 "GET http://subdomain.test.domain:%d/U7 HTTP/1.0\r\n\r\n",
1914 ipv4_port);
1915
1916 i = mg_get_response(client_conn, ebuf, sizeof(ebuf), 10000);
1917 ck_assert_int_ge(i, 0);
1918 ck_assert_str_eq(ebuf, "");
1919
1920 client_ri = mg_get_response_info(client_conn);
1921
1922 ck_assert(client_ri != NULL);
1923 ck_assert_int_eq(client_ri->status_code, 200);
1924 i = mg_read(client_conn, buf, sizeof(buf));
1925 ck_assert_int_eq(i, (int)strlen(expected));
1926 buf[i] = 0;
1927 ck_assert_str_eq(buf, expected);
1928 mg_close_connection(client_conn);
1929
1930 /* Get data from handler2 */
1931 client_conn =
1932 mg_connect_client("localhost", ipv4_port, 0, ebuf, sizeof(ebuf));
1933
1934 ck_assert_str_eq(ebuf, "");
1935 ck_assert(client_conn != NULL);
1936
1937 mg_printf(client_conn,
1938 "GET /handler2 HTTP/1.1\r\n"
1939 "Host: %s\r\n"
1940 "\r\n",
1941 server_host);
1942
1943 i = mg_get_response(client_conn, ebuf, sizeof(ebuf), 10000);
1944 ck_assert_int_ge(i, 0);
1945 ck_assert_str_eq(ebuf, "");
1946
1947 client_ri = mg_get_response_info(client_conn);
1948
1949 ck_assert(client_ri != NULL);
1950 ck_assert_int_eq(client_ri->status_code, 200);
1951 i = mg_read(client_conn, buf, sizeof(buf));
1952 ck_assert_int_eq(i, (int)strlen(expected));
1953 buf[i] = 0;
1954 ck_assert_str_eq(buf, expected);
1955 mg_close_connection(client_conn);
1956
1957 /* Get data non existing handler (will return 404) */
1958 client_conn =
1959 mg_connect_client("localhost", ipv4_port, 0, ebuf, sizeof(ebuf));
1960
1961 ck_assert_str_eq(ebuf, "");
1962 ck_assert(client_conn != NULL);
1963
1964 mg_printf(client_conn,
1965 "GET /unknown_url HTTP/1.1\r\n"
1966 "Host: localhost:%u\r\n"
1967 "\r\n",
1968 ipv4_port);
1969
1970 i = mg_get_response(client_conn, ebuf, sizeof(ebuf), 10000);
1971 ck_assert_int_ge(i, 0);
1972 ck_assert_str_eq(ebuf, "");
1973
1974 client_ri = mg_get_response_info(client_conn);
1975
1976 ck_assert(client_ri != NULL);
1977 ck_assert_int_eq(client_ri->status_code, 404);
1978 mg_close_connection(client_conn);
1979
1980 /* Get data from handler2, but only read a part of it */
1981 client_conn =
1982 mg_connect_client("localhost", ipv4_port, 0, ebuf, sizeof(ebuf));
1983
1984 ck_assert_str_eq(ebuf, "");
1985 ck_assert(client_conn != NULL);
1986
1987 mg_printf(client_conn,
1988 "GET /handler2 HTTP/1.1\r\n"
1989 "Host: localhost:%u\r\n"
1990 "\r\n",
1991 ipv4_port);
1992
1993 i = mg_get_response(client_conn, ebuf, sizeof(ebuf), 10000);
1994 ck_assert_int_ge(i, 0);
1995 ck_assert_str_eq(ebuf, "");
1996
1997 client_ri = mg_get_response_info(client_conn);
1998
1999 ck_assert(client_ri != NULL);
2000 ck_assert_int_eq(client_ri->status_code, 200);
2001 i = mg_read(client_conn, buf, 7);
2002 ck_assert_int_eq(i, 7);
2003 ck_assert(0 == memcmp(buf, expected, 7));
2004 mg_close_connection(client_conn);
2005
2006
2007 /* Websocket test */
2008 #if defined(USE_WEBSOCKET)
2009 /* Then connect a first client */
2010 ws_client1_conn =
2011 mg_connect_websocket_client("localhost",
2012 ipv4_port,
2013 0,
2014 ebuf,
2015 sizeof(ebuf),
2016 "/websocket",
2017 NULL,
2018 websocket_client_data_handler,
2019 websocket_client_close_handler,
2020 &ws_client1_data);
2021
2022 ck_assert(ws_client1_conn != NULL);
2023
2024 wait_not_null(
2025 &(ws_client1_data.data)); /* Wait for the websocket welcome message */
2026 ck_assert_int_eq(ws_client1_data.closed, 0);
2027 ck_assert_int_eq(ws_client2_data.closed, 0);
2028 ck_assert_int_eq(ws_client3_data.closed, 0);
2029 ck_assert(ws_client2_data.data == NULL);
2030 ck_assert_uint_eq(ws_client2_data.len, 0);
2031 ck_assert(ws_client1_data.data != NULL);
2032 ck_assert_uint_eq(ws_client1_data.len, websocket_welcome_msg_len);
2033 ck_assert(!memcmp(ws_client1_data.data,
2034 websocket_welcome_msg,
2035 websocket_welcome_msg_len));
2036 free(ws_client1_data.data);
2037 ws_client1_data.data = NULL;
2038 ws_client1_data.len = 0;
2039
2040 mg_websocket_client_write(ws_client1_conn,
2041 MG_WEBSOCKET_OPCODE_TEXT,
2042 "data1",
2043 5);
2044
2045 wait_not_null(&(
2046 ws_client1_data.data)); /* Wait for the websocket acknowledge message */
2047 ck_assert_int_eq(ws_client1_data.closed, 0);
2048 ck_assert_int_eq(ws_client2_data.closed, 0);
2049 ck_assert(ws_client2_data.data == NULL);
2050 ck_assert_uint_eq(ws_client2_data.len, 0);
2051 ck_assert(ws_client1_data.data != NULL);
2052 ck_assert_uint_eq(ws_client1_data.len, 3);
2053 ck_assert(!memcmp(ws_client1_data.data, "ok1", 3));
2054 free(ws_client1_data.data);
2055 ws_client1_data.data = NULL;
2056 ws_client1_data.len = 0;
2057
2058 /* Now connect a second client */
2059 #if defined(USE_IPV6)
2060 ws_client2_conn =
2061 mg_connect_websocket_client("[::1]",
2062 ipv6_port,
2063 0,
2064 ebuf,
2065 sizeof(ebuf),
2066 "/websocket",
2067 NULL,
2068 websocket_client_data_handler,
2069 websocket_client_close_handler,
2070 &ws_client2_data);
2071 #else
2072 ws_client2_conn =
2073 mg_connect_websocket_client("127.0.0.1",
2074 ipv4_port,
2075 0,
2076 ebuf,
2077 sizeof(ebuf),
2078 "/websocket",
2079 NULL,
2080 websocket_client_data_handler,
2081 websocket_client_close_handler,
2082 &ws_client2_data);
2083 #endif
2084 ck_assert(ws_client2_conn != NULL);
2085
2086 wait_not_null(
2087 &(ws_client2_data.data)); /* Wait for the websocket welcome message */
2088 ck_assert(ws_client1_data.closed == 0);
2089 ck_assert(ws_client2_data.closed == 0);
2090 ck_assert(ws_client1_data.data == NULL);
2091 ck_assert(ws_client1_data.len == 0);
2092 ck_assert(ws_client2_data.data != NULL);
2093 ck_assert(ws_client2_data.len == websocket_welcome_msg_len);
2094 ck_assert(!memcmp(ws_client2_data.data,
2095 websocket_welcome_msg,
2096 websocket_welcome_msg_len));
2097 free(ws_client2_data.data);
2098 ws_client2_data.data = NULL;
2099 ws_client2_data.len = 0;
2100
2101 mg_websocket_client_write(ws_client1_conn,
2102 MG_WEBSOCKET_OPCODE_TEXT,
2103 "data2",
2104 5);
2105
2106 wait_not_null(&(
2107 ws_client1_data.data)); /* Wait for the websocket acknowledge message */
2108
2109 ck_assert(ws_client1_data.closed == 0);
2110 ck_assert(ws_client2_data.closed == 0);
2111 ck_assert(ws_client2_data.data == NULL);
2112 ck_assert(ws_client2_data.len == 0);
2113 ck_assert(ws_client1_data.data != NULL);
2114 ck_assert(ws_client1_data.len == 4);
2115 ck_assert(!memcmp(ws_client1_data.data, "ok 2", 4));
2116 free(ws_client1_data.data);
2117 ws_client1_data.data = NULL;
2118 ws_client1_data.len = 0;
2119
2120 mg_websocket_client_write(ws_client1_conn,
2121 MG_WEBSOCKET_OPCODE_TEXT,
2122 "bye",
2123 3);
2124
2125 wait_not_null(
2126 &(ws_client1_data.data)); /* Wait for the websocket goodbye message */
2127
2128 ck_assert(ws_client1_data.closed == 0);
2129 ck_assert(ws_client2_data.closed == 0);
2130 ck_assert(ws_client2_data.data == NULL);
2131 ck_assert(ws_client2_data.len == 0);
2132 ck_assert(ws_client1_data.data != NULL);
2133 ck_assert(ws_client1_data.len == websocket_goodbye_msg_len);
2134 ck_assert(!memcmp(ws_client1_data.data,
2135 websocket_goodbye_msg,
2136 websocket_goodbye_msg_len));
2137 free(ws_client1_data.data);
2138 ws_client1_data.data = NULL;
2139 ws_client1_data.len = 0;
2140
2141 ck_assert(ws_client1_data.closed == 0); /* Not closed */
2142
2143 mg_close_connection(ws_client1_conn);
2144
2145 test_sleep(3); /* Won't get any message */
2146
2147 ck_assert(ws_client1_data.closed == 1); /* Closed */
2148
2149 ck_assert(ws_client2_data.closed == 0);
2150 ck_assert(ws_client1_data.data == NULL);
2151 ck_assert(ws_client1_data.len == 0);
2152 ck_assert(ws_client2_data.data == NULL);
2153 ck_assert(ws_client2_data.len == 0);
2154
2155 mg_websocket_client_write(ws_client2_conn,
2156 MG_WEBSOCKET_OPCODE_TEXT,
2157 "bye",
2158 3);
2159
2160 wait_not_null(
2161 &(ws_client2_data.data)); /* Wait for the websocket goodbye message */
2162
2163 ck_assert(ws_client1_data.closed == 1);
2164 ck_assert(ws_client2_data.closed == 0);
2165 ck_assert(ws_client1_data.data == NULL);
2166 ck_assert(ws_client1_data.len == 0);
2167 ck_assert(ws_client2_data.data != NULL);
2168 ck_assert(ws_client2_data.len == websocket_goodbye_msg_len);
2169 ck_assert(!memcmp(ws_client2_data.data,
2170 websocket_goodbye_msg,
2171 websocket_goodbye_msg_len));
2172 free(ws_client2_data.data);
2173 ws_client2_data.data = NULL;
2174 ws_client2_data.len = 0;
2175
2176 mg_close_connection(ws_client2_conn);
2177
2178 test_sleep(3); /* Won't get any message */
2179
2180 ck_assert(ws_client1_data.closed == 1);
2181 ck_assert(ws_client2_data.closed == 1);
2182 ck_assert(ws_client1_data.data == NULL);
2183 ck_assert(ws_client1_data.len == 0);
2184 ck_assert(ws_client2_data.data == NULL);
2185 ck_assert(ws_client2_data.len == 0);
2186
2187 /* Connect client 3 */
2188 ws_client3_conn =
2189 mg_connect_websocket_client("localhost",
2190 #if defined(NO_SSL)
2191 ipv4_port,
2192 0,
2193 #else
2194 ipv4s_port,
2195 1,
2196 #endif
2197 ebuf,
2198 sizeof(ebuf),
2199 "/websocket",
2200 NULL,
2201 websocket_client_data_handler,
2202 websocket_client_close_handler,
2203 &ws_client3_data);
2204
2205 ck_assert(ws_client3_conn != NULL);
2206
2207 wait_not_null(
2208 &(ws_client3_data.data)); /* Wait for the websocket welcome message */
2209 ck_assert(ws_client1_data.closed == 1);
2210 ck_assert(ws_client2_data.closed == 1);
2211 ck_assert(ws_client3_data.closed == 0);
2212 ck_assert(ws_client1_data.data == NULL);
2213 ck_assert(ws_client1_data.len == 0);
2214 ck_assert(ws_client2_data.data == NULL);
2215 ck_assert(ws_client2_data.len == 0);
2216 ck_assert(ws_client3_data.data != NULL);
2217 ck_assert(ws_client3_data.len == websocket_welcome_msg_len);
2218 ck_assert(!memcmp(ws_client3_data.data,
2219 websocket_welcome_msg,
2220 websocket_welcome_msg_len));
2221 free(ws_client3_data.data);
2222 ws_client3_data.data = NULL;
2223 ws_client3_data.len = 0;
2224
2225 /* Write long data (16 bit size header) */
2226 mg_websocket_client_write(ws_client3_conn,
2227 MG_WEBSOCKET_OPCODE_BINARY,
2228 long_ws_buf,
2229 long_ws_buf_len_16);
2230
2231 /* Wait for the response */
2232 wait_not_null(&(ws_client3_data.data));
2233
2234 ck_assert_int_eq((int)ws_client3_data.len, (int)long_ws_buf_len_16);
2235 ck_assert(!memcmp(ws_client3_data.data, long_ws_buf, long_ws_buf_len_16));
2236 free(ws_client3_data.data);
2237 ws_client3_data.data = NULL;
2238 ws_client3_data.len = 0;
2239
2240 /* Write long data (64 bit size header) */
2241 mg_websocket_client_write(ws_client3_conn,
2242 MG_WEBSOCKET_OPCODE_BINARY,
2243 long_ws_buf,
2244 long_ws_buf_len_64);
2245
2246 /* Wait for the response */
2247 wait_not_null(&(ws_client3_data.data));
2248
2249 ck_assert_int_eq((int)ws_client3_data.len, (int)long_ws_buf_len_64);
2250 ck_assert(!memcmp(ws_client3_data.data, long_ws_buf, long_ws_buf_len_64));
2251 free(ws_client3_data.data);
2252 ws_client3_data.data = NULL;
2253 ws_client3_data.len = 0;
2254
2255 /* Disconnect client 3 */
2256 ck_assert(ws_client3_data.closed == 0);
2257 mg_close_connection(ws_client3_conn);
2258 ck_assert(ws_client3_data.closed == 1);
2259
2260 /* Connect client 4 */
2261 ws_client4_conn =
2262 mg_connect_websocket_client("localhost",
2263 #if defined(NO_SSL)
2264 ipv4_port,
2265 0,
2266 #else
2267 ipv4s_port,
2268 1,
2269 #endif
2270 ebuf,
2271 sizeof(ebuf),
2272 "/websocket",
2273 NULL,
2274 websocket_client_data_handler,
2275 websocket_client_close_handler,
2276 &ws_client4_data);
2277
2278 ck_assert(ws_client4_conn != NULL);
2279
2280 wait_not_null(
2281 &(ws_client4_data.data)); /* Wait for the websocket welcome message */
2282 ck_assert(ws_client1_data.closed == 1);
2283 ck_assert(ws_client2_data.closed == 1);
2284 ck_assert(ws_client3_data.closed == 1);
2285 ck_assert(ws_client4_data.closed == 0);
2286 ck_assert(ws_client4_data.data != NULL);
2287 ck_assert(ws_client4_data.len == websocket_welcome_msg_len);
2288 ck_assert(!memcmp(ws_client4_data.data,
2289 websocket_welcome_msg,
2290 websocket_welcome_msg_len));
2291 free(ws_client4_data.data);
2292 ws_client4_data.data = NULL;
2293 ws_client4_data.len = 0;
2294
2295 /* stop the server without closing this connection */
2296
2297 #endif
2298
2299 /* Close the server */
2300 g_ctx = NULL;
2301 test_mg_stop(ctx, __LINE__);
2302 mark_point();
2303
2304 #if defined(USE_WEBSOCKET)
2305 for (i = 0; i < 100; i++) {
2306 test_sleep(1);
2307 if (ws_client3_data.closed != 0) {
2308 mark_point();
2309 break;
2310 }
2311 }
2312
2313 ck_assert_int_eq(ws_client4_data.closed, 1);
2314
2315 /* Free data in ws_client4_conn */
2316 mg_close_connection(ws_client4_conn);
2317
2318 #endif
2319 mark_point();
2320 }
2321 END_TEST
2322
2323
2324 static int g_field_found_return = -999;
2325
2326 static int
field_found(const char * key,const char * filename,char * path,size_t pathlen,void * user_data)2327 field_found(const char *key,
2328 const char *filename,
2329 char *path,
2330 size_t pathlen,
2331 void *user_data)
2332 {
2333 ck_assert_ptr_ne(key, NULL);
2334 ck_assert_ptr_ne(filename, NULL);
2335 ck_assert_ptr_ne(path, NULL);
2336 ck_assert_uint_gt(pathlen, 128);
2337 ck_assert_ptr_eq(user_data, (void *)&g_field_found_return);
2338
2339 ck_assert((g_field_found_return == MG_FORM_FIELD_STORAGE_GET)
2340 || (g_field_found_return == MG_FORM_FIELD_STORAGE_STORE)
2341 || (g_field_found_return == MG_FORM_FIELD_STORAGE_SKIP)
2342 || (g_field_found_return == MG_FORM_FIELD_STORAGE_ABORT));
2343
2344 ck_assert_str_ne(key, "dontread");
2345
2346 if (!strcmp(key, "break_field_handler")) {
2347 return MG_FORM_FIELD_STORAGE_ABORT;
2348 }
2349 if (!strcmp(key, "continue_field_handler")) {
2350 return MG_FORM_FIELD_STORAGE_SKIP;
2351 }
2352
2353 if (g_field_found_return == MG_FORM_FIELD_STORAGE_STORE) {
2354 strncpy(path, key, pathlen - 8);
2355 strcat(path, ".txt");
2356 }
2357
2358 mark_point();
2359
2360 return g_field_found_return;
2361 }
2362
2363
2364 static int g_field_step;
2365
2366 static int
field_get(const char * key,const char * value_untruncated,size_t valuelen,void * user_data)2367 field_get(const char *key,
2368 const char *value_untruncated,
2369 size_t valuelen,
2370 void *user_data)
2371 {
2372 /* Copy the untruncated value, so string compare functions can be used. */
2373 /* The check unit test library does not have build in memcmp functions. */
2374 char *value = (char *)malloc(valuelen + 1);
2375 ck_assert(value != NULL);
2376 memcpy(value, value_untruncated, valuelen);
2377 value[valuelen] = 0;
2378
2379 ck_assert_ptr_eq(user_data, (void *)&g_field_found_return);
2380 ck_assert_int_ge(g_field_step, 0);
2381
2382 ++g_field_step;
2383 switch (g_field_step) {
2384 case 1:
2385 ck_assert_str_eq(key, "textin");
2386 ck_assert_uint_eq(valuelen, 4);
2387 ck_assert_str_eq(value, "text");
2388 break;
2389 case 2:
2390 ck_assert_str_eq(key, "passwordin");
2391 ck_assert_uint_eq(valuelen, 0);
2392 ck_assert_str_eq(value, "");
2393 break;
2394 case 3:
2395 ck_assert_str_eq(key, "radio1");
2396 ck_assert_uint_eq(valuelen, 4);
2397 ck_assert_str_eq(value, "val1");
2398 break;
2399 case 4:
2400 ck_assert_str_eq(key, "radio2");
2401 ck_assert_uint_eq(valuelen, 4);
2402 ck_assert_str_eq(value, "val1");
2403 break;
2404 case 5:
2405 ck_assert_str_eq(key, "check1");
2406 ck_assert_uint_eq(valuelen, 4);
2407 ck_assert_str_eq(value, "val1");
2408 break;
2409 case 6:
2410 ck_assert_str_eq(key, "numberin");
2411 ck_assert_uint_eq(valuelen, 1);
2412 ck_assert_str_eq(value, "1");
2413 break;
2414 case 7:
2415 ck_assert_str_eq(key, "datein");
2416 ck_assert_uint_eq(valuelen, 8);
2417 ck_assert_str_eq(value, "1.1.2016");
2418 break;
2419 case 8:
2420 ck_assert_str_eq(key, "colorin");
2421 ck_assert_uint_eq(valuelen, 7);
2422 ck_assert_str_eq(value, "#80ff00");
2423 break;
2424 case 9:
2425 ck_assert_str_eq(key, "rangein");
2426 ck_assert_uint_eq(valuelen, 1);
2427 ck_assert_str_eq(value, "3");
2428 break;
2429 case 10:
2430 ck_assert_str_eq(key, "monthin");
2431 ck_assert_uint_eq(valuelen, 0);
2432 ck_assert_str_eq(value, "");
2433 break;
2434 case 11:
2435 ck_assert_str_eq(key, "weekin");
2436 ck_assert_uint_eq(valuelen, 0);
2437 ck_assert_str_eq(value, "");
2438 break;
2439 case 12:
2440 ck_assert_str_eq(key, "timein");
2441 ck_assert_uint_eq(valuelen, 0);
2442 ck_assert_str_eq(value, "");
2443 break;
2444 case 13:
2445 ck_assert_str_eq(key, "datetimen");
2446 ck_assert_uint_eq(valuelen, 0);
2447 ck_assert_str_eq(value, "");
2448 break;
2449 case 14:
2450 ck_assert_str_eq(key, "datetimelocalin");
2451 ck_assert_uint_eq(valuelen, 0);
2452 ck_assert_str_eq(value, "");
2453 break;
2454 case 15:
2455 ck_assert_str_eq(key, "emailin");
2456 ck_assert_uint_eq(valuelen, 0);
2457 ck_assert_str_eq(value, "");
2458 break;
2459 case 16:
2460 ck_assert_str_eq(key, "searchin");
2461 ck_assert_uint_eq(valuelen, 0);
2462 ck_assert_str_eq(value, "");
2463 break;
2464 case 17:
2465 ck_assert_str_eq(key, "telin");
2466 ck_assert_uint_eq(valuelen, 0);
2467 ck_assert_str_eq(value, "");
2468 break;
2469 case 18:
2470 ck_assert_str_eq(key, "urlin");
2471 ck_assert_uint_eq(valuelen, 0);
2472 ck_assert_str_eq(value, "");
2473 break;
2474 case 19:
2475 ck_assert_str_eq(key, "filein");
2476 ck_assert_uint_eq(valuelen, 0);
2477 ck_assert_str_eq(value, "");
2478 break;
2479 case 20:
2480 ck_assert_str_eq(key, "filesin");
2481 ck_assert_uint_eq(valuelen, 0);
2482 ck_assert_str_eq(value, "");
2483 break;
2484 case 21:
2485 ck_assert_str_eq(key, "selectin");
2486 ck_assert_uint_eq(valuelen, 4);
2487 ck_assert_str_eq(value, "opt1");
2488 break;
2489 case 22:
2490 ck_assert_str_eq(key, "message");
2491 ck_assert_uint_eq(valuelen, 23);
2492 ck_assert_str_eq(value, "Text area default text.");
2493 break;
2494 default:
2495 ck_abort_msg("field_get called with g_field_step == %i",
2496 (int)g_field_step);
2497 }
2498
2499 free(value);
2500 mark_point();
2501
2502 return 0;
2503 }
2504
2505
2506 static const char *myfile_content = "Content of myfile.txt\r\n";
2507 static const int myfile_content_rep = 500;
2508 static int myfile_content_len = 23; /* (int)strlen(myfile_content); */
2509
2510
2511 static int
field_store(const char * path,long long file_size,void * user_data)2512 field_store(const char *path, long long file_size, void *user_data)
2513 {
2514 FILE *f;
2515
2516 ck_assert_int_eq(myfile_content_len, 23);
2517 ck_assert_int_eq(myfile_content_len, (int)strlen(myfile_content));
2518
2519 ck_assert_ptr_eq(user_data, (void *)&g_field_found_return);
2520 ck_assert_int_ge(g_field_step, 100);
2521
2522 ++g_field_step;
2523 switch (g_field_step) {
2524 case 101:
2525 ck_assert_str_eq(path, "storeme.txt");
2526 ck_assert_int_eq(file_size, 9);
2527 f = fopen(path, "r");
2528 ck_assert_ptr_ne(f, NULL);
2529 if (f) {
2530 char buf[32] = {0};
2531 int i = (int)fread(buf, 1, sizeof(buf) - 1, f);
2532 ck_assert_int_eq(i, 9);
2533 fclose(f);
2534 ck_assert_str_eq(buf, "storetest");
2535 }
2536 break;
2537 case 102:
2538 ck_assert_str_eq(path, "file2store.txt");
2539 ck_assert_int_eq(myfile_content_len, (int)strlen(myfile_content));
2540 ck_assert_int_eq(file_size, myfile_content_len * myfile_content_rep);
2541 #ifdef _WIN32
2542 f = fopen(path, "rb");
2543 #else
2544 f = fopen(path, "r");
2545 #endif
2546 ck_assert_ptr_ne(f, NULL);
2547 if (f) {
2548 char buf[32] = {0};
2549 int r, i;
2550 for (r = 0; r < myfile_content_rep; r++) {
2551 i = (int)fread(buf, 1, (size_t)myfile_content_len, f);
2552 ck_assert_int_eq(i, myfile_content_len);
2553 ck_assert_str_eq(buf, myfile_content);
2554 }
2555 i = (int)fread(buf, 1, (size_t)myfile_content_len, f);
2556 ck_assert_int_eq(i, 0);
2557 fclose(f);
2558 }
2559 break;
2560 default:
2561 ck_abort_msg("field_get called with g_field_step == %i",
2562 (int)g_field_step);
2563 }
2564 mark_point();
2565
2566 return 0;
2567 }
2568
2569
2570 static int
FormGet(struct mg_connection * conn,void * cbdata)2571 FormGet(struct mg_connection *conn, void *cbdata)
2572 {
2573 const struct mg_request_info *req_info = mg_get_request_info(conn);
2574 int ret;
2575 struct mg_form_data_handler fdh = {field_found, field_get, NULL, NULL};
2576
2577 (void)cbdata;
2578
2579 ck_assert(req_info != NULL);
2580
2581 mg_printf(conn, "HTTP/1.0 200 OK\r\nContent-Type: text/plain\r\n\r\n");
2582 fdh.user_data = (void *)&g_field_found_return;
2583
2584 /* Call the form handler */
2585 g_field_step = 0;
2586 g_field_found_return = MG_FORM_FIELD_STORAGE_GET;
2587 ret = mg_handle_form_request(conn, &fdh);
2588 g_field_found_return = -888;
2589 ck_assert_int_eq(ret, 22);
2590 ck_assert_int_eq(g_field_step, 22);
2591 mg_printf(conn, "%i\r\n", ret);
2592 g_field_step = 1000;
2593
2594 mark_point();
2595
2596 return 1;
2597 }
2598
2599
2600 static int
FormStore(struct mg_connection * conn,void * cbdata,int ret_expected,int field_step_expected)2601 FormStore(struct mg_connection *conn,
2602 void *cbdata,
2603 int ret_expected,
2604 int field_step_expected)
2605 {
2606 const struct mg_request_info *req_info = mg_get_request_info(conn);
2607 int ret;
2608 struct mg_form_data_handler fdh = {field_found,
2609 field_get,
2610 field_store,
2611 NULL};
2612
2613 (void)cbdata;
2614
2615 ck_assert(req_info != NULL);
2616
2617 mg_printf(conn, "HTTP/1.0 200 OK\r\nContent-Type: text/plain\r\n\r\n");
2618 fdh.user_data = (void *)&g_field_found_return;
2619
2620 /* Call the form handler */
2621 g_field_step = 100;
2622 g_field_found_return = MG_FORM_FIELD_STORAGE_STORE;
2623 ret = mg_handle_form_request(conn, &fdh);
2624 ck_assert_int_eq(ret, ret_expected);
2625 ck_assert_int_eq(g_field_step, field_step_expected);
2626 mg_printf(conn, "%i\r\n", ret);
2627 g_field_step = 1000;
2628
2629 mark_point();
2630
2631 return 1;
2632 }
2633
2634
2635 static int
FormStore1(struct mg_connection * conn,void * cbdata)2636 FormStore1(struct mg_connection *conn, void *cbdata)
2637 {
2638 mark_point();
2639 return FormStore(conn, cbdata, 3, 101);
2640 }
2641
2642
2643 static int
FormStore2(struct mg_connection * conn,void * cbdata)2644 FormStore2(struct mg_connection *conn, void *cbdata)
2645 {
2646 mark_point();
2647 return FormStore(conn, cbdata, 4, 102);
2648 }
2649
2650
2651 static void
send_chunk_stringl(struct mg_connection * conn,const char * chunk,unsigned int chunk_len)2652 send_chunk_stringl(struct mg_connection *conn,
2653 const char *chunk,
2654 unsigned int chunk_len)
2655 {
2656 char lenbuf[16];
2657 size_t lenbuf_len;
2658 int ret;
2659
2660 mark_point();
2661
2662 /* First store the length information in a text buffer. */
2663 sprintf(lenbuf, "%x\r\n", chunk_len);
2664 lenbuf_len = strlen(lenbuf);
2665
2666 /* Then send length information, chunk and terminating \r\n. */
2667 ret = mg_write(conn, lenbuf, lenbuf_len);
2668 ck_assert_int_eq(ret, (int)lenbuf_len);
2669
2670 ret = mg_write(conn, chunk, chunk_len);
2671 ck_assert_int_eq(ret, (int)chunk_len);
2672
2673 ret = mg_write(conn, "\r\n", 2);
2674 ck_assert_int_eq(ret, 2);
2675 }
2676
2677
2678 static void
send_chunk_string(struct mg_connection * conn,const char * chunk)2679 send_chunk_string(struct mg_connection *conn, const char *chunk)
2680 {
2681 mark_point();
2682 send_chunk_stringl(conn, chunk, (unsigned int)strlen(chunk));
2683 mark_point();
2684 }
2685
2686
START_TEST(test_handle_form)2687 START_TEST(test_handle_form)
2688 {
2689 struct mg_context *ctx;
2690 struct mg_connection *client_conn;
2691 const struct mg_response_info *client_ri;
2692 const char *OPTIONS[8];
2693 const char *opt;
2694 int opt_idx = 0;
2695 char ebuf[1024];
2696 const char *multipart_body;
2697 const char *boundary;
2698 size_t body_len, body_sent, chunk_len, bound_len;
2699 int sleep_cnt;
2700
2701 mark_point();
2702
2703 memset((void *)OPTIONS, 0, sizeof(OPTIONS));
2704 OPTIONS[opt_idx++] = "listening_ports";
2705 OPTIONS[opt_idx++] = "8884";
2706 ck_assert_int_le(opt_idx, (int)(sizeof(OPTIONS) / sizeof(OPTIONS[0])));
2707 ck_assert(OPTIONS[sizeof(OPTIONS) / sizeof(OPTIONS[0]) - 1] == NULL);
2708 ck_assert(OPTIONS[sizeof(OPTIONS) / sizeof(OPTIONS[0]) - 2] == NULL);
2709
2710 ctx = test_mg_start(NULL, &g_ctx, OPTIONS, __LINE__);
2711
2712 ck_assert(ctx != NULL);
2713 g_ctx = ctx;
2714
2715 opt = mg_get_option(ctx, "listening_ports");
2716 ck_assert_str_eq(opt, "8884");
2717
2718 mg_set_request_handler(ctx, "/handle_form", FormGet, NULL);
2719 mg_set_request_handler(ctx, "/handle_form_store", FormStore1, NULL);
2720 mg_set_request_handler(ctx, "/handle_form_store2", FormStore2, NULL);
2721
2722 test_sleep(1);
2723
2724 /* Handle form: "GET" */
2725 client_conn = mg_download("localhost",
2726 8884,
2727 0,
2728 ebuf,
2729 sizeof(ebuf),
2730 "%s",
2731 "GET /handle_form"
2732 "?textin=text&passwordin=&radio1=val1"
2733 "&radio2=val1&check1=val1&numberin=1"
2734 "&datein=1.1.2016&colorin=%2380ff00"
2735 "&rangein=3&monthin=&weekin=&timein="
2736 "&datetimen=&datetimelocalin=&emailin="
2737 "&searchin=&telin=&urlin=&filein="
2738 "&filesin=&selectin=opt1"
2739 "&message=Text+area+default+text. "
2740 "HTTP/1.0\r\n"
2741 "Host: localhost:8884\r\n"
2742 "Connection: close\r\n\r\n");
2743 ck_assert(client_conn != NULL);
2744 for (sleep_cnt = 0; sleep_cnt < 30; sleep_cnt++) {
2745 test_sleep(1);
2746 if (g_field_step == 1000) {
2747 break;
2748 }
2749 }
2750 client_ri = mg_get_response_info(client_conn);
2751
2752 ck_assert(client_ri != NULL);
2753 ck_assert_int_eq(client_ri->status_code, 200);
2754 mg_close_connection(client_conn);
2755
2756 /* Handle form: "POST x-www-form-urlencoded" */
2757 client_conn =
2758 mg_download("localhost",
2759 8884,
2760 0,
2761 ebuf,
2762 sizeof(ebuf),
2763 "%s",
2764 "POST /handle_form HTTP/1.1\r\n"
2765 "Host: localhost:8884\r\n"
2766 "Connection: close\r\n"
2767 "Content-Type: application/x-www-form-urlencoded\r\n"
2768 "Content-Length: 263\r\n"
2769 "\r\n"
2770 "textin=text&passwordin=&radio1=val1&radio2=val1"
2771 "&check1=val1&numberin=1&datein=1.1.2016"
2772 "&colorin=%2380ff00&rangein=3&monthin=&weekin="
2773 "&timein=&datetimen=&datetimelocalin=&emailin="
2774 "&searchin=&telin=&urlin=&filein=&filesin="
2775 "&selectin=opt1&message=Text+area+default+text.");
2776 ck_assert(client_conn != NULL);
2777 for (sleep_cnt = 0; sleep_cnt < 30; sleep_cnt++) {
2778 test_sleep(1);
2779 if (g_field_step == 1000) {
2780 break;
2781 }
2782 }
2783 client_ri = mg_get_response_info(client_conn);
2784
2785 ck_assert(client_ri != NULL);
2786 ck_assert_int_eq(client_ri->status_code, 200);
2787 mg_close_connection(client_conn);
2788
2789 /* Handle form: "POST multipart/form-data" */
2790 multipart_body =
2791 "--multipart-form-data-boundary--see-RFC-2388\r\n"
2792 "Content-Disposition: form-data; name=\"textin\"\r\n"
2793 "\r\n"
2794 "text\r\n"
2795 "--multipart-form-data-boundary--see-RFC-2388\r\n"
2796 "Content-Disposition: form-data; name=\"passwordin\"\r\n"
2797 "\r\n"
2798 "\r\n"
2799 "--multipart-form-data-boundary--see-RFC-2388\r\n"
2800 "Content-Disposition: form-data; name=\"radio1\"\r\n"
2801 "\r\n"
2802 "val1\r\n"
2803 "--multipart-form-data-boundary--see-RFC-2388\r\n"
2804 "Content-Disposition: form-data; name=radio2\r\n"
2805 "\r\n"
2806 "val1\r\n"
2807 "--multipart-form-data-boundary--see-RFC-2388\r\n"
2808 "Content-Disposition: form-data; name=\"check1\"\r\n"
2809 "\r\n"
2810 "val1\r\n"
2811 "--multipart-form-data-boundary--see-RFC-2388\r\n"
2812 "Content-Disposition: form-data; name=\"numberin\"\r\n"
2813 "\r\n"
2814 "1\r\n"
2815 "--multipart-form-data-boundary--see-RFC-2388\r\n"
2816 "Content-Disposition: form-data; name=\"datein\"\r\n"
2817 "\r\n"
2818 "1.1.2016\r\n"
2819 "--multipart-form-data-boundary--see-RFC-2388\r\n"
2820 "Content-Disposition: form-data; name=\"colorin\"\r\n"
2821 "\r\n"
2822 "#80ff00\r\n"
2823 "--multipart-form-data-boundary--see-RFC-2388\r\n"
2824 "Content-Disposition: form-data; name=\"rangein\"\r\n"
2825 "\r\n"
2826 "3\r\n"
2827 "--multipart-form-data-boundary--see-RFC-2388\r\n"
2828 "Content-Disposition: form-data; name=\"monthin\"\r\n"
2829 "\r\n"
2830 "\r\n"
2831 "--multipart-form-data-boundary--see-RFC-2388\r\n"
2832 "Content-Disposition: form-data; name=\"weekin\"\r\n"
2833 "\r\n"
2834 "\r\n"
2835 "--multipart-form-data-boundary--see-RFC-2388\r\n"
2836 "Content-Disposition: form-data; name=\"timein\"\r\n"
2837 "\r\n"
2838 "\r\n"
2839 "--multipart-form-data-boundary--see-RFC-2388\r\n"
2840 "Content-Disposition: form-data; name=\"datetimen\"\r\n"
2841 "\r\n"
2842 "\r\n"
2843 "--multipart-form-data-boundary--see-RFC-2388\r\n"
2844 "Content-Disposition: form-data; name=\"datetimelocalin\"\r\n"
2845 "\r\n"
2846 "\r\n"
2847 "--multipart-form-data-boundary--see-RFC-2388\r\n"
2848 "Content-Disposition: form-data; name=\"emailin\"\r\n"
2849 "\r\n"
2850 "\r\n"
2851 "--multipart-form-data-boundary--see-RFC-2388\r\n"
2852 "Content-Disposition: form-data; name=\"searchin\"\r\n"
2853 "\r\n"
2854 "\r\n"
2855 "--multipart-form-data-boundary--see-RFC-2388\r\n"
2856 "Content-Disposition: form-data; name=\"telin\"\r\n"
2857 "\r\n"
2858 "\r\n"
2859 "--multipart-form-data-boundary--see-RFC-2388\r\n"
2860 "Content-Disposition: form-data; name=\"urlin\"\r\n"
2861 "\r\n"
2862 "\r\n"
2863 "--multipart-form-data-boundary--see-RFC-2388\r\n"
2864 "Content-Disposition: form-data; name=\"filein\"; filename=\"\"\r\n"
2865 "Content-Type: application/octet-stream\r\n"
2866 "\r\n"
2867 "\r\n"
2868 "--multipart-form-data-boundary--see-RFC-2388\r\n"
2869 "Content-Disposition: form-data; name=filesin; filename=\r\n"
2870 "Content-Type: application/octet-stream\r\n"
2871 "\r\n"
2872 "\r\n"
2873 "--multipart-form-data-boundary--see-RFC-2388\r\n"
2874 "Content-Disposition: form-data; name=\"selectin\"\r\n"
2875 "\r\n"
2876 "opt1\r\n"
2877 "--multipart-form-data-boundary--see-RFC-2388\r\n"
2878 "Content-Disposition: form-data; name=\"message\"\r\n"
2879 "\r\n"
2880 "Text area default text.\r\n"
2881 "--multipart-form-data-boundary--see-RFC-2388--\r\n";
2882 body_len = strlen(multipart_body);
2883 ck_assert_uint_eq(body_len, 2368); /* not required */
2884
2885 client_conn =
2886 mg_download("localhost",
2887 8884,
2888 0,
2889 ebuf,
2890 sizeof(ebuf),
2891 "POST /handle_form HTTP/1.1\r\n"
2892 "Host: localhost:8884\r\n"
2893 "Connection: close\r\n"
2894 "Content-Type: multipart/form-data; "
2895 "boundary=multipart-form-data-boundary--see-RFC-2388\r\n"
2896 "Content-Length: %u\r\n"
2897 "\r\n%s",
2898 (unsigned int)body_len,
2899 multipart_body);
2900
2901 ck_assert(client_conn != NULL);
2902 for (sleep_cnt = 0; sleep_cnt < 30; sleep_cnt++) {
2903 test_sleep(1);
2904 if (g_field_step == 1000) {
2905 break;
2906 }
2907 }
2908 client_ri = mg_get_response_info(client_conn);
2909
2910 ck_assert(client_ri != NULL);
2911 ck_assert_int_eq(client_ri->status_code, 200);
2912 mg_close_connection(client_conn);
2913
2914
2915 /* Handle form: "POST multipart/form-data" with chunked transfer encoding */
2916 client_conn =
2917 mg_download("localhost",
2918 8884,
2919 0,
2920 ebuf,
2921 sizeof(ebuf),
2922 "%s",
2923 "POST /handle_form HTTP/1.1\r\n"
2924 "Host: localhost:8884\r\n"
2925 "Connection: close\r\n"
2926 "Content-Type: multipart/form-data; "
2927 "boundary=multipart-form-data-boundary--see-RFC-2388\r\n"
2928 "Transfer-Encoding: chunked\r\n"
2929 "\r\n");
2930
2931 ck_assert(client_conn != NULL);
2932
2933 body_len = strlen(multipart_body);
2934 chunk_len = 1;
2935 body_sent = 0;
2936 while (body_len > body_sent) {
2937 if (chunk_len > (body_len - body_sent)) {
2938 chunk_len = body_len - body_sent;
2939 }
2940 ck_assert_int_gt((int)chunk_len, 0);
2941 mg_printf(client_conn, "%x\r\n", (unsigned int)chunk_len);
2942 mg_write(client_conn, multipart_body + body_sent, chunk_len);
2943 mg_printf(client_conn, "\r\n");
2944 body_sent += chunk_len;
2945 chunk_len = (chunk_len % 40) + 1;
2946 }
2947 mg_printf(client_conn, "0\r\n\r\n");
2948
2949 for (sleep_cnt = 0; sleep_cnt < 30; sleep_cnt++) {
2950 test_sleep(1);
2951 if (g_field_step == 1000) {
2952 break;
2953 }
2954 }
2955 client_ri = mg_get_response_info(client_conn);
2956
2957 ck_assert(client_ri != NULL);
2958 ck_assert_int_eq(client_ri->status_code, 200);
2959 mg_close_connection(client_conn);
2960
2961 /* Handle form: "POST multipart/form-data" with chunked transfer
2962 * encoding, using a quoted boundary string */
2963 client_conn = mg_download(
2964 "localhost",
2965 8884,
2966 0,
2967 ebuf,
2968 sizeof(ebuf),
2969 "%s",
2970 "POST /handle_form HTTP/1.1\r\n"
2971 "Host: localhost:8884\r\n"
2972 "Connection: close\r\n"
2973 "Content-Type: multipart/form-data; "
2974 "boundary=\"multipart-form-data-boundary--see-RFC-2388\"\r\n"
2975 "Transfer-Encoding: chunked\r\n"
2976 "\r\n");
2977
2978 ck_assert(client_conn != NULL);
2979
2980 body_len = strlen(multipart_body);
2981 chunk_len = 1;
2982 body_sent = 0;
2983 while (body_len > body_sent) {
2984 if (chunk_len > (body_len - body_sent)) {
2985 chunk_len = body_len - body_sent;
2986 }
2987 ck_assert_int_gt((int)chunk_len, 0);
2988 mg_printf(client_conn, "%x\r\n", (unsigned int)chunk_len);
2989 mg_write(client_conn, multipart_body + body_sent, chunk_len);
2990 mg_printf(client_conn, "\r\n");
2991 body_sent += chunk_len;
2992 chunk_len = (chunk_len % 40) + 1;
2993 }
2994 mg_printf(client_conn, "0\r\n\r\n");
2995
2996 for (sleep_cnt = 0; sleep_cnt < 30; sleep_cnt++) {
2997 test_sleep(1);
2998 if (g_field_step == 1000) {
2999 break;
3000 }
3001 }
3002 client_ri = mg_get_response_info(client_conn);
3003
3004 ck_assert(client_ri != NULL);
3005 ck_assert_int_eq(client_ri->status_code, 200);
3006 mg_close_connection(client_conn);
3007
3008
3009 /* Now test form_store */
3010
3011 /* First test with GET */
3012 client_conn = mg_download("localhost",
3013 8884,
3014 0,
3015 ebuf,
3016 sizeof(ebuf),
3017 "%s",
3018 "GET /handle_form_store"
3019 "?storeme=storetest"
3020 "&continue_field_handler=ignore"
3021 "&break_field_handler=abort"
3022 "&dontread=xyz "
3023 "HTTP/1.0\r\n"
3024 "Host: localhost:8884\r\n"
3025 "Connection: close\r\n\r\n");
3026
3027 ck_assert(client_conn != NULL);
3028
3029 for (sleep_cnt = 0; sleep_cnt < 30; sleep_cnt++) {
3030 test_sleep(1);
3031 if (g_field_step == 1000) {
3032 break;
3033 }
3034 }
3035 client_ri = mg_get_response_info(client_conn);
3036
3037 ck_assert(client_ri != NULL);
3038 ck_assert_int_eq(client_ri->status_code, 200);
3039 mg_close_connection(client_conn);
3040
3041
3042 /* Handle form: "POST x-www-form-urlencoded", chunked, store */
3043 client_conn =
3044 mg_download("localhost",
3045 8884,
3046 0,
3047 ebuf,
3048 sizeof(ebuf),
3049 "%s",
3050 "POST /handle_form_store HTTP/1.0\r\n"
3051 "Host: localhost:8884\r\n"
3052 "Connection: close\r\n"
3053 "Content-Type: application/x-www-form-urlencoded\r\n"
3054 "Transfer-Encoding: chunked\r\n"
3055 "\r\n");
3056 ck_assert(client_conn != NULL);
3057
3058 send_chunk_string(client_conn, "storeme=store");
3059 send_chunk_string(client_conn, "test&");
3060 send_chunk_string(client_conn, "continue_field_handler=ignore");
3061 send_chunk_string(client_conn, "&br");
3062 test_sleep(1);
3063 send_chunk_string(client_conn, "eak_field_handler=abort&");
3064 send_chunk_string(client_conn, "dontread=xyz");
3065 mg_printf(client_conn, "0\r\n\r\n");
3066
3067 for (sleep_cnt = 0; sleep_cnt < 30; sleep_cnt++) {
3068 test_sleep(1);
3069 if (g_field_step == 1000) {
3070 break;
3071 }
3072 }
3073 client_ri = mg_get_response_info(client_conn);
3074
3075 ck_assert(client_ri != NULL);
3076 ck_assert_int_eq(client_ri->status_code, 200);
3077 mg_close_connection(client_conn);
3078
3079 /* Handle form: "POST multipart/form-data", chunked, store */
3080 client_conn =
3081 mg_download("localhost",
3082 8884,
3083 0,
3084 ebuf,
3085 sizeof(ebuf),
3086 "%s",
3087 "POST /handle_form_store HTTP/1.0\r\n"
3088 "Host: localhost:8884\r\n"
3089 "Connection: close\r\n"
3090 "Content-Type: multipart/form-data; "
3091 "boundary=multipart-form-data-boundary--see-RFC-2388\r\n"
3092 "Transfer-Encoding: chunked\r\n"
3093 "\r\n");
3094 ck_assert(client_conn != NULL);
3095
3096 send_chunk_string(client_conn, "--multipart-form-data-boundary");
3097 send_chunk_string(client_conn, "--see-RFC-2388\r\n");
3098 send_chunk_string(client_conn, "Content-Disposition: form-data; ");
3099 send_chunk_string(client_conn, "name=\"storeme\"\r\n");
3100 send_chunk_string(client_conn, "\r\n");
3101 send_chunk_string(client_conn, "storetest\r\n");
3102
3103 send_chunk_string(client_conn, "--multipart-form-data-boundary-");
3104 send_chunk_string(client_conn, "-see-RFC-2388\r\n");
3105 send_chunk_string(client_conn, "Content-Disposition: form-data; ");
3106 send_chunk_string(client_conn, "name=\"continue_field_handler\"\r\n");
3107 send_chunk_string(client_conn, "\r\n");
3108 send_chunk_string(client_conn, "ignore\r\n");
3109
3110 send_chunk_string(client_conn, "--multipart-form-data-boundary-");
3111 send_chunk_string(client_conn, "-see-RFC-2388\r\n");
3112 send_chunk_string(client_conn, "Content-Disposition: form-data; ");
3113 send_chunk_string(client_conn, "name=\"break_field_handler\"\r\n");
3114 send_chunk_string(client_conn, "\r\n");
3115 send_chunk_string(client_conn, "abort\r\n");
3116
3117 send_chunk_string(client_conn, "--multipart-form-data-boundary-");
3118 send_chunk_string(client_conn, "-see-RFC-2388\r\n");
3119 send_chunk_string(client_conn, "Content-Disposition: form-data; ");
3120 send_chunk_string(client_conn, "name=\"dontread\"\r\n");
3121 send_chunk_string(client_conn, "\r\n");
3122 send_chunk_string(client_conn, "xyz\r\n");
3123 send_chunk_string(client_conn, "--multipart-form-data-boundary");
3124 send_chunk_string(client_conn, "--see-RFC-2388--\r\n");
3125 mg_printf(client_conn, "0\r\n\r\n");
3126
3127 for (sleep_cnt = 0; sleep_cnt < 30; sleep_cnt++) {
3128 test_sleep(1);
3129 if (g_field_step == 1000) {
3130 break;
3131 }
3132 }
3133 client_ri = mg_get_response_info(client_conn);
3134
3135 ck_assert(client_ri != NULL);
3136 ck_assert_int_eq(client_ri->status_code, 200);
3137 mg_close_connection(client_conn);
3138
3139
3140 /* Handle form: "POST multipart/form-data", chunked, store, with files */
3141 client_conn =
3142 mg_download("localhost",
3143 8884,
3144 0,
3145 ebuf,
3146 sizeof(ebuf),
3147 "%s",
3148 "POST /handle_form_store2 HTTP/1.0\r\n"
3149 "Host: localhost:8884\r\n"
3150 "Connection: close\r\n"
3151 "Content-Type: multipart/form-data; "
3152 "boundary=multipart-form-data-boundary--see-RFC-2388\r\n"
3153 "Transfer-Encoding: chunked\r\n"
3154 "\r\n");
3155 ck_assert(client_conn != NULL);
3156
3157 boundary = "--multipart-form-data-boundary--see-RFC-2388\r\n";
3158
3159 send_chunk_string(client_conn, boundary);
3160 send_chunk_string(client_conn, "Content-Disposition: form-data; ");
3161 send_chunk_string(client_conn, "name=\"storeme\"\r\n");
3162 send_chunk_string(client_conn, "\r\n");
3163 send_chunk_string(client_conn, "storetest\r\n");
3164
3165 send_chunk_string(client_conn, boundary);
3166 send_chunk_string(client_conn, "Content-Disposition: form-data; ");
3167 send_chunk_string(client_conn, "name=\"continue_field_handler\";");
3168 send_chunk_string(client_conn, "filename=\"file_ignored.txt\"\r\n");
3169 send_chunk_string(client_conn, "Content-Type: ");
3170 send_chunk_string(client_conn, "application/octet-stream\r\n");
3171 send_chunk_string(client_conn, "X-Ignored-Header: xyz\r\n");
3172 send_chunk_string(client_conn, "\r\n");
3173
3174 /* send some kilobyte of data */
3175 /* sending megabytes to localhost does not always work in CI test
3176 * environments (depending on the network stack) */
3177 body_sent = 0;
3178 bound_len = strlen(boundary);
3179 do {
3180 send_chunk_string(client_conn, "ignore\r\n");
3181 body_sent += 8;
3182 /* send some strings that are almost boundaries */
3183 for (chunk_len = 1; chunk_len < bound_len; chunk_len++) {
3184 /* chunks from 1 byte to strlen(boundary)-1 */
3185 send_chunk_stringl(client_conn, boundary, (unsigned int)chunk_len);
3186 body_sent += chunk_len;
3187 }
3188 } while (body_sent < 8 * 1024);
3189 send_chunk_string(client_conn, "\r\n");
3190
3191 send_chunk_string(client_conn, boundary);
3192 send_chunk_string(client_conn, "Content-Disposition: form-data; ");
3193 send_chunk_string(client_conn, "name=\"file2store\";");
3194 send_chunk_string(client_conn, "filename=\"myfile.txt\"\r\n");
3195 send_chunk_string(client_conn, "Content-Type: ");
3196 send_chunk_string(client_conn, "application/octet-stream\r\n");
3197 send_chunk_string(client_conn, "X-Ignored-Header: xyz\r\n");
3198 send_chunk_string(client_conn, "\r\n");
3199 for (body_sent = 0; (int)body_sent < (int)myfile_content_rep; body_sent++) {
3200 send_chunk_string(client_conn, myfile_content);
3201 }
3202 send_chunk_string(client_conn, "\r\n");
3203
3204 send_chunk_string(client_conn, boundary);
3205 send_chunk_string(client_conn, "Content-Disposition: form-data; ");
3206 send_chunk_string(client_conn, "name=\"break_field_handler\"\r\n");
3207 send_chunk_string(client_conn, "\r\n");
3208 send_chunk_string(client_conn, "abort\r\n");
3209
3210 send_chunk_string(client_conn, boundary);
3211 send_chunk_string(client_conn, "Content-Disposition: form-data; ");
3212 send_chunk_string(client_conn, "name=\"dontread\"\r\n");
3213 send_chunk_string(client_conn, "\r\n");
3214 send_chunk_string(client_conn, "xyz\r\n");
3215 send_chunk_string(client_conn, "--multipart-form-data-boundary");
3216 send_chunk_string(client_conn, "--see-RFC-2388--\r\n");
3217 mg_printf(client_conn, "0\r\n\r\n");
3218
3219 for (sleep_cnt = 0; sleep_cnt < 30; sleep_cnt++) {
3220 test_sleep(1);
3221 if (g_field_step == 1000) {
3222 break;
3223 }
3224 }
3225 client_ri = mg_get_response_info(client_conn);
3226
3227 ck_assert(client_ri != NULL);
3228 ck_assert_int_eq(client_ri->status_code, 200);
3229 mg_close_connection(client_conn);
3230
3231
3232 /* Close the server */
3233 g_ctx = NULL;
3234 test_mg_stop(ctx, __LINE__);
3235 mark_point();
3236 }
3237 END_TEST
3238
3239
START_TEST(test_http_auth)3240 START_TEST(test_http_auth)
3241 {
3242 #if !defined(NO_FILES)
3243 const char *OPTIONS[] = {
3244 "document_root",
3245 ".",
3246 "listening_ports",
3247 "8080",
3248 #if !defined(NO_CACHING)
3249 "static_file_max_age",
3250 "0",
3251 #endif
3252 "put_delete_auth_file",
3253 "put_delete_auth_file.csv",
3254 NULL,
3255 };
3256
3257 struct mg_context *ctx;
3258 struct mg_connection *client_conn;
3259 char client_err[256], nonce[256];
3260 const struct mg_response_info *client_ri;
3261 int client_res;
3262 FILE *f;
3263 const char *passwd_file = ".htpasswd";
3264 const char *test_file = "test_http_auth.test_file.txt";
3265 const char *test_content = "test_http_auth test_file content";
3266 const char *domain;
3267 const char *doc_root;
3268 const char *auth_request;
3269 const char *str;
3270 size_t len;
3271 int i;
3272 char HA1[256], HA2[256];
3273 char HA1_md5_buf[33], HA2_md5_buf[33], HA_md5_buf[33];
3274 char *HA1_md5_ret, *HA2_md5_ret, *HA_md5_ret;
3275 const char *nc = "00000001";
3276 const char *cnonce = "6789ABCD";
3277
3278 mark_point();
3279
3280 /* Start with default options */
3281 ctx = test_mg_start(NULL, NULL, OPTIONS, __LINE__);
3282
3283 ck_assert(ctx != NULL);
3284 domain = mg_get_option(ctx, "authentication_domain");
3285 ck_assert(domain != NULL);
3286 len = strlen(domain);
3287 ck_assert_uint_gt(len, 0);
3288 ck_assert_uint_lt(len, 64);
3289 doc_root = mg_get_option(ctx, "document_root");
3290 ck_assert_str_eq(doc_root, ".");
3291
3292 /* Create a default file in the document root */
3293 f = fopen(test_file, "w");
3294 if (f) {
3295 fprintf(f, "%s", test_content);
3296 fclose(f);
3297 } else {
3298 ck_abort_msg("Cannot create file %s", test_file);
3299 }
3300
3301 (void)remove(passwd_file);
3302 (void)remove("put_delete_auth_file.csv");
3303
3304 client_res = mg_modify_passwords_file("put_delete_auth_file.csv",
3305 domain,
3306 "admin",
3307 "adminpass");
3308 ck_assert_int_eq(client_res, 1);
3309
3310 /* Read file before a .htpasswd file has been created */
3311 memset(client_err, 0, sizeof(client_err));
3312 client_conn =
3313 mg_connect_client("127.0.0.1", 8080, 0, client_err, sizeof(client_err));
3314
3315 ck_assert_str_eq(client_err, "");
3316 ck_assert(client_conn != NULL);
3317
3318 mg_printf(client_conn, "GET /%s HTTP/1.0\r\n\r\n", test_file);
3319 client_res =
3320 mg_get_response(client_conn, client_err, sizeof(client_err), 10000);
3321 ck_assert_int_ge(client_res, 0);
3322 ck_assert_str_eq(client_err, "");
3323 client_ri = mg_get_response_info(client_conn);
3324 ck_assert(client_ri != NULL);
3325
3326 ck_assert_int_eq(client_ri->status_code, 200);
3327 client_res = (int)mg_read(client_conn, client_err, sizeof(client_err));
3328 ck_assert_int_gt(client_res, 0);
3329 ck_assert_int_le(client_res, sizeof(client_err));
3330 ck_assert_str_eq(client_err, test_content);
3331 mg_close_connection(client_conn);
3332
3333 test_sleep(1);
3334
3335 /* Create a .htpasswd file */
3336 client_res = mg_modify_passwords_file(passwd_file, domain, "user", "pass");
3337 ck_assert_int_eq(client_res, 1);
3338
3339 client_res = mg_modify_passwords_file(NULL, domain, "user", "pass");
3340 ck_assert_int_eq(client_res, 0); /* Filename is required */
3341
3342 test_sleep(1);
3343
3344 /* Repeat test after .htpasswd is created */
3345 memset(client_err, 0, sizeof(client_err));
3346 client_conn =
3347 mg_connect_client("127.0.0.1", 8080, 0, client_err, sizeof(client_err));
3348
3349 ck_assert_str_eq(client_err, "");
3350 ck_assert(client_conn != NULL);
3351
3352 mg_printf(client_conn, "GET /%s HTTP/1.0\r\n\r\n", test_file);
3353 client_res =
3354 mg_get_response(client_conn, client_err, sizeof(client_err), 10000);
3355 ck_assert_int_ge(client_res, 0);
3356 ck_assert_str_eq(client_err, "");
3357 client_ri = mg_get_response_info(client_conn);
3358 ck_assert(client_ri != NULL);
3359
3360 ck_assert_int_eq(client_ri->status_code, 401);
3361
3362 auth_request = NULL;
3363 for (i = 0; i < client_ri->num_headers; i++) {
3364 if (!mg_strcasecmp(client_ri->http_headers[i].name,
3365 "WWW-Authenticate")) {
3366 ck_assert_ptr_eq(auth_request, NULL);
3367 auth_request = client_ri->http_headers[i].value;
3368 ck_assert_ptr_ne(auth_request, NULL);
3369 }
3370 }
3371 ck_assert_ptr_ne(auth_request, NULL);
3372 str = "Digest qop=\"auth\", realm=\"";
3373 len = strlen(str);
3374 ck_assert(!mg_strncasecmp(auth_request, str, len));
3375 ck_assert(!strncmp(auth_request + len, domain, strlen(domain)));
3376 len += strlen(domain);
3377 str = "\", nonce=\"";
3378 ck_assert(!strncmp(auth_request + len, str, strlen(str)));
3379 len += strlen(str);
3380 str = strchr(auth_request + len, '\"');
3381 ck_assert_ptr_ne(str, NULL);
3382 ck_assert_ptr_ne(str, auth_request + len);
3383 /* nonce is from including (auth_request + len) to excluding (str) */
3384 ck_assert_int_gt((ptrdiff_t)(str) - (ptrdiff_t)(auth_request + len), 0);
3385 ck_assert_int_lt((ptrdiff_t)(str) - (ptrdiff_t)(auth_request + len),
3386 (ptrdiff_t)sizeof(nonce));
3387 memset(nonce, 0, sizeof(nonce));
3388 memcpy(nonce,
3389 auth_request + len,
3390 (size_t)((ptrdiff_t)(str) - (ptrdiff_t)(auth_request + len)));
3391 memset(HA1, 0, sizeof(HA1));
3392 memset(HA2, 0, sizeof(HA2));
3393 memset(HA1_md5_buf, 0, sizeof(HA1_md5_buf));
3394 memset(HA2_md5_buf, 0, sizeof(HA2_md5_buf));
3395 memset(HA_md5_buf, 0, sizeof(HA_md5_buf));
3396
3397 sprintf(HA1, "%s:%s:%s", "user", domain, "pass");
3398 sprintf(HA2, "%s:/%s", "GET", test_file);
3399 HA1_md5_ret = mg_md5(HA1_md5_buf, HA1, NULL);
3400 HA2_md5_ret = mg_md5(HA2_md5_buf, HA2, NULL);
3401
3402 ck_assert_ptr_eq(HA1_md5_ret, HA1_md5_buf);
3403 ck_assert_ptr_eq(HA2_md5_ret, HA2_md5_buf);
3404
3405 HA_md5_ret = mg_md5(HA_md5_buf, "user", ":", domain, ":", "pass", NULL);
3406 ck_assert_ptr_eq(HA_md5_ret, HA_md5_buf);
3407 ck_assert_str_eq(HA1_md5_ret, HA_md5_buf);
3408
3409 HA_md5_ret = mg_md5(HA_md5_buf, "GET", ":", "/", test_file, NULL);
3410 ck_assert_ptr_eq(HA_md5_ret, HA_md5_buf);
3411 ck_assert_str_eq(HA2_md5_ret, HA_md5_buf);
3412
3413 HA_md5_ret = mg_md5(HA_md5_buf,
3414 HA1_md5_buf,
3415 ":",
3416 nonce,
3417 ":",
3418 nc,
3419 ":",
3420 cnonce,
3421 ":",
3422 "auth",
3423 ":",
3424 HA2_md5_buf,
3425 NULL);
3426 ck_assert_ptr_eq(HA_md5_ret, HA_md5_buf);
3427
3428 mg_close_connection(client_conn);
3429
3430 /* Retry with authorization */
3431 memset(client_err, 0, sizeof(client_err));
3432 client_conn =
3433 mg_connect_client("127.0.0.1", 8080, 0, client_err, sizeof(client_err));
3434
3435 ck_assert_str_eq(client_err, "");
3436 ck_assert(client_conn != NULL);
3437
3438 mg_printf(client_conn, "GET /%s HTTP/1.0\r\n", test_file);
3439 mg_printf(client_conn,
3440 "Authorization: Digest "
3441 "username=\"%s\", "
3442 "realm=\"%s\", "
3443 "nonce=\"%s\", "
3444 "uri=\"/%s\", "
3445 "qop=auth, "
3446 "nc=%s, "
3447 "cnonce=\"%s\", "
3448 "response=\"%s\"\r\n\r\n",
3449 "user",
3450 domain,
3451 nonce,
3452 test_file,
3453 nc,
3454 cnonce,
3455 HA_md5_buf);
3456 client_res =
3457 mg_get_response(client_conn, client_err, sizeof(client_err), 10000);
3458 ck_assert_int_ge(client_res, 0);
3459 ck_assert_str_eq(client_err, "");
3460 client_ri = mg_get_response_info(client_conn);
3461 ck_assert(client_ri != NULL);
3462
3463 ck_assert_int_eq(client_ri->status_code, 200);
3464 client_res = (int)mg_read(client_conn, client_err, sizeof(client_err));
3465 ck_assert_int_gt(client_res, 0);
3466 ck_assert_int_le(client_res, sizeof(client_err));
3467 ck_assert_str_eq(client_err, test_content);
3468 mg_close_connection(client_conn);
3469
3470 test_sleep(1);
3471
3472 /* Retry DELETE with authorization of a user not authorized for DELETE */
3473 memset(client_err, 0, sizeof(client_err));
3474 client_conn =
3475 mg_connect_client("127.0.0.1", 8080, 0, client_err, sizeof(client_err));
3476
3477 ck_assert_str_eq(client_err, "");
3478 ck_assert(client_conn != NULL);
3479
3480 mg_printf(client_conn, "DELETE /%s HTTP/1.0\r\n", test_file);
3481 mg_printf(client_conn,
3482 "Authorization: Digest "
3483 "username=\"%s\", "
3484 "realm=\"%s\", "
3485 "nonce=\"%s\", "
3486 "uri=\"/%s\", "
3487 "qop=auth, "
3488 "nc=%s, "
3489 "cnonce=\"%s\", "
3490 "response=\"%s\"\r\n\r\n",
3491 "user",
3492 domain,
3493 nonce,
3494 test_file,
3495 nc,
3496 cnonce,
3497 HA_md5_buf);
3498 client_res =
3499 mg_get_response(client_conn, client_err, sizeof(client_err), 10000);
3500 ck_assert_int_ge(client_res, 0);
3501 ck_assert_str_eq(client_err, "");
3502 client_ri = mg_get_response_info(client_conn);
3503 ck_assert(client_ri != NULL);
3504
3505 ck_assert_int_eq(client_ri->status_code, 401);
3506 mg_close_connection(client_conn);
3507
3508 test_sleep(1);
3509
3510 /* Remove the user from the .htpasswd file again */
3511 client_res = mg_modify_passwords_file(passwd_file, domain, "user", NULL);
3512 ck_assert_int_eq(client_res, 1);
3513
3514 test_sleep(1);
3515
3516
3517 /* Try to access the file again. Expected: 401 error */
3518 memset(client_err, 0, sizeof(client_err));
3519 client_conn =
3520 mg_connect_client("127.0.0.1", 8080, 0, client_err, sizeof(client_err));
3521
3522 ck_assert_str_eq(client_err, "");
3523 ck_assert(client_conn != NULL);
3524
3525 mg_printf(client_conn, "GET /%s HTTP/1.0\r\n\r\n", test_file);
3526 client_res =
3527 mg_get_response(client_conn, client_err, sizeof(client_err), 10000);
3528 ck_assert_int_ge(client_res, 0);
3529 ck_assert_str_eq(client_err, "");
3530 client_ri = mg_get_response_info(client_conn);
3531 ck_assert(client_ri != NULL);
3532
3533 ck_assert_int_eq(client_ri->status_code, 401);
3534 mg_close_connection(client_conn);
3535
3536 test_sleep(1);
3537
3538
3539 /* Now remove the password file */
3540 (void)remove(passwd_file);
3541 test_sleep(1);
3542
3543
3544 /* Access to the file must work like before */
3545 memset(client_err, 0, sizeof(client_err));
3546 client_conn =
3547 mg_connect_client("127.0.0.1", 8080, 0, client_err, sizeof(client_err));
3548
3549 ck_assert_str_eq(client_err, "");
3550 ck_assert(client_conn != NULL);
3551
3552 mg_printf(client_conn, "GET /%s HTTP/1.0\r\n\r\n", test_file);
3553 client_res =
3554 mg_get_response(client_conn, client_err, sizeof(client_err), 10000);
3555 ck_assert_int_ge(client_res, 0);
3556 ck_assert_str_eq(client_err, "");
3557 client_ri = mg_get_response_info(client_conn);
3558 ck_assert(client_ri != NULL);
3559
3560 ck_assert_int_eq(client_ri->status_code, 200);
3561 client_res = (int)mg_read(client_conn, client_err, sizeof(client_err));
3562 ck_assert_int_gt(client_res, 0);
3563 ck_assert_int_le(client_res, sizeof(client_err));
3564 ck_assert_str_eq(client_err, test_content);
3565 mg_close_connection(client_conn);
3566
3567 test_sleep(1);
3568
3569
3570 /* Stop the server and clean up */
3571 test_mg_stop(ctx, __LINE__);
3572 (void)remove(test_file);
3573 (void)remove(passwd_file);
3574 (void)remove("put_delete_auth_file.csv");
3575
3576 #endif
3577 mark_point();
3578 }
3579 END_TEST
3580
3581
START_TEST(test_keep_alive)3582 START_TEST(test_keep_alive)
3583 {
3584 struct mg_context *ctx;
3585 const char *OPTIONS[] =
3586 { "listening_ports",
3587 "8081",
3588 "request_timeout_ms",
3589 "10000",
3590 "enable_keep_alive",
3591 "yes",
3592 #if !defined(NO_FILES)
3593 "document_root",
3594 ".",
3595 "enable_directory_listing",
3596 "no",
3597 #endif
3598 NULL };
3599
3600 struct mg_connection *client_conn;
3601 char client_err[256];
3602 const struct mg_response_info *client_ri;
3603 int client_res, i;
3604 const char *connection_header;
3605
3606 mark_point();
3607
3608 ctx = test_mg_start(NULL, NULL, OPTIONS, __LINE__);
3609
3610 ck_assert(ctx != NULL);
3611
3612 /* HTTP 1.1 GET request */
3613 memset(client_err, 0, sizeof(client_err));
3614 client_conn =
3615 mg_connect_client("127.0.0.1", 8081, 0, client_err, sizeof(client_err));
3616
3617 ck_assert_str_eq(client_err, "");
3618 ck_assert(client_conn != NULL);
3619
3620 mg_printf(client_conn,
3621 "GET / HTTP/1.1\r\nHost: "
3622 "localhost:8081\r\nConnection: keep-alive\r\n\r\n");
3623 client_res =
3624 mg_get_response(client_conn, client_err, sizeof(client_err), 10000);
3625 ck_assert_int_ge(client_res, 0);
3626 ck_assert_str_eq(client_err, "");
3627 client_ri = mg_get_response_info(client_conn);
3628 ck_assert(client_ri != NULL);
3629
3630 #if defined(NO_FILES)
3631 ck_assert_int_eq(client_ri->status_code, 404);
3632 #else
3633 ck_assert_int_eq(client_ri->status_code, 403);
3634 #endif
3635
3636 connection_header = 0;
3637 for (i = 0; i < client_ri->num_headers; i++) {
3638 if (!mg_strcasecmp(client_ri->http_headers[i].name, "Connection")) {
3639 ck_assert_ptr_eq(connection_header, NULL);
3640 connection_header = client_ri->http_headers[i].value;
3641 ck_assert_ptr_ne(connection_header, NULL);
3642 }
3643 }
3644 /* Error replies will close the connection, even if keep-alive is set. */
3645 ck_assert_ptr_ne(connection_header, NULL);
3646 ck_assert_str_eq(connection_header, "close");
3647 mg_close_connection(client_conn);
3648
3649 test_sleep(1);
3650
3651 /* TODO: request a file and keep alive
3652 * (will only work if NO_FILES is not set). */
3653
3654 /* Stop the server and clean up */
3655 test_mg_stop(ctx, __LINE__);
3656
3657 mark_point();
3658 }
3659 END_TEST
3660
3661
START_TEST(test_error_handling)3662 START_TEST(test_error_handling)
3663 {
3664 struct mg_context *ctx;
3665 FILE *f;
3666
3667 char bad_thread_num[32] = "badnumber";
3668
3669 struct mg_callbacks callbacks;
3670 char errmsg[256];
3671
3672 struct mg_connection *client_conn;
3673 char client_err[256];
3674 const struct mg_response_info *client_ri;
3675 int client_res, i;
3676
3677 const char *OPTIONS[32];
3678 int opt_cnt = 0;
3679
3680 mark_point();
3681
3682 #if !defined(NO_FILES)
3683 OPTIONS[opt_cnt++] = "document_root";
3684 OPTIONS[opt_cnt++] = ".";
3685 #endif
3686 OPTIONS[opt_cnt++] = "error_pages";
3687 OPTIONS[opt_cnt++] = "./";
3688 OPTIONS[opt_cnt++] = "listening_ports";
3689 OPTIONS[opt_cnt++] = "8080";
3690 OPTIONS[opt_cnt++] = "num_threads";
3691 OPTIONS[opt_cnt++] = bad_thread_num;
3692 OPTIONS[opt_cnt++] = "unknown_option";
3693 OPTIONS[opt_cnt++] = "unknown_option_value";
3694 OPTIONS[opt_cnt] = NULL;
3695
3696 memset(&callbacks, 0, sizeof(callbacks));
3697
3698 callbacks.log_message = log_msg_func;
3699
3700 /* test with unknown option */
3701 memset(errmsg, 0, sizeof(errmsg));
3702 ctx = test_mg_start(&callbacks, (void *)errmsg, OPTIONS, 0);
3703
3704 /* Details of errmsg may vary, but it may not be empty */
3705 ck_assert_str_ne(errmsg, "");
3706 ck_assert(ctx == NULL);
3707 ck_assert_str_eq(errmsg, "Invalid option: unknown_option");
3708
3709 /* Remove invalid option */
3710 for (i = 0; OPTIONS[i]; i++) {
3711 if (strstr(OPTIONS[i], "unknown_option")) {
3712 OPTIONS[i] = 0;
3713 }
3714 }
3715
3716 /* Test with bad num_thread option */
3717 memset(errmsg, 0, sizeof(errmsg));
3718 ctx = test_mg_start(&callbacks, (void *)errmsg, OPTIONS, 0);
3719
3720 /* Details of errmsg may vary, but it may not be empty */
3721 ck_assert_str_ne(errmsg, "");
3722 ck_assert(ctx == NULL);
3723 ck_assert_str_eq(errmsg, "Invalid number of worker threads");
3724
3725 /* Set to a number - but use a number above the limit */
3726 #if defined(MAX_WORKER_THREADS)
3727 sprintf(bad_thread_num, "%u", MAX_WORKER_THREADS + 1);
3728 #else
3729 sprintf(bad_thread_num, "%lu", 1000000000lu);
3730 #endif
3731
3732 /* Test with bad num_thread option */
3733 memset(errmsg, 0, sizeof(errmsg));
3734 ctx = test_mg_start(&callbacks, (void *)errmsg, OPTIONS, 0);
3735
3736 /* Details of errmsg may vary, but it may not be empty */
3737 ck_assert_str_ne(errmsg, "");
3738 ck_assert(ctx == NULL);
3739 ck_assert_str_eq(errmsg, "Too many worker threads");
3740
3741
3742 /* HTTP 1.0 GET request - server is not running */
3743 memset(client_err, 0, sizeof(client_err));
3744 client_conn =
3745 mg_connect_client("127.0.0.1", 8080, 0, client_err, sizeof(client_err));
3746 ck_assert(client_conn == NULL);
3747
3748 /* Error message detail may vary - it may not be empty and should contain
3749 * some information "connect" failed */
3750 ck_assert_str_ne(client_err, "");
3751 ck_assert(strstr(client_err, "connect"));
3752
3753
3754 /* This time start the server with a valid configuration */
3755 sprintf(bad_thread_num, "%i", 1);
3756 memset(errmsg, 0, sizeof(errmsg));
3757 ctx = test_mg_start(&callbacks, (void *)errmsg, OPTIONS, __LINE__);
3758
3759 ck_assert_str_eq(errmsg, "");
3760 ck_assert(ctx != NULL);
3761
3762
3763 /* Server is running now */
3764 test_sleep(1);
3765
3766 /* Remove error files (in case they exist) */
3767 (void)remove("error.htm");
3768 (void)remove("error4xx.htm");
3769 (void)remove("error404.htm");
3770
3771
3772 /* Ask for something not existing - should get default 404 */
3773 memset(client_err, 0, sizeof(client_err));
3774 client_conn =
3775 mg_connect_client("127.0.0.1", 8080, 0, client_err, sizeof(client_err));
3776
3777 ck_assert_str_eq(client_err, "");
3778 ck_assert(client_conn != NULL);
3779
3780 mg_printf(client_conn, "GET /something/not/existing HTTP/1.0\r\n\r\n");
3781 client_res =
3782 mg_get_response(client_conn, client_err, sizeof(client_err), 10000);
3783 ck_assert_int_ge(client_res, 0);
3784 ck_assert_str_eq(client_err, "");
3785 client_ri = mg_get_response_info(client_conn);
3786 ck_assert(client_ri != NULL);
3787
3788 ck_assert_int_eq(client_ri->status_code, 404);
3789 mg_close_connection(client_conn);
3790 test_sleep(1);
3791
3792 /* Create an error.htm file */
3793 f = fopen("error.htm", "wt");
3794 ck_assert(f != NULL);
3795 (void)fprintf(f, "err-all");
3796 (void)fclose(f);
3797
3798
3799 /* Ask for something not existing - should get error.htm */
3800 memset(client_err, 0, sizeof(client_err));
3801 client_conn =
3802 mg_connect_client("127.0.0.1", 8080, 0, client_err, sizeof(client_err));
3803
3804 ck_assert_str_eq(client_err, "");
3805 ck_assert(client_conn != NULL);
3806
3807 mg_printf(client_conn, "GET /something/not/existing HTTP/1.0\r\n\r\n");
3808 client_res =
3809 mg_get_response(client_conn, client_err, sizeof(client_err), 10000);
3810 ck_assert_int_ge(client_res, 0);
3811 ck_assert_str_eq(client_err, "");
3812 client_ri = mg_get_response_info(client_conn);
3813 ck_assert(client_ri != NULL);
3814
3815 ck_assert_int_eq(client_ri->status_code, 200);
3816
3817 client_res = (int)mg_read(client_conn, client_err, sizeof(client_err));
3818 mg_close_connection(client_conn);
3819 ck_assert_int_eq(client_res, 7);
3820 client_err[8] = 0;
3821 ck_assert_str_eq(client_err, "err-all");
3822 test_sleep(1);
3823
3824 /* Create an error4xx.htm file */
3825 f = fopen("error4xx.htm", "wt");
3826 ck_assert(f != NULL);
3827 (void)fprintf(f, "err-4xx");
3828 (void)fclose(f);
3829
3830
3831 /* Ask for something not existing - should get error4xx.htm */
3832 memset(client_err, 0, sizeof(client_err));
3833 client_conn =
3834 mg_connect_client("127.0.0.1", 8080, 0, client_err, sizeof(client_err));
3835
3836 ck_assert_str_eq(client_err, "");
3837 ck_assert(client_conn != NULL);
3838
3839 mg_printf(client_conn, "GET /something/not/existing HTTP/1.0\r\n\r\n");
3840 client_res =
3841 mg_get_response(client_conn, client_err, sizeof(client_err), 10000);
3842 ck_assert_int_ge(client_res, 0);
3843 ck_assert_str_eq(client_err, "");
3844 client_ri = mg_get_response_info(client_conn);
3845 ck_assert(client_ri != NULL);
3846
3847 ck_assert_int_eq(client_ri->status_code, 200);
3848
3849 client_res = (int)mg_read(client_conn, client_err, sizeof(client_err));
3850 mg_close_connection(client_conn);
3851 ck_assert_int_eq(client_res, 7);
3852 client_err[8] = 0;
3853 ck_assert_str_eq(client_err, "err-4xx");
3854 test_sleep(1);
3855
3856 /* Create an error404.htm file */
3857 f = fopen("error404.htm", "wt");
3858 ck_assert(f != NULL);
3859 (void)fprintf(f, "err-404");
3860 (void)fclose(f);
3861
3862
3863 /* Ask for something not existing - should get error404.htm */
3864 memset(client_err, 0, sizeof(client_err));
3865 client_conn =
3866 mg_connect_client("127.0.0.1", 8080, 0, client_err, sizeof(client_err));
3867
3868 ck_assert_str_eq(client_err, "");
3869 ck_assert(client_conn != NULL);
3870
3871 mg_printf(client_conn, "GET /something/not/existing HTTP/1.0\r\n\r\n");
3872 client_res =
3873 mg_get_response(client_conn, client_err, sizeof(client_err), 10000);
3874 ck_assert_int_ge(client_res, 0);
3875 ck_assert_str_eq(client_err, "");
3876 client_ri = mg_get_response_info(client_conn);
3877 ck_assert(client_ri != NULL);
3878
3879 ck_assert_int_eq(client_ri->status_code, 200);
3880
3881 client_res = (int)mg_read(client_conn, client_err, sizeof(client_err));
3882 mg_close_connection(client_conn);
3883 ck_assert_int_eq(client_res, 7);
3884 client_err[8] = 0;
3885 ck_assert_str_eq(client_err, "err-404");
3886 test_sleep(1);
3887
3888
3889 /* Ask in a malformed way - should get error4xx.htm */
3890 memset(client_err, 0, sizeof(client_err));
3891 client_conn =
3892 mg_connect_client("127.0.0.1", 8080, 0, client_err, sizeof(client_err));
3893
3894 ck_assert_str_eq(client_err, "");
3895 ck_assert(client_conn != NULL);
3896
3897 mg_printf(client_conn, "Gimme some file!\r\n\r\n");
3898 client_res =
3899 mg_get_response(client_conn, client_err, sizeof(client_err), 10000);
3900 ck_assert_int_ge(client_res, 0);
3901 ck_assert_str_eq(client_err, "");
3902 client_ri = mg_get_response_info(client_conn);
3903 ck_assert(client_ri != NULL);
3904
3905 ck_assert_int_eq(client_ri->status_code, 200);
3906
3907 client_res = (int)mg_read(client_conn, client_err, sizeof(client_err));
3908 mg_close_connection(client_conn);
3909 ck_assert_int_eq(client_res, 7);
3910 client_err[8] = 0;
3911 ck_assert_str_eq(client_err, "err-4xx");
3912 test_sleep(1);
3913
3914
3915 /* Remove all error files created by this test */
3916 (void)remove("error.htm");
3917 (void)remove("error4xx.htm");
3918 (void)remove("error404.htm");
3919
3920
3921 /* Stop the server */
3922 test_mg_stop(ctx, __LINE__);
3923
3924
3925 /* HTTP 1.1 GET request - must not work, since server is already stopped */
3926 memset(client_err, 0, sizeof(client_err));
3927 client_conn =
3928 mg_connect_client("127.0.0.1", 8080, 0, client_err, sizeof(client_err));
3929
3930 ck_assert(client_conn == NULL);
3931 ck_assert_str_ne(client_err, "");
3932
3933 test_sleep(1);
3934
3935 mark_point();
3936 }
3937 END_TEST
3938
3939
START_TEST(test_error_log_file)3940 START_TEST(test_error_log_file)
3941 {
3942 /* Server var */
3943 struct mg_context *ctx;
3944 const char *OPTIONS[32];
3945 int opt_cnt = 0;
3946
3947 /* Client var */
3948 struct mg_connection *client;
3949 char client_err_buf[256];
3950 char client_data_buf[256];
3951 const struct mg_response_info *client_ri;
3952
3953 /* File content check var */
3954 FILE *f;
3955 char buf[1024];
3956 int len, ok;
3957
3958 mark_point();
3959
3960 /* Set options and start server */
3961 OPTIONS[opt_cnt++] = "listening_ports";
3962 OPTIONS[opt_cnt++] = "8080";
3963 OPTIONS[opt_cnt++] = "error_log_file";
3964 OPTIONS[opt_cnt++] = "error.log";
3965 OPTIONS[opt_cnt++] = "access_log_file";
3966 OPTIONS[opt_cnt++] = "access.log";
3967 #if !defined(NO_FILES)
3968 OPTIONS[opt_cnt++] = "document_root";
3969 OPTIONS[opt_cnt++] = ".";
3970 #endif
3971 OPTIONS[opt_cnt] = NULL;
3972
3973 ctx = test_mg_start(NULL, 0, OPTIONS, __LINE__);
3974 ck_assert(ctx != NULL);
3975
3976 /* Remove log files (they may exist from previous incomplete runs of
3977 * this test) */
3978 (void)remove("error.log");
3979 (void)remove("access.log");
3980
3981 /* connect client */
3982 memset(client_err_buf, 0, sizeof(client_err_buf));
3983 memset(client_data_buf, 0, sizeof(client_data_buf));
3984
3985 client = mg_download("127.0.0.1",
3986 8080,
3987 0,
3988 client_err_buf,
3989 sizeof(client_err_buf),
3990 "GET /not_existing_file.ext HTTP/1.0\r\n\r\n");
3991
3992 ck_assert(ctx != NULL);
3993 ck_assert_str_eq(client_err_buf, "");
3994
3995 client_ri = mg_get_response_info(client);
3996
3997 /* Check status - should be 404 Not Found */
3998 ck_assert(client_ri != NULL);
3999 ck_assert_int_eq(client_ri->status_code, 404);
4000
4001 /* Get body data (could exist, but does not have to) */
4002 len = mg_read(client, client_data_buf, sizeof(client_data_buf));
4003 ck_assert_int_ge(len, 0);
4004
4005 /* Close the client connection */
4006 mg_close_connection(client);
4007
4008 /* Stop the server */
4009 test_mg_stop(ctx, __LINE__);
4010
4011
4012 /* Check access.log */
4013 memset(buf, 0, sizeof(buf));
4014 f = fopen("access.log", "r");
4015 ck_assert_msg(f != NULL, "Cannot open access log file");
4016 ok = (NULL != fgets(buf, sizeof(buf) - 1, f));
4017 (void)fclose(f);
4018 ck_assert_msg(ok, "Cannot read access log file");
4019 len = (int)strlen(buf);
4020 ck_assert_int_gt(len, 0);
4021 ok = (NULL != strstr(buf, "not_existing_file.ext"));
4022 ck_assert_msg(ok, "Did not find uri in access log file");
4023 ok = (NULL != strstr(buf, "404"));
4024 ck_assert_msg(ok, "Did not find HTTP status code in access log file");
4025
4026 /* Check error.log */
4027 memset(buf, 0, sizeof(buf));
4028 f = fopen("error.log", "r");
4029 if (f) {
4030 (void)fgets(buf, sizeof(buf) - 1, f);
4031 fclose(f);
4032 }
4033 ck_assert_msg(f == NULL,
4034 "Should not create error log file on 404, but got [%s]",
4035 buf);
4036
4037 /* Remove log files */
4038 (void)remove("error.log");
4039 (void)remove("access.log");
4040
4041 /* Start server with bad options */
4042 ck_assert_str_eq(OPTIONS[0], "listening_ports");
4043 OPTIONS[1] = "bad !"; /* no r or s in string */
4044
4045 ctx = test_mg_start(NULL, 0, OPTIONS, 0);
4046 ck_assert_msg(
4047 ctx == NULL,
4048 "Should not be able to start server with bad port configuration");
4049
4050 /* Check access.log */
4051 memset(buf, 0, sizeof(buf));
4052 f = fopen("access.log", "r");
4053 if (f) {
4054 (void)fgets(buf, sizeof(buf) - 1, f);
4055 fclose(f);
4056 }
4057 ck_assert_msg(
4058 f == NULL,
4059 "Should not create access log file if start fails, but got [%s]",
4060 buf);
4061
4062 /* Check error.log */
4063 memset(buf, 0, sizeof(buf));
4064 f = fopen("error.log", "r");
4065 ck_assert_msg(f != NULL, "Cannot open access log file");
4066 ok = (NULL != fgets(buf, sizeof(buf) - 1, f));
4067 (void)fclose(f);
4068 ck_assert_msg(ok, "Cannot read access log file");
4069 len = (int)strlen(buf);
4070 ck_assert_int_gt(len, 0);
4071 ok = (NULL != strstr(buf, "port"));
4072 ck_assert_msg(ok, "Did not find port as error reason in error log file");
4073
4074
4075 /* Remove log files */
4076 (void)remove("error.log");
4077 (void)remove("access.log");
4078
4079 mark_point();
4080 }
4081 END_TEST
4082
4083
4084 static int
test_throttle_begin_request(struct mg_connection * conn)4085 test_throttle_begin_request(struct mg_connection *conn)
4086 {
4087 const struct mg_request_info *ri;
4088 long unsigned len = 1024 * 10;
4089 const char *block = "0123456789";
4090 unsigned long i, blocklen;
4091
4092 ck_assert(conn != NULL);
4093 ri = mg_get_request_info(conn);
4094 ck_assert(ri != NULL);
4095
4096 ck_assert_str_eq(ri->request_method, "GET");
4097 ck_assert_str_eq(ri->request_uri, "/throttle");
4098 ck_assert_str_eq(ri->local_uri, "/throttle");
4099 ck_assert_str_eq(ri->http_version, "1.0");
4100 ck_assert_str_eq(ri->query_string, "q");
4101 ck_assert_str_eq(ri->remote_addr, "127.0.0.1");
4102
4103 mg_printf(conn,
4104 "HTTP/1.1 200 OK\r\n"
4105 "Content-Length: %lu\r\n"
4106 "Connection: close\r\n\r\n",
4107 len);
4108
4109 blocklen = (unsigned long)strlen(block);
4110
4111 for (i = 0; i < len; i += blocklen) {
4112 mg_write(conn, block, blocklen);
4113 }
4114
4115 mark_point();
4116
4117 return 987; /* Not a valid HTTP response code,
4118 * but it should be written to the log and passed to
4119 * end_request. */
4120 }
4121
4122
4123 static void
test_throttle_end_request(const struct mg_connection * conn,int reply_status_code)4124 test_throttle_end_request(const struct mg_connection *conn,
4125 int reply_status_code)
4126 {
4127 const struct mg_request_info *ri;
4128
4129 ck_assert(conn != NULL);
4130 ri = mg_get_request_info(conn);
4131 ck_assert(ri != NULL);
4132
4133 ck_assert_str_eq(ri->request_method, "GET");
4134 ck_assert_str_eq(ri->request_uri, "/throttle");
4135 ck_assert_str_eq(ri->local_uri, "/throttle");
4136 ck_assert_str_eq(ri->http_version, "1.0");
4137 ck_assert_str_eq(ri->query_string, "q");
4138 ck_assert_str_eq(ri->remote_addr, "127.0.0.1");
4139
4140 ck_assert_int_eq(reply_status_code, 987);
4141 }
4142
4143
START_TEST(test_throttle)4144 START_TEST(test_throttle)
4145 {
4146 /* Server var */
4147 struct mg_context *ctx;
4148 struct mg_callbacks callbacks;
4149 const char *OPTIONS[32];
4150 int opt_cnt = 0;
4151
4152 /* Client var */
4153 struct mg_connection *client;
4154 char client_err_buf[256];
4155 char client_data_buf[256];
4156 const struct mg_response_info *client_ri;
4157
4158 /* timing test */
4159 int r, data_read;
4160 time_t t0, t1;
4161 double dt;
4162
4163 mark_point();
4164
4165
4166 /* Set options and start server */
4167 #if !defined(NO_FILES)
4168 OPTIONS[opt_cnt++] = "document_root";
4169 OPTIONS[opt_cnt++] = ".";
4170 #endif
4171 OPTIONS[opt_cnt++] = "listening_ports";
4172 OPTIONS[opt_cnt++] = "8080";
4173 OPTIONS[opt_cnt++] = "throttle";
4174 OPTIONS[opt_cnt++] = "*=1k";
4175 OPTIONS[opt_cnt] = NULL;
4176
4177 memset(&callbacks, 0, sizeof(callbacks));
4178 callbacks.begin_request = test_throttle_begin_request;
4179 callbacks.end_request = test_throttle_end_request;
4180
4181 ctx = test_mg_start(&callbacks, 0, OPTIONS, __LINE__);
4182 ck_assert(ctx != NULL);
4183
4184 /* connect client */
4185 memset(client_err_buf, 0, sizeof(client_err_buf));
4186 memset(client_data_buf, 0, sizeof(client_data_buf));
4187
4188 strcpy(client_err_buf, "reset-content");
4189 client = mg_download("127.0.0.1",
4190 8080,
4191 0,
4192 client_err_buf,
4193 sizeof(client_err_buf),
4194 "GET /throttle?q HTTP/1.0\r\n\r\n");
4195
4196 ck_assert(ctx != NULL);
4197 ck_assert_str_eq(client_err_buf, "");
4198
4199 client_ri = mg_get_response_info(client);
4200
4201 ck_assert(client_ri != NULL);
4202 ck_assert_int_eq(client_ri->status_code, 200);
4203
4204 ck_assert_int_eq(client_ri->content_length, 1024 * 10);
4205
4206 data_read = 0;
4207 t0 = time(NULL);
4208 while (data_read < client_ri->content_length) {
4209 r = mg_read(client, client_data_buf, sizeof(client_data_buf));
4210 ck_assert_int_ge(r, 0);
4211 data_read += r;
4212 }
4213 t1 = time(NULL);
4214 dt = difftime(t1, t0) * 1000.0; /* Elapsed time in ms - in most systems
4215 * only with second resolution */
4216
4217 /* Time estimation: Data size is 10 kB, with 1 kB/s speed limit.
4218 * The first block (1st kB) is transferred immediately, the second
4219 * block (2nd kB) one second later, the third block (3rd kB) two
4220 * seconds later, .. the last block (10th kB) nine seconds later.
4221 * The resolution of time measurement using the "time" C library
4222 * function is 1 second, so we should add +/- one second tolerance.
4223 * Thus, download of 10 kB with 1 kB/s should not be faster than
4224 * 8 seconds. */
4225
4226 /* Check if there are at least 8 seconds */
4227 ck_assert_int_ge((int)dt, 8 * 1000);
4228
4229 /* Nothing left to read */
4230 r = mg_read(client, client_data_buf, sizeof(client_data_buf));
4231 ck_assert_int_eq(r, 0);
4232
4233 /* Close the client connection */
4234 mg_close_connection(client);
4235
4236 /* Stop the server */
4237 test_mg_stop(ctx, __LINE__);
4238
4239 mark_point();
4240 }
4241 END_TEST
4242
4243
START_TEST(test_init_library)4244 START_TEST(test_init_library)
4245 {
4246 unsigned f_avail, f_ret;
4247
4248 mark_point();
4249
4250 f_avail = mg_check_feature(0xFF);
4251 f_ret = mg_init_library(f_avail);
4252 ck_assert_uint_eq(f_ret, f_avail);
4253 }
4254 END_TEST
4255
4256
4257 #define LARGE_FILE_SIZE (1024 * 1024 * 10)
4258
4259 static int
test_large_file_begin_request(struct mg_connection * conn)4260 test_large_file_begin_request(struct mg_connection *conn)
4261 {
4262 const struct mg_request_info *ri;
4263 long unsigned len = LARGE_FILE_SIZE;
4264 const char *block = "0123456789";
4265 uint64_t i;
4266 size_t blocklen;
4267
4268 ck_assert(conn != NULL);
4269 ri = mg_get_request_info(conn);
4270 ck_assert(ri != NULL);
4271
4272 ck_assert_str_eq(ri->request_method, "GET");
4273 ck_assert_str_eq(ri->http_version, "1.1");
4274 ck_assert_str_eq(ri->remote_addr, "127.0.0.1");
4275 ck_assert_ptr_eq(ri->query_string, NULL);
4276 ck_assert_ptr_ne(ri->local_uri, NULL);
4277
4278 mg_printf(conn,
4279 "HTTP/1.1 200 OK\r\n"
4280 "Content-Length: %lu\r\n"
4281 "Connection: close\r\n\r\n",
4282 len);
4283
4284 blocklen = strlen(block);
4285
4286 for (i = 0; i < len; i += blocklen) {
4287 mg_write(conn, block, blocklen);
4288 }
4289
4290 mark_point();
4291
4292 return 200;
4293 }
4294
4295
START_TEST(test_large_file)4296 START_TEST(test_large_file)
4297 {
4298 /* Server var */
4299 struct mg_context *ctx;
4300 struct mg_callbacks callbacks;
4301 const char *OPTIONS[32];
4302 int opt_cnt = 0;
4303 #if !defined(NO_SSL)
4304 const char *ssl_cert = locate_ssl_cert();
4305 #endif
4306 char errmsg[256] = {0};
4307
4308 /* Client var */
4309 struct mg_connection *client;
4310 char client_err_buf[256];
4311 char client_data_buf[256];
4312 const struct mg_response_info *client_ri;
4313 int64_t data_read;
4314 int r;
4315 int retry, retry_ok_cnt, retry_fail_cnt;
4316
4317 mark_point();
4318
4319 /* Set options and start server */
4320 #if !defined(NO_FILES)
4321 OPTIONS[opt_cnt++] = "document_root";
4322 OPTIONS[opt_cnt++] = ".";
4323 #endif
4324 #if defined(NO_SSL)
4325 OPTIONS[opt_cnt++] = "listening_ports";
4326 OPTIONS[opt_cnt++] = "8080";
4327 #else
4328 OPTIONS[opt_cnt++] = "listening_ports";
4329 OPTIONS[opt_cnt++] = "8443s";
4330 OPTIONS[opt_cnt++] = "ssl_certificate";
4331 OPTIONS[opt_cnt++] = ssl_cert;
4332 #ifdef __MACH__
4333 /* The Apple builds on Travis CI seem to have problems with TLS1.x
4334 * Allow SSLv3 and TLS */
4335 OPTIONS[opt_cnt++] = "ssl_protocol_version";
4336 OPTIONS[opt_cnt++] = "2";
4337 #else
4338 /* The Linux builds on Travis CI work fine with TLS1.2 */
4339 OPTIONS[opt_cnt++] = "ssl_protocol_version";
4340 OPTIONS[opt_cnt++] = "4";
4341 #endif
4342 ck_assert(ssl_cert != NULL);
4343 #endif
4344 OPTIONS[opt_cnt] = NULL;
4345
4346
4347 memset(&callbacks, 0, sizeof(callbacks));
4348 callbacks.begin_request = test_large_file_begin_request;
4349 callbacks.log_message = log_msg_func;
4350
4351 ctx = test_mg_start(&callbacks, (void *)errmsg, OPTIONS, __LINE__);
4352 ck_assert_str_eq(errmsg, "");
4353 ck_assert(ctx != NULL);
4354
4355 /* Try downloading several times */
4356 retry_ok_cnt = 0;
4357 retry_fail_cnt = 0;
4358 for (retry = 0; retry < 3; retry++) {
4359 int fail = 0;
4360 /* connect client */
4361 memset(client_err_buf, 0, sizeof(client_err_buf));
4362 memset(client_data_buf, 0, sizeof(client_data_buf));
4363
4364 client =
4365 mg_download("127.0.0.1",
4366 #if defined(NO_SSL)
4367 8080,
4368 0,
4369 #else
4370 8443,
4371 1,
4372 #endif
4373 client_err_buf,
4374 sizeof(client_err_buf),
4375 "GET /large.file HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n");
4376
4377 ck_assert(client != NULL);
4378 ck_assert_str_eq(client_err_buf, "");
4379
4380 client_ri = mg_get_response_info(client);
4381
4382 ck_assert(client_ri != NULL);
4383 ck_assert_int_eq(client_ri->status_code, 200);
4384
4385 ck_assert_int_eq(client_ri->content_length, LARGE_FILE_SIZE);
4386
4387 data_read = 0;
4388 while (data_read < client_ri->content_length) {
4389 r = mg_read(client, client_data_buf, sizeof(client_data_buf));
4390 if (r < 0) {
4391 fail = 1;
4392 break;
4393 };
4394 data_read += r;
4395 }
4396
4397 /* Nothing left to read */
4398 r = mg_read(client, client_data_buf, sizeof(client_data_buf));
4399 if (fail) {
4400 ck_assert_int_eq(r, -1);
4401 retry_fail_cnt++;
4402 } else {
4403 ck_assert_int_eq(r, 0);
4404 retry_ok_cnt++;
4405 }
4406
4407 /* Close the client connection */
4408 mg_close_connection(client);
4409 }
4410
4411 #if defined(_WIN32)
4412 // TODO: Check this problem on AppVeyor
4413 // ck_assert_int_le(retry_fail_cnt, 2);
4414 // ck_assert_int_ge(retry_ok_cnt, 1);
4415 #else
4416 ck_assert_int_eq(retry_fail_cnt, 0);
4417 ck_assert_int_eq(retry_ok_cnt, 3);
4418 #endif
4419
4420 /* Stop the server */
4421 test_mg_stop(ctx, __LINE__);
4422
4423 mark_point();
4424 }
4425 END_TEST
4426
4427
4428 static int test_mg_store_body_con_len = 20000;
4429
4430
4431 static int
test_mg_store_body_put_delete_handler(struct mg_connection * conn,void * ignored)4432 test_mg_store_body_put_delete_handler(struct mg_connection *conn, void *ignored)
4433 {
4434 char path[4096] = {0};
4435 const struct mg_request_info *info = mg_get_request_info(conn);
4436 int64_t rc;
4437
4438 (void)ignored;
4439
4440 mark_point();
4441
4442 sprintf(path, "./%s", info->local_uri);
4443 rc = mg_store_body(conn, path);
4444
4445 ck_assert_int_eq(test_mg_store_body_con_len, rc);
4446
4447 if (rc < 0) {
4448 mg_printf(conn,
4449 "HTTP/1.1 500 Internal Server Error\r\n"
4450 "Content-Type:text/plain;charset=UTF-8\r\n"
4451 "Connection:close\r\n\r\n"
4452 "%s (ret: %ld)\n",
4453 path,
4454 (long)rc);
4455 mg_close_connection(conn);
4456
4457 /* Debug output for tests */
4458 printf("mg_store_body(%s) failed (ret: %ld)\n", path, (long)rc);
4459
4460 return 500;
4461 }
4462
4463 mg_printf(conn,
4464 "HTTP/1.1 200 OK\r\n"
4465 "Content-Type:text/plain;charset=UTF-8\r\n"
4466 "Connection:close\r\n\r\n"
4467 "%s OK (%ld bytes saved)\n",
4468 path,
4469 (long)rc);
4470 mg_close_connection(conn);
4471
4472 /* Debug output for tests */
4473 printf("mg_store_body(%s) OK (%ld bytes)\n", path, (long)rc);
4474
4475 mark_point();
4476
4477 return 200;
4478 }
4479
4480
4481 static int
test_mg_store_body_begin_request_callback(struct mg_connection * conn)4482 test_mg_store_body_begin_request_callback(struct mg_connection *conn)
4483 {
4484 const struct mg_request_info *info = mg_get_request_info(conn);
4485
4486 mark_point();
4487
4488 /* Debug output for tests */
4489 printf("test_mg_store_body_begin_request_callback called (%s)\n",
4490 info->request_method);
4491
4492 if ((strcmp(info->request_method, "PUT") == 0)
4493 || (strcmp(info->request_method, "DELETE") == 0)) {
4494 return test_mg_store_body_put_delete_handler(conn, NULL);
4495 }
4496
4497 mark_point();
4498
4499 return 0;
4500 }
4501
4502
START_TEST(test_mg_store_body)4503 START_TEST(test_mg_store_body)
4504 {
4505 /* Client data */
4506 char client_err_buf[256];
4507 char client_data_buf[1024];
4508 struct mg_connection *client;
4509 const struct mg_response_info *client_ri;
4510 int r;
4511 char check_data[256];
4512 char *check_ptr;
4513 char errmsg[256] = {0};
4514
4515 /* Server context handle */
4516 struct mg_context *ctx;
4517 struct mg_callbacks callbacks;
4518 const char *options[] = {
4519 #if !defined(NO_FILES)
4520 "document_root",
4521 ".",
4522 #endif
4523 #if !defined(NO_CACHING)
4524 "static_file_max_age",
4525 "0",
4526 #endif
4527 "listening_ports",
4528 "127.0.0.1:8082",
4529 "num_threads",
4530 "1",
4531 NULL
4532 };
4533
4534 mark_point();
4535
4536 memset(&callbacks, 0, sizeof(callbacks));
4537 callbacks.begin_request = test_mg_store_body_begin_request_callback;
4538 callbacks.log_message = log_msg_func;
4539
4540 /* Initialize the library */
4541 mg_init_library(0);
4542
4543 /* Start the server */
4544 ctx = mg_start(&callbacks, (void *)errmsg, options);
4545 ck_assert_str_eq(errmsg, "");
4546 ck_assert(ctx != NULL);
4547
4548 /* Run the server for 15 seconds */
4549 test_sleep(15);
4550
4551 /* Call a test client */
4552 client = mg_connect_client(
4553 "127.0.0.1", 8082, 0, client_err_buf, sizeof(client_err_buf));
4554
4555 ck_assert_str_eq(client_err_buf, "");
4556 ck_assert(client != NULL);
4557
4558 mg_printf(client,
4559 "PUT /%s HTTP/1.0\r\nContent-Length: %i\r\n\r\n",
4560 "test_file_name.txt",
4561 test_mg_store_body_con_len);
4562
4563 r = 0;
4564 while (r < test_mg_store_body_con_len) {
4565 int l = mg_write(client, "1234567890", 10);
4566 ck_assert_int_eq(l, 10);
4567 r += 10;
4568 }
4569
4570 r = mg_get_response(client, client_err_buf, sizeof(client_err_buf), 10000);
4571 ck_assert_int_ge(r, 0);
4572 ck_assert_str_eq(client_err_buf, "");
4573
4574 client_ri = mg_get_response_info(client);
4575 ck_assert(client_ri != NULL);
4576
4577 /* Response must be 200 OK */
4578 ck_assert_int_eq(client_ri->status_code, 200);
4579
4580 /* Read PUT response */
4581 r = mg_read(client, client_data_buf, sizeof(client_data_buf) - 1);
4582 ck_assert_int_gt(r, 0);
4583 client_data_buf[r] = 0;
4584
4585 sprintf(check_data, "(%i bytes saved)", test_mg_store_body_con_len);
4586 check_ptr = strstr(client_data_buf, check_data);
4587 ck_assert_ptr_ne(check_ptr, NULL);
4588
4589 mg_close_connection(client);
4590
4591 /* Run the server for 5 seconds */
4592 test_sleep(5);
4593
4594 /* Stop the server */
4595 test_mg_stop(ctx, __LINE__);
4596
4597 /* Un-initialize the library */
4598 mg_exit_library();
4599
4600 mark_point();
4601 }
4602 END_TEST
4603
4604
4605 #if defined(MG_USE_OPEN_FILE) && !defined(NO_FILES)
4606
4607 #define FILE_IN_MEM_SIZE (1024 * 100)
4608 static char *file_in_mem_data;
4609
4610 static const char *
test_file_in_memory_open_file(const struct mg_connection * conn,const char * file_path,size_t * file_size)4611 test_file_in_memory_open_file(const struct mg_connection *conn,
4612 const char *file_path,
4613 size_t *file_size)
4614 {
4615 (void)conn;
4616
4617 if (strcmp(file_path, "./file_in_mem") == 0) {
4618 /* File is in memory */
4619 *file_size = FILE_IN_MEM_SIZE;
4620 return file_in_mem_data;
4621 } else {
4622 /* File is not in memory */
4623 return NULL;
4624 }
4625 }
4626
4627
START_TEST(test_file_in_memory)4628 START_TEST(test_file_in_memory)
4629 {
4630 /* Server var */
4631 struct mg_context *ctx;
4632 struct mg_callbacks callbacks;
4633 const char *OPTIONS[32];
4634 int opt_cnt = 0;
4635 #if !defined(NO_SSL)
4636 const char *ssl_cert = locate_ssl_cert();
4637 #endif
4638
4639 /* Client var */
4640 struct mg_connection *client;
4641 char client_err_buf[256];
4642 char client_data_buf[256];
4643 const struct mg_request_info *client_ri;
4644 int64_t data_read;
4645 int r, i;
4646
4647 /* Prepare test data */
4648 file_in_mem_data = (char *)malloc(FILE_IN_MEM_SIZE);
4649 ck_assert_ptr_ne(file_in_mem_data, NULL);
4650 for (r = 0; r < FILE_IN_MEM_SIZE; r++) {
4651 file_in_mem_data[r] = (char)(r);
4652 }
4653
4654 /* Set options and start server */
4655 OPTIONS[opt_cnt++] = "document_root";
4656 OPTIONS[opt_cnt++] = ".";
4657 #if defined(NO_SSL)
4658 OPTIONS[opt_cnt++] = "listening_ports";
4659 OPTIONS[opt_cnt++] = "8080";
4660 #else
4661 OPTIONS[opt_cnt++] = "listening_ports";
4662 OPTIONS[opt_cnt++] = "8443s";
4663 OPTIONS[opt_cnt++] = "ssl_certificate";
4664 OPTIONS[opt_cnt++] = ssl_cert;
4665 ck_assert(ssl_cert != NULL);
4666 #endif
4667 OPTIONS[opt_cnt] = NULL;
4668
4669
4670 memset(&callbacks, 0, sizeof(callbacks));
4671 callbacks.open_file = test_file_in_memory_open_file;
4672
4673 ctx = test_mg_start(&callbacks, 0, OPTIONS, __LINE__);
4674 ck_assert(ctx != NULL);
4675
4676 /* connect client */
4677 memset(client_err_buf, 0, sizeof(client_err_buf));
4678 memset(client_data_buf, 0, sizeof(client_data_buf));
4679
4680 client =
4681 mg_download("127.0.0.1",
4682 #if defined(NO_SSL)
4683 8080,
4684 0,
4685 #else
4686 8443,
4687 1,
4688 #endif
4689 client_err_buf,
4690 sizeof(client_err_buf),
4691 "GET /file_in_mem HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n");
4692
4693 ck_assert(client != NULL);
4694 ck_assert_str_eq(client_err_buf, "");
4695
4696 client_ri = mg_get_response_info(client);
4697
4698 ck_assert(client_ri != NULL);
4699 ck_assert_int_eq(client_ri->status_code, 200);
4700
4701 ck_assert_int_eq(client_ri->content_length, FILE_IN_MEM_SIZE);
4702
4703 data_read = 0;
4704 while (data_read < client_ri->content_length) {
4705 r = mg_read(client, client_data_buf, sizeof(client_data_buf));
4706 if (r > 0) {
4707 for (i = 0; i < r; i++) {
4708 ck_assert_int_eq((int)client_data_buf[i],
4709 (int)file_in_mem_data[data_read + i]);
4710 }
4711 data_read += r;
4712 }
4713 }
4714
4715 /* Nothing left to read */
4716 r = mg_read(client, client_data_buf, sizeof(client_data_buf));
4717 ck_assert_int_eq(r, 0);
4718
4719 /* Close the client connection */
4720 mg_close_connection(client);
4721
4722 /* Stop the server */
4723 test_mg_stop(ctx, __LINE__);
4724
4725 /* Free test data */
4726 free(file_in_mem_data);
4727 file_in_mem_data = NULL;
4728 }
4729 END_TEST
4730
4731 #else /* defined(MG_USE_OPEN_FILE) */
4732
4733 START_TEST(test_file_in_memory)
4734 {
4735 mark_point();
4736 }
4737 END_TEST
4738
4739 #endif
4740
4741
4742 static void
minimal_http_https_client_impl(const char * server,uint16_t port,int use_ssl,const char * uri,const char * expected)4743 minimal_http_https_client_impl(const char *server,
4744 uint16_t port,
4745 int use_ssl,
4746 const char *uri,
4747 const char *expected)
4748 {
4749 /* Client var */
4750 struct mg_connection *client;
4751 char client_err_buf[256];
4752 char client_data_buf[4096];
4753 const struct mg_response_info *client_ri;
4754 int64_t data_read;
4755 int r;
4756
4757 mark_point();
4758
4759 client = mg_connect_client(
4760 server, port, use_ssl, client_err_buf, sizeof(client_err_buf));
4761
4762 if ((client == NULL) || (0 != strcmp(client_err_buf, ""))) {
4763 ck_abort_msg("%s connection to server [%s] port [%u] failed: [%s]",
4764 use_ssl ? "HTTPS" : "HTTP",
4765 server,
4766 port,
4767 client_err_buf);
4768 }
4769
4770 mg_printf(client, "GET %s HTTP/1.0\r\n\r\n", uri);
4771
4772 r = mg_get_response(client, client_err_buf, sizeof(client_err_buf), 10000);
4773
4774 if ((r < 0) || (0 != strcmp(client_err_buf, ""))) {
4775 ck_abort_msg(
4776 "%s connection to server [%s] port [%u] did not respond: [%s]",
4777 use_ssl ? "HTTPS" : "HTTP",
4778 server,
4779 port,
4780 client_err_buf);
4781 }
4782
4783 client_ri = mg_get_response_info(client);
4784 ck_assert(client_ri != NULL);
4785
4786 /* Check for status code 200 OK or 30? moved */
4787 if ((client_ri->status_code != 200)
4788 && (client_ri->status_code / 10 != 30)) {
4789 ck_abort_msg("Request to %s://%s:%u/%s: Status %u",
4790 use_ssl ? "HTTPS" : "HTTP",
4791 server,
4792 port,
4793 uri,
4794 client_ri->status_code);
4795 }
4796
4797 data_read = 0;
4798 while (data_read < client_ri->content_length) {
4799 r = mg_read(client,
4800 client_data_buf + data_read,
4801 sizeof(client_data_buf) - (size_t)data_read);
4802 if (r > 0) {
4803 data_read += r;
4804 ck_assert_int_lt(data_read, sizeof(client_data_buf));
4805 }
4806 }
4807
4808 /* Nothing left to read */
4809 r = mg_read(client, client_data_buf, sizeof(client_data_buf));
4810 ck_assert_int_eq(r, 0);
4811
4812 mark_point();
4813
4814 if (expected) {
4815 ck_assert_str_eq(client_data_buf, expected);
4816 }
4817
4818 mark_point();
4819
4820 mg_close_connection(client);
4821
4822 mark_point();
4823 }
4824
4825
4826 static void
minimal_http_client_check(const char * server,uint16_t port,const char * uri,const char * expected)4827 minimal_http_client_check(const char *server,
4828 uint16_t port,
4829 const char *uri,
4830 const char *expected)
4831 {
4832 minimal_http_https_client_impl(server, port, 0, uri, expected);
4833 }
4834
4835
4836 #if !defined(NO_SSL)
4837 static void
minimal_https_client_check(const char * server,uint16_t port,const char * uri,const char * expected)4838 minimal_https_client_check(const char *server,
4839 uint16_t port,
4840 const char *uri,
4841 const char *expected)
4842 {
4843 minimal_http_https_client_impl(server, port, 1, uri, expected);
4844 }
4845 #endif
4846
4847
START_TEST(test_minimal_client)4848 START_TEST(test_minimal_client)
4849 {
4850 const char *external_server_ip;
4851 mark_point();
4852 external_server_ip = get_external_server_ip();
4853 mark_point();
4854
4855 /* Initialize the library */
4856 mg_init_library(0);
4857
4858 mark_point();
4859
4860 /* Call a test client */
4861 minimal_http_client_check(external_server_ip,
4862 80,
4863 "/civetweb/civetweb/",
4864 NULL /* no check */);
4865
4866 mark_point();
4867
4868 /* Un-initialize the library */
4869 mg_exit_library();
4870
4871 mark_point();
4872 }
4873 END_TEST
4874
4875
START_TEST(test_minimal_tls_client)4876 START_TEST(test_minimal_tls_client)
4877 {
4878 const char *external_server_ip;
4879 mark_point();
4880 external_server_ip = get_external_server_ip();
4881 mark_point();
4882
4883 #if !defined(NO_SSL) /* dont run https test if SSL is not enabled */
4884
4885 #if (!defined(__MACH__) || defined(LOCAL_TEST)) && !defined(OPENSSL_API_1_1)
4886 /* dont run on Travis OSX worker with OpenSSL 1.0 */
4887
4888 /* Initialize the library */
4889 mg_init_library(2);
4890
4891 mark_point();
4892
4893 /* Call a test client */
4894 minimal_https_client_check(external_server_ip,
4895 443,
4896 "/civetweb/civetweb/",
4897 NULL /* no check */);
4898
4899 mark_point();
4900
4901 /* Un-initialize the library */
4902 mg_exit_library();
4903
4904 #endif
4905 #endif
4906
4907 mark_point();
4908 }
4909 END_TEST
4910
4911
4912 static int
minimal_test_request_handler(struct mg_connection * conn,void * cbdata)4913 minimal_test_request_handler(struct mg_connection *conn, void *cbdata)
4914 {
4915 const char *msg = (const char *)cbdata;
4916 unsigned long len = (unsigned long)strlen(msg) + 1;
4917 const struct mg_request_info *ri = mg_get_request_info(conn);
4918
4919 ck_assert(conn != NULL);
4920 ck_assert(ri != NULL);
4921 ck_assert(len > 0);
4922
4923 ck_assert_str_eq(ri->request_method, "GET");
4924 ck_assert(ri->request_uri[0] == '/');
4925 ck_assert(ri->local_uri[0] == '/');
4926 ck_assert(ri->http_version[0] == '1');
4927 ck_assert(ri->http_version[1] == '.');
4928 ck_assert(ri->http_version[3] == 0);
4929 ck_assert(ri->num_headers >= 0);
4930
4931 if (ri->query_string != NULL) {
4932 msg = ri->query_string;
4933 len = (unsigned long)strlen(msg) + 1;
4934 }
4935
4936 mg_printf(conn,
4937 "HTTP/1.1 200 OK\r\n"
4938 "Content-Length: %lu\r\n"
4939 "Content-Type: text/plain\r\n"
4940 "Connection: close\r\n\r\n",
4941 len);
4942
4943 mark_point();
4944
4945 mg_write(conn, msg, len);
4946
4947 mark_point();
4948
4949 return 200;
4950 }
4951
4952
START_TEST(test_minimal_http_server_callback)4953 START_TEST(test_minimal_http_server_callback)
4954 {
4955 /* This test should ensure the minimum server example in
4956 * docs/Embedding.md is still running. */
4957
4958 /* Server context handle */
4959 struct mg_context *ctx;
4960
4961 mark_point();
4962
4963 /* Initialize the library */
4964 mg_init_library(0);
4965
4966 /* Start the server */
4967 ctx = test_mg_start(NULL, 0, NULL, __LINE__);
4968 ck_assert(ctx != NULL);
4969
4970 /* Add some handler */
4971 mg_set_request_handler(ctx,
4972 "/hello",
4973 minimal_test_request_handler,
4974 (void *)"Hello world");
4975 mg_set_request_handler(ctx,
4976 "/8",
4977 minimal_test_request_handler,
4978 (void *)"Number eight");
4979
4980 /* Run the server for 15 seconds */
4981 test_sleep(10);
4982
4983 /* Call a test client */
4984 minimal_http_client_check("127.0.0.1", 8080, "/hello", "Hello world");
4985
4986 /* Run the server for 1 second */
4987 test_sleep(1);
4988
4989 /* Call a test client */
4990 minimal_http_client_check("127.0.0.1", 8080, "/8", "Number eight");
4991
4992 /* Run the server for 1 second */
4993 test_sleep(1);
4994
4995 /* Call a test client */
4996 minimal_http_client_check("127.0.0.1",
4997 8080,
4998 "/8?Altenative=Response",
4999 "Altenative=Response");
5000
5001 /* Run the server for 5 seconds */
5002 test_sleep(5);
5003
5004
5005 /* Stop the server */
5006 test_mg_stop(ctx, __LINE__);
5007
5008 /* Un-initialize the library */
5009 mg_exit_library();
5010
5011 mark_point();
5012 }
5013 END_TEST
5014
5015
START_TEST(test_minimal_https_server_callback)5016 START_TEST(test_minimal_https_server_callback)
5017 {
5018 #if !defined(NO_SSL)
5019 /* This test should show a HTTPS server with enhanced
5020 * security settings.
5021 *
5022 * Articles:
5023 * https://hynek.me/articles/hardening-your-web-servers-ssl-ciphers/
5024 *
5025 * Scanners:
5026 * https://securityheaders.io/
5027 * https://www.htbridge.com/ssl/
5028 * https://www.htbridge.com/websec/
5029 * https://www.ssllabs.com/ssltest/
5030 * https://www.qualys.com/forms/freescan/
5031 */
5032
5033 /* Server context handle */
5034 struct mg_context *ctx;
5035
5036 /* Server start parameters for HTTPS */
5037 const char *OPTIONS[32];
5038 int opt_idx = 0;
5039
5040 /* HTTPS port - required */
5041 OPTIONS[opt_idx++] = "listening_ports";
5042 OPTIONS[opt_idx++] = "8443s";
5043
5044 /* path to certificate file - required */
5045 OPTIONS[opt_idx++] = "ssl_certificate";
5046 OPTIONS[opt_idx++] = locate_ssl_cert();
5047
5048 #if defined(LOCAL_TEST) || defined(_WIN32)
5049 /* Do not set this on Travis CI, since the build containers
5050 * contain older SSL libraries */
5051
5052 /* set minimum SSL version to TLS 1.2 - recommended */
5053 OPTIONS[opt_idx++] = "ssl_protocol_version";
5054 OPTIONS[opt_idx++] = "4";
5055
5056 /* set some modern ciphers - recommended */
5057 OPTIONS[opt_idx++] = "ssl_cipher_list";
5058 OPTIONS[opt_idx++] = "ECDH+AESGCM+AES256:!aNULL:!MD5:!DSS";
5059 #endif
5060
5061 /* set "HTTPS only" header - recommended */
5062 OPTIONS[opt_idx++] = "strict_transport_security_max_age";
5063 OPTIONS[opt_idx++] = "31622400";
5064
5065 /* end of options - required */
5066 OPTIONS[opt_idx] = NULL;
5067
5068 mark_point();
5069
5070 /* Initialize the library */
5071 mg_init_library(0);
5072
5073
5074 /* Start the server */
5075 ctx = test_mg_start(NULL, 0, OPTIONS, __LINE__);
5076 ck_assert(ctx != NULL);
5077
5078 /* Add some handler */
5079 mg_set_request_handler(ctx,
5080 "/hello",
5081 minimal_test_request_handler,
5082 (void *)"Hello world");
5083 mg_set_request_handler(ctx,
5084 "/8",
5085 minimal_test_request_handler,
5086 (void *)"Number eight");
5087
5088 /* Run the server for 15 seconds */
5089 test_sleep(10);
5090
5091 /* Call a test client */
5092 minimal_https_client_check("127.0.0.1", 8443, "/hello", "Hello world");
5093
5094 /* Run the server for 15 seconds */
5095 test_sleep(1);
5096
5097 /* Call a test client */
5098 minimal_https_client_check("127.0.0.1", 8443, "/8", "Number eight");
5099
5100 /* Run the server for 1 second */
5101 test_sleep(1);
5102
5103 /* Call a test client */
5104 minimal_https_client_check("127.0.0.1",
5105 8443,
5106 "/8?Altenative=Response",
5107 "Altenative=Response");
5108
5109 /* Run the server for 5 seconds */
5110 test_sleep(5);
5111
5112
5113 /* Stop the server */
5114 test_mg_stop(ctx, __LINE__);
5115
5116 /* Un-initialize the library */
5117 mg_exit_library();
5118 #endif
5119 mark_point();
5120 }
5121 END_TEST
5122
5123
5124 #if !defined(REPLACE_CHECK_FOR_LOCAL_DEBUGGING)
5125 Suite *
make_public_server_suite(void)5126 make_public_server_suite(void)
5127 {
5128 Suite *const suite = suite_create("PublicServer");
5129
5130 TCase *const tcase_checktestenv = tcase_create("Check test environment");
5131 TCase *const tcase_initlib = tcase_create("Init library");
5132 TCase *const tcase_startthreads = tcase_create("Start threads");
5133 TCase *const tcase_minimal_http_svr = tcase_create("Minimal HTTP Server");
5134 TCase *const tcase_minimal_https_svr = tcase_create("Minimal HTTPS Server");
5135 TCase *const tcase_minimal_http_cli = tcase_create("Minimal HTTP Client");
5136 TCase *const tcase_minimal_https_cli = tcase_create("Minimal HTTPS Client");
5137 TCase *const tcase_startstophttp = tcase_create("Start Stop HTTP Server");
5138 TCase *const tcase_startstophttp_ipv6 =
5139 tcase_create("Start Stop HTTP Server IPv6");
5140 TCase *const tcase_startstophttps = tcase_create("Start Stop HTTPS Server");
5141 TCase *const tcase_serverandclienttls = tcase_create("TLS Server Client");
5142 TCase *const tcase_serverrequests = tcase_create("Server Requests");
5143 TCase *const tcase_storebody = tcase_create("Store Body");
5144 TCase *const tcase_handle_form = tcase_create("Handle Form");
5145 TCase *const tcase_http_auth = tcase_create("HTTP Authentication");
5146 TCase *const tcase_keep_alive = tcase_create("HTTP Keep Alive");
5147 TCase *const tcase_error_handling = tcase_create("Error handling");
5148 TCase *const tcase_error_log = tcase_create("Error logging");
5149 TCase *const tcase_throttle = tcase_create("Limit speed");
5150 TCase *const tcase_large_file = tcase_create("Large file");
5151 TCase *const tcase_file_in_mem = tcase_create("File in memory");
5152
5153
5154 tcase_add_test(tcase_checktestenv, test_the_test_environment);
5155 tcase_set_timeout(tcase_checktestenv, civetweb_min_test_timeout);
5156 suite_add_tcase(suite, tcase_checktestenv);
5157
5158 tcase_add_test(tcase_initlib, test_init_library);
5159 tcase_set_timeout(tcase_initlib, civetweb_min_test_timeout);
5160 suite_add_tcase(suite, tcase_initlib);
5161
5162 tcase_add_test(tcase_startthreads, test_threading);
5163 tcase_set_timeout(tcase_startthreads, civetweb_min_test_timeout);
5164 suite_add_tcase(suite, tcase_startthreads);
5165
5166 tcase_add_test(tcase_minimal_http_svr, test_minimal_http_server_callback);
5167 tcase_set_timeout(tcase_minimal_http_svr, civetweb_min_server_test_timeout);
5168 suite_add_tcase(suite, tcase_minimal_http_svr);
5169
5170 tcase_add_test(tcase_minimal_https_svr, test_minimal_https_server_callback);
5171 tcase_set_timeout(tcase_minimal_https_svr,
5172 civetweb_min_server_test_timeout);
5173 suite_add_tcase(suite, tcase_minimal_https_svr);
5174
5175 tcase_add_test(tcase_minimal_http_cli, test_minimal_client);
5176 tcase_set_timeout(tcase_minimal_http_cli, civetweb_min_server_test_timeout);
5177 suite_add_tcase(suite, tcase_minimal_http_cli);
5178
5179 tcase_add_test(tcase_minimal_https_cli, test_minimal_tls_client);
5180 tcase_set_timeout(tcase_minimal_https_cli,
5181 civetweb_min_server_test_timeout);
5182 suite_add_tcase(suite, tcase_minimal_https_cli);
5183
5184 tcase_add_test(tcase_startstophttp, test_mg_start_stop_http_server);
5185 tcase_set_timeout(tcase_startstophttp, civetweb_min_server_test_timeout);
5186 suite_add_tcase(suite, tcase_startstophttp);
5187
5188 tcase_add_test(tcase_startstophttp_ipv6,
5189 test_mg_start_stop_http_server_ipv6);
5190 tcase_set_timeout(tcase_startstophttp_ipv6,
5191 civetweb_min_server_test_timeout);
5192 suite_add_tcase(suite, tcase_startstophttp_ipv6);
5193
5194 tcase_add_test(tcase_startstophttps, test_mg_start_stop_https_server);
5195 tcase_set_timeout(tcase_startstophttps, civetweb_min_server_test_timeout);
5196 suite_add_tcase(suite, tcase_startstophttps);
5197
5198 tcase_add_test(tcase_serverandclienttls, test_mg_server_and_client_tls);
5199 tcase_set_timeout(tcase_serverandclienttls,
5200 civetweb_min_server_test_timeout);
5201 suite_add_tcase(suite, tcase_serverandclienttls);
5202
5203 tcase_add_test(tcase_serverrequests, test_request_handlers);
5204 tcase_set_timeout(tcase_serverrequests, civetweb_mid_server_test_timeout);
5205 suite_add_tcase(suite, tcase_serverrequests);
5206
5207 tcase_add_test(tcase_storebody, test_mg_store_body);
5208 tcase_set_timeout(tcase_storebody, civetweb_mid_server_test_timeout);
5209 suite_add_tcase(suite, tcase_storebody);
5210
5211 tcase_add_test(tcase_handle_form, test_handle_form);
5212 tcase_set_timeout(tcase_handle_form, civetweb_mid_server_test_timeout);
5213 suite_add_tcase(suite, tcase_handle_form);
5214
5215 tcase_add_test(tcase_http_auth, test_http_auth);
5216 tcase_set_timeout(tcase_http_auth, civetweb_min_server_test_timeout);
5217 suite_add_tcase(suite, tcase_http_auth);
5218
5219 tcase_add_test(tcase_keep_alive, test_keep_alive);
5220 tcase_set_timeout(tcase_keep_alive, civetweb_mid_server_test_timeout);
5221 suite_add_tcase(suite, tcase_keep_alive);
5222
5223 tcase_add_test(tcase_error_handling, test_error_handling);
5224 tcase_set_timeout(tcase_error_handling, civetweb_mid_server_test_timeout);
5225 suite_add_tcase(suite, tcase_error_handling);
5226
5227 tcase_add_test(tcase_error_log, test_error_log_file);
5228 tcase_set_timeout(tcase_error_log, civetweb_mid_server_test_timeout);
5229 suite_add_tcase(suite, tcase_error_log);
5230
5231 tcase_add_test(tcase_throttle, test_throttle);
5232 tcase_set_timeout(tcase_throttle, civetweb_mid_server_test_timeout);
5233 suite_add_tcase(suite, tcase_throttle);
5234
5235 tcase_add_test(tcase_large_file, test_large_file);
5236 tcase_set_timeout(tcase_large_file, civetweb_mid_server_test_timeout);
5237 suite_add_tcase(suite, tcase_large_file);
5238
5239 tcase_add_test(tcase_file_in_mem, test_file_in_memory);
5240 tcase_set_timeout(tcase_file_in_mem, civetweb_mid_server_test_timeout);
5241 suite_add_tcase(suite, tcase_file_in_mem);
5242
5243 return suite;
5244 }
5245 #endif
5246
5247
5248 #ifdef REPLACE_CHECK_FOR_LOCAL_DEBUGGING
5249 /* Used to debug test cases without using the check framework */
5250 /* Build command for Linux:
5251 gcc test/public_server.c src/civetweb.c -I include/ -I test/ -l pthread -l dl -D
5252 LOCAL_TEST -D REPLACE_CHECK_FOR_LOCAL_DEBUGGING -D MAIN_PUBLIC_SERVER=main
5253 */
5254
5255 static int chk_ok = 0;
5256 static int chk_failed = 0;
5257
5258
5259 void
MAIN_PUBLIC_SERVER(void)5260 MAIN_PUBLIC_SERVER(void)
5261 {
5262 unsigned f_avail = mg_check_feature(0xFF);
5263 unsigned f_ret = mg_init_library(f_avail);
5264 ck_assert_uint_eq(f_ret, f_avail);
5265
5266 test_handle_form(0);
5267
5268 test_the_test_environment(0);
5269 test_threading(0);
5270
5271 test_minimal_client(0);
5272
5273 test_mg_start_stop_http_server(0);
5274 test_mg_start_stop_https_server(0);
5275 test_request_handlers(0);
5276 test_mg_store_body(0);
5277 test_mg_server_and_client_tls(0);
5278 test_handle_form(0);
5279 test_http_auth(0);
5280 test_keep_alive(0);
5281 test_error_handling(0);
5282 test_error_log_file(0);
5283 test_throttle(0);
5284 test_large_file(0);
5285 test_file_in_memory(0);
5286
5287 mg_exit_library();
5288
5289 printf("\nok: %i\nfailed: %i\n\n", chk_ok, chk_failed);
5290 }
5291
5292 void
_ck_assert_failed(const char * file,int line,const char * expr,...)5293 _ck_assert_failed(const char *file, int line, const char *expr, ...)
5294 {
5295 va_list va;
5296 va_start(va, expr);
5297 fprintf(stderr, "Error: %s, line %i\n", file, line); /* breakpoint here ! */
5298 vfprintf(stderr, expr, va);
5299 fprintf(stderr, "\n\n");
5300 va_end(va);
5301 chk_failed++;
5302 }
5303
5304 void
_ck_assert_msg(int cond,const char * file,int line,const char * expr,...)5305 _ck_assert_msg(int cond, const char *file, int line, const char *expr, ...)
5306 {
5307 va_list va;
5308
5309 if (cond) {
5310 chk_ok++;
5311 return;
5312 }
5313
5314 va_start(va, expr);
5315 fprintf(stderr, "Error: %s, line %i\n", file, line); /* breakpoint here ! */
5316 vfprintf(stderr, expr, va);
5317 fprintf(stderr, "\n\n");
5318 va_end(va);
5319 chk_failed++;
5320 }
5321
5322 void
_mark_point(const char * file,int line)5323 _mark_point(const char *file, int line)
5324 {
5325 chk_ok++;
5326 }
5327
5328 void
tcase_fn_start(const char * fname,const char * file,int line)5329 tcase_fn_start(const char *fname, const char *file, int line)
5330 {
5331 }
suite_add_tcase(Suite * s,TCase * tc)5332 void suite_add_tcase(Suite *s, TCase *tc){};
_tcase_add_test(TCase * tc,TFun tf,const char * fname,int _signal,int allowed_exit_value,int start,int end)5333 void _tcase_add_test(TCase *tc,
5334 TFun tf,
5335 const char *fname,
5336 int _signal,
5337 int allowed_exit_value,
5338 int start,
5339 int end){};
5340 TCase *
tcase_create(const char * name)5341 tcase_create(const char *name)
5342 {
5343 return NULL;
5344 };
5345 Suite *
suite_create(const char * name)5346 suite_create(const char *name)
5347 {
5348 return NULL;
5349 };
tcase_set_timeout(TCase * tc,double timeout)5350 void tcase_set_timeout(TCase *tc, double timeout){};
5351
5352 #endif
5353