unit_test.c 47 KB

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