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)
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);
173 * signal we are closing, libsocket_write will
174 * add any necessary version-specific stuff. If the write fails,
175 * no worries we are closing anyway. If we didn't initiate this
176 * close, then our state has been changed to
177 * WSI_STATE_RETURNED_CLOSE_ALREADY and we will skip this
180 if (old_state == WSI_STATE_ESTABLISHED)
181 libwebsocket_write(wsi, &buf[LWS_SEND_BUFFER_PRE_PADDING], 0,
184 wsi->state = WSI_STATE_DEAD_SOCKET;
186 /* tell the user it's all over for this guy */
188 if (wsi->protocol->callback && old_state == WSI_STATE_ESTABLISHED)
189 wsi->protocol->callback(this, wsi, LWS_CALLBACK_CLOSED,
190 wsi->user_space, NULL, 0);
192 /* free up his allocations */
194 for (n = 0; n < WSI_TOKEN_COUNT; n++)
195 if (wsi->utf8_token[n].token)
196 free(wsi->utf8_token[n].token);
198 /* fprintf(stderr, "closing fd=%d\n", wsi->sock); */
200 #ifdef LWS_OPENSSL_SUPPORT
202 n = SSL_get_fd(wsi->ssl);
203 SSL_shutdown(wsi->ssl);
208 shutdown(wsi->sock, SHUT_RDWR);
210 #ifdef LWS_OPENSSL_SUPPORT
214 free(wsi->user_space);
220 * libwebsockets_hangup_on_client() - Server calls to terminate client
222 * @this: libwebsockets context
223 * @fd: Connection socket descriptor
227 libwebsockets_hangup_on_client(struct libwebsocket_context *this, int fd)
229 struct libwebsocket *wsi = wsi_from_fd(this, fd);
235 delete_from_fd(this, fd);
237 for (n = 0; n < this->fds_count - 1; n++)
238 if (this->fds[n].fd == fd) {
239 while (n < this->fds_count - 1) {
240 this->fds[n] = this->fds[n + 1];
247 libwebsocket_close_and_free_session(this, wsi);
252 * libwebsockets_get_peer_addresses() - Get client address information
253 * @fd: Connection socket descriptor
254 * @name: Buffer to take client address name
255 * @name_len: Length of client address name buffer
256 * @rip: Buffer to take client address IP qotted quad
257 * @rip_len: Length of client address IP buffer
259 * This function fills in @name and @rip with the name and IP of
260 * the client connected with socket descriptor @fd. Names may be
261 * truncated if there is not enough room. If either cannot be
262 * determined, they will be returned as valid zero-length strings.
266 libwebsockets_get_peer_addresses(int fd, char *name, int name_len,
267 char *rip, int rip_len)
270 struct sockaddr_in sin;
271 struct hostent *host;
272 struct hostent *host1;
281 if (getpeername(fd, (struct sockaddr *) &sin, &len) < 0) {
282 perror("getpeername");
286 host = gethostbyaddr((char *) &sin.sin_addr, sizeof sin.sin_addr,
289 perror("gethostbyaddr");
293 strncpy(name, host->h_name, name_len);
294 name[name_len - 1] = '\0';
296 host1 = gethostbyname(host->h_name);
302 p = host1->h_addr_list[n++];
305 if (host1->h_addrtype != AF_INET)
308 sprintf(ip, "%d.%d.%d.%d",
309 p[0], p[1], p[2], p[3]);
311 strncpy(rip, ip, rip_len);
312 rip[rip_len - 1] = '\0';
317 * libwebsocket_service_fd() - Service polled socket with something waiting
318 * @this: Websocket context
319 * @pollfd: The pollfd entry describing the socket fd and which events
322 * This function closes any active connections and then frees the
323 * context. After calling this, any further use of the context is
328 libwebsocket_service_fd(struct libwebsocket_context *this,
329 struct pollfd *pollfd)
331 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + MAX_BROADCAST_PAYLOAD +
332 LWS_SEND_BUFFER_POST_PADDING];
333 struct libwebsocket *wsi;
334 struct libwebsocket *new_wsi;
340 struct sockaddr_in cli_addr;
342 static const char magic_websocket_guid[] =
343 "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
344 static const char magic_websocket_04_masking_guid[] =
345 "61AC5F19-FBBA-4540-B96F-6561F1AB40A8";
351 #ifdef LWS_OPENSSL_SUPPORT
352 char ssl_err_buf[512];
355 * you can call us with pollfd = NULL to just allow the once-per-second
356 * global timeout checks; if less than a second since the last check
357 * it returns immediately then.
360 gettimeofday(&tv, NULL);
362 if (this->last_timeout_check_s != tv.tv_sec) {
363 this->last_timeout_check_s = tv.tv_sec;
365 /* global timeout check once per second */
367 for (n = 0; n < this->fds_count; n++) {
368 wsi = wsi_from_fd(this, this->fds[n].fd);
369 if (!wsi->pending_timeout)
373 * if we went beyond the allowed time, kill the
377 if (tv.tv_sec > wsi->pending_timeout_limit)
378 libwebsocket_close_and_free_session(this, wsi);
382 /* just here for timeout management? */
387 /* no, here to service a socket descriptor */
389 wsi = wsi_from_fd(this, pollfd->fd);
395 case LWS_CONNMODE_SERVER_LISTENER:
397 /* pollin means a client has connected to us then */
399 if (!pollfd->revents & POLLIN)
402 /* listen socket got an unencrypted connection... */
404 clilen = sizeof(cli_addr);
405 accept_fd = accept(pollfd->fd, (struct sockaddr *)&cli_addr,
408 fprintf(stderr, "ERROR on accept");
412 if (this->fds_count >= MAX_CLIENTS) {
413 fprintf(stderr, "too busy to accept new client\n");
419 * look at who we connected to and give user code a chance
420 * to reject based on client IP. There's no protocol selected
421 * yet so we issue this to protocols[0]
424 if ((this->protocols[0].callback)(this, wsi,
425 LWS_CALLBACK_FILTER_NETWORK_CONNECTION,
426 (void*)(long)accept_fd, NULL, 0)) {
427 fprintf(stderr, "Callback denied network connection\n");
432 /* accepting connection to main listener */
434 new_wsi = malloc(sizeof(struct libwebsocket));
435 if (new_wsi == NULL) {
436 fprintf(stderr, "Out of memory for new connection\n");
440 memset(new_wsi, 0, sizeof (struct libwebsocket));
441 new_wsi->sock = accept_fd;
442 new_wsi->pending_timeout = NO_PENDING_TIMEOUT;
444 #ifdef LWS_OPENSSL_SUPPORT
449 new_wsi->ssl = SSL_new(this->ssl_ctx);
450 if (new_wsi->ssl == NULL) {
451 fprintf(stderr, "SSL_new failed: %s\n",
452 ERR_error_string(SSL_get_error(
453 new_wsi->ssl, 0), NULL));
454 libwebsockets_decode_ssl_error();
459 SSL_set_fd(new_wsi->ssl, accept_fd);
461 n = SSL_accept(new_wsi->ssl);
464 * browsers seem to probe with various
465 * ssl params which fail then retry
468 debug("SSL_accept failed skt %u: %s\n",
470 ERR_error_string(SSL_get_error(
471 new_wsi->ssl, n), NULL));
477 debug("accepted new SSL conn "
478 "port %u on fd=%d SSL ver %s\n",
479 ntohs(cli_addr.sin_port), accept_fd,
480 SSL_get_version(new_wsi->ssl));
484 debug("accepted new conn port %u on fd=%d\n",
485 ntohs(cli_addr.sin_port), accept_fd);
487 /* intialize the instance struct */
489 new_wsi->state = WSI_STATE_HTTP;
490 new_wsi->name_buffer_pos = 0;
491 new_wsi->mode = LWS_CONNMODE_WS_SERVING;
493 for (n = 0; n < WSI_TOKEN_COUNT; n++) {
494 new_wsi->utf8_token[n].token = NULL;
495 new_wsi->utf8_token[n].token_len = 0;
499 * these can only be set once the protocol is known
500 * we set an unestablished connection's protocol pointer
501 * to the start of the supported list, so it can look
502 * for matching ones during the handshake
504 new_wsi->protocol = this->protocols;
505 new_wsi->user_space = NULL;
508 * Default protocol is 76 / 00
509 * After 76, there's a header specified to inform which
510 * draft the client wants, when that's seen we modify
511 * the individual connection's spec revision accordingly
513 new_wsi->ietf_spec_revision = 0;
515 insert_wsi(this, new_wsi);
518 * make sure NO events are seen yet on this new socket
519 * (otherwise we inherit old fds[client].revents from
520 * previous socket there and die mysteriously! )
522 this->fds[this->fds_count].revents = 0;
524 this->fds[this->fds_count].events = POLLIN;
525 this->fds[this->fds_count++].fd = accept_fd;
527 /* external POLL support via protocol 0 */
528 this->protocols[0].callback(this, new_wsi,
529 LWS_CALLBACK_ADD_POLL_FD,
530 (void *)(long)accept_fd, NULL, POLLIN);
534 case LWS_CONNMODE_BROADCAST_PROXY_LISTENER:
536 /* as we are listening, POLLIN means accept() is needed */
538 if (!pollfd->revents & POLLIN)
541 /* listen socket got an unencrypted connection... */
543 clilen = sizeof(cli_addr);
544 accept_fd = accept(pollfd->fd, (struct sockaddr *)&cli_addr,
547 fprintf(stderr, "ERROR on accept");
551 if (this->fds_count >= MAX_CLIENTS) {
552 fprintf(stderr, "too busy to accept new broadcast "
558 /* create a dummy wsi for the connection and add it */
560 new_wsi = malloc(sizeof(struct libwebsocket));
561 memset(new_wsi, 0, sizeof (struct libwebsocket));
562 new_wsi->sock = accept_fd;
563 new_wsi->mode = LWS_CONNMODE_BROADCAST_PROXY;
564 new_wsi->state = WSI_STATE_ESTABLISHED;
565 /* note which protocol we are proxying */
566 new_wsi->protocol_index_for_broadcast_proxy =
567 wsi->protocol_index_for_broadcast_proxy;
568 insert_wsi(this, new_wsi);
570 /* add connected socket to internal poll array */
572 this->fds[this->fds_count].revents = 0;
573 this->fds[this->fds_count].events = POLLIN;
574 this->fds[this->fds_count++].fd = accept_fd;
576 /* external POLL support via protocol 0 */
577 this->protocols[0].callback(this, new_wsi,
578 LWS_CALLBACK_ADD_POLL_FD,
579 (void *)(long)accept_fd, NULL, POLLIN);
583 case LWS_CONNMODE_BROADCAST_PROXY:
585 /* handle session socket closed */
587 if (pollfd->revents & (POLLERR | POLLHUP)) {
589 debug("Session Socket %p (fd=%d) dead\n",
590 (void *)wsi, pollfd->fd);
592 libwebsocket_close_and_free_session(this, wsi);
596 /* the guy requested a callback when it was OK to write */
598 if (pollfd->revents & POLLOUT) {
602 pollfd->events &= ~POLLOUT;
604 /* external POLL support via protocol 0 */
605 this->protocols[0].callback(this, wsi,
606 LWS_CALLBACK_CLEAR_MODE_POLL_FD,
607 (void *)(long)wsi->sock, NULL, POLLOUT);
609 wsi->protocol->callback(this, wsi,
610 LWS_CALLBACK_CLIENT_WRITEABLE,
615 /* any incoming data ready? */
617 if (!(pollfd->revents & POLLIN))
620 /* get the issued broadcast payload from the socket */
622 len = read(pollfd->fd, buf + LWS_SEND_BUFFER_PRE_PADDING,
623 MAX_BROADCAST_PAYLOAD);
625 fprintf(stderr, "Error reading broadcast payload\n");
629 /* broadcast it to all guys with this protocol index */
631 for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
633 for (m = 0; m < this->fd_hashtable[n].length; m++) {
635 new_wsi = this->fd_hashtable[n].wsi[m];
637 /* only to clients we are serving to */
639 if (new_wsi->mode != LWS_CONNMODE_WS_SERVING)
643 * never broadcast to non-established
647 if (new_wsi->state != WSI_STATE_ESTABLISHED)
651 * only broadcast to connections using
652 * the requested protocol
655 if (new_wsi->protocol->protocol_index !=
656 wsi->protocol_index_for_broadcast_proxy)
659 /* broadcast it to this connection */
661 new_wsi->protocol->callback(this, new_wsi,
662 LWS_CALLBACK_BROADCAST,
664 buf + LWS_SEND_BUFFER_PRE_PADDING, len);
669 case LWS_CONNMODE_WS_CLIENT_WAITING_PROXY_REPLY:
671 /* handle proxy hung up on us */
673 if (pollfd->revents & (POLLERR | POLLHUP)) {
675 fprintf(stderr, "Proxy connection %p (fd=%d) dead\n",
676 (void *)wsi, pollfd->fd);
678 libwebsocket_close_and_free_session(this, wsi);
682 n = recv(wsi->sock, pkt, sizeof pkt, 0);
684 libwebsocket_close_and_free_session(this, wsi);
685 fprintf(stderr, "ERROR reading from proxy socket\n");
690 if (strcmp(pkt, "HTTP/1.0 200 ") != 0) {
691 libwebsocket_close_and_free_session(this, wsi);
692 fprintf(stderr, "ERROR from proxy: %s\n", pkt);
696 /* clear his proxy connection timeout */
698 libwebsocket_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
702 case LWS_CONNMODE_WS_CLIENT_ISSUE_HANDSHAKE:
704 #ifdef LWS_OPENSSL_SUPPORT
707 wsi->ssl = SSL_new(this->ssl_client_ctx);
708 wsi->client_bio = BIO_new_socket(wsi->sock, BIO_NOCLOSE);
709 SSL_set_bio(wsi->ssl, wsi->client_bio, wsi->client_bio);
711 if (SSL_connect(wsi->ssl) <= 0) {
712 fprintf(stderr, "SSL connect error %s\n",
713 ERR_error_string(ERR_get_error(), ssl_err_buf));
714 libwebsocket_close_and_free_session(this, wsi);
718 n = SSL_get_verify_result(wsi->ssl);
719 if (n != X509_V_OK) {
720 if (n != X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT ||
723 fprintf(stderr, "server's cert didn't "
724 "look good %d\n", n);
725 libwebsocket_close_and_free_session(this, wsi);
734 #ifdef LWS_OPENSSL_SUPPORT
739 * create the random key
742 n = read(this->fd_random, hash, 16);
744 fprintf(stderr, "Unable to read from random dev %s\n",
745 SYSTEM_RANDOM_FILEPATH);
750 free(wsi->c_protocol);
751 libwebsocket_close_and_free_session(this, wsi);
755 lws_b64_encode_string(hash, 16, wsi->key_b64,
756 sizeof wsi->key_b64);
759 * 04 example client handshake
762 * Host: server.example.com
764 * Connection: Upgrade
765 * Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
766 * Sec-WebSocket-Origin: http://example.com
767 * Sec-WebSocket-Protocol: chat, superchat
768 * Sec-WebSocket-Version: 4
771 p += sprintf(p, "GET %s HTTP/1.1\x0d\x0a", wsi->c_path);
772 p += sprintf(p, "Host: %s\x0d\x0a", wsi->c_host);
773 p += sprintf(p, "Upgrade: websocket\x0d\x0a");
774 p += sprintf(p, "Connection: Upgrade\x0d\x0a"
775 "Sec-WebSocket-Key: ");
776 strcpy(p, wsi->key_b64);
777 p += strlen(wsi->key_b64);
778 p += sprintf(p, "\x0d\x0aSec-WebSocket-Origin: %s\x0d\x0a",
780 if (wsi->c_protocol != NULL)
781 p += sprintf(p, "Sec-WebSocket-Protocol: %s\x0d\x0a",
783 p += sprintf(p, "Sec-WebSocket-Version: %d\x0d\x0a\x0d\x0a",
784 wsi->ietf_spec_revision);
786 /* done with these now */
792 /* prepare the expected server accept response */
794 strcpy((char *)buf, wsi->key_b64);
795 strcpy((char *)&buf[strlen((char *)buf)], magic_websocket_guid);
797 SHA1(buf, strlen((char *)buf), (unsigned char *)hash);
799 lws_b64_encode_string(hash, 20,
800 wsi->initial_handshake_hash_base64,
801 sizeof wsi->initial_handshake_hash_base64);
803 /* send our request to the server */
805 #ifdef LWS_OPENSSL_SUPPORT
807 n = SSL_write(wsi->ssl, pkt, p - pkt);
810 n = send(wsi->sock, pkt, p - pkt, 0);
813 fprintf(stderr, "ERROR writing to client socket\n");
814 libwebsocket_close_and_free_session(this, wsi);
818 wsi->parser_state = WSI_TOKEN_NAME_PART;
819 wsi->mode = LWS_CONNMODE_WS_CLIENT_WAITING_SERVER_REPLY;
820 libwebsocket_set_timeout(wsi,
821 PENDING_TIMEOUT_AWAITING_SERVER_RESPONSE, 5);
825 case LWS_CONNMODE_WS_CLIENT_WAITING_SERVER_REPLY:
827 /* handle server hung up on us */
829 if (pollfd->revents & (POLLERR | POLLHUP)) {
831 fprintf(stderr, "Server connection %p (fd=%d) dead\n",
832 (void *)wsi, pollfd->fd);
838 /* interpret the server response */
841 * HTTP/1.1 101 Switching Protocols
843 * Connection: Upgrade
844 * Sec-WebSocket-Accept: me89jWimTRKTWwrS3aRrL53YZSo=
845 * Sec-WebSocket-Nonce: AQIDBAUGBwgJCgsMDQ4PEC==
846 * Sec-WebSocket-Protocol: chat
849 #ifdef LWS_OPENSSL_SUPPORT
851 len = SSL_read(wsi->ssl, pkt, sizeof pkt);
854 len = recv(wsi->sock, pkt, sizeof pkt, 0);
858 "libwebsocket_client_handshake read error\n");
863 for (n = 0; n < len; n++)
864 libwebsocket_parse(wsi, *p++);
866 if (wsi->parser_state != WSI_PARSING_COMPLETE) {
867 fprintf(stderr, "libwebsocket_client_handshake "
868 "server response ailed parsing\n");
873 * well, what the server sent looked reasonable for syntax.
874 * Now let's confirm it sent all the necessary headers
877 if (!wsi->utf8_token[WSI_TOKEN_HTTP].token_len ||
878 !wsi->utf8_token[WSI_TOKEN_UPGRADE].token_len ||
879 !wsi->utf8_token[WSI_TOKEN_CONNECTION].token_len ||
880 !wsi->utf8_token[WSI_TOKEN_ACCEPT].token_len ||
881 !wsi->utf8_token[WSI_TOKEN_NONCE].token_len ||
882 (!wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len &&
883 wsi->c_protocol != NULL)) {
884 fprintf(stderr, "libwebsocket_client_handshake "
885 "missing required header(s)\n");
887 fprintf(stderr, "%s", pkt);
892 * Everything seems to be there, now take a closer look at what
896 strtolower(wsi->utf8_token[WSI_TOKEN_HTTP].token);
897 if (strcmp(wsi->utf8_token[WSI_TOKEN_HTTP].token,
898 "101 switching protocols")) {
899 fprintf(stderr, "libwebsocket_client_handshake "
900 "server sent bad HTTP response '%s'\n",
901 wsi->utf8_token[WSI_TOKEN_HTTP].token);
905 strtolower(wsi->utf8_token[WSI_TOKEN_UPGRADE].token);
906 if (strcmp(wsi->utf8_token[WSI_TOKEN_UPGRADE].token,
908 fprintf(stderr, "libwebsocket_client_handshake server "
909 "sent bad Upgrade header '%s'\n",
910 wsi->utf8_token[WSI_TOKEN_UPGRADE].token);
914 strtolower(wsi->utf8_token[WSI_TOKEN_CONNECTION].token);
915 if (strcmp(wsi->utf8_token[WSI_TOKEN_CONNECTION].token,
917 fprintf(stderr, "libwebsocket_client_handshake server "
918 "sent bad Connection hdr '%s'\n",
919 wsi->utf8_token[WSI_TOKEN_CONNECTION].token);
924 pc = wsi->c_protocol;
927 * confirm the protocol the server wants to talk was in the list
928 * of protocols we offered
931 if (!wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len) {
934 * no protocol name to work from,
935 * default to first protocol
937 wsi->protocol = &this->protocols[0];
939 free(wsi->c_protocol);
944 while (*pc && !okay) {
946 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token,
947 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len)) &&
948 (pc[wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len] == ',' ||
949 pc[wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len] == '\0')) {
953 while (*pc && *pc != ',')
955 while (*pc && *pc != ' ')
959 /* done with him now */
962 free(wsi->c_protocol);
966 fprintf(stderr, "libwebsocket_client_handshake server "
967 "sent bad protocol '%s'\n",
968 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token);
973 * identify the selected protocol struct and set it
976 wsi->protocol = NULL;
977 while (this->protocols[n].callback) {
978 if (strcmp(wsi->utf8_token[WSI_TOKEN_PROTOCOL].token,
979 this->protocols[n].name) == 0)
980 wsi->protocol = &this->protocols[n];
984 if (wsi->protocol == NULL) {
985 fprintf(stderr, "libwebsocket_client_handshake server "
986 "requested protocol '%s', which we "
987 "said we supported but we don't!\n",
988 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token);
994 * Confirm his accept token is the one we precomputed
997 if (strcmp(wsi->utf8_token[WSI_TOKEN_ACCEPT].token,
998 wsi->initial_handshake_hash_base64)) {
999 fprintf(stderr, "libwebsocket_client_handshake server "
1000 "sent bad ACCEPT '%s' vs computed '%s'\n",
1001 wsi->utf8_token[WSI_TOKEN_ACCEPT].token,
1002 wsi->initial_handshake_hash_base64);
1007 * Calculate the masking key to use when sending data to server
1010 strcpy((char *)buf, wsi->key_b64);
1011 p = (char *)buf + strlen(wsi->key_b64);
1012 strcpy(p, wsi->utf8_token[WSI_TOKEN_NONCE].token);
1013 p += wsi->utf8_token[WSI_TOKEN_NONCE].token_len;
1014 strcpy(p, magic_websocket_04_masking_guid);
1015 SHA1(buf, strlen((char *)buf), wsi->masking_key_04);
1017 /* allocate the per-connection user memory (if any) */
1019 if (wsi->protocol->per_session_data_size) {
1020 wsi->user_space = malloc(
1021 wsi->protocol->per_session_data_size);
1022 if (wsi->user_space == NULL) {
1023 fprintf(stderr, "Out of memory for "
1024 "conn user space\n");
1028 wsi->user_space = NULL;
1030 /* clear his proxy connection timeout */
1032 libwebsocket_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
1034 /* mark him as being alive */
1036 wsi->state = WSI_STATE_ESTABLISHED;
1037 wsi->mode = LWS_CONNMODE_WS_CLIENT;
1039 fprintf(stderr, "handshake OK for protocol %s\n",
1040 wsi->protocol->name);
1042 /* call him back to inform him he is up */
1044 wsi->protocol->callback(this, wsi,
1045 LWS_CALLBACK_CLIENT_ESTABLISHED,
1052 if (wsi->c_protocol)
1053 free(wsi->c_protocol);
1056 libwebsocket_close_and_free_session(this, wsi);
1060 case LWS_CONNMODE_WS_SERVING:
1061 case LWS_CONNMODE_WS_CLIENT:
1063 /* handle session socket closed */
1065 if (pollfd->revents & (POLLERR | POLLHUP)) {
1067 fprintf(stderr, "Session Socket %p (fd=%d) dead\n",
1068 (void *)wsi, pollfd->fd);
1070 libwebsocket_close_and_free_session(this, wsi);
1074 /* the guy requested a callback when it was OK to write */
1076 if (pollfd->revents & POLLOUT) {
1078 pollfd->events &= ~POLLOUT;
1080 /* external POLL support via protocol 0 */
1081 this->protocols[0].callback(this, wsi,
1082 LWS_CALLBACK_CLEAR_MODE_POLL_FD,
1083 (void *)(long)wsi->sock, NULL, POLLOUT);
1085 wsi->protocol->callback(this, wsi,
1086 LWS_CALLBACK_CLIENT_WRITEABLE,
1091 /* any incoming data ready? */
1093 if (!(pollfd->revents & POLLIN))
1096 #ifdef LWS_OPENSSL_SUPPORT
1098 n = SSL_read(wsi->ssl, buf, sizeof buf);
1101 n = recv(pollfd->fd, buf, sizeof buf, 0);
1104 fprintf(stderr, "Socket read returned %d\n", n);
1108 libwebsocket_close_and_free_session(this, wsi);
1112 /* service incoming data */
1114 n = libwebsocket_read(this, wsi, buf, n);
1128 * libwebsocket_context_destroy() - Destroy the websocket context
1129 * @this: Websocket context
1131 * This function closes any active connections and then frees the
1132 * context. After calling this, any further use of the context is
1136 libwebsocket_context_destroy(struct libwebsocket_context *this)
1140 struct libwebsocket *wsi;
1142 for (n = 0; n < FD_HASHTABLE_MODULUS; n++)
1143 for (m = 0; m < this->fd_hashtable[n].length; m++) {
1144 wsi = this->fd_hashtable[n].wsi[m];
1145 libwebsocket_close_and_free_session(this, wsi);
1148 close(this->fd_random);
1150 #ifdef LWS_OPENSSL_SUPPORT
1152 SSL_CTX_free(this->ssl_ctx);
1153 if (this->ssl_client_ctx)
1154 SSL_CTX_free(this->ssl_client_ctx);
1161 * libwebsocket_service() - Service any pending websocket activity
1162 * @this: Websocket context
1163 * @timeout_ms: Timeout for poll; 0 means return immediately if nothing needed
1164 * service otherwise block and service immediately, returning
1165 * after the timeout if nothing needed service.
1167 * This function deals with any pending websocket traffic, for three
1168 * kinds of event. It handles these events on both server and client
1169 * types of connection the same.
1171 * 1) Accept new connections to our context's server
1173 * 2) Perform pending broadcast writes initiated from other forked
1174 * processes (effectively serializing asynchronous broadcasts)
1176 * 3) Call the receive callback for incoming frame data received by
1177 * server or client connections.
1179 * You need to call this service function periodically to all the above
1180 * functions to happen; if your application is single-threaded you can
1181 * just call it in your main event loop.
1183 * Alternatively you can fork a new process that asynchronously handles
1184 * calling this service in a loop. In that case you are happy if this
1185 * call blocks your thread until it needs to take care of something and
1186 * would call it with a large nonzero timeout. Your loop then takes no
1187 * CPU while there is nothing happening.
1189 * If you are calling it in a single-threaded app, you don't want it to
1190 * wait around blocking other things in your loop from happening, so you
1191 * would call it with a timeout_ms of 0, so it returns immediately if
1192 * nothing is pending, or as soon as it services whatever was pending.
1197 libwebsocket_service(struct libwebsocket_context *this, int timeout_ms)
1201 /* stay dead once we are dead */
1206 /* wait for something to need service */
1208 n = poll(this->fds, this->fds_count, timeout_ms);
1209 if (n == 0) /* poll timeout */
1214 fprintf(stderr, "Listen Socket dead\n");
1219 /* handle accept on listening socket? */
1221 for (n = 0; n < this->fds_count; n++)
1222 if (this->fds[n].revents)
1223 libwebsocket_service_fd(this, &this->fds[n]);
1229 * libwebsocket_callback_on_writable() - Request a callback when this socket
1230 * becomes able to be written to without
1233 * @this: libwebsockets context
1234 * @wsi: Websocket connection instance to get callback for
1238 libwebsocket_callback_on_writable(struct libwebsocket_context *this,
1239 struct libwebsocket *wsi)
1243 for (n = 0; n < this->fds_count; n++)
1244 if (this->fds[n].fd == wsi->sock) {
1245 this->fds[n].events |= POLLOUT;
1246 n = this->fds_count;
1249 /* external POLL support via protocol 0 */
1250 this->protocols[0].callback(this, wsi,
1251 LWS_CALLBACK_SET_MODE_POLL_FD,
1252 (void *)(long)wsi->sock, NULL, POLLOUT);
1258 * libwebsocket_callback_on_writable_all_protocol() - Request a callback for
1259 * all connections using the given protocol when it
1260 * becomes possible to write to each socket without
1263 * @protocol: Protocol whose connections will get callbacks
1267 libwebsocket_callback_on_writable_all_protocol(
1268 const struct libwebsocket_protocols *protocol)
1270 struct libwebsocket_context *this = protocol->owning_server;
1273 struct libwebsocket *wsi;
1275 for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
1277 for (m = 0; m < this->fd_hashtable[n].length; m++) {
1279 wsi = this->fd_hashtable[n].wsi[m];
1281 if (wsi->protocol == protocol)
1282 libwebsocket_callback_on_writable(this, wsi);
1290 * libwebsocket_set_timeout() - marks the wsi as subject to a timeout
1292 * You will not need this unless you are doing something special
1294 * @wsi: Websocket connection instance
1295 * @reason: timeout reason
1296 * @secs: how many seconds
1300 libwebsocket_set_timeout(struct libwebsocket *wsi,
1301 enum pending_timeout reason, int secs)
1305 gettimeofday(&tv, NULL);
1307 wsi->pending_timeout_limit = tv.tv_sec + secs;
1308 wsi->pending_timeout = reason;
1313 * libwebsocket_get_socket_fd() - returns the socket file descriptor
1315 * You will not need this unless you are doing something special
1317 * @wsi: Websocket connection instance
1321 libwebsocket_get_socket_fd(struct libwebsocket *wsi)
1327 * libwebsocket_rx_flow_control() - Enable and disable socket servicing for
1328 * receieved packets.
1330 * If the output side of a server process becomes choked, this allows flow
1331 * control for the input side.
1333 * @wsi: Websocket connection instance to get callback for
1334 * @enable: 0 = disable read servicing for this connection, 1 = enable
1338 libwebsocket_rx_flow_control(struct libwebsocket *wsi, int enable)
1340 struct libwebsocket_context *this = wsi->protocol->owning_server;
1343 for (n = 0; n < this->fds_count; n++)
1344 if (this->fds[n].fd == wsi->sock) {
1346 this->fds[n].events |= POLLIN;
1348 this->fds[n].events &= ~POLLIN;
1354 /* external POLL support via protocol 0 */
1355 this->protocols[0].callback(this, wsi,
1356 LWS_CALLBACK_SET_MODE_POLL_FD,
1357 (void *)(long)wsi->sock, NULL, POLLIN);
1359 /* external POLL support via protocol 0 */
1360 this->protocols[0].callback(this, wsi,
1361 LWS_CALLBACK_CLEAR_MODE_POLL_FD,
1362 (void *)(long)wsi->sock, NULL, POLLIN);
1365 fprintf(stderr, "libwebsocket_callback_on_writable "
1366 "unable to find socket\n");
1371 * libwebsocket_canonical_hostname() - returns this host's hostname
1373 * This is typically used by client code to fill in the host parameter
1374 * when making a client connection. You can only call it after the context
1377 * @this: Websocket context
1382 libwebsocket_canonical_hostname(struct libwebsocket_context *this)
1384 return (const char *)this->canonical_hostname;
1388 static void sigpipe_handler(int x)
1394 * libwebsocket_create_context() - Create the websocket handler
1395 * @port: Port to listen on... you can use 0 to suppress listening on
1396 * any port, that's what you want if you are not running a
1397 * websocket server at all but just using it as a client
1398 * @interface: NULL to bind the listen socket to all interfaces, or the
1399 * interface name, eg, "eth2"
1400 * @protocols: Array of structures listing supported protocols and a protocol-
1401 * specific callback for each one. The list is ended with an
1402 * entry that has a NULL callback pointer.
1403 * It's not const because we write the owning_server member
1404 * @ssl_cert_filepath: If libwebsockets was compiled to use ssl, and you want
1405 * to listen using SSL, set to the filepath to fetch the
1406 * server cert from, otherwise NULL for unencrypted
1407 * @ssl_private_key_filepath: filepath to private key if wanting SSL mode,
1409 * @gid: group id to change to after setting listen socket, or -1.
1410 * @uid: user id to change to after setting listen socket, or -1.
1411 * @options: 0, or LWS_SERVER_OPTION_DEFEAT_CLIENT_MASK
1413 * This function creates the listening socket and takes care
1414 * of all initialization in one step.
1416 * After initialization, it returns a struct libwebsocket_context * that
1417 * represents this server. After calling, user code needs to take care
1418 * of calling libwebsocket_service() with the context pointer to get the
1419 * server's sockets serviced. This can be done in the same process context
1420 * or a forked process, or another thread,
1422 * The protocol callback functions are called for a handful of events
1423 * including http requests coming in, websocket connections becoming
1424 * established, and data arriving; it's also called periodically to allow
1425 * async transmission.
1427 * HTTP requests are sent always to the FIRST protocol in @protocol, since
1428 * at that time websocket protocol has not been negotiated. Other
1429 * protocols after the first one never see any HTTP callack activity.
1431 * The server created is a simple http server by default; part of the
1432 * websocket standard is upgrading this http connection to a websocket one.
1434 * This allows the same server to provide files like scripts and favicon /
1435 * images or whatever over http and dynamic data over websockets all in
1436 * one place; they're all handled in the user callback.
1439 struct libwebsocket_context *
1440 libwebsocket_create_context(int port, const char *interface,
1441 struct libwebsocket_protocols *protocols,
1442 const char *ssl_cert_filepath,
1443 const char *ssl_private_key_filepath,
1444 int gid, int uid, unsigned int options)
1449 struct sockaddr_in serv_addr, cli_addr;
1451 struct libwebsocket_context *this = NULL;
1454 char hostname[1024];
1456 struct libwebsocket *wsi;
1458 #ifdef LWS_OPENSSL_SUPPORT
1460 char ssl_err_buf[512];
1463 this = malloc(sizeof(struct libwebsocket_context));
1465 fprintf(stderr, "No memory for websocket context\n");
1468 this->protocols = protocols;
1469 this->listen_port = port;
1470 this->http_proxy_port = 0;
1471 this->http_proxy_address[0] = '\0';
1472 this->options = options;
1473 this->fds_count = 0;
1475 this->fd_random = open(SYSTEM_RANDOM_FILEPATH, O_RDONLY);
1476 if (this->fd_random < 0) {
1477 fprintf(stderr, "Unable to open random device %s %d\n",
1478 SYSTEM_RANDOM_FILEPATH, this->fd_random);
1482 /* find canonical hostname */
1484 hostname[(sizeof hostname) - 1] = '\0';
1485 gethostname(hostname, (sizeof hostname) - 1);
1486 he = gethostbyname(hostname);
1488 strncpy(this->canonical_hostname, he->h_name,
1489 sizeof this->canonical_hostname - 1);
1490 this->canonical_hostname[sizeof this->canonical_hostname - 1] =
1493 strncpy(this->canonical_hostname, hostname,
1494 sizeof this->canonical_hostname - 1);
1496 /* split the proxy ads:port if given */
1498 p = getenv("http_proxy");
1500 strncpy(this->http_proxy_address, p,
1501 sizeof this->http_proxy_address - 1);
1502 this->http_proxy_address[
1503 sizeof this->http_proxy_address - 1] = '\0';
1505 p = strchr(this->http_proxy_address, ':');
1507 fprintf(stderr, "http_proxy needs to be ads:port\n");
1511 this->http_proxy_port = atoi(p + 1);
1513 fprintf(stderr, "Using proxy %s:%u\n",
1514 this->http_proxy_address,
1515 this->http_proxy_port);
1520 #ifdef LWS_OPENSSL_SUPPORT
1521 this->use_ssl = ssl_cert_filepath != NULL &&
1522 ssl_private_key_filepath != NULL;
1524 fprintf(stderr, " Compiled with SSL support, "
1527 fprintf(stderr, " Compiled with SSL support, "
1531 if (ssl_cert_filepath != NULL &&
1532 ssl_private_key_filepath != NULL) {
1533 fprintf(stderr, " Not compiled for OpenSSl support!\n");
1536 fprintf(stderr, " Compiled without SSL support, "
1537 "serving unencrypted\n");
1541 /* ignore SIGPIPE */
1543 signal(SIGPIPE, sigpipe_handler);
1546 #ifdef LWS_OPENSSL_SUPPORT
1548 /* basic openssl init */
1552 OpenSSL_add_all_algorithms();
1553 SSL_load_error_strings();
1556 * Firefox insists on SSLv23 not SSLv3
1557 * Konq disables SSLv2 by default now, SSLv23 works
1560 method = (SSL_METHOD *)SSLv23_server_method();
1562 fprintf(stderr, "problem creating ssl method: %s\n",
1563 ERR_error_string(ERR_get_error(), ssl_err_buf));
1566 this->ssl_ctx = SSL_CTX_new(method); /* create context */
1567 if (!this->ssl_ctx) {
1568 fprintf(stderr, "problem creating ssl context: %s\n",
1569 ERR_error_string(ERR_get_error(), ssl_err_buf));
1573 /* client context */
1575 method = (SSL_METHOD *)SSLv23_client_method();
1577 fprintf(stderr, "problem creating ssl method: %s\n",
1578 ERR_error_string(ERR_get_error(), ssl_err_buf));
1581 this->ssl_client_ctx = SSL_CTX_new(method); /* create context */
1582 if (!this->ssl_client_ctx) {
1583 fprintf(stderr, "problem creating ssl context: %s\n",
1584 ERR_error_string(ERR_get_error(), ssl_err_buf));
1589 /* openssl init for cert verification (used with client sockets) */
1591 if (!SSL_CTX_load_verify_locations(this->ssl_client_ctx, NULL,
1592 LWS_OPENSSL_CLIENT_CERTS)) {
1593 fprintf(stderr, "Unable to load SSL Client certs from %s "
1594 "(set by --with-client-cert-dir= in configure) -- "
1595 " client ssl isn't going to work",
1596 LWS_OPENSSL_CLIENT_CERTS);
1599 if (this->use_ssl) {
1601 /* openssl init for server sockets */
1603 /* set the local certificate from CertFile */
1604 n = SSL_CTX_use_certificate_file(this->ssl_ctx,
1605 ssl_cert_filepath, SSL_FILETYPE_PEM);
1607 fprintf(stderr, "problem getting cert '%s': %s\n",
1609 ERR_error_string(ERR_get_error(), ssl_err_buf));
1612 /* set the private key from KeyFile */
1613 if (SSL_CTX_use_PrivateKey_file(this->ssl_ctx,
1614 ssl_private_key_filepath,
1615 SSL_FILETYPE_PEM) != 1) {
1616 fprintf(stderr, "ssl problem getting key '%s': %s\n",
1617 ssl_private_key_filepath,
1618 ERR_error_string(ERR_get_error(), ssl_err_buf));
1621 /* verify private key */
1622 if (!SSL_CTX_check_private_key(this->ssl_ctx)) {
1623 fprintf(stderr, "Private SSL key doesn't match cert\n");
1627 /* SSL is happy and has a cert it's content with */
1633 if (lws_b64_selftest())
1636 /* fd hashtable init */
1638 for (n = 0; n < FD_HASHTABLE_MODULUS; n++)
1639 this->fd_hashtable[n].length = 0;
1641 /* set up our external listening socket we serve on */
1645 sockfd = socket(AF_INET, SOCK_STREAM, 0);
1647 fprintf(stderr, "ERROR opening socket");
1651 /* allow us to restart even if old sockets in TIME_WAIT */
1652 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
1654 bzero((char *) &serv_addr, sizeof(serv_addr));
1655 serv_addr.sin_family = AF_INET;
1656 if (interface == NULL)
1657 serv_addr.sin_addr.s_addr = INADDR_ANY;
1659 interface_to_sa(interface, &serv_addr,
1661 serv_addr.sin_port = htons(port);
1663 n = bind(sockfd, (struct sockaddr *) &serv_addr,
1666 fprintf(stderr, "ERROR on binding to port %d (%d %d)\n",
1671 wsi = malloc(sizeof(struct libwebsocket));
1672 memset(wsi, 0, sizeof (struct libwebsocket));
1674 wsi->mode = LWS_CONNMODE_SERVER_LISTENER;
1675 insert_wsi(this, wsi);
1678 fprintf(stderr, " Listening on port %d\n", port);
1680 /* list in the internal poll array */
1682 this->fds[this->fds_count].fd = sockfd;
1683 this->fds[this->fds_count++].events = POLLIN;
1685 /* external POLL support via protocol 0 */
1686 this->protocols[0].callback(this, wsi,
1687 LWS_CALLBACK_ADD_POLL_FD,
1688 (void *)(long)sockfd, NULL, POLLIN);
1692 /* drop any root privs for this process */
1696 fprintf(stderr, "setgid: %s\n", strerror(errno));
1699 fprintf(stderr, "setuid: %s\n", strerror(errno));
1702 /* set up our internal broadcast trigger sockets per-protocol */
1704 for (this->count_protocols = 0;
1705 protocols[this->count_protocols].callback;
1706 this->count_protocols++) {
1707 protocols[this->count_protocols].owning_server = this;
1708 protocols[this->count_protocols].protocol_index =
1709 this->count_protocols;
1711 fd = socket(AF_INET, SOCK_STREAM, 0);
1713 fprintf(stderr, "ERROR opening socket");
1717 /* allow us to restart even if old sockets in TIME_WAIT */
1718 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
1720 bzero((char *) &serv_addr, sizeof(serv_addr));
1721 serv_addr.sin_family = AF_INET;
1722 serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
1723 serv_addr.sin_port = 0; /* pick the port for us */
1725 n = bind(fd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));
1727 fprintf(stderr, "ERROR on binding to port %d (%d %d)\n",
1732 slen = sizeof cli_addr;
1733 n = getsockname(fd, (struct sockaddr *)&cli_addr, &slen);
1735 fprintf(stderr, "getsockname failed\n");
1738 protocols[this->count_protocols].broadcast_socket_port =
1739 ntohs(cli_addr.sin_port);
1742 debug(" Protocol %s broadcast socket %d\n",
1743 protocols[this->count_protocols].name,
1744 ntohs(cli_addr.sin_port));
1746 /* dummy wsi per broadcast proxy socket */
1748 wsi = malloc(sizeof(struct libwebsocket));
1749 memset(wsi, 0, sizeof (struct libwebsocket));
1751 wsi->mode = LWS_CONNMODE_BROADCAST_PROXY_LISTENER;
1752 /* note which protocol we are proxying */
1753 wsi->protocol_index_for_broadcast_proxy = this->count_protocols;
1754 insert_wsi(this, wsi);
1756 /* list in internal poll array */
1758 this->fds[this->fds_count].fd = fd;
1759 this->fds[this->fds_count].events = POLLIN;
1760 this->fds[this->fds_count].revents = 0;
1763 /* external POLL support via protocol 0 */
1764 this->protocols[0].callback(this, wsi,
1765 LWS_CALLBACK_ADD_POLL_FD,
1766 (void *)(long)fd, NULL, POLLIN);
1776 * libwebsockets_fork_service_loop() - Optional helper function forks off
1777 * a process for the websocket server loop.
1778 * You don't have to use this but if not, you
1779 * have to make sure you are calling
1780 * libwebsocket_service periodically to service
1781 * the websocket traffic
1782 * @this: server context returned by creation function
1786 libwebsockets_fork_service_loop(struct libwebsocket_context *this)
1789 struct sockaddr_in cli_addr;
1799 /* main process context */
1802 * set up the proxy sockets to allow broadcast from
1803 * service process context
1806 for (p = 0; p < this->count_protocols; p++) {
1807 fd = socket(AF_INET, SOCK_STREAM, 0);
1809 fprintf(stderr, "Unable to create socket\n");
1812 cli_addr.sin_family = AF_INET;
1813 cli_addr.sin_port = htons(
1814 this->protocols[p].broadcast_socket_port);
1815 cli_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
1816 n = connect(fd, (struct sockaddr *)&cli_addr,
1819 fprintf(stderr, "Unable to connect to "
1820 "broadcast socket %d, %s\n",
1821 n, strerror(errno));
1825 this->protocols[p].broadcast_socket_user_fd = fd;
1831 /* we want a SIGHUP when our parent goes down */
1832 prctl(PR_SET_PDEATHSIG, SIGHUP);
1834 /* in this forked process, sit and service websocket connections */
1837 if (libwebsocket_service(this, 1000))
1846 * libwebsockets_get_protocol() - Returns a protocol pointer from a websocket
1848 * @wsi: pointer to struct websocket you want to know the protocol of
1851 * This is useful to get the protocol to broadcast back to from inside
1855 const struct libwebsocket_protocols *
1856 libwebsockets_get_protocol(struct libwebsocket *wsi)
1858 return wsi->protocol;
1862 * libwebsockets_broadcast() - Sends a buffer to the callback for all active
1863 * connections of the given protocol.
1864 * @protocol: pointer to the protocol you will broadcast to all members of
1865 * @buf: buffer containing the data to be broadcase. NOTE: this has to be
1866 * allocated with LWS_SEND_BUFFER_PRE_PADDING valid bytes before
1867 * the pointer and LWS_SEND_BUFFER_POST_PADDING afterwards in the
1868 * case you are calling this function from callback context.
1869 * @len: length of payload data in buf, starting from buf.
1871 * This function allows bulk sending of a packet to every connection using
1872 * the given protocol. It does not send the data directly; instead it calls
1873 * the callback with a reason type of LWS_CALLBACK_BROADCAST. If the callback
1874 * wants to actually send the data for that connection, the callback itself
1875 * should call libwebsocket_write().
1877 * libwebsockets_broadcast() can be called from another fork context without
1878 * having to take any care about data visibility between the processes, it'll
1884 libwebsockets_broadcast(const struct libwebsocket_protocols *protocol,
1885 unsigned char *buf, size_t len)
1887 struct libwebsocket_context *this = protocol->owning_server;
1890 struct libwebsocket * wsi;
1892 if (!protocol->broadcast_socket_user_fd) {
1894 * We are either running unforked / flat, or we are being
1895 * called from poll thread context
1896 * eg, from a callback. In that case don't use sockets for
1897 * broadcast IPC (since we can't open a socket connection to
1898 * a socket listening on our own thread) but directly do the
1901 * Locking is not needed because we are by definition being
1902 * called in the poll thread context and are serialized.
1905 for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
1907 for (m = 0; m < this->fd_hashtable[n].length; m++) {
1909 wsi = this->fd_hashtable[n].wsi[m];
1911 if (wsi->mode != LWS_CONNMODE_WS_SERVING)
1915 * never broadcast to
1916 * non-established connections
1918 if (wsi->state != WSI_STATE_ESTABLISHED)
1921 /* only broadcast to guys using
1922 * requested protocol
1924 if (wsi->protocol != protocol)
1927 wsi->protocol->callback(this, wsi,
1928 LWS_CALLBACK_BROADCAST,
1938 * We're being called from a different process context than the server
1939 * loop. Instead of broadcasting directly, we send our
1940 * payload on a socket to do the IPC; the server process will serialize
1941 * the broadcast action in its main poll() loop.
1943 * There's one broadcast socket listening for each protocol supported
1944 * set up when the websocket server initializes
1947 n = send(protocol->broadcast_socket_user_fd, buf, len, MSG_NOSIGNAL);