unit_test.c 46 KB

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