unit_test.c 44 KB

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