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);
90 #ifdef LWS_OPENSSL_SUPPORT
92 libwebsockets_decode_ssl_error(void)
97 while ((err = ERR_get_error()) != 0) {
98 ERR_error_string_n(err, buf, sizeof(buf));
99 fprintf(stderr, "*** %s\n", buf);
105 libwebsocket_close_and_free_session(struct libwebsocket_context *this,
106 struct libwebsocket *wsi)
110 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 2 +
111 LWS_SEND_BUFFER_POST_PADDING];
116 old_state = wsi->state;
118 if (old_state == WSI_STATE_DEAD_SOCKET)
121 /* remove this fd from wsi mapping hashtable */
123 delete_from_fd(this, wsi->sock);
125 /* delete it from the internal poll list if still present */
127 for (n = 0; n < this->fds_count; n++) {
128 if (this->fds[n].fd != wsi->sock)
130 while (n < this->fds_count - 1) {
131 this->fds[n] = this->fds[n + 1];
135 /* we only have to deal with one */
139 /* remove also from external POLL support via protocol 0 */
141 this->protocols[0].callback(this, wsi,
142 LWS_CALLBACK_DEL_POLL_FD, (void *)(long)wsi->sock, NULL, 0);
145 * signal we are closing, libsocket_write will
146 * add any necessary version-specific stuff. If the write fails,
147 * no worries we are closing anyway. If we didn't initiate this
148 * close, then our state has been changed to
149 * WSI_STATE_RETURNED_CLOSE_ALREADY and we will skip this
152 if (old_state == WSI_STATE_ESTABLISHED)
153 libwebsocket_write(wsi, &buf[LWS_SEND_BUFFER_PRE_PADDING], 0,
156 wsi->state = WSI_STATE_DEAD_SOCKET;
158 /* tell the user it's all over for this guy */
160 if (wsi->protocol->callback && old_state == WSI_STATE_ESTABLISHED)
161 wsi->protocol->callback(this, wsi, LWS_CALLBACK_CLOSED,
162 wsi->user_space, NULL, 0);
164 /* free up his allocations */
166 for (n = 0; n < WSI_TOKEN_COUNT; n++)
167 if (wsi->utf8_token[n].token)
168 free(wsi->utf8_token[n].token);
170 /* fprintf(stderr, "closing fd=%d\n", wsi->sock); */
172 #ifdef LWS_OPENSSL_SUPPORT
174 n = SSL_get_fd(wsi->ssl);
175 SSL_shutdown(wsi->ssl);
180 shutdown(wsi->sock, SHUT_RDWR);
182 #ifdef LWS_OPENSSL_SUPPORT
186 free(wsi->user_space);
192 * libwebsockets_hangup_on_client() - Server calls to terminate client
194 * @this: libwebsockets context
195 * @fd: Connection socket descriptor
199 libwebsockets_hangup_on_client(struct libwebsocket_context *this, int fd)
201 struct libwebsocket *wsi = wsi_from_fd(this, fd);
207 delete_from_fd(this, fd);
209 for (n = 0; n < this->fds_count - 1; n++)
210 if (this->fds[n].fd == fd) {
211 while (n < this->fds_count - 1) {
212 this->fds[n] = this->fds[n + 1];
219 libwebsocket_close_and_free_session(this, wsi);
224 * libwebsockets_get_peer_addresses() - Get client address information
225 * @fd: Connection socket descriptor
226 * @name: Buffer to take client address name
227 * @name_len: Length of client address name buffer
228 * @rip: Buffer to take client address IP qotted quad
229 * @rip_len: Length of client address IP buffer
231 * This function fills in @name and @rip with the name and IP of
232 * the client connected with socket descriptor @fd. Names may be
233 * truncated if there is not enough room. If either cannot be
234 * determined, they will be returned as valid zero-length strings.
238 libwebsockets_get_peer_addresses(int fd, char *name, int name_len,
239 char *rip, int rip_len)
242 struct sockaddr_in sin;
243 struct hostent *host;
244 struct hostent *host1;
253 if (getpeername(fd, (struct sockaddr *) &sin, &len) < 0) {
254 perror("getpeername");
258 host = gethostbyaddr((char *) &sin.sin_addr, sizeof sin.sin_addr,
261 perror("gethostbyaddr");
265 strncpy(name, host->h_name, name_len);
266 name[name_len - 1] = '\0';
268 host1 = gethostbyname(host->h_name);
274 p = host1->h_addr_list[n++];
277 if (host1->h_addrtype != AF_INET)
280 sprintf(ip, "%d.%d.%d.%d",
281 p[0], p[1], p[2], p[3]);
283 strncpy(rip, ip, rip_len);
284 rip[rip_len - 1] = '\0';
289 * libwebsocket_service_fd() - Service polled socket with something waiting
290 * @this: Websocket context
291 * @pollfd: The pollfd entry describing the socket fd and which events
294 * This function closes any active connections and then frees the
295 * context. After calling this, any further use of the context is
300 libwebsocket_service_fd(struct libwebsocket_context *this,
301 struct pollfd *pollfd)
303 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + MAX_BROADCAST_PAYLOAD +
304 LWS_SEND_BUFFER_POST_PADDING];
305 struct libwebsocket *wsi;
306 struct libwebsocket *new_wsi;
312 struct sockaddr_in cli_addr;
314 static const char magic_websocket_guid[] =
315 "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
316 static const char magic_websocket_04_masking_guid[] =
317 "61AC5F19-FBBA-4540-B96F-6561F1AB40A8";
323 #ifdef LWS_OPENSSL_SUPPORT
324 char ssl_err_buf[512];
327 * you can call us with pollfd = NULL to just allow the once-per-second
328 * global timeout checks; if less than a second since the last check
329 * it returns immediately then.
332 gettimeofday(&tv, NULL);
334 if (this->last_timeout_check_s != tv.tv_sec) {
335 this->last_timeout_check_s = tv.tv_sec;
337 /* global timeout check once per second */
339 for (n = 0; n < this->fds_count; n++) {
340 wsi = wsi_from_fd(this, this->fds[n].fd);
341 if (!wsi->pending_timeout)
345 * if we went beyond the allowed time, kill the
349 if (tv.tv_sec > wsi->pending_timeout_limit)
350 libwebsocket_close_and_free_session(this, wsi);
354 /* just here for timeout management? */
359 /* no, here to service a socket descriptor */
361 wsi = wsi_from_fd(this, pollfd->fd);
367 case LWS_CONNMODE_SERVER_LISTENER:
369 /* pollin means a client has connected to us then */
371 if (!pollfd->revents & POLLIN)
374 /* listen socket got an unencrypted connection... */
376 clilen = sizeof(cli_addr);
377 accept_fd = accept(pollfd->fd, (struct sockaddr *)&cli_addr,
380 fprintf(stderr, "ERROR on accept");
384 if (this->fds_count >= MAX_CLIENTS) {
385 fprintf(stderr, "too busy to accept new client\n");
391 * look at who we connected to and give user code a chance
392 * to reject based on client IP. There's no protocol selected
393 * yet so we issue this to protocols[0]
396 if ((this->protocols[0].callback)(this, wsi,
397 LWS_CALLBACK_FILTER_NETWORK_CONNECTION,
398 (void*)(long)accept_fd, NULL, 0)) {
399 fprintf(stderr, "Callback denied network connection\n");
404 /* accepting connection to main listener */
406 new_wsi = malloc(sizeof(struct libwebsocket));
407 if (new_wsi == NULL) {
408 fprintf(stderr, "Out of memory for new connection\n");
412 memset(new_wsi, 0, sizeof (struct libwebsocket));
413 new_wsi->sock = accept_fd;
414 new_wsi->pending_timeout = NO_PENDING_TIMEOUT;
416 #ifdef LWS_OPENSSL_SUPPORT
421 new_wsi->ssl = SSL_new(this->ssl_ctx);
422 if (new_wsi->ssl == NULL) {
423 fprintf(stderr, "SSL_new failed: %s\n",
424 ERR_error_string(SSL_get_error(
425 new_wsi->ssl, 0), NULL));
426 libwebsockets_decode_ssl_error();
431 SSL_set_fd(new_wsi->ssl, accept_fd);
433 n = SSL_accept(new_wsi->ssl);
436 * browsers seem to probe with various
437 * ssl params which fail then retry
440 debug("SSL_accept failed skt %u: %s\n",
442 ERR_error_string(SSL_get_error(
443 new_wsi->ssl, n), NULL));
449 debug("accepted new SSL conn "
450 "port %u on fd=%d SSL ver %s\n",
451 ntohs(cli_addr.sin_port), accept_fd,
452 SSL_get_version(new_wsi->ssl));
456 debug("accepted new conn port %u on fd=%d\n",
457 ntohs(cli_addr.sin_port), accept_fd);
459 /* intialize the instance struct */
461 new_wsi->state = WSI_STATE_HTTP;
462 new_wsi->name_buffer_pos = 0;
463 new_wsi->mode = LWS_CONNMODE_WS_SERVING;
465 for (n = 0; n < WSI_TOKEN_COUNT; n++) {
466 new_wsi->utf8_token[n].token = NULL;
467 new_wsi->utf8_token[n].token_len = 0;
471 * these can only be set once the protocol is known
472 * we set an unestablished connection's protocol pointer
473 * to the start of the supported list, so it can look
474 * for matching ones during the handshake
476 new_wsi->protocol = this->protocols;
477 new_wsi->user_space = NULL;
480 * Default protocol is 76 / 00
481 * After 76, there's a header specified to inform which
482 * draft the client wants, when that's seen we modify
483 * the individual connection's spec revision accordingly
485 new_wsi->ietf_spec_revision = 0;
487 insert_wsi(this, new_wsi);
490 * make sure NO events are seen yet on this new socket
491 * (otherwise we inherit old fds[client].revents from
492 * previous socket there and die mysteriously! )
494 this->fds[this->fds_count].revents = 0;
496 this->fds[this->fds_count].events = POLLIN;
497 this->fds[this->fds_count++].fd = accept_fd;
499 /* external POLL support via protocol 0 */
500 this->protocols[0].callback(this, new_wsi,
501 LWS_CALLBACK_ADD_POLL_FD,
502 (void *)(long)accept_fd, NULL, POLLIN);
506 case LWS_CONNMODE_BROADCAST_PROXY_LISTENER:
508 /* as we are listening, POLLIN means accept() is needed */
510 if (!pollfd->revents & POLLIN)
513 /* listen socket got an unencrypted connection... */
515 clilen = sizeof(cli_addr);
516 accept_fd = accept(pollfd->fd, (struct sockaddr *)&cli_addr,
519 fprintf(stderr, "ERROR on accept");
523 if (this->fds_count >= MAX_CLIENTS) {
524 fprintf(stderr, "too busy to accept new broadcast "
530 /* create a dummy wsi for the connection and add it */
532 new_wsi = malloc(sizeof(struct libwebsocket));
533 memset(new_wsi, 0, sizeof (struct libwebsocket));
534 new_wsi->sock = accept_fd;
535 new_wsi->mode = LWS_CONNMODE_BROADCAST_PROXY;
536 new_wsi->state = WSI_STATE_ESTABLISHED;
537 /* note which protocol we are proxying */
538 new_wsi->protocol_index_for_broadcast_proxy =
539 wsi->protocol_index_for_broadcast_proxy;
540 insert_wsi(this, new_wsi);
542 /* add connected socket to internal poll array */
544 this->fds[this->fds_count].revents = 0;
545 this->fds[this->fds_count].events = POLLIN;
546 this->fds[this->fds_count++].fd = accept_fd;
548 /* external POLL support via protocol 0 */
549 this->protocols[0].callback(this, new_wsi,
550 LWS_CALLBACK_ADD_POLL_FD,
551 (void *)(long)accept_fd, NULL, POLLIN);
555 case LWS_CONNMODE_BROADCAST_PROXY:
557 /* handle session socket closed */
559 if (pollfd->revents & (POLLERR | POLLHUP)) {
561 debug("Session Socket %p (fd=%d) dead\n",
562 (void *)wsi, pollfd->fd);
564 libwebsocket_close_and_free_session(this, wsi);
568 /* the guy requested a callback when it was OK to write */
570 if (pollfd->revents & POLLOUT) {
574 pollfd->events &= ~POLLOUT;
576 /* external POLL support via protocol 0 */
577 this->protocols[0].callback(this, wsi,
578 LWS_CALLBACK_CLEAR_MODE_POLL_FD,
579 (void *)(long)wsi->sock, NULL, POLLOUT);
581 wsi->protocol->callback(this, wsi,
582 LWS_CALLBACK_CLIENT_WRITEABLE,
587 /* any incoming data ready? */
589 if (!(pollfd->revents & POLLIN))
592 /* get the issued broadcast payload from the socket */
594 len = read(pollfd->fd, buf + LWS_SEND_BUFFER_PRE_PADDING,
595 MAX_BROADCAST_PAYLOAD);
597 fprintf(stderr, "Error reading broadcast payload\n");
601 /* broadcast it to all guys with this protocol index */
603 for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
605 for (m = 0; m < this->fd_hashtable[n].length; m++) {
607 new_wsi = this->fd_hashtable[n].wsi[m];
609 /* only to clients we are serving to */
611 if (new_wsi->mode != LWS_CONNMODE_WS_SERVING)
615 * never broadcast to non-established
619 if (new_wsi->state != WSI_STATE_ESTABLISHED)
623 * only broadcast to connections using
624 * the requested protocol
627 if (new_wsi->protocol->protocol_index !=
628 wsi->protocol_index_for_broadcast_proxy)
631 /* broadcast it to this connection */
633 new_wsi->protocol->callback(this, new_wsi,
634 LWS_CALLBACK_BROADCAST,
636 buf + LWS_SEND_BUFFER_PRE_PADDING, len);
641 case LWS_CONNMODE_WS_CLIENT_WAITING_PROXY_REPLY:
643 /* handle proxy hung up on us */
645 if (pollfd->revents & (POLLERR | POLLHUP)) {
647 fprintf(stderr, "Proxy connection %p (fd=%d) dead\n",
648 (void *)wsi, pollfd->fd);
650 libwebsocket_close_and_free_session(this, wsi);
654 n = recv(wsi->sock, pkt, sizeof pkt, 0);
656 libwebsocket_close_and_free_session(this, wsi);
657 fprintf(stderr, "ERROR reading from proxy socket\n");
662 if (strcmp(pkt, "HTTP/1.0 200 ") != 0) {
663 libwebsocket_close_and_free_session(this, wsi);
664 fprintf(stderr, "ERROR from proxy: %s\n", pkt);
668 /* clear his proxy connection timeout */
670 libwebsocket_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
674 case LWS_CONNMODE_WS_CLIENT_ISSUE_HANDSHAKE:
676 #ifdef LWS_OPENSSL_SUPPORT
679 wsi->ssl = SSL_new(this->ssl_client_ctx);
680 wsi->client_bio = BIO_new_socket(wsi->sock, BIO_NOCLOSE);
681 SSL_set_bio(wsi->ssl, wsi->client_bio, wsi->client_bio);
683 if (SSL_connect(wsi->ssl) <= 0) {
684 fprintf(stderr, "SSL connect error %s\n",
685 ERR_error_string(ERR_get_error(), ssl_err_buf));
686 libwebsocket_close_and_free_session(this, wsi);
690 n = SSL_get_verify_result(wsi->ssl);
691 if (n != X509_V_OK) {
692 if (n != X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT ||
695 fprintf(stderr, "server's cert didn't "
696 "look good %d\n", n);
697 libwebsocket_close_and_free_session(this, wsi);
706 #ifdef LWS_OPENSSL_SUPPORT
711 * create the random key
714 n = read(this->fd_random, hash, 16);
716 fprintf(stderr, "Unable to read from random dev %s\n",
717 SYSTEM_RANDOM_FILEPATH);
722 free(wsi->c_protocol);
723 libwebsocket_close_and_free_session(this, wsi);
727 lws_b64_encode_string(hash, 16, wsi->key_b64,
728 sizeof wsi->key_b64);
731 * 04 example client handshake
734 * Host: server.example.com
736 * Connection: Upgrade
737 * Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
738 * Sec-WebSocket-Origin: http://example.com
739 * Sec-WebSocket-Protocol: chat, superchat
740 * Sec-WebSocket-Version: 4
743 p += sprintf(p, "GET %s HTTP/1.1\x0d\x0a", wsi->c_path);
744 p += sprintf(p, "Host: %s\x0d\x0a", wsi->c_host);
745 p += sprintf(p, "Upgrade: websocket\x0d\x0a");
746 p += sprintf(p, "Connection: Upgrade\x0d\x0a"
747 "Sec-WebSocket-Key: ");
748 strcpy(p, wsi->key_b64);
749 p += strlen(wsi->key_b64);
750 p += sprintf(p, "\x0d\x0aSec-WebSocket-Origin: %s\x0d\x0a",
752 if (wsi->c_protocol != NULL)
753 p += sprintf(p, "Sec-WebSocket-Protocol: %s\x0d\x0a",
755 p += sprintf(p, "Sec-WebSocket-Version: %d\x0d\x0a\x0d\x0a",
756 wsi->ietf_spec_revision);
758 /* done with these now */
764 /* prepare the expected server accept response */
766 strcpy((char *)buf, wsi->key_b64);
767 strcpy((char *)&buf[strlen((char *)buf)], magic_websocket_guid);
769 SHA1(buf, strlen((char *)buf), (unsigned char *)hash);
771 lws_b64_encode_string(hash, 20,
772 wsi->initial_handshake_hash_base64,
773 sizeof wsi->initial_handshake_hash_base64);
775 /* send our request to the server */
777 #ifdef LWS_OPENSSL_SUPPORT
779 n = SSL_write(wsi->ssl, pkt, p - pkt);
782 n = send(wsi->sock, pkt, p - pkt, 0);
785 fprintf(stderr, "ERROR writing to client socket\n");
786 libwebsocket_close_and_free_session(this, wsi);
790 wsi->parser_state = WSI_TOKEN_NAME_PART;
791 wsi->mode = LWS_CONNMODE_WS_CLIENT_WAITING_SERVER_REPLY;
792 libwebsocket_set_timeout(wsi,
793 PENDING_TIMEOUT_AWAITING_SERVER_RESPONSE, 5);
797 case LWS_CONNMODE_WS_CLIENT_WAITING_SERVER_REPLY:
799 /* handle server hung up on us */
801 if (pollfd->revents & (POLLERR | POLLHUP)) {
803 fprintf(stderr, "Server connection %p (fd=%d) dead\n",
804 (void *)wsi, pollfd->fd);
810 /* interpret the server response */
813 * HTTP/1.1 101 Switching Protocols
815 * Connection: Upgrade
816 * Sec-WebSocket-Accept: me89jWimTRKTWwrS3aRrL53YZSo=
817 * Sec-WebSocket-Nonce: AQIDBAUGBwgJCgsMDQ4PEC==
818 * Sec-WebSocket-Protocol: chat
821 #ifdef LWS_OPENSSL_SUPPORT
823 len = SSL_read(wsi->ssl, pkt, sizeof pkt);
826 len = recv(wsi->sock, pkt, sizeof pkt, 0);
830 "libwebsocket_client_handshake read error\n");
835 for (n = 0; n < len; n++)
836 libwebsocket_parse(wsi, *p++);
838 if (wsi->parser_state != WSI_PARSING_COMPLETE) {
839 fprintf(stderr, "libwebsocket_client_handshake "
840 "server response ailed parsing\n");
845 * well, what the server sent looked reasonable for syntax.
846 * Now let's confirm it sent all the necessary headers
849 if (!wsi->utf8_token[WSI_TOKEN_HTTP].token_len ||
850 !wsi->utf8_token[WSI_TOKEN_UPGRADE].token_len ||
851 !wsi->utf8_token[WSI_TOKEN_CONNECTION].token_len ||
852 !wsi->utf8_token[WSI_TOKEN_ACCEPT].token_len ||
853 !wsi->utf8_token[WSI_TOKEN_NONCE].token_len ||
854 (!wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len &&
855 wsi->c_protocol != NULL)) {
856 fprintf(stderr, "libwebsocket_client_handshake "
857 "missing required header(s)\n");
859 fprintf(stderr, "%s", pkt);
864 * Everything seems to be there, now take a closer look at what
868 strtolower(wsi->utf8_token[WSI_TOKEN_HTTP].token);
869 if (strcmp(wsi->utf8_token[WSI_TOKEN_HTTP].token,
870 "101 switching protocols")) {
871 fprintf(stderr, "libwebsocket_client_handshake "
872 "server sent bad HTTP response '%s'\n",
873 wsi->utf8_token[WSI_TOKEN_HTTP].token);
877 strtolower(wsi->utf8_token[WSI_TOKEN_UPGRADE].token);
878 if (strcmp(wsi->utf8_token[WSI_TOKEN_UPGRADE].token,
880 fprintf(stderr, "libwebsocket_client_handshake server "
881 "sent bad Upgrade header '%s'\n",
882 wsi->utf8_token[WSI_TOKEN_UPGRADE].token);
886 strtolower(wsi->utf8_token[WSI_TOKEN_CONNECTION].token);
887 if (strcmp(wsi->utf8_token[WSI_TOKEN_CONNECTION].token,
889 fprintf(stderr, "libwebsocket_client_handshake server "
890 "sent bad Connection hdr '%s'\n",
891 wsi->utf8_token[WSI_TOKEN_CONNECTION].token);
896 pc = wsi->c_protocol;
899 * confirm the protocol the server wants to talk was in the list
900 * of protocols we offered
903 if (!wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len) {
906 * no protocol name to work from,
907 * default to first protocol
909 wsi->protocol = &this->protocols[0];
911 free(wsi->c_protocol);
916 while (*pc && !okay) {
918 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token,
919 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len)) &&
920 (pc[wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len] == ',' ||
921 pc[wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len] == '\0')) {
925 while (*pc && *pc != ',')
927 while (*pc && *pc != ' ')
931 /* done with him now */
934 free(wsi->c_protocol);
938 fprintf(stderr, "libwebsocket_client_handshake server "
939 "sent bad protocol '%s'\n",
940 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token);
945 * identify the selected protocol struct and set it
948 wsi->protocol = NULL;
949 while (this->protocols[n].callback) {
950 if (strcmp(wsi->utf8_token[WSI_TOKEN_PROTOCOL].token,
951 this->protocols[n].name) == 0)
952 wsi->protocol = &this->protocols[n];
956 if (wsi->protocol == NULL) {
957 fprintf(stderr, "libwebsocket_client_handshake server "
958 "requested protocol '%s', which we "
959 "said we supported but we don't!\n",
960 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token);
966 * Confirm his accept token is the one we precomputed
969 if (strcmp(wsi->utf8_token[WSI_TOKEN_ACCEPT].token,
970 wsi->initial_handshake_hash_base64)) {
971 fprintf(stderr, "libwebsocket_client_handshake server "
972 "sent bad ACCEPT '%s' vs computed '%s'\n",
973 wsi->utf8_token[WSI_TOKEN_ACCEPT].token,
974 wsi->initial_handshake_hash_base64);
979 * Calculate the masking key to use when sending data to server
982 strcpy((char *)buf, wsi->key_b64);
983 p = (char *)buf + strlen(wsi->key_b64);
984 strcpy(p, wsi->utf8_token[WSI_TOKEN_NONCE].token);
985 p += wsi->utf8_token[WSI_TOKEN_NONCE].token_len;
986 strcpy(p, magic_websocket_04_masking_guid);
987 SHA1(buf, strlen((char *)buf), wsi->masking_key_04);
989 /* allocate the per-connection user memory (if any) */
991 if (wsi->protocol->per_session_data_size) {
992 wsi->user_space = malloc(
993 wsi->protocol->per_session_data_size);
994 if (wsi->user_space == NULL) {
995 fprintf(stderr, "Out of memory for "
996 "conn user space\n");
1000 wsi->user_space = NULL;
1002 /* clear his proxy connection timeout */
1004 libwebsocket_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
1006 /* mark him as being alive */
1008 wsi->state = WSI_STATE_ESTABLISHED;
1009 wsi->mode = LWS_CONNMODE_WS_CLIENT;
1011 fprintf(stderr, "handshake OK for protocol %s\n",
1012 wsi->protocol->name);
1014 /* call him back to inform him he is up */
1016 wsi->protocol->callback(this, wsi,
1017 LWS_CALLBACK_CLIENT_ESTABLISHED,
1024 if (wsi->c_protocol)
1025 free(wsi->c_protocol);
1028 libwebsocket_close_and_free_session(this, wsi);
1032 case LWS_CONNMODE_WS_SERVING:
1033 case LWS_CONNMODE_WS_CLIENT:
1035 /* handle session socket closed */
1037 if (pollfd->revents & (POLLERR | POLLHUP)) {
1039 fprintf(stderr, "Session Socket %p (fd=%d) dead\n",
1040 (void *)wsi, pollfd->fd);
1042 libwebsocket_close_and_free_session(this, wsi);
1046 /* the guy requested a callback when it was OK to write */
1048 if (pollfd->revents & POLLOUT) {
1050 pollfd->events &= ~POLLOUT;
1052 /* external POLL support via protocol 0 */
1053 this->protocols[0].callback(this, wsi,
1054 LWS_CALLBACK_CLEAR_MODE_POLL_FD,
1055 (void *)(long)wsi->sock, NULL, POLLOUT);
1057 wsi->protocol->callback(this, wsi,
1058 LWS_CALLBACK_CLIENT_WRITEABLE,
1063 /* any incoming data ready? */
1065 if (!(pollfd->revents & POLLIN))
1068 #ifdef LWS_OPENSSL_SUPPORT
1070 n = SSL_read(wsi->ssl, buf, sizeof buf);
1073 n = recv(pollfd->fd, buf, sizeof buf, 0);
1076 fprintf(stderr, "Socket read returned %d\n", n);
1080 libwebsocket_close_and_free_session(this, wsi);
1084 /* service incoming data */
1086 n = libwebsocket_read(this, wsi, buf, n);
1100 * libwebsocket_context_destroy() - Destroy the websocket context
1101 * @this: Websocket context
1103 * This function closes any active connections and then frees the
1104 * context. After calling this, any further use of the context is
1108 libwebsocket_context_destroy(struct libwebsocket_context *this)
1112 struct libwebsocket *wsi;
1114 for (n = 0; n < FD_HASHTABLE_MODULUS; n++)
1115 for (m = 0; m < this->fd_hashtable[n].length; m++) {
1116 wsi = this->fd_hashtable[n].wsi[m];
1117 libwebsocket_close_and_free_session(this, wsi);
1120 close(this->fd_random);
1122 #ifdef LWS_OPENSSL_SUPPORT
1124 SSL_CTX_free(this->ssl_ctx);
1125 if (this->ssl_client_ctx)
1126 SSL_CTX_free(this->ssl_client_ctx);
1133 * libwebsocket_service() - Service any pending websocket activity
1134 * @this: Websocket context
1135 * @timeout_ms: Timeout for poll; 0 means return immediately if nothing needed
1136 * service otherwise block and service immediately, returning
1137 * after the timeout if nothing needed service.
1139 * This function deals with any pending websocket traffic, for three
1140 * kinds of event. It handles these events on both server and client
1141 * types of connection the same.
1143 * 1) Accept new connections to our context's server
1145 * 2) Perform pending broadcast writes initiated from other forked
1146 * processes (effectively serializing asynchronous broadcasts)
1148 * 3) Call the receive callback for incoming frame data received by
1149 * server or client connections.
1151 * You need to call this service function periodically to all the above
1152 * functions to happen; if your application is single-threaded you can
1153 * just call it in your main event loop.
1155 * Alternatively you can fork a new process that asynchronously handles
1156 * calling this service in a loop. In that case you are happy if this
1157 * call blocks your thread until it needs to take care of something and
1158 * would call it with a large nonzero timeout. Your loop then takes no
1159 * CPU while there is nothing happening.
1161 * If you are calling it in a single-threaded app, you don't want it to
1162 * wait around blocking other things in your loop from happening, so you
1163 * would call it with a timeout_ms of 0, so it returns immediately if
1164 * nothing is pending, or as soon as it services whatever was pending.
1169 libwebsocket_service(struct libwebsocket_context *this, int timeout_ms)
1173 /* stay dead once we are dead */
1178 /* wait for something to need service */
1180 n = poll(this->fds, this->fds_count, timeout_ms);
1181 if (n == 0) /* poll timeout */
1186 fprintf(stderr, "Listen Socket dead\n");
1191 /* handle accept on listening socket? */
1193 for (n = 0; n < this->fds_count; n++)
1194 if (this->fds[n].revents)
1195 libwebsocket_service_fd(this, &this->fds[n]);
1201 * libwebsocket_callback_on_writable() - Request a callback when this socket
1202 * becomes able to be written to without
1205 * @wsi: Websocket connection instance to get callback for
1209 libwebsocket_callback_on_writable(struct libwebsocket_context *this,
1210 struct libwebsocket *wsi)
1214 for (n = 0; n < this->fds_count; n++)
1215 if (this->fds[n].fd == wsi->sock) {
1216 this->fds[n].events |= POLLOUT;
1217 n = this->fds_count;
1220 /* external POLL support via protocol 0 */
1221 this->protocols[0].callback(this, wsi,
1222 LWS_CALLBACK_SET_MODE_POLL_FD,
1223 (void *)(long)wsi->sock, NULL, POLLOUT);
1229 * libwebsocket_callback_on_writable_all_protocol() - Request a callback for
1230 * all connections using the given protocol when it
1231 * becomes possible to write to each socket without
1234 * @protocol: Protocol whose connections will get callbacks
1238 libwebsocket_callback_on_writable_all_protocol(
1239 const struct libwebsocket_protocols *protocol)
1241 struct libwebsocket_context *this = protocol->owning_server;
1244 struct libwebsocket *wsi;
1246 for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
1248 for (m = 0; m < this->fd_hashtable[n].length; m++) {
1250 wsi = this->fd_hashtable[n].wsi[m];
1252 if (wsi->protocol == protocol)
1253 libwebsocket_callback_on_writable(this, wsi);
1261 * libwebsocket_set_timeout() - marks the wsi as subject to a timeout
1263 * You will not need this unless you are doing something special
1265 * @wsi: Websocket connection instance
1266 * @reason: timeout reason
1267 * @secs: how many seconds
1271 libwebsocket_set_timeout(struct libwebsocket *wsi,
1272 enum pending_timeout reason, int secs)
1276 gettimeofday(&tv, NULL);
1278 wsi->pending_timeout_limit = tv.tv_sec + secs;
1279 wsi->pending_timeout = reason;
1284 * libwebsocket_get_socket_fd() - returns the socket file descriptor
1286 * You will not need this unless you are doing something special
1288 * @wsi: Websocket connection instance
1292 libwebsocket_get_socket_fd(struct libwebsocket *wsi)
1298 * libwebsocket_rx_flow_control() - Enable and disable socket servicing for
1299 * receieved packets.
1301 * If the output side of a server process becomes choked, this allows flow
1302 * control for the input side.
1304 * @wsi: Websocket connection instance to get callback for
1305 * @enable: 0 = disable read servicing for this connection, 1 = enable
1309 libwebsocket_rx_flow_control(struct libwebsocket *wsi, int enable)
1311 struct libwebsocket_context *this = wsi->protocol->owning_server;
1314 for (n = 0; n < this->fds_count; n++)
1315 if (this->fds[n].fd == wsi->sock) {
1317 this->fds[n].events |= POLLIN;
1319 this->fds[n].events &= ~POLLIN;
1325 /* external POLL support via protocol 0 */
1326 this->protocols[0].callback(this, wsi,
1327 LWS_CALLBACK_SET_MODE_POLL_FD,
1328 (void *)(long)wsi->sock, NULL, POLLIN);
1330 /* external POLL support via protocol 0 */
1331 this->protocols[0].callback(this, wsi,
1332 LWS_CALLBACK_CLEAR_MODE_POLL_FD,
1333 (void *)(long)wsi->sock, NULL, POLLIN);
1336 fprintf(stderr, "libwebsocket_callback_on_writable "
1337 "unable to find socket\n");
1342 * libwebsocket_canonical_hostname() - returns this host's hostname
1344 * This is typically used by client code to fill in the host parameter
1345 * when making a client connection. You can only call it after the context
1348 * @this: Websocket context
1353 libwebsocket_canonical_hostname(struct libwebsocket_context *this)
1355 return (const char *)this->canonical_hostname;
1359 static void sigpipe_handler(int x)
1365 * libwebsocket_create_context() - Create the websocket handler
1366 * @port: Port to listen on... you can use 0 to suppress listening on
1367 * any port, that's what you want if you are not running a
1368 * websocket server at all but just using it as a client
1369 * @protocols: Array of structures listing supported protocols and a protocol-
1370 * specific callback for each one. The list is ended with an
1371 * entry that has a NULL callback pointer.
1372 * It's not const because we write the owning_server member
1373 * @ssl_cert_filepath: If libwebsockets was compiled to use ssl, and you want
1374 * to listen using SSL, set to the filepath to fetch the
1375 * server cert from, otherwise NULL for unencrypted
1376 * @ssl_private_key_filepath: filepath to private key if wanting SSL mode,
1378 * @gid: group id to change to after setting listen socket, or -1.
1379 * @uid: user id to change to after setting listen socket, or -1.
1380 * @options: 0, or LWS_SERVER_OPTION_DEFEAT_CLIENT_MASK
1382 * This function creates the listening socket and takes care
1383 * of all initialization in one step.
1385 * After initialization, it returns a struct libwebsocket_context * that
1386 * represents this server. After calling, user code needs to take care
1387 * of calling libwebsocket_service() with the context pointer to get the
1388 * server's sockets serviced. This can be done in the same process context
1389 * or a forked process, or another thread,
1391 * The protocol callback functions are called for a handful of events
1392 * including http requests coming in, websocket connections becoming
1393 * established, and data arriving; it's also called periodically to allow
1394 * async transmission.
1396 * HTTP requests are sent always to the FIRST protocol in @protocol, since
1397 * at that time websocket protocol has not been negotiated. Other
1398 * protocols after the first one never see any HTTP callack activity.
1400 * The server created is a simple http server by default; part of the
1401 * websocket standard is upgrading this http connection to a websocket one.
1403 * This allows the same server to provide files like scripts and favicon /
1404 * images or whatever over http and dynamic data over websockets all in
1405 * one place; they're all handled in the user callback.
1408 struct libwebsocket_context *
1409 libwebsocket_create_context(int port,
1410 struct libwebsocket_protocols *protocols,
1411 const char *ssl_cert_filepath,
1412 const char *ssl_private_key_filepath,
1413 int gid, int uid, unsigned int options)
1418 struct sockaddr_in serv_addr, cli_addr;
1420 struct libwebsocket_context *this = NULL;
1423 char hostname[1024];
1425 struct libwebsocket *wsi;
1427 #ifdef LWS_OPENSSL_SUPPORT
1429 char ssl_err_buf[512];
1432 this = malloc(sizeof(struct libwebsocket_context));
1434 fprintf(stderr, "No memory for websocket context\n");
1437 this->protocols = protocols;
1438 this->listen_port = port;
1439 this->http_proxy_port = 0;
1440 this->http_proxy_address[0] = '\0';
1441 this->options = options;
1442 this->fds_count = 0;
1444 this->fd_random = open(SYSTEM_RANDOM_FILEPATH, O_RDONLY);
1445 if (this->fd_random < 0) {
1446 fprintf(stderr, "Unable to open random device %s %d\n",
1447 SYSTEM_RANDOM_FILEPATH, this->fd_random);
1451 /* find canonical hostname */
1453 hostname[(sizeof hostname) - 1] = '\0';
1454 gethostname(hostname, (sizeof hostname) - 1);
1455 he = gethostbyname(hostname);
1457 strncpy(this->canonical_hostname, he->h_name,
1458 sizeof this->canonical_hostname - 1);
1459 this->canonical_hostname[sizeof this->canonical_hostname - 1] =
1462 strncpy(this->canonical_hostname, hostname,
1463 sizeof this->canonical_hostname - 1);
1465 /* split the proxy ads:port if given */
1467 p = getenv("http_proxy");
1469 strncpy(this->http_proxy_address, p,
1470 sizeof this->http_proxy_address - 1);
1471 this->http_proxy_address[
1472 sizeof this->http_proxy_address - 1] = '\0';
1474 p = strchr(this->http_proxy_address, ':');
1476 fprintf(stderr, "http_proxy needs to be ads:port\n");
1480 this->http_proxy_port = atoi(p + 1);
1482 fprintf(stderr, "Using proxy %s:%u\n",
1483 this->http_proxy_address,
1484 this->http_proxy_port);
1489 #ifdef LWS_OPENSSL_SUPPORT
1490 this->use_ssl = ssl_cert_filepath != NULL &&
1491 ssl_private_key_filepath != NULL;
1493 fprintf(stderr, " Compiled with SSL support, "
1496 fprintf(stderr, " Compiled with SSL support, "
1500 if (ssl_cert_filepath != NULL &&
1501 ssl_private_key_filepath != NULL) {
1502 fprintf(stderr, " Not compiled for OpenSSl support!\n");
1505 fprintf(stderr, " Compiled without SSL support, "
1506 "serving unencrypted\n");
1510 /* ignore SIGPIPE */
1512 signal(SIGPIPE, sigpipe_handler);
1515 #ifdef LWS_OPENSSL_SUPPORT
1517 /* basic openssl init */
1521 OpenSSL_add_all_algorithms();
1522 SSL_load_error_strings();
1525 * Firefox insists on SSLv23 not SSLv3
1526 * Konq disables SSLv2 by default now, SSLv23 works
1529 method = (SSL_METHOD *)SSLv23_server_method();
1531 fprintf(stderr, "problem creating ssl method: %s\n",
1532 ERR_error_string(ERR_get_error(), ssl_err_buf));
1535 this->ssl_ctx = SSL_CTX_new(method); /* create context */
1536 if (!this->ssl_ctx) {
1537 fprintf(stderr, "problem creating ssl context: %s\n",
1538 ERR_error_string(ERR_get_error(), ssl_err_buf));
1542 /* client context */
1544 method = (SSL_METHOD *)SSLv23_client_method();
1546 fprintf(stderr, "problem creating ssl method: %s\n",
1547 ERR_error_string(ERR_get_error(), ssl_err_buf));
1550 this->ssl_client_ctx = SSL_CTX_new(method); /* create context */
1551 if (!this->ssl_client_ctx) {
1552 fprintf(stderr, "problem creating ssl context: %s\n",
1553 ERR_error_string(ERR_get_error(), ssl_err_buf));
1558 /* openssl init for cert verification (used with client sockets) */
1560 if (!SSL_CTX_load_verify_locations(this->ssl_client_ctx, NULL,
1561 LWS_OPENSSL_CLIENT_CERTS)) {
1562 fprintf(stderr, "Unable to load SSL Client certs from %s "
1563 "(set by --with-client-cert-dir= in configure) -- "
1564 " client ssl isn't going to work",
1565 LWS_OPENSSL_CLIENT_CERTS);
1568 if (this->use_ssl) {
1570 /* openssl init for server sockets */
1572 /* set the local certificate from CertFile */
1573 n = SSL_CTX_use_certificate_file(this->ssl_ctx,
1574 ssl_cert_filepath, SSL_FILETYPE_PEM);
1576 fprintf(stderr, "problem getting cert '%s': %s\n",
1578 ERR_error_string(ERR_get_error(), ssl_err_buf));
1581 /* set the private key from KeyFile */
1582 if (SSL_CTX_use_PrivateKey_file(this->ssl_ctx,
1583 ssl_private_key_filepath,
1584 SSL_FILETYPE_PEM) != 1) {
1585 fprintf(stderr, "ssl problem getting key '%s': %s\n",
1586 ssl_private_key_filepath,
1587 ERR_error_string(ERR_get_error(), ssl_err_buf));
1590 /* verify private key */
1591 if (!SSL_CTX_check_private_key(this->ssl_ctx)) {
1592 fprintf(stderr, "Private SSL key doesn't match cert\n");
1596 /* SSL is happy and has a cert it's content with */
1602 if (lws_b64_selftest())
1605 /* fd hashtable init */
1607 for (n = 0; n < FD_HASHTABLE_MODULUS; n++)
1608 this->fd_hashtable[n].length = 0;
1610 /* set up our external listening socket we serve on */
1614 sockfd = socket(AF_INET, SOCK_STREAM, 0);
1616 fprintf(stderr, "ERROR opening socket");
1620 /* allow us to restart even if old sockets in TIME_WAIT */
1621 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
1623 bzero((char *) &serv_addr, sizeof(serv_addr));
1624 serv_addr.sin_family = AF_INET;
1625 serv_addr.sin_addr.s_addr = INADDR_ANY;
1626 serv_addr.sin_port = htons(port);
1628 n = bind(sockfd, (struct sockaddr *) &serv_addr,
1631 fprintf(stderr, "ERROR on binding to port %d (%d %d)\n",
1636 wsi = malloc(sizeof(struct libwebsocket));
1637 memset(wsi, 0, sizeof (struct libwebsocket));
1639 wsi->mode = LWS_CONNMODE_SERVER_LISTENER;
1640 insert_wsi(this, wsi);
1643 fprintf(stderr, " Listening on port %d\n", port);
1645 /* list in the internal poll array */
1647 this->fds[this->fds_count].fd = sockfd;
1648 this->fds[this->fds_count++].events = POLLIN;
1650 /* external POLL support via protocol 0 */
1651 this->protocols[0].callback(this, wsi,
1652 LWS_CALLBACK_ADD_POLL_FD,
1653 (void *)(long)sockfd, NULL, POLLIN);
1657 /* drop any root privs for this process */
1661 fprintf(stderr, "setgid: %s\n", strerror(errno));
1664 fprintf(stderr, "setuid: %s\n", strerror(errno));
1667 /* set up our internal broadcast trigger sockets per-protocol */
1669 for (this->count_protocols = 0;
1670 protocols[this->count_protocols].callback;
1671 this->count_protocols++) {
1672 protocols[this->count_protocols].owning_server = this;
1673 protocols[this->count_protocols].protocol_index =
1674 this->count_protocols;
1676 fd = socket(AF_INET, SOCK_STREAM, 0);
1678 fprintf(stderr, "ERROR opening socket");
1682 /* allow us to restart even if old sockets in TIME_WAIT */
1683 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
1685 bzero((char *) &serv_addr, sizeof(serv_addr));
1686 serv_addr.sin_family = AF_INET;
1687 serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
1688 serv_addr.sin_port = 0; /* pick the port for us */
1690 n = bind(fd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));
1692 fprintf(stderr, "ERROR on binding to port %d (%d %d)\n",
1697 slen = sizeof cli_addr;
1698 n = getsockname(fd, (struct sockaddr *)&cli_addr, &slen);
1700 fprintf(stderr, "getsockname failed\n");
1703 protocols[this->count_protocols].broadcast_socket_port =
1704 ntohs(cli_addr.sin_port);
1707 debug(" Protocol %s broadcast socket %d\n",
1708 protocols[this->count_protocols].name,
1709 ntohs(cli_addr.sin_port));
1711 /* dummy wsi per broadcast proxy socket */
1713 wsi = malloc(sizeof(struct libwebsocket));
1714 memset(wsi, 0, sizeof (struct libwebsocket));
1716 wsi->mode = LWS_CONNMODE_BROADCAST_PROXY_LISTENER;
1717 /* note which protocol we are proxying */
1718 wsi->protocol_index_for_broadcast_proxy = this->count_protocols;
1719 insert_wsi(this, wsi);
1721 /* list in internal poll array */
1723 this->fds[this->fds_count].fd = fd;
1724 this->fds[this->fds_count].events = POLLIN;
1725 this->fds[this->fds_count].revents = 0;
1728 /* external POLL support via protocol 0 */
1729 this->protocols[0].callback(this, wsi,
1730 LWS_CALLBACK_ADD_POLL_FD,
1731 (void *)(long)fd, NULL, POLLIN);
1741 * libwebsockets_fork_service_loop() - Optional helper function forks off
1742 * a process for the websocket server loop.
1743 * You don't have to use this but if not, you
1744 * have to make sure you are calling
1745 * libwebsocket_service periodically to service
1746 * the websocket traffic
1747 * @this: server context returned by creation function
1751 libwebsockets_fork_service_loop(struct libwebsocket_context *this)
1754 struct sockaddr_in cli_addr;
1764 /* main process context */
1767 * set up the proxy sockets to allow broadcast from
1768 * service process context
1771 for (p = 0; p < this->count_protocols; p++) {
1772 fd = socket(AF_INET, SOCK_STREAM, 0);
1774 fprintf(stderr, "Unable to create socket\n");
1777 cli_addr.sin_family = AF_INET;
1778 cli_addr.sin_port = htons(
1779 this->protocols[p].broadcast_socket_port);
1780 cli_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
1781 n = connect(fd, (struct sockaddr *)&cli_addr,
1784 fprintf(stderr, "Unable to connect to "
1785 "broadcast socket %d, %s\n",
1786 n, strerror(errno));
1790 this->protocols[p].broadcast_socket_user_fd = fd;
1796 /* we want a SIGHUP when our parent goes down */
1797 prctl(PR_SET_PDEATHSIG, SIGHUP);
1799 /* in this forked process, sit and service websocket connections */
1802 if (libwebsocket_service(this, 1000))
1811 * libwebsockets_get_protocol() - Returns a protocol pointer from a websocket
1813 * @wsi: pointer to struct websocket you want to know the protocol of
1816 * This is useful to get the protocol to broadcast back to from inside
1820 const struct libwebsocket_protocols *
1821 libwebsockets_get_protocol(struct libwebsocket *wsi)
1823 return wsi->protocol;
1827 * libwebsockets_broadcast() - Sends a buffer to the callback for all active
1828 * connections of the given protocol.
1829 * @protocol: pointer to the protocol you will broadcast to all members of
1830 * @buf: buffer containing the data to be broadcase. NOTE: this has to be
1831 * allocated with LWS_SEND_BUFFER_PRE_PADDING valid bytes before
1832 * the pointer and LWS_SEND_BUFFER_POST_PADDING afterwards in the
1833 * case you are calling this function from callback context.
1834 * @len: length of payload data in buf, starting from buf.
1836 * This function allows bulk sending of a packet to every connection using
1837 * the given protocol. It does not send the data directly; instead it calls
1838 * the callback with a reason type of LWS_CALLBACK_BROADCAST. If the callback
1839 * wants to actually send the data for that connection, the callback itself
1840 * should call libwebsocket_write().
1842 * libwebsockets_broadcast() can be called from another fork context without
1843 * having to take any care about data visibility between the processes, it'll
1849 libwebsockets_broadcast(const struct libwebsocket_protocols *protocol,
1850 unsigned char *buf, size_t len)
1852 struct libwebsocket_context *this = protocol->owning_server;
1855 struct libwebsocket * wsi;
1857 if (!protocol->broadcast_socket_user_fd) {
1859 * We are either running unforked / flat, or we are being
1860 * called from poll thread context
1861 * eg, from a callback. In that case don't use sockets for
1862 * broadcast IPC (since we can't open a socket connection to
1863 * a socket listening on our own thread) but directly do the
1866 * Locking is not needed because we are by definition being
1867 * called in the poll thread context and are serialized.
1870 for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
1872 for (m = 0; m < this->fd_hashtable[n].length; m++) {
1874 wsi = this->fd_hashtable[n].wsi[m];
1876 if (wsi->mode != LWS_CONNMODE_WS_SERVING)
1880 * never broadcast to
1881 * non-established connections
1883 if (wsi->state != WSI_STATE_ESTABLISHED)
1886 /* only broadcast to guys using
1887 * requested protocol
1889 if (wsi->protocol != protocol)
1892 wsi->protocol->callback(this, wsi,
1893 LWS_CALLBACK_BROADCAST,
1903 * We're being called from a different process context than the server
1904 * loop. Instead of broadcasting directly, we send our
1905 * payload on a socket to do the IPC; the server process will serialize
1906 * the broadcast action in its main poll() loop.
1908 * There's one broadcast socket listening for each protocol supported
1909 * set up when the websocket server initializes
1912 n = send(protocol->broadcast_socket_user_fd, buf, len, MSG_NOSIGNAL);