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 #if defined(WIN32) || defined(_WIN32)
29 #ifdef LWS_BUILTIN_GETIFADDRS
30 #include <getifaddrs.h>
36 #include <sys/socket.h>
40 #ifdef LWS_OPENSSL_SUPPORT
41 int openssl_websocket_private_data_index;
45 #include "../win32port/win32helpers/websock-w32.c"
48 #include "../win32port/win32helpers/websock-w32.c"
52 #ifndef LWS_BUILD_HASH
53 #define LWS_BUILD_HASH "unknown-build-hash"
56 static int log_level = LLL_ERR | LLL_WARN | LLL_NOTICE;
57 static void lwsl_emit_stderr(int level, const char *line);
58 static void (*lwsl_emit)(int level, const char *line) = lwsl_emit_stderr;
60 static const char *library_version = LWS_LIBRARY_VERSION " " LWS_BUILD_HASH;
62 static const char * const log_level_names[] = {
76 extern int lws_client_socket_service(
77 struct libwebsocket_context *context,
78 struct libwebsocket *wsi, struct pollfd *pollfd);
81 extern int lws_server_socket_service(
82 struct libwebsocket_context *context,
83 struct libwebsocket *wsi, struct pollfd *pollfd);
87 * lws_get_library_version: get version and git hash library built from
89 * returns a const char * to a string like "1.1 178d78c"
90 * representing the library version followed by the git head hash it
94 LWS_VISIBLE const char *
95 lws_get_library_version(void)
97 return library_version;
101 insert_wsi_socket_into_fds(struct libwebsocket_context *context,
102 struct libwebsocket *wsi)
104 if (context->fds_count >= context->max_fds) {
105 lwsl_err("Too many fds (%d)\n", context->max_fds);
109 if (wsi->sock > context->max_fds) {
110 lwsl_err("Socket fd %d is too high (%d)\n",
111 wsi->sock, context->max_fds);
116 assert(wsi->sock >= 0);
118 lwsl_info("insert_wsi_socket_into_fds: wsi=%p, sock=%d, fds pos=%d\n",
119 wsi, wsi->sock, context->fds_count);
121 context->protocols[0].callback(context, wsi,
122 LWS_CALLBACK_LOCK_POLL,
123 wsi->user_space, (void *)(long)wsi->sock, 0);
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);
136 context->protocols[0].callback(context, wsi,
137 LWS_CALLBACK_UNLOCK_POLL,
138 wsi->user_space, (void *)(long)wsi->sock, 0);
144 remove_wsi_socket_from_fds(struct libwebsocket_context *context,
145 struct libwebsocket *wsi)
149 if (!--context->fds_count) {
150 context->protocols[0].callback(context, wsi,
151 LWS_CALLBACK_LOCK_POLL,
152 wsi->user_space, (void *)(long)wsi->sock, 0);
156 if (wsi->sock > context->max_fds) {
157 lwsl_err("Socket fd %d too high (%d)\n",
158 wsi->sock, context->max_fds);
162 lwsl_info("remove_wsi_socket_from_fds: wsi=%p, sock=%d, fds pos=%d\n",
163 wsi, wsi->sock, wsi->position_in_fds_table);
165 context->protocols[0].callback(context, wsi,
166 LWS_CALLBACK_LOCK_POLL,
167 wsi->user_space, (void *)(long)wsi->sock, 0);
169 m = wsi->position_in_fds_table; /* replace the contents for this */
171 /* have the last guy take up the vacant slot */
172 context->fds[m] = context->fds[context->fds_count];
174 * end guy's fds_lookup entry remains unchanged
175 * (still same fd pointing to same wsi)
177 /* end guy's "position in fds table" changed */
178 context->lws_lookup[context->fds[context->fds_count].fd]->
179 position_in_fds_table = m;
180 /* deletion guy's lws_lookup entry needs nuking */
181 context->lws_lookup[wsi->sock] = NULL;
182 /* removed wsi has no position any more */
183 wsi->position_in_fds_table = -1;
186 /* remove also from external POLL support via protocol 0 */
188 context->protocols[0].callback(context, wsi,
189 LWS_CALLBACK_DEL_POLL_FD, wsi->user_space,
190 (void *)(long)wsi->sock, 0);
192 context->protocols[0].callback(context, wsi,
193 LWS_CALLBACK_UNLOCK_POLL,
194 wsi->user_space, (void *)(long)wsi->sock, 0);
201 libwebsocket_close_and_free_session(struct libwebsocket_context *context,
202 struct libwebsocket *wsi, enum lws_close_status reason)
206 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 2 +
207 LWS_SEND_BUFFER_POST_PADDING];
208 #ifndef LWS_NO_EXTENSIONS
211 struct lws_tokens eff_buf;
212 struct libwebsocket_extension *ext;
218 old_state = wsi->state;
220 if (old_state == WSI_STATE_DEAD_SOCKET)
223 /* we tried the polite way... */
224 if (old_state == WSI_STATE_AWAITING_CLOSE_ACK)
225 goto just_kill_connection;
227 wsi->u.ws.close_reason = reason;
229 if (wsi->mode == LWS_CONNMODE_WS_CLIENT_WAITING_CONNECT ||
230 wsi->mode == LWS_CONNMODE_WS_CLIENT_ISSUE_HANDSHAKE) {
232 context->protocols[0].callback(context, wsi,
233 LWS_CALLBACK_CLIENT_CONNECTION_ERROR, NULL, NULL, 0);
236 goto just_kill_connection;
240 if (wsi->mode == LWS_CONNMODE_HTTP_SERVING_ACCEPTED) {
241 if (wsi->u.http.post_buffer) {
242 free(wsi->u.http.post_buffer);
243 wsi->u.http.post_buffer = NULL;
245 if (wsi->u.http.fd >= 0) {
246 lwsl_debug("closing http fd %d\n", wsi->u.http.fd);
247 close(wsi->u.http.fd);
249 context->protocols[0].callback(context, wsi,
250 LWS_CALLBACK_CLOSED_HTTP, wsi->user_space, NULL, 0);
254 #ifndef LWS_NO_EXTENSIONS
256 * are his extensions okay with him closing? Eg he might be a mux
257 * parent and just his ch1 aspect is closing?
260 for (n = 0; n < wsi->count_active_extensions; n++) {
261 if (!wsi->active_extensions[n]->callback)
264 m = wsi->active_extensions[n]->callback(context,
265 wsi->active_extensions[n], wsi,
266 LWS_EXT_CALLBACK_CHECK_OK_TO_REALLY_CLOSE,
267 wsi->active_extensions_user[n], NULL, 0);
270 * if somebody vetoed actually closing him at this time....
271 * up to the extension to track the attempted close, let's
276 lwsl_ext("extension vetoed close\n");
282 * flush any tx pending from extensions, since we may send close packet
283 * if there are problems with send, just nuke the connection
289 /* default to nobody has more to spill */
292 eff_buf.token = NULL;
293 eff_buf.token_len = 0;
295 /* show every extension the new incoming data */
297 for (n = 0; n < wsi->count_active_extensions; n++) {
298 m = wsi->active_extensions[n]->callback(
299 wsi->protocol->owning_server,
300 wsi->active_extensions[n], wsi,
301 LWS_EXT_CALLBACK_FLUSH_PENDING_TX,
302 wsi->active_extensions_user[n], &eff_buf, 0);
304 lwsl_ext("Extension reports fatal error\n");
305 goto just_kill_connection;
309 * at least one extension told us he has more
310 * to spill, so we will go around again after
315 /* assuming they left us something to send, send it */
317 if (eff_buf.token_len)
318 if (lws_issue_raw(wsi, (unsigned char *)eff_buf.token,
319 eff_buf.token_len) != eff_buf.token_len) {
320 lwsl_debug("close: ext spill failed\n");
321 goto just_kill_connection;
327 * signal we are closing, libsocket_write will
328 * add any necessary version-specific stuff. If the write fails,
329 * no worries we are closing anyway. If we didn't initiate this
330 * close, then our state has been changed to
331 * WSI_STATE_RETURNED_CLOSE_ALREADY and we will skip this.
333 * Likewise if it's a second call to close this connection after we
334 * sent the close indication to the peer already, we are in state
335 * WSI_STATE_AWAITING_CLOSE_ACK and will skip doing this a second time.
338 if (old_state == WSI_STATE_ESTABLISHED &&
339 reason != LWS_CLOSE_STATUS_NOSTATUS) {
341 lwsl_debug("sending close indication...\n");
343 /* make valgrind happy */
344 memset(buf, 0, sizeof(buf));
345 n = libwebsocket_write(wsi,
346 &buf[LWS_SEND_BUFFER_PRE_PADDING + 2],
350 * we have sent a nice protocol level indication we
351 * now wish to close, we should not send anything more
354 wsi->state = WSI_STATE_AWAITING_CLOSE_ACK;
357 * ...and we should wait for a reply for a bit
361 libwebsocket_set_timeout(wsi,
362 PENDING_TIMEOUT_CLOSE_ACK, 1);
364 lwsl_debug("sent close indication, awaiting ack\n");
369 lwsl_info("close: sending close packet failed, hanging up\n");
371 /* else, the send failed and we should just hang up */
374 just_kill_connection:
376 lwsl_debug("close: just_kill_connection\n");
379 * we won't be servicing or receiving anything further from this guy
380 * delete socket from the internal poll list if still present
383 remove_wsi_socket_from_fds(context, wsi);
385 wsi->state = WSI_STATE_DEAD_SOCKET;
387 if ((old_state == WSI_STATE_ESTABLISHED ||
388 wsi->mode == LWS_CONNMODE_WS_SERVING ||
389 wsi->mode == LWS_CONNMODE_WS_CLIENT)) {
391 if (wsi->u.ws.rx_user_buffer) {
392 free(wsi->u.ws.rx_user_buffer);
393 wsi->u.ws.rx_user_buffer = NULL;
395 if (wsi->u.ws.rxflow_buffer) {
396 free(wsi->u.ws.rxflow_buffer);
397 wsi->u.ws.rxflow_buffer = NULL;
399 if (wsi->truncated_send_malloc) {
400 /* not going to be completed... nuke it */
401 free(wsi->truncated_send_malloc);
402 wsi->truncated_send_malloc = NULL;
406 /* tell the user it's all over for this guy */
408 if (wsi->protocol && wsi->protocol->callback &&
409 ((old_state == WSI_STATE_ESTABLISHED) ||
410 (old_state == WSI_STATE_RETURNED_CLOSE_ALREADY) ||
411 (old_state == WSI_STATE_AWAITING_CLOSE_ACK))) {
412 lwsl_debug("calling back CLOSED\n");
413 wsi->protocol->callback(context, wsi, LWS_CALLBACK_CLOSED,
414 wsi->user_space, NULL, 0);
415 } else if ( wsi->mode == LWS_CONNMODE_HTTP_SERVING_ACCEPTED ) {
416 lwsl_debug("calling back CLOSED_HTTP\n");
417 context->protocols[0].callback(context, wsi,
418 LWS_CALLBACK_CLOSED_HTTP, wsi->user_space, NULL, 0 );
420 lwsl_debug("not calling back closed\n");
422 #ifndef LWS_NO_EXTENSIONS
423 /* deallocate any active extension contexts */
425 for (n = 0; n < wsi->count_active_extensions; n++) {
426 if (!wsi->active_extensions[n]->callback)
429 wsi->active_extensions[n]->callback(context,
430 wsi->active_extensions[n], wsi,
431 LWS_EXT_CALLBACK_DESTROY,
432 wsi->active_extensions_user[n], NULL, 0);
434 free(wsi->active_extensions_user[n]);
438 * inform all extensions in case they tracked this guy out of band
439 * even though not active on him specifically
442 ext = context->extensions;
443 while (ext && ext->callback) {
444 ext->callback(context, ext, wsi,
445 LWS_EXT_CALLBACK_DESTROY_ANY_WSI_CLOSING,
451 /* lwsl_info("closing fd=%d\n", wsi->sock); */
453 #ifdef LWS_OPENSSL_SUPPORT
455 n = SSL_get_fd(wsi->ssl);
456 SSL_shutdown(wsi->ssl);
462 n = shutdown(wsi->sock, SHUT_RDWR);
464 lwsl_debug("closing: shutdown returned %d\n",
467 n = compatible_close(wsi->sock);
469 lwsl_debug("closing: close returned %d\n",
472 #ifdef LWS_OPENSSL_SUPPORT
475 if (wsi->protocol && wsi->protocol->per_session_data_size &&
476 wsi->user_space) /* user code may own */
477 free(wsi->user_space);
483 * libwebsockets_get_peer_addresses() - Get client address information
484 * @context: Libwebsockets context
485 * @wsi: Local struct libwebsocket associated with
486 * @fd: Connection socket descriptor
487 * @name: Buffer to take client address name
488 * @name_len: Length of client address name buffer
489 * @rip: Buffer to take client address IP qotted quad
490 * @rip_len: Length of client address IP buffer
492 * This function fills in @name and @rip with the name and IP of
493 * the client connected with socket descriptor @fd. Names may be
494 * truncated if there is not enough room. If either cannot be
495 * determined, they will be returned as valid zero-length strings.
499 libwebsockets_get_peer_addresses(struct libwebsocket_context *context,
500 struct libwebsocket *wsi, int fd, char *name, int name_len,
501 char *rip, int rip_len)
504 struct sockaddr_in sin;
505 struct hostent *host;
506 struct hostent *host1;
512 struct sockaddr_un *un;
518 lws_latency_pre(context, wsi);
521 if (getpeername(fd, (struct sockaddr *) &sin, &len) < 0) {
522 perror("getpeername");
526 host = gethostbyaddr((char *) &sin.sin_addr, sizeof(sin.sin_addr),
529 perror("gethostbyaddr");
533 strncpy(name, host->h_name, name_len);
534 name[name_len - 1] = '\0';
536 host1 = gethostbyname(host->h_name);
539 p = (unsigned char *)host1;
542 p = (unsigned char *)host1->h_addr_list[n++];
545 if ((host1->h_addrtype != AF_INET)
547 && (host1->h_addrtype != AF_LOCAL)
552 if (host1->h_addrtype == AF_INET)
553 sprintf(ip, "%u.%u.%u.%u", p[0], p[1], p[2], p[3]);
556 un = (struct sockaddr_un *)p;
557 strncpy(ip, un->sun_path, sizeof(ip) - 1);
558 ip[sizeof(ip) - 1] = '\0';
562 strncpy(rip, ip, rip_len);
563 rip[rip_len - 1] = '\0';
568 lws_latency(context, wsi, "libwebsockets_get_peer_addresses", ret, 1);
571 LWS_VISIBLE int libwebsockets_get_random(struct libwebsocket_context *context,
575 char *p = (char *)buf;
577 #if defined(WIN32) || defined(_WIN32)
578 for (n = 0; n < len; n++)
579 p[n] = (unsigned char)rand();
581 n = read(context->fd_random, p, len);
587 int lws_set_socket_options(struct libwebsocket_context *context, int fd)
590 socklen_t optlen = sizeof(optval);
591 #if defined(WIN32) || defined(_WIN32)
592 unsigned long optl = 0;
594 #if defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__)
595 struct protoent *tcp_proto;
598 if (context->ka_time) {
599 /* enable keepalive on this socket */
601 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE,
602 (const void *)&optval, optlen) < 0)
605 #if defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__CYGWIN__)
608 * didn't find a way to set these per-socket, need to
609 * tune kernel systemwide values
614 struct tcp_keepalive alive;
616 alive.keepalivetime = context->ka_time;
617 alive.keepaliveinterval = context->ka_interval;
619 if (WSAIoctl(fd, SIO_KEEPALIVE_VALS, &alive, sizeof(alive),
620 NULL, 0, &dwBytesRet, NULL, NULL))
624 /* set the keepalive conditions we want on it too */
625 optval = context->ka_time;
626 if (setsockopt(fd, IPPROTO_IP, TCP_KEEPIDLE,
627 (const void *)&optval, optlen) < 0)
630 optval = context->ka_interval;
631 if (setsockopt(fd, IPPROTO_IP, TCP_KEEPINTVL,
632 (const void *)&optval, optlen) < 0)
635 optval = context->ka_probes;
636 if (setsockopt(fd, IPPROTO_IP, TCP_KEEPCNT,
637 (const void *)&optval, optlen) < 0)
644 #if !defined(__APPLE__) && !defined(__FreeBSD__) && !defined(__NetBSD__)
645 setsockopt(fd, SOL_TCP, TCP_NODELAY, (const void *)&optval, optlen);
647 tcp_proto = getprotobyname("TCP");
648 setsockopt(fd, tcp_proto->p_proto, TCP_NODELAY, &optval, optlen);
651 /* We are nonblocking... */
652 #if defined(WIN32) || defined(_WIN32)
653 ioctlsocket(fd, FIONBIO, &optl);
655 fcntl(fd, F_SETFL, O_NONBLOCK);
661 LWS_VISIBLE int lws_send_pipe_choked(struct libwebsocket *wsi)
665 /* treat the fact we got a truncated send pending as if we're choked */
666 if (wsi->truncated_send_malloc)
670 fds.events = POLLOUT;
673 if (poll(&fds, 1, 0) != 1)
676 if ((fds.revents & POLLOUT) == 0)
679 /* okay to send another packet without blocking */
685 lws_handle_POLLOUT_event(struct libwebsocket_context *context,
686 struct libwebsocket *wsi, struct pollfd *pollfd)
690 #ifndef LWS_NO_EXTENSIONS
691 struct lws_tokens eff_buf;
696 /* pending truncated sends have uber priority */
698 if (wsi->truncated_send_malloc) {
699 lws_issue_raw(wsi, wsi->truncated_send_malloc +
700 wsi->truncated_send_offset,
701 wsi->truncated_send_len);
702 /* leave POLLOUT active either way */
706 for (n = 0; n < wsi->count_active_extensions; n++) {
707 if (!wsi->active_extensions[n]->callback)
710 m = wsi->active_extensions[n]->callback(context,
711 wsi->active_extensions[n], wsi,
712 LWS_EXT_CALLBACK_IS_WRITEABLE,
713 wsi->active_extensions_user[n], NULL, 0);
721 if (!wsi->extension_data_pending || handled == 2)
725 * check in on the active extensions, see if they
726 * had pending stuff to spill... they need to get the
727 * first look-in otherwise sequence will be disordered
729 * NULL, zero-length eff_buf means just spill pending
735 /* default to nobody has more to spill */
738 eff_buf.token = NULL;
739 eff_buf.token_len = 0;
741 /* give every extension a chance to spill */
743 for (n = 0; n < wsi->count_active_extensions; n++) {
744 m = wsi->active_extensions[n]->callback(
745 wsi->protocol->owning_server,
746 wsi->active_extensions[n], wsi,
747 LWS_EXT_CALLBACK_PACKET_TX_PRESEND,
748 wsi->active_extensions_user[n], &eff_buf, 0);
750 lwsl_err("ext reports fatal error\n");
755 * at least one extension told us he has more
756 * to spill, so we will go around again after
761 /* assuming they gave us something to send, send it */
763 if (eff_buf.token_len) {
764 n = lws_issue_raw(wsi, (unsigned char *)eff_buf.token,
769 * Keep amount spilled small to minimize chance of this
771 if (n != eff_buf.token_len) {
772 lwsl_err("Unable to spill ext %d vs %s\n",
773 eff_buf.token_len, n);
779 /* no extension has more to spill */
785 * There's more to spill from an extension, but we just sent
786 * something... did that leave the pipe choked?
789 if (!lws_send_pipe_choked(wsi))
790 /* no we could add more */
793 lwsl_info("choked in POLLOUT service\n");
796 * Yes, he's choked. Leave the POLLOUT masked on so we will
797 * come back here when he is unchoked. Don't call the user
798 * callback to enforce ordering of spilling, he'll get called
799 * when we come back here and there's nothing more to spill.
805 wsi->extension_data_pending = 0;
813 context->protocols[0].callback(context, wsi,
814 LWS_CALLBACK_LOCK_POLL,
815 wsi->user_space, (void *)(long)wsi->sock, 0);
817 pollfd->events &= ~POLLOUT;
819 /* external POLL support via protocol 0 */
820 context->protocols[0].callback(context, wsi,
821 LWS_CALLBACK_CLEAR_MODE_POLL_FD,
822 wsi->user_space, (void *)(long)wsi->sock, POLLOUT);
824 context->protocols[0].callback(context, wsi,
825 LWS_CALLBACK_UNLOCK_POLL,
826 wsi->user_space, (void *)(long)wsi->sock, 0);
828 #ifndef LWS_NO_EXTENSIONS
832 if (wsi->mode == LWS_CONNMODE_WS_CLIENT)
833 n = LWS_CALLBACK_CLIENT_WRITEABLE;
835 n = LWS_CALLBACK_SERVER_WRITEABLE;
837 return user_callback_handle_rxflow(wsi->protocol->callback, context,
838 wsi, (enum libwebsocket_callback_reasons) n,
839 wsi->user_space, NULL, 0);
845 libwebsocket_service_timeout_check(struct libwebsocket_context *context,
846 struct libwebsocket *wsi, unsigned int sec)
848 #ifndef LWS_NO_EXTENSIONS
852 * if extensions want in on it (eg, we are a mux parent)
853 * give them a chance to service child timeouts
856 for (n = 0; n < wsi->count_active_extensions; n++)
857 wsi->active_extensions[n]->callback(
858 context, wsi->active_extensions[n],
859 wsi, LWS_EXT_CALLBACK_1HZ,
860 wsi->active_extensions_user[n], NULL, sec);
863 if (!wsi->pending_timeout)
867 * if we went beyond the allowed time, kill the
871 if (sec > wsi->pending_timeout_limit) {
872 lwsl_info("TIMEDOUT WAITING\n");
873 libwebsocket_close_and_free_session(context,
874 wsi, LWS_CLOSE_STATUS_NOSTATUS);
882 * libwebsocket_service_fd() - Service polled socket with something waiting
883 * @context: Websocket context
884 * @pollfd: The pollfd entry describing the socket fd and which events
887 * This function takes a pollfd that has POLLIN or POLLOUT activity and
888 * services it according to the state of the associated
889 * struct libwebsocket.
891 * The one call deals with all "service" that might happen on a socket
892 * including listen accepts, http files as well as websocket protocol.
894 * If a pollfd says it has something, you can just pass it to
895 * libwebsocket_serice_fd() whether it is a socket handled by lws or not.
896 * If it sees it is a lws socket, the traffic will be handled and
897 * pollfd->revents will be zeroed now.
899 * If the socket is foreign to lws, it leaves revents alone. So you can
900 * see if you should service yourself by checking the pollfd revents
901 * after letting lws try to service it.
905 libwebsocket_service_fd(struct libwebsocket_context *context,
906 struct pollfd *pollfd)
908 struct libwebsocket *wsi;
911 int listen_socket_fds_index = 0;
915 char draining_flow = 0;
917 #ifndef LWS_NO_EXTENSIONS
920 struct lws_tokens eff_buf;
922 if (context->listen_service_fd)
923 listen_socket_fds_index = context->lws_lookup[
924 context->listen_service_fd]->position_in_fds_table;
927 * you can call us with pollfd = NULL to just allow the once-per-second
928 * global timeout checks; if less than a second since the last check
929 * it returns immediately then.
932 gettimeofday(&tv, NULL);
934 if (context->last_timeout_check_s != tv.tv_sec) {
935 context->last_timeout_check_s = tv.tv_sec;
938 /* if our parent went down, don't linger around */
939 if (context->started_with_parent &&
940 kill(context->started_with_parent, 0) < 0)
941 kill(getpid(), SIGTERM);
944 /* global timeout check once per second */
949 for (n = 0; n < context->fds_count; n++) {
950 m = context->fds[n].fd;
951 wsi = context->lws_lookup[m];
955 if (libwebsocket_service_timeout_check(context, wsi,
957 /* he did time out... */
959 /* it was the guy we came to service! */
961 /* mark as handled */
967 /* the socket we came to service timed out, nothing to do */
971 /* just here for timeout management? */
975 /* no, here to service a socket descriptor */
976 wsi = context->lws_lookup[pollfd->fd];
978 /* not lws connection ... leave revents alone and return */
982 * so that caller can tell we handled, past here we need to
983 * zero down pollfd->revents after handling
987 * deal with listen service piggybacking
988 * every listen_service_modulo services of other fds, we
989 * sneak one in to service the listen socket if there's anything waiting
991 * To handle connection storms, as found in ab, if we previously saw a
992 * pending connection here, it causes us to check again next time.
995 if (context->listen_service_fd && pollfd !=
996 &context->fds[listen_socket_fds_index]) {
997 context->listen_service_count++;
998 if (context->listen_service_extraseen ||
999 context->listen_service_count ==
1000 context->listen_service_modulo) {
1001 context->listen_service_count = 0;
1003 if (context->listen_service_extraseen > 5)
1007 * even with extpoll, we prepared this
1008 * internal fds for listen
1010 n = poll(&context->fds[listen_socket_fds_index],
1012 if (n > 0) { /* there's a conn waiting for us */
1013 libwebsocket_service_fd(context,
1015 fds[listen_socket_fds_index]);
1016 context->listen_service_extraseen++;
1018 if (context->listen_service_extraseen)
1020 listen_service_extraseen--;
1028 /* handle session socket closed */
1030 if ((!(pollfd->revents & POLLIN)) &&
1031 (pollfd->revents & (POLLERR | POLLHUP))) {
1033 lwsl_debug("Session Socket %p (fd=%d) dead\n",
1034 (void *)wsi, pollfd->fd);
1036 goto close_and_handled;
1039 /* okay, what we came here to do... */
1041 switch (wsi->mode) {
1043 #ifndef LWS_NO_SERVER
1044 case LWS_CONNMODE_HTTP_SERVING:
1045 case LWS_CONNMODE_HTTP_SERVING_ACCEPTED:
1046 case LWS_CONNMODE_SERVER_LISTENER:
1047 case LWS_CONNMODE_SSL_ACK_PENDING:
1048 n = lws_server_socket_service(context, wsi, pollfd);
1052 case LWS_CONNMODE_WS_SERVING:
1053 case LWS_CONNMODE_WS_CLIENT:
1055 /* the guy requested a callback when it was OK to write */
1057 if ((pollfd->revents & POLLOUT) &&
1058 wsi->state == WSI_STATE_ESTABLISHED &&
1059 lws_handle_POLLOUT_event(context, wsi, pollfd) < 0) {
1060 lwsl_info("libwebsocket_service_fd: closing\n");
1061 goto close_and_handled;
1064 if (wsi->u.ws.rxflow_buffer &&
1065 (wsi->u.ws.rxflow_change_to & LWS_RXFLOW_ALLOW)) {
1066 lwsl_info("draining rxflow\n");
1067 /* well, drain it */
1068 eff_buf.token = (char *)wsi->u.ws.rxflow_buffer +
1069 wsi->u.ws.rxflow_pos;
1070 eff_buf.token_len = wsi->u.ws.rxflow_len -
1071 wsi->u.ws.rxflow_pos;
1076 /* any incoming data ready? */
1078 if (!(pollfd->revents & POLLIN))
1081 #ifdef LWS_OPENSSL_SUPPORT
1084 eff_buf.token_len = SSL_read(wsi->ssl,
1085 context->service_buffer,
1086 sizeof(context->service_buffer));
1087 if (!eff_buf.token_len) {
1088 n = SSL_get_error(wsi->ssl, eff_buf.token_len);
1089 lwsl_err("SSL_read returned 0 with reason %s\n",
1091 (char *)context->service_buffer));
1095 eff_buf.token_len = recv(pollfd->fd,
1096 context->service_buffer,
1097 sizeof(context->service_buffer), 0);
1099 if (eff_buf.token_len < 0) {
1100 lwsl_debug("service_fd read ret = %d, errno = %d\n",
1101 eff_buf.token_len, errno);
1102 if (errno != EINTR && errno != EAGAIN)
1103 goto close_and_handled;
1107 if (!eff_buf.token_len) {
1108 lwsl_info("service_fd: closing due to 0 length read\n");
1109 goto close_and_handled;
1113 * give any active extensions a chance to munge the buffer
1114 * before parse. We pass in a pointer to an lws_tokens struct
1115 * prepared with the default buffer and content length that's in
1116 * there. Rather than rewrite the default buffer, extensions
1117 * that expect to grow the buffer can adapt .token to
1118 * point to their own per-connection buffer in the extension
1119 * user allocation. By default with no extensions or no
1120 * extension callback handling, just the normal input buffer is
1121 * used then so it is efficient.
1124 eff_buf.token = (char *)context->service_buffer;
1126 #ifndef LWS_NO_EXTENSIONS
1132 for (n = 0; n < wsi->count_active_extensions; n++) {
1133 m = wsi->active_extensions[n]->callback(context,
1134 wsi->active_extensions[n], wsi,
1135 LWS_EXT_CALLBACK_PACKET_RX_PREPARSE,
1136 wsi->active_extensions_user[n],
1140 "Extension reports fatal error\n");
1141 goto close_and_handled;
1147 /* service incoming data */
1149 if (eff_buf.token_len) {
1150 n = libwebsocket_read(context, wsi,
1151 (unsigned char *)eff_buf.token,
1159 #ifndef LWS_NO_EXTENSIONS
1160 eff_buf.token = NULL;
1161 eff_buf.token_len = 0;
1164 if (draining_flow && wsi->u.ws.rxflow_buffer &&
1165 wsi->u.ws.rxflow_pos == wsi->u.ws.rxflow_len) {
1166 lwsl_info("flow buffer: drained\n");
1167 free(wsi->u.ws.rxflow_buffer);
1168 wsi->u.ws.rxflow_buffer = NULL;
1169 /* having drained the rxflow buffer, can rearm POLLIN */
1170 _libwebsocket_rx_flow_control(wsi);
1173 #ifdef LWS_OPENSSL_SUPPORT
1174 if (wsi->ssl && SSL_pending(wsi->ssl))
1180 #ifdef LWS_NO_CLIENT
1183 n = lws_client_socket_service(context, wsi, pollfd);
1192 libwebsocket_close_and_free_session(context, wsi,
1193 LWS_CLOSE_STATUS_NOSTATUS);
1197 pollfd->revents = 0;
1203 * libwebsocket_context_destroy() - Destroy the websocket context
1204 * @context: Websocket context
1206 * This function closes any active connections and then frees the
1207 * context. After calling this, any further use of the context is
1211 libwebsocket_context_destroy(struct libwebsocket_context *context)
1213 #ifndef LWS_NO_EXTENSIONS
1216 struct libwebsocket_extension *ext;
1217 struct libwebsocket_protocols *protocol = context->protocols;
1220 if (context->worst_latency_info[0])
1221 lwsl_notice("Worst latency: %s\n", context->worst_latency_info);
1224 for (n = 0; n < context->fds_count; n++) {
1225 struct libwebsocket *wsi =
1226 context->lws_lookup[context->fds[n].fd];
1227 libwebsocket_close_and_free_session(context,
1228 wsi, LWS_CLOSE_STATUS_NOSTATUS /* no protocol close */);
1233 * give all extensions a chance to clean up any per-context
1234 * allocations they might have made
1237 ext = context->extensions;
1238 m = LWS_EXT_CALLBACK_CLIENT_CONTEXT_DESTRUCT;
1239 if (context->listen_port)
1240 m = LWS_EXT_CALLBACK_SERVER_CONTEXT_DESTRUCT;
1241 while (ext && ext->callback) {
1242 ext->callback(context, ext, NULL,
1243 (enum libwebsocket_extension_callback_reasons)m,
1249 * inform all the protocols that they are done and will have no more
1253 while (protocol->callback) {
1254 protocol->callback(context, NULL, LWS_CALLBACK_PROTOCOL_DESTROY,
1261 #if defined(WIN32) || defined(_WIN32)
1263 close(context->fd_random);
1266 #ifdef LWS_OPENSSL_SUPPORT
1267 if (context->ssl_ctx)
1268 SSL_CTX_free(context->ssl_ctx);
1269 if (context->ssl_client_ctx)
1270 SSL_CTX_free(context->ssl_client_ctx);
1272 ERR_remove_state(0);
1275 CRYPTO_cleanup_all_ex_data();
1280 if (context->lws_lookup)
1281 free(context->lws_lookup);
1285 #if defined(WIN32) || defined(_WIN32)
1291 * libwebsocket_context_user() - get the user data associated with the context
1292 * @context: Websocket context
1294 * This returns the optional user allocation that can be attached to
1295 * the context the sockets live in at context_create time. It's a way
1296 * to let all sockets serviced in the same context share data without
1297 * using globals statics in the user code.
1300 libwebsocket_context_user(struct libwebsocket_context *context)
1302 return context->user_space;
1306 * libwebsocket_service() - Service any pending websocket activity
1307 * @context: Websocket context
1308 * @timeout_ms: Timeout for poll; 0 means return immediately if nothing needed
1309 * service otherwise block and service immediately, returning
1310 * after the timeout if nothing needed service.
1312 * This function deals with any pending websocket traffic, for three
1313 * kinds of event. It handles these events on both server and client
1314 * types of connection the same.
1316 * 1) Accept new connections to our context's server
1318 * 2) Call the receive callback for incoming frame data received by
1319 * server or client connections.
1321 * You need to call this service function periodically to all the above
1322 * functions to happen; if your application is single-threaded you can
1323 * just call it in your main event loop.
1325 * Alternatively you can fork a new process that asynchronously handles
1326 * calling this service in a loop. In that case you are happy if this
1327 * call blocks your thread until it needs to take care of something and
1328 * would call it with a large nonzero timeout. Your loop then takes no
1329 * CPU while there is nothing happening.
1331 * If you are calling it in a single-threaded app, you don't want it to
1332 * wait around blocking other things in your loop from happening, so you
1333 * would call it with a timeout_ms of 0, so it returns immediately if
1334 * nothing is pending, or as soon as it services whatever was pending.
1338 libwebsocket_service(struct libwebsocket_context *context, int timeout_ms)
1343 /* stay dead once we are dead */
1345 if (context == NULL)
1348 /* wait for something to need service */
1350 n = poll(context->fds, context->fds_count, timeout_ms);
1351 if (n == 0) /* poll timeout */ {
1352 libwebsocket_service_fd(context, NULL);
1359 /* any socket with events to service? */
1361 for (n = 0; n < context->fds_count; n++) {
1362 if (!context->fds[n].revents)
1364 m = libwebsocket_service_fd(context, &context->fds[n]);
1367 /* if something closed, retry this slot */
1375 #ifndef LWS_NO_EXTENSIONS
1377 lws_any_extension_handled(struct libwebsocket_context *context,
1378 struct libwebsocket *wsi,
1379 enum libwebsocket_extension_callback_reasons r,
1380 void *v, size_t len)
1385 /* maybe an extension will take care of it for us */
1387 for (n = 0; n < wsi->count_active_extensions && !handled; n++) {
1388 if (!wsi->active_extensions[n]->callback)
1391 handled |= wsi->active_extensions[n]->callback(context,
1392 wsi->active_extensions[n], wsi,
1393 r, wsi->active_extensions_user[n], v, len);
1401 lws_get_extension_user_matching_ext(struct libwebsocket *wsi,
1402 struct libwebsocket_extension *ext)
1409 while (n < wsi->count_active_extensions) {
1410 if (wsi->active_extensions[n] != ext) {
1414 return wsi->active_extensions_user[n];
1422 * libwebsocket_callback_on_writable() - Request a callback when this socket
1423 * becomes able to be written to without
1426 * @context: libwebsockets context
1427 * @wsi: Websocket connection instance to get callback for
1431 libwebsocket_callback_on_writable(struct libwebsocket_context *context,
1432 struct libwebsocket *wsi)
1434 #ifndef LWS_NO_EXTENSIONS
1438 /* maybe an extension will take care of it for us */
1440 for (n = 0; n < wsi->count_active_extensions; n++) {
1441 if (!wsi->active_extensions[n]->callback)
1444 handled |= wsi->active_extensions[n]->callback(context,
1445 wsi->active_extensions[n], wsi,
1446 LWS_EXT_CALLBACK_REQUEST_ON_WRITEABLE,
1447 wsi->active_extensions_user[n], NULL, 0);
1453 if (wsi->position_in_fds_table < 0) {
1454 lwsl_err("libwebsocket_callback_on_writable: failed to find socket %d\n",
1459 context->protocols[0].callback(context, wsi,
1460 LWS_CALLBACK_LOCK_POLL,
1461 wsi->user_space, (void *)(long)wsi->sock, 0);
1463 context->fds[wsi->position_in_fds_table].events |= POLLOUT;
1465 /* external POLL support via protocol 0 */
1466 context->protocols[0].callback(context, wsi,
1467 LWS_CALLBACK_SET_MODE_POLL_FD,
1468 wsi->user_space, (void *)(long)wsi->sock, POLLOUT);
1470 context->protocols[0].callback(context, wsi,
1471 LWS_CALLBACK_UNLOCK_POLL,
1472 wsi->user_space, (void *)(long)wsi->sock, 0);
1478 * libwebsocket_callback_on_writable_all_protocol() - Request a callback for
1479 * all connections using the given protocol when it
1480 * becomes possible to write to each socket without
1483 * @protocol: Protocol whose connections will get callbacks
1487 libwebsocket_callback_on_writable_all_protocol(
1488 const struct libwebsocket_protocols *protocol)
1490 struct libwebsocket_context *context = protocol->owning_server;
1492 struct libwebsocket *wsi;
1494 for (n = 0; n < context->fds_count; n++) {
1495 wsi = context->lws_lookup[context->fds[n].fd];
1498 if (wsi->protocol == protocol)
1499 libwebsocket_callback_on_writable(context, wsi);
1506 * libwebsocket_set_timeout() - marks the wsi as subject to a timeout
1508 * You will not need this unless you are doing something special
1510 * @wsi: Websocket connection instance
1511 * @reason: timeout reason
1512 * @secs: how many seconds
1516 libwebsocket_set_timeout(struct libwebsocket *wsi,
1517 enum pending_timeout reason, int secs)
1521 gettimeofday(&tv, NULL);
1523 wsi->pending_timeout_limit = tv.tv_sec + secs;
1524 wsi->pending_timeout = reason;
1529 * libwebsocket_get_socket_fd() - returns the socket file descriptor
1531 * You will not need this unless you are doing something special
1533 * @wsi: Websocket connection instance
1537 libwebsocket_get_socket_fd(struct libwebsocket *wsi)
1544 lws_latency(struct libwebsocket_context *context, struct libwebsocket *wsi,
1545 const char *action, int ret, int completed)
1551 gettimeofday(&tv, NULL);
1553 u = (tv.tv_sec * 1000000) + tv.tv_usec;
1557 if (wsi->action_start == wsi->latency_start)
1559 "Completion first try lat %luus: %p: ret %d: %s\n",
1560 u - wsi->latency_start,
1561 (void *)wsi, ret, action);
1564 "Completion %luus: lat %luus: %p: ret %d: %s\n",
1565 u - wsi->action_start,
1566 u - wsi->latency_start,
1567 (void *)wsi, ret, action);
1568 wsi->action_start = 0;
1570 sprintf(buf, "lat %luus: %p: ret %d: %s\n",
1571 u - wsi->latency_start,
1572 (void *)wsi, ret, action);
1573 if (u - wsi->latency_start > context->worst_latency) {
1574 context->worst_latency = u - wsi->latency_start;
1575 strcpy(context->worst_latency_info, buf);
1577 lwsl_latency("%s", buf);
1579 wsi->latency_start = u;
1580 if (!wsi->action_start)
1581 wsi->action_start = u;
1586 #ifdef LWS_NO_SERVER
1588 _libwebsocket_rx_flow_control(struct libwebsocket *wsi)
1594 _libwebsocket_rx_flow_control(struct libwebsocket *wsi)
1596 struct libwebsocket_context *context = wsi->protocol->owning_server;
1598 /* there is no pending change */
1599 if (!(wsi->u.ws.rxflow_change_to & LWS_RXFLOW_PENDING_CHANGE))
1602 /* stuff is still buffered, not ready to really accept new input */
1603 if (wsi->u.ws.rxflow_buffer) {
1604 /* get ourselves called back to deal with stashed buffer */
1605 libwebsocket_callback_on_writable(context, wsi);
1609 /* pending is cleared, we can change rxflow state */
1611 wsi->u.ws.rxflow_change_to &= ~LWS_RXFLOW_PENDING_CHANGE;
1613 lwsl_info("rxflow: wsi %p change_to %d\n", wsi,
1614 wsi->u.ws.rxflow_change_to & LWS_RXFLOW_ALLOW);
1616 /* adjust the pollfd for this wsi */
1618 context->protocols[0].callback(context, wsi,
1619 LWS_CALLBACK_LOCK_POLL,
1620 wsi->user_space, (void *)(long)wsi->sock, 0);
1622 if (wsi->u.ws.rxflow_change_to & LWS_RXFLOW_ALLOW)
1623 context->fds[wsi->position_in_fds_table].events |= POLLIN;
1625 context->fds[wsi->position_in_fds_table].events &= ~POLLIN;
1627 if (wsi->u.ws.rxflow_change_to & LWS_RXFLOW_ALLOW)
1628 /* external POLL support via protocol 0 */
1629 context->protocols[0].callback(context, wsi,
1630 LWS_CALLBACK_SET_MODE_POLL_FD,
1631 wsi->user_space, (void *)(long)wsi->sock, POLLIN);
1633 /* external POLL support via protocol 0 */
1634 context->protocols[0].callback(context, wsi,
1635 LWS_CALLBACK_CLEAR_MODE_POLL_FD,
1636 wsi->user_space, (void *)(long)wsi->sock, POLLIN);
1638 context->protocols[0].callback(context, wsi,
1639 LWS_CALLBACK_UNLOCK_POLL,
1640 wsi->user_space, (void *)(long)wsi->sock, 0);
1647 * libwebsocket_rx_flow_control() - Enable and disable socket servicing for
1648 * receieved packets.
1650 * If the output side of a server process becomes choked, this allows flow
1651 * control for the input side.
1653 * @wsi: Websocket connection instance to get callback for
1654 * @enable: 0 = disable read servicing for this connection, 1 = enable
1658 libwebsocket_rx_flow_control(struct libwebsocket *wsi, int enable)
1660 if (enable == (wsi->u.ws.rxflow_change_to & LWS_RXFLOW_ALLOW))
1663 lwsl_info("libwebsocket_rx_flow_control(0x%p, %d)\n", wsi, enable);
1664 wsi->u.ws.rxflow_change_to = LWS_RXFLOW_PENDING_CHANGE | !!enable;
1670 * libwebsocket_rx_flow_allow_all_protocol() - Allow all connections with this protocol to receive
1672 * When the user server code realizes it can accept more input, it can
1673 * call this to have the RX flow restriction removed from all connections using
1674 * the given protocol.
1676 * @protocol: all connections using this protocol will be allowed to receive
1680 libwebsocket_rx_flow_allow_all_protocol(
1681 const struct libwebsocket_protocols *protocol)
1683 struct libwebsocket_context *context = protocol->owning_server;
1685 struct libwebsocket *wsi;
1687 for (n = 0; n < context->fds_count; n++) {
1688 wsi = context->lws_lookup[context->fds[n].fd];
1691 if (wsi->protocol == protocol)
1692 libwebsocket_rx_flow_control(wsi, LWS_RXFLOW_ALLOW);
1698 * libwebsocket_canonical_hostname() - returns this host's hostname
1700 * This is typically used by client code to fill in the host parameter
1701 * when making a client connection. You can only call it after the context
1704 * @context: Websocket context
1708 LWS_VISIBLE extern const char *
1709 libwebsocket_canonical_hostname(struct libwebsocket_context *context)
1711 return (const char *)context->canonical_hostname;
1715 static void sigpipe_handler(int x)
1719 #ifdef LWS_OPENSSL_SUPPORT
1721 OpenSSL_verify_callback(int preverify_ok, X509_STORE_CTX *x509_ctx)
1726 struct libwebsocket_context *context;
1728 ssl = X509_STORE_CTX_get_ex_data(x509_ctx,
1729 SSL_get_ex_data_X509_STORE_CTX_idx());
1732 * !!! nasty openssl requires the index to come as a library-scope
1735 context = SSL_get_ex_data(ssl, openssl_websocket_private_data_index);
1737 n = context->protocols[0].callback(NULL, NULL,
1738 LWS_CALLBACK_OPENSSL_PERFORM_CLIENT_CERT_VERIFICATION,
1739 x509_ctx, ssl, preverify_ok);
1741 /* convert return code from 0 = OK to 1 = OK */
1752 int user_callback_handle_rxflow(callback_function callback_function,
1753 struct libwebsocket_context *context,
1754 struct libwebsocket *wsi,
1755 enum libwebsocket_callback_reasons reason, void *user,
1756 void *in, size_t len)
1760 n = callback_function(context, wsi, reason, user, in, len);
1762 n = _libwebsocket_rx_flow_control(wsi);
1769 * libwebsocket_create_context() - Create the websocket handler
1770 * @info: pointer to struct with parameters
1772 * This function creates the listening socket (if serving) and takes care
1773 * of all initialization in one step.
1775 * After initialization, it returns a struct libwebsocket_context * that
1776 * represents this server. After calling, user code needs to take care
1777 * of calling libwebsocket_service() with the context pointer to get the
1778 * server's sockets serviced. This can be done in the same process context
1779 * or a forked process, or another thread,
1781 * The protocol callback functions are called for a handful of events
1782 * including http requests coming in, websocket connections becoming
1783 * established, and data arriving; it's also called periodically to allow
1784 * async transmission.
1786 * HTTP requests are sent always to the FIRST protocol in @protocol, since
1787 * at that time websocket protocol has not been negotiated. Other
1788 * protocols after the first one never see any HTTP callack activity.
1790 * The server created is a simple http server by default; part of the
1791 * websocket standard is upgrading this http connection to a websocket one.
1793 * This allows the same server to provide files like scripts and favicon /
1794 * images or whatever over http and dynamic data over websockets all in
1795 * one place; they're all handled in the user callback.
1798 LWS_VISIBLE struct libwebsocket_context *
1799 libwebsocket_create_context(struct lws_context_creation_info *info)
1801 struct libwebsocket_context *context = NULL;
1804 #ifndef LWS_NO_SERVER
1806 struct libwebsocket *wsi;
1807 struct sockaddr_in serv_addr;
1809 #ifndef LWS_NO_EXTENSIONS
1811 struct libwebsocket_extension *ext;
1814 #ifdef LWS_OPENSSL_SUPPORT
1818 #ifndef LWS_NO_DAEMONIZE
1819 int pid_daemon = get_daemonize_pid();
1822 lwsl_notice("Initial logging level %d\n", log_level);
1823 lwsl_notice("Library version: %s\n", library_version);
1824 lwsl_info(" LWS_MAX_HEADER_LEN: %u\n", LWS_MAX_HEADER_LEN);
1825 lwsl_info(" LWS_MAX_PROTOCOLS: %u\n", LWS_MAX_PROTOCOLS);
1826 #ifndef LWS_NO_EXTENSIONS
1827 lwsl_info(" LWS_MAX_EXTENSIONS_ACTIVE: %u\n",
1828 LWS_MAX_EXTENSIONS_ACTIVE);
1830 lwsl_notice(" Configured without extension support\n");
1832 lwsl_info(" SPEC_LATEST_SUPPORTED: %u\n", SPEC_LATEST_SUPPORTED);
1833 lwsl_info(" AWAITING_TIMEOUT: %u\n", AWAITING_TIMEOUT);
1834 if (info->ssl_cipher_list)
1835 lwsl_info(" SSL ciphers: '%s'\n", info->ssl_cipher_list);
1836 lwsl_info(" SYSTEM_RANDOM_FILEPATH: '%s'\n", SYSTEM_RANDOM_FILEPATH);
1837 lwsl_info(" LWS_MAX_ZLIB_CONN_BUFFER: %u\n", LWS_MAX_ZLIB_CONN_BUFFER);
1841 WORD wVersionRequested;
1846 /* Use the MAKEWORD(lowbyte, highbyte) macro from Windef.h */
1847 wVersionRequested = MAKEWORD(2, 2);
1849 err = WSAStartup(wVersionRequested, &wsaData);
1851 /* Tell the user that we could not find a usable */
1853 lwsl_err("WSAStartup failed with error: %d\n", err);
1857 /* default to a poll() made out of select() */
1858 poll = emulated_poll;
1860 /* if windows socket lib available, use his WSAPoll */
1861 wsdll = GetModuleHandle(_T("Ws2_32.dll"));
1863 poll = (PFNWSAPOLL)GetProcAddress(wsdll, "WSAPoll");
1865 /* Finally fall back to emulated poll if all else fails */
1867 poll = emulated_poll;
1871 context = (struct libwebsocket_context *)
1872 malloc(sizeof(struct libwebsocket_context));
1874 lwsl_err("No memory for websocket context\n");
1877 memset(context, 0, sizeof(*context));
1878 #ifndef LWS_NO_DAEMONIZE
1879 context->started_with_parent = pid_daemon;
1880 lwsl_notice(" Started with daemon pid %d\n", pid_daemon);
1883 context->listen_service_extraseen = 0;
1884 context->protocols = info->protocols;
1885 context->listen_port = info->port;
1886 context->http_proxy_port = 0;
1887 context->http_proxy_address[0] = '\0';
1888 context->options = info->options;
1889 /* to reduce this allocation, */
1890 context->max_fds = getdtablesize();
1891 lwsl_notice(" static allocation: %u + (%u x %u fds) = %u bytes\n",
1892 sizeof(struct libwebsocket_context),
1893 sizeof(struct pollfd) + sizeof(struct libwebsocket *),
1895 sizeof(struct libwebsocket_context) +
1896 ((sizeof(struct pollfd) + sizeof(struct libwebsocket *)) *
1899 context->fds = (struct pollfd *)malloc(sizeof(struct pollfd) *
1901 if (context->fds == NULL) {
1902 lwsl_err("Unable to allocate fds array for %d connections\n",
1907 context->lws_lookup = (struct libwebsocket **)
1908 malloc(sizeof(struct libwebsocket *) * context->max_fds);
1909 if (context->lws_lookup == NULL) {
1911 "Unable to allocate lws_lookup array for %d connections\n",
1917 memset(context->lws_lookup, 0, sizeof(struct libwebsocket *) *
1920 context->fds_count = 0;
1921 #ifndef LWS_NO_EXTENSIONS
1922 context->extensions = info->extensions;
1924 context->last_timeout_check_s = 0;
1925 context->user_space = info->user;
1927 #if defined(WIN32) || defined(_WIN32)
1928 context->fd_random = 0;
1930 context->fd_random = open(SYSTEM_RANDOM_FILEPATH, O_RDONLY);
1931 if (context->fd_random < 0) {
1932 lwsl_err("Unable to open random device %s %d\n",
1933 SYSTEM_RANDOM_FILEPATH, context->fd_random);
1938 #ifdef LWS_OPENSSL_SUPPORT
1939 context->use_ssl = 0;
1940 context->allow_non_ssl_on_ssl_port = 0;
1941 context->ssl_ctx = NULL;
1942 context->ssl_client_ctx = NULL;
1943 openssl_websocket_private_data_index = 0;
1946 strcpy(context->canonical_hostname, "unknown");
1948 #ifndef LWS_NO_SERVER
1949 if (!(info->options & LWS_SERVER_OPTION_SKIP_SERVER_CANONICAL_NAME)) {
1950 /* find canonical hostname */
1951 gethostname((char *)context->canonical_hostname,
1952 sizeof(context->canonical_hostname) - 1);
1954 lwsl_notice(" canonical_hostname = %s\n",
1955 context->canonical_hostname);
1959 /* split the proxy ads:port if given */
1961 p = getenv("http_proxy");
1963 strncpy(context->http_proxy_address, p,
1964 sizeof(context->http_proxy_address) - 1);
1965 context->http_proxy_address[
1966 sizeof(context->http_proxy_address) - 1] = '\0';
1968 p = strchr(context->http_proxy_address, ':');
1970 lwsl_err("http_proxy needs to be ads:port\n");
1974 context->http_proxy_port = atoi(p + 1);
1976 lwsl_notice(" Proxy %s:%u\n",
1977 context->http_proxy_address,
1978 context->http_proxy_port);
1981 #ifndef LWS_NO_SERVER
1984 #ifdef LWS_OPENSSL_SUPPORT
1985 context->use_ssl = info->ssl_cert_filepath != NULL &&
1986 info->ssl_private_key_filepath != NULL;
1988 lwsl_notice(" Compiled with CYASSL support\n");
1990 lwsl_notice(" Compiled with OpenSSL support\n");
1992 if (context->use_ssl)
1993 lwsl_notice(" Using SSL mode\n");
1995 lwsl_notice(" Using non-SSL mode\n");
1998 if (info->ssl_cert_filepath != NULL &&
1999 info->ssl_private_key_filepath != NULL) {
2000 lwsl_notice(" Not compiled for OpenSSl support!\n");
2003 lwsl_notice(" Compiled without SSL support\n");
2007 " per-conn mem: %u + %u headers + protocol rx buf\n",
2008 sizeof(struct libwebsocket),
2009 sizeof(struct allocated_headers));
2013 /* ignore SIGPIPE */
2014 #if defined(WIN32) || defined(_WIN32)
2016 signal(SIGPIPE, sigpipe_handler);
2020 #ifdef LWS_OPENSSL_SUPPORT
2022 /* basic openssl init */
2026 OpenSSL_add_all_algorithms();
2027 SSL_load_error_strings();
2029 openssl_websocket_private_data_index =
2030 SSL_get_ex_new_index(0, "libwebsockets", NULL, NULL, NULL);
2033 * Firefox insists on SSLv23 not SSLv3
2034 * Konq disables SSLv2 by default now, SSLv23 works
2037 method = (SSL_METHOD *)SSLv23_server_method();
2039 int error = ERR_get_error();
2040 lwsl_err("problem creating ssl method %lu: %s\n",
2042 ERR_error_string(error,
2043 (char *)context->service_buffer));
2046 context->ssl_ctx = SSL_CTX_new(method); /* create context */
2047 if (!context->ssl_ctx) {
2048 int error = ERR_get_error();
2049 lwsl_err("problem creating ssl context %lu: %s\n",
2051 ERR_error_string(error,
2052 (char *)context->service_buffer));
2056 #ifdef SSL_OP_NO_COMPRESSION
2057 SSL_CTX_set_options(context->ssl_ctx, SSL_OP_NO_COMPRESSION);
2059 SSL_CTX_set_options(context->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
2060 if (info->ssl_cipher_list)
2061 SSL_CTX_set_cipher_list(context->ssl_ctx,
2062 info->ssl_cipher_list);
2064 #ifndef LWS_NO_CLIENT
2066 /* client context */
2068 if (info->port == CONTEXT_PORT_NO_LISTEN) {
2069 method = (SSL_METHOD *)SSLv23_client_method();
2071 int error = ERR_get_error();
2072 lwsl_err("problem creating ssl method %lu: %s\n",
2074 ERR_error_string(error,
2075 (char *)context->service_buffer));
2078 /* create context */
2079 context->ssl_client_ctx = SSL_CTX_new(method);
2080 if (!context->ssl_client_ctx) {
2081 int error = ERR_get_error();
2082 lwsl_err("problem creating ssl context %lu: %s\n",
2084 ERR_error_string(error,
2085 (char *)context->service_buffer));
2089 #ifdef SSL_OP_NO_COMPRESSION
2090 SSL_CTX_set_options(context->ssl_client_ctx,
2091 SSL_OP_NO_COMPRESSION);
2093 SSL_CTX_set_options(context->ssl_client_ctx,
2094 SSL_OP_CIPHER_SERVER_PREFERENCE);
2095 if (info->ssl_cipher_list)
2096 SSL_CTX_set_cipher_list(context->ssl_client_ctx,
2097 info->ssl_cipher_list);
2099 /* openssl init for cert verification (for client sockets) */
2100 if (!info->ssl_ca_filepath) {
2101 if (!SSL_CTX_load_verify_locations(
2102 context->ssl_client_ctx, NULL,
2103 LWS_OPENSSL_CLIENT_CERTS))
2105 "Unable to load SSL Client certs from %s "
2106 "(set by --with-client-cert-dir= "
2107 "in configure) -- client ssl isn't "
2108 "going to work", LWS_OPENSSL_CLIENT_CERTS);
2110 if (!SSL_CTX_load_verify_locations(
2111 context->ssl_client_ctx, info->ssl_ca_filepath,
2114 "Unable to load SSL Client certs "
2115 "file from %s -- client ssl isn't "
2116 "going to work", info->ssl_ca_filepath);
2119 * callback allowing user code to load extra verification certs
2120 * helping the client to verify server identity
2123 /* support for client-side certificate authentication */
2124 if (info->ssl_cert_filepath) {
2125 n = SSL_CTX_use_certificate_chain_file(
2126 context->ssl_client_ctx,
2127 info->ssl_cert_filepath);
2129 lwsl_err("problem getting cert '%s' %lu: %s\n",
2130 info->ssl_cert_filepath,
2132 ERR_error_string(ERR_get_error(),
2133 (char *)context->service_buffer));
2137 if (info->ssl_private_key_filepath) {
2138 /* set the private key from KeyFile */
2139 if (SSL_CTX_use_PrivateKey_file(context->ssl_client_ctx,
2140 info->ssl_private_key_filepath,
2141 SSL_FILETYPE_PEM) != 1) {
2142 lwsl_err("use_PrivateKey_file '%s' %lu: %s\n",
2143 info->ssl_private_key_filepath,
2145 ERR_error_string(ERR_get_error(),
2146 (char *)context->service_buffer));
2150 /* verify private key */
2151 if (!SSL_CTX_check_private_key(context->ssl_client_ctx)) {
2152 lwsl_err("Private SSL key doesn't match cert\n");
2157 context->protocols[0].callback(context, NULL,
2158 LWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS,
2159 context->ssl_client_ctx, NULL, 0);
2163 /* as a server, are we requiring clients to identify themselves? */
2166 LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT) {
2168 /* absolutely require the client cert */
2170 SSL_CTX_set_verify(context->ssl_ctx,
2171 SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
2172 OpenSSL_verify_callback);
2175 * give user code a chance to load certs into the server
2176 * allowing it to verify incoming client certs
2179 context->protocols[0].callback(context, NULL,
2180 LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS,
2181 context->ssl_ctx, NULL, 0);
2184 if(info->options & LWS_SERVER_OPTION_ALLOW_NON_SSL_ON_SSL_PORT) {
2185 /* Normally SSL listener rejects non-ssl, optionally allow */
2186 context->allow_non_ssl_on_ssl_port = 1;
2189 if (context->use_ssl) {
2191 /* openssl init for server sockets */
2193 /* set the local certificate from CertFile */
2194 n = SSL_CTX_use_certificate_chain_file(context->ssl_ctx,
2195 info->ssl_cert_filepath);
2197 int error = ERR_get_error();
2198 lwsl_err("problem getting cert '%s' %lu: %s\n",
2199 info->ssl_cert_filepath,
2201 ERR_error_string(error,
2202 (char *)context->service_buffer));
2205 /* set the private key from KeyFile */
2206 if (SSL_CTX_use_PrivateKey_file(context->ssl_ctx,
2207 info->ssl_private_key_filepath,
2208 SSL_FILETYPE_PEM) != 1) {
2209 int error = ERR_get_error();
2210 lwsl_err("ssl problem getting key '%s' %lu: %s\n",
2211 info->ssl_private_key_filepath,
2213 ERR_error_string(error,
2214 (char *)context->service_buffer));
2217 /* verify private key */
2218 if (!SSL_CTX_check_private_key(context->ssl_ctx)) {
2219 lwsl_err("Private SSL key doesn't match cert\n");
2223 /* SSL is happy and has a cert it's content with */
2227 #ifndef LWS_NO_SERVER
2228 /* set up our external listening socket we serve on */
2233 sockfd = socket(AF_INET, SOCK_STREAM, 0);
2235 lwsl_err("ERROR opening socket\n");
2241 * allow us to restart even if old sockets in TIME_WAIT
2242 * (REUSEADDR on Unix means, "don't hang on to this
2243 * address after the listener is closed." On Windows, though,
2244 * it means "don't keep other processes from binding to
2245 * this address while we're using it)
2247 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
2248 (const void *)&opt, sizeof(opt));
2253 setsockopt(sockfd, IPPROTO_TCP, TCP_NODELAY,
2254 (const void *)&opt, sizeof(opt));
2256 #if defined(WIN32) || defined(_WIN32)
2258 ioctlsocket(sockfd, FIONBIO, (unsigned long *)&opt);
2260 fcntl(sockfd, F_SETFL, O_NONBLOCK);
2263 bzero((char *) &serv_addr, sizeof(serv_addr));
2264 serv_addr.sin_family = AF_INET;
2265 if (info->iface == NULL)
2266 serv_addr.sin_addr.s_addr = INADDR_ANY;
2268 if (interface_to_sa(info->iface, &serv_addr,
2269 sizeof(serv_addr)) < 0) {
2270 lwsl_err("Unable to find interface %s\n",
2272 compatible_close(sockfd);
2275 serv_addr.sin_port = htons(info->port);
2277 n = bind(sockfd, (struct sockaddr *) &serv_addr,
2280 lwsl_err("ERROR on binding to port %d (%d %d)\n",
2281 info->port, n, errno);
2282 compatible_close(sockfd);
2286 wsi = (struct libwebsocket *)malloc(
2287 sizeof(struct libwebsocket));
2289 lwsl_err("Out of mem\n");
2290 compatible_close(sockfd);
2293 memset(wsi, 0, sizeof(struct libwebsocket));
2295 #ifndef LWS_NO_EXTENSIONS
2296 wsi->count_active_extensions = 0;
2298 wsi->mode = LWS_CONNMODE_SERVER_LISTENER;
2300 insert_wsi_socket_into_fds(context, wsi);
2302 context->listen_service_modulo = LWS_LISTEN_SERVICE_MODULO;
2303 context->listen_service_count = 0;
2304 context->listen_service_fd = sockfd;
2306 listen(sockfd, LWS_SOMAXCONN);
2307 lwsl_notice(" Listening on port %d\n", info->port);
2312 * drop any root privs for this process
2313 * to listen on port < 1023 we would have needed root, but now we are
2314 * listening, we don't want the power for anything else
2316 #if defined(WIN32) || defined(_WIN32)
2318 if (info->gid != -1)
2319 if (setgid(info->gid))
2320 lwsl_warn("setgid: %s\n", strerror(errno));
2321 if (info->uid != -1)
2322 if (setuid(info->uid))
2323 lwsl_warn("setuid: %s\n", strerror(errno));
2326 /* initialize supported protocols */
2328 for (context->count_protocols = 0;
2329 info->protocols[context->count_protocols].callback;
2330 context->count_protocols++) {
2332 lwsl_parser(" Protocol: %s\n",
2333 info->protocols[context->count_protocols].name);
2335 info->protocols[context->count_protocols].owning_server =
2337 info->protocols[context->count_protocols].protocol_index =
2338 context->count_protocols;
2341 * inform all the protocols that they are doing their one-time
2342 * initialization if they want to
2344 info->protocols[context->count_protocols].callback(context,
2345 NULL, LWS_CALLBACK_PROTOCOL_INIT, NULL, NULL, 0);
2348 #ifndef LWS_NO_EXTENSIONS
2350 * give all extensions a chance to create any per-context
2351 * allocations they need
2354 m = LWS_EXT_CALLBACK_CLIENT_CONTEXT_CONSTRUCT;
2356 m = LWS_EXT_CALLBACK_SERVER_CONTEXT_CONSTRUCT;
2358 if (info->extensions) {
2359 ext = info->extensions;
2360 while (ext->callback) {
2361 lwsl_ext(" Extension: %s\n", ext->name);
2362 ext->callback(context, ext, NULL,
2363 (enum libwebsocket_extension_callback_reasons)m,
2372 libwebsocket_context_destroy(context);
2377 * libwebsocket_set_proxy() - Setups proxy to libwebsocket_context.
2378 * @context: pointer to struct libwebsocket_context you want set proxy to
2379 * @proxy: pointer to c string containing proxy in format address:port
2381 * Returns 0 if proxy string was parsed and proxy was setup.
2382 * Returns -1 if @proxy is NULL or has incorrect format.
2384 * This is only required if your OS does not provide the http_proxy
2385 * enviroment variable (eg, OSX)
2387 * IMPORTANT! You should call this function right after creation of the
2388 * libwebsocket_context and before call to connect. If you call this
2389 * function after connect behavior is undefined.
2390 * This function will override proxy settings made on libwebsocket_context
2391 * creation with genenv() call.
2395 libwebsocket_set_proxy(struct libwebsocket_context *context, const char *proxy)
2402 strncpy(context->http_proxy_address, proxy,
2403 sizeof(context->http_proxy_address) - 1);
2404 context->http_proxy_address[
2405 sizeof(context->http_proxy_address) - 1] = '\0';
2407 p = strchr(context->http_proxy_address, ':');
2409 lwsl_err("http_proxy needs to be ads:port\n");
2414 context->http_proxy_port = atoi(p + 1);
2416 lwsl_notice(" Proxy %s:%u\n", context->http_proxy_address,
2417 context->http_proxy_port);
2423 * libwebsockets_get_protocol() - Returns a protocol pointer from a websocket
2425 * @wsi: pointer to struct websocket you want to know the protocol of
2428 * Some apis can act on all live connections of a given protocol,
2429 * this is how you can get a pointer to the active protocol if needed.
2432 LWS_VISIBLE const struct libwebsocket_protocols *
2433 libwebsockets_get_protocol(struct libwebsocket *wsi)
2435 return wsi->protocol;
2439 libwebsocket_is_final_fragment(struct libwebsocket *wsi)
2441 return wsi->u.ws.final;
2444 LWS_VISIBLE unsigned char
2445 libwebsocket_get_reserved_bits(struct libwebsocket *wsi)
2447 return wsi->u.ws.rsv;
2451 libwebsocket_ensure_user_space(struct libwebsocket *wsi)
2456 /* allocate the per-connection user memory (if any) */
2458 if (wsi->protocol->per_session_data_size && !wsi->user_space) {
2459 wsi->user_space = malloc(
2460 wsi->protocol->per_session_data_size);
2461 if (wsi->user_space == NULL) {
2462 lwsl_err("Out of memory for conn user space\n");
2465 memset(wsi->user_space, 0,
2466 wsi->protocol->per_session_data_size);
2471 static void lwsl_emit_stderr(int level, const char *line)
2477 gettimeofday(&tv, NULL);
2480 for (n = 0; n < LLL_COUNT; n++)
2481 if (level == (1 << n)) {
2482 sprintf(buf, "[%ld:%04d] %s: ", tv.tv_sec,
2483 (int)(tv.tv_usec / 100), log_level_names[n]);
2487 fprintf(stderr, "%s%s", buf, line);
2490 #if defined(WIN32) || defined(_WIN32)
2491 LWS_VISIBLE void lwsl_emit_syslog(int level, const char *line)
2493 lwsl_emit_stderr(level, line);
2496 LWS_VISIBLE void lwsl_emit_syslog(int level, const char *line)
2498 int syslog_level = LOG_DEBUG;
2502 syslog_level = LOG_ERR;
2505 syslog_level = LOG_WARNING;
2508 syslog_level = LOG_NOTICE;
2511 syslog_level = LOG_INFO;
2514 syslog(syslog_level, "%s", line);
2518 LWS_VISIBLE void _lws_log(int filter, const char *format, ...)
2523 if (!(log_level & filter))
2526 va_start(ap, format);
2527 vsnprintf(buf, sizeof(buf), format, ap);
2528 buf[sizeof(buf) - 1] = '\0';
2531 lwsl_emit(filter, buf);
2535 * lws_set_log_level() - Set the logging bitfield
2536 * @level: OR together the LLL_ debug contexts you want output from
2537 * @log_emit_function: NULL to leave it as it is, or a user-supplied
2538 * function to perform log string emission instead of
2539 * the default stderr one.
2541 * log level defaults to "err", "warn" and "notice" contexts enabled and
2542 * emission on stderr.
2545 LWS_VISIBLE void lws_set_log_level(int level, void (*log_emit_function)(int level,
2549 if (log_emit_function)
2550 lwsl_emit = log_emit_function;