unit_test.c 41 KB

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