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"
26 * In-place str to lower case
38 /* file descriptor hash management */
41 wsi_from_fd(struct libwebsocket_context *this, int fd)
43 int h = LWS_FD_HASH(fd);
46 for (n = 0; n < this->fd_hashtable[h].length; n++)
47 if (this->fd_hashtable[h].wsi[n]->sock == fd)
48 return this->fd_hashtable[h].wsi[n];
54 insert_wsi(struct libwebsocket_context *this, struct libwebsocket *wsi)
56 int h = LWS_FD_HASH(wsi->sock);
58 if (this->fd_hashtable[h].length == MAX_CLIENTS - 1) {
59 fprintf(stderr, "hash table overflow\n");
63 this->fd_hashtable[h].wsi[this->fd_hashtable[h].length++] = wsi;
69 delete_from_fd(struct libwebsocket_context *this, int fd)
71 int h = LWS_FD_HASH(fd);
74 for (n = 0; n < this->fd_hashtable[h].length; n++)
75 if (this->fd_hashtable[h].wsi[n]->sock == fd) {
76 while (n < this->fd_hashtable[h].length) {
77 this->fd_hashtable[h].wsi[n] =
78 this->fd_hashtable[h].wsi[n + 1];
81 this->fd_hashtable[h].length--;
86 fprintf(stderr, "Failed to find fd %d requested for "
87 "delete in hashtable\n", fd);
91 #ifdef LWS_OPENSSL_SUPPORT
93 libwebsockets_decode_ssl_error(void)
98 while ((err = ERR_get_error()) != 0) {
99 ERR_error_string_n(err, buf, sizeof(buf));
100 fprintf(stderr, "*** %s\n", buf);
107 interface_to_sa(const char* ifname, struct sockaddr_in *addr, size_t addrlen)
112 struct sockaddr_in *sin;
115 for (ifc = ifr; ifc != NULL; ifc = ifc->ifa_next) {
116 if (strcmp(ifc->ifa_name, ifname))
118 if (ifc->ifa_addr == NULL)
120 sin = (struct sockaddr_in *)ifc->ifa_addr;
121 if (sin->sin_family != AF_INET)
123 memcpy(addr, sin, addrlen);
133 libwebsocket_close_and_free_session(struct libwebsocket_context *this,
134 struct libwebsocket *wsi, enum lws_close_status reason)
138 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 2 +
139 LWS_SEND_BUFFER_POST_PADDING];
144 old_state = wsi->state;
146 if (old_state == WSI_STATE_DEAD_SOCKET)
149 /* remove this fd from wsi mapping hashtable */
151 delete_from_fd(this, wsi->sock);
153 /* delete it from the internal poll list if still present */
155 for (n = 0; n < this->fds_count; n++) {
156 if (this->fds[n].fd != wsi->sock)
158 while (n < this->fds_count - 1) {
159 this->fds[n] = this->fds[n + 1];
163 /* we only have to deal with one */
167 /* remove also from external POLL support via protocol 0 */
169 this->protocols[0].callback(this, wsi,
170 LWS_CALLBACK_DEL_POLL_FD, (void *)(long)wsi->sock, NULL, 0);
172 wsi->close_reason = reason;
175 * signal we are closing, libsocket_write will
176 * add any necessary version-specific stuff. If the write fails,
177 * no worries we are closing anyway. If we didn't initiate this
178 * close, then our state has been changed to
179 * WSI_STATE_RETURNED_CLOSE_ALREADY and we will skip this
182 if (old_state == WSI_STATE_ESTABLISHED)
183 libwebsocket_write(wsi, &buf[LWS_SEND_BUFFER_PRE_PADDING], 0,
186 wsi->state = WSI_STATE_DEAD_SOCKET;
188 /* tell the user it's all over for this guy */
190 if (wsi->protocol && wsi->protocol->callback &&
191 old_state == WSI_STATE_ESTABLISHED)
192 wsi->protocol->callback(this, wsi, LWS_CALLBACK_CLOSED,
193 wsi->user_space, NULL, 0);
195 /* free up his allocations */
197 for (n = 0; n < WSI_TOKEN_COUNT; n++)
198 if (wsi->utf8_token[n].token)
199 free(wsi->utf8_token[n].token);
201 /* fprintf(stderr, "closing fd=%d\n", wsi->sock); */
203 #ifdef LWS_OPENSSL_SUPPORT
205 n = SSL_get_fd(wsi->ssl);
206 SSL_shutdown(wsi->ssl);
211 shutdown(wsi->sock, SHUT_RDWR);
213 #ifdef LWS_OPENSSL_SUPPORT
217 free(wsi->user_space);
223 * libwebsockets_hangup_on_client() - Server calls to terminate client
225 * @this: libwebsockets context
226 * @fd: Connection socket descriptor
230 libwebsockets_hangup_on_client(struct libwebsocket_context *this, int fd)
232 struct libwebsocket *wsi = wsi_from_fd(this, fd);
237 libwebsocket_close_and_free_session(this, wsi,
238 LWS_CLOSE_STATUS_NOSTATUS);
243 * libwebsockets_get_peer_addresses() - Get client address information
244 * @fd: Connection socket descriptor
245 * @name: Buffer to take client address name
246 * @name_len: Length of client address name buffer
247 * @rip: Buffer to take client address IP qotted quad
248 * @rip_len: Length of client address IP buffer
250 * This function fills in @name and @rip with the name and IP of
251 * the client connected with socket descriptor @fd. Names may be
252 * truncated if there is not enough room. If either cannot be
253 * determined, they will be returned as valid zero-length strings.
257 libwebsockets_get_peer_addresses(int fd, char *name, int name_len,
258 char *rip, int rip_len)
261 struct sockaddr_in sin;
262 struct hostent *host;
263 struct hostent *host1;
272 if (getpeername(fd, (struct sockaddr *) &sin, &len) < 0) {
273 perror("getpeername");
277 host = gethostbyaddr((char *) &sin.sin_addr, sizeof sin.sin_addr,
280 perror("gethostbyaddr");
284 strncpy(name, host->h_name, name_len);
285 name[name_len - 1] = '\0';
287 host1 = gethostbyname(host->h_name);
293 p = host1->h_addr_list[n++];
296 if (host1->h_addrtype != AF_INET)
299 sprintf(ip, "%d.%d.%d.%d",
300 p[0], p[1], p[2], p[3]);
302 strncpy(rip, ip, rip_len);
303 rip[rip_len - 1] = '\0';
307 void libwebsockets_00_spaceout(char *key, int spaces, int seed)
313 if (*key && (seed & 1))
317 p = key + strlen(key);
326 void libwebsockets_00_spam(char *key, int count, int seed)
333 if (*key && (seed & 1))
337 p = key + strlen(key);
342 *key++ = 0x21 + ((seed & 0xffff) % 15);
343 /* 4 would use it up too fast.. not like it matters */
349 * libwebsocket_service_fd() - Service polled socket with something waiting
350 * @this: Websocket context
351 * @pollfd: The pollfd entry describing the socket fd and which events
354 * This function closes any active connections and then frees the
355 * context. After calling this, any further use of the context is
360 libwebsocket_service_fd(struct libwebsocket_context *this,
361 struct pollfd *pollfd)
363 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + MAX_BROADCAST_PAYLOAD +
364 LWS_SEND_BUFFER_POST_PADDING];
365 struct libwebsocket *wsi;
366 struct libwebsocket *new_wsi;
372 struct sockaddr_in cli_addr;
374 static const char magic_websocket_guid[] =
375 "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
376 static const char magic_websocket_04_masking_guid[] =
377 "61AC5F19-FBBA-4540-B96F-6561F1AB40A8";
383 #ifdef LWS_OPENSSL_SUPPORT
384 char ssl_err_buf[512];
387 * you can call us with pollfd = NULL to just allow the once-per-second
388 * global timeout checks; if less than a second since the last check
389 * it returns immediately then.
392 gettimeofday(&tv, NULL);
394 if (this->last_timeout_check_s != tv.tv_sec) {
395 this->last_timeout_check_s = tv.tv_sec;
397 /* global timeout check once per second */
399 for (n = 0; n < this->fds_count; n++) {
400 wsi = wsi_from_fd(this, this->fds[n].fd);
401 if (!wsi->pending_timeout)
405 * if we went beyond the allowed time, kill the
409 if (tv.tv_sec > wsi->pending_timeout_limit)
410 libwebsocket_close_and_free_session(this, wsi,
411 LWS_CLOSE_STATUS_NOSTATUS);
415 /* just here for timeout management? */
420 /* no, here to service a socket descriptor */
422 wsi = wsi_from_fd(this, pollfd->fd);
428 case LWS_CONNMODE_SERVER_LISTENER:
430 /* pollin means a client has connected to us then */
432 if (!pollfd->revents & POLLIN)
435 /* listen socket got an unencrypted connection... */
437 clilen = sizeof(cli_addr);
438 accept_fd = accept(pollfd->fd, (struct sockaddr *)&cli_addr,
441 fprintf(stderr, "ERROR on accept");
445 if (this->fds_count >= MAX_CLIENTS) {
446 fprintf(stderr, "too busy to accept new client\n");
452 * look at who we connected to and give user code a chance
453 * to reject based on client IP. There's no protocol selected
454 * yet so we issue this to protocols[0]
457 if ((this->protocols[0].callback)(this, wsi,
458 LWS_CALLBACK_FILTER_NETWORK_CONNECTION,
459 (void*)(long)accept_fd, NULL, 0)) {
460 fprintf(stderr, "Callback denied network connection\n");
465 /* accepting connection to main listener */
467 new_wsi = malloc(sizeof(struct libwebsocket));
468 if (new_wsi == NULL) {
469 fprintf(stderr, "Out of memory for new connection\n");
473 memset(new_wsi, 0, sizeof (struct libwebsocket));
474 new_wsi->sock = accept_fd;
475 new_wsi->pending_timeout = NO_PENDING_TIMEOUT;
477 #ifdef LWS_OPENSSL_SUPPORT
482 new_wsi->ssl = SSL_new(this->ssl_ctx);
483 if (new_wsi->ssl == NULL) {
484 fprintf(stderr, "SSL_new failed: %s\n",
485 ERR_error_string(SSL_get_error(
486 new_wsi->ssl, 0), NULL));
487 libwebsockets_decode_ssl_error();
492 SSL_set_fd(new_wsi->ssl, accept_fd);
494 n = SSL_accept(new_wsi->ssl);
497 * browsers seem to probe with various
498 * ssl params which fail then retry
501 debug("SSL_accept failed skt %u: %s\n",
503 ERR_error_string(SSL_get_error(
504 new_wsi->ssl, n), NULL));
511 debug("accepted new SSL conn "
512 "port %u on fd=%d SSL ver %s\n",
513 ntohs(cli_addr.sin_port), accept_fd,
514 SSL_get_version(new_wsi->ssl));
518 debug("accepted new conn port %u on fd=%d\n",
519 ntohs(cli_addr.sin_port), accept_fd);
521 /* intialize the instance struct */
523 new_wsi->state = WSI_STATE_HTTP;
524 new_wsi->name_buffer_pos = 0;
525 new_wsi->mode = LWS_CONNMODE_WS_SERVING;
527 for (n = 0; n < WSI_TOKEN_COUNT; n++) {
528 new_wsi->utf8_token[n].token = NULL;
529 new_wsi->utf8_token[n].token_len = 0;
533 * these can only be set once the protocol is known
534 * we set an unestablished connection's protocol pointer
535 * to the start of the supported list, so it can look
536 * for matching ones during the handshake
538 new_wsi->protocol = this->protocols;
539 new_wsi->user_space = NULL;
542 * Default protocol is 76 / 00
543 * After 76, there's a header specified to inform which
544 * draft the client wants, when that's seen we modify
545 * the individual connection's spec revision accordingly
547 new_wsi->ietf_spec_revision = 0;
549 insert_wsi(this, new_wsi);
552 * make sure NO events are seen yet on this new socket
553 * (otherwise we inherit old fds[client].revents from
554 * previous socket there and die mysteriously! )
556 this->fds[this->fds_count].revents = 0;
558 this->fds[this->fds_count].events = POLLIN;
559 this->fds[this->fds_count++].fd = accept_fd;
561 /* external POLL support via protocol 0 */
562 this->protocols[0].callback(this, new_wsi,
563 LWS_CALLBACK_ADD_POLL_FD,
564 (void *)(long)accept_fd, NULL, POLLIN);
568 case LWS_CONNMODE_BROADCAST_PROXY_LISTENER:
570 /* as we are listening, POLLIN means accept() is needed */
572 if (!pollfd->revents & POLLIN)
575 /* listen socket got an unencrypted connection... */
577 clilen = sizeof(cli_addr);
578 accept_fd = accept(pollfd->fd, (struct sockaddr *)&cli_addr,
581 fprintf(stderr, "ERROR on accept");
585 if (this->fds_count >= MAX_CLIENTS) {
586 fprintf(stderr, "too busy to accept new broadcast "
592 /* create a dummy wsi for the connection and add it */
594 new_wsi = malloc(sizeof(struct libwebsocket));
595 memset(new_wsi, 0, sizeof (struct libwebsocket));
596 new_wsi->sock = accept_fd;
597 new_wsi->mode = LWS_CONNMODE_BROADCAST_PROXY;
598 new_wsi->state = WSI_STATE_ESTABLISHED;
599 /* note which protocol we are proxying */
600 new_wsi->protocol_index_for_broadcast_proxy =
601 wsi->protocol_index_for_broadcast_proxy;
602 insert_wsi(this, new_wsi);
604 /* add connected socket to internal poll array */
606 this->fds[this->fds_count].revents = 0;
607 this->fds[this->fds_count].events = POLLIN;
608 this->fds[this->fds_count++].fd = accept_fd;
610 /* external POLL support via protocol 0 */
611 this->protocols[0].callback(this, new_wsi,
612 LWS_CALLBACK_ADD_POLL_FD,
613 (void *)(long)accept_fd, NULL, POLLIN);
617 case LWS_CONNMODE_BROADCAST_PROXY:
619 /* handle session socket closed */
621 if (pollfd->revents & (POLLERR | POLLHUP)) {
623 debug("Session Socket %p (fd=%d) dead\n",
624 (void *)wsi, pollfd->fd);
626 libwebsocket_close_and_free_session(this, wsi,
627 LWS_CLOSE_STATUS_NORMAL);
631 /* the guy requested a callback when it was OK to write */
633 if (pollfd->revents & POLLOUT) {
637 pollfd->events &= ~POLLOUT;
639 /* external POLL support via protocol 0 */
640 this->protocols[0].callback(this, wsi,
641 LWS_CALLBACK_CLEAR_MODE_POLL_FD,
642 (void *)(long)wsi->sock, NULL, POLLOUT);
644 wsi->protocol->callback(this, wsi,
645 LWS_CALLBACK_CLIENT_WRITEABLE,
650 /* any incoming data ready? */
652 if (!(pollfd->revents & POLLIN))
655 /* get the issued broadcast payload from the socket */
657 len = read(pollfd->fd, buf + LWS_SEND_BUFFER_PRE_PADDING,
658 MAX_BROADCAST_PAYLOAD);
660 fprintf(stderr, "Error reading broadcast payload\n");
664 /* broadcast it to all guys with this protocol index */
666 for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
668 for (m = 0; m < this->fd_hashtable[n].length; m++) {
670 new_wsi = this->fd_hashtable[n].wsi[m];
672 /* only to clients we are serving to */
674 if (new_wsi->mode != LWS_CONNMODE_WS_SERVING)
678 * never broadcast to non-established
682 if (new_wsi->state != WSI_STATE_ESTABLISHED)
686 * only broadcast to connections using
687 * the requested protocol
690 if (new_wsi->protocol->protocol_index !=
691 wsi->protocol_index_for_broadcast_proxy)
694 /* broadcast it to this connection */
696 new_wsi->protocol->callback(this, new_wsi,
697 LWS_CALLBACK_BROADCAST,
699 buf + LWS_SEND_BUFFER_PRE_PADDING, len);
704 case LWS_CONNMODE_WS_CLIENT_WAITING_PROXY_REPLY:
706 /* handle proxy hung up on us */
708 if (pollfd->revents & (POLLERR | POLLHUP)) {
710 fprintf(stderr, "Proxy connection %p (fd=%d) dead\n",
711 (void *)wsi, pollfd->fd);
713 libwebsocket_close_and_free_session(this, wsi,
714 LWS_CLOSE_STATUS_NOSTATUS);
718 n = recv(wsi->sock, pkt, sizeof pkt, 0);
720 libwebsocket_close_and_free_session(this, wsi,
721 LWS_CLOSE_STATUS_NOSTATUS);
722 fprintf(stderr, "ERROR reading from proxy socket\n");
727 if (strcmp(pkt, "HTTP/1.0 200 ") != 0) {
728 libwebsocket_close_and_free_session(this, wsi,
729 LWS_CLOSE_STATUS_NOSTATUS);
730 fprintf(stderr, "ERROR from proxy: %s\n", pkt);
734 /* clear his proxy connection timeout */
736 libwebsocket_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
740 case LWS_CONNMODE_WS_CLIENT_ISSUE_HANDSHAKE:
742 #ifdef LWS_OPENSSL_SUPPORT
745 wsi->ssl = SSL_new(this->ssl_client_ctx);
746 wsi->client_bio = BIO_new_socket(wsi->sock, BIO_NOCLOSE);
747 SSL_set_bio(wsi->ssl, wsi->client_bio, wsi->client_bio);
749 SSL_set_ex_data(wsi->ssl,
750 this->openssl_websocket_private_data_index, this);
752 if (SSL_connect(wsi->ssl) <= 0) {
753 fprintf(stderr, "SSL connect error %s\n",
754 ERR_error_string(ERR_get_error(),
756 libwebsocket_close_and_free_session(this, wsi,
757 LWS_CLOSE_STATUS_NOSTATUS);
761 n = SSL_get_verify_result(wsi->ssl);
762 if (n != X509_V_OK) && (
763 n != X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT ||
764 wsi->use_ssl != 2)) {
766 fprintf(stderr, "server's cert didn't "
767 "look good %d\n", n);
768 libwebsocket_close_and_free_session(this, wsi,
769 LWS_CLOSE_STATUS_NOSTATUS);
777 #ifdef LWS_OPENSSL_SUPPORT
782 * create the random key
785 n = read(this->fd_random, hash, 16);
787 fprintf(stderr, "Unable to read from random dev %s\n",
788 SYSTEM_RANDOM_FILEPATH);
794 free(wsi->c_protocol);
795 libwebsocket_close_and_free_session(this, wsi,
796 LWS_CLOSE_STATUS_NOSTATUS);
800 lws_b64_encode_string(hash, 16, wsi->key_b64,
801 sizeof wsi->key_b64);
804 * 00 example client handshake
806 * GET /socket.io/websocket HTTP/1.1
808 * Connection: Upgrade
809 * Host: 127.0.0.1:9999
810 * Origin: http://127.0.0.1
811 * Sec-WebSocket-Key1: 1 0 2#0W 9 89 7 92 ^
812 * Sec-WebSocket-Key2: 7 7Y 4328 B2v[8(z1
813 * Cookie: socketio=websocket
817 * 04 example client handshake
820 * Host: server.example.com
822 * Connection: Upgrade
823 * Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
824 * Sec-WebSocket-Origin: http://example.com
825 * Sec-WebSocket-Protocol: chat, superchat
826 * Sec-WebSocket-Version: 4
829 p += sprintf(p, "GET %s HTTP/1.1\x0d\x0a", wsi->c_path);
831 if (wsi->ietf_spec_revision == 0) {
832 unsigned char spaces_1, spaces_2;
833 unsigned int max_1, max_2;
834 unsigned int num_1, num_2;
835 unsigned long product_1, product_2;
842 read(this->fd_random, &spaces_1, sizeof(char));
843 read(this->fd_random, &spaces_2, sizeof(char));
845 spaces_1 = (spaces_1 % 12) + 1;
846 spaces_2 = (spaces_2 % 12) + 1;
848 max_1 = 4294967295 / spaces_1;
849 max_2 = 4294967295 / spaces_2;
851 read(this->fd_random, &num_1, sizeof(int));
852 read(this->fd_random, &num_2, sizeof(int));
854 num_1 = (num_1 % max_1);
855 num_2 = (num_2 % max_2);
857 challenge[0] = num_1 >> 24;
858 challenge[1] = num_1 >> 16;
859 challenge[2] = num_1 >> 8;
860 challenge[3] = num_1;
861 challenge[4] = num_2 >> 24;
862 challenge[5] = num_2 >> 16;
863 challenge[6] = num_2 >> 8;
864 challenge[7] = num_2;
866 product_1 = num_1 * spaces_1;
867 product_2 = num_2 * spaces_2;
869 sprintf(key_1, "%lu", product_1);
870 sprintf(key_2, "%lu", product_2);
872 read(this->fd_random, &seed, sizeof(int));
873 read(this->fd_random, &count, sizeof(int));
875 libwebsockets_00_spam(key_1, (count % 12) + 1, seed);
877 read(this->fd_random, &seed, sizeof(int));
878 read(this->fd_random, &count, sizeof(int));
880 libwebsockets_00_spam(key_2, (count % 12) + 1, seed);
882 read(this->fd_random, &seed, sizeof(int));
884 libwebsockets_00_spaceout(key_1, spaces_1, seed);
885 libwebsockets_00_spaceout(key_2, spaces_2, seed >> 16);
887 p += sprintf(p, "Upgrade: websocket\x0d\x0a"
888 "Connection: Upgrade\x0d\x0aHost: %s\x0d\x0a",
891 p += sprintf(p, "Origin: %s\x0d\x0a",
895 p += sprintf(p, "Sec-WebSocket-Protocol: %s\x0d\x0a",
898 p += sprintf(p, "Sec-WebSocket-Key1: %s\x0d\x0a",
900 p += sprintf(p, "Sec-WebSocket-Key2: %s\x0d\x0a",
903 p += sprintf(p, "\x0d\x0a");
905 read(this->fd_random, p, 8);
906 memcpy(&challenge[8], p, 8);
909 /* precompute what we want to see from the server */
911 MD5((unsigned char *)challenge, 16,
912 (unsigned char *)wsi->initial_handshake_hash_base64);
917 p += sprintf(p, "Host: %s\x0d\x0a", wsi->c_host);
918 p += sprintf(p, "Upgrade: websocket\x0d\x0a");
919 p += sprintf(p, "Connection: Upgrade\x0d\x0a"
920 "Sec-WebSocket-Key: ");
921 strcpy(p, wsi->key_b64);
922 p += strlen(wsi->key_b64);
923 p += sprintf(p, "\x0d\x0a");
925 p += sprintf(p, "Sec-WebSocket-Origin: %s\x0d\x0a",
928 p += sprintf(p, "Sec-WebSocket-Protocol: %s\x0d\x0a",
930 p += sprintf(p, "Sec-WebSocket-Version: %d\x0d\x0a\x0d\x0a",
931 wsi->ietf_spec_revision);
933 /* prepare the expected server accept response */
935 strcpy((char *)buf, wsi->key_b64);
936 strcpy((char *)&buf[strlen((char *)buf)], magic_websocket_guid);
938 SHA1(buf, strlen((char *)buf), (unsigned char *)hash);
940 lws_b64_encode_string(hash, 20,
941 wsi->initial_handshake_hash_base64,
942 sizeof wsi->initial_handshake_hash_base64);
945 /* done with these now */
953 /* send our request to the server */
955 #ifdef LWS_OPENSSL_SUPPORT
957 n = SSL_write(wsi->ssl, pkt, p - pkt);
960 n = send(wsi->sock, pkt, p - pkt, 0);
963 fprintf(stderr, "ERROR writing to client socket\n");
964 libwebsocket_close_and_free_session(this, wsi,
965 LWS_CLOSE_STATUS_NOSTATUS);
969 wsi->parser_state = WSI_TOKEN_NAME_PART;
970 wsi->mode = LWS_CONNMODE_WS_CLIENT_WAITING_SERVER_REPLY;
971 libwebsocket_set_timeout(wsi,
972 PENDING_TIMEOUT_AWAITING_SERVER_RESPONSE, 5);
976 case LWS_CONNMODE_WS_CLIENT_WAITING_SERVER_REPLY:
978 /* handle server hung up on us */
980 if (pollfd->revents & (POLLERR | POLLHUP)) {
982 fprintf(stderr, "Server connection %p (fd=%d) dead\n",
983 (void *)wsi, pollfd->fd);
989 /* interpret the server response */
992 * HTTP/1.1 101 Switching Protocols
994 * Connection: Upgrade
995 * Sec-WebSocket-Accept: me89jWimTRKTWwrS3aRrL53YZSo=
996 * Sec-WebSocket-Nonce: AQIDBAUGBwgJCgsMDQ4PEC==
997 * Sec-WebSocket-Protocol: chat
1000 #ifdef LWS_OPENSSL_SUPPORT
1002 len = SSL_read(wsi->ssl, pkt, sizeof pkt);
1005 len = recv(wsi->sock, pkt, sizeof pkt, 0);
1009 "libwebsocket_client_handshake read error\n");
1014 for (n = 0; n < len; n++)
1015 libwebsocket_parse(wsi, *p++);
1017 if (wsi->parser_state != WSI_PARSING_COMPLETE) {
1018 fprintf(stderr, "libwebsocket_client_handshake "
1019 "server response ailed parsing\n");
1026 * HTTP/1.1 101 WebSocket Protocol Handshake
1027 * Upgrade: WebSocket
1028 * Connection: Upgrade
1029 * Sec-WebSocket-Origin: http://127.0.0.1
1030 * Sec-WebSocket-Location: ws://127.0.0.1:9999/socket.io/websocket
1035 if (wsi->ietf_spec_revision == 0) {
1036 if (!wsi->utf8_token[WSI_TOKEN_HTTP].token_len ||
1037 !wsi->utf8_token[WSI_TOKEN_UPGRADE].token_len ||
1038 !wsi->utf8_token[WSI_TOKEN_CHALLENGE].token_len ||
1039 !wsi->utf8_token[WSI_TOKEN_CONNECTION].token_len ||
1040 (!wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len &&
1041 wsi->c_protocol != NULL)) {
1042 fprintf(stderr, "libwebsocket_client_handshake "
1043 "missing required header(s)\n");
1045 fprintf(stderr, "%s", pkt);
1049 strtolower(wsi->utf8_token[WSI_TOKEN_HTTP].token);
1050 if (strcmp(wsi->utf8_token[WSI_TOKEN_HTTP].token,
1051 "101 websocket protocol handshake")) {
1052 fprintf(stderr, "libwebsocket_client_handshake "
1053 "server sent bad HTTP response '%s'\n",
1054 wsi->utf8_token[WSI_TOKEN_HTTP].token);
1058 if (wsi->utf8_token[WSI_TOKEN_CHALLENGE].token_len < 16) {
1059 fprintf(stderr, "libwebsocket_client_handshake "
1060 "challenge reply too short %d\n",
1061 wsi->utf8_token[WSI_TOKEN_CHALLENGE].token_len);
1063 fprintf(stderr, "%s", pkt);
1068 goto select_protocol;
1072 * well, what the server sent looked reasonable for syntax.
1073 * Now let's confirm it sent all the necessary headers
1076 if (!wsi->utf8_token[WSI_TOKEN_HTTP].token_len ||
1077 !wsi->utf8_token[WSI_TOKEN_UPGRADE].token_len ||
1078 !wsi->utf8_token[WSI_TOKEN_CONNECTION].token_len ||
1079 !wsi->utf8_token[WSI_TOKEN_ACCEPT].token_len ||
1080 (!wsi->utf8_token[WSI_TOKEN_NONCE].token_len &&
1081 wsi->ietf_spec_revision == 4) ||
1082 (!wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len &&
1083 wsi->c_protocol != NULL)) {
1084 fprintf(stderr, "libwebsocket_client_handshake "
1085 "missing required header(s)\n");
1087 fprintf(stderr, "%s", pkt);
1092 * Everything seems to be there, now take a closer look at what
1096 strtolower(wsi->utf8_token[WSI_TOKEN_HTTP].token);
1097 if (strcmp(wsi->utf8_token[WSI_TOKEN_HTTP].token,
1098 "101 switching protocols")) {
1099 fprintf(stderr, "libwebsocket_client_handshake "
1100 "server sent bad HTTP response '%s'\n",
1101 wsi->utf8_token[WSI_TOKEN_HTTP].token);
1105 strtolower(wsi->utf8_token[WSI_TOKEN_UPGRADE].token);
1106 if (strcmp(wsi->utf8_token[WSI_TOKEN_UPGRADE].token,
1108 fprintf(stderr, "libwebsocket_client_handshake server "
1109 "sent bad Upgrade header '%s'\n",
1110 wsi->utf8_token[WSI_TOKEN_UPGRADE].token);
1114 strtolower(wsi->utf8_token[WSI_TOKEN_CONNECTION].token);
1115 if (strcmp(wsi->utf8_token[WSI_TOKEN_CONNECTION].token,
1117 fprintf(stderr, "libwebsocket_client_handshake server "
1118 "sent bad Connection hdr '%s'\n",
1119 wsi->utf8_token[WSI_TOKEN_CONNECTION].token);
1125 pc = wsi->c_protocol;
1128 * confirm the protocol the server wants to talk was in the list
1129 * of protocols we offered
1132 if (!wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len) {
1135 * no protocol name to work from,
1136 * default to first protocol
1138 wsi->protocol = &this->protocols[0];
1140 free(wsi->c_protocol);
1145 while (*pc && !okay) {
1147 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token,
1148 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len)) &&
1149 (pc[wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len] == ',' ||
1150 pc[wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len] == '\0')) {
1154 while (*pc && *pc != ',')
1156 while (*pc && *pc != ' ')
1160 /* done with him now */
1162 if (wsi->c_protocol)
1163 free(wsi->c_protocol);
1167 fprintf(stderr, "libwebsocket_client_handshake server "
1168 "sent bad protocol '%s'\n",
1169 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token);
1174 * identify the selected protocol struct and set it
1177 wsi->protocol = NULL;
1178 while (this->protocols[n].callback) {
1179 if (strcmp(wsi->utf8_token[WSI_TOKEN_PROTOCOL].token,
1180 this->protocols[n].name) == 0)
1181 wsi->protocol = &this->protocols[n];
1185 if (wsi->protocol == NULL) {
1186 fprintf(stderr, "libwebsocket_client_handshake server "
1187 "requested protocol '%s', which we "
1188 "said we supported but we don't!\n",
1189 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token);
1195 if (wsi->ietf_spec_revision == 0) {
1197 if (memcmp(wsi->initial_handshake_hash_base64,
1198 wsi->utf8_token[WSI_TOKEN_CHALLENGE].token, 16)) {
1199 fprintf(stderr, "libwebsocket_client_handshake "
1200 "failed 00 challenge compare\n");
1203 fprintf(stderr, "%s", pkt);
1211 * Confirm his accept token is the one we precomputed
1214 if (strcmp(wsi->utf8_token[WSI_TOKEN_ACCEPT].token,
1215 wsi->initial_handshake_hash_base64)) {
1216 fprintf(stderr, "libwebsocket_client_handshake server "
1217 "sent bad ACCEPT '%s' vs computed '%s'\n",
1218 wsi->utf8_token[WSI_TOKEN_ACCEPT].token,
1219 wsi->initial_handshake_hash_base64);
1223 if (wsi->ietf_spec_revision == 4) {
1225 * Calculate the 04 masking key to use when
1226 * sending data to server
1229 strcpy((char *)buf, wsi->key_b64);
1230 p = (char *)buf + strlen(wsi->key_b64);
1231 strcpy(p, wsi->utf8_token[WSI_TOKEN_NONCE].token);
1232 p += wsi->utf8_token[WSI_TOKEN_NONCE].token_len;
1233 strcpy(p, magic_websocket_04_masking_guid);
1234 SHA1(buf, strlen((char *)buf), wsi->masking_key_04);
1239 /* allocate the per-connection user memory (if any) */
1241 if (wsi->protocol->per_session_data_size) {
1242 wsi->user_space = malloc(
1243 wsi->protocol->per_session_data_size);
1244 if (wsi->user_space == NULL) {
1245 fprintf(stderr, "Out of memory for "
1246 "conn user space\n");
1250 wsi->user_space = NULL;
1252 /* clear his proxy connection timeout */
1254 libwebsocket_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
1256 /* mark him as being alive */
1258 wsi->state = WSI_STATE_ESTABLISHED;
1259 wsi->mode = LWS_CONNMODE_WS_CLIENT;
1261 fprintf(stderr, "handshake OK for protocol %s\n",
1262 wsi->protocol->name);
1264 /* call him back to inform him he is up */
1266 wsi->protocol->callback(this, wsi,
1267 LWS_CALLBACK_CLIENT_ESTABLISHED,
1274 if (wsi->c_protocol)
1275 free(wsi->c_protocol);
1278 libwebsocket_close_and_free_session(this, wsi,
1279 LWS_CLOSE_STATUS_NOSTATUS);
1283 case LWS_CONNMODE_WS_SERVING:
1284 case LWS_CONNMODE_WS_CLIENT:
1286 /* handle session socket closed */
1288 if (pollfd->revents & (POLLERR | POLLHUP)) {
1290 fprintf(stderr, "Session Socket %p (fd=%d) dead\n",
1291 (void *)wsi, pollfd->fd);
1293 libwebsocket_close_and_free_session(this, wsi,
1294 LWS_CLOSE_STATUS_NOSTATUS);
1298 /* the guy requested a callback when it was OK to write */
1300 if (pollfd->revents & POLLOUT) {
1302 pollfd->events &= ~POLLOUT;
1304 /* external POLL support via protocol 0 */
1305 this->protocols[0].callback(this, wsi,
1306 LWS_CALLBACK_CLEAR_MODE_POLL_FD,
1307 (void *)(long)wsi->sock, NULL, POLLOUT);
1309 wsi->protocol->callback(this, wsi,
1310 LWS_CALLBACK_CLIENT_WRITEABLE,
1315 /* any incoming data ready? */
1317 if (!(pollfd->revents & POLLIN))
1320 #ifdef LWS_OPENSSL_SUPPORT
1322 n = SSL_read(wsi->ssl, buf, sizeof buf);
1325 n = recv(pollfd->fd, buf, sizeof buf, 0);
1328 fprintf(stderr, "Socket read returned %d\n", n);
1332 libwebsocket_close_and_free_session(this, wsi,
1333 LWS_CLOSE_STATUS_NOSTATUS);
1337 /* service incoming data */
1339 n = libwebsocket_read(this, wsi, buf, n);
1353 * libwebsocket_context_destroy() - Destroy the websocket context
1354 * @this: Websocket context
1356 * This function closes any active connections and then frees the
1357 * context. After calling this, any further use of the context is
1361 libwebsocket_context_destroy(struct libwebsocket_context *this)
1365 struct libwebsocket *wsi;
1367 for (n = 0; n < FD_HASHTABLE_MODULUS; n++)
1368 for (m = 0; m < this->fd_hashtable[n].length; m++) {
1369 wsi = this->fd_hashtable[n].wsi[m];
1370 libwebsocket_close_and_free_session(this, wsi,
1371 LWS_CLOSE_STATUS_GOINGAWAY);
1374 close(this->fd_random);
1376 #ifdef LWS_OPENSSL_SUPPORT
1378 SSL_CTX_free(this->ssl_ctx);
1379 if (this->ssl_client_ctx)
1380 SSL_CTX_free(this->ssl_client_ctx);
1387 * libwebsocket_service() - Service any pending websocket activity
1388 * @this: Websocket context
1389 * @timeout_ms: Timeout for poll; 0 means return immediately if nothing needed
1390 * service otherwise block and service immediately, returning
1391 * after the timeout if nothing needed service.
1393 * This function deals with any pending websocket traffic, for three
1394 * kinds of event. It handles these events on both server and client
1395 * types of connection the same.
1397 * 1) Accept new connections to our context's server
1399 * 2) Perform pending broadcast writes initiated from other forked
1400 * processes (effectively serializing asynchronous broadcasts)
1402 * 3) Call the receive callback for incoming frame data received by
1403 * server or client connections.
1405 * You need to call this service function periodically to all the above
1406 * functions to happen; if your application is single-threaded you can
1407 * just call it in your main event loop.
1409 * Alternatively you can fork a new process that asynchronously handles
1410 * calling this service in a loop. In that case you are happy if this
1411 * call blocks your thread until it needs to take care of something and
1412 * would call it with a large nonzero timeout. Your loop then takes no
1413 * CPU while there is nothing happening.
1415 * If you are calling it in a single-threaded app, you don't want it to
1416 * wait around blocking other things in your loop from happening, so you
1417 * would call it with a timeout_ms of 0, so it returns immediately if
1418 * nothing is pending, or as soon as it services whatever was pending.
1423 libwebsocket_service(struct libwebsocket_context *this, int timeout_ms)
1427 /* stay dead once we are dead */
1432 /* wait for something to need service */
1434 n = poll(this->fds, this->fds_count, timeout_ms);
1435 if (n == 0) /* poll timeout */
1440 fprintf(stderr, "Listen Socket dead\n");
1445 /* handle accept on listening socket? */
1447 for (n = 0; n < this->fds_count; n++)
1448 if (this->fds[n].revents)
1449 libwebsocket_service_fd(this, &this->fds[n]);
1455 * libwebsocket_callback_on_writable() - Request a callback when this socket
1456 * becomes able to be written to without
1459 * @this: libwebsockets context
1460 * @wsi: Websocket connection instance to get callback for
1464 libwebsocket_callback_on_writable(struct libwebsocket_context *this,
1465 struct libwebsocket *wsi)
1469 for (n = 0; n < this->fds_count; n++)
1470 if (this->fds[n].fd == wsi->sock) {
1471 this->fds[n].events |= POLLOUT;
1472 n = this->fds_count;
1475 /* external POLL support via protocol 0 */
1476 this->protocols[0].callback(this, wsi,
1477 LWS_CALLBACK_SET_MODE_POLL_FD,
1478 (void *)(long)wsi->sock, NULL, POLLOUT);
1484 * libwebsocket_callback_on_writable_all_protocol() - Request a callback for
1485 * all connections using the given protocol when it
1486 * becomes possible to write to each socket without
1489 * @protocol: Protocol whose connections will get callbacks
1493 libwebsocket_callback_on_writable_all_protocol(
1494 const struct libwebsocket_protocols *protocol)
1496 struct libwebsocket_context *this = protocol->owning_server;
1499 struct libwebsocket *wsi;
1501 for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
1503 for (m = 0; m < this->fd_hashtable[n].length; m++) {
1505 wsi = this->fd_hashtable[n].wsi[m];
1507 if (wsi->protocol == protocol)
1508 libwebsocket_callback_on_writable(this, wsi);
1516 * libwebsocket_set_timeout() - marks the wsi as subject to a timeout
1518 * You will not need this unless you are doing something special
1520 * @wsi: Websocket connection instance
1521 * @reason: timeout reason
1522 * @secs: how many seconds
1526 libwebsocket_set_timeout(struct libwebsocket *wsi,
1527 enum pending_timeout reason, int secs)
1531 gettimeofday(&tv, NULL);
1533 wsi->pending_timeout_limit = tv.tv_sec + secs;
1534 wsi->pending_timeout = reason;
1539 * libwebsocket_get_socket_fd() - returns the socket file descriptor
1541 * You will not need this unless you are doing something special
1543 * @wsi: Websocket connection instance
1547 libwebsocket_get_socket_fd(struct libwebsocket *wsi)
1553 * libwebsocket_rx_flow_control() - Enable and disable socket servicing for
1554 * receieved packets.
1556 * If the output side of a server process becomes choked, this allows flow
1557 * control for the input side.
1559 * @wsi: Websocket connection instance to get callback for
1560 * @enable: 0 = disable read servicing for this connection, 1 = enable
1564 libwebsocket_rx_flow_control(struct libwebsocket *wsi, int enable)
1566 struct libwebsocket_context *this = wsi->protocol->owning_server;
1569 for (n = 0; n < this->fds_count; n++)
1570 if (this->fds[n].fd == wsi->sock) {
1572 this->fds[n].events |= POLLIN;
1574 this->fds[n].events &= ~POLLIN;
1580 /* external POLL support via protocol 0 */
1581 this->protocols[0].callback(this, wsi,
1582 LWS_CALLBACK_SET_MODE_POLL_FD,
1583 (void *)(long)wsi->sock, NULL, POLLIN);
1585 /* external POLL support via protocol 0 */
1586 this->protocols[0].callback(this, wsi,
1587 LWS_CALLBACK_CLEAR_MODE_POLL_FD,
1588 (void *)(long)wsi->sock, NULL, POLLIN);
1591 fprintf(stderr, "libwebsocket_callback_on_writable "
1592 "unable to find socket\n");
1597 * libwebsocket_canonical_hostname() - returns this host's hostname
1599 * This is typically used by client code to fill in the host parameter
1600 * when making a client connection. You can only call it after the context
1603 * @this: Websocket context
1608 libwebsocket_canonical_hostname(struct libwebsocket_context *this)
1610 return (const char *)this->canonical_hostname;
1614 static void sigpipe_handler(int x)
1618 #ifdef LWS_OPENSSL_SUPPORT
1620 OpenSSL_verify_callback(int preverify_ok, X509_STORE_CTX *x509_ctx)
1625 // struct libwebsocket_context *this;
1627 ssl = X509_STORE_CTX_get_ex_data(x509_ctx,
1628 SSL_get_ex_data_X509_STORE_CTX_idx());
1631 * !!! can't get this->openssl_websocket_private_data_index
1632 * can't store as a static either
1634 // this = SSL_get_ex_data(ssl, this->openssl_websocket_private_data_index);
1636 n = this->protocols[0].callback(NULL, NULL,
1637 LWS_CALLBACK_OPENSSL_PERFORM_CLIENT_CERT_VERIFICATION,
1638 x509_ctx, ssl, preverify_ok);
1640 /* convert return code from 0 = OK to 1 = OK */
1653 * libwebsocket_create_context() - Create the websocket handler
1654 * @port: Port to listen on... you can use 0 to suppress listening on
1655 * any port, that's what you want if you are not running a
1656 * websocket server at all but just using it as a client
1657 * @interface: NULL to bind the listen socket to all interfaces, or the
1658 * interface name, eg, "eth2"
1659 * @protocols: Array of structures listing supported protocols and a protocol-
1660 * specific callback for each one. The list is ended with an
1661 * entry that has a NULL callback pointer.
1662 * It's not const because we write the owning_server member
1663 * @ssl_cert_filepath: If libwebsockets was compiled to use ssl, and you want
1664 * to listen using SSL, set to the filepath to fetch the
1665 * server cert from, otherwise NULL for unencrypted
1666 * @ssl_private_key_filepath: filepath to private key if wanting SSL mode,
1668 * @gid: group id to change to after setting listen socket, or -1.
1669 * @uid: user id to change to after setting listen socket, or -1.
1670 * @options: 0, or LWS_SERVER_OPTION_DEFEAT_CLIENT_MASK
1672 * This function creates the listening socket and takes care
1673 * of all initialization in one step.
1675 * After initialization, it returns a struct libwebsocket_context * that
1676 * represents this server. After calling, user code needs to take care
1677 * of calling libwebsocket_service() with the context pointer to get the
1678 * server's sockets serviced. This can be done in the same process context
1679 * or a forked process, or another thread,
1681 * The protocol callback functions are called for a handful of events
1682 * including http requests coming in, websocket connections becoming
1683 * established, and data arriving; it's also called periodically to allow
1684 * async transmission.
1686 * HTTP requests are sent always to the FIRST protocol in @protocol, since
1687 * at that time websocket protocol has not been negotiated. Other
1688 * protocols after the first one never see any HTTP callack activity.
1690 * The server created is a simple http server by default; part of the
1691 * websocket standard is upgrading this http connection to a websocket one.
1693 * This allows the same server to provide files like scripts and favicon /
1694 * images or whatever over http and dynamic data over websockets all in
1695 * one place; they're all handled in the user callback.
1698 struct libwebsocket_context *
1699 libwebsocket_create_context(int port, const char *interface,
1700 struct libwebsocket_protocols *protocols,
1701 const char *ssl_cert_filepath,
1702 const char *ssl_private_key_filepath,
1703 int gid, int uid, unsigned int options)
1708 struct sockaddr_in serv_addr, cli_addr;
1710 struct libwebsocket_context *this = NULL;
1713 char hostname[1024];
1715 struct libwebsocket *wsi;
1717 #ifdef LWS_OPENSSL_SUPPORT
1719 char ssl_err_buf[512];
1722 this = malloc(sizeof(struct libwebsocket_context));
1724 fprintf(stderr, "No memory for websocket context\n");
1727 this->protocols = protocols;
1728 this->listen_port = port;
1729 this->http_proxy_port = 0;
1730 this->http_proxy_address[0] = '\0';
1731 this->options = options;
1732 this->fds_count = 0;
1734 this->fd_random = open(SYSTEM_RANDOM_FILEPATH, O_RDONLY);
1735 if (this->fd_random < 0) {
1736 fprintf(stderr, "Unable to open random device %s %d\n",
1737 SYSTEM_RANDOM_FILEPATH, this->fd_random);
1741 /* find canonical hostname */
1743 hostname[(sizeof hostname) - 1] = '\0';
1744 gethostname(hostname, (sizeof hostname) - 1);
1745 he = gethostbyname(hostname);
1747 strncpy(this->canonical_hostname, he->h_name,
1748 sizeof this->canonical_hostname - 1);
1749 this->canonical_hostname[sizeof this->canonical_hostname - 1] =
1752 strncpy(this->canonical_hostname, hostname,
1753 sizeof this->canonical_hostname - 1);
1755 /* split the proxy ads:port if given */
1757 p = getenv("http_proxy");
1759 strncpy(this->http_proxy_address, p,
1760 sizeof this->http_proxy_address - 1);
1761 this->http_proxy_address[
1762 sizeof this->http_proxy_address - 1] = '\0';
1764 p = strchr(this->http_proxy_address, ':');
1766 fprintf(stderr, "http_proxy needs to be ads:port\n");
1770 this->http_proxy_port = atoi(p + 1);
1772 fprintf(stderr, "Using proxy %s:%u\n",
1773 this->http_proxy_address,
1774 this->http_proxy_port);
1779 #ifdef LWS_OPENSSL_SUPPORT
1780 this->use_ssl = ssl_cert_filepath != NULL &&
1781 ssl_private_key_filepath != NULL;
1783 fprintf(stderr, " Compiled with SSL support, "
1786 fprintf(stderr, " Compiled with SSL support, "
1790 if (ssl_cert_filepath != NULL &&
1791 ssl_private_key_filepath != NULL) {
1792 fprintf(stderr, " Not compiled for OpenSSl support!\n");
1795 fprintf(stderr, " Compiled without SSL support, "
1796 "serving unencrypted\n");
1800 /* ignore SIGPIPE */
1802 signal(SIGPIPE, sigpipe_handler);
1805 #ifdef LWS_OPENSSL_SUPPORT
1807 /* basic openssl init */
1811 OpenSSL_add_all_algorithms();
1812 SSL_load_error_strings();
1814 this->openssl_websocket_private_data_index =
1815 SSL_get_ex_new_index(0, "libwebsockets", NULL, NULL, NULL);
1818 * Firefox insists on SSLv23 not SSLv3
1819 * Konq disables SSLv2 by default now, SSLv23 works
1822 method = (SSL_METHOD *)SSLv23_server_method();
1824 fprintf(stderr, "problem creating ssl method: %s\n",
1825 ERR_error_string(ERR_get_error(), ssl_err_buf));
1828 this->ssl_ctx = SSL_CTX_new(method); /* create context */
1829 if (!this->ssl_ctx) {
1830 fprintf(stderr, "problem creating ssl context: %s\n",
1831 ERR_error_string(ERR_get_error(), ssl_err_buf));
1835 /* client context */
1837 method = (SSL_METHOD *)SSLv23_client_method();
1839 fprintf(stderr, "problem creating ssl method: %s\n",
1840 ERR_error_string(ERR_get_error(), ssl_err_buf));
1843 this->ssl_client_ctx = SSL_CTX_new(method); /* create context */
1844 if (!this->ssl_client_ctx) {
1845 fprintf(stderr, "problem creating ssl context: %s\n",
1846 ERR_error_string(ERR_get_error(), ssl_err_buf));
1851 /* openssl init for cert verification (used with client sockets) */
1853 if (!SSL_CTX_load_verify_locations(this->ssl_client_ctx, NULL,
1854 LWS_OPENSSL_CLIENT_CERTS)) {
1855 fprintf(stderr, "Unable to load SSL Client certs from %s "
1856 "(set by --with-client-cert-dir= in configure) -- "
1857 " client ssl isn't going to work",
1858 LWS_OPENSSL_CLIENT_CERTS);
1862 * callback allowing user code to load extra verification certs
1863 * helping the client to verify server identity
1866 this->protocols[0].callback(this, NULL,
1867 LWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS,
1868 this->ssl_client_ctx, NULL, 0);
1870 /* as a server, are we requiring clients to identify themselves? */
1872 if (options & LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT) {
1874 /* absolutely require the client cert */
1876 SSL_CTX_set_verify(this->ssl_ctx,
1877 SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
1878 OpenSSL_verify_callback);
1881 * give user code a chance to load certs into the server
1882 * allowing it to verify incoming client certs
1885 this->protocols[0].callback(this, NULL,
1886 LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS,
1887 this->ssl_ctx, NULL, 0);
1890 if (this->use_ssl) {
1892 /* openssl init for server sockets */
1894 /* set the local certificate from CertFile */
1895 n = SSL_CTX_use_certificate_file(this->ssl_ctx,
1896 ssl_cert_filepath, SSL_FILETYPE_PEM);
1898 fprintf(stderr, "problem getting cert '%s': %s\n",
1900 ERR_error_string(ERR_get_error(), ssl_err_buf));
1903 /* set the private key from KeyFile */
1904 if (SSL_CTX_use_PrivateKey_file(this->ssl_ctx,
1905 ssl_private_key_filepath,
1906 SSL_FILETYPE_PEM) != 1) {
1907 fprintf(stderr, "ssl problem getting key '%s': %s\n",
1908 ssl_private_key_filepath,
1909 ERR_error_string(ERR_get_error(), ssl_err_buf));
1912 /* verify private key */
1913 if (!SSL_CTX_check_private_key(this->ssl_ctx)) {
1914 fprintf(stderr, "Private SSL key doesn't match cert\n");
1918 /* SSL is happy and has a cert it's content with */
1924 if (lws_b64_selftest())
1927 /* fd hashtable init */
1929 for (n = 0; n < FD_HASHTABLE_MODULUS; n++)
1930 this->fd_hashtable[n].length = 0;
1932 /* set up our external listening socket we serve on */
1936 sockfd = socket(AF_INET, SOCK_STREAM, 0);
1938 fprintf(stderr, "ERROR opening socket");
1942 /* allow us to restart even if old sockets in TIME_WAIT */
1943 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
1945 bzero((char *) &serv_addr, sizeof(serv_addr));
1946 serv_addr.sin_family = AF_INET;
1947 if (interface == NULL)
1948 serv_addr.sin_addr.s_addr = INADDR_ANY;
1950 interface_to_sa(interface, &serv_addr,
1952 serv_addr.sin_port = htons(port);
1954 n = bind(sockfd, (struct sockaddr *) &serv_addr,
1957 fprintf(stderr, "ERROR on binding to port %d (%d %d)\n",
1962 wsi = malloc(sizeof(struct libwebsocket));
1963 memset(wsi, 0, sizeof (struct libwebsocket));
1965 wsi->mode = LWS_CONNMODE_SERVER_LISTENER;
1966 insert_wsi(this, wsi);
1969 fprintf(stderr, " Listening on port %d\n", port);
1971 /* list in the internal poll array */
1973 this->fds[this->fds_count].fd = sockfd;
1974 this->fds[this->fds_count++].events = POLLIN;
1976 /* external POLL support via protocol 0 */
1977 this->protocols[0].callback(this, wsi,
1978 LWS_CALLBACK_ADD_POLL_FD,
1979 (void *)(long)sockfd, NULL, POLLIN);
1983 /* drop any root privs for this process */
1987 fprintf(stderr, "setgid: %s\n", strerror(errno));
1990 fprintf(stderr, "setuid: %s\n", strerror(errno));
1993 /* set up our internal broadcast trigger sockets per-protocol */
1995 for (this->count_protocols = 0;
1996 protocols[this->count_protocols].callback;
1997 this->count_protocols++) {
1998 protocols[this->count_protocols].owning_server = this;
1999 protocols[this->count_protocols].protocol_index =
2000 this->count_protocols;
2002 fd = socket(AF_INET, SOCK_STREAM, 0);
2004 fprintf(stderr, "ERROR opening socket");
2008 /* allow us to restart even if old sockets in TIME_WAIT */
2009 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
2011 bzero((char *) &serv_addr, sizeof(serv_addr));
2012 serv_addr.sin_family = AF_INET;
2013 serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
2014 serv_addr.sin_port = 0; /* pick the port for us */
2016 n = bind(fd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));
2018 fprintf(stderr, "ERROR on binding to port %d (%d %d)\n",
2023 slen = sizeof cli_addr;
2024 n = getsockname(fd, (struct sockaddr *)&cli_addr, &slen);
2026 fprintf(stderr, "getsockname failed\n");
2029 protocols[this->count_protocols].broadcast_socket_port =
2030 ntohs(cli_addr.sin_port);
2033 debug(" Protocol %s broadcast socket %d\n",
2034 protocols[this->count_protocols].name,
2035 ntohs(cli_addr.sin_port));
2037 /* dummy wsi per broadcast proxy socket */
2039 wsi = malloc(sizeof(struct libwebsocket));
2040 memset(wsi, 0, sizeof (struct libwebsocket));
2042 wsi->mode = LWS_CONNMODE_BROADCAST_PROXY_LISTENER;
2043 /* note which protocol we are proxying */
2044 wsi->protocol_index_for_broadcast_proxy = this->count_protocols;
2045 insert_wsi(this, wsi);
2047 /* list in internal poll array */
2049 this->fds[this->fds_count].fd = fd;
2050 this->fds[this->fds_count].events = POLLIN;
2051 this->fds[this->fds_count].revents = 0;
2054 /* external POLL support via protocol 0 */
2055 this->protocols[0].callback(this, wsi,
2056 LWS_CALLBACK_ADD_POLL_FD,
2057 (void *)(long)fd, NULL, POLLIN);
2067 * libwebsockets_fork_service_loop() - Optional helper function forks off
2068 * a process for the websocket server loop.
2069 * You don't have to use this but if not, you
2070 * have to make sure you are calling
2071 * libwebsocket_service periodically to service
2072 * the websocket traffic
2073 * @this: server context returned by creation function
2077 libwebsockets_fork_service_loop(struct libwebsocket_context *this)
2080 struct sockaddr_in cli_addr;
2090 /* main process context */
2093 * set up the proxy sockets to allow broadcast from
2094 * service process context
2097 for (p = 0; p < this->count_protocols; p++) {
2098 fd = socket(AF_INET, SOCK_STREAM, 0);
2100 fprintf(stderr, "Unable to create socket\n");
2103 cli_addr.sin_family = AF_INET;
2104 cli_addr.sin_port = htons(
2105 this->protocols[p].broadcast_socket_port);
2106 cli_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
2107 n = connect(fd, (struct sockaddr *)&cli_addr,
2110 fprintf(stderr, "Unable to connect to "
2111 "broadcast socket %d, %s\n",
2112 n, strerror(errno));
2116 this->protocols[p].broadcast_socket_user_fd = fd;
2122 /* we want a SIGHUP when our parent goes down */
2123 prctl(PR_SET_PDEATHSIG, SIGHUP);
2125 /* in this forked process, sit and service websocket connections */
2128 if (libwebsocket_service(this, 1000))
2137 * libwebsockets_get_protocol() - Returns a protocol pointer from a websocket
2139 * @wsi: pointer to struct websocket you want to know the protocol of
2142 * This is useful to get the protocol to broadcast back to from inside
2146 const struct libwebsocket_protocols *
2147 libwebsockets_get_protocol(struct libwebsocket *wsi)
2149 return wsi->protocol;
2153 * libwebsockets_broadcast() - Sends a buffer to the callback for all active
2154 * connections of the given protocol.
2155 * @protocol: pointer to the protocol you will broadcast to all members of
2156 * @buf: buffer containing the data to be broadcase. NOTE: this has to be
2157 * allocated with LWS_SEND_BUFFER_PRE_PADDING valid bytes before
2158 * the pointer and LWS_SEND_BUFFER_POST_PADDING afterwards in the
2159 * case you are calling this function from callback context.
2160 * @len: length of payload data in buf, starting from buf.
2162 * This function allows bulk sending of a packet to every connection using
2163 * the given protocol. It does not send the data directly; instead it calls
2164 * the callback with a reason type of LWS_CALLBACK_BROADCAST. If the callback
2165 * wants to actually send the data for that connection, the callback itself
2166 * should call libwebsocket_write().
2168 * libwebsockets_broadcast() can be called from another fork context without
2169 * having to take any care about data visibility between the processes, it'll
2175 libwebsockets_broadcast(const struct libwebsocket_protocols *protocol,
2176 unsigned char *buf, size_t len)
2178 struct libwebsocket_context *this = protocol->owning_server;
2181 struct libwebsocket * wsi;
2183 if (!protocol->broadcast_socket_user_fd) {
2185 * We are either running unforked / flat, or we are being
2186 * called from poll thread context
2187 * eg, from a callback. In that case don't use sockets for
2188 * broadcast IPC (since we can't open a socket connection to
2189 * a socket listening on our own thread) but directly do the
2192 * Locking is not needed because we are by definition being
2193 * called in the poll thread context and are serialized.
2196 for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
2198 for (m = 0; m < this->fd_hashtable[n].length; m++) {
2200 wsi = this->fd_hashtable[n].wsi[m];
2202 if (wsi->mode != LWS_CONNMODE_WS_SERVING)
2206 * never broadcast to
2207 * non-established connections
2209 if (wsi->state != WSI_STATE_ESTABLISHED)
2212 /* only broadcast to guys using
2213 * requested protocol
2215 if (wsi->protocol != protocol)
2218 wsi->protocol->callback(this, wsi,
2219 LWS_CALLBACK_BROADCAST,
2229 * We're being called from a different process context than the server
2230 * loop. Instead of broadcasting directly, we send our
2231 * payload on a socket to do the IPC; the server process will serialize
2232 * the broadcast action in its main poll() loop.
2234 * There's one broadcast socket listening for each protocol supported
2235 * set up when the websocket server initializes
2238 n = send(protocol->broadcast_socket_user_fd, buf, len, MSG_NOSIGNAL);