fork-echoserv.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  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 <nettle/base64.h>
  53. #include <nettle/sha.h>
  54. #include <wslay/wslay.h>
  55. /*
  56. * Create server socket, listen on *service*. This function returns
  57. * file descriptor of server socket if it succeeds, or returns -1.
  58. */
  59. int create_listen_socket(const char *service)
  60. {
  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. int make_non_block(int fd)
  101. {
  102. int flags, r;
  103. while((flags = fcntl(fd, F_GETFL, 0)) == -1 && errno == EINTR);
  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. if(r == -1) {
  110. perror("fcntl");
  111. return -1;
  112. }
  113. return 0;
  114. }
  115. /*
  116. * Calculates SHA-1 hash of *src*. The size of *src* is *src_length* bytes.
  117. * *dst* must be at least SHA1_DIGEST_SIZE.
  118. */
  119. void sha1(uint8_t *dst, const uint8_t *src, size_t src_length)
  120. {
  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. void base64(uint8_t *dst, const uint8_t *src, size_t src_length)
  132. {
  133. struct base64_encode_ctx ctx;
  134. base64_encode_init(&ctx);
  135. base64_encode_raw(dst, src_length, src);
  136. }
  137. #define WS_GUID "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
  138. /*
  139. * Create Server's accept key in *dst*.
  140. * *client_key* is the value of |Sec-WebSocket-Key| header field in
  141. * client's handshake and it must be length of 24.
  142. * *dst* must be at least BASE64_ENCODE_RAW_LENGTH(20)+1.
  143. */
  144. void create_accept_key(char *dst, const char *client_key)
  145. {
  146. uint8_t sha1buf[20], key_src[60];
  147. memcpy(key_src, client_key, 24);
  148. memcpy(key_src+24, WS_GUID, 36);
  149. sha1(sha1buf, key_src, sizeof(key_src));
  150. base64((uint8_t*)dst, sha1buf, 20);
  151. dst[BASE64_ENCODE_RAW_LENGTH(20)] = '\0';
  152. }
  153. /*
  154. * Performs HTTP handshake. *fd* is the file descriptor of the
  155. * connection to the client. This function returns 0 if it succeeds,
  156. * or returns -1.
  157. */
  158. int http_handshake(int fd)
  159. {
  160. /*
  161. * Note: The implementation of HTTP handshake in this function is
  162. * written for just a example of how to use of wslay library and is
  163. * not meant to be used in production code. In practice, you need
  164. * to do more strict verification of the client's handshake.
  165. */
  166. char header[16384], accept_key[29], *keyhdstart, *keyhdend, res_header[256];
  167. size_t header_length = 0, res_header_sent = 0, res_header_length;
  168. ssize_t r;
  169. while(1) {
  170. while((r = read(fd, header+header_length,
  171. sizeof(header)-header_length)) == -1 && errno == EINTR);
  172. if(r == -1) {
  173. perror("read");
  174. return -1;
  175. } else if(r == 0) {
  176. fprintf(stderr, "HTTP Handshake: Got EOF");
  177. return -1;
  178. } else {
  179. header_length += r;
  180. if(header_length >= 4 &&
  181. memcmp(header+header_length-4, "\r\n\r\n", 4) == 0) {
  182. break;
  183. } else if(header_length == sizeof(header)) {
  184. fprintf(stderr, "HTTP Handshake: Too large HTTP headers");
  185. return -1;
  186. }
  187. }
  188. }
  189. if(strstr(header, "\r\nUpgrade: websocket\r\n") == NULL ||
  190. strstr(header, "\r\nConnection: Upgrade\r\n") == NULL ||
  191. (keyhdstart = strstr(header, "\r\nSec-WebSocket-Key:")) == NULL) {
  192. fprintf(stderr, "HTTP Handshake: Missing required header fields");
  193. return -1;
  194. }
  195. keyhdstart += 20;
  196. for(; *keyhdstart == ' '; ++keyhdstart);
  197. keyhdend = keyhdstart;
  198. for(; *keyhdend != '\r' && *keyhdend != ' '; ++keyhdend);
  199. if(keyhdend-keyhdstart != 24) {
  200. printf("%s\n", keyhdstart);
  201. fprintf(stderr, "HTTP Handshake: Invalid value in Sec-WebSocket-Key");
  202. return -1;
  203. }
  204. create_accept_key(accept_key, keyhdstart);
  205. snprintf(res_header, sizeof(res_header),
  206. "HTTP/1.1 101 Switching Protocols\r\n"
  207. "Upgrade: websocket\r\n"
  208. "Connection: Upgrade\r\n"
  209. "Sec-WebSocket-Accept: %s\r\n"
  210. "\r\n", accept_key);
  211. res_header_length = strlen(res_header);
  212. while(res_header_sent < res_header_length) {
  213. while((r = write(fd, res_header+res_header_sent,
  214. res_header_length-res_header_sent)) == -1 &&
  215. errno == EINTR);
  216. if(r == -1) {
  217. perror("write");
  218. return -1;
  219. } else {
  220. res_header_sent += r;
  221. }
  222. }
  223. return 0;
  224. }
  225. /*
  226. * This struct is passed as *user_data* in callback function. The
  227. * *fd* member is the file descriptor of the connection to the client.
  228. */
  229. struct Session {
  230. int fd;
  231. };
  232. ssize_t send_callback(wslay_event_context_ptr ctx,
  233. const uint8_t *data, size_t len, int flags,
  234. void *user_data)
  235. {
  236. struct Session *session = (struct Session*)user_data;
  237. ssize_t r;
  238. int sflags = 0;
  239. #ifdef MSG_MORE
  240. if(flags & WSLAY_MSG_MORE) {
  241. sflags |= MSG_MORE;
  242. }
  243. #endif // MSG_MORE
  244. while((r = send(session->fd, data, len, sflags)) == -1 && errno == EINTR);
  245. if(r == -1) {
  246. if(errno == EAGAIN || errno == EWOULDBLOCK) {
  247. wslay_event_set_error(ctx, WSLAY_ERR_WOULDBLOCK);
  248. } else {
  249. wslay_event_set_error(ctx, WSLAY_ERR_CALLBACK_FAILURE);
  250. }
  251. }
  252. return r;
  253. }
  254. ssize_t recv_callback(wslay_event_context_ptr ctx, uint8_t *buf, size_t len,
  255. int flags, void *user_data)
  256. {
  257. struct Session *session = (struct Session*)user_data;
  258. ssize_t r;
  259. while((r = recv(session->fd, buf, len, 0)) == -1 && errno == EINTR);
  260. if(r == -1) {
  261. if(errno == EAGAIN || errno == EWOULDBLOCK) {
  262. wslay_event_set_error(ctx, WSLAY_ERR_WOULDBLOCK);
  263. } else {
  264. wslay_event_set_error(ctx, WSLAY_ERR_CALLBACK_FAILURE);
  265. }
  266. } else if(r == 0) {
  267. /* Unexpected EOF is also treated as an error */
  268. wslay_event_set_error(ctx, WSLAY_ERR_CALLBACK_FAILURE);
  269. r = -1;
  270. }
  271. return r;
  272. }
  273. void on_msg_recv_callback(wslay_event_context_ptr ctx,
  274. const struct wslay_event_on_msg_recv_arg *arg,
  275. void *user_data)
  276. {
  277. /* Echo back non-control message */
  278. if(!wslay_is_ctrl_frame(arg->opcode)) {
  279. struct wslay_event_msg msgarg = {
  280. arg->opcode, arg->msg, arg->msg_length
  281. };
  282. wslay_event_queue_msg(ctx, &msgarg);
  283. }
  284. }
  285. /*
  286. * Communicate with the client. This function performs HTTP handshake
  287. * and WebSocket data transfer until close handshake is done or an
  288. * error occurs. *fd* is the file descriptor of the connection to the
  289. * client. This function returns 0 if it succeeds, or returns 0.
  290. */
  291. int communicate(int fd)
  292. {
  293. wslay_event_context_ptr ctx;
  294. struct wslay_event_callbacks callbacks = {
  295. recv_callback,
  296. send_callback,
  297. NULL,
  298. NULL,
  299. NULL,
  300. NULL,
  301. on_msg_recv_callback
  302. };
  303. struct Session session = { fd };
  304. int val = 1;
  305. struct pollfd event;
  306. int res = 0;
  307. if(http_handshake(fd) == -1) {
  308. return -1;
  309. }
  310. if(make_non_block(fd) == -1) {
  311. return -1;
  312. }
  313. if(setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &val, (socklen_t)sizeof(val))
  314. == -1) {
  315. perror("setsockopt: TCP_NODELAY");
  316. return -1;
  317. }
  318. memset(&event, 0, sizeof(struct pollfd));
  319. event.fd = fd;
  320. event.events = POLLIN;
  321. wslay_event_context_server_init(&ctx, &callbacks, &session);
  322. /*
  323. * Event loop: basically loop until both wslay_event_want_read(ctx)
  324. * and wslay_event_want_write(ctx) return 0.
  325. */
  326. while(wslay_event_want_read(ctx) || wslay_event_want_write(ctx)) {
  327. int r;
  328. while((r = poll(&event, 1, -1)) == -1 && errno == EINTR);
  329. if(r == -1) {
  330. perror("poll");
  331. res = -1;
  332. break;
  333. }
  334. if(((event.revents & POLLIN) && wslay_event_recv(ctx) != 0) ||
  335. ((event.revents & POLLOUT) && wslay_event_send(ctx) != 0) ||
  336. (event.revents & (POLLERR | POLLHUP | POLLNVAL))) {
  337. /*
  338. * If either wslay_event_recv() or wslay_event_send() return
  339. * non-zero value, it means serious error which prevents wslay
  340. * library from processing further data, so WebSocket connection
  341. * must be closed.
  342. */
  343. res = -1;
  344. break;
  345. }
  346. event.events = 0;
  347. if(wslay_event_want_read(ctx)) {
  348. event.events |= POLLIN;
  349. }
  350. if(wslay_event_want_write(ctx)) {
  351. event.events |= POLLOUT;
  352. }
  353. }
  354. return res;
  355. }
  356. /*
  357. * Serves echo back service forever. *sfd* is the file descriptor of
  358. * the server socket. when the incoming connection from the client is
  359. * accepted, this function forks another process and the forked
  360. * process communicates with client. The parent process goes back to
  361. * the loop and can accept another client.
  362. */
  363. void serve(int sfd)
  364. {
  365. while(1) {
  366. int fd;
  367. while((fd = accept(sfd, NULL, NULL)) == -1 && errno == EINTR);
  368. if(fd == -1) {
  369. perror("accept");
  370. } else {
  371. int r = fork();
  372. if(r == -1) {
  373. perror("fork");
  374. close(fd);
  375. } else if(r == 0) {
  376. int r = communicate(fd);
  377. shutdown(fd, SHUT_WR);
  378. close(fd);
  379. if(r == 0) {
  380. exit(EXIT_SUCCESS);
  381. } else {
  382. exit(EXIT_FAILURE);
  383. }
  384. }
  385. }
  386. }
  387. }
  388. int main(int argc, char **argv)
  389. {
  390. struct sigaction act;
  391. int sfd;
  392. if(argc < 2) {
  393. fprintf(stderr, "Usage: %s PORT\n", argv[0]);
  394. exit(EXIT_FAILURE);
  395. }
  396. memset(&act, 0, sizeof(struct sigaction));
  397. act.sa_handler = SIG_IGN;
  398. sigaction(SIGPIPE, &act, NULL);
  399. sigaction(SIGCHLD, &act, NULL);
  400. sfd = create_listen_socket(argv[1]);
  401. if(sfd == -1) {
  402. fprintf(stderr, "Failed to create server socket\n");
  403. exit(EXIT_FAILURE);
  404. }
  405. printf("WebSocket echo server, listening on %s\n", argv[1]);
  406. serve(sfd);
  407. return EXIT_SUCCESS;
  408. }