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);
138 * libwebsocket_service_fd() - Service polled socket with something waiting
139 * @this: Websocket context
140 * @pollfd: The pollfd entry describing the socket fd and which events
143 * This function closes any active connections and then frees the
144 * context. After calling this, any further use of the context is
149 libwebsocket_service_fd(struct libwebsocket_context *this,
150 struct pollfd *pollfd)
152 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + MAX_BROADCAST_PAYLOAD +
153 LWS_SEND_BUFFER_POST_PADDING];
154 struct libwebsocket *wsi = wsi_from_fd(this, pollfd->fd);
155 struct libwebsocket *new_wsi;
161 struct sockaddr_in cli_addr;
167 case LWS_CONNMODE_SERVER_LISTENER:
169 /* pollin means a client has connected to us then */
171 if (!pollfd->revents & POLLIN)
174 /* listen socket got an unencrypted connection... */
176 clilen = sizeof(cli_addr);
177 accept_fd = accept(pollfd->fd, (struct sockaddr *)&cli_addr,
180 fprintf(stderr, "ERROR on accept");
184 if (this->fds_count >= MAX_CLIENTS) {
185 fprintf(stderr, "too busy");
190 /* accepting connection to main listener */
192 new_wsi = malloc(sizeof(struct libwebsocket));
193 if (new_wsi == NULL) {
194 fprintf(stderr, "Out of memory for new connection\n");
198 memset(new_wsi, 0, sizeof (struct libwebsocket));
199 new_wsi->sock = accept_fd;
201 #ifdef LWS_OPENSSL_SUPPORT
203 this->ssl_ctx = NULL;
207 new_wsi->ssl = SSL_new(this->ssl_ctx);
208 if (new_wsi->ssl == NULL) {
209 fprintf(stderr, "SSL_new failed: %s\n",
210 ERR_error_string(SSL_get_error(
211 new_wsi->ssl, 0), NULL));
216 SSL_set_fd(new_wsi->ssl, accept_fd);
218 n = SSL_accept(new_wsi->ssl);
221 * browsers seem to probe with various
222 * ssl params which fail then retry
225 debug("SSL_accept failed skt %u: %s\n",
227 ERR_error_string(SSL_get_error(
228 new_wsi->ssl, n), NULL));
234 debug("accepted new SSL conn "
235 "port %u on fd=%d SSL ver %s\n",
236 ntohs(cli_addr.sin_port), accept_fd,
237 SSL_get_version(new_wsi->ssl));
241 debug("accepted new conn port %u on fd=%d\n",
242 ntohs(cli_addr.sin_port), accept_fd);
244 /* intialize the instance struct */
246 new_wsi->state = WSI_STATE_HTTP;
247 new_wsi->name_buffer_pos = 0;
248 new_wsi->mode = LWS_CONNMODE_WS_SERVING;
250 for (n = 0; n < WSI_TOKEN_COUNT; n++) {
251 new_wsi->utf8_token[n].token = NULL;
252 new_wsi->utf8_token[n].token_len = 0;
256 * these can only be set once the protocol is known
257 * we set an unestablished connection's protocol pointer
258 * to the start of the supported list, so it can look
259 * for matching ones during the handshake
261 new_wsi->protocol = this->protocols;
262 new_wsi->user_space = NULL;
265 * Default protocol is 76 / 00
266 * After 76, there's a header specified to inform which
267 * draft the client wants, when that's seen we modify
268 * the individual connection's spec revision accordingly
270 new_wsi->ietf_spec_revision = 0;
272 insert_wsi(this, new_wsi);
276 * make sure NO events are seen yet on this new socket
277 * (otherwise we inherit old fds[client].revents from
278 * previous socket there and die mysteriously! )
280 this->fds[this->fds_count].revents = 0;
282 this->fds[this->fds_count].events = POLLIN;
283 this->fds[this->fds_count++].fd = accept_fd;
287 case LWS_CONNMODE_BROADCAST_PROXY_LISTENER:
289 /* as we are listening, POLLIN means accept() is needed */
291 if (!pollfd->revents & POLLIN)
294 /* listen socket got an unencrypted connection... */
296 clilen = sizeof(cli_addr);
297 accept_fd = accept(pollfd->fd, (struct sockaddr *)&cli_addr,
300 fprintf(stderr, "ERROR on accept");
304 if (this->fds_count >= MAX_CLIENTS) {
305 fprintf(stderr, "too busy");
310 /* create a dummy wsi for the connection and add it */
312 new_wsi = malloc(sizeof(struct libwebsocket));
313 memset(new_wsi, 0, sizeof (struct libwebsocket));
314 new_wsi->sock = accept_fd;
315 new_wsi->mode = LWS_CONNMODE_BROADCAST_PROXY;
316 new_wsi->state = WSI_STATE_ESTABLISHED;
317 /* note which protocol we are proxying */
318 new_wsi->protocol_index_for_broadcast_proxy =
319 wsi->protocol_index_for_broadcast_proxy;
320 insert_wsi(this, new_wsi);
322 /* add connected socket to internal poll array */
324 this->fds[this->fds_count].revents = 0;
325 this->fds[this->fds_count].events = POLLIN;
326 this->fds[this->fds_count++].fd = accept_fd;
330 case LWS_CONNMODE_BROADCAST_PROXY:
332 /* handle session socket closed */
334 if (pollfd->revents & (POLLERR | POLLHUP)) {
336 debug("Session Socket %p (fd=%d) dead\n",
337 (void *)wsi, accept_fd);
339 libwebsocket_close_and_free_session(wsi);
343 /* the guy requested a callback when it was OK to write */
345 if (pollfd->revents & POLLOUT) {
349 pollfd->events &= ~POLLOUT;
351 wsi->protocol->callback(wsi,
352 LWS_CALLBACK_CLIENT_WRITEABLE,
357 /* any incoming data ready? */
359 if (!(pollfd->revents & POLLIN))
362 /* get the issued broadcast payload from the socket */
364 len = read(pollfd->fd, buf + LWS_SEND_BUFFER_PRE_PADDING,
365 MAX_BROADCAST_PAYLOAD);
367 fprintf(stderr, "Error reading broadcast payload\n");
371 /* broadcast it to all guys with this protocol index */
373 for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
375 for (m = 0; m < this->fd_hashtable[n].length; m++) {
377 new_wsi = this->fd_hashtable[n].wsi[m];
379 /* only to clients we are serving to */
381 if (new_wsi->mode != LWS_CONNMODE_WS_SERVING)
385 * never broadcast to non-established
389 if (new_wsi->state != WSI_STATE_ESTABLISHED)
393 * only broadcast to connections using
394 * the requested protocol
397 if (new_wsi->protocol->protocol_index !=
398 wsi->protocol_index_for_broadcast_proxy)
401 /* broadcast it to this connection */
403 new_wsi->protocol->callback(new_wsi,
404 LWS_CALLBACK_BROADCAST,
406 buf + LWS_SEND_BUFFER_PRE_PADDING, len);
411 case LWS_CONNMODE_WS_SERVING:
412 case LWS_CONNMODE_WS_CLIENT:
414 /* handle session socket closed */
416 if (pollfd->revents & (POLLERR | POLLHUP)) {
418 debug("Session Socket %p (fd=%d) dead\n",
419 (void *)wsi, pollfd->fd);
421 libwebsocket_close_and_free_session(wsi);
425 /* the guy requested a callback when it was OK to write */
427 if (pollfd->revents & POLLOUT) {
429 pollfd->events &= ~POLLOUT;
431 wsi->protocol->callback(wsi,
432 LWS_CALLBACK_CLIENT_WRITEABLE,
437 /* any incoming data ready? */
439 if (!(pollfd->revents & POLLIN))
442 #ifdef LWS_OPENSSL_SUPPORT
444 n = SSL_read(wsi->ssl, buf, sizeof buf);
447 n = recv(pollfd->fd, buf, sizeof buf, 0);
450 fprintf(stderr, "Socket read returned %d\n", n);
454 libwebsocket_close_and_free_session(wsi);
458 /* service incoming data */
460 n = libwebsocket_read(wsi, buf, n);
464 * it closed and nuked wsi[client], so remove the
465 * socket handle and wsi from our service list
469 debug("nuking wsi %p, fsd_count = %d\n",
470 (void *)wsi, this->fds_count - 1);
472 delete_from_fd(this, pollfd->fd);
475 for (n = 0; n < this->fds_count; n++)
476 if (this->fds[n].fd == pollfd->fd) {
477 while (n < this->fds_count) {
478 this->fds[n] = this->fds[n + 1];
492 * libwebsocket_context_destroy() - Destroy the websocket context
493 * @this: Websocket context
495 * This function closes any active connections and then frees the
496 * context. After calling this, any further use of the context is
500 libwebsocket_context_destroy(struct libwebsocket_context *this)
504 struct libwebsocket *wsi;
506 for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
508 for (m = 0; m < this->fd_hashtable[n].length; m++) {
510 wsi = this->fd_hashtable[n].wsi[m];
513 case LWS_CONNMODE_WS_SERVING:
514 libwebsocket_close_and_free_session(wsi);
516 case LWS_CONNMODE_WS_CLIENT:
517 libwebsocket_client_close(wsi);
525 close(this->fd_random);
527 #ifdef LWS_OPENSSL_SUPPORT
529 SSL_CTX_free(this->ssl_ctx);
530 if (this->ssl_client_ctx)
531 SSL_CTX_free(this->ssl_client_ctx);
538 * libwebsocket_service() - Service any pending websocket activity
539 * @this: Websocket context
540 * @timeout_ms: Timeout for poll; 0 means return immediately if nothing needed
541 * service otherwise block and service immediately, returning
542 * after the timeout if nothing needed service.
544 * This function deals with any pending websocket traffic, for three
545 * kinds of event. It handles these events on both server and client
546 * types of connection the same.
548 * 1) Accept new connections to our context's server
550 * 2) Perform pending broadcast writes initiated from other forked
551 * processes (effectively serializing asynchronous broadcasts)
553 * 3) Call the receive callback for incoming frame data received by
554 * server or client connections.
556 * You need to call this service function periodically to all the above
557 * functions to happen; if your application is single-threaded you can
558 * just call it in your main event loop.
560 * Alternatively you can fork a new process that asynchronously handles
561 * calling this service in a loop. In that case you are happy if this
562 * call blocks your thread until it needs to take care of something and
563 * would call it with a large nonzero timeout. Your loop then takes no
564 * CPU while there is nothing happening.
566 * If you are calling it in a single-threaded app, you don't want it to
567 * wait around blocking other things in your loop from happening, so you
568 * would call it with a timeout_ms of 0, so it returns immediately if
569 * nothing is pending, or as soon as it services whatever was pending.
574 libwebsocket_service(struct libwebsocket_context *this, int timeout_ms)
578 /* stay dead once we are dead */
583 /* wait for something to need service */
585 n = poll(this->fds, this->fds_count, timeout_ms);
587 if (n < 0 || this->fds[0].revents & (POLLERR | POLLHUP)) {
589 fprintf(stderr, "Listen Socket dead\n");
593 if (n == 0) /* poll timeout */
596 /* handle accept on listening socket? */
598 for (n = 0; n < this->fds_count; n++)
599 if (this->fds[n].revents)
600 libwebsocket_service_fd(this, &this->fds[n]);
606 * libwebsocket_callback_on_writable() - Request a callback when this socket
607 * becomes able to be written to without
610 * This only works for internal poll() management, (ie, calling the libwebsocket
611 * service loop, you will have to make your own arrangements if your poll()
612 * loop is managed externally.
614 * @wsi: Websocket connection instance to get callback for
618 libwebsocket_callback_on_writable(struct libwebsocket *wsi)
620 struct libwebsocket_context *this = wsi->protocol->owning_server;
623 for (n = 0; n < this->fds_count; n++)
624 if (this->fds[n].fd == wsi->sock) {
625 this->fds[n].events |= POLLOUT;
629 fprintf(stderr, "libwebsocket_callback_on_writable "
630 "didn't find socket\n");
635 * libwebsocket_callback_on_writable_all_protocol() - Request a callback for
636 * all connections using the given protocol when it
637 * becomes possible to write to each socket without
640 * This only works for internal poll() management, (ie, calling the libwebsocket
641 * service loop, you will have to make your own arrangements if your poll()
642 * loop is managed externally.
644 * @protocol: Protocol whose connections will get callbacks
648 libwebsocket_callback_on_writable_all_protocol(
649 const struct libwebsocket_protocols *protocol)
651 struct libwebsocket_context *this = protocol->owning_server;
654 struct libwebsocket *wsi;
656 for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
658 for (m = 0; m < this->fd_hashtable[n].length; m++) {
660 wsi = this->fd_hashtable[n].wsi[m];
662 if (wsi->protocol == protocol)
663 libwebsocket_callback_on_writable(wsi);
672 * libwebsocket_get_socket_fd() - returns the socket file descriptor
674 * You will not need this unless you are doing something special
676 * @wsi: Websocket connection instance
680 libwebsocket_get_socket_fd(struct libwebsocket *wsi)
686 * libwebsocket_rx_flow_control() - Enable and disable socket servicing for
689 * If the output side of a server process becomes choked, this allows flow
690 * control for the input side.
692 * This only works for internal poll() management, (ie, calling the libwebsocket
693 * service loop, you will have to make your own arrangements if your poll()
694 * loop is managed externally.
696 * @wsi: Websocket connection instance to get callback for
697 * @enable: 0 = disable read servicing for this connection, 1 = enable
701 libwebsocket_rx_flow_control(struct libwebsocket *wsi, int enable)
703 struct libwebsocket_context *this = wsi->protocol->owning_server;
706 for (n = 0; n < this->fds_count; n++)
707 if (this->fds[n].fd == wsi->sock) {
709 this->fds[n].events |= POLLIN;
711 this->fds[n].events &= ~POLLIN;
716 fprintf(stderr, "libwebsocket_callback_on_writable "
717 "unable to find socket\n");
722 * libwebsocket_canonical_hostname() - returns this host's hostname
724 * This is typically used by client code to fill in the host parameter
725 * when making a client connection. You can only call it after the context
728 * @this: Websocket context
733 libwebsocket_canonical_hostname(struct libwebsocket_context *this)
735 return (const char *)this->canonical_hostname;
739 static void sigpipe_handler(int x)
746 * libwebsocket_create_context() - Create the websocket handler
747 * @port: Port to listen on... you can use 0 to suppress listening on
748 * any port, that's what you want if you are not running a
749 * websocket server at all but just using it as a client
750 * @protocols: Array of structures listing supported protocols and a protocol-
751 * specific callback for each one. The list is ended with an
752 * entry that has a NULL callback pointer.
753 * It's not const because we write the owning_server member
754 * @ssl_cert_filepath: If libwebsockets was compiled to use ssl, and you want
755 * to listen using SSL, set to the filepath to fetch the
756 * server cert from, otherwise NULL for unencrypted
757 * @ssl_private_key_filepath: filepath to private key if wanting SSL mode,
759 * @gid: group id to change to after setting listen socket, or -1.
760 * @uid: user id to change to after setting listen socket, or -1.
761 * @options: 0, or LWS_SERVER_OPTION_DEFEAT_CLIENT_MASK
763 * This function creates the listening socket and takes care
764 * of all initialization in one step.
766 * After initialization, it returns a struct libwebsocket_context * that
767 * represents this server. After calling, user code needs to take care
768 * of calling libwebsocket_service() with the context pointer to get the
769 * server's sockets serviced. This can be done in the same process context
770 * or a forked process, or another thread,
772 * The protocol callback functions are called for a handful of events
773 * including http requests coming in, websocket connections becoming
774 * established, and data arriving; it's also called periodically to allow
775 * async transmission.
777 * HTTP requests are sent always to the FIRST protocol in @protocol, since
778 * at that time websocket protocol has not been negotiated. Other
779 * protocols after the first one never see any HTTP callack activity.
781 * The server created is a simple http server by default; part of the
782 * websocket standard is upgrading this http connection to a websocket one.
784 * This allows the same server to provide files like scripts and favicon /
785 * images or whatever over http and dynamic data over websockets all in
786 * one place; they're all handled in the user callback.
789 struct libwebsocket_context *
790 libwebsocket_create_context(int port,
791 struct libwebsocket_protocols *protocols,
792 const char *ssl_cert_filepath,
793 const char *ssl_private_key_filepath,
794 int gid, int uid, unsigned int options)
799 struct sockaddr_in serv_addr, cli_addr;
801 struct libwebsocket_context *this = NULL;
806 struct libwebsocket *wsi;
808 #ifdef LWS_OPENSSL_SUPPORT
810 char ssl_err_buf[512];
813 this = malloc(sizeof(struct libwebsocket_context));
815 fprintf(stderr, "No memory for websocket context\n");
818 this->protocols = protocols;
819 this->listen_port = port;
820 this->http_proxy_port = 0;
821 this->http_proxy_address[0] = '\0';
822 this->options = options;
825 this->fd_random = open(SYSTEM_RANDOM_FILEPATH, O_RDONLY);
826 if (this->fd_random < 0) {
827 fprintf(stderr, "Unable to open random device %s %d\n",
828 SYSTEM_RANDOM_FILEPATH, this->fd_random);
832 /* find canonical hostname */
834 hostname[(sizeof hostname) - 1] = '\0';
835 gethostname(hostname, (sizeof hostname) - 1);
836 he = gethostbyname(hostname);
837 strncpy(this->canonical_hostname, he->h_name,
838 sizeof this->canonical_hostname - 1);
839 this->canonical_hostname[sizeof this->canonical_hostname - 1] = '\0';
840 fprintf(stderr, " canonical hostname = '%s'\n",
841 this->canonical_hostname);
843 /* split the proxy ads:port if given */
845 p = getenv("http_proxy");
847 strncpy(this->http_proxy_address, p,
848 sizeof this->http_proxy_address - 1);
849 this->http_proxy_address[
850 sizeof this->http_proxy_address - 1] = '\0';
852 p = strchr(this->http_proxy_address, ':');
854 fprintf(stderr, "http_proxy needs to be ads:port\n");
858 this->http_proxy_port = atoi(p + 1);
860 fprintf(stderr, "Using proxy %s:%u\n",
861 this->http_proxy_address,
862 this->http_proxy_port);
867 #ifdef LWS_OPENSSL_SUPPORT
868 this->use_ssl = ssl_cert_filepath != NULL &&
869 ssl_private_key_filepath != NULL;
871 fprintf(stderr, " Compiled with SSL support, "
874 fprintf(stderr, " Compiled with SSL support, "
878 if (ssl_cert_filepath != NULL &&
879 ssl_private_key_filepath != NULL) {
880 fprintf(stderr, " Not compiled for OpenSSl support!\n");
883 fprintf(stderr, " Compiled without SSL support, "
884 "serving unencrypted\n");
890 signal(SIGPIPE, sigpipe_handler);
893 #ifdef LWS_OPENSSL_SUPPORT
895 /* basic openssl init */
899 OpenSSL_add_all_algorithms();
900 SSL_load_error_strings();
903 * Firefox insists on SSLv23 not SSLv3
904 * Konq disables SSLv2 by default now, SSLv23 works
907 method = (SSL_METHOD *)SSLv23_server_method();
909 fprintf(stderr, "problem creating ssl method: %s\n",
910 ERR_error_string(ERR_get_error(), ssl_err_buf));
913 this->ssl_ctx = SSL_CTX_new(method); /* create context */
914 if (!this->ssl_ctx) {
915 fprintf(stderr, "problem creating ssl context: %s\n",
916 ERR_error_string(ERR_get_error(), ssl_err_buf));
922 method = (SSL_METHOD *)SSLv23_client_method();
924 fprintf(stderr, "problem creating ssl method: %s\n",
925 ERR_error_string(ERR_get_error(), ssl_err_buf));
928 this->ssl_client_ctx = SSL_CTX_new(method); /* create context */
929 if (!this->ssl_client_ctx) {
930 fprintf(stderr, "problem creating ssl context: %s\n",
931 ERR_error_string(ERR_get_error(), ssl_err_buf));
936 /* openssl init for cert verification (used with client sockets) */
938 if (!SSL_CTX_load_verify_locations(this->ssl_client_ctx, NULL,
939 LWS_OPENSSL_CLIENT_CERTS)) {
940 fprintf(stderr, "Unable to load SSL Client certs from %s "
941 "(set by --with-client-cert-dir= in configure) -- "
942 " client ssl isn't going to work",
943 LWS_OPENSSL_CLIENT_CERTS);
948 /* openssl init for server sockets */
950 /* set the local certificate from CertFile */
951 n = SSL_CTX_use_certificate_file(this->ssl_ctx,
952 ssl_cert_filepath, SSL_FILETYPE_PEM);
954 fprintf(stderr, "problem getting cert '%s': %s\n",
956 ERR_error_string(ERR_get_error(), ssl_err_buf));
959 /* set the private key from KeyFile */
960 if (SSL_CTX_use_PrivateKey_file(this->ssl_ctx,
961 ssl_private_key_filepath,
962 SSL_FILETYPE_PEM) != 1) {
963 fprintf(stderr, "ssl problem getting key '%s': %s\n",
964 ssl_private_key_filepath,
965 ERR_error_string(ERR_get_error(), ssl_err_buf));
968 /* verify private key */
969 if (!SSL_CTX_check_private_key(this->ssl_ctx)) {
970 fprintf(stderr, "Private SSL key doesn't match cert\n");
974 /* SSL is happy and has a cert it's content with */
980 if (lws_b64_selftest())
983 /* fd hashtable init */
985 for (n = 0; n < FD_HASHTABLE_MODULUS; n++)
986 this->fd_hashtable[n].length = 0;
988 /* set up our external listening socket we serve on */
992 sockfd = socket(AF_INET, SOCK_STREAM, 0);
994 fprintf(stderr, "ERROR opening socket");
998 /* allow us to restart even if old sockets in TIME_WAIT */
999 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
1001 bzero((char *) &serv_addr, sizeof(serv_addr));
1002 serv_addr.sin_family = AF_INET;
1003 serv_addr.sin_addr.s_addr = INADDR_ANY;
1004 serv_addr.sin_port = htons(port);
1006 n = bind(sockfd, (struct sockaddr *) &serv_addr,
1009 fprintf(stderr, "ERROR on binding to port %d (%d %d)\n",
1014 wsi = malloc(sizeof(struct libwebsocket));
1015 memset(wsi, 0, sizeof (struct libwebsocket));
1017 wsi->mode = LWS_CONNMODE_SERVER_LISTENER;
1018 insert_wsi(this, wsi);
1021 fprintf(stderr, " Listening on port %d\n", port);
1023 /* list in the internal poll array */
1025 this->fds[this->fds_count].fd = sockfd;
1026 this->fds[this->fds_count++].events = POLLIN;
1029 /* drop any root privs for this process */
1033 fprintf(stderr, "setgid: %s\n", strerror(errno));
1036 fprintf(stderr, "setuid: %s\n", strerror(errno));
1039 /* set up our internal broadcast trigger sockets per-protocol */
1041 for (this->count_protocols = 0;
1042 protocols[this->count_protocols].callback;
1043 this->count_protocols++) {
1044 protocols[this->count_protocols].owning_server = this;
1045 protocols[this->count_protocols].protocol_index =
1046 this->count_protocols;
1048 fd = socket(AF_INET, SOCK_STREAM, 0);
1050 fprintf(stderr, "ERROR opening socket");
1054 /* allow us to restart even if old sockets in TIME_WAIT */
1055 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
1057 bzero((char *) &serv_addr, sizeof(serv_addr));
1058 serv_addr.sin_family = AF_INET;
1059 serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
1060 serv_addr.sin_port = 0; /* pick the port for us */
1062 n = bind(fd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));
1064 fprintf(stderr, "ERROR on binding to port %d (%d %d)\n",
1069 slen = sizeof cli_addr;
1070 n = getsockname(fd, (struct sockaddr *)&cli_addr, &slen);
1072 fprintf(stderr, "getsockname failed\n");
1075 protocols[this->count_protocols].broadcast_socket_port =
1076 ntohs(cli_addr.sin_port);
1079 debug(" Protocol %s broadcast socket %d\n",
1080 protocols[this->count_protocols].name,
1081 ntohs(cli_addr.sin_port));
1083 /* dummy wsi per broadcast proxy socket */
1085 wsi = malloc(sizeof(struct libwebsocket));
1086 memset(wsi, 0, sizeof (struct libwebsocket));
1088 wsi->mode = LWS_CONNMODE_BROADCAST_PROXY_LISTENER;
1089 /* note which protocol we are proxying */
1090 wsi->protocol_index_for_broadcast_proxy = this->count_protocols;
1091 insert_wsi(this, wsi);
1093 /* list in internal poll array */
1095 this->fds[this->fds_count].fd = fd;
1096 this->fds[this->fds_count].events = POLLIN;
1107 * libwebsockets_fork_service_loop() - Optional helper function forks off
1108 * a process for the websocket server loop.
1109 * You don't have to use this but if not, you
1110 * have to make sure you are calling
1111 * libwebsocket_service periodically to service
1112 * the websocket traffic
1113 * @this: server context returned by creation function
1117 libwebsockets_fork_service_loop(struct libwebsocket_context *this)
1121 struct sockaddr_in cli_addr;
1130 /* main process context */
1132 for (client = 1; client < this->count_protocols + 1; client++) {
1133 fd = socket(AF_INET, SOCK_STREAM, 0);
1135 fprintf(stderr, "Unable to create socket\n");
1138 cli_addr.sin_family = AF_INET;
1139 cli_addr.sin_port = htons(
1140 this->protocols[client - 1].broadcast_socket_port);
1141 cli_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
1142 n = connect(fd, (struct sockaddr *)&cli_addr,
1145 fprintf(stderr, "Unable to connect to "
1146 "broadcast socket %d, %s\n",
1147 client, strerror(errno));
1151 this->protocols[client - 1].broadcast_socket_user_fd =
1159 /* we want a SIGHUP when our parent goes down */
1160 prctl(PR_SET_PDEATHSIG, SIGHUP);
1162 /* in this forked process, sit and service websocket connections */
1165 if (libwebsocket_service(this, 1000))
1174 * libwebsockets_get_protocol() - Returns a protocol pointer from a websocket
1176 * @wsi: pointer to struct websocket you want to know the protocol of
1179 * This is useful to get the protocol to broadcast back to from inside
1183 const struct libwebsocket_protocols *
1184 libwebsockets_get_protocol(struct libwebsocket *wsi)
1186 return wsi->protocol;
1190 * libwebsockets_broadcast() - Sends a buffer to the callback for all active
1191 * connections of the given protocol.
1192 * @protocol: pointer to the protocol you will broadcast to all members of
1193 * @buf: buffer containing the data to be broadcase. NOTE: this has to be
1194 * allocated with LWS_SEND_BUFFER_PRE_PADDING valid bytes before
1195 * the pointer and LWS_SEND_BUFFER_POST_PADDING afterwards in the
1196 * case you are calling this function from callback context.
1197 * @len: length of payload data in buf, starting from buf.
1199 * This function allows bulk sending of a packet to every connection using
1200 * the given protocol. It does not send the data directly; instead it calls
1201 * the callback with a reason type of LWS_CALLBACK_BROADCAST. If the callback
1202 * wants to actually send the data for that connection, the callback itself
1203 * should call libwebsocket_write().
1205 * libwebsockets_broadcast() can be called from another fork context without
1206 * having to take any care about data visibility between the processes, it'll
1212 libwebsockets_broadcast(const struct libwebsocket_protocols *protocol,
1213 unsigned char *buf, size_t len)
1215 struct libwebsocket_context *this = protocol->owning_server;
1218 struct libwebsocket * wsi;
1220 if (!protocol->broadcast_socket_user_fd) {
1222 * We are either running unforked / flat, or we are being
1223 * called from poll thread context
1224 * eg, from a callback. In that case don't use sockets for
1225 * broadcast IPC (since we can't open a socket connection to
1226 * a socket listening on our own thread) but directly do the
1229 * Locking is not needed because we are by definition being
1230 * called in the poll thread context and are serialized.
1233 for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
1235 for (m = 0; m < this->fd_hashtable[n].length; m++) {
1237 wsi = this->fd_hashtable[n].wsi[m];
1239 if (wsi->mode != LWS_CONNMODE_WS_SERVING)
1243 * never broadcast to
1244 * non-established connections
1246 if (wsi->state != WSI_STATE_ESTABLISHED)
1249 /* only broadcast to guys using
1250 * requested protocol
1252 if (wsi->protocol != protocol)
1255 wsi->protocol->callback(wsi,
1256 LWS_CALLBACK_BROADCAST,
1266 * We're being called from a different process context than the server
1267 * loop. Instead of broadcasting directly, we send our
1268 * payload on a socket to do the IPC; the server process will serialize
1269 * the broadcast action in its main poll() loop.
1271 * There's one broadcast socket listening for each protocol supported
1272 * set up when the websocket server initializes
1275 n = send(protocol->broadcast_socket_user_fd, buf, len, MSG_NOSIGNAL);