embedded_c.c 16 KB

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