2 * libwebsockets - small server side websockets and web server implementation
4 * Copyright (C) 2010-2016 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,
23 #include "private-libwebsockets.h"
26 lws_context_init_server(struct lws_context_creation_info *info,
27 struct lws_context *context)
30 struct sockaddr_in6 serv_addr6;
33 struct sockaddr_in serv_addr4;
34 socklen_t len = sizeof(struct sockaddr);
35 int n, opt = 1, limit = 1;
36 struct sockaddr_in sin;
39 lws_sockfd_type sockfd;
43 /* set up our external listening socket we serve on */
45 if (info->port == CONTEXT_PORT_NO_LISTEN)
49 #if defined(__linux__)
50 limit = context->count_threads;
53 for (m = 0; m < limit; m++) {
55 if (LWS_IPV6_ENABLED(context))
56 sockfd = socket(AF_INET6, SOCK_STREAM, 0);
59 sockfd = socket(AF_INET, SOCK_STREAM, 0);
63 sockfd = mbed3_create_tcp_stream_socket();
64 if (!lws_sockfd_valid(sockfd)) {
66 lwsl_err("ERROR opening socket\n");
72 * allow us to restart even if old sockets in TIME_WAIT
74 if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
75 (const void *)&opt, sizeof(opt)) < 0) {
76 compatible_close(sockfd);
79 #if defined(__linux__) && defined(SO_REUSEPORT) && LWS_MAX_SMP > 1
80 if (context->count_threads > 1)
81 if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEPORT,
82 (const void *)&opt, sizeof(opt)) < 0) {
83 compatible_close(sockfd);
88 lws_plat_set_socket_options(context, sockfd);
92 if (LWS_IPV6_ENABLED(context)) {
93 v = (struct sockaddr *)&serv_addr6;
94 n = sizeof(struct sockaddr_in6);
95 bzero((char *) &serv_addr6, sizeof(serv_addr6));
96 serv_addr6.sin6_addr = in6addr_any;
97 serv_addr6.sin6_family = AF_INET6;
98 serv_addr6.sin6_port = htons(info->port);
102 v = (struct sockaddr *)&serv_addr4;
103 n = sizeof(serv_addr4);
104 bzero((char *) &serv_addr4, sizeof(serv_addr4));
105 serv_addr4.sin_addr.s_addr = INADDR_ANY;
106 serv_addr4.sin_family = AF_INET;
108 if (info->iface && interface_to_sa(context, info->iface,
109 (struct sockaddr_in *)v, n) < 0) {
110 lwsl_err("Unable to find interface %s\n", info->iface);
114 serv_addr4.sin_port = htons(info->port);
117 n = bind(sockfd, v, n);
119 lwsl_err("ERROR on binding to port %d (%d %d)\n",
120 info->port, n, LWS_ERRNO);
124 if (getsockname(sockfd, (struct sockaddr *)&sin, &len) == -1)
125 lwsl_warn("getsockname: %s\n", strerror(LWS_ERRNO));
127 info->port = ntohs(sin.sin_port);
129 context->listen_port = info->port;
131 wsi = lws_zalloc(sizeof(struct lws));
133 lwsl_err("Out of mem\n");
136 wsi->context = context;
138 wsi->mode = LWSCM_SERVER_LISTENER;
139 wsi->protocol = context->protocols;
142 context->pt[m].wsi_listening = wsi;
143 if (insert_wsi_socket_into_fds(context, wsi))
146 context->count_wsi_allocated++;
147 context->pt[m].lserv_fd = sockfd;
150 listen(wsi->sock, LWS_SOMAXCONN);
151 } /* for each thread able to independently lister */
153 mbed3_tcp_stream_bind(wsi->sock, info->port, wsi);
155 lwsl_notice(" Listening on port %d\n", info->port);
160 compatible_close(sockfd);
166 _lws_server_listen_accept_flow_control(struct lws *twsi, int on)
168 struct lws_context_per_thread *pt = &twsi->context->pt[(int)twsi->tsi];
169 struct lws *wsi = pt->wsi_listening;
172 if (!wsi || twsi->context->being_destroyed)
175 lwsl_debug("%s: Thr %d: LISTEN wsi %p: state %d\n",
176 __func__, twsi->tsi, (void *)wsi, on);
179 n = lws_change_pollfd(wsi, 0, LWS_POLLIN);
181 n = lws_change_pollfd(wsi, LWS_POLLIN, 0);
187 lws_http_action(struct lws *wsi)
189 enum http_connection_type connection_type;
190 enum http_version request_version;
191 char content_length_str[32];
192 unsigned int n, count = 0;
193 char http_version_str[10];
194 char http_conn_str[20];
195 int http_version_len;
196 char *uri_ptr = NULL;
199 static const unsigned char methods[] = {
202 WSI_TOKEN_OPTIONS_URI,
205 WSI_TOKEN_DELETE_URI,
207 WSI_TOKEN_HTTP_COLON_PATH,
211 static const char * const method_names[] = {
212 "GET", "POST", "OPTIONS", "PUT", "PATCH", "DELETE",
219 /* it's not websocket.... shall we accept it as http? */
221 for (n = 0; n < ARRAY_SIZE(methods); n++)
222 if (lws_hdr_total_length(wsi, methods[n]))
225 lwsl_warn("Missing URI in HTTP request\n");
230 lwsl_warn("multiple methods?\n");
234 if (lws_ensure_user_space(wsi))
237 for (n = 0; n < ARRAY_SIZE(methods); n++)
238 if (lws_hdr_total_length(wsi, methods[n])) {
239 uri_ptr = lws_hdr_simple_ptr(wsi, methods[n]);
240 uri_len = lws_hdr_total_length(wsi, methods[n]);
241 lwsl_info("Method: %s request for '%s'\n",
242 method_names[n], uri_ptr);
246 /* we insist on absolute paths */
248 if (uri_ptr[0] != '/') {
249 lws_return_http_status(wsi, HTTP_STATUS_FORBIDDEN, NULL);
254 /* HTTP header had a content length? */
256 wsi->u.http.content_length = 0;
257 if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI) ||
258 lws_hdr_total_length(wsi, WSI_TOKEN_PATCH_URI) ||
259 lws_hdr_total_length(wsi, WSI_TOKEN_PUT_URI))
260 wsi->u.http.content_length = 100 * 1024 * 1024;
262 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH)) {
263 lws_hdr_copy(wsi, content_length_str,
264 sizeof(content_length_str) - 1,
265 WSI_TOKEN_HTTP_CONTENT_LENGTH);
266 wsi->u.http.content_length = atoi(content_length_str);
269 /* http_version? Default to 1.0, override with token: */
270 request_version = HTTP_VERSION_1_0;
272 /* Works for single digit HTTP versions. : */
273 http_version_len = lws_hdr_total_length(wsi, WSI_TOKEN_HTTP);
274 if (http_version_len > 7) {
275 lws_hdr_copy(wsi, http_version_str,
276 sizeof(http_version_str) - 1, WSI_TOKEN_HTTP);
277 if (http_version_str[5] == '1' && http_version_str[7] == '1')
278 request_version = HTTP_VERSION_1_1;
280 wsi->u.http.request_version = request_version;
282 /* HTTP/1.1 defaults to "keep-alive", 1.0 to "close" */
283 if (request_version == HTTP_VERSION_1_1)
284 connection_type = HTTP_CONNECTION_KEEP_ALIVE;
286 connection_type = HTTP_CONNECTION_CLOSE;
288 /* Override default if http "Connection:" header: */
289 if (lws_hdr_total_length(wsi, WSI_TOKEN_CONNECTION)) {
290 lws_hdr_copy(wsi, http_conn_str, sizeof(http_conn_str) - 1,
291 WSI_TOKEN_CONNECTION);
292 http_conn_str[sizeof(http_conn_str) - 1] = '\0';
293 if (!strcasecmp(http_conn_str, "keep-alive"))
294 connection_type = HTTP_CONNECTION_KEEP_ALIVE;
296 if (!strcasecmp(http_conn_str, "close"))
297 connection_type = HTTP_CONNECTION_CLOSE;
299 wsi->u.http.connection_type = connection_type;
301 n = wsi->protocol->callback(wsi, LWS_CALLBACK_FILTER_HTTP_CONNECTION,
302 wsi->user_space, uri_ptr, uri_len);
304 lwsl_info("LWS_CALLBACK_HTTP closing\n");
309 * if there is content supposed to be coming,
310 * put a timeout on it having arrived
312 lws_set_timeout(wsi, PENDING_TIMEOUT_HTTP_CONTENT,
313 wsi->context->timeout_secs);
315 n = wsi->protocol->callback(wsi, LWS_CALLBACK_HTTP,
316 wsi->user_space, uri_ptr, uri_len);
318 lwsl_info("LWS_CALLBACK_HTTP closing\n");
324 * If we're not issuing a file, check for content_length or
325 * HTTP keep-alive. No keep-alive header allocation for
326 * ISSUING_FILE, as this uses HTTP/1.0.
328 * In any case, return 0 and let lws_read decide how to
329 * proceed based on state
331 if (wsi->state != LWSS_HTTP_ISSUING_FILE)
332 /* Prepare to read body if we have a content length: */
333 if (wsi->u.http.content_length > 0)
334 wsi->state = LWSS_HTTP_BODY;
339 /* we're closing, losing some rx is OK */
340 wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
341 lws_header_table_detach(wsi);
348 lws_handshake_server(struct lws *wsi, unsigned char **buf, size_t len)
350 struct lws_context *context = lws_get_context(wsi);
351 struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
352 struct _lws_header_related hdr;
353 struct allocated_headers *ah;
354 int protocol_len, n, hit;
355 char protocol_list[128];
356 char protocol_name[32];
359 assert(len < 10000000);
360 assert(wsi->u.hdr.ah);
363 wsi->more_rx_waiting = !!len;
365 assert(wsi->mode == LWSCM_HTTP_SERVING);
367 if (lws_parse(wsi, *(*buf)++)) {
368 lwsl_info("lws_parse failed\n");
372 if (wsi->u.hdr.parser_state != WSI_PARSING_COMPLETE)
375 lwsl_parser("%s: lws_parse sees parsing complete\n", __func__);
376 lwsl_debug("%s: wsi->more_rx_waiting=%d\n", __func__,
377 wsi->more_rx_waiting);
379 wsi->mode = LWSCM_PRE_WS_SERVING_ACCEPT;
380 lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
382 /* is this websocket protocol or normal http 1.0? */
384 if (lws_hdr_total_length(wsi, WSI_TOKEN_UPGRADE)) {
385 if (!strcasecmp(lws_hdr_simple_ptr(wsi, WSI_TOKEN_UPGRADE),
387 lwsl_info("Upgrade to ws\n");
391 if (!strcasecmp(lws_hdr_simple_ptr(wsi, WSI_TOKEN_UPGRADE),
393 lwsl_info("Upgrade to h2c-14\n");
397 lwsl_err("Unknown upgrade\n");
398 /* dunno what he wanted to upgrade to */
402 /* no upgrade ack... he remained as HTTP */
404 lwsl_info("No upgrade\n");
407 lws_union_transition(wsi, LWSCM_HTTP_SERVING_ACCEPTED);
408 wsi->state = LWSS_HTTP;
409 wsi->u.http.fd = LWS_INVALID_FILE;
411 /* expose it at the same offset as u.hdr */
413 lwsl_debug("%s: wsi %p: ah %p\n", __func__, (void *)wsi, (void *)wsi->u.hdr.ah);
415 n = lws_http_action(wsi);
421 if (!lws_hdr_total_length(wsi, WSI_TOKEN_HTTP2_SETTINGS)) {
422 lwsl_err("missing http2_settings\n");
426 lwsl_err("h2c upgrade...\n");
428 p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP2_SETTINGS);
429 /* convert the peer's HTTP-Settings */
430 n = lws_b64_decode_string(p, protocol_list,
431 sizeof(protocol_list));
433 lwsl_parser("HTTP2_SETTINGS too long\n");
437 /* adopt the header info */
441 lws_union_transition(wsi, LWSCM_HTTP2_SERVING);
443 /* http2 union member has http union struct at start */
446 lws_http2_init(&wsi->u.http2.peer_settings);
447 lws_http2_init(&wsi->u.http2.my_settings);
451 lws_http2_interpret_settings_payload(&wsi->u.http2.peer_settings,
452 (unsigned char *)protocol_list, n);
454 strcpy(protocol_list,
455 "HTTP/1.1 101 Switching Protocols\x0d\x0a"
456 "Connection: Upgrade\x0d\x0a"
457 "Upgrade: h2c\x0d\x0a\x0d\x0a");
458 n = lws_issue_raw(wsi, (unsigned char *)protocol_list,
459 strlen(protocol_list));
460 if (n != strlen(protocol_list)) {
461 lwsl_debug("http2 switch: ERROR writing to socket\n");
465 wsi->state = LWSS_HTTP2_AWAIT_CLIENT_PREFACE;
472 lwsl_err("NULL protocol at lws_read\n");
477 * Select the first protocol we support from the list
478 * the client sent us.
480 * Copy it to remove header fragmentation
483 if (lws_hdr_copy(wsi, protocol_list, sizeof(protocol_list) - 1,
484 WSI_TOKEN_PROTOCOL) < 0) {
485 lwsl_err("protocol list too long");
489 protocol_len = lws_hdr_total_length(wsi, WSI_TOKEN_PROTOCOL);
490 protocol_list[protocol_len] = '\0';
496 while (n < sizeof(protocol_name) - 1 && *p && *p !=',')
497 protocol_name[n++] = *p++;
498 protocol_name[n] = '\0';
502 lwsl_info("checking %s\n", protocol_name);
505 while (context->protocols[n].callback) {
506 if (context->protocols[n].name &&
507 !strcmp(context->protocols[n].name,
509 lwsl_info("prot match %d\n", n);
510 wsi->protocol = &context->protocols[n];
519 /* we didn't find a protocol he wanted? */
522 if (lws_hdr_simple_ptr(wsi, WSI_TOKEN_PROTOCOL)) {
523 lwsl_err("No protocol from \"%s\" supported\n",
528 * some clients only have one protocol and
529 * do not sent the protocol list header...
530 * allow it and match to protocol 0
532 lwsl_info("defaulting to prot 0 handler\n");
533 wsi->protocol = &context->protocols[0];
536 /* allocate wsi->user storage */
537 if (lws_ensure_user_space(wsi))
541 * Give the user code a chance to study the request and
542 * have the opportunity to deny it
545 if ((wsi->protocol->callback)(wsi,
546 LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION,
548 lws_hdr_simple_ptr(wsi, WSI_TOKEN_PROTOCOL), 0)) {
549 lwsl_warn("User code denied connection\n");
554 * Perform the handshake according to the protocol version the
558 switch (wsi->ietf_spec_revision) {
560 lwsl_parser("lws_parse calling handshake_04\n");
561 if (handshake_0405(context, wsi)) {
562 lwsl_info("hs0405 has failed the connection\n");
568 lwsl_warn("Unknown client spec version %d\n",
569 wsi->ietf_spec_revision);
573 /* we are upgrading to ws, so http/1.1 and keepalive +
574 * pipelined header considerations about keeping the ah around
575 * no longer apply. However it's common for the first ws
576 * protocol data to have been coalesced with the browser
577 * upgrade request and to already be in the ah rx buffer.
580 lwsl_info("%s: %p: inheriting ah in ws mode (rxpos:%d, rxlen:%d)\n",
581 __func__, wsi, wsi->u.hdr.ah->rxpos,
582 wsi->u.hdr.ah->rxlen);
586 lws_union_transition(wsi, LWSCM_WS_SERVING);
588 * first service is WS mode will notice this, use the RX and
589 * then detach the ah (caution: we are not in u.hdr union
590 * mode any more then... ah_temp member is at start the same
593 * Because rxpos/rxlen shows something in the ah, we will get
594 * service guaranteed next time around the event loop
596 * All union members begin with hdr, so we can use it even
597 * though we transitioned to ws union mode (the ah detach
598 * code uses it anyway).
604 * create the frame buffer for this connection according to the
605 * size mentioned in the protocol definition. If 0 there, use
606 * a big default for compatibility
609 n = wsi->protocol->rx_buffer_size;
611 n = LWS_MAX_SOCKET_IO_BUF;
613 wsi->u.ws.rx_ubuf = lws_malloc(n + 4 /* 0x0000ffff zlib */);
614 if (!wsi->u.ws.rx_ubuf) {
615 lwsl_err("Out of Mem allocating rx buffer %d\n", n);
618 wsi->u.ws.rx_ubuf_alloc = n;
619 lwsl_info("Allocating RX buffer %d\n", n);
621 if (setsockopt(wsi->sock, SOL_SOCKET, SO_SNDBUF,
622 (const char *)&n, sizeof n)) {
623 lwsl_warn("Failed to set SNDBUF to %d", n);
627 lwsl_parser("accepted v%02d connection\n", wsi->ietf_spec_revision);
630 } /* while all chars are handled */
635 /* drop the header info */
636 /* we're closing, losing some rx is OK */
637 wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
638 lws_header_table_detach(wsi);
644 lws_get_idlest_tsi(struct lws_context *context)
646 unsigned int lowest = ~0;
649 for (; n < context->count_threads; n++) {
650 if ((unsigned int)context->pt[n].fds_count != context->fd_limit_per_thread - 1 &&
651 (unsigned int)context->pt[n].fds_count < lowest) {
652 lowest = context->pt[n].fds_count;
661 lws_create_new_server_wsi(struct lws_context *context)
664 int n = lws_get_idlest_tsi(context);
667 lwsl_err("no space for new conn\n");
671 new_wsi = lws_zalloc(sizeof(struct lws));
672 if (new_wsi == NULL) {
673 lwsl_err("Out of memory for new connection\n");
678 lwsl_info("Accepted %p to tsi %d\n", new_wsi, new_wsi->tsi);
680 new_wsi->context = context;
681 new_wsi->pending_timeout = NO_PENDING_TIMEOUT;
682 new_wsi->rxflow_change_to = LWS_RXFLOW_ALLOW;
684 /* intialize the instance struct */
686 new_wsi->state = LWSS_HTTP;
687 new_wsi->mode = LWSCM_HTTP_SERVING;
688 new_wsi->hdr_parsing_completed = 0;
690 #ifdef LWS_OPENSSL_SUPPORT
691 new_wsi->use_ssl = LWS_SSL_ENABLED(context);
695 * these can only be set once the protocol is known
696 * we set an unestablished connection's protocol pointer
697 * to the start of the supported list, so it can look
698 * for matching ones during the handshake
700 new_wsi->protocol = context->protocols;
701 new_wsi->user_space = NULL;
702 new_wsi->ietf_spec_revision = 0;
703 new_wsi->sock = LWS_SOCK_INVALID;
704 context->count_wsi_allocated++;
707 * outermost create notification for wsi
708 * no user_space because no protocol selection
710 context->protocols[0].callback(new_wsi, LWS_CALLBACK_WSI_CREATE,
717 * lws_http_transaction_completed() - wait for new http transaction or close
718 * @wsi: websocket connection
720 * Returns 1 if the HTTP connection must close now
721 * Returns 0 and resets connection to wait for new HTTP header /
722 * transaction if possible
725 LWS_VISIBLE int LWS_WARN_UNUSED_RESULT
726 lws_http_transaction_completed(struct lws *wsi)
728 lwsl_debug("%s: wsi %p\n", __func__, wsi);
729 /* if we can't go back to accept new headers, drop the connection */
730 if (wsi->u.http.connection_type != HTTP_CONNECTION_KEEP_ALIVE) {
731 lwsl_info("%s: %p: close connection\n", __func__, wsi);
735 /* otherwise set ourselves up ready to go again */
736 wsi->state = LWSS_HTTP;
737 wsi->mode = LWSCM_HTTP_SERVING;
738 wsi->u.http.content_length = 0;
739 wsi->hdr_parsing_completed = 0;
741 /* He asked for it to stay alive indefinitely */
742 lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
745 * We already know we are on http1.1 / keepalive and the next thing
746 * coming will be another header set.
748 * If there is no pending rx and we still have the ah, drop it and
749 * reacquire a new ah when the new headers start to arrive. (Otherwise
750 * we needlessly hog an ah indefinitely.)
752 * However if there is pending rx and we know from the keepalive state
753 * that is already at least the start of another header set, simply
754 * reset the existing header table and keep it.
757 lwsl_info("%s: wsi->more_rx_waiting=%d\n", __func__,
758 wsi->more_rx_waiting);
760 if (!wsi->more_rx_waiting) {
761 wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
762 lws_header_table_detach(wsi);
764 lws_header_table_reset(wsi);
767 /* If we're (re)starting on headers, need other implied init */
768 wsi->u.hdr.ues = URIES_IDLE;
770 lwsl_info("%s: %p: keep-alive await new transaction\n", __func__, wsi);
776 * lws_adopt_socket() - adopt foreign socket as if listen socket accepted it
777 * @context: lws context
778 * @accept_fd: fd of already-accepted socket to adopt
780 * Either returns new wsi bound to accept_fd, or closes accept_fd and
781 * returns NULL, having cleaned up any new wsi pieces.
783 * LWS adopts the socket in http serving mode, it's ready to accept an upgrade
784 * to ws or just serve http.
787 LWS_VISIBLE struct lws *
788 lws_adopt_socket(struct lws_context *context, lws_sockfd_type accept_fd)
790 struct lws *new_wsi = lws_create_new_server_wsi(context);
793 compatible_close(accept_fd);
797 lwsl_debug("%s: new wsi %p\n", __func__, new_wsi);
799 new_wsi->sock = accept_fd;
801 /* the transport is accepted... give him time to negotiate */
802 lws_set_timeout(new_wsi, PENDING_TIMEOUT_ESTABLISH_WITH_SERVER,
803 context->timeout_secs);
806 mbed3_tcp_stream_accept(accept_fd, new_wsi);
810 * A new connection was accepted. Give the user a chance to
811 * set properties of the newly created wsi. There's no protocol
812 * selected yet so we issue this to protocols[0]
814 if ((context->protocols[0].callback)(new_wsi,
815 LWS_CALLBACK_SERVER_NEW_CLIENT_INSTANTIATED, NULL, NULL, 0)) {
816 compatible_close(new_wsi->sock);
821 lws_libev_accept(new_wsi, new_wsi->sock);
822 lws_libuv_accept(new_wsi, new_wsi->sock);
824 if (!LWS_SSL_ENABLED(context)) {
825 if (insert_wsi_socket_into_fds(context, new_wsi))
828 new_wsi->mode = LWSCM_SSL_INIT;
829 if (lws_server_socket_service_ssl(new_wsi, accept_fd))
836 lwsl_err("%s: fail\n", __func__);
837 lws_close_free_wsi(new_wsi, LWS_CLOSE_STATUS_NOSTATUS);
843 lws_server_socket_service(struct lws_context *context, struct lws *wsi,
844 struct lws_pollfd *pollfd)
846 struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
847 lws_sockfd_type accept_fd = LWS_SOCK_INVALID;
848 struct allocated_headers *ah;
850 struct sockaddr_in cli_addr;
857 case LWSCM_HTTP_SERVING:
858 case LWSCM_HTTP_SERVING_ACCEPTED:
859 case LWSCM_HTTP2_SERVING:
861 /* handle http headers coming in */
863 /* pending truncated sends have uber priority */
865 if (wsi->trunc_len) {
866 if (!(pollfd->revents & LWS_POLLOUT))
869 if (lws_issue_raw(wsi, wsi->trunc_alloc +
874 * we can't afford to allow input processing to send
875 * something new, so spin around he event loop until
876 * he doesn't have any partials
881 /* any incoming data ready? */
883 if (!(pollfd->revents & pollfd->events & LWS_POLLIN))
886 /* these states imply we MUST have an ah attached */
888 if (wsi->state == LWSS_HTTP ||
889 wsi->state == LWSS_HTTP_ISSUING_FILE ||
890 wsi->state == LWSS_HTTP_HEADERS) {
892 if (lws_header_table_attach(wsi))
897 lwsl_debug("%s: %p: rxpos:%d rxlen:%d\n", __func__, wsi,
898 ah->rxpos, ah->rxlen);
900 /* if nothing in ah rx buffer, get some fresh rx */
901 if (ah->rxpos == ah->rxlen) {
902 ah->rxlen = lws_ssl_capable_read(wsi, ah->rx,
905 lwsl_debug("%s: wsi %p, ah->rxlen = %d\r\n",
906 __func__, wsi, ah->rxlen);
909 lwsl_info("%s: read 0 len\n", __func__);
910 /* lwsl_info(" state=%d\n", wsi->state); */
911 // if (!wsi->hdr_parsing_completed)
912 // lws_header_table_detach(wsi);
914 case LWS_SSL_CAPABLE_ERROR:
916 case LWS_SSL_CAPABLE_MORE_SERVICE:
917 ah->rxlen = ah->rxpos = 0;
921 assert(ah->rxpos != ah->rxlen && ah->rxlen);
922 /* just ignore incoming if waiting for close */
923 if (wsi->state != LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE) {
924 n = lws_read(wsi, ah->rx + ah->rxpos,
925 ah->rxlen - ah->rxpos);
926 if (n < 0) /* we closed wsi */
929 if ( wsi->u.hdr.ah->rxlen)
930 wsi->u.hdr.ah->rxpos += n;
932 if (wsi->u.hdr.ah->rxpos == wsi->u.hdr.ah->rxlen &&
933 (wsi->mode != LWSCM_HTTP_SERVING &&
934 wsi->mode != LWSCM_HTTP_SERVING_ACCEPTED &&
935 wsi->mode != LWSCM_HTTP2_SERVING))
936 lws_header_table_detach(wsi);
944 len = lws_ssl_capable_read(wsi, pt->serv_buf,
945 LWS_MAX_SOCKET_IO_BUF);
946 lwsl_debug("%s: wsi %p read %d\r\n", __func__, wsi, len);
949 lwsl_info("%s: read 0 len\n", __func__);
950 /* lwsl_info(" state=%d\n", wsi->state); */
951 // if (!wsi->hdr_parsing_completed)
952 // lws_header_table_detach(wsi);
954 case LWS_SSL_CAPABLE_ERROR:
956 case LWS_SSL_CAPABLE_MORE_SERVICE:
960 /* just ignore incoming if waiting for close */
961 if (wsi->state != LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE) {
963 * hm this may want to send
964 * (via HTTP callback for example)
966 n = lws_read(wsi, pt->serv_buf, len);
967 if (n < 0) /* we closed wsi */
969 /* hum he may have used up the
970 * writability above */
975 /* this handles POLLOUT for http serving fragments */
977 if (!(pollfd->revents & LWS_POLLOUT))
981 if (lws_change_pollfd(wsi, LWS_POLLOUT, 0)) {
982 lwsl_notice("%s a\n", __func__);
986 if (wsi->state != LWSS_HTTP_ISSUING_FILE) {
987 n = user_callback_handle_rxflow(wsi->protocol->callback,
988 wsi, LWS_CALLBACK_HTTP_WRITEABLE,
989 wsi->user_space, NULL, 0);
991 lwsl_info("writeable_fail\n");
997 /* >0 == completion, <0 == error */
998 n = lws_serve_http_file_fragment(wsi);
999 if (n < 0 || (n > 0 && lws_http_transaction_completed(wsi))) {
1000 lwsl_info("completed\n");
1005 case LWSCM_SERVER_LISTENER:
1008 /* pollin means a client has connected to us then */
1011 if (!(pollfd->revents & LWS_POLLIN) || !(pollfd->events & LWS_POLLIN))
1014 /* listen socket got an unencrypted connection... */
1016 clilen = sizeof(cli_addr);
1017 lws_latency_pre(context, wsi);
1018 accept_fd = accept(pollfd->fd, (struct sockaddr *)&cli_addr,
1020 lws_latency(context, wsi, "listener accept", accept_fd,
1022 if (accept_fd < 0) {
1023 if (LWS_ERRNO == LWS_EAGAIN ||
1024 LWS_ERRNO == LWS_EWOULDBLOCK) {
1025 lwsl_err("accept asks to try again\n");
1028 lwsl_err("ERROR on accept: %s\n", strerror(LWS_ERRNO));
1032 lws_plat_set_socket_options(context, accept_fd);
1034 lwsl_debug("accepted new conn port %u on fd=%d\n",
1035 ntohs(cli_addr.sin_port), accept_fd);
1038 /* not very beautiful... */
1039 accept_fd = (lws_sockfd_type)pollfd;
1042 * look at who we connected to and give user code a chance
1043 * to reject based on client IP. There's no protocol selected
1044 * yet so we issue this to protocols[0]
1046 if ((context->protocols[0].callback)(wsi,
1047 LWS_CALLBACK_FILTER_NETWORK_CONNECTION,
1048 NULL, (void *)(long)accept_fd, 0)) {
1049 lwsl_debug("Callback denied network connection\n");
1050 compatible_close(accept_fd);
1054 if (!lws_adopt_socket(context, accept_fd))
1055 /* already closed cleanly as necessary */
1059 } while (pt->fds_count < context->fd_limit_per_thread - 1 &&
1060 lws_poll_listen_fd(&pt->fds[wsi->position_in_fds_table]) > 0);
1068 if (!lws_server_socket_service_ssl(wsi, accept_fd))
1072 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
1078 * lws_serve_http_file() - Send a file back to the client using http
1079 * @wsi: Websocket instance (available from user callback)
1080 * @file: The file to issue over http
1081 * @content_type: The http content type, eg, text/html
1082 * @other_headers: NULL or pointer to header string
1083 * @other_headers_len: length of the other headers if non-NULL
1085 * This function is intended to be called from the callback in response
1086 * to http requests from the client. It allows the callback to issue
1087 * local files down the http link in a single step.
1089 * Returning <0 indicates error and the wsi should be closed. Returning
1090 * >0 indicates the file was completely sent and
1091 * lws_http_transaction_completed() called on the wsi (and close if != 0)
1092 * ==0 indicates the file transfer is started and needs more service later,
1093 * the wsi should be left alone.
1097 lws_serve_http_file(struct lws *wsi, const char *file, const char *content_type,
1098 const char *other_headers, int other_headers_len)
1100 struct lws_context *context = lws_get_context(wsi);
1101 struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
1102 unsigned char *response = pt->serv_buf + LWS_PRE;
1103 unsigned char *p = response;
1104 unsigned char *end = p + LWS_MAX_SOCKET_IO_BUF - LWS_PRE;
1107 wsi->u.http.fd = lws_plat_file_open(wsi, file, &wsi->u.http.filelen,
1110 if (wsi->u.http.fd == LWS_INVALID_FILE) {
1111 lwsl_err("Unable to open '%s'\n", file);
1112 lws_return_http_status(wsi, HTTP_STATUS_NOT_FOUND, NULL);
1117 if (lws_add_http_header_status(wsi, 200, &p, end))
1119 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_SERVER,
1120 (unsigned char *)"libwebsockets", 13,
1123 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE,
1124 (unsigned char *)content_type,
1125 strlen(content_type), &p, end))
1127 if (lws_add_http_header_content_length(wsi, wsi->u.http.filelen, &p, end))
1130 if (other_headers) {
1131 if ((end - p) < other_headers_len)
1133 memcpy(p, other_headers, other_headers_len);
1134 p += other_headers_len;
1137 if (lws_finalize_http_header(wsi, &p, end))
1140 ret = lws_write(wsi, response, p - response, LWS_WRITE_HTTP_HEADERS);
1141 if (ret != (p - response)) {
1142 lwsl_err("_write returned %d from %d\n", ret, (p - response));
1146 wsi->u.http.filepos = 0;
1147 wsi->state = LWSS_HTTP_ISSUING_FILE;
1149 return lws_serve_http_file_fragment(wsi);
1153 lws_interpret_incoming_packet(struct lws *wsi, unsigned char **buf, size_t len)
1157 lwsl_parser("%s: received %d byte packet\n", __func__, (int)len);
1159 lwsl_hexdump(*buf, len);
1162 /* let the rx protocol state machine have as much as it needs */
1166 * we were accepting input but now we stopped doing so
1168 if (!(wsi->rxflow_change_to & LWS_RXFLOW_ALLOW)) {
1169 lws_rxflow_cache(wsi, *buf, 0, len);
1170 lwsl_parser("%s: cached %d\n", __func__, len);
1174 if (wsi->u.ws.rx_draining_ext) {
1175 m = lws_rx_sm(wsi, 0);
1181 /* account for what we're using in rxflow buffer */
1182 if (wsi->rxflow_buffer)
1185 /* consume payload bytes efficiently */
1186 if (wsi->lws_rx_parse_state ==
1187 LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED)
1188 lws_payload_until_length_exhausted(wsi, buf, &len);
1190 /* process the byte */
1191 m = lws_rx_sm(wsi, *(*buf)++);
1197 lwsl_parser("%s: exit with %d unused\n", __func__, (int)len);
1203 lws_server_get_canonical_hostname(struct lws_context *context,
1204 struct lws_context_creation_info *info)
1206 if (info->options & LWS_SERVER_OPTION_SKIP_SERVER_CANONICAL_NAME)
1209 /* find canonical hostname */
1210 gethostname((char *)context->canonical_hostname,
1211 sizeof(context->canonical_hostname) - 1);
1213 lwsl_notice(" canonical_hostname = %s\n", context->canonical_hostname);