unit_test.c 44 KB

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