embedded_c.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  1. /*
  2. * Copyright (c) 2013-2015 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"
  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. #ifdef USE_WEBSOCKET
  60. mg_printf(conn,
  61. "<p>To test websocket handler <a href=\"/websocket\">click "
  62. "websocket</a></p>");
  63. #endif
  64. mg_printf(conn, "<p>To exit <a href=\"%s\">click exit</a></p>", EXIT_URI);
  65. mg_printf(conn, "</body></html>\n");
  66. return 1;
  67. }
  68. int
  69. ExitHandler(struct mg_connection *conn, void *cbdata)
  70. {
  71. mg_printf(conn, "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\n");
  72. mg_printf(conn, "Server will shut down.\n");
  73. mg_printf(conn, "Bye!\n");
  74. exitNow = 1;
  75. return 1;
  76. }
  77. int
  78. AHandler(struct mg_connection *conn, void *cbdata)
  79. {
  80. mg_printf(conn, "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n");
  81. mg_printf(conn, "<html><body>");
  82. mg_printf(conn, "<h2>This is the A handler!!!</h2>");
  83. mg_printf(conn, "</body></html>\n");
  84. return 1;
  85. }
  86. int
  87. ABHandler(struct mg_connection *conn, void *cbdata)
  88. {
  89. mg_printf(conn, "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n");
  90. mg_printf(conn, "<html><body>");
  91. mg_printf(conn, "<h2>This is the AB handler!!!</h2>");
  92. mg_printf(conn, "</body></html>\n");
  93. return 1;
  94. }
  95. int
  96. BXHandler(struct mg_connection *conn, void *cbdata)
  97. {
  98. /* Handler may access the request info using mg_get_request_info */
  99. const struct mg_request_info *req_info = mg_get_request_info(conn);
  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 BX handler %p!!!</h2>", cbdata);
  103. mg_printf(conn, "<p>The actual uri is %s</p>", req_info->uri);
  104. mg_printf(conn, "</body></html>\n");
  105. return 1;
  106. }
  107. int
  108. FooHandler(struct mg_connection *conn, void *cbdata)
  109. {
  110. /* Handler may access the request info using mg_get_request_info */
  111. const struct mg_request_info *req_info = mg_get_request_info(conn);
  112. mg_printf(conn, "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n");
  113. mg_printf(conn, "<html><body>");
  114. mg_printf(conn, "<h2>This is the Foo handler!!!</h2>");
  115. mg_printf(conn,
  116. "<p>The request was:<br><pre>%s %s HTTP/%s</pre></p>",
  117. req_info->request_method,
  118. req_info->uri,
  119. req_info->http_version);
  120. mg_printf(conn, "</body></html>\n");
  121. return 1;
  122. }
  123. int
  124. WebSocketStartHandler(struct mg_connection *conn, void *cbdata)
  125. {
  126. mg_printf(conn, "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n");
  127. mg_printf(conn, "<!DOCTYPE html>\n");
  128. mg_printf(conn, "<html>\n<head>\n");
  129. mg_printf(conn, "<meta charset=\"UTF-8\">\n");
  130. mg_printf(conn, "<title>Embedded websocket example</title>\n");
  131. #ifdef USE_WEBSOCKET
  132. /* mg_printf(conn, "<script type=\"text/javascript\"><![CDATA[\n"); ...
  133. * xhtml style */
  134. mg_printf(conn, "<script>\n");
  135. mg_printf(
  136. conn,
  137. "function load() {\n"
  138. " var wsproto = (location.protocol === 'https:') ? 'wss:' : 'ws:';\n"
  139. " connection = new WebSocket(wsproto + '//' + window.location.host + "
  140. "'/websocket');\n"
  141. " websock_text_field = "
  142. "document.getElementById('websock_text_field');\n"
  143. " connection.onmessage = function (e) {\n"
  144. " websock_text_field.innerHTML=e.data;\n"
  145. " }\n"
  146. " connection.onerror = function (error) {\n"
  147. " alert('WebSocket error');\n"
  148. " connection.close();\n"
  149. " }\n"
  150. "}\n");
  151. /* mg_printf(conn, "]]></script>\n"); ... xhtml style */
  152. mg_printf(conn, "</script>\n");
  153. mg_printf(conn, "</head>\n<body onload=\"load()\">\n");
  154. mg_printf(
  155. conn,
  156. "<div id='websock_text_field'>No websocket connection yet</div>\n");
  157. #else
  158. mg_printf(conn, "</head>\n<body>\n");
  159. mg_printf(conn, "Example not compiled with USE_WEBSOCKET\n");
  160. #endif
  161. mg_printf(conn, "</body>\n</html>\n");
  162. return 1;
  163. }
  164. #ifdef USE_WEBSOCKET
  165. /* MAX_WS_CLIENTS defines how many clients can connect to a websocket at the
  166. * same time. The value 5 is very small and used here only for demonstration;
  167. * it can be easily tested to connect more than MAX_WS_CLIENTS clients.
  168. * A real server should use a much higher number, or better use a dynamic list
  169. * of currently connected websocket clients. */
  170. #define MAX_WS_CLIENTS (5)
  171. struct t_ws_client {
  172. struct mg_connection *conn;
  173. int state;
  174. } static ws_clients[MAX_WS_CLIENTS];
  175. #define ASSERT(x) \
  176. { \
  177. if (!(x)) { \
  178. fprintf(stderr, \
  179. "Assertion failed in line %u\n", \
  180. (unsigned)__LINE__); \
  181. } \
  182. }
  183. int
  184. WebSocketConnectHandler(const struct mg_connection *conn, void *cbdata)
  185. {
  186. struct mg_context *ctx = mg_get_context(conn);
  187. int reject = 1;
  188. int i;
  189. mg_lock_context(ctx);
  190. for (i = 0; i < MAX_WS_CLIENTS; i++) {
  191. if (ws_clients[i].conn == NULL) {
  192. ws_clients[i].conn = (struct mg_connection *)conn;
  193. ws_clients[i].state = 1;
  194. mg_set_user_connection_data(conn, (void *)(ws_clients + i));
  195. reject = 0;
  196. break;
  197. }
  198. }
  199. mg_unlock_context(ctx);
  200. fprintf(stdout,
  201. "Websocket client %s\r\n\r\n",
  202. (reject ? "rejected" : "accepted"));
  203. return reject;
  204. }
  205. void
  206. WebSocketReadyHandler(struct mg_connection *conn, void *cbdata)
  207. {
  208. const char *text = "Hello from the websocket ready handler";
  209. struct t_ws_client *client = mg_get_user_connection_data(conn);
  210. mg_websocket_write(conn, WEBSOCKET_OPCODE_TEXT, text, strlen(text));
  211. fprintf(stdout, "Greeting message sent to websocket client\r\n\r\n");
  212. ASSERT(client->conn == conn);
  213. ASSERT(client->state == 1);
  214. client->state = 2;
  215. }
  216. int
  217. WebsocketDataHandler(struct mg_connection *conn,
  218. int bits,
  219. char *data,
  220. size_t len,
  221. void *cbdata)
  222. {
  223. struct t_ws_client *client = mg_get_user_connection_data(conn);
  224. ASSERT(client->conn == conn);
  225. ASSERT(client->state >= 1);
  226. fprintf(stdout, "Websocket got data:\r\n");
  227. fwrite(data, len, 1, stdout);
  228. fprintf(stdout, "\r\n\r\n");
  229. return 1;
  230. }
  231. void
  232. WebSocketCloseHandler(const struct mg_connection *conn, void *cbdata)
  233. {
  234. struct mg_context *ctx = mg_get_context(conn);
  235. struct t_ws_client *client = mg_get_user_connection_data(conn);
  236. ASSERT(client->conn == conn);
  237. ASSERT(client->state >= 1);
  238. mg_lock_context(ctx);
  239. client->state = 0;
  240. client->conn = NULL;
  241. mg_unlock_context(ctx);
  242. fprintf(stdout,
  243. "Client droped from the set of webserver connections\r\n\r\n");
  244. }
  245. void
  246. InformWebsockets(struct mg_context *ctx)
  247. {
  248. static unsigned long cnt = 0;
  249. char text[32];
  250. int i;
  251. sprintf(text, "%lu", ++cnt);
  252. mg_lock_context(ctx);
  253. for (i = 0; i < MAX_WS_CLIENTS; i++) {
  254. if (ws_clients[i].state == 2) {
  255. mg_websocket_write(ws_clients[i].conn,
  256. WEBSOCKET_OPCODE_TEXT,
  257. text,
  258. strlen(text));
  259. }
  260. }
  261. mg_unlock_context(ctx);
  262. }
  263. #endif
  264. int
  265. main(int argc, char *argv[])
  266. {
  267. const char *options[] = {"document_root",
  268. DOCUMENT_ROOT,
  269. "listening_ports",
  270. PORT,
  271. "request_timeout_ms",
  272. "10000",
  273. "error_log_file",
  274. "error.log",
  275. #ifdef USE_WEBSOCKET
  276. "websocket_timeout_ms",
  277. "3600000",
  278. #endif
  279. #ifndef NO_SSL
  280. "ssl_certificate",
  281. "../../resources/cert/server.pem",
  282. #endif
  283. 0};
  284. struct mg_callbacks callbacks;
  285. struct mg_context *ctx;
  286. struct mg_server_ports ports[32];
  287. int port_cnt, n;
  288. int err = 0;
  289. /* Check if libcivetweb has been built with all required features. */
  290. #ifdef USE_IPV6
  291. if (!mg_check_feature(8)) {
  292. fprintf(stderr,
  293. "Error: Embedded example built with websocket support, "
  294. "but civetweb library build without.\n");
  295. err = 1;
  296. }
  297. #endif
  298. #ifdef USE_WEBSOCKET
  299. if (!mg_check_feature(16)) {
  300. fprintf(stderr,
  301. "Error: Embedded example built with websocket support, "
  302. "but civetweb library build without.\n");
  303. err = 1;
  304. }
  305. #endif
  306. #ifndef NO_SSL
  307. if (!mg_check_feature(2)) {
  308. fprintf(stderr,
  309. "Error: Embedded example built with SSL support, "
  310. "but civetweb library build without.\n");
  311. err = 1;
  312. }
  313. #endif
  314. if (err) {
  315. fprintf(stderr, "Cannot start CivetWeb - inconsistent build.\n");
  316. return EXIT_FAILURE;
  317. }
  318. /* Start CivetWeb web server */
  319. memset(&callbacks, 0, sizeof(callbacks));
  320. ctx = mg_start(&callbacks, 0, options);
  321. /* Add handler EXAMPLE_URI, to explain the example */
  322. mg_set_request_handler(ctx, EXAMPLE_URI, ExampleHandler, 0);
  323. mg_set_request_handler(ctx, EXIT_URI, ExitHandler, 0);
  324. /* Add handler for /A* and special handler for /A/B */
  325. mg_set_request_handler(ctx, "/A", AHandler, 0);
  326. mg_set_request_handler(ctx, "/A/B", ABHandler, 0);
  327. /* Add handler for /B, /B/A, /B/B but not for /B* */
  328. mg_set_request_handler(ctx, "/B$", BXHandler, (void *)0);
  329. mg_set_request_handler(ctx, "/B/A$", BXHandler, (void *)1);
  330. mg_set_request_handler(ctx, "/B/B$", BXHandler, (void *)2);
  331. /* Add handler for all files with .foo extention */
  332. mg_set_request_handler(ctx, "**.foo$", FooHandler, 0);
  333. /* Add HTTP site to open a websocket connection */
  334. mg_set_request_handler(ctx, "/websocket", WebSocketStartHandler, 0);
  335. #ifdef USE_WEBSOCKET
  336. /* WS site for the websocket connection */
  337. mg_set_websocket_handler(ctx,
  338. "/websocket",
  339. WebSocketConnectHandler,
  340. WebSocketReadyHandler,
  341. WebsocketDataHandler,
  342. WebSocketCloseHandler,
  343. 0);
  344. #endif
  345. /* List all listening ports */
  346. memset(ports, 0, sizeof(ports));
  347. port_cnt = mg_get_server_ports(ctx, 32, ports);
  348. printf("\n%i listening ports:\n\n", port_cnt);
  349. for (n = 0; n < port_cnt && n < 32; n++) {
  350. const char *proto = ports[n].is_ssl ? "https" : "http";
  351. const char *host;
  352. if ((ports[n].protocol & 1) == 1) {
  353. /* IPv4 */
  354. host = "127.0.0.1";
  355. printf("Browse files at %s://%s:%i/\n", proto, host, ports[n].port);
  356. printf("Run example at %s://%s:%i%s\n",
  357. proto,
  358. host,
  359. ports[n].port,
  360. EXAMPLE_URI);
  361. printf(
  362. "Exit at %s://%s:%i%s\n", proto, host, ports[n].port, EXIT_URI);
  363. printf("\n");
  364. }
  365. if ((ports[n].protocol & 2) == 2) {
  366. /* IPv6 */
  367. host = "[::1]";
  368. printf("Browse files at %s://%s:%i/\n", proto, host, ports[n].port);
  369. printf("Run example at %s://%s:%i%s\n",
  370. proto,
  371. host,
  372. ports[n].port,
  373. EXAMPLE_URI);
  374. printf(
  375. "Exit at %s://%s:%i%s\n", proto, host, ports[n].port, EXIT_URI);
  376. printf("\n");
  377. }
  378. }
  379. /* Wait until the server should be closed */
  380. while (!exitNow) {
  381. #ifdef _WIN32
  382. Sleep(1000);
  383. #else
  384. sleep(1);
  385. #endif
  386. #ifdef USE_WEBSOCKET
  387. InformWebsockets(ctx);
  388. #endif
  389. }
  390. /* Stop the server */
  391. mg_stop(ctx);
  392. printf("Server stopped.\n");
  393. printf("Bye!\n");
  394. return EXIT_SUCCESS;
  395. }