unit_test.c 46 KB

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