embedded_c.c 27 KB

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