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