embedded_c.c 14 KB

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