embedded_c.c 16 KB

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