unit_test.c 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549
  1. /* Copyright (c) 2013-2015 the Civetweb developers
  2. * Copyright (c) 2004-2013 Sergey Lyubka
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to deal
  6. * in the Software without restriction, including without limitation the rights
  7. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. * copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. * THE SOFTWARE.
  21. */
  22. #if defined(_MSC_VER)
  23. #pragma message("Warning: " __FILE__ " is obsolete. See note below.")
  24. #else
  25. #pragma message __FILE__ ": This file is obsolete. See note below."
  26. #endif
  27. /* Note: The unit_test.c file is mostly obsolete, since the current unit
  28. * tests are performed by the CMake build framework based on the
  29. * CMakeList (https://github.com/civetweb/civetweb/blob/master/test/CMakeLists.txt).
  30. * The tests do no longer use unit_test.c but public_func.c, public_server.c,
  31. * private.c, private_exe.c and others.
  32. * This file is left here for reference and will be removed in the future.
  33. * It is no longer actively maintained.
  34. */
  35. /* Unit test for the civetweb web server. Tests embedded API.
  36. */
  37. #define USE_WEBSOCKET
  38. #ifndef _WIN32
  39. #define __cdecl
  40. #define USE_IPV6
  41. #endif
  42. /* USE_* definitions must be made before #include "civetweb.c" !
  43. * We include the source file so that our object file will have visibility to
  44. * all the static functions.
  45. */
  46. #include "civetweb.c"
  47. void check_func(int condition, const char *cond_txt, unsigned line);
  48. static int s_total_tests = 0;
  49. static int s_failed_tests = 0;
  50. void check_func(int condition, const char *cond_txt, unsigned line)
  51. {
  52. ++s_total_tests;
  53. if (!condition) {
  54. printf("Fail on line %d: [%s]\n", line, cond_txt);
  55. ++s_failed_tests;
  56. }
  57. }
  58. #define ASSERT(expr) \
  59. do { \
  60. check_func(expr, #expr, __LINE__); \
  61. } while (0)
  62. #define REQUIRE(expr) \
  63. do { \
  64. check_func(expr, #expr, __LINE__); \
  65. if (!(expr)) { \
  66. exit(EXIT_FAILURE); \
  67. } \
  68. } while (0)
  69. #define HTTP_PORT "8080"
  70. #ifdef NO_SSL
  71. #define HTTPS_PORT HTTP_PORT
  72. #define LISTENING_ADDR "127.0.0.1:" HTTP_PORT
  73. #else
  74. #define HTTP_REDIRECT_PORT "8088"
  75. #define HTTPS_PORT "8443"
  76. #define LISTENING_ADDR \
  77. "127.0.0.1:" HTTP_PORT ",127.0.0.1:" HTTP_REDIRECT_PORT "r" \
  78. ",127.0.0.1:" HTTPS_PORT "s"
  79. #endif
  80. static void test_parse_http_message()
  81. {
  82. struct mg_request_info ri;
  83. char req1[] = "GET / HTTP/1.1\r\n\r\n";
  84. char req2[] = "BLAH / HTTP/1.1\r\n\r\n";
  85. char req3[] = "GET / HTTP/1.1\r\nBah\r\n";
  86. char req4[] = "GET / HTTP/1.1\r\nA: foo bar\r\nB: bar\r\nbaz:\r\n\r\n";
  87. char req5[] = "GET / HTTP/1.1\r\n\r\n";
  88. char req6[] = "G";
  89. char req7[] = " blah ";
  90. char req8[] = " HTTP/1.1 200 OK \n\n";
  91. char req9[] = "HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n";
  92. ASSERT(parse_http_message(req9, sizeof(req9), &ri) == sizeof(req9) - 1);
  93. ASSERT(ri.num_headers == 1);
  94. ASSERT(parse_http_message(req1, sizeof(req1), &ri) == sizeof(req1) - 1);
  95. ASSERT(strcmp(ri.http_version, "1.1") == 0);
  96. ASSERT(ri.num_headers == 0);
  97. ASSERT(parse_http_message(req2, sizeof(req2), &ri) == -1);
  98. ASSERT(parse_http_message(req3, sizeof(req3), &ri) == 0);
  99. ASSERT(parse_http_message(req6, sizeof(req6), &ri) == 0);
  100. ASSERT(parse_http_message(req7, sizeof(req7), &ri) == 0);
  101. ASSERT(parse_http_message("", 0, &ri) == 0);
  102. ASSERT(parse_http_message(req8, sizeof(req8), &ri) == sizeof(req8) - 1);
  103. /* TODO(lsm): Fix this. Header value may span multiple lines. */
  104. ASSERT(parse_http_message(req4, sizeof(req4), &ri) == sizeof(req4) - 1);
  105. ASSERT(strcmp(ri.http_version, "1.1") == 0);
  106. ASSERT(ri.num_headers == 3);
  107. ASSERT(strcmp(ri.http_headers[0].name, "A") == 0);
  108. ASSERT(strcmp(ri.http_headers[0].value, "foo bar") == 0);
  109. ASSERT(strcmp(ri.http_headers[1].name, "B") == 0);
  110. ASSERT(strcmp(ri.http_headers[1].value, "bar") == 0);
  111. ASSERT(strcmp(ri.http_headers[2].name, "baz") == 0);
  112. ASSERT(strcmp(ri.http_headers[2].value, "") == 0);
  113. ASSERT(parse_http_message(req5, sizeof(req5), &ri) == sizeof(req5) - 1);
  114. ASSERT(strcmp(ri.request_method, "GET") == 0);
  115. ASSERT(strcmp(ri.http_version, "1.1") == 0);
  116. }
  117. static void test_should_keep_alive(void)
  118. {
  119. struct mg_connection conn;
  120. struct mg_context ctx;
  121. char req1[] = "GET / HTTP/1.1\r\n\r\n";
  122. char req2[] = "GET / HTTP/1.0\r\n\r\n";
  123. char req3[] = "GET / HTTP/1.1\r\nConnection: close\r\n\r\n";
  124. char req4[] = "GET / HTTP/1.1\r\nConnection: keep-alive\r\n\r\n";
  125. memset(&conn, 0, sizeof(conn));
  126. conn.ctx = &ctx;
  127. ASSERT(parse_http_message(req1, sizeof(req1), &conn.request_info) ==
  128. sizeof(req1) - 1);
  129. ctx.config[ENABLE_KEEP_ALIVE] = "no";
  130. ASSERT(should_keep_alive(&conn) == 0);
  131. ctx.config[ENABLE_KEEP_ALIVE] = "yes";
  132. ASSERT(should_keep_alive(&conn) == 1);
  133. conn.must_close = 1;
  134. ASSERT(should_keep_alive(&conn) == 0);
  135. conn.must_close = 0;
  136. parse_http_message(req2, sizeof(req2), &conn.request_info);
  137. ASSERT(should_keep_alive(&conn) == 0);
  138. parse_http_message(req3, sizeof(req3), &conn.request_info);
  139. ASSERT(should_keep_alive(&conn) == 0);
  140. parse_http_message(req4, sizeof(req4), &conn.request_info);
  141. ASSERT(should_keep_alive(&conn) == 1);
  142. conn.status_code = 401;
  143. ASSERT(should_keep_alive(&conn) == 0);
  144. conn.status_code = 200;
  145. conn.must_close = 1;
  146. ASSERT(should_keep_alive(&conn) == 0);
  147. }
  148. static void test_match_prefix(void)
  149. {
  150. ASSERT(match_prefix("/api", 4, "/api") == 4);
  151. ASSERT(match_prefix("/a/", 3, "/a/b/c") == 3);
  152. ASSERT(match_prefix("/a/", 3, "/ab/c") == -1);
  153. ASSERT(match_prefix("/*/", 3, "/ab/c") == 4);
  154. ASSERT(match_prefix("**", 2, "/a/b/c") == 6);
  155. ASSERT(match_prefix("/*", 2, "/a/b/c") == 2);
  156. ASSERT(match_prefix("*/*", 3, "/a/b/c") == 2);
  157. ASSERT(match_prefix("**/", 3, "/a/b/c") == 5);
  158. ASSERT(match_prefix("**.foo|**.bar", 13, "a.bar") == 5);
  159. ASSERT(match_prefix("a|b|cd", 6, "cdef") == 2);
  160. ASSERT(match_prefix("a|b|c?", 6, "cdef") == 2);
  161. ASSERT(match_prefix("a|?|cd", 6, "cdef") == 1);
  162. ASSERT(match_prefix("/a/**.cgi", 9, "/foo/bar/x.cgi") == -1);
  163. ASSERT(match_prefix("/a/**.cgi", 9, "/a/bar/x.cgi") == 12);
  164. ASSERT(match_prefix("**/", 3, "/a/b/c") == 5);
  165. ASSERT(match_prefix("**/$", 4, "/a/b/c") == -1);
  166. ASSERT(match_prefix("**/$", 4, "/a/b/") == 5);
  167. ASSERT(match_prefix("$", 1, "") == 0);
  168. ASSERT(match_prefix("$", 1, "x") == -1);
  169. ASSERT(match_prefix("*$", 2, "x") == 1);
  170. ASSERT(match_prefix("/$", 2, "/") == 1);
  171. ASSERT(match_prefix("**/$", 4, "/a/b/c") == -1);
  172. ASSERT(match_prefix("**/$", 4, "/a/b/") == 5);
  173. ASSERT(match_prefix("*", 1, "/hello/") == 0);
  174. ASSERT(match_prefix("**.a$|**.b$", 11, "/a/b.b/") == -1);
  175. ASSERT(match_prefix("**.a$|**.b$", 11, "/a/b.b") == 6);
  176. ASSERT(match_prefix("**.a$|**.b$", 11, "/a/B.A") == 6);
  177. ASSERT(match_prefix("**o$", 4, "HELLO") == 5);
  178. }
  179. static void test_remove_double_dots()
  180. {
  181. struct {
  182. char before[20], after[20];
  183. } data[] = {
  184. {"////a", "/a"},
  185. {"/.....", "/."},
  186. {"/......", "/"},
  187. {"...", "..."},
  188. {"/...///", "/./"},
  189. {"/a...///", "/a.../"},
  190. {"/.x", "/.x"},
  191. {"/\\", "/"},
  192. {"/a\\", "/a\\"},
  193. {"/a\\\\...", "/a\\."},
  194. };
  195. size_t i;
  196. for (i = 0; i < ARRAY_SIZE(data); i++) {
  197. remove_double_dots_and_double_slashes(data[i].before);
  198. ASSERT(strcmp(data[i].before, data[i].after) == 0);
  199. }
  200. }
  201. static char *read_file(const char *path, int *size)
  202. {
  203. FILE *fp;
  204. struct stat st;
  205. char *data = NULL;
  206. if ((fp = fopen(path, "rb")) != NULL && !fstat(fileno(fp), &st)) {
  207. *size = (int)st.st_size;
  208. data = mg_malloc(*size);
  209. ASSERT(data != NULL);
  210. ASSERT(fread(data, 1, *size, fp) == (size_t)*size);
  211. fclose(fp);
  212. }
  213. return data;
  214. }
  215. static long fetch_data_size = 1024 * 1024;
  216. static char *fetch_data;
  217. static const char *inmemory_file_data = "hi there";
  218. static const char *upload_filename = "upload_test.txt";
  219. #if 0
  220. static const char *upload_filename2 = "upload_test2.txt";
  221. #endif
  222. static const char *upload_ok_message = "upload successful";
  223. static const char *
  224. open_file_cb(const struct mg_connection *conn, const char *path, size_t *size)
  225. {
  226. (void)conn;
  227. if (!strcmp(path, "./blah")) {
  228. *size = strlen(inmemory_file_data);
  229. return inmemory_file_data;
  230. }
  231. return NULL;
  232. }
  233. #if defined(MG_LEGACY_INTERFACE)
  234. static void upload_cb(struct mg_connection *conn, const char *path)
  235. {
  236. const struct mg_request_info *ri = mg_get_request_info(conn);
  237. char *p1, *p2;
  238. int len1, len2;
  239. if (atoi(ri->query_string) == 1) {
  240. ASSERT(!strcmp(path, "./upload_test.txt"));
  241. ASSERT((p1 = read_file("src/civetweb.c", &len1)) != NULL);
  242. ASSERT((p2 = read_file(path, &len2)) != NULL);
  243. ASSERT(len1 == len2);
  244. ASSERT(memcmp(p1, p2, len1) == 0);
  245. mg_free(p1);
  246. mg_free(p2);
  247. remove(upload_filename);
  248. } else if (atoi(ri->query_string) == 2) {
  249. if (!strcmp(path, "./upload_test.txt")) {
  250. ASSERT((p1 = read_file("include/civetweb.h", &len1)) != NULL);
  251. ASSERT((p2 = read_file(path, &len2)) != NULL);
  252. ASSERT(len1 == len2);
  253. ASSERT(memcmp(p1, p2, len1) == 0);
  254. mg_free(p1);
  255. mg_free(p2);
  256. remove(upload_filename);
  257. } else if (!strcmp(path, "./upload_test2.txt")) {
  258. ASSERT((p1 = read_file("README.md", &len1)) != NULL);
  259. ASSERT((p2 = read_file(path, &len2)) != NULL);
  260. ASSERT(len1 == len2);
  261. ASSERT(memcmp(p1, p2, len1) == 0);
  262. mg_free(p1);
  263. mg_free(p2);
  264. remove(upload_filename);
  265. } else {
  266. ASSERT(0);
  267. }
  268. } else {
  269. ASSERT(0);
  270. }
  271. mg_printf(conn,
  272. "HTTP/1.0 200 OK\r\nContent-Length: %d\r\n\r\n%s",
  273. (int)strlen(upload_ok_message),
  274. upload_ok_message);
  275. }
  276. #endif
  277. static int begin_request_handler_cb(struct mg_connection *conn)
  278. {
  279. const struct mg_request_info *ri = mg_get_request_info(conn);
  280. int req_len = (int)(ri->content_length);
  281. const char *s_req_len = mg_get_header(conn, "Content-Length");
  282. char *data;
  283. long to_write, write_now;
  284. int bytes_read, bytes_written;
  285. ASSERT(((req_len == -1) && (s_req_len == NULL)) ||
  286. ((s_req_len != NULL) && (req_len = atol(s_req_len))));
  287. if (!strncmp(ri->uri, "/data/", 6)) {
  288. if (!strcmp(ri->uri + 6, "all")) {
  289. to_write = fetch_data_size;
  290. } else {
  291. to_write = atol(ri->uri + 6);
  292. }
  293. mg_printf(conn,
  294. "HTTP/1.1 200 OK\r\n"
  295. "Connection: close\r\n"
  296. "Content-Length: %li\r\n"
  297. "Content-Type: text/plain\r\n\r\n",
  298. to_write);
  299. while (to_write > 0) {
  300. write_now = to_write > fetch_data_size ? fetch_data_size : to_write;
  301. bytes_written = mg_write(conn, fetch_data, write_now);
  302. ASSERT(bytes_written == write_now);
  303. if (bytes_written < 0) {
  304. ASSERT(0);
  305. break;
  306. }
  307. to_write -= bytes_written;
  308. }
  309. close_connection(conn);
  310. return 1;
  311. }
  312. if (!strcmp(ri->uri, "/content_length")) {
  313. if (req_len > 0) {
  314. data = mg_malloc(req_len);
  315. assert(data != NULL);
  316. bytes_read = mg_read(conn, data, req_len);
  317. ASSERT(bytes_read == req_len);
  318. mg_printf(conn,
  319. "HTTP/1.1 200 OK\r\n"
  320. "Connection: close\r\n"
  321. "Content-Length: %d\r\n" /* The official definition */
  322. "Content-Type: text/plain\r\n\r\n",
  323. bytes_read);
  324. mg_write(conn, data, bytes_read);
  325. mg_free(data);
  326. } else {
  327. data = mg_malloc(1024);
  328. assert(data != NULL);
  329. bytes_read = mg_read(conn, data, 1024);
  330. mg_printf(conn,
  331. "HTTP/1.1 200 OK\r\n"
  332. "Connection: close\r\n"
  333. "Content-Type: text/plain\r\n\r\n");
  334. mg_write(conn, data, bytes_read);
  335. mg_free(data);
  336. }
  337. close_connection(conn);
  338. return 1;
  339. }
  340. #if defined(MG_LEGACY_INTERFACE)
  341. if (!strcmp(ri->uri, "/upload")) {
  342. ASSERT(ri->query_string != NULL);
  343. ASSERT(mg_upload(conn, ".") == atoi(ri->query_string));
  344. }
  345. #endif
  346. return 0;
  347. }
  348. static int log_message_cb(const struct mg_connection *conn, const char *msg)
  349. {
  350. (void)conn;
  351. printf("%s\n", msg);
  352. return 0;
  353. }
  354. int (*begin_request)(struct mg_connection *);
  355. void (*end_request)(const struct mg_connection *, int reply_status_code);
  356. int (*log_message)(const struct mg_connection *, const char *message);
  357. int (*init_ssl)(void *ssl_context, void *user_data);
  358. int (*websocket_connect)(const struct mg_connection *);
  359. void (*websocket_ready)(struct mg_connection *);
  360. int (*websocket_data)(struct mg_connection *,
  361. int bits,
  362. char *data,
  363. size_t data_len);
  364. void (*connection_close)(struct mg_connection *);
  365. const char *(*open_file)(const struct mg_connection *,
  366. const char *path,
  367. size_t *data_len);
  368. void (*init_lua)(struct mg_connection *, void *lua_context);
  369. void (*upload)(struct mg_connection *, const char *file_name);
  370. int (*http_error)(struct mg_connection *, int status);
  371. static struct mg_callbacks CALLBACKS;
  372. static void init_CALLBACKS()
  373. {
  374. memset(&CALLBACKS, 0, sizeof(CALLBACKS));
  375. CALLBACKS.begin_request = begin_request_handler_cb;
  376. CALLBACKS.log_message = log_message_cb;
  377. CALLBACKS.open_file = open_file_cb;
  378. #if defined(MG_LEGACY_INTERFACE)
  379. CALLBACKS.upload = upload_cb;
  380. #endif
  381. };
  382. static const char *OPTIONS[] = {
  383. "document_root",
  384. ".",
  385. "listening_ports",
  386. LISTENING_ADDR,
  387. "enable_keep_alive",
  388. "yes",
  389. #ifndef NO_SSL
  390. "ssl_certificate",
  391. "../resources/ssl_cert.pem",
  392. #endif
  393. NULL,
  394. };
  395. static char *read_conn(struct mg_connection *conn, int *size)
  396. {
  397. char buf[100], *data = NULL;
  398. int len;
  399. *size = 0;
  400. while ((len = mg_read(conn, buf, sizeof(buf))) > 0) {
  401. *size += len;
  402. data = mg_realloc(data, *size);
  403. ASSERT(data != NULL);
  404. memcpy(data + *size - len, buf, len);
  405. }
  406. return data;
  407. }
  408. #ifdef MEMORY_DEBUGGING
  409. extern unsigned long mg_memory_debug_blockCount;
  410. extern unsigned long mg_memory_debug_totalMemUsed;
  411. #endif
  412. static void ut_mg_stop(struct mg_context *ctx)
  413. {
  414. /* mg_stop for unit_test */
  415. mg_stop(ctx);
  416. #ifdef MEMORY_DEBUGGING
  417. ASSERT(mg_memory_debug_blockCount == 0);
  418. ASSERT(mg_memory_debug_totalMemUsed == 0);
  419. mg_memory_debug_blockCount = 0;
  420. mg_memory_debug_totalMemUsed = 0;
  421. #endif
  422. mg_sleep(31000); /* This is required to ensure the operating system already
  423. allows to use the port again */
  424. }
  425. static void test_mg_download(int use_ssl)
  426. {
  427. const char *test_data = "123456789A123456789B";
  428. char *p1, *p2, ebuf[100];
  429. const char *h;
  430. int i, len1, len2, port;
  431. struct mg_connection *conn;
  432. struct mg_context *ctx;
  433. const struct mg_request_info *ri;
  434. if (use_ssl) {
  435. port = atoi(HTTPS_PORT);
  436. } else {
  437. port = atoi(HTTP_PORT);
  438. }
  439. ctx = mg_start(&CALLBACKS, NULL, OPTIONS);
  440. ASSERT(ctx != NULL);
  441. ASSERT(mg_download(NULL, port, use_ssl, ebuf, sizeof(ebuf), "%s", "") ==
  442. NULL);
  443. ASSERT(mg_download("localhost", 0, use_ssl, ebuf, sizeof(ebuf), "%s", "") ==
  444. NULL);
  445. ASSERT(
  446. mg_download("localhost", port, use_ssl, ebuf, sizeof(ebuf), "%s", "") ==
  447. NULL);
  448. /* Fetch nonexistent file, should see 404 */
  449. ASSERT((conn = mg_download("localhost",
  450. port,
  451. use_ssl,
  452. ebuf,
  453. sizeof(ebuf),
  454. "%s",
  455. "GET /gimbec HTTP/1.0\r\n\r\n")) != NULL);
  456. ASSERT(strcmp(conn->request_info.uri, "404") == 0);
  457. mg_close_connection(conn);
  458. if (use_ssl) {
  459. ASSERT((conn = mg_download("google.com",
  460. 443,
  461. 1,
  462. ebuf,
  463. sizeof(ebuf),
  464. "%s",
  465. "GET / HTTP/1.0\r\n\r\n")) != NULL);
  466. mg_close_connection(conn);
  467. } else {
  468. ASSERT((conn = mg_download("google.com",
  469. 80,
  470. 0,
  471. ebuf,
  472. sizeof(ebuf),
  473. "%s",
  474. "GET / HTTP/1.0\r\n\r\n")) != NULL);
  475. mg_close_connection(conn);
  476. }
  477. /* Fetch unit_test.c, should succeed */
  478. ASSERT((conn = mg_download("localhost",
  479. port,
  480. use_ssl,
  481. ebuf,
  482. sizeof(ebuf),
  483. "%s",
  484. "GET /unit_test.c HTTP/1.0\r\n\r\n")) != NULL);
  485. ASSERT(&conn->request_info == mg_get_request_info(conn));
  486. ASSERT(!strcmp(conn->request_info.uri, "200"));
  487. ASSERT((p1 = read_conn(conn, &len1)) != NULL);
  488. ASSERT((p2 = read_file("unit_test.c", &len2)) != NULL);
  489. ASSERT(len1 == len2);
  490. ASSERT(memcmp(p1, p2, len1) == 0);
  491. mg_free(p1);
  492. mg_free(p2);
  493. mg_close_connection(conn);
  494. /* Fetch in-memory file, should succeed. */
  495. ASSERT((conn = mg_download("localhost",
  496. port,
  497. use_ssl,
  498. ebuf,
  499. sizeof(ebuf),
  500. "%s",
  501. "GET /blah HTTP/1.1\r\n\r\n")) != NULL);
  502. ASSERT((p1 = read_conn(conn, &len1)) != NULL);
  503. ASSERT(len1 == (int)strlen(inmemory_file_data));
  504. ASSERT(memcmp(p1, inmemory_file_data, len1) == 0);
  505. mg_free(p1);
  506. mg_close_connection(conn);
  507. /* Fetch in-memory data with no Content-Length, should succeed. */
  508. ASSERT((conn = mg_download("localhost",
  509. port,
  510. use_ssl,
  511. ebuf,
  512. sizeof(ebuf),
  513. "%s",
  514. "GET /data/all HTTP/1.1\r\n\r\n")) != NULL);
  515. ASSERT(conn->request_info.content_length == fetch_data_size);
  516. ASSERT((p1 = read_conn(conn, &len1)) != NULL);
  517. ASSERT(len1 == (int)fetch_data_size);
  518. ASSERT(memcmp(p1, fetch_data, len1) == 0);
  519. mg_free(p1);
  520. mg_close_connection(conn);
  521. /* Fetch in-memory data with no Content-Length, should succeed. */
  522. for (i = 0; i <= 1024 * /* 1024 * */ 8; i += (i < 2 ? 1 : i)) {
  523. ASSERT((conn = mg_download("localhost",
  524. port,
  525. use_ssl,
  526. ebuf,
  527. sizeof(ebuf),
  528. "GET /data/%i HTTP/1.1\r\n\r\n",
  529. i)) != NULL);
  530. ASSERT(conn->request_info.content_length == i);
  531. len1 = -1;
  532. p1 = read_conn(conn, &len1);
  533. if (i == 0) {
  534. ASSERT(len1 == 0);
  535. ASSERT(p1 == 0);
  536. } else if (i <= fetch_data_size) {
  537. ASSERT(p1 != NULL);
  538. ASSERT(len1 == i);
  539. ASSERT(memcmp(p1, fetch_data, len1) == 0);
  540. } else {
  541. ASSERT(p1 != NULL);
  542. ASSERT(len1 == i);
  543. ASSERT(memcmp(p1, fetch_data, fetch_data_size) == 0);
  544. }
  545. mg_free(p1);
  546. mg_close_connection(conn);
  547. }
  548. /* Fetch data with Content-Length, should succeed and return the defined
  549. * length. */
  550. ASSERT((conn = mg_download(
  551. "localhost",
  552. port,
  553. use_ssl,
  554. ebuf,
  555. sizeof(ebuf),
  556. "POST /content_length HTTP/1.1\r\nContent-Length: %u\r\n\r\n%s",
  557. (unsigned)strlen(test_data),
  558. test_data)) != NULL);
  559. h = mg_get_header(conn, "Content-Length");
  560. ASSERT((h != NULL) && (atoi(h) == (int)strlen(test_data)));
  561. ASSERT((p1 = read_conn(conn, &len1)) != NULL);
  562. ASSERT(len1 == (int)strlen(test_data));
  563. ASSERT(conn->request_info.content_length == (int)strlen(test_data));
  564. ASSERT(memcmp(p1, test_data, len1) == 0);
  565. ASSERT(strcmp(conn->request_info.request_method, "HTTP/1.1") == 0);
  566. ASSERT(strcmp(conn->request_info.uri, "200") == 0);
  567. ASSERT(strcmp(conn->request_info.http_version, "OK") == 0);
  568. mg_free(p1);
  569. mg_close_connection(conn);
  570. /* A POST request without Content-Length set is only valid, if the request
  571. * used Transfer-Encoding: chunked. Otherwise, it is an HTTP protocol
  572. * violation. Here we send a chunked request, the reply is not chunked. */
  573. ASSERT((conn = mg_download("localhost",
  574. port,
  575. use_ssl,
  576. ebuf,
  577. sizeof(ebuf),
  578. "POST /content_length "
  579. "HTTP/1.1\r\n"
  580. "Transfer-Encoding: chunked\r\n"
  581. "\r\n%x\r\n%s\r\n0\r\n\r\n",
  582. (uint32_t)strlen(test_data),
  583. test_data)) != NULL);
  584. h = mg_get_header(conn, "Content-Length");
  585. ASSERT(h == NULL);
  586. ASSERT(conn->request_info.content_length == -1);
  587. ASSERT((p1 = read_conn(conn, &len1)) != NULL);
  588. ASSERT(len1 == (int)strlen(test_data));
  589. ASSERT(memcmp(p1, test_data, len1) == 0);
  590. mg_free(p1);
  591. mg_close_connection(conn);
  592. /* Another chunked POST request with different chunk sizes. */
  593. ASSERT((conn = mg_download("localhost",
  594. port,
  595. use_ssl,
  596. ebuf,
  597. sizeof(ebuf),
  598. "POST /content_length "
  599. "HTTP/1.1\r\n"
  600. "Transfer-Encoding: chunked\r\n\r\n"
  601. "2\r\n%c%c\r\n"
  602. "1\r\n%c\r\n"
  603. "2\r\n%c%c\r\n"
  604. "2\r\n%c%c\r\n"
  605. "%x\r\n%s\r\n"
  606. "0\r\n\r\n",
  607. test_data[0],
  608. test_data[1],
  609. test_data[2],
  610. test_data[3],
  611. test_data[4],
  612. test_data[5],
  613. test_data[6],
  614. (uint32_t)strlen(test_data + 7),
  615. test_data + 7)) != NULL);
  616. h = mg_get_header(conn, "Content-Length");
  617. ASSERT(h == NULL);
  618. ASSERT(conn->request_info.content_length == -1);
  619. ASSERT((p1 = read_conn(conn, &len1)) != NULL);
  620. ASSERT(len1 == (int)strlen(test_data));
  621. ASSERT(memcmp(p1, test_data, len1) == 0);
  622. mg_free(p1);
  623. mg_close_connection(conn);
  624. /* Test non existent */
  625. ASSERT((conn = mg_download("localhost",
  626. port,
  627. use_ssl,
  628. ebuf,
  629. sizeof(ebuf),
  630. "%s",
  631. "GET /non_exist HTTP/1.1\r\n\r\n")) != NULL);
  632. ASSERT(strcmp(conn->request_info.request_method, "HTTP/1.1") == 0);
  633. ASSERT(strcmp(conn->request_info.uri, "404") == 0);
  634. ASSERT(strcmp(conn->request_info.http_version, "Not Found") == 0);
  635. mg_close_connection(conn);
  636. if (use_ssl) {
  637. #ifndef NO_SSL
  638. /* Test SSL redirect */
  639. ASSERT((conn = mg_download("localhost",
  640. atoi(HTTP_REDIRECT_PORT),
  641. 0,
  642. ebuf,
  643. sizeof(ebuf),
  644. "%s",
  645. "GET /data/4711 HTTP/1.1\r\n\r\n")) != NULL);
  646. ASSERT(strcmp(conn->request_info.uri, "302") == 0);
  647. h = mg_get_header(conn, "Location");
  648. ASSERT(h != NULL);
  649. ASSERT(strcmp(h, "https://127.0.0.1:" HTTPS_PORT "/data/4711") == 0);
  650. mg_close_connection(conn);
  651. #endif
  652. }
  653. /* Test new API */
  654. ebuf[0] = 1;
  655. conn = mg_connect_client("localhost", port, use_ssl, ebuf, sizeof(ebuf));
  656. ASSERT(conn != NULL);
  657. ASSERT(ebuf[0] == 0);
  658. ri = mg_get_request_info(conn);
  659. ASSERT(ri->content_length == 0);
  660. i = mg_get_response(conn, ebuf, sizeof(ebuf), 1000);
  661. ASSERT(ebuf[0] != 0);
  662. ri = mg_get_request_info(conn);
  663. ASSERT(ri->content_length == -1);
  664. mg_printf(conn, "GET /index.html HTTP/1.1\r\n");
  665. mg_printf(conn, "Host: www.example.com\r\n");
  666. mg_printf(conn, "\r\n");
  667. i = mg_get_response(conn, ebuf, sizeof(ebuf), 1000);
  668. ASSERT(ebuf[0] == 0);
  669. ri = mg_get_request_info(conn);
  670. ASSERT(ri->content_length > 0);
  671. mg_read(conn, ebuf, sizeof(ebuf));
  672. ASSERT(!strncmp(ebuf, "Error 404", 9));
  673. mg_close_connection(conn);
  674. /* Stop the test server */
  675. ut_mg_stop(ctx);
  676. }
  677. static int websocket_data_handler(const struct mg_connection *conn,
  678. int flags,
  679. char *data,
  680. size_t data_len,
  681. void *cbdata)
  682. {
  683. (void)conn;
  684. (void)flags;
  685. (void)data;
  686. (void)data_len;
  687. (void)cbdata;
  688. return 1;
  689. }
  690. static void test_mg_websocket_client_connect(int use_ssl)
  691. {
  692. struct mg_connection *conn;
  693. char ebuf[100];
  694. int port;
  695. struct mg_context *ctx;
  696. if (use_ssl)
  697. port = atoi(HTTPS_PORT);
  698. else
  699. port = atoi(HTTP_PORT);
  700. ASSERT((ctx = mg_start(&CALLBACKS, NULL, OPTIONS)) != NULL);
  701. /* Try to connect to our own server */
  702. /* Invalid port test */
  703. conn = mg_connect_websocket_client("localhost",
  704. 0,
  705. use_ssl,
  706. ebuf,
  707. sizeof(ebuf),
  708. "/",
  709. "http://localhost",
  710. (mg_websocket_data_handler)websocket_data_handler,
  711. NULL,
  712. NULL);
  713. ASSERT(conn == NULL);
  714. /* Should succeed, the default civetweb server should complete the handshake
  715. */
  716. conn = mg_connect_websocket_client("localhost",
  717. port,
  718. use_ssl,
  719. ebuf,
  720. sizeof(ebuf),
  721. "/",
  722. "http://localhost",
  723. (mg_websocket_data_handler)websocket_data_handler,
  724. NULL,
  725. NULL);
  726. ASSERT(conn != NULL);
  727. /* Try an external server test */
  728. port = 80;
  729. if (use_ssl) {
  730. port = 443;
  731. }
  732. /* Not a websocket server path */
  733. conn = mg_connect_websocket_client("websocket.org",
  734. port,
  735. use_ssl,
  736. ebuf,
  737. sizeof(ebuf),
  738. "/",
  739. "http://websocket.org",
  740. (mg_websocket_data_handler)websocket_data_handler,
  741. NULL,
  742. NULL);
  743. ASSERT(conn == NULL);
  744. /* Invalid port test */
  745. conn = mg_connect_websocket_client("echo.websocket.org",
  746. 0,
  747. use_ssl,
  748. ebuf,
  749. sizeof(ebuf),
  750. "/",
  751. "http://websocket.org",
  752. (mg_websocket_data_handler)websocket_data_handler,
  753. NULL,
  754. NULL);
  755. ASSERT(conn == NULL);
  756. /* Should succeed, echo.websocket.org echos the data back */
  757. conn = mg_connect_websocket_client("echo.websocket.org",
  758. port,
  759. use_ssl,
  760. ebuf,
  761. sizeof(ebuf),
  762. "/",
  763. "http://websocket.org",
  764. (mg_websocket_data_handler)websocket_data_handler,
  765. NULL,
  766. NULL);
  767. ASSERT(conn != NULL);
  768. ut_mg_stop(ctx);
  769. }
  770. static int alloc_printf(char **out_buf, char *buf, size_t size, char *fmt, ...)
  771. {
  772. va_list ap;
  773. int ret = 0;
  774. va_start(ap, fmt);
  775. ret = alloc_vprintf(out_buf, buf, size, fmt, ap);
  776. va_end(ap);
  777. return ret;
  778. }
  779. #if defined(MG_LEGACY_INTERFACE)
  780. static void test_mg_upload(void)
  781. {
  782. static const char *boundary = "OOO___MY_BOUNDARY___OOO";
  783. struct mg_context *ctx;
  784. #if 0
  785. struct mg_connection *conn;
  786. char ebuf[100], buf[20], *file2_data;
  787. int file2_len;
  788. #endif
  789. char *file_data, *post_data;
  790. int file_len, post_data_len;
  791. ASSERT((ctx = mg_start(&CALLBACKS, NULL, OPTIONS)) != NULL);
  792. /* Upload one file */
  793. ASSERT((file_data = read_file("unit_test.c", &file_len)) != NULL);
  794. post_data = NULL;
  795. post_data_len = alloc_printf(&post_data,
  796. NULL,
  797. 0,
  798. "--%s\r\n"
  799. "Content-Disposition: form-data; "
  800. "name=\"file\"; "
  801. "filename=\"%s\"\r\n\r\n"
  802. "%.*s\r\n"
  803. "--%s--\r\n",
  804. boundary,
  805. upload_filename,
  806. file_len,
  807. file_data,
  808. boundary);
  809. ASSERT(post_data_len > 0);
  810. #if 0 /* TODO (bel): ... */
  811. ASSERT((conn = mg_download("localhost", atoi(HTTPS_PORT), 1,
  812. ebuf, sizeof(ebuf),
  813. "POST /upload?1 HTTP/1.1\r\n"
  814. "Content-Length: %d\r\n"
  815. "Content-Type: multipart/form-data; "
  816. "boundary=%s\r\n\r\n"
  817. "%.*s", post_data_len, boundary,
  818. post_data_len, post_data)) != NULL);
  819. mg_free(file_data), mg_free(post_data);
  820. ASSERT(mg_read(conn, buf, sizeof(buf)) == (int) strlen(upload_ok_message));
  821. ASSERT(memcmp(buf, upload_ok_message, strlen(upload_ok_message)) == 0);
  822. mg_close_connection(conn);
  823. /* Upload two files */
  824. ASSERT((file_data = read_file("include/civetweb.h", &file_len)) != NULL);
  825. ASSERT((file2_data = read_file("README.md", &file2_len)) != NULL);
  826. post_data = NULL;
  827. post_data_len = alloc_printf(&post_data, 0,
  828. /* First file */
  829. "--%s\r\n"
  830. "Content-Disposition: form-data; "
  831. "name=\"file\"; "
  832. "filename=\"%s\"\r\n\r\n"
  833. "%.*s\r\n"
  834. /* Second file */
  835. "--%s\r\n"
  836. "Content-Disposition: form-data; "
  837. "name=\"file\"; "
  838. "filename=\"%s\"\r\n\r\n"
  839. "%.*s\r\n"
  840. /* Final boundary */
  841. "--%s--\r\n",
  842. boundary, upload_filename,
  843. file_len, file_data,
  844. boundary, upload_filename2,
  845. file2_len, file2_data,
  846. boundary);
  847. ASSERT(post_data_len > 0);
  848. ASSERT((conn = mg_download("localhost", atoi(HTTPS_PORT), 1,
  849. ebuf, sizeof(ebuf),
  850. "POST /upload?2 HTTP/1.1\r\n"
  851. "Content-Length: %d\r\n"
  852. "Content-Type: multipart/form-data; "
  853. "boundary=%s\r\n\r\n"
  854. "%.*s", post_data_len, boundary,
  855. post_data_len, post_data)) != NULL);
  856. mg_free(file_data), mg_free(file2_data), mg_free(post_data);
  857. ASSERT(mg_read(conn, buf, sizeof(buf)) == (int) strlen(upload_ok_message));
  858. ASSERT(memcmp(buf, upload_ok_message, strlen(upload_ok_message)) == 0);
  859. mg_close_connection(conn);
  860. #endif
  861. ut_mg_stop(ctx);
  862. }
  863. #endif
  864. static void test_base64_encode(void)
  865. {
  866. const char *in[] = {"a", "ab", "abc", "abcd", NULL};
  867. const char *out[] = {"YQ==", "YWI=", "YWJj", "YWJjZA=="};
  868. char buf[100];
  869. int i;
  870. for (i = 0; in [i] != NULL; i++) {
  871. base64_encode((unsigned char *)in[i], strlen(in[i]), buf);
  872. ASSERT(!strcmp(buf, out[i]));
  873. }
  874. }
  875. static void test_mg_get_var(void)
  876. {
  877. static const char *post[] = {"a=1&&b=2&d&=&c=3%20&e=",
  878. "q=&st=2012%2F11%2F13+17%3A05&et=&team_id=",
  879. NULL};
  880. char buf[20];
  881. ASSERT(mg_get_var(post[0], strlen(post[0]), "a", buf, sizeof(buf)) == 1);
  882. ASSERT(buf[0] == '1' && buf[1] == '\0');
  883. ASSERT(mg_get_var(post[0], strlen(post[0]), "b", buf, sizeof(buf)) == 1);
  884. ASSERT(buf[0] == '2' && buf[1] == '\0');
  885. ASSERT(mg_get_var(post[0], strlen(post[0]), "c", buf, sizeof(buf)) == 2);
  886. ASSERT(buf[0] == '3' && buf[1] == ' ' && buf[2] == '\0');
  887. ASSERT(mg_get_var(post[0], strlen(post[0]), "e", buf, sizeof(buf)) == 0);
  888. ASSERT(buf[0] == '\0');
  889. ASSERT(mg_get_var(post[0], strlen(post[0]), "d", buf, sizeof(buf)) == -1);
  890. ASSERT(mg_get_var(post[0], strlen(post[0]), "c", buf, 2) == -2);
  891. ASSERT(mg_get_var(post[0], strlen(post[0]), "x", NULL, 10) == -2);
  892. ASSERT(mg_get_var(post[0], strlen(post[0]), "x", buf, 0) == -2);
  893. ASSERT(mg_get_var(post[1], strlen(post[1]), "st", buf, 16) == -2);
  894. ASSERT(mg_get_var(post[1], strlen(post[1]), "st", buf, 17) == 16);
  895. }
  896. static void test_set_throttle(void)
  897. {
  898. ASSERT(set_throttle(NULL, 0x0a000001, "/") == 0);
  899. ASSERT(set_throttle("10.0.0.0/8=20", 0x0a000001, "/") == 20);
  900. ASSERT(set_throttle("10.0.0.0/8=0.5k", 0x0a000001, "/") == 512);
  901. ASSERT(set_throttle("10.0.0.0/8=17m", 0x0a000001, "/") == 1048576 * 17);
  902. ASSERT(set_throttle("10.0.0.0/8=1x", 0x0a000001, "/") == 0);
  903. ASSERT(set_throttle("10.0.0.0/8=5,0.0.0.0/0=10", 0x0a000001, "/") == 10);
  904. ASSERT(set_throttle("10.0.0.0/8=5,/foo/**=7", 0x0a000001, "/index") == 5);
  905. ASSERT(set_throttle("10.0.0.0/8=5,/foo/**=7", 0x0a000001, "/foo/x") == 7);
  906. ASSERT(set_throttle("10.0.0.0/8=5,/foo/**=7", 0x0b000001, "/foxo/x") == 0);
  907. ASSERT(set_throttle("10.0.0.0/8=5,*=1", 0x0b000001, "/foxo/x") == 1);
  908. }
  909. static void test_next_option(void)
  910. {
  911. const char *p, *list = "x/8,/y**=1;2k,z";
  912. struct vec a, b;
  913. int i;
  914. ASSERT(next_option(NULL, &a, &b) == NULL);
  915. for (i = 0, p = list; (p = next_option(p, &a, &b)) != NULL; i++) {
  916. ASSERT(i != 0 || (a.ptr == list && a.len == 3 && b.len == 0));
  917. ASSERT(i != 1 || (a.ptr == list + 4 && a.len == 4 &&
  918. b.ptr == list + 9 && b.len == 4));
  919. ASSERT(i != 2 || (a.ptr == list + 14 && a.len == 1 && b.len == 0));
  920. }
  921. }
  922. #if defined(USE_LUA)
  923. static void check_lua_expr(lua_State *L, const char *expr, const char *value)
  924. {
  925. const char *v, *var_name = "myVar";
  926. char buf[100];
  927. mg_snprintf(buf, sizeof(buf), "%s = %s", var_name, expr);
  928. (void)luaL_dostring(L, buf);
  929. lua_getglobal(L, var_name);
  930. v = lua_tostring(L, -1);
  931. ASSERT((value == NULL && v == NULL) ||
  932. (value != NULL && v != NULL && !strcmp(value, v)));
  933. }
  934. static void test_lua(void)
  935. {
  936. static struct mg_connection conn;
  937. static struct mg_context ctx;
  938. char http_request[] = "POST /foo/bar HTTP/1.1\r\n"
  939. "Content-Length: 12\r\n"
  940. "Connection: close\r\n\r\nhello world!";
  941. lua_State *L = luaL_newstate();
  942. conn.ctx = &ctx;
  943. conn.buf = http_request;
  944. conn.buf_size = conn.data_len = strlen(http_request);
  945. conn.request_len =
  946. parse_http_message(conn.buf, conn.data_len, &conn.request_info);
  947. conn.content_len = conn.data_len - conn.request_len;
  948. prepare_lua_environment(&ctx, &conn, NULL, L, "unit_test", LUA_ENV_TYPE_PLAIN_LUA_PAGE);
  949. ASSERT(lua_gettop(L) == 4);
  950. check_lua_expr(L, "'hi'", "hi");
  951. check_lua_expr(L, "mg.request_info.request_method", "POST");
  952. check_lua_expr(L, "mg.request_info.uri", "/foo/bar");
  953. check_lua_expr(L, "mg.request_info.num_headers", "2");
  954. check_lua_expr(L, "mg.request_info.remote_ip", "0");
  955. check_lua_expr(L, "mg.request_info.http_headers['Content-Length']", "12");
  956. check_lua_expr(L, "mg.request_info.http_headers['Connection']", "close");
  957. (void)luaL_dostring(L, "post = mg.read()");
  958. check_lua_expr(L, "# post", "12");
  959. check_lua_expr(L, "post", "hello world!");
  960. lua_close(L);
  961. }
  962. #endif
  963. static void test_mg_stat(void)
  964. {
  965. static struct mg_context ctx;
  966. struct file file = STRUCT_FILE_INITIALIZER;
  967. ASSERT(!mg_stat(fc(&ctx), " does not exist ", &file));
  968. }
  969. static void test_skip_quoted(void)
  970. {
  971. char x[] = "a=1, b=2, c='hi \' there', d='here\\, there'", *s = x, *p;
  972. p = skip_quoted(&s, ", ", ", ", 0);
  973. ASSERT(p != NULL && !strcmp(p, "a=1"));
  974. p = skip_quoted(&s, ", ", ", ", 0);
  975. ASSERT(p != NULL && !strcmp(p, "b=2"));
  976. p = skip_quoted(&s, ",", " ", 0);
  977. ASSERT(p != NULL && !strcmp(p, "c='hi \' there'"));
  978. p = skip_quoted(&s, ",", " ", '\\');
  979. ASSERT(p != NULL && !strcmp(p, "d='here, there'"));
  980. ASSERT(*s == 0);
  981. }
  982. static void test_alloc_vprintf(void)
  983. {
  984. char buf[MG_BUF_LEN], *p = buf;
  985. ASSERT(alloc_printf(&p, buf, sizeof(buf), "%s", "hi") == 2);
  986. ASSERT(p == buf);
  987. ASSERT(alloc_printf(&p, buf, sizeof(buf), "%s", "") == 0);
  988. ASSERT(alloc_printf(&p, buf, sizeof(buf), "") == 0);
  989. /* Pass small buffer, make sure alloc_printf allocates */
  990. ASSERT(alloc_printf(&p, buf, 1, "%s", "hello") == 5);
  991. ASSERT(p != buf);
  992. mg_free(p);
  993. }
  994. static void test_request_replies(void)
  995. {
  996. char ebuf[100];
  997. int i;
  998. struct mg_connection *conn;
  999. struct mg_context *ctx;
  1000. static struct {
  1001. const char *request, *reply_regex;
  1002. } tests[] = {
  1003. {"GET hello.txt HTTP/1.0\r\nRange: bytes=3-5\r\n\r\n",
  1004. "^HTTP/1.1 206 Partial Content"},
  1005. {NULL, NULL},
  1006. };
  1007. ASSERT((ctx = mg_start(&CALLBACKS, NULL, OPTIONS)) != NULL);
  1008. for (i = 0; tests[i].request != NULL; i++) {
  1009. ASSERT((conn = mg_download("localhost",
  1010. atoi(HTTP_PORT),
  1011. 0,
  1012. ebuf,
  1013. sizeof(ebuf),
  1014. "%s",
  1015. tests[i].request)) != NULL);
  1016. mg_close_connection(conn);
  1017. }
  1018. ut_mg_stop(ctx);
  1019. #ifndef NO_SSL
  1020. ASSERT((ctx = mg_start(&CALLBACKS, NULL, OPTIONS)) != NULL);
  1021. for (i = 0; tests[i].request != NULL; i++) {
  1022. ASSERT((conn = mg_download("localhost",
  1023. atoi(HTTPS_PORT),
  1024. 1,
  1025. ebuf,
  1026. sizeof(ebuf),
  1027. "%s",
  1028. tests[i].request)) != NULL);
  1029. mg_close_connection(conn);
  1030. }
  1031. ut_mg_stop(ctx);
  1032. #endif
  1033. }
  1034. static int request_test_handler(struct mg_connection *conn, void *cbdata)
  1035. {
  1036. int i;
  1037. char chunk_data[32];
  1038. ASSERT(cbdata == (void *)7);
  1039. strcpy(chunk_data, "123456789A123456789B123456789C");
  1040. mg_printf(conn,
  1041. "HTTP/1.1 200 OK\r\n"
  1042. "Transfer-Encoding: chunked\r\n"
  1043. "Content-Type: text/plain\r\n\r\n");
  1044. for (i = 0; i < 20; i++) {
  1045. mg_printf(conn, "%x\r\n", i);
  1046. mg_write(conn, chunk_data, i);
  1047. mg_printf(conn, "\r\n");
  1048. }
  1049. mg_printf(conn, "0\r\n\r\n");
  1050. return 1;
  1051. }
  1052. static void test_request_handlers(void)
  1053. {
  1054. char ebuf[100];
  1055. struct mg_context *ctx;
  1056. struct mg_connection *conn;
  1057. char uri[64];
  1058. int i;
  1059. const char *request = "GET /U7 HTTP/1.0\r\n\r\n";
  1060. ctx = mg_start(NULL, NULL, OPTIONS);
  1061. ASSERT(ctx != NULL);
  1062. for (i = 0; i < 1000; i++) {
  1063. sprintf(uri, "/U%u", i);
  1064. mg_set_request_handler(ctx, uri, request_test_handler, NULL);
  1065. }
  1066. for (i = 500; i < 800; i++) {
  1067. sprintf(uri, "/U%u", i);
  1068. mg_set_request_handler(ctx, uri, NULL, (void *)1);
  1069. }
  1070. for (i = 600; i >= 0; i--) {
  1071. sprintf(uri, "/U%u", i);
  1072. mg_set_request_handler(ctx, uri, NULL, (void *)2);
  1073. }
  1074. for (i = 750; i <= 1000; i++) {
  1075. sprintf(uri, "/U%u", i);
  1076. mg_set_request_handler(ctx, uri, NULL, (void *)3);
  1077. }
  1078. for (i = 5; i < 9; i++) {
  1079. sprintf(uri, "/U%u", i);
  1080. mg_set_request_handler(ctx, uri, request_test_handler, (void *)(intptr_t)i);
  1081. }
  1082. conn = mg_download(
  1083. "localhost", atoi(HTTP_PORT), 0, ebuf, sizeof(ebuf), "%s", request);
  1084. ASSERT(conn != NULL);
  1085. mg_sleep(1000);
  1086. mg_close_connection(conn);
  1087. ut_mg_stop(ctx);
  1088. }
  1089. static int api_callback(struct mg_connection *conn)
  1090. {
  1091. const struct mg_request_info *ri = mg_get_request_info(conn);
  1092. char post_data[100] = "";
  1093. ASSERT(ri->user_data == (void *)123);
  1094. ASSERT(ri->num_headers == 2);
  1095. ASSERT(strcmp(mg_get_header(conn, "host"), "blah.com") == 0);
  1096. ASSERT(mg_read(conn, post_data, sizeof(post_data)) == 3);
  1097. ASSERT(memcmp(post_data, "b=1", 3) == 0);
  1098. ASSERT(ri->query_string != NULL);
  1099. ASSERT(ri->remote_addr[0] != 0);
  1100. ASSERT(ri->remote_port > 0);
  1101. ASSERT(strcmp(ri->http_version, "1.0") == 0);
  1102. mg_printf(conn, "HTTP/1.0 200 OK\r\n\r\n");
  1103. return 1;
  1104. }
  1105. static void test_api_calls(void)
  1106. {
  1107. char ebuf[100];
  1108. struct mg_callbacks callbacks;
  1109. struct mg_connection *conn;
  1110. struct mg_context *ctx;
  1111. static const char *request =
  1112. "POST /?a=%20&b=&c=xx HTTP/1.0\r\n"
  1113. "Host: blah.com\n" /* More spaces before */
  1114. "content-length: 3\r\n" /* Lower case header name */
  1115. "\r\nb=123456"; /* Content size > content-length, test for mg_read() */
  1116. memset(&callbacks, 0, sizeof(callbacks));
  1117. callbacks.begin_request = api_callback;
  1118. ASSERT((ctx = mg_start(&callbacks, (void *)123, OPTIONS)) != NULL);
  1119. ASSERT((conn = mg_download("localhost",
  1120. atoi(HTTP_PORT),
  1121. 0,
  1122. ebuf,
  1123. sizeof(ebuf),
  1124. "%s",
  1125. request)) != NULL);
  1126. mg_close_connection(conn);
  1127. ut_mg_stop(ctx);
  1128. }
  1129. static void test_url_decode(void)
  1130. {
  1131. char buf[100];
  1132. ASSERT(mg_url_decode("foo", 3, buf, 3, 0) == -1); /* No space for \0 */
  1133. ASSERT(mg_url_decode("foo", 3, buf, 4, 0) == 3);
  1134. ASSERT(strcmp(buf, "foo") == 0);
  1135. ASSERT(mg_url_decode("a+", 2, buf, sizeof(buf), 0) == 2);
  1136. ASSERT(strcmp(buf, "a+") == 0);
  1137. ASSERT(mg_url_decode("a+", 2, buf, sizeof(buf), 1) == 2);
  1138. ASSERT(strcmp(buf, "a ") == 0);
  1139. ASSERT(mg_url_decode("%61", 1, buf, sizeof(buf), 1) == 1);
  1140. ASSERT(strcmp(buf, "%") == 0);
  1141. ASSERT(mg_url_decode("%61", 2, buf, sizeof(buf), 1) == 2);
  1142. ASSERT(strcmp(buf, "%6") == 0);
  1143. ASSERT(mg_url_decode("%61", 3, buf, sizeof(buf), 1) == 1);
  1144. ASSERT(strcmp(buf, "a") == 0);
  1145. }
  1146. static void test_mg_strcasestr(void)
  1147. {
  1148. static const char *big1 = "abcdef";
  1149. ASSERT(mg_strcasestr("Y", "X") == NULL);
  1150. ASSERT(mg_strcasestr("Y", "y") != NULL);
  1151. ASSERT(mg_strcasestr(big1, "X") == NULL);
  1152. ASSERT(mg_strcasestr(big1, "CD") == big1 + 2);
  1153. ASSERT(mg_strcasestr("aa", "AAB") == NULL);
  1154. }
  1155. static void test_mg_get_cookie(void)
  1156. {
  1157. char buf[20];
  1158. ASSERT(mg_get_cookie("", "foo", NULL, sizeof(buf)) == -2);
  1159. ASSERT(mg_get_cookie("", "foo", buf, 0) == -2);
  1160. ASSERT(mg_get_cookie("", "foo", buf, sizeof(buf)) == -1);
  1161. ASSERT(mg_get_cookie("", NULL, buf, sizeof(buf)) == -1);
  1162. ASSERT(mg_get_cookie("a=1; b=2; c; d", "a", buf, sizeof(buf)) == 1);
  1163. ASSERT(strcmp(buf, "1") == 0);
  1164. ASSERT(mg_get_cookie("a=1; b=2; c; d", "b", buf, sizeof(buf)) == 1);
  1165. ASSERT(strcmp(buf, "2") == 0);
  1166. ASSERT(mg_get_cookie("a=1; b=123", "b", buf, sizeof(buf)) == 3);
  1167. ASSERT(strcmp(buf, "123") == 0);
  1168. ASSERT(mg_get_cookie("a=1; b=2; c; d", "c", buf, sizeof(buf)) == -1);
  1169. }
  1170. static void test_strtoll(void)
  1171. {
  1172. ASSERT(strtoll("0", NULL, 10) == 0);
  1173. ASSERT(strtoll("123", NULL, 10) == 123);
  1174. ASSERT(strtoll("-34", NULL, 10) == -34);
  1175. ASSERT(strtoll("3566626116", NULL, 10) == 3566626116);
  1176. }
  1177. static void test_parse_port_string(void)
  1178. {
  1179. static const char *valid[] = {
  1180. "0",
  1181. "1",
  1182. "1s",
  1183. "1r",
  1184. "1.2.3.4:1",
  1185. "1.2.3.4:1s",
  1186. "1.2.3.4:1r",
  1187. #if defined(USE_IPV6)
  1188. "[::1]:123",
  1189. "[3ffe:2a00:100:7031::1]:900",
  1190. #endif
  1191. NULL
  1192. };
  1193. static const char *invalid[] = {
  1194. "99999", "1k", "1.2.3", "1.2.3.4:", "1.2.3.4:2p", NULL};
  1195. struct socket so;
  1196. struct vec vec;
  1197. int ipv;
  1198. int i;
  1199. for (i = 0; valid[i] != NULL; i++) {
  1200. vec.ptr = valid[i];
  1201. vec.len = strlen(vec.ptr);
  1202. ASSERT(parse_port_string(&vec, &so, &ipv) != 0);
  1203. }
  1204. for (i = 0; invalid[i] != NULL; i++) {
  1205. vec.ptr = invalid[i];
  1206. vec.len = strlen(vec.ptr);
  1207. ASSERT(parse_port_string(&vec, &so, &ipv) == 0);
  1208. }
  1209. }
  1210. static void test_md5(void)
  1211. {
  1212. md5_state_t md5_state;
  1213. unsigned char md5_val[16 + 1];
  1214. char md5_str[32 + 1];
  1215. const char *test_str = "The quick brown fox jumps over the lazy dog";
  1216. md5_val[16] = 0;
  1217. md5_init(&md5_state);
  1218. md5_finish(&md5_state, md5_val);
  1219. ASSERT(strcmp((const char *)md5_val,
  1220. "\xd4\x1d\x8c\xd9\x8f\x00\xb2\x04\xe9"
  1221. "\x80\x09\x98\xec\xf8\x42\x7e") == 0);
  1222. sprintf(md5_str,
  1223. "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
  1224. md5_val[0],
  1225. md5_val[1],
  1226. md5_val[2],
  1227. md5_val[3],
  1228. md5_val[4],
  1229. md5_val[5],
  1230. md5_val[6],
  1231. md5_val[7],
  1232. md5_val[8],
  1233. md5_val[9],
  1234. md5_val[10],
  1235. md5_val[11],
  1236. md5_val[12],
  1237. md5_val[13],
  1238. md5_val[14],
  1239. md5_val[15]);
  1240. ASSERT(strcmp(md5_str, "d41d8cd98f00b204e9800998ecf8427e") == 0);
  1241. mg_md5(md5_str, "", NULL);
  1242. ASSERT(strcmp(md5_str, "d41d8cd98f00b204e9800998ecf8427e") == 0);
  1243. md5_init(&md5_state);
  1244. md5_append(&md5_state, (const md5_byte_t *)test_str, strlen(test_str));
  1245. md5_finish(&md5_state, md5_val);
  1246. sprintf(md5_str,
  1247. "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
  1248. md5_val[0],
  1249. md5_val[1],
  1250. md5_val[2],
  1251. md5_val[3],
  1252. md5_val[4],
  1253. md5_val[5],
  1254. md5_val[6],
  1255. md5_val[7],
  1256. md5_val[8],
  1257. md5_val[9],
  1258. md5_val[10],
  1259. md5_val[11],
  1260. md5_val[12],
  1261. md5_val[13],
  1262. md5_val[14],
  1263. md5_val[15]);
  1264. ASSERT(strcmp(md5_str, "9e107d9d372bb6826bd81d3542a419d6") == 0);
  1265. mg_md5(md5_str, test_str, NULL);
  1266. ASSERT(strcmp(md5_str, "9e107d9d372bb6826bd81d3542a419d6") == 0);
  1267. mg_md5(md5_str,
  1268. "The",
  1269. " ",
  1270. "quick brown fox",
  1271. "",
  1272. " jumps ",
  1273. "over the lazy dog",
  1274. "",
  1275. "",
  1276. NULL);
  1277. ASSERT(strcmp(md5_str, "9e107d9d372bb6826bd81d3542a419d6") == 0);
  1278. mg_md5(md5_str, "civetweb", NULL);
  1279. ASSERT(strcmp(md5_str, "95c098bd85b619b24a83d9cea5e8ba54") == 0);
  1280. }
  1281. int __cdecl main(void)
  1282. {
  1283. char buffer[512];
  1284. FILE *f;
  1285. struct mg_context *ctx;
  1286. int i;
  1287. /* print headline */
  1288. printf("Civetweb %s unit test\n", mg_version());
  1289. #if defined(_WIN32)
  1290. GetCurrentDirectoryA(sizeof(buffer), buffer);
  1291. #else
  1292. getcwd(buffer, sizeof(buffer));
  1293. #endif
  1294. printf("Test directory is \"%s\"\n",
  1295. buffer); /* should be the "test" directory */
  1296. f = fopen("hello.txt", "r");
  1297. if (f) {
  1298. fclose(f);
  1299. } else {
  1300. printf("Error: Test directory does not contain hello.txt\n");
  1301. }
  1302. f = fopen("unit_test.c", "r");
  1303. if (f) {
  1304. fclose(f);
  1305. } else {
  1306. printf("Error: Test directory does not contain unit_test.c\n");
  1307. }
  1308. /* test local functions */
  1309. test_parse_port_string();
  1310. test_mg_strcasestr();
  1311. test_alloc_vprintf();
  1312. test_base64_encode();
  1313. test_match_prefix();
  1314. test_remove_double_dots();
  1315. test_should_keep_alive();
  1316. test_parse_http_message();
  1317. test_mg_get_var();
  1318. test_set_throttle();
  1319. test_next_option();
  1320. test_mg_stat();
  1321. test_skip_quoted();
  1322. test_url_decode();
  1323. test_mg_get_cookie();
  1324. test_strtoll();
  1325. test_md5();
  1326. /* start stop server */
  1327. ctx = mg_start(NULL, NULL, OPTIONS);
  1328. REQUIRE(ctx != NULL);
  1329. mg_sleep(1000);
  1330. ut_mg_stop(ctx);
  1331. /* create test data */
  1332. fetch_data = (char *)mg_malloc(fetch_data_size);
  1333. for (i = 0; i < fetch_data_size; i++) {
  1334. fetch_data[i] = 'a' + i % 10;
  1335. }
  1336. /* tests with network access */
  1337. init_CALLBACKS();
  1338. test_mg_download(0);
  1339. #ifndef NO_SSL
  1340. test_mg_download(1);
  1341. #endif
  1342. test_mg_websocket_client_connect(0);
  1343. #ifndef NO_SSL
  1344. test_mg_websocket_client_connect(1);
  1345. #endif
  1346. #if defined(MG_LEGACY_INTERFACE)
  1347. test_mg_upload();
  1348. #endif
  1349. test_request_replies();
  1350. test_api_calls();
  1351. test_request_handlers();
  1352. #if defined(USE_LUA)
  1353. test_lua();
  1354. #endif
  1355. /* test completed */
  1356. mg_free(fetch_data);
  1357. #ifdef MEMORY_DEBUGGING
  1358. {
  1359. extern unsigned long mg_memory_debug_blockCount;
  1360. extern unsigned long mg_memory_debug_totalMemUsed;
  1361. printf("MEMORY DEBUGGING: %lu %lu\n",
  1362. mg_memory_debug_blockCount,
  1363. mg_memory_debug_totalMemUsed);
  1364. }
  1365. #endif
  1366. printf("TOTAL TESTS: %d, FAILED: %d\n", s_total_tests, s_failed_tests);
  1367. return s_failed_tests == 0 ? EXIT_SUCCESS : EXIT_FAILURE;
  1368. }