embedded_c.c 15 KB

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