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_context *this,
80 struct libwebsocket *wsi)
84 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 2 +
85 LWS_SEND_BUFFER_POST_PADDING];
90 old_state = wsi->state;
92 if (old_state == WSI_STATE_DEAD_SOCKET)
95 /* remove this fd from wsi mapping hashtable */
97 delete_from_fd(this, wsi->sock);
99 /* delete it from the internal poll list if still present */
101 for (n = 0; n < this->fds_count; n++) {
102 if (this->fds[n].fd != wsi->sock)
104 while (n < this->fds_count - 1) {
105 this->fds[n] = this->fds[n + 1];
109 /* we only have to deal with one */
113 /* remove also from external POLL support via protocol 0 */
115 this->protocols[0].callback(this, wsi,
116 LWS_CALLBACK_DEL_POLL_FD, (void *)(long)wsi->sock, NULL, 0);
119 * signal we are closing, libsocket_write will
120 * add any necessary version-specific stuff. If the write fails,
121 * no worries we are closing anyway. If we didn't initiate this
122 * close, then our state has been changed to
123 * WSI_STATE_RETURNED_CLOSE_ALREADY and we will skip this
126 if (old_state == WSI_STATE_ESTABLISHED)
127 libwebsocket_write(wsi, &buf[LWS_SEND_BUFFER_PRE_PADDING], 0,
130 wsi->state = WSI_STATE_DEAD_SOCKET;
132 /* tell the user it's all over for this guy */
134 if (wsi->protocol->callback && old_state == WSI_STATE_ESTABLISHED)
135 wsi->protocol->callback(this, wsi, LWS_CALLBACK_CLOSED,
136 wsi->user_space, NULL, 0);
138 /* free up his allocations */
140 for (n = 0; n < WSI_TOKEN_COUNT; n++)
141 if (wsi->utf8_token[n].token)
142 free(wsi->utf8_token[n].token);
144 /* fprintf(stderr, "closing fd=%d\n", wsi->sock); */
146 #ifdef LWS_OPENSSL_SUPPORT
148 n = SSL_get_fd(wsi->ssl);
149 SSL_shutdown(wsi->ssl);
154 shutdown(wsi->sock, SHUT_RDWR);
156 #ifdef LWS_OPENSSL_SUPPORT
160 free(wsi->user_space);
166 * libwebsockets_hangup_on_client() - Server calls to terminate client
168 * @this: libwebsockets context
169 * @fd: Connection socket descriptor
173 libwebsockets_hangup_on_client(struct libwebsocket_context *this, int fd)
175 struct libwebsocket *wsi = wsi_from_fd(this, fd);
181 delete_from_fd(this, fd);
183 for (n = 0; n < this->fds_count - 1; n++)
184 if (this->fds[n].fd == fd) {
185 while (n < this->fds_count - 1) {
186 this->fds[n] = this->fds[n + 1];
193 libwebsocket_close_and_free_session(this, wsi);
198 * libwebsockets_get_peer_addresses() - Get client address information
199 * @fd: Connection socket descriptor
200 * @name: Buffer to take client address name
201 * @name_len: Length of client address name buffer
202 * @rip: Buffer to take client address IP qotted quad
203 * @rip_len: Length of client address IP buffer
205 * This function fills in @name and @rip with the name and IP of
206 * the client connected with socket descriptor @fd. Names may be
207 * truncated if there is not enough room. If either cannot be
208 * determined, they will be returned as valid zero-length strings.
212 libwebsockets_get_peer_addresses(int fd, char *name, int name_len,
213 char *rip, int rip_len)
216 struct sockaddr_in sin;
217 struct hostent *host;
218 struct hostent *host1;
227 if (getpeername(fd, (struct sockaddr *) &sin, &len) < 0) {
228 perror("getpeername");
232 host = gethostbyaddr((char *) &sin.sin_addr, sizeof sin.sin_addr,
235 perror("gethostbyaddr");
239 strncpy(name, host->h_name, name_len);
240 name[name_len - 1] = '\0';
242 host1 = gethostbyname(host->h_name);
248 p = host1->h_addr_list[n++];
251 if (host1->h_addrtype != AF_INET)
254 sprintf(ip, "%d.%d.%d.%d",
255 p[0], p[1], p[2], p[3]);
257 strncpy(rip, ip, rip_len);
258 rip[rip_len - 1] = '\0';
263 * libwebsocket_service_fd() - Service polled socket with something waiting
264 * @this: Websocket context
265 * @pollfd: The pollfd entry describing the socket fd and which events
268 * This function closes any active connections and then frees the
269 * context. After calling this, any further use of the context is
274 libwebsocket_service_fd(struct libwebsocket_context *this,
275 struct pollfd *pollfd)
277 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + MAX_BROADCAST_PAYLOAD +
278 LWS_SEND_BUFFER_POST_PADDING];
279 struct libwebsocket *wsi = wsi_from_fd(this, pollfd->fd);
280 struct libwebsocket *new_wsi;
286 struct sockaddr_in cli_addr;
292 case LWS_CONNMODE_SERVER_LISTENER:
294 /* pollin means a client has connected to us then */
296 if (!pollfd->revents & POLLIN)
299 /* listen socket got an unencrypted connection... */
301 clilen = sizeof(cli_addr);
302 accept_fd = accept(pollfd->fd, (struct sockaddr *)&cli_addr,
305 fprintf(stderr, "ERROR on accept");
309 if (this->fds_count >= MAX_CLIENTS) {
310 fprintf(stderr, "too busy to accept new client\n");
316 * look at who we connected to and give user code a chance
317 * to reject based on client IP. There's no protocol selected
318 * yet so we issue this to protocols[0]
321 if ((this->protocols[0].callback)(this, wsi,
322 LWS_CALLBACK_FILTER_NETWORK_CONNECTION,
323 (void*)(long)accept_fd, NULL, 0)) {
324 fprintf(stderr, "Callback denied network connection\n");
329 /* accepting connection to main listener */
331 new_wsi = malloc(sizeof(struct libwebsocket));
332 if (new_wsi == NULL) {
333 fprintf(stderr, "Out of memory for new connection\n");
337 memset(new_wsi, 0, sizeof (struct libwebsocket));
338 new_wsi->sock = accept_fd;
340 #ifdef LWS_OPENSSL_SUPPORT
342 this->ssl_ctx = NULL;
346 new_wsi->ssl = SSL_new(this->ssl_ctx);
347 if (new_wsi->ssl == NULL) {
348 fprintf(stderr, "SSL_new failed: %s\n",
349 ERR_error_string(SSL_get_error(
350 new_wsi->ssl, 0), NULL));
355 SSL_set_fd(new_wsi->ssl, accept_fd);
357 n = SSL_accept(new_wsi->ssl);
360 * browsers seem to probe with various
361 * ssl params which fail then retry
364 debug("SSL_accept failed skt %u: %s\n",
366 ERR_error_string(SSL_get_error(
367 new_wsi->ssl, n), NULL));
373 debug("accepted new SSL conn "
374 "port %u on fd=%d SSL ver %s\n",
375 ntohs(cli_addr.sin_port), accept_fd,
376 SSL_get_version(new_wsi->ssl));
380 debug("accepted new conn port %u on fd=%d\n",
381 ntohs(cli_addr.sin_port), accept_fd);
383 /* intialize the instance struct */
385 new_wsi->state = WSI_STATE_HTTP;
386 new_wsi->name_buffer_pos = 0;
387 new_wsi->mode = LWS_CONNMODE_WS_SERVING;
389 for (n = 0; n < WSI_TOKEN_COUNT; n++) {
390 new_wsi->utf8_token[n].token = NULL;
391 new_wsi->utf8_token[n].token_len = 0;
395 * these can only be set once the protocol is known
396 * we set an unestablished connection's protocol pointer
397 * to the start of the supported list, so it can look
398 * for matching ones during the handshake
400 new_wsi->protocol = this->protocols;
401 new_wsi->user_space = NULL;
404 * Default protocol is 76 / 00
405 * After 76, there's a header specified to inform which
406 * draft the client wants, when that's seen we modify
407 * the individual connection's spec revision accordingly
409 new_wsi->ietf_spec_revision = 0;
411 insert_wsi(this, new_wsi);
414 * make sure NO events are seen yet on this new socket
415 * (otherwise we inherit old fds[client].revents from
416 * previous socket there and die mysteriously! )
418 this->fds[this->fds_count].revents = 0;
420 this->fds[this->fds_count].events = POLLIN;
421 this->fds[this->fds_count++].fd = accept_fd;
423 /* external POLL support via protocol 0 */
424 this->protocols[0].callback(this, new_wsi,
425 LWS_CALLBACK_ADD_POLL_FD,
426 (void *)(long)accept_fd, NULL, POLLIN);
430 case LWS_CONNMODE_BROADCAST_PROXY_LISTENER:
432 /* as we are listening, POLLIN means accept() is needed */
434 if (!pollfd->revents & POLLIN)
437 /* listen socket got an unencrypted connection... */
439 clilen = sizeof(cli_addr);
440 accept_fd = accept(pollfd->fd, (struct sockaddr *)&cli_addr,
443 fprintf(stderr, "ERROR on accept");
447 if (this->fds_count >= MAX_CLIENTS) {
448 fprintf(stderr, "too busy to accept new broadcast "
454 /* create a dummy wsi for the connection and add it */
456 new_wsi = malloc(sizeof(struct libwebsocket));
457 memset(new_wsi, 0, sizeof (struct libwebsocket));
458 new_wsi->sock = accept_fd;
459 new_wsi->mode = LWS_CONNMODE_BROADCAST_PROXY;
460 new_wsi->state = WSI_STATE_ESTABLISHED;
461 /* note which protocol we are proxying */
462 new_wsi->protocol_index_for_broadcast_proxy =
463 wsi->protocol_index_for_broadcast_proxy;
464 insert_wsi(this, new_wsi);
466 /* add connected socket to internal poll array */
468 this->fds[this->fds_count].revents = 0;
469 this->fds[this->fds_count].events = POLLIN;
470 this->fds[this->fds_count++].fd = accept_fd;
472 /* external POLL support via protocol 0 */
473 this->protocols[0].callback(this, new_wsi,
474 LWS_CALLBACK_ADD_POLL_FD,
475 (void *)(long)accept_fd, NULL, POLLIN);
479 case LWS_CONNMODE_BROADCAST_PROXY:
481 /* handle session socket closed */
483 if (pollfd->revents & (POLLERR | POLLHUP)) {
485 debug("Session Socket %p (fd=%d) dead\n",
486 (void *)wsi, accept_fd);
488 libwebsocket_close_and_free_session(this, wsi);
492 /* the guy requested a callback when it was OK to write */
494 if (pollfd->revents & POLLOUT) {
498 pollfd->events &= ~POLLOUT;
500 /* external POLL support via protocol 0 */
501 this->protocols[0].callback(this, wsi,
502 LWS_CALLBACK_CLEAR_MODE_POLL_FD,
503 (void *)(long)wsi->sock, NULL, POLLOUT);
505 wsi->protocol->callback(this, wsi,
506 LWS_CALLBACK_CLIENT_WRITEABLE,
511 /* any incoming data ready? */
513 if (!(pollfd->revents & POLLIN))
516 /* get the issued broadcast payload from the socket */
518 len = read(pollfd->fd, buf + LWS_SEND_BUFFER_PRE_PADDING,
519 MAX_BROADCAST_PAYLOAD);
521 fprintf(stderr, "Error reading broadcast payload\n");
525 /* broadcast it to all guys with this protocol index */
527 for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
529 for (m = 0; m < this->fd_hashtable[n].length; m++) {
531 new_wsi = this->fd_hashtable[n].wsi[m];
533 /* only to clients we are serving to */
535 if (new_wsi->mode != LWS_CONNMODE_WS_SERVING)
539 * never broadcast to non-established
543 if (new_wsi->state != WSI_STATE_ESTABLISHED)
547 * only broadcast to connections using
548 * the requested protocol
551 if (new_wsi->protocol->protocol_index !=
552 wsi->protocol_index_for_broadcast_proxy)
555 /* broadcast it to this connection */
557 new_wsi->protocol->callback(this, new_wsi,
558 LWS_CALLBACK_BROADCAST,
560 buf + LWS_SEND_BUFFER_PRE_PADDING, len);
565 case LWS_CONNMODE_WS_SERVING:
566 case LWS_CONNMODE_WS_CLIENT:
568 /* handle session socket closed */
570 if (pollfd->revents & (POLLERR | POLLHUP)) {
572 fprintf(stderr, "Session Socket %p (fd=%d) dead\n",
573 (void *)wsi, pollfd->fd);
575 libwebsocket_close_and_free_session(this, wsi);
579 /* the guy requested a callback when it was OK to write */
581 if (pollfd->revents & POLLOUT) {
583 pollfd->events &= ~POLLOUT;
585 /* external POLL support via protocol 0 */
586 this->protocols[0].callback(this, wsi,
587 LWS_CALLBACK_CLEAR_MODE_POLL_FD,
588 (void *)(long)wsi->sock, NULL, POLLOUT);
590 wsi->protocol->callback(this, wsi,
591 LWS_CALLBACK_CLIENT_WRITEABLE,
596 /* any incoming data ready? */
598 if (!(pollfd->revents & POLLIN))
601 #ifdef LWS_OPENSSL_SUPPORT
603 n = SSL_read(wsi->ssl, buf, sizeof buf);
606 n = recv(pollfd->fd, buf, sizeof buf, 0);
609 fprintf(stderr, "Socket read returned %d\n", n);
613 libwebsocket_close_and_free_session(this, wsi);
617 /* service incoming data */
619 n = libwebsocket_read(this, wsi, buf, n);
633 * libwebsocket_context_destroy() - Destroy the websocket context
634 * @this: Websocket context
636 * This function closes any active connections and then frees the
637 * context. After calling this, any further use of the context is
641 libwebsocket_context_destroy(struct libwebsocket_context *this)
645 struct libwebsocket *wsi;
647 for (n = 0; n < FD_HASHTABLE_MODULUS; n++)
648 for (m = 0; m < this->fd_hashtable[n].length; m++) {
649 wsi = this->fd_hashtable[n].wsi[m];
650 libwebsocket_close_and_free_session(this, wsi);
653 close(this->fd_random);
655 #ifdef LWS_OPENSSL_SUPPORT
657 SSL_CTX_free(this->ssl_ctx);
658 if (this->ssl_client_ctx)
659 SSL_CTX_free(this->ssl_client_ctx);
666 * libwebsocket_service() - Service any pending websocket activity
667 * @this: Websocket context
668 * @timeout_ms: Timeout for poll; 0 means return immediately if nothing needed
669 * service otherwise block and service immediately, returning
670 * after the timeout if nothing needed service.
672 * This function deals with any pending websocket traffic, for three
673 * kinds of event. It handles these events on both server and client
674 * types of connection the same.
676 * 1) Accept new connections to our context's server
678 * 2) Perform pending broadcast writes initiated from other forked
679 * processes (effectively serializing asynchronous broadcasts)
681 * 3) Call the receive callback for incoming frame data received by
682 * server or client connections.
684 * You need to call this service function periodically to all the above
685 * functions to happen; if your application is single-threaded you can
686 * just call it in your main event loop.
688 * Alternatively you can fork a new process that asynchronously handles
689 * calling this service in a loop. In that case you are happy if this
690 * call blocks your thread until it needs to take care of something and
691 * would call it with a large nonzero timeout. Your loop then takes no
692 * CPU while there is nothing happening.
694 * If you are calling it in a single-threaded app, you don't want it to
695 * wait around blocking other things in your loop from happening, so you
696 * would call it with a timeout_ms of 0, so it returns immediately if
697 * nothing is pending, or as soon as it services whatever was pending.
702 libwebsocket_service(struct libwebsocket_context *this, int timeout_ms)
706 /* stay dead once we are dead */
711 /* wait for something to need service */
713 n = poll(this->fds, this->fds_count, timeout_ms);
714 if (n == 0) /* poll timeout */
719 fprintf(stderr, "Listen Socket dead\n");
724 /* handle accept on listening socket? */
726 for (n = 0; n < this->fds_count; n++)
727 if (this->fds[n].revents)
728 libwebsocket_service_fd(this, &this->fds[n]);
734 * libwebsocket_callback_on_writable() - Request a callback when this socket
735 * becomes able to be written to without
738 * @wsi: Websocket connection instance to get callback for
742 libwebsocket_callback_on_writable(struct libwebsocket_context *this,
743 struct libwebsocket *wsi)
747 for (n = 0; n < this->fds_count; n++)
748 if (this->fds[n].fd == wsi->sock) {
749 this->fds[n].events |= POLLOUT;
753 /* external POLL support via protocol 0 */
754 this->protocols[0].callback(this, wsi,
755 LWS_CALLBACK_SET_MODE_POLL_FD,
756 (void *)(long)wsi->sock, NULL, POLLOUT);
762 * libwebsocket_callback_on_writable_all_protocol() - Request a callback for
763 * all connections using the given protocol when it
764 * becomes possible to write to each socket without
767 * @protocol: Protocol whose connections will get callbacks
771 libwebsocket_callback_on_writable_all_protocol(
772 const struct libwebsocket_protocols *protocol)
774 struct libwebsocket_context *this = protocol->owning_server;
777 struct libwebsocket *wsi;
779 for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
781 for (m = 0; m < this->fd_hashtable[n].length; m++) {
783 wsi = this->fd_hashtable[n].wsi[m];
785 if (wsi->protocol == protocol)
786 libwebsocket_callback_on_writable(this, wsi);
795 * libwebsocket_get_socket_fd() - returns the socket file descriptor
797 * You will not need this unless you are doing something special
799 * @wsi: Websocket connection instance
803 libwebsocket_get_socket_fd(struct libwebsocket *wsi)
809 * libwebsocket_rx_flow_control() - Enable and disable socket servicing for
812 * If the output side of a server process becomes choked, this allows flow
813 * control for the input side.
815 * @wsi: Websocket connection instance to get callback for
816 * @enable: 0 = disable read servicing for this connection, 1 = enable
820 libwebsocket_rx_flow_control(struct libwebsocket *wsi, int enable)
822 struct libwebsocket_context *this = wsi->protocol->owning_server;
825 for (n = 0; n < this->fds_count; n++)
826 if (this->fds[n].fd == wsi->sock) {
828 this->fds[n].events |= POLLIN;
830 this->fds[n].events &= ~POLLIN;
836 /* external POLL support via protocol 0 */
837 this->protocols[0].callback(this, wsi,
838 LWS_CALLBACK_SET_MODE_POLL_FD,
839 (void *)(long)wsi->sock, NULL, POLLIN);
841 /* external POLL support via protocol 0 */
842 this->protocols[0].callback(this, wsi,
843 LWS_CALLBACK_CLEAR_MODE_POLL_FD,
844 (void *)(long)wsi->sock, NULL, POLLIN);
847 fprintf(stderr, "libwebsocket_callback_on_writable "
848 "unable to find socket\n");
853 * libwebsocket_canonical_hostname() - returns this host's hostname
855 * This is typically used by client code to fill in the host parameter
856 * when making a client connection. You can only call it after the context
859 * @this: Websocket context
864 libwebsocket_canonical_hostname(struct libwebsocket_context *this)
866 return (const char *)this->canonical_hostname;
870 static void sigpipe_handler(int x)
877 * libwebsocket_create_context() - Create the websocket handler
878 * @port: Port to listen on... you can use 0 to suppress listening on
879 * any port, that's what you want if you are not running a
880 * websocket server at all but just using it as a client
881 * @protocols: Array of structures listing supported protocols and a protocol-
882 * specific callback for each one. The list is ended with an
883 * entry that has a NULL callback pointer.
884 * It's not const because we write the owning_server member
885 * @ssl_cert_filepath: If libwebsockets was compiled to use ssl, and you want
886 * to listen using SSL, set to the filepath to fetch the
887 * server cert from, otherwise NULL for unencrypted
888 * @ssl_private_key_filepath: filepath to private key if wanting SSL mode,
890 * @gid: group id to change to after setting listen socket, or -1.
891 * @uid: user id to change to after setting listen socket, or -1.
892 * @options: 0, or LWS_SERVER_OPTION_DEFEAT_CLIENT_MASK
894 * This function creates the listening socket and takes care
895 * of all initialization in one step.
897 * After initialization, it returns a struct libwebsocket_context * that
898 * represents this server. After calling, user code needs to take care
899 * of calling libwebsocket_service() with the context pointer to get the
900 * server's sockets serviced. This can be done in the same process context
901 * or a forked process, or another thread,
903 * The protocol callback functions are called for a handful of events
904 * including http requests coming in, websocket connections becoming
905 * established, and data arriving; it's also called periodically to allow
906 * async transmission.
908 * HTTP requests are sent always to the FIRST protocol in @protocol, since
909 * at that time websocket protocol has not been negotiated. Other
910 * protocols after the first one never see any HTTP callack activity.
912 * The server created is a simple http server by default; part of the
913 * websocket standard is upgrading this http connection to a websocket one.
915 * This allows the same server to provide files like scripts and favicon /
916 * images or whatever over http and dynamic data over websockets all in
917 * one place; they're all handled in the user callback.
920 struct libwebsocket_context *
921 libwebsocket_create_context(int port,
922 struct libwebsocket_protocols *protocols,
923 const char *ssl_cert_filepath,
924 const char *ssl_private_key_filepath,
925 int gid, int uid, unsigned int options)
930 struct sockaddr_in serv_addr, cli_addr;
932 struct libwebsocket_context *this = NULL;
937 struct libwebsocket *wsi;
939 #ifdef LWS_OPENSSL_SUPPORT
941 char ssl_err_buf[512];
944 this = malloc(sizeof(struct libwebsocket_context));
946 fprintf(stderr, "No memory for websocket context\n");
949 this->protocols = protocols;
950 this->listen_port = port;
951 this->http_proxy_port = 0;
952 this->http_proxy_address[0] = '\0';
953 this->options = options;
956 this->fd_random = open(SYSTEM_RANDOM_FILEPATH, O_RDONLY);
957 if (this->fd_random < 0) {
958 fprintf(stderr, "Unable to open random device %s %d\n",
959 SYSTEM_RANDOM_FILEPATH, this->fd_random);
963 /* find canonical hostname */
965 hostname[(sizeof hostname) - 1] = '\0';
966 gethostname(hostname, (sizeof hostname) - 1);
967 he = gethostbyname(hostname);
969 strncpy(this->canonical_hostname, he->h_name,
970 sizeof this->canonical_hostname - 1);
971 this->canonical_hostname[sizeof this->canonical_hostname - 1] =
974 strncpy(this->canonical_hostname, hostname,
975 sizeof this->canonical_hostname - 1);
977 /* split the proxy ads:port if given */
979 p = getenv("http_proxy");
981 strncpy(this->http_proxy_address, p,
982 sizeof this->http_proxy_address - 1);
983 this->http_proxy_address[
984 sizeof this->http_proxy_address - 1] = '\0';
986 p = strchr(this->http_proxy_address, ':');
988 fprintf(stderr, "http_proxy needs to be ads:port\n");
992 this->http_proxy_port = atoi(p + 1);
994 fprintf(stderr, "Using proxy %s:%u\n",
995 this->http_proxy_address,
996 this->http_proxy_port);
1001 #ifdef LWS_OPENSSL_SUPPORT
1002 this->use_ssl = ssl_cert_filepath != NULL &&
1003 ssl_private_key_filepath != NULL;
1005 fprintf(stderr, " Compiled with SSL support, "
1008 fprintf(stderr, " Compiled with SSL support, "
1012 if (ssl_cert_filepath != NULL &&
1013 ssl_private_key_filepath != NULL) {
1014 fprintf(stderr, " Not compiled for OpenSSl support!\n");
1017 fprintf(stderr, " Compiled without SSL support, "
1018 "serving unencrypted\n");
1022 /* ignore SIGPIPE */
1024 signal(SIGPIPE, sigpipe_handler);
1027 #ifdef LWS_OPENSSL_SUPPORT
1029 /* basic openssl init */
1033 OpenSSL_add_all_algorithms();
1034 SSL_load_error_strings();
1037 * Firefox insists on SSLv23 not SSLv3
1038 * Konq disables SSLv2 by default now, SSLv23 works
1041 method = (SSL_METHOD *)SSLv23_server_method();
1043 fprintf(stderr, "problem creating ssl method: %s\n",
1044 ERR_error_string(ERR_get_error(), ssl_err_buf));
1047 this->ssl_ctx = SSL_CTX_new(method); /* create context */
1048 if (!this->ssl_ctx) {
1049 fprintf(stderr, "problem creating ssl context: %s\n",
1050 ERR_error_string(ERR_get_error(), ssl_err_buf));
1054 /* client context */
1056 method = (SSL_METHOD *)SSLv23_client_method();
1058 fprintf(stderr, "problem creating ssl method: %s\n",
1059 ERR_error_string(ERR_get_error(), ssl_err_buf));
1062 this->ssl_client_ctx = SSL_CTX_new(method); /* create context */
1063 if (!this->ssl_client_ctx) {
1064 fprintf(stderr, "problem creating ssl context: %s\n",
1065 ERR_error_string(ERR_get_error(), ssl_err_buf));
1070 /* openssl init for cert verification (used with client sockets) */
1072 if (!SSL_CTX_load_verify_locations(this->ssl_client_ctx, NULL,
1073 LWS_OPENSSL_CLIENT_CERTS)) {
1074 fprintf(stderr, "Unable to load SSL Client certs from %s "
1075 "(set by --with-client-cert-dir= in configure) -- "
1076 " client ssl isn't going to work",
1077 LWS_OPENSSL_CLIENT_CERTS);
1080 if (this->use_ssl) {
1082 /* openssl init for server sockets */
1084 /* set the local certificate from CertFile */
1085 n = SSL_CTX_use_certificate_file(this->ssl_ctx,
1086 ssl_cert_filepath, SSL_FILETYPE_PEM);
1088 fprintf(stderr, "problem getting cert '%s': %s\n",
1090 ERR_error_string(ERR_get_error(), ssl_err_buf));
1093 /* set the private key from KeyFile */
1094 if (SSL_CTX_use_PrivateKey_file(this->ssl_ctx,
1095 ssl_private_key_filepath,
1096 SSL_FILETYPE_PEM) != 1) {
1097 fprintf(stderr, "ssl problem getting key '%s': %s\n",
1098 ssl_private_key_filepath,
1099 ERR_error_string(ERR_get_error(), ssl_err_buf));
1102 /* verify private key */
1103 if (!SSL_CTX_check_private_key(this->ssl_ctx)) {
1104 fprintf(stderr, "Private SSL key doesn't match cert\n");
1108 /* SSL is happy and has a cert it's content with */
1114 if (lws_b64_selftest())
1117 /* fd hashtable init */
1119 for (n = 0; n < FD_HASHTABLE_MODULUS; n++)
1120 this->fd_hashtable[n].length = 0;
1122 /* set up our external listening socket we serve on */
1126 sockfd = socket(AF_INET, SOCK_STREAM, 0);
1128 fprintf(stderr, "ERROR opening socket");
1132 /* allow us to restart even if old sockets in TIME_WAIT */
1133 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
1135 bzero((char *) &serv_addr, sizeof(serv_addr));
1136 serv_addr.sin_family = AF_INET;
1137 serv_addr.sin_addr.s_addr = INADDR_ANY;
1138 serv_addr.sin_port = htons(port);
1140 n = bind(sockfd, (struct sockaddr *) &serv_addr,
1143 fprintf(stderr, "ERROR on binding to port %d (%d %d)\n",
1148 wsi = malloc(sizeof(struct libwebsocket));
1149 memset(wsi, 0, sizeof (struct libwebsocket));
1151 wsi->mode = LWS_CONNMODE_SERVER_LISTENER;
1152 insert_wsi(this, wsi);
1155 fprintf(stderr, " Listening on port %d\n", port);
1157 /* list in the internal poll array */
1159 this->fds[this->fds_count].fd = sockfd;
1160 this->fds[this->fds_count++].events = POLLIN;
1162 /* external POLL support via protocol 0 */
1163 this->protocols[0].callback(this, wsi,
1164 LWS_CALLBACK_ADD_POLL_FD,
1165 (void *)(long)sockfd, NULL, POLLIN);
1169 /* drop any root privs for this process */
1173 fprintf(stderr, "setgid: %s\n", strerror(errno));
1176 fprintf(stderr, "setuid: %s\n", strerror(errno));
1179 /* set up our internal broadcast trigger sockets per-protocol */
1181 for (this->count_protocols = 0;
1182 protocols[this->count_protocols].callback;
1183 this->count_protocols++) {
1184 protocols[this->count_protocols].owning_server = this;
1185 protocols[this->count_protocols].protocol_index =
1186 this->count_protocols;
1188 fd = socket(AF_INET, SOCK_STREAM, 0);
1190 fprintf(stderr, "ERROR opening socket");
1194 /* allow us to restart even if old sockets in TIME_WAIT */
1195 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
1197 bzero((char *) &serv_addr, sizeof(serv_addr));
1198 serv_addr.sin_family = AF_INET;
1199 serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
1200 serv_addr.sin_port = 0; /* pick the port for us */
1202 n = bind(fd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));
1204 fprintf(stderr, "ERROR on binding to port %d (%d %d)\n",
1209 slen = sizeof cli_addr;
1210 n = getsockname(fd, (struct sockaddr *)&cli_addr, &slen);
1212 fprintf(stderr, "getsockname failed\n");
1215 protocols[this->count_protocols].broadcast_socket_port =
1216 ntohs(cli_addr.sin_port);
1219 debug(" Protocol %s broadcast socket %d\n",
1220 protocols[this->count_protocols].name,
1221 ntohs(cli_addr.sin_port));
1223 /* dummy wsi per broadcast proxy socket */
1225 wsi = malloc(sizeof(struct libwebsocket));
1226 memset(wsi, 0, sizeof (struct libwebsocket));
1228 wsi->mode = LWS_CONNMODE_BROADCAST_PROXY_LISTENER;
1229 /* note which protocol we are proxying */
1230 wsi->protocol_index_for_broadcast_proxy = this->count_protocols;
1231 insert_wsi(this, wsi);
1233 /* list in internal poll array */
1235 this->fds[this->fds_count].fd = fd;
1236 this->fds[this->fds_count].events = POLLIN;
1237 this->fds[this->fds_count].revents = 0;
1240 /* external POLL support via protocol 0 */
1241 this->protocols[0].callback(this, wsi,
1242 LWS_CALLBACK_ADD_POLL_FD,
1243 (void *)(long)fd, NULL, POLLIN);
1253 * libwebsockets_fork_service_loop() - Optional helper function forks off
1254 * a process for the websocket server loop.
1255 * You don't have to use this but if not, you
1256 * have to make sure you are calling
1257 * libwebsocket_service periodically to service
1258 * the websocket traffic
1259 * @this: server context returned by creation function
1263 libwebsockets_fork_service_loop(struct libwebsocket_context *this)
1266 struct sockaddr_in cli_addr;
1276 /* main process context */
1279 * set up the proxy sockets to allow broadcast from
1280 * service process context
1283 for (p = 0; p < this->count_protocols; p++) {
1284 fd = socket(AF_INET, SOCK_STREAM, 0);
1286 fprintf(stderr, "Unable to create socket\n");
1289 cli_addr.sin_family = AF_INET;
1290 cli_addr.sin_port = htons(
1291 this->protocols[p].broadcast_socket_port);
1292 cli_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
1293 n = connect(fd, (struct sockaddr *)&cli_addr,
1296 fprintf(stderr, "Unable to connect to "
1297 "broadcast socket %d, %s\n",
1298 n, strerror(errno));
1302 this->protocols[p].broadcast_socket_user_fd = fd;
1308 /* we want a SIGHUP when our parent goes down */
1309 prctl(PR_SET_PDEATHSIG, SIGHUP);
1311 /* in this forked process, sit and service websocket connections */
1314 if (libwebsocket_service(this, 1000))
1323 * libwebsockets_get_protocol() - Returns a protocol pointer from a websocket
1325 * @wsi: pointer to struct websocket you want to know the protocol of
1328 * This is useful to get the protocol to broadcast back to from inside
1332 const struct libwebsocket_protocols *
1333 libwebsockets_get_protocol(struct libwebsocket *wsi)
1335 return wsi->protocol;
1339 * libwebsockets_broadcast() - Sends a buffer to the callback for all active
1340 * connections of the given protocol.
1341 * @protocol: pointer to the protocol you will broadcast to all members of
1342 * @buf: buffer containing the data to be broadcase. NOTE: this has to be
1343 * allocated with LWS_SEND_BUFFER_PRE_PADDING valid bytes before
1344 * the pointer and LWS_SEND_BUFFER_POST_PADDING afterwards in the
1345 * case you are calling this function from callback context.
1346 * @len: length of payload data in buf, starting from buf.
1348 * This function allows bulk sending of a packet to every connection using
1349 * the given protocol. It does not send the data directly; instead it calls
1350 * the callback with a reason type of LWS_CALLBACK_BROADCAST. If the callback
1351 * wants to actually send the data for that connection, the callback itself
1352 * should call libwebsocket_write().
1354 * libwebsockets_broadcast() can be called from another fork context without
1355 * having to take any care about data visibility between the processes, it'll
1361 libwebsockets_broadcast(const struct libwebsocket_protocols *protocol,
1362 unsigned char *buf, size_t len)
1364 struct libwebsocket_context *this = protocol->owning_server;
1367 struct libwebsocket * wsi;
1369 if (!protocol->broadcast_socket_user_fd) {
1371 * We are either running unforked / flat, or we are being
1372 * called from poll thread context
1373 * eg, from a callback. In that case don't use sockets for
1374 * broadcast IPC (since we can't open a socket connection to
1375 * a socket listening on our own thread) but directly do the
1378 * Locking is not needed because we are by definition being
1379 * called in the poll thread context and are serialized.
1382 for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
1384 for (m = 0; m < this->fd_hashtable[n].length; m++) {
1386 wsi = this->fd_hashtable[n].wsi[m];
1388 if (wsi->mode != LWS_CONNMODE_WS_SERVING)
1392 * never broadcast to
1393 * non-established connections
1395 if (wsi->state != WSI_STATE_ESTABLISHED)
1398 /* only broadcast to guys using
1399 * requested protocol
1401 if (wsi->protocol != protocol)
1404 wsi->protocol->callback(this, wsi,
1405 LWS_CALLBACK_BROADCAST,
1415 * We're being called from a different process context than the server
1416 * loop. Instead of broadcasting directly, we send our
1417 * payload on a socket to do the IPC; the server process will serialize
1418 * the broadcast action in its main poll() loop.
1420 * There's one broadcast socket listening for each protocol supported
1421 * set up when the websocket server initializes
1424 n = send(protocol->broadcast_socket_user_fd, buf, len, MSG_NOSIGNAL);