embedded_c.c 31 KB

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