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"
29 #ifdef LWS_BUILTIN_GETIFADDRS
30 #include <getifaddrs.h>
36 #include <sys/socket.h>
40 #ifdef HAVE_SYSTEMD_DAEMON
41 #include <systemd/sd-daemon.h>
42 #endif /* HAVE_SYSTEMD_DAEMON */
44 #ifdef LWS_OPENSSL_SUPPORT
45 int openssl_websocket_private_data_index;
49 #include "../win32port/win32helpers/websock-w32.c"
52 #include "../win32port/win32helpers/websock-w32.c"
56 #ifndef LWS_BUILD_HASH
57 #define LWS_BUILD_HASH "unknown-build-hash"
60 static int log_level = LLL_ERR | LLL_WARN | LLL_NOTICE;
61 static void lwsl_emit_stderr(int level, const char *line);
62 static void (*lwsl_emit)(int level, const char *line) = lwsl_emit_stderr;
64 static const char *library_version = LWS_LIBRARY_VERSION " " LWS_BUILD_HASH;
66 static const char * const log_level_names[] = {
80 extern int lws_client_socket_service(
81 struct libwebsocket_context *context,
82 struct libwebsocket *wsi, struct pollfd *pollfd);
85 extern int lws_server_socket_service(
86 struct libwebsocket_context *context,
87 struct libwebsocket *wsi, struct pollfd *pollfd);
91 * lws_get_library_version: get version and git hash library built from
93 * returns a const char * to a string like "1.1 178d78c"
94 * representing the library version followed by the git head hash it
99 lws_get_library_version(void)
101 return library_version;
105 insert_wsi_socket_into_fds(struct libwebsocket_context *context,
106 struct libwebsocket *wsi)
108 if (context->fds_count >= context->max_fds) {
109 lwsl_err("Too many fds (%d)\n", context->max_fds);
113 if (wsi->sock > context->max_fds) {
114 lwsl_err("Socket fd %d is too high (%d)\n",
115 wsi->sock, context->max_fds);
122 lwsl_info("insert_wsi_socket_into_fds: wsi=%p, sock=%d, fds pos=%d\n",
123 wsi, wsi->sock, context->fds_count);
125 context->lws_lookup[wsi->sock] = wsi;
126 wsi->position_in_fds_table = context->fds_count;
127 context->fds[context->fds_count].fd = wsi->sock;
128 context->fds[context->fds_count].events = POLLIN;
129 context->fds[context->fds_count++].revents = 0;
131 /* external POLL support via protocol 0 */
132 context->protocols[0].callback(context, wsi,
133 LWS_CALLBACK_ADD_POLL_FD,
134 wsi->user_space, (void *)(long)wsi->sock, POLLIN);
140 remove_wsi_socket_from_fds(struct libwebsocket_context *context,
141 struct libwebsocket *wsi)
145 if (!--context->fds_count)
148 if (wsi->sock > context->max_fds) {
149 lwsl_err("Socket fd %d too high (%d)\n",
150 wsi->sock, context->max_fds);
154 lwsl_info("remove_wsi_socket_from_fds: wsi=%p, sock=%d, fds pos=%d\n",
155 wsi, wsi->sock, wsi->position_in_fds_table);
157 m = wsi->position_in_fds_table; /* replace the contents for this */
159 /* have the last guy take up the vacant slot */
160 context->fds[m] = context->fds[context->fds_count];
162 * end guy's fds_lookup entry remains unchanged
163 * (still same fd pointing to same wsi)
165 /* end guy's "position in fds table" changed */
166 context->lws_lookup[context->fds[context->fds_count].fd]->
167 position_in_fds_table = m;
168 /* deletion guy's lws_lookup entry needs nuking */
169 context->lws_lookup[wsi->sock] = NULL;
170 /* removed wsi has no position any more */
171 wsi->position_in_fds_table = -1;
174 /* remove also from external POLL support via protocol 0 */
176 context->protocols[0].callback(context, wsi,
177 LWS_CALLBACK_DEL_POLL_FD, wsi->user_space,
178 (void *)(long)wsi->sock, 0);
185 libwebsocket_close_and_free_session(struct libwebsocket_context *context,
186 struct libwebsocket *wsi, enum lws_close_status reason)
190 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 2 +
191 LWS_SEND_BUFFER_POST_PADDING];
192 #ifndef LWS_NO_EXTENSIONS
195 struct lws_tokens eff_buf;
196 struct libwebsocket_extension *ext;
202 old_state = wsi->state;
204 if (old_state == WSI_STATE_DEAD_SOCKET)
207 /* we tried the polite way... */
208 if (old_state == WSI_STATE_AWAITING_CLOSE_ACK)
209 goto just_kill_connection;
211 wsi->u.ws.close_reason = reason;
213 if (wsi->mode == LWS_CONNMODE_HTTP_SERVING && wsi->u.http.fd) {
214 close(wsi->u.http.fd);
218 #ifndef LWS_NO_EXTENSIONS
220 * are his extensions okay with him closing? Eg he might be a mux
221 * parent and just his ch1 aspect is closing?
224 for (n = 0; n < wsi->count_active_extensions; n++) {
225 if (!wsi->active_extensions[n]->callback)
228 m = wsi->active_extensions[n]->callback(context,
229 wsi->active_extensions[n], wsi,
230 LWS_EXT_CALLBACK_CHECK_OK_TO_REALLY_CLOSE,
231 wsi->active_extensions_user[n], NULL, 0);
234 * if somebody vetoed actually closing him at this time....
235 * up to the extension to track the attempted close, let's
240 lwsl_ext("extension vetoed close\n");
246 * flush any tx pending from extensions, since we may send close packet
247 * if there are problems with send, just nuke the connection
253 /* default to nobody has more to spill */
256 eff_buf.token = NULL;
257 eff_buf.token_len = 0;
259 /* show every extension the new incoming data */
261 for (n = 0; n < wsi->count_active_extensions; n++) {
262 m = wsi->active_extensions[n]->callback(
263 wsi->protocol->owning_server,
264 wsi->active_extensions[n], wsi,
265 LWS_EXT_CALLBACK_FLUSH_PENDING_TX,
266 wsi->active_extensions_user[n], &eff_buf, 0);
268 lwsl_ext("Extension reports fatal error\n");
269 goto just_kill_connection;
273 * at least one extension told us he has more
274 * to spill, so we will go around again after
279 /* assuming they left us something to send, send it */
281 if (eff_buf.token_len)
282 if (lws_issue_raw(wsi, (unsigned char *)eff_buf.token,
283 eff_buf.token_len) != eff_buf.token_len) {
284 lwsl_debug("close: ext spill failed\n");
285 goto just_kill_connection;
291 * signal we are closing, libsocket_write will
292 * add any necessary version-specific stuff. If the write fails,
293 * no worries we are closing anyway. If we didn't initiate this
294 * close, then our state has been changed to
295 * WSI_STATE_RETURNED_CLOSE_ALREADY and we will skip this.
297 * Likewise if it's a second call to close this connection after we
298 * sent the close indication to the peer already, we are in state
299 * WSI_STATE_AWAITING_CLOSE_ACK and will skip doing this a second time.
302 if (old_state == WSI_STATE_ESTABLISHED &&
303 reason != LWS_CLOSE_STATUS_NOSTATUS) {
305 lwsl_debug("sending close indication...\n");
307 /* make valgrind happy */
308 memset(buf, 0, sizeof(buf));
309 n = libwebsocket_write(wsi,
310 &buf[LWS_SEND_BUFFER_PRE_PADDING + 2],
314 * we have sent a nice protocol level indication we
315 * now wish to close, we should not send anything more
318 wsi->state = WSI_STATE_AWAITING_CLOSE_ACK;
321 * ...and we should wait for a reply for a bit
325 libwebsocket_set_timeout(wsi,
326 PENDING_TIMEOUT_CLOSE_ACK, 1);
328 lwsl_debug("sent close indication, awaiting ack\n");
333 lwsl_info("close: sending close packet failed, hanging up\n");
335 /* else, the send failed and we should just hang up */
338 just_kill_connection:
340 lwsl_debug("close: just_kill_connection\n");
343 * we won't be servicing or receiving anything further from this guy
344 * delete socket from the internal poll list if still present
347 remove_wsi_socket_from_fds(context, wsi);
349 wsi->state = WSI_STATE_DEAD_SOCKET;
351 if ((old_state == WSI_STATE_ESTABLISHED ||
352 wsi->mode == LWS_CONNMODE_WS_SERVING ||
353 wsi->mode == LWS_CONNMODE_WS_CLIENT)) {
355 if (wsi->u.ws.rx_user_buffer) {
356 free(wsi->u.ws.rx_user_buffer);
357 wsi->u.ws.rx_user_buffer = NULL;
359 if (wsi->u.ws.rxflow_buffer) {
360 free(wsi->u.ws.rxflow_buffer);
361 wsi->u.ws.rxflow_buffer = NULL;
365 /* tell the user it's all over for this guy */
367 if (wsi->protocol && wsi->protocol->callback &&
368 ((old_state == WSI_STATE_ESTABLISHED) ||
369 (old_state == WSI_STATE_RETURNED_CLOSE_ALREADY) ||
370 (old_state == WSI_STATE_AWAITING_CLOSE_ACK))) {
371 lwsl_debug("calling back CLOSED\n");
372 wsi->protocol->callback(context, wsi, LWS_CALLBACK_CLOSED,
373 wsi->user_space, NULL, 0);
375 lwsl_debug("not calling back closed\n");
377 #ifndef LWS_NO_EXTENSIONS
378 /* deallocate any active extension contexts */
380 for (n = 0; n < wsi->count_active_extensions; n++) {
381 if (!wsi->active_extensions[n]->callback)
384 wsi->active_extensions[n]->callback(context,
385 wsi->active_extensions[n], wsi,
386 LWS_EXT_CALLBACK_DESTROY,
387 wsi->active_extensions_user[n], NULL, 0);
389 free(wsi->active_extensions_user[n]);
393 * inform all extensions in case they tracked this guy out of band
394 * even though not active on him specifically
397 ext = context->extensions;
398 while (ext && ext->callback) {
399 ext->callback(context, ext, wsi,
400 LWS_EXT_CALLBACK_DESTROY_ANY_WSI_CLOSING,
406 /* lwsl_info("closing fd=%d\n", wsi->sock); */
408 #ifdef LWS_OPENSSL_SUPPORT
410 n = SSL_get_fd(wsi->ssl);
411 SSL_shutdown(wsi->ssl);
417 n = shutdown(wsi->sock, SHUT_RDWR);
419 lwsl_debug("closing: shutdown returned %d\n",
422 n = compatible_close(wsi->sock);
424 lwsl_debug("closing: close returned %d\n",
427 #ifdef LWS_OPENSSL_SUPPORT
430 if (wsi->protocol && wsi->protocol->per_session_data_size &&
431 wsi->user_space) /* user code may own */
432 free(wsi->user_space);
438 * libwebsockets_get_peer_addresses() - Get client address information
439 * @context: Libwebsockets context
440 * @wsi: Local struct libwebsocket associated with
441 * @fd: Connection socket descriptor
442 * @name: Buffer to take client address name
443 * @name_len: Length of client address name buffer
444 * @rip: Buffer to take client address IP qotted quad
445 * @rip_len: Length of client address IP buffer
447 * This function fills in @name and @rip with the name and IP of
448 * the client connected with socket descriptor @fd. Names may be
449 * truncated if there is not enough room. If either cannot be
450 * determined, they will be returned as valid zero-length strings.
454 libwebsockets_get_peer_addresses(struct libwebsocket_context *context,
455 struct libwebsocket *wsi, int fd, char *name, int name_len,
456 char *rip, int rip_len)
459 struct sockaddr_in sin;
460 struct hostent *host;
461 struct hostent *host1;
467 struct sockaddr_un *un;
473 lws_latency_pre(context, wsi);
476 if (getpeername(fd, (struct sockaddr *) &sin, &len) < 0) {
477 perror("getpeername");
481 host = gethostbyaddr((char *) &sin.sin_addr, sizeof(sin.sin_addr),
484 perror("gethostbyaddr");
488 strncpy(name, host->h_name, name_len);
489 name[name_len - 1] = '\0';
491 host1 = gethostbyname(host->h_name);
494 p = (unsigned char *)host1;
497 p = (unsigned char *)host1->h_addr_list[n++];
500 if ((host1->h_addrtype != AF_INET)
502 && (host1->h_addrtype != AF_LOCAL)
507 if (host1->h_addrtype == AF_INET)
508 sprintf(ip, "%u.%u.%u.%u", p[0], p[1], p[2], p[3]);
511 un = (struct sockaddr_un *)p;
512 strncpy(ip, un->sun_path, sizeof(ip) - 1);
513 ip[sizeof(ip) - 1] = '\0';
517 strncpy(rip, ip, rip_len);
518 rip[rip_len - 1] = '\0';
523 lws_latency(context, wsi, "libwebsockets_get_peer_addresses", ret, 1);
526 int libwebsockets_get_random(struct libwebsocket_context *context,
530 char *p = (char *)buf;
533 for (n = 0; n < len; n++)
534 p[n] = (unsigned char)rand();
536 n = read(context->fd_random, p, len);
542 int lws_set_socket_options(struct libwebsocket_context *context, int fd)
545 socklen_t optlen = sizeof(optval);
547 unsigned long optl = 0;
549 #if defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__)
550 struct protoent *tcp_proto;
553 if (context->ka_time) {
554 /* enable keepalive on this socket */
556 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE,
557 (const void *)&optval, optlen) < 0)
560 #if defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__)
563 * didn't find a way to set these per-socket, need to
564 * tune kernel systemwide values
569 struct tcp_keepalive alive;
571 alive.keepalivetime = context->ka_time;
572 alive.keepaliveinterval = context->ka_interval;
574 if (WSAIoctl(fd, SIO_KEEPALIVE_VALS, &alive, sizeof(alive),
575 NULL, 0, &dwBytesRet, NULL, NULL))
579 /* set the keepalive conditions we want on it too */
580 optval = context->ka_time;
581 if (setsockopt(fd, IPPROTO_IP, TCP_KEEPIDLE,
582 (const void *)&optval, optlen) < 0)
585 optval = context->ka_interval;
586 if (setsockopt(fd, IPPROTO_IP, TCP_KEEPINTVL,
587 (const void *)&optval, optlen) < 0)
590 optval = context->ka_probes;
591 if (setsockopt(fd, IPPROTO_IP, TCP_KEEPCNT,
592 (const void *)&optval, optlen) < 0)
599 #if !defined(__APPLE__) && !defined(__FreeBSD__) && !defined(__NetBSD__)
600 setsockopt(fd, SOL_TCP, TCP_NODELAY, (const void *)&optval, optlen);
602 tcp_proto = getprotobyname("TCP");
603 setsockopt(fd, tcp_proto->p_proto, TCP_NODELAY, &optval, optlen);
606 /* We are nonblocking... */
608 ioctlsocket(fd, FIONBIO, &optl);
610 fcntl(fd, F_SETFL, O_NONBLOCK);
616 int lws_send_pipe_choked(struct libwebsocket *wsi)
621 fds.events = POLLOUT;
624 if (poll(&fds, 1, 0) != 1)
627 if ((fds.revents & POLLOUT) == 0)
630 /* okay to send another packet without blocking */
636 lws_handle_POLLOUT_event(struct libwebsocket_context *context,
637 struct libwebsocket *wsi, struct pollfd *pollfd)
641 #ifndef LWS_NO_EXTENSIONS
642 struct lws_tokens eff_buf;
647 for (n = 0; n < wsi->count_active_extensions; n++) {
648 if (!wsi->active_extensions[n]->callback)
651 m = wsi->active_extensions[n]->callback(context,
652 wsi->active_extensions[n], wsi,
653 LWS_EXT_CALLBACK_IS_WRITEABLE,
654 wsi->active_extensions_user[n], NULL, 0);
662 if (!wsi->extension_data_pending || handled == 2)
666 * check in on the active extensions, see if they
667 * had pending stuff to spill... they need to get the
668 * first look-in otherwise sequence will be disordered
670 * NULL, zero-length eff_buf means just spill pending
676 /* default to nobody has more to spill */
679 eff_buf.token = NULL;
680 eff_buf.token_len = 0;
682 /* give every extension a chance to spill */
684 for (n = 0; n < wsi->count_active_extensions; n++) {
685 m = wsi->active_extensions[n]->callback(
686 wsi->protocol->owning_server,
687 wsi->active_extensions[n], wsi,
688 LWS_EXT_CALLBACK_PACKET_TX_PRESEND,
689 wsi->active_extensions_user[n], &eff_buf, 0);
691 lwsl_err("ext reports fatal error\n");
696 * at least one extension told us he has more
697 * to spill, so we will go around again after
702 /* assuming they gave us something to send, send it */
704 if (eff_buf.token_len) {
705 n = lws_issue_raw(wsi, (unsigned char *)eff_buf.token,
710 * Keep amount spilled small to minimize chance of this
712 if (n != eff_buf.token_len) {
713 lwsl_err("Unable to spill ext %d vs %s\n",
714 eff_buf.token_len, n);
720 /* no extension has more to spill */
726 * There's more to spill from an extension, but we just sent
727 * something... did that leave the pipe choked?
730 if (!lws_send_pipe_choked(wsi))
731 /* no we could add more */
734 lwsl_info("choked in POLLOUT service\n");
737 * Yes, he's choked. Leave the POLLOUT masked on so we will
738 * come back here when he is unchoked. Don't call the user
739 * callback to enforce ordering of spilling, he'll get called
740 * when we come back here and there's nothing more to spill.
746 wsi->extension_data_pending = 0;
753 pollfd->events &= ~POLLOUT;
755 /* external POLL support via protocol 0 */
756 context->protocols[0].callback(context, wsi,
757 LWS_CALLBACK_CLEAR_MODE_POLL_FD,
758 wsi->user_space, (void *)(long)wsi->sock, POLLOUT);
760 #ifndef LWS_NO_EXTENSIONS
764 if (wsi->mode == LWS_CONNMODE_WS_CLIENT)
765 n = LWS_CALLBACK_CLIENT_WRITEABLE;
767 n = LWS_CALLBACK_SERVER_WRITEABLE;
769 return user_callback_handle_rxflow(wsi->protocol->callback, context,
770 wsi, (enum libwebsocket_callback_reasons) n,
771 wsi->user_space, NULL, 0);
777 libwebsocket_service_timeout_check(struct libwebsocket_context *context,
778 struct libwebsocket *wsi, unsigned int sec)
780 #ifndef LWS_NO_EXTENSIONS
784 * if extensions want in on it (eg, we are a mux parent)
785 * give them a chance to service child timeouts
788 for (n = 0; n < wsi->count_active_extensions; n++)
789 wsi->active_extensions[n]->callback(
790 context, wsi->active_extensions[n],
791 wsi, LWS_EXT_CALLBACK_1HZ,
792 wsi->active_extensions_user[n], NULL, sec);
795 if (!wsi->pending_timeout)
799 * if we went beyond the allowed time, kill the
803 if (sec > wsi->pending_timeout_limit) {
804 lwsl_info("TIMEDOUT WAITING\n");
805 libwebsocket_close_and_free_session(context,
806 wsi, LWS_CLOSE_STATUS_NOSTATUS);
814 * libwebsocket_service_fd() - Service polled socket with something waiting
815 * @context: Websocket context
816 * @pollfd: The pollfd entry describing the socket fd and which events
819 * This function takes a pollfd that has POLLIN or POLLOUT activity and
820 * services it according to the state of the associated
821 * struct libwebsocket.
823 * The one call deals with all "service" that might happen on a socket
824 * including listen accepts, http files as well as websocket protocol.
828 libwebsocket_service_fd(struct libwebsocket_context *context,
829 struct pollfd *pollfd)
831 struct libwebsocket *wsi;
834 int listen_socket_fds_index = 0;
839 #ifndef LWS_NO_EXTENSIONS
842 struct lws_tokens eff_buf;
844 if (context->listen_service_fd)
845 listen_socket_fds_index = context->lws_lookup[
846 context->listen_service_fd]->position_in_fds_table;
849 * you can call us with pollfd = NULL to just allow the once-per-second
850 * global timeout checks; if less than a second since the last check
851 * it returns immediately then.
854 gettimeofday(&tv, NULL);
856 if (context->last_timeout_check_s != tv.tv_sec) {
857 context->last_timeout_check_s = tv.tv_sec;
860 /* if our parent went down, don't linger around */
861 if (context->started_with_parent &&
862 kill(context->started_with_parent, 0) < 0)
863 kill(getpid(), SIGTERM);
866 /* global timeout check once per second */
871 for (n = 0; n < context->fds_count; n++) {
872 m = context->fds[n].fd;
873 wsi = context->lws_lookup[m];
877 if (libwebsocket_service_timeout_check(context, wsi,
879 /* he did time out... */
881 /* it was the guy we came to service! */
886 /* the socket we came to service timed out, nothing to do */
890 /* just here for timeout management? */
895 /* no, here to service a socket descriptor */
898 * deal with listen service piggybacking
899 * every listen_service_modulo services of other fds, we
900 * sneak one in to service the listen socket if there's anything waiting
902 * To handle connection storms, as found in ab, if we previously saw a
903 * pending connection here, it causes us to check again next time.
906 if (context->listen_service_fd && pollfd !=
907 &context->fds[listen_socket_fds_index]) {
908 context->listen_service_count++;
909 if (context->listen_service_extraseen ||
910 context->listen_service_count ==
911 context->listen_service_modulo) {
912 context->listen_service_count = 0;
914 if (context->listen_service_extraseen > 5)
918 * even with extpoll, we prepared this
919 * internal fds for listen
921 n = poll(&context->fds[listen_socket_fds_index],
923 if (n > 0) { /* there's a conn waiting for us */
924 libwebsocket_service_fd(context,
926 fds[listen_socket_fds_index]);
927 context->listen_service_extraseen++;
929 if (context->listen_service_extraseen)
931 listen_service_extraseen--;
939 /* okay, what we came here to do... */
941 wsi = context->lws_lookup[pollfd->fd];
944 lwsl_err("unexpected NULL wsi fd=%d fds_count=%d\n",
945 pollfd->fd, context->fds_count);
951 #ifndef LWS_NO_SERVER
952 case LWS_CONNMODE_HTTP_SERVING:
953 case LWS_CONNMODE_SERVER_LISTENER:
954 case LWS_CONNMODE_SSL_ACK_PENDING:
955 return lws_server_socket_service(context, wsi, pollfd);
958 case LWS_CONNMODE_WS_SERVING:
959 case LWS_CONNMODE_WS_CLIENT:
961 /* handle session socket closed */
963 if ((!pollfd->revents & POLLIN) &&
964 (pollfd->revents & (POLLERR | POLLHUP))) {
966 lwsl_debug("Session Socket %p (fd=%d) dead\n",
967 (void *)wsi, pollfd->fd);
969 libwebsocket_close_and_free_session(context, wsi,
970 LWS_CLOSE_STATUS_NOSTATUS);
974 /* the guy requested a callback when it was OK to write */
976 if ((pollfd->revents & POLLOUT) &&
977 wsi->state == WSI_STATE_ESTABLISHED)
978 if (lws_handle_POLLOUT_event(context, wsi,
980 lwsl_info("libwebsocket_service_fd: closing\n");
981 libwebsocket_close_and_free_session(
982 context, wsi, LWS_CLOSE_STATUS_NOSTATUS);
987 /* any incoming data ready? */
989 if (!(pollfd->revents & POLLIN))
992 #ifdef LWS_OPENSSL_SUPPORT
995 eff_buf.token_len = SSL_read(wsi->ssl,
996 context->service_buffer,
997 sizeof(context->service_buffer));
998 if (!eff_buf.token_len) {
999 n = SSL_get_error(wsi->ssl, eff_buf.token_len);
1000 lwsl_err("SSL_read returned 0 with reason %s\n",
1002 (char *)context->service_buffer));
1006 eff_buf.token_len = recv(pollfd->fd,
1007 context->service_buffer,
1008 sizeof(context->service_buffer), 0);
1010 if (eff_buf.token_len < 0) {
1011 lwsl_debug("Socket read returned %d\n",
1013 if (errno != EINTR && errno != EAGAIN)
1014 libwebsocket_close_and_free_session(context,
1015 wsi, LWS_CLOSE_STATUS_NOSTATUS);
1018 if (!eff_buf.token_len) {
1019 lwsl_info("closing connection due to 0 length read\n");
1020 libwebsocket_close_and_free_session(context, wsi,
1021 LWS_CLOSE_STATUS_NOSTATUS);
1026 * give any active extensions a chance to munge the buffer
1027 * before parse. We pass in a pointer to an lws_tokens struct
1028 * prepared with the default buffer and content length that's in
1029 * there. Rather than rewrite the default buffer, extensions
1030 * that expect to grow the buffer can adapt .token to
1031 * point to their own per-connection buffer in the extension
1032 * user allocation. By default with no extensions or no
1033 * extension callback handling, just the normal input buffer is
1034 * used then so it is efficient.
1037 eff_buf.token = (char *)context->service_buffer;
1038 #ifndef LWS_NO_EXTENSIONS
1044 for (n = 0; n < wsi->count_active_extensions; n++) {
1045 m = wsi->active_extensions[n]->callback(context,
1046 wsi->active_extensions[n], wsi,
1047 LWS_EXT_CALLBACK_PACKET_RX_PREPARSE,
1048 wsi->active_extensions_user[n],
1052 "Extension reports fatal error\n");
1053 libwebsocket_close_and_free_session(
1055 LWS_CLOSE_STATUS_NOSTATUS);
1062 /* service incoming data */
1064 if (eff_buf.token_len) {
1065 n = libwebsocket_read(context, wsi,
1066 (unsigned char *)eff_buf.token,
1072 #ifndef LWS_NO_EXTENSIONS
1073 eff_buf.token = NULL;
1074 eff_buf.token_len = 0;
1078 #ifdef LWS_OPENSSL_SUPPORT
1079 if (wsi->ssl && SSL_pending(wsi->ssl))
1085 #ifdef LWS_NO_CLIENT
1088 return lws_client_socket_service(context, wsi, pollfd);
1097 * libwebsocket_context_destroy() - Destroy the websocket context
1098 * @context: Websocket context
1100 * This function closes any active connections and then frees the
1101 * context. After calling this, any further use of the context is
1105 libwebsocket_context_destroy(struct libwebsocket_context *context)
1107 #ifndef LWS_NO_EXTENSIONS
1110 struct libwebsocket_extension *ext;
1111 struct libwebsocket_protocols *protocol = context->protocols;
1114 if (context->worst_latency_info[0])
1115 lwsl_notice("Worst latency: %s\n", context->worst_latency_info);
1118 for (n = 0; n < context->fds_count; n++) {
1119 struct libwebsocket *wsi =
1120 context->lws_lookup[context->fds[n].fd];
1121 libwebsocket_close_and_free_session(context,
1122 wsi, LWS_CLOSE_STATUS_NOSTATUS /* no protocol close */);
1127 * give all extensions a chance to clean up any per-context
1128 * allocations they might have made
1131 ext = context->extensions;
1132 m = LWS_EXT_CALLBACK_CLIENT_CONTEXT_DESTRUCT;
1133 if (context->listen_port)
1134 m = LWS_EXT_CALLBACK_SERVER_CONTEXT_DESTRUCT;
1135 while (ext && ext->callback) {
1136 ext->callback(context, ext, NULL,
1137 (enum libwebsocket_extension_callback_reasons)m,
1143 * inform all the protocols that they are done and will have no more
1147 while (protocol->callback) {
1148 protocol->callback(context, NULL, LWS_CALLBACK_PROTOCOL_DESTROY,
1157 close(context->fd_random);
1160 #ifdef LWS_OPENSSL_SUPPORT
1161 if (context->ssl_ctx)
1162 SSL_CTX_free(context->ssl_ctx);
1163 if (context->ssl_client_ctx)
1164 SSL_CTX_free(context->ssl_client_ctx);
1166 ERR_remove_state(0);
1169 CRYPTO_cleanup_all_ex_data();
1174 if (context->lws_lookup)
1175 free(context->lws_lookup);
1185 * libwebsocket_context_user() - get the user data associated with the context
1186 * @context: Websocket context
1188 * This returns the optional user allocation that can be attached to
1189 * the context the sockets live in at context_create time. It's a way
1190 * to let all sockets serviced in the same context share data without
1191 * using globals statics in the user code.
1194 libwebsocket_context_user(struct libwebsocket_context *context)
1196 return context->user_space;
1200 * libwebsocket_service() - Service any pending websocket activity
1201 * @context: Websocket context
1202 * @timeout_ms: Timeout for poll; 0 means return immediately if nothing needed
1203 * service otherwise block and service immediately, returning
1204 * after the timeout if nothing needed service.
1206 * This function deals with any pending websocket traffic, for three
1207 * kinds of event. It handles these events on both server and client
1208 * types of connection the same.
1210 * 1) Accept new connections to our context's server
1212 * 2) Call the receive callback for incoming frame data received by
1213 * server or client connections.
1215 * You need to call this service function periodically to all the above
1216 * functions to happen; if your application is single-threaded you can
1217 * just call it in your main event loop.
1219 * Alternatively you can fork a new process that asynchronously handles
1220 * calling this service in a loop. In that case you are happy if this
1221 * call blocks your thread until it needs to take care of something and
1222 * would call it with a large nonzero timeout. Your loop then takes no
1223 * CPU while there is nothing happening.
1225 * If you are calling it in a single-threaded app, you don't want it to
1226 * wait around blocking other things in your loop from happening, so you
1227 * would call it with a timeout_ms of 0, so it returns immediately if
1228 * nothing is pending, or as soon as it services whatever was pending.
1232 libwebsocket_service(struct libwebsocket_context *context, int timeout_ms)
1236 /* stay dead once we are dead */
1238 if (context == NULL)
1241 /* wait for something to need service */
1243 n = poll(context->fds, context->fds_count, timeout_ms);
1244 if (n == 0) /* poll timeout */
1250 /* any socket with events to service? */
1252 for (n = 0; n < context->fds_count; n++)
1253 if (context->fds[n].revents)
1254 if (libwebsocket_service_fd(context,
1255 &context->fds[n]) < 0)
1260 #ifndef LWS_NO_EXTENSIONS
1262 lws_any_extension_handled(struct libwebsocket_context *context,
1263 struct libwebsocket *wsi,
1264 enum libwebsocket_extension_callback_reasons r,
1265 void *v, size_t len)
1270 /* maybe an extension will take care of it for us */
1272 for (n = 0; n < wsi->count_active_extensions && !handled; n++) {
1273 if (!wsi->active_extensions[n]->callback)
1276 handled |= wsi->active_extensions[n]->callback(context,
1277 wsi->active_extensions[n], wsi,
1278 r, wsi->active_extensions_user[n], v, len);
1286 lws_get_extension_user_matching_ext(struct libwebsocket *wsi,
1287 struct libwebsocket_extension *ext)
1294 while (n < wsi->count_active_extensions) {
1295 if (wsi->active_extensions[n] != ext) {
1299 return wsi->active_extensions_user[n];
1307 * libwebsocket_callback_on_writable() - Request a callback when this socket
1308 * becomes able to be written to without
1311 * @context: libwebsockets context
1312 * @wsi: Websocket connection instance to get callback for
1316 libwebsocket_callback_on_writable(struct libwebsocket_context *context,
1317 struct libwebsocket *wsi)
1319 #ifndef LWS_NO_EXTENSIONS
1323 /* maybe an extension will take care of it for us */
1325 for (n = 0; n < wsi->count_active_extensions; n++) {
1326 if (!wsi->active_extensions[n]->callback)
1329 handled |= wsi->active_extensions[n]->callback(context,
1330 wsi->active_extensions[n], wsi,
1331 LWS_EXT_CALLBACK_REQUEST_ON_WRITEABLE,
1332 wsi->active_extensions_user[n], NULL, 0);
1338 if (wsi->position_in_fds_table < 0) {
1339 lwsl_err("libwebsocket_callback_on_writable: failed to find socket %d\n",
1344 context->fds[wsi->position_in_fds_table].events |= POLLOUT;
1346 /* external POLL support via protocol 0 */
1347 context->protocols[0].callback(context, wsi,
1348 LWS_CALLBACK_SET_MODE_POLL_FD,
1349 wsi->user_space, (void *)(long)wsi->sock, POLLOUT);
1355 * libwebsocket_callback_on_writable_all_protocol() - Request a callback for
1356 * all connections using the given protocol when it
1357 * becomes possible to write to each socket without
1360 * @protocol: Protocol whose connections will get callbacks
1364 libwebsocket_callback_on_writable_all_protocol(
1365 const struct libwebsocket_protocols *protocol)
1367 struct libwebsocket_context *context = protocol->owning_server;
1369 struct libwebsocket *wsi;
1371 for (n = 0; n < context->fds_count; n++) {
1372 wsi = context->lws_lookup[context->fds[n].fd];
1375 if (wsi->protocol == protocol)
1376 libwebsocket_callback_on_writable(context, wsi);
1383 * libwebsocket_set_timeout() - marks the wsi as subject to a timeout
1385 * You will not need this unless you are doing something special
1387 * @wsi: Websocket connection instance
1388 * @reason: timeout reason
1389 * @secs: how many seconds
1393 libwebsocket_set_timeout(struct libwebsocket *wsi,
1394 enum pending_timeout reason, int secs)
1398 gettimeofday(&tv, NULL);
1400 wsi->pending_timeout_limit = tv.tv_sec + secs;
1401 wsi->pending_timeout = reason;
1406 * libwebsocket_get_socket_fd() - returns the socket file descriptor
1408 * You will not need this unless you are doing something special
1410 * @wsi: Websocket connection instance
1414 libwebsocket_get_socket_fd(struct libwebsocket *wsi)
1421 lws_latency(struct libwebsocket_context *context, struct libwebsocket *wsi,
1422 const char *action, int ret, int completed)
1428 gettimeofday(&tv, NULL);
1430 u = (tv.tv_sec * 1000000) + tv.tv_usec;
1434 if (wsi->action_start == wsi->latency_start)
1436 "Completion first try lat %luus: %p: ret %d: %s\n",
1437 u - wsi->latency_start,
1438 (void *)wsi, ret, action);
1441 "Completion %luus: lat %luus: %p: ret %d: %s\n",
1442 u - wsi->action_start,
1443 u - wsi->latency_start,
1444 (void *)wsi, ret, action);
1445 wsi->action_start = 0;
1447 sprintf(buf, "lat %luus: %p: ret %d: %s\n",
1448 u - wsi->latency_start,
1449 (void *)wsi, ret, action);
1450 if (u - wsi->latency_start > context->worst_latency) {
1451 context->worst_latency = u - wsi->latency_start;
1452 strcpy(context->worst_latency_info, buf);
1454 lwsl_latency("%s", buf);
1456 wsi->latency_start = u;
1457 if (!wsi->action_start)
1458 wsi->action_start = u;
1463 #ifdef LWS_NO_SERVER
1465 _libwebsocket_rx_flow_control(struct libwebsocket *wsi)
1471 _libwebsocket_rx_flow_control(struct libwebsocket *wsi)
1473 struct libwebsocket_context *context = wsi->protocol->owning_server;
1476 if (!(wsi->u.ws.rxflow_change_to & 2))
1479 wsi->u.ws.rxflow_change_to &= ~2;
1481 lwsl_info("rxflow: wsi %p change_to %d\n",
1482 wsi, wsi->u.ws.rxflow_change_to);
1484 /* if we're letting it come again, did we interrupt anything? */
1485 if ((wsi->u.ws.rxflow_change_to & 1) && wsi->u.ws.rxflow_buffer) {
1486 n = libwebsocket_interpret_incoming_packet(wsi, NULL, 0);
1488 lwsl_info("libwebsocket_rx_flow_control: close req\n");
1492 /* oh he stuck again, do nothing */
1496 if (wsi->u.ws.rxflow_change_to & 1)
1497 context->fds[wsi->position_in_fds_table].events |= POLLIN;
1499 context->fds[wsi->position_in_fds_table].events &= ~POLLIN;
1501 if (wsi->u.ws.rxflow_change_to & 1)
1502 /* external POLL support via protocol 0 */
1503 context->protocols[0].callback(context, wsi,
1504 LWS_CALLBACK_SET_MODE_POLL_FD,
1505 wsi->user_space, (void *)(long)wsi->sock, POLLIN);
1507 /* external POLL support via protocol 0 */
1508 context->protocols[0].callback(context, wsi,
1509 LWS_CALLBACK_CLEAR_MODE_POLL_FD,
1510 wsi->user_space, (void *)(long)wsi->sock, POLLIN);
1517 * libwebsocket_rx_flow_control() - Enable and disable socket servicing for
1518 * receieved packets.
1520 * If the output side of a server process becomes choked, this allows flow
1521 * control for the input side.
1523 * @wsi: Websocket connection instance to get callback for
1524 * @enable: 0 = disable read servicing for this connection, 1 = enable
1528 libwebsocket_rx_flow_control(struct libwebsocket *wsi, int enable)
1530 wsi->u.ws.rxflow_change_to = 2 | !!enable;
1537 * libwebsocket_canonical_hostname() - returns this host's hostname
1539 * This is typically used by client code to fill in the host parameter
1540 * when making a client connection. You can only call it after the context
1543 * @context: Websocket context
1548 libwebsocket_canonical_hostname(struct libwebsocket_context *context)
1550 return (const char *)context->canonical_hostname;
1554 static void sigpipe_handler(int x)
1558 #ifdef LWS_OPENSSL_SUPPORT
1560 OpenSSL_verify_callback(int preverify_ok, X509_STORE_CTX *x509_ctx)
1565 struct libwebsocket_context *context;
1567 ssl = X509_STORE_CTX_get_ex_data(x509_ctx,
1568 SSL_get_ex_data_X509_STORE_CTX_idx());
1571 * !!! nasty openssl requires the index to come as a library-scope
1574 context = SSL_get_ex_data(ssl, openssl_websocket_private_data_index);
1576 n = context->protocols[0].callback(NULL, NULL,
1577 LWS_CALLBACK_OPENSSL_PERFORM_CLIENT_CERT_VERIFICATION,
1578 x509_ctx, ssl, preverify_ok);
1580 /* convert return code from 0 = OK to 1 = OK */
1591 int user_callback_handle_rxflow(callback_function callback_function,
1592 struct libwebsocket_context *context,
1593 struct libwebsocket *wsi,
1594 enum libwebsocket_callback_reasons reason, void *user,
1595 void *in, size_t len)
1599 n = callback_function(context, wsi, reason, user, in, len);
1601 n = _libwebsocket_rx_flow_control(wsi);
1608 * libwebsocket_create_context() - Create the websocket handler
1609 * @info: pointer to struct with parameters
1611 * This function creates the listening socket (if serving) and takes care
1612 * of all initialization in one step.
1614 * After initialization, it returns a struct libwebsocket_context * that
1615 * represents this server. After calling, user code needs to take care
1616 * of calling libwebsocket_service() with the context pointer to get the
1617 * server's sockets serviced. This can be done in the same process context
1618 * or a forked process, or another thread,
1620 * The protocol callback functions are called for a handful of events
1621 * including http requests coming in, websocket connections becoming
1622 * established, and data arriving; it's also called periodically to allow
1623 * async transmission.
1625 * HTTP requests are sent always to the FIRST protocol in @protocol, since
1626 * at that time websocket protocol has not been negotiated. Other
1627 * protocols after the first one never see any HTTP callack activity.
1629 * The server created is a simple http server by default; part of the
1630 * websocket standard is upgrading this http connection to a websocket one.
1632 * This allows the same server to provide files like scripts and favicon /
1633 * images or whatever over http and dynamic data over websockets all in
1634 * one place; they're all handled in the user callback.
1637 struct libwebsocket_context *
1638 libwebsocket_create_context(struct lws_context_creation_info *info)
1640 struct libwebsocket_context *context = NULL;
1643 #ifndef LWS_NO_SERVER
1645 struct libwebsocket *wsi;
1646 struct sockaddr_in serv_addr;
1648 #ifndef LWS_NO_EXTENSIONS
1650 struct libwebsocket_extension *ext;
1653 #ifdef LWS_OPENSSL_SUPPORT
1657 #ifndef LWS_NO_DAEMONIZE
1658 int pid_daemon = get_daemonize_pid();
1661 lwsl_notice("Initial logging level %d\n", log_level);
1662 lwsl_notice("Library version: %s\n", library_version);
1663 lwsl_info(" LWS_MAX_HEADER_LEN: %u\n", LWS_MAX_HEADER_LEN);
1664 lwsl_info(" LWS_MAX_PROTOCOLS: %u\n", LWS_MAX_PROTOCOLS);
1665 #ifndef LWS_NO_EXTENSIONS
1666 lwsl_info(" LWS_MAX_EXTENSIONS_ACTIVE: %u\n",
1667 LWS_MAX_EXTENSIONS_ACTIVE);
1669 lwsl_notice(" Configured without extension support\n");
1671 lwsl_info(" SPEC_LATEST_SUPPORTED: %u\n", SPEC_LATEST_SUPPORTED);
1672 lwsl_info(" AWAITING_TIMEOUT: %u\n", AWAITING_TIMEOUT);
1673 if (info->ssl_cipher_list)
1674 lwsl_info(" SSL ciphers: '%s'\n", info->ssl_cipher_list);
1675 lwsl_info(" SYSTEM_RANDOM_FILEPATH: '%s'\n", SYSTEM_RANDOM_FILEPATH);
1676 lwsl_info(" LWS_MAX_ZLIB_CONN_BUFFER: %u\n", LWS_MAX_ZLIB_CONN_BUFFER);
1680 WORD wVersionRequested;
1685 /* Use the MAKEWORD(lowbyte, highbyte) macro from Windef.h */
1686 wVersionRequested = MAKEWORD(2, 2);
1688 err = WSAStartup(wVersionRequested, &wsaData);
1690 /* Tell the user that we could not find a usable */
1692 lwsl_err("WSAStartup failed with error: %d\n", err);
1696 /* default to a poll() made out of select() */
1697 poll = emulated_poll;
1699 /* if windows socket lib available, use his WSAPoll */
1700 wsdll = GetModuleHandle(_T("Ws2_32.dll"));
1702 poll = (PFNWSAPOLL)GetProcAddress(wsdll, "WSAPoll");
1704 /* Finally fall back to emulated poll if all else fails */
1706 poll = emulated_poll;
1710 context = (struct libwebsocket_context *)
1711 malloc(sizeof(struct libwebsocket_context));
1713 lwsl_err("No memory for websocket context\n");
1716 memset(context, 0, sizeof(*context));
1717 #ifndef LWS_NO_DAEMONIZE
1718 context->started_with_parent = pid_daemon;
1719 lwsl_notice(" Started with daemon pid %d\n", pid_daemon);
1722 context->listen_service_extraseen = 0;
1723 context->protocols = info->protocols;
1724 context->listen_port = info->port;
1725 context->http_proxy_port = 0;
1726 context->http_proxy_address[0] = '\0';
1727 context->options = info->options;
1728 /* to reduce this allocation, */
1729 context->max_fds = getdtablesize();
1730 lwsl_notice(" static allocation: %u + (%u x %u fds) = %u bytes\n",
1731 sizeof(struct libwebsocket_context),
1732 sizeof(struct pollfd) + sizeof(struct libwebsocket *),
1734 sizeof(struct libwebsocket_context) +
1735 ((sizeof(struct pollfd) + sizeof(struct libwebsocket *)) *
1738 context->fds = (struct pollfd *)malloc(sizeof(struct pollfd) *
1740 if (context->fds == NULL) {
1741 lwsl_err("Unable to allocate fds array for %d connections\n",
1746 context->lws_lookup = (struct libwebsocket **)
1747 malloc(sizeof(struct libwebsocket *) * context->max_fds);
1748 if (context->lws_lookup == NULL) {
1750 "Unable to allocate lws_lookup array for %d connections\n",
1757 context->fds_count = 0;
1758 #ifndef LWS_NO_EXTENSIONS
1759 context->extensions = info->extensions;
1761 context->last_timeout_check_s = 0;
1762 context->user_space = info->user;
1765 context->fd_random = 0;
1767 context->fd_random = open(SYSTEM_RANDOM_FILEPATH, O_RDONLY);
1768 if (context->fd_random < 0) {
1769 lwsl_err("Unable to open random device %s %d\n",
1770 SYSTEM_RANDOM_FILEPATH, context->fd_random);
1775 #ifdef LWS_OPENSSL_SUPPORT
1776 context->use_ssl = 0;
1777 context->ssl_ctx = NULL;
1778 context->ssl_client_ctx = NULL;
1779 openssl_websocket_private_data_index = 0;
1782 strcpy(context->canonical_hostname, "unknown");
1784 #ifndef LWS_NO_SERVER
1785 if (!(info->options & LWS_SERVER_OPTION_SKIP_SERVER_CANONICAL_NAME)) {
1786 /* find canonical hostname */
1787 gethostname((char *)context->canonical_hostname,
1788 sizeof(context->canonical_hostname) - 1);
1790 lwsl_notice(" canonical_hostname = %s\n",
1791 context->canonical_hostname);
1795 /* split the proxy ads:port if given */
1797 p = getenv("http_proxy");
1799 strncpy(context->http_proxy_address, p,
1800 sizeof(context->http_proxy_address) - 1);
1801 context->http_proxy_address[
1802 sizeof(context->http_proxy_address) - 1] = '\0';
1804 p = strchr(context->http_proxy_address, ':');
1806 lwsl_err("http_proxy needs to be ads:port\n");
1810 context->http_proxy_port = atoi(p + 1);
1812 lwsl_notice(" Proxy %s:%u\n",
1813 context->http_proxy_address,
1814 context->http_proxy_port);
1817 #ifndef LWS_NO_SERVER
1820 #ifdef LWS_OPENSSL_SUPPORT
1821 context->use_ssl = info->ssl_cert_filepath != NULL &&
1822 info->ssl_private_key_filepath != NULL;
1824 lwsl_notice(" Compiled with CYASSL support\n");
1826 lwsl_notice(" Compiled with OpenSSL support\n");
1828 if (context->use_ssl)
1829 lwsl_notice(" Using SSL mode\n");
1831 lwsl_notice(" Using non-SSL mode\n");
1834 if (info->ssl_cert_filepath != NULL &&
1835 info->ssl_private_key_filepath != NULL) {
1836 lwsl_notice(" Not compiled for OpenSSl support!\n");
1839 lwsl_notice(" Compiled without SSL support\n");
1843 " per-conn mem: %u + %u headers + protocol rx buf\n",
1844 sizeof(struct libwebsocket),
1845 sizeof(struct allocated_headers));
1849 /* ignore SIGPIPE */
1852 signal(SIGPIPE, sigpipe_handler);
1856 #ifdef LWS_OPENSSL_SUPPORT
1858 /* basic openssl init */
1862 OpenSSL_add_all_algorithms();
1863 SSL_load_error_strings();
1865 openssl_websocket_private_data_index =
1866 SSL_get_ex_new_index(0, "libwebsockets", NULL, NULL, NULL);
1869 * Firefox insists on SSLv23 not SSLv3
1870 * Konq disables SSLv2 by default now, SSLv23 works
1873 method = (SSL_METHOD *)SSLv23_server_method();
1875 lwsl_err("problem creating ssl method %lu: %s\n",
1877 ERR_error_string(ERR_get_error(),
1878 (char *)context->service_buffer));
1881 context->ssl_ctx = SSL_CTX_new(method); /* create context */
1882 if (!context->ssl_ctx) {
1883 lwsl_err("problem creating ssl context %lu: %s\n",
1885 ERR_error_string(ERR_get_error(),
1886 (char *)context->service_buffer));
1890 #ifdef SSL_OP_NO_COMPRESSION
1891 SSL_CTX_set_options(context->ssl_ctx, SSL_OP_NO_COMPRESSION);
1893 SSL_CTX_set_options(context->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
1894 if (info->ssl_cipher_list)
1895 SSL_CTX_set_cipher_list(context->ssl_ctx,
1896 info->ssl_cipher_list);
1898 #ifndef LWS_NO_CLIENT
1900 /* client context */
1902 if (info->port == CONTEXT_PORT_NO_LISTEN) {
1903 method = (SSL_METHOD *)SSLv23_client_method();
1905 lwsl_err("problem creating ssl method %lu: %s\n",
1907 ERR_error_string(ERR_get_error(),
1908 (char *)context->service_buffer));
1911 /* create context */
1912 context->ssl_client_ctx = SSL_CTX_new(method);
1913 if (!context->ssl_client_ctx) {
1914 lwsl_err("problem creating ssl context %lu: %s\n",
1916 ERR_error_string(ERR_get_error(),
1917 (char *)context->service_buffer));
1921 #ifdef SSL_OP_NO_COMPRESSION
1922 SSL_CTX_set_options(context->ssl_client_ctx,
1923 SSL_OP_NO_COMPRESSION);
1925 SSL_CTX_set_options(context->ssl_client_ctx,
1926 SSL_OP_CIPHER_SERVER_PREFERENCE);
1927 if (info->ssl_cipher_list)
1928 SSL_CTX_set_cipher_list(context->ssl_client_ctx,
1929 info->ssl_cipher_list);
1931 /* openssl init for cert verification (for client sockets) */
1932 if (!info->ssl_ca_filepath) {
1933 if (!SSL_CTX_load_verify_locations(
1934 context->ssl_client_ctx, NULL,
1935 LWS_OPENSSL_CLIENT_CERTS))
1937 "Unable to load SSL Client certs from %s "
1938 "(set by --with-client-cert-dir= "
1939 "in configure) -- client ssl isn't "
1940 "going to work", LWS_OPENSSL_CLIENT_CERTS);
1942 if (!SSL_CTX_load_verify_locations(
1943 context->ssl_client_ctx, info->ssl_ca_filepath,
1946 "Unable to load SSL Client certs "
1947 "file from %s -- client ssl isn't "
1948 "going to work", info->ssl_ca_filepath);
1951 * callback allowing user code to load extra verification certs
1952 * helping the client to verify server identity
1955 context->protocols[0].callback(context, NULL,
1956 LWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS,
1957 context->ssl_client_ctx, NULL, 0);
1961 /* as a server, are we requiring clients to identify themselves? */
1964 LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT) {
1966 /* absolutely require the client cert */
1968 SSL_CTX_set_verify(context->ssl_ctx,
1969 SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
1970 OpenSSL_verify_callback);
1973 * give user code a chance to load certs into the server
1974 * allowing it to verify incoming client certs
1977 context->protocols[0].callback(context, NULL,
1978 LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS,
1979 context->ssl_ctx, NULL, 0);
1982 if (context->use_ssl) {
1984 /* openssl init for server sockets */
1986 /* set the local certificate from CertFile */
1987 n = SSL_CTX_use_certificate_chain_file(context->ssl_ctx,
1988 info->ssl_cert_filepath);
1990 lwsl_err("problem getting cert '%s' %lu: %s\n",
1991 info->ssl_cert_filepath,
1993 ERR_error_string(ERR_get_error(),
1994 (char *)context->service_buffer));
1997 /* set the private key from KeyFile */
1998 if (SSL_CTX_use_PrivateKey_file(context->ssl_ctx,
1999 info->ssl_private_key_filepath,
2000 SSL_FILETYPE_PEM) != 1) {
2001 lwsl_err("ssl problem getting key '%s' %lu: %s\n",
2002 info->ssl_private_key_filepath,
2004 ERR_error_string(ERR_get_error(),
2005 (char *)context->service_buffer));
2008 /* verify private key */
2009 if (!SSL_CTX_check_private_key(context->ssl_ctx)) {
2010 lwsl_err("Private SSL key doesn't match cert\n");
2014 /* SSL is happy and has a cert it's content with */
2020 if (lws_b64_selftest())
2023 #ifndef LWS_NO_SERVER
2024 /* set up our external listening socket we serve on */
2029 #ifdef HAVE_SYSTEMD_DAEMON
2030 int const begin = SD_LISTEN_FDS_START;
2031 int const end = begin + sd_listen_fds(0);
2035 * Check if we have a systemd activated socket we can
2036 * use. Otherwise explicitly create the socket.
2038 for (fd = begin; fd < end; ++fd) {
2039 if (sd_is_socket_inet(fd,
2042 1, // check if in accepting mode
2045 lwsl_notice("Systemd socket activation "
2053 lwsl_warn("Systemd socket activation "
2055 "Creating new socket instead.\n");
2057 #endif /* HAVE_SYSTEMD_DAEMON */
2058 sockfd = socket(AF_INET, SOCK_STREAM, 0);
2060 lwsl_err("ERROR opening socket\n");
2066 * allow us to restart even if old sockets in TIME_WAIT
2067 * (REUSEADDR on Unix means, "don't hang on to this
2068 * address after the listener is closed." On Windows, though,
2069 * it means "don't keep other processes from binding to
2070 * this address while we're using it)
2072 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
2073 (const void *)&opt, sizeof(opt));
2078 setsockopt(sockfd, IPPROTO_TCP, TCP_NODELAY,
2079 (const void *)&opt, sizeof(opt));
2083 ioctlsocket(sockfd, FIONBIO, (unsigned long *)&opt);
2085 fcntl(sockfd, F_SETFL, O_NONBLOCK);
2088 bzero((char *) &serv_addr, sizeof(serv_addr));
2089 serv_addr.sin_family = AF_INET;
2090 if (info->iface == NULL)
2091 serv_addr.sin_addr.s_addr = INADDR_ANY;
2093 interface_to_sa(info->iface, &serv_addr,
2095 serv_addr.sin_port = htons(info->port);
2097 n = bind(sockfd, (struct sockaddr *) &serv_addr,
2100 lwsl_err("ERROR on binding to port %d (%d %d)\n",
2101 info->port, n, errno);
2106 listen(sockfd, LWS_SOMAXCONN);
2107 #ifdef HAVE_SYSTEMD_DAEMON
2109 #endif /* HAVE_SYSTEMD_DAEMON */
2111 wsi = (struct libwebsocket *)malloc(
2112 sizeof(struct libwebsocket));
2114 lwsl_err("Out of mem\n");
2118 memset(wsi, 0, sizeof(struct libwebsocket));
2120 #ifndef LWS_NO_EXTENSIONS
2121 wsi->count_active_extensions = 0;
2123 wsi->mode = LWS_CONNMODE_SERVER_LISTENER;
2125 insert_wsi_socket_into_fds(context, wsi);
2127 context->listen_service_modulo = LWS_LISTEN_SERVICE_MODULO;
2128 context->listen_service_count = 0;
2129 context->listen_service_fd = sockfd;
2131 lwsl_notice(" Listening on port %d\n", info->port);
2137 * drop any root privs for this process
2138 * to listen on port < 1023 we would have needed root, but now we are
2139 * listening, we don't want the power for anything else
2143 if (info->gid != -1)
2144 if (setgid(info->gid))
2145 lwsl_warn("setgid: %s\n", strerror(errno));
2146 if (info->uid != -1)
2147 if (setuid(info->uid))
2148 lwsl_warn("setuid: %s\n", strerror(errno));
2151 /* initialize supported protocols */
2153 for (context->count_protocols = 0;
2154 info->protocols[context->count_protocols].callback;
2155 context->count_protocols++) {
2157 lwsl_parser(" Protocol: %s\n",
2158 info->protocols[context->count_protocols].name);
2160 info->protocols[context->count_protocols].owning_server =
2162 info->protocols[context->count_protocols].protocol_index =
2163 context->count_protocols;
2166 * inform all the protocols that they are doing their one-time
2167 * initialization if they want to
2169 info->protocols[context->count_protocols].callback(context,
2170 NULL, LWS_CALLBACK_PROTOCOL_INIT, NULL, NULL, 0);
2173 #ifndef LWS_NO_EXTENSIONS
2175 * give all extensions a chance to create any per-context
2176 * allocations they need
2179 m = LWS_EXT_CALLBACK_CLIENT_CONTEXT_CONSTRUCT;
2181 m = LWS_EXT_CALLBACK_SERVER_CONTEXT_CONSTRUCT;
2183 if (info->extensions) {
2184 ext = info->extensions;
2185 while (ext->callback) {
2186 lwsl_ext(" Extension: %s\n", ext->name);
2187 ext->callback(context, ext, NULL,
2188 (enum libwebsocket_extension_callback_reasons)m,
2197 libwebsocket_context_destroy(context);
2202 * libwebsockets_get_protocol() - Returns a protocol pointer from a websocket
2204 * @wsi: pointer to struct websocket you want to know the protocol of
2207 * Some apis can act on all live connections of a given protocol,
2208 * this is how you can get a pointer to the active protocol if needed.
2211 const struct libwebsocket_protocols *
2212 libwebsockets_get_protocol(struct libwebsocket *wsi)
2214 return wsi->protocol;
2218 libwebsocket_is_final_fragment(struct libwebsocket *wsi)
2220 return wsi->u.ws.final;
2224 libwebsocket_get_reserved_bits(struct libwebsocket *wsi)
2226 return wsi->u.ws.rsv;
2230 libwebsocket_ensure_user_space(struct libwebsocket *wsi)
2235 /* allocate the per-connection user memory (if any) */
2237 if (wsi->protocol->per_session_data_size && !wsi->user_space) {
2238 wsi->user_space = malloc(
2239 wsi->protocol->per_session_data_size);
2240 if (wsi->user_space == NULL) {
2241 lwsl_err("Out of memory for conn user space\n");
2244 memset(wsi->user_space, 0,
2245 wsi->protocol->per_session_data_size);
2250 static void lwsl_emit_stderr(int level, const char *line)
2256 gettimeofday(&tv, NULL);
2259 for (n = 0; n < LLL_COUNT; n++)
2260 if (level == (1 << n)) {
2261 sprintf(buf, "[%ld:%04d] %s: ", tv.tv_sec,
2262 (int)(tv.tv_usec / 100), log_level_names[n]);
2266 fprintf(stderr, "%s%s", buf, line);
2270 void lwsl_emit_syslog(int level, const char *line)
2272 lwsl_emit_stderr(level, line);
2275 void lwsl_emit_syslog(int level, const char *line)
2277 int syslog_level = LOG_DEBUG;
2281 syslog_level = LOG_ERR;
2284 syslog_level = LOG_WARNING;
2287 syslog_level = LOG_NOTICE;
2290 syslog_level = LOG_INFO;
2293 syslog(syslog_level, "%s", line);
2297 void _lws_log(int filter, const char *format, ...)
2302 if (!(log_level & filter))
2305 va_start(ap, format);
2306 vsnprintf(buf, sizeof(buf), format, ap);
2307 buf[sizeof(buf) - 1] = '\0';
2310 lwsl_emit(filter, buf);
2314 * lws_set_log_level() - Set the logging bitfield
2315 * @level: OR together the LLL_ debug contexts you want output from
2316 * @log_emit_function: NULL to leave it as it is, or a user-supplied
2317 * function to perform log string emission instead of
2318 * the default stderr one.
2320 * log level defaults to "err", "warn" and "notice" contexts enabled and
2321 * emission on stderr.
2324 void lws_set_log_level(int level, void (*log_emit_function)(int level,
2328 if (log_emit_function)
2329 lwsl_emit = log_emit_function;