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"
25 * In-place str to lower case
37 /* file descriptor hash management */
40 wsi_from_fd(struct libwebsocket_context *this, int fd)
42 int h = LWS_FD_HASH(fd);
45 for (n = 0; n < this->fd_hashtable[h].length; n++)
46 if (this->fd_hashtable[h].wsi[n]->sock == fd)
47 return this->fd_hashtable[h].wsi[n];
53 insert_wsi(struct libwebsocket_context *this, struct libwebsocket *wsi)
55 int h = LWS_FD_HASH(wsi->sock);
57 if (this->fd_hashtable[h].length == MAX_CLIENTS - 1) {
58 fprintf(stderr, "hash table overflow\n");
62 this->fd_hashtable[h].wsi[this->fd_hashtable[h].length++] = wsi;
68 delete_from_fd(struct libwebsocket_context *this, int fd)
70 int h = LWS_FD_HASH(fd);
73 for (n = 0; n < this->fd_hashtable[h].length; n++)
74 if (this->fd_hashtable[h].wsi[n]->sock == fd) {
75 while (n < this->fd_hashtable[h].length) {
76 this->fd_hashtable[h].wsi[n] =
77 this->fd_hashtable[h].wsi[n + 1];
80 this->fd_hashtable[h].length--;
85 fprintf(stderr, "Failed to find fd %d requested for "
86 "delete in hashtable\n", fd);
92 libwebsocket_close_and_free_session(struct libwebsocket_context *this,
93 struct libwebsocket *wsi)
97 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 2 +
98 LWS_SEND_BUFFER_POST_PADDING];
103 old_state = wsi->state;
105 if (old_state == WSI_STATE_DEAD_SOCKET)
108 /* remove this fd from wsi mapping hashtable */
110 delete_from_fd(this, wsi->sock);
112 /* delete it from the internal poll list if still present */
114 for (n = 0; n < this->fds_count; n++) {
115 if (this->fds[n].fd != wsi->sock)
117 while (n < this->fds_count - 1) {
118 this->fds[n] = this->fds[n + 1];
122 /* we only have to deal with one */
126 /* remove also from external POLL support via protocol 0 */
128 this->protocols[0].callback(this, wsi,
129 LWS_CALLBACK_DEL_POLL_FD, (void *)(long)wsi->sock, NULL, 0);
132 * signal we are closing, libsocket_write will
133 * add any necessary version-specific stuff. If the write fails,
134 * no worries we are closing anyway. If we didn't initiate this
135 * close, then our state has been changed to
136 * WSI_STATE_RETURNED_CLOSE_ALREADY and we will skip this
139 if (old_state == WSI_STATE_ESTABLISHED)
140 libwebsocket_write(wsi, &buf[LWS_SEND_BUFFER_PRE_PADDING], 0,
143 wsi->state = WSI_STATE_DEAD_SOCKET;
145 /* tell the user it's all over for this guy */
147 if (wsi->protocol->callback && old_state == WSI_STATE_ESTABLISHED)
148 wsi->protocol->callback(this, wsi, LWS_CALLBACK_CLOSED,
149 wsi->user_space, NULL, 0);
151 /* free up his allocations */
153 for (n = 0; n < WSI_TOKEN_COUNT; n++)
154 if (wsi->utf8_token[n].token)
155 free(wsi->utf8_token[n].token);
157 /* fprintf(stderr, "closing fd=%d\n", wsi->sock); */
159 #ifdef LWS_OPENSSL_SUPPORT
161 n = SSL_get_fd(wsi->ssl);
162 SSL_shutdown(wsi->ssl);
167 shutdown(wsi->sock, SHUT_RDWR);
169 #ifdef LWS_OPENSSL_SUPPORT
173 free(wsi->user_space);
179 * libwebsockets_hangup_on_client() - Server calls to terminate client
181 * @this: libwebsockets context
182 * @fd: Connection socket descriptor
186 libwebsockets_hangup_on_client(struct libwebsocket_context *this, int fd)
188 struct libwebsocket *wsi = wsi_from_fd(this, fd);
194 delete_from_fd(this, fd);
196 for (n = 0; n < this->fds_count - 1; n++)
197 if (this->fds[n].fd == fd) {
198 while (n < this->fds_count - 1) {
199 this->fds[n] = this->fds[n + 1];
206 libwebsocket_close_and_free_session(this, wsi);
211 * libwebsockets_get_peer_addresses() - Get client address information
212 * @fd: Connection socket descriptor
213 * @name: Buffer to take client address name
214 * @name_len: Length of client address name buffer
215 * @rip: Buffer to take client address IP qotted quad
216 * @rip_len: Length of client address IP buffer
218 * This function fills in @name and @rip with the name and IP of
219 * the client connected with socket descriptor @fd. Names may be
220 * truncated if there is not enough room. If either cannot be
221 * determined, they will be returned as valid zero-length strings.
225 libwebsockets_get_peer_addresses(int fd, char *name, int name_len,
226 char *rip, int rip_len)
229 struct sockaddr_in sin;
230 struct hostent *host;
231 struct hostent *host1;
240 if (getpeername(fd, (struct sockaddr *) &sin, &len) < 0) {
241 perror("getpeername");
245 host = gethostbyaddr((char *) &sin.sin_addr, sizeof sin.sin_addr,
248 perror("gethostbyaddr");
252 strncpy(name, host->h_name, name_len);
253 name[name_len - 1] = '\0';
255 host1 = gethostbyname(host->h_name);
261 p = host1->h_addr_list[n++];
264 if (host1->h_addrtype != AF_INET)
267 sprintf(ip, "%d.%d.%d.%d",
268 p[0], p[1], p[2], p[3]);
270 strncpy(rip, ip, rip_len);
271 rip[rip_len - 1] = '\0';
276 * libwebsocket_service_fd() - Service polled socket with something waiting
277 * @this: Websocket context
278 * @pollfd: The pollfd entry describing the socket fd and which events
281 * This function closes any active connections and then frees the
282 * context. After calling this, any further use of the context is
287 libwebsocket_service_fd(struct libwebsocket_context *this,
288 struct pollfd *pollfd)
290 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + MAX_BROADCAST_PAYLOAD +
291 LWS_SEND_BUFFER_POST_PADDING];
292 struct libwebsocket *wsi;
293 struct libwebsocket *new_wsi;
299 struct sockaddr_in cli_addr;
301 static const char magic_websocket_guid[] =
302 "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
303 static const char magic_websocket_04_masking_guid[] =
304 "61AC5F19-FBBA-4540-B96F-6561F1AB40A8";
310 #ifdef LWS_OPENSSL_SUPPORT
311 char ssl_err_buf[512];
314 * you can call us with pollfd = NULL to just allow the once-per-second
315 * global timeout checks; if less than a second since the last check
316 * it returns immediately then.
319 gettimeofday(&tv, NULL);
321 if (this->last_timeout_check_s != tv.tv_sec) {
322 this->last_timeout_check_s = tv.tv_sec;
324 /* global timeout check once per second */
326 for (n = 0; n < this->fds_count; n++) {
327 wsi = wsi_from_fd(this, this->fds[n].fd);
328 if (!wsi->pending_timeout)
332 * if we went beyond the allowed time, kill the
336 if (tv.tv_sec > wsi->pending_timeout_limit)
337 libwebsocket_close_and_free_session(this, wsi);
341 /* just here for timeout management? */
346 /* no, here to service a socket descriptor */
348 wsi = wsi_from_fd(this, pollfd->fd);
354 case LWS_CONNMODE_SERVER_LISTENER:
356 /* pollin means a client has connected to us then */
358 if (!pollfd->revents & POLLIN)
361 /* listen socket got an unencrypted connection... */
363 clilen = sizeof(cli_addr);
364 accept_fd = accept(pollfd->fd, (struct sockaddr *)&cli_addr,
367 fprintf(stderr, "ERROR on accept");
371 if (this->fds_count >= MAX_CLIENTS) {
372 fprintf(stderr, "too busy to accept new client\n");
378 * look at who we connected to and give user code a chance
379 * to reject based on client IP. There's no protocol selected
380 * yet so we issue this to protocols[0]
383 if ((this->protocols[0].callback)(this, wsi,
384 LWS_CALLBACK_FILTER_NETWORK_CONNECTION,
385 (void*)(long)accept_fd, NULL, 0)) {
386 fprintf(stderr, "Callback denied network connection\n");
391 /* accepting connection to main listener */
393 new_wsi = malloc(sizeof(struct libwebsocket));
394 if (new_wsi == NULL) {
395 fprintf(stderr, "Out of memory for new connection\n");
399 memset(new_wsi, 0, sizeof (struct libwebsocket));
400 new_wsi->sock = accept_fd;
401 new_wsi->pending_timeout = NO_PENDING_TIMEOUT;
403 #ifdef LWS_OPENSSL_SUPPORT
405 this->ssl_ctx = NULL;
409 new_wsi->ssl = SSL_new(this->ssl_ctx);
410 if (new_wsi->ssl == NULL) {
411 fprintf(stderr, "SSL_new failed: %s\n",
412 ERR_error_string(SSL_get_error(
413 new_wsi->ssl, 0), NULL));
418 SSL_set_fd(new_wsi->ssl, accept_fd);
420 n = SSL_accept(new_wsi->ssl);
423 * browsers seem to probe with various
424 * ssl params which fail then retry
427 debug("SSL_accept failed skt %u: %s\n",
429 ERR_error_string(SSL_get_error(
430 new_wsi->ssl, n), NULL));
436 debug("accepted new SSL conn "
437 "port %u on fd=%d SSL ver %s\n",
438 ntohs(cli_addr.sin_port), accept_fd,
439 SSL_get_version(new_wsi->ssl));
443 debug("accepted new conn port %u on fd=%d\n",
444 ntohs(cli_addr.sin_port), accept_fd);
446 /* intialize the instance struct */
448 new_wsi->state = WSI_STATE_HTTP;
449 new_wsi->name_buffer_pos = 0;
450 new_wsi->mode = LWS_CONNMODE_WS_SERVING;
452 for (n = 0; n < WSI_TOKEN_COUNT; n++) {
453 new_wsi->utf8_token[n].token = NULL;
454 new_wsi->utf8_token[n].token_len = 0;
458 * these can only be set once the protocol is known
459 * we set an unestablished connection's protocol pointer
460 * to the start of the supported list, so it can look
461 * for matching ones during the handshake
463 new_wsi->protocol = this->protocols;
464 new_wsi->user_space = NULL;
467 * Default protocol is 76 / 00
468 * After 76, there's a header specified to inform which
469 * draft the client wants, when that's seen we modify
470 * the individual connection's spec revision accordingly
472 new_wsi->ietf_spec_revision = 0;
474 insert_wsi(this, new_wsi);
477 * make sure NO events are seen yet on this new socket
478 * (otherwise we inherit old fds[client].revents from
479 * previous socket there and die mysteriously! )
481 this->fds[this->fds_count].revents = 0;
483 this->fds[this->fds_count].events = POLLIN;
484 this->fds[this->fds_count++].fd = accept_fd;
486 /* external POLL support via protocol 0 */
487 this->protocols[0].callback(this, new_wsi,
488 LWS_CALLBACK_ADD_POLL_FD,
489 (void *)(long)accept_fd, NULL, POLLIN);
493 case LWS_CONNMODE_BROADCAST_PROXY_LISTENER:
495 /* as we are listening, POLLIN means accept() is needed */
497 if (!pollfd->revents & POLLIN)
500 /* listen socket got an unencrypted connection... */
502 clilen = sizeof(cli_addr);
503 accept_fd = accept(pollfd->fd, (struct sockaddr *)&cli_addr,
506 fprintf(stderr, "ERROR on accept");
510 if (this->fds_count >= MAX_CLIENTS) {
511 fprintf(stderr, "too busy to accept new broadcast "
517 /* create a dummy wsi for the connection and add it */
519 new_wsi = malloc(sizeof(struct libwebsocket));
520 memset(new_wsi, 0, sizeof (struct libwebsocket));
521 new_wsi->sock = accept_fd;
522 new_wsi->mode = LWS_CONNMODE_BROADCAST_PROXY;
523 new_wsi->state = WSI_STATE_ESTABLISHED;
524 /* note which protocol we are proxying */
525 new_wsi->protocol_index_for_broadcast_proxy =
526 wsi->protocol_index_for_broadcast_proxy;
527 insert_wsi(this, new_wsi);
529 /* add connected socket to internal poll array */
531 this->fds[this->fds_count].revents = 0;
532 this->fds[this->fds_count].events = POLLIN;
533 this->fds[this->fds_count++].fd = accept_fd;
535 /* external POLL support via protocol 0 */
536 this->protocols[0].callback(this, new_wsi,
537 LWS_CALLBACK_ADD_POLL_FD,
538 (void *)(long)accept_fd, NULL, POLLIN);
542 case LWS_CONNMODE_BROADCAST_PROXY:
544 /* handle session socket closed */
546 if (pollfd->revents & (POLLERR | POLLHUP)) {
548 debug("Session Socket %p (fd=%d) dead\n",
549 (void *)wsi, pollfd->fd);
551 libwebsocket_close_and_free_session(this, wsi);
555 /* the guy requested a callback when it was OK to write */
557 if (pollfd->revents & POLLOUT) {
561 pollfd->events &= ~POLLOUT;
563 /* external POLL support via protocol 0 */
564 this->protocols[0].callback(this, wsi,
565 LWS_CALLBACK_CLEAR_MODE_POLL_FD,
566 (void *)(long)wsi->sock, NULL, POLLOUT);
568 wsi->protocol->callback(this, wsi,
569 LWS_CALLBACK_CLIENT_WRITEABLE,
574 /* any incoming data ready? */
576 if (!(pollfd->revents & POLLIN))
579 /* get the issued broadcast payload from the socket */
581 len = read(pollfd->fd, buf + LWS_SEND_BUFFER_PRE_PADDING,
582 MAX_BROADCAST_PAYLOAD);
584 fprintf(stderr, "Error reading broadcast payload\n");
588 /* broadcast it to all guys with this protocol index */
590 for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
592 for (m = 0; m < this->fd_hashtable[n].length; m++) {
594 new_wsi = this->fd_hashtable[n].wsi[m];
596 /* only to clients we are serving to */
598 if (new_wsi->mode != LWS_CONNMODE_WS_SERVING)
602 * never broadcast to non-established
606 if (new_wsi->state != WSI_STATE_ESTABLISHED)
610 * only broadcast to connections using
611 * the requested protocol
614 if (new_wsi->protocol->protocol_index !=
615 wsi->protocol_index_for_broadcast_proxy)
618 /* broadcast it to this connection */
620 new_wsi->protocol->callback(this, new_wsi,
621 LWS_CALLBACK_BROADCAST,
623 buf + LWS_SEND_BUFFER_PRE_PADDING, len);
628 case LWS_CONNMODE_WS_CLIENT_WAITING_PROXY_REPLY:
630 /* handle proxy hung up on us */
632 if (pollfd->revents & (POLLERR | POLLHUP)) {
634 fprintf(stderr, "Proxy connection %p (fd=%d) dead\n",
635 (void *)wsi, pollfd->fd);
637 libwebsocket_close_and_free_session(this, wsi);
641 n = recv(wsi->sock, pkt, sizeof pkt, 0);
643 libwebsocket_close_and_free_session(this, wsi);
644 fprintf(stderr, "ERROR reading from proxy socket\n");
649 if (strcmp(pkt, "HTTP/1.0 200 ") != 0) {
650 libwebsocket_close_and_free_session(this, wsi);
651 fprintf(stderr, "ERROR from proxy: %s\n", pkt);
655 /* clear his proxy connection timeout */
657 libwebsocket_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
661 case LWS_CONNMODE_WS_CLIENT_ISSUE_HANDSHAKE:
663 #ifdef LWS_OPENSSL_SUPPORT
666 wsi->ssl = SSL_new(this->ssl_client_ctx);
667 wsi->client_bio = BIO_new_socket(wsi->sock, BIO_NOCLOSE);
668 SSL_set_bio(wsi->ssl, wsi->client_bio, wsi->client_bio);
670 if (SSL_connect(wsi->ssl) <= 0) {
671 fprintf(stderr, "SSL connect error %s\n",
672 ERR_error_string(ERR_get_error(), ssl_err_buf));
673 libwebsocket_close_and_free_session(this, wsi);
677 n = SSL_get_verify_result(wsi->ssl);
678 if (n != X509_V_OK) {
679 if (n != X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT ||
682 fprintf(stderr, "server's cert didn't "
683 "look good %d\n", n);
684 libwebsocket_close_and_free_session(this, wsi);
693 #ifdef LWS_OPENSSL_SUPPORT
698 * create the random key
701 n = read(this->fd_random, hash, 16);
703 fprintf(stderr, "Unable to read from random dev %s\n",
704 SYSTEM_RANDOM_FILEPATH);
709 free(wsi->c_protocol);
710 libwebsocket_close_and_free_session(this, wsi);
714 lws_b64_encode_string(hash, 16, wsi->key_b64,
715 sizeof wsi->key_b64);
718 * 04 example client handshake
721 * Host: server.example.com
723 * Connection: Upgrade
724 * Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
725 * Sec-WebSocket-Origin: http://example.com
726 * Sec-WebSocket-Protocol: chat, superchat
727 * Sec-WebSocket-Version: 4
730 p += sprintf(p, "GET %s HTTP/1.1\x0d\x0a", wsi->c_path);
731 p += sprintf(p, "Host: %s\x0d\x0a", wsi->c_host);
732 p += sprintf(p, "Upgrade: websocket\x0d\x0a");
733 p += sprintf(p, "Connection: Upgrade\x0d\x0a"
734 "Sec-WebSocket-Key: ");
735 strcpy(p, wsi->key_b64);
736 p += strlen(wsi->key_b64);
737 p += sprintf(p, "\x0d\x0aSec-WebSocket-Origin: %s\x0d\x0a",
739 if (wsi->c_protocol != NULL)
740 p += sprintf(p, "Sec-WebSocket-Protocol: %s\x0d\x0a",
742 p += sprintf(p, "Sec-WebSocket-Version: %d\x0d\x0a\x0d\x0a",
743 wsi->ietf_spec_revision);
745 /* done with these now */
751 /* prepare the expected server accept response */
753 strcpy((char *)buf, wsi->key_b64);
754 strcpy((char *)&buf[strlen((char *)buf)], magic_websocket_guid);
756 SHA1(buf, strlen((char *)buf), (unsigned char *)hash);
758 lws_b64_encode_string(hash, 20,
759 wsi->initial_handshake_hash_base64,
760 sizeof wsi->initial_handshake_hash_base64);
762 /* send our request to the server */
764 #ifdef LWS_OPENSSL_SUPPORT
766 n = SSL_write(wsi->ssl, pkt, p - pkt);
769 n = send(wsi->sock, pkt, p - pkt, 0);
772 fprintf(stderr, "ERROR writing to client socket\n");
773 libwebsocket_close_and_free_session(this, wsi);
777 wsi->parser_state = WSI_TOKEN_NAME_PART;
778 wsi->mode = LWS_CONNMODE_WS_CLIENT_WAITING_SERVER_REPLY;
779 libwebsocket_set_timeout(wsi,
780 PENDING_TIMEOUT_AWAITING_SERVER_RESPONSE, 5);
784 case LWS_CONNMODE_WS_CLIENT_WAITING_SERVER_REPLY:
786 /* handle server hung up on us */
788 if (pollfd->revents & (POLLERR | POLLHUP)) {
790 fprintf(stderr, "Server connection %p (fd=%d) dead\n",
791 (void *)wsi, pollfd->fd);
797 /* interpret the server response */
800 * HTTP/1.1 101 Switching Protocols
802 * Connection: Upgrade
803 * Sec-WebSocket-Accept: me89jWimTRKTWwrS3aRrL53YZSo=
804 * Sec-WebSocket-Nonce: AQIDBAUGBwgJCgsMDQ4PEC==
805 * Sec-WebSocket-Protocol: chat
808 #ifdef LWS_OPENSSL_SUPPORT
810 len = SSL_read(wsi->ssl, pkt, sizeof pkt);
813 len = recv(wsi->sock, pkt, sizeof pkt, 0);
817 "libwebsocket_client_handshake read error\n");
822 for (n = 0; n < len; n++)
823 libwebsocket_parse(wsi, *p++);
825 if (wsi->parser_state != WSI_PARSING_COMPLETE) {
826 fprintf(stderr, "libwebsocket_client_handshake "
827 "server response ailed parsing\n");
832 * well, what the server sent looked reasonable for syntax.
833 * Now let's confirm it sent all the necessary headers
836 if (!wsi->utf8_token[WSI_TOKEN_HTTP].token_len ||
837 !wsi->utf8_token[WSI_TOKEN_UPGRADE].token_len ||
838 !wsi->utf8_token[WSI_TOKEN_CONNECTION].token_len ||
839 !wsi->utf8_token[WSI_TOKEN_ACCEPT].token_len ||
840 !wsi->utf8_token[WSI_TOKEN_NONCE].token_len ||
841 (!wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len &&
842 wsi->c_protocol != NULL)) {
843 fprintf(stderr, "libwebsocket_client_handshake "
844 "missing required header(s)\n");
846 fprintf(stderr, "%s", pkt);
851 * Everything seems to be there, now take a closer look at what
855 strtolower(wsi->utf8_token[WSI_TOKEN_HTTP].token);
856 if (strcmp(wsi->utf8_token[WSI_TOKEN_HTTP].token,
857 "101 switching protocols")) {
858 fprintf(stderr, "libwebsocket_client_handshake "
859 "server sent bad HTTP response '%s'\n",
860 wsi->utf8_token[WSI_TOKEN_HTTP].token);
864 strtolower(wsi->utf8_token[WSI_TOKEN_UPGRADE].token);
865 if (strcmp(wsi->utf8_token[WSI_TOKEN_UPGRADE].token,
867 fprintf(stderr, "libwebsocket_client_handshake server "
868 "sent bad Upgrade header '%s'\n",
869 wsi->utf8_token[WSI_TOKEN_UPGRADE].token);
873 strtolower(wsi->utf8_token[WSI_TOKEN_CONNECTION].token);
874 if (strcmp(wsi->utf8_token[WSI_TOKEN_CONNECTION].token,
876 fprintf(stderr, "libwebsocket_client_handshake server "
877 "sent bad Connection hdr '%s'\n",
878 wsi->utf8_token[WSI_TOKEN_CONNECTION].token);
883 pc = wsi->c_protocol;
886 * confirm the protocol the server wants to talk was in the list
887 * of protocols we offered
890 if (!wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len) {
893 * no protocol name to work from,
894 * default to first protocol
896 wsi->protocol = &this->protocols[0];
898 free(wsi->c_protocol);
903 while (*pc && !okay) {
905 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token,
906 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len)) &&
907 (pc[wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len] == ',' ||
908 pc[wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len] == '\0')) {
912 while (*pc && *pc != ',')
914 while (*pc && *pc != ' ')
918 /* done with him now */
921 free(wsi->c_protocol);
925 fprintf(stderr, "libwebsocket_client_handshake server "
926 "sent bad protocol '%s'\n",
927 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token);
932 * identify the selected protocol struct and set it
935 wsi->protocol = NULL;
936 while (this->protocols[n].callback) {
937 if (strcmp(wsi->utf8_token[WSI_TOKEN_PROTOCOL].token,
938 this->protocols[n].name) == 0)
939 wsi->protocol = &this->protocols[n];
943 if (wsi->protocol == NULL) {
944 fprintf(stderr, "libwebsocket_client_handshake server "
945 "requested protocol '%s', which we "
946 "said we supported but we don't!\n",
947 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token);
953 * Confirm his accept token is the one we precomputed
956 if (strcmp(wsi->utf8_token[WSI_TOKEN_ACCEPT].token,
957 wsi->initial_handshake_hash_base64)) {
958 fprintf(stderr, "libwebsocket_client_handshake server "
959 "sent bad ACCEPT '%s' vs computed '%s'\n",
960 wsi->utf8_token[WSI_TOKEN_ACCEPT].token,
961 wsi->initial_handshake_hash_base64);
966 * Calculate the masking key to use when sending data to server
969 strcpy((char *)buf, wsi->key_b64);
970 p = (char *)buf + strlen(wsi->key_b64);
971 strcpy(p, wsi->utf8_token[WSI_TOKEN_NONCE].token);
972 p += wsi->utf8_token[WSI_TOKEN_NONCE].token_len;
973 strcpy(p, magic_websocket_04_masking_guid);
974 SHA1(buf, strlen((char *)buf), wsi->masking_key_04);
976 /* allocate the per-connection user memory (if any) */
978 if (wsi->protocol->per_session_data_size) {
979 wsi->user_space = malloc(
980 wsi->protocol->per_session_data_size);
981 if (wsi->user_space == NULL) {
982 fprintf(stderr, "Out of memory for "
983 "conn user space\n");
987 wsi->user_space = NULL;
989 /* clear his proxy connection timeout */
991 libwebsocket_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
993 /* mark him as being alive */
995 wsi->state = WSI_STATE_ESTABLISHED;
996 wsi->mode = LWS_CONNMODE_WS_CLIENT;
998 fprintf(stderr, "handshake OK for protocol %s\n",
999 wsi->protocol->name);
1001 /* call him back to inform him he is up */
1003 wsi->protocol->callback(this, wsi,
1004 LWS_CALLBACK_CLIENT_ESTABLISHED,
1011 if (wsi->c_protocol)
1012 free(wsi->c_protocol);
1015 libwebsocket_close_and_free_session(this, wsi);
1019 case LWS_CONNMODE_WS_SERVING:
1020 case LWS_CONNMODE_WS_CLIENT:
1022 /* handle session socket closed */
1024 if (pollfd->revents & (POLLERR | POLLHUP)) {
1026 fprintf(stderr, "Session Socket %p (fd=%d) dead\n",
1027 (void *)wsi, pollfd->fd);
1029 libwebsocket_close_and_free_session(this, wsi);
1033 /* the guy requested a callback when it was OK to write */
1035 if (pollfd->revents & POLLOUT) {
1037 pollfd->events &= ~POLLOUT;
1039 /* external POLL support via protocol 0 */
1040 this->protocols[0].callback(this, wsi,
1041 LWS_CALLBACK_CLEAR_MODE_POLL_FD,
1042 (void *)(long)wsi->sock, NULL, POLLOUT);
1044 wsi->protocol->callback(this, wsi,
1045 LWS_CALLBACK_CLIENT_WRITEABLE,
1050 /* any incoming data ready? */
1052 if (!(pollfd->revents & POLLIN))
1055 #ifdef LWS_OPENSSL_SUPPORT
1057 n = SSL_read(wsi->ssl, buf, sizeof buf);
1060 n = recv(pollfd->fd, buf, sizeof buf, 0);
1063 fprintf(stderr, "Socket read returned %d\n", n);
1067 libwebsocket_close_and_free_session(this, wsi);
1071 /* service incoming data */
1073 n = libwebsocket_read(this, wsi, buf, n);
1087 * libwebsocket_context_destroy() - Destroy the websocket context
1088 * @this: Websocket context
1090 * This function closes any active connections and then frees the
1091 * context. After calling this, any further use of the context is
1095 libwebsocket_context_destroy(struct libwebsocket_context *this)
1099 struct libwebsocket *wsi;
1101 for (n = 0; n < FD_HASHTABLE_MODULUS; n++)
1102 for (m = 0; m < this->fd_hashtable[n].length; m++) {
1103 wsi = this->fd_hashtable[n].wsi[m];
1104 libwebsocket_close_and_free_session(this, wsi);
1107 close(this->fd_random);
1109 #ifdef LWS_OPENSSL_SUPPORT
1111 SSL_CTX_free(this->ssl_ctx);
1112 if (this->ssl_client_ctx)
1113 SSL_CTX_free(this->ssl_client_ctx);
1120 * libwebsocket_service() - Service any pending websocket activity
1121 * @this: Websocket context
1122 * @timeout_ms: Timeout for poll; 0 means return immediately if nothing needed
1123 * service otherwise block and service immediately, returning
1124 * after the timeout if nothing needed service.
1126 * This function deals with any pending websocket traffic, for three
1127 * kinds of event. It handles these events on both server and client
1128 * types of connection the same.
1130 * 1) Accept new connections to our context's server
1132 * 2) Perform pending broadcast writes initiated from other forked
1133 * processes (effectively serializing asynchronous broadcasts)
1135 * 3) Call the receive callback for incoming frame data received by
1136 * server or client connections.
1138 * You need to call this service function periodically to all the above
1139 * functions to happen; if your application is single-threaded you can
1140 * just call it in your main event loop.
1142 * Alternatively you can fork a new process that asynchronously handles
1143 * calling this service in a loop. In that case you are happy if this
1144 * call blocks your thread until it needs to take care of something and
1145 * would call it with a large nonzero timeout. Your loop then takes no
1146 * CPU while there is nothing happening.
1148 * If you are calling it in a single-threaded app, you don't want it to
1149 * wait around blocking other things in your loop from happening, so you
1150 * would call it with a timeout_ms of 0, so it returns immediately if
1151 * nothing is pending, or as soon as it services whatever was pending.
1156 libwebsocket_service(struct libwebsocket_context *this, int timeout_ms)
1160 /* stay dead once we are dead */
1165 /* wait for something to need service */
1167 n = poll(this->fds, this->fds_count, timeout_ms);
1168 if (n == 0) /* poll timeout */
1173 fprintf(stderr, "Listen Socket dead\n");
1178 /* handle accept on listening socket? */
1180 for (n = 0; n < this->fds_count; n++)
1181 if (this->fds[n].revents)
1182 libwebsocket_service_fd(this, &this->fds[n]);
1188 * libwebsocket_callback_on_writable() - Request a callback when this socket
1189 * becomes able to be written to without
1192 * @wsi: Websocket connection instance to get callback for
1196 libwebsocket_callback_on_writable(struct libwebsocket_context *this,
1197 struct libwebsocket *wsi)
1201 for (n = 0; n < this->fds_count; n++)
1202 if (this->fds[n].fd == wsi->sock) {
1203 this->fds[n].events |= POLLOUT;
1204 n = this->fds_count;
1207 /* external POLL support via protocol 0 */
1208 this->protocols[0].callback(this, wsi,
1209 LWS_CALLBACK_SET_MODE_POLL_FD,
1210 (void *)(long)wsi->sock, NULL, POLLOUT);
1216 * libwebsocket_callback_on_writable_all_protocol() - Request a callback for
1217 * all connections using the given protocol when it
1218 * becomes possible to write to each socket without
1221 * @protocol: Protocol whose connections will get callbacks
1225 libwebsocket_callback_on_writable_all_protocol(
1226 const struct libwebsocket_protocols *protocol)
1228 struct libwebsocket_context *this = protocol->owning_server;
1231 struct libwebsocket *wsi;
1233 for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
1235 for (m = 0; m < this->fd_hashtable[n].length; m++) {
1237 wsi = this->fd_hashtable[n].wsi[m];
1239 if (wsi->protocol == protocol)
1240 libwebsocket_callback_on_writable(this, wsi);
1248 * libwebsocket_set_timeout() - marks the wsi as subject to a timeout
1250 * You will not need this unless you are doing something special
1252 * @wsi: Websocket connection instance
1253 * @reason: timeout reason
1254 * @secs: how many seconds
1258 libwebsocket_set_timeout(struct libwebsocket *wsi,
1259 enum pending_timeout reason, int secs)
1263 gettimeofday(&tv, NULL);
1265 wsi->pending_timeout_limit = tv.tv_sec + secs;
1266 wsi->pending_timeout = reason;
1271 * libwebsocket_get_socket_fd() - returns the socket file descriptor
1273 * You will not need this unless you are doing something special
1275 * @wsi: Websocket connection instance
1279 libwebsocket_get_socket_fd(struct libwebsocket *wsi)
1285 * libwebsocket_rx_flow_control() - Enable and disable socket servicing for
1286 * receieved packets.
1288 * If the output side of a server process becomes choked, this allows flow
1289 * control for the input side.
1291 * @wsi: Websocket connection instance to get callback for
1292 * @enable: 0 = disable read servicing for this connection, 1 = enable
1296 libwebsocket_rx_flow_control(struct libwebsocket *wsi, int enable)
1298 struct libwebsocket_context *this = wsi->protocol->owning_server;
1301 for (n = 0; n < this->fds_count; n++)
1302 if (this->fds[n].fd == wsi->sock) {
1304 this->fds[n].events |= POLLIN;
1306 this->fds[n].events &= ~POLLIN;
1312 /* external POLL support via protocol 0 */
1313 this->protocols[0].callback(this, wsi,
1314 LWS_CALLBACK_SET_MODE_POLL_FD,
1315 (void *)(long)wsi->sock, NULL, POLLIN);
1317 /* external POLL support via protocol 0 */
1318 this->protocols[0].callback(this, wsi,
1319 LWS_CALLBACK_CLEAR_MODE_POLL_FD,
1320 (void *)(long)wsi->sock, NULL, POLLIN);
1323 fprintf(stderr, "libwebsocket_callback_on_writable "
1324 "unable to find socket\n");
1329 * libwebsocket_canonical_hostname() - returns this host's hostname
1331 * This is typically used by client code to fill in the host parameter
1332 * when making a client connection. You can only call it after the context
1335 * @this: Websocket context
1340 libwebsocket_canonical_hostname(struct libwebsocket_context *this)
1342 return (const char *)this->canonical_hostname;
1346 static void sigpipe_handler(int x)
1353 * libwebsocket_create_context() - Create the websocket handler
1354 * @port: Port to listen on... you can use 0 to suppress listening on
1355 * any port, that's what you want if you are not running a
1356 * websocket server at all but just using it as a client
1357 * @protocols: Array of structures listing supported protocols and a protocol-
1358 * specific callback for each one. The list is ended with an
1359 * entry that has a NULL callback pointer.
1360 * It's not const because we write the owning_server member
1361 * @ssl_cert_filepath: If libwebsockets was compiled to use ssl, and you want
1362 * to listen using SSL, set to the filepath to fetch the
1363 * server cert from, otherwise NULL for unencrypted
1364 * @ssl_private_key_filepath: filepath to private key if wanting SSL mode,
1366 * @gid: group id to change to after setting listen socket, or -1.
1367 * @uid: user id to change to after setting listen socket, or -1.
1368 * @options: 0, or LWS_SERVER_OPTION_DEFEAT_CLIENT_MASK
1370 * This function creates the listening socket and takes care
1371 * of all initialization in one step.
1373 * After initialization, it returns a struct libwebsocket_context * that
1374 * represents this server. After calling, user code needs to take care
1375 * of calling libwebsocket_service() with the context pointer to get the
1376 * server's sockets serviced. This can be done in the same process context
1377 * or a forked process, or another thread,
1379 * The protocol callback functions are called for a handful of events
1380 * including http requests coming in, websocket connections becoming
1381 * established, and data arriving; it's also called periodically to allow
1382 * async transmission.
1384 * HTTP requests are sent always to the FIRST protocol in @protocol, since
1385 * at that time websocket protocol has not been negotiated. Other
1386 * protocols after the first one never see any HTTP callack activity.
1388 * The server created is a simple http server by default; part of the
1389 * websocket standard is upgrading this http connection to a websocket one.
1391 * This allows the same server to provide files like scripts and favicon /
1392 * images or whatever over http and dynamic data over websockets all in
1393 * one place; they're all handled in the user callback.
1396 struct libwebsocket_context *
1397 libwebsocket_create_context(int port,
1398 struct libwebsocket_protocols *protocols,
1399 const char *ssl_cert_filepath,
1400 const char *ssl_private_key_filepath,
1401 int gid, int uid, unsigned int options)
1406 struct sockaddr_in serv_addr, cli_addr;
1408 struct libwebsocket_context *this = NULL;
1411 char hostname[1024];
1413 struct libwebsocket *wsi;
1415 #ifdef LWS_OPENSSL_SUPPORT
1417 char ssl_err_buf[512];
1420 this = malloc(sizeof(struct libwebsocket_context));
1422 fprintf(stderr, "No memory for websocket context\n");
1425 this->protocols = protocols;
1426 this->listen_port = port;
1427 this->http_proxy_port = 0;
1428 this->http_proxy_address[0] = '\0';
1429 this->options = options;
1430 this->fds_count = 0;
1432 this->fd_random = open(SYSTEM_RANDOM_FILEPATH, O_RDONLY);
1433 if (this->fd_random < 0) {
1434 fprintf(stderr, "Unable to open random device %s %d\n",
1435 SYSTEM_RANDOM_FILEPATH, this->fd_random);
1439 /* find canonical hostname */
1441 hostname[(sizeof hostname) - 1] = '\0';
1442 gethostname(hostname, (sizeof hostname) - 1);
1443 he = gethostbyname(hostname);
1445 strncpy(this->canonical_hostname, he->h_name,
1446 sizeof this->canonical_hostname - 1);
1447 this->canonical_hostname[sizeof this->canonical_hostname - 1] =
1450 strncpy(this->canonical_hostname, hostname,
1451 sizeof this->canonical_hostname - 1);
1453 /* split the proxy ads:port if given */
1455 p = getenv("http_proxy");
1457 strncpy(this->http_proxy_address, p,
1458 sizeof this->http_proxy_address - 1);
1459 this->http_proxy_address[
1460 sizeof this->http_proxy_address - 1] = '\0';
1462 p = strchr(this->http_proxy_address, ':');
1464 fprintf(stderr, "http_proxy needs to be ads:port\n");
1468 this->http_proxy_port = atoi(p + 1);
1470 fprintf(stderr, "Using proxy %s:%u\n",
1471 this->http_proxy_address,
1472 this->http_proxy_port);
1477 #ifdef LWS_OPENSSL_SUPPORT
1478 this->use_ssl = ssl_cert_filepath != NULL &&
1479 ssl_private_key_filepath != NULL;
1481 fprintf(stderr, " Compiled with SSL support, "
1484 fprintf(stderr, " Compiled with SSL support, "
1488 if (ssl_cert_filepath != NULL &&
1489 ssl_private_key_filepath != NULL) {
1490 fprintf(stderr, " Not compiled for OpenSSl support!\n");
1493 fprintf(stderr, " Compiled without SSL support, "
1494 "serving unencrypted\n");
1498 /* ignore SIGPIPE */
1500 signal(SIGPIPE, sigpipe_handler);
1503 #ifdef LWS_OPENSSL_SUPPORT
1505 /* basic openssl init */
1509 OpenSSL_add_all_algorithms();
1510 SSL_load_error_strings();
1513 * Firefox insists on SSLv23 not SSLv3
1514 * Konq disables SSLv2 by default now, SSLv23 works
1517 method = (SSL_METHOD *)SSLv23_server_method();
1519 fprintf(stderr, "problem creating ssl method: %s\n",
1520 ERR_error_string(ERR_get_error(), ssl_err_buf));
1523 this->ssl_ctx = SSL_CTX_new(method); /* create context */
1524 if (!this->ssl_ctx) {
1525 fprintf(stderr, "problem creating ssl context: %s\n",
1526 ERR_error_string(ERR_get_error(), ssl_err_buf));
1530 /* client context */
1532 method = (SSL_METHOD *)SSLv23_client_method();
1534 fprintf(stderr, "problem creating ssl method: %s\n",
1535 ERR_error_string(ERR_get_error(), ssl_err_buf));
1538 this->ssl_client_ctx = SSL_CTX_new(method); /* create context */
1539 if (!this->ssl_client_ctx) {
1540 fprintf(stderr, "problem creating ssl context: %s\n",
1541 ERR_error_string(ERR_get_error(), ssl_err_buf));
1546 /* openssl init for cert verification (used with client sockets) */
1548 if (!SSL_CTX_load_verify_locations(this->ssl_client_ctx, NULL,
1549 LWS_OPENSSL_CLIENT_CERTS)) {
1550 fprintf(stderr, "Unable to load SSL Client certs from %s "
1551 "(set by --with-client-cert-dir= in configure) -- "
1552 " client ssl isn't going to work",
1553 LWS_OPENSSL_CLIENT_CERTS);
1556 if (this->use_ssl) {
1558 /* openssl init for server sockets */
1560 /* set the local certificate from CertFile */
1561 n = SSL_CTX_use_certificate_file(this->ssl_ctx,
1562 ssl_cert_filepath, SSL_FILETYPE_PEM);
1564 fprintf(stderr, "problem getting cert '%s': %s\n",
1566 ERR_error_string(ERR_get_error(), ssl_err_buf));
1569 /* set the private key from KeyFile */
1570 if (SSL_CTX_use_PrivateKey_file(this->ssl_ctx,
1571 ssl_private_key_filepath,
1572 SSL_FILETYPE_PEM) != 1) {
1573 fprintf(stderr, "ssl problem getting key '%s': %s\n",
1574 ssl_private_key_filepath,
1575 ERR_error_string(ERR_get_error(), ssl_err_buf));
1578 /* verify private key */
1579 if (!SSL_CTX_check_private_key(this->ssl_ctx)) {
1580 fprintf(stderr, "Private SSL key doesn't match cert\n");
1584 /* SSL is happy and has a cert it's content with */
1590 if (lws_b64_selftest())
1593 /* fd hashtable init */
1595 for (n = 0; n < FD_HASHTABLE_MODULUS; n++)
1596 this->fd_hashtable[n].length = 0;
1598 /* set up our external listening socket we serve on */
1602 sockfd = socket(AF_INET, SOCK_STREAM, 0);
1604 fprintf(stderr, "ERROR opening socket");
1608 /* allow us to restart even if old sockets in TIME_WAIT */
1609 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
1611 bzero((char *) &serv_addr, sizeof(serv_addr));
1612 serv_addr.sin_family = AF_INET;
1613 serv_addr.sin_addr.s_addr = INADDR_ANY;
1614 serv_addr.sin_port = htons(port);
1616 n = bind(sockfd, (struct sockaddr *) &serv_addr,
1619 fprintf(stderr, "ERROR on binding to port %d (%d %d)\n",
1624 wsi = malloc(sizeof(struct libwebsocket));
1625 memset(wsi, 0, sizeof (struct libwebsocket));
1627 wsi->mode = LWS_CONNMODE_SERVER_LISTENER;
1628 insert_wsi(this, wsi);
1631 fprintf(stderr, " Listening on port %d\n", port);
1633 /* list in the internal poll array */
1635 this->fds[this->fds_count].fd = sockfd;
1636 this->fds[this->fds_count++].events = POLLIN;
1638 /* external POLL support via protocol 0 */
1639 this->protocols[0].callback(this, wsi,
1640 LWS_CALLBACK_ADD_POLL_FD,
1641 (void *)(long)sockfd, NULL, POLLIN);
1645 /* drop any root privs for this process */
1649 fprintf(stderr, "setgid: %s\n", strerror(errno));
1652 fprintf(stderr, "setuid: %s\n", strerror(errno));
1655 /* set up our internal broadcast trigger sockets per-protocol */
1657 for (this->count_protocols = 0;
1658 protocols[this->count_protocols].callback;
1659 this->count_protocols++) {
1660 protocols[this->count_protocols].owning_server = this;
1661 protocols[this->count_protocols].protocol_index =
1662 this->count_protocols;
1664 fd = socket(AF_INET, SOCK_STREAM, 0);
1666 fprintf(stderr, "ERROR opening socket");
1670 /* allow us to restart even if old sockets in TIME_WAIT */
1671 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
1673 bzero((char *) &serv_addr, sizeof(serv_addr));
1674 serv_addr.sin_family = AF_INET;
1675 serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
1676 serv_addr.sin_port = 0; /* pick the port for us */
1678 n = bind(fd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));
1680 fprintf(stderr, "ERROR on binding to port %d (%d %d)\n",
1685 slen = sizeof cli_addr;
1686 n = getsockname(fd, (struct sockaddr *)&cli_addr, &slen);
1688 fprintf(stderr, "getsockname failed\n");
1691 protocols[this->count_protocols].broadcast_socket_port =
1692 ntohs(cli_addr.sin_port);
1695 debug(" Protocol %s broadcast socket %d\n",
1696 protocols[this->count_protocols].name,
1697 ntohs(cli_addr.sin_port));
1699 /* dummy wsi per broadcast proxy socket */
1701 wsi = malloc(sizeof(struct libwebsocket));
1702 memset(wsi, 0, sizeof (struct libwebsocket));
1704 wsi->mode = LWS_CONNMODE_BROADCAST_PROXY_LISTENER;
1705 /* note which protocol we are proxying */
1706 wsi->protocol_index_for_broadcast_proxy = this->count_protocols;
1707 insert_wsi(this, wsi);
1709 /* list in internal poll array */
1711 this->fds[this->fds_count].fd = fd;
1712 this->fds[this->fds_count].events = POLLIN;
1713 this->fds[this->fds_count].revents = 0;
1716 /* external POLL support via protocol 0 */
1717 this->protocols[0].callback(this, wsi,
1718 LWS_CALLBACK_ADD_POLL_FD,
1719 (void *)(long)fd, NULL, POLLIN);
1729 * libwebsockets_fork_service_loop() - Optional helper function forks off
1730 * a process for the websocket server loop.
1731 * You don't have to use this but if not, you
1732 * have to make sure you are calling
1733 * libwebsocket_service periodically to service
1734 * the websocket traffic
1735 * @this: server context returned by creation function
1739 libwebsockets_fork_service_loop(struct libwebsocket_context *this)
1742 struct sockaddr_in cli_addr;
1752 /* main process context */
1755 * set up the proxy sockets to allow broadcast from
1756 * service process context
1759 for (p = 0; p < this->count_protocols; p++) {
1760 fd = socket(AF_INET, SOCK_STREAM, 0);
1762 fprintf(stderr, "Unable to create socket\n");
1765 cli_addr.sin_family = AF_INET;
1766 cli_addr.sin_port = htons(
1767 this->protocols[p].broadcast_socket_port);
1768 cli_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
1769 n = connect(fd, (struct sockaddr *)&cli_addr,
1772 fprintf(stderr, "Unable to connect to "
1773 "broadcast socket %d, %s\n",
1774 n, strerror(errno));
1778 this->protocols[p].broadcast_socket_user_fd = fd;
1784 /* we want a SIGHUP when our parent goes down */
1785 prctl(PR_SET_PDEATHSIG, SIGHUP);
1787 /* in this forked process, sit and service websocket connections */
1790 if (libwebsocket_service(this, 1000))
1799 * libwebsockets_get_protocol() - Returns a protocol pointer from a websocket
1801 * @wsi: pointer to struct websocket you want to know the protocol of
1804 * This is useful to get the protocol to broadcast back to from inside
1808 const struct libwebsocket_protocols *
1809 libwebsockets_get_protocol(struct libwebsocket *wsi)
1811 return wsi->protocol;
1815 * libwebsockets_broadcast() - Sends a buffer to the callback for all active
1816 * connections of the given protocol.
1817 * @protocol: pointer to the protocol you will broadcast to all members of
1818 * @buf: buffer containing the data to be broadcase. NOTE: this has to be
1819 * allocated with LWS_SEND_BUFFER_PRE_PADDING valid bytes before
1820 * the pointer and LWS_SEND_BUFFER_POST_PADDING afterwards in the
1821 * case you are calling this function from callback context.
1822 * @len: length of payload data in buf, starting from buf.
1824 * This function allows bulk sending of a packet to every connection using
1825 * the given protocol. It does not send the data directly; instead it calls
1826 * the callback with a reason type of LWS_CALLBACK_BROADCAST. If the callback
1827 * wants to actually send the data for that connection, the callback itself
1828 * should call libwebsocket_write().
1830 * libwebsockets_broadcast() can be called from another fork context without
1831 * having to take any care about data visibility between the processes, it'll
1837 libwebsockets_broadcast(const struct libwebsocket_protocols *protocol,
1838 unsigned char *buf, size_t len)
1840 struct libwebsocket_context *this = protocol->owning_server;
1843 struct libwebsocket * wsi;
1845 if (!protocol->broadcast_socket_user_fd) {
1847 * We are either running unforked / flat, or we are being
1848 * called from poll thread context
1849 * eg, from a callback. In that case don't use sockets for
1850 * broadcast IPC (since we can't open a socket connection to
1851 * a socket listening on our own thread) but directly do the
1854 * Locking is not needed because we are by definition being
1855 * called in the poll thread context and are serialized.
1858 for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
1860 for (m = 0; m < this->fd_hashtable[n].length; m++) {
1862 wsi = this->fd_hashtable[n].wsi[m];
1864 if (wsi->mode != LWS_CONNMODE_WS_SERVING)
1868 * never broadcast to
1869 * non-established connections
1871 if (wsi->state != WSI_STATE_ESTABLISHED)
1874 /* only broadcast to guys using
1875 * requested protocol
1877 if (wsi->protocol != protocol)
1880 wsi->protocol->callback(this, wsi,
1881 LWS_CALLBACK_BROADCAST,
1891 * We're being called from a different process context than the server
1892 * loop. Instead of broadcasting directly, we send our
1893 * payload on a socket to do the IPC; the server process will serialize
1894 * the broadcast action in its main poll() loop.
1896 * There's one broadcast socket listening for each protocol supported
1897 * set up when the websocket server initializes
1900 n = send(protocol->broadcast_socket_user_fd, buf, len, MSG_NOSIGNAL);