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 /* HTTP header had a content length? */
248 wsi->u.http.content_length = 0;
249 if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI) ||
250 lws_hdr_total_length(wsi, WSI_TOKEN_PATCH_URI) ||
251 lws_hdr_total_length(wsi, WSI_TOKEN_PUT_URI))
252 wsi->u.http.content_length = 100 * 1024 * 1024;
254 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH)) {
255 lws_hdr_copy(wsi, content_length_str,
256 sizeof(content_length_str) - 1,
257 WSI_TOKEN_HTTP_CONTENT_LENGTH);
258 wsi->u.http.content_length = atoi(content_length_str);
261 /* http_version? Default to 1.0, override with token: */
262 request_version = HTTP_VERSION_1_0;
264 /* Works for single digit HTTP versions. : */
265 http_version_len = lws_hdr_total_length(wsi, WSI_TOKEN_HTTP);
266 if (http_version_len > 7) {
267 lws_hdr_copy(wsi, http_version_str,
268 sizeof(http_version_str) - 1, WSI_TOKEN_HTTP);
269 if (http_version_str[5] == '1' && http_version_str[7] == '1')
270 request_version = HTTP_VERSION_1_1;
272 wsi->u.http.request_version = request_version;
274 /* HTTP/1.1 defaults to "keep-alive", 1.0 to "close" */
275 if (request_version == HTTP_VERSION_1_1)
276 connection_type = HTTP_CONNECTION_KEEP_ALIVE;
278 connection_type = HTTP_CONNECTION_CLOSE;
280 /* Override default if http "Connection:" header: */
281 if (lws_hdr_total_length(wsi, WSI_TOKEN_CONNECTION)) {
282 lws_hdr_copy(wsi, http_conn_str, sizeof(http_conn_str) - 1,
283 WSI_TOKEN_CONNECTION);
284 http_conn_str[sizeof(http_conn_str) - 1] = '\0';
285 if (!strcasecmp(http_conn_str, "keep-alive"))
286 connection_type = HTTP_CONNECTION_KEEP_ALIVE;
288 if (!strcasecmp(http_conn_str, "close"))
289 connection_type = HTTP_CONNECTION_CLOSE;
291 wsi->u.http.connection_type = connection_type;
293 n = wsi->protocol->callback(wsi, LWS_CALLBACK_FILTER_HTTP_CONNECTION,
294 wsi->user_space, uri_ptr, uri_len);
296 lwsl_info("LWS_CALLBACK_HTTP closing\n");
301 * if there is content supposed to be coming,
302 * put a timeout on it having arrived
304 lws_set_timeout(wsi, PENDING_TIMEOUT_HTTP_CONTENT,
307 n = wsi->protocol->callback(wsi, LWS_CALLBACK_HTTP,
308 wsi->user_space, uri_ptr, uri_len);
311 * If we're not issuing a file, check for content_length or
312 * HTTP keep-alive. No keep-alive header allocation for
313 * ISSUING_FILE, as this uses HTTP/1.0.
315 * In any case, return 0 and let lws_read decide how to
316 * proceed based on state
318 if (wsi->state != LWSS_HTTP_ISSUING_FILE)
319 /* Prepare to read body if we have a content length: */
320 if (wsi->u.http.content_length > 0)
321 wsi->state = LWSS_HTTP_BODY;
326 /* we're closing, losing some rx is OK */
327 wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
328 lws_header_table_detach(wsi);
335 lws_handshake_server(struct lws *wsi, unsigned char **buf, size_t len)
337 struct lws_context *context = lws_get_context(wsi);
338 struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
339 struct _lws_header_related hdr;
340 struct allocated_headers *ah;
341 int protocol_len, n, hit;
342 char protocol_list[128];
343 char protocol_name[32];
346 assert(len < 10000000);
347 assert(wsi->u.hdr.ah);
350 wsi->u.hdr.more_rx_waiting = !!len;
352 assert(wsi->mode == LWSCM_HTTP_SERVING);
354 if (lws_parse(wsi, *(*buf)++)) {
355 lwsl_info("lws_parse failed\n");
359 if (wsi->u.hdr.parser_state != WSI_PARSING_COMPLETE)
362 lwsl_parser("lws_parse sees parsing complete\n");
364 wsi->mode = LWSCM_PRE_WS_SERVING_ACCEPT;
365 lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
367 /* is this websocket protocol or normal http 1.0? */
369 if (lws_hdr_total_length(wsi, WSI_TOKEN_UPGRADE)) {
370 if (!strcasecmp(lws_hdr_simple_ptr(wsi, WSI_TOKEN_UPGRADE),
372 lwsl_info("Upgrade to ws\n");
376 if (!strcasecmp(lws_hdr_simple_ptr(wsi, WSI_TOKEN_UPGRADE),
378 lwsl_info("Upgrade to h2c-14\n");
382 lwsl_err("Unknown upgrade\n");
383 /* dunno what he wanted to upgrade to */
387 /* no upgrade ack... he remained as HTTP */
389 lwsl_info("No upgrade\n");
392 lws_union_transition(wsi, LWSCM_HTTP_SERVING_ACCEPTED);
393 wsi->state = LWSS_HTTP;
394 wsi->u.http.fd = LWS_INVALID_FILE;
396 /* expose it at the same offset as u.hdr */
398 lwsl_debug("%s: wsi %p: ah %p\n", __func__, (void *)wsi, (void *)wsi->u.hdr.ah);
400 n = lws_http_action(wsi);
406 if (!lws_hdr_total_length(wsi, WSI_TOKEN_HTTP2_SETTINGS)) {
407 lwsl_err("missing http2_settings\n");
411 lwsl_err("h2c upgrade...\n");
413 p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP2_SETTINGS);
414 /* convert the peer's HTTP-Settings */
415 n = lws_b64_decode_string(p, protocol_list,
416 sizeof(protocol_list));
418 lwsl_parser("HTTP2_SETTINGS too long\n");
422 /* adopt the header info */
426 lws_union_transition(wsi, LWSCM_HTTP2_SERVING);
428 /* http2 union member has http union struct at start */
431 lws_http2_init(&wsi->u.http2.peer_settings);
432 lws_http2_init(&wsi->u.http2.my_settings);
436 lws_http2_interpret_settings_payload(&wsi->u.http2.peer_settings,
437 (unsigned char *)protocol_list, n);
439 strcpy(protocol_list,
440 "HTTP/1.1 101 Switching Protocols\x0d\x0a"
441 "Connection: Upgrade\x0d\x0a"
442 "Upgrade: h2c\x0d\x0a\x0d\x0a");
443 n = lws_issue_raw(wsi, (unsigned char *)protocol_list,
444 strlen(protocol_list));
445 if (n != strlen(protocol_list)) {
446 lwsl_debug("http2 switch: ERROR writing to socket\n");
450 wsi->state = LWSS_HTTP2_AWAIT_CLIENT_PREFACE;
457 lwsl_err("NULL protocol at lws_read\n");
462 * Select the first protocol we support from the list
463 * the client sent us.
465 * Copy it to remove header fragmentation
468 if (lws_hdr_copy(wsi, protocol_list, sizeof(protocol_list) - 1,
469 WSI_TOKEN_PROTOCOL) < 0) {
470 lwsl_err("protocol list too long");
474 protocol_len = lws_hdr_total_length(wsi, WSI_TOKEN_PROTOCOL);
475 protocol_list[protocol_len] = '\0';
481 while (n < sizeof(protocol_name) - 1 && *p && *p !=',')
482 protocol_name[n++] = *p++;
483 protocol_name[n] = '\0';
487 lwsl_info("checking %s\n", protocol_name);
490 while (context->protocols[n].callback) {
491 if (context->protocols[n].name &&
492 !strcmp(context->protocols[n].name,
494 lwsl_info("prot match %d\n", n);
495 wsi->protocol = &context->protocols[n];
504 /* we didn't find a protocol he wanted? */
507 if (lws_hdr_simple_ptr(wsi, WSI_TOKEN_PROTOCOL)) {
508 lwsl_err("No protocol from \"%s\" supported\n",
513 * some clients only have one protocol and
514 * do not sent the protocol list header...
515 * allow it and match to protocol 0
517 lwsl_info("defaulting to prot 0 handler\n");
518 wsi->protocol = &context->protocols[0];
521 /* allocate wsi->user storage */
522 if (lws_ensure_user_space(wsi))
526 * Give the user code a chance to study the request and
527 * have the opportunity to deny it
530 if ((wsi->protocol->callback)(wsi,
531 LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION,
533 lws_hdr_simple_ptr(wsi, WSI_TOKEN_PROTOCOL), 0)) {
534 lwsl_warn("User code denied connection\n");
539 * Perform the handshake according to the protocol version the
543 switch (wsi->ietf_spec_revision) {
545 lwsl_parser("lws_parse calling handshake_04\n");
546 if (handshake_0405(context, wsi)) {
547 lwsl_info("hs0405 has failed the connection\n");
553 lwsl_warn("Unknown client spec version %d\n",
554 wsi->ietf_spec_revision);
558 /* we are upgrading to ws, so http/1.1 and keepalive +
559 * pipelined header considerations about keeping the ah around
560 * no longer apply. However it's common for the first ws
561 * protocol data to have been coalesced with the browser
562 * upgrade request and to already be in the ah rx buffer.
565 lwsl_err("%s: %p: inheriting ah in ws mode (rxpos: %d, rxlen: %d)\n",
566 __func__, wsi, wsi->u.hdr.ah->rxpos, wsi->u.hdr.ah->rxlen);
570 lws_union_transition(wsi, LWSCM_WS_SERVING);
572 * first service is WS mode will notice this, use the RX and
573 * then detach the ah (caution: we are not in u.hdr union
574 * mode any more then... ah_temp member is at start the same
577 * Beacuse rxpos/rxlen shows something in the ah, we will get
578 * service guaranteed next time around the event loop
580 * All union members begin with hdr, so we can use it even
581 * though we transitioned to ws union mode (the ah detach
582 * code uses it anyway).
588 * create the frame buffer for this connection according to the
589 * size mentioned in the protocol definition. If 0 there, use
590 * a big default for compatibility
593 n = wsi->protocol->rx_buffer_size;
595 n = LWS_MAX_SOCKET_IO_BUF;
597 wsi->u.ws.rx_ubuf = lws_malloc(n + 4 /* 0x0000ffff zlib */);
598 if (!wsi->u.ws.rx_ubuf) {
599 lwsl_err("Out of Mem allocating rx buffer %d\n", n);
602 wsi->u.ws.rx_ubuf_alloc = n;
603 lwsl_info("Allocating RX buffer %d\n", n);
605 if (setsockopt(wsi->sock, SOL_SOCKET, SO_SNDBUF,
606 (const char *)&n, sizeof n)) {
607 lwsl_warn("Failed to set SNDBUF to %d", n);
611 lwsl_parser("accepted v%02d connection\n", wsi->ietf_spec_revision);
614 } /* while all chars are handled */
619 /* drop the header info */
620 /* we're closing, losing some rx is OK */
621 wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
622 lws_header_table_detach(wsi);
628 lws_get_idlest_tsi(struct lws_context *context)
630 unsigned int lowest = ~0;
633 for (; n < context->count_threads; n++) {
634 if ((unsigned int)context->pt[n].fds_count != context->fd_limit_per_thread - 1 &&
635 (unsigned int)context->pt[n].fds_count < lowest) {
636 lowest = context->pt[n].fds_count;
645 lws_create_new_server_wsi(struct lws_context *context)
648 int n = lws_get_idlest_tsi(context);
651 lwsl_err("no space for new conn\n");
655 new_wsi = lws_zalloc(sizeof(struct lws));
656 if (new_wsi == NULL) {
657 lwsl_err("Out of memory for new connection\n");
662 lwsl_info("Accepted %p to tsi %d\n", new_wsi, new_wsi->tsi);
664 new_wsi->context = context;
665 new_wsi->pending_timeout = NO_PENDING_TIMEOUT;
666 new_wsi->rxflow_change_to = LWS_RXFLOW_ALLOW;
668 /* intialize the instance struct */
670 new_wsi->state = LWSS_HTTP;
671 new_wsi->mode = LWSCM_HTTP_SERVING;
672 new_wsi->hdr_parsing_completed = 0;
674 #ifdef LWS_OPENSSL_SUPPORT
675 new_wsi->use_ssl = LWS_SSL_ENABLED(context);
679 * these can only be set once the protocol is known
680 * we set an unestablished connection's protocol pointer
681 * to the start of the supported list, so it can look
682 * for matching ones during the handshake
684 new_wsi->protocol = context->protocols;
685 new_wsi->user_space = NULL;
686 new_wsi->ietf_spec_revision = 0;
687 new_wsi->sock = LWS_SOCK_INVALID;
688 context->count_wsi_allocated++;
691 * outermost create notification for wsi
692 * no user_space because no protocol selection
694 context->protocols[0].callback(new_wsi, LWS_CALLBACK_WSI_CREATE,
701 * lws_http_transaction_completed() - wait for new http transaction or close
702 * @wsi: websocket connection
704 * Returns 1 if the HTTP connection must close now
705 * Returns 0 and resets connection to wait for new HTTP header /
706 * transaction if possible
709 LWS_VISIBLE int LWS_WARN_UNUSED_RESULT
710 lws_http_transaction_completed(struct lws *wsi)
712 lwsl_debug("%s: wsi %p\n", __func__, wsi);
713 /* if we can't go back to accept new headers, drop the connection */
714 if (wsi->u.http.connection_type != HTTP_CONNECTION_KEEP_ALIVE) {
715 lwsl_info("%s: %p: close connection\n", __func__, wsi);
719 /* otherwise set ourselves up ready to go again */
720 wsi->state = LWSS_HTTP;
721 wsi->mode = LWSCM_HTTP_SERVING;
722 wsi->u.http.content_length = 0;
723 wsi->hdr_parsing_completed = 0;
725 /* He asked for it to stay alive indefinitely */
726 lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
729 * We already know we are on http1.1 / keepalive and the next thing
730 * coming will be another header set.
732 * If there is no pending rx and we still have the ah, drop it and
733 * reacquire a new ah when the new headers start to arrive. (Otherwise
734 * we needlessly hog an ah indefinitely.)
736 * However if there is pending rx and we know from the keepalive state
737 * that is already at least the start of another header set, simply
738 * reset the existing header table and keep it.
741 if (wsi->u.hdr.ah->rxpos == wsi->u.hdr.ah->rxlen)
742 lws_header_table_detach(wsi);
744 lws_header_table_reset(wsi);
747 /* If we're (re)starting on headers, need other implied init */
748 wsi->u.hdr.ues = URIES_IDLE;
750 lwsl_info("%s: %p: keep-alive await new transaction\n", __func__, wsi);
756 * lws_adopt_socket() - adopt foreign socket as if listen socket accepted it
757 * @context: lws context
758 * @accept_fd: fd of already-accepted socket to adopt
760 * Either returns new wsi bound to accept_fd, or closes accept_fd and
761 * returns NULL, having cleaned up any new wsi pieces.
763 * LWS adopts the socket in http serving mode, it's ready to accept an upgrade
764 * to ws or just serve http.
767 LWS_VISIBLE struct lws *
768 lws_adopt_socket(struct lws_context *context, lws_sockfd_type accept_fd)
770 struct lws *new_wsi = lws_create_new_server_wsi(context);
773 compatible_close(accept_fd);
777 lwsl_debug("%s: new wsi %p\n", __func__, new_wsi);
779 new_wsi->sock = accept_fd;
781 /* the transport is accepted... give him time to negotiate */
782 lws_set_timeout(new_wsi, PENDING_TIMEOUT_ESTABLISH_WITH_SERVER,
786 mbed3_tcp_stream_accept(accept_fd, new_wsi);
790 * A new connection was accepted. Give the user a chance to
791 * set properties of the newly created wsi. There's no protocol
792 * selected yet so we issue this to protocols[0]
794 if ((context->protocols[0].callback)(new_wsi,
795 LWS_CALLBACK_SERVER_NEW_CLIENT_INSTANTIATED, NULL, NULL, 0)) {
796 compatible_close(new_wsi->sock);
801 lws_libev_accept(new_wsi, new_wsi->sock);
802 lws_libuv_accept(new_wsi, new_wsi->sock);
804 if (!LWS_SSL_ENABLED(context)) {
805 if (insert_wsi_socket_into_fds(context, new_wsi))
808 new_wsi->mode = LWSCM_SSL_INIT;
809 if (lws_server_socket_service_ssl(new_wsi, accept_fd))
816 lwsl_err("%s: fail\n", __func__);
817 lws_close_free_wsi(new_wsi, LWS_CLOSE_STATUS_NOSTATUS);
823 lws_server_socket_service(struct lws_context *context, struct lws *wsi,
824 struct lws_pollfd *pollfd)
826 struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
827 lws_sockfd_type accept_fd = LWS_SOCK_INVALID;
828 struct allocated_headers *ah;
830 struct sockaddr_in cli_addr;
837 case LWSCM_HTTP_SERVING:
838 case LWSCM_HTTP_SERVING_ACCEPTED:
839 case LWSCM_HTTP2_SERVING:
841 /* handle http headers coming in */
843 /* pending truncated sends have uber priority */
845 if (wsi->trunc_len) {
846 if (!(pollfd->revents & LWS_POLLOUT))
849 if (lws_issue_raw(wsi, wsi->trunc_alloc +
854 * we can't afford to allow input processing to send
855 * something new, so spin around he event loop until
856 * he doesn't have any partials
861 /* any incoming data ready? */
863 if (!(pollfd->revents & pollfd->events & LWS_POLLIN))
866 /* these states imply we MUST have an ah attached */
868 if (wsi->state == LWSS_HTTP ||
869 wsi->state == LWSS_HTTP_ISSUING_FILE ||
870 wsi->state == LWSS_HTTP_HEADERS) {
872 if (lws_header_table_attach(wsi))
877 lwsl_debug("%s: %p: rxpos:%d rxlen:%d\n", __func__, wsi,
878 ah->rxpos, ah->rxlen);
880 /* if nothing in ah rx buffer, get some fresh rx */
881 if (ah->rxpos == ah->rxlen) {
882 ah->rxlen = lws_ssl_capable_read(wsi, ah->rx,
885 lwsl_debug("%s: wsi %p, ah->rxlen = %d\r\n",
886 __func__, wsi, ah->rxlen);
889 lwsl_info("%s: read 0 len\n", __func__);
890 /* lwsl_info(" state=%d\n", wsi->state); */
891 // if (!wsi->hdr_parsing_completed)
892 // lws_header_table_detach(wsi);
894 case LWS_SSL_CAPABLE_ERROR:
896 case LWS_SSL_CAPABLE_MORE_SERVICE:
897 ah->rxlen = ah->rxpos = 0;
901 assert(ah->rxpos != ah->rxlen && ah->rxlen);
902 /* just ignore incoming if waiting for close */
903 if (wsi->state != LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE) {
904 n = lws_read(wsi, ah->rx + ah->rxpos,
905 ah->rxlen - ah->rxpos);
906 if (n < 0) /* we closed wsi */
909 if ( wsi->u.hdr.ah->rxlen)
910 wsi->u.hdr.ah->rxpos += n;
912 if (wsi->u.hdr.ah->rxpos == wsi->u.hdr.ah->rxlen &&
913 (wsi->mode != LWSCM_HTTP_SERVING &&
914 wsi->mode != LWSCM_HTTP_SERVING_ACCEPTED &&
915 wsi->mode != LWSCM_HTTP2_SERVING))
916 lws_header_table_detach(wsi);
924 len = lws_ssl_capable_read(wsi, pt->serv_buf,
925 LWS_MAX_SOCKET_IO_BUF);
926 lwsl_debug("%s: wsi %p read %d\r\n", __func__, wsi, len);
929 lwsl_info("%s: read 0 len\n", __func__);
930 /* lwsl_info(" state=%d\n", wsi->state); */
931 // if (!wsi->hdr_parsing_completed)
932 // lws_header_table_detach(wsi);
934 case LWS_SSL_CAPABLE_ERROR:
936 case LWS_SSL_CAPABLE_MORE_SERVICE:
940 /* just ignore incoming if waiting for close */
941 if (wsi->state != LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE) {
943 * hm this may want to send
944 * (via HTTP callback for example)
946 n = lws_read(wsi, pt->serv_buf, len);
947 if (n < 0) /* we closed wsi */
949 /* hum he may have used up the
950 * writability above */
955 /* this handles POLLOUT for http serving fragments */
957 if (!(pollfd->revents & LWS_POLLOUT))
961 if (lws_change_pollfd(wsi, LWS_POLLOUT, 0)) {
962 lwsl_notice("%s a\n", __func__);
966 if (wsi->state != LWSS_HTTP_ISSUING_FILE) {
967 n = user_callback_handle_rxflow(wsi->protocol->callback,
968 wsi, LWS_CALLBACK_HTTP_WRITEABLE,
969 wsi->user_space, NULL, 0);
971 lwsl_info("writeable_fail\n");
977 /* >0 == completion, <0 == error */
978 n = lws_serve_http_file_fragment(wsi);
979 if (n < 0 || (n > 0 && lws_http_transaction_completed(wsi))) {
980 lwsl_info("completed\n");
985 case LWSCM_SERVER_LISTENER:
988 /* pollin means a client has connected to us then */
991 if (!(pollfd->revents & LWS_POLLIN) || !(pollfd->events & LWS_POLLIN))
994 /* listen socket got an unencrypted connection... */
996 clilen = sizeof(cli_addr);
997 lws_latency_pre(context, wsi);
998 accept_fd = accept(pollfd->fd, (struct sockaddr *)&cli_addr,
1000 lws_latency(context, wsi, "listener accept", accept_fd,
1002 if (accept_fd < 0) {
1003 if (LWS_ERRNO == LWS_EAGAIN ||
1004 LWS_ERRNO == LWS_EWOULDBLOCK) {
1005 lwsl_err("accept asks to try again\n");
1008 lwsl_err("ERROR on accept: %s\n", strerror(LWS_ERRNO));
1012 lws_plat_set_socket_options(context, accept_fd);
1014 lwsl_debug("accepted new conn port %u on fd=%d\n",
1015 ntohs(cli_addr.sin_port), accept_fd);
1018 /* not very beautiful... */
1019 accept_fd = (lws_sockfd_type)pollfd;
1022 * look at who we connected to and give user code a chance
1023 * to reject based on client IP. There's no protocol selected
1024 * yet so we issue this to protocols[0]
1026 if ((context->protocols[0].callback)(wsi,
1027 LWS_CALLBACK_FILTER_NETWORK_CONNECTION,
1028 NULL, (void *)(long)accept_fd, 0)) {
1029 lwsl_debug("Callback denied network connection\n");
1030 compatible_close(accept_fd);
1034 if (!lws_adopt_socket(context, accept_fd))
1035 /* already closed cleanly as necessary */
1039 } while (pt->fds_count < context->fd_limit_per_thread - 1 &&
1040 lws_poll_listen_fd(&pt->fds[wsi->position_in_fds_table]) > 0);
1048 if (!lws_server_socket_service_ssl(wsi, accept_fd))
1052 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
1058 * lws_serve_http_file() - Send a file back to the client using http
1059 * @wsi: Websocket instance (available from user callback)
1060 * @file: The file to issue over http
1061 * @content_type: The http content type, eg, text/html
1062 * @other_headers: NULL or pointer to header string
1063 * @other_headers_len: length of the other headers if non-NULL
1065 * This function is intended to be called from the callback in response
1066 * to http requests from the client. It allows the callback to issue
1067 * local files down the http link in a single step.
1069 * Returning <0 indicates error and the wsi should be closed. Returning
1070 * >0 indicates the file was completely sent and
1071 * lws_http_transaction_completed() called on the wsi (and close if != 0)
1072 * ==0 indicates the file transfer is started and needs more service later,
1073 * the wsi should be left alone.
1077 lws_serve_http_file(struct lws *wsi, const char *file, const char *content_type,
1078 const char *other_headers, int other_headers_len)
1080 struct lws_context *context = lws_get_context(wsi);
1081 struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
1082 unsigned char *response = pt->serv_buf + LWS_PRE;
1083 unsigned char *p = response;
1084 unsigned char *end = p + LWS_MAX_SOCKET_IO_BUF - LWS_PRE;
1087 wsi->u.http.fd = lws_plat_file_open(wsi, file, &wsi->u.http.filelen,
1090 if (wsi->u.http.fd == LWS_INVALID_FILE) {
1091 lwsl_err("Unable to open '%s'\n", file);
1092 lws_return_http_status(wsi, HTTP_STATUS_NOT_FOUND, NULL);
1097 if (lws_add_http_header_status(wsi, 200, &p, end))
1099 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_SERVER,
1100 (unsigned char *)"libwebsockets", 13,
1103 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE,
1104 (unsigned char *)content_type,
1105 strlen(content_type), &p, end))
1107 if (lws_add_http_header_content_length(wsi, wsi->u.http.filelen, &p, end))
1110 if (other_headers) {
1111 if ((end - p) < other_headers_len)
1113 memcpy(p, other_headers, other_headers_len);
1114 p += other_headers_len;
1117 if (lws_finalize_http_header(wsi, &p, end))
1120 ret = lws_write(wsi, response, p - response, LWS_WRITE_HTTP_HEADERS);
1121 if (ret != (p - response)) {
1122 lwsl_err("_write returned %d from %d\n", ret, (p - response));
1126 wsi->u.http.filepos = 0;
1127 wsi->state = LWSS_HTTP_ISSUING_FILE;
1129 return lws_serve_http_file_fragment(wsi);
1133 lws_interpret_incoming_packet(struct lws *wsi, unsigned char **buf, size_t len)
1137 lwsl_parser("%s: received %d byte packet\n", __func__, (int)len);
1139 lwsl_hexdump(*buf, len);
1142 /* let the rx protocol state machine have as much as it needs */
1146 * we were accepting input but now we stopped doing so
1148 if (!(wsi->rxflow_change_to & LWS_RXFLOW_ALLOW)) {
1149 lws_rxflow_cache(wsi, *buf, 0, len);
1150 lwsl_parser("%s: cached %d\n", __func__, len);
1154 if (wsi->u.ws.rx_draining_ext) {
1155 m = lws_rx_sm(wsi, 0);
1161 /* account for what we're using in rxflow buffer */
1162 if (wsi->rxflow_buffer)
1165 /* process the byte */
1166 m = lws_rx_sm(wsi, *(*buf)++);
1172 lwsl_parser("%s: exit with %d unused\n", __func__, (int)len);
1178 lws_server_get_canonical_hostname(struct lws_context *context,
1179 struct lws_context_creation_info *info)
1181 if (info->options & LWS_SERVER_OPTION_SKIP_SERVER_CANONICAL_NAME)
1184 /* find canonical hostname */
1185 gethostname((char *)context->canonical_hostname,
1186 sizeof(context->canonical_hostname) - 1);
1188 lwsl_notice(" canonical_hostname = %s\n", context->canonical_hostname);