2 * libwebsockets - small server side websockets and web server implementation
4 * Copyright (C) 2010 Andy Green <andy@warmcat.com>
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation:
9 * version 2.1 of the License.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
22 #include "private-libwebsockets.h"
30 #ifdef LWS_OPENSSL_SUPPORT
31 int openssl_websocket_private_data_index;
35 * In-place str to lower case
47 /* file descriptor hash management */
50 wsi_from_fd(struct libwebsocket_context *context, int fd)
52 int h = LWS_FD_HASH(fd);
55 for (n = 0; n < context->fd_hashtable[h].length; n++)
56 if (context->fd_hashtable[h].wsi[n]->sock == fd)
57 return context->fd_hashtable[h].wsi[n];
63 insert_wsi(struct libwebsocket_context *context, struct libwebsocket *wsi)
65 int h = LWS_FD_HASH(wsi->sock);
67 if (context->fd_hashtable[h].length == MAX_CLIENTS - 1) {
68 fprintf(stderr, "hash table overflow\n");
72 context->fd_hashtable[h].wsi[context->fd_hashtable[h].length++] = wsi;
78 delete_from_fd(struct libwebsocket_context *context, int fd)
80 int h = LWS_FD_HASH(fd);
83 for (n = 0; n < context->fd_hashtable[h].length; n++)
84 if (context->fd_hashtable[h].wsi[n]->sock == fd) {
85 while (n < context->fd_hashtable[h].length) {
86 context->fd_hashtable[h].wsi[n] =
87 context->fd_hashtable[h].wsi[n + 1];
90 context->fd_hashtable[h].length--;
95 fprintf(stderr, "Failed to find fd %d requested for "
96 "delete in hashtable\n", fd);
100 #ifdef LWS_OPENSSL_SUPPORT
102 libwebsockets_decode_ssl_error(void)
107 while ((err = ERR_get_error()) != 0) {
108 ERR_error_string_n(err, buf, sizeof(buf));
109 fprintf(stderr, "*** %s\n", buf);
116 interface_to_sa(const char* ifname, struct sockaddr_in *addr, size_t addrlen)
124 struct sockaddr_in *sin;
127 for (ifc = ifr; ifc != NULL; ifc = ifc->ifa_next) {
128 if (strcmp(ifc->ifa_name, ifname))
130 if (ifc->ifa_addr == NULL)
132 sin = (struct sockaddr_in *)ifc->ifa_addr;
133 if (sin->sin_family != AF_INET)
135 memcpy(addr, sin, addrlen);
145 libwebsocket_close_and_free_session(struct libwebsocket_context *context,
146 struct libwebsocket *wsi, enum lws_close_status reason)
150 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 2 +
151 LWS_SEND_BUFFER_POST_PADDING];
156 old_state = wsi->state;
158 if (old_state == WSI_STATE_DEAD_SOCKET)
161 /* remove this fd from wsi mapping hashtable */
163 delete_from_fd(context, wsi->sock);
165 /* delete it from the internal poll list if still present */
167 for (n = 0; n < context->fds_count; n++) {
168 if (context->fds[n].fd != wsi->sock)
170 while (n < context->fds_count - 1) {
171 context->fds[n] = context->fds[n + 1];
174 context->fds_count--;
175 /* we only have to deal with one */
176 n = context->fds_count;
179 /* remove also from external POLL support via protocol 0 */
181 context->protocols[0].callback(context, wsi,
182 LWS_CALLBACK_DEL_POLL_FD, (void *)(long)wsi->sock, NULL, 0);
184 wsi->close_reason = reason;
187 * signal we are closing, libsocket_write will
188 * add any necessary version-specific stuff. If the write fails,
189 * no worries we are closing anyway. If we didn't initiate this
190 * close, then our state has been changed to
191 * WSI_STATE_RETURNED_CLOSE_ALREADY and we will skip this
194 if (old_state == WSI_STATE_ESTABLISHED)
195 libwebsocket_write(wsi, &buf[LWS_SEND_BUFFER_PRE_PADDING], 0,
198 wsi->state = WSI_STATE_DEAD_SOCKET;
200 /* tell the user it's all over for this guy */
202 if (wsi->protocol && wsi->protocol->callback &&
203 old_state == WSI_STATE_ESTABLISHED)
204 wsi->protocol->callback(context, wsi, LWS_CALLBACK_CLOSED,
205 wsi->user_space, NULL, 0);
207 /* free up his allocations */
209 for (n = 0; n < WSI_TOKEN_COUNT; n++)
210 if (wsi->utf8_token[n].token)
211 free(wsi->utf8_token[n].token);
213 /* fprintf(stderr, "closing fd=%d\n", wsi->sock); */
215 #ifdef LWS_OPENSSL_SUPPORT
217 n = SSL_get_fd(wsi->ssl);
218 SSL_shutdown(wsi->ssl);
227 shutdown(wsi->sock, SHUT_RDWR);
229 closesocket(wsi->sock);
233 #ifdef LWS_OPENSSL_SUPPORT
237 free(wsi->user_space);
243 * libwebsockets_hangup_on_client() - Server calls to terminate client
245 * @context: libwebsockets context
246 * @fd: Connection socket descriptor
250 libwebsockets_hangup_on_client(struct libwebsocket_context *context, int fd)
252 struct libwebsocket *wsi = wsi_from_fd(context, fd);
257 libwebsocket_close_and_free_session(context, wsi,
258 LWS_CLOSE_STATUS_NOSTATUS);
263 * libwebsockets_get_peer_addresses() - Get client address information
264 * @fd: Connection socket descriptor
265 * @name: Buffer to take client address name
266 * @name_len: Length of client address name buffer
267 * @rip: Buffer to take client address IP qotted quad
268 * @rip_len: Length of client address IP buffer
270 * This function fills in @name and @rip with the name and IP of
271 * the client connected with socket descriptor @fd. Names may be
272 * truncated if there is not enough room. If either cannot be
273 * determined, they will be returned as valid zero-length strings.
277 libwebsockets_get_peer_addresses(int fd, char *name, int name_len,
278 char *rip, int rip_len)
281 struct sockaddr_in sin;
282 struct hostent *host;
283 struct hostent *host1;
292 if (getpeername(fd, (struct sockaddr *) &sin, &len) < 0) {
293 perror("getpeername");
297 host = gethostbyaddr((char *) &sin.sin_addr, sizeof sin.sin_addr,
300 perror("gethostbyaddr");
304 strncpy(name, host->h_name, name_len);
305 name[name_len - 1] = '\0';
307 host1 = gethostbyname(host->h_name);
313 p = host1->h_addr_list[n++];
316 if (host1->h_addrtype != AF_INET)
319 sprintf(ip, "%d.%d.%d.%d",
320 p[0], p[1], p[2], p[3]);
322 strncpy(rip, ip, rip_len);
323 rip[rip_len - 1] = '\0';
327 int libwebsockets_get_random(struct libwebsocket_context *context,
334 for (n = 0; n < len; n++)
335 p[n] = (unsigned char)rand();
337 n = read(context->fd_random, p, len);
343 void libwebsockets_00_spaceout(char *key, int spaces, int seed)
349 if (*key && (seed & 1))
353 p = key + strlen(key);
362 void libwebsockets_00_spam(char *key, int count, int seed)
369 if (*key && (seed & 1))
373 p = key + strlen(key);
378 *key++ = 0x21 + ((seed & 0xffff) % 15);
379 /* 4 would use it up too fast.. not like it matters */
385 * libwebsocket_service_fd() - Service polled socket with something waiting
386 * @context: Websocket context
387 * @pollfd: The pollfd entry describing the socket fd and which events
390 * This function closes any active connections and then frees the
391 * context. After calling this, any further use of the context is
396 libwebsocket_service_fd(struct libwebsocket_context *context,
397 struct pollfd *pollfd)
399 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + MAX_BROADCAST_PAYLOAD +
400 LWS_SEND_BUFFER_POST_PADDING];
401 struct libwebsocket *wsi;
402 struct libwebsocket *new_wsi;
408 struct sockaddr_in cli_addr;
410 static const char magic_websocket_guid[] =
411 "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
412 static const char magic_websocket_04_masking_guid[] =
413 "61AC5F19-FBBA-4540-B96F-6561F1AB40A8";
419 #ifdef LWS_OPENSSL_SUPPORT
420 char ssl_err_buf[512];
423 * you can call us with pollfd = NULL to just allow the once-per-second
424 * global timeout checks; if less than a second since the last check
425 * it returns immediately then.
428 gettimeofday(&tv, NULL);
430 if (context->last_timeout_check_s != tv.tv_sec) {
431 context->last_timeout_check_s = tv.tv_sec;
433 /* global timeout check once per second */
435 for (n = 0; n < context->fds_count; n++) {
436 wsi = wsi_from_fd(context, context->fds[n].fd);
437 if (!wsi->pending_timeout)
441 * if we went beyond the allowed time, kill the
445 if (tv.tv_sec > wsi->pending_timeout_limit)
446 libwebsocket_close_and_free_session(context,
447 wsi, LWS_CLOSE_STATUS_NOSTATUS);
451 /* just here for timeout management? */
456 /* no, here to service a socket descriptor */
458 wsi = wsi_from_fd(context, pollfd->fd);
464 case LWS_CONNMODE_SERVER_LISTENER:
466 /* pollin means a client has connected to us then */
468 if (!pollfd->revents & POLLIN)
471 /* listen socket got an unencrypted connection... */
473 clilen = sizeof(cli_addr);
474 accept_fd = accept(pollfd->fd, (struct sockaddr *)&cli_addr,
477 fprintf(stderr, "ERROR on accept");
481 if (context->fds_count >= MAX_CLIENTS) {
482 fprintf(stderr, "too busy to accept new client\n");
484 closesocket(accept_fd);
492 * look at who we connected to and give user code a chance
493 * to reject based on client IP. There's no protocol selected
494 * yet so we issue this to protocols[0]
497 if ((context->protocols[0].callback)(context, wsi,
498 LWS_CALLBACK_FILTER_NETWORK_CONNECTION,
499 (void*)(long)accept_fd, NULL, 0)) {
500 fprintf(stderr, "Callback denied network connection\n");
502 closesocket(accept_fd);
509 /* accepting connection to main listener */
511 new_wsi = malloc(sizeof(struct libwebsocket));
512 if (new_wsi == NULL) {
513 fprintf(stderr, "Out of memory for new connection\n");
517 memset(new_wsi, 0, sizeof (struct libwebsocket));
518 new_wsi->sock = accept_fd;
519 new_wsi->count_active_extensions = 0;
520 new_wsi->pending_timeout = NO_PENDING_TIMEOUT;
522 #ifdef LWS_OPENSSL_SUPPORT
525 if (context->use_ssl) {
527 new_wsi->ssl = SSL_new(context->ssl_ctx);
528 if (new_wsi->ssl == NULL) {
529 fprintf(stderr, "SSL_new failed: %s\n",
530 ERR_error_string(SSL_get_error(
531 new_wsi->ssl, 0), NULL));
532 libwebsockets_decode_ssl_error();
537 SSL_set_fd(new_wsi->ssl, accept_fd);
539 n = SSL_accept(new_wsi->ssl);
542 * browsers seem to probe with various
543 * ssl params which fail then retry
546 debug("SSL_accept failed skt %u: %s\n",
548 ERR_error_string(SSL_get_error(
549 new_wsi->ssl, n), NULL));
556 debug("accepted new SSL conn "
557 "port %u on fd=%d SSL ver %s\n",
558 ntohs(cli_addr.sin_port), accept_fd,
559 SSL_get_version(new_wsi->ssl));
563 debug("accepted new conn port %u on fd=%d\n",
564 ntohs(cli_addr.sin_port), accept_fd);
566 /* intialize the instance struct */
568 new_wsi->state = WSI_STATE_HTTP;
569 new_wsi->name_buffer_pos = 0;
570 new_wsi->mode = LWS_CONNMODE_WS_SERVING;
572 for (n = 0; n < WSI_TOKEN_COUNT; n++) {
573 new_wsi->utf8_token[n].token = NULL;
574 new_wsi->utf8_token[n].token_len = 0;
578 * these can only be set once the protocol is known
579 * we set an unestablished connection's protocol pointer
580 * to the start of the supported list, so it can look
581 * for matching ones during the handshake
583 new_wsi->protocol = context->protocols;
584 new_wsi->user_space = NULL;
587 * Default protocol is 76 / 00
588 * After 76, there's a header specified to inform which
589 * draft the client wants, when that's seen we modify
590 * the individual connection's spec revision accordingly
592 new_wsi->ietf_spec_revision = 0;
594 insert_wsi(context, new_wsi);
597 * make sure NO events are seen yet on this new socket
598 * (otherwise we inherit old fds[client].revents from
599 * previous socket there and die mysteriously! )
601 context->fds[context->fds_count].revents = 0;
603 context->fds[context->fds_count].events = POLLIN;
604 context->fds[context->fds_count++].fd = accept_fd;
606 /* external POLL support via protocol 0 */
607 context->protocols[0].callback(context, new_wsi,
608 LWS_CALLBACK_ADD_POLL_FD,
609 (void *)(long)accept_fd, NULL, POLLIN);
613 case LWS_CONNMODE_BROADCAST_PROXY_LISTENER:
615 /* as we are listening, POLLIN means accept() is needed */
617 if (!pollfd->revents & POLLIN)
620 /* listen socket got an unencrypted connection... */
622 clilen = sizeof(cli_addr);
623 accept_fd = accept(pollfd->fd, (struct sockaddr *)&cli_addr,
626 fprintf(stderr, "ERROR on accept");
630 if (context->fds_count >= MAX_CLIENTS) {
631 fprintf(stderr, "too busy to accept new broadcast "
634 closesocket(accept_fd);
641 /* create a dummy wsi for the connection and add it */
643 new_wsi = malloc(sizeof(struct libwebsocket));
644 memset(new_wsi, 0, sizeof (struct libwebsocket));
645 new_wsi->sock = accept_fd;
646 new_wsi->mode = LWS_CONNMODE_BROADCAST_PROXY;
647 new_wsi->state = WSI_STATE_ESTABLISHED;
648 new_wsi->count_active_extensions = 0;
649 /* note which protocol we are proxying */
650 new_wsi->protocol_index_for_broadcast_proxy =
651 wsi->protocol_index_for_broadcast_proxy;
652 insert_wsi(context, new_wsi);
654 /* add connected socket to internal poll array */
656 context->fds[context->fds_count].revents = 0;
657 context->fds[context->fds_count].events = POLLIN;
658 context->fds[context->fds_count++].fd = accept_fd;
660 /* external POLL support via protocol 0 */
661 context->protocols[0].callback(context, new_wsi,
662 LWS_CALLBACK_ADD_POLL_FD,
663 (void *)(long)accept_fd, NULL, POLLIN);
667 case LWS_CONNMODE_BROADCAST_PROXY:
669 /* handle session socket closed */
671 if (pollfd->revents & (POLLERR | POLLHUP)) {
673 debug("Session Socket %p (fd=%d) dead\n",
674 (void *)wsi, pollfd->fd);
676 libwebsocket_close_and_free_session(context, wsi,
677 LWS_CLOSE_STATUS_NORMAL);
681 /* the guy requested a callback when it was OK to write */
683 if (pollfd->revents & POLLOUT) {
687 pollfd->events &= ~POLLOUT;
689 /* external POLL support via protocol 0 */
690 context->protocols[0].callback(context, wsi,
691 LWS_CALLBACK_CLEAR_MODE_POLL_FD,
692 (void *)(long)wsi->sock, NULL, POLLOUT);
694 wsi->protocol->callback(context, wsi,
695 LWS_CALLBACK_CLIENT_WRITEABLE,
700 /* any incoming data ready? */
702 if (!(pollfd->revents & POLLIN))
705 /* get the issued broadcast payload from the socket */
707 len = read(pollfd->fd, buf + LWS_SEND_BUFFER_PRE_PADDING,
708 MAX_BROADCAST_PAYLOAD);
710 fprintf(stderr, "Error reading broadcast payload\n");
714 /* broadcast it to all guys with this protocol index */
716 for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
718 for (m = 0; m < context->fd_hashtable[n].length; m++) {
720 new_wsi = context->fd_hashtable[n].wsi[m];
722 /* only to clients we are serving to */
724 if (new_wsi->mode != LWS_CONNMODE_WS_SERVING)
728 * never broadcast to non-established
732 if (new_wsi->state != WSI_STATE_ESTABLISHED)
736 * only broadcast to connections using
737 * the requested protocol
740 if (new_wsi->protocol->protocol_index !=
741 wsi->protocol_index_for_broadcast_proxy)
744 /* broadcast it to this connection */
746 new_wsi->protocol->callback(context, new_wsi,
747 LWS_CALLBACK_BROADCAST,
749 buf + LWS_SEND_BUFFER_PRE_PADDING, len);
754 case LWS_CONNMODE_WS_CLIENT_WAITING_PROXY_REPLY:
756 /* handle proxy hung up on us */
758 if (pollfd->revents & (POLLERR | POLLHUP)) {
760 fprintf(stderr, "Proxy connection %p (fd=%d) dead\n",
761 (void *)wsi, pollfd->fd);
763 libwebsocket_close_and_free_session(context, wsi,
764 LWS_CLOSE_STATUS_NOSTATUS);
768 n = recv(wsi->sock, pkt, sizeof pkt, 0);
770 libwebsocket_close_and_free_session(context, wsi,
771 LWS_CLOSE_STATUS_NOSTATUS);
772 fprintf(stderr, "ERROR reading from proxy socket\n");
777 if (strcmp(pkt, "HTTP/1.0 200 ") != 0) {
778 libwebsocket_close_and_free_session(context, wsi,
779 LWS_CLOSE_STATUS_NOSTATUS);
780 fprintf(stderr, "ERROR from proxy: %s\n", pkt);
784 /* clear his proxy connection timeout */
786 libwebsocket_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
790 case LWS_CONNMODE_WS_CLIENT_ISSUE_HANDSHAKE:
792 #ifdef LWS_OPENSSL_SUPPORT
795 wsi->ssl = SSL_new(context->ssl_client_ctx);
796 wsi->client_bio = BIO_new_socket(wsi->sock,
798 SSL_set_bio(wsi->ssl, wsi->client_bio, wsi->client_bio);
800 SSL_set_ex_data(wsi->ssl,
801 openssl_websocket_private_data_index,
804 if (SSL_connect(wsi->ssl) <= 0) {
805 fprintf(stderr, "SSL connect error %s\n",
806 ERR_error_string(ERR_get_error(),
808 libwebsocket_close_and_free_session(context, wsi,
809 LWS_CLOSE_STATUS_NOSTATUS);
813 n = SSL_get_verify_result(wsi->ssl);
814 if ((n != X509_V_OK) && (
815 n != X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT ||
816 wsi->use_ssl != 2)) {
818 fprintf(stderr, "server's cert didn't "
819 "look good %d\n", n);
820 libwebsocket_close_and_free_session(context,
821 wsi, LWS_CLOSE_STATUS_NOSTATUS);
829 #ifdef LWS_OPENSSL_SUPPORT
834 * create the random key
837 n = libwebsockets_get_random(context, hash, 16);
839 fprintf(stderr, "Unable to read from random dev %s\n",
840 SYSTEM_RANDOM_FILEPATH);
846 free(wsi->c_protocol);
847 libwebsocket_close_and_free_session(context, wsi,
848 LWS_CLOSE_STATUS_NOSTATUS);
852 lws_b64_encode_string(hash, 16, wsi->key_b64,
853 sizeof wsi->key_b64);
856 * 00 example client handshake
858 * GET /socket.io/websocket HTTP/1.1
860 * Connection: Upgrade
861 * Host: 127.0.0.1:9999
862 * Origin: http://127.0.0.1
863 * Sec-WebSocket-Key1: 1 0 2#0W 9 89 7 92 ^
864 * Sec-WebSocket-Key2: 7 7Y 4328 B2v[8(z1
865 * Cookie: socketio=websocket
869 * 04 example client handshake
872 * Host: server.example.com
874 * Connection: Upgrade
875 * Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
876 * Sec-WebSocket-Origin: http://example.com
877 * Sec-WebSocket-Protocol: chat, superchat
878 * Sec-WebSocket-Version: 4
881 p += sprintf(p, "GET %s HTTP/1.1\x0d\x0a", wsi->c_path);
883 if (wsi->ietf_spec_revision == 0) {
884 unsigned char spaces_1, spaces_2;
885 unsigned int max_1, max_2;
886 unsigned int num_1, num_2;
887 unsigned long product_1, product_2;
894 libwebsockets_get_random(context, &spaces_1,
896 libwebsockets_get_random(context, &spaces_2,
899 spaces_1 = (spaces_1 % 12) + 1;
900 spaces_2 = (spaces_2 % 12) + 1;
902 max_1 = 4294967295 / spaces_1;
903 max_2 = 4294967295 / spaces_2;
905 libwebsockets_get_random(context, &num_1, sizeof(int));
906 libwebsockets_get_random(context, &num_2, sizeof(int));
908 num_1 = (num_1 % max_1);
909 num_2 = (num_2 % max_2);
911 challenge[0] = num_1 >> 24;
912 challenge[1] = num_1 >> 16;
913 challenge[2] = num_1 >> 8;
914 challenge[3] = num_1;
915 challenge[4] = num_2 >> 24;
916 challenge[5] = num_2 >> 16;
917 challenge[6] = num_2 >> 8;
918 challenge[7] = num_2;
920 product_1 = num_1 * spaces_1;
921 product_2 = num_2 * spaces_2;
923 sprintf(key_1, "%lu", product_1);
924 sprintf(key_2, "%lu", product_2);
926 libwebsockets_get_random(context, &seed, sizeof(int));
927 libwebsockets_get_random(context, &count, sizeof(int));
929 libwebsockets_00_spam(key_1, (count % 12) + 1, seed);
931 libwebsockets_get_random(context, &seed, sizeof(int));
932 libwebsockets_get_random(context, &count, sizeof(int));
934 libwebsockets_00_spam(key_2, (count % 12) + 1, seed);
936 libwebsockets_get_random(context, &seed, sizeof(int));
938 libwebsockets_00_spaceout(key_1, spaces_1, seed);
939 libwebsockets_00_spaceout(key_2, spaces_2, seed >> 16);
941 p += sprintf(p, "Upgrade: websocket\x0d\x0a"
942 "Connection: Upgrade\x0d\x0aHost: %s\x0d\x0a",
945 p += sprintf(p, "Origin: %s\x0d\x0a",
949 p += sprintf(p, "Sec-WebSocket-Protocol: %s"
950 "\x0d\x0a", wsi->c_protocol);
952 p += sprintf(p, "Sec-WebSocket-Key1: %s\x0d\x0a",
954 p += sprintf(p, "Sec-WebSocket-Key2: %s\x0d\x0a",
957 /* give userland a chance to append, eg, cookies */
959 context->protocols[0].callback(context, wsi,
960 LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER,
961 NULL, &p, (pkt + sizeof(pkt)) - p - 12);
963 p += sprintf(p, "\x0d\x0a");
965 read(context->fd_random, p, 8);
966 memcpy(&challenge[8], p, 8);
969 /* precompute what we want to see from the server */
971 MD5((unsigned char *)challenge, 16,
972 (unsigned char *)wsi->initial_handshake_hash_base64);
977 p += sprintf(p, "Host: %s\x0d\x0a", wsi->c_host);
978 p += sprintf(p, "Upgrade: websocket\x0d\x0a");
979 p += sprintf(p, "Connection: Upgrade\x0d\x0a"
980 "Sec-WebSocket-Key: ");
981 strcpy(p, wsi->key_b64);
982 p += strlen(wsi->key_b64);
983 p += sprintf(p, "\x0d\x0a");
985 p += sprintf(p, "Sec-WebSocket-Origin: %s\x0d\x0a",
988 p += sprintf(p, "Sec-WebSocket-Protocol: %s\x0d\x0a",
990 p += sprintf(p, "Sec-WebSocket-Version: %d\x0d\x0a",
991 wsi->ietf_spec_revision);
992 /* give userland a chance to append, eg, cookies */
994 context->protocols[0].callback(context, wsi,
995 LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER,
996 NULL, &p, (pkt + sizeof(pkt)) - p - 12);
998 p += sprintf(p, "\x0d\x0a");
1000 /* prepare the expected server accept response */
1002 strcpy((char *)buf, wsi->key_b64);
1003 strcpy((char *)&buf[strlen((char *)buf)], magic_websocket_guid);
1005 SHA1(buf, strlen((char *)buf), (unsigned char *)hash);
1007 lws_b64_encode_string(hash, 20,
1008 wsi->initial_handshake_hash_base64,
1009 sizeof wsi->initial_handshake_hash_base64);
1013 /* done with these now */
1018 free(wsi->c_origin);
1020 /* send our request to the server */
1022 #ifdef LWS_OPENSSL_SUPPORT
1024 n = SSL_write(wsi->ssl, pkt, p - pkt);
1027 n = send(wsi->sock, pkt, p - pkt, 0);
1030 fprintf(stderr, "ERROR writing to client socket\n");
1031 libwebsocket_close_and_free_session(context, wsi,
1032 LWS_CLOSE_STATUS_NOSTATUS);
1036 wsi->parser_state = WSI_TOKEN_NAME_PART;
1037 wsi->mode = LWS_CONNMODE_WS_CLIENT_WAITING_SERVER_REPLY;
1038 libwebsocket_set_timeout(wsi,
1039 PENDING_TIMEOUT_AWAITING_SERVER_RESPONSE, 5);
1043 case LWS_CONNMODE_WS_CLIENT_WAITING_SERVER_REPLY:
1045 /* handle server hung up on us */
1047 if (pollfd->revents & (POLLERR | POLLHUP)) {
1049 fprintf(stderr, "Server connection %p (fd=%d) dead\n",
1050 (void *)wsi, pollfd->fd);
1056 /* interpret the server response */
1059 * HTTP/1.1 101 Switching Protocols
1060 * Upgrade: websocket
1061 * Connection: Upgrade
1062 * Sec-WebSocket-Accept: me89jWimTRKTWwrS3aRrL53YZSo=
1063 * Sec-WebSocket-Nonce: AQIDBAUGBwgJCgsMDQ4PEC==
1064 * Sec-WebSocket-Protocol: chat
1067 #ifdef LWS_OPENSSL_SUPPORT
1069 len = SSL_read(wsi->ssl, pkt, sizeof pkt);
1072 len = recv(wsi->sock, pkt, sizeof pkt, 0);
1076 "libwebsocket_client_handshake read error\n");
1081 for (n = 0; n < len; n++)
1082 libwebsocket_parse(wsi, *p++);
1084 if (wsi->parser_state != WSI_PARSING_COMPLETE) {
1085 fprintf(stderr, "libwebsocket_client_handshake "
1086 "server response failed parsing\n");
1093 * HTTP/1.1 101 WebSocket Protocol Handshake
1094 * Upgrade: WebSocket
1095 * Connection: Upgrade
1096 * Sec-WebSocket-Origin: http://127.0.0.1
1097 * Sec-WebSocket-Location: ws://127.0.0.1:9999/socket.io/websocket
1102 if (wsi->ietf_spec_revision == 0) {
1103 if (!wsi->utf8_token[WSI_TOKEN_HTTP].token_len ||
1104 !wsi->utf8_token[WSI_TOKEN_UPGRADE].token_len ||
1105 !wsi->utf8_token[WSI_TOKEN_CHALLENGE].token_len ||
1106 !wsi->utf8_token[WSI_TOKEN_CONNECTION].token_len ||
1107 (!wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len &&
1108 wsi->c_protocol != NULL)) {
1109 fprintf(stderr, "libwebsocket_client_handshake "
1110 "missing required header(s)\n");
1112 fprintf(stderr, "%s", pkt);
1116 strtolower(wsi->utf8_token[WSI_TOKEN_HTTP].token);
1117 if (strcmp(wsi->utf8_token[WSI_TOKEN_HTTP].token,
1118 "101 websocket protocol handshake")) {
1119 fprintf(stderr, "libwebsocket_client_handshake "
1120 "server sent bad HTTP response '%s'\n",
1121 wsi->utf8_token[WSI_TOKEN_HTTP].token);
1125 if (wsi->utf8_token[WSI_TOKEN_CHALLENGE].token_len <
1127 fprintf(stderr, "libwebsocket_client_handshake "
1128 "challenge reply too short %d\n",
1130 WSI_TOKEN_CHALLENGE].token_len);
1132 fprintf(stderr, "%s", pkt);
1137 goto select_protocol;
1141 * well, what the server sent looked reasonable for syntax.
1142 * Now let's confirm it sent all the necessary headers
1145 if (!wsi->utf8_token[WSI_TOKEN_HTTP].token_len ||
1146 !wsi->utf8_token[WSI_TOKEN_UPGRADE].token_len ||
1147 !wsi->utf8_token[WSI_TOKEN_CONNECTION].token_len ||
1148 !wsi->utf8_token[WSI_TOKEN_ACCEPT].token_len ||
1149 (!wsi->utf8_token[WSI_TOKEN_NONCE].token_len &&
1150 wsi->ietf_spec_revision == 4) ||
1151 (!wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len &&
1152 wsi->c_protocol != NULL)) {
1153 fprintf(stderr, "libwebsocket_client_handshake "
1154 "missing required header(s)\n");
1156 fprintf(stderr, "%s", pkt);
1161 * Everything seems to be there, now take a closer look at what
1165 strtolower(wsi->utf8_token[WSI_TOKEN_HTTP].token);
1166 if (strcmp(wsi->utf8_token[WSI_TOKEN_HTTP].token,
1167 "101 switching protocols")) {
1168 fprintf(stderr, "libwebsocket_client_handshake "
1169 "server sent bad HTTP response '%s'\n",
1170 wsi->utf8_token[WSI_TOKEN_HTTP].token);
1174 strtolower(wsi->utf8_token[WSI_TOKEN_UPGRADE].token);
1175 if (strcmp(wsi->utf8_token[WSI_TOKEN_UPGRADE].token,
1177 fprintf(stderr, "libwebsocket_client_handshake server "
1178 "sent bad Upgrade header '%s'\n",
1179 wsi->utf8_token[WSI_TOKEN_UPGRADE].token);
1183 strtolower(wsi->utf8_token[WSI_TOKEN_CONNECTION].token);
1184 if (strcmp(wsi->utf8_token[WSI_TOKEN_CONNECTION].token,
1186 fprintf(stderr, "libwebsocket_client_handshake server "
1187 "sent bad Connection hdr '%s'\n",
1188 wsi->utf8_token[WSI_TOKEN_CONNECTION].token);
1193 pc = wsi->c_protocol;
1196 * confirm the protocol the server wants to talk was in the list
1197 * of protocols we offered
1200 if (!wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len) {
1203 * no protocol name to work from,
1204 * default to first protocol
1206 wsi->protocol = &context->protocols[0];
1208 free(wsi->c_protocol);
1213 while (*pc && !okay) {
1215 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token,
1216 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len)) &&
1217 (pc[wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len] == ',' ||
1218 pc[wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len] == '\0')) {
1222 while (*pc && *pc != ',')
1224 while (*pc && *pc != ' ')
1228 /* done with him now */
1230 if (wsi->c_protocol)
1231 free(wsi->c_protocol);
1235 fprintf(stderr, "libwebsocket_client_handshake server "
1236 "sent bad protocol '%s'\n",
1237 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token);
1242 * identify the selected protocol struct and set it
1245 wsi->protocol = NULL;
1246 while (context->protocols[n].callback) {
1247 if (strcmp(wsi->utf8_token[WSI_TOKEN_PROTOCOL].token,
1248 context->protocols[n].name) == 0)
1249 wsi->protocol = &context->protocols[n];
1253 if (wsi->protocol == NULL) {
1254 fprintf(stderr, "libwebsocket_client_handshake server "
1255 "requested protocol '%s', which we "
1256 "said we supported but we don't!\n",
1257 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token);
1263 if (wsi->ietf_spec_revision == 0) {
1265 if (memcmp(wsi->initial_handshake_hash_base64,
1266 wsi->utf8_token[WSI_TOKEN_CHALLENGE].token, 16)) {
1267 fprintf(stderr, "libwebsocket_client_handshake "
1268 "failed 00 challenge compare\n");
1270 fprintf(stderr, "%s", pkt);
1278 * Confirm his accept token is the one we precomputed
1281 if (strcmp(wsi->utf8_token[WSI_TOKEN_ACCEPT].token,
1282 wsi->initial_handshake_hash_base64)) {
1283 fprintf(stderr, "libwebsocket_client_handshake server "
1284 "sent bad ACCEPT '%s' vs computed '%s'\n",
1285 wsi->utf8_token[WSI_TOKEN_ACCEPT].token,
1286 wsi->initial_handshake_hash_base64);
1290 if (wsi->ietf_spec_revision == 4) {
1292 * Calculate the 04 masking key to use when
1293 * sending data to server
1296 strcpy((char *)buf, wsi->key_b64);
1297 p = (char *)buf + strlen(wsi->key_b64);
1298 strcpy(p, wsi->utf8_token[WSI_TOKEN_NONCE].token);
1299 p += wsi->utf8_token[WSI_TOKEN_NONCE].token_len;
1300 strcpy(p, magic_websocket_04_masking_guid);
1301 SHA1(buf, strlen((char *)buf), wsi->masking_key_04);
1305 /* allocate the per-connection user memory (if any) */
1307 if (wsi->protocol->per_session_data_size) {
1308 wsi->user_space = malloc(
1309 wsi->protocol->per_session_data_size);
1310 if (wsi->user_space == NULL) {
1311 fprintf(stderr, "Out of memory for "
1312 "conn user space\n");
1316 wsi->user_space = NULL;
1318 /* clear his proxy connection timeout */
1320 libwebsocket_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
1322 /* mark him as being alive */
1324 wsi->state = WSI_STATE_ESTABLISHED;
1325 wsi->mode = LWS_CONNMODE_WS_CLIENT;
1327 fprintf(stderr, "handshake OK for protocol %s\n",
1328 wsi->protocol->name);
1330 /* call him back to inform him he is up */
1332 wsi->protocol->callback(context, wsi,
1333 LWS_CALLBACK_CLIENT_ESTABLISHED,
1340 if (wsi->c_protocol)
1341 free(wsi->c_protocol);
1344 libwebsocket_close_and_free_session(context, wsi,
1345 LWS_CLOSE_STATUS_NOSTATUS);
1349 case LWS_CONNMODE_WS_SERVING:
1350 case LWS_CONNMODE_WS_CLIENT:
1352 /* handle session socket closed */
1354 if (pollfd->revents & (POLLERR | POLLHUP)) {
1356 fprintf(stderr, "Session Socket %p (fd=%d) dead\n",
1357 (void *)wsi, pollfd->fd);
1359 libwebsocket_close_and_free_session(context, wsi,
1360 LWS_CLOSE_STATUS_NOSTATUS);
1364 /* the guy requested a callback when it was OK to write */
1366 if (pollfd->revents & POLLOUT) {
1368 pollfd->events &= ~POLLOUT;
1370 /* external POLL support via protocol 0 */
1371 context->protocols[0].callback(context, wsi,
1372 LWS_CALLBACK_CLEAR_MODE_POLL_FD,
1373 (void *)(long)wsi->sock, NULL, POLLOUT);
1375 wsi->protocol->callback(context, wsi,
1376 LWS_CALLBACK_CLIENT_WRITEABLE,
1381 /* any incoming data ready? */
1383 if (!(pollfd->revents & POLLIN))
1386 #ifdef LWS_OPENSSL_SUPPORT
1388 n = SSL_read(wsi->ssl, buf, sizeof buf);
1391 n = recv(pollfd->fd, buf, sizeof buf, 0);
1394 fprintf(stderr, "Socket read returned %d\n", n);
1398 libwebsocket_close_and_free_session(context, wsi,
1399 LWS_CLOSE_STATUS_NOSTATUS);
1403 /* service incoming data */
1405 n = libwebsocket_read(context, wsi, buf, n);
1419 * libwebsocket_context_destroy() - Destroy the websocket context
1420 * @context: Websocket context
1422 * This function closes any active connections and then frees the
1423 * context. After calling this, any further use of the context is
1427 libwebsocket_context_destroy(struct libwebsocket_context *context)
1431 struct libwebsocket *wsi;
1433 for (n = 0; n < FD_HASHTABLE_MODULUS; n++)
1434 for (m = 0; m < context->fd_hashtable[n].length; m++) {
1435 wsi = context->fd_hashtable[n].wsi[m];
1436 libwebsocket_close_and_free_session(context, wsi,
1437 LWS_CLOSE_STATUS_GOINGAWAY);
1442 close(context->fd_random);
1445 #ifdef LWS_OPENSSL_SUPPORT
1446 if (context->ssl_ctx)
1447 SSL_CTX_free(context->ssl_ctx);
1448 if (context->ssl_client_ctx)
1449 SSL_CTX_free(context->ssl_client_ctx);
1460 * libwebsocket_service() - Service any pending websocket activity
1461 * @context: Websocket context
1462 * @timeout_ms: Timeout for poll; 0 means return immediately if nothing needed
1463 * service otherwise block and service immediately, returning
1464 * after the timeout if nothing needed service.
1466 * This function deals with any pending websocket traffic, for three
1467 * kinds of event. It handles these events on both server and client
1468 * types of connection the same.
1470 * 1) Accept new connections to our context's server
1472 * 2) Perform pending broadcast writes initiated from other forked
1473 * processes (effectively serializing asynchronous broadcasts)
1475 * 3) Call the receive callback for incoming frame data received by
1476 * server or client connections.
1478 * You need to call this service function periodically to all the above
1479 * functions to happen; if your application is single-threaded you can
1480 * just call it in your main event loop.
1482 * Alternatively you can fork a new process that asynchronously handles
1483 * calling this service in a loop. In that case you are happy if this
1484 * call blocks your thread until it needs to take care of something and
1485 * would call it with a large nonzero timeout. Your loop then takes no
1486 * CPU while there is nothing happening.
1488 * If you are calling it in a single-threaded app, you don't want it to
1489 * wait around blocking other things in your loop from happening, so you
1490 * would call it with a timeout_ms of 0, so it returns immediately if
1491 * nothing is pending, or as soon as it services whatever was pending.
1496 libwebsocket_service(struct libwebsocket_context *context, int timeout_ms)
1500 /* stay dead once we are dead */
1502 if (context == NULL)
1505 /* wait for something to need service */
1507 n = poll(context->fds, context->fds_count, timeout_ms);
1508 if (n == 0) /* poll timeout */
1513 fprintf(stderr, "Listen Socket dead\n");
1518 /* handle accept on listening socket? */
1520 for (n = 0; n < context->fds_count; n++)
1521 if (context->fds[n].revents)
1522 libwebsocket_service_fd(context, &context->fds[n]);
1528 * libwebsocket_callback_on_writable() - Request a callback when this socket
1529 * becomes able to be written to without
1532 * @context: libwebsockets context
1533 * @wsi: Websocket connection instance to get callback for
1537 libwebsocket_callback_on_writable(struct libwebsocket_context *context,
1538 struct libwebsocket *wsi)
1542 for (n = 0; n < context->fds_count; n++)
1543 if (context->fds[n].fd == wsi->sock) {
1544 context->fds[n].events |= POLLOUT;
1545 n = context->fds_count;
1548 /* external POLL support via protocol 0 */
1549 context->protocols[0].callback(context, wsi,
1550 LWS_CALLBACK_SET_MODE_POLL_FD,
1551 (void *)(long)wsi->sock, NULL, POLLOUT);
1557 * libwebsocket_callback_on_writable_all_protocol() - Request a callback for
1558 * all connections using the given protocol when it
1559 * becomes possible to write to each socket without
1562 * @protocol: Protocol whose connections will get callbacks
1566 libwebsocket_callback_on_writable_all_protocol(
1567 const struct libwebsocket_protocols *protocol)
1569 struct libwebsocket_context *context = protocol->owning_server;
1572 struct libwebsocket *wsi;
1574 for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
1576 for (m = 0; m < context->fd_hashtable[n].length; m++) {
1578 wsi = context->fd_hashtable[n].wsi[m];
1580 if (wsi->protocol == protocol)
1581 libwebsocket_callback_on_writable(context, wsi);
1589 * libwebsocket_set_timeout() - marks the wsi as subject to a timeout
1591 * You will not need this unless you are doing something special
1593 * @wsi: Websocket connection instance
1594 * @reason: timeout reason
1595 * @secs: how many seconds
1599 libwebsocket_set_timeout(struct libwebsocket *wsi,
1600 enum pending_timeout reason, int secs)
1604 gettimeofday(&tv, NULL);
1606 wsi->pending_timeout_limit = tv.tv_sec + secs;
1607 wsi->pending_timeout = reason;
1612 * libwebsocket_get_socket_fd() - returns the socket file descriptor
1614 * You will not need this unless you are doing something special
1616 * @wsi: Websocket connection instance
1620 libwebsocket_get_socket_fd(struct libwebsocket *wsi)
1626 * libwebsocket_rx_flow_control() - Enable and disable socket servicing for
1627 * receieved packets.
1629 * If the output side of a server process becomes choked, this allows flow
1630 * control for the input side.
1632 * @wsi: Websocket connection instance to get callback for
1633 * @enable: 0 = disable read servicing for this connection, 1 = enable
1637 libwebsocket_rx_flow_control(struct libwebsocket *wsi, int enable)
1639 struct libwebsocket_context *context = wsi->protocol->owning_server;
1642 for (n = 0; n < context->fds_count; n++)
1643 if (context->fds[n].fd == wsi->sock) {
1645 context->fds[n].events |= POLLIN;
1647 context->fds[n].events &= ~POLLIN;
1653 /* external POLL support via protocol 0 */
1654 context->protocols[0].callback(context, wsi,
1655 LWS_CALLBACK_SET_MODE_POLL_FD,
1656 (void *)(long)wsi->sock, NULL, POLLIN);
1658 /* external POLL support via protocol 0 */
1659 context->protocols[0].callback(context, wsi,
1660 LWS_CALLBACK_CLEAR_MODE_POLL_FD,
1661 (void *)(long)wsi->sock, NULL, POLLIN);
1664 fprintf(stderr, "libwebsocket_callback_on_writable "
1665 "unable to find socket\n");
1670 * libwebsocket_canonical_hostname() - returns this host's hostname
1672 * This is typically used by client code to fill in the host parameter
1673 * when making a client connection. You can only call it after the context
1676 * @context: Websocket context
1681 libwebsocket_canonical_hostname(struct libwebsocket_context *context)
1683 return (const char *)context->canonical_hostname;
1687 static void sigpipe_handler(int x)
1691 #ifdef LWS_OPENSSL_SUPPORT
1693 OpenSSL_verify_callback(int preverify_ok, X509_STORE_CTX *x509_ctx)
1698 struct libwebsocket_context *context;
1700 ssl = X509_STORE_CTX_get_ex_data(x509_ctx,
1701 SSL_get_ex_data_X509_STORE_CTX_idx());
1704 * !!! nasty openssl requires the index to come as a library-scope
1707 context = SSL_get_ex_data(ssl, openssl_websocket_private_data_index);
1709 n = context->protocols[0].callback(NULL, NULL,
1710 LWS_CALLBACK_OPENSSL_PERFORM_CLIENT_CERT_VERIFICATION,
1711 x509_ctx, ssl, preverify_ok);
1713 /* convert return code from 0 = OK to 1 = OK */
1726 * libwebsocket_create_context() - Create the websocket handler
1727 * @port: Port to listen on... you can use 0 to suppress listening on
1728 * any port, that's what you want if you are not running a
1729 * websocket server at all but just using it as a client
1730 * @interf: NULL to bind the listen socket to all interfaces, or the
1731 * interface name, eg, "eth2"
1732 * @protocols: Array of structures listing supported protocols and a protocol-
1733 * specific callback for each one. The list is ended with an
1734 * entry that has a NULL callback pointer.
1735 * It's not const because we write the owning_server member
1736 * @extensions: NULL or array of libwebsocket_extension structs listing the
1737 * extensions this context supports
1738 * @ssl_cert_filepath: If libwebsockets was compiled to use ssl, and you want
1739 * to listen using SSL, set to the filepath to fetch the
1740 * server cert from, otherwise NULL for unencrypted
1741 * @ssl_private_key_filepath: filepath to private key if wanting SSL mode,
1743 * @gid: group id to change to after setting listen socket, or -1.
1744 * @uid: user id to change to after setting listen socket, or -1.
1745 * @options: 0, or LWS_SERVER_OPTION_DEFEAT_CLIENT_MASK
1747 * This function creates the listening socket and takes care
1748 * of all initialization in one step.
1750 * After initialization, it returns a struct libwebsocket_context * that
1751 * represents this server. After calling, user code needs to take care
1752 * of calling libwebsocket_service() with the context pointer to get the
1753 * server's sockets serviced. This can be done in the same process context
1754 * or a forked process, or another thread,
1756 * The protocol callback functions are called for a handful of events
1757 * including http requests coming in, websocket connections becoming
1758 * established, and data arriving; it's also called periodically to allow
1759 * async transmission.
1761 * HTTP requests are sent always to the FIRST protocol in @protocol, since
1762 * at that time websocket protocol has not been negotiated. Other
1763 * protocols after the first one never see any HTTP callack activity.
1765 * The server created is a simple http server by default; part of the
1766 * websocket standard is upgrading this http connection to a websocket one.
1768 * This allows the same server to provide files like scripts and favicon /
1769 * images or whatever over http and dynamic data over websockets all in
1770 * one place; they're all handled in the user callback.
1773 struct libwebsocket_context *
1774 libwebsocket_create_context(int port, const char *interf,
1775 struct libwebsocket_protocols *protocols,
1776 struct libwebsocket_extension *extensions,
1777 const char *ssl_cert_filepath,
1778 const char *ssl_private_key_filepath,
1779 int gid, int uid, unsigned int options)
1784 struct sockaddr_in serv_addr, cli_addr;
1786 struct libwebsocket_context *context = NULL;
1789 char hostname[1024];
1791 struct libwebsocket *wsi;
1793 #ifdef LWS_OPENSSL_SUPPORT
1795 char ssl_err_buf[512];
1800 WORD wVersionRequested;
1804 /* Use the MAKEWORD(lowbyte, highbyte) macro from Windef.h */
1805 wVersionRequested = MAKEWORD(2, 2);
1807 err = WSAStartup(wVersionRequested, &wsaData);
1809 /* Tell the user that we could not find a usable */
1811 fprintf(stderr, "WSAStartup failed with error: %d\n",
1819 context = malloc(sizeof(struct libwebsocket_context));
1821 fprintf(stderr, "No memory for websocket context\n");
1824 context->protocols = protocols;
1825 context->listen_port = port;
1826 context->http_proxy_port = 0;
1827 context->http_proxy_address[0] = '\0';
1828 context->options = options;
1829 context->fds_count = 0;
1830 context->extensions = extensions;
1833 context->fd_random = 0;
1835 context->fd_random = open(SYSTEM_RANDOM_FILEPATH, O_RDONLY);
1836 if (context->fd_random < 0) {
1837 fprintf(stderr, "Unable to open random device %s %d\n",
1838 SYSTEM_RANDOM_FILEPATH, context->fd_random);
1843 #ifdef LWS_OPENSSL_SUPPORT
1844 context->use_ssl = 0;
1845 context->ssl_ctx = NULL;
1846 context->ssl_client_ctx = NULL;
1847 openssl_websocket_private_data_index = 0;
1849 /* find canonical hostname */
1851 hostname[(sizeof hostname) - 1] = '\0';
1852 gethostname(hostname, (sizeof hostname) - 1);
1853 he = gethostbyname(hostname);
1855 strncpy(context->canonical_hostname, he->h_name,
1856 sizeof context->canonical_hostname - 1);
1857 context->canonical_hostname[
1858 sizeof context->canonical_hostname - 1] = '\0';
1860 strncpy(context->canonical_hostname, hostname,
1861 sizeof context->canonical_hostname - 1);
1863 /* split the proxy ads:port if given */
1865 p = getenv("http_proxy");
1867 strncpy(context->http_proxy_address, p,
1868 sizeof context->http_proxy_address - 1);
1869 context->http_proxy_address[
1870 sizeof context->http_proxy_address - 1] = '\0';
1872 p = strchr(context->http_proxy_address, ':');
1874 fprintf(stderr, "http_proxy needs to be ads:port\n");
1878 context->http_proxy_port = atoi(p + 1);
1880 fprintf(stderr, "Using proxy %s:%u\n",
1881 context->http_proxy_address,
1882 context->http_proxy_port);
1887 #ifdef LWS_OPENSSL_SUPPORT
1888 context->use_ssl = ssl_cert_filepath != NULL &&
1889 ssl_private_key_filepath != NULL;
1890 if (context->use_ssl)
1891 fprintf(stderr, " Compiled with SSL support, "
1894 fprintf(stderr, " Compiled with SSL support, "
1898 if (ssl_cert_filepath != NULL &&
1899 ssl_private_key_filepath != NULL) {
1900 fprintf(stderr, " Not compiled for OpenSSl support!\n");
1903 fprintf(stderr, " Compiled without SSL support, "
1904 "serving unencrypted\n");
1908 /* ignore SIGPIPE */
1911 signal(SIGPIPE, sigpipe_handler);
1915 #ifdef LWS_OPENSSL_SUPPORT
1917 /* basic openssl init */
1921 OpenSSL_add_all_algorithms();
1922 SSL_load_error_strings();
1924 openssl_websocket_private_data_index =
1925 SSL_get_ex_new_index(0, "libwebsockets", NULL, NULL, NULL);
1928 * Firefox insists on SSLv23 not SSLv3
1929 * Konq disables SSLv2 by default now, SSLv23 works
1932 method = (SSL_METHOD *)SSLv23_server_method();
1934 fprintf(stderr, "problem creating ssl method: %s\n",
1935 ERR_error_string(ERR_get_error(), ssl_err_buf));
1938 context->ssl_ctx = SSL_CTX_new(method); /* create context */
1939 if (!context->ssl_ctx) {
1940 fprintf(stderr, "problem creating ssl context: %s\n",
1941 ERR_error_string(ERR_get_error(), ssl_err_buf));
1945 /* client context */
1946 if (port == CONTEXT_PORT_NO_LISTEN)
1948 method = (SSL_METHOD *)SSLv23_client_method();
1950 fprintf(stderr, "problem creating ssl method: %s\n",
1951 ERR_error_string(ERR_get_error(), ssl_err_buf));
1954 /* create context */
1955 context->ssl_client_ctx = SSL_CTX_new(method);
1956 if (!context->ssl_client_ctx) {
1957 fprintf(stderr, "problem creating ssl context: %s\n",
1958 ERR_error_string(ERR_get_error(), ssl_err_buf));
1962 /* openssl init for cert verification (for client sockets) */
1964 if (!SSL_CTX_load_verify_locations(
1965 context->ssl_client_ctx, NULL,
1966 LWS_OPENSSL_CLIENT_CERTS))
1968 "Unable to load SSL Client certs from %s "
1969 "(set by --with-client-cert-dir= in configure) -- "
1970 " client ssl isn't going to work",
1971 LWS_OPENSSL_CLIENT_CERTS);
1974 * callback allowing user code to load extra verification certs
1975 * helping the client to verify server identity
1978 context->protocols[0].callback(context, NULL,
1979 LWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS,
1980 context->ssl_client_ctx, NULL, 0);
1982 /* as a server, are we requiring clients to identify themselves? */
1984 if (options & LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT) {
1986 /* absolutely require the client cert */
1988 SSL_CTX_set_verify(context->ssl_ctx,
1989 SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
1990 OpenSSL_verify_callback);
1993 * give user code a chance to load certs into the server
1994 * allowing it to verify incoming client certs
1997 context->protocols[0].callback(context, NULL,
1998 LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS,
1999 context->ssl_ctx, NULL, 0);
2002 if (context->use_ssl) {
2004 /* openssl init for server sockets */
2006 /* set the local certificate from CertFile */
2007 n = SSL_CTX_use_certificate_file(context->ssl_ctx,
2008 ssl_cert_filepath, SSL_FILETYPE_PEM);
2010 fprintf(stderr, "problem getting cert '%s': %s\n",
2012 ERR_error_string(ERR_get_error(), ssl_err_buf));
2015 /* set the private key from KeyFile */
2016 if (SSL_CTX_use_PrivateKey_file(context->ssl_ctx,
2017 ssl_private_key_filepath, SSL_FILETYPE_PEM) != 1) {
2018 fprintf(stderr, "ssl problem getting key '%s': %s\n",
2019 ssl_private_key_filepath,
2020 ERR_error_string(ERR_get_error(), ssl_err_buf));
2023 /* verify private key */
2024 if (!SSL_CTX_check_private_key(context->ssl_ctx)) {
2025 fprintf(stderr, "Private SSL key doesn't match cert\n");
2029 /* SSL is happy and has a cert it's content with */
2035 if (lws_b64_selftest())
2038 /* fd hashtable init */
2040 for (n = 0; n < FD_HASHTABLE_MODULUS; n++)
2041 context->fd_hashtable[n].length = 0;
2043 /* set up our external listening socket we serve on */
2047 sockfd = socket(AF_INET, SOCK_STREAM, 0);
2049 fprintf(stderr, "ERROR opening socket");
2053 /* allow us to restart even if old sockets in TIME_WAIT */
2054 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
2056 bzero((char *) &serv_addr, sizeof(serv_addr));
2057 serv_addr.sin_family = AF_INET;
2059 serv_addr.sin_addr.s_addr = INADDR_ANY;
2061 interface_to_sa(interf, &serv_addr,
2063 serv_addr.sin_port = htons(port);
2065 n = bind(sockfd, (struct sockaddr *) &serv_addr,
2068 fprintf(stderr, "ERROR on binding to port %d (%d %d)\n",
2073 wsi = malloc(sizeof(struct libwebsocket));
2074 memset(wsi, 0, sizeof (struct libwebsocket));
2076 wsi->count_active_extensions = 0;
2077 wsi->mode = LWS_CONNMODE_SERVER_LISTENER;
2078 insert_wsi(context, wsi);
2081 fprintf(stderr, " Listening on port %d\n", port);
2083 /* list in the internal poll array */
2085 context->fds[context->fds_count].fd = sockfd;
2086 context->fds[context->fds_count++].events = POLLIN;
2088 /* external POLL support via protocol 0 */
2089 context->protocols[0].callback(context, wsi,
2090 LWS_CALLBACK_ADD_POLL_FD,
2091 (void *)(long)sockfd, NULL, POLLIN);
2095 /* drop any root privs for this process */
2100 fprintf(stderr, "setgid: %s\n", strerror(errno));
2103 fprintf(stderr, "setuid: %s\n", strerror(errno));
2106 /* set up our internal broadcast trigger sockets per-protocol */
2108 for (context->count_protocols = 0;
2109 protocols[context->count_protocols].callback;
2110 context->count_protocols++) {
2111 protocols[context->count_protocols].owning_server = context;
2112 protocols[context->count_protocols].protocol_index =
2113 context->count_protocols;
2115 fd = socket(AF_INET, SOCK_STREAM, 0);
2117 fprintf(stderr, "ERROR opening socket");
2121 /* allow us to restart even if old sockets in TIME_WAIT */
2122 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
2124 bzero((char *) &serv_addr, sizeof(serv_addr));
2125 serv_addr.sin_family = AF_INET;
2126 serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
2127 serv_addr.sin_port = 0; /* pick the port for us */
2129 n = bind(fd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));
2131 fprintf(stderr, "ERROR on binding to port %d (%d %d)\n",
2136 slen = sizeof cli_addr;
2137 n = getsockname(fd, (struct sockaddr *)&cli_addr, &slen);
2139 fprintf(stderr, "getsockname failed\n");
2142 protocols[context->count_protocols].broadcast_socket_port =
2143 ntohs(cli_addr.sin_port);
2146 debug(" Protocol %s broadcast socket %d\n",
2147 protocols[context->count_protocols].name,
2148 ntohs(cli_addr.sin_port));
2150 /* dummy wsi per broadcast proxy socket */
2152 wsi = malloc(sizeof(struct libwebsocket));
2153 memset(wsi, 0, sizeof (struct libwebsocket));
2155 wsi->mode = LWS_CONNMODE_BROADCAST_PROXY_LISTENER;
2156 wsi->count_active_extensions = 0;
2157 /* note which protocol we are proxying */
2158 wsi->protocol_index_for_broadcast_proxy =
2159 context->count_protocols;
2160 insert_wsi(context, wsi);
2162 /* list in internal poll array */
2164 context->fds[context->fds_count].fd = fd;
2165 context->fds[context->fds_count].events = POLLIN;
2166 context->fds[context->fds_count].revents = 0;
2167 context->fds_count++;
2169 /* external POLL support via protocol 0 */
2170 context->protocols[0].callback(context, wsi,
2171 LWS_CALLBACK_ADD_POLL_FD,
2172 (void *)(long)fd, NULL, POLLIN);
2182 * libwebsockets_fork_service_loop() - Optional helper function forks off
2183 * a process for the websocket server loop.
2184 * You don't have to use this but if not, you
2185 * have to make sure you are calling
2186 * libwebsocket_service periodically to service
2187 * the websocket traffic
2188 * @context: server context returned by creation function
2192 libwebsockets_fork_service_loop(struct libwebsocket_context *context)
2195 struct sockaddr_in cli_addr;
2205 /* main process context */
2208 * set up the proxy sockets to allow broadcast from
2209 * service process context
2212 for (p = 0; p < context->count_protocols; p++) {
2213 fd = socket(AF_INET, SOCK_STREAM, 0);
2215 fprintf(stderr, "Unable to create socket\n");
2218 cli_addr.sin_family = AF_INET;
2219 cli_addr.sin_port = htons(
2220 context->protocols[p].broadcast_socket_port);
2221 cli_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
2222 n = connect(fd, (struct sockaddr *)&cli_addr,
2225 fprintf(stderr, "Unable to connect to "
2226 "broadcast socket %d, %s\n",
2227 n, strerror(errno));
2231 context->protocols[p].broadcast_socket_user_fd = fd;
2237 /* we want a SIGHUP when our parent goes down */
2238 prctl(PR_SET_PDEATHSIG, SIGHUP);
2240 /* in this forked process, sit and service websocket connections */
2243 if (libwebsocket_service(context, 1000))
2252 * libwebsockets_get_protocol() - Returns a protocol pointer from a websocket
2254 * @wsi: pointer to struct websocket you want to know the protocol of
2257 * This is useful to get the protocol to broadcast back to from inside
2261 const struct libwebsocket_protocols *
2262 libwebsockets_get_protocol(struct libwebsocket *wsi)
2264 return wsi->protocol;
2268 * libwebsockets_broadcast() - Sends a buffer to the callback for all active
2269 * connections of the given protocol.
2270 * @protocol: pointer to the protocol you will broadcast to all members of
2271 * @buf: buffer containing the data to be broadcase. NOTE: this has to be
2272 * allocated with LWS_SEND_BUFFER_PRE_PADDING valid bytes before
2273 * the pointer and LWS_SEND_BUFFER_POST_PADDING afterwards in the
2274 * case you are calling this function from callback context.
2275 * @len: length of payload data in buf, starting from buf.
2277 * This function allows bulk sending of a packet to every connection using
2278 * the given protocol. It does not send the data directly; instead it calls
2279 * the callback with a reason type of LWS_CALLBACK_BROADCAST. If the callback
2280 * wants to actually send the data for that connection, the callback itself
2281 * should call libwebsocket_write().
2283 * libwebsockets_broadcast() can be called from another fork context without
2284 * having to take any care about data visibility between the processes, it'll
2290 libwebsockets_broadcast(const struct libwebsocket_protocols *protocol,
2291 unsigned char *buf, size_t len)
2293 struct libwebsocket_context *context = protocol->owning_server;
2296 struct libwebsocket * wsi;
2298 if (!protocol->broadcast_socket_user_fd) {
2300 * We are either running unforked / flat, or we are being
2301 * called from poll thread context
2302 * eg, from a callback. In that case don't use sockets for
2303 * broadcast IPC (since we can't open a socket connection to
2304 * a socket listening on our own thread) but directly do the
2307 * Locking is not needed because we are by definition being
2308 * called in the poll thread context and are serialized.
2311 for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
2313 for (m = 0; m < context->fd_hashtable[n].length; m++) {
2315 wsi = context->fd_hashtable[n].wsi[m];
2317 if (wsi->mode != LWS_CONNMODE_WS_SERVING)
2321 * never broadcast to
2322 * non-established connections
2324 if (wsi->state != WSI_STATE_ESTABLISHED)
2327 /* only broadcast to guys using
2328 * requested protocol
2330 if (wsi->protocol != protocol)
2333 wsi->protocol->callback(context, wsi,
2334 LWS_CALLBACK_BROADCAST,
2344 * We're being called from a different process context than the server
2345 * loop. Instead of broadcasting directly, we send our
2346 * payload on a socket to do the IPC; the server process will serialize
2347 * the broadcast action in its main poll() loop.
2349 * There's one broadcast socket listening for each protocol supported
2350 * set up when the websocket server initializes
2353 n = send(protocol->broadcast_socket_user_fd, buf, len, MSG_NOSIGNAL);