unit_test.c 44 KB

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