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 * libwebsockets_hangup_on_client() - Server calls to terminate client
139 * @this: libwebsockets context
140 * @fd: Connection socket descriptor
144 libwebsockets_hangup_on_client(struct libwebsocket_context *this, int fd)
146 struct libwebsocket *wsi = wsi_from_fd(this, fd);
152 delete_from_fd(this, fd);
154 for (n = 0; n < this->fds_count - 1; n++)
155 if (this->fds[n].fd == fd) {
156 while (n < this->fds_count - 1) {
157 this->fds[n] = this->fds[n + 1];
164 libwebsocket_close_and_free_session(wsi);
169 * libwebsockets_get_peer_addresses() - Get client address information
170 * @fd: Connection socket descriptor
171 * @name: Buffer to take client address name
172 * @name_len: Length of client address name buffer
173 * @rip: Buffer to take client address IP qotted quad
174 * @rip_len: Length of client address IP buffer
176 * This function fills in @name and @rip with the name and IP of
177 * the client connected with socket descriptor @fd. Names may be
178 * truncated if there is not enough room. If either cannot be
179 * determined, they will be returned as valid zero-length strings.
183 libwebsockets_get_peer_addresses(int fd, char *name, int name_len,
184 char *rip, int rip_len)
187 struct sockaddr_in sin;
188 struct hostent *host;
189 struct hostent *host1;
198 if (getpeername(fd, (struct sockaddr *) &sin, &len) < 0) {
199 perror("getpeername");
203 host = gethostbyaddr((char *) &sin.sin_addr, sizeof sin.sin_addr,
206 perror("gethostbyaddr");
210 strncpy(name, host->h_name, name_len);
211 name[name_len - 1] = '\0';
213 host1 = gethostbyname(host->h_name);
219 p = host1->h_addr_list[n++];
222 if (host1->h_addrtype != AF_INET)
225 sprintf(ip, "%d.%d.%d.%d",
226 p[0], p[1], p[2], p[3]);
228 strncpy(rip, ip, rip_len);
229 rip[rip_len - 1] = '\0';
234 * libwebsocket_service_fd() - Service polled socket with something waiting
235 * @this: Websocket context
236 * @pollfd: The pollfd entry describing the socket fd and which events
239 * This function closes any active connections and then frees the
240 * context. After calling this, any further use of the context is
245 libwebsocket_service_fd(struct libwebsocket_context *this,
246 struct pollfd *pollfd)
248 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + MAX_BROADCAST_PAYLOAD +
249 LWS_SEND_BUFFER_POST_PADDING];
250 struct libwebsocket *wsi = wsi_from_fd(this, pollfd->fd);
251 struct libwebsocket *new_wsi;
257 struct sockaddr_in cli_addr;
263 case LWS_CONNMODE_SERVER_LISTENER:
265 /* pollin means a client has connected to us then */
267 if (!pollfd->revents & POLLIN)
270 /* listen socket got an unencrypted connection... */
272 clilen = sizeof(cli_addr);
273 accept_fd = accept(pollfd->fd, (struct sockaddr *)&cli_addr,
276 fprintf(stderr, "ERROR on accept");
280 if (this->fds_count >= MAX_CLIENTS) {
281 fprintf(stderr, "too busy to accept new client\n");
287 * look at who we connected to and give user code a chance
288 * to reject based on client IP. There's no protocol selected
289 * yet so we issue this to protocols[0]
292 if ((this->protocols[0].callback)(wsi,
293 LWS_CALLBACK_FILTER_NETWORK_CONNECTION,
294 (void*)(long)accept_fd, NULL, 0)) {
295 fprintf(stderr, "Callback denied network connection\n");
300 /* accepting connection to main listener */
302 new_wsi = malloc(sizeof(struct libwebsocket));
303 if (new_wsi == NULL) {
304 fprintf(stderr, "Out of memory for new connection\n");
308 memset(new_wsi, 0, sizeof (struct libwebsocket));
309 new_wsi->sock = accept_fd;
311 #ifdef LWS_OPENSSL_SUPPORT
313 this->ssl_ctx = NULL;
317 new_wsi->ssl = SSL_new(this->ssl_ctx);
318 if (new_wsi->ssl == NULL) {
319 fprintf(stderr, "SSL_new failed: %s\n",
320 ERR_error_string(SSL_get_error(
321 new_wsi->ssl, 0), NULL));
326 SSL_set_fd(new_wsi->ssl, accept_fd);
328 n = SSL_accept(new_wsi->ssl);
331 * browsers seem to probe with various
332 * ssl params which fail then retry
335 debug("SSL_accept failed skt %u: %s\n",
337 ERR_error_string(SSL_get_error(
338 new_wsi->ssl, n), NULL));
344 debug("accepted new SSL conn "
345 "port %u on fd=%d SSL ver %s\n",
346 ntohs(cli_addr.sin_port), accept_fd,
347 SSL_get_version(new_wsi->ssl));
351 debug("accepted new conn port %u on fd=%d\n",
352 ntohs(cli_addr.sin_port), accept_fd);
354 /* intialize the instance struct */
356 new_wsi->state = WSI_STATE_HTTP;
357 new_wsi->name_buffer_pos = 0;
358 new_wsi->mode = LWS_CONNMODE_WS_SERVING;
360 for (n = 0; n < WSI_TOKEN_COUNT; n++) {
361 new_wsi->utf8_token[n].token = NULL;
362 new_wsi->utf8_token[n].token_len = 0;
366 * these can only be set once the protocol is known
367 * we set an unestablished connection's protocol pointer
368 * to the start of the supported list, so it can look
369 * for matching ones during the handshake
371 new_wsi->protocol = this->protocols;
372 new_wsi->user_space = NULL;
375 * Default protocol is 76 / 00
376 * After 76, there's a header specified to inform which
377 * draft the client wants, when that's seen we modify
378 * the individual connection's spec revision accordingly
380 new_wsi->ietf_spec_revision = 0;
382 insert_wsi(this, new_wsi);
385 * make sure NO events are seen yet on this new socket
386 * (otherwise we inherit old fds[client].revents from
387 * previous socket there and die mysteriously! )
389 this->fds[this->fds_count].revents = 0;
391 this->fds[this->fds_count].events = POLLIN;
392 this->fds[this->fds_count++].fd = accept_fd;
394 /* external POLL support via protocol 0 */
395 this->protocols[0].callback(new_wsi,
396 LWS_CALLBACK_ADD_POLL_FD,
397 (void *)(long)accept_fd, NULL, POLLIN);
401 case LWS_CONNMODE_BROADCAST_PROXY_LISTENER:
403 /* as we are listening, POLLIN means accept() is needed */
405 if (!pollfd->revents & POLLIN)
408 /* listen socket got an unencrypted connection... */
410 clilen = sizeof(cli_addr);
411 accept_fd = accept(pollfd->fd, (struct sockaddr *)&cli_addr,
414 fprintf(stderr, "ERROR on accept");
418 if (this->fds_count >= MAX_CLIENTS) {
419 fprintf(stderr, "too busy to accept new broadcast "
425 /* create a dummy wsi for the connection and add it */
427 new_wsi = malloc(sizeof(struct libwebsocket));
428 memset(new_wsi, 0, sizeof (struct libwebsocket));
429 new_wsi->sock = accept_fd;
430 new_wsi->mode = LWS_CONNMODE_BROADCAST_PROXY;
431 new_wsi->state = WSI_STATE_ESTABLISHED;
432 /* note which protocol we are proxying */
433 new_wsi->protocol_index_for_broadcast_proxy =
434 wsi->protocol_index_for_broadcast_proxy;
435 insert_wsi(this, new_wsi);
437 /* add connected socket to internal poll array */
439 this->fds[this->fds_count].revents = 0;
440 this->fds[this->fds_count].events = POLLIN;
441 this->fds[this->fds_count++].fd = accept_fd;
443 /* external POLL support via protocol 0 */
444 this->protocols[0].callback(new_wsi,
445 LWS_CALLBACK_ADD_POLL_FD,
446 (void *)(long)accept_fd, NULL, POLLIN);
450 case LWS_CONNMODE_BROADCAST_PROXY:
452 /* handle session socket closed */
454 if (pollfd->revents & (POLLERR | POLLHUP)) {
456 debug("Session Socket %p (fd=%d) dead\n",
457 (void *)wsi, accept_fd);
459 libwebsocket_close_and_free_session(wsi);
463 /* the guy requested a callback when it was OK to write */
465 if (pollfd->revents & POLLOUT) {
469 pollfd->events &= ~POLLOUT;
471 /* external POLL support via protocol 0 */
472 this->protocols[0].callback(wsi,
473 LWS_CALLBACK_CLEAR_MODE_POLL_FD,
474 (void *)(long)wsi->sock, NULL, POLLOUT);
476 wsi->protocol->callback(wsi,
477 LWS_CALLBACK_CLIENT_WRITEABLE,
482 /* any incoming data ready? */
484 if (!(pollfd->revents & POLLIN))
487 /* get the issued broadcast payload from the socket */
489 len = read(pollfd->fd, buf + LWS_SEND_BUFFER_PRE_PADDING,
490 MAX_BROADCAST_PAYLOAD);
492 fprintf(stderr, "Error reading broadcast payload\n");
496 /* broadcast it to all guys with this protocol index */
498 for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
500 for (m = 0; m < this->fd_hashtable[n].length; m++) {
502 new_wsi = this->fd_hashtable[n].wsi[m];
504 /* only to clients we are serving to */
506 if (new_wsi->mode != LWS_CONNMODE_WS_SERVING)
510 * never broadcast to non-established
514 if (new_wsi->state != WSI_STATE_ESTABLISHED)
518 * only broadcast to connections using
519 * the requested protocol
522 if (new_wsi->protocol->protocol_index !=
523 wsi->protocol_index_for_broadcast_proxy)
526 /* broadcast it to this connection */
528 new_wsi->protocol->callback(new_wsi,
529 LWS_CALLBACK_BROADCAST,
531 buf + LWS_SEND_BUFFER_PRE_PADDING, len);
536 case LWS_CONNMODE_WS_SERVING:
537 case LWS_CONNMODE_WS_CLIENT:
539 /* handle session socket closed */
541 if (pollfd->revents & (POLLERR | POLLHUP)) {
543 debug("Session Socket %p (fd=%d) dead\n",
544 (void *)wsi, pollfd->fd);
546 libwebsocket_close_and_free_session(wsi);
550 /* the guy requested a callback when it was OK to write */
552 if (pollfd->revents & POLLOUT) {
554 pollfd->events &= ~POLLOUT;
556 /* external POLL support via protocol 0 */
557 this->protocols[0].callback(wsi,
558 LWS_CALLBACK_CLEAR_MODE_POLL_FD,
559 (void *)(long)wsi->sock, NULL, POLLOUT);
561 wsi->protocol->callback(wsi,
562 LWS_CALLBACK_CLIENT_WRITEABLE,
567 /* any incoming data ready? */
569 if (!(pollfd->revents & POLLIN))
572 #ifdef LWS_OPENSSL_SUPPORT
574 n = SSL_read(wsi->ssl, buf, sizeof buf);
577 n = recv(pollfd->fd, buf, sizeof buf, 0);
580 fprintf(stderr, "Socket read returned %d\n", n);
584 libwebsocket_close_and_free_session(wsi);
588 /* service incoming data */
590 n = libwebsocket_read(wsi, buf, n);
594 * it closed and nuked wsi[client], so remove the
595 * socket handle and wsi from our service list
599 debug("nuking wsi %p, fsd_count = %d\n",
600 (void *)wsi, this->fds_count - 1);
602 delete_from_fd(this, pollfd->fd);
605 for (n = 0; n < this->fds_count; n++)
606 if (this->fds[n].fd == pollfd->fd) {
607 while (n < this->fds_count) {
608 this->fds[n] = this->fds[n + 1];
614 /* external POLL support via protocol 0 */
615 this->protocols[0].callback(wsi,
616 LWS_CALLBACK_DEL_POLL_FD,
617 (void *)(long)pollfd->fd, NULL, 0);
628 * libwebsocket_context_destroy() - Destroy the websocket context
629 * @this: Websocket context
631 * This function closes any active connections and then frees the
632 * context. After calling this, any further use of the context is
636 libwebsocket_context_destroy(struct libwebsocket_context *this)
640 struct libwebsocket *wsi;
642 for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
644 for (m = 0; m < this->fd_hashtable[n].length; m++) {
646 wsi = this->fd_hashtable[n].wsi[m];
649 case LWS_CONNMODE_WS_SERVING:
650 libwebsocket_close_and_free_session(wsi);
652 case LWS_CONNMODE_WS_CLIENT:
653 libwebsocket_client_close(wsi);
661 close(this->fd_random);
663 #ifdef LWS_OPENSSL_SUPPORT
665 SSL_CTX_free(this->ssl_ctx);
666 if (this->ssl_client_ctx)
667 SSL_CTX_free(this->ssl_client_ctx);
674 * libwebsocket_service() - Service any pending websocket activity
675 * @this: Websocket context
676 * @timeout_ms: Timeout for poll; 0 means return immediately if nothing needed
677 * service otherwise block and service immediately, returning
678 * after the timeout if nothing needed service.
680 * This function deals with any pending websocket traffic, for three
681 * kinds of event. It handles these events on both server and client
682 * types of connection the same.
684 * 1) Accept new connections to our context's server
686 * 2) Perform pending broadcast writes initiated from other forked
687 * processes (effectively serializing asynchronous broadcasts)
689 * 3) Call the receive callback for incoming frame data received by
690 * server or client connections.
692 * You need to call this service function periodically to all the above
693 * functions to happen; if your application is single-threaded you can
694 * just call it in your main event loop.
696 * Alternatively you can fork a new process that asynchronously handles
697 * calling this service in a loop. In that case you are happy if this
698 * call blocks your thread until it needs to take care of something and
699 * would call it with a large nonzero timeout. Your loop then takes no
700 * CPU while there is nothing happening.
702 * If you are calling it in a single-threaded app, you don't want it to
703 * wait around blocking other things in your loop from happening, so you
704 * would call it with a timeout_ms of 0, so it returns immediately if
705 * nothing is pending, or as soon as it services whatever was pending.
710 libwebsocket_service(struct libwebsocket_context *this, int timeout_ms)
714 /* stay dead once we are dead */
719 /* wait for something to need service */
721 n = poll(this->fds, this->fds_count, timeout_ms);
722 if (n == 0) /* poll timeout */
725 if (n < 0 || this->fds[0].revents & (POLLERR | POLLHUP)) {
727 fprintf(stderr, "Listen Socket dead\n");
732 /* handle accept on listening socket? */
734 for (n = 0; n < this->fds_count; n++)
735 if (this->fds[n].revents)
736 libwebsocket_service_fd(this, &this->fds[n]);
742 * libwebsocket_callback_on_writable() - Request a callback when this socket
743 * becomes able to be written to without
746 * @wsi: Websocket connection instance to get callback for
750 libwebsocket_callback_on_writable(struct libwebsocket *wsi)
752 struct libwebsocket_context *this = wsi->protocol->owning_server;
755 for (n = 0; n < this->fds_count; n++)
756 if (this->fds[n].fd == wsi->sock) {
757 this->fds[n].events |= POLLOUT;
761 /* external POLL support via protocol 0 */
762 this->protocols[0].callback(wsi,
763 LWS_CALLBACK_SET_MODE_POLL_FD,
764 (void *)(long)wsi->sock, NULL, POLLOUT);
770 * libwebsocket_callback_on_writable_all_protocol() - Request a callback for
771 * all connections using the given protocol when it
772 * becomes possible to write to each socket without
775 * @protocol: Protocol whose connections will get callbacks
779 libwebsocket_callback_on_writable_all_protocol(
780 const struct libwebsocket_protocols *protocol)
782 struct libwebsocket_context *this = protocol->owning_server;
785 struct libwebsocket *wsi;
787 for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
789 for (m = 0; m < this->fd_hashtable[n].length; m++) {
791 wsi = this->fd_hashtable[n].wsi[m];
793 if (wsi->protocol == protocol)
794 libwebsocket_callback_on_writable(wsi);
803 * libwebsocket_get_socket_fd() - returns the socket file descriptor
805 * You will not need this unless you are doing something special
807 * @wsi: Websocket connection instance
811 libwebsocket_get_socket_fd(struct libwebsocket *wsi)
817 * libwebsocket_rx_flow_control() - Enable and disable socket servicing for
820 * If the output side of a server process becomes choked, this allows flow
821 * control for the input side.
823 * @wsi: Websocket connection instance to get callback for
824 * @enable: 0 = disable read servicing for this connection, 1 = enable
828 libwebsocket_rx_flow_control(struct libwebsocket *wsi, int enable)
830 struct libwebsocket_context *this = wsi->protocol->owning_server;
833 for (n = 0; n < this->fds_count; n++)
834 if (this->fds[n].fd == wsi->sock) {
836 this->fds[n].events |= POLLIN;
838 this->fds[n].events &= ~POLLIN;
844 /* external POLL support via protocol 0 */
845 this->protocols[0].callback(wsi,
846 LWS_CALLBACK_SET_MODE_POLL_FD,
847 (void *)(long)wsi->sock, NULL, POLLIN);
849 /* external POLL support via protocol 0 */
850 this->protocols[0].callback(wsi,
851 LWS_CALLBACK_CLEAR_MODE_POLL_FD,
852 (void *)(long)wsi->sock, NULL, POLLIN);
855 fprintf(stderr, "libwebsocket_callback_on_writable "
856 "unable to find socket\n");
861 * libwebsocket_canonical_hostname() - returns this host's hostname
863 * This is typically used by client code to fill in the host parameter
864 * when making a client connection. You can only call it after the context
867 * @this: Websocket context
872 libwebsocket_canonical_hostname(struct libwebsocket_context *this)
874 return (const char *)this->canonical_hostname;
878 static void sigpipe_handler(int x)
885 * libwebsocket_create_context() - Create the websocket handler
886 * @port: Port to listen on... you can use 0 to suppress listening on
887 * any port, that's what you want if you are not running a
888 * websocket server at all but just using it as a client
889 * @protocols: Array of structures listing supported protocols and a protocol-
890 * specific callback for each one. The list is ended with an
891 * entry that has a NULL callback pointer.
892 * It's not const because we write the owning_server member
893 * @ssl_cert_filepath: If libwebsockets was compiled to use ssl, and you want
894 * to listen using SSL, set to the filepath to fetch the
895 * server cert from, otherwise NULL for unencrypted
896 * @ssl_private_key_filepath: filepath to private key if wanting SSL mode,
898 * @gid: group id to change to after setting listen socket, or -1.
899 * @uid: user id to change to after setting listen socket, or -1.
900 * @options: 0, or LWS_SERVER_OPTION_DEFEAT_CLIENT_MASK
902 * This function creates the listening socket and takes care
903 * of all initialization in one step.
905 * After initialization, it returns a struct libwebsocket_context * that
906 * represents this server. After calling, user code needs to take care
907 * of calling libwebsocket_service() with the context pointer to get the
908 * server's sockets serviced. This can be done in the same process context
909 * or a forked process, or another thread,
911 * The protocol callback functions are called for a handful of events
912 * including http requests coming in, websocket connections becoming
913 * established, and data arriving; it's also called periodically to allow
914 * async transmission.
916 * HTTP requests are sent always to the FIRST protocol in @protocol, since
917 * at that time websocket protocol has not been negotiated. Other
918 * protocols after the first one never see any HTTP callack activity.
920 * The server created is a simple http server by default; part of the
921 * websocket standard is upgrading this http connection to a websocket one.
923 * This allows the same server to provide files like scripts and favicon /
924 * images or whatever over http and dynamic data over websockets all in
925 * one place; they're all handled in the user callback.
928 struct libwebsocket_context *
929 libwebsocket_create_context(int port,
930 struct libwebsocket_protocols *protocols,
931 const char *ssl_cert_filepath,
932 const char *ssl_private_key_filepath,
933 int gid, int uid, unsigned int options)
938 struct sockaddr_in serv_addr, cli_addr;
940 struct libwebsocket_context *this = NULL;
945 struct libwebsocket *wsi;
947 #ifdef LWS_OPENSSL_SUPPORT
949 char ssl_err_buf[512];
952 this = malloc(sizeof(struct libwebsocket_context));
954 fprintf(stderr, "No memory for websocket context\n");
957 this->protocols = protocols;
958 this->listen_port = port;
959 this->http_proxy_port = 0;
960 this->http_proxy_address[0] = '\0';
961 this->options = options;
964 this->fd_random = open(SYSTEM_RANDOM_FILEPATH, O_RDONLY);
965 if (this->fd_random < 0) {
966 fprintf(stderr, "Unable to open random device %s %d\n",
967 SYSTEM_RANDOM_FILEPATH, this->fd_random);
971 /* find canonical hostname */
973 hostname[(sizeof hostname) - 1] = '\0';
974 gethostname(hostname, (sizeof hostname) - 1);
975 he = gethostbyname(hostname);
976 strncpy(this->canonical_hostname, he->h_name,
977 sizeof this->canonical_hostname - 1);
978 this->canonical_hostname[sizeof this->canonical_hostname - 1] = '\0';
980 /* split the proxy ads:port if given */
982 p = getenv("http_proxy");
984 strncpy(this->http_proxy_address, p,
985 sizeof this->http_proxy_address - 1);
986 this->http_proxy_address[
987 sizeof this->http_proxy_address - 1] = '\0';
989 p = strchr(this->http_proxy_address, ':');
991 fprintf(stderr, "http_proxy needs to be ads:port\n");
995 this->http_proxy_port = atoi(p + 1);
997 fprintf(stderr, "Using proxy %s:%u\n",
998 this->http_proxy_address,
999 this->http_proxy_port);
1004 #ifdef LWS_OPENSSL_SUPPORT
1005 this->use_ssl = ssl_cert_filepath != NULL &&
1006 ssl_private_key_filepath != NULL;
1008 fprintf(stderr, " Compiled with SSL support, "
1011 fprintf(stderr, " Compiled with SSL support, "
1015 if (ssl_cert_filepath != NULL &&
1016 ssl_private_key_filepath != NULL) {
1017 fprintf(stderr, " Not compiled for OpenSSl support!\n");
1020 fprintf(stderr, " Compiled without SSL support, "
1021 "serving unencrypted\n");
1025 /* ignore SIGPIPE */
1027 signal(SIGPIPE, sigpipe_handler);
1030 #ifdef LWS_OPENSSL_SUPPORT
1032 /* basic openssl init */
1036 OpenSSL_add_all_algorithms();
1037 SSL_load_error_strings();
1040 * Firefox insists on SSLv23 not SSLv3
1041 * Konq disables SSLv2 by default now, SSLv23 works
1044 method = (SSL_METHOD *)SSLv23_server_method();
1046 fprintf(stderr, "problem creating ssl method: %s\n",
1047 ERR_error_string(ERR_get_error(), ssl_err_buf));
1050 this->ssl_ctx = SSL_CTX_new(method); /* create context */
1051 if (!this->ssl_ctx) {
1052 fprintf(stderr, "problem creating ssl context: %s\n",
1053 ERR_error_string(ERR_get_error(), ssl_err_buf));
1057 /* client context */
1059 method = (SSL_METHOD *)SSLv23_client_method();
1061 fprintf(stderr, "problem creating ssl method: %s\n",
1062 ERR_error_string(ERR_get_error(), ssl_err_buf));
1065 this->ssl_client_ctx = SSL_CTX_new(method); /* create context */
1066 if (!this->ssl_client_ctx) {
1067 fprintf(stderr, "problem creating ssl context: %s\n",
1068 ERR_error_string(ERR_get_error(), ssl_err_buf));
1073 /* openssl init for cert verification (used with client sockets) */
1075 if (!SSL_CTX_load_verify_locations(this->ssl_client_ctx, NULL,
1076 LWS_OPENSSL_CLIENT_CERTS)) {
1077 fprintf(stderr, "Unable to load SSL Client certs from %s "
1078 "(set by --with-client-cert-dir= in configure) -- "
1079 " client ssl isn't going to work",
1080 LWS_OPENSSL_CLIENT_CERTS);
1083 if (this->use_ssl) {
1085 /* openssl init for server sockets */
1087 /* set the local certificate from CertFile */
1088 n = SSL_CTX_use_certificate_file(this->ssl_ctx,
1089 ssl_cert_filepath, SSL_FILETYPE_PEM);
1091 fprintf(stderr, "problem getting cert '%s': %s\n",
1093 ERR_error_string(ERR_get_error(), ssl_err_buf));
1096 /* set the private key from KeyFile */
1097 if (SSL_CTX_use_PrivateKey_file(this->ssl_ctx,
1098 ssl_private_key_filepath,
1099 SSL_FILETYPE_PEM) != 1) {
1100 fprintf(stderr, "ssl problem getting key '%s': %s\n",
1101 ssl_private_key_filepath,
1102 ERR_error_string(ERR_get_error(), ssl_err_buf));
1105 /* verify private key */
1106 if (!SSL_CTX_check_private_key(this->ssl_ctx)) {
1107 fprintf(stderr, "Private SSL key doesn't match cert\n");
1111 /* SSL is happy and has a cert it's content with */
1117 if (lws_b64_selftest())
1120 /* fd hashtable init */
1122 for (n = 0; n < FD_HASHTABLE_MODULUS; n++)
1123 this->fd_hashtable[n].length = 0;
1125 /* set up our external listening socket we serve on */
1129 sockfd = socket(AF_INET, SOCK_STREAM, 0);
1131 fprintf(stderr, "ERROR opening socket");
1135 /* allow us to restart even if old sockets in TIME_WAIT */
1136 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
1138 bzero((char *) &serv_addr, sizeof(serv_addr));
1139 serv_addr.sin_family = AF_INET;
1140 serv_addr.sin_addr.s_addr = INADDR_ANY;
1141 serv_addr.sin_port = htons(port);
1143 n = bind(sockfd, (struct sockaddr *) &serv_addr,
1146 fprintf(stderr, "ERROR on binding to port %d (%d %d)\n",
1151 wsi = malloc(sizeof(struct libwebsocket));
1152 memset(wsi, 0, sizeof (struct libwebsocket));
1154 wsi->mode = LWS_CONNMODE_SERVER_LISTENER;
1155 insert_wsi(this, wsi);
1158 fprintf(stderr, " Listening on port %d\n", port);
1160 /* list in the internal poll array */
1162 this->fds[this->fds_count].fd = sockfd;
1163 this->fds[this->fds_count++].events = POLLIN;
1165 /* external POLL support via protocol 0 */
1166 this->protocols[0].callback(wsi,
1167 LWS_CALLBACK_ADD_POLL_FD,
1168 (void *)(long)sockfd, NULL, POLLIN);
1172 /* drop any root privs for this process */
1176 fprintf(stderr, "setgid: %s\n", strerror(errno));
1179 fprintf(stderr, "setuid: %s\n", strerror(errno));
1182 /* set up our internal broadcast trigger sockets per-protocol */
1184 for (this->count_protocols = 0;
1185 protocols[this->count_protocols].callback;
1186 this->count_protocols++) {
1187 protocols[this->count_protocols].owning_server = this;
1188 protocols[this->count_protocols].protocol_index =
1189 this->count_protocols;
1191 fd = socket(AF_INET, SOCK_STREAM, 0);
1193 fprintf(stderr, "ERROR opening socket");
1197 /* allow us to restart even if old sockets in TIME_WAIT */
1198 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
1200 bzero((char *) &serv_addr, sizeof(serv_addr));
1201 serv_addr.sin_family = AF_INET;
1202 serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
1203 serv_addr.sin_port = 0; /* pick the port for us */
1205 n = bind(fd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));
1207 fprintf(stderr, "ERROR on binding to port %d (%d %d)\n",
1212 slen = sizeof cli_addr;
1213 n = getsockname(fd, (struct sockaddr *)&cli_addr, &slen);
1215 fprintf(stderr, "getsockname failed\n");
1218 protocols[this->count_protocols].broadcast_socket_port =
1219 ntohs(cli_addr.sin_port);
1222 debug(" Protocol %s broadcast socket %d\n",
1223 protocols[this->count_protocols].name,
1224 ntohs(cli_addr.sin_port));
1226 /* dummy wsi per broadcast proxy socket */
1228 wsi = malloc(sizeof(struct libwebsocket));
1229 memset(wsi, 0, sizeof (struct libwebsocket));
1231 wsi->mode = LWS_CONNMODE_BROADCAST_PROXY_LISTENER;
1232 /* note which protocol we are proxying */
1233 wsi->protocol_index_for_broadcast_proxy = this->count_protocols;
1234 insert_wsi(this, wsi);
1236 /* list in internal poll array */
1238 this->fds[this->fds_count].fd = fd;
1239 this->fds[this->fds_count].events = POLLIN;
1240 this->fds[this->fds_count].revents = 0;
1243 /* external POLL support via protocol 0 */
1244 this->protocols[0].callback(wsi,
1245 LWS_CALLBACK_ADD_POLL_FD,
1246 (void *)(long)fd, NULL, POLLIN);
1256 * libwebsockets_fork_service_loop() - Optional helper function forks off
1257 * a process for the websocket server loop.
1258 * You don't have to use this but if not, you
1259 * have to make sure you are calling
1260 * libwebsocket_service periodically to service
1261 * the websocket traffic
1262 * @this: server context returned by creation function
1266 libwebsockets_fork_service_loop(struct libwebsocket_context *this)
1269 struct sockaddr_in cli_addr;
1279 /* main process context */
1282 * set up the proxy sockets to allow broadcast from
1283 * service process context
1286 for (p = 0; p < this->count_protocols; p++) {
1287 fd = socket(AF_INET, SOCK_STREAM, 0);
1289 fprintf(stderr, "Unable to create socket\n");
1292 cli_addr.sin_family = AF_INET;
1293 cli_addr.sin_port = htons(
1294 this->protocols[p].broadcast_socket_port);
1295 cli_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
1296 n = connect(fd, (struct sockaddr *)&cli_addr,
1299 fprintf(stderr, "Unable to connect to "
1300 "broadcast socket %d, %s\n",
1301 n, strerror(errno));
1305 this->protocols[p].broadcast_socket_user_fd = fd;
1311 /* we want a SIGHUP when our parent goes down */
1312 prctl(PR_SET_PDEATHSIG, SIGHUP);
1314 /* in this forked process, sit and service websocket connections */
1317 if (libwebsocket_service(this, 1000))
1326 * libwebsockets_get_protocol() - Returns a protocol pointer from a websocket
1328 * @wsi: pointer to struct websocket you want to know the protocol of
1331 * This is useful to get the protocol to broadcast back to from inside
1335 const struct libwebsocket_protocols *
1336 libwebsockets_get_protocol(struct libwebsocket *wsi)
1338 return wsi->protocol;
1342 * libwebsockets_broadcast() - Sends a buffer to the callback for all active
1343 * connections of the given protocol.
1344 * @protocol: pointer to the protocol you will broadcast to all members of
1345 * @buf: buffer containing the data to be broadcase. NOTE: this has to be
1346 * allocated with LWS_SEND_BUFFER_PRE_PADDING valid bytes before
1347 * the pointer and LWS_SEND_BUFFER_POST_PADDING afterwards in the
1348 * case you are calling this function from callback context.
1349 * @len: length of payload data in buf, starting from buf.
1351 * This function allows bulk sending of a packet to every connection using
1352 * the given protocol. It does not send the data directly; instead it calls
1353 * the callback with a reason type of LWS_CALLBACK_BROADCAST. If the callback
1354 * wants to actually send the data for that connection, the callback itself
1355 * should call libwebsocket_write().
1357 * libwebsockets_broadcast() can be called from another fork context without
1358 * having to take any care about data visibility between the processes, it'll
1364 libwebsockets_broadcast(const struct libwebsocket_protocols *protocol,
1365 unsigned char *buf, size_t len)
1367 struct libwebsocket_context *this = protocol->owning_server;
1370 struct libwebsocket * wsi;
1372 if (!protocol->broadcast_socket_user_fd) {
1374 * We are either running unforked / flat, or we are being
1375 * called from poll thread context
1376 * eg, from a callback. In that case don't use sockets for
1377 * broadcast IPC (since we can't open a socket connection to
1378 * a socket listening on our own thread) but directly do the
1381 * Locking is not needed because we are by definition being
1382 * called in the poll thread context and are serialized.
1385 for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
1387 for (m = 0; m < this->fd_hashtable[n].length; m++) {
1389 wsi = this->fd_hashtable[n].wsi[m];
1391 if (wsi->mode != LWS_CONNMODE_WS_SERVING)
1395 * never broadcast to
1396 * non-established connections
1398 if (wsi->state != WSI_STATE_ESTABLISHED)
1401 /* only broadcast to guys using
1402 * requested protocol
1404 if (wsi->protocol != protocol)
1407 wsi->protocol->callback(wsi,
1408 LWS_CALLBACK_BROADCAST,
1418 * We're being called from a different process context than the server
1419 * loop. Instead of broadcasting directly, we send our
1420 * payload on a socket to do the IPC; the server process will serialize
1421 * the broadcast action in its main poll() loop.
1423 * There's one broadcast socket listening for each protocol supported
1424 * set up when the websocket server initializes
1427 n = send(protocol->broadcast_socket_user_fd, buf, len, MSG_NOSIGNAL);