unit_test.c 41 KB

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