embedded_c.c 16 KB

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