embedded_c.c 16 KB

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