embedded_c.c 30 KB

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