embedded_c.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023
  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"
  20. #else
  21. #define PORT "8888"
  22. #endif
  23. #else
  24. #ifdef USE_IPV6
  25. #define PORT "[::]:8888r,[::]:8843s,8884"
  26. #else
  27. #define PORT "8888r,8843s"
  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. static int
  391. send_chunk(struct mg_connection *conn,
  392. const char *chunk,
  393. unsigned int chunk_len)
  394. {
  395. char lenbuf[16];
  396. size_t lenbuf_len;
  397. int ret;
  398. int t;
  399. /* First store the length information in a text buffer. */
  400. sprintf(lenbuf, "%x\r\n", chunk_len);
  401. lenbuf_len = strlen(lenbuf);
  402. /* Then send length information, chunk and terminating \r\n. */
  403. ret = mg_write(conn, lenbuf, lenbuf_len);
  404. if (ret != (int)lenbuf_len) {
  405. return -1;
  406. }
  407. t = ret;
  408. ret = mg_write(conn, chunk, chunk_len);
  409. if (ret != (int)chunk_len) {
  410. return -1;
  411. }
  412. t += ret;
  413. ret = mg_write(conn, "\r\n", 2);
  414. if (ret != 2) {
  415. return -1;
  416. }
  417. t += ret;
  418. return t;
  419. }
  420. int
  421. PostResponser(struct mg_connection *conn, void *cbdata)
  422. {
  423. long long r_total = 0;
  424. int r, s;
  425. char buf[2048];
  426. const struct mg_request_info *ri = mg_get_request_info(conn);
  427. if (strcmp(ri->request_method, "POST")) {
  428. char buf[1024];
  429. int ret = mg_get_request_link(conn, buf, sizeof(buf));
  430. mg_printf(conn,
  431. "HTTP/1.1 405 Method Not Allowed\r\nConnection: close\r\n");
  432. mg_printf(conn, "Content-Type: text/plain\r\n\r\n");
  433. mg_printf(conn,
  434. "%s method not allowed in the POST handler\n",
  435. ri->request_method);
  436. if (ret >= 0) {
  437. mg_printf(conn,
  438. "use a web tool to send a POST request to %s\n",
  439. buf);
  440. }
  441. return 1;
  442. }
  443. if (ri->content_length >= 0) {
  444. /* We know the content length in advance */
  445. } else {
  446. /* We must read until we find the end (chunked encoding
  447. * or connection close), indicated my mg_read returning 0 */
  448. }
  449. mg_printf(conn,
  450. "HTTP/1.1 200 OK\r\nConnection: "
  451. "close\r\nTransfer-Encoding: chunked\r\n");
  452. mg_printf(conn, "Content-Type: text/plain\r\n\r\n");
  453. r = mg_read(conn, buf, sizeof(buf));
  454. while (r > 0) {
  455. r_total += r;
  456. s = send_chunk(conn, buf, r);
  457. if (r != s) {
  458. /* Send error */
  459. break;
  460. }
  461. r = mg_read(conn, buf, sizeof(buf));
  462. }
  463. mg_printf(conn, "0\r\n");
  464. return 1;
  465. }
  466. int
  467. WebSocketStartHandler(struct mg_connection *conn, void *cbdata)
  468. {
  469. mg_printf(conn,
  470. "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nConnection: "
  471. "close\r\n\r\n");
  472. mg_printf(conn, "<!DOCTYPE html>\n");
  473. mg_printf(conn, "<html>\n<head>\n");
  474. mg_printf(conn, "<meta charset=\"UTF-8\">\n");
  475. mg_printf(conn, "<title>Embedded websocket example</title>\n");
  476. #ifdef USE_WEBSOCKET
  477. /* mg_printf(conn, "<script type=\"text/javascript\"><![CDATA[\n"); ...
  478. * xhtml style */
  479. mg_printf(conn, "<script>\n");
  480. mg_printf(
  481. conn,
  482. "function load() {\n"
  483. " var wsproto = (location.protocol === 'https:') ? 'wss:' : 'ws:';\n"
  484. " connection = new WebSocket(wsproto + '//' + window.location.host + "
  485. "'/websocket');\n"
  486. " websock_text_field = "
  487. "document.getElementById('websock_text_field');\n"
  488. " connection.onmessage = function (e) {\n"
  489. " websock_text_field.innerHTML=e.data;\n"
  490. " }\n"
  491. " connection.onerror = function (error) {\n"
  492. " alert('WebSocket error');\n"
  493. " connection.close();\n"
  494. " }\n"
  495. "}\n");
  496. /* mg_printf(conn, "]]></script>\n"); ... xhtml style */
  497. mg_printf(conn, "</script>\n");
  498. mg_printf(conn, "</head>\n<body onload=\"load()\">\n");
  499. mg_printf(
  500. conn,
  501. "<div id='websock_text_field'>No websocket connection yet</div>\n");
  502. #else
  503. mg_printf(conn, "</head>\n<body>\n");
  504. mg_printf(conn, "Example not compiled with USE_WEBSOCKET\n");
  505. #endif
  506. mg_printf(conn, "</body>\n</html>\n");
  507. return 1;
  508. }
  509. #ifdef USE_WEBSOCKET
  510. /* MAX_WS_CLIENTS defines how many clients can connect to a websocket at the
  511. * same time. The value 5 is very small and used here only for demonstration;
  512. * it can be easily tested to connect more than MAX_WS_CLIENTS clients.
  513. * A real server should use a much higher number, or better use a dynamic list
  514. * of currently connected websocket clients. */
  515. #define MAX_WS_CLIENTS (5)
  516. struct t_ws_client {
  517. struct mg_connection *conn;
  518. int state;
  519. } static ws_clients[MAX_WS_CLIENTS];
  520. #define ASSERT(x) \
  521. { \
  522. if (!(x)) { \
  523. fprintf(stderr, \
  524. "Assertion failed in line %u\n", \
  525. (unsigned)__LINE__); \
  526. } \
  527. }
  528. int
  529. WebSocketConnectHandler(const struct mg_connection *conn, void *cbdata)
  530. {
  531. struct mg_context *ctx = mg_get_context(conn);
  532. int reject = 1;
  533. int i;
  534. mg_lock_context(ctx);
  535. for (i = 0; i < MAX_WS_CLIENTS; i++) {
  536. if (ws_clients[i].conn == NULL) {
  537. ws_clients[i].conn = (struct mg_connection *)conn;
  538. ws_clients[i].state = 1;
  539. mg_set_user_connection_data(ws_clients[i].conn,
  540. (void *)(ws_clients + i));
  541. reject = 0;
  542. break;
  543. }
  544. }
  545. mg_unlock_context(ctx);
  546. fprintf(stdout,
  547. "Websocket client %s\r\n\r\n",
  548. (reject ? "rejected" : "accepted"));
  549. return reject;
  550. }
  551. void
  552. WebSocketReadyHandler(struct mg_connection *conn, void *cbdata)
  553. {
  554. const char *text = "Hello from the websocket ready handler";
  555. struct t_ws_client *client = mg_get_user_connection_data(conn);
  556. mg_websocket_write(conn, WEBSOCKET_OPCODE_TEXT, text, strlen(text));
  557. fprintf(stdout, "Greeting message sent to websocket client\r\n\r\n");
  558. ASSERT(client->conn == conn);
  559. ASSERT(client->state == 1);
  560. client->state = 2;
  561. }
  562. int
  563. WebsocketDataHandler(struct mg_connection *conn,
  564. int bits,
  565. char *data,
  566. size_t len,
  567. void *cbdata)
  568. {
  569. struct t_ws_client *client = mg_get_user_connection_data(conn);
  570. ASSERT(client->conn == conn);
  571. ASSERT(client->state >= 1);
  572. fprintf(stdout, "Websocket got data:\r\n");
  573. fwrite(data, len, 1, stdout);
  574. fprintf(stdout, "\r\n\r\n");
  575. return 1;
  576. }
  577. void
  578. WebSocketCloseHandler(const struct mg_connection *conn, void *cbdata)
  579. {
  580. struct mg_context *ctx = mg_get_context(conn);
  581. struct t_ws_client *client = mg_get_user_connection_data(conn);
  582. ASSERT(client->conn == conn);
  583. ASSERT(client->state >= 1);
  584. mg_lock_context(ctx);
  585. client->state = 0;
  586. client->conn = NULL;
  587. mg_unlock_context(ctx);
  588. fprintf(stdout,
  589. "Client droped from the set of webserver connections\r\n\r\n");
  590. }
  591. void
  592. InformWebsockets(struct mg_context *ctx)
  593. {
  594. static unsigned long cnt = 0;
  595. char text[32];
  596. int i;
  597. sprintf(text, "%lu", ++cnt);
  598. mg_lock_context(ctx);
  599. for (i = 0; i < MAX_WS_CLIENTS; i++) {
  600. if (ws_clients[i].state == 2) {
  601. mg_websocket_write(ws_clients[i].conn,
  602. WEBSOCKET_OPCODE_TEXT,
  603. text,
  604. strlen(text));
  605. }
  606. }
  607. mg_unlock_context(ctx);
  608. }
  609. #endif
  610. #ifdef USE_SSL_DH
  611. #include "openssl/ssl.h"
  612. #include "openssl/dh.h"
  613. #include "openssl/ec.h"
  614. #include "openssl/evp.h"
  615. #include "openssl/ecdsa.h"
  616. DH *
  617. get_dh2236()
  618. {
  619. static unsigned char dh2236_p[] = {
  620. 0x0E, 0x97, 0x6E, 0x6A, 0x88, 0x84, 0xD2, 0xD7, 0x55, 0x6A, 0x17, 0xB7,
  621. 0x81, 0x9A, 0x98, 0xBC, 0x7E, 0xD1, 0x6A, 0x44, 0xB1, 0x18, 0xE6, 0x25,
  622. 0x3A, 0x62, 0x35, 0xF0, 0x41, 0x91, 0xE2, 0x16, 0x43, 0x9D, 0x8F, 0x7D,
  623. 0x5D, 0xDA, 0x85, 0x47, 0x25, 0xC4, 0xBA, 0x68, 0x0A, 0x87, 0xDC, 0x2C,
  624. 0x33, 0xF9, 0x75, 0x65, 0x17, 0xCB, 0x8B, 0x80, 0xFE, 0xE0, 0xA8, 0xAF,
  625. 0xC7, 0x9E, 0x82, 0xBE, 0x6F, 0x1F, 0x00, 0x04, 0xBD, 0x69, 0x50, 0x8D,
  626. 0x9C, 0x3C, 0x41, 0x69, 0x21, 0x4E, 0x86, 0xC8, 0x2B, 0xCC, 0x07, 0x4D,
  627. 0xCF, 0xE4, 0xA2, 0x90, 0x8F, 0x66, 0xA9, 0xEF, 0xF7, 0xFC, 0x6F, 0x5F,
  628. 0x06, 0x22, 0x00, 0xCB, 0xCB, 0xC3, 0x98, 0x3F, 0x06, 0xB9, 0xEC, 0x48,
  629. 0x3B, 0x70, 0x6E, 0x94, 0xE9, 0x16, 0xE1, 0xB7, 0x63, 0x2E, 0xAB, 0xB2,
  630. 0xF3, 0x84, 0xB5, 0x3D, 0xD7, 0x74, 0xF1, 0x6A, 0xD1, 0xEF, 0xE8, 0x04,
  631. 0x18, 0x76, 0xD2, 0xD6, 0xB0, 0xB7, 0x71, 0xB6, 0x12, 0x8F, 0xD1, 0x33,
  632. 0xAB, 0x49, 0xAB, 0x09, 0x97, 0x35, 0x9D, 0x4B, 0xBB, 0x54, 0x22, 0x6E,
  633. 0x1A, 0x33, 0x18, 0x02, 0x8A, 0xF4, 0x7C, 0x0A, 0xCE, 0x89, 0x75, 0x2D,
  634. 0x10, 0x68, 0x25, 0xA9, 0x6E, 0xCD, 0x97, 0x49, 0xED, 0xAE, 0xE6, 0xA7,
  635. 0xB0, 0x07, 0x26, 0x25, 0x60, 0x15, 0x2B, 0x65, 0x88, 0x17, 0xF2, 0x5D,
  636. 0x2C, 0xF6, 0x2A, 0x7A, 0x8C, 0xAD, 0xB6, 0x0A, 0xA2, 0x57, 0xB0, 0xC1,
  637. 0x0E, 0x5C, 0xA8, 0xA1, 0x96, 0x58, 0x9A, 0x2B, 0xD4, 0xC0, 0x8A, 0xCF,
  638. 0x91, 0x25, 0x94, 0xB4, 0x14, 0xA7, 0xE4, 0xE2, 0x1B, 0x64, 0x5F, 0xD2,
  639. 0xCA, 0x70, 0x46, 0xD0, 0x2C, 0x95, 0x6B, 0x9A, 0xFB, 0x83, 0xF9, 0x76,
  640. 0xE6, 0xD4, 0xA4, 0xA1, 0x2B, 0x2F, 0xF5, 0x1D, 0xE4, 0x06, 0xAF, 0x7D,
  641. 0x22, 0xF3, 0x04, 0x30, 0x2E, 0x4C, 0x64, 0x12, 0x5B, 0xB0, 0x55, 0x3E,
  642. 0xC0, 0x5E, 0x56, 0xCB, 0x99, 0xBC, 0xA8, 0xD9, 0x23, 0xF5, 0x57, 0x40,
  643. 0xF0, 0x52, 0x85, 0x9B,
  644. };
  645. static unsigned char dh2236_g[] = {
  646. 0x02,
  647. };
  648. DH *dh;
  649. if ((dh = DH_new()) == NULL)
  650. return (NULL);
  651. dh->p = BN_bin2bn(dh2236_p, sizeof(dh2236_p), NULL);
  652. dh->g = BN_bin2bn(dh2236_g, sizeof(dh2236_g), NULL);
  653. if ((dh->p == NULL) || (dh->g == NULL)) {
  654. DH_free(dh);
  655. return (NULL);
  656. }
  657. return (dh);
  658. }
  659. #endif
  660. #ifndef NO_SSL
  661. int
  662. init_ssl(void *ssl_context, void *user_data)
  663. {
  664. /* Add application specific SSL initialization */
  665. struct ssl_ctx_st *ctx = (struct ssl_ctx_st *)ssl_context;
  666. #ifdef USE_SSL_DH
  667. /* example from https://github.com/civetweb/civetweb/issues/347 */
  668. DH *dh = get_dh2236();
  669. if (!dh)
  670. return -1;
  671. if (1 != SSL_CTX_set_tmp_dh(ctx, dh))
  672. return -1;
  673. DH_free(dh);
  674. EC_KEY *ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
  675. if (!ecdh)
  676. return -1;
  677. if (1 != SSL_CTX_set_tmp_ecdh(ctx, ecdh))
  678. return -1;
  679. EC_KEY_free(ecdh);
  680. printf("ECDH ciphers initialized\n");
  681. #endif
  682. return 0;
  683. }
  684. #endif
  685. int
  686. log_message(const struct mg_connection *conn, const char *message)
  687. {
  688. puts(message);
  689. return 1;
  690. }
  691. int
  692. main(int argc, char *argv[])
  693. {
  694. const char *options[] = {
  695. "document_root",
  696. DOCUMENT_ROOT,
  697. "listening_ports",
  698. PORT,
  699. "request_timeout_ms",
  700. "10000",
  701. "error_log_file",
  702. "error.log",
  703. #ifdef USE_WEBSOCKET
  704. "websocket_timeout_ms",
  705. "3600000",
  706. #endif
  707. #ifndef NO_SSL
  708. "ssl_certificate",
  709. "../../resources/cert/server.pem",
  710. "ssl_protocol_version",
  711. "3",
  712. "ssl_cipher_list",
  713. #ifdef USE_SSL_DH
  714. "ECDHE-RSA-AES256-GCM-SHA384:DES-CBC3-SHA:AES128-SHA:AES128-GCM-SHA256",
  715. #else
  716. "DES-CBC3-SHA:AES128-SHA:AES128-GCM-SHA256",
  717. #endif
  718. #endif
  719. "enable_auth_domain_check",
  720. "no",
  721. 0};
  722. struct mg_callbacks callbacks;
  723. struct mg_context *ctx;
  724. struct mg_server_ports ports[32];
  725. int port_cnt, n;
  726. int err = 0;
  727. /* Check if libcivetweb has been built with all required features. */
  728. #ifdef USE_IPV6
  729. if (!mg_check_feature(8)) {
  730. fprintf(stderr,
  731. "Error: Embedded example built with IPv6 support, "
  732. "but civetweb library build without.\n");
  733. err = 1;
  734. }
  735. #endif
  736. #ifdef USE_WEBSOCKET
  737. if (!mg_check_feature(16)) {
  738. fprintf(stderr,
  739. "Error: Embedded example built with websocket support, "
  740. "but civetweb library build without.\n");
  741. err = 1;
  742. }
  743. #endif
  744. #ifndef NO_SSL
  745. if (!mg_check_feature(2)) {
  746. fprintf(stderr,
  747. "Error: Embedded example built with SSL support, "
  748. "but civetweb library build without.\n");
  749. err = 1;
  750. }
  751. #endif
  752. if (err) {
  753. fprintf(stderr, "Cannot start CivetWeb - inconsistent build.\n");
  754. return EXIT_FAILURE;
  755. }
  756. /* Start CivetWeb web server */
  757. memset(&callbacks, 0, sizeof(callbacks));
  758. #ifndef NO_SSL
  759. callbacks.init_ssl = init_ssl;
  760. #endif
  761. callbacks.log_message = log_message;
  762. ctx = mg_start(&callbacks, 0, options);
  763. /* Check return value: */
  764. if (ctx == NULL) {
  765. fprintf(stderr, "Cannot start CivetWeb - mg_start failed.\n");
  766. return EXIT_FAILURE;
  767. }
  768. /* Add handler EXAMPLE_URI, to explain the example */
  769. mg_set_request_handler(ctx, EXAMPLE_URI, ExampleHandler, 0);
  770. mg_set_request_handler(ctx, EXIT_URI, ExitHandler, 0);
  771. /* Add handler for /A* and special handler for /A/B */
  772. mg_set_request_handler(ctx, "/A", AHandler, 0);
  773. mg_set_request_handler(ctx, "/A/B", ABHandler, 0);
  774. /* Add handler for /B, /B/A, /B/B but not for /B* */
  775. mg_set_request_handler(ctx, "/B$", BXHandler, (void *)0);
  776. mg_set_request_handler(ctx, "/B/A$", BXHandler, (void *)1);
  777. mg_set_request_handler(ctx, "/B/B$", BXHandler, (void *)2);
  778. /* Add handler for all files with .foo extention */
  779. mg_set_request_handler(ctx, "**.foo$", FooHandler, 0);
  780. /* Add handler for /close extention */
  781. mg_set_request_handler(ctx, "/close", CloseHandler, 0);
  782. /* Add handler for /form (serve a file outside the document root) */
  783. mg_set_request_handler(ctx,
  784. "/form",
  785. FileHandler,
  786. (void *)"../../test/form.html");
  787. /* Add handler for form data */
  788. mg_set_request_handler(ctx,
  789. "/handle_form.embedded_c.example.callback",
  790. FormHandler,
  791. (void *)0);
  792. /* Add a file upload handler for parsing files on the fly */
  793. mg_set_request_handler(ctx,
  794. "/on_the_fly_form",
  795. FileUploadForm,
  796. (void *)"/on_the_fly_form.md5.callback");
  797. mg_set_request_handler(ctx,
  798. "/on_the_fly_form.md5.callback",
  799. CheckSumHandler,
  800. (void *)0);
  801. /* Add handler for /cookie example */
  802. mg_set_request_handler(ctx, "/cookie", CookieHandler, 0);
  803. /* Add handler for /postresponse example */
  804. mg_set_request_handler(ctx, "/postresponse", PostResponser, 0);
  805. /* Add HTTP site to open a websocket connection */
  806. mg_set_request_handler(ctx, "/websocket", WebSocketStartHandler, 0);
  807. #ifdef USE_WEBSOCKET
  808. /* WS site for the websocket connection */
  809. mg_set_websocket_handler(ctx,
  810. "/websocket",
  811. WebSocketConnectHandler,
  812. WebSocketReadyHandler,
  813. WebsocketDataHandler,
  814. WebSocketCloseHandler,
  815. 0);
  816. #endif
  817. /* List all listening ports */
  818. memset(ports, 0, sizeof(ports));
  819. port_cnt = mg_get_server_ports(ctx, 32, ports);
  820. printf("\n%i listening ports:\n\n", port_cnt);
  821. for (n = 0; n < port_cnt && n < 32; n++) {
  822. const char *proto = ports[n].is_ssl ? "https" : "http";
  823. const char *host;
  824. if ((ports[n].protocol & 1) == 1) {
  825. /* IPv4 */
  826. host = "127.0.0.1";
  827. printf("Browse files at %s://%s:%i/\n", proto, host, ports[n].port);
  828. printf("Run example at %s://%s:%i%s\n",
  829. proto,
  830. host,
  831. ports[n].port,
  832. EXAMPLE_URI);
  833. printf(
  834. "Exit at %s://%s:%i%s\n", proto, host, ports[n].port, EXIT_URI);
  835. printf("\n");
  836. }
  837. if ((ports[n].protocol & 2) == 2) {
  838. /* IPv6 */
  839. host = "[::1]";
  840. printf("Browse files at %s://%s:%i/\n", proto, host, ports[n].port);
  841. printf("Run example at %s://%s:%i%s\n",
  842. proto,
  843. host,
  844. ports[n].port,
  845. EXAMPLE_URI);
  846. printf(
  847. "Exit at %s://%s:%i%s\n", proto, host, ports[n].port, EXIT_URI);
  848. printf("\n");
  849. }
  850. }
  851. /* Wait until the server should be closed */
  852. while (!exitNow) {
  853. #ifdef _WIN32
  854. Sleep(1000);
  855. #else
  856. sleep(1);
  857. #endif
  858. #ifdef USE_WEBSOCKET
  859. InformWebsockets(ctx);
  860. #endif
  861. }
  862. /* Stop the server */
  863. mg_stop(ctx);
  864. printf("Server stopped.\n");
  865. printf("Bye!\n");
  866. return EXIT_SUCCESS;
  867. }