lwsws cgi integration
[platform/upstream/libwebsockets.git] / lib / server.c
1 /*
2  * libwebsockets - small server side websockets and web server implementation
3  *
4  * Copyright (C) 2010-2016 Andy Green <andy@warmcat.com>
5  *
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.
10  *
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.
15  *
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,
19  *  MA  02110-1301  USA
20  */
21
22
23 #include "private-libwebsockets.h"
24
25 int
26 lws_context_init_server(struct lws_context_creation_info *info,
27                         struct lws_vhost *vhost)
28 {
29 #ifdef LWS_POSIX
30         int n, opt = 1, limit = 1;
31 #endif
32         lws_sockfd_type sockfd;
33         struct lws_vhost *vh;
34         struct lws *wsi;
35         int m = 0;
36
37         /* set up our external listening socket we serve on */
38
39         if (info->port == CONTEXT_PORT_NO_LISTEN)
40                 return 0;
41
42         vh = vhost->context->vhost_list;
43         while (vh) {
44                 if (vh->listen_port == info->port) {
45                         if ((!info->iface && !vh->iface) ||
46                             (info->iface && vh->iface &&
47                             !strcmp(info->iface, vh->iface))) {
48                                 vhost->listen_port = info->port;
49                                 vhost->iface = info->iface;
50                                 lwsl_notice(" using listen skt from vhost %s\n",
51                                             vh->name);
52                                 return 0;
53                         }
54                 }
55                 vh = vh->vhost_next;
56         }
57
58 #if LWS_POSIX
59 #if defined(__linux__)
60         limit = vhost->context->count_threads;
61 #endif
62
63         for (m = 0; m < limit; m++) {
64 #ifdef LWS_USE_IPV6
65         if (LWS_IPV6_ENABLED(context))
66                 sockfd = socket(AF_INET6, SOCK_STREAM, 0);
67         else
68 #endif
69                 sockfd = socket(AF_INET, SOCK_STREAM, 0);
70
71         if (sockfd == -1) {
72 #else
73         sockfd = mbed3_create_tcp_stream_socket();
74         if (!lws_sockfd_valid(sockfd)) {
75 #endif
76                 lwsl_err("ERROR opening socket\n");
77                 return 1;
78         }
79
80 #if LWS_POSIX
81         /*
82          * allow us to restart even if old sockets in TIME_WAIT
83          */
84         if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
85                        (const void *)&opt, sizeof(opt)) < 0) {
86                 compatible_close(sockfd);
87                 return 1;
88         }
89 #if defined(__linux__) && defined(SO_REUSEPORT) && LWS_MAX_SMP > 1
90         if (vhost->context->count_threads > 1)
91                 if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEPORT,
92                                 (const void *)&opt, sizeof(opt)) < 0) {
93                         compatible_close(sockfd);
94                         return 1;
95                 }
96 #endif
97 #endif
98         lws_plat_set_socket_options(vhost, sockfd);
99
100 #if LWS_POSIX
101         n = lws_socket_bind(vhost->context, sockfd, info->port, info->iface);
102         if (n < 0)
103                 goto bail;
104         info->port = n;
105 #endif
106         vhost->listen_port = info->port;
107         vhost->iface = info->iface;
108
109         wsi = lws_zalloc(sizeof(struct lws));
110         if (wsi == NULL) {
111                 lwsl_err("Out of mem\n");
112                 goto bail;
113         }
114         wsi->context = vhost->context;
115         wsi->sock = sockfd;
116         wsi->mode = LWSCM_SERVER_LISTENER;
117         wsi->protocol = vhost->protocols;
118         wsi->tsi = m;
119         wsi->vhost = vhost;
120         wsi->listener = 1;
121
122         vhost->context->pt[m].wsi_listening = wsi;
123         if (insert_wsi_socket_into_fds(vhost->context, wsi))
124                 goto bail;
125
126         vhost->context->count_wsi_allocated++;
127         vhost->lserv_wsi = wsi;
128
129 #if LWS_POSIX
130         listen(wsi->sock, LWS_SOMAXCONN);
131         } /* for each thread able to independently lister */
132 #else
133         mbed3_tcp_stream_bind(wsi->sock, info->port, wsi);
134 #endif
135         if (!lws_check_opt(info->options, LWS_SERVER_OPTION_EXPLICIT_VHOSTS))
136                 lwsl_notice(" Listening on port %d\n", info->port);
137
138         return 0;
139
140 bail:
141         compatible_close(sockfd);
142
143         return 1;
144 }
145
146 int
147 _lws_server_listen_accept_flow_control(struct lws *twsi, int on)
148 {
149         struct lws_context_per_thread *pt = &twsi->context->pt[(int)twsi->tsi];
150         struct lws *wsi = pt->wsi_listening;
151         int n;
152
153         if (!wsi || twsi->context->being_destroyed)
154                 return 0;
155
156         lwsl_debug("%s: Thr %d: LISTEN wsi %p: state %d\n",
157                    __func__, twsi->tsi, (void *)wsi, on);
158
159         if (on)
160                 n = lws_change_pollfd(wsi, 0, LWS_POLLIN);
161         else
162                 n = lws_change_pollfd(wsi, LWS_POLLIN, 0);
163
164         return n;
165 }
166
167 struct lws_vhost *
168 lws_select_vhost(struct lws_context *context, int port, const char *servername)
169 {
170         struct lws_vhost *vhost = context->vhost_list;
171
172         while (vhost) {
173                 if (port == vhost->listen_port &&
174                     !strcmp(vhost->name, servername)) {
175                         lwsl_info("SNI: Found: %s\n", servername);
176                         return vhost;
177                 }
178                 vhost = vhost->vhost_next;
179         }
180
181         return NULL;
182 }
183
184 static const char * get_mimetype(const char *file)
185 {
186         int n = strlen(file);
187
188         if (n < 5)
189                 return NULL;
190
191         if (!strcmp(&file[n - 4], ".ico"))
192                 return "image/x-icon";
193
194         if (!strcmp(&file[n - 4], ".gif"))
195                 return "image/gif";
196
197         if (!strcmp(&file[n - 3], ".js"))
198                 return "text/javascript";
199
200         if (!strcmp(&file[n - 4], ".png"))
201                 return "image/png";
202
203         if (!strcmp(&file[n - 4], ".jpg"))
204                 return "image/jpeg";
205
206         if (!strcmp(&file[n - 5], ".html"))
207                 return "text/html";
208
209         if (!strcmp(&file[n - 4], ".css"))
210                 return "text/css";
211
212         if (!strcmp(&file[n - 4], ".ttf"))
213                 return "application/x-font-ttf";
214
215         return NULL;
216 }
217
218 int lws_http_serve(struct lws *wsi, char *uri, const char *origin)
219 {
220         const char *mimetype;
221         struct stat st;
222         char path[256], sym[256];
223         int n, spin = 0;
224
225         lwsl_notice("%s: %s %s\n", __func__, uri, origin);
226         snprintf(path, sizeof(path) - 1, "%s/%s", origin, uri);
227
228         do {
229                 spin++;
230
231                 if (stat(path, &st)) {
232                         lwsl_err("unable to stat %s\n", path);
233                         goto bail;
234                 }
235
236                 lwsl_debug(" %s mode %d\n", path, S_IFMT & st.st_mode);
237
238                 if ((S_IFMT & st.st_mode) == S_IFLNK) {
239                         if (readlink(path, sym, sizeof(sym))) {
240                                 lwsl_err("Failed to read link %s\n", path);
241                                 goto bail;
242                         }
243                         lwsl_debug("symlink %s -> %s\n", path, sym);
244                         snprintf(path, sizeof(path) - 1, "%s", sym);
245                 }
246
247                 if ((S_IFMT & st.st_mode) == S_IFDIR) {
248                         lwsl_debug("default filename append to dir\n");
249                         snprintf(path, sizeof(path) - 1, "%s/%s/index.html",
250                                  origin, uri);
251                 }
252
253         } while ((S_IFMT & st.st_mode) != S_IFREG && spin < 5);
254
255         if (spin == 5) {
256                 lwsl_err("symlink loop %s \n", path);
257         }
258
259         mimetype = get_mimetype(path);
260         if (!mimetype) {
261                 lwsl_err("unknown mimetype for %s", path);
262                 goto bail;
263         }
264
265         n = lws_serve_http_file(wsi, path, mimetype, NULL, 0);
266
267         if (n < 0 || ((n > 0) && lws_http_transaction_completed(wsi)))
268                 return -1; /* error or can't reuse connection: close the socket */
269
270         return 0;
271 bail:
272         lws_return_http_status(wsi, HTTP_STATUS_NOT_FOUND, NULL);
273
274         return -1;
275 }
276
277 int
278 lws_http_action(struct lws *wsi)
279 {
280         struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
281         enum http_connection_type connection_type;
282         enum http_version request_version;
283         char content_length_str[32];
284         struct lws_http_mount *hm, *hit = NULL;
285         unsigned int n, count = 0;
286         char http_version_str[10];
287         char http_conn_str[20];
288         int http_version_len;
289         char *uri_ptr = NULL;
290         int uri_len = 0, best = 0;
291
292         static const unsigned char methods[] = {
293                 WSI_TOKEN_GET_URI,
294                 WSI_TOKEN_POST_URI,
295                 WSI_TOKEN_OPTIONS_URI,
296                 WSI_TOKEN_PUT_URI,
297                 WSI_TOKEN_PATCH_URI,
298                 WSI_TOKEN_DELETE_URI,
299 #ifdef LWS_USE_HTTP2
300                 WSI_TOKEN_HTTP_COLON_PATH,
301 #endif
302         };
303 #ifdef _DEBUG
304         static const char * const method_names[] = {
305                 "GET", "POST", "OPTIONS", "PUT", "PATCH", "DELETE",
306 #ifdef LWS_USE_HTTP2
307                 ":path",
308 #endif
309         };
310 #endif
311
312         /* it's not websocket.... shall we accept it as http? */
313
314         for (n = 0; n < ARRAY_SIZE(methods); n++)
315                 if (lws_hdr_total_length(wsi, methods[n]))
316                         count++;
317         if (!count) {
318                 lwsl_warn("Missing URI in HTTP request\n");
319                 goto bail_nuke_ah;
320         }
321
322         if (count != 1) {
323                 lwsl_warn("multiple methods?\n");
324                 goto bail_nuke_ah;
325         }
326
327         if (lws_ensure_user_space(wsi))
328                 goto bail_nuke_ah;
329
330         for (n = 0; n < ARRAY_SIZE(methods); n++)
331                 if (lws_hdr_total_length(wsi, methods[n])) {
332                         uri_ptr = lws_hdr_simple_ptr(wsi, methods[n]);
333                         uri_len = lws_hdr_total_length(wsi, methods[n]);
334                         lwsl_info("Method: %s request for '%s'\n",
335                                         method_names[n], uri_ptr);
336                         break;
337                 }
338
339         /* we insist on absolute paths */
340
341         if (uri_ptr[0] != '/') {
342                 lws_return_http_status(wsi, HTTP_STATUS_FORBIDDEN, NULL);
343
344                 goto bail_nuke_ah;
345         }
346
347         /* HTTP header had a content length? */
348
349         wsi->u.http.content_length = 0;
350         if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI) ||
351                 lws_hdr_total_length(wsi, WSI_TOKEN_PATCH_URI) ||
352                 lws_hdr_total_length(wsi, WSI_TOKEN_PUT_URI))
353                 wsi->u.http.content_length = 100 * 1024 * 1024;
354
355         if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH)) {
356                 lws_hdr_copy(wsi, content_length_str,
357                              sizeof(content_length_str) - 1,
358                              WSI_TOKEN_HTTP_CONTENT_LENGTH);
359                 wsi->u.http.content_length = atoi(content_length_str);
360         }
361
362         /* http_version? Default to 1.0, override with token: */
363         request_version = HTTP_VERSION_1_0;
364
365         /* Works for single digit HTTP versions. : */
366         http_version_len = lws_hdr_total_length(wsi, WSI_TOKEN_HTTP);
367         if (http_version_len > 7) {
368                 lws_hdr_copy(wsi, http_version_str,
369                                 sizeof(http_version_str) - 1, WSI_TOKEN_HTTP);
370                 if (http_version_str[5] == '1' && http_version_str[7] == '1')
371                         request_version = HTTP_VERSION_1_1;
372         }
373         wsi->u.http.request_version = request_version;
374
375         /* HTTP/1.1 defaults to "keep-alive", 1.0 to "close" */
376         if (request_version == HTTP_VERSION_1_1)
377                 connection_type = HTTP_CONNECTION_KEEP_ALIVE;
378         else
379                 connection_type = HTTP_CONNECTION_CLOSE;
380
381         /* Override default if http "Connection:" header: */
382         if (lws_hdr_total_length(wsi, WSI_TOKEN_CONNECTION)) {
383                 lws_hdr_copy(wsi, http_conn_str, sizeof(http_conn_str) - 1,
384                              WSI_TOKEN_CONNECTION);
385                 http_conn_str[sizeof(http_conn_str) - 1] = '\0';
386                 if (!strcasecmp(http_conn_str, "keep-alive"))
387                         connection_type = HTTP_CONNECTION_KEEP_ALIVE;
388                 else
389                         if (!strcasecmp(http_conn_str, "close"))
390                                 connection_type = HTTP_CONNECTION_CLOSE;
391         }
392         wsi->u.http.connection_type = connection_type;
393
394         n = wsi->protocol->callback(wsi, LWS_CALLBACK_FILTER_HTTP_CONNECTION,
395                                     wsi->user_space, uri_ptr, uri_len);
396         if (n) {
397                 lwsl_info("LWS_CALLBACK_HTTP closing\n");
398
399                 return 1;
400         }
401         /*
402          * if there is content supposed to be coming,
403          * put a timeout on it having arrived
404          */
405         lws_set_timeout(wsi, PENDING_TIMEOUT_HTTP_CONTENT,
406                         wsi->context->timeout_secs);
407 #ifdef LWS_OPENSSL_SUPPORT
408         if (wsi->redirect_to_https) {
409                 /*
410                  * we accepted http:// only so we could redirect to
411                  * https://, so issue the redirect.  Create the redirection
412                  * URI from the host: header and ignore the path part
413                  */
414                 unsigned char *start = pt->serv_buf + LWS_PRE, *p = start,
415                               *end = p + 512;
416
417                 if (!lws_hdr_total_length(wsi, WSI_TOKEN_HOST))
418                         goto bail_nuke_ah;
419                 if (lws_add_http_header_status(wsi, 301, &p, end))
420                         goto bail_nuke_ah;
421                 n = sprintf((char *)end, "https://%s/",
422                             lws_hdr_simple_ptr(wsi, WSI_TOKEN_HOST));
423                 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_LOCATION,
424                                 end, n, &p, end))
425                         goto bail_nuke_ah;
426                 if (lws_finalize_http_header(wsi, &p, end))
427                         goto bail_nuke_ah;
428                 n = lws_write(wsi, start, p - start, LWS_WRITE_HTTP_HEADERS);
429                 if ((int)n < 0)
430                         goto bail_nuke_ah;
431
432                 return lws_http_transaction_completed(wsi);
433         }
434 #endif
435
436         /* can we serve it from the mount list? */
437
438         hm = wsi->vhost->mount_list;
439         while (hm) {
440                 if (uri_len >= hm->mountpoint_len &&
441                     !strncmp(uri_ptr, hm->mountpoint, hm->mountpoint_len) &&
442                     (uri_ptr[hm->mountpoint_len] == '\0' ||
443                      uri_ptr[hm->mountpoint_len] == '/' ||
444                      hm->mountpoint_len == 1)
445                     ) {
446                         if (hm->mountpoint_len > best) {
447                                 best = hm->mountpoint_len;
448                                 hit = hm;
449                         }
450                 }
451                 hm = hm->mount_next;
452         }
453         if (hit) {
454                 char *s = uri_ptr + hit->mountpoint_len;
455
456                 lwsl_debug("*** hit %d %d %s\n", hit->mountpoint_len,
457                            hit->origin_protocol , hit->origin);
458
459                 /*
460                  * if we have a mountpoint like https://xxx.com/yyy
461                  * there is an implied / at the end for our purposes since
462                  * we can only mount on a "directory".
463                  *
464                  * But if we just go with that, the browser cannot understand
465                  * that he is actually looking down one "directory level", so
466                  * even though we give him /yyy/abc.html he acts like the
467                  * current directory level is /.  So relative urls like "x.png"
468                  * wrongly look outside the mountpoint.
469                  *
470                  * Therefore if we didn't come in on a url with an explicit
471                  * / at the end, we must redirect to add it so the browser
472                  * understands he is one "directory level" down.
473                  */
474                 if ((hit->mountpoint_len > 1 || (hit->origin_protocol & 4)) &&
475                     (*s != '/' || (hit->origin_protocol & 4))) {
476                         unsigned char *start = pt->serv_buf + LWS_PRE,
477                                               *p = start, *end = p + 512;
478                         static const char *oprot[] = {
479                                 "http://", "https://"
480                         };
481
482                         if (!lws_hdr_total_length(wsi, WSI_TOKEN_HOST))
483                                 goto bail_nuke_ah;
484                         if (lws_add_http_header_status(wsi, 301, &p, end))
485                                 goto bail_nuke_ah;
486
487                         lwsl_debug("**** %s", hit->origin);
488
489                         /* > at start indicates deal with by redirect */
490                         if (hit->origin_protocol & 4)
491                                 n = snprintf((char *)end, 256, "%s%s",
492                                             oprot[hit->origin_protocol & 1],
493                                             hit->origin);
494                         else
495                                 n = snprintf((char *)end, 256,
496                                     "https://%s/%s/",
497                                     lws_hdr_simple_ptr(wsi, WSI_TOKEN_HOST),
498                                     uri_ptr);
499                         if (lws_add_http_header_by_token(wsi,
500                                         WSI_TOKEN_HTTP_LOCATION,
501                                         end, n, &p, end))
502                                 goto bail_nuke_ah;
503                         if (lws_finalize_http_header(wsi, &p, end))
504                                 goto bail_nuke_ah;
505                         n = lws_write(wsi, start, p - start,
506                                         LWS_WRITE_HTTP_HEADERS);
507                         if ((int)n < 0)
508                                 goto bail_nuke_ah;
509
510                         return lws_http_transaction_completed(wsi);
511                 }
512
513 #ifdef LWS_WITH_CGI
514                 /* did we hit something with a cgi:// origin? */
515                 if (hit->origin_protocol == LWSMPRO_CGI) {
516                         const char *cmd[] = {
517                                 NULL, /* replace with cgi path */
518                                 NULL
519                         };
520                         unsigned char *p, *end, buffer[256];
521
522                         lwsl_debug("%s: cgi\n", __func__);
523                         cmd[0] = hit->origin;
524                         n = lws_cgi(wsi, cmd, hit->mountpoint_len, 5,
525                                     hit->cgienv);
526                         if (n) {
527                                 lwsl_err("%s: cgi failed\n");
528                                 return -1;
529                         }
530                         p = buffer + LWS_PRE;
531                         end = p + sizeof(buffer) - LWS_PRE;
532
533                         if (lws_add_http_header_status(wsi, 200, &p, end))
534                                 return 1;
535                         if (lws_add_http_header_by_token(wsi, WSI_TOKEN_CONNECTION,
536                                         (unsigned char *)"close", 5, &p, end))
537                                 return 1;
538                         n = lws_write(wsi, buffer + LWS_PRE,
539                                       p - (buffer + LWS_PRE),
540                                       LWS_WRITE_HTTP_HEADERS);
541
542                         return 0;
543                 }
544 #endif
545
546                 n = strlen(s);
547                 if (s[0] == '\0' || (n == 1 && s[n - 1] == '/'))
548                         s = (char *)hit->def;
549
550                 if (!s)
551                         s = "index.html";
552
553
554
555                 n = lws_http_serve(wsi, s, hit->origin);
556         } else
557                 n = wsi->protocol->callback(wsi, LWS_CALLBACK_HTTP,
558                                     wsi->user_space, uri_ptr, uri_len);
559
560         if (n) {
561                 lwsl_info("LWS_CALLBACK_HTTP closing\n");
562
563                 return 1;
564         }
565
566         /*
567          * If we're not issuing a file, check for content_length or
568          * HTTP keep-alive. No keep-alive header allocation for
569          * ISSUING_FILE, as this uses HTTP/1.0.
570          *
571          * In any case, return 0 and let lws_read decide how to
572          * proceed based on state
573          */
574         if (wsi->state != LWSS_HTTP_ISSUING_FILE)
575                 /* Prepare to read body if we have a content length: */
576                 if (wsi->u.http.content_length > 0)
577                         wsi->state = LWSS_HTTP_BODY;
578
579         return 0;
580
581 bail_nuke_ah:
582         /* we're closing, losing some rx is OK */
583         wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
584         lws_header_table_detach(wsi, 1);
585
586         return 1;
587 }
588
589
590 int
591 lws_handshake_server(struct lws *wsi, unsigned char **buf, size_t len)
592 {
593         struct lws_context *context = lws_get_context(wsi);
594         struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
595         struct _lws_header_related hdr;
596         struct allocated_headers *ah;
597         int protocol_len, n, hit;
598         char protocol_list[128];
599         char protocol_name[32];
600         char *p;
601
602         assert(len < 10000000);
603         assert(wsi->u.hdr.ah);
604
605         while (len--) {
606                 wsi->more_rx_waiting = !!len;
607
608                 assert(wsi->mode == LWSCM_HTTP_SERVING);
609
610                 if (lws_parse(wsi, *(*buf)++)) {
611                         lwsl_info("lws_parse failed\n");
612                         goto bail_nuke_ah;
613                 }
614
615                 if (wsi->u.hdr.parser_state != WSI_PARSING_COMPLETE)
616                         continue;
617
618                 lwsl_parser("%s: lws_parse sees parsing complete\n", __func__);
619                 lwsl_debug("%s: wsi->more_rx_waiting=%d\n", __func__,
620                                 wsi->more_rx_waiting);
621
622                 wsi->mode = LWSCM_PRE_WS_SERVING_ACCEPT;
623                 lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
624
625                 /* is this websocket protocol or normal http 1.0? */
626
627                 if (lws_hdr_total_length(wsi, WSI_TOKEN_UPGRADE)) {
628                         if (!strcasecmp(lws_hdr_simple_ptr(wsi, WSI_TOKEN_UPGRADE),
629                                         "websocket")) {
630                                 lwsl_info("Upgrade to ws\n");
631                                 goto upgrade_ws;
632                         }
633 #ifdef LWS_USE_HTTP2
634                         if (!strcasecmp(lws_hdr_simple_ptr(wsi, WSI_TOKEN_UPGRADE),
635                                         "h2c-14")) {
636                                 lwsl_info("Upgrade to h2c-14\n");
637                                 goto upgrade_h2c;
638                         }
639 #endif
640                         lwsl_err("Unknown upgrade\n");
641                         /* dunno what he wanted to upgrade to */
642                         goto bail_nuke_ah;
643                 }
644
645                 /* no upgrade ack... he remained as HTTP */
646
647                 lwsl_info("No upgrade\n");
648                 ah = wsi->u.hdr.ah;
649
650                 /* select vhost */
651
652                 if (lws_hdr_total_length(wsi, WSI_TOKEN_HOST)) {
653                         struct lws_vhost *vhost = lws_select_vhost(
654                                 context, wsi->vhost->listen_port,
655                                 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HOST));
656
657                         if (vhost)
658                                 wsi->vhost = vhost;
659                 }
660
661                 lws_union_transition(wsi, LWSCM_HTTP_SERVING_ACCEPTED);
662                 wsi->state = LWSS_HTTP;
663                 wsi->u.http.fd = LWS_INVALID_FILE;
664
665                 /* expose it at the same offset as u.hdr */
666                 wsi->u.http.ah = ah;
667                 lwsl_debug("%s: wsi %p: ah %p\n", __func__, (void *)wsi,
668                            (void *)wsi->u.hdr.ah);
669
670                 n = lws_http_action(wsi);
671
672                 return n;
673
674 #ifdef LWS_USE_HTTP2
675 upgrade_h2c:
676                 if (!lws_hdr_total_length(wsi, WSI_TOKEN_HTTP2_SETTINGS)) {
677                         lwsl_err("missing http2_settings\n");
678                         goto bail_nuke_ah;
679                 }
680
681                 lwsl_err("h2c upgrade...\n");
682
683                 p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP2_SETTINGS);
684                 /* convert the peer's HTTP-Settings */
685                 n = lws_b64_decode_string(p, protocol_list,
686                                           sizeof(protocol_list));
687                 if (n < 0) {
688                         lwsl_parser("HTTP2_SETTINGS too long\n");
689                         return 1;
690                 }
691
692                 /* adopt the header info */
693
694                 ah = wsi->u.hdr.ah;
695
696                 lws_union_transition(wsi, LWSCM_HTTP2_SERVING);
697
698                 /* http2 union member has http union struct at start */
699                 wsi->u.http.ah = ah;
700
701                 lws_http2_init(&wsi->u.http2.peer_settings);
702                 lws_http2_init(&wsi->u.http2.my_settings);
703
704                 /* HTTP2 union */
705
706                 lws_http2_interpret_settings_payload(&wsi->u.http2.peer_settings,
707                                 (unsigned char *)protocol_list, n);
708
709                 strcpy(protocol_list,
710                        "HTTP/1.1 101 Switching Protocols\x0d\x0a"
711                       "Connection: Upgrade\x0d\x0a"
712                       "Upgrade: h2c\x0d\x0a\x0d\x0a");
713                 n = lws_issue_raw(wsi, (unsigned char *)protocol_list,
714                                         strlen(protocol_list));
715                 if (n != strlen(protocol_list)) {
716                         lwsl_debug("http2 switch: ERROR writing to socket\n");
717                         return 1;
718                 }
719
720                 wsi->state = LWSS_HTTP2_AWAIT_CLIENT_PREFACE;
721
722                 return 0;
723 #endif
724
725 upgrade_ws:
726                 if (!wsi->protocol)
727                         lwsl_err("NULL protocol at lws_read\n");
728
729                 /*
730                  * It's websocket
731                  *
732                  * Select the first protocol we support from the list
733                  * the client sent us.
734                  *
735                  * Copy it to remove header fragmentation
736                  */
737
738                 if (lws_hdr_copy(wsi, protocol_list, sizeof(protocol_list) - 1,
739                                  WSI_TOKEN_PROTOCOL) < 0) {
740                         lwsl_err("protocol list too long");
741                         goto bail_nuke_ah;
742                 }
743
744                 protocol_len = lws_hdr_total_length(wsi, WSI_TOKEN_PROTOCOL);
745                 protocol_list[protocol_len] = '\0';
746                 p = protocol_list;
747                 hit = 0;
748
749                 while (*p && !hit) {
750                         unsigned int n = 0;
751                         while (n < sizeof(protocol_name) - 1 && *p && *p !=',')
752                                 protocol_name[n++] = *p++;
753                         protocol_name[n] = '\0';
754                         if (*p)
755                                 p++;
756
757                         lwsl_info("checking %s\n", protocol_name);
758
759                         n = 0;
760                         while (wsi->vhost->protocols[n].callback) {
761                                 if (wsi->vhost->protocols[n].name &&
762                                     !strcmp(wsi->vhost->protocols[n].name,
763                                             protocol_name)) {
764                                         lwsl_info("prot match %d\n", n);
765                                         wsi->protocol = &wsi->vhost->protocols[n];
766                                         hit = 1;
767                                         break;
768                                 }
769
770                                 n++;
771                         }
772                 }
773
774                 /* we didn't find a protocol he wanted? */
775
776                 if (!hit) {
777                         if (lws_hdr_simple_ptr(wsi, WSI_TOKEN_PROTOCOL)) {
778                                 lwsl_err("No protocol from \"%s\" supported\n",
779                                          protocol_list);
780                                 goto bail_nuke_ah;
781                         }
782                         /*
783                          * some clients only have one protocol and
784                          * do not sent the protocol list header...
785                          * allow it and match to protocol 0
786                          */
787                         lwsl_info("defaulting to prot 0 handler\n");
788                         wsi->protocol = &wsi->vhost->protocols[0];
789                 }
790
791                 /* allocate wsi->user storage */
792                 if (lws_ensure_user_space(wsi))
793                         goto bail_nuke_ah;
794
795                 /*
796                  * Give the user code a chance to study the request and
797                  * have the opportunity to deny it
798                  */
799
800                 if ((wsi->protocol->callback)(wsi,
801                                 LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION,
802                                 wsi->user_space,
803                               lws_hdr_simple_ptr(wsi, WSI_TOKEN_PROTOCOL), 0)) {
804                         lwsl_warn("User code denied connection\n");
805                         goto bail_nuke_ah;
806                 }
807
808                 /*
809                  * Perform the handshake according to the protocol version the
810                  * client announced
811                  */
812
813                 switch (wsi->ietf_spec_revision) {
814                 case 13:
815                         lwsl_parser("lws_parse calling handshake_04\n");
816                         if (handshake_0405(context, wsi)) {
817                                 lwsl_info("hs0405 has failed the connection\n");
818                                 goto bail_nuke_ah;
819                         }
820                         break;
821
822                 default:
823                         lwsl_warn("Unknown client spec version %d\n",
824                                   wsi->ietf_spec_revision);
825                         goto bail_nuke_ah;
826                 }
827
828                 /* we are upgrading to ws, so http/1.1 and keepalive +
829                  * pipelined header considerations about keeping the ah around
830                  * no longer apply.  However it's common for the first ws
831                  * protocol data to have been coalesced with the browser
832                  * upgrade request and to already be in the ah rx buffer.
833                  */
834
835                 lwsl_info("%s: %p: inheriting ah in ws mode (rxpos:%d, rxlen:%d)\n",
836                           __func__, wsi, wsi->u.hdr.ah->rxpos,
837                           wsi->u.hdr.ah->rxlen);
838                 lws_pt_lock(pt);
839                 hdr = wsi->u.hdr;
840
841                 lws_union_transition(wsi, LWSCM_WS_SERVING);
842                 /*
843                  * first service is WS mode will notice this, use the RX and
844                  * then detach the ah (caution: we are not in u.hdr union
845                  * mode any more then... ah_temp member is at start the same
846                  * though)
847                  *
848                  * Because rxpos/rxlen shows something in the ah, we will get
849                  * service guaranteed next time around the event loop
850                  *
851                  * All union members begin with hdr, so we can use it even
852                  * though we transitioned to ws union mode (the ah detach
853                  * code uses it anyway).
854                  */
855                 wsi->u.hdr = hdr;
856                 lws_pt_unlock(pt);
857
858                 /*
859                  * create the frame buffer for this connection according to the
860                  * size mentioned in the protocol definition.  If 0 there, use
861                  * a big default for compatibility
862                  */
863
864                 n = wsi->protocol->rx_buffer_size;
865                 if (!n)
866                         n = LWS_MAX_SOCKET_IO_BUF;
867                 n += LWS_PRE;
868                 wsi->u.ws.rx_ubuf = lws_malloc(n + 4 /* 0x0000ffff zlib */);
869                 if (!wsi->u.ws.rx_ubuf) {
870                         lwsl_err("Out of Mem allocating rx buffer %d\n", n);
871                         return 1;
872                 }
873                 wsi->u.ws.rx_ubuf_alloc = n;
874                 lwsl_info("Allocating RX buffer %d\n", n);
875 #if LWS_POSIX
876                 if (setsockopt(wsi->sock, SOL_SOCKET, SO_SNDBUF,
877                                (const char *)&n, sizeof n)) {
878                         lwsl_warn("Failed to set SNDBUF to %d", n);
879                         return 1;
880                 }
881 #endif
882                 lwsl_parser("accepted v%02d connection\n",
883                             wsi->ietf_spec_revision);
884
885                 return 0;
886         } /* while all chars are handled */
887
888         return 0;
889
890 bail_nuke_ah:
891         /* drop the header info */
892         /* we're closing, losing some rx is OK */
893         wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
894         lws_header_table_detach(wsi, 1);
895
896         return 1;
897 }
898
899 static int
900 lws_get_idlest_tsi(struct lws_context *context)
901 {
902         unsigned int lowest = ~0;
903         int n = 0, hit = -1;
904
905         for (; n < context->count_threads; n++) {
906                 if ((unsigned int)context->pt[n].fds_count !=
907                     context->fd_limit_per_thread - 1 &&
908                     (unsigned int)context->pt[n].fds_count < lowest) {
909                         lowest = context->pt[n].fds_count;
910                         hit = n;
911                 }
912         }
913
914         return hit;
915 }
916
917 struct lws *
918 lws_create_new_server_wsi(struct lws_vhost *vhost)
919 {
920         struct lws *new_wsi;
921         int n = lws_get_idlest_tsi(vhost->context);
922
923         if (n < 0) {
924                 lwsl_err("no space for new conn\n");
925                 return NULL;
926         }
927
928         new_wsi = lws_zalloc(sizeof(struct lws));
929         if (new_wsi == NULL) {
930                 lwsl_err("Out of memory for new connection\n");
931                 return NULL;
932         }
933
934         new_wsi->tsi = n;
935         lwsl_info("Accepted %p to tsi %d\n", new_wsi, new_wsi->tsi);
936
937         new_wsi->vhost = vhost;
938         new_wsi->context = vhost->context;
939         new_wsi->pending_timeout = NO_PENDING_TIMEOUT;
940         new_wsi->rxflow_change_to = LWS_RXFLOW_ALLOW;
941
942         /* intialize the instance struct */
943
944         new_wsi->state = LWSS_HTTP;
945         new_wsi->mode = LWSCM_HTTP_SERVING;
946         new_wsi->hdr_parsing_completed = 0;
947
948 #ifdef LWS_OPENSSL_SUPPORT
949         new_wsi->use_ssl = LWS_SSL_ENABLED(vhost);
950 #endif
951
952         /*
953          * these can only be set once the protocol is known
954          * we set an unestablished connection's protocol pointer
955          * to the start of the supported list, so it can look
956          * for matching ones during the handshake
957          */
958         new_wsi->protocol = vhost->protocols;
959         new_wsi->user_space = NULL;
960         new_wsi->ietf_spec_revision = 0;
961         new_wsi->sock = LWS_SOCK_INVALID;
962         vhost->context->count_wsi_allocated++;
963
964         /*
965          * outermost create notification for wsi
966          * no user_space because no protocol selection
967          */
968         vhost->protocols[0].callback(new_wsi, LWS_CALLBACK_WSI_CREATE,
969                                        NULL, NULL, 0);
970
971         return new_wsi;
972 }
973
974 /**
975  * lws_http_transaction_completed() - wait for new http transaction or close
976  * @wsi:        websocket connection
977  *
978  *      Returns 1 if the HTTP connection must close now
979  *      Returns 0 and resets connection to wait for new HTTP header /
980  *        transaction if possible
981  */
982
983 LWS_VISIBLE int LWS_WARN_UNUSED_RESULT
984 lws_http_transaction_completed(struct lws *wsi)
985 {
986         lwsl_debug("%s: wsi %p\n", __func__, wsi);
987         /* if we can't go back to accept new headers, drop the connection */
988         if (wsi->u.http.connection_type != HTTP_CONNECTION_KEEP_ALIVE) {
989                 lwsl_info("%s: %p: close connection\n", __func__, wsi);
990                 return 1;
991         }
992
993         /* otherwise set ourselves up ready to go again */
994         wsi->state = LWSS_HTTP;
995         wsi->mode = LWSCM_HTTP_SERVING;
996         wsi->u.http.content_length = 0;
997         wsi->hdr_parsing_completed = 0;
998
999         /* He asked for it to stay alive indefinitely */
1000         lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
1001
1002         /*
1003          * We already know we are on http1.1 / keepalive and the next thing
1004          * coming will be another header set.
1005          *
1006          * If there is no pending rx and we still have the ah, drop it and
1007          * reacquire a new ah when the new headers start to arrive.  (Otherwise
1008          * we needlessly hog an ah indefinitely.)
1009          *
1010          * However if there is pending rx and we know from the keepalive state
1011          * that is already at least the start of another header set, simply
1012          * reset the existing header table and keep it.
1013          */
1014         if (wsi->u.hdr.ah) {
1015                 lwsl_info("%s: wsi->more_rx_waiting=%d\n", __func__,
1016                                 wsi->more_rx_waiting);
1017
1018                 if (!wsi->more_rx_waiting) {
1019                         wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
1020                         lws_header_table_detach(wsi, 1);
1021                 } else
1022                         lws_header_table_reset(wsi, 1);
1023         }
1024
1025         /* If we're (re)starting on headers, need other implied init */
1026         wsi->u.hdr.ues = URIES_IDLE;
1027
1028         lwsl_info("%s: %p: keep-alive await new transaction\n", __func__, wsi);
1029
1030         return 0;
1031 }
1032
1033 static struct lws *
1034 lws_adopt_socket_vhost(struct lws_vhost *vh, lws_sockfd_type accept_fd)
1035 {
1036         struct lws_context *context = vh->context;
1037         struct lws *new_wsi = lws_create_new_server_wsi(vh);
1038
1039         if (!new_wsi) {
1040                 compatible_close(accept_fd);
1041                 return NULL;
1042         }
1043
1044         lwsl_info("%s: new wsi %p, sockfd %d\n", __func__, new_wsi, accept_fd);
1045
1046         new_wsi->sock = accept_fd;
1047
1048         /* the transport is accepted... give him time to negotiate */
1049         lws_set_timeout(new_wsi, PENDING_TIMEOUT_ESTABLISH_WITH_SERVER,
1050                         context->timeout_secs);
1051
1052 #if LWS_POSIX == 0
1053         mbed3_tcp_stream_accept(accept_fd, new_wsi);
1054 #endif
1055
1056         /*
1057          * A new connection was accepted. Give the user a chance to
1058          * set properties of the newly created wsi. There's no protocol
1059          * selected yet so we issue this to protocols[0]
1060          */
1061         if ((context->vhost_list->protocols[0].callback)(new_wsi,
1062              LWS_CALLBACK_SERVER_NEW_CLIENT_INSTANTIATED, NULL, NULL, 0)) {
1063                 compatible_close(new_wsi->sock);
1064                 lws_free(new_wsi);
1065                 return NULL;
1066         }
1067
1068         lws_libev_accept(new_wsi, new_wsi->sock);
1069         lws_libuv_accept(new_wsi, new_wsi->sock);
1070
1071         if (!LWS_SSL_ENABLED(new_wsi->vhost)) {
1072                 if (insert_wsi_socket_into_fds(context, new_wsi)) {
1073                         lwsl_err("%s: fail inserting socket\n", __func__);
1074                         goto fail;
1075                 }
1076         } else {
1077                 new_wsi->mode = LWSCM_SSL_INIT;
1078                 if (lws_server_socket_service_ssl(new_wsi, accept_fd)) {
1079                         lwsl_err("%s: fail ssl negotiation\n", __func__);
1080                         goto fail;
1081                 }
1082         }
1083
1084         return new_wsi;
1085
1086 fail:
1087         lws_close_free_wsi(new_wsi, LWS_CLOSE_STATUS_NOSTATUS);
1088
1089         return NULL;
1090 }
1091
1092 /**
1093  * lws_adopt_socket() - adopt foreign socket as if listen socket accepted it
1094  * @context: lws context
1095  * @accept_fd: fd of already-accepted socket to adopt
1096  *
1097  * Either returns new wsi bound to accept_fd, or closes accept_fd and
1098  * returns NULL, having cleaned up any new wsi pieces.
1099  *
1100  * LWS adopts the socket in http serving mode, it's ready to accept an upgrade
1101  * to ws or just serve http.
1102  */
1103
1104 LWS_VISIBLE struct lws *
1105 lws_adopt_socket(struct lws_context *context, lws_sockfd_type accept_fd)
1106 {
1107         return lws_adopt_socket_vhost(context->vhost_list, accept_fd);
1108 }
1109
1110
1111 /**
1112  * lws_adopt_socket_readbuf() - adopt foreign socket and first rx as if listen socket accepted it
1113  * @context:    lws context
1114  * @accept_fd:  fd of already-accepted socket to adopt
1115  * @readbuf:    NULL or pointer to data that must be drained before reading from
1116  *              accept_fd
1117  * @len:        The length of the data held at @readbuf
1118  *
1119  * Either returns new wsi bound to accept_fd, or closes accept_fd and
1120  * returns NULL, having cleaned up any new wsi pieces.
1121  *
1122  * LWS adopts the socket in http serving mode, it's ready to accept an upgrade
1123  * to ws or just serve http.
1124  *
1125  * If your external code did not already read from the socket, you can use
1126  * lws_adopt_socket() instead.
1127  *
1128  * This api is guaranteed to use the data at @readbuf first, before reading from
1129  * the socket.
1130  *
1131  * @readbuf is limited to the size of the ah rx buf, currently 2048 bytes.
1132  */
1133
1134 LWS_VISIBLE LWS_EXTERN struct lws *
1135 lws_adopt_socket_readbuf(struct lws_context *context, lws_sockfd_type accept_fd,
1136                          const char *readbuf, size_t len)
1137 {
1138         struct lws *wsi = lws_adopt_socket(context, accept_fd);
1139         struct lws_context_per_thread *pt;
1140         struct allocated_headers *ah;
1141         struct lws_pollfd *pfd;
1142
1143         if (!wsi)
1144                 return NULL;
1145
1146         if (!readbuf)
1147                 return wsi;
1148
1149         if (len > sizeof(ah->rx)) {
1150                 lwsl_err("%s: rx in too big\n", __func__);
1151                 goto bail;
1152         }
1153         /*
1154          * we can't process the initial read data until we can attach an ah.
1155          *
1156          * if one is available, get it and place the data in his ah rxbuf...
1157          * wsi with ah that have pending rxbuf get auto-POLLIN service.
1158          *
1159          * no autoservice because we didn't get a chance to attach the
1160          * readbuf data to wsi or ah yet, and we will do it next if we get
1161          * the ah.
1162          */
1163         if (!lws_header_table_attach(wsi, 0)) {
1164                 ah = wsi->u.hdr.ah;
1165                 memcpy(ah->rx, readbuf, len);
1166                 ah->rxpos = 0;
1167                 ah->rxlen = len;
1168
1169                 lwsl_notice("%s: calling service on readbuf ah\n", __func__);
1170                 pt = &context->pt[(int)wsi->tsi];
1171
1172                 /* unlike a normal connect, we have the headers already
1173                  * (or the first part of them anyway).
1174                  * libuv won't come back and service us without a network
1175                  * event, so we need to do the header service right here.
1176                  */
1177                 pfd = &pt->fds[wsi->position_in_fds_table];
1178                 pfd->revents |= LWS_POLLIN;
1179                 lwsl_err("%s: calling service\n", __func__);
1180                 if (lws_service_fd_tsi(context, pfd, wsi->tsi))
1181                         /* service closed us */
1182                         return NULL;
1183
1184                 return wsi;
1185         }
1186         lwsl_err("%s: deferring handling ah\n", __func__);
1187         /*
1188          * hum if no ah came, we are on the wait list and must defer
1189          * dealing with this until the ah arrives.
1190          *
1191          * later successful lws_header_table_attach() will apply the
1192          * below to the rx buffer (via lws_header_table_reset()).
1193          */
1194         wsi->u.hdr.preamble_rx = lws_malloc(len);
1195         memcpy(wsi->u.hdr.preamble_rx, readbuf, len);
1196         wsi->u.hdr.preamble_rx_len = len;
1197
1198         return wsi;
1199
1200 bail:
1201         lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
1202
1203         return NULL;
1204 }
1205
1206 LWS_VISIBLE int
1207 lws_server_socket_service(struct lws_context *context, struct lws *wsi,
1208                           struct lws_pollfd *pollfd)
1209 {
1210         struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
1211         lws_sockfd_type accept_fd = LWS_SOCK_INVALID;
1212         struct allocated_headers *ah;
1213 #if LWS_POSIX
1214         struct sockaddr_in cli_addr;
1215         socklen_t clilen;
1216 #endif
1217         int n, len;
1218
1219         switch (wsi->mode) {
1220
1221         case LWSCM_HTTP_SERVING:
1222         case LWSCM_HTTP_SERVING_ACCEPTED:
1223         case LWSCM_HTTP2_SERVING:
1224
1225                 /* handle http headers coming in */
1226
1227                 /* pending truncated sends have uber priority */
1228
1229                 if (wsi->trunc_len) {
1230                         if (!(pollfd->revents & LWS_POLLOUT))
1231                                 break;
1232
1233                         if (lws_issue_raw(wsi, wsi->trunc_alloc +
1234                                                wsi->trunc_offset,
1235                                           wsi->trunc_len) < 0)
1236                                 goto fail;
1237                         /*
1238                          * we can't afford to allow input processing to send
1239                          * something new, so spin around he event loop until
1240                          * he doesn't have any partials
1241                          */
1242                         break;
1243                 }
1244
1245                 /* any incoming data ready? */
1246
1247                 if (!(pollfd->revents & pollfd->events & LWS_POLLIN))
1248                         goto try_pollout;
1249
1250                 /* these states imply we MUST have an ah attached */
1251
1252                 if (wsi->state == LWSS_HTTP ||
1253                     wsi->state == LWSS_HTTP_ISSUING_FILE ||
1254                     wsi->state == LWSS_HTTP_HEADERS) {
1255                         if (!wsi->u.hdr.ah)
1256                                 /* no autoservice beacuse we will do it next */
1257                                 if (lws_header_table_attach(wsi, 0))
1258                                         goto try_pollout;
1259
1260                         ah = wsi->u.hdr.ah;
1261
1262                         lwsl_debug("%s: %p: rxpos:%d rxlen:%d\n", __func__, wsi,
1263                                    ah->rxpos, ah->rxlen);
1264
1265                         /* if nothing in ah rx buffer, get some fresh rx */
1266                         if (ah->rxpos == ah->rxlen) {
1267                                 ah->rxlen = lws_ssl_capable_read(wsi, ah->rx,
1268                                                    sizeof(ah->rx));
1269                                 ah->rxpos = 0;
1270                                 lwsl_debug("%s: wsi %p, ah->rxlen = %d\r\n",
1271                                            __func__, wsi, ah->rxlen);
1272                                 switch (ah->rxlen) {
1273                                 case 0:
1274                                         lwsl_info("%s: read 0 len\n", __func__);
1275                                         /* lwsl_info("   state=%d\n", wsi->state); */
1276 //                                      if (!wsi->hdr_parsing_completed)
1277 //                                              lws_header_table_detach(wsi);
1278                                         /* fallthru */
1279                                 case LWS_SSL_CAPABLE_ERROR:
1280                                         goto fail;
1281                                 case LWS_SSL_CAPABLE_MORE_SERVICE:
1282                                         ah->rxlen = ah->rxpos = 0;
1283                                         goto try_pollout;
1284                                 }
1285                         }
1286                         assert(ah->rxpos != ah->rxlen && ah->rxlen);
1287                         /* just ignore incoming if waiting for close */
1288                         if (wsi->state != LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE) {
1289                                 n = lws_read(wsi, ah->rx + ah->rxpos,
1290                                              ah->rxlen - ah->rxpos);
1291                                 if (n < 0) /* we closed wsi */
1292                                         return 1;
1293                                 if (wsi->u.hdr.ah) {
1294                                         if ( wsi->u.hdr.ah->rxlen)
1295                                                  wsi->u.hdr.ah->rxpos += n;
1296
1297                                         if (wsi->u.hdr.ah->rxpos == wsi->u.hdr.ah->rxlen &&
1298                                             (wsi->mode != LWSCM_HTTP_SERVING &&
1299                                              wsi->mode != LWSCM_HTTP_SERVING_ACCEPTED &&
1300                                              wsi->mode != LWSCM_HTTP2_SERVING))
1301                                                 lws_header_table_detach(wsi, 1);
1302                                 }
1303                                 break;
1304                         }
1305
1306                         goto try_pollout;
1307                 }
1308
1309                 len = lws_ssl_capable_read(wsi, pt->serv_buf,
1310                                            LWS_MAX_SOCKET_IO_BUF);
1311                 lwsl_debug("%s: wsi %p read %d\r\n", __func__, wsi, len);
1312                 switch (len) {
1313                 case 0:
1314                         lwsl_info("%s: read 0 len\n", __func__);
1315                         /* lwsl_info("   state=%d\n", wsi->state); */
1316 //                      if (!wsi->hdr_parsing_completed)
1317 //                              lws_header_table_detach(wsi);
1318                         /* fallthru */
1319                 case LWS_SSL_CAPABLE_ERROR:
1320                         goto fail;
1321                 case LWS_SSL_CAPABLE_MORE_SERVICE:
1322                         goto try_pollout;
1323                 }
1324
1325                 /* just ignore incoming if waiting for close */
1326                 if (wsi->state != LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE) {
1327                         /*
1328                          * hm this may want to send
1329                          * (via HTTP callback for example)
1330                          */
1331                         n = lws_read(wsi, pt->serv_buf, len);
1332                         if (n < 0) /* we closed wsi */
1333                                 return 1;
1334                         /* hum he may have used up the
1335                          * writability above */
1336                         break;
1337                 }
1338
1339 try_pollout:
1340                 /* this handles POLLOUT for http serving fragments */
1341
1342                 if (!(pollfd->revents & LWS_POLLOUT))
1343                         break;
1344
1345                 /* one shot */
1346                 if (lws_change_pollfd(wsi, LWS_POLLOUT, 0)) {
1347                         lwsl_notice("%s a\n", __func__);
1348                         goto fail;
1349                 }
1350
1351                 if (!wsi->hdr_parsing_completed)
1352                         break;
1353
1354                 if (wsi->state != LWSS_HTTP_ISSUING_FILE) {
1355                         n = user_callback_handle_rxflow(wsi->protocol->callback,
1356                                         wsi, LWS_CALLBACK_HTTP_WRITEABLE,
1357                                         wsi->user_space, NULL, 0);
1358                         if (n < 0) {
1359                                 lwsl_info("writeable_fail\n");
1360                                 goto fail;
1361                         }
1362                         break;
1363                 }
1364
1365                 /* >0 == completion, <0 == error */
1366                 n = lws_serve_http_file_fragment(wsi);
1367                 if (n < 0 || (n > 0 && lws_http_transaction_completed(wsi))) {
1368                         lwsl_info("completed\n");
1369                         goto fail;
1370                 }
1371                 break;
1372
1373         case LWSCM_SERVER_LISTENER:
1374
1375 #if LWS_POSIX
1376                 /* pollin means a client has connected to us then */
1377
1378                 do {
1379                         if (!(pollfd->revents & LWS_POLLIN) || !(pollfd->events & LWS_POLLIN))
1380                                 break;
1381
1382                         /* listen socket got an unencrypted connection... */
1383
1384                         clilen = sizeof(cli_addr);
1385                         lws_latency_pre(context, wsi);
1386                         accept_fd  = accept(pollfd->fd, (struct sockaddr *)&cli_addr,
1387                                             &clilen);
1388                         lws_latency(context, wsi, "listener accept", accept_fd,
1389                                     accept_fd >= 0);
1390                         if (accept_fd < 0) {
1391                                 if (LWS_ERRNO == LWS_EAGAIN ||
1392                                     LWS_ERRNO == LWS_EWOULDBLOCK) {
1393                                         lwsl_err("accept asks to try again\n");
1394                                         break;
1395                                 }
1396                                 lwsl_err("ERROR on accept: %s\n", strerror(LWS_ERRNO));
1397                                 break;
1398                         }
1399
1400                         lws_plat_set_socket_options(wsi->vhost, accept_fd);
1401
1402                         lwsl_debug("accepted new conn  port %u on fd=%d\n",
1403                                           ntohs(cli_addr.sin_port), accept_fd);
1404
1405 #else
1406                         /* not very beautiful... */
1407                         accept_fd = (lws_sockfd_type)pollfd;
1408 #endif
1409                         /*
1410                          * look at who we connected to and give user code a chance
1411                          * to reject based on client IP.  There's no protocol selected
1412                          * yet so we issue this to protocols[0]
1413                          */
1414                         if ((wsi->vhost->protocols[0].callback)(wsi,
1415                                         LWS_CALLBACK_FILTER_NETWORK_CONNECTION,
1416                                         NULL, (void *)(long)accept_fd, 0)) {
1417                                 lwsl_debug("Callback denied network connection\n");
1418                                 compatible_close(accept_fd);
1419                                 break;
1420                         }
1421
1422                         if (!lws_adopt_socket_vhost(wsi->vhost, accept_fd))
1423                                 /* already closed cleanly as necessary */
1424                                 return 1;
1425
1426 #if LWS_POSIX
1427                 } while (pt->fds_count < context->fd_limit_per_thread - 1 &&
1428                          lws_poll_listen_fd(&pt->fds[wsi->position_in_fds_table]) > 0);
1429 #endif
1430                 return 0;
1431
1432         default:
1433                 break;
1434         }
1435
1436         if (!lws_server_socket_service_ssl(wsi, accept_fd))
1437                 return 0;
1438
1439 fail:
1440         lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
1441
1442         return 1;
1443 }
1444
1445 /**
1446  * lws_serve_http_file() - Send a file back to the client using http
1447  * @wsi:                Websocket instance (available from user callback)
1448  * @file:               The file to issue over http
1449  * @content_type:       The http content type, eg, text/html
1450  * @other_headers:      NULL or pointer to header string
1451  * @other_headers_len:  length of the other headers if non-NULL
1452  *
1453  *      This function is intended to be called from the callback in response
1454  *      to http requests from the client.  It allows the callback to issue
1455  *      local files down the http link in a single step.
1456  *
1457  *      Returning <0 indicates error and the wsi should be closed.  Returning
1458  *      >0 indicates the file was completely sent and
1459  *      lws_http_transaction_completed() called on the wsi (and close if != 0)
1460  *      ==0 indicates the file transfer is started and needs more service later,
1461  *      the wsi should be left alone.
1462  */
1463
1464 LWS_VISIBLE int
1465 lws_serve_http_file(struct lws *wsi, const char *file, const char *content_type,
1466                     const char *other_headers, int other_headers_len)
1467 {
1468         struct lws_context *context = lws_get_context(wsi);
1469         struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
1470         unsigned char *response = pt->serv_buf + LWS_PRE;
1471         unsigned char *p = response;
1472         unsigned char *end = p + LWS_MAX_SOCKET_IO_BUF - LWS_PRE;
1473         int ret = 0;
1474
1475         wsi->u.http.fd = lws_plat_file_open(wsi, file, &wsi->u.http.filelen,
1476                                             O_RDONLY);
1477
1478         if (wsi->u.http.fd == LWS_INVALID_FILE) {
1479                 lwsl_err("Unable to open '%s'\n", file);
1480                 lws_return_http_status(wsi, HTTP_STATUS_NOT_FOUND, NULL);
1481
1482                 return -1;
1483         }
1484
1485         if (lws_add_http_header_status(wsi, 200, &p, end))
1486                 return -1;
1487         if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_SERVER,
1488                                          (unsigned char *)"libwebsockets", 13,
1489                                          &p, end))
1490                 return -1;
1491         if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE,
1492                                          (unsigned char *)content_type,
1493                                          strlen(content_type), &p, end))
1494                 return -1;
1495         if (lws_add_http_header_content_length(wsi, wsi->u.http.filelen, &p, end))
1496                 return -1;
1497
1498         if (other_headers) {
1499                 if ((end - p) < other_headers_len)
1500                         return -1;
1501                 memcpy(p, other_headers, other_headers_len);
1502                 p += other_headers_len;
1503         }
1504
1505         if (lws_finalize_http_header(wsi, &p, end))
1506                 return -1;
1507
1508         ret = lws_write(wsi, response, p - response, LWS_WRITE_HTTP_HEADERS);
1509         if (ret != (p - response)) {
1510                 lwsl_err("_write returned %d from %d\n", ret, (p - response));
1511                 return -1;
1512         }
1513
1514         wsi->u.http.filepos = 0;
1515         wsi->state = LWSS_HTTP_ISSUING_FILE;
1516
1517         return lws_serve_http_file_fragment(wsi);
1518 }
1519
1520 int
1521 lws_interpret_incoming_packet(struct lws *wsi, unsigned char **buf, size_t len)
1522 {
1523         int m;
1524
1525         lwsl_parser("%s: received %d byte packet\n", __func__, (int)len);
1526 #if 0
1527         lwsl_hexdump(*buf, len);
1528 #endif
1529
1530         /* let the rx protocol state machine have as much as it needs */
1531
1532         while (len) {
1533                 /*
1534                  * we were accepting input but now we stopped doing so
1535                  */
1536                 if (!(wsi->rxflow_change_to & LWS_RXFLOW_ALLOW)) {
1537                         lws_rxflow_cache(wsi, *buf, 0, len);
1538                         lwsl_parser("%s: cached %d\n", __func__, len);
1539                         return 1;
1540                 }
1541
1542                 if (wsi->u.ws.rx_draining_ext) {
1543                         m = lws_rx_sm(wsi, 0);
1544                         if (m < 0)
1545                                 return -1;
1546                         continue;
1547                 }
1548
1549                 /* account for what we're using in rxflow buffer */
1550                 if (wsi->rxflow_buffer)
1551                         wsi->rxflow_pos++;
1552
1553                 /* consume payload bytes efficiently */
1554                 if (wsi->lws_rx_parse_state ==
1555                     LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED)
1556                         lws_payload_until_length_exhausted(wsi, buf, &len);
1557
1558                 /* process the byte */
1559                 m = lws_rx_sm(wsi, *(*buf)++);
1560                 if (m < 0)
1561                         return -1;
1562                 len--;
1563         }
1564
1565         lwsl_parser("%s: exit with %d unused\n", __func__, (int)len);
1566
1567         return 0;
1568 }
1569
1570 LWS_VISIBLE void
1571 lws_server_get_canonical_hostname(struct lws_context *context,
1572                                   struct lws_context_creation_info *info)
1573 {
1574         if (lws_check_opt(info->options, LWS_SERVER_OPTION_SKIP_SERVER_CANONICAL_NAME))
1575                 return;
1576 #if LWS_POSIX
1577         /* find canonical hostname */
1578         gethostname((char *)context->canonical_hostname,
1579                     sizeof(context->canonical_hostname) - 1);
1580
1581         lwsl_notice(" canonical_hostname = %s\n", context->canonical_hostname);
1582 #else
1583         (void)context;
1584 #endif
1585 }