unit_test.c 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918
  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. /* TODO(bel):
  45. #define HTTP_PORT "56789"
  46. #define HTTPS_PORT "56790"
  47. #define HTTP_PORT2 "56791"
  48. #define LISTENING_ADDR \
  49. "127.0.0.1:" HTTP_PORT "r" \
  50. ",127.0.0.1:" HTTPS_PORT "s" \
  51. ",127.0.0.1:" HTTP_PORT2
  52. */
  53. #define HTTP_PORT "8080"
  54. #ifdef NO_SSL
  55. #define HTTPS_PORT HTTP_PORT
  56. #define LISTENING_ADDR "127.0.0.1:" HTTP_PORT
  57. #else
  58. #define HTTPS_PORT "443"
  59. #define LISTENING_ADDR "127.0.0.1:" HTTP_PORT ",127.0.0.1:" HTTPS_PORT "s"
  60. #endif
  61. static void test_parse_http_message() {
  62. struct mg_request_info ri;
  63. char req1[] = "GET / HTTP/1.1\r\n\r\n";
  64. char req2[] = "BLAH / HTTP/1.1\r\n\r\n";
  65. char req3[] = "GET / HTTP/1.1\r\nBah\r\n";
  66. char req4[] = "GET / HTTP/1.1\r\nA: foo bar\r\nB: bar\r\nbaz\r\n\r\n";
  67. char req5[] = "GET / HTTP/1.1\r\n\r\n";
  68. char req6[] = "G";
  69. char req7[] = " blah ";
  70. char req8[] = " HTTP/1.1 200 OK \n\n";
  71. char req9[] = "HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n";
  72. ASSERT(parse_http_message(req9, sizeof(req9), &ri) == sizeof(req9) - 1);
  73. ASSERT(ri.num_headers == 1);
  74. ASSERT(parse_http_message(req1, sizeof(req1), &ri) == sizeof(req1) - 1);
  75. ASSERT(strcmp(ri.http_version, "1.1") == 0);
  76. ASSERT(ri.num_headers == 0);
  77. ASSERT(parse_http_message(req2, sizeof(req2), &ri) == -1);
  78. ASSERT(parse_http_message(req3, sizeof(req3), &ri) == 0);
  79. ASSERT(parse_http_message(req6, sizeof(req6), &ri) == 0);
  80. ASSERT(parse_http_message(req7, sizeof(req7), &ri) == 0);
  81. ASSERT(parse_http_message("", 0, &ri) == 0);
  82. ASSERT(parse_http_message(req8, sizeof(req8), &ri) == sizeof(req8) - 1);
  83. /* TODO(lsm): Fix this. Header value may span multiple lines. */
  84. ASSERT(parse_http_message(req4, sizeof(req4), &ri) == sizeof(req4) - 1);
  85. ASSERT(strcmp(ri.http_version, "1.1") == 0);
  86. ASSERT(ri.num_headers == 3);
  87. ASSERT(strcmp(ri.http_headers[0].name, "A") == 0);
  88. ASSERT(strcmp(ri.http_headers[0].value, "foo bar") == 0);
  89. ASSERT(strcmp(ri.http_headers[1].name, "B") == 0);
  90. ASSERT(strcmp(ri.http_headers[1].value, "bar") == 0);
  91. ASSERT(strcmp(ri.http_headers[2].name, "baz\r\n\r") == 0);
  92. ASSERT(strcmp(ri.http_headers[2].value, "") == 0);
  93. ASSERT(parse_http_message(req5, sizeof(req5), &ri) == sizeof(req5) - 1);
  94. ASSERT(strcmp(ri.request_method, "GET") == 0);
  95. ASSERT(strcmp(ri.http_version, "1.1") == 0);
  96. }
  97. static void test_should_keep_alive(void) {
  98. struct mg_connection conn;
  99. struct mg_context ctx;
  100. char req1[] = "GET / HTTP/1.1\r\n\r\n";
  101. char req2[] = "GET / HTTP/1.0\r\n\r\n";
  102. char req3[] = "GET / HTTP/1.1\r\nConnection: close\r\n\r\n";
  103. char req4[] = "GET / HTTP/1.1\r\nConnection: keep-alive\r\n\r\n";
  104. memset(&conn, 0, sizeof(conn));
  105. conn.ctx = &ctx;
  106. ASSERT(parse_http_message(req1, sizeof(req1), &conn.request_info) ==
  107. sizeof(req1) - 1);
  108. ctx.config[ENABLE_KEEP_ALIVE] = "no";
  109. ASSERT(should_keep_alive(&conn) == 0);
  110. ctx.config[ENABLE_KEEP_ALIVE] = "yes";
  111. ASSERT(should_keep_alive(&conn) == 1);
  112. conn.must_close = 1;
  113. ASSERT(should_keep_alive(&conn) == 0);
  114. conn.must_close = 0;
  115. parse_http_message(req2, sizeof(req2), &conn.request_info);
  116. ASSERT(should_keep_alive(&conn) == 0);
  117. parse_http_message(req3, sizeof(req3), &conn.request_info);
  118. ASSERT(should_keep_alive(&conn) == 0);
  119. parse_http_message(req4, sizeof(req4), &conn.request_info);
  120. ASSERT(should_keep_alive(&conn) == 1);
  121. conn.status_code = 401;
  122. ASSERT(should_keep_alive(&conn) == 0);
  123. conn.status_code = 200;
  124. conn.must_close = 1;
  125. ASSERT(should_keep_alive(&conn) == 0);
  126. }
  127. static void test_match_prefix(void) {
  128. ASSERT(match_prefix("/api", 4, "/api") == 4);
  129. ASSERT(match_prefix("/a/", 3, "/a/b/c") == 3);
  130. ASSERT(match_prefix("/a/", 3, "/ab/c") == -1);
  131. ASSERT(match_prefix("/*/", 3, "/ab/c") == 4);
  132. ASSERT(match_prefix("**", 2, "/a/b/c") == 6);
  133. ASSERT(match_prefix("/*", 2, "/a/b/c") == 2);
  134. ASSERT(match_prefix("*/*", 3, "/a/b/c") == 2);
  135. ASSERT(match_prefix("**/", 3, "/a/b/c") == 5);
  136. ASSERT(match_prefix("**.foo|**.bar", 13, "a.bar") == 5);
  137. ASSERT(match_prefix("a|b|cd", 6, "cdef") == 2);
  138. ASSERT(match_prefix("a|b|c?", 6, "cdef") == 2);
  139. ASSERT(match_prefix("a|?|cd", 6, "cdef") == 1);
  140. ASSERT(match_prefix("/a/**.cgi", 9, "/foo/bar/x.cgi") == -1);
  141. ASSERT(match_prefix("/a/**.cgi", 9, "/a/bar/x.cgi") == 12);
  142. ASSERT(match_prefix("**/", 3, "/a/b/c") == 5);
  143. ASSERT(match_prefix("**/$", 4, "/a/b/c") == -1);
  144. ASSERT(match_prefix("**/$", 4, "/a/b/") == 5);
  145. ASSERT(match_prefix("$", 1, "") == 0);
  146. ASSERT(match_prefix("$", 1, "x") == -1);
  147. ASSERT(match_prefix("*$", 2, "x") == 1);
  148. ASSERT(match_prefix("/$", 2, "/") == 1);
  149. ASSERT(match_prefix("**/$", 4, "/a/b/c") == -1);
  150. ASSERT(match_prefix("**/$", 4, "/a/b/") == 5);
  151. ASSERT(match_prefix("*", 1, "/hello/") == 0);
  152. ASSERT(match_prefix("**.a$|**.b$", 11, "/a/b.b/") == -1);
  153. ASSERT(match_prefix("**.a$|**.b$", 11, "/a/b.b") == 6);
  154. ASSERT(match_prefix("**.a$|**.b$", 11, "/a/B.A") == 6);
  155. ASSERT(match_prefix("**o$", 4, "HELLO") == 5);
  156. }
  157. static void test_remove_double_dots() {
  158. struct { char before[20], after[20]; } data[] = {
  159. {"////a", "/a"},
  160. {"/.....", "/."},
  161. {"/......", "/"},
  162. {"...", "..."},
  163. {"/...///", "/./"},
  164. {"/a...///", "/a.../"},
  165. {"/.x", "/.x"},
  166. {"/\\", "/"},
  167. {"/a\\", "/a\\"},
  168. {"/a\\\\...", "/a\\."},
  169. };
  170. size_t i;
  171. for (i = 0; i < ARRAY_SIZE(data); i++) {
  172. remove_double_dots_and_double_slashes(data[i].before);
  173. ASSERT(strcmp(data[i].before, data[i].after) == 0);
  174. }
  175. }
  176. static char *read_file(const char *path, int *size) {
  177. FILE *fp;
  178. struct stat st;
  179. char *data = NULL;
  180. if ((fp = fopen(path, "rb")) != NULL && !fstat(fileno(fp), &st)) {
  181. *size = (int) st.st_size;
  182. ASSERT((data = mg_malloc(*size)) != NULL);
  183. ASSERT(fread(data, 1, *size, fp) == (size_t) *size);
  184. fclose(fp);
  185. }
  186. return data;
  187. }
  188. static const char *fetch_data = "hello world!\n";
  189. static const char *inmemory_file_data = "hi there";
  190. static const char *upload_filename = "upload_test.txt";
  191. static const char *upload_filename2 = "upload_test2.txt";
  192. static const char *upload_ok_message = "upload successful";
  193. static const char *open_file_cb(const struct mg_connection *conn,
  194. const char *path, size_t *size) {
  195. (void) conn;
  196. if (!strcmp(path, "./blah")) {
  197. *size = strlen(inmemory_file_data);
  198. return inmemory_file_data;
  199. }
  200. return NULL;
  201. }
  202. static void upload_cb(struct mg_connection *conn, const char *path) {
  203. const struct mg_request_info *ri = mg_get_request_info(conn);
  204. char *p1, *p2;
  205. int len1, len2;
  206. if (atoi(ri->query_string) == 1) {
  207. ASSERT(!strcmp(path, "./upload_test.txt"));
  208. ASSERT((p1 = read_file("src/civetweb.c", &len1)) != NULL);
  209. ASSERT((p2 = read_file(path, &len2)) != NULL);
  210. ASSERT(len1 == len2);
  211. ASSERT(memcmp(p1, p2, len1) == 0);
  212. mg_free(p1), mg_free(p2);
  213. remove(upload_filename);
  214. } else if (atoi(ri->query_string) == 2) {
  215. if (!strcmp(path, "./upload_test.txt")) {
  216. ASSERT((p1 = read_file("include/civetweb.h", &len1)) != NULL);
  217. ASSERT((p2 = read_file(path, &len2)) != NULL);
  218. ASSERT(len1 == len2);
  219. ASSERT(memcmp(p1, p2, len1) == 0);
  220. mg_free(p1), mg_free(p2);
  221. remove(upload_filename);
  222. } else if (!strcmp(path, "./upload_test2.txt")) {
  223. ASSERT((p1 = read_file("README.md", &len1)) != NULL);
  224. ASSERT((p2 = read_file(path, &len2)) != NULL);
  225. ASSERT(len1 == len2);
  226. ASSERT(memcmp(p1, p2, len1) == 0);
  227. mg_free(p1), mg_free(p2);
  228. remove(upload_filename);
  229. } else {
  230. ASSERT(0);
  231. }
  232. } else {
  233. ASSERT(0);
  234. }
  235. mg_printf(conn, "HTTP/1.0 200 OK\r\nContent-Length: %d\r\n\r\n%s",
  236. (int) strlen(upload_ok_message), upload_ok_message);
  237. }
  238. static int begin_request_handler_cb(struct mg_connection *conn) {
  239. const struct mg_request_info *ri = mg_get_request_info(conn);
  240. if (!strcmp(ri->uri, "/data")) {
  241. mg_printf(conn, "HTTP/1.1 200 OK\r\n"
  242. "Content-Type: text/plain\r\n\r\n"
  243. "%s", fetch_data);
  244. close_connection(conn);
  245. return 1;
  246. }
  247. if (!strcmp(ri->uri, "/upload")) {
  248. ASSERT(ri->query_string != NULL);
  249. ASSERT(mg_upload(conn, ".") == atoi(ri->query_string));
  250. }
  251. return 0;
  252. }
  253. static int log_message_cb(const struct mg_connection *conn, const char *msg) {
  254. (void) conn;
  255. printf("%s\n", msg);
  256. return 0;
  257. }
  258. int (*begin_request)(struct mg_connection *);
  259. void (*end_request)(const struct mg_connection *, int reply_status_code);
  260. int (*log_message)(const struct mg_connection *, const char *message);
  261. int (*init_ssl)(void *ssl_context, void *user_data);
  262. int (*websocket_connect)(const struct mg_connection *);
  263. void (*websocket_ready)(struct mg_connection *);
  264. int (*websocket_data)(struct mg_connection *, int bits,
  265. char *data, size_t data_len);
  266. void (*connection_close)(struct mg_connection *);
  267. const char * (*open_file)(const struct mg_connection *,
  268. const char *path, size_t *data_len);
  269. void (*init_lua)(struct mg_connection *, void *lua_context);
  270. void (*upload)(struct mg_connection *, const char *file_name);
  271. int (*http_error)(struct mg_connection *, int status);
  272. static const struct mg_callbacks CALLBACKS = {
  273. &begin_request_handler_cb, NULL, &log_message_cb, NULL, NULL, NULL, NULL, NULL,
  274. &open_file_cb, NULL, &upload_cb, NULL
  275. };
  276. static const char *OPTIONS[] = {
  277. "document_root", ".",
  278. "listening_ports", LISTENING_ADDR,
  279. "enable_keep_alive", "yes",
  280. #ifndef NO_SSL
  281. "ssl_certificate", "../resources/ssl_cert.pem",
  282. #endif
  283. NULL,
  284. };
  285. static char *read_conn(struct mg_connection *conn, int *size) {
  286. char buf[100], *data = NULL;
  287. int len;
  288. *size = 0;
  289. while ((len = mg_read(conn, buf, sizeof(buf))) > 0) {
  290. *size += len;
  291. ASSERT((data = mg_realloc(data, *size)) != NULL);
  292. memcpy(data + *size - len, buf, len);
  293. }
  294. return data;
  295. }
  296. static void test_mg_download(int use_ssl) {
  297. char *p1, *p2, ebuf[100];
  298. int len1, len2, port;
  299. struct mg_connection *conn;
  300. struct mg_context *ctx;
  301. if (use_ssl) port = atoi(HTTPS_PORT); else port = atoi(HTTP_PORT);
  302. ASSERT((ctx = mg_start(&CALLBACKS, NULL, OPTIONS)) != NULL);
  303. ASSERT(mg_download(NULL, port, use_ssl, ebuf, sizeof(ebuf), "%s", "") == NULL);
  304. ASSERT(mg_download("localhost", 0, use_ssl, ebuf, sizeof(ebuf), "%s", "") == NULL);
  305. ASSERT(mg_download("localhost", port, use_ssl, ebuf, sizeof(ebuf), "%s", "") == NULL);
  306. /* Fetch nonexistent file, should see 404 */
  307. ASSERT((conn = mg_download("localhost", port, use_ssl, ebuf, sizeof(ebuf), "%s",
  308. "GET /gimbec HTTP/1.0\r\n\r\n")) != NULL);
  309. ASSERT(strcmp(conn->request_info.uri, "404") == 0);
  310. mg_close_connection(conn);
  311. if (use_ssl) {
  312. ASSERT((conn = mg_download("google.com", 443, 1, ebuf, sizeof(ebuf), "%s",
  313. "GET / HTTP/1.0\r\n\r\n")) != NULL);
  314. mg_close_connection(conn);
  315. } else {
  316. ASSERT((conn = mg_download("google.com", 80, 0, ebuf, sizeof(ebuf), "%s",
  317. "GET / HTTP/1.0\r\n\r\n")) != NULL);
  318. mg_close_connection(conn);
  319. }
  320. /* Fetch unit_test.c, should succeed */
  321. ASSERT((conn = mg_download("localhost", port, use_ssl, ebuf, sizeof(ebuf), "%s",
  322. "GET /unit_test.c HTTP/1.0\r\n\r\n")) != NULL);
  323. ASSERT(!strcmp(conn->request_info.uri, "200"));
  324. ASSERT((p1 = read_conn(conn, &len1)) != NULL);
  325. ASSERT((p2 = read_file("unit_test.c", &len2)) != NULL);
  326. ASSERT(len1 == len2);
  327. ASSERT(memcmp(p1, p2, len1) == 0);
  328. mg_free(p1), mg_free(p2);
  329. mg_close_connection(conn);
  330. /* Fetch in-memory file, should succeed. */
  331. ASSERT((conn = mg_download("localhost", port, use_ssl, ebuf, sizeof(ebuf), "%s",
  332. "GET /blah HTTP/1.1\r\n\r\n")) != NULL);
  333. ASSERT((p1 = read_conn(conn, &len1)) != NULL);
  334. ASSERT(len1 == (int) strlen(inmemory_file_data));
  335. ASSERT(memcmp(p1, inmemory_file_data, len1) == 0);
  336. mg_free(p1);
  337. mg_close_connection(conn);
  338. /* Fetch in-memory data with no Content-Length, should succeed. */
  339. ASSERT((conn = mg_download("localhost", port, use_ssl, ebuf, sizeof(ebuf), "%s",
  340. "GET /data HTTP/1.1\r\n\r\n")) != NULL);
  341. ASSERT((p1 = read_conn(conn, &len1)) != NULL);
  342. ASSERT(len1 == (int) strlen(fetch_data));
  343. ASSERT(memcmp(p1, fetch_data, len1) == 0);
  344. mg_free(p1);
  345. mg_close_connection(conn);
  346. /* Test SSL redirect, IP address */
  347. /* TODO(bel):
  348. ASSERT((conn = mg_download("localhost", atoi(HTTP_PORT), 0,
  349. ebuf, sizeof(ebuf), "%s",
  350. "GET /foo HTTP/1.1\r\n\r\n")) != NULL);
  351. ASSERT(strcmp(conn->request_info.uri, "302") == 0);
  352. ASSERT(strcmp(mg_get_header(conn, "Location"),
  353. "https://127.0.0.1:" HTTPS_PORT "/foo") == 0);
  354. mg_close_connection(conn);
  355. */
  356. /* Test SSL redirect, Host: */
  357. /* TODO(bel):
  358. ASSERT((conn = mg_download("localhost", atoi(HTTP_PORT), 0,
  359. ebuf, sizeof(ebuf), "%s",
  360. "GET /foo HTTP/1.1\r\nHost: a.b:77\n\n")) != NULL);
  361. ASSERT(strcmp(conn->request_info.uri, "302") == 0);
  362. ASSERT(strcmp(mg_get_header(conn, "Location"),
  363. "https://a.b:" HTTPS_PORT "/foo") == 0);
  364. mg_close_connection(conn);
  365. */
  366. mg_stop(ctx);
  367. }
  368. static int alloc_printf(char **buf, size_t size, char *fmt, ...) {
  369. va_list ap;
  370. va_start(ap, fmt);
  371. return alloc_vprintf(buf, size, fmt, ap);
  372. }
  373. static void test_mg_upload(void) {
  374. static const char *boundary = "OOO___MY_BOUNDARY___OOO";
  375. struct mg_context *ctx;
  376. struct mg_connection *conn;
  377. char ebuf[100], buf[20], *file_data, *file2_data, *post_data;
  378. int file_len, file2_len, post_data_len;
  379. ASSERT((ctx = mg_start(&CALLBACKS, NULL, OPTIONS)) != NULL);
  380. /* Upload one file */
  381. ASSERT((file_data = read_file("unit_test.c", &file_len)) != NULL);
  382. post_data = NULL;
  383. post_data_len = alloc_printf(&post_data, 0,
  384. "--%s\r\n"
  385. "Content-Disposition: form-data; "
  386. "name=\"file\"; "
  387. "filename=\"%s\"\r\n\r\n"
  388. "%.*s\r\n"
  389. "--%s--\r\n",
  390. boundary, upload_filename,
  391. file_len, file_data, boundary);
  392. ASSERT(post_data_len > 0);
  393. #if 0 /* TODO (bel): ... */
  394. ASSERT((conn = mg_download("localhost", atoi(HTTPS_PORT), 1,
  395. ebuf, sizeof(ebuf),
  396. "POST /upload?1 HTTP/1.1\r\n"
  397. "Content-Length: %d\r\n"
  398. "Content-Type: multipart/form-data; "
  399. "boundary=%s\r\n\r\n"
  400. "%.*s", post_data_len, boundary,
  401. post_data_len, post_data)) != NULL);
  402. mg_free(file_data), mg_free(post_data);
  403. ASSERT(mg_read(conn, buf, sizeof(buf)) == (int) strlen(upload_ok_message));
  404. ASSERT(memcmp(buf, upload_ok_message, strlen(upload_ok_message)) == 0);
  405. mg_close_connection(conn);
  406. /* Upload two files */
  407. ASSERT((file_data = read_file("include/civetweb.h", &file_len)) != NULL);
  408. ASSERT((file2_data = read_file("README.md", &file2_len)) != NULL);
  409. post_data = NULL;
  410. post_data_len = alloc_printf(&post_data, 0,
  411. /* First file */
  412. "--%s\r\n"
  413. "Content-Disposition: form-data; "
  414. "name=\"file\"; "
  415. "filename=\"%s\"\r\n\r\n"
  416. "%.*s\r\n"
  417. /* Second file */
  418. "--%s\r\n"
  419. "Content-Disposition: form-data; "
  420. "name=\"file\"; "
  421. "filename=\"%s\"\r\n\r\n"
  422. "%.*s\r\n"
  423. /* Final boundary */
  424. "--%s--\r\n",
  425. boundary, upload_filename,
  426. file_len, file_data,
  427. boundary, upload_filename2,
  428. file2_len, file2_data,
  429. boundary);
  430. ASSERT(post_data_len > 0);
  431. ASSERT((conn = mg_download("localhost", atoi(HTTPS_PORT), 1,
  432. ebuf, sizeof(ebuf),
  433. "POST /upload?2 HTTP/1.1\r\n"
  434. "Content-Length: %d\r\n"
  435. "Content-Type: multipart/form-data; "
  436. "boundary=%s\r\n\r\n"
  437. "%.*s", post_data_len, boundary,
  438. post_data_len, post_data)) != NULL);
  439. mg_free(file_data), mg_free(file2_data), mg_free(post_data);
  440. ASSERT(mg_read(conn, buf, sizeof(buf)) == (int) strlen(upload_ok_message));
  441. ASSERT(memcmp(buf, upload_ok_message, strlen(upload_ok_message)) == 0);
  442. mg_close_connection(conn);
  443. #endif
  444. mg_stop(ctx);
  445. }
  446. static void test_base64_encode(void) {
  447. const char *in[] = {"a", "ab", "abc", "abcd", NULL};
  448. const char *out[] = {"YQ==", "YWI=", "YWJj", "YWJjZA=="};
  449. char buf[100];
  450. int i;
  451. for (i = 0; in[i] != NULL; i++) {
  452. base64_encode((unsigned char *) in[i], strlen(in[i]), buf);
  453. ASSERT(!strcmp(buf, out[i]));
  454. }
  455. }
  456. static void test_mg_get_var(void) {
  457. static const char *post[] = {
  458. "a=1&&b=2&d&=&c=3%20&e=",
  459. "q=&st=2012%2F11%2F13+17%3A05&et=&team_id=",
  460. NULL
  461. };
  462. char buf[20];
  463. ASSERT(mg_get_var(post[0], strlen(post[0]), "a", buf, sizeof(buf)) == 1);
  464. ASSERT(buf[0] == '1' && buf[1] == '\0');
  465. ASSERT(mg_get_var(post[0], strlen(post[0]), "b", buf, sizeof(buf)) == 1);
  466. ASSERT(buf[0] == '2' && buf[1] == '\0');
  467. ASSERT(mg_get_var(post[0], strlen(post[0]), "c", buf, sizeof(buf)) == 2);
  468. ASSERT(buf[0] == '3' && buf[1] == ' ' && buf[2] == '\0');
  469. ASSERT(mg_get_var(post[0], strlen(post[0]), "e", buf, sizeof(buf)) == 0);
  470. ASSERT(buf[0] == '\0');
  471. ASSERT(mg_get_var(post[0], strlen(post[0]), "d", buf, sizeof(buf)) == -1);
  472. ASSERT(mg_get_var(post[0], strlen(post[0]), "c", buf, 2) == -2);
  473. ASSERT(mg_get_var(post[0], strlen(post[0]), "x", NULL, 10) == -2);
  474. ASSERT(mg_get_var(post[0], strlen(post[0]), "x", buf, 0) == -2);
  475. ASSERT(mg_get_var(post[1], strlen(post[1]), "st", buf, 16) == -2);
  476. ASSERT(mg_get_var(post[1], strlen(post[1]), "st", buf, 17) == 16);
  477. }
  478. static void test_set_throttle(void) {
  479. ASSERT(set_throttle(NULL, 0x0a000001, "/") == 0);
  480. ASSERT(set_throttle("10.0.0.0/8=20", 0x0a000001, "/") == 20);
  481. ASSERT(set_throttle("10.0.0.0/8=0.5k", 0x0a000001, "/") == 512);
  482. ASSERT(set_throttle("10.0.0.0/8=17m", 0x0a000001, "/") == 1048576 * 17);
  483. ASSERT(set_throttle("10.0.0.0/8=1x", 0x0a000001, "/") == 0);
  484. ASSERT(set_throttle("10.0.0.0/8=5,0.0.0.0/0=10", 0x0a000001, "/") == 10);
  485. ASSERT(set_throttle("10.0.0.0/8=5,/foo/**=7", 0x0a000001, "/index") == 5);
  486. ASSERT(set_throttle("10.0.0.0/8=5,/foo/**=7", 0x0a000001, "/foo/x") == 7);
  487. ASSERT(set_throttle("10.0.0.0/8=5,/foo/**=7", 0x0b000001, "/foxo/x") == 0);
  488. ASSERT(set_throttle("10.0.0.0/8=5,*=1", 0x0b000001, "/foxo/x") == 1);
  489. }
  490. static void test_next_option(void) {
  491. const char *p, *list = "x/8,/y**=1;2k,z";
  492. struct vec a, b;
  493. int i;
  494. ASSERT(next_option(NULL, &a, &b) == NULL);
  495. for (i = 0, p = list; (p = next_option(p, &a, &b)) != NULL; i++) {
  496. ASSERT(i != 0 || (a.ptr == list && a.len == 3 && b.len == 0));
  497. ASSERT(i != 1 || (a.ptr == list + 4 && a.len == 4 && b.ptr == list + 9 && b.len == 4));
  498. ASSERT(i != 2 || (a.ptr == list + 14 && a.len == 1 && b.len == 0));
  499. }
  500. }
  501. #if defined(USE_LUA)
  502. static void check_lua_expr(lua_State *L, const char *expr, const char *value) {
  503. const char *v, *var_name = "myVar";
  504. char buf[100];
  505. snprintf(buf, sizeof(buf), "%s = %s", var_name, expr);
  506. (void) luaL_dostring(L, buf);
  507. lua_getglobal(L, var_name);
  508. v = lua_tostring(L, -1);
  509. ASSERT((value == NULL && v == NULL) || (value != NULL && v != NULL && !strcmp(value, v)));
  510. }
  511. static void test_lua(void) {
  512. static struct mg_connection conn;
  513. static struct mg_context ctx;
  514. char http_request[] = "POST /foo/bar HTTP/1.1\r\n"
  515. "Content-Length: 12\r\n"
  516. "Connection: close\r\n\r\nhello world!";
  517. lua_State *L = luaL_newstate();
  518. conn.ctx = &ctx;
  519. conn.buf = http_request;
  520. conn.buf_size = conn.data_len = strlen(http_request);
  521. conn.request_len = parse_http_message(conn.buf, conn.data_len, &conn.request_info);
  522. conn.content_len = conn.data_len - conn.request_len;
  523. prepare_lua_environment(&conn, L, "unit_test", LUA_ENV_TYPE_PLAIN_LUA_PAGE);
  524. ASSERT(lua_gettop(L) == 4);
  525. check_lua_expr(L, "'hi'", "hi");
  526. check_lua_expr(L, "mg.request_info.request_method", "POST");
  527. check_lua_expr(L, "mg.request_info.uri", "/foo/bar");
  528. check_lua_expr(L, "mg.request_info.num_headers", "2");
  529. check_lua_expr(L, "mg.request_info.remote_ip", "0");
  530. check_lua_expr(L, "mg.request_info.http_headers['Content-Length']", "12");
  531. check_lua_expr(L, "mg.request_info.http_headers['Connection']", "close");
  532. (void) luaL_dostring(L, "post = mg.read()");
  533. check_lua_expr(L, "# post", "12");
  534. check_lua_expr(L, "post", "hello world!");
  535. lua_close(L);
  536. }
  537. #endif
  538. static void test_mg_stat(void) {
  539. static struct mg_context ctx;
  540. struct file file = STRUCT_FILE_INITIALIZER;
  541. ASSERT(!mg_stat(fc(&ctx), " does not exist ", &file));
  542. }
  543. static void test_skip_quoted(void) {
  544. char x[] = "a=1, b=2 c='hi \' there'", *s = x, *p;
  545. p = skip_quoted(&s, ", ", ", ", 0);
  546. ASSERT(p != NULL && !strcmp(p, "a=1"));
  547. p = skip_quoted(&s, ", ", ", ", 0);
  548. ASSERT(p != NULL && !strcmp(p, "b=2"));
  549. /* TODO(lsm): fix this */
  550. #if 0
  551. p = skip_quoted(&s, "'", ", ", '\\');
  552. p = skip_quoted(&s, "'", ", ", '\\');
  553. printf("[%s]\n", p);
  554. ASSERT(p != NULL && !strcmp(p, "hi ' there"));
  555. #endif
  556. }
  557. static void test_alloc_vprintf(void) {
  558. char buf[MG_BUF_LEN], *p = buf;
  559. ASSERT(alloc_printf(&p, sizeof(buf), "%s", "hi") == 2);
  560. ASSERT(p == buf);
  561. ASSERT(alloc_printf(&p, sizeof(buf), "%s", "") == 0);
  562. ASSERT(alloc_printf(&p, sizeof(buf), "") == 0);
  563. /* Pass small buffer, make sure alloc_printf allocates */
  564. ASSERT(alloc_printf(&p, 1, "%s", "hello") == 5);
  565. ASSERT(p != buf);
  566. mg_free(p);
  567. }
  568. static void test_request_replies(void) {
  569. char ebuf[100];
  570. int i;
  571. struct mg_connection *conn;
  572. struct mg_context *ctx;
  573. static struct { const char *request, *reply_regex; } tests[] = {
  574. {
  575. "GET hello.txt HTTP/1.0\r\nRange: bytes=3-5\r\n\r\n",
  576. "^HTTP/1.1 206 Partial Content"
  577. },
  578. {NULL, NULL},
  579. };
  580. ASSERT((ctx = mg_start(&CALLBACKS, NULL, OPTIONS)) != NULL);
  581. for (i = 0; tests[i].request != NULL; i++) {
  582. ASSERT((conn = mg_download("localhost", atoi(HTTP_PORT), 0, ebuf, sizeof(ebuf), "%s",
  583. tests[i].request)) != NULL);
  584. mg_close_connection(conn);
  585. }
  586. mg_stop(ctx);
  587. /* TODO(bel):
  588. ASSERT((ctx = mg_start(&CALLBACKS, NULL, OPTIONS)) != NULL);
  589. for (i = 0; tests[i].request != NULL; i++) {
  590. ASSERT((conn = mg_download("localhost", atoi(HTTPS_PORT), 1, ebuf, sizeof(ebuf), "%s",
  591. tests[i].request)) != NULL);
  592. mg_close_connection(conn);
  593. }
  594. mg_stop(ctx);
  595. */
  596. }
  597. static int api_callback(struct mg_connection *conn) {
  598. struct mg_request_info *ri = mg_get_request_info(conn);
  599. char post_data[100] = "";
  600. ASSERT(ri->user_data == (void *) 123);
  601. ASSERT(ri->num_headers == 2);
  602. ASSERT(strcmp(mg_get_header(conn, "host"), "blah.com") == 0);
  603. ASSERT(mg_read(conn, post_data, sizeof(post_data)) == 3);
  604. ASSERT(memcmp(post_data, "b=1", 3) == 0);
  605. ASSERT(ri->query_string != NULL);
  606. ASSERT(ri->remote_ip > 0);
  607. ASSERT(ri->remote_port > 0);
  608. ASSERT(strcmp(ri->http_version, "1.0") == 0);
  609. mg_printf(conn, "HTTP/1.0 200 OK\r\n\r\n");
  610. return 1;
  611. }
  612. static void test_api_calls(void) {
  613. char ebuf[100];
  614. struct mg_callbacks callbacks;
  615. struct mg_connection *conn;
  616. struct mg_context *ctx;
  617. static const char *request = "POST /?a=%20&b=&c=xx HTTP/1.0\r\n"
  618. "Host: blah.com\n" /* More spaces before */
  619. "content-length: 3\r\n" /* Lower case header name */
  620. "\r\nb=123456"; /* Content size > content-length, test for mg_read() */
  621. memset(&callbacks, 0, sizeof(callbacks));
  622. callbacks.begin_request = api_callback;
  623. ASSERT((ctx = mg_start(&callbacks, (void *) 123, OPTIONS)) != NULL);
  624. ASSERT((conn = mg_download("localhost", atoi(HTTP_PORT), 0,
  625. ebuf, sizeof(ebuf), "%s", request)) != NULL);
  626. mg_close_connection(conn);
  627. mg_stop(ctx);
  628. }
  629. static void test_url_decode(void) {
  630. char buf[100];
  631. ASSERT(mg_url_decode("foo", 3, buf, 3, 0) == -1); /* No space for \0 */
  632. ASSERT(mg_url_decode("foo", 3, buf, 4, 0) == 3);
  633. ASSERT(strcmp(buf, "foo") == 0);
  634. ASSERT(mg_url_decode("a+", 2, buf, sizeof(buf), 0) == 2);
  635. ASSERT(strcmp(buf, "a+") == 0);
  636. ASSERT(mg_url_decode("a+", 2, buf, sizeof(buf), 1) == 2);
  637. ASSERT(strcmp(buf, "a ") == 0);
  638. ASSERT(mg_url_decode("%61", 1, buf, sizeof(buf), 1) == 1);
  639. ASSERT(strcmp(buf, "%") == 0);
  640. ASSERT(mg_url_decode("%61", 2, buf, sizeof(buf), 1) == 2);
  641. ASSERT(strcmp(buf, "%6") == 0);
  642. ASSERT(mg_url_decode("%61", 3, buf, sizeof(buf), 1) == 1);
  643. ASSERT(strcmp(buf, "a") == 0);
  644. }
  645. static void test_mg_strcasestr(void) {
  646. static const char *big1 = "abcdef";
  647. ASSERT(mg_strcasestr("Y", "X") == NULL);
  648. ASSERT(mg_strcasestr("Y", "y") != NULL);
  649. ASSERT(mg_strcasestr(big1, "X") == NULL);
  650. ASSERT(mg_strcasestr(big1, "CD") == big1 + 2);
  651. ASSERT(mg_strcasestr("aa", "AAB") == NULL);
  652. }
  653. static void test_mg_get_cookie(void) {
  654. char buf[20];
  655. ASSERT(mg_get_cookie("", "foo", NULL, sizeof(buf)) == -2);
  656. ASSERT(mg_get_cookie("", "foo", buf, 0) == -2);
  657. ASSERT(mg_get_cookie("", "foo", buf, sizeof(buf)) == -1);
  658. ASSERT(mg_get_cookie("", NULL, buf, sizeof(buf)) == -1);
  659. ASSERT(mg_get_cookie("a=1; b=2; c; d", "a", buf, sizeof(buf)) == 1);
  660. ASSERT(strcmp(buf, "1") == 0);
  661. ASSERT(mg_get_cookie("a=1; b=2; c; d", "b", buf, sizeof(buf)) == 1);
  662. ASSERT(strcmp(buf, "2") == 0);
  663. ASSERT(mg_get_cookie("a=1; b=123", "b", buf, sizeof(buf)) == 3);
  664. ASSERT(strcmp(buf, "123") == 0);
  665. ASSERT(mg_get_cookie("a=1; b=2; c; d", "c", buf, sizeof(buf)) == -1);
  666. }
  667. static void test_strtoll(void) {
  668. ASSERT(strtoll("0", NULL, 10) == 0);
  669. ASSERT(strtoll("123", NULL, 10) == 123);
  670. ASSERT(strtoll("-34", NULL, 10) == -34);
  671. ASSERT(strtoll("3566626116", NULL, 10) == 3566626116);
  672. }
  673. static void test_parse_port_string(void) {
  674. static const char *valid[] = {
  675. "0", "1", "1s", "1r", "1.2.3.4:1", "1.2.3.4:1s", "1.2.3.4:1r",
  676. #if defined(USE_IPV6)
  677. "[::1]:123", "[3ffe:2a00:100:7031::1]:900",
  678. #endif
  679. NULL
  680. };
  681. static const char *invalid[] = {
  682. "99999", "1k", "1.2.3", "1.2.3.4:", "1.2.3.4:2p",
  683. NULL
  684. };
  685. struct socket so;
  686. struct vec vec;
  687. int i;
  688. for (i = 0; valid[i] != NULL; i++) {
  689. vec.ptr = valid[i];
  690. vec.len = strlen(vec.ptr);
  691. ASSERT(parse_port_string(&vec, &so) != 0);
  692. }
  693. for (i = 0; invalid[i] != NULL; i++) {
  694. vec.ptr = invalid[i];
  695. vec.len = strlen(vec.ptr);
  696. ASSERT(parse_port_string(&vec, &so) == 0);
  697. }
  698. }
  699. static void test_md5(void) {
  700. md5_state_t md5_state;
  701. unsigned char md5_val[16+1];
  702. char md5_str[32+1];
  703. const char *test_str = "The quick brown fox jumps over the lazy dog";
  704. md5_val[16]=0;
  705. md5_init(&md5_state);
  706. md5_finish(&md5_state, md5_val);
  707. ASSERT(strcmp(md5_val, "\xd4\x1d\x8c\xd9\x8f\x00\xb2\x04\xe9\x80\x09\x98\xec\xf8\x42\x7e")==0);
  708. sprintf(md5_str, "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
  709. md5_val[0], md5_val[1], md5_val[2], md5_val[3],
  710. md5_val[4], md5_val[5], md5_val[6], md5_val[7],
  711. md5_val[8], md5_val[9], md5_val[10], md5_val[11],
  712. md5_val[12], md5_val[13], md5_val[14], md5_val[15]);
  713. ASSERT(strcmp(md5_str, "d41d8cd98f00b204e9800998ecf8427e")==0);
  714. mg_md5(md5_str, "", NULL);
  715. ASSERT(strcmp(md5_str, "d41d8cd98f00b204e9800998ecf8427e")==0);
  716. md5_init(&md5_state);
  717. md5_append(&md5_state, test_str, strlen(test_str));
  718. md5_finish(&md5_state, md5_val);
  719. sprintf(md5_str, "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
  720. md5_val[0], md5_val[1], md5_val[2], md5_val[3],
  721. md5_val[4], md5_val[5], md5_val[6], md5_val[7],
  722. md5_val[8], md5_val[9], md5_val[10], md5_val[11],
  723. md5_val[12], md5_val[13], md5_val[14], md5_val[15]);
  724. ASSERT(strcmp(md5_str, "9e107d9d372bb6826bd81d3542a419d6")==0);
  725. mg_md5(md5_str, test_str, NULL);
  726. ASSERT(strcmp(md5_str, "9e107d9d372bb6826bd81d3542a419d6")==0);
  727. mg_md5(md5_str, "The", " ", "quick brown fox", "", " jumps ", "over the lazy dog", "", "", NULL);
  728. ASSERT(strcmp(md5_str, "9e107d9d372bb6826bd81d3542a419d6")==0);
  729. mg_md5(md5_str, "civetweb", NULL);
  730. ASSERT(strcmp(md5_str, "95c098bd85b619b24a83d9cea5e8ba54")==0);
  731. }
  732. int __cdecl main(void) {
  733. char buffer[512];
  734. FILE * f;
  735. struct mg_context *ctx;
  736. /* print headline */
  737. printf("Civetweb %s unit test\n", mg_version());
  738. #if defined(_WIN32)
  739. GetCurrentDirectoryA(sizeof(buffer), buffer);
  740. #else
  741. getcwd(buffer, sizeof(buffer));
  742. #endif
  743. printf("Test directory is \"%s\"\n", buffer); /* should be the "test" directory */
  744. f = fopen("hello.txt", "r");
  745. if (f) {
  746. fclose(f);
  747. } else {
  748. printf("Error: Test directory does not contain hello.txt\n", buffer);
  749. }
  750. f = fopen("unit_test.c", "r");
  751. if (f) {
  752. fclose(f);
  753. } else {
  754. printf("Error: Test directory does not contain unit_test.c\n", buffer);
  755. }
  756. /* test local functions */
  757. test_parse_port_string();
  758. test_mg_strcasestr();
  759. test_alloc_vprintf();
  760. test_base64_encode();
  761. test_match_prefix();
  762. test_remove_double_dots();
  763. test_should_keep_alive();
  764. test_parse_http_message();
  765. test_mg_get_var();
  766. test_set_throttle();
  767. test_next_option();
  768. test_mg_stat();
  769. test_skip_quoted();
  770. test_url_decode();
  771. test_mg_get_cookie();
  772. test_strtoll();
  773. test_md5();
  774. /* start stop server */
  775. ctx = mg_start(NULL, NULL, OPTIONS);
  776. ASSERT(ctx != NULL);
  777. mg_sleep(1000);
  778. mg_stop(ctx);
  779. /* tests with network access */
  780. test_mg_download(0);
  781. #ifndef NO_SSL
  782. test_mg_download(1);
  783. #endif
  784. test_mg_upload();
  785. test_request_replies();
  786. test_api_calls();
  787. #if defined(USE_LUA)
  788. test_lua();
  789. #endif
  790. printf("TOTAL TESTS: %d, FAILED: %d\n", s_total_tests, s_failed_tests);
  791. return s_failed_tests == 0 ? EXIT_SUCCESS : EXIT_FAILURE;
  792. }