embedded_c.c 15 KB

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