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->lws_lookup[wsi->sock] = wsi;
122 wsi->position_in_fds_table = context->fds_count;
123 context->fds[context->fds_count].fd = wsi->sock;
124 context->fds[context->fds_count].events = POLLIN;
125 context->fds[context->fds_count++].revents = 0;
127 /* external POLL support via protocol 0 */
128 context->protocols[0].callback(context, wsi,
129 LWS_CALLBACK_ADD_POLL_FD,
130 wsi->user_space, (void *)(long)wsi->sock, POLLIN);
136 remove_wsi_socket_from_fds(struct libwebsocket_context *context,
137 struct libwebsocket *wsi)
141 if (!--context->fds_count)
144 if (wsi->sock > context->max_fds) {
145 lwsl_err("Socket fd %d too high (%d)\n",
146 wsi->sock, context->max_fds);
150 lwsl_info("remove_wsi_socket_from_fds: wsi=%p, sock=%d, fds pos=%d\n",
151 wsi, wsi->sock, wsi->position_in_fds_table);
153 m = wsi->position_in_fds_table; /* replace the contents for this */
155 /* have the last guy take up the vacant slot */
156 context->fds[m] = context->fds[context->fds_count];
158 * end guy's fds_lookup entry remains unchanged
159 * (still same fd pointing to same wsi)
161 /* end guy's "position in fds table" changed */
162 context->lws_lookup[context->fds[context->fds_count].fd]->
163 position_in_fds_table = m;
164 /* deletion guy's lws_lookup entry needs nuking */
165 context->lws_lookup[wsi->sock] = NULL;
166 /* removed wsi has no position any more */
167 wsi->position_in_fds_table = -1;
170 /* remove also from external POLL support via protocol 0 */
172 context->protocols[0].callback(context, wsi,
173 LWS_CALLBACK_DEL_POLL_FD, wsi->user_space,
174 (void *)(long)wsi->sock, 0);
181 libwebsocket_close_and_free_session(struct libwebsocket_context *context,
182 struct libwebsocket *wsi, enum lws_close_status reason)
186 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 2 +
187 LWS_SEND_BUFFER_POST_PADDING];
188 #ifndef LWS_NO_EXTENSIONS
191 struct lws_tokens eff_buf;
192 struct libwebsocket_extension *ext;
198 old_state = wsi->state;
200 if (old_state == WSI_STATE_DEAD_SOCKET)
203 /* we tried the polite way... */
204 if (old_state == WSI_STATE_AWAITING_CLOSE_ACK)
205 goto just_kill_connection;
207 wsi->u.ws.close_reason = reason;
209 if (wsi->mode == LWS_CONNMODE_WS_CLIENT_WAITING_CONNECT ||
210 wsi->mode == LWS_CONNMODE_WS_CLIENT_ISSUE_HANDSHAKE) {
212 context->protocols[0].callback(context, wsi,
213 LWS_CALLBACK_CLIENT_CONNECTION_ERROR, NULL, NULL, 0);
216 goto just_kill_connection;
220 if (wsi->mode == LWS_CONNMODE_HTTP_SERVING_ACCEPTED) {
221 if (wsi->u.http.post_buffer) {
222 free(wsi->u.http.post_buffer);
223 wsi->u.http.post_buffer = NULL;
225 if (wsi->u.http.fd >= 0) {
226 lwsl_debug("closing http fd %d\n", wsi->u.http.fd);
227 close(wsi->u.http.fd);
229 context->protocols[0].callback(context, wsi,
230 LWS_CALLBACK_CLOSED_HTTP, wsi->user_space, NULL, 0);
234 #ifndef LWS_NO_EXTENSIONS
236 * are his extensions okay with him closing? Eg he might be a mux
237 * parent and just his ch1 aspect is closing?
240 for (n = 0; n < wsi->count_active_extensions; n++) {
241 if (!wsi->active_extensions[n]->callback)
244 m = wsi->active_extensions[n]->callback(context,
245 wsi->active_extensions[n], wsi,
246 LWS_EXT_CALLBACK_CHECK_OK_TO_REALLY_CLOSE,
247 wsi->active_extensions_user[n], NULL, 0);
250 * if somebody vetoed actually closing him at this time....
251 * up to the extension to track the attempted close, let's
256 lwsl_ext("extension vetoed close\n");
262 * flush any tx pending from extensions, since we may send close packet
263 * if there are problems with send, just nuke the connection
269 /* default to nobody has more to spill */
272 eff_buf.token = NULL;
273 eff_buf.token_len = 0;
275 /* show every extension the new incoming data */
277 for (n = 0; n < wsi->count_active_extensions; n++) {
278 m = wsi->active_extensions[n]->callback(
279 wsi->protocol->owning_server,
280 wsi->active_extensions[n], wsi,
281 LWS_EXT_CALLBACK_FLUSH_PENDING_TX,
282 wsi->active_extensions_user[n], &eff_buf, 0);
284 lwsl_ext("Extension reports fatal error\n");
285 goto just_kill_connection;
289 * at least one extension told us he has more
290 * to spill, so we will go around again after
295 /* assuming they left us something to send, send it */
297 if (eff_buf.token_len)
298 if (lws_issue_raw(wsi, (unsigned char *)eff_buf.token,
299 eff_buf.token_len) != eff_buf.token_len) {
300 lwsl_debug("close: ext spill failed\n");
301 goto just_kill_connection;
307 * signal we are closing, libsocket_write will
308 * add any necessary version-specific stuff. If the write fails,
309 * no worries we are closing anyway. If we didn't initiate this
310 * close, then our state has been changed to
311 * WSI_STATE_RETURNED_CLOSE_ALREADY and we will skip this.
313 * Likewise if it's a second call to close this connection after we
314 * sent the close indication to the peer already, we are in state
315 * WSI_STATE_AWAITING_CLOSE_ACK and will skip doing this a second time.
318 if (old_state == WSI_STATE_ESTABLISHED &&
319 reason != LWS_CLOSE_STATUS_NOSTATUS) {
321 lwsl_debug("sending close indication...\n");
323 /* make valgrind happy */
324 memset(buf, 0, sizeof(buf));
325 n = libwebsocket_write(wsi,
326 &buf[LWS_SEND_BUFFER_PRE_PADDING + 2],
330 * we have sent a nice protocol level indication we
331 * now wish to close, we should not send anything more
334 wsi->state = WSI_STATE_AWAITING_CLOSE_ACK;
337 * ...and we should wait for a reply for a bit
341 libwebsocket_set_timeout(wsi,
342 PENDING_TIMEOUT_CLOSE_ACK, 1);
344 lwsl_debug("sent close indication, awaiting ack\n");
349 lwsl_info("close: sending close packet failed, hanging up\n");
351 /* else, the send failed and we should just hang up */
354 just_kill_connection:
356 lwsl_debug("close: just_kill_connection\n");
359 * we won't be servicing or receiving anything further from this guy
360 * delete socket from the internal poll list if still present
363 remove_wsi_socket_from_fds(context, wsi);
365 wsi->state = WSI_STATE_DEAD_SOCKET;
367 if ((old_state == WSI_STATE_ESTABLISHED ||
368 wsi->mode == LWS_CONNMODE_WS_SERVING ||
369 wsi->mode == LWS_CONNMODE_WS_CLIENT)) {
371 if (wsi->u.ws.rx_user_buffer) {
372 free(wsi->u.ws.rx_user_buffer);
373 wsi->u.ws.rx_user_buffer = NULL;
375 if (wsi->u.ws.rxflow_buffer) {
376 free(wsi->u.ws.rxflow_buffer);
377 wsi->u.ws.rxflow_buffer = NULL;
379 if (wsi->truncated_send_malloc) {
380 /* not going to be completed... nuke it */
381 free(wsi->truncated_send_malloc);
382 wsi->truncated_send_malloc = NULL;
386 /* tell the user it's all over for this guy */
388 if (wsi->protocol && wsi->protocol->callback &&
389 ((old_state == WSI_STATE_ESTABLISHED) ||
390 (old_state == WSI_STATE_RETURNED_CLOSE_ALREADY) ||
391 (old_state == WSI_STATE_AWAITING_CLOSE_ACK))) {
392 lwsl_debug("calling back CLOSED\n");
393 wsi->protocol->callback(context, wsi, LWS_CALLBACK_CLOSED,
394 wsi->user_space, NULL, 0);
395 } else if ( wsi->mode == LWS_CONNMODE_HTTP_SERVING_ACCEPTED ) {
396 lwsl_debug("calling back CLOSED_HTTP\n");
397 context->protocols[0].callback(context, wsi,
398 LWS_CALLBACK_CLOSED_HTTP, wsi->user_space, NULL, 0 );
400 lwsl_debug("not calling back closed\n");
402 #ifndef LWS_NO_EXTENSIONS
403 /* deallocate any active extension contexts */
405 for (n = 0; n < wsi->count_active_extensions; n++) {
406 if (!wsi->active_extensions[n]->callback)
409 wsi->active_extensions[n]->callback(context,
410 wsi->active_extensions[n], wsi,
411 LWS_EXT_CALLBACK_DESTROY,
412 wsi->active_extensions_user[n], NULL, 0);
414 free(wsi->active_extensions_user[n]);
418 * inform all extensions in case they tracked this guy out of band
419 * even though not active on him specifically
422 ext = context->extensions;
423 while (ext && ext->callback) {
424 ext->callback(context, ext, wsi,
425 LWS_EXT_CALLBACK_DESTROY_ANY_WSI_CLOSING,
431 /* lwsl_info("closing fd=%d\n", wsi->sock); */
433 #ifdef LWS_OPENSSL_SUPPORT
435 n = SSL_get_fd(wsi->ssl);
436 SSL_shutdown(wsi->ssl);
442 n = shutdown(wsi->sock, SHUT_RDWR);
444 lwsl_debug("closing: shutdown returned %d\n",
447 n = compatible_close(wsi->sock);
449 lwsl_debug("closing: close returned %d\n",
452 #ifdef LWS_OPENSSL_SUPPORT
455 if (wsi->protocol && wsi->protocol->per_session_data_size &&
456 wsi->user_space) /* user code may own */
457 free(wsi->user_space);
463 * libwebsockets_get_peer_addresses() - Get client address information
464 * @context: Libwebsockets context
465 * @wsi: Local struct libwebsocket associated with
466 * @fd: Connection socket descriptor
467 * @name: Buffer to take client address name
468 * @name_len: Length of client address name buffer
469 * @rip: Buffer to take client address IP qotted quad
470 * @rip_len: Length of client address IP buffer
472 * This function fills in @name and @rip with the name and IP of
473 * the client connected with socket descriptor @fd. Names may be
474 * truncated if there is not enough room. If either cannot be
475 * determined, they will be returned as valid zero-length strings.
479 libwebsockets_get_peer_addresses(struct libwebsocket_context *context,
480 struct libwebsocket *wsi, int fd, char *name, int name_len,
481 char *rip, int rip_len)
484 struct sockaddr_in sin;
485 struct hostent *host;
486 struct hostent *host1;
492 struct sockaddr_un *un;
498 lws_latency_pre(context, wsi);
501 if (getpeername(fd, (struct sockaddr *) &sin, &len) < 0) {
502 perror("getpeername");
506 host = gethostbyaddr((char *) &sin.sin_addr, sizeof(sin.sin_addr),
509 perror("gethostbyaddr");
513 strncpy(name, host->h_name, name_len);
514 name[name_len - 1] = '\0';
516 host1 = gethostbyname(host->h_name);
519 p = (unsigned char *)host1;
522 p = (unsigned char *)host1->h_addr_list[n++];
525 if ((host1->h_addrtype != AF_INET)
527 && (host1->h_addrtype != AF_LOCAL)
532 if (host1->h_addrtype == AF_INET)
533 sprintf(ip, "%u.%u.%u.%u", p[0], p[1], p[2], p[3]);
536 un = (struct sockaddr_un *)p;
537 strncpy(ip, un->sun_path, sizeof(ip) - 1);
538 ip[sizeof(ip) - 1] = '\0';
542 strncpy(rip, ip, rip_len);
543 rip[rip_len - 1] = '\0';
548 lws_latency(context, wsi, "libwebsockets_get_peer_addresses", ret, 1);
551 LWS_VISIBLE int libwebsockets_get_random(struct libwebsocket_context *context,
555 char *p = (char *)buf;
557 #if defined(WIN32) || defined(_WIN32)
558 for (n = 0; n < len; n++)
559 p[n] = (unsigned char)rand();
561 n = read(context->fd_random, p, len);
567 int lws_set_socket_options(struct libwebsocket_context *context, int fd)
570 socklen_t optlen = sizeof(optval);
571 #if defined(WIN32) || defined(_WIN32)
572 unsigned long optl = 0;
574 #if defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__)
575 struct protoent *tcp_proto;
578 if (context->ka_time) {
579 /* enable keepalive on this socket */
581 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE,
582 (const void *)&optval, optlen) < 0)
585 #if defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__CYGWIN__)
588 * didn't find a way to set these per-socket, need to
589 * tune kernel systemwide values
594 struct tcp_keepalive alive;
596 alive.keepalivetime = context->ka_time;
597 alive.keepaliveinterval = context->ka_interval;
599 if (WSAIoctl(fd, SIO_KEEPALIVE_VALS, &alive, sizeof(alive),
600 NULL, 0, &dwBytesRet, NULL, NULL))
604 /* set the keepalive conditions we want on it too */
605 optval = context->ka_time;
606 if (setsockopt(fd, IPPROTO_IP, TCP_KEEPIDLE,
607 (const void *)&optval, optlen) < 0)
610 optval = context->ka_interval;
611 if (setsockopt(fd, IPPROTO_IP, TCP_KEEPINTVL,
612 (const void *)&optval, optlen) < 0)
615 optval = context->ka_probes;
616 if (setsockopt(fd, IPPROTO_IP, TCP_KEEPCNT,
617 (const void *)&optval, optlen) < 0)
624 #if !defined(__APPLE__) && !defined(__FreeBSD__) && !defined(__NetBSD__)
625 setsockopt(fd, SOL_TCP, TCP_NODELAY, (const void *)&optval, optlen);
627 tcp_proto = getprotobyname("TCP");
628 setsockopt(fd, tcp_proto->p_proto, TCP_NODELAY, &optval, optlen);
631 /* We are nonblocking... */
632 #if defined(WIN32) || defined(_WIN32)
633 ioctlsocket(fd, FIONBIO, &optl);
635 fcntl(fd, F_SETFL, O_NONBLOCK);
641 LWS_VISIBLE int lws_send_pipe_choked(struct libwebsocket *wsi)
645 /* treat the fact we got a truncated send pending as if we're choked */
646 if (wsi->truncated_send_malloc)
650 fds.events = POLLOUT;
653 if (poll(&fds, 1, 0) != 1)
656 if ((fds.revents & POLLOUT) == 0)
659 /* okay to send another packet without blocking */
665 lws_handle_POLLOUT_event(struct libwebsocket_context *context,
666 struct libwebsocket *wsi, struct pollfd *pollfd)
670 #ifndef LWS_NO_EXTENSIONS
671 struct lws_tokens eff_buf;
676 /* pending truncated sends have uber priority */
678 if (wsi->truncated_send_malloc) {
679 lws_issue_raw(wsi, wsi->truncated_send_malloc +
680 wsi->truncated_send_offset,
681 wsi->truncated_send_len);
682 /* leave POLLOUT active either way */
686 for (n = 0; n < wsi->count_active_extensions; n++) {
687 if (!wsi->active_extensions[n]->callback)
690 m = wsi->active_extensions[n]->callback(context,
691 wsi->active_extensions[n], wsi,
692 LWS_EXT_CALLBACK_IS_WRITEABLE,
693 wsi->active_extensions_user[n], NULL, 0);
701 if (!wsi->extension_data_pending || handled == 2)
705 * check in on the active extensions, see if they
706 * had pending stuff to spill... they need to get the
707 * first look-in otherwise sequence will be disordered
709 * NULL, zero-length eff_buf means just spill pending
715 /* default to nobody has more to spill */
718 eff_buf.token = NULL;
719 eff_buf.token_len = 0;
721 /* give every extension a chance to spill */
723 for (n = 0; n < wsi->count_active_extensions; n++) {
724 m = wsi->active_extensions[n]->callback(
725 wsi->protocol->owning_server,
726 wsi->active_extensions[n], wsi,
727 LWS_EXT_CALLBACK_PACKET_TX_PRESEND,
728 wsi->active_extensions_user[n], &eff_buf, 0);
730 lwsl_err("ext reports fatal error\n");
735 * at least one extension told us he has more
736 * to spill, so we will go around again after
741 /* assuming they gave us something to send, send it */
743 if (eff_buf.token_len) {
744 n = lws_issue_raw(wsi, (unsigned char *)eff_buf.token,
749 * Keep amount spilled small to minimize chance of this
751 if (n != eff_buf.token_len) {
752 lwsl_err("Unable to spill ext %d vs %s\n",
753 eff_buf.token_len, n);
759 /* no extension has more to spill */
765 * There's more to spill from an extension, but we just sent
766 * something... did that leave the pipe choked?
769 if (!lws_send_pipe_choked(wsi))
770 /* no we could add more */
773 lwsl_info("choked in POLLOUT service\n");
776 * Yes, he's choked. Leave the POLLOUT masked on so we will
777 * come back here when he is unchoked. Don't call the user
778 * callback to enforce ordering of spilling, he'll get called
779 * when we come back here and there's nothing more to spill.
785 wsi->extension_data_pending = 0;
792 pollfd->events &= ~POLLOUT;
794 /* external POLL support via protocol 0 */
795 context->protocols[0].callback(context, wsi,
796 LWS_CALLBACK_CLEAR_MODE_POLL_FD,
797 wsi->user_space, (void *)(long)wsi->sock, POLLOUT);
799 #ifndef LWS_NO_EXTENSIONS
803 if (wsi->mode == LWS_CONNMODE_WS_CLIENT)
804 n = LWS_CALLBACK_CLIENT_WRITEABLE;
806 n = LWS_CALLBACK_SERVER_WRITEABLE;
808 return user_callback_handle_rxflow(wsi->protocol->callback, context,
809 wsi, (enum libwebsocket_callback_reasons) n,
810 wsi->user_space, NULL, 0);
816 libwebsocket_service_timeout_check(struct libwebsocket_context *context,
817 struct libwebsocket *wsi, unsigned int sec)
819 #ifndef LWS_NO_EXTENSIONS
823 * if extensions want in on it (eg, we are a mux parent)
824 * give them a chance to service child timeouts
827 for (n = 0; n < wsi->count_active_extensions; n++)
828 wsi->active_extensions[n]->callback(
829 context, wsi->active_extensions[n],
830 wsi, LWS_EXT_CALLBACK_1HZ,
831 wsi->active_extensions_user[n], NULL, sec);
834 if (!wsi->pending_timeout)
838 * if we went beyond the allowed time, kill the
842 if (sec > wsi->pending_timeout_limit) {
843 lwsl_info("TIMEDOUT WAITING\n");
844 libwebsocket_close_and_free_session(context,
845 wsi, LWS_CLOSE_STATUS_NOSTATUS);
853 * libwebsocket_service_fd() - Service polled socket with something waiting
854 * @context: Websocket context
855 * @pollfd: The pollfd entry describing the socket fd and which events
858 * This function takes a pollfd that has POLLIN or POLLOUT activity and
859 * services it according to the state of the associated
860 * struct libwebsocket.
862 * The one call deals with all "service" that might happen on a socket
863 * including listen accepts, http files as well as websocket protocol.
865 * If a pollfd says it has something, you can just pass it to
866 * libwebsocket_serice_fd() whether it is a socket handled by lws or not.
867 * If it sees it is a lws socket, the traffic will be handled and
868 * pollfd->revents will be zeroed now.
870 * If the socket is foreign to lws, it leaves revents alone. So you can
871 * see if you should service yourself by checking the pollfd revents
872 * after letting lws try to service it.
876 libwebsocket_service_fd(struct libwebsocket_context *context,
877 struct pollfd *pollfd)
879 struct libwebsocket *wsi;
882 int listen_socket_fds_index = 0;
886 char draining_flow = 0;
888 #ifndef LWS_NO_EXTENSIONS
891 struct lws_tokens eff_buf;
893 if (context->listen_service_fd)
894 listen_socket_fds_index = context->lws_lookup[
895 context->listen_service_fd]->position_in_fds_table;
898 * you can call us with pollfd = NULL to just allow the once-per-second
899 * global timeout checks; if less than a second since the last check
900 * it returns immediately then.
903 gettimeofday(&tv, NULL);
905 if (context->last_timeout_check_s != tv.tv_sec) {
906 context->last_timeout_check_s = tv.tv_sec;
909 /* if our parent went down, don't linger around */
910 if (context->started_with_parent &&
911 kill(context->started_with_parent, 0) < 0)
912 kill(getpid(), SIGTERM);
915 /* global timeout check once per second */
920 for (n = 0; n < context->fds_count; n++) {
921 m = context->fds[n].fd;
922 wsi = context->lws_lookup[m];
926 if (libwebsocket_service_timeout_check(context, wsi,
928 /* he did time out... */
930 /* it was the guy we came to service! */
932 /* mark as handled */
938 /* the socket we came to service timed out, nothing to do */
942 /* just here for timeout management? */
946 /* no, here to service a socket descriptor */
947 wsi = context->lws_lookup[pollfd->fd];
949 /* not lws connection ... leave revents alone and return */
953 * so that caller can tell we handled, past here we need to
954 * zero down pollfd->revents after handling
958 * deal with listen service piggybacking
959 * every listen_service_modulo services of other fds, we
960 * sneak one in to service the listen socket if there's anything waiting
962 * To handle connection storms, as found in ab, if we previously saw a
963 * pending connection here, it causes us to check again next time.
966 if (context->listen_service_fd && pollfd !=
967 &context->fds[listen_socket_fds_index]) {
968 context->listen_service_count++;
969 if (context->listen_service_extraseen ||
970 context->listen_service_count ==
971 context->listen_service_modulo) {
972 context->listen_service_count = 0;
974 if (context->listen_service_extraseen > 5)
978 * even with extpoll, we prepared this
979 * internal fds for listen
981 n = poll(&context->fds[listen_socket_fds_index],
983 if (n > 0) { /* there's a conn waiting for us */
984 libwebsocket_service_fd(context,
986 fds[listen_socket_fds_index]);
987 context->listen_service_extraseen++;
989 if (context->listen_service_extraseen)
991 listen_service_extraseen--;
999 /* handle session socket closed */
1001 if ((!(pollfd->revents & POLLIN)) &&
1002 (pollfd->revents & (POLLERR | POLLHUP))) {
1004 lwsl_debug("Session Socket %p (fd=%d) dead\n",
1005 (void *)wsi, pollfd->fd);
1007 goto close_and_handled;
1010 /* okay, what we came here to do... */
1012 switch (wsi->mode) {
1014 #ifndef LWS_NO_SERVER
1015 case LWS_CONNMODE_HTTP_SERVING:
1016 case LWS_CONNMODE_HTTP_SERVING_ACCEPTED:
1017 case LWS_CONNMODE_SERVER_LISTENER:
1018 case LWS_CONNMODE_SSL_ACK_PENDING:
1019 n = lws_server_socket_service(context, wsi, pollfd);
1023 case LWS_CONNMODE_WS_SERVING:
1024 case LWS_CONNMODE_WS_CLIENT:
1026 /* the guy requested a callback when it was OK to write */
1028 if ((pollfd->revents & POLLOUT) &&
1029 wsi->state == WSI_STATE_ESTABLISHED &&
1030 lws_handle_POLLOUT_event(context, wsi, pollfd) < 0) {
1031 lwsl_info("libwebsocket_service_fd: closing\n");
1032 goto close_and_handled;
1035 if (wsi->u.ws.rxflow_buffer &&
1036 (wsi->u.ws.rxflow_change_to & LWS_RXFLOW_ALLOW)) {
1037 lwsl_info("draining rxflow\n");
1038 /* well, drain it */
1039 eff_buf.token = (char *)wsi->u.ws.rxflow_buffer +
1040 wsi->u.ws.rxflow_pos;
1041 eff_buf.token_len = wsi->u.ws.rxflow_len -
1042 wsi->u.ws.rxflow_pos;
1047 /* any incoming data ready? */
1049 if (!(pollfd->revents & POLLIN))
1052 #ifdef LWS_OPENSSL_SUPPORT
1055 eff_buf.token_len = SSL_read(wsi->ssl,
1056 context->service_buffer,
1057 sizeof(context->service_buffer));
1058 if (!eff_buf.token_len) {
1059 n = SSL_get_error(wsi->ssl, eff_buf.token_len);
1060 lwsl_err("SSL_read returned 0 with reason %s\n",
1062 (char *)context->service_buffer));
1066 eff_buf.token_len = recv(pollfd->fd,
1067 context->service_buffer,
1068 sizeof(context->service_buffer), 0);
1070 if (eff_buf.token_len < 0) {
1071 lwsl_debug("service_fd read ret = %d, errno = %d\n",
1072 eff_buf.token_len, errno);
1073 if (errno != EINTR && errno != EAGAIN)
1074 goto close_and_handled;
1078 if (!eff_buf.token_len) {
1079 lwsl_info("service_fd: closing due to 0 length read\n");
1080 goto close_and_handled;
1084 * give any active extensions a chance to munge the buffer
1085 * before parse. We pass in a pointer to an lws_tokens struct
1086 * prepared with the default buffer and content length that's in
1087 * there. Rather than rewrite the default buffer, extensions
1088 * that expect to grow the buffer can adapt .token to
1089 * point to their own per-connection buffer in the extension
1090 * user allocation. By default with no extensions or no
1091 * extension callback handling, just the normal input buffer is
1092 * used then so it is efficient.
1095 eff_buf.token = (char *)context->service_buffer;
1097 #ifndef LWS_NO_EXTENSIONS
1103 for (n = 0; n < wsi->count_active_extensions; n++) {
1104 m = wsi->active_extensions[n]->callback(context,
1105 wsi->active_extensions[n], wsi,
1106 LWS_EXT_CALLBACK_PACKET_RX_PREPARSE,
1107 wsi->active_extensions_user[n],
1111 "Extension reports fatal error\n");
1112 goto close_and_handled;
1118 /* service incoming data */
1120 if (eff_buf.token_len) {
1121 n = libwebsocket_read(context, wsi,
1122 (unsigned char *)eff_buf.token,
1130 #ifndef LWS_NO_EXTENSIONS
1131 eff_buf.token = NULL;
1132 eff_buf.token_len = 0;
1135 if (draining_flow && wsi->u.ws.rxflow_buffer &&
1136 wsi->u.ws.rxflow_pos == wsi->u.ws.rxflow_len) {
1137 lwsl_info("flow buffer: drained\n");
1138 free(wsi->u.ws.rxflow_buffer);
1139 wsi->u.ws.rxflow_buffer = NULL;
1140 /* having drained the rxflow buffer, can rearm POLLIN */
1141 _libwebsocket_rx_flow_control(wsi);
1144 #ifdef LWS_OPENSSL_SUPPORT
1145 if (wsi->ssl && SSL_pending(wsi->ssl))
1151 #ifdef LWS_NO_CLIENT
1154 n = lws_client_socket_service(context, wsi, pollfd);
1163 libwebsocket_close_and_free_session(context, wsi,
1164 LWS_CLOSE_STATUS_NOSTATUS);
1168 pollfd->revents = 0;
1174 * libwebsocket_context_destroy() - Destroy the websocket context
1175 * @context: Websocket context
1177 * This function closes any active connections and then frees the
1178 * context. After calling this, any further use of the context is
1182 libwebsocket_context_destroy(struct libwebsocket_context *context)
1184 #ifndef LWS_NO_EXTENSIONS
1187 struct libwebsocket_extension *ext;
1188 struct libwebsocket_protocols *protocol = context->protocols;
1191 if (context->worst_latency_info[0])
1192 lwsl_notice("Worst latency: %s\n", context->worst_latency_info);
1195 for (n = 0; n < context->fds_count; n++) {
1196 struct libwebsocket *wsi =
1197 context->lws_lookup[context->fds[n].fd];
1198 libwebsocket_close_and_free_session(context,
1199 wsi, LWS_CLOSE_STATUS_NOSTATUS /* no protocol close */);
1204 * give all extensions a chance to clean up any per-context
1205 * allocations they might have made
1208 ext = context->extensions;
1209 m = LWS_EXT_CALLBACK_CLIENT_CONTEXT_DESTRUCT;
1210 if (context->listen_port)
1211 m = LWS_EXT_CALLBACK_SERVER_CONTEXT_DESTRUCT;
1212 while (ext && ext->callback) {
1213 ext->callback(context, ext, NULL,
1214 (enum libwebsocket_extension_callback_reasons)m,
1220 * inform all the protocols that they are done and will have no more
1224 while (protocol->callback) {
1225 protocol->callback(context, NULL, LWS_CALLBACK_PROTOCOL_DESTROY,
1232 #if defined(WIN32) || defined(_WIN32)
1234 close(context->fd_random);
1237 #ifdef LWS_OPENSSL_SUPPORT
1238 if (context->ssl_ctx)
1239 SSL_CTX_free(context->ssl_ctx);
1240 if (context->ssl_client_ctx)
1241 SSL_CTX_free(context->ssl_client_ctx);
1243 ERR_remove_state(0);
1246 CRYPTO_cleanup_all_ex_data();
1251 if (context->lws_lookup)
1252 free(context->lws_lookup);
1256 #if defined(WIN32) || defined(_WIN32)
1262 * libwebsocket_context_user() - get the user data associated with the context
1263 * @context: Websocket context
1265 * This returns the optional user allocation that can be attached to
1266 * the context the sockets live in at context_create time. It's a way
1267 * to let all sockets serviced in the same context share data without
1268 * using globals statics in the user code.
1271 libwebsocket_context_user(struct libwebsocket_context *context)
1273 return context->user_space;
1277 * libwebsocket_service() - Service any pending websocket activity
1278 * @context: Websocket context
1279 * @timeout_ms: Timeout for poll; 0 means return immediately if nothing needed
1280 * service otherwise block and service immediately, returning
1281 * after the timeout if nothing needed service.
1283 * This function deals with any pending websocket traffic, for three
1284 * kinds of event. It handles these events on both server and client
1285 * types of connection the same.
1287 * 1) Accept new connections to our context's server
1289 * 2) Call the receive callback for incoming frame data received by
1290 * server or client connections.
1292 * You need to call this service function periodically to all the above
1293 * functions to happen; if your application is single-threaded you can
1294 * just call it in your main event loop.
1296 * Alternatively you can fork a new process that asynchronously handles
1297 * calling this service in a loop. In that case you are happy if this
1298 * call blocks your thread until it needs to take care of something and
1299 * would call it with a large nonzero timeout. Your loop then takes no
1300 * CPU while there is nothing happening.
1302 * If you are calling it in a single-threaded app, you don't want it to
1303 * wait around blocking other things in your loop from happening, so you
1304 * would call it with a timeout_ms of 0, so it returns immediately if
1305 * nothing is pending, or as soon as it services whatever was pending.
1309 libwebsocket_service(struct libwebsocket_context *context, int timeout_ms)
1314 /* stay dead once we are dead */
1316 if (context == NULL)
1319 /* wait for something to need service */
1321 n = poll(context->fds, context->fds_count, timeout_ms);
1322 if (n == 0) /* poll timeout */ {
1323 libwebsocket_service_fd(context, NULL);
1330 /* any socket with events to service? */
1332 for (n = 0; n < context->fds_count; n++) {
1333 if (!context->fds[n].revents)
1335 m = libwebsocket_service_fd(context, &context->fds[n]);
1338 /* if something closed, retry this slot */
1346 #ifndef LWS_NO_EXTENSIONS
1348 lws_any_extension_handled(struct libwebsocket_context *context,
1349 struct libwebsocket *wsi,
1350 enum libwebsocket_extension_callback_reasons r,
1351 void *v, size_t len)
1356 /* maybe an extension will take care of it for us */
1358 for (n = 0; n < wsi->count_active_extensions && !handled; n++) {
1359 if (!wsi->active_extensions[n]->callback)
1362 handled |= wsi->active_extensions[n]->callback(context,
1363 wsi->active_extensions[n], wsi,
1364 r, wsi->active_extensions_user[n], v, len);
1372 lws_get_extension_user_matching_ext(struct libwebsocket *wsi,
1373 struct libwebsocket_extension *ext)
1380 while (n < wsi->count_active_extensions) {
1381 if (wsi->active_extensions[n] != ext) {
1385 return wsi->active_extensions_user[n];
1393 * libwebsocket_callback_on_writable() - Request a callback when this socket
1394 * becomes able to be written to without
1397 * @context: libwebsockets context
1398 * @wsi: Websocket connection instance to get callback for
1402 libwebsocket_callback_on_writable(struct libwebsocket_context *context,
1403 struct libwebsocket *wsi)
1405 #ifndef LWS_NO_EXTENSIONS
1409 /* maybe an extension will take care of it for us */
1411 for (n = 0; n < wsi->count_active_extensions; n++) {
1412 if (!wsi->active_extensions[n]->callback)
1415 handled |= wsi->active_extensions[n]->callback(context,
1416 wsi->active_extensions[n], wsi,
1417 LWS_EXT_CALLBACK_REQUEST_ON_WRITEABLE,
1418 wsi->active_extensions_user[n], NULL, 0);
1424 if (wsi->position_in_fds_table < 0) {
1425 lwsl_err("libwebsocket_callback_on_writable: failed to find socket %d\n",
1430 context->fds[wsi->position_in_fds_table].events |= POLLOUT;
1432 /* external POLL support via protocol 0 */
1433 context->protocols[0].callback(context, wsi,
1434 LWS_CALLBACK_SET_MODE_POLL_FD,
1435 wsi->user_space, (void *)(long)wsi->sock, POLLOUT);
1441 * libwebsocket_callback_on_writable_all_protocol() - Request a callback for
1442 * all connections using the given protocol when it
1443 * becomes possible to write to each socket without
1446 * @protocol: Protocol whose connections will get callbacks
1450 libwebsocket_callback_on_writable_all_protocol(
1451 const struct libwebsocket_protocols *protocol)
1453 struct libwebsocket_context *context = protocol->owning_server;
1455 struct libwebsocket *wsi;
1457 for (n = 0; n < context->fds_count; n++) {
1458 wsi = context->lws_lookup[context->fds[n].fd];
1461 if (wsi->protocol == protocol)
1462 libwebsocket_callback_on_writable(context, wsi);
1469 * libwebsocket_set_timeout() - marks the wsi as subject to a timeout
1471 * You will not need this unless you are doing something special
1473 * @wsi: Websocket connection instance
1474 * @reason: timeout reason
1475 * @secs: how many seconds
1479 libwebsocket_set_timeout(struct libwebsocket *wsi,
1480 enum pending_timeout reason, int secs)
1484 gettimeofday(&tv, NULL);
1486 wsi->pending_timeout_limit = tv.tv_sec + secs;
1487 wsi->pending_timeout = reason;
1492 * libwebsocket_get_socket_fd() - returns the socket file descriptor
1494 * You will not need this unless you are doing something special
1496 * @wsi: Websocket connection instance
1500 libwebsocket_get_socket_fd(struct libwebsocket *wsi)
1507 lws_latency(struct libwebsocket_context *context, struct libwebsocket *wsi,
1508 const char *action, int ret, int completed)
1514 gettimeofday(&tv, NULL);
1516 u = (tv.tv_sec * 1000000) + tv.tv_usec;
1520 if (wsi->action_start == wsi->latency_start)
1522 "Completion first try lat %luus: %p: ret %d: %s\n",
1523 u - wsi->latency_start,
1524 (void *)wsi, ret, action);
1527 "Completion %luus: lat %luus: %p: ret %d: %s\n",
1528 u - wsi->action_start,
1529 u - wsi->latency_start,
1530 (void *)wsi, ret, action);
1531 wsi->action_start = 0;
1533 sprintf(buf, "lat %luus: %p: ret %d: %s\n",
1534 u - wsi->latency_start,
1535 (void *)wsi, ret, action);
1536 if (u - wsi->latency_start > context->worst_latency) {
1537 context->worst_latency = u - wsi->latency_start;
1538 strcpy(context->worst_latency_info, buf);
1540 lwsl_latency("%s", buf);
1542 wsi->latency_start = u;
1543 if (!wsi->action_start)
1544 wsi->action_start = u;
1549 #ifdef LWS_NO_SERVER
1551 _libwebsocket_rx_flow_control(struct libwebsocket *wsi)
1557 _libwebsocket_rx_flow_control(struct libwebsocket *wsi)
1559 struct libwebsocket_context *context = wsi->protocol->owning_server;
1561 /* there is no pending change */
1562 if (!(wsi->u.ws.rxflow_change_to & LWS_RXFLOW_PENDING_CHANGE))
1565 /* stuff is still buffered, not ready to really accept new input */
1566 if (wsi->u.ws.rxflow_buffer) {
1567 /* get ourselves called back to deal with stashed buffer */
1568 libwebsocket_callback_on_writable(context, wsi);
1572 /* pending is cleared, we can change rxflow state */
1574 wsi->u.ws.rxflow_change_to &= ~LWS_RXFLOW_PENDING_CHANGE;
1576 lwsl_info("rxflow: wsi %p change_to %d\n", wsi,
1577 wsi->u.ws.rxflow_change_to & LWS_RXFLOW_ALLOW);
1579 /* adjust the pollfd for this wsi */
1581 if (wsi->u.ws.rxflow_change_to & LWS_RXFLOW_ALLOW)
1582 context->fds[wsi->position_in_fds_table].events |= POLLIN;
1584 context->fds[wsi->position_in_fds_table].events &= ~POLLIN;
1586 if (wsi->u.ws.rxflow_change_to & LWS_RXFLOW_ALLOW)
1587 /* external POLL support via protocol 0 */
1588 context->protocols[0].callback(context, wsi,
1589 LWS_CALLBACK_SET_MODE_POLL_FD,
1590 wsi->user_space, (void *)(long)wsi->sock, POLLIN);
1592 /* external POLL support via protocol 0 */
1593 context->protocols[0].callback(context, wsi,
1594 LWS_CALLBACK_CLEAR_MODE_POLL_FD,
1595 wsi->user_space, (void *)(long)wsi->sock, POLLIN);
1602 * libwebsocket_rx_flow_control() - Enable and disable socket servicing for
1603 * receieved packets.
1605 * If the output side of a server process becomes choked, this allows flow
1606 * control for the input side.
1608 * @wsi: Websocket connection instance to get callback for
1609 * @enable: 0 = disable read servicing for this connection, 1 = enable
1613 libwebsocket_rx_flow_control(struct libwebsocket *wsi, int enable)
1615 if (enable == (wsi->u.ws.rxflow_change_to & LWS_RXFLOW_ALLOW))
1618 lwsl_info("libwebsocket_rx_flow_control(0x%p, %d)\n", wsi, enable);
1619 wsi->u.ws.rxflow_change_to = LWS_RXFLOW_PENDING_CHANGE | !!enable;
1625 * libwebsocket_rx_flow_allow_all_protocol() - Allow all connections with this protocol to receive
1627 * When the user server code realizes it can accept more input, it can
1628 * call this to have the RX flow restriction removed from all connections using
1629 * the given protocol.
1631 * @protocol: all connections using this protocol will be allowed to receive
1635 libwebsocket_rx_flow_allow_all_protocol(
1636 const struct libwebsocket_protocols *protocol)
1638 struct libwebsocket_context *context = protocol->owning_server;
1640 struct libwebsocket *wsi;
1642 for (n = 0; n < context->fds_count; n++) {
1643 wsi = context->lws_lookup[context->fds[n].fd];
1646 if (wsi->protocol == protocol)
1647 libwebsocket_rx_flow_control(wsi, LWS_RXFLOW_ALLOW);
1653 * libwebsocket_canonical_hostname() - returns this host's hostname
1655 * This is typically used by client code to fill in the host parameter
1656 * when making a client connection. You can only call it after the context
1659 * @context: Websocket context
1663 LWS_VISIBLE extern const char *
1664 libwebsocket_canonical_hostname(struct libwebsocket_context *context)
1666 return (const char *)context->canonical_hostname;
1670 static void sigpipe_handler(int x)
1674 #ifdef LWS_OPENSSL_SUPPORT
1676 OpenSSL_verify_callback(int preverify_ok, X509_STORE_CTX *x509_ctx)
1681 struct libwebsocket_context *context;
1683 ssl = X509_STORE_CTX_get_ex_data(x509_ctx,
1684 SSL_get_ex_data_X509_STORE_CTX_idx());
1687 * !!! nasty openssl requires the index to come as a library-scope
1690 context = SSL_get_ex_data(ssl, openssl_websocket_private_data_index);
1692 n = context->protocols[0].callback(NULL, NULL,
1693 LWS_CALLBACK_OPENSSL_PERFORM_CLIENT_CERT_VERIFICATION,
1694 x509_ctx, ssl, preverify_ok);
1696 /* convert return code from 0 = OK to 1 = OK */
1707 int user_callback_handle_rxflow(callback_function callback_function,
1708 struct libwebsocket_context *context,
1709 struct libwebsocket *wsi,
1710 enum libwebsocket_callback_reasons reason, void *user,
1711 void *in, size_t len)
1715 n = callback_function(context, wsi, reason, user, in, len);
1717 n = _libwebsocket_rx_flow_control(wsi);
1724 * libwebsocket_create_context() - Create the websocket handler
1725 * @info: pointer to struct with parameters
1727 * This function creates the listening socket (if serving) and takes care
1728 * of all initialization in one step.
1730 * After initialization, it returns a struct libwebsocket_context * that
1731 * represents this server. After calling, user code needs to take care
1732 * of calling libwebsocket_service() with the context pointer to get the
1733 * server's sockets serviced. This can be done in the same process context
1734 * or a forked process, or another thread,
1736 * The protocol callback functions are called for a handful of events
1737 * including http requests coming in, websocket connections becoming
1738 * established, and data arriving; it's also called periodically to allow
1739 * async transmission.
1741 * HTTP requests are sent always to the FIRST protocol in @protocol, since
1742 * at that time websocket protocol has not been negotiated. Other
1743 * protocols after the first one never see any HTTP callack activity.
1745 * The server created is a simple http server by default; part of the
1746 * websocket standard is upgrading this http connection to a websocket one.
1748 * This allows the same server to provide files like scripts and favicon /
1749 * images or whatever over http and dynamic data over websockets all in
1750 * one place; they're all handled in the user callback.
1753 LWS_VISIBLE struct libwebsocket_context *
1754 libwebsocket_create_context(struct lws_context_creation_info *info)
1756 struct libwebsocket_context *context = NULL;
1759 #ifndef LWS_NO_SERVER
1761 struct libwebsocket *wsi;
1762 struct sockaddr_in serv_addr;
1764 #ifndef LWS_NO_EXTENSIONS
1766 struct libwebsocket_extension *ext;
1769 #ifdef LWS_OPENSSL_SUPPORT
1773 #ifndef LWS_NO_DAEMONIZE
1774 int pid_daemon = get_daemonize_pid();
1777 lwsl_notice("Initial logging level %d\n", log_level);
1778 lwsl_notice("Library version: %s\n", library_version);
1779 lwsl_info(" LWS_MAX_HEADER_LEN: %u\n", LWS_MAX_HEADER_LEN);
1780 lwsl_info(" LWS_MAX_PROTOCOLS: %u\n", LWS_MAX_PROTOCOLS);
1781 #ifndef LWS_NO_EXTENSIONS
1782 lwsl_info(" LWS_MAX_EXTENSIONS_ACTIVE: %u\n",
1783 LWS_MAX_EXTENSIONS_ACTIVE);
1785 lwsl_notice(" Configured without extension support\n");
1787 lwsl_info(" SPEC_LATEST_SUPPORTED: %u\n", SPEC_LATEST_SUPPORTED);
1788 lwsl_info(" AWAITING_TIMEOUT: %u\n", AWAITING_TIMEOUT);
1789 if (info->ssl_cipher_list)
1790 lwsl_info(" SSL ciphers: '%s'\n", info->ssl_cipher_list);
1791 lwsl_info(" SYSTEM_RANDOM_FILEPATH: '%s'\n", SYSTEM_RANDOM_FILEPATH);
1792 lwsl_info(" LWS_MAX_ZLIB_CONN_BUFFER: %u\n", LWS_MAX_ZLIB_CONN_BUFFER);
1796 WORD wVersionRequested;
1801 /* Use the MAKEWORD(lowbyte, highbyte) macro from Windef.h */
1802 wVersionRequested = MAKEWORD(2, 2);
1804 err = WSAStartup(wVersionRequested, &wsaData);
1806 /* Tell the user that we could not find a usable */
1808 lwsl_err("WSAStartup failed with error: %d\n", err);
1812 /* default to a poll() made out of select() */
1813 poll = emulated_poll;
1815 /* if windows socket lib available, use his WSAPoll */
1816 wsdll = GetModuleHandle(_T("Ws2_32.dll"));
1818 poll = (PFNWSAPOLL)GetProcAddress(wsdll, "WSAPoll");
1820 /* Finally fall back to emulated poll if all else fails */
1822 poll = emulated_poll;
1826 context = (struct libwebsocket_context *)
1827 malloc(sizeof(struct libwebsocket_context));
1829 lwsl_err("No memory for websocket context\n");
1832 memset(context, 0, sizeof(*context));
1833 #ifndef LWS_NO_DAEMONIZE
1834 context->started_with_parent = pid_daemon;
1835 lwsl_notice(" Started with daemon pid %d\n", pid_daemon);
1838 context->listen_service_extraseen = 0;
1839 context->protocols = info->protocols;
1840 context->listen_port = info->port;
1841 context->http_proxy_port = 0;
1842 context->http_proxy_address[0] = '\0';
1843 context->options = info->options;
1844 /* to reduce this allocation, */
1845 context->max_fds = getdtablesize();
1846 lwsl_notice(" static allocation: %u + (%u x %u fds) = %u bytes\n",
1847 sizeof(struct libwebsocket_context),
1848 sizeof(struct pollfd) + sizeof(struct libwebsocket *),
1850 sizeof(struct libwebsocket_context) +
1851 ((sizeof(struct pollfd) + sizeof(struct libwebsocket *)) *
1854 context->fds = (struct pollfd *)malloc(sizeof(struct pollfd) *
1856 if (context->fds == NULL) {
1857 lwsl_err("Unable to allocate fds array for %d connections\n",
1862 context->lws_lookup = (struct libwebsocket **)
1863 malloc(sizeof(struct libwebsocket *) * context->max_fds);
1864 if (context->lws_lookup == NULL) {
1866 "Unable to allocate lws_lookup array for %d connections\n",
1872 memset(context->lws_lookup, 0, sizeof(struct libwebsocket *) *
1875 context->fds_count = 0;
1876 #ifndef LWS_NO_EXTENSIONS
1877 context->extensions = info->extensions;
1879 context->last_timeout_check_s = 0;
1880 context->user_space = info->user;
1882 #if defined(WIN32) || defined(_WIN32)
1883 context->fd_random = 0;
1885 context->fd_random = open(SYSTEM_RANDOM_FILEPATH, O_RDONLY);
1886 if (context->fd_random < 0) {
1887 lwsl_err("Unable to open random device %s %d\n",
1888 SYSTEM_RANDOM_FILEPATH, context->fd_random);
1893 #ifdef LWS_OPENSSL_SUPPORT
1894 context->use_ssl = 0;
1895 context->allow_non_ssl_on_ssl_port = 0;
1896 context->ssl_ctx = NULL;
1897 context->ssl_client_ctx = NULL;
1898 openssl_websocket_private_data_index = 0;
1901 strcpy(context->canonical_hostname, "unknown");
1903 #ifndef LWS_NO_SERVER
1904 if (!(info->options & LWS_SERVER_OPTION_SKIP_SERVER_CANONICAL_NAME)) {
1905 /* find canonical hostname */
1906 gethostname((char *)context->canonical_hostname,
1907 sizeof(context->canonical_hostname) - 1);
1909 lwsl_notice(" canonical_hostname = %s\n",
1910 context->canonical_hostname);
1914 /* split the proxy ads:port if given */
1916 p = getenv("http_proxy");
1918 strncpy(context->http_proxy_address, p,
1919 sizeof(context->http_proxy_address) - 1);
1920 context->http_proxy_address[
1921 sizeof(context->http_proxy_address) - 1] = '\0';
1923 p = strchr(context->http_proxy_address, ':');
1925 lwsl_err("http_proxy needs to be ads:port\n");
1929 context->http_proxy_port = atoi(p + 1);
1931 lwsl_notice(" Proxy %s:%u\n",
1932 context->http_proxy_address,
1933 context->http_proxy_port);
1936 #ifndef LWS_NO_SERVER
1939 #ifdef LWS_OPENSSL_SUPPORT
1940 context->use_ssl = info->ssl_cert_filepath != NULL &&
1941 info->ssl_private_key_filepath != NULL;
1943 lwsl_notice(" Compiled with CYASSL support\n");
1945 lwsl_notice(" Compiled with OpenSSL support\n");
1947 if (context->use_ssl)
1948 lwsl_notice(" Using SSL mode\n");
1950 lwsl_notice(" Using non-SSL mode\n");
1953 if (info->ssl_cert_filepath != NULL &&
1954 info->ssl_private_key_filepath != NULL) {
1955 lwsl_notice(" Not compiled for OpenSSl support!\n");
1958 lwsl_notice(" Compiled without SSL support\n");
1962 " per-conn mem: %u + %u headers + protocol rx buf\n",
1963 sizeof(struct libwebsocket),
1964 sizeof(struct allocated_headers));
1968 /* ignore SIGPIPE */
1969 #if defined(WIN32) || defined(_WIN32)
1971 signal(SIGPIPE, sigpipe_handler);
1975 #ifdef LWS_OPENSSL_SUPPORT
1977 /* basic openssl init */
1981 OpenSSL_add_all_algorithms();
1982 SSL_load_error_strings();
1984 openssl_websocket_private_data_index =
1985 SSL_get_ex_new_index(0, "libwebsockets", NULL, NULL, NULL);
1988 * Firefox insists on SSLv23 not SSLv3
1989 * Konq disables SSLv2 by default now, SSLv23 works
1992 method = (SSL_METHOD *)SSLv23_server_method();
1994 int error = ERR_get_error();
1995 lwsl_err("problem creating ssl method %lu: %s\n",
1997 ERR_error_string(error,
1998 (char *)context->service_buffer));
2001 context->ssl_ctx = SSL_CTX_new(method); /* create context */
2002 if (!context->ssl_ctx) {
2003 int error = ERR_get_error();
2004 lwsl_err("problem creating ssl context %lu: %s\n",
2006 ERR_error_string(error,
2007 (char *)context->service_buffer));
2011 #ifdef SSL_OP_NO_COMPRESSION
2012 SSL_CTX_set_options(context->ssl_ctx, SSL_OP_NO_COMPRESSION);
2014 SSL_CTX_set_options(context->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
2015 if (info->ssl_cipher_list)
2016 SSL_CTX_set_cipher_list(context->ssl_ctx,
2017 info->ssl_cipher_list);
2019 #ifndef LWS_NO_CLIENT
2021 /* client context */
2023 if (info->port == CONTEXT_PORT_NO_LISTEN) {
2024 method = (SSL_METHOD *)SSLv23_client_method();
2026 int error = ERR_get_error();
2027 lwsl_err("problem creating ssl method %lu: %s\n",
2029 ERR_error_string(error,
2030 (char *)context->service_buffer));
2033 /* create context */
2034 context->ssl_client_ctx = SSL_CTX_new(method);
2035 if (!context->ssl_client_ctx) {
2036 int error = ERR_get_error();
2037 lwsl_err("problem creating ssl context %lu: %s\n",
2039 ERR_error_string(error,
2040 (char *)context->service_buffer));
2044 #ifdef SSL_OP_NO_COMPRESSION
2045 SSL_CTX_set_options(context->ssl_client_ctx,
2046 SSL_OP_NO_COMPRESSION);
2048 SSL_CTX_set_options(context->ssl_client_ctx,
2049 SSL_OP_CIPHER_SERVER_PREFERENCE);
2050 if (info->ssl_cipher_list)
2051 SSL_CTX_set_cipher_list(context->ssl_client_ctx,
2052 info->ssl_cipher_list);
2054 /* openssl init for cert verification (for client sockets) */
2055 if (!info->ssl_ca_filepath) {
2056 if (!SSL_CTX_load_verify_locations(
2057 context->ssl_client_ctx, NULL,
2058 LWS_OPENSSL_CLIENT_CERTS))
2060 "Unable to load SSL Client certs from %s "
2061 "(set by --with-client-cert-dir= "
2062 "in configure) -- client ssl isn't "
2063 "going to work", LWS_OPENSSL_CLIENT_CERTS);
2065 if (!SSL_CTX_load_verify_locations(
2066 context->ssl_client_ctx, info->ssl_ca_filepath,
2069 "Unable to load SSL Client certs "
2070 "file from %s -- client ssl isn't "
2071 "going to work", info->ssl_ca_filepath);
2074 * callback allowing user code to load extra verification certs
2075 * helping the client to verify server identity
2078 /* support for client-side certificate authentication */
2079 if (info->ssl_cert_filepath) {
2080 n = SSL_CTX_use_certificate_chain_file(
2081 context->ssl_client_ctx,
2082 info->ssl_cert_filepath);
2084 lwsl_err("problem getting cert '%s' %lu: %s\n",
2085 info->ssl_cert_filepath,
2087 ERR_error_string(ERR_get_error(),
2088 (char *)context->service_buffer));
2092 if (info->ssl_private_key_filepath) {
2093 /* set the private key from KeyFile */
2094 if (SSL_CTX_use_PrivateKey_file(context->ssl_client_ctx,
2095 info->ssl_private_key_filepath,
2096 SSL_FILETYPE_PEM) != 1) {
2097 lwsl_err("use_PrivateKey_file '%s' %lu: %s\n",
2098 info->ssl_private_key_filepath,
2100 ERR_error_string(ERR_get_error(),
2101 (char *)context->service_buffer));
2105 /* verify private key */
2106 if (!SSL_CTX_check_private_key(context->ssl_client_ctx)) {
2107 lwsl_err("Private SSL key doesn't match cert\n");
2112 context->protocols[0].callback(context, NULL,
2113 LWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS,
2114 context->ssl_client_ctx, NULL, 0);
2118 /* as a server, are we requiring clients to identify themselves? */
2121 LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT) {
2123 /* absolutely require the client cert */
2125 SSL_CTX_set_verify(context->ssl_ctx,
2126 SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
2127 OpenSSL_verify_callback);
2130 * give user code a chance to load certs into the server
2131 * allowing it to verify incoming client certs
2134 context->protocols[0].callback(context, NULL,
2135 LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS,
2136 context->ssl_ctx, NULL, 0);
2139 if(info->options & LWS_SERVER_OPTION_ALLOW_NON_SSL_ON_SSL_PORT) {
2140 /* Normally SSL listener rejects non-ssl, optionally allow */
2141 context->allow_non_ssl_on_ssl_port = 1;
2144 if (context->use_ssl) {
2146 /* openssl init for server sockets */
2148 /* set the local certificate from CertFile */
2149 n = SSL_CTX_use_certificate_chain_file(context->ssl_ctx,
2150 info->ssl_cert_filepath);
2152 int error = ERR_get_error();
2153 lwsl_err("problem getting cert '%s' %lu: %s\n",
2154 info->ssl_cert_filepath,
2156 ERR_error_string(error,
2157 (char *)context->service_buffer));
2160 /* set the private key from KeyFile */
2161 if (SSL_CTX_use_PrivateKey_file(context->ssl_ctx,
2162 info->ssl_private_key_filepath,
2163 SSL_FILETYPE_PEM) != 1) {
2164 int error = ERR_get_error();
2165 lwsl_err("ssl problem getting key '%s' %lu: %s\n",
2166 info->ssl_private_key_filepath,
2168 ERR_error_string(error,
2169 (char *)context->service_buffer));
2172 /* verify private key */
2173 if (!SSL_CTX_check_private_key(context->ssl_ctx)) {
2174 lwsl_err("Private SSL key doesn't match cert\n");
2178 /* SSL is happy and has a cert it's content with */
2182 #ifndef LWS_NO_SERVER
2183 /* set up our external listening socket we serve on */
2188 sockfd = socket(AF_INET, SOCK_STREAM, 0);
2190 lwsl_err("ERROR opening socket\n");
2196 * allow us to restart even if old sockets in TIME_WAIT
2197 * (REUSEADDR on Unix means, "don't hang on to this
2198 * address after the listener is closed." On Windows, though,
2199 * it means "don't keep other processes from binding to
2200 * this address while we're using it)
2202 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
2203 (const void *)&opt, sizeof(opt));
2208 setsockopt(sockfd, IPPROTO_TCP, TCP_NODELAY,
2209 (const void *)&opt, sizeof(opt));
2211 #if defined(WIN32) || defined(_WIN32)
2213 ioctlsocket(sockfd, FIONBIO, (unsigned long *)&opt);
2215 fcntl(sockfd, F_SETFL, O_NONBLOCK);
2218 bzero((char *) &serv_addr, sizeof(serv_addr));
2219 serv_addr.sin_family = AF_INET;
2220 if (info->iface == NULL)
2221 serv_addr.sin_addr.s_addr = INADDR_ANY;
2223 if (interface_to_sa(info->iface, &serv_addr,
2224 sizeof(serv_addr)) < 0) {
2225 lwsl_err("Unable to find interface %s\n",
2227 compatible_close(sockfd);
2230 serv_addr.sin_port = htons(info->port);
2232 n = bind(sockfd, (struct sockaddr *) &serv_addr,
2235 lwsl_err("ERROR on binding to port %d (%d %d)\n",
2236 info->port, n, errno);
2237 compatible_close(sockfd);
2241 wsi = (struct libwebsocket *)malloc(
2242 sizeof(struct libwebsocket));
2244 lwsl_err("Out of mem\n");
2245 compatible_close(sockfd);
2248 memset(wsi, 0, sizeof(struct libwebsocket));
2250 #ifndef LWS_NO_EXTENSIONS
2251 wsi->count_active_extensions = 0;
2253 wsi->mode = LWS_CONNMODE_SERVER_LISTENER;
2255 insert_wsi_socket_into_fds(context, wsi);
2257 context->listen_service_modulo = LWS_LISTEN_SERVICE_MODULO;
2258 context->listen_service_count = 0;
2259 context->listen_service_fd = sockfd;
2261 listen(sockfd, LWS_SOMAXCONN);
2262 lwsl_notice(" Listening on port %d\n", info->port);
2267 * drop any root privs for this process
2268 * to listen on port < 1023 we would have needed root, but now we are
2269 * listening, we don't want the power for anything else
2271 #if defined(WIN32) || defined(_WIN32)
2273 if (info->gid != -1)
2274 if (setgid(info->gid))
2275 lwsl_warn("setgid: %s\n", strerror(errno));
2276 if (info->uid != -1)
2277 if (setuid(info->uid))
2278 lwsl_warn("setuid: %s\n", strerror(errno));
2281 /* initialize supported protocols */
2283 for (context->count_protocols = 0;
2284 info->protocols[context->count_protocols].callback;
2285 context->count_protocols++) {
2287 lwsl_parser(" Protocol: %s\n",
2288 info->protocols[context->count_protocols].name);
2290 info->protocols[context->count_protocols].owning_server =
2292 info->protocols[context->count_protocols].protocol_index =
2293 context->count_protocols;
2296 * inform all the protocols that they are doing their one-time
2297 * initialization if they want to
2299 info->protocols[context->count_protocols].callback(context,
2300 NULL, LWS_CALLBACK_PROTOCOL_INIT, NULL, NULL, 0);
2303 #ifndef LWS_NO_EXTENSIONS
2305 * give all extensions a chance to create any per-context
2306 * allocations they need
2309 m = LWS_EXT_CALLBACK_CLIENT_CONTEXT_CONSTRUCT;
2311 m = LWS_EXT_CALLBACK_SERVER_CONTEXT_CONSTRUCT;
2313 if (info->extensions) {
2314 ext = info->extensions;
2315 while (ext->callback) {
2316 lwsl_ext(" Extension: %s\n", ext->name);
2317 ext->callback(context, ext, NULL,
2318 (enum libwebsocket_extension_callback_reasons)m,
2327 libwebsocket_context_destroy(context);
2332 * libwebsocket_set_proxy() - Setups proxy to libwebsocket_context.
2333 * @context: pointer to struct libwebsocket_context you want set proxy to
2334 * @proxy: pointer to c string containing proxy in format address:port
2336 * Returns 0 if proxy string was parsed and proxy was setup.
2337 * Returns -1 if @proxy is NULL or has incorrect format.
2339 * This is only required if your OS does not provide the http_proxy
2340 * enviroment variable (eg, OSX)
2342 * IMPORTANT! You should call this function right after creation of the
2343 * libwebsocket_context and before call to connect. If you call this
2344 * function after connect behavior is undefined.
2345 * This function will override proxy settings made on libwebsocket_context
2346 * creation with genenv() call.
2350 libwebsocket_set_proxy(struct libwebsocket_context *context, const char *proxy)
2357 strncpy(context->http_proxy_address, proxy,
2358 sizeof(context->http_proxy_address) - 1);
2359 context->http_proxy_address[
2360 sizeof(context->http_proxy_address) - 1] = '\0';
2362 p = strchr(context->http_proxy_address, ':');
2364 lwsl_err("http_proxy needs to be ads:port\n");
2369 context->http_proxy_port = atoi(p + 1);
2371 lwsl_notice(" Proxy %s:%u\n", context->http_proxy_address,
2372 context->http_proxy_port);
2378 * libwebsockets_get_protocol() - Returns a protocol pointer from a websocket
2380 * @wsi: pointer to struct websocket you want to know the protocol of
2383 * Some apis can act on all live connections of a given protocol,
2384 * this is how you can get a pointer to the active protocol if needed.
2387 LWS_VISIBLE const struct libwebsocket_protocols *
2388 libwebsockets_get_protocol(struct libwebsocket *wsi)
2390 return wsi->protocol;
2394 libwebsocket_is_final_fragment(struct libwebsocket *wsi)
2396 return wsi->u.ws.final;
2399 LWS_VISIBLE unsigned char
2400 libwebsocket_get_reserved_bits(struct libwebsocket *wsi)
2402 return wsi->u.ws.rsv;
2406 libwebsocket_ensure_user_space(struct libwebsocket *wsi)
2411 /* allocate the per-connection user memory (if any) */
2413 if (wsi->protocol->per_session_data_size && !wsi->user_space) {
2414 wsi->user_space = malloc(
2415 wsi->protocol->per_session_data_size);
2416 if (wsi->user_space == NULL) {
2417 lwsl_err("Out of memory for conn user space\n");
2420 memset(wsi->user_space, 0,
2421 wsi->protocol->per_session_data_size);
2426 static void lwsl_emit_stderr(int level, const char *line)
2432 gettimeofday(&tv, NULL);
2435 for (n = 0; n < LLL_COUNT; n++)
2436 if (level == (1 << n)) {
2437 sprintf(buf, "[%ld:%04d] %s: ", tv.tv_sec,
2438 (int)(tv.tv_usec / 100), log_level_names[n]);
2442 fprintf(stderr, "%s%s", buf, line);
2445 #if defined(WIN32) || defined(_WIN32)
2446 LWS_VISIBLE void lwsl_emit_syslog(int level, const char *line)
2448 lwsl_emit_stderr(level, line);
2451 LWS_VISIBLE void lwsl_emit_syslog(int level, const char *line)
2453 int syslog_level = LOG_DEBUG;
2457 syslog_level = LOG_ERR;
2460 syslog_level = LOG_WARNING;
2463 syslog_level = LOG_NOTICE;
2466 syslog_level = LOG_INFO;
2469 syslog(syslog_level, "%s", line);
2473 LWS_VISIBLE void _lws_log(int filter, const char *format, ...)
2478 if (!(log_level & filter))
2481 va_start(ap, format);
2482 vsnprintf(buf, sizeof(buf), format, ap);
2483 buf[sizeof(buf) - 1] = '\0';
2486 lwsl_emit(filter, buf);
2490 * lws_set_log_level() - Set the logging bitfield
2491 * @level: OR together the LLL_ debug contexts you want output from
2492 * @log_emit_function: NULL to leave it as it is, or a user-supplied
2493 * function to perform log string emission instead of
2494 * the default stderr one.
2496 * log level defaults to "err", "warn" and "notice" contexts enabled and
2497 * emission on stderr.
2500 LWS_VISIBLE void lws_set_log_level(int level, void (*log_emit_function)(int level,
2504 if (log_emit_function)
2505 lwsl_emit = log_emit_function;