fork-echoserv.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. /*
  2. * Wslay - The WebSocket Library
  3. *
  4. * Copyright (c) 2011, 2012 Tatsuhiro Tsujikawa
  5. *
  6. * Permission is hereby granted, free of charge, to any person obtaining
  7. * a copy of this software and associated documentation files (the
  8. * "Software"), to deal in the Software without restriction, including
  9. * without limitation the rights to use, copy, modify, merge, publish,
  10. * distribute, sublicense, and/or sell copies of the Software, and to
  11. * permit persons to whom the Software is furnished to do so, subject to
  12. * the following conditions:
  13. *
  14. * The above copyright notice and this permission notice shall be
  15. * included in all copies or substantial portions of the Software.
  16. *
  17. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  18. * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  19. * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  20. * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  21. * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  22. * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  23. * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  24. */
  25. /*
  26. * WebSocket Echo Server
  27. * This is suitable for Autobahn server test.
  28. *
  29. * Dependency: nettle-dev
  30. *
  31. * To compile:
  32. * $ gcc -Wall -O2 -g -o fork-echoserv fork-echoserv.c -L../lib/.libs -I../lib/includes -lwslay -lnettle
  33. *
  34. * To run:
  35. * $ export LD_LIBRARY_PATH=../lib/.libs
  36. * $ ./a.out 9000
  37. */
  38. #include <sys/types.h>
  39. #include <sys/socket.h>
  40. #include <netdb.h>
  41. #include <unistd.h>
  42. #include <fcntl.h>
  43. #include <poll.h>
  44. #include <netinet/in.h>
  45. #include <netinet/tcp.h>
  46. #include <signal.h>
  47. #include <assert.h>
  48. #include <stdio.h>
  49. #include <errno.h>
  50. #include <stdlib.h>
  51. #include <string.h>
  52. #include <ctype.h>
  53. #include <nettle/base64.h>
  54. #include <nettle/sha.h>
  55. #include <wslay/wslay.h>
  56. /*
  57. * Create server socket, listen on *service*. This function returns
  58. * file descriptor of server socket if it succeeds, or returns -1.
  59. */
  60. static int create_listen_socket(const char *service) {
  61. struct addrinfo hints, *res, *rp;
  62. int sfd = -1;
  63. int r;
  64. memset(&hints, 0, sizeof(struct addrinfo));
  65. hints.ai_family = AF_UNSPEC;
  66. hints.ai_socktype = SOCK_STREAM;
  67. hints.ai_flags = AI_PASSIVE | AI_ADDRCONFIG;
  68. r = getaddrinfo(0, service, &hints, &res);
  69. if (r != 0) {
  70. fprintf(stderr, "getaddrinfo: %s", gai_strerror(r));
  71. return -1;
  72. }
  73. for (rp = res; rp; rp = rp->ai_next) {
  74. int val = 1;
  75. sfd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  76. if (sfd == -1) {
  77. continue;
  78. }
  79. if (setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &val,
  80. (socklen_t)sizeof(val)) == -1) {
  81. continue;
  82. }
  83. if (bind(sfd, rp->ai_addr, rp->ai_addrlen) == 0) {
  84. break;
  85. }
  86. close(sfd);
  87. }
  88. freeaddrinfo(res);
  89. if (listen(sfd, 16) == -1) {
  90. perror("listen");
  91. close(sfd);
  92. return -1;
  93. }
  94. return sfd;
  95. }
  96. /*
  97. * Makes file descriptor *fd* non-blocking mode.
  98. * This function returns 0, or returns -1.
  99. */
  100. static int make_non_block(int fd) {
  101. int flags, r;
  102. while ((flags = fcntl(fd, F_GETFL, 0)) == -1 && errno == EINTR)
  103. ;
  104. if (flags == -1) {
  105. perror("fcntl");
  106. return -1;
  107. }
  108. while ((r = fcntl(fd, F_SETFL, flags | O_NONBLOCK)) == -1 && errno == EINTR)
  109. ;
  110. if (r == -1) {
  111. perror("fcntl");
  112. return -1;
  113. }
  114. return 0;
  115. }
  116. /*
  117. * Calculates SHA-1 hash of *src*. The size of *src* is *src_length* bytes.
  118. * *dst* must be at least SHA1_DIGEST_SIZE.
  119. */
  120. static void sha1(uint8_t *dst, const uint8_t *src, size_t src_length) {
  121. struct sha1_ctx ctx;
  122. sha1_init(&ctx);
  123. sha1_update(&ctx, src_length, src);
  124. sha1_digest(&ctx, SHA1_DIGEST_SIZE, dst);
  125. }
  126. /*
  127. * Base64-encode *src* and stores it in *dst*.
  128. * The size of *src* is *src_length*.
  129. * *dst* must be at least BASE64_ENCODE_RAW_LENGTH(src_length).
  130. */
  131. static void base64(uint8_t *dst, const uint8_t *src, size_t src_length) {
  132. struct base64_encode_ctx ctx;
  133. base64_encode_init(&ctx);
  134. base64_encode_raw((char *)dst, src_length, src);
  135. }
  136. #define WS_GUID "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
  137. /*
  138. * Create Server's accept key in *dst*.
  139. * *client_key* is the value of |Sec-WebSocket-Key| header field in
  140. * client's handshake and it must be length of 24.
  141. * *dst* must be at least BASE64_ENCODE_RAW_LENGTH(20)+1.
  142. */
  143. static void create_accept_key(char *dst, const char *client_key) {
  144. uint8_t sha1buf[20], key_src[60];
  145. memcpy(key_src, client_key, 24);
  146. memcpy(key_src + 24, WS_GUID, 36);
  147. sha1(sha1buf, key_src, sizeof(key_src));
  148. base64((uint8_t *)dst, sha1buf, 20);
  149. dst[BASE64_ENCODE_RAW_LENGTH(20)] = '\0';
  150. }
  151. /* We parse HTTP header lines of the format
  152. * \r\nfield_name: value1, value2, ... \r\n
  153. *
  154. * If the caller is looking for a specific value, we return a pointer to the
  155. * start of that value, else we simply return the start of values list.
  156. */
  157. static const char *http_header_find_field_value(const char *header,
  158. const char *field_name,
  159. const char *value) {
  160. const char *header_end, *field_start, *field_end, *next_crlf, *value_start;
  161. int field_name_len;
  162. /* Pointer to the last character in the header */
  163. header_end = header + strlen(header) - 1;
  164. field_name_len = (int)strlen(field_name);
  165. field_start = header;
  166. do {
  167. field_start = strstr(field_start + 1, field_name);
  168. field_end = field_start + field_name_len - 1;
  169. if (field_start != NULL && field_start - header >= 2 &&
  170. field_start[-2] == '\r' && field_start[-1] == '\n' &&
  171. header_end - field_end >= 1 && field_end[1] == ':') {
  172. break; /* Found the field */
  173. } else {
  174. continue; /* This is not the one; keep looking. */
  175. }
  176. } while (field_start != NULL);
  177. if (field_start == NULL)
  178. return NULL;
  179. /* Find the field terminator */
  180. next_crlf = strstr(field_start, "\r\n");
  181. /* A field is expected to end with \r\n */
  182. if (next_crlf == NULL)
  183. return NULL; /* Malformed HTTP header! */
  184. /* If not looking for a value, then return a pointer to the start of values string */
  185. if (value == NULL)
  186. return field_end + 2;
  187. value_start = strstr(field_start, value);
  188. /* Value not found */
  189. if (value_start == NULL)
  190. return NULL;
  191. /* Found the value we're looking for */
  192. if (value_start > next_crlf)
  193. return NULL; /* ... but after the CRLF terminator of the field. */
  194. /* The value we found should be properly delineated from the other tokens */
  195. if (isalnum(value_start[-1]) || isalnum(value_start[strlen(value)]))
  196. return NULL;
  197. return value_start;
  198. }
  199. /*
  200. * Performs HTTP handshake. *fd* is the file descriptor of the
  201. * connection to the client. This function returns 0 if it succeeds,
  202. * or returns -1.
  203. */
  204. static int http_handshake(int fd) {
  205. /*
  206. * Note: The implementation of HTTP handshake in this function is
  207. * written for just a example of how to use of wslay library and is
  208. * not meant to be used in production code. In practice, you need
  209. * to do more strict verification of the client's handshake.
  210. */
  211. char header[16384], accept_key[29], res_header[256];
  212. const char *keyhdstart, *keyhdend;
  213. size_t header_length = 0, res_header_sent = 0, res_header_length;
  214. ssize_t r;
  215. while (1) {
  216. while ((r = read(fd, header + header_length,
  217. sizeof(header) - header_length)) == -1 &&
  218. errno == EINTR)
  219. ;
  220. if (r == -1) {
  221. perror("read");
  222. return -1;
  223. } else if (r == 0) {
  224. fprintf(stderr, "HTTP Handshake: Got EOF");
  225. return -1;
  226. } else {
  227. header_length += (size_t)r;
  228. if (header_length >= 4 &&
  229. memcmp(header + header_length - 4, "\r\n\r\n", 4) == 0) {
  230. break;
  231. } else if (header_length == sizeof(header)) {
  232. fprintf(stderr, "HTTP Handshake: Too large HTTP headers");
  233. return -1;
  234. }
  235. }
  236. }
  237. if (http_header_find_field_value(header, "Upgrade", "websocket") == NULL ||
  238. http_header_find_field_value(header, "Connection", "Upgrade") == NULL ||
  239. (keyhdstart = http_header_find_field_value(header, "Sec-WebSocket-Key",
  240. NULL)) == NULL) {
  241. fprintf(stderr, "HTTP Handshake: Missing required header fields");
  242. return -1;
  243. }
  244. for (; *keyhdstart == ' '; ++keyhdstart)
  245. ;
  246. keyhdend = keyhdstart;
  247. for (; *keyhdend != '\r' && *keyhdend != ' '; ++keyhdend)
  248. ;
  249. if (keyhdend - keyhdstart != 24) {
  250. printf("%s\n", keyhdstart);
  251. fprintf(stderr, "HTTP Handshake: Invalid value in Sec-WebSocket-Key");
  252. return -1;
  253. }
  254. create_accept_key(accept_key, keyhdstart);
  255. snprintf(res_header, sizeof(res_header),
  256. "HTTP/1.1 101 Switching Protocols\r\n"
  257. "Upgrade: websocket\r\n"
  258. "Connection: Upgrade\r\n"
  259. "Sec-WebSocket-Accept: %s\r\n"
  260. "\r\n",
  261. accept_key);
  262. res_header_length = strlen(res_header);
  263. while (res_header_sent < res_header_length) {
  264. while ((r = write(fd, res_header + res_header_sent,
  265. res_header_length - res_header_sent)) == -1 &&
  266. errno == EINTR)
  267. ;
  268. if (r == -1) {
  269. perror("write");
  270. return -1;
  271. } else {
  272. res_header_sent += (size_t)r;
  273. }
  274. }
  275. return 0;
  276. }
  277. /*
  278. * This struct is passed as *user_data* in callback function. The
  279. * *fd* member is the file descriptor of the connection to the client.
  280. */
  281. struct Session {
  282. int fd;
  283. };
  284. static ssize_t send_callback(wslay_event_context_ptr ctx, const uint8_t *data,
  285. size_t len, int flags, void *user_data) {
  286. struct Session *session = (struct Session *)user_data;
  287. ssize_t r;
  288. int sflags = 0;
  289. #ifdef MSG_MORE
  290. if (flags & WSLAY_MSG_MORE) {
  291. sflags |= MSG_MORE;
  292. }
  293. #endif // MSG_MORE
  294. while ((r = send(session->fd, data, len, sflags)) == -1 && errno == EINTR)
  295. ;
  296. if (r == -1) {
  297. if (errno == EAGAIN || errno == EWOULDBLOCK) {
  298. wslay_event_set_error(ctx, WSLAY_ERR_WOULDBLOCK);
  299. } else {
  300. wslay_event_set_error(ctx, WSLAY_ERR_CALLBACK_FAILURE);
  301. }
  302. }
  303. return r;
  304. }
  305. static ssize_t recv_callback(wslay_event_context_ptr ctx, uint8_t *buf,
  306. size_t len, int flags, void *user_data) {
  307. struct Session *session = (struct Session *)user_data;
  308. ssize_t r;
  309. (void)flags;
  310. while ((r = recv(session->fd, buf, len, 0)) == -1 && errno == EINTR)
  311. ;
  312. if (r == -1) {
  313. if (errno == EAGAIN || errno == EWOULDBLOCK) {
  314. wslay_event_set_error(ctx, WSLAY_ERR_WOULDBLOCK);
  315. } else {
  316. wslay_event_set_error(ctx, WSLAY_ERR_CALLBACK_FAILURE);
  317. }
  318. } else if (r == 0) {
  319. /* Unexpected EOF is also treated as an error */
  320. wslay_event_set_error(ctx, WSLAY_ERR_CALLBACK_FAILURE);
  321. r = -1;
  322. }
  323. return r;
  324. }
  325. static void on_msg_recv_callback(wslay_event_context_ptr ctx,
  326. const struct wslay_event_on_msg_recv_arg *arg,
  327. void *user_data) {
  328. (void)user_data;
  329. /* Echo back non-control message */
  330. if (!wslay_is_ctrl_frame(arg->opcode)) {
  331. struct wslay_event_msg msgarg = {arg->opcode, arg->msg, arg->msg_length};
  332. wslay_event_queue_msg(ctx, &msgarg);
  333. }
  334. }
  335. /*
  336. * Communicate with the client. This function performs HTTP handshake
  337. * and WebSocket data transfer until close handshake is done or an
  338. * error occurs. *fd* is the file descriptor of the connection to the
  339. * client. This function returns 0 if it succeeds, or returns 0.
  340. */
  341. static int communicate(int fd) {
  342. wslay_event_context_ptr ctx;
  343. struct wslay_event_callbacks callbacks = {
  344. recv_callback, send_callback, NULL, NULL, NULL,
  345. NULL, on_msg_recv_callback};
  346. struct Session session = {fd};
  347. int val = 1;
  348. struct pollfd event;
  349. int res = 0;
  350. if (http_handshake(fd) == -1) {
  351. return -1;
  352. }
  353. if (make_non_block(fd) == -1) {
  354. return -1;
  355. }
  356. if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &val, (socklen_t)sizeof(val)) ==
  357. -1) {
  358. perror("setsockopt: TCP_NODELAY");
  359. return -1;
  360. }
  361. memset(&event, 0, sizeof(struct pollfd));
  362. event.fd = fd;
  363. event.events = POLLIN;
  364. wslay_event_context_server_init(&ctx, &callbacks, &session);
  365. /*
  366. * Event loop: basically loop until both wslay_event_want_read(ctx)
  367. * and wslay_event_want_write(ctx) return 0.
  368. */
  369. while (wslay_event_want_read(ctx) || wslay_event_want_write(ctx)) {
  370. int r;
  371. while ((r = poll(&event, 1, -1)) == -1 && errno == EINTR)
  372. ;
  373. if (r == -1) {
  374. perror("poll");
  375. res = -1;
  376. break;
  377. }
  378. if (((event.revents & POLLIN) && wslay_event_recv(ctx) != 0) ||
  379. ((event.revents & POLLOUT) && wslay_event_send(ctx) != 0) ||
  380. (event.revents & (POLLERR | POLLHUP | POLLNVAL))) {
  381. /*
  382. * If either wslay_event_recv() or wslay_event_send() return
  383. * non-zero value, it means serious error which prevents wslay
  384. * library from processing further data, so WebSocket connection
  385. * must be closed.
  386. */
  387. res = -1;
  388. break;
  389. }
  390. event.events = 0;
  391. if (wslay_event_want_read(ctx)) {
  392. event.events |= POLLIN;
  393. }
  394. if (wslay_event_want_write(ctx)) {
  395. event.events |= POLLOUT;
  396. }
  397. }
  398. return res;
  399. }
  400. /*
  401. * Serves echo back service forever. *sfd* is the file descriptor of
  402. * the server socket. when the incoming connection from the client is
  403. * accepted, this function forks another process and the forked
  404. * process communicates with client. The parent process goes back to
  405. * the loop and can accept another client.
  406. */
  407. static void __attribute__((noreturn)) serve(int sfd) {
  408. while (1) {
  409. int fd;
  410. while ((fd = accept(sfd, NULL, NULL)) == -1 && errno == EINTR)
  411. ;
  412. if (fd == -1) {
  413. perror("accept");
  414. } else {
  415. int r = fork();
  416. if (r == -1) {
  417. perror("fork");
  418. close(fd);
  419. } else if (r == 0) {
  420. r = communicate(fd);
  421. shutdown(fd, SHUT_WR);
  422. close(fd);
  423. if (r == 0) {
  424. exit(EXIT_SUCCESS);
  425. } else {
  426. exit(EXIT_FAILURE);
  427. }
  428. }
  429. }
  430. }
  431. }
  432. int main(int argc, char **argv) {
  433. struct sigaction act;
  434. int sfd;
  435. if (argc < 2) {
  436. fprintf(stderr, "Usage: %s PORT\n", argv[0]);
  437. exit(EXIT_FAILURE);
  438. }
  439. memset(&act, 0, sizeof(struct sigaction));
  440. act.sa_handler = SIG_IGN;
  441. sigaction(SIGPIPE, &act, NULL);
  442. sigaction(SIGCHLD, &act, NULL);
  443. sfd = create_listen_socket(argv[1]);
  444. if (sfd == -1) {
  445. fprintf(stderr, "Failed to create server socket\n");
  446. exit(EXIT_FAILURE);
  447. }
  448. printf("WebSocket echo server, listening on %s\n", argv[1]);
  449. serve(sfd);
  450. return EXIT_SUCCESS;
  451. }