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"
24 /* file descriptor hash management */
27 wsi_from_fd(struct libwebsocket_context *this, int fd)
29 int h = LWS_FD_HASH(fd);
32 for (n = 0; n < this->fd_hashtable[h].length; n++)
33 if (this->fd_hashtable[h].wsi[n]->sock == fd)
34 return this->fd_hashtable[h].wsi[n];
40 insert_wsi(struct libwebsocket_context *this, struct libwebsocket *wsi)
42 int h = LWS_FD_HASH(wsi->sock);
44 if (this->fd_hashtable[h].length == MAX_CLIENTS - 1) {
45 fprintf(stderr, "hash table overflow\n");
49 this->fd_hashtable[h].wsi[this->fd_hashtable[h].length++] = wsi;
55 delete_from_fd(struct libwebsocket_context *this, int fd)
57 int h = LWS_FD_HASH(fd);
60 for (n = 0; n < this->fd_hashtable[h].length; n++)
61 if (this->fd_hashtable[h].wsi[n]->sock == fd) {
62 while (n < this->fd_hashtable[h].length) {
63 this->fd_hashtable[h].wsi[n] =
64 this->fd_hashtable[h].wsi[n + 1];
67 this->fd_hashtable[h].length--;
72 fprintf(stderr, "Failed to find fd %d requested for "
73 "delete in hashtable\n", fd);
79 libwebsocket_close_and_free_session(struct libwebsocket *wsi)
82 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 2 +
83 LWS_SEND_BUFFER_POST_PADDING];
85 if ((unsigned long)wsi < LWS_MAX_PROTOCOLS)
90 if (n == WSI_STATE_DEAD_SOCKET)
94 * signal we are closing, libsocket_write will
95 * add any necessary version-specific stuff. If the write fails,
96 * no worries we are closing anyway. If we didn't initiate this
97 * close, then our state has been changed to
98 * WSI_STATE_RETURNED_CLOSE_ALREADY and we can skip this
101 if (n == WSI_STATE_ESTABLISHED)
102 libwebsocket_write(wsi, &buf[LWS_SEND_BUFFER_PRE_PADDING], 0,
105 wsi->state = WSI_STATE_DEAD_SOCKET;
107 if (wsi->protocol->callback && n == WSI_STATE_ESTABLISHED)
108 wsi->protocol->callback(wsi, LWS_CALLBACK_CLOSED,
109 wsi->user_space, NULL, 0);
111 for (n = 0; n < WSI_TOKEN_COUNT; n++)
112 if (wsi->utf8_token[n].token)
113 free(wsi->utf8_token[n].token);
115 /* fprintf(stderr, "closing fd=%d\n", wsi->sock); */
117 #ifdef LWS_OPENSSL_SUPPORT
119 n = SSL_get_fd(wsi->ssl);
120 SSL_shutdown(wsi->ssl);
125 shutdown(wsi->sock, SHUT_RDWR);
127 #ifdef LWS_OPENSSL_SUPPORT
131 free(wsi->user_space);
137 libwebsocket_service_fd(struct libwebsocket_context *this,
138 struct pollfd *pollfd)
140 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + MAX_BROADCAST_PAYLOAD +
141 LWS_SEND_BUFFER_POST_PADDING];
142 struct libwebsocket *wsi = wsi_from_fd(this, pollfd->fd);
143 struct libwebsocket *new_wsi;
149 struct sockaddr_in cli_addr;
155 case LWS_CONNMODE_SERVER_LISTENER:
157 /* pollin means a client has connected to us then */
159 if (!pollfd->revents & POLLIN)
162 /* listen socket got an unencrypted connection... */
164 clilen = sizeof(cli_addr);
165 accept_fd = accept(pollfd->fd, (struct sockaddr *)&cli_addr,
168 fprintf(stderr, "ERROR on accept");
172 if (this->fds_count >= MAX_CLIENTS) {
173 fprintf(stderr, "too busy");
178 /* accepting connection to main listener */
180 new_wsi = malloc(sizeof(struct libwebsocket));
181 if (new_wsi == NULL) {
182 fprintf(stderr, "Out of memory for new connection\n");
186 memset(new_wsi, 0, sizeof (struct libwebsocket));
187 new_wsi->sock = accept_fd;
189 #ifdef LWS_OPENSSL_SUPPORT
191 this->ssl_ctx = NULL;
195 new_wsi->ssl = SSL_new(this->ssl_ctx);
196 if (new_wsi->ssl == NULL) {
197 fprintf(stderr, "SSL_new failed: %s\n",
198 ERR_error_string(SSL_get_error(
199 new_wsi->ssl, 0), NULL));
204 SSL_set_fd(new_wsi->ssl, accept_fd);
206 n = SSL_accept(new_wsi->ssl);
209 * browsers seem to probe with various
210 * ssl params which fail then retry
213 debug("SSL_accept failed skt %u: %s\n",
215 ERR_error_string(SSL_get_error(
216 new_wsi->ssl, n), NULL));
222 debug("accepted new SSL conn "
223 "port %u on fd=%d SSL ver %s\n",
224 ntohs(cli_addr.sin_port), accept_fd,
225 SSL_get_version(new_wsi->ssl));
229 debug("accepted new conn port %u on fd=%d\n",
230 ntohs(cli_addr.sin_port), accept_fd);
232 /* intialize the instance struct */
234 new_wsi->state = WSI_STATE_HTTP;
235 new_wsi->name_buffer_pos = 0;
236 new_wsi->mode = LWS_CONNMODE_WS_SERVING;
238 for (n = 0; n < WSI_TOKEN_COUNT; n++) {
239 new_wsi->utf8_token[n].token = NULL;
240 new_wsi->utf8_token[n].token_len = 0;
244 * these can only be set once the protocol is known
245 * we set an unestablished connection's protocol pointer
246 * to the start of the supported list, so it can look
247 * for matching ones during the handshake
249 new_wsi->protocol = this->protocols;
250 new_wsi->user_space = NULL;
253 * Default protocol is 76 / 00
254 * After 76, there's a header specified to inform which
255 * draft the client wants, when that's seen we modify
256 * the individual connection's spec revision accordingly
258 new_wsi->ietf_spec_revision = 0;
260 insert_wsi(this, new_wsi);
264 * make sure NO events are seen yet on this new socket
265 * (otherwise we inherit old fds[client].revents from
266 * previous socket there and die mysteriously! )
268 this->fds[this->fds_count].revents = 0;
270 this->fds[this->fds_count].events = POLLIN;
271 this->fds[this->fds_count++].fd = accept_fd;
275 case LWS_CONNMODE_BROADCAST_PROXY_LISTENER:
277 /* as we are listening, POLLIN means accept() is needed */
279 if (!pollfd->revents & POLLIN)
282 /* listen socket got an unencrypted connection... */
284 clilen = sizeof(cli_addr);
285 accept_fd = accept(pollfd->fd, (struct sockaddr *)&cli_addr,
288 fprintf(stderr, "ERROR on accept");
292 if (this->fds_count >= MAX_CLIENTS) {
293 fprintf(stderr, "too busy");
298 /* create a dummy wsi for the connection and add it */
300 new_wsi = malloc(sizeof(struct libwebsocket));
301 memset(new_wsi, 0, sizeof (struct libwebsocket));
302 new_wsi->sock = accept_fd;
303 new_wsi->mode = LWS_CONNMODE_BROADCAST_PROXY;
304 new_wsi->state = WSI_STATE_ESTABLISHED;
305 /* note which protocol we are proxying */
306 new_wsi->protocol_index_for_broadcast_proxy =
307 wsi->protocol_index_for_broadcast_proxy;
308 insert_wsi(this, new_wsi);
310 /* add connected socket to internal poll array */
312 this->fds[this->fds_count].revents = 0;
313 this->fds[this->fds_count].events = POLLIN;
314 this->fds[this->fds_count++].fd = accept_fd;
318 case LWS_CONNMODE_BROADCAST_PROXY:
320 /* handle session socket closed */
322 if (pollfd->revents & (POLLERR | POLLHUP)) {
324 debug("Session Socket %p (fd=%d) dead\n",
325 (void *)wsi, accept_fd);
327 libwebsocket_close_and_free_session(wsi);
331 /* the guy requested a callback when it was OK to write */
333 if (pollfd->revents & POLLOUT) {
337 pollfd->events &= ~POLLOUT;
339 wsi->protocol->callback(wsi,
340 LWS_CALLBACK_CLIENT_WRITEABLE,
345 /* any incoming data ready? */
347 if (!(pollfd->revents & POLLIN))
350 /* get the issued broadcast payload from the socket */
352 len = read(pollfd->fd, buf + LWS_SEND_BUFFER_PRE_PADDING,
353 MAX_BROADCAST_PAYLOAD);
355 fprintf(stderr, "Error reading broadcast payload\n");
359 /* broadcast it to all guys with this protocol index */
361 for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
363 for (m = 0; m < this->fd_hashtable[n].length; m++) {
365 new_wsi = this->fd_hashtable[n].wsi[m];
367 /* only to clients we are serving to */
369 if (new_wsi->mode != LWS_CONNMODE_WS_SERVING)
373 * never broadcast to non-established
377 if (new_wsi->state != WSI_STATE_ESTABLISHED)
381 * only broadcast to connections using
382 * the requested protocol
385 if (new_wsi->protocol->protocol_index !=
386 wsi->protocol_index_for_broadcast_proxy)
389 /* broadcast it to this connection */
391 new_wsi->protocol->callback(new_wsi,
392 LWS_CALLBACK_BROADCAST,
394 buf + LWS_SEND_BUFFER_PRE_PADDING, len);
399 case LWS_CONNMODE_WS_SERVING:
400 case LWS_CONNMODE_WS_CLIENT:
402 /* handle session socket closed */
404 if (pollfd->revents & (POLLERR | POLLHUP)) {
406 debug("Session Socket %p (fd=%d) dead\n",
407 (void *)wsi, pollfd->fd);
409 libwebsocket_close_and_free_session(wsi);
413 /* the guy requested a callback when it was OK to write */
415 if (pollfd->revents & POLLOUT) {
417 pollfd->events &= ~POLLOUT;
419 wsi->protocol->callback(wsi,
420 LWS_CALLBACK_CLIENT_WRITEABLE,
425 /* any incoming data ready? */
427 if (!(pollfd->revents & POLLIN))
430 #ifdef LWS_OPENSSL_SUPPORT
432 n = SSL_read(wsi->ssl, buf, sizeof buf);
435 n = recv(pollfd->fd, buf, sizeof buf, 0);
438 fprintf(stderr, "Socket read returned %d\n", n);
442 libwebsocket_close_and_free_session(wsi);
446 /* service incoming data */
448 n = libwebsocket_read(wsi, buf, n);
452 * it closed and nuked wsi[client], so remove the
453 * socket handle and wsi from our service list
457 debug("nuking wsi %p, fsd_count = %d\n",
458 (void *)wsi, this->fds_count - 1);
460 delete_from_fd(this, pollfd->fd);
463 for (n = 0; n < this->fds_count; n++)
464 if (this->fds[n].fd == pollfd->fd) {
465 while (n < this->fds_count) {
466 this->fds[n] = this->fds[n + 1];
480 * libwebsocket_context_destroy() - Destroy the websocket context
481 * @this: Websocket context
483 * This function closes any active connections and then frees the
484 * context. After calling this, any further use of the context is
488 libwebsocket_context_destroy(struct libwebsocket_context *this)
492 struct libwebsocket *wsi;
494 for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
496 for (m = 0; m < this->fd_hashtable[n].length; m++) {
498 wsi = this->fd_hashtable[n].wsi[m];
501 case LWS_CONNMODE_WS_SERVING:
502 libwebsocket_close_and_free_session(wsi);
504 case LWS_CONNMODE_WS_CLIENT:
505 libwebsocket_client_close(wsi);
513 close(this->fd_random);
515 #ifdef LWS_OPENSSL_SUPPORT
517 SSL_CTX_free(this->ssl_ctx);
518 if (this->ssl_client_ctx)
519 SSL_CTX_free(this->ssl_client_ctx);
526 * libwebsocket_service() - Service any pending websocket activity
527 * @this: Websocket context
528 * @timeout_ms: Timeout for poll; 0 means return immediately if nothing needed
529 * service otherwise block and service immediately, returning
530 * after the timeout if nothing needed service.
532 * This function deals with any pending websocket traffic, for three
533 * kinds of event. It handles these events on both server and client
534 * types of connection the same.
536 * 1) Accept new connections to our context's server
538 * 2) Perform pending broadcast writes initiated from other forked
539 * processes (effectively serializing asynchronous broadcasts)
541 * 3) Call the receive callback for incoming frame data received by
542 * server or client connections.
544 * You need to call this service function periodically to all the above
545 * functions to happen; if your application is single-threaded you can
546 * just call it in your main event loop.
548 * Alternatively you can fork a new process that asynchronously handles
549 * calling this service in a loop. In that case you are happy if this
550 * call blocks your thread until it needs to take care of something and
551 * would call it with a large nonzero timeout. Your loop then takes no
552 * CPU while there is nothing happening.
554 * If you are calling it in a single-threaded app, you don't want it to
555 * wait around blocking other things in your loop from happening, so you
556 * would call it with a timeout_ms of 0, so it returns immediately if
557 * nothing is pending, or as soon as it services whatever was pending.
562 libwebsocket_service(struct libwebsocket_context *this, int timeout_ms)
566 /* stay dead once we are dead */
571 /* wait for something to need service */
573 n = poll(this->fds, this->fds_count, timeout_ms);
575 if (n < 0 || this->fds[0].revents & (POLLERR | POLLHUP)) {
577 fprintf(stderr, "Listen Socket dead\n");
581 if (n == 0) /* poll timeout */
584 /* handle accept on listening socket? */
586 for (n = 0; n < this->fds_count; n++)
587 if (this->fds[n].revents)
588 libwebsocket_service_fd(this, &this->fds[n]);
594 * libwebsocket_callback_on_writable() - Request a callback when this socket
595 * becomes able to be written to without
598 * This only works for internal poll() management, (ie, calling the libwebsocket
599 * service loop, you will have to make your own arrangements if your poll()
600 * loop is managed externally.
602 * @wsi: Websocket connection instance to get callback for
606 libwebsocket_callback_on_writable(struct libwebsocket *wsi)
608 struct libwebsocket_context *this = wsi->protocol->owning_server;
611 for (n = 0; n < this->fds_count; n++)
612 if (this->fds[n].fd == wsi->sock) {
613 this->fds[n].events |= POLLOUT;
617 fprintf(stderr, "libwebsocket_callback_on_writable "
618 "didn't find socket\n");
623 * libwebsocket_callback_on_writable_all_protocol() - Request a callback for
624 * all connections using the given protocol when it
625 * becomes possible to write to each socket without
628 * This only works for internal poll() management, (ie, calling the libwebsocket
629 * service loop, you will have to make your own arrangements if your poll()
630 * loop is managed externally.
632 * @protocol: Protocol whose connections will get callbacks
636 libwebsocket_callback_on_writable_all_protocol(
637 const struct libwebsocket_protocols *protocol)
639 struct libwebsocket_context *this = protocol->owning_server;
642 struct libwebsocket *wsi;
644 for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
646 for (m = 0; m < this->fd_hashtable[n].length; m++) {
648 wsi = this->fd_hashtable[n].wsi[m];
650 if (wsi->protocol == protocol)
651 libwebsocket_callback_on_writable(wsi);
660 * libwebsocket_get_socket_fd() - returns the socket file descriptor
662 * You will not need this unless you are doing something special
664 * @wsi: Websocket connection instance
668 libwebsocket_get_socket_fd(struct libwebsocket *wsi)
674 * libwebsocket_rx_flow_control() - Enable and disable socket servicing for
677 * If the output side of a server process becomes choked, this allows flow
678 * control for the input side.
680 * This only works for internal poll() management, (ie, calling the libwebsocket
681 * service loop, you will have to make your own arrangements if your poll()
682 * loop is managed externally.
684 * @wsi: Websocket connection instance to get callback for
685 * @enable: 0 = disable read servicing for this connection, 1 = enable
689 libwebsocket_rx_flow_control(struct libwebsocket *wsi, int enable)
691 struct libwebsocket_context *this = wsi->protocol->owning_server;
694 for (n = 0; n < this->fds_count; n++)
695 if (this->fds[n].fd == wsi->sock) {
697 this->fds[n].events |= POLLIN;
699 this->fds[n].events &= ~POLLIN;
704 fprintf(stderr, "libwebsocket_callback_on_writable "
705 "unable to find socket\n");
710 * libwebsocket_canonical_hostname() - returns this host's hostname
712 * This is typically used by client code to fill in the host parameter
713 * when making a client connection. You can only call it after the context
716 * @this: Websocket context
721 libwebsocket_canonical_hostname(struct libwebsocket_context *this)
723 return (const char *)this->canonical_hostname;
727 static void sigpipe_handler(int x)
734 * libwebsocket_create_context() - Create the websocket handler
735 * @port: Port to listen on... you can use 0 to suppress listening on
736 * any port, that's what you want if you are not running a
737 * websocket server at all but just using it as a client
738 * @protocols: Array of structures listing supported protocols and a protocol-
739 * specific callback for each one. The list is ended with an
740 * entry that has a NULL callback pointer.
741 * It's not const because we write the owning_server member
742 * @ssl_cert_filepath: If libwebsockets was compiled to use ssl, and you want
743 * to listen using SSL, set to the filepath to fetch the
744 * server cert from, otherwise NULL for unencrypted
745 * @ssl_private_key_filepath: filepath to private key if wanting SSL mode,
747 * @gid: group id to change to after setting listen socket, or -1.
748 * @uid: user id to change to after setting listen socket, or -1.
749 * @options: 0, or LWS_SERVER_OPTION_DEFEAT_CLIENT_MASK
751 * This function creates the listening socket and takes care
752 * of all initialization in one step.
754 * After initialization, it returns a struct libwebsocket_context * that
755 * represents this server. After calling, user code needs to take care
756 * of calling libwebsocket_service() with the context pointer to get the
757 * server's sockets serviced. This can be done in the same process context
758 * or a forked process, or another thread,
760 * The protocol callback functions are called for a handful of events
761 * including http requests coming in, websocket connections becoming
762 * established, and data arriving; it's also called periodically to allow
763 * async transmission.
765 * HTTP requests are sent always to the FIRST protocol in @protocol, since
766 * at that time websocket protocol has not been negotiated. Other
767 * protocols after the first one never see any HTTP callack activity.
769 * The server created is a simple http server by default; part of the
770 * websocket standard is upgrading this http connection to a websocket one.
772 * This allows the same server to provide files like scripts and favicon /
773 * images or whatever over http and dynamic data over websockets all in
774 * one place; they're all handled in the user callback.
777 struct libwebsocket_context *
778 libwebsocket_create_context(int port,
779 struct libwebsocket_protocols *protocols,
780 const char *ssl_cert_filepath,
781 const char *ssl_private_key_filepath,
782 int gid, int uid, unsigned int options)
787 struct sockaddr_in serv_addr, cli_addr;
789 struct libwebsocket_context *this = NULL;
794 struct libwebsocket *wsi;
796 #ifdef LWS_OPENSSL_SUPPORT
798 char ssl_err_buf[512];
801 this = malloc(sizeof(struct libwebsocket_context));
803 fprintf(stderr, "No memory for websocket context\n");
806 this->protocols = protocols;
807 this->listen_port = port;
808 this->http_proxy_port = 0;
809 this->http_proxy_address[0] = '\0';
810 this->options = options;
813 this->fd_random = open(SYSTEM_RANDOM_FILEPATH, O_RDONLY);
814 if (this->fd_random < 0) {
815 fprintf(stderr, "Unable to open random device %s %d\n",
816 SYSTEM_RANDOM_FILEPATH, this->fd_random);
820 /* find canonical hostname */
822 hostname[(sizeof hostname) - 1] = '\0';
823 gethostname(hostname, (sizeof hostname) - 1);
824 he = gethostbyname(hostname);
825 strncpy(this->canonical_hostname, he->h_name,
826 sizeof this->canonical_hostname - 1);
827 this->canonical_hostname[sizeof this->canonical_hostname - 1] = '\0';
828 fprintf(stderr, " canonical hostname = '%s'\n",
829 this->canonical_hostname);
831 /* split the proxy ads:port if given */
833 p = getenv("http_proxy");
835 strncpy(this->http_proxy_address, p,
836 sizeof this->http_proxy_address - 1);
837 this->http_proxy_address[
838 sizeof this->http_proxy_address - 1] = '\0';
840 p = strchr(this->http_proxy_address, ':');
842 fprintf(stderr, "http_proxy needs to be ads:port\n");
846 this->http_proxy_port = atoi(p + 1);
848 fprintf(stderr, "Using proxy %s:%u\n",
849 this->http_proxy_address,
850 this->http_proxy_port);
855 #ifdef LWS_OPENSSL_SUPPORT
856 this->use_ssl = ssl_cert_filepath != NULL &&
857 ssl_private_key_filepath != NULL;
859 fprintf(stderr, " Compiled with SSL support, "
862 fprintf(stderr, " Compiled with SSL support, "
866 if (ssl_cert_filepath != NULL &&
867 ssl_private_key_filepath != NULL) {
868 fprintf(stderr, " Not compiled for OpenSSl support!\n");
871 fprintf(stderr, " Compiled without SSL support, "
872 "serving unencrypted\n");
878 signal(SIGPIPE, sigpipe_handler);
881 #ifdef LWS_OPENSSL_SUPPORT
883 /* basic openssl init */
887 OpenSSL_add_all_algorithms();
888 SSL_load_error_strings();
891 * Firefox insists on SSLv23 not SSLv3
892 * Konq disables SSLv2 by default now, SSLv23 works
895 method = (SSL_METHOD *)SSLv23_server_method();
897 fprintf(stderr, "problem creating ssl method: %s\n",
898 ERR_error_string(ERR_get_error(), ssl_err_buf));
901 this->ssl_ctx = SSL_CTX_new(method); /* create context */
902 if (!this->ssl_ctx) {
903 fprintf(stderr, "problem creating ssl context: %s\n",
904 ERR_error_string(ERR_get_error(), ssl_err_buf));
910 method = (SSL_METHOD *)SSLv23_client_method();
912 fprintf(stderr, "problem creating ssl method: %s\n",
913 ERR_error_string(ERR_get_error(), ssl_err_buf));
916 this->ssl_client_ctx = SSL_CTX_new(method); /* create context */
917 if (!this->ssl_client_ctx) {
918 fprintf(stderr, "problem creating ssl context: %s\n",
919 ERR_error_string(ERR_get_error(), ssl_err_buf));
924 /* openssl init for cert verification (used with client sockets) */
926 if (!SSL_CTX_load_verify_locations(this->ssl_client_ctx, NULL,
927 LWS_OPENSSL_CLIENT_CERTS)) {
928 fprintf(stderr, "Unable to load SSL Client certs from %s "
929 "(set by --with-client-cert-dir= in configure) -- "
930 " client ssl isn't going to work",
931 LWS_OPENSSL_CLIENT_CERTS);
936 /* openssl init for server sockets */
938 /* set the local certificate from CertFile */
939 n = SSL_CTX_use_certificate_file(this->ssl_ctx,
940 ssl_cert_filepath, SSL_FILETYPE_PEM);
942 fprintf(stderr, "problem getting cert '%s': %s\n",
944 ERR_error_string(ERR_get_error(), ssl_err_buf));
947 /* set the private key from KeyFile */
948 if (SSL_CTX_use_PrivateKey_file(this->ssl_ctx,
949 ssl_private_key_filepath,
950 SSL_FILETYPE_PEM) != 1) {
951 fprintf(stderr, "ssl problem getting key '%s': %s\n",
952 ssl_private_key_filepath,
953 ERR_error_string(ERR_get_error(), ssl_err_buf));
956 /* verify private key */
957 if (!SSL_CTX_check_private_key(this->ssl_ctx)) {
958 fprintf(stderr, "Private SSL key doesn't match cert\n");
962 /* SSL is happy and has a cert it's content with */
968 if (lws_b64_selftest())
971 /* fd hashtable init */
973 for (n = 0; n < FD_HASHTABLE_MODULUS; n++)
974 this->fd_hashtable[n].length = 0;
976 /* set up our external listening socket we serve on */
980 sockfd = socket(AF_INET, SOCK_STREAM, 0);
982 fprintf(stderr, "ERROR opening socket");
986 /* allow us to restart even if old sockets in TIME_WAIT */
987 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
989 bzero((char *) &serv_addr, sizeof(serv_addr));
990 serv_addr.sin_family = AF_INET;
991 serv_addr.sin_addr.s_addr = INADDR_ANY;
992 serv_addr.sin_port = htons(port);
994 n = bind(sockfd, (struct sockaddr *) &serv_addr,
997 fprintf(stderr, "ERROR on binding to port %d (%d %d)\n",
1002 wsi = malloc(sizeof(struct libwebsocket));
1003 memset(wsi, 0, sizeof (struct libwebsocket));
1005 wsi->mode = LWS_CONNMODE_SERVER_LISTENER;
1006 insert_wsi(this, wsi);
1009 fprintf(stderr, " Listening on port %d\n", port);
1011 /* list in the internal poll array */
1013 this->fds[this->fds_count].fd = sockfd;
1014 this->fds[this->fds_count++].events = POLLIN;
1017 /* drop any root privs for this process */
1021 fprintf(stderr, "setgid: %s\n", strerror(errno));
1024 fprintf(stderr, "setuid: %s\n", strerror(errno));
1027 /* set up our internal broadcast trigger sockets per-protocol */
1029 for (this->count_protocols = 0;
1030 protocols[this->count_protocols].callback;
1031 this->count_protocols++) {
1032 protocols[this->count_protocols].owning_server = this;
1033 protocols[this->count_protocols].protocol_index =
1034 this->count_protocols;
1036 fd = socket(AF_INET, SOCK_STREAM, 0);
1038 fprintf(stderr, "ERROR opening socket");
1042 /* allow us to restart even if old sockets in TIME_WAIT */
1043 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
1045 bzero((char *) &serv_addr, sizeof(serv_addr));
1046 serv_addr.sin_family = AF_INET;
1047 serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
1048 serv_addr.sin_port = 0; /* pick the port for us */
1050 n = bind(fd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));
1052 fprintf(stderr, "ERROR on binding to port %d (%d %d)\n",
1057 slen = sizeof cli_addr;
1058 n = getsockname(fd, (struct sockaddr *)&cli_addr, &slen);
1060 fprintf(stderr, "getsockname failed\n");
1063 protocols[this->count_protocols].broadcast_socket_port =
1064 ntohs(cli_addr.sin_port);
1067 debug(" Protocol %s broadcast socket %d\n",
1068 protocols[this->count_protocols].name,
1069 ntohs(cli_addr.sin_port));
1071 /* dummy wsi per broadcast proxy socket */
1073 wsi = malloc(sizeof(struct libwebsocket));
1074 memset(wsi, 0, sizeof (struct libwebsocket));
1076 wsi->mode = LWS_CONNMODE_BROADCAST_PROXY_LISTENER;
1077 /* note which protocol we are proxying */
1078 wsi->protocol_index_for_broadcast_proxy = this->count_protocols;
1079 insert_wsi(this, wsi);
1081 /* list in internal poll array */
1083 this->fds[this->fds_count].fd = fd;
1084 this->fds[this->fds_count].events = POLLIN;
1095 * libwebsockets_fork_service_loop() - Optional helper function forks off
1096 * a process for the websocket server loop.
1097 * You don't have to use this but if not, you
1098 * have to make sure you are calling
1099 * libwebsocket_service periodically to service
1100 * the websocket traffic
1101 * @this: server context returned by creation function
1105 libwebsockets_fork_service_loop(struct libwebsocket_context *this)
1109 struct sockaddr_in cli_addr;
1118 /* main process context */
1120 for (client = 1; client < this->count_protocols + 1; client++) {
1121 fd = socket(AF_INET, SOCK_STREAM, 0);
1123 fprintf(stderr, "Unable to create socket\n");
1126 cli_addr.sin_family = AF_INET;
1127 cli_addr.sin_port = htons(
1128 this->protocols[client - 1].broadcast_socket_port);
1129 cli_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
1130 n = connect(fd, (struct sockaddr *)&cli_addr,
1133 fprintf(stderr, "Unable to connect to "
1134 "broadcast socket %d, %s\n",
1135 client, strerror(errno));
1139 this->protocols[client - 1].broadcast_socket_user_fd =
1147 /* we want a SIGHUP when our parent goes down */
1148 prctl(PR_SET_PDEATHSIG, SIGHUP);
1150 /* in this forked process, sit and service websocket connections */
1153 if (libwebsocket_service(this, 1000))
1162 * libwebsockets_get_protocol() - Returns a protocol pointer from a websocket
1164 * @wsi: pointer to struct websocket you want to know the protocol of
1167 * This is useful to get the protocol to broadcast back to from inside
1171 const struct libwebsocket_protocols *
1172 libwebsockets_get_protocol(struct libwebsocket *wsi)
1174 return wsi->protocol;
1178 * libwebsockets_broadcast() - Sends a buffer to the callback for all active
1179 * connections of the given protocol.
1180 * @protocol: pointer to the protocol you will broadcast to all members of
1181 * @buf: buffer containing the data to be broadcase. NOTE: this has to be
1182 * allocated with LWS_SEND_BUFFER_PRE_PADDING valid bytes before
1183 * the pointer and LWS_SEND_BUFFER_POST_PADDING afterwards in the
1184 * case you are calling this function from callback context.
1185 * @len: length of payload data in buf, starting from buf.
1187 * This function allows bulk sending of a packet to every connection using
1188 * the given protocol. It does not send the data directly; instead it calls
1189 * the callback with a reason type of LWS_CALLBACK_BROADCAST. If the callback
1190 * wants to actually send the data for that connection, the callback itself
1191 * should call libwebsocket_write().
1193 * libwebsockets_broadcast() can be called from another fork context without
1194 * having to take any care about data visibility between the processes, it'll
1200 libwebsockets_broadcast(const struct libwebsocket_protocols *protocol,
1201 unsigned char *buf, size_t len)
1203 struct libwebsocket_context *this = protocol->owning_server;
1206 struct libwebsocket * wsi;
1208 if (!protocol->broadcast_socket_user_fd) {
1210 * We are either running unforked / flat, or we are being
1211 * called from poll thread context
1212 * eg, from a callback. In that case don't use sockets for
1213 * broadcast IPC (since we can't open a socket connection to
1214 * a socket listening on our own thread) but directly do the
1217 * Locking is not needed because we are by definition being
1218 * called in the poll thread context and are serialized.
1221 for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
1223 for (m = 0; m < this->fd_hashtable[n].length; m++) {
1225 wsi = this->fd_hashtable[n].wsi[m];
1227 if (wsi->mode != LWS_CONNMODE_WS_SERVING)
1231 * never broadcast to
1232 * non-established connections
1234 if (wsi->state != WSI_STATE_ESTABLISHED)
1237 /* only broadcast to guys using
1238 * requested protocol
1240 if (wsi->protocol != protocol)
1243 wsi->protocol->callback(wsi,
1244 LWS_CALLBACK_BROADCAST,
1254 * We're being called from a different process context than the server
1255 * loop. Instead of broadcasting directly, we send our
1256 * payload on a socket to do the IPC; the server process will serialize
1257 * the broadcast action in its main poll() loop.
1259 * There's one broadcast socket listening for each protocol supported
1260 * set up when the websocket server initializes
1263 n = send(protocol->broadcast_socket_user_fd, buf, len, MSG_NOSIGNAL);