embedded_c.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653
  1. /*
  2. * Copyright (c) 2013-2016 the CivetWeb developers
  3. * Copyright (c) 2013 No Face Press, LLC
  4. * License http://opensource.org/licenses/mit-license.php MIT License
  5. */
  6. /* Simple example program on how to use CivetWeb embedded into a C program. */
  7. #ifdef _WIN32
  8. #include <Windows.h>
  9. #else
  10. #include <unistd.h>
  11. #endif
  12. #include <stdlib.h>
  13. #include <string.h>
  14. #include <time.h>
  15. #include "civetweb.h"
  16. #define DOCUMENT_ROOT "."
  17. #ifdef NO_SSL
  18. #ifdef USE_IPV6
  19. #define PORT "[::]:8888"
  20. #else
  21. #define PORT "8888"
  22. #endif
  23. #else
  24. #ifdef USE_IPV6
  25. #define PORT "[::]:8888r,[::]:8843s,8884"
  26. #else
  27. #define PORT "8888r,8843s"
  28. #endif
  29. #endif
  30. #define EXAMPLE_URI "/example"
  31. #define EXIT_URI "/exit"
  32. int exitNow = 0;
  33. int
  34. ExampleHandler(struct mg_connection *conn, void *cbdata)
  35. {
  36. mg_printf(conn, "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n");
  37. mg_printf(conn, "<html><body>");
  38. mg_printf(conn, "<h2>This is an example text from a C handler</h2>");
  39. mg_printf(
  40. conn,
  41. "<p>To see a page from the A handler <a href=\"A\">click A</a></p>");
  42. mg_printf(conn,
  43. "<p>To see a page from the A handler <a href=\"A/A\">click "
  44. "A/A</a></p>");
  45. mg_printf(conn,
  46. "<p>To see a page from the A/B handler <a "
  47. "href=\"A/B\">click A/B</a></p>");
  48. mg_printf(conn,
  49. "<p>To see a page from the B handler (0) <a "
  50. "href=\"B\">click B</a></p>");
  51. mg_printf(conn,
  52. "<p>To see a page from the B handler (1) <a "
  53. "href=\"B/A\">click B/A</a></p>");
  54. mg_printf(conn,
  55. "<p>To see a page from the B handler (2) <a "
  56. "href=\"B/B\">click B/B</a></p>");
  57. mg_printf(conn,
  58. "<p>To see a page from the *.foo handler <a "
  59. "href=\"xy.foo\">click xy.foo</a></p>");
  60. mg_printf(conn,
  61. "<p>To see a page from the close handler <a "
  62. "href=\"close\">click close</a></p>");
  63. mg_printf(conn,
  64. "<p>To see a page from the FileHandler handler <a "
  65. "href=\"form\">click form</a> (the starting point of the "
  66. "<b>form</b> test)</p>");
  67. mg_printf(conn,
  68. "<p>To see a page from the CookieHandler handler <a "
  69. "href=\"cookie\">click cookie</a></p>");
  70. #ifdef USE_WEBSOCKET
  71. mg_printf(conn,
  72. "<p>To test websocket handler <a href=\"/websocket\">click "
  73. "websocket</a></p>");
  74. #endif
  75. mg_printf(conn, "<p>To exit <a href=\"%s\">click exit</a></p>", EXIT_URI);
  76. mg_printf(conn, "</body></html>\n");
  77. return 1;
  78. }
  79. int
  80. ExitHandler(struct mg_connection *conn, void *cbdata)
  81. {
  82. mg_printf(conn, "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\n");
  83. mg_printf(conn, "Server will shut down.\n");
  84. mg_printf(conn, "Bye!\n");
  85. exitNow = 1;
  86. return 1;
  87. }
  88. int
  89. AHandler(struct mg_connection *conn, void *cbdata)
  90. {
  91. mg_printf(conn, "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n");
  92. mg_printf(conn, "<html><body>");
  93. mg_printf(conn, "<h2>This is the A handler!!!</h2>");
  94. mg_printf(conn, "</body></html>\n");
  95. return 1;
  96. }
  97. int
  98. ABHandler(struct mg_connection *conn, void *cbdata)
  99. {
  100. mg_printf(conn, "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n");
  101. mg_printf(conn, "<html><body>");
  102. mg_printf(conn, "<h2>This is the AB handler!!!</h2>");
  103. mg_printf(conn, "</body></html>\n");
  104. return 1;
  105. }
  106. int
  107. BXHandler(struct mg_connection *conn, void *cbdata)
  108. {
  109. /* Handler may access the request info using mg_get_request_info */
  110. const struct mg_request_info *req_info = mg_get_request_info(conn);
  111. mg_printf(conn, "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n");
  112. mg_printf(conn, "<html><body>");
  113. mg_printf(conn, "<h2>This is the BX handler %p!!!</h2>", cbdata);
  114. mg_printf(conn, "<p>The actual uri is %s</p>", req_info->uri);
  115. mg_printf(conn, "</body></html>\n");
  116. return 1;
  117. }
  118. int
  119. FooHandler(struct mg_connection *conn, void *cbdata)
  120. {
  121. /* Handler may access the request info using mg_get_request_info */
  122. const struct mg_request_info *req_info = mg_get_request_info(conn);
  123. mg_printf(conn, "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n");
  124. mg_printf(conn, "<html><body>");
  125. mg_printf(conn, "<h2>This is the Foo handler!!!</h2>");
  126. mg_printf(conn,
  127. "<p>The request was:<br><pre>%s %s HTTP/%s</pre></p>",
  128. req_info->request_method,
  129. req_info->uri,
  130. req_info->http_version);
  131. mg_printf(conn, "</body></html>\n");
  132. return 1;
  133. }
  134. int
  135. CloseHandler(struct mg_connection *conn, void *cbdata)
  136. {
  137. /* Handler may access the request info using mg_get_request_info */
  138. const struct mg_request_info *req_info = mg_get_request_info(conn);
  139. mg_printf(conn, "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n");
  140. mg_printf(conn, "<html><body>");
  141. mg_printf(conn,
  142. "<h2>This handler will close the connection in a second</h2>");
  143. #ifdef _WIN32
  144. Sleep(1000);
  145. #else
  146. sleep(1);
  147. #endif
  148. mg_printf(conn, "bye");
  149. printf("CloseHandler: close connection\n");
  150. mg_close_connection(conn);
  151. printf("CloseHandler: wait 10 sec\n");
  152. #ifdef _WIN32
  153. Sleep(10000);
  154. #else
  155. sleep(10);
  156. #endif
  157. printf("CloseHandler: return from function\n");
  158. return 1;
  159. }
  160. int
  161. FileHandler(struct mg_connection *conn, void *cbdata)
  162. {
  163. /* In this handler, we ignore the req_info and send the file "fileName". */
  164. const char *fileName = (const char *)cbdata;
  165. mg_send_file(conn, fileName);
  166. return 1;
  167. }
  168. int
  169. field_found(const char *key,
  170. const char *filename,
  171. char *path,
  172. size_t pathlen,
  173. void *user_data)
  174. {
  175. struct mg_connection *conn = (struct mg_connection *)user_data;
  176. mg_printf(conn, "\r\n\r\n%s:\r\n", key);
  177. if (filename && *filename) {
  178. #ifdef _WIN32
  179. _snprintf(path, pathlen, "D:\\tmp\\%s", filename);
  180. #else
  181. snprintf(path, pathlen, "/tmp/%s", filename);
  182. #endif
  183. return FORM_FIELD_STORAGE_STORE;
  184. }
  185. return FORM_FIELD_STORAGE_GET;
  186. }
  187. int
  188. field_get(const char *key, const char *value, size_t valuelen, void *user_data)
  189. {
  190. struct mg_connection *conn = (struct mg_connection *)user_data;
  191. if (key[0]) {
  192. mg_printf(conn, "%s = ", key);
  193. }
  194. mg_write(conn, value, valuelen);
  195. return 0;
  196. }
  197. int
  198. field_stored(const char *path, long long file_size, void *user_data)
  199. {
  200. struct mg_connection *conn = (struct mg_connection *)user_data;
  201. mg_printf(conn,
  202. "stored as %s (%lu bytes)\r\n\r\n",
  203. path,
  204. (unsigned long)file_size);
  205. return 0;
  206. }
  207. int
  208. FormHandler(struct mg_connection *conn, void *cbdata)
  209. {
  210. /* Handler may access the request info using mg_get_request_info */
  211. const struct mg_request_info *req_info = mg_get_request_info(conn);
  212. int ret;
  213. struct mg_form_data_handler fdh = {field_found, field_get, field_stored, 0};
  214. /* It would be possible to check the request info here before calling
  215. * mg_handle_form_request. */
  216. (void)req_info;
  217. mg_printf(conn, "HTTP/1.0 200 OK\r\nContent-Type: text/plain\r\n\r\n");
  218. fdh.user_data = (void *)conn;
  219. /* Call the form handler */
  220. mg_printf(conn, "Form data:");
  221. ret = mg_handle_form_request(conn, &fdh);
  222. mg_printf(conn, "\r\n%i fields found", ret);
  223. return 1;
  224. }
  225. int
  226. CookieHandler(struct mg_connection *conn, void *cbdata)
  227. {
  228. /* Handler may access the request info using mg_get_request_info */
  229. const struct mg_request_info *req_info = mg_get_request_info(conn);
  230. const char *cookie = mg_get_header(conn, "Cookie");
  231. char first_str[64], count_str[64];
  232. int count;
  233. (void)mg_get_cookie(cookie, "first", first_str, sizeof(first_str));
  234. (void)mg_get_cookie(cookie, "count", count_str, sizeof(count_str));
  235. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  236. if (first_str[0] == 0) {
  237. time_t t = time(0);
  238. struct tm *ptm = localtime(&t);
  239. mg_printf(conn,
  240. "Set-Cookie: first=%04i-%02i-%02iT%02i:%02i:%02i\r\n",
  241. ptm->tm_year + 1900,
  242. ptm->tm_mon + 1,
  243. ptm->tm_mday,
  244. ptm->tm_hour,
  245. ptm->tm_min,
  246. ptm->tm_sec);
  247. }
  248. count = (count_str[0] == 0) ? 0 : atoi(count_str);
  249. mg_printf(conn, "Set-Cookie: count=%i\r\n", count + 1);
  250. mg_printf(conn, "Content-Type: text/html\r\n\r\n");
  251. mg_printf(conn, "<html><body>");
  252. mg_printf(conn, "<h2>This is the CookieHandler.</h2>", cbdata);
  253. mg_printf(conn, "<p>The actual uri is %s</p>", req_info->uri);
  254. if (first_str[0] == 0) {
  255. mg_printf(conn, "<p>This is the first time, you opened this page</p>");
  256. } else {
  257. mg_printf(conn, "<p>You opened this page %i times before.</p>", count);
  258. mg_printf(conn, "<p>You first opened this page on %s.</p>", first_str);
  259. }
  260. mg_printf(conn, "</body></html>\n");
  261. return 1;
  262. }
  263. int
  264. WebSocketStartHandler(struct mg_connection *conn, void *cbdata)
  265. {
  266. mg_printf(conn, "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n");
  267. mg_printf(conn, "<!DOCTYPE html>\n");
  268. mg_printf(conn, "<html>\n<head>\n");
  269. mg_printf(conn, "<meta charset=\"UTF-8\">\n");
  270. mg_printf(conn, "<title>Embedded websocket example</title>\n");
  271. #ifdef USE_WEBSOCKET
  272. /* mg_printf(conn, "<script type=\"text/javascript\"><![CDATA[\n"); ...
  273. * xhtml style */
  274. mg_printf(conn, "<script>\n");
  275. mg_printf(
  276. conn,
  277. "function load() {\n"
  278. " var wsproto = (location.protocol === 'https:') ? 'wss:' : 'ws:';\n"
  279. " connection = new WebSocket(wsproto + '//' + window.location.host + "
  280. "'/websocket');\n"
  281. " websock_text_field = "
  282. "document.getElementById('websock_text_field');\n"
  283. " connection.onmessage = function (e) {\n"
  284. " websock_text_field.innerHTML=e.data;\n"
  285. " }\n"
  286. " connection.onerror = function (error) {\n"
  287. " alert('WebSocket error');\n"
  288. " connection.close();\n"
  289. " }\n"
  290. "}\n");
  291. /* mg_printf(conn, "]]></script>\n"); ... xhtml style */
  292. mg_printf(conn, "</script>\n");
  293. mg_printf(conn, "</head>\n<body onload=\"load()\">\n");
  294. mg_printf(
  295. conn,
  296. "<div id='websock_text_field'>No websocket connection yet</div>\n");
  297. #else
  298. mg_printf(conn, "</head>\n<body>\n");
  299. mg_printf(conn, "Example not compiled with USE_WEBSOCKET\n");
  300. #endif
  301. mg_printf(conn, "</body>\n</html>\n");
  302. return 1;
  303. }
  304. #ifdef USE_WEBSOCKET
  305. /* MAX_WS_CLIENTS defines how many clients can connect to a websocket at the
  306. * same time. The value 5 is very small and used here only for demonstration;
  307. * it can be easily tested to connect more than MAX_WS_CLIENTS clients.
  308. * A real server should use a much higher number, or better use a dynamic list
  309. * of currently connected websocket clients. */
  310. #define MAX_WS_CLIENTS (5)
  311. struct t_ws_client {
  312. struct mg_connection *conn;
  313. int state;
  314. } static ws_clients[MAX_WS_CLIENTS];
  315. #define ASSERT(x) \
  316. { \
  317. if (!(x)) { \
  318. fprintf(stderr, \
  319. "Assertion failed in line %u\n", \
  320. (unsigned)__LINE__); \
  321. } \
  322. }
  323. int
  324. WebSocketConnectHandler(const struct mg_connection *conn, void *cbdata)
  325. {
  326. struct mg_context *ctx = mg_get_context(conn);
  327. int reject = 1;
  328. int i;
  329. mg_lock_context(ctx);
  330. for (i = 0; i < MAX_WS_CLIENTS; i++) {
  331. if (ws_clients[i].conn == NULL) {
  332. ws_clients[i].conn = (struct mg_connection *)conn;
  333. ws_clients[i].state = 1;
  334. mg_set_user_connection_data(ws_clients[i].conn,
  335. (void *)(ws_clients + i));
  336. reject = 0;
  337. break;
  338. }
  339. }
  340. mg_unlock_context(ctx);
  341. fprintf(stdout,
  342. "Websocket client %s\r\n\r\n",
  343. (reject ? "rejected" : "accepted"));
  344. return reject;
  345. }
  346. void
  347. WebSocketReadyHandler(struct mg_connection *conn, void *cbdata)
  348. {
  349. const char *text = "Hello from the websocket ready handler";
  350. struct t_ws_client *client = mg_get_user_connection_data(conn);
  351. mg_websocket_write(conn, WEBSOCKET_OPCODE_TEXT, text, strlen(text));
  352. fprintf(stdout, "Greeting message sent to websocket client\r\n\r\n");
  353. ASSERT(client->conn == conn);
  354. ASSERT(client->state == 1);
  355. client->state = 2;
  356. }
  357. int
  358. WebsocketDataHandler(struct mg_connection *conn,
  359. int bits,
  360. char *data,
  361. size_t len,
  362. void *cbdata)
  363. {
  364. struct t_ws_client *client = mg_get_user_connection_data(conn);
  365. ASSERT(client->conn == conn);
  366. ASSERT(client->state >= 1);
  367. fprintf(stdout, "Websocket got data:\r\n");
  368. fwrite(data, len, 1, stdout);
  369. fprintf(stdout, "\r\n\r\n");
  370. return 1;
  371. }
  372. void
  373. WebSocketCloseHandler(const struct mg_connection *conn, void *cbdata)
  374. {
  375. struct mg_context *ctx = mg_get_context(conn);
  376. struct t_ws_client *client = mg_get_user_connection_data(conn);
  377. ASSERT(client->conn == conn);
  378. ASSERT(client->state >= 1);
  379. mg_lock_context(ctx);
  380. client->state = 0;
  381. client->conn = NULL;
  382. mg_unlock_context(ctx);
  383. fprintf(stdout,
  384. "Client droped from the set of webserver connections\r\n\r\n");
  385. }
  386. void
  387. InformWebsockets(struct mg_context *ctx)
  388. {
  389. static unsigned long cnt = 0;
  390. char text[32];
  391. int i;
  392. sprintf(text, "%lu", ++cnt);
  393. mg_lock_context(ctx);
  394. for (i = 0; i < MAX_WS_CLIENTS; i++) {
  395. if (ws_clients[i].state == 2) {
  396. mg_websocket_write(ws_clients[i].conn,
  397. WEBSOCKET_OPCODE_TEXT,
  398. text,
  399. strlen(text));
  400. }
  401. }
  402. mg_unlock_context(ctx);
  403. }
  404. #endif
  405. int
  406. main(int argc, char *argv[])
  407. {
  408. const char *options[] = {"document_root",
  409. DOCUMENT_ROOT,
  410. "listening_ports",
  411. PORT,
  412. "request_timeout_ms",
  413. "10000",
  414. "error_log_file",
  415. "error.log",
  416. #ifdef USE_WEBSOCKET
  417. "websocket_timeout_ms",
  418. "3600000",
  419. #endif
  420. #ifndef NO_SSL
  421. "ssl_certificate",
  422. "../../resources/cert/server.pem",
  423. #endif
  424. 0};
  425. struct mg_callbacks callbacks;
  426. struct mg_context *ctx;
  427. struct mg_server_ports ports[32];
  428. int port_cnt, n;
  429. int err = 0;
  430. /* Check if libcivetweb has been built with all required features. */
  431. #ifdef USE_IPV6
  432. if (!mg_check_feature(8)) {
  433. fprintf(stderr,
  434. "Error: Embedded example built with IPv6 support, "
  435. "but civetweb library build without.\n");
  436. err = 1;
  437. }
  438. #endif
  439. #ifdef USE_WEBSOCKET
  440. if (!mg_check_feature(16)) {
  441. fprintf(stderr,
  442. "Error: Embedded example built with websocket support, "
  443. "but civetweb library build without.\n");
  444. err = 1;
  445. }
  446. #endif
  447. #ifndef NO_SSL
  448. if (!mg_check_feature(2)) {
  449. fprintf(stderr,
  450. "Error: Embedded example built with SSL support, "
  451. "but civetweb library build without.\n");
  452. err = 1;
  453. }
  454. #endif
  455. if (err) {
  456. fprintf(stderr, "Cannot start CivetWeb - inconsistent build.\n");
  457. return EXIT_FAILURE;
  458. }
  459. /* Start CivetWeb web server */
  460. memset(&callbacks, 0, sizeof(callbacks));
  461. ctx = mg_start(&callbacks, 0, options);
  462. /* Add handler EXAMPLE_URI, to explain the example */
  463. mg_set_request_handler(ctx, EXAMPLE_URI, ExampleHandler, 0);
  464. mg_set_request_handler(ctx, EXIT_URI, ExitHandler, 0);
  465. /* Add handler for /A* and special handler for /A/B */
  466. mg_set_request_handler(ctx, "/A", AHandler, 0);
  467. mg_set_request_handler(ctx, "/A/B", ABHandler, 0);
  468. /* Add handler for /B, /B/A, /B/B but not for /B* */
  469. mg_set_request_handler(ctx, "/B$", BXHandler, (void *)0);
  470. mg_set_request_handler(ctx, "/B/A$", BXHandler, (void *)1);
  471. mg_set_request_handler(ctx, "/B/B$", BXHandler, (void *)2);
  472. /* Add handler for all files with .foo extention */
  473. mg_set_request_handler(ctx, "**.foo$", FooHandler, 0);
  474. /* Add handler for /close extention */
  475. mg_set_request_handler(ctx, "/close", CloseHandler, 0);
  476. /* Add handler for /form (serve a file outside the document root) */
  477. mg_set_request_handler(ctx,
  478. "/form",
  479. FileHandler,
  480. (void *)"../../test/form.html");
  481. /* Add handler for form data */
  482. mg_set_request_handler(ctx,
  483. "/handle_form.embedded_c.example.callback",
  484. FormHandler,
  485. (void *)0);
  486. /* Add handler for /cookie example */
  487. mg_set_request_handler(ctx, "/cookie", CookieHandler, 0);
  488. /* Add HTTP site to open a websocket connection */
  489. mg_set_request_handler(ctx, "/websocket", WebSocketStartHandler, 0);
  490. #ifdef USE_WEBSOCKET
  491. /* WS site for the websocket connection */
  492. mg_set_websocket_handler(ctx,
  493. "/websocket",
  494. WebSocketConnectHandler,
  495. WebSocketReadyHandler,
  496. WebsocketDataHandler,
  497. WebSocketCloseHandler,
  498. 0);
  499. #endif
  500. /* List all listening ports */
  501. memset(ports, 0, sizeof(ports));
  502. port_cnt = mg_get_server_ports(ctx, 32, ports);
  503. printf("\n%i listening ports:\n\n", port_cnt);
  504. for (n = 0; n < port_cnt && n < 32; n++) {
  505. const char *proto = ports[n].is_ssl ? "https" : "http";
  506. const char *host;
  507. if ((ports[n].protocol & 1) == 1) {
  508. /* IPv4 */
  509. host = "127.0.0.1";
  510. printf("Browse files at %s://%s:%i/\n", proto, host, ports[n].port);
  511. printf("Run example at %s://%s:%i%s\n",
  512. proto,
  513. host,
  514. ports[n].port,
  515. EXAMPLE_URI);
  516. printf(
  517. "Exit at %s://%s:%i%s\n", proto, host, ports[n].port, EXIT_URI);
  518. printf("\n");
  519. }
  520. if ((ports[n].protocol & 2) == 2) {
  521. /* IPv6 */
  522. host = "[::1]";
  523. printf("Browse files at %s://%s:%i/\n", proto, host, ports[n].port);
  524. printf("Run example at %s://%s:%i%s\n",
  525. proto,
  526. host,
  527. ports[n].port,
  528. EXAMPLE_URI);
  529. printf(
  530. "Exit at %s://%s:%i%s\n", proto, host, ports[n].port, EXIT_URI);
  531. printf("\n");
  532. }
  533. }
  534. /* Wait until the server should be closed */
  535. while (!exitNow) {
  536. #ifdef _WIN32
  537. Sleep(1000);
  538. #else
  539. sleep(1);
  540. #endif
  541. #ifdef USE_WEBSOCKET
  542. InformWebsockets(ctx);
  543. #endif
  544. }
  545. /* Stop the server */
  546. mg_stop(ctx);
  547. printf("Server stopped.\n");
  548. printf("Bye!\n");
  549. return EXIT_SUCCESS;
  550. }