embedded_c.c 11 KB

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