embedded_c.c 31 KB

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