embedded_c.c 31 KB

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