2 * libwebsockets - small server side websockets and web server implementation
4 * Copyright (C) 2010 Andy Green <andy@warmcat.com>
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation:
9 * version 2.1 of the License.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
22 #include "private-libwebsockets.h"
29 #ifdef LWS_BUILTIN_GETIFADDRS
30 #include <getifaddrs.h>
36 #include <sys/socket.h>
40 #ifdef 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
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);
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_HTTP_SERVING && wsi->u.http.fd) {
210 close(wsi->u.http.fd);
214 #ifndef LWS_NO_EXTENSIONS
216 * are his extensions okay with him closing? Eg he might be a mux
217 * parent and just his ch1 aspect is closing?
220 for (n = 0; n < wsi->count_active_extensions; n++) {
221 if (!wsi->active_extensions[n]->callback)
224 m = wsi->active_extensions[n]->callback(context,
225 wsi->active_extensions[n], wsi,
226 LWS_EXT_CALLBACK_CHECK_OK_TO_REALLY_CLOSE,
227 wsi->active_extensions_user[n], NULL, 0);
230 * if somebody vetoed actually closing him at this time....
231 * up to the extension to track the attempted close, let's
236 lwsl_ext("extension vetoed close\n");
242 * flush any tx pending from extensions, since we may send close packet
243 * if there are problems with send, just nuke the connection
249 /* default to nobody has more to spill */
252 eff_buf.token = NULL;
253 eff_buf.token_len = 0;
255 /* show every extension the new incoming data */
257 for (n = 0; n < wsi->count_active_extensions; n++) {
258 m = wsi->active_extensions[n]->callback(
259 wsi->protocol->owning_server,
260 wsi->active_extensions[n], wsi,
261 LWS_EXT_CALLBACK_FLUSH_PENDING_TX,
262 wsi->active_extensions_user[n], &eff_buf, 0);
264 lwsl_ext("Extension reports fatal error\n");
265 goto just_kill_connection;
269 * at least one extension told us he has more
270 * to spill, so we will go around again after
275 /* assuming they left us something to send, send it */
277 if (eff_buf.token_len)
278 if (lws_issue_raw(wsi, (unsigned char *)eff_buf.token,
279 eff_buf.token_len) != eff_buf.token_len) {
280 lwsl_debug("close: ext spill failed\n");
281 goto just_kill_connection;
287 * signal we are closing, libsocket_write will
288 * add any necessary version-specific stuff. If the write fails,
289 * no worries we are closing anyway. If we didn't initiate this
290 * close, then our state has been changed to
291 * WSI_STATE_RETURNED_CLOSE_ALREADY and we will skip this.
293 * Likewise if it's a second call to close this connection after we
294 * sent the close indication to the peer already, we are in state
295 * WSI_STATE_AWAITING_CLOSE_ACK and will skip doing this a second time.
298 if (old_state == WSI_STATE_ESTABLISHED &&
299 reason != LWS_CLOSE_STATUS_NOSTATUS) {
301 lwsl_debug("sending close indication...\n");
303 /* make valgrind happy */
304 memset(buf, 0, sizeof(buf));
305 n = libwebsocket_write(wsi,
306 &buf[LWS_SEND_BUFFER_PRE_PADDING + 2],
310 * we have sent a nice protocol level indication we
311 * now wish to close, we should not send anything more
314 wsi->state = WSI_STATE_AWAITING_CLOSE_ACK;
317 * ...and we should wait for a reply for a bit
321 libwebsocket_set_timeout(wsi,
322 PENDING_TIMEOUT_CLOSE_ACK, 1);
324 lwsl_debug("sent close indication, awaiting ack\n");
329 lwsl_info("close: sending close packet failed, hanging up\n");
331 /* else, the send failed and we should just hang up */
334 just_kill_connection:
336 lwsl_debug("close: just_kill_connection\n");
339 * we won't be servicing or receiving anything further from this guy
340 * delete socket from the internal poll list if still present
343 remove_wsi_socket_from_fds(context, wsi);
345 wsi->state = WSI_STATE_DEAD_SOCKET;
347 if ((old_state == WSI_STATE_ESTABLISHED ||
348 wsi->mode == LWS_CONNMODE_WS_SERVING ||
349 wsi->mode == LWS_CONNMODE_WS_CLIENT)) {
351 if (wsi->u.ws.rx_user_buffer) {
352 free(wsi->u.ws.rx_user_buffer);
353 wsi->u.ws.rx_user_buffer = NULL;
355 if (wsi->u.ws.rxflow_buffer) {
356 free(wsi->u.ws.rxflow_buffer);
357 wsi->u.ws.rxflow_buffer = NULL;
361 /* tell the user it's all over for this guy */
363 if (wsi->protocol && wsi->protocol->callback &&
364 ((old_state == WSI_STATE_ESTABLISHED) ||
365 (old_state == WSI_STATE_RETURNED_CLOSE_ALREADY) ||
366 (old_state == WSI_STATE_AWAITING_CLOSE_ACK))) {
367 lwsl_debug("calling back CLOSED\n");
368 wsi->protocol->callback(context, wsi, LWS_CALLBACK_CLOSED,
369 wsi->user_space, NULL, 0);
371 lwsl_debug("not calling back closed\n");
373 #ifndef LWS_NO_EXTENSIONS
374 /* deallocate any active extension contexts */
376 for (n = 0; n < wsi->count_active_extensions; n++) {
377 if (!wsi->active_extensions[n]->callback)
380 wsi->active_extensions[n]->callback(context,
381 wsi->active_extensions[n], wsi,
382 LWS_EXT_CALLBACK_DESTROY,
383 wsi->active_extensions_user[n], NULL, 0);
385 free(wsi->active_extensions_user[n]);
389 * inform all extensions in case they tracked this guy out of band
390 * even though not active on him specifically
393 ext = context->extensions;
394 while (ext && ext->callback) {
395 ext->callback(context, ext, wsi,
396 LWS_EXT_CALLBACK_DESTROY_ANY_WSI_CLOSING,
402 /* lwsl_info("closing fd=%d\n", wsi->sock); */
404 #ifdef LWS_OPENSSL_SUPPORT
406 n = SSL_get_fd(wsi->ssl);
407 SSL_shutdown(wsi->ssl);
413 n = shutdown(wsi->sock, SHUT_RDWR);
415 lwsl_debug("closing: shutdown returned %d\n",
418 n = compatible_close(wsi->sock);
420 lwsl_debug("closing: close returned %d\n",
423 #ifdef LWS_OPENSSL_SUPPORT
426 if (wsi->protocol && wsi->protocol->per_session_data_size &&
427 wsi->user_space) /* user code may own */
428 free(wsi->user_space);
434 * libwebsockets_get_peer_addresses() - Get client address information
435 * @context: Libwebsockets context
436 * @wsi: Local struct libwebsocket associated with
437 * @fd: Connection socket descriptor
438 * @name: Buffer to take client address name
439 * @name_len: Length of client address name buffer
440 * @rip: Buffer to take client address IP qotted quad
441 * @rip_len: Length of client address IP buffer
443 * This function fills in @name and @rip with the name and IP of
444 * the client connected with socket descriptor @fd. Names may be
445 * truncated if there is not enough room. If either cannot be
446 * determined, they will be returned as valid zero-length strings.
450 libwebsockets_get_peer_addresses(struct libwebsocket_context *context,
451 struct libwebsocket *wsi, int fd, char *name, int name_len,
452 char *rip, int rip_len)
455 struct sockaddr_in sin;
456 struct hostent *host;
457 struct hostent *host1;
463 struct sockaddr_un *un;
469 lws_latency_pre(context, wsi);
472 if (getpeername(fd, (struct sockaddr *) &sin, &len) < 0) {
473 perror("getpeername");
477 host = gethostbyaddr((char *) &sin.sin_addr, sizeof(sin.sin_addr),
480 perror("gethostbyaddr");
484 strncpy(name, host->h_name, name_len);
485 name[name_len - 1] = '\0';
487 host1 = gethostbyname(host->h_name);
490 p = (unsigned char *)host1;
493 p = (unsigned char *)host1->h_addr_list[n++];
496 if ((host1->h_addrtype != AF_INET)
498 && (host1->h_addrtype != AF_LOCAL)
503 if (host1->h_addrtype == AF_INET)
504 sprintf(ip, "%u.%u.%u.%u", p[0], p[1], p[2], p[3]);
507 un = (struct sockaddr_un *)p;
508 strncpy(ip, un->sun_path, sizeof(ip) - 1);
509 ip[sizeof(ip) - 1] = '\0';
513 strncpy(rip, ip, rip_len);
514 rip[rip_len - 1] = '\0';
519 lws_latency(context, wsi, "libwebsockets_get_peer_addresses", ret, 1);
522 int libwebsockets_get_random(struct libwebsocket_context *context,
526 char *p = (char *)buf;
529 for (n = 0; n < len; n++)
530 p[n] = (unsigned char)rand();
532 n = read(context->fd_random, p, len);
538 int lws_set_socket_options(struct libwebsocket_context *context, int fd)
541 socklen_t optlen = sizeof(optval);
543 unsigned long optl = 0;
545 #if defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__)
546 struct protoent *tcp_proto;
549 if (context->ka_time) {
550 /* enable keepalive on this socket */
552 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE,
553 (const void *)&optval, optlen) < 0)
556 #if defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__)
559 * didn't find a way to set these per-socket, need to
560 * tune kernel systemwide values
565 struct tcp_keepalive alive;
567 alive.keepalivetime = context->ka_time;
568 alive.keepaliveinterval = context->ka_interval;
570 if (WSAIoctl(fd, SIO_KEEPALIVE_VALS, &alive, sizeof(alive),
571 NULL, 0, &dwBytesRet, NULL, NULL))
575 /* set the keepalive conditions we want on it too */
576 optval = context->ka_time;
577 if (setsockopt(fd, IPPROTO_IP, TCP_KEEPIDLE,
578 (const void *)&optval, optlen) < 0)
581 optval = context->ka_interval;
582 if (setsockopt(fd, IPPROTO_IP, TCP_KEEPINTVL,
583 (const void *)&optval, optlen) < 0)
586 optval = context->ka_probes;
587 if (setsockopt(fd, IPPROTO_IP, TCP_KEEPCNT,
588 (const void *)&optval, optlen) < 0)
595 #if !defined(__APPLE__) && !defined(__FreeBSD__) && !defined(__NetBSD__)
596 setsockopt(fd, SOL_TCP, TCP_NODELAY, (const void *)&optval, optlen);
598 tcp_proto = getprotobyname("TCP");
599 setsockopt(fd, tcp_proto->p_proto, TCP_NODELAY, &optval, optlen);
602 /* We are nonblocking... */
604 ioctlsocket(fd, FIONBIO, &optl);
606 fcntl(fd, F_SETFL, O_NONBLOCK);
612 int lws_send_pipe_choked(struct libwebsocket *wsi)
617 fds.events = POLLOUT;
620 if (poll(&fds, 1, 0) != 1)
623 if ((fds.revents & POLLOUT) == 0)
626 /* okay to send another packet without blocking */
632 lws_handle_POLLOUT_event(struct libwebsocket_context *context,
633 struct libwebsocket *wsi, struct pollfd *pollfd)
637 #ifndef LWS_NO_EXTENSIONS
638 struct lws_tokens eff_buf;
643 for (n = 0; n < wsi->count_active_extensions; n++) {
644 if (!wsi->active_extensions[n]->callback)
647 m = wsi->active_extensions[n]->callback(context,
648 wsi->active_extensions[n], wsi,
649 LWS_EXT_CALLBACK_IS_WRITEABLE,
650 wsi->active_extensions_user[n], NULL, 0);
658 if (!wsi->extension_data_pending || handled == 2)
662 * check in on the active extensions, see if they
663 * had pending stuff to spill... they need to get the
664 * first look-in otherwise sequence will be disordered
666 * NULL, zero-length eff_buf means just spill pending
672 /* default to nobody has more to spill */
675 eff_buf.token = NULL;
676 eff_buf.token_len = 0;
678 /* give every extension a chance to spill */
680 for (n = 0; n < wsi->count_active_extensions; n++) {
681 m = wsi->active_extensions[n]->callback(
682 wsi->protocol->owning_server,
683 wsi->active_extensions[n], wsi,
684 LWS_EXT_CALLBACK_PACKET_TX_PRESEND,
685 wsi->active_extensions_user[n], &eff_buf, 0);
687 lwsl_err("ext reports fatal error\n");
692 * at least one extension told us he has more
693 * to spill, so we will go around again after
698 /* assuming they gave us something to send, send it */
700 if (eff_buf.token_len) {
701 n = lws_issue_raw(wsi, (unsigned char *)eff_buf.token,
706 * Keep amount spilled small to minimize chance of this
708 if (n != eff_buf.token_len) {
709 lwsl_err("Unable to spill ext %d vs %s\n",
710 eff_buf.token_len, n);
716 /* no extension has more to spill */
722 * There's more to spill from an extension, but we just sent
723 * something... did that leave the pipe choked?
726 if (!lws_send_pipe_choked(wsi))
727 /* no we could add more */
730 lwsl_info("choked in POLLOUT service\n");
733 * Yes, he's choked. Leave the POLLOUT masked on so we will
734 * come back here when he is unchoked. Don't call the user
735 * callback to enforce ordering of spilling, he'll get called
736 * when we come back here and there's nothing more to spill.
742 wsi->extension_data_pending = 0;
749 pollfd->events &= ~POLLOUT;
751 /* external POLL support via protocol 0 */
752 context->protocols[0].callback(context, wsi,
753 LWS_CALLBACK_CLEAR_MODE_POLL_FD,
754 wsi->user_space, (void *)(long)wsi->sock, POLLOUT);
756 #ifndef LWS_NO_EXTENSIONS
760 if (wsi->mode == LWS_CONNMODE_WS_CLIENT)
761 n = LWS_CALLBACK_CLIENT_WRITEABLE;
763 n = LWS_CALLBACK_SERVER_WRITEABLE;
765 return user_callback_handle_rxflow(wsi->protocol->callback, context,
766 wsi, (enum libwebsocket_callback_reasons) n,
767 wsi->user_space, NULL, 0);
773 libwebsocket_service_timeout_check(struct libwebsocket_context *context,
774 struct libwebsocket *wsi, unsigned int sec)
776 #ifndef LWS_NO_EXTENSIONS
780 * if extensions want in on it (eg, we are a mux parent)
781 * give them a chance to service child timeouts
784 for (n = 0; n < wsi->count_active_extensions; n++)
785 wsi->active_extensions[n]->callback(
786 context, wsi->active_extensions[n],
787 wsi, LWS_EXT_CALLBACK_1HZ,
788 wsi->active_extensions_user[n], NULL, sec);
791 if (!wsi->pending_timeout)
795 * if we went beyond the allowed time, kill the
799 if (sec > wsi->pending_timeout_limit) {
800 lwsl_info("TIMEDOUT WAITING\n");
801 libwebsocket_close_and_free_session(context,
802 wsi, LWS_CLOSE_STATUS_NOSTATUS);
810 * libwebsocket_service_fd() - Service polled socket with something waiting
811 * @context: Websocket context
812 * @pollfd: The pollfd entry describing the socket fd and which events
815 * This function takes a pollfd that has POLLIN or POLLOUT activity and
816 * services it according to the state of the associated
817 * struct libwebsocket.
819 * The one call deals with all "service" that might happen on a socket
820 * including listen accepts, http files as well as websocket protocol.
824 libwebsocket_service_fd(struct libwebsocket_context *context,
825 struct pollfd *pollfd)
827 struct libwebsocket *wsi;
830 int listen_socket_fds_index = 0;
835 #ifndef LWS_NO_EXTENSIONS
838 struct lws_tokens eff_buf;
840 if (context->listen_service_fd)
841 listen_socket_fds_index = context->lws_lookup[
842 context->listen_service_fd]->position_in_fds_table;
845 * you can call us with pollfd = NULL to just allow the once-per-second
846 * global timeout checks; if less than a second since the last check
847 * it returns immediately then.
850 gettimeofday(&tv, NULL);
852 if (context->last_timeout_check_s != tv.tv_sec) {
853 context->last_timeout_check_s = tv.tv_sec;
856 /* if our parent went down, don't linger around */
857 if (context->started_with_parent &&
858 kill(context->started_with_parent, 0) < 0)
859 kill(getpid(), SIGTERM);
862 /* global timeout check once per second */
867 for (n = 0; n < context->fds_count; n++) {
868 m = context->fds[n].fd;
869 wsi = context->lws_lookup[m];
873 if (libwebsocket_service_timeout_check(context, wsi,
875 /* he did time out... */
877 /* it was the guy we came to service! */
882 /* the socket we came to service timed out, nothing to do */
886 /* just here for timeout management? */
891 /* no, here to service a socket descriptor */
894 * deal with listen service piggybacking
895 * every listen_service_modulo services of other fds, we
896 * sneak one in to service the listen socket if there's anything waiting
898 * To handle connection storms, as found in ab, if we previously saw a
899 * pending connection here, it causes us to check again next time.
902 if (context->listen_service_fd && pollfd !=
903 &context->fds[listen_socket_fds_index]) {
904 context->listen_service_count++;
905 if (context->listen_service_extraseen ||
906 context->listen_service_count ==
907 context->listen_service_modulo) {
908 context->listen_service_count = 0;
910 if (context->listen_service_extraseen > 5)
914 * even with extpoll, we prepared this
915 * internal fds for listen
917 n = poll(&context->fds[listen_socket_fds_index],
919 if (n > 0) { /* there's a conn waiting for us */
920 libwebsocket_service_fd(context,
922 fds[listen_socket_fds_index]);
923 context->listen_service_extraseen++;
925 if (context->listen_service_extraseen)
927 listen_service_extraseen--;
935 /* okay, what we came here to do... */
937 wsi = context->lws_lookup[pollfd->fd];
940 lwsl_err("unexpected NULL wsi fd=%d fds_count=%d\n",
941 pollfd->fd, context->fds_count);
947 #ifndef LWS_NO_SERVER
948 case LWS_CONNMODE_HTTP_SERVING:
949 case LWS_CONNMODE_SERVER_LISTENER:
950 case LWS_CONNMODE_SSL_ACK_PENDING:
951 return lws_server_socket_service(context, wsi, pollfd);
954 case LWS_CONNMODE_WS_SERVING:
955 case LWS_CONNMODE_WS_CLIENT:
957 /* handle session socket closed */
959 if ((!pollfd->revents & POLLIN) &&
960 (pollfd->revents & (POLLERR | POLLHUP))) {
962 lwsl_debug("Session Socket %p (fd=%d) dead\n",
963 (void *)wsi, pollfd->fd);
965 libwebsocket_close_and_free_session(context, wsi,
966 LWS_CLOSE_STATUS_NOSTATUS);
970 /* the guy requested a callback when it was OK to write */
972 if ((pollfd->revents & POLLOUT) &&
973 wsi->state == WSI_STATE_ESTABLISHED)
974 if (lws_handle_POLLOUT_event(context, wsi,
976 lwsl_info("libwebsocket_service_fd: closing\n");
977 libwebsocket_close_and_free_session(
978 context, wsi, LWS_CLOSE_STATUS_NOSTATUS);
983 /* any incoming data ready? */
985 if (!(pollfd->revents & POLLIN))
988 #ifdef LWS_OPENSSL_SUPPORT
991 eff_buf.token_len = SSL_read(wsi->ssl,
992 context->service_buffer,
993 sizeof(context->service_buffer));
994 if (!eff_buf.token_len) {
995 n = SSL_get_error(wsi->ssl, eff_buf.token_len);
996 lwsl_err("SSL_read returned 0 with reason %s\n",
998 (char *)context->service_buffer));
1002 eff_buf.token_len = recv(pollfd->fd,
1003 context->service_buffer,
1004 sizeof(context->service_buffer), 0);
1006 if (eff_buf.token_len < 0) {
1007 lwsl_debug("Socket read returned %d\n",
1009 if (errno != EINTR && errno != EAGAIN)
1010 libwebsocket_close_and_free_session(context,
1011 wsi, LWS_CLOSE_STATUS_NOSTATUS);
1014 if (!eff_buf.token_len) {
1015 lwsl_info("closing connection due to 0 length read\n");
1016 libwebsocket_close_and_free_session(context, wsi,
1017 LWS_CLOSE_STATUS_NOSTATUS);
1022 * give any active extensions a chance to munge the buffer
1023 * before parse. We pass in a pointer to an lws_tokens struct
1024 * prepared with the default buffer and content length that's in
1025 * there. Rather than rewrite the default buffer, extensions
1026 * that expect to grow the buffer can adapt .token to
1027 * point to their own per-connection buffer in the extension
1028 * user allocation. By default with no extensions or no
1029 * extension callback handling, just the normal input buffer is
1030 * used then so it is efficient.
1033 eff_buf.token = (char *)context->service_buffer;
1034 #ifndef LWS_NO_EXTENSIONS
1040 for (n = 0; n < wsi->count_active_extensions; n++) {
1041 m = wsi->active_extensions[n]->callback(context,
1042 wsi->active_extensions[n], wsi,
1043 LWS_EXT_CALLBACK_PACKET_RX_PREPARSE,
1044 wsi->active_extensions_user[n],
1048 "Extension reports fatal error\n");
1049 libwebsocket_close_and_free_session(
1051 LWS_CLOSE_STATUS_NOSTATUS);
1058 /* service incoming data */
1060 if (eff_buf.token_len) {
1061 n = libwebsocket_read(context, wsi,
1062 (unsigned char *)eff_buf.token,
1068 #ifndef LWS_NO_EXTENSIONS
1069 eff_buf.token = NULL;
1070 eff_buf.token_len = 0;
1074 #ifdef LWS_OPENSSL_SUPPORT
1075 if (wsi->ssl && SSL_pending(wsi->ssl))
1081 #ifdef LWS_NO_CLIENT
1084 return lws_client_socket_service(context, wsi, pollfd);
1093 * libwebsocket_context_destroy() - Destroy the websocket context
1094 * @context: Websocket context
1096 * This function closes any active connections and then frees the
1097 * context. After calling this, any further use of the context is
1101 libwebsocket_context_destroy(struct libwebsocket_context *context)
1103 #ifndef LWS_NO_EXTENSIONS
1106 struct libwebsocket_extension *ext;
1107 struct libwebsocket_protocols *protocol = context->protocols;
1110 if (context->worst_latency_info[0])
1111 lwsl_notice("Worst latency: %s\n", context->worst_latency_info);
1114 for (n = 0; n < context->fds_count; n++) {
1115 struct libwebsocket *wsi =
1116 context->lws_lookup[context->fds[n].fd];
1117 libwebsocket_close_and_free_session(context,
1118 wsi, LWS_CLOSE_STATUS_NOSTATUS /* no protocol close */);
1123 * give all extensions a chance to clean up any per-context
1124 * allocations they might have made
1127 ext = context->extensions;
1128 m = LWS_EXT_CALLBACK_CLIENT_CONTEXT_DESTRUCT;
1129 if (context->listen_port)
1130 m = LWS_EXT_CALLBACK_SERVER_CONTEXT_DESTRUCT;
1131 while (ext && ext->callback) {
1132 ext->callback(context, ext, NULL,
1133 (enum libwebsocket_extension_callback_reasons)m,
1139 * inform all the protocols that they are done and will have no more
1143 while (protocol->callback) {
1144 protocol->callback(context, NULL, LWS_CALLBACK_PROTOCOL_DESTROY,
1153 close(context->fd_random);
1156 #ifdef LWS_OPENSSL_SUPPORT
1157 if (context->ssl_ctx)
1158 SSL_CTX_free(context->ssl_ctx);
1159 if (context->ssl_client_ctx)
1160 SSL_CTX_free(context->ssl_client_ctx);
1162 ERR_remove_state(0);
1165 CRYPTO_cleanup_all_ex_data();
1170 if (context->lws_lookup)
1171 free(context->lws_lookup);
1181 * libwebsocket_context_user() - get the user data associated with the context
1182 * @context: Websocket context
1184 * This returns the optional user allocation that can be attached to
1185 * the context the sockets live in at context_create time. It's a way
1186 * to let all sockets serviced in the same context share data without
1187 * using globals statics in the user code.
1190 libwebsocket_context_user(struct libwebsocket_context *context)
1192 return context->user_space;
1196 * libwebsocket_service() - Service any pending websocket activity
1197 * @context: Websocket context
1198 * @timeout_ms: Timeout for poll; 0 means return immediately if nothing needed
1199 * service otherwise block and service immediately, returning
1200 * after the timeout if nothing needed service.
1202 * This function deals with any pending websocket traffic, for three
1203 * kinds of event. It handles these events on both server and client
1204 * types of connection the same.
1206 * 1) Accept new connections to our context's server
1208 * 2) Call the receive callback for incoming frame data received by
1209 * server or client connections.
1211 * You need to call this service function periodically to all the above
1212 * functions to happen; if your application is single-threaded you can
1213 * just call it in your main event loop.
1215 * Alternatively you can fork a new process that asynchronously handles
1216 * calling this service in a loop. In that case you are happy if this
1217 * call blocks your thread until it needs to take care of something and
1218 * would call it with a large nonzero timeout. Your loop then takes no
1219 * CPU while there is nothing happening.
1221 * If you are calling it in a single-threaded app, you don't want it to
1222 * wait around blocking other things in your loop from happening, so you
1223 * would call it with a timeout_ms of 0, so it returns immediately if
1224 * nothing is pending, or as soon as it services whatever was pending.
1228 libwebsocket_service(struct libwebsocket_context *context, int timeout_ms)
1232 /* stay dead once we are dead */
1234 if (context == NULL)
1237 /* wait for something to need service */
1239 n = poll(context->fds, context->fds_count, timeout_ms);
1240 if (n == 0) /* poll timeout */
1246 /* any socket with events to service? */
1248 for (n = 0; n < context->fds_count; n++)
1249 if (context->fds[n].revents)
1250 if (libwebsocket_service_fd(context,
1251 &context->fds[n]) < 0)
1256 #ifndef LWS_NO_EXTENSIONS
1258 lws_any_extension_handled(struct libwebsocket_context *context,
1259 struct libwebsocket *wsi,
1260 enum libwebsocket_extension_callback_reasons r,
1261 void *v, size_t len)
1266 /* maybe an extension will take care of it for us */
1268 for (n = 0; n < wsi->count_active_extensions && !handled; n++) {
1269 if (!wsi->active_extensions[n]->callback)
1272 handled |= wsi->active_extensions[n]->callback(context,
1273 wsi->active_extensions[n], wsi,
1274 r, wsi->active_extensions_user[n], v, len);
1282 lws_get_extension_user_matching_ext(struct libwebsocket *wsi,
1283 struct libwebsocket_extension *ext)
1290 while (n < wsi->count_active_extensions) {
1291 if (wsi->active_extensions[n] != ext) {
1295 return wsi->active_extensions_user[n];
1303 * libwebsocket_callback_on_writable() - Request a callback when this socket
1304 * becomes able to be written to without
1307 * @context: libwebsockets context
1308 * @wsi: Websocket connection instance to get callback for
1312 libwebsocket_callback_on_writable(struct libwebsocket_context *context,
1313 struct libwebsocket *wsi)
1315 #ifndef LWS_NO_EXTENSIONS
1319 /* maybe an extension will take care of it for us */
1321 for (n = 0; n < wsi->count_active_extensions; n++) {
1322 if (!wsi->active_extensions[n]->callback)
1325 handled |= wsi->active_extensions[n]->callback(context,
1326 wsi->active_extensions[n], wsi,
1327 LWS_EXT_CALLBACK_REQUEST_ON_WRITEABLE,
1328 wsi->active_extensions_user[n], NULL, 0);
1334 if (wsi->position_in_fds_table < 0) {
1335 lwsl_err("libwebsocket_callback_on_writable: failed to find socket %d\n",
1340 context->fds[wsi->position_in_fds_table].events |= POLLOUT;
1342 /* external POLL support via protocol 0 */
1343 context->protocols[0].callback(context, wsi,
1344 LWS_CALLBACK_SET_MODE_POLL_FD,
1345 wsi->user_space, (void *)(long)wsi->sock, POLLOUT);
1351 * libwebsocket_callback_on_writable_all_protocol() - Request a callback for
1352 * all connections using the given protocol when it
1353 * becomes possible to write to each socket without
1356 * @protocol: Protocol whose connections will get callbacks
1360 libwebsocket_callback_on_writable_all_protocol(
1361 const struct libwebsocket_protocols *protocol)
1363 struct libwebsocket_context *context = protocol->owning_server;
1365 struct libwebsocket *wsi;
1367 for (n = 0; n < context->fds_count; n++) {
1368 wsi = context->lws_lookup[context->fds[n].fd];
1371 if (wsi->protocol == protocol)
1372 libwebsocket_callback_on_writable(context, wsi);
1379 * libwebsocket_set_timeout() - marks the wsi as subject to a timeout
1381 * You will not need this unless you are doing something special
1383 * @wsi: Websocket connection instance
1384 * @reason: timeout reason
1385 * @secs: how many seconds
1389 libwebsocket_set_timeout(struct libwebsocket *wsi,
1390 enum pending_timeout reason, int secs)
1394 gettimeofday(&tv, NULL);
1396 wsi->pending_timeout_limit = tv.tv_sec + secs;
1397 wsi->pending_timeout = reason;
1402 * libwebsocket_get_socket_fd() - returns the socket file descriptor
1404 * You will not need this unless you are doing something special
1406 * @wsi: Websocket connection instance
1410 libwebsocket_get_socket_fd(struct libwebsocket *wsi)
1417 lws_latency(struct libwebsocket_context *context, struct libwebsocket *wsi,
1418 const char *action, int ret, int completed)
1424 gettimeofday(&tv, NULL);
1426 u = (tv.tv_sec * 1000000) + tv.tv_usec;
1430 if (wsi->action_start == wsi->latency_start)
1432 "Completion first try lat %luus: %p: ret %d: %s\n",
1433 u - wsi->latency_start,
1434 (void *)wsi, ret, action);
1437 "Completion %luus: lat %luus: %p: ret %d: %s\n",
1438 u - wsi->action_start,
1439 u - wsi->latency_start,
1440 (void *)wsi, ret, action);
1441 wsi->action_start = 0;
1443 sprintf(buf, "lat %luus: %p: ret %d: %s\n",
1444 u - wsi->latency_start,
1445 (void *)wsi, ret, action);
1446 if (u - wsi->latency_start > context->worst_latency) {
1447 context->worst_latency = u - wsi->latency_start;
1448 strcpy(context->worst_latency_info, buf);
1450 lwsl_latency("%s", buf);
1452 wsi->latency_start = u;
1453 if (!wsi->action_start)
1454 wsi->action_start = u;
1459 #ifdef LWS_NO_SERVER
1461 _libwebsocket_rx_flow_control(struct libwebsocket *wsi)
1467 _libwebsocket_rx_flow_control(struct libwebsocket *wsi)
1469 struct libwebsocket_context *context = wsi->protocol->owning_server;
1472 if (!(wsi->u.ws.rxflow_change_to & 2))
1475 wsi->u.ws.rxflow_change_to &= ~2;
1477 lwsl_info("rxflow: wsi %p change_to %d\n",
1478 wsi, wsi->u.ws.rxflow_change_to);
1480 /* if we're letting it come again, did we interrupt anything? */
1481 if ((wsi->u.ws.rxflow_change_to & 1) && wsi->u.ws.rxflow_buffer) {
1482 n = libwebsocket_interpret_incoming_packet(wsi, NULL, 0);
1484 lwsl_info("libwebsocket_rx_flow_control: close req\n");
1488 /* oh he stuck again, do nothing */
1492 if (wsi->u.ws.rxflow_change_to & 1)
1493 context->fds[wsi->position_in_fds_table].events |= POLLIN;
1495 context->fds[wsi->position_in_fds_table].events &= ~POLLIN;
1497 if (wsi->u.ws.rxflow_change_to & 1)
1498 /* external POLL support via protocol 0 */
1499 context->protocols[0].callback(context, wsi,
1500 LWS_CALLBACK_SET_MODE_POLL_FD,
1501 wsi->user_space, (void *)(long)wsi->sock, POLLIN);
1503 /* external POLL support via protocol 0 */
1504 context->protocols[0].callback(context, wsi,
1505 LWS_CALLBACK_CLEAR_MODE_POLL_FD,
1506 wsi->user_space, (void *)(long)wsi->sock, POLLIN);
1513 * libwebsocket_rx_flow_control() - Enable and disable socket servicing for
1514 * receieved packets.
1516 * If the output side of a server process becomes choked, this allows flow
1517 * control for the input side.
1519 * @wsi: Websocket connection instance to get callback for
1520 * @enable: 0 = disable read servicing for this connection, 1 = enable
1524 libwebsocket_rx_flow_control(struct libwebsocket *wsi, int enable)
1526 wsi->u.ws.rxflow_change_to = 2 | !!enable;
1533 * libwebsocket_canonical_hostname() - returns this host's hostname
1535 * This is typically used by client code to fill in the host parameter
1536 * when making a client connection. You can only call it after the context
1539 * @context: Websocket context
1544 libwebsocket_canonical_hostname(struct libwebsocket_context *context)
1546 return (const char *)context->canonical_hostname;
1550 static void sigpipe_handler(int x)
1554 #ifdef LWS_OPENSSL_SUPPORT
1556 OpenSSL_verify_callback(int preverify_ok, X509_STORE_CTX *x509_ctx)
1561 struct libwebsocket_context *context;
1563 ssl = X509_STORE_CTX_get_ex_data(x509_ctx,
1564 SSL_get_ex_data_X509_STORE_CTX_idx());
1567 * !!! nasty openssl requires the index to come as a library-scope
1570 context = SSL_get_ex_data(ssl, openssl_websocket_private_data_index);
1572 n = context->protocols[0].callback(NULL, NULL,
1573 LWS_CALLBACK_OPENSSL_PERFORM_CLIENT_CERT_VERIFICATION,
1574 x509_ctx, ssl, preverify_ok);
1576 /* convert return code from 0 = OK to 1 = OK */
1587 int user_callback_handle_rxflow(callback_function callback_function,
1588 struct libwebsocket_context *context,
1589 struct libwebsocket *wsi,
1590 enum libwebsocket_callback_reasons reason, void *user,
1591 void *in, size_t len)
1595 n = callback_function(context, wsi, reason, user, in, len);
1597 n = _libwebsocket_rx_flow_control(wsi);
1604 * libwebsocket_create_context() - Create the websocket handler
1605 * @info: pointer to struct with parameters
1607 * This function creates the listening socket (if serving) and takes care
1608 * of all initialization in one step.
1610 * After initialization, it returns a struct libwebsocket_context * that
1611 * represents this server. After calling, user code needs to take care
1612 * of calling libwebsocket_service() with the context pointer to get the
1613 * server's sockets serviced. This can be done in the same process context
1614 * or a forked process, or another thread,
1616 * The protocol callback functions are called for a handful of events
1617 * including http requests coming in, websocket connections becoming
1618 * established, and data arriving; it's also called periodically to allow
1619 * async transmission.
1621 * HTTP requests are sent always to the FIRST protocol in @protocol, since
1622 * at that time websocket protocol has not been negotiated. Other
1623 * protocols after the first one never see any HTTP callack activity.
1625 * The server created is a simple http server by default; part of the
1626 * websocket standard is upgrading this http connection to a websocket one.
1628 * This allows the same server to provide files like scripts and favicon /
1629 * images or whatever over http and dynamic data over websockets all in
1630 * one place; they're all handled in the user callback.
1633 struct libwebsocket_context *
1634 libwebsocket_create_context(struct lws_context_creation_info *info)
1636 struct libwebsocket_context *context = NULL;
1639 #ifndef LWS_NO_SERVER
1641 struct libwebsocket *wsi;
1642 struct sockaddr_in serv_addr;
1644 #ifndef LWS_NO_EXTENSIONS
1646 struct libwebsocket_extension *ext;
1649 #ifdef LWS_OPENSSL_SUPPORT
1653 #ifndef LWS_NO_DAEMONIZE
1654 int pid_daemon = get_daemonize_pid();
1657 lwsl_notice("Initial logging level %d\n", log_level);
1658 lwsl_notice("Library version: %s\n", library_version);
1659 lwsl_info(" LWS_MAX_HEADER_LEN: %u\n", LWS_MAX_HEADER_LEN);
1660 lwsl_info(" LWS_MAX_PROTOCOLS: %u\n", LWS_MAX_PROTOCOLS);
1661 #ifndef LWS_NO_EXTENSIONS
1662 lwsl_info(" LWS_MAX_EXTENSIONS_ACTIVE: %u\n",
1663 LWS_MAX_EXTENSIONS_ACTIVE);
1665 lwsl_notice(" Configured without extension support\n");
1667 lwsl_info(" SPEC_LATEST_SUPPORTED: %u\n", SPEC_LATEST_SUPPORTED);
1668 lwsl_info(" AWAITING_TIMEOUT: %u\n", AWAITING_TIMEOUT);
1669 if (info->ssl_cipher_list)
1670 lwsl_info(" SSL ciphers: '%s'\n", info->ssl_cipher_list);
1671 lwsl_info(" SYSTEM_RANDOM_FILEPATH: '%s'\n", SYSTEM_RANDOM_FILEPATH);
1672 lwsl_info(" LWS_MAX_ZLIB_CONN_BUFFER: %u\n", LWS_MAX_ZLIB_CONN_BUFFER);
1676 WORD wVersionRequested;
1681 /* Use the MAKEWORD(lowbyte, highbyte) macro from Windef.h */
1682 wVersionRequested = MAKEWORD(2, 2);
1684 err = WSAStartup(wVersionRequested, &wsaData);
1686 /* Tell the user that we could not find a usable */
1688 lwsl_err("WSAStartup failed with error: %d\n", err);
1692 /* default to a poll() made out of select() */
1693 poll = emulated_poll;
1695 /* if windows socket lib available, use his WSAPoll */
1696 wsdll = GetModuleHandle(_T("Ws2_32.dll"));
1698 poll = (PFNWSAPOLL)GetProcAddress(wsdll, "WSAPoll");
1700 /* Finally fall back to emulated poll if all else fails */
1702 poll = emulated_poll;
1706 context = (struct libwebsocket_context *)
1707 malloc(sizeof(struct libwebsocket_context));
1709 lwsl_err("No memory for websocket context\n");
1712 memset(context, 0, sizeof(*context));
1713 #ifndef LWS_NO_DAEMONIZE
1714 context->started_with_parent = pid_daemon;
1715 lwsl_notice(" Started with daemon pid %d\n", pid_daemon);
1718 context->listen_service_extraseen = 0;
1719 context->protocols = info->protocols;
1720 context->listen_port = info->port;
1721 context->http_proxy_port = 0;
1722 context->http_proxy_address[0] = '\0';
1723 context->options = info->options;
1724 /* to reduce this allocation, */
1725 context->max_fds = getdtablesize();
1726 lwsl_notice(" static allocation: %u + (%u x %u fds) = %u bytes\n",
1727 sizeof(struct libwebsocket_context),
1728 sizeof(struct pollfd) + sizeof(struct libwebsocket *),
1730 sizeof(struct libwebsocket_context) +
1731 ((sizeof(struct pollfd) + sizeof(struct libwebsocket *)) *
1734 context->fds = (struct pollfd *)malloc(sizeof(struct pollfd) *
1736 if (context->fds == NULL) {
1737 lwsl_err("Unable to allocate fds array for %d connections\n",
1742 context->lws_lookup = (struct libwebsocket **)
1743 malloc(sizeof(struct libwebsocket *) * context->max_fds);
1744 if (context->lws_lookup == NULL) {
1746 "Unable to allocate lws_lookup array for %d connections\n",
1753 context->fds_count = 0;
1754 #ifndef LWS_NO_EXTENSIONS
1755 context->extensions = info->extensions;
1757 context->last_timeout_check_s = 0;
1758 context->user_space = info->user;
1761 context->fd_random = 0;
1763 context->fd_random = open(SYSTEM_RANDOM_FILEPATH, O_RDONLY);
1764 if (context->fd_random < 0) {
1765 lwsl_err("Unable to open random device %s %d\n",
1766 SYSTEM_RANDOM_FILEPATH, context->fd_random);
1771 #ifdef LWS_OPENSSL_SUPPORT
1772 context->use_ssl = 0;
1773 context->ssl_ctx = NULL;
1774 context->ssl_client_ctx = NULL;
1775 openssl_websocket_private_data_index = 0;
1778 strcpy(context->canonical_hostname, "unknown");
1780 #ifndef LWS_NO_SERVER
1781 if (!(info->options & LWS_SERVER_OPTION_SKIP_SERVER_CANONICAL_NAME)) {
1782 /* find canonical hostname */
1783 gethostname((char *)context->canonical_hostname,
1784 sizeof(context->canonical_hostname) - 1);
1786 lwsl_notice(" canonical_hostname = %s\n",
1787 context->canonical_hostname);
1791 /* split the proxy ads:port if given */
1793 p = getenv("http_proxy");
1795 strncpy(context->http_proxy_address, p,
1796 sizeof(context->http_proxy_address) - 1);
1797 context->http_proxy_address[
1798 sizeof(context->http_proxy_address) - 1] = '\0';
1800 p = strchr(context->http_proxy_address, ':');
1802 lwsl_err("http_proxy needs to be ads:port\n");
1806 context->http_proxy_port = atoi(p + 1);
1808 lwsl_notice(" Proxy %s:%u\n",
1809 context->http_proxy_address,
1810 context->http_proxy_port);
1813 #ifndef LWS_NO_SERVER
1816 #ifdef LWS_OPENSSL_SUPPORT
1817 context->use_ssl = info->ssl_cert_filepath != NULL &&
1818 info->ssl_private_key_filepath != NULL;
1820 lwsl_notice(" Compiled with CYASSL support\n");
1822 lwsl_notice(" Compiled with OpenSSL support\n");
1824 if (context->use_ssl)
1825 lwsl_notice(" Using SSL mode\n");
1827 lwsl_notice(" Using non-SSL mode\n");
1830 if (info->ssl_cert_filepath != NULL &&
1831 info->ssl_private_key_filepath != NULL) {
1832 lwsl_notice(" Not compiled for OpenSSl support!\n");
1835 lwsl_notice(" Compiled without SSL support\n");
1839 " per-conn mem: %u + %u headers + protocol rx buf\n",
1840 sizeof(struct libwebsocket),
1841 sizeof(struct allocated_headers));
1845 /* ignore SIGPIPE */
1848 signal(SIGPIPE, sigpipe_handler);
1852 #ifdef LWS_OPENSSL_SUPPORT
1854 /* basic openssl init */
1858 OpenSSL_add_all_algorithms();
1859 SSL_load_error_strings();
1861 openssl_websocket_private_data_index =
1862 SSL_get_ex_new_index(0, "libwebsockets", NULL, NULL, NULL);
1865 * Firefox insists on SSLv23 not SSLv3
1866 * Konq disables SSLv2 by default now, SSLv23 works
1869 method = (SSL_METHOD *)SSLv23_server_method();
1871 lwsl_err("problem creating ssl method %lu: %s\n",
1873 ERR_error_string(ERR_get_error(),
1874 (char *)context->service_buffer));
1877 context->ssl_ctx = SSL_CTX_new(method); /* create context */
1878 if (!context->ssl_ctx) {
1879 lwsl_err("problem creating ssl context %lu: %s\n",
1881 ERR_error_string(ERR_get_error(),
1882 (char *)context->service_buffer));
1886 #ifdef SSL_OP_NO_COMPRESSION
1887 SSL_CTX_set_options(context->ssl_ctx, SSL_OP_NO_COMPRESSION);
1889 SSL_CTX_set_options(context->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
1890 if (info->ssl_cipher_list)
1891 SSL_CTX_set_cipher_list(context->ssl_ctx,
1892 info->ssl_cipher_list);
1894 #ifndef LWS_NO_CLIENT
1896 /* client context */
1898 if (info->port == CONTEXT_PORT_NO_LISTEN) {
1899 method = (SSL_METHOD *)SSLv23_client_method();
1901 lwsl_err("problem creating ssl method %lu: %s\n",
1903 ERR_error_string(ERR_get_error(),
1904 (char *)context->service_buffer));
1907 /* create context */
1908 context->ssl_client_ctx = SSL_CTX_new(method);
1909 if (!context->ssl_client_ctx) {
1910 lwsl_err("problem creating ssl context %lu: %s\n",
1912 ERR_error_string(ERR_get_error(),
1913 (char *)context->service_buffer));
1917 #ifdef SSL_OP_NO_COMPRESSION
1918 SSL_CTX_set_options(context->ssl_client_ctx,
1919 SSL_OP_NO_COMPRESSION);
1921 SSL_CTX_set_options(context->ssl_client_ctx,
1922 SSL_OP_CIPHER_SERVER_PREFERENCE);
1923 if (info->ssl_cipher_list)
1924 SSL_CTX_set_cipher_list(context->ssl_client_ctx,
1925 info->ssl_cipher_list);
1927 /* openssl init for cert verification (for client sockets) */
1928 if (!info->ssl_ca_filepath) {
1929 if (!SSL_CTX_load_verify_locations(
1930 context->ssl_client_ctx, NULL,
1931 LWS_OPENSSL_CLIENT_CERTS))
1933 "Unable to load SSL Client certs from %s "
1934 "(set by --with-client-cert-dir= "
1935 "in configure) -- client ssl isn't "
1936 "going to work", LWS_OPENSSL_CLIENT_CERTS);
1938 if (!SSL_CTX_load_verify_locations(
1939 context->ssl_client_ctx, info->ssl_ca_filepath,
1942 "Unable to load SSL Client certs "
1943 "file from %s -- client ssl isn't "
1944 "going to work", info->ssl_ca_filepath);
1947 * callback allowing user code to load extra verification certs
1948 * helping the client to verify server identity
1951 context->protocols[0].callback(context, NULL,
1952 LWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS,
1953 context->ssl_client_ctx, NULL, 0);
1957 /* as a server, are we requiring clients to identify themselves? */
1960 LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT) {
1962 /* absolutely require the client cert */
1964 SSL_CTX_set_verify(context->ssl_ctx,
1965 SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
1966 OpenSSL_verify_callback);
1969 * give user code a chance to load certs into the server
1970 * allowing it to verify incoming client certs
1973 context->protocols[0].callback(context, NULL,
1974 LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS,
1975 context->ssl_ctx, NULL, 0);
1978 if (context->use_ssl) {
1980 /* openssl init for server sockets */
1982 /* set the local certificate from CertFile */
1983 n = SSL_CTX_use_certificate_chain_file(context->ssl_ctx,
1984 info->ssl_cert_filepath);
1986 lwsl_err("problem getting cert '%s' %lu: %s\n",
1987 info->ssl_cert_filepath,
1989 ERR_error_string(ERR_get_error(),
1990 (char *)context->service_buffer));
1993 /* set the private key from KeyFile */
1994 if (SSL_CTX_use_PrivateKey_file(context->ssl_ctx,
1995 info->ssl_private_key_filepath,
1996 SSL_FILETYPE_PEM) != 1) {
1997 lwsl_err("ssl problem getting key '%s' %lu: %s\n",
1998 info->ssl_private_key_filepath,
2000 ERR_error_string(ERR_get_error(),
2001 (char *)context->service_buffer));
2004 /* verify private key */
2005 if (!SSL_CTX_check_private_key(context->ssl_ctx)) {
2006 lwsl_err("Private SSL key doesn't match cert\n");
2010 /* SSL is happy and has a cert it's content with */
2016 if (lws_b64_selftest())
2019 #ifndef LWS_NO_SERVER
2020 /* set up our external listening socket we serve on */
2025 sockfd = socket(AF_INET, SOCK_STREAM, 0);
2027 lwsl_err("ERROR opening socket\n");
2033 * allow us to restart even if old sockets in TIME_WAIT
2034 * (REUSEADDR on Unix means, "don't hang on to this
2035 * address after the listener is closed." On Windows, though,
2036 * it means "don't keep other processes from binding to
2037 * this address while we're using it)
2039 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
2040 (const void *)&opt, sizeof(opt));
2045 setsockopt(sockfd, IPPROTO_TCP, TCP_NODELAY,
2046 (const void *)&opt, sizeof(opt));
2050 ioctlsocket(sockfd, FIONBIO, (unsigned long *)&opt);
2052 fcntl(sockfd, F_SETFL, O_NONBLOCK);
2055 bzero((char *) &serv_addr, sizeof(serv_addr));
2056 serv_addr.sin_family = AF_INET;
2057 if (info->iface == NULL)
2058 serv_addr.sin_addr.s_addr = INADDR_ANY;
2060 interface_to_sa(info->iface, &serv_addr,
2062 serv_addr.sin_port = htons(info->port);
2064 n = bind(sockfd, (struct sockaddr *) &serv_addr,
2067 lwsl_err("ERROR on binding to port %d (%d %d)\n",
2068 info->port, n, errno);
2073 wsi = (struct libwebsocket *)malloc(
2074 sizeof(struct libwebsocket));
2076 lwsl_err("Out of mem\n");
2080 memset(wsi, 0, sizeof(struct libwebsocket));
2082 #ifndef LWS_NO_EXTENSIONS
2083 wsi->count_active_extensions = 0;
2085 wsi->mode = LWS_CONNMODE_SERVER_LISTENER;
2087 insert_wsi_socket_into_fds(context, wsi);
2089 context->listen_service_modulo = LWS_LISTEN_SERVICE_MODULO;
2090 context->listen_service_count = 0;
2091 context->listen_service_fd = sockfd;
2093 listen(sockfd, LWS_SOMAXCONN);
2094 lwsl_notice(" Listening on port %d\n", info->port);
2099 * drop any root privs for this process
2100 * to listen on port < 1023 we would have needed root, but now we are
2101 * listening, we don't want the power for anything else
2105 if (info->gid != -1)
2106 if (setgid(info->gid))
2107 lwsl_warn("setgid: %s\n", strerror(errno));
2108 if (info->uid != -1)
2109 if (setuid(info->uid))
2110 lwsl_warn("setuid: %s\n", strerror(errno));
2113 /* initialize supported protocols */
2115 for (context->count_protocols = 0;
2116 info->protocols[context->count_protocols].callback;
2117 context->count_protocols++) {
2119 lwsl_parser(" Protocol: %s\n",
2120 info->protocols[context->count_protocols].name);
2122 info->protocols[context->count_protocols].owning_server =
2124 info->protocols[context->count_protocols].protocol_index =
2125 context->count_protocols;
2128 * inform all the protocols that they are doing their one-time
2129 * initialization if they want to
2131 info->protocols[context->count_protocols].callback(context,
2132 NULL, LWS_CALLBACK_PROTOCOL_INIT, NULL, NULL, 0);
2135 #ifndef LWS_NO_EXTENSIONS
2137 * give all extensions a chance to create any per-context
2138 * allocations they need
2141 m = LWS_EXT_CALLBACK_CLIENT_CONTEXT_CONSTRUCT;
2143 m = LWS_EXT_CALLBACK_SERVER_CONTEXT_CONSTRUCT;
2145 if (info->extensions) {
2146 ext = info->extensions;
2147 while (ext->callback) {
2148 lwsl_ext(" Extension: %s\n", ext->name);
2149 ext->callback(context, ext, NULL,
2150 (enum libwebsocket_extension_callback_reasons)m,
2159 libwebsocket_context_destroy(context);
2164 * libwebsockets_get_protocol() - Returns a protocol pointer from a websocket
2166 * @wsi: pointer to struct websocket you want to know the protocol of
2169 * Some apis can act on all live connections of a given protocol,
2170 * this is how you can get a pointer to the active protocol if needed.
2173 const struct libwebsocket_protocols *
2174 libwebsockets_get_protocol(struct libwebsocket *wsi)
2176 return wsi->protocol;
2180 libwebsocket_is_final_fragment(struct libwebsocket *wsi)
2182 return wsi->u.ws.final;
2186 libwebsocket_get_reserved_bits(struct libwebsocket *wsi)
2188 return wsi->u.ws.rsv;
2192 libwebsocket_ensure_user_space(struct libwebsocket *wsi)
2197 /* allocate the per-connection user memory (if any) */
2199 if (wsi->protocol->per_session_data_size && !wsi->user_space) {
2200 wsi->user_space = malloc(
2201 wsi->protocol->per_session_data_size);
2202 if (wsi->user_space == NULL) {
2203 lwsl_err("Out of memory for conn user space\n");
2206 memset(wsi->user_space, 0,
2207 wsi->protocol->per_session_data_size);
2212 static void lwsl_emit_stderr(int level, const char *line)
2218 gettimeofday(&tv, NULL);
2221 for (n = 0; n < LLL_COUNT; n++)
2222 if (level == (1 << n)) {
2223 sprintf(buf, "[%ld:%04d] %s: ", tv.tv_sec,
2224 (int)(tv.tv_usec / 100), log_level_names[n]);
2228 fprintf(stderr, "%s%s", buf, line);
2232 void lwsl_emit_syslog(int level, const char *line)
2234 lwsl_emit_stderr(level, line);
2237 void lwsl_emit_syslog(int level, const char *line)
2239 int syslog_level = LOG_DEBUG;
2243 syslog_level = LOG_ERR;
2246 syslog_level = LOG_WARNING;
2249 syslog_level = LOG_NOTICE;
2252 syslog_level = LOG_INFO;
2255 syslog(syslog_level, "%s", line);
2259 void _lws_log(int filter, const char *format, ...)
2264 if (!(log_level & filter))
2267 va_start(ap, format);
2268 vsnprintf(buf, sizeof(buf), format, ap);
2269 buf[sizeof(buf) - 1] = '\0';
2272 lwsl_emit(filter, buf);
2276 * lws_set_log_level() - Set the logging bitfield
2277 * @level: OR together the LLL_ debug contexts you want output from
2278 * @log_emit_function: NULL to leave it as it is, or a user-supplied
2279 * function to perform log string emission instead of
2280 * the default stderr one.
2282 * log level defaults to "err", "warn" and "notice" contexts enabled and
2283 * emission on stderr.
2286 void lws_set_log_level(int level, void (*log_emit_function)(int level,
2290 if (log_emit_function)
2291 lwsl_emit = log_emit_function;