embedded_c.c 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163
  1. /*
  2. * Copyright (c) 2013-2017 the CivetWeb developers
  3. * Copyright (c) 2013 No Face Press, LLC
  4. * License http://opensource.org/licenses/mit-license.php MIT License
  5. */
  6. #ifdef NO_SSL
  7. #define TEST_WITHOUT_SSL
  8. #endif
  9. /* Simple example program on how to use CivetWeb embedded into a C program. */
  10. #ifdef _WIN32
  11. #include <windows.h>
  12. #else
  13. #include <unistd.h>
  14. #endif
  15. #include <stdlib.h>
  16. #include <string.h>
  17. #include <time.h>
  18. #include "civetweb.h"
  19. #define DOCUMENT_ROOT "."
  20. #ifdef TEST_WITHOUT_SSL
  21. #ifdef USE_IPV6
  22. #define PORT "[::]:8888,8884"
  23. #else
  24. #define PORT "8888,8884"
  25. #endif
  26. #else
  27. #ifdef USE_IPV6
  28. #define PORT "[::]:8888r,[::]:8843s,8884"
  29. #else
  30. #define PORT "8888r,8843s,8884"
  31. #endif
  32. #endif
  33. #define EXAMPLE_URI "/example"
  34. #define EXIT_URI "/exit"
  35. int exitNow = 0;
  36. int
  37. ExampleHandler(struct mg_connection *conn, void *cbdata)
  38. {
  39. mg_printf(conn,
  40. "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nConnection: "
  41. "close\r\n\r\n");
  42. mg_printf(conn, "<html><body>");
  43. mg_printf(conn, "<h2>This is an example text from a C handler</h2>");
  44. mg_printf(
  45. conn,
  46. "<p>To see a page from the A handler <a href=\"A\">click A</a></p>");
  47. mg_printf(conn,
  48. "<p>To see a page from the A handler <a href=\"A/A\">click "
  49. "A/A</a></p>");
  50. mg_printf(conn,
  51. "<p>To see a page from the A/B handler <a "
  52. "href=\"A/B\">click A/B</a></p>");
  53. mg_printf(conn,
  54. "<p>To see a page from the B handler (0) <a "
  55. "href=\"B\">click B</a></p>");
  56. mg_printf(conn,
  57. "<p>To see a page from the B handler (1) <a "
  58. "href=\"B/A\">click B/A</a></p>");
  59. mg_printf(conn,
  60. "<p>To see a page from the B handler (2) <a "
  61. "href=\"B/B\">click B/B</a></p>");
  62. mg_printf(conn,
  63. "<p>To see a page from the *.foo handler <a "
  64. "href=\"xy.foo\">click xy.foo</a></p>");
  65. mg_printf(conn,
  66. "<p>To see a page from the close handler <a "
  67. "href=\"close\">click close</a></p>");
  68. mg_printf(conn,
  69. "<p>To see a page from the FileHandler handler <a "
  70. "href=\"form\">click form</a> (the starting point of the "
  71. "<b>form</b> test)</p>");
  72. mg_printf(conn,
  73. "<p>To see a page from the CookieHandler handler <a "
  74. "href=\"cookie\">click cookie</a></p>");
  75. mg_printf(conn,
  76. "<p>To see a page from the PostResponser handler <a "
  77. "href=\"postresponse\">click post response</a></p>");
  78. mg_printf(conn,
  79. "<p>To see an example for parsing files on the fly <a "
  80. "href=\"on_the_fly_form\">click form</a> (form for "
  81. "uploading files)</p>");
  82. #ifdef USE_WEBSOCKET
  83. mg_printf(conn,
  84. "<p>To test the websocket handler <a href=\"/websocket\">click "
  85. "websocket</a></p>");
  86. #endif
  87. mg_printf(conn,
  88. "<p>To test the authentication handler <a href=\"/auth\">click "
  89. "auth</a></p>");
  90. mg_printf(conn, "<p>To exit <a href=\"%s\">click exit</a></p>", EXIT_URI);
  91. mg_printf(conn, "</body></html>\n");
  92. return 1;
  93. }
  94. int
  95. ExitHandler(struct mg_connection *conn, void *cbdata)
  96. {
  97. mg_printf(conn,
  98. "HTTP/1.1 200 OK\r\nContent-Type: "
  99. "text/plain\r\nConnection: close\r\n\r\n");
  100. mg_printf(conn, "Server will shut down.\n");
  101. mg_printf(conn, "Bye!\n");
  102. exitNow = 1;
  103. return 1;
  104. }
  105. int
  106. AHandler(struct mg_connection *conn, void *cbdata)
  107. {
  108. mg_printf(conn,
  109. "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nConnection: "
  110. "close\r\n\r\n");
  111. mg_printf(conn, "<html><body>");
  112. mg_printf(conn, "<h2>This is the A handler!!!</h2>");
  113. mg_printf(conn, "</body></html>\n");
  114. return 1;
  115. }
  116. int
  117. ABHandler(struct mg_connection *conn, void *cbdata)
  118. {
  119. mg_printf(conn,
  120. "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nConnection: "
  121. "close\r\n\r\n");
  122. mg_printf(conn, "<html><body>");
  123. mg_printf(conn, "<h2>This is the AB handler!!!</h2>");
  124. mg_printf(conn, "</body></html>\n");
  125. return 1;
  126. }
  127. int
  128. BXHandler(struct mg_connection *conn, void *cbdata)
  129. {
  130. /* Handler may access the request info using mg_get_request_info */
  131. const struct mg_request_info *req_info = mg_get_request_info(conn);
  132. mg_printf(conn,
  133. "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nConnection: "
  134. "close\r\n\r\n");
  135. mg_printf(conn, "<html><body>");
  136. mg_printf(conn,
  137. "<h2>This is the BX handler with argument %s.</h2>",
  138. cbdata);
  139. mg_printf(conn, "<p>The actual uri is %s</p>", req_info->local_uri);
  140. mg_printf(conn, "</body></html>\n");
  141. return 1;
  142. }
  143. int
  144. FooHandler(struct mg_connection *conn, void *cbdata)
  145. {
  146. /* Handler may access the request info using mg_get_request_info */
  147. const struct mg_request_info *req_info = mg_get_request_info(conn);
  148. mg_printf(conn,
  149. "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nConnection: "
  150. "close\r\n\r\n");
  151. mg_printf(conn, "<html><body>");
  152. mg_printf(conn, "<h2>This is the Foo handler!!!</h2>");
  153. mg_printf(conn,
  154. "<p>The request was:<br><pre>%s %s HTTP/%s</pre></p>",
  155. req_info->request_method,
  156. req_info->local_uri,
  157. req_info->http_version);
  158. mg_printf(conn, "</body></html>\n");
  159. return 1;
  160. }
  161. int
  162. CloseHandler(struct mg_connection *conn, void *cbdata)
  163. {
  164. /* Handler may access the request info using mg_get_request_info */
  165. const struct mg_request_info *req_info = mg_get_request_info(conn);
  166. mg_printf(conn,
  167. "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nConnection: "
  168. "close\r\n\r\n");
  169. mg_printf(conn, "<html><body>");
  170. mg_printf(conn,
  171. "<h2>This handler will close the connection in a second</h2>");
  172. #ifdef _WIN32
  173. Sleep(1000);
  174. #else
  175. sleep(1);
  176. #endif
  177. mg_printf(conn, "bye");
  178. printf("CloseHandler: close connection\n");
  179. mg_close_connection(conn);
  180. printf("CloseHandler: wait 10 sec\n");
  181. #ifdef _WIN32
  182. Sleep(10000);
  183. #else
  184. sleep(10);
  185. #endif
  186. printf("CloseHandler: return from function\n");
  187. return 1;
  188. }
  189. #if !defined(NO_FILESYSTEMS)
  190. int
  191. FileHandler(struct mg_connection *conn, void *cbdata)
  192. {
  193. /* In this handler, we ignore the req_info and send the file "fileName". */
  194. const char *fileName = (const char *)cbdata;
  195. mg_send_file(conn, fileName);
  196. return 1;
  197. }
  198. #endif /* NO_FILESYSTEMS */
  199. #define MD5_STATIC static
  200. #include "../src/md5.inl"
  201. /* Stringify binary data. Output buffer must be twice as big as input,
  202. * because each byte takes 2 bytes in string representation */
  203. static void
  204. bin2str(char *to, const unsigned char *p, size_t len)
  205. {
  206. static const char *hex = "0123456789abcdef";
  207. for (; len--; p++) {
  208. *to++ = hex[p[0] >> 4];
  209. *to++ = hex[p[0] & 0x0f];
  210. }
  211. *to = '\0';
  212. }
  213. int
  214. field_found(const char *key,
  215. const char *filename,
  216. char *path,
  217. size_t pathlen,
  218. void *user_data)
  219. {
  220. struct mg_connection *conn = (struct mg_connection *)user_data;
  221. mg_printf(conn, "\r\n\r\n%s:\r\n", key);
  222. if (filename && *filename) {
  223. #ifdef _WIN32
  224. _snprintf(path, pathlen, "D:\\tmp\\%s", filename);
  225. #else
  226. snprintf(path, pathlen, "/tmp/%s", filename);
  227. #endif
  228. return MG_FORM_FIELD_STORAGE_GET;
  229. }
  230. return MG_FORM_FIELD_STORAGE_GET;
  231. }
  232. int
  233. field_get(const char *key, const char *value, size_t valuelen, void *user_data)
  234. {
  235. struct mg_connection *conn = (struct mg_connection *)user_data;
  236. if ((key != NULL) && (key[0] == '\0')) {
  237. /* Incorrect form data detected */
  238. return MG_FORM_FIELD_HANDLE_ABORT;
  239. }
  240. if ((valuelen > 0) && (value == NULL)) {
  241. /* Unreachable, since this call will not be generated by civetweb. */
  242. return MG_FORM_FIELD_HANDLE_ABORT;
  243. }
  244. if (key) {
  245. mg_printf(conn, "key = %s\n", key);
  246. }
  247. mg_printf(conn, "valuelen = %u\n", valuelen);
  248. if (valuelen > 0) {
  249. /* mg_write(conn, value, valuelen); */
  250. md5_byte_t hash[16];
  251. md5_state_t ctx;
  252. char outputbuf[33];
  253. md5_init(&ctx);
  254. md5_append(&ctx, (const md5_byte_t *)value, valuelen);
  255. md5_finish(&ctx, hash);
  256. bin2str(outputbuf, hash, sizeof(hash));
  257. mg_printf(conn, "value md5 hash = %s\n", outputbuf);
  258. }
  259. #if 0 /* for debugging */
  260. if (!strcmp(key, "File")) {
  261. FILE *f = fopen("test.txt", "wb");
  262. if (f) {
  263. fwrite(value, 1, valuelen, f);
  264. fclose(f);
  265. }
  266. }
  267. #endif
  268. return 0;
  269. }
  270. int
  271. field_stored(const char *path, long long file_size, void *user_data)
  272. {
  273. struct mg_connection *conn = (struct mg_connection *)user_data;
  274. mg_printf(conn,
  275. "stored as %s (%lu bytes)\r\n\r\n",
  276. path,
  277. (unsigned long)file_size);
  278. return 0;
  279. }
  280. int
  281. FormHandler(struct mg_connection *conn, void *cbdata)
  282. {
  283. /* Handler may access the request info using mg_get_request_info */
  284. const struct mg_request_info *req_info = mg_get_request_info(conn);
  285. int ret;
  286. struct mg_form_data_handler fdh = {field_found, field_get, field_stored, 0};
  287. /* It would be possible to check the request info here before calling
  288. * mg_handle_form_request. */
  289. (void)req_info;
  290. mg_printf(conn,
  291. "HTTP/1.1 200 OK\r\nContent-Type: "
  292. "text/plain\r\nConnection: close\r\n\r\n");
  293. fdh.user_data = (void *)conn;
  294. /* Call the form handler */
  295. mg_printf(conn, "Form data:");
  296. ret = mg_handle_form_request(conn, &fdh);
  297. mg_printf(conn, "\r\n%i fields found", ret);
  298. return 1;
  299. }
  300. int
  301. FileUploadForm(struct mg_connection *conn, void *cbdata)
  302. {
  303. mg_printf(conn,
  304. "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nConnection: "
  305. "close\r\n\r\n");
  306. mg_printf(conn, "<!DOCTYPE html>\n");
  307. mg_printf(conn, "<html>\n<head>\n");
  308. mg_printf(conn, "<meta charset=\"UTF-8\">\n");
  309. mg_printf(conn, "<title>File upload</title>\n");
  310. mg_printf(conn, "</head>\n<body>\n");
  311. mg_printf(conn,
  312. "<form action=\"%s\" method=\"POST\" "
  313. "enctype=\"multipart/form-data\">\n",
  314. (const char *)cbdata);
  315. mg_printf(conn, "<input type=\"file\" name=\"filesin\" multiple>\n");
  316. mg_printf(conn, "<input type=\"submit\" value=\"Submit\">\n");
  317. mg_printf(conn, "</form>\n</body>\n</html>\n");
  318. return 1;
  319. }
  320. struct tfile_checksum {
  321. char name[128];
  322. unsigned long long length;
  323. md5_state_t chksum;
  324. };
  325. #define MAX_FILES (10)
  326. struct tfiles_checksums {
  327. int index;
  328. struct tfile_checksum file[MAX_FILES];
  329. };
  330. int
  331. field_disp_read_on_the_fly(const char *key,
  332. const char *filename,
  333. char *path,
  334. size_t pathlen,
  335. void *user_data)
  336. {
  337. struct tfiles_checksums *context = (struct tfiles_checksums *)user_data;
  338. (void)key;
  339. (void)path;
  340. (void)pathlen;
  341. if (context->index < MAX_FILES) {
  342. context->index++;
  343. strncpy(context->file[context->index - 1].name, filename, 128);
  344. context->file[context->index - 1].name[127] = 0;
  345. context->file[context->index - 1].length = 0;
  346. md5_init(&(context->file[context->index - 1].chksum));
  347. return MG_FORM_FIELD_STORAGE_GET;
  348. }
  349. return MG_FORM_FIELD_STORAGE_ABORT;
  350. }
  351. int
  352. field_get_checksum(const char *key,
  353. const char *value,
  354. size_t valuelen,
  355. void *user_data)
  356. {
  357. struct tfiles_checksums *context = (struct tfiles_checksums *)user_data;
  358. (void)key;
  359. context->file[context->index - 1].length += valuelen;
  360. md5_append(&(context->file[context->index - 1].chksum),
  361. (const md5_byte_t *)value,
  362. valuelen);
  363. return 0;
  364. }
  365. int
  366. CheckSumHandler(struct mg_connection *conn, void *cbdata)
  367. {
  368. /* Handler may access the request info using mg_get_request_info */
  369. const struct mg_request_info *req_info = mg_get_request_info(conn);
  370. int i, j, ret;
  371. struct tfiles_checksums chksums;
  372. md5_byte_t digest[16];
  373. struct mg_form_data_handler fdh = {field_disp_read_on_the_fly,
  374. field_get_checksum,
  375. 0,
  376. (void *)&chksums};
  377. /* It would be possible to check the request info here before calling
  378. * mg_handle_form_request. */
  379. (void)req_info;
  380. memset(&chksums, 0, sizeof(chksums));
  381. mg_printf(conn,
  382. "HTTP/1.1 200 OK\r\n"
  383. "Content-Type: text/plain\r\n"
  384. "Connection: close\r\n\r\n");
  385. /* Call the form handler */
  386. mg_printf(conn, "File checksums:");
  387. ret = mg_handle_form_request(conn, &fdh);
  388. for (i = 0; i < chksums.index; i++) {
  389. md5_finish(&(chksums.file[i].chksum), digest);
  390. /* Visual Studio 2010+ support llu */
  391. mg_printf(conn,
  392. "\r\n%s %llu ",
  393. chksums.file[i].name,
  394. chksums.file[i].length);
  395. for (j = 0; j < 16; j++) {
  396. mg_printf(conn, "%02x", (unsigned int)digest[j]);
  397. }
  398. }
  399. mg_printf(conn, "\r\n%i files\r\n", ret);
  400. return 1;
  401. }
  402. int
  403. CookieHandler(struct mg_connection *conn, void *cbdata)
  404. {
  405. /* Handler may access the request info using mg_get_request_info */
  406. const struct mg_request_info *req_info = mg_get_request_info(conn);
  407. const char *cookie = mg_get_header(conn, "Cookie");
  408. char first_str[64], count_str[64];
  409. int count;
  410. (void)mg_get_cookie(cookie, "first", first_str, sizeof(first_str));
  411. (void)mg_get_cookie(cookie, "count", count_str, sizeof(count_str));
  412. mg_printf(conn, "HTTP/1.1 200 OK\r\nConnection: close\r\n");
  413. if (first_str[0] == 0) {
  414. time_t t = time(0);
  415. struct tm *ptm = localtime(&t);
  416. mg_printf(conn,
  417. "Set-Cookie: first=%04i-%02i-%02iT%02i:%02i:%02i\r\n",
  418. ptm->tm_year + 1900,
  419. ptm->tm_mon + 1,
  420. ptm->tm_mday,
  421. ptm->tm_hour,
  422. ptm->tm_min,
  423. ptm->tm_sec);
  424. }
  425. count = (count_str[0] == 0) ? 0 : atoi(count_str);
  426. mg_printf(conn, "Set-Cookie: count=%i\r\n", count + 1);
  427. mg_printf(conn, "Content-Type: text/html\r\n\r\n");
  428. mg_printf(conn, "<html><body>");
  429. mg_printf(conn, "<h2>This is the CookieHandler.</h2>");
  430. mg_printf(conn, "<p>The actual uri is %s</p>", req_info->local_uri);
  431. if (first_str[0] == 0) {
  432. mg_printf(conn, "<p>This is the first time, you opened this page</p>");
  433. } else {
  434. mg_printf(conn, "<p>You opened this page %i times before.</p>", count);
  435. mg_printf(conn, "<p>You first opened this page on %s.</p>", first_str);
  436. }
  437. mg_printf(conn, "</body></html>\n");
  438. return 1;
  439. }
  440. int
  441. PostResponser(struct mg_connection *conn, void *cbdata)
  442. {
  443. long long r_total = 0;
  444. int r, s;
  445. char buf[2048];
  446. const struct mg_request_info *ri = mg_get_request_info(conn);
  447. if (0 != strcmp(ri->request_method, "POST")) {
  448. /* Not a POST request */
  449. char buf[1024];
  450. int ret = mg_get_request_link(conn, buf, sizeof(buf));
  451. mg_printf(conn,
  452. "HTTP/1.1 405 Method Not Allowed\r\nConnection: close\r\n");
  453. mg_printf(conn, "Content-Type: text/plain\r\n\r\n");
  454. mg_printf(conn,
  455. "%s method not allowed in the POST handler\n",
  456. ri->request_method);
  457. if (ret >= 0) {
  458. mg_printf(conn,
  459. "use a web tool to send a POST request to %s\n",
  460. buf);
  461. }
  462. return 1;
  463. }
  464. if (ri->content_length >= 0) {
  465. /* We know the content length in advance */
  466. } else {
  467. /* We must read until we find the end (chunked encoding
  468. * or connection close), indicated my mg_read returning 0 */
  469. }
  470. mg_printf(conn,
  471. "HTTP/1.1 200 OK\r\nConnection: "
  472. "close\r\nTransfer-Encoding: chunked\r\n");
  473. mg_printf(conn, "Content-Type: text/plain\r\n\r\n");
  474. r = mg_read(conn, buf, sizeof(buf));
  475. while (r > 0) {
  476. r_total += r;
  477. s = mg_send_chunk(conn, buf, r);
  478. if (r != s) {
  479. /* Send error */
  480. break;
  481. }
  482. r = mg_read(conn, buf, sizeof(buf));
  483. }
  484. mg_printf(conn, "0\r\n");
  485. return 1;
  486. }
  487. #if !defined(NO_FILESYSTEMS)
  488. int
  489. AuthStartHandler(struct mg_connection *conn, void *cbdata)
  490. {
  491. static unsigned long long firstload = 0;
  492. const char *passfile = "password_example_file.txt";
  493. const char *realm = "password_example";
  494. const char *user = "user";
  495. char passwd[64];
  496. if (firstload == 0) {
  497. /* Set a random password (4 digit number - bad idea from a security
  498. * point of view, but this is an API demo, not a security tutorial),
  499. * and store it in some directory within the document root (extremely
  500. * bad idea, but this is still not a security tutorial).
  501. * The reason we create a new password every time the server starts
  502. * is just for demonstration - we don't want the browser to store the
  503. * password, so when we repeat the test we start with a new password.
  504. */
  505. firstload = (unsigned long long)time(NULL);
  506. sprintf(passwd, "%04u", (unsigned int)(firstload % 10000));
  507. mg_modify_passwords_file(passfile, realm, user, passwd);
  508. /* Just tell the user the new password generated for this test. */
  509. mg_printf(conn,
  510. "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nConnection: "
  511. "close\r\n\r\n");
  512. mg_printf(conn, "<!DOCTYPE html>\n");
  513. mg_printf(conn, "<html>\n<head>\n");
  514. mg_printf(conn, "<meta charset=\"UTF-8\">\n");
  515. mg_printf(conn, "<title>Auth handlerexample</title>\n");
  516. mg_printf(conn, "</head>\n");
  517. mg_printf(conn, "<body>\n");
  518. mg_printf(conn,
  519. "<p>The first time you visit this page, it's free!</p>\n");
  520. mg_printf(conn,
  521. "<p>Next time, use username \"%s\" and password \"%s\"</p>\n",
  522. user,
  523. passwd);
  524. mg_printf(conn, "</body>\n</html>\n");
  525. return 1;
  526. }
  527. if (mg_check_digest_access_authentication(conn, realm, passfile) <= 0) {
  528. /* No valid authorization */
  529. mg_send_digest_access_authentication_request(conn, realm);
  530. return 1;
  531. }
  532. mg_printf(conn,
  533. "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nConnection: "
  534. "close\r\n\r\n");
  535. mg_printf(conn, "<!DOCTYPE html>\n");
  536. mg_printf(conn, "<html>\n<head>\n");
  537. mg_printf(conn, "<meta charset=\"UTF-8\">\n");
  538. mg_printf(conn, "<title>Auth handlerexample</title>\n");
  539. mg_printf(conn, "</head>\n");
  540. mg_printf(conn, "<body>\n");
  541. mg_printf(conn, "<p>This is the password protected contents</p>\n");
  542. mg_printf(conn, "</body>\n</html>\n");
  543. return 1;
  544. }
  545. #endif /* NO_FILESYSTEMS */
  546. int
  547. WebSocketStartHandler(struct mg_connection *conn, void *cbdata)
  548. {
  549. mg_printf(conn,
  550. "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nConnection: "
  551. "close\r\n\r\n");
  552. mg_printf(conn, "<!DOCTYPE html>\n");
  553. mg_printf(conn, "<html>\n<head>\n");
  554. mg_printf(conn, "<meta charset=\"UTF-8\">\n");
  555. mg_printf(conn, "<title>Embedded websocket example</title>\n");
  556. #ifdef USE_WEBSOCKET
  557. /* mg_printf(conn, "<script type=\"text/javascript\"><![CDATA[\n"); ...
  558. * xhtml style */
  559. mg_printf(conn, "<script>\n");
  560. mg_printf(
  561. conn,
  562. "function load() {\n"
  563. " var wsproto = (location.protocol === 'https:') ? 'wss:' : 'ws:';\n"
  564. " connection = new WebSocket(wsproto + '//' + window.location.host + "
  565. "'/websocket');\n"
  566. " websock_text_field = "
  567. "document.getElementById('websock_text_field');\n"
  568. " connection.onmessage = function (e) {\n"
  569. " websock_text_field.innerHTML=e.data;\n"
  570. " }\n"
  571. " connection.onerror = function (error) {\n"
  572. " alert('WebSocket error');\n"
  573. " connection.close();\n"
  574. " }\n"
  575. "}\n");
  576. /* mg_printf(conn, "]]></script>\n"); ... xhtml style */
  577. mg_printf(conn, "</script>\n");
  578. mg_printf(conn, "</head>\n<body onload=\"load()\">\n");
  579. mg_printf(
  580. conn,
  581. "<div id='websock_text_field'>No websocket connection yet</div>\n");
  582. #else
  583. mg_printf(conn, "</head>\n<body>\n");
  584. mg_printf(conn, "Example not compiled with USE_WEBSOCKET\n");
  585. #endif
  586. mg_printf(conn, "</body>\n</html>\n");
  587. return 1;
  588. }
  589. #ifdef USE_WEBSOCKET
  590. /* MAX_WS_CLIENTS defines how many clients can connect to a websocket at the
  591. * same time. The value 5 is very small and used here only for demonstration;
  592. * it can be easily tested to connect more than MAX_WS_CLIENTS clients.
  593. * A real server should use a much higher number, or better use a dynamic list
  594. * of currently connected websocket clients. */
  595. #define MAX_WS_CLIENTS (5)
  596. struct t_ws_client {
  597. struct mg_connection *conn;
  598. int state;
  599. } static ws_clients[MAX_WS_CLIENTS];
  600. #define ASSERT(x) \
  601. { \
  602. if (!(x)) { \
  603. fprintf(stderr, \
  604. "Assertion failed in line %u\n", \
  605. (unsigned)__LINE__); \
  606. } \
  607. }
  608. int
  609. WebSocketConnectHandler(const struct mg_connection *conn, void *cbdata)
  610. {
  611. struct mg_context *ctx = mg_get_context(conn);
  612. int reject = 1;
  613. int i;
  614. mg_lock_context(ctx);
  615. for (i = 0; i < MAX_WS_CLIENTS; i++) {
  616. if (ws_clients[i].conn == NULL) {
  617. ws_clients[i].conn = (struct mg_connection *)conn;
  618. ws_clients[i].state = 1;
  619. mg_set_user_connection_data(ws_clients[i].conn,
  620. (void *)(ws_clients + i));
  621. reject = 0;
  622. break;
  623. }
  624. }
  625. mg_unlock_context(ctx);
  626. fprintf(stdout,
  627. "Websocket client %s\r\n\r\n",
  628. (reject ? "rejected" : "accepted"));
  629. return reject;
  630. }
  631. void
  632. WebSocketReadyHandler(struct mg_connection *conn, void *cbdata)
  633. {
  634. const char *text = "Hello from the websocket ready handler";
  635. struct t_ws_client *client = mg_get_user_connection_data(conn);
  636. mg_websocket_write(conn, MG_WEBSOCKET_OPCODE_TEXT, text, strlen(text));
  637. fprintf(stdout, "Greeting message sent to websocket client\r\n\r\n");
  638. ASSERT(client->conn == conn);
  639. ASSERT(client->state == 1);
  640. client->state = 2;
  641. }
  642. int
  643. WebsocketDataHandler(struct mg_connection *conn,
  644. int bits,
  645. char *data,
  646. size_t len,
  647. void *cbdata)
  648. {
  649. struct t_ws_client *client = mg_get_user_connection_data(conn);
  650. ASSERT(client->conn == conn);
  651. ASSERT(client->state >= 1);
  652. fprintf(stdout, "Websocket got %lu bytes of ", (unsigned long)len);
  653. switch (((unsigned char)bits) & 0x0F) {
  654. case MG_WEBSOCKET_OPCODE_CONTINUATION:
  655. fprintf(stdout, "continuation");
  656. break;
  657. case MG_WEBSOCKET_OPCODE_TEXT:
  658. fprintf(stdout, "text");
  659. break;
  660. case MG_WEBSOCKET_OPCODE_BINARY:
  661. fprintf(stdout, "binary");
  662. break;
  663. case MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE:
  664. fprintf(stdout, "close");
  665. break;
  666. case MG_WEBSOCKET_OPCODE_PING:
  667. fprintf(stdout, "ping");
  668. break;
  669. case MG_WEBSOCKET_OPCODE_PONG:
  670. fprintf(stdout, "pong");
  671. break;
  672. default:
  673. fprintf(stdout, "unknown(%1xh)", ((unsigned char)bits) & 0x0F);
  674. break;
  675. }
  676. fprintf(stdout, " data:\r\n");
  677. fwrite(data, len, 1, stdout);
  678. fprintf(stdout, "\r\n\r\n");
  679. return 1;
  680. }
  681. void
  682. WebSocketCloseHandler(const struct mg_connection *conn, void *cbdata)
  683. {
  684. struct mg_context *ctx = mg_get_context(conn);
  685. struct t_ws_client *client = mg_get_user_connection_data(conn);
  686. ASSERT(client->conn == conn);
  687. ASSERT(client->state >= 1);
  688. mg_lock_context(ctx);
  689. client->state = 0;
  690. client->conn = NULL;
  691. mg_unlock_context(ctx);
  692. fprintf(stdout,
  693. "Client dropped from the set of webserver connections\r\n\r\n");
  694. }
  695. void
  696. InformWebsockets(struct mg_context *ctx)
  697. {
  698. static unsigned long cnt = 0;
  699. char text[32];
  700. size_t textlen;
  701. int i;
  702. sprintf(text, "%lu", ++cnt);
  703. textlen = strlen(text);
  704. mg_lock_context(ctx);
  705. for (i = 0; i < MAX_WS_CLIENTS; i++) {
  706. if (ws_clients[i].state == 2) {
  707. mg_websocket_write(ws_clients[i].conn,
  708. MG_WEBSOCKET_OPCODE_TEXT,
  709. text,
  710. textlen);
  711. }
  712. }
  713. mg_unlock_context(ctx);
  714. }
  715. #endif
  716. #ifdef USE_SSL_DH
  717. #include "openssl/dh.h"
  718. #include "openssl/ec.h"
  719. #include "openssl/ecdsa.h"
  720. #include "openssl/evp.h"
  721. #include "openssl/ssl.h"
  722. DH *
  723. get_dh2236()
  724. {
  725. static unsigned char dh2236_p[] = {
  726. 0x0E, 0x97, 0x6E, 0x6A, 0x88, 0x84, 0xD2, 0xD7, 0x55, 0x6A, 0x17, 0xB7,
  727. 0x81, 0x9A, 0x98, 0xBC, 0x7E, 0xD1, 0x6A, 0x44, 0xB1, 0x18, 0xE6, 0x25,
  728. 0x3A, 0x62, 0x35, 0xF0, 0x41, 0x91, 0xE2, 0x16, 0x43, 0x9D, 0x8F, 0x7D,
  729. 0x5D, 0xDA, 0x85, 0x47, 0x25, 0xC4, 0xBA, 0x68, 0x0A, 0x87, 0xDC, 0x2C,
  730. 0x33, 0xF9, 0x75, 0x65, 0x17, 0xCB, 0x8B, 0x80, 0xFE, 0xE0, 0xA8, 0xAF,
  731. 0xC7, 0x9E, 0x82, 0xBE, 0x6F, 0x1F, 0x00, 0x04, 0xBD, 0x69, 0x50, 0x8D,
  732. 0x9C, 0x3C, 0x41, 0x69, 0x21, 0x4E, 0x86, 0xC8, 0x2B, 0xCC, 0x07, 0x4D,
  733. 0xCF, 0xE4, 0xA2, 0x90, 0x8F, 0x66, 0xA9, 0xEF, 0xF7, 0xFC, 0x6F, 0x5F,
  734. 0x06, 0x22, 0x00, 0xCB, 0xCB, 0xC3, 0x98, 0x3F, 0x06, 0xB9, 0xEC, 0x48,
  735. 0x3B, 0x70, 0x6E, 0x94, 0xE9, 0x16, 0xE1, 0xB7, 0x63, 0x2E, 0xAB, 0xB2,
  736. 0xF3, 0x84, 0xB5, 0x3D, 0xD7, 0x74, 0xF1, 0x6A, 0xD1, 0xEF, 0xE8, 0x04,
  737. 0x18, 0x76, 0xD2, 0xD6, 0xB0, 0xB7, 0x71, 0xB6, 0x12, 0x8F, 0xD1, 0x33,
  738. 0xAB, 0x49, 0xAB, 0x09, 0x97, 0x35, 0x9D, 0x4B, 0xBB, 0x54, 0x22, 0x6E,
  739. 0x1A, 0x33, 0x18, 0x02, 0x8A, 0xF4, 0x7C, 0x0A, 0xCE, 0x89, 0x75, 0x2D,
  740. 0x10, 0x68, 0x25, 0xA9, 0x6E, 0xCD, 0x97, 0x49, 0xED, 0xAE, 0xE6, 0xA7,
  741. 0xB0, 0x07, 0x26, 0x25, 0x60, 0x15, 0x2B, 0x65, 0x88, 0x17, 0xF2, 0x5D,
  742. 0x2C, 0xF6, 0x2A, 0x7A, 0x8C, 0xAD, 0xB6, 0x0A, 0xA2, 0x57, 0xB0, 0xC1,
  743. 0x0E, 0x5C, 0xA8, 0xA1, 0x96, 0x58, 0x9A, 0x2B, 0xD4, 0xC0, 0x8A, 0xCF,
  744. 0x91, 0x25, 0x94, 0xB4, 0x14, 0xA7, 0xE4, 0xE2, 0x1B, 0x64, 0x5F, 0xD2,
  745. 0xCA, 0x70, 0x46, 0xD0, 0x2C, 0x95, 0x6B, 0x9A, 0xFB, 0x83, 0xF9, 0x76,
  746. 0xE6, 0xD4, 0xA4, 0xA1, 0x2B, 0x2F, 0xF5, 0x1D, 0xE4, 0x06, 0xAF, 0x7D,
  747. 0x22, 0xF3, 0x04, 0x30, 0x2E, 0x4C, 0x64, 0x12, 0x5B, 0xB0, 0x55, 0x3E,
  748. 0xC0, 0x5E, 0x56, 0xCB, 0x99, 0xBC, 0xA8, 0xD9, 0x23, 0xF5, 0x57, 0x40,
  749. 0xF0, 0x52, 0x85, 0x9B,
  750. };
  751. static unsigned char dh2236_g[] = {
  752. 0x02,
  753. };
  754. DH *dh;
  755. if ((dh = DH_new()) == NULL)
  756. return (NULL);
  757. dh->p = BN_bin2bn(dh2236_p, sizeof(dh2236_p), NULL);
  758. dh->g = BN_bin2bn(dh2236_g, sizeof(dh2236_g), NULL);
  759. if ((dh->p == NULL) || (dh->g == NULL)) {
  760. DH_free(dh);
  761. return (NULL);
  762. }
  763. return (dh);
  764. }
  765. #endif
  766. #ifndef TEST_WITHOUT_SSL
  767. int
  768. init_ssl(void *ssl_context, void *user_data)
  769. {
  770. /* Add application specific SSL initialization */
  771. struct ssl_ctx_st *ctx = (struct ssl_ctx_st *)ssl_context;
  772. #ifdef USE_SSL_DH
  773. /* example from https://github.com/civetweb/civetweb/issues/347 */
  774. DH *dh = get_dh2236();
  775. if (!dh)
  776. return -1;
  777. if (1 != SSL_CTX_set_tmp_dh(ctx, dh))
  778. return -1;
  779. DH_free(dh);
  780. EC_KEY *ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
  781. if (!ecdh)
  782. return -1;
  783. if (1 != SSL_CTX_set_tmp_ecdh(ctx, ecdh))
  784. return -1;
  785. EC_KEY_free(ecdh);
  786. printf("ECDH ciphers initialized\n");
  787. #endif
  788. return 0;
  789. }
  790. #endif
  791. int
  792. log_message(const struct mg_connection *conn, const char *message)
  793. {
  794. puts(message);
  795. return 1;
  796. }
  797. int
  798. main(int argc, char *argv[])
  799. {
  800. const char *options[] = {
  801. #if !defined(NO_FILES)
  802. "document_root",
  803. DOCUMENT_ROOT,
  804. #endif
  805. "listening_ports",
  806. PORT,
  807. "request_timeout_ms",
  808. "10000",
  809. "error_log_file",
  810. "error.log",
  811. #ifdef USE_WEBSOCKET
  812. "websocket_timeout_ms",
  813. "3600000",
  814. #endif
  815. #ifndef TEST_WITHOUT_SSL
  816. "ssl_certificate",
  817. "../../resources/cert/server.pem",
  818. "ssl_protocol_version",
  819. "3",
  820. "ssl_cipher_list",
  821. #ifdef USE_SSL_DH
  822. "ECDHE-RSA-AES256-GCM-SHA384:DES-CBC3-SHA:AES128-SHA:AES128-GCM-SHA256",
  823. #else
  824. "DES-CBC3-SHA:AES128-SHA:AES128-GCM-SHA256",
  825. #endif
  826. #endif
  827. "enable_auth_domain_check",
  828. "no",
  829. 0};
  830. struct mg_callbacks callbacks;
  831. struct mg_context *ctx;
  832. struct mg_server_port ports[32];
  833. int port_cnt, n;
  834. int err = 0;
  835. /* Check if libcivetweb has been built with all required features. */
  836. #ifdef USE_IPV6
  837. if (!mg_check_feature(8)) {
  838. fprintf(stderr,
  839. "Error: Embedded example built with IPv6 support, "
  840. "but civetweb library build without.\n");
  841. err = 1;
  842. }
  843. #endif
  844. #ifdef USE_WEBSOCKET
  845. if (!mg_check_feature(16)) {
  846. fprintf(stderr,
  847. "Error: Embedded example built with websocket support, "
  848. "but civetweb library build without.\n");
  849. err = 1;
  850. }
  851. #endif
  852. #ifndef TEST_WITHOUT_SSL
  853. if (!mg_check_feature(2)) {
  854. fprintf(stderr,
  855. "Error: Embedded example built with SSL support, "
  856. "but civetweb library build without.\n");
  857. err = 1;
  858. }
  859. #endif
  860. if (err) {
  861. fprintf(stderr, "Cannot start CivetWeb - inconsistent build.\n");
  862. return EXIT_FAILURE;
  863. }
  864. /* Start CivetWeb web server */
  865. memset(&callbacks, 0, sizeof(callbacks));
  866. #ifndef TEST_WITHOUT_SSL
  867. callbacks.init_ssl = init_ssl;
  868. #endif
  869. callbacks.log_message = log_message;
  870. ctx = mg_start(&callbacks, 0, options);
  871. /* Check return value: */
  872. if (ctx == NULL) {
  873. fprintf(stderr, "Cannot start CivetWeb - mg_start failed.\n");
  874. return EXIT_FAILURE;
  875. }
  876. /* Add handler EXAMPLE_URI, to explain the example */
  877. mg_set_request_handler(ctx, EXAMPLE_URI, ExampleHandler, 0);
  878. mg_set_request_handler(ctx, EXIT_URI, ExitHandler, 0);
  879. /* Add handler for /A* and special handler for /A/B */
  880. mg_set_request_handler(ctx, "/A", AHandler, 0);
  881. mg_set_request_handler(ctx, "/A/B", ABHandler, 0);
  882. /* Add handler for /B, /B/A, /B/B but not for /B* */
  883. mg_set_request_handler(ctx, "/B$", BXHandler, (void *)"alpha");
  884. mg_set_request_handler(ctx, "/B/A$", BXHandler, (void *)"beta");
  885. mg_set_request_handler(ctx, "/B/B$", BXHandler, (void *)"gamma");
  886. /* Add handler for all files with .foo extension */
  887. mg_set_request_handler(ctx, "**.foo$", FooHandler, 0);
  888. /* Add handler for /close extension */
  889. mg_set_request_handler(ctx, "/close", CloseHandler, 0);
  890. #if !defined(NO_FILESYSTEMS)
  891. /* Add handler for /form (serve a file outside the document root) */
  892. mg_set_request_handler(ctx,
  893. "/form",
  894. FileHandler,
  895. (void *)"../../test/form.html");
  896. #endif /* NO_FILESYSTEMS */
  897. /* Add handler for form data */
  898. mg_set_request_handler(ctx,
  899. "/handle_form.embedded_c.example.callback",
  900. FormHandler,
  901. (void *)0);
  902. /* Add a file upload handler for parsing files on the fly */
  903. mg_set_request_handler(ctx,
  904. "/on_the_fly_form",
  905. FileUploadForm,
  906. (void *)"/on_the_fly_form.md5.callback");
  907. mg_set_request_handler(ctx,
  908. "/on_the_fly_form.md5.callback",
  909. CheckSumHandler,
  910. (void *)0);
  911. /* Add handler for /cookie example */
  912. mg_set_request_handler(ctx, "/cookie", CookieHandler, 0);
  913. /* Add handler for /postresponse example */
  914. mg_set_request_handler(ctx, "/postresponse", PostResponser, 0);
  915. /* Add HTTP site to open a websocket connection */
  916. mg_set_request_handler(ctx, "/websocket", WebSocketStartHandler, 0);
  917. #if !defined(NO_FILESYSTEMS)
  918. /* Add HTTP site with auth */
  919. mg_set_request_handler(ctx, "/auth", AuthStartHandler, 0);
  920. #endif /* NO_FILESYSTEMS */
  921. #ifdef USE_WEBSOCKET
  922. /* WS site for the websocket connection */
  923. mg_set_websocket_handler(ctx,
  924. "/websocket",
  925. WebSocketConnectHandler,
  926. WebSocketReadyHandler,
  927. WebsocketDataHandler,
  928. WebSocketCloseHandler,
  929. 0);
  930. #endif
  931. /* List all listening ports */
  932. memset(ports, 0, sizeof(ports));
  933. port_cnt = mg_get_server_ports(ctx, 32, ports);
  934. printf("\n%i listening ports:\n\n", port_cnt);
  935. for (n = 0; n < port_cnt && n < 32; n++) {
  936. const char *proto = ports[n].is_ssl ? "https" : "http";
  937. const char *host;
  938. if ((ports[n].protocol & 1) == 1) {
  939. /* IPv4 */
  940. host = "127.0.0.1";
  941. printf("Browse files at %s://%s:%i/\n", proto, host, ports[n].port);
  942. printf("Run example at %s://%s:%i%s\n",
  943. proto,
  944. host,
  945. ports[n].port,
  946. EXAMPLE_URI);
  947. printf(
  948. "Exit at %s://%s:%i%s\n", proto, host, ports[n].port, EXIT_URI);
  949. printf("\n");
  950. }
  951. if ((ports[n].protocol & 2) == 2) {
  952. /* IPv6 */
  953. host = "[::1]";
  954. printf("Browse files at %s://%s:%i/\n", proto, host, ports[n].port);
  955. printf("Run example at %s://%s:%i%s\n",
  956. proto,
  957. host,
  958. ports[n].port,
  959. EXAMPLE_URI);
  960. printf(
  961. "Exit at %s://%s:%i%s\n", proto, host, ports[n].port, EXIT_URI);
  962. printf("\n");
  963. }
  964. }
  965. /* Wait until the server should be closed */
  966. while (!exitNow) {
  967. #ifdef _WIN32
  968. Sleep(1000);
  969. #else
  970. sleep(1);
  971. #endif
  972. #ifdef USE_WEBSOCKET
  973. InformWebsockets(ctx);
  974. #endif
  975. }
  976. /* Stop the server */
  977. mg_stop(ctx);
  978. printf("Server stopped.\n");
  979. printf("Bye!\n");
  980. return EXIT_SUCCESS;
  981. }