embedded_c.c 33 KB

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