embedded_c.c 12 KB

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