fork-echoserv.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  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. int create_listen_socket(const char *service)
  61. {
  62. struct addrinfo hints, *res, *rp;
  63. int sfd = -1;
  64. int r;
  65. memset(&hints, 0, sizeof(struct addrinfo));
  66. hints.ai_family = AF_UNSPEC;
  67. hints.ai_socktype = SOCK_STREAM;
  68. hints.ai_flags = AI_PASSIVE | AI_ADDRCONFIG;
  69. r = getaddrinfo(0, service, &hints, &res);
  70. if(r != 0) {
  71. fprintf(stderr, "getaddrinfo: %s", gai_strerror(r));
  72. return -1;
  73. }
  74. for(rp = res; rp; rp = rp->ai_next) {
  75. int val = 1;
  76. sfd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  77. if(sfd == -1) {
  78. continue;
  79. }
  80. if(setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &val,
  81. (socklen_t)sizeof(val)) == -1) {
  82. continue;
  83. }
  84. if(bind(sfd, rp->ai_addr, rp->ai_addrlen) == 0) {
  85. break;
  86. }
  87. close(sfd);
  88. }
  89. freeaddrinfo(res);
  90. if(listen(sfd, 16) == -1) {
  91. perror("listen");
  92. close(sfd);
  93. return -1;
  94. }
  95. return sfd;
  96. }
  97. /*
  98. * Makes file descriptor *fd* non-blocking mode.
  99. * This function returns 0, or returns -1.
  100. */
  101. int make_non_block(int fd)
  102. {
  103. int flags, r;
  104. while((flags = fcntl(fd, F_GETFL, 0)) == -1 && errno == EINTR);
  105. if(flags == -1) {
  106. perror("fcntl");
  107. return -1;
  108. }
  109. while((r = fcntl(fd, F_SETFL, flags | O_NONBLOCK)) == -1 && errno == EINTR);
  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. void sha1(uint8_t *dst, const uint8_t *src, size_t src_length)
  121. {
  122. struct sha1_ctx ctx;
  123. sha1_init(&ctx);
  124. sha1_update(&ctx, src_length, src);
  125. sha1_digest(&ctx, SHA1_DIGEST_SIZE, dst);
  126. }
  127. /*
  128. * Base64-encode *src* and stores it in *dst*.
  129. * The size of *src* is *src_length*.
  130. * *dst* must be at least BASE64_ENCODE_RAW_LENGTH(src_length).
  131. */
  132. void base64(uint8_t *dst, const uint8_t *src, size_t src_length)
  133. {
  134. struct base64_encode_ctx ctx;
  135. base64_encode_init(&ctx);
  136. base64_encode_raw(dst, src_length, src);
  137. }
  138. #define WS_GUID "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
  139. /*
  140. * Create Server's accept key in *dst*.
  141. * *client_key* is the value of |Sec-WebSocket-Key| header field in
  142. * client's handshake and it must be length of 24.
  143. * *dst* must be at least BASE64_ENCODE_RAW_LENGTH(20)+1.
  144. */
  145. void create_accept_key(char *dst, const char *client_key)
  146. {
  147. uint8_t sha1buf[20], key_src[60];
  148. memcpy(key_src, client_key, 24);
  149. memcpy(key_src+24, WS_GUID, 36);
  150. sha1(sha1buf, key_src, sizeof(key_src));
  151. base64((uint8_t*)dst, sha1buf, 20);
  152. dst[BASE64_ENCODE_RAW_LENGTH(20)] = '\0';
  153. }
  154. /* We parse HTTP header lines of the format
  155. * \r\nfield_name: value1, value2, ... \r\n
  156. *
  157. * If the caller is looking for a specific value, we return a pointer to the
  158. * start of that value, else we simply return the start of values list.
  159. */
  160. static char*
  161. http_header_find_field_value(char *header, char *field_name, char *value)
  162. {
  163. char *header_end,
  164. *field_start,
  165. *field_end,
  166. *next_crlf,
  167. *value_start;
  168. int field_name_len;
  169. /* Pointer to the last character in the header */
  170. header_end = header + strlen(header) - 1;
  171. field_name_len = strlen(field_name);
  172. field_start = header;
  173. do{
  174. field_start = strstr(field_start+1, field_name);
  175. field_end = field_start + field_name_len - 1;
  176. if(field_start != NULL
  177. && field_start - header >= 2
  178. && field_start[-2] == '\r'
  179. && field_start[-1] == '\n'
  180. && header_end - field_end >= 1
  181. && field_end[1] == ':')
  182. {
  183. break; /* Found the field */
  184. }
  185. else
  186. {
  187. continue; /* This is not the one; keep looking. */
  188. }
  189. } while(field_start != NULL);
  190. if(field_start == NULL)
  191. return NULL;
  192. /* Find the field terminator */
  193. next_crlf = strstr(field_start, "\r\n");
  194. /* A field is expected to end with \r\n */
  195. if(next_crlf == NULL)
  196. return NULL; /* Malformed HTTP header! */
  197. /* If not looking for a value, then return a pointer to the start of values string */
  198. if(value == NULL)
  199. return field_end+2;
  200. value_start = strstr(field_start, value);
  201. /* Value not found */
  202. if(value_start == NULL)
  203. return NULL;
  204. /* Found the value we're looking for */
  205. if(value_start > next_crlf)
  206. return NULL; /* ... but after the CRLF terminator of the field. */
  207. /* The value we found should be properly delineated from the other tokens */
  208. if(isalnum(value_start[-1]) || isalnum(value_start[strlen(value)]))
  209. return NULL;
  210. return value_start;
  211. }
  212. /*
  213. * Performs HTTP handshake. *fd* is the file descriptor of the
  214. * connection to the client. This function returns 0 if it succeeds,
  215. * or returns -1.
  216. */
  217. int http_handshake(int fd)
  218. {
  219. /*
  220. * Note: The implementation of HTTP handshake in this function is
  221. * written for just a example of how to use of wslay library and is
  222. * not meant to be used in production code. In practice, you need
  223. * to do more strict verification of the client's handshake.
  224. */
  225. char header[16384], accept_key[29], *keyhdstart, *keyhdend, res_header[256];
  226. size_t header_length = 0, res_header_sent = 0, res_header_length;
  227. ssize_t r;
  228. while(1) {
  229. while((r = read(fd, header+header_length,
  230. sizeof(header)-header_length)) == -1 && errno == EINTR);
  231. if(r == -1) {
  232. perror("read");
  233. return -1;
  234. } else if(r == 0) {
  235. fprintf(stderr, "HTTP Handshake: Got EOF");
  236. return -1;
  237. } else {
  238. header_length += r;
  239. if(header_length >= 4 &&
  240. memcmp(header+header_length-4, "\r\n\r\n", 4) == 0) {
  241. break;
  242. } else if(header_length == sizeof(header)) {
  243. fprintf(stderr, "HTTP Handshake: Too large HTTP headers");
  244. return -1;
  245. }
  246. }
  247. }
  248. if(http_header_find_field_value(header, "Upgrade", "websocket") == NULL ||
  249. http_header_find_field_value(header, "Connection", "Upgrade") == NULL ||
  250. (keyhdstart = http_header_find_field_value(header, "Sec-WebSocket-Key", NULL)) == NULL) {
  251. fprintf(stderr, "HTTP Handshake: Missing required header fields");
  252. return -1;
  253. }
  254. for(; *keyhdstart == ' '; ++keyhdstart);
  255. keyhdend = keyhdstart;
  256. for(; *keyhdend != '\r' && *keyhdend != ' '; ++keyhdend);
  257. if(keyhdend-keyhdstart != 24) {
  258. printf("%s\n", keyhdstart);
  259. fprintf(stderr, "HTTP Handshake: Invalid value in Sec-WebSocket-Key");
  260. return -1;
  261. }
  262. create_accept_key(accept_key, keyhdstart);
  263. snprintf(res_header, sizeof(res_header),
  264. "HTTP/1.1 101 Switching Protocols\r\n"
  265. "Upgrade: websocket\r\n"
  266. "Connection: Upgrade\r\n"
  267. "Sec-WebSocket-Accept: %s\r\n"
  268. "\r\n", accept_key);
  269. res_header_length = strlen(res_header);
  270. while(res_header_sent < res_header_length) {
  271. while((r = write(fd, res_header+res_header_sent,
  272. res_header_length-res_header_sent)) == -1 &&
  273. errno == EINTR);
  274. if(r == -1) {
  275. perror("write");
  276. return -1;
  277. } else {
  278. res_header_sent += r;
  279. }
  280. }
  281. return 0;
  282. }
  283. /*
  284. * This struct is passed as *user_data* in callback function. The
  285. * *fd* member is the file descriptor of the connection to the client.
  286. */
  287. struct Session {
  288. int fd;
  289. };
  290. ssize_t send_callback(wslay_event_context_ptr ctx,
  291. const uint8_t *data, size_t len, int flags,
  292. void *user_data)
  293. {
  294. struct Session *session = (struct Session*)user_data;
  295. ssize_t r;
  296. int sflags = 0;
  297. #ifdef MSG_MORE
  298. if(flags & WSLAY_MSG_MORE) {
  299. sflags |= MSG_MORE;
  300. }
  301. #endif // MSG_MORE
  302. while((r = send(session->fd, data, len, sflags)) == -1 && errno == EINTR);
  303. if(r == -1) {
  304. if(errno == EAGAIN || errno == EWOULDBLOCK) {
  305. wslay_event_set_error(ctx, WSLAY_ERR_WOULDBLOCK);
  306. } else {
  307. wslay_event_set_error(ctx, WSLAY_ERR_CALLBACK_FAILURE);
  308. }
  309. }
  310. return r;
  311. }
  312. ssize_t recv_callback(wslay_event_context_ptr ctx, uint8_t *buf, size_t len,
  313. int flags, void *user_data)
  314. {
  315. struct Session *session = (struct Session*)user_data;
  316. ssize_t r;
  317. while((r = recv(session->fd, buf, len, 0)) == -1 && errno == EINTR);
  318. if(r == -1) {
  319. if(errno == EAGAIN || errno == EWOULDBLOCK) {
  320. wslay_event_set_error(ctx, WSLAY_ERR_WOULDBLOCK);
  321. } else {
  322. wslay_event_set_error(ctx, WSLAY_ERR_CALLBACK_FAILURE);
  323. }
  324. } else if(r == 0) {
  325. /* Unexpected EOF is also treated as an error */
  326. wslay_event_set_error(ctx, WSLAY_ERR_CALLBACK_FAILURE);
  327. r = -1;
  328. }
  329. return r;
  330. }
  331. void on_msg_recv_callback(wslay_event_context_ptr ctx,
  332. const struct wslay_event_on_msg_recv_arg *arg,
  333. void *user_data)
  334. {
  335. /* Echo back non-control message */
  336. if(!wslay_is_ctrl_frame(arg->opcode)) {
  337. struct wslay_event_msg msgarg = {
  338. arg->opcode, arg->msg, arg->msg_length
  339. };
  340. wslay_event_queue_msg(ctx, &msgarg);
  341. }
  342. }
  343. /*
  344. * Communicate with the client. This function performs HTTP handshake
  345. * and WebSocket data transfer until close handshake is done or an
  346. * error occurs. *fd* is the file descriptor of the connection to the
  347. * client. This function returns 0 if it succeeds, or returns 0.
  348. */
  349. int communicate(int fd)
  350. {
  351. wslay_event_context_ptr ctx;
  352. struct wslay_event_callbacks callbacks = {
  353. recv_callback,
  354. send_callback,
  355. NULL,
  356. NULL,
  357. NULL,
  358. NULL,
  359. on_msg_recv_callback
  360. };
  361. struct Session session = { fd };
  362. int val = 1;
  363. struct pollfd event;
  364. int res = 0;
  365. if(http_handshake(fd) == -1) {
  366. return -1;
  367. }
  368. if(make_non_block(fd) == -1) {
  369. return -1;
  370. }
  371. if(setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &val, (socklen_t)sizeof(val))
  372. == -1) {
  373. perror("setsockopt: TCP_NODELAY");
  374. return -1;
  375. }
  376. memset(&event, 0, sizeof(struct pollfd));
  377. event.fd = fd;
  378. event.events = POLLIN;
  379. wslay_event_context_server_init(&ctx, &callbacks, &session);
  380. /*
  381. * Event loop: basically loop until both wslay_event_want_read(ctx)
  382. * and wslay_event_want_write(ctx) return 0.
  383. */
  384. while(wslay_event_want_read(ctx) || wslay_event_want_write(ctx)) {
  385. int r;
  386. while((r = poll(&event, 1, -1)) == -1 && errno == EINTR);
  387. if(r == -1) {
  388. perror("poll");
  389. res = -1;
  390. break;
  391. }
  392. if(((event.revents & POLLIN) && wslay_event_recv(ctx) != 0) ||
  393. ((event.revents & POLLOUT) && wslay_event_send(ctx) != 0) ||
  394. (event.revents & (POLLERR | POLLHUP | POLLNVAL))) {
  395. /*
  396. * If either wslay_event_recv() or wslay_event_send() return
  397. * non-zero value, it means serious error which prevents wslay
  398. * library from processing further data, so WebSocket connection
  399. * must be closed.
  400. */
  401. res = -1;
  402. break;
  403. }
  404. event.events = 0;
  405. if(wslay_event_want_read(ctx)) {
  406. event.events |= POLLIN;
  407. }
  408. if(wslay_event_want_write(ctx)) {
  409. event.events |= POLLOUT;
  410. }
  411. }
  412. return res;
  413. }
  414. /*
  415. * Serves echo back service forever. *sfd* is the file descriptor of
  416. * the server socket. when the incoming connection from the client is
  417. * accepted, this function forks another process and the forked
  418. * process communicates with client. The parent process goes back to
  419. * the loop and can accept another client.
  420. */
  421. void serve(int sfd)
  422. {
  423. while(1) {
  424. int fd;
  425. while((fd = accept(sfd, NULL, NULL)) == -1 && errno == EINTR);
  426. if(fd == -1) {
  427. perror("accept");
  428. } else {
  429. int r = fork();
  430. if(r == -1) {
  431. perror("fork");
  432. close(fd);
  433. } else if(r == 0) {
  434. int r = communicate(fd);
  435. shutdown(fd, SHUT_WR);
  436. close(fd);
  437. if(r == 0) {
  438. exit(EXIT_SUCCESS);
  439. } else {
  440. exit(EXIT_FAILURE);
  441. }
  442. }
  443. }
  444. }
  445. }
  446. int main(int argc, char **argv)
  447. {
  448. struct sigaction act;
  449. int sfd;
  450. if(argc < 2) {
  451. fprintf(stderr, "Usage: %s PORT\n", argv[0]);
  452. exit(EXIT_FAILURE);
  453. }
  454. memset(&act, 0, sizeof(struct sigaction));
  455. act.sa_handler = SIG_IGN;
  456. sigaction(SIGPIPE, &act, NULL);
  457. sigaction(SIGCHLD, &act, NULL);
  458. sfd = create_listen_socket(argv[1]);
  459. if(sfd == -1) {
  460. fprintf(stderr, "Failed to create server socket\n");
  461. exit(EXIT_FAILURE);
  462. }
  463. printf("WebSocket echo server, listening on %s\n", argv[1]);
  464. serve(sfd);
  465. return EXIT_SUCCESS;
  466. }