unit_test.c 47 KB

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