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,
305 wsi->context->timeout_secs);
307 n = wsi->protocol->callback(wsi, LWS_CALLBACK_HTTP,
308 wsi->user_space, uri_ptr, uri_len);
310 lwsl_info("LWS_CALLBACK_HTTP closing\n");
316 * If we're not issuing a file, check for content_length or
317 * HTTP keep-alive. No keep-alive header allocation for
318 * ISSUING_FILE, as this uses HTTP/1.0.
320 * In any case, return 0 and let lws_read decide how to
321 * proceed based on state
323 if (wsi->state != LWSS_HTTP_ISSUING_FILE)
324 /* Prepare to read body if we have a content length: */
325 if (wsi->u.http.content_length > 0)
326 wsi->state = LWSS_HTTP_BODY;
331 /* we're closing, losing some rx is OK */
332 wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
333 lws_header_table_detach(wsi);
340 lws_handshake_server(struct lws *wsi, unsigned char **buf, size_t len)
342 struct lws_context *context = lws_get_context(wsi);
343 struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
344 struct _lws_header_related hdr;
345 struct allocated_headers *ah;
346 int protocol_len, n, hit;
347 char protocol_list[128];
348 char protocol_name[32];
351 assert(len < 10000000);
352 assert(wsi->u.hdr.ah);
355 wsi->u.hdr.more_rx_waiting = !!len;
357 assert(wsi->mode == LWSCM_HTTP_SERVING);
359 if (lws_parse(wsi, *(*buf)++)) {
360 lwsl_info("lws_parse failed\n");
364 if (wsi->u.hdr.parser_state != WSI_PARSING_COMPLETE)
367 lwsl_parser("lws_parse sees parsing complete\n");
369 wsi->mode = LWSCM_PRE_WS_SERVING_ACCEPT;
370 lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
372 /* is this websocket protocol or normal http 1.0? */
374 if (lws_hdr_total_length(wsi, WSI_TOKEN_UPGRADE)) {
375 if (!strcasecmp(lws_hdr_simple_ptr(wsi, WSI_TOKEN_UPGRADE),
377 lwsl_info("Upgrade to ws\n");
381 if (!strcasecmp(lws_hdr_simple_ptr(wsi, WSI_TOKEN_UPGRADE),
383 lwsl_info("Upgrade to h2c-14\n");
387 lwsl_err("Unknown upgrade\n");
388 /* dunno what he wanted to upgrade to */
392 /* no upgrade ack... he remained as HTTP */
394 lwsl_info("No upgrade\n");
397 lws_union_transition(wsi, LWSCM_HTTP_SERVING_ACCEPTED);
398 wsi->state = LWSS_HTTP;
399 wsi->u.http.fd = LWS_INVALID_FILE;
401 /* expose it at the same offset as u.hdr */
403 lwsl_debug("%s: wsi %p: ah %p\n", __func__, (void *)wsi, (void *)wsi->u.hdr.ah);
405 n = lws_http_action(wsi);
411 if (!lws_hdr_total_length(wsi, WSI_TOKEN_HTTP2_SETTINGS)) {
412 lwsl_err("missing http2_settings\n");
416 lwsl_err("h2c upgrade...\n");
418 p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP2_SETTINGS);
419 /* convert the peer's HTTP-Settings */
420 n = lws_b64_decode_string(p, protocol_list,
421 sizeof(protocol_list));
423 lwsl_parser("HTTP2_SETTINGS too long\n");
427 /* adopt the header info */
431 lws_union_transition(wsi, LWSCM_HTTP2_SERVING);
433 /* http2 union member has http union struct at start */
436 lws_http2_init(&wsi->u.http2.peer_settings);
437 lws_http2_init(&wsi->u.http2.my_settings);
441 lws_http2_interpret_settings_payload(&wsi->u.http2.peer_settings,
442 (unsigned char *)protocol_list, n);
444 strcpy(protocol_list,
445 "HTTP/1.1 101 Switching Protocols\x0d\x0a"
446 "Connection: Upgrade\x0d\x0a"
447 "Upgrade: h2c\x0d\x0a\x0d\x0a");
448 n = lws_issue_raw(wsi, (unsigned char *)protocol_list,
449 strlen(protocol_list));
450 if (n != strlen(protocol_list)) {
451 lwsl_debug("http2 switch: ERROR writing to socket\n");
455 wsi->state = LWSS_HTTP2_AWAIT_CLIENT_PREFACE;
462 lwsl_err("NULL protocol at lws_read\n");
467 * Select the first protocol we support from the list
468 * the client sent us.
470 * Copy it to remove header fragmentation
473 if (lws_hdr_copy(wsi, protocol_list, sizeof(protocol_list) - 1,
474 WSI_TOKEN_PROTOCOL) < 0) {
475 lwsl_err("protocol list too long");
479 protocol_len = lws_hdr_total_length(wsi, WSI_TOKEN_PROTOCOL);
480 protocol_list[protocol_len] = '\0';
486 while (n < sizeof(protocol_name) - 1 && *p && *p !=',')
487 protocol_name[n++] = *p++;
488 protocol_name[n] = '\0';
492 lwsl_info("checking %s\n", protocol_name);
495 while (context->protocols[n].callback) {
496 if (context->protocols[n].name &&
497 !strcmp(context->protocols[n].name,
499 lwsl_info("prot match %d\n", n);
500 wsi->protocol = &context->protocols[n];
509 /* we didn't find a protocol he wanted? */
512 if (lws_hdr_simple_ptr(wsi, WSI_TOKEN_PROTOCOL)) {
513 lwsl_err("No protocol from \"%s\" supported\n",
518 * some clients only have one protocol and
519 * do not sent the protocol list header...
520 * allow it and match to protocol 0
522 lwsl_info("defaulting to prot 0 handler\n");
523 wsi->protocol = &context->protocols[0];
526 /* allocate wsi->user storage */
527 if (lws_ensure_user_space(wsi))
531 * Give the user code a chance to study the request and
532 * have the opportunity to deny it
535 if ((wsi->protocol->callback)(wsi,
536 LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION,
538 lws_hdr_simple_ptr(wsi, WSI_TOKEN_PROTOCOL), 0)) {
539 lwsl_warn("User code denied connection\n");
544 * Perform the handshake according to the protocol version the
548 switch (wsi->ietf_spec_revision) {
550 lwsl_parser("lws_parse calling handshake_04\n");
551 if (handshake_0405(context, wsi)) {
552 lwsl_info("hs0405 has failed the connection\n");
558 lwsl_warn("Unknown client spec version %d\n",
559 wsi->ietf_spec_revision);
563 /* we are upgrading to ws, so http/1.1 and keepalive +
564 * pipelined header considerations about keeping the ah around
565 * no longer apply. However it's common for the first ws
566 * protocol data to have been coalesced with the browser
567 * upgrade request and to already be in the ah rx buffer.
570 lwsl_info("%s: %p: inheriting ah in ws mode (rxpos:%d, rxlen:%d)\n",
571 __func__, wsi, wsi->u.hdr.ah->rxpos,
572 wsi->u.hdr.ah->rxlen);
576 lws_union_transition(wsi, LWSCM_WS_SERVING);
578 * first service is WS mode will notice this, use the RX and
579 * then detach the ah (caution: we are not in u.hdr union
580 * mode any more then... ah_temp member is at start the same
583 * Because rxpos/rxlen shows something in the ah, we will get
584 * service guaranteed next time around the event loop
586 * All union members begin with hdr, so we can use it even
587 * though we transitioned to ws union mode (the ah detach
588 * code uses it anyway).
594 * create the frame buffer for this connection according to the
595 * size mentioned in the protocol definition. If 0 there, use
596 * a big default for compatibility
599 n = wsi->protocol->rx_buffer_size;
601 n = LWS_MAX_SOCKET_IO_BUF;
603 wsi->u.ws.rx_ubuf = lws_malloc(n + 4 /* 0x0000ffff zlib */);
604 if (!wsi->u.ws.rx_ubuf) {
605 lwsl_err("Out of Mem allocating rx buffer %d\n", n);
608 wsi->u.ws.rx_ubuf_alloc = n;
609 lwsl_info("Allocating RX buffer %d\n", n);
611 if (setsockopt(wsi->sock, SOL_SOCKET, SO_SNDBUF,
612 (const char *)&n, sizeof n)) {
613 lwsl_warn("Failed to set SNDBUF to %d", n);
617 lwsl_parser("accepted v%02d connection\n", wsi->ietf_spec_revision);
620 } /* while all chars are handled */
625 /* drop the header info */
626 /* we're closing, losing some rx is OK */
627 wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
628 lws_header_table_detach(wsi);
634 lws_get_idlest_tsi(struct lws_context *context)
636 unsigned int lowest = ~0;
639 for (; n < context->count_threads; n++) {
640 if ((unsigned int)context->pt[n].fds_count != context->fd_limit_per_thread - 1 &&
641 (unsigned int)context->pt[n].fds_count < lowest) {
642 lowest = context->pt[n].fds_count;
651 lws_create_new_server_wsi(struct lws_context *context)
654 int n = lws_get_idlest_tsi(context);
657 lwsl_err("no space for new conn\n");
661 new_wsi = lws_zalloc(sizeof(struct lws));
662 if (new_wsi == NULL) {
663 lwsl_err("Out of memory for new connection\n");
668 lwsl_info("Accepted %p to tsi %d\n", new_wsi, new_wsi->tsi);
670 new_wsi->context = context;
671 new_wsi->pending_timeout = NO_PENDING_TIMEOUT;
672 new_wsi->rxflow_change_to = LWS_RXFLOW_ALLOW;
674 /* intialize the instance struct */
676 new_wsi->state = LWSS_HTTP;
677 new_wsi->mode = LWSCM_HTTP_SERVING;
678 new_wsi->hdr_parsing_completed = 0;
680 #ifdef LWS_OPENSSL_SUPPORT
681 new_wsi->use_ssl = LWS_SSL_ENABLED(context);
685 * these can only be set once the protocol is known
686 * we set an unestablished connection's protocol pointer
687 * to the start of the supported list, so it can look
688 * for matching ones during the handshake
690 new_wsi->protocol = context->protocols;
691 new_wsi->user_space = NULL;
692 new_wsi->ietf_spec_revision = 0;
693 new_wsi->sock = LWS_SOCK_INVALID;
694 context->count_wsi_allocated++;
697 * outermost create notification for wsi
698 * no user_space because no protocol selection
700 context->protocols[0].callback(new_wsi, LWS_CALLBACK_WSI_CREATE,
707 * lws_http_transaction_completed() - wait for new http transaction or close
708 * @wsi: websocket connection
710 * Returns 1 if the HTTP connection must close now
711 * Returns 0 and resets connection to wait for new HTTP header /
712 * transaction if possible
715 LWS_VISIBLE int LWS_WARN_UNUSED_RESULT
716 lws_http_transaction_completed(struct lws *wsi)
718 lwsl_debug("%s: wsi %p\n", __func__, wsi);
719 /* if we can't go back to accept new headers, drop the connection */
720 if (wsi->u.http.connection_type != HTTP_CONNECTION_KEEP_ALIVE) {
721 lwsl_info("%s: %p: close connection\n", __func__, wsi);
725 /* otherwise set ourselves up ready to go again */
726 wsi->state = LWSS_HTTP;
727 wsi->mode = LWSCM_HTTP_SERVING;
728 wsi->u.http.content_length = 0;
729 wsi->hdr_parsing_completed = 0;
731 /* He asked for it to stay alive indefinitely */
732 lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
735 * We already know we are on http1.1 / keepalive and the next thing
736 * coming will be another header set.
738 * If there is no pending rx and we still have the ah, drop it and
739 * reacquire a new ah when the new headers start to arrive. (Otherwise
740 * we needlessly hog an ah indefinitely.)
742 * However if there is pending rx and we know from the keepalive state
743 * that is already at least the start of another header set, simply
744 * reset the existing header table and keep it.
747 if (!wsi->u.hdr.more_rx_waiting) {
748 wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
749 lws_header_table_detach(wsi);
751 lws_header_table_reset(wsi);
754 /* If we're (re)starting on headers, need other implied init */
755 wsi->u.hdr.ues = URIES_IDLE;
757 lwsl_info("%s: %p: keep-alive await new transaction\n", __func__, wsi);
763 * lws_adopt_socket() - adopt foreign socket as if listen socket accepted it
764 * @context: lws context
765 * @accept_fd: fd of already-accepted socket to adopt
767 * Either returns new wsi bound to accept_fd, or closes accept_fd and
768 * returns NULL, having cleaned up any new wsi pieces.
770 * LWS adopts the socket in http serving mode, it's ready to accept an upgrade
771 * to ws or just serve http.
774 LWS_VISIBLE struct lws *
775 lws_adopt_socket(struct lws_context *context, lws_sockfd_type accept_fd)
777 struct lws *new_wsi = lws_create_new_server_wsi(context);
780 compatible_close(accept_fd);
784 lwsl_debug("%s: new wsi %p\n", __func__, new_wsi);
786 new_wsi->sock = accept_fd;
788 /* the transport is accepted... give him time to negotiate */
789 lws_set_timeout(new_wsi, PENDING_TIMEOUT_ESTABLISH_WITH_SERVER,
790 context->timeout_secs);
793 mbed3_tcp_stream_accept(accept_fd, new_wsi);
797 * A new connection was accepted. Give the user a chance to
798 * set properties of the newly created wsi. There's no protocol
799 * selected yet so we issue this to protocols[0]
801 if ((context->protocols[0].callback)(new_wsi,
802 LWS_CALLBACK_SERVER_NEW_CLIENT_INSTANTIATED, NULL, NULL, 0)) {
803 compatible_close(new_wsi->sock);
808 lws_libev_accept(new_wsi, new_wsi->sock);
809 lws_libuv_accept(new_wsi, new_wsi->sock);
811 if (!LWS_SSL_ENABLED(context)) {
812 if (insert_wsi_socket_into_fds(context, new_wsi))
815 new_wsi->mode = LWSCM_SSL_INIT;
816 if (lws_server_socket_service_ssl(new_wsi, accept_fd))
823 lwsl_err("%s: fail\n", __func__);
824 lws_close_free_wsi(new_wsi, LWS_CLOSE_STATUS_NOSTATUS);
830 lws_server_socket_service(struct lws_context *context, struct lws *wsi,
831 struct lws_pollfd *pollfd)
833 struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
834 lws_sockfd_type accept_fd = LWS_SOCK_INVALID;
835 struct allocated_headers *ah;
837 struct sockaddr_in cli_addr;
844 case LWSCM_HTTP_SERVING:
845 case LWSCM_HTTP_SERVING_ACCEPTED:
846 case LWSCM_HTTP2_SERVING:
848 /* handle http headers coming in */
850 /* pending truncated sends have uber priority */
852 if (wsi->trunc_len) {
853 if (!(pollfd->revents & LWS_POLLOUT))
856 if (lws_issue_raw(wsi, wsi->trunc_alloc +
861 * we can't afford to allow input processing to send
862 * something new, so spin around he event loop until
863 * he doesn't have any partials
868 /* any incoming data ready? */
870 if (!(pollfd->revents & pollfd->events & LWS_POLLIN))
873 /* these states imply we MUST have an ah attached */
875 if (wsi->state == LWSS_HTTP ||
876 wsi->state == LWSS_HTTP_ISSUING_FILE ||
877 wsi->state == LWSS_HTTP_HEADERS) {
879 if (lws_header_table_attach(wsi))
884 lwsl_debug("%s: %p: rxpos:%d rxlen:%d\n", __func__, wsi,
885 ah->rxpos, ah->rxlen);
887 /* if nothing in ah rx buffer, get some fresh rx */
888 if (ah->rxpos == ah->rxlen) {
889 ah->rxlen = lws_ssl_capable_read(wsi, ah->rx,
892 lwsl_debug("%s: wsi %p, ah->rxlen = %d\r\n",
893 __func__, wsi, ah->rxlen);
896 lwsl_info("%s: read 0 len\n", __func__);
897 /* lwsl_info(" state=%d\n", wsi->state); */
898 // if (!wsi->hdr_parsing_completed)
899 // lws_header_table_detach(wsi);
901 case LWS_SSL_CAPABLE_ERROR:
903 case LWS_SSL_CAPABLE_MORE_SERVICE:
904 ah->rxlen = ah->rxpos = 0;
908 assert(ah->rxpos != ah->rxlen && ah->rxlen);
909 /* just ignore incoming if waiting for close */
910 if (wsi->state != LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE) {
911 n = lws_read(wsi, ah->rx + ah->rxpos,
912 ah->rxlen - ah->rxpos);
913 if (n < 0) /* we closed wsi */
916 if ( wsi->u.hdr.ah->rxlen)
917 wsi->u.hdr.ah->rxpos += n;
919 if (wsi->u.hdr.ah->rxpos == wsi->u.hdr.ah->rxlen &&
920 (wsi->mode != LWSCM_HTTP_SERVING &&
921 wsi->mode != LWSCM_HTTP_SERVING_ACCEPTED &&
922 wsi->mode != LWSCM_HTTP2_SERVING))
923 lws_header_table_detach(wsi);
931 len = lws_ssl_capable_read(wsi, pt->serv_buf,
932 LWS_MAX_SOCKET_IO_BUF);
933 lwsl_debug("%s: wsi %p read %d\r\n", __func__, wsi, len);
936 lwsl_info("%s: read 0 len\n", __func__);
937 /* lwsl_info(" state=%d\n", wsi->state); */
938 // if (!wsi->hdr_parsing_completed)
939 // lws_header_table_detach(wsi);
941 case LWS_SSL_CAPABLE_ERROR:
943 case LWS_SSL_CAPABLE_MORE_SERVICE:
947 /* just ignore incoming if waiting for close */
948 if (wsi->state != LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE) {
950 * hm this may want to send
951 * (via HTTP callback for example)
953 n = lws_read(wsi, pt->serv_buf, len);
954 if (n < 0) /* we closed wsi */
956 /* hum he may have used up the
957 * writability above */
962 /* this handles POLLOUT for http serving fragments */
964 if (!(pollfd->revents & LWS_POLLOUT))
968 if (lws_change_pollfd(wsi, LWS_POLLOUT, 0)) {
969 lwsl_notice("%s a\n", __func__);
973 if (wsi->state != LWSS_HTTP_ISSUING_FILE) {
974 n = user_callback_handle_rxflow(wsi->protocol->callback,
975 wsi, LWS_CALLBACK_HTTP_WRITEABLE,
976 wsi->user_space, NULL, 0);
978 lwsl_info("writeable_fail\n");
984 /* >0 == completion, <0 == error */
985 n = lws_serve_http_file_fragment(wsi);
986 if (n < 0 || (n > 0 && lws_http_transaction_completed(wsi))) {
987 lwsl_info("completed\n");
992 case LWSCM_SERVER_LISTENER:
995 /* pollin means a client has connected to us then */
998 if (!(pollfd->revents & LWS_POLLIN) || !(pollfd->events & LWS_POLLIN))
1001 /* listen socket got an unencrypted connection... */
1003 clilen = sizeof(cli_addr);
1004 lws_latency_pre(context, wsi);
1005 accept_fd = accept(pollfd->fd, (struct sockaddr *)&cli_addr,
1007 lws_latency(context, wsi, "listener accept", accept_fd,
1009 if (accept_fd < 0) {
1010 if (LWS_ERRNO == LWS_EAGAIN ||
1011 LWS_ERRNO == LWS_EWOULDBLOCK) {
1012 lwsl_err("accept asks to try again\n");
1015 lwsl_err("ERROR on accept: %s\n", strerror(LWS_ERRNO));
1019 lws_plat_set_socket_options(context, accept_fd);
1021 lwsl_debug("accepted new conn port %u on fd=%d\n",
1022 ntohs(cli_addr.sin_port), accept_fd);
1025 /* not very beautiful... */
1026 accept_fd = (lws_sockfd_type)pollfd;
1029 * look at who we connected to and give user code a chance
1030 * to reject based on client IP. There's no protocol selected
1031 * yet so we issue this to protocols[0]
1033 if ((context->protocols[0].callback)(wsi,
1034 LWS_CALLBACK_FILTER_NETWORK_CONNECTION,
1035 NULL, (void *)(long)accept_fd, 0)) {
1036 lwsl_debug("Callback denied network connection\n");
1037 compatible_close(accept_fd);
1041 if (!lws_adopt_socket(context, accept_fd))
1042 /* already closed cleanly as necessary */
1046 } while (pt->fds_count < context->fd_limit_per_thread - 1 &&
1047 lws_poll_listen_fd(&pt->fds[wsi->position_in_fds_table]) > 0);
1055 if (!lws_server_socket_service_ssl(wsi, accept_fd))
1059 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
1065 * lws_serve_http_file() - Send a file back to the client using http
1066 * @wsi: Websocket instance (available from user callback)
1067 * @file: The file to issue over http
1068 * @content_type: The http content type, eg, text/html
1069 * @other_headers: NULL or pointer to header string
1070 * @other_headers_len: length of the other headers if non-NULL
1072 * This function is intended to be called from the callback in response
1073 * to http requests from the client. It allows the callback to issue
1074 * local files down the http link in a single step.
1076 * Returning <0 indicates error and the wsi should be closed. Returning
1077 * >0 indicates the file was completely sent and
1078 * lws_http_transaction_completed() called on the wsi (and close if != 0)
1079 * ==0 indicates the file transfer is started and needs more service later,
1080 * the wsi should be left alone.
1084 lws_serve_http_file(struct lws *wsi, const char *file, const char *content_type,
1085 const char *other_headers, int other_headers_len)
1087 struct lws_context *context = lws_get_context(wsi);
1088 struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
1089 unsigned char *response = pt->serv_buf + LWS_PRE;
1090 unsigned char *p = response;
1091 unsigned char *end = p + LWS_MAX_SOCKET_IO_BUF - LWS_PRE;
1094 wsi->u.http.fd = lws_plat_file_open(wsi, file, &wsi->u.http.filelen,
1097 if (wsi->u.http.fd == LWS_INVALID_FILE) {
1098 lwsl_err("Unable to open '%s'\n", file);
1099 lws_return_http_status(wsi, HTTP_STATUS_NOT_FOUND, NULL);
1104 if (lws_add_http_header_status(wsi, 200, &p, end))
1106 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_SERVER,
1107 (unsigned char *)"libwebsockets", 13,
1110 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE,
1111 (unsigned char *)content_type,
1112 strlen(content_type), &p, end))
1114 if (lws_add_http_header_content_length(wsi, wsi->u.http.filelen, &p, end))
1117 if (other_headers) {
1118 if ((end - p) < other_headers_len)
1120 memcpy(p, other_headers, other_headers_len);
1121 p += other_headers_len;
1124 if (lws_finalize_http_header(wsi, &p, end))
1127 ret = lws_write(wsi, response, p - response, LWS_WRITE_HTTP_HEADERS);
1128 if (ret != (p - response)) {
1129 lwsl_err("_write returned %d from %d\n", ret, (p - response));
1133 wsi->u.http.filepos = 0;
1134 wsi->state = LWSS_HTTP_ISSUING_FILE;
1136 return lws_serve_http_file_fragment(wsi);
1140 lws_interpret_incoming_packet(struct lws *wsi, unsigned char **buf, size_t len)
1144 lwsl_parser("%s: received %d byte packet\n", __func__, (int)len);
1146 lwsl_hexdump(*buf, len);
1149 /* let the rx protocol state machine have as much as it needs */
1153 * we were accepting input but now we stopped doing so
1155 if (!(wsi->rxflow_change_to & LWS_RXFLOW_ALLOW)) {
1156 lws_rxflow_cache(wsi, *buf, 0, len);
1157 lwsl_parser("%s: cached %d\n", __func__, len);
1161 if (wsi->u.ws.rx_draining_ext) {
1162 m = lws_rx_sm(wsi, 0);
1168 /* account for what we're using in rxflow buffer */
1169 if (wsi->rxflow_buffer)
1172 /* process the byte */
1173 m = lws_rx_sm(wsi, *(*buf)++);
1179 lwsl_parser("%s: exit with %d unused\n", __func__, (int)len);
1185 lws_server_get_canonical_hostname(struct lws_context *context,
1186 struct lws_context_creation_info *info)
1188 if (info->options & LWS_SERVER_OPTION_SKIP_SERVER_CANONICAL_NAME)
1191 /* find canonical hostname */
1192 gethostname((char *)context->canonical_hostname,
1193 sizeof(context->canonical_hostname) - 1);
1195 lwsl_notice(" canonical_hostname = %s\n", context->canonical_hostname);