668f6f1f6658192a14a788460a46b452b4bcd9bb
[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 #if defined (LWS_WITH_ESP8266)
26 #undef memcpy
27 void *memcpy(void *dest, const void *src, size_t n)
28 {
29         return ets_memcpy(dest, src, n);
30 }
31 #endif
32
33 int
34 lws_context_init_server(struct lws_context_creation_info *info,
35                         struct lws_vhost *vhost)
36 {
37 #if LWS_POSIX
38         int n, opt = 1, limit = 1;
39 #endif
40         lws_sockfd_type sockfd;
41         struct lws_vhost *vh;
42         struct lws *wsi;
43         int m = 0;
44
45         (void)opt;
46         /* set up our external listening socket we serve on */
47
48         if (info->port == CONTEXT_PORT_NO_LISTEN || info->port == CONTEXT_PORT_NO_LISTEN_SERVER)
49                 return 0;
50
51         vh = vhost->context->vhost_list;
52         while (vh) {
53                 if (vh->listen_port == info->port) {
54                         if ((!info->iface && !vh->iface) ||
55                             (info->iface && vh->iface &&
56                             !strcmp(info->iface, vh->iface))) {
57                                 vhost->listen_port = info->port;
58                                 vhost->iface = info->iface;
59                                 lwsl_notice(" using listen skt from vhost %s\n",
60                                             vh->name);
61                                 return 0;
62                         }
63                 }
64                 vh = vh->vhost_next;
65         }
66
67 #if LWS_POSIX
68         (void)n;
69 #if defined(__linux__)
70         limit = vhost->context->count_threads;
71 #endif
72
73         for (m = 0; m < limit; m++) {
74 #ifdef LWS_USE_UNIX_SOCK
75         if (LWS_UNIX_SOCK_ENABLED(vhost))
76                 sockfd = socket(AF_UNIX, SOCK_STREAM, 0);
77         else
78 #endif
79 #ifdef LWS_USE_IPV6
80         if (LWS_IPV6_ENABLED(vhost))
81                 sockfd = socket(AF_INET6, SOCK_STREAM, 0);
82         else
83 #endif
84                 sockfd = socket(AF_INET, SOCK_STREAM, 0);
85
86         if (sockfd == -1) {
87 #else
88 #if defined(LWS_WITH_ESP8266)
89         sockfd = esp8266_create_tcp_listen_socket(vhost);
90         if (!lws_sockfd_valid(sockfd)) {
91 #endif
92 #endif
93                 lwsl_err("ERROR opening socket\n");
94                 return 1;
95         }
96 #if LWS_POSIX && !defined(LWS_WITH_ESP32)
97
98 #if (defined(WIN32) || defined(_WIN32)) && defined(SO_EXCLUSIVEADDRUSE)
99         /*
100          * only accept that we are the only listener on the port
101          * https://msdn.microsoft.com/zh-tw/library/windows/desktop/ms740621(v=vs.85).aspx
102          *
103          * for lws, to match Linux, we default to exclusive listen
104          */
105         if (!lws_check_opt(vhost->options, LWS_SERVER_OPTION_ALLOW_LISTEN_SHARE)) {
106                 if (setsockopt(sockfd, SOL_SOCKET, SO_EXCLUSIVEADDRUSE,
107                                (const void *)&opt, sizeof(opt)) < 0) {
108                         lwsl_err("reuseaddr failed\n");
109                         compatible_close(sockfd);
110                         return 1;
111                 }
112         } else
113 #endif
114
115         /*
116          * allow us to restart even if old sockets in TIME_WAIT
117          */
118         if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
119                        (const void *)&opt, sizeof(opt)) < 0) {
120                 lwsl_err("reuseaddr failed\n");
121                 compatible_close(sockfd);
122                 return 1;
123         }
124
125 #if defined(LWS_USE_IPV6) && defined(IPV6_V6ONLY)
126         if (LWS_IPV6_ENABLED(vhost)) {
127                 if (vhost->options & LWS_SERVER_OPTION_IPV6_V6ONLY_MODIFY) {
128                         int value = (vhost->options & LWS_SERVER_OPTION_IPV6_V6ONLY_VALUE) ? 1 : 0;
129                         if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY,
130                                         (const void*)&value, sizeof(value)) < 0) {
131                                 compatible_close(sockfd);
132                                 return 1;
133                         }
134                 }
135         }
136 #endif
137
138 #if defined(__linux__) && defined(SO_REUSEPORT)
139         n = lws_check_opt(vhost->options, LWS_SERVER_OPTION_ALLOW_LISTEN_SHARE);
140 #if LWS_MAX_SMP > 1
141         n = 1;
142 #endif
143
144         if (n)
145                 if (vhost->context->count_threads > 1)
146                         if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEPORT,
147                                         (const void *)&opt, sizeof(opt)) < 0) {
148                                 compatible_close(sockfd);
149                                 return 1;
150                         }
151 #endif
152 #endif
153         lws_plat_set_socket_options(vhost, sockfd);
154
155 #if LWS_POSIX
156         n = lws_socket_bind(vhost, sockfd, info->port, info->iface);
157         if (n < 0)
158                 goto bail;
159         info->port = n;
160 #endif
161         vhost->listen_port = info->port;
162         vhost->iface = info->iface;
163
164         wsi = lws_zalloc(sizeof(struct lws));
165         if (wsi == NULL) {
166                 lwsl_err("Out of mem\n");
167                 goto bail;
168         }
169         wsi->context = vhost->context;
170         wsi->desc.sockfd = sockfd;
171         wsi->mode = LWSCM_SERVER_LISTENER;
172         wsi->protocol = vhost->protocols;
173         wsi->tsi = m;
174         wsi->vhost = vhost;
175         wsi->listener = 1;
176
177 #ifdef LWS_USE_LIBUV
178         if (LWS_LIBUV_ENABLED(vhost->context))
179                 lws_uv_initvhost(vhost, wsi);
180 #endif
181
182         if (insert_wsi_socket_into_fds(vhost->context, wsi))
183                 goto bail;
184
185         vhost->context->count_wsi_allocated++;
186         vhost->lserv_wsi = wsi;
187
188 #if LWS_POSIX
189         n = listen(wsi->desc.sockfd, LWS_SOMAXCONN);
190         if (n < 0) {
191                 lwsl_err("listen failed with error %d\n", LWS_ERRNO);
192                 vhost->lserv_wsi = NULL;
193                 vhost->context->count_wsi_allocated--;
194                 remove_wsi_socket_from_fds(wsi);
195                 goto bail;
196         }
197         } /* for each thread able to independently listen */
198 #else
199 #if defined(LWS_WITH_ESP8266)
200         esp8266_tcp_stream_bind(wsi->desc.sockfd, info->port, wsi);
201 #endif
202 #endif
203         if (!lws_check_opt(info->options, LWS_SERVER_OPTION_EXPLICIT_VHOSTS)) {
204 #ifdef LWS_USE_UNIX_SOCK
205                 if (LWS_UNIX_SOCK_ENABLED(vhost))
206                         lwsl_notice(" Listening on \"%s\"\n", info->iface);
207                 else
208 #endif
209                         lwsl_notice(" Listening on port %d\n", info->port);
210         }
211
212         return 0;
213
214 bail:
215         compatible_close(sockfd);
216
217         return 1;
218 }
219
220 #if defined(LWS_WITH_ESP8266)
221 #undef strchr
222 #define strchr ets_strchr
223 #endif
224
225 struct lws_vhost *
226 lws_select_vhost(struct lws_context *context, int port, const char *servername)
227 {
228         struct lws_vhost *vhost = context->vhost_list;
229         const char *p;
230         int n, m, colon;
231
232         n = strlen(servername);
233         colon = n;
234         p = strchr(servername, ':');
235         if (p)
236                 colon = p - servername;
237
238         /* Priotity 1: first try exact matches */
239
240         while (vhost) {
241                 if (port == vhost->listen_port &&
242                     !strncmp(vhost->name, servername, colon)) {
243                         lwsl_info("SNI: Found: %s\n", servername);
244                         return vhost;
245                 }
246                 vhost = vhost->vhost_next;
247         }
248
249         /*
250          * Priority 2: if no exact matches, try matching *.vhost-name
251          * unintentional matches are possible but resolve to x.com for *.x.com
252          * which is reasonable.  If exact match exists we already chose it and
253          * never reach here.  SSL will still fail it if the cert doesn't allow
254          * *.x.com.
255          */
256
257         vhost = context->vhost_list;
258         while (vhost) {
259                 m = strlen(vhost->name);
260                 if (port == vhost->listen_port &&
261                     m <= (colon - 2) &&
262                     servername[colon - m - 1] == '.' &&
263                     !strncmp(vhost->name, servername + colon - m, m)) {
264                         lwsl_info("SNI: Found %s on wildcard: %s\n",
265                                     servername, vhost->name);
266                         return vhost;
267                 }
268                 vhost = vhost->vhost_next;
269         }
270
271         /* Priority 3: match the first vhost on our port */
272
273         vhost = context->vhost_list;
274         while (vhost) {
275                 if (port == vhost->listen_port) {
276                         lwsl_info("vhost match to %s based on port %d\n",
277                                         vhost->name, port);
278                         return vhost;
279                 }
280                 vhost = vhost->vhost_next;
281         }
282
283         /* no match */
284
285         return NULL;
286 }
287
288 LWS_VISIBLE LWS_EXTERN const char *
289 lws_get_mimetype(const char *file, const struct lws_http_mount *m)
290 {
291         int n = strlen(file);
292         const struct lws_protocol_vhost_options *pvo = NULL;
293
294         if (m)
295                 pvo = m->extra_mimetypes;
296
297         if (n < 5)
298                 return NULL;
299
300         if (!strcmp(&file[n - 4], ".ico"))
301                 return "image/x-icon";
302
303         if (!strcmp(&file[n - 4], ".gif"))
304                 return "image/gif";
305
306         if (!strcmp(&file[n - 3], ".js"))
307                 return "text/javascript";
308
309         if (!strcmp(&file[n - 4], ".png"))
310                 return "image/png";
311
312         if (!strcmp(&file[n - 4], ".jpg"))
313                 return "image/jpeg";
314
315         if (!strcmp(&file[n - 3], ".gz"))
316                 return "application/gzip";
317
318         if (!strcmp(&file[n - 4], ".JPG"))
319                 return "image/jpeg";
320
321         if (!strcmp(&file[n - 5], ".html"))
322                 return "text/html";
323
324         if (!strcmp(&file[n - 4], ".css"))
325                 return "text/css";
326
327         if (!strcmp(&file[n - 4], ".txt"))
328                 return "text/plain";
329
330         if (!strcmp(&file[n - 4], ".svg"))
331                 return "image/svg+xml";
332
333         if (!strcmp(&file[n - 4], ".ttf"))
334                 return "application/x-font-ttf";
335
336         if (!strcmp(&file[n - 4], ".otf"))
337                 return "application/font-woff";
338
339         if (!strcmp(&file[n - 5], ".woff"))
340                 return "application/font-woff";
341
342         if (!strcmp(&file[n - 4], ".xml"))
343                 return "application/xml";
344
345         while (pvo) {
346                 if (pvo->name[0] == '*') /* ie, match anything */
347                         return pvo->value;
348
349                 if (!strcmp(&file[n - strlen(pvo->name)], pvo->name))
350                         return pvo->value;
351
352                 pvo = pvo->next;
353         }
354
355         return NULL;
356 }
357 static lws_fop_flags_t
358 lws_vfs_prepare_flags(struct lws *wsi)
359 {
360         lws_fop_flags_t f = 0;
361
362         if (!lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_ACCEPT_ENCODING))
363                 return f;
364
365         if (strstr(lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_ACCEPT_ENCODING),
366                    "gzip")) {
367                 lwsl_info("client indicates GZIP is acceptable\n");
368                 f |= LWS_FOP_FLAG_COMPR_ACCEPTABLE_GZIP;
369         }
370
371         return f;
372 }
373
374 static int
375 lws_http_serve(struct lws *wsi, char *uri, const char *origin,
376                const struct lws_http_mount *m)
377 {
378         const struct lws_protocol_vhost_options *pvo = m->interpret;
379         struct lws_process_html_args args;
380         const char *mimetype;
381 #if !defined(_WIN32_WCE) && !defined(LWS_WITH_ESP8266)
382         const struct lws_plat_file_ops *fops;
383         const char *vpath;
384         lws_fop_flags_t fflags = LWS_O_RDONLY;
385 #if defined(WIN32) && defined(LWS_HAVE__STAT32I64)
386         struct _stat32i64 st;
387 #else
388         struct stat st;
389 #endif
390         int spin = 0;
391 #endif
392         char path[256], sym[512];
393         unsigned char *p = (unsigned char *)sym + 32 + LWS_PRE, *start = p;
394         unsigned char *end = p + sizeof(sym) - 32 - LWS_PRE;
395 #if !defined(WIN32) && LWS_POSIX && !defined(LWS_WITH_ESP32)
396         size_t len;
397 #endif
398         int n;
399
400         lws_snprintf(path, sizeof(path) - 1, "%s/%s", origin, uri);
401
402 #if !defined(_WIN32_WCE) && !defined(LWS_WITH_ESP8266)
403
404         fflags |= lws_vfs_prepare_flags(wsi);
405
406         do {
407                 spin++;
408                 fops = lws_vfs_select_fops(wsi->context->fops, path, &vpath);
409
410                 if (wsi->u.http.fop_fd)
411                         lws_vfs_file_close(&wsi->u.http.fop_fd);
412
413                 wsi->u.http.fop_fd = fops->LWS_FOP_OPEN(wsi->context->fops,
414                                                         path, vpath, &fflags);
415                 if (!wsi->u.http.fop_fd) {
416                         lwsl_err("Unable to open '%s'\n", path);
417
418                         return -1;
419                 }
420
421                 /* if it can't be statted, don't try */
422                 if (fflags & LWS_FOP_FLAG_VIRTUAL)
423                         break;
424 #if defined(LWS_WITH_ESP32)
425                 break;
426 #endif
427 #if !defined(WIN32)
428                 if (fstat(wsi->u.http.fop_fd->fd, &st)) {
429                         lwsl_info("unable to stat %s\n", path);
430                         goto bail;
431                 }
432 #else
433 #if defined(LWS_HAVE__STAT32I64)
434                 if (_stat32i64(path, &st)) {
435                         lwsl_info("unable to stat %s\n", path);
436                         goto bail;
437                 }
438 #else
439                 if (stat(path, &st)) {
440                         lwsl_info("unable to stat %s\n", path);
441                         goto bail;
442                 }
443 #endif
444 #endif
445
446                 wsi->u.http.fop_fd->mod_time = (uint32_t)st.st_mtime;
447                 fflags |= LWS_FOP_FLAG_MOD_TIME_VALID;
448
449                 lwsl_debug(" %s mode %d\n", path, S_IFMT & st.st_mode);
450 #if !defined(WIN32) && LWS_POSIX && !defined(LWS_WITH_ESP32)
451                 if ((S_IFMT & st.st_mode) == S_IFLNK) {
452                         len = readlink(path, sym, sizeof(sym) - 1);
453                         if (len) {
454                                 lwsl_err("Failed to read link %s\n", path);
455                                 goto bail;
456                         }
457                         sym[len] = '\0';
458                         lwsl_debug("symlink %s -> %s\n", path, sym);
459                         lws_snprintf(path, sizeof(path) - 1, "%s", sym);
460                 }
461 #endif
462                 if ((S_IFMT & st.st_mode) == S_IFDIR) {
463                         lwsl_debug("default filename append to dir\n");
464                         lws_snprintf(path, sizeof(path) - 1, "%s/%s/index.html",
465                                  origin, uri);
466                 }
467
468         } while ((S_IFMT & st.st_mode) != S_IFREG && spin < 5);
469
470         if (spin == 5)
471                 lwsl_err("symlink loop %s \n", path);
472
473         n = sprintf(sym, "%08llX%08lX",
474                     (unsigned long long)lws_vfs_get_length(wsi->u.http.fop_fd),
475                     (unsigned long)lws_vfs_get_mod_time(wsi->u.http.fop_fd));
476
477         /* disable ranges if IF_RANGE token invalid */
478
479         if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_IF_RANGE))
480                 if (strcmp(sym, lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_IF_RANGE)))
481                         /* differs - defeat Range: */
482                         wsi->u.http.ah->frag_index[WSI_TOKEN_HTTP_RANGE] = 0;
483
484         if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_IF_NONE_MATCH)) {
485                 /*
486                  * he thinks he has some version of it already,
487                  * check if the tag matches
488                  */
489                 if (!strcmp(sym, lws_hdr_simple_ptr(wsi,
490                                         WSI_TOKEN_HTTP_IF_NONE_MATCH))) {
491
492                         lwsl_debug("%s: ETAG match %s %s\n", __func__,
493                                    uri, origin);
494
495                         /* we don't need to send the payload */
496                         if (lws_add_http_header_status(wsi,
497                                         HTTP_STATUS_NOT_MODIFIED, &p, end))
498                                 return -1;
499
500                         if (lws_add_http_header_by_token(wsi,
501                                         WSI_TOKEN_HTTP_ETAG,
502                                         (unsigned char *)sym, n, &p, end))
503                                 return -1;
504
505                         if (lws_finalize_http_header(wsi, &p, end))
506                                 return -1;
507
508                         n = lws_write(wsi, start, p - start,
509                                       LWS_WRITE_HTTP_HEADERS);
510                         if (n != (p - start)) {
511                                 lwsl_err("_write returned %d from %ld\n", n,
512                                          (long)(p - start));
513                                 return -1;
514                         }
515
516                         lws_vfs_file_close(&wsi->u.http.fop_fd);
517
518                         return lws_http_transaction_completed(wsi);
519                 }
520         }
521
522         if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_ETAG,
523                         (unsigned char *)sym, n, &p, end))
524                 return -1;
525 #endif
526
527         mimetype = lws_get_mimetype(path, m);
528         if (!mimetype) {
529                 lwsl_err("unknown mimetype for %s\n", path);
530                goto bail;
531         }
532         if (!mimetype[0])
533                 lwsl_debug("sending no mimetype for %s\n", path);
534
535         wsi->sending_chunked = 0;
536
537         /*
538          * check if this is in the list of file suffixes to be interpreted by
539          * a protocol
540          */
541         while (pvo) {
542                 n = strlen(path);
543                 if (n > (int)strlen(pvo->name) &&
544                     !strcmp(&path[n - strlen(pvo->name)], pvo->name)) {
545                         wsi->sending_chunked = 1;
546                         wsi->protocol_interpret_idx = (char)(lws_intptr_t)pvo->value;
547                         lwsl_info("want %s interpreted by %s\n", path,
548                                     wsi->vhost->protocols[(int)(lws_intptr_t)(pvo->value)].name);
549                         wsi->protocol = &wsi->vhost->protocols[(int)(lws_intptr_t)(pvo->value)];
550                         if (lws_ensure_user_space(wsi))
551                                 return -1;
552                         break;
553                 }
554                 pvo = pvo->next;
555         }
556
557         if (m->protocol) {
558                 const struct lws_protocols *pp = lws_vhost_name_to_protocol(
559                                                         wsi->vhost, m->protocol);
560
561                 if (lws_bind_protocol(wsi, pp))
562                         return 1;
563                 args.p = (char *)p;
564                 args.max_len = end - p;
565                 if (pp->callback(wsi, LWS_CALLBACK_ADD_HEADERS,
566                                           wsi->user_space, &args, 0))
567                         return -1;
568                 p = (unsigned char *)args.p;
569         }
570
571         n = lws_serve_http_file(wsi, path, mimetype, (char *)start, p - start);
572
573         if (n < 0 || ((n > 0) && lws_http_transaction_completed(wsi)))
574                 return -1; /* error or can't reuse connection: close the socket */
575
576         return 0;
577 bail:
578
579         return -1;
580 }
581
582 const struct lws_http_mount *
583 lws_find_mount(struct lws *wsi, const char *uri_ptr, int uri_len)
584 {
585         const struct lws_http_mount *hm, *hit = NULL;
586         int best = 0;
587
588         hm = wsi->vhost->mount_list;
589         while (hm) {
590                 if (uri_len >= hm->mountpoint_len &&
591                     !strncmp(uri_ptr, hm->mountpoint, hm->mountpoint_len) &&
592                     (uri_ptr[hm->mountpoint_len] == '\0' ||
593                      uri_ptr[hm->mountpoint_len] == '/' ||
594                      hm->mountpoint_len == 1)
595                     ) {
596                         if (hm->origin_protocol == LWSMPRO_CALLBACK ||
597                             ((hm->origin_protocol == LWSMPRO_CGI ||
598                              lws_hdr_total_length(wsi, WSI_TOKEN_GET_URI) ||
599                              hm->protocol) &&
600                             hm->mountpoint_len > best)) {
601                                 best = hm->mountpoint_len;
602                                 hit = hm;
603                         }
604                 }
605                 hm = hm->mount_next;
606         }
607
608         return hit;
609 }
610
611 #if LWS_POSIX
612
613 static int
614 lws_find_string_in_file(const char *filename, const char *string, int stringlen)
615 {
616         char buf[128];
617         int fd, match = 0, pos = 0, n = 0, hit = 0;
618
619         fd = open(filename, O_RDONLY);
620         if (fd < 0) {
621                 lwsl_err("can't open auth file: %s\n", filename);
622                 return 1;
623         }
624
625         while (1) {
626                 if (pos == n) {
627                         n = read(fd, buf, sizeof(buf));
628                         if (n <= 0) {
629                                 if (match == stringlen)
630                                         hit = 1;
631                                 break;
632                         }
633                         pos = 0;
634                 }
635
636                 if (match == stringlen) {
637                         if (buf[pos] == '\r' || buf[pos] == '\n') {
638                                 hit = 1;
639                                 break;
640                         }
641                         match = 0;
642                 }
643
644                 if (buf[pos] == string[match])
645                         match++;
646                 else
647                         match = 0;
648
649                 pos++;
650         }
651
652         close(fd);
653
654         return hit;
655 }
656
657 static int
658 lws_unauthorised_basic_auth(struct lws *wsi)
659 {
660         struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
661         unsigned char *start = pt->serv_buf + LWS_PRE,
662                       *p = start, *end = p + 512;
663         char buf[64];
664         int n;
665
666         /* no auth... tell him it is required */
667
668         if (lws_add_http_header_status(wsi, HTTP_STATUS_UNAUTHORIZED, &p, end))
669                 return -1;
670
671         n = lws_snprintf(buf, sizeof(buf), "Basic realm=\"lwsws\"");
672         if (lws_add_http_header_by_token(wsi,
673                         WSI_TOKEN_HTTP_WWW_AUTHENTICATE,
674                         (unsigned char *)buf, n, &p, end))
675                 return -1;
676
677         if (lws_finalize_http_header(wsi, &p, end))
678                 return -1;
679
680         n = lws_write(wsi, start, p - start, LWS_WRITE_HTTP_HEADERS);
681         if (n < 0)
682                 return -1;
683
684         return lws_http_transaction_completed(wsi);
685
686 }
687
688 #endif
689
690 int lws_clean_url(char *p)
691 {
692         while (*p) {
693                 if (p[0] == '/' && p[1] == '/') {
694                         char *p1 = p;
695                         while (*p1) {
696                                 *p1 = p1[1];
697                                 p1++;
698                         }
699                         continue;
700                 }
701                 p++;
702         }
703
704         return 0;
705 }
706
707 int
708 lws_http_action(struct lws *wsi)
709 {
710         struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
711         enum http_connection_type connection_type;
712         enum http_version request_version;
713         char content_length_str[32];
714         struct lws_process_html_args args;
715         const struct lws_http_mount *hit = NULL;
716         unsigned int n, count = 0;
717         char http_version_str[10];
718         char http_conn_str[20];
719         int http_version_len;
720         char *uri_ptr = NULL, *s;
721         int uri_len = 0;
722         int meth = -1;
723
724         static const unsigned char methods[] = {
725                 WSI_TOKEN_GET_URI,
726                 WSI_TOKEN_POST_URI,
727                 WSI_TOKEN_OPTIONS_URI,
728                 WSI_TOKEN_PUT_URI,
729                 WSI_TOKEN_PATCH_URI,
730                 WSI_TOKEN_DELETE_URI,
731                 WSI_TOKEN_CONNECT,
732 #ifdef LWS_USE_HTTP2
733                 WSI_TOKEN_HTTP_COLON_PATH,
734 #endif
735         };
736 #if defined(_DEBUG) || defined(LWS_WITH_ACCESS_LOG)
737         static const char * const method_names[] = {
738                 "GET", "POST", "OPTIONS", "PUT", "PATCH", "DELETE", "CONNECT",
739 #ifdef LWS_USE_HTTP2
740                 ":path",
741 #endif
742         };
743 #endif
744         static const char * const oprot[] = {
745                 "http://", "https://"
746         };
747
748         /* it's not websocket.... shall we accept it as http? */
749
750         for (n = 0; n < ARRAY_SIZE(methods); n++)
751                 if (lws_hdr_total_length(wsi, methods[n]))
752                         count++;
753         if (!count) {
754                 lwsl_warn("Missing URI in HTTP request\n");
755                 goto bail_nuke_ah;
756         }
757
758         if (count != 1) {
759                 lwsl_warn("multiple methods?\n");
760                 goto bail_nuke_ah;
761         }
762
763         if (lws_ensure_user_space(wsi))
764                 goto bail_nuke_ah;
765
766         for (n = 0; n < ARRAY_SIZE(methods); n++)
767                 if (lws_hdr_total_length(wsi, methods[n])) {
768                         uri_ptr = lws_hdr_simple_ptr(wsi, methods[n]);
769                         uri_len = lws_hdr_total_length(wsi, methods[n]);
770                         lwsl_info("Method: %s request for '%s'\n",
771                                         method_names[n], uri_ptr);
772                         meth = n;
773                         break;
774                 }
775
776         (void)meth;
777
778         /* we insist on absolute paths */
779
780         if (uri_ptr[0] != '/') {
781                 lws_return_http_status(wsi, HTTP_STATUS_FORBIDDEN, NULL);
782
783                 goto bail_nuke_ah;
784         }
785
786         /* HTTP header had a content length? */
787
788         wsi->u.http.content_length = 0;
789         if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI) ||
790                 lws_hdr_total_length(wsi, WSI_TOKEN_PATCH_URI) ||
791                 lws_hdr_total_length(wsi, WSI_TOKEN_PUT_URI))
792                 wsi->u.http.content_length = 100 * 1024 * 1024;
793
794         if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH)) {
795                 lws_hdr_copy(wsi, content_length_str,
796                              sizeof(content_length_str) - 1,
797                              WSI_TOKEN_HTTP_CONTENT_LENGTH);
798                 wsi->u.http.content_length = atoll(content_length_str);
799         }
800
801         if (wsi->http2_substream) {
802                 wsi->u.http.request_version = HTTP_VERSION_2;
803         } else {
804                 /* http_version? Default to 1.0, override with token: */
805                 request_version = HTTP_VERSION_1_0;
806
807                 /* Works for single digit HTTP versions. : */
808                 http_version_len = lws_hdr_total_length(wsi, WSI_TOKEN_HTTP);
809                 if (http_version_len > 7) {
810                         lws_hdr_copy(wsi, http_version_str,
811                                         sizeof(http_version_str) - 1, WSI_TOKEN_HTTP);
812                         if (http_version_str[5] == '1' && http_version_str[7] == '1')
813                                 request_version = HTTP_VERSION_1_1;
814                 }
815                 wsi->u.http.request_version = request_version;
816
817                 /* HTTP/1.1 defaults to "keep-alive", 1.0 to "close" */
818                 if (request_version == HTTP_VERSION_1_1)
819                         connection_type = HTTP_CONNECTION_KEEP_ALIVE;
820                 else
821                         connection_type = HTTP_CONNECTION_CLOSE;
822
823                 /* Override default if http "Connection:" header: */
824                 if (lws_hdr_total_length(wsi, WSI_TOKEN_CONNECTION)) {
825                         lws_hdr_copy(wsi, http_conn_str, sizeof(http_conn_str) - 1,
826                                      WSI_TOKEN_CONNECTION);
827                         http_conn_str[sizeof(http_conn_str) - 1] = '\0';
828                         if (!strcasecmp(http_conn_str, "keep-alive"))
829                                 connection_type = HTTP_CONNECTION_KEEP_ALIVE;
830                         else
831                                 if (!strcasecmp(http_conn_str, "close"))
832                                         connection_type = HTTP_CONNECTION_CLOSE;
833                 }
834                 wsi->u.http.connection_type = connection_type;
835         }
836
837         n = wsi->protocol->callback(wsi, LWS_CALLBACK_FILTER_HTTP_CONNECTION,
838                                     wsi->user_space, uri_ptr, uri_len);
839         if (n) {
840                 lwsl_info("LWS_CALLBACK_HTTP closing\n");
841
842                 return 1;
843         }
844         /*
845          * if there is content supposed to be coming,
846          * put a timeout on it having arrived
847          */
848         lws_set_timeout(wsi, PENDING_TIMEOUT_HTTP_CONTENT,
849                         wsi->context->timeout_secs);
850 #ifdef LWS_OPENSSL_SUPPORT
851         if (wsi->redirect_to_https) {
852                 /*
853                  * we accepted http:// only so we could redirect to
854                  * https://, so issue the redirect.  Create the redirection
855                  * URI from the host: header and ignore the path part
856                  */
857                 unsigned char *start = pt->serv_buf + LWS_PRE, *p = start,
858                               *end = p + 512;
859
860                 if (!lws_hdr_total_length(wsi, WSI_TOKEN_HOST))
861                         goto bail_nuke_ah;
862
863                 n = sprintf((char *)end, "https://%s/",
864                             lws_hdr_simple_ptr(wsi, WSI_TOKEN_HOST));
865
866                 n = lws_http_redirect(wsi, HTTP_STATUS_MOVED_PERMANENTLY,
867                                       end, n, &p, end);
868                 if ((int)n < 0)
869                         goto bail_nuke_ah;
870
871                 return lws_http_transaction_completed(wsi);
872         }
873 #endif
874
875 #ifdef LWS_WITH_ACCESS_LOG
876         /*
877          * Produce Apache-compatible log string for wsi, like this:
878          *
879          * 2.31.234.19 - - [27/Mar/2016:03:22:44 +0800]
880          * "GET /aep-screen.png HTTP/1.1"
881          * 200 152987 "https://libwebsockets.org/index.html"
882          * "Mozilla/5.0 (Macint... Chrome/49.0.2623.87 Safari/537.36"
883          *
884          */
885         {
886                 static const char * const hver[] = {
887                         "http/1.0", "http/1.1", "http/2"
888                 };
889 #ifdef LWS_USE_IPV6
890                 char ads[INET6_ADDRSTRLEN];
891 #else
892                 char ads[INET_ADDRSTRLEN];
893 #endif
894                 char da[64];
895                 const char *pa, *me;
896                 struct tm *tmp;
897                 time_t t = time(NULL);
898                 int l = 256;
899
900                 if (wsi->access_log_pending)
901                         lws_access_log(wsi);
902
903                 wsi->access_log.header_log = lws_malloc(l);
904                 if (wsi->access_log.header_log) {
905
906                         tmp = localtime(&t);
907                         if (tmp)
908                                 strftime(da, sizeof(da), "%d/%b/%Y:%H:%M:%S %z", tmp);
909                         else
910                                 strcpy(da, "01/Jan/1970:00:00:00 +0000");
911
912                         pa = lws_get_peer_simple(wsi, ads, sizeof(ads));
913                         if (!pa)
914                                 pa = "(unknown)";
915
916                         if (meth >= 0)
917                                 me = method_names[meth];
918                         else
919                                 me = "unknown";
920
921                         lws_snprintf(wsi->access_log.header_log, l,
922                                  "%s - - [%s] \"%s %s %s\"",
923                                  pa, da, me, uri_ptr,
924                                  hver[wsi->u.http.request_version]);
925
926                         l = lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_USER_AGENT);
927                         if (l) {
928                                 wsi->access_log.user_agent = lws_malloc(l + 2);
929                                 if (wsi->access_log.user_agent)
930                                         lws_hdr_copy(wsi, wsi->access_log.user_agent,
931                                                         l + 1, WSI_TOKEN_HTTP_USER_AGENT);
932                                 else
933                                         lwsl_err("OOM getting user agent\n");
934                         }
935                         wsi->access_log_pending = 1;
936                 }
937         }
938 #endif
939
940         /* can we serve it from the mount list? */
941
942         hit = lws_find_mount(wsi, uri_ptr, uri_len);
943         if (!hit) {
944                 /* deferred cleanup and reset to protocols[0] */
945
946                 lwsl_info("no hit\n");
947
948                 if (lws_bind_protocol(wsi, &wsi->vhost->protocols[0]))
949                         return 1;
950
951                 n = wsi->protocol->callback(wsi, LWS_CALLBACK_HTTP,
952                                     wsi->user_space, uri_ptr, uri_len);
953
954                 goto after;
955         }
956
957         s = uri_ptr + hit->mountpoint_len;
958
959         /*
960          * if we have a mountpoint like https://xxx.com/yyy
961          * there is an implied / at the end for our purposes since
962          * we can only mount on a "directory".
963          *
964          * But if we just go with that, the browser cannot understand
965          * that he is actually looking down one "directory level", so
966          * even though we give him /yyy/abc.html he acts like the
967          * current directory level is /.  So relative urls like "x.png"
968          * wrongly look outside the mountpoint.
969          *
970          * Therefore if we didn't come in on a url with an explicit
971          * / at the end, we must redirect to add it so the browser
972          * understands he is one "directory level" down.
973          */
974         if ((hit->mountpoint_len > 1 ||
975              (hit->origin_protocol == LWSMPRO_REDIR_HTTP ||
976               hit->origin_protocol == LWSMPRO_REDIR_HTTPS)) &&
977             (*s != '/' ||
978              (hit->origin_protocol == LWSMPRO_REDIR_HTTP ||
979               hit->origin_protocol == LWSMPRO_REDIR_HTTPS)) &&
980             (hit->origin_protocol != LWSMPRO_CGI &&
981              hit->origin_protocol != LWSMPRO_CALLBACK //&&
982              //hit->protocol == NULL
983              )) {
984                 unsigned char *start = pt->serv_buf + LWS_PRE,
985                               *p = start, *end = p + 512;
986
987                 lwsl_debug("Doing 301 '%s' org %s\n", s, hit->origin);
988
989                 if (!lws_hdr_total_length(wsi, WSI_TOKEN_HOST))
990                         goto bail_nuke_ah;
991
992                 /* > at start indicates deal with by redirect */
993                 if (hit->origin_protocol == LWSMPRO_REDIR_HTTP ||
994                     hit->origin_protocol == LWSMPRO_REDIR_HTTPS)
995                         n = lws_snprintf((char *)end, 256, "%s%s",
996                                     oprot[hit->origin_protocol & 1],
997                                     hit->origin);
998                 else
999                         n = lws_snprintf((char *)end, 256,
1000                             "%s%s%s/", oprot[lws_is_ssl(wsi)],
1001                             lws_hdr_simple_ptr(wsi, WSI_TOKEN_HOST),
1002                             uri_ptr);
1003                 lws_clean_url((char *)end);
1004
1005                 n = lws_http_redirect(wsi, HTTP_STATUS_MOVED_PERMANENTLY,
1006                                       end, n, &p, end);
1007                 if ((int)n < 0)
1008                         goto bail_nuke_ah;
1009
1010                 return lws_http_transaction_completed(wsi);
1011         }
1012
1013 #if LWS_POSIX
1014         /* basic auth? */
1015
1016         if (hit->basic_auth_login_file) {
1017                 char b64[160], plain[(sizeof(b64) * 3) / 4];
1018                 int m;
1019
1020                 /* Did he send auth? */
1021                 if (!lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_AUTHORIZATION))
1022                         return lws_unauthorised_basic_auth(wsi);
1023
1024                 n = HTTP_STATUS_FORBIDDEN;
1025
1026                 m = lws_hdr_copy(wsi, b64, sizeof(b64), WSI_TOKEN_HTTP_AUTHORIZATION);
1027                 if (m < 7) {
1028                         lwsl_err("b64 auth too long\n");
1029                         goto transaction_result_n;
1030                 }
1031
1032                 b64[5] = '\0';
1033                 if (strcasecmp(b64, "Basic")) {
1034                         lwsl_err("auth missing basic: %s\n", b64);
1035                         goto transaction_result_n;
1036                 }
1037
1038                 /* It'll be like Authorization: Basic QWxhZGRpbjpPcGVuU2VzYW1l */
1039
1040                 m = lws_b64_decode_string(b64 + 6, plain, sizeof(plain));
1041                 if (m < 0) {
1042                         lwsl_err("plain auth too long\n");
1043                         goto transaction_result_n;
1044                 }
1045
1046 //              lwsl_notice(plain);
1047
1048                 if (!lws_find_string_in_file(hit->basic_auth_login_file, plain, m)) {
1049                         lwsl_err("basic auth lookup failed\n");
1050                         return lws_unauthorised_basic_auth(wsi);
1051                 }
1052
1053                 lwsl_notice("basic auth accepted\n");
1054
1055                 /* accept the auth */
1056         }
1057 #endif
1058
1059 #if defined(LWS_WITH_HTTP_PROXY)
1060         /*
1061          * The mount is a reverse proxy?
1062          */
1063
1064         if (hit->origin_protocol == LWSMPRO_HTTPS ||
1065             hit->origin_protocol == LWSMPRO_HTTP)  {
1066                 struct lws_client_connect_info i;
1067                 char ads[96], rpath[256], *pcolon, *pslash, *p;
1068                 int n, na;
1069
1070                 memset(&i, 0, sizeof(i));
1071                 i.context = lws_get_context(wsi);
1072
1073                 pcolon = strchr(hit->origin, ':');
1074                 pslash = strchr(hit->origin, '/');
1075                 if (!pslash) {
1076                         lwsl_err("Proxy mount origin '%s' must have /\n", hit->origin);
1077                         return -1;
1078                 }
1079                 if (pcolon > pslash)
1080                         pcolon = NULL;
1081                 
1082                 if (pcolon)
1083                         n = pcolon - hit->origin;
1084                 else
1085                         n = pslash - hit->origin;
1086
1087                 if (n >= sizeof(ads) - 2)
1088                         n = sizeof(ads) - 2;
1089
1090                 memcpy(ads, hit->origin, n);
1091                 ads[n] = '\0';
1092
1093                 i.address = ads;
1094                 i.port = 80;
1095                 if (hit->origin_protocol == LWSMPRO_HTTPS) { 
1096                         i.port = 443;
1097                         i.ssl_connection = 1;
1098                 }
1099                 if (pcolon)
1100                         i.port = atoi(pcolon + 1);
1101                 
1102                 lws_snprintf(rpath, sizeof(rpath) - 1, "/%s/%s", pslash + 1, uri_ptr + hit->mountpoint_len);
1103                 lws_clean_url(rpath);
1104                 na = lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_URI_ARGS);
1105                 if (na) {
1106                         p = rpath + strlen(rpath);
1107                         *p++ = '?';
1108                         lws_hdr_copy(wsi, p, &rpath[sizeof(rpath) - 1] - p, WSI_TOKEN_HTTP_URI_ARGS);
1109                         while (--na) {
1110                                 if (*p == '\0')
1111                                         *p = '&';
1112                                 p++;
1113                         }
1114                 }
1115                                 
1116
1117                 i.path = rpath;
1118                 i.host = i.address;
1119                 i.origin = NULL;
1120                 i.method = "GET";
1121                 i.parent_wsi = wsi;
1122                 i.uri_replace_from = hit->origin;
1123                 i.uri_replace_to = hit->mountpoint;
1124
1125                 lwsl_notice("proxying to %s port %d url %s, ssl %d, from %s, to %s\n",
1126                                 i.address, i.port, i.path, i.ssl_connection, i.uri_replace_from, i.uri_replace_to);
1127         
1128                 if (!lws_client_connect_via_info(&i)) {
1129                         lwsl_err("proxy connect fail\n");
1130                         return 1;
1131                 }
1132
1133                 return 0;
1134         }
1135 #endif
1136
1137         /*
1138          * A particular protocol callback is mounted here?
1139          *
1140          * For the duration of this http transaction, bind us to the
1141          * associated protocol
1142          */
1143         if (hit->origin_protocol == LWSMPRO_CALLBACK || hit->protocol) {
1144                 const struct lws_protocols *pp;
1145                 const char *name = hit->origin;
1146                 if (hit->protocol)
1147                         name = hit->protocol;
1148
1149                 pp = lws_vhost_name_to_protocol(wsi->vhost, name);
1150                 if (!pp) {
1151                         n = -1;
1152                         lwsl_err("Unable to find plugin '%s'\n",
1153                                  hit->origin);
1154                         return 1;
1155                 }
1156
1157                 if (lws_bind_protocol(wsi, pp))
1158                         return 1;
1159
1160                 args.p = uri_ptr;
1161                 args.len = uri_len;
1162                 args.max_len = hit->auth_mask;
1163                 args.final = 0; /* used to signal callback dealt with it */
1164
1165                 n = wsi->protocol->callback(wsi, LWS_CALLBACK_CHECK_ACCESS_RIGHTS,
1166                                             wsi->user_space, &args, 0);
1167                 if (n) {
1168                         lws_return_http_status(wsi, HTTP_STATUS_UNAUTHORIZED,
1169                                                NULL);
1170                         goto bail_nuke_ah;
1171                 }
1172                 if (args.final) /* callback completely handled it well */
1173                         return 0;
1174
1175                 if (hit->cgienv && wsi->protocol->callback(wsi,
1176                                 LWS_CALLBACK_HTTP_PMO,
1177                                 wsi->user_space, (void *)hit->cgienv, 0))
1178                         return 1;
1179
1180                 if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI)) {
1181                         n = wsi->protocol->callback(wsi, LWS_CALLBACK_HTTP,
1182                                             wsi->user_space,
1183                                             uri_ptr + hit->mountpoint_len,
1184                                             uri_len - hit->mountpoint_len);
1185                         goto after;
1186                 }
1187         }
1188
1189 #ifdef LWS_WITH_CGI
1190         /* did we hit something with a cgi:// origin? */
1191         if (hit->origin_protocol == LWSMPRO_CGI) {
1192                 const char *cmd[] = {
1193                         NULL, /* replace with cgi path */
1194                         NULL
1195                 };
1196
1197                 lwsl_debug("%s: cgi\n", __func__);
1198                 cmd[0] = hit->origin;
1199
1200                 n = 5;
1201                 if (hit->cgi_timeout)
1202                         n = hit->cgi_timeout;
1203
1204                 n = lws_cgi(wsi, cmd, hit->mountpoint_len, n,
1205                             hit->cgienv);
1206                 if (n) {
1207                         lwsl_err("%s: cgi failed\n", __func__);
1208                         return -1;
1209                 }
1210
1211                 goto deal_body;
1212         }
1213 #endif
1214
1215         n = strlen(s);
1216         if (s[0] == '\0' || (n == 1 && s[n - 1] == '/'))
1217                 s = (char *)hit->def;
1218         if (!s)
1219                 s = "index.html";
1220
1221         wsi->cache_secs = hit->cache_max_age;
1222         wsi->cache_reuse = hit->cache_reusable;
1223         wsi->cache_revalidate = hit->cache_revalidate;
1224         wsi->cache_intermediaries = hit->cache_intermediaries;
1225
1226         n = lws_http_serve(wsi, s, hit->origin, hit);
1227         if (n) {
1228                 /*
1229                  *      lws_return_http_status(wsi, HTTP_STATUS_NOT_FOUND, NULL);
1230                  */
1231                 if (hit->protocol) {
1232                         const struct lws_protocols *pp = lws_vhost_name_to_protocol(
1233                                         wsi->vhost, hit->protocol);
1234
1235                         if (lws_bind_protocol(wsi, pp))
1236                                 return 1;
1237
1238                         n = pp->callback(wsi, LWS_CALLBACK_HTTP,
1239                                          wsi->user_space,
1240                                          uri_ptr + hit->mountpoint_len,
1241                                          uri_len - hit->mountpoint_len);
1242                 } else
1243                         n = wsi->protocol->callback(wsi, LWS_CALLBACK_HTTP,
1244                                     wsi->user_space, uri_ptr, uri_len);
1245         }
1246
1247 after:
1248         if (n) {
1249                 lwsl_info("LWS_CALLBACK_HTTP closing\n");
1250
1251                 return 1;
1252         }
1253
1254 #ifdef LWS_WITH_CGI
1255 deal_body:
1256 #endif
1257         /*
1258          * If we're not issuing a file, check for content_length or
1259          * HTTP keep-alive. No keep-alive header allocation for
1260          * ISSUING_FILE, as this uses HTTP/1.0.
1261          *
1262          * In any case, return 0 and let lws_read decide how to
1263          * proceed based on state
1264          */
1265         if (wsi->state != LWSS_HTTP_ISSUING_FILE)
1266                 /* Prepare to read body if we have a content length: */
1267                 if (wsi->u.http.content_length > 0)
1268                         wsi->state = LWSS_HTTP_BODY;
1269
1270         return 0;
1271
1272 bail_nuke_ah:
1273         /* we're closing, losing some rx is OK */
1274         lws_header_table_force_to_detachable_state(wsi);
1275         // lwsl_notice("%s: drop1\n", __func__);
1276         lws_header_table_detach(wsi, 1);
1277
1278         return 1;
1279 #if LWS_POSIX
1280 transaction_result_n:
1281         lws_return_http_status(wsi, n, NULL);
1282
1283         return lws_http_transaction_completed(wsi);
1284 #endif
1285 }
1286
1287 static int
1288 lws_server_init_wsi_for_ws(struct lws *wsi)
1289 {
1290         int n;
1291
1292         wsi->state = LWSS_ESTABLISHED;
1293         lws_restart_ws_ping_pong_timer(wsi);
1294
1295         /*
1296          * create the frame buffer for this connection according to the
1297          * size mentioned in the protocol definition.  If 0 there, use
1298          * a big default for compatibility
1299          */
1300
1301         n = wsi->protocol->rx_buffer_size;
1302         if (!n)
1303                 n = wsi->context->pt_serv_buf_size;
1304         n += LWS_PRE;
1305         wsi->u.ws.rx_ubuf = lws_malloc(n + 4 /* 0x0000ffff zlib */);
1306         if (!wsi->u.ws.rx_ubuf) {
1307                 lwsl_err("Out of Mem allocating rx buffer %d\n", n);
1308                 return 1;
1309         }
1310         wsi->u.ws.rx_ubuf_alloc = n;
1311         lwsl_debug("Allocating RX buffer %d\n", n);
1312
1313 #if LWS_POSIX && !defined(LWS_WITH_ESP32)
1314         if (!wsi->parent_carries_io)
1315                 if (setsockopt(wsi->desc.sockfd, SOL_SOCKET, SO_SNDBUF,
1316                        (const char *)&n, sizeof n)) {
1317                         lwsl_warn("Failed to set SNDBUF to %d", n);
1318                         return 1;
1319                 }
1320 #endif
1321
1322         /* notify user code that we're ready to roll */
1323
1324         if (wsi->protocol->callback)
1325                 if (wsi->protocol->callback(wsi, LWS_CALLBACK_ESTABLISHED,
1326                                             wsi->user_space,
1327 #ifdef LWS_OPENSSL_SUPPORT
1328                                             wsi->ssl,
1329 #else
1330                                             NULL,
1331 #endif
1332                                             0))
1333                         return 1;
1334
1335         return 0;
1336 }
1337
1338 int
1339 lws_handshake_server(struct lws *wsi, unsigned char **buf, size_t len)
1340 {
1341         int protocol_len, n = 0, hit, non_space_char_found = 0, m;
1342         struct lws_context *context = lws_get_context(wsi);
1343         struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
1344         struct _lws_header_related hdr;
1345         struct allocated_headers *ah;
1346         unsigned char *obuf = *buf;
1347         char protocol_list[128];
1348         char protocol_name[64];
1349         size_t olen = len;
1350         char *p;
1351
1352         if (len >= 10000000) {
1353                 lwsl_err("%s: assert: len %ld\n", __func__, (long)len);
1354                 assert(0);
1355         }
1356
1357         if (!wsi->u.hdr.ah) {
1358                 lwsl_err("%s: assert: NULL ah\n", __func__);
1359                 assert(0);
1360         }
1361
1362         while (len--) {
1363                 wsi->more_rx_waiting = !!len;
1364
1365                 if (wsi->mode != LWSCM_HTTP_SERVING &&
1366                     wsi->mode != LWSCM_HTTP_SERVING_ACCEPTED) {
1367                         lwsl_err("%s: bad wsi mode %d\n", __func__, wsi->mode);
1368                         goto bail_nuke_ah;
1369                 }
1370
1371                 m = lws_parse(wsi, *(*buf)++);
1372                 if (m) {
1373                         if (m == 2) {
1374                                 /*
1375                                  * we are transitioning from http with
1376                                  * an AH, to raw.  Drop the ah and set
1377                                  * the mode.
1378                                  */
1379 raw_transition:
1380                                 lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
1381                                 lws_bind_protocol(wsi, &wsi->vhost->protocols[
1382                                                         wsi->vhost->
1383                                                         raw_protocol_index]);
1384                                 lwsl_info("transition to raw vh %s prot %d\n",
1385                                           wsi->vhost->name,
1386                                           wsi->vhost->raw_protocol_index);
1387                                 if ((wsi->protocol->callback)(wsi,
1388                                                 LWS_CALLBACK_RAW_ADOPT,
1389                                                 wsi->user_space, NULL, 0))
1390                                         goto bail_nuke_ah;
1391
1392                                 lws_header_table_force_to_detachable_state(wsi);
1393                                 lws_union_transition(wsi, LWSCM_RAW);
1394                                 lws_header_table_detach(wsi, 1);
1395
1396                                 if (m == 2 && (wsi->protocol->callback)(wsi,
1397                                                 LWS_CALLBACK_RAW_RX,
1398                                                 wsi->user_space, obuf, olen))
1399                                         return 1;
1400
1401                                 return 0;
1402                         }
1403                         lwsl_info("lws_parse failed\n");
1404                         goto bail_nuke_ah;
1405                 }
1406
1407                 if (wsi->u.hdr.parser_state != WSI_PARSING_COMPLETE)
1408                         continue;
1409
1410                 lwsl_parser("%s: lws_parse sees parsing complete\n", __func__);
1411                 lwsl_debug("%s: wsi->more_rx_waiting=%d\n", __func__,
1412                                 wsi->more_rx_waiting);
1413
1414                 /* check for unwelcome guests */
1415
1416                 if (wsi->context->reject_service_keywords) {
1417                         const struct lws_protocol_vhost_options *rej =
1418                                         wsi->context->reject_service_keywords;
1419                         char ua[384], *msg = NULL;
1420
1421                         if (lws_hdr_copy(wsi, ua, sizeof(ua) - 1,
1422                                           WSI_TOKEN_HTTP_USER_AGENT) > 0) {
1423                                 ua[sizeof(ua) - 1] = '\0';
1424                                 while (rej) {
1425                                         if (strstr(ua, rej->name)) {
1426                                                 msg = strchr(rej->value, ' ');
1427                                                 if (msg)
1428                                                         msg++;
1429                                                 lws_return_http_status(wsi, atoi(rej->value), msg);
1430
1431                                                 wsi->vhost->conn_stats.rejected++;
1432
1433                                                 goto bail_nuke_ah;
1434                                         }
1435                                         rej = rej->next;
1436                                 }
1437                         }
1438                 }
1439
1440                 /* select vhost */
1441
1442                 if (lws_hdr_total_length(wsi, WSI_TOKEN_HOST)) {
1443                         struct lws_vhost *vhost = lws_select_vhost(
1444                                 context, wsi->vhost->listen_port,
1445                                 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HOST));
1446
1447                         if (vhost)
1448                                 wsi->vhost = vhost;
1449                 } else
1450                         lwsl_info("no host\n");
1451
1452                 wsi->vhost->conn_stats.trans++;
1453                 if (!wsi->conn_stat_done) {
1454                         wsi->vhost->conn_stats.conn++;
1455                         wsi->conn_stat_done = 1;
1456                 }
1457
1458                 if (lws_hdr_total_length(wsi, WSI_TOKEN_CONNECT)) {
1459                         lwsl_info("Changing to RAW mode\n");
1460                         m = 0;
1461                         goto raw_transition;
1462                 }
1463
1464                 wsi->mode = LWSCM_PRE_WS_SERVING_ACCEPT;
1465                 lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
1466
1467                 /* is this websocket protocol or normal http 1.0? */
1468
1469                 if (lws_hdr_total_length(wsi, WSI_TOKEN_UPGRADE)) {
1470                         if (!strcasecmp(lws_hdr_simple_ptr(wsi, WSI_TOKEN_UPGRADE),
1471                                         "websocket")) {
1472                                 wsi->vhost->conn_stats.ws_upg++;
1473                                 lwsl_info("Upgrade to ws\n");
1474                                 goto upgrade_ws;
1475                         }
1476 #ifdef LWS_USE_HTTP2
1477                         if (!strcasecmp(lws_hdr_simple_ptr(wsi, WSI_TOKEN_UPGRADE),
1478                                         "h2c")) {
1479                                 wsi->vhost->conn_stats.http2_upg++;
1480                                 lwsl_info("Upgrade to h2c\n");
1481                                 goto upgrade_h2c;
1482                         }
1483 #endif
1484                         lwsl_info("Unknown upgrade\n");
1485                         /* dunno what he wanted to upgrade to */
1486                         goto bail_nuke_ah;
1487                 }
1488
1489                 /* no upgrade ack... he remained as HTTP */
1490
1491                 lwsl_info("No upgrade\n");
1492                 ah = wsi->u.hdr.ah;
1493
1494                 lws_union_transition(wsi, LWSCM_HTTP_SERVING_ACCEPTED);
1495                 wsi->state = LWSS_HTTP;
1496                 wsi->u.http.fop_fd = NULL;
1497
1498                 /* expose it at the same offset as u.hdr */
1499                 wsi->u.http.ah = ah;
1500                 lwsl_debug("%s: wsi %p: ah %p\n", __func__, (void *)wsi,
1501                            (void *)wsi->u.hdr.ah);
1502
1503                 n = lws_http_action(wsi);
1504
1505                 return n;
1506
1507 #ifdef LWS_USE_HTTP2
1508 upgrade_h2c:
1509                 if (!lws_hdr_total_length(wsi, WSI_TOKEN_HTTP2_SETTINGS)) {
1510                         lwsl_info("missing http2_settings\n");
1511                         goto bail_nuke_ah;
1512                 }
1513
1514                 lwsl_info("h2c upgrade...\n");
1515
1516                 p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP2_SETTINGS);
1517                 /* convert the peer's HTTP-Settings */
1518                 n = lws_b64_decode_string(p, protocol_list,
1519                                           sizeof(protocol_list));
1520                 if (n < 0) {
1521                         lwsl_parser("HTTP2_SETTINGS too long\n");
1522                         return 1;
1523                 }
1524
1525                 /* adopt the header info */
1526
1527                 ah = wsi->u.hdr.ah;
1528
1529                 lws_union_transition(wsi, LWSCM_HTTP2_SERVING);
1530
1531                 /* http2 union member has http union struct at start */
1532                 wsi->u.http.ah = ah;
1533
1534                 lws_http2_init(&wsi->u.http2.peer_settings);
1535                 lws_http2_init(&wsi->u.http2.my_settings);
1536
1537                 /* HTTP2 union */
1538
1539                 lws_http2_interpret_settings_payload(&wsi->u.http2.peer_settings,
1540                                 (unsigned char *)protocol_list, n);
1541
1542                 strcpy(protocol_list,
1543                        "HTTP/1.1 101 Switching Protocols\x0d\x0a"
1544                       "Connection: Upgrade\x0d\x0a"
1545                       "Upgrade: h2c\x0d\x0a\x0d\x0a");
1546                 n = lws_issue_raw(wsi, (unsigned char *)protocol_list,
1547                                         strlen(protocol_list));
1548                 if (n != strlen(protocol_list)) {
1549                         lwsl_debug("http2 switch: ERROR writing to socket\n");
1550                         return 1;
1551                 }
1552
1553                 wsi->state = LWSS_HTTP2_AWAIT_CLIENT_PREFACE;
1554
1555                 return 0;
1556 #endif
1557
1558 upgrade_ws:
1559                 if (!wsi->protocol)
1560                         lwsl_err("NULL protocol at lws_read\n");
1561
1562                 /*
1563                  * It's websocket
1564                  *
1565                  * Select the first protocol we support from the list
1566                  * the client sent us.
1567                  *
1568                  * Copy it to remove header fragmentation
1569                  */
1570
1571                 if (lws_hdr_copy(wsi, protocol_list, sizeof(protocol_list) - 1,
1572                                  WSI_TOKEN_PROTOCOL) < 0) {
1573                         lwsl_err("protocol list too long");
1574                         goto bail_nuke_ah;
1575                 }
1576
1577                 protocol_len = lws_hdr_total_length(wsi, WSI_TOKEN_PROTOCOL);
1578                 protocol_list[protocol_len] = '\0';
1579                 p = protocol_list;
1580                 hit = 0;
1581
1582                 while (*p && !hit) {
1583                         n = 0;
1584                         non_space_char_found = 0;
1585                         while (n < sizeof(protocol_name) - 1 && *p &&
1586                                *p != ',') {
1587                                 // ignore leading spaces
1588                                 if (!non_space_char_found && *p == ' ') {
1589                                         n++;
1590                                         continue;
1591                                 }
1592                                 non_space_char_found = 1;
1593                                 protocol_name[n++] = *p++;
1594                         }
1595                         protocol_name[n] = '\0';
1596                         if (*p)
1597                                 p++;
1598
1599                         lwsl_info("checking %s\n", protocol_name);
1600
1601                         n = 0;
1602                         while (wsi->vhost->protocols[n].callback) {
1603                                 lwsl_info("try %s\n", wsi->vhost->protocols[n].name);
1604
1605                                 if (wsi->vhost->protocols[n].name &&
1606                                     !strcmp(wsi->vhost->protocols[n].name,
1607                                             protocol_name)) {
1608                                         wsi->protocol = &wsi->vhost->protocols[n];
1609                                         hit = 1;
1610                                         break;
1611                                 }
1612
1613                                 n++;
1614                         }
1615                 }
1616
1617                 /* we didn't find a protocol he wanted? */
1618
1619                 if (!hit) {
1620                         if (lws_hdr_simple_ptr(wsi, WSI_TOKEN_PROTOCOL)) {
1621                                 lwsl_info("No protocol from \"%s\" supported\n",
1622                                          protocol_list);
1623                                 goto bail_nuke_ah;
1624                         }
1625                         /*
1626                          * some clients only have one protocol and
1627                          * do not send the protocol list header...
1628                          * allow it and match to the vhost's default
1629                          * protocol (which itself defaults to zero)
1630                          */
1631                         lwsl_info("defaulting to prot handler %d\n",
1632                                 wsi->vhost->default_protocol_index);
1633                         n = wsi->vhost->default_protocol_index;
1634                         wsi->protocol = &wsi->vhost->protocols[
1635                                       (int)wsi->vhost->default_protocol_index];
1636                 }
1637
1638                 /* allocate wsi->user storage */
1639                 if (lws_ensure_user_space(wsi))
1640                         goto bail_nuke_ah;
1641
1642                 /*
1643                  * Give the user code a chance to study the request and
1644                  * have the opportunity to deny it
1645                  */
1646                 if ((wsi->protocol->callback)(wsi,
1647                                 LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION,
1648                                 wsi->user_space,
1649                               lws_hdr_simple_ptr(wsi, WSI_TOKEN_PROTOCOL), 0)) {
1650                         lwsl_warn("User code denied connection\n");
1651                         goto bail_nuke_ah;
1652                 }
1653
1654                 /*
1655                  * Perform the handshake according to the protocol version the
1656                  * client announced
1657                  */
1658
1659                 switch (wsi->ietf_spec_revision) {
1660                 case 13:
1661                         lwsl_parser("lws_parse calling handshake_04\n");
1662                         if (handshake_0405(context, wsi)) {
1663                                 lwsl_info("hs0405 has failed the connection\n");
1664                                 goto bail_nuke_ah;
1665                         }
1666                         break;
1667
1668                 default:
1669                         lwsl_info("Unknown client spec version %d\n",
1670                                   wsi->ietf_spec_revision);
1671                         goto bail_nuke_ah;
1672                 }
1673
1674                 lws_same_vh_protocol_insert(wsi, n);
1675
1676                 /* we are upgrading to ws, so http/1.1 and keepalive +
1677                  * pipelined header considerations about keeping the ah around
1678                  * no longer apply.  However it's common for the first ws
1679                  * protocol data to have been coalesced with the browser
1680                  * upgrade request and to already be in the ah rx buffer.
1681                  */
1682
1683                 lwsl_info("%s: %p: inheriting ah in ws mode (rxpos:%d, rxlen:%d)\n",
1684                           __func__, wsi, wsi->u.hdr.ah->rxpos,
1685                           wsi->u.hdr.ah->rxlen);
1686                 lws_pt_lock(pt);
1687                 hdr = wsi->u.hdr;
1688
1689                 lws_union_transition(wsi, LWSCM_WS_SERVING);
1690                 /*
1691                  * first service is WS mode will notice this, use the RX and
1692                  * then detach the ah (caution: we are not in u.hdr union
1693                  * mode any more then... ah_temp member is at start the same
1694                  * though)
1695                  *
1696                  * Because rxpos/rxlen shows something in the ah, we will get
1697                  * service guaranteed next time around the event loop
1698                  *
1699                  * All union members begin with hdr, so we can use it even
1700                  * though we transitioned to ws union mode (the ah detach
1701                  * code uses it anyway).
1702                  */
1703                 wsi->u.hdr = hdr;
1704                 lws_pt_unlock(pt);
1705
1706                 lws_server_init_wsi_for_ws(wsi);
1707                 lwsl_parser("accepted v%02d connection\n",
1708                             wsi->ietf_spec_revision);
1709
1710                 /* !!! drop ah unreservedly after ESTABLISHED */
1711                 if (!wsi->more_rx_waiting) {
1712                         lws_header_table_force_to_detachable_state(wsi);
1713
1714                         //lwsl_notice("%p: dropping ah EST\n", wsi);
1715                         lws_header_table_detach(wsi, 1);
1716                 }
1717
1718                 return 0;
1719         } /* while all chars are handled */
1720
1721         return 0;
1722
1723 bail_nuke_ah:
1724         /* drop the header info */
1725         /* we're closing, losing some rx is OK */
1726         lws_header_table_force_to_detachable_state(wsi);
1727         //lwsl_notice("%s: drop2\n", __func__);
1728         lws_header_table_detach(wsi, 1);
1729
1730         return 1;
1731 }
1732
1733 static int
1734 lws_get_idlest_tsi(struct lws_context *context)
1735 {
1736         unsigned int lowest = ~0;
1737         int n = 0, hit = -1;
1738
1739         for (; n < context->count_threads; n++) {
1740                 if ((unsigned int)context->pt[n].fds_count !=
1741                     context->fd_limit_per_thread - 1 &&
1742                     (unsigned int)context->pt[n].fds_count < lowest) {
1743                         lowest = context->pt[n].fds_count;
1744                         hit = n;
1745                 }
1746         }
1747
1748         return hit;
1749 }
1750
1751 struct lws *
1752 lws_create_new_server_wsi(struct lws_vhost *vhost)
1753 {
1754         struct lws *new_wsi;
1755         int n = lws_get_idlest_tsi(vhost->context);
1756
1757         if (n < 0) {
1758                 lwsl_err("no space for new conn\n");
1759                 return NULL;
1760         }
1761
1762         new_wsi = lws_zalloc(sizeof(struct lws));
1763         if (new_wsi == NULL) {
1764                 lwsl_err("Out of memory for new connection\n");
1765                 return NULL;
1766         }
1767
1768         new_wsi->tsi = n;
1769         lwsl_debug("Accepted wsi %p to context %p, tsi %d\n", new_wsi,
1770                     vhost->context, new_wsi->tsi);
1771
1772         new_wsi->vhost = vhost;
1773         new_wsi->context = vhost->context;
1774         new_wsi->pending_timeout = NO_PENDING_TIMEOUT;
1775         new_wsi->rxflow_change_to = LWS_RXFLOW_ALLOW;
1776
1777         /* initialize the instance struct */
1778
1779         new_wsi->state = LWSS_HTTP;
1780         new_wsi->mode = LWSCM_HTTP_SERVING;
1781         new_wsi->hdr_parsing_completed = 0;
1782
1783 #ifdef LWS_OPENSSL_SUPPORT
1784         new_wsi->use_ssl = LWS_SSL_ENABLED(vhost);
1785 #endif
1786
1787         /*
1788          * these can only be set once the protocol is known
1789          * we set an unestablished connection's protocol pointer
1790          * to the start of the supported list, so it can look
1791          * for matching ones during the handshake
1792          */
1793         new_wsi->protocol = vhost->protocols;
1794         new_wsi->user_space = NULL;
1795         new_wsi->ietf_spec_revision = 0;
1796         new_wsi->desc.sockfd = LWS_SOCK_INVALID;
1797         new_wsi->position_in_fds_table = -1;
1798
1799         vhost->context->count_wsi_allocated++;
1800
1801         /*
1802          * outermost create notification for wsi
1803          * no user_space because no protocol selection
1804          */
1805         vhost->protocols[0].callback(new_wsi, LWS_CALLBACK_WSI_CREATE,
1806                                        NULL, NULL, 0);
1807
1808         return new_wsi;
1809 }
1810
1811 LWS_VISIBLE int LWS_WARN_UNUSED_RESULT
1812 lws_http_transaction_completed(struct lws *wsi)
1813 {
1814         int n = NO_PENDING_TIMEOUT;
1815
1816         lws_access_log(wsi);
1817
1818         if (!wsi->hdr_parsing_completed) {
1819                 lwsl_notice("%s: ignoring, ah parsing incomplete\n", __func__);
1820                 return 0;
1821         }
1822
1823         lwsl_debug("%s: wsi %p\n", __func__, wsi);
1824         /* if we can't go back to accept new headers, drop the connection */
1825         if (wsi->u.http.connection_type != HTTP_CONNECTION_KEEP_ALIVE) {
1826                 lwsl_info("%s: %p: close connection\n", __func__, wsi);
1827                 return 1;
1828         }
1829
1830         if (lws_bind_protocol(wsi, &wsi->vhost->protocols[0]))
1831                 return 1;
1832
1833         /* otherwise set ourselves up ready to go again */
1834         wsi->state = LWSS_HTTP;
1835         wsi->mode = LWSCM_HTTP_SERVING;
1836         wsi->u.http.content_length = 0;
1837         wsi->u.http.content_remain = 0;
1838         wsi->hdr_parsing_completed = 0;
1839 #ifdef LWS_WITH_ACCESS_LOG
1840         wsi->access_log.sent = 0;
1841 #endif
1842
1843         if (wsi->vhost->keepalive_timeout)
1844                 n = PENDING_TIMEOUT_HTTP_KEEPALIVE_IDLE;
1845         lws_set_timeout(wsi, n, wsi->vhost->keepalive_timeout);
1846
1847         /*
1848          * We already know we are on http1.1 / keepalive and the next thing
1849          * coming will be another header set.
1850          *
1851          * If there is no pending rx and we still have the ah, drop it and
1852          * reacquire a new ah when the new headers start to arrive.  (Otherwise
1853          * we needlessly hog an ah indefinitely.)
1854          *
1855          * However if there is pending rx and we know from the keepalive state
1856          * that is already at least the start of another header set, simply
1857          * reset the existing header table and keep it.
1858          */
1859         if (wsi->u.hdr.ah) {
1860                 lwsl_info("%s: wsi->more_rx_waiting=%d\n", __func__,
1861                                 wsi->more_rx_waiting);
1862
1863                 if (!wsi->more_rx_waiting) {
1864                         lws_header_table_force_to_detachable_state(wsi);
1865                         lws_header_table_detach(wsi, 1);
1866 #ifdef LWS_OPENSSL_SUPPORT
1867                         /*
1868                          * additionally... if we are hogging an SSL instance
1869                          * with no pending pipelined headers (or ah now), and
1870                          * SSL is scarce, drop this connection without waiting
1871                          */
1872
1873                         if (wsi->vhost->use_ssl &&
1874                             wsi->context->simultaneous_ssl_restriction &&
1875                             wsi->context->simultaneous_ssl ==
1876                                    wsi->context->simultaneous_ssl_restriction) {
1877                                 lwsl_info("%s: simultaneous_ssl_restriction and nothing pipelined\n", __func__);
1878                                 return 1;
1879                         }
1880 #endif
1881                 } else
1882                         lws_header_table_reset(wsi, 1);
1883         }
1884
1885         /* If we're (re)starting on headers, need other implied init */
1886         wsi->u.hdr.ues = URIES_IDLE;
1887
1888         lwsl_info("%s: %p: keep-alive await new transaction\n", __func__, wsi);
1889
1890         return 0;
1891 }
1892
1893 /* if not a socket, it's a raw, non-ssl file descriptor */
1894
1895 LWS_VISIBLE struct lws *
1896 lws_adopt_descriptor_vhost(struct lws_vhost *vh, lws_adoption_type type,
1897                            lws_sock_file_fd_type fd, const char *vh_prot_name,
1898                            struct lws *parent)
1899 {
1900         struct lws_context *context = vh->context;
1901         struct lws *new_wsi = lws_create_new_server_wsi(vh);
1902         struct lws_context_per_thread *pt;
1903         int n, ssl = 0;
1904
1905         if (!new_wsi) {
1906                 if (type & LWS_ADOPT_SOCKET && !(type & LWS_ADOPT_WS_PARENTIO))
1907                         compatible_close(fd.sockfd);
1908                 return NULL;
1909         }
1910         pt = &context->pt[(int)new_wsi->tsi];
1911         lws_stats_atomic_bump(context, pt, LWSSTATS_C_CONNECTIONS, 1);
1912
1913         if (parent) {
1914                 new_wsi->parent = parent;
1915                 new_wsi->sibling_list = parent->child_list;
1916                 parent->child_list = new_wsi;
1917
1918                 if (type & LWS_ADOPT_WS_PARENTIO)
1919                         new_wsi->parent_carries_io = 1;
1920         }
1921
1922         new_wsi->desc = fd;
1923
1924         if (vh_prot_name) {
1925                 new_wsi->protocol = lws_vhost_name_to_protocol(new_wsi->vhost,
1926                                                                vh_prot_name);
1927                 if (!new_wsi->protocol) {
1928                         lwsl_err("Protocol %s not enabled on vhost %s\n",
1929                                  vh_prot_name, new_wsi->vhost->name);
1930                         goto bail;
1931                 }
1932                if (lws_ensure_user_space(new_wsi)) {
1933                        lwsl_notice("OOM trying to get user_space\n");
1934                         goto bail;
1935                }
1936                if (type & LWS_ADOPT_WS_PARENTIO) {
1937                         new_wsi->desc.sockfd = LWS_SOCK_INVALID;
1938                         lwsl_debug("binding to %s\n", new_wsi->protocol->name);
1939                         lws_bind_protocol(new_wsi, new_wsi->protocol);
1940                         lws_union_transition(new_wsi, LWSCM_WS_SERVING);
1941                         lws_server_init_wsi_for_ws(new_wsi);
1942
1943                         return new_wsi;
1944                }
1945         } else
1946                 if (type & LWS_ADOPT_HTTP) /* he will transition later */
1947                         new_wsi->protocol =
1948                                 &vh->protocols[vh->default_protocol_index];
1949                 else { /* this is the only time he will transition */
1950                         lws_bind_protocol(new_wsi,
1951                                 &vh->protocols[vh->raw_protocol_index]);
1952                         lws_union_transition(new_wsi, LWSCM_RAW);
1953                 }
1954
1955         if (type & LWS_ADOPT_SOCKET) { /* socket desc */
1956                 lwsl_debug("%s: new wsi %p, sockfd %d\n", __func__, new_wsi,
1957                            (int)(lws_intptr_t)fd.sockfd);
1958
1959                 if (type & LWS_ADOPT_HTTP)
1960                         /* the transport is accepted...
1961                          * give him time to negotiate */
1962                         lws_set_timeout(new_wsi,
1963                                         PENDING_TIMEOUT_ESTABLISH_WITH_SERVER,
1964                                         context->timeout_secs);
1965
1966 #if LWS_POSIX == 0
1967 #if defined(LWS_WITH_ESP8266)
1968                 esp8266_tcp_stream_accept(accept_fd, new_wsi);
1969 #endif
1970 #endif
1971         } else /* file desc */
1972                 lwsl_debug("%s: new wsi %p, filefd %d\n", __func__, new_wsi,
1973                            (int)(lws_intptr_t)fd.filefd);
1974
1975         /*
1976          * A new connection was accepted. Give the user a chance to
1977          * set properties of the newly created wsi. There's no protocol
1978          * selected yet so we issue this to the vhosts's default protocol,
1979          * itself by default protocols[0]
1980          */
1981         n = LWS_CALLBACK_SERVER_NEW_CLIENT_INSTANTIATED;
1982         if (!(type & LWS_ADOPT_HTTP)) {
1983                 if (!(type & LWS_ADOPT_SOCKET))
1984                         n = LWS_CALLBACK_RAW_ADOPT_FILE;
1985                 else
1986                         n = LWS_CALLBACK_RAW_ADOPT;
1987         }
1988
1989         if (!LWS_SSL_ENABLED(new_wsi->vhost) || !(type & LWS_ADOPT_ALLOW_SSL) ||
1990             !(type & LWS_ADOPT_SOCKET)) {
1991                 /* non-SSL */
1992                 if (!(type & LWS_ADOPT_HTTP)) {
1993                         if (!(type & LWS_ADOPT_SOCKET))
1994                                 new_wsi->mode = LWSCM_RAW_FILEDESC;
1995                         else
1996                                 new_wsi->mode = LWSCM_RAW;
1997                 }
1998         } else {
1999                 /* SSL */
2000                 if (!(type & LWS_ADOPT_HTTP))
2001                         new_wsi->mode = LWSCM_SSL_INIT_RAW;
2002                 else
2003                         new_wsi->mode = LWSCM_SSL_INIT;
2004
2005                 ssl = 1;
2006         }
2007
2008         lws_libev_accept(new_wsi, new_wsi->desc);
2009         lws_libuv_accept(new_wsi, new_wsi->desc);
2010         lws_libevent_accept(new_wsi, new_wsi->desc);
2011
2012         if (!ssl) {
2013                 if (insert_wsi_socket_into_fds(context, new_wsi)) {
2014                         lwsl_err("%s: fail inserting socket\n", __func__);
2015                         goto fail;
2016                 }
2017         } else
2018                 if (lws_server_socket_service_ssl(new_wsi, fd.sockfd)) {
2019                         lwsl_err("%s: fail ssl negotiation\n", __func__);
2020                         goto fail;
2021                 }
2022
2023         /*
2024          *  by deferring callback to this point, after insertion to fds,
2025          * lws_callback_on_writable() can work from the callback
2026          */
2027         if ((new_wsi->protocol->callback)(
2028                         new_wsi, n, new_wsi->user_space, NULL, 0))
2029                 goto fail;
2030
2031         if (type & LWS_ADOPT_HTTP) {
2032                 if (!lws_header_table_attach(new_wsi, 0)) {
2033                         lwsl_debug("Attached ah immediately\n");
2034                 } else {
2035                         lwsl_notice("%s: waiting for ah\n", __func__);
2036                 }
2037         }
2038
2039         return new_wsi;
2040
2041 fail:
2042         if (type & LWS_ADOPT_SOCKET)
2043                 lws_close_free_wsi(new_wsi, LWS_CLOSE_STATUS_NOSTATUS);
2044
2045         return NULL;
2046
2047 bail:
2048        lwsl_notice("%s: exiting on bail\n", __func__);
2049         if (parent)
2050                 parent->child_list = new_wsi->sibling_list;
2051         if (new_wsi->user_space)
2052                 lws_free(new_wsi->user_space);
2053         lws_free(new_wsi);
2054        compatible_close(fd.sockfd);
2055
2056         return NULL;
2057 }
2058
2059 LWS_VISIBLE struct lws *
2060 lws_adopt_socket_vhost(struct lws_vhost *vh, lws_sockfd_type accept_fd)
2061 {
2062         lws_sock_file_fd_type fd;
2063
2064         fd.sockfd = accept_fd;
2065         return lws_adopt_descriptor_vhost(vh, LWS_ADOPT_SOCKET |
2066                         LWS_ADOPT_HTTP | LWS_ADOPT_ALLOW_SSL, fd, NULL, NULL);
2067 }
2068
2069 LWS_VISIBLE struct lws *
2070 lws_adopt_socket(struct lws_context *context, lws_sockfd_type accept_fd)
2071 {
2072         return lws_adopt_socket_vhost(context->vhost_list, accept_fd);
2073 }
2074
2075 /* Common read-buffer adoption for lws_adopt_*_readbuf */
2076 static struct lws*
2077 adopt_socket_readbuf(struct lws *wsi, const char *readbuf, size_t len)
2078 {
2079         struct lws_context_per_thread *pt;
2080         struct allocated_headers *ah;
2081         struct lws_pollfd *pfd;
2082
2083         if (!wsi)
2084                 return NULL;
2085
2086         if (!readbuf || len == 0)
2087                 return wsi;
2088
2089         if (len > sizeof(ah->rx)) {
2090                 lwsl_err("%s: rx in too big\n", __func__);
2091                 goto bail;
2092         }
2093
2094         /*
2095          * we can't process the initial read data until we can attach an ah.
2096          *
2097          * if one is available, get it and place the data in his ah rxbuf...
2098          * wsi with ah that have pending rxbuf get auto-POLLIN service.
2099          *
2100          * no autoservice because we didn't get a chance to attach the
2101          * readbuf data to wsi or ah yet, and we will do it next if we get
2102          * the ah.
2103          */
2104         if (wsi->u.hdr.ah || !lws_header_table_attach(wsi, 0)) {
2105                 ah = wsi->u.hdr.ah;
2106                 memcpy(ah->rx, readbuf, len);
2107                 ah->rxpos = 0;
2108                 ah->rxlen = len;
2109
2110                 lwsl_notice("%s: calling service on readbuf ah\n", __func__);
2111                 pt = &wsi->context->pt[(int)wsi->tsi];
2112
2113                 /* unlike a normal connect, we have the headers already
2114                  * (or the first part of them anyway).
2115                  * libuv won't come back and service us without a network
2116                  * event, so we need to do the header service right here.
2117                  */
2118                 pfd = &pt->fds[wsi->position_in_fds_table];
2119                 pfd->revents |= LWS_POLLIN;
2120                 lwsl_err("%s: calling service\n", __func__);
2121                 if (lws_service_fd_tsi(wsi->context, pfd, wsi->tsi))
2122                         /* service closed us */
2123                         return NULL;
2124
2125                 return wsi;
2126         }
2127         lwsl_err("%s: deferring handling ah\n", __func__);
2128         /*
2129          * hum if no ah came, we are on the wait list and must defer
2130          * dealing with this until the ah arrives.
2131          *
2132          * later successful lws_header_table_attach() will apply the
2133          * below to the rx buffer (via lws_header_table_reset()).
2134          */
2135         wsi->u.hdr.preamble_rx = lws_malloc(len);
2136         if (!wsi->u.hdr.preamble_rx) {
2137                 lwsl_err("OOM\n");
2138                 goto bail;
2139         }
2140         memcpy(wsi->u.hdr.preamble_rx, readbuf, len);
2141         wsi->u.hdr.preamble_rx_len = len;
2142
2143         return wsi;
2144
2145 bail:
2146         lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
2147
2148         return NULL;
2149 }
2150
2151 LWS_VISIBLE struct lws *
2152 lws_adopt_socket_readbuf(struct lws_context *context, lws_sockfd_type accept_fd,
2153                          const char *readbuf, size_t len)
2154 {
2155         return adopt_socket_readbuf(lws_adopt_socket(context, accept_fd), readbuf, len);
2156 }
2157
2158 LWS_VISIBLE struct lws *
2159 lws_adopt_socket_vhost_readbuf(struct lws_vhost *vhost, lws_sockfd_type accept_fd,
2160                          const char *readbuf, size_t len)
2161 {
2162         return adopt_socket_readbuf(lws_adopt_socket_vhost(vhost, accept_fd), readbuf, len);
2163 }
2164
2165 LWS_VISIBLE int
2166 lws_server_socket_service(struct lws_context *context, struct lws *wsi,
2167                           struct lws_pollfd *pollfd)
2168 {
2169         struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
2170         lws_sockfd_type accept_fd = LWS_SOCK_INVALID;
2171         struct allocated_headers *ah;
2172         lws_sock_file_fd_type fd;
2173         int opts = LWS_ADOPT_SOCKET | LWS_ADOPT_ALLOW_SSL;
2174 #if LWS_POSIX
2175         struct sockaddr_storage cli_addr;
2176         socklen_t clilen;
2177 #endif
2178         int n, len;
2179         
2180         // lwsl_notice("%s: mode %d\n", __func__, wsi->mode);
2181
2182         switch (wsi->mode) {
2183
2184         case LWSCM_HTTP_SERVING:
2185         case LWSCM_HTTP_SERVING_ACCEPTED:
2186         case LWSCM_HTTP2_SERVING:
2187         case LWSCM_RAW:
2188
2189                 /* handle http headers coming in */
2190
2191                 /* pending truncated sends have uber priority */
2192
2193                 if (wsi->trunc_len) {
2194                         if (!(pollfd->revents & LWS_POLLOUT))
2195                                 break;
2196
2197                         if (lws_issue_raw(wsi, wsi->trunc_alloc +
2198                                                wsi->trunc_offset,
2199                                           wsi->trunc_len) < 0)
2200                                 goto fail;
2201                         /*
2202                          * we can't afford to allow input processing to send
2203                          * something new, so spin around he event loop until
2204                          * he doesn't have any partials
2205                          */
2206                         break;
2207                 }
2208
2209                 /* any incoming data ready? */
2210
2211                 if (!(pollfd->revents & pollfd->events & LWS_POLLIN))
2212                         goto try_pollout;
2213
2214                 /*
2215                  * If we previously just did POLLIN when IN and OUT were
2216                  * signalled (because POLLIN processing may have used up
2217                  * the POLLOUT), don't let that happen twice in a row...
2218                  * next time we see the situation favour POLLOUT
2219                  */
2220 #if !defined(LWS_WITH_ESP8266)
2221                 if (wsi->favoured_pollin &&
2222                     (pollfd->revents & pollfd->events & LWS_POLLOUT)) {
2223                         wsi->favoured_pollin = 0;
2224                         goto try_pollout;
2225                 }
2226 #endif
2227
2228                 /* these states imply we MUST have an ah attached */
2229
2230                 if (wsi->mode != LWSCM_RAW && (wsi->state == LWSS_HTTP ||
2231                     wsi->state == LWSS_HTTP_ISSUING_FILE ||
2232                     wsi->state == LWSS_HTTP_HEADERS)) {
2233                         if (!wsi->u.hdr.ah) {
2234                                 
2235                                 //lwsl_err("wsi %p: missing ah\n", wsi);
2236                                 /* no autoservice beacuse we will do it next */
2237                                 if (lws_header_table_attach(wsi, 0)) {
2238                                         lwsl_info("wsi %p: failed to acquire ah\n", wsi);
2239                                         goto try_pollout;
2240                                 }
2241                         }
2242                         ah = wsi->u.hdr.ah;
2243
2244                         //lwsl_notice("%s: %p: rxpos:%d rxlen:%d\n", __func__, wsi,
2245                         //         ah->rxpos, ah->rxlen);
2246
2247                         /* if nothing in ah rx buffer, get some fresh rx */
2248                         if (ah->rxpos == ah->rxlen) {
2249                                 ah->rxlen = lws_ssl_capable_read(wsi, ah->rx,
2250                                                    sizeof(ah->rx));
2251                                 ah->rxpos = 0;
2252                                 //lwsl_notice("%s: wsi %p, ah->rxlen = %d\r\n",
2253                                 //         __func__, wsi, ah->rxlen);
2254                                 switch (ah->rxlen) {
2255                                 case 0:
2256                                         lwsl_info("%s: read 0 len\n", __func__);
2257                                         /* lwsl_info("   state=%d\n", wsi->state); */
2258 //                                      if (!wsi->hdr_parsing_completed)
2259 //                                              lws_header_table_detach(wsi);
2260                                         /* fallthru */
2261                                 case LWS_SSL_CAPABLE_ERROR:
2262                                         goto fail;
2263                                 case LWS_SSL_CAPABLE_MORE_SERVICE:
2264                                         ah->rxlen = ah->rxpos = 0;
2265                                         goto try_pollout;
2266                                 }
2267
2268                                 /*
2269                                  *  make sure ah does not get detached if we
2270                                  * have live data in the rx
2271                                  */
2272                                 if (ah->rxlen)
2273                                         wsi->more_rx_waiting = 1;
2274                         }
2275
2276                         if (!(ah->rxpos != ah->rxlen && ah->rxlen)) {
2277                                 lwsl_err("%s: assert: rxpos %d, rxlen %d\n",
2278                                          __func__, ah->rxpos, ah->rxlen);
2279
2280                                 assert(0);
2281                         }
2282                         
2283                         /* just ignore incoming if waiting for close */
2284                         if (wsi->state != LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE &&
2285                             wsi->state != LWSS_HTTP_ISSUING_FILE) {
2286                                 n = lws_read(wsi, ah->rx + ah->rxpos,
2287                                              ah->rxlen - ah->rxpos);
2288                                 if (n < 0) /* we closed wsi */
2289                                         return 1;
2290                                 if (wsi->u.hdr.ah) {
2291                                         if ( wsi->u.hdr.ah->rxlen)
2292                                                  wsi->u.hdr.ah->rxpos += n;
2293
2294                                         lwsl_debug("%s: wsi %p: ah read rxpos %d, rxlen %d\n", __func__, wsi, wsi->u.hdr.ah->rxpos, wsi->u.hdr.ah->rxlen);
2295
2296                                         if (lws_header_table_is_in_detachable_state(wsi) &&
2297                                             (wsi->mode != LWSCM_HTTP_SERVING &&
2298                                              wsi->mode != LWSCM_HTTP_SERVING_ACCEPTED &&
2299                                              wsi->mode != LWSCM_HTTP2_SERVING))
2300                                                 lws_header_table_detach(wsi, 1);
2301                                 }
2302                                 break;
2303                         }
2304
2305                         goto try_pollout;
2306                 }
2307
2308                 len = lws_ssl_capable_read(wsi, pt->serv_buf,
2309                                            context->pt_serv_buf_size);
2310                 lwsl_debug("%s: wsi %p read %d\r\n", __func__, wsi, len);
2311                 switch (len) {
2312                 case 0:
2313                         lwsl_info("%s: read 0 len\n", __func__);
2314                         /* lwsl_info("   state=%d\n", wsi->state); */
2315 //                      if (!wsi->hdr_parsing_completed)
2316 //                              lws_header_table_detach(wsi);
2317                         /* fallthru */
2318                 case LWS_SSL_CAPABLE_ERROR:
2319                         goto fail;
2320                 case LWS_SSL_CAPABLE_MORE_SERVICE:
2321                         goto try_pollout;
2322                 }
2323                 
2324                 if (wsi->mode == LWSCM_RAW) {
2325                         n = user_callback_handle_rxflow(wsi->protocol->callback,
2326                                         wsi, LWS_CALLBACK_RAW_RX,
2327                                         wsi->user_space, pt->serv_buf, len);
2328                         if (n < 0) {
2329                                 lwsl_info("LWS_CALLBACK_RAW_RX_fail\n");
2330                                 goto fail;
2331                         }
2332                         goto try_pollout;
2333                 }
2334
2335                 /* just ignore incoming if waiting for close */
2336                 if (wsi->state != LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE &&
2337                     wsi->state != LWSS_HTTP_ISSUING_FILE) {
2338                         /*
2339                          * this may want to send
2340                          * (via HTTP callback for example)
2341                          */
2342                         n = lws_read(wsi, pt->serv_buf, len);
2343                         if (n < 0) /* we closed wsi */
2344                                 return 1;
2345                         /*
2346                          *  he may have used up the
2347                          * writability above, if we will defer POLLOUT
2348                          * processing in favour of POLLIN, note it
2349                          */
2350                         if (pollfd->revents & LWS_POLLOUT)
2351                                 wsi->favoured_pollin = 1;
2352                         break;
2353                 }
2354
2355 try_pollout:
2356                 
2357                 /* this handles POLLOUT for http serving fragments */
2358
2359                 if (!(pollfd->revents & LWS_POLLOUT))
2360                         break;
2361
2362                 /* one shot */
2363                 if (lws_change_pollfd(wsi, LWS_POLLOUT, 0)) {
2364                         lwsl_notice("%s a\n", __func__);
2365                         goto fail;
2366                 }
2367
2368                 if (wsi->mode == LWSCM_RAW) {
2369                         lws_stats_atomic_bump(wsi->context, pt, LWSSTATS_C_WRITEABLE_CB, 1);
2370 #if defined(LWS_WITH_STATS)
2371                         {
2372                                 uint64_t ul = time_in_microseconds() - wsi->active_writable_req_us;
2373
2374                                 lws_stats_atomic_bump(wsi->context, pt, LWSSTATS_MS_WRITABLE_DELAY, ul);
2375                                 lws_stats_atomic_max(wsi->context, pt, LWSSTATS_MS_WORST_WRITABLE_DELAY, ul);
2376                                 wsi->active_writable_req_us = 0;
2377                         }
2378 #endif
2379                         n = user_callback_handle_rxflow(wsi->protocol->callback,
2380                                         wsi, LWS_CALLBACK_RAW_WRITEABLE,
2381                                         wsi->user_space, NULL, 0);
2382                         if (n < 0) {
2383                                 lwsl_info("writeable_fail\n");
2384                                 goto fail;
2385                         }
2386                         break;
2387                 }
2388
2389                 if (!wsi->hdr_parsing_completed)
2390                         break;
2391
2392                 if (wsi->state != LWSS_HTTP_ISSUING_FILE) {
2393
2394                         lws_stats_atomic_bump(wsi->context, pt, LWSSTATS_C_WRITEABLE_CB, 1);
2395 #if defined(LWS_WITH_STATS)
2396                         {
2397                                 uint64_t ul = time_in_microseconds() - wsi->active_writable_req_us;
2398
2399                                 lws_stats_atomic_bump(wsi->context, pt, LWSSTATS_MS_WRITABLE_DELAY, ul);
2400                                 lws_stats_atomic_max(wsi->context, pt, LWSSTATS_MS_WORST_WRITABLE_DELAY, ul);
2401                                 wsi->active_writable_req_us = 0;
2402                         }
2403 #endif
2404
2405                         n = user_callback_handle_rxflow(wsi->protocol->callback,
2406                                         wsi, LWS_CALLBACK_HTTP_WRITEABLE,
2407                                         wsi->user_space, NULL, 0);
2408                         if (n < 0) {
2409                                 lwsl_info("writeable_fail\n");
2410                                 goto fail;
2411                         }
2412                         break;
2413                 }
2414
2415                 /* >0 == completion, <0 == error
2416                  *
2417                  * We'll get a LWS_CALLBACK_HTTP_FILE_COMPLETION callback when
2418                  * it's done.  That's the case even if we just completed the
2419                  * send, so wait for that.
2420                  */
2421                 n = lws_serve_http_file_fragment(wsi);
2422                 if (n < 0)
2423                         goto fail;
2424
2425                 break;
2426
2427         case LWSCM_SERVER_LISTENER:
2428
2429 #if LWS_POSIX
2430                 /* pollin means a client has connected to us then */
2431
2432                 do {
2433                         if (!(pollfd->revents & LWS_POLLIN) || !(pollfd->events & LWS_POLLIN))
2434                                 break;
2435
2436 #ifdef LWS_OPENSSL_SUPPORT
2437                         /*
2438                          * can we really accept it, with regards to SSL limit?
2439                          * another vhost may also have had POLLIN on his listener this
2440                          * round and used it up already
2441                          */
2442
2443                         if (wsi->vhost->use_ssl &&
2444                             context->simultaneous_ssl_restriction &&
2445                             context->simultaneous_ssl ==
2446                                           context->simultaneous_ssl_restriction)
2447                                 /* no... ignore it, he won't come again until we are
2448                                  * below the simultaneous_ssl_restriction limit and
2449                                  * POLLIN is enabled on him again
2450                                  */
2451                                 break;
2452 #endif
2453                         /* listen socket got an unencrypted connection... */
2454
2455                         clilen = sizeof(cli_addr);
2456                         lws_latency_pre(context, wsi);
2457                         accept_fd  = accept(pollfd->fd, (struct sockaddr *)&cli_addr,
2458                                             &clilen);
2459                         lws_latency(context, wsi, "listener accept", accept_fd,
2460                                     accept_fd >= 0);
2461                         if (accept_fd < 0) {
2462                                 if (LWS_ERRNO == LWS_EAGAIN ||
2463                                     LWS_ERRNO == LWS_EWOULDBLOCK) {
2464 //                                      lwsl_err("accept asks to try again\n");
2465                                         break;
2466                                 }
2467                                 lwsl_err("ERROR on accept: %s\n", strerror(LWS_ERRNO));
2468                                 break;
2469                         }
2470
2471                         lws_plat_set_socket_options(wsi->vhost, accept_fd);
2472
2473 #if defined(LWS_USE_IPV6)
2474                         lwsl_debug("accepted new conn port %u on fd=%d\n",
2475                                           ((cli_addr.ss_family == AF_INET6) ?
2476                                           ntohs(((struct sockaddr_in6 *) &cli_addr)->sin6_port) :
2477                                           ntohs(((struct sockaddr_in *) &cli_addr)->sin_port)),
2478                                           accept_fd);
2479 #else
2480                         lwsl_debug("accepted new conn port %u on fd=%d\n",
2481                                           ntohs(((struct sockaddr_in *) &cli_addr)->sin_port),
2482                                           accept_fd);
2483 #endif
2484
2485 #else
2486                         /* not very beautiful... */
2487                         accept_fd = (lws_sockfd_type)pollfd;
2488 #endif
2489                         /*
2490                          * look at who we connected to and give user code a chance
2491                          * to reject based on client IP.  There's no protocol selected
2492                          * yet so we issue this to protocols[0]
2493                          */
2494                         if ((wsi->vhost->protocols[0].callback)(wsi,
2495                                         LWS_CALLBACK_FILTER_NETWORK_CONNECTION,
2496                                         NULL, (void *)(lws_intptr_t)accept_fd, 0)) {
2497                                 lwsl_debug("Callback denied network connection\n");
2498                                 compatible_close(accept_fd);
2499                                 break;
2500                         }
2501
2502                         if (!(wsi->vhost->options & LWS_SERVER_OPTION_ONLY_RAW))
2503                                 opts |= LWS_ADOPT_HTTP;
2504
2505                         fd.sockfd = accept_fd;
2506                         if (!lws_adopt_descriptor_vhost(wsi->vhost, opts, fd,
2507                                                         NULL, NULL))
2508                                 /* already closed cleanly as necessary */
2509                                 return 1;
2510
2511 #if LWS_POSIX
2512                 } while (pt->fds_count < context->fd_limit_per_thread - 1 &&
2513                          lws_poll_listen_fd(&pt->fds[wsi->position_in_fds_table]) > 0);
2514 #endif
2515                 return 0;
2516
2517         default:
2518                 break;
2519         }
2520
2521         if (!lws_server_socket_service_ssl(wsi, accept_fd))
2522                 return 0;
2523
2524 fail:
2525         lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
2526
2527         return 1;
2528 }
2529
2530 LWS_VISIBLE int
2531 lws_serve_http_file(struct lws *wsi, const char *file, const char *content_type,
2532                     const char *other_headers, int other_headers_len)
2533 {
2534         static const char * const intermediates[] = { "private", "public" };
2535         struct lws_context *context = lws_get_context(wsi);
2536         struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
2537 #if defined(LWS_WITH_RANGES)
2538         struct lws_range_parsing *rp = &wsi->u.http.range;
2539 #endif
2540         char cache_control[50], *cc = "no-store";
2541         unsigned char *response = pt->serv_buf + LWS_PRE;
2542         unsigned char *p = response;
2543         unsigned char *end = p + context->pt_serv_buf_size - LWS_PRE;
2544         lws_filepos_t computed_total_content_length;
2545         int ret = 0, cclen = 8, n = HTTP_STATUS_OK;
2546         lws_fop_flags_t fflags = LWS_O_RDONLY;
2547 #if defined(LWS_WITH_RANGES)
2548         int ranges;
2549 #endif
2550         const struct lws_plat_file_ops *fops;
2551         const char *vpath;
2552
2553         /*
2554          * We either call the platform fops .open with first arg platform fops,
2555          * or we call fops_zip .open with first arg platform fops, and fops_zip
2556          * open will decide whether to switch to fops_zip or stay with fops_def.
2557          *
2558          * If wsi->u.http.fop_fd is already set, the caller already opened it
2559          */
2560         if (!wsi->u.http.fop_fd) {
2561                 fops = lws_vfs_select_fops(wsi->context->fops, file, &vpath);
2562                 fflags |= lws_vfs_prepare_flags(wsi);
2563                 wsi->u.http.fop_fd = fops->LWS_FOP_OPEN(wsi->context->fops,
2564                                                         file, vpath, &fflags);
2565                 if (!wsi->u.http.fop_fd) {
2566                         lwsl_err("Unable to open '%s'\n", file);
2567
2568                         return -1;
2569                 }
2570         }
2571         wsi->u.http.filelen = lws_vfs_get_length(wsi->u.http.fop_fd);
2572         computed_total_content_length = wsi->u.http.filelen;
2573
2574 #if defined(LWS_WITH_RANGES)
2575         ranges = lws_ranges_init(wsi, rp, wsi->u.http.filelen);
2576
2577         lwsl_debug("Range count %d\n", ranges);
2578         /*
2579          * no ranges -> 200;
2580          *  1 range  -> 206 + Content-Type: normal; Content-Range;
2581          *  more     -> 206 + Content-Type: multipart/byteranges
2582          *              Repeat the true Content-Type in each multipart header
2583          *              along with Content-Range
2584          */
2585         if (ranges < 0) {
2586                 /* it means he expressed a range in Range:, but it was illegal */
2587                 lws_return_http_status(wsi, HTTP_STATUS_REQ_RANGE_NOT_SATISFIABLE, NULL);
2588                 if (lws_http_transaction_completed(wsi))
2589                         return -1; /* <0 means just hang up */
2590
2591                 lws_vfs_file_close(&wsi->u.http.fop_fd);
2592
2593                 return 0; /* == 0 means we dealt with the transaction complete */
2594         }
2595         if (ranges)
2596                 n = HTTP_STATUS_PARTIAL_CONTENT;
2597 #endif
2598
2599         if (lws_add_http_header_status(wsi, n, &p, end))
2600                 return -1;
2601
2602         if ((wsi->u.http.fop_fd->flags & (LWS_FOP_FLAG_COMPR_ACCEPTABLE_GZIP |
2603                        LWS_FOP_FLAG_COMPR_IS_GZIP)) ==
2604             (LWS_FOP_FLAG_COMPR_ACCEPTABLE_GZIP | LWS_FOP_FLAG_COMPR_IS_GZIP)) {
2605                 if (lws_add_http_header_by_token(wsi,
2606                         WSI_TOKEN_HTTP_CONTENT_ENCODING,
2607                         (unsigned char *)"gzip", 4, &p, end))
2608                         return -1;
2609                 lwsl_info("file is being provided in gzip\n");
2610         }
2611
2612 #if defined(LWS_WITH_RANGES)
2613         if (ranges < 2 && content_type && content_type[0])
2614                 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE,
2615                                                  (unsigned char *)content_type,
2616                                                  strlen(content_type), &p, end))
2617                         return -1;
2618
2619         if (ranges >= 2) { /* multipart byteranges */
2620                 strncpy(wsi->u.http.multipart_content_type, content_type,
2621                         sizeof(wsi->u.http.multipart_content_type) - 1);
2622                 wsi->u.http.multipart_content_type[
2623                          sizeof(wsi->u.http.multipart_content_type) - 1] = '\0';
2624                 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE,
2625                                                  (unsigned char *)"multipart/byteranges; boundary=_lws",
2626                                                  20, &p, end))
2627                         return -1;
2628
2629                 /*
2630                  *  our overall content length has to include
2631                  *
2632                  *  - (n + 1) x "_lws\r\n"
2633                  *  - n x Content-Type: xxx/xxx\r\n
2634                  *  - n x Content-Range: bytes xxx-yyy/zzz\r\n
2635                  *  - n x /r/n
2636                  *  - the actual payloads (aggregated in rp->agg)
2637                  *
2638                  *  Precompute it for the main response header
2639                  */
2640
2641                 computed_total_content_length = (lws_filepos_t)rp->agg +
2642                                                 6 /* final _lws\r\n */;
2643
2644                 lws_ranges_reset(rp);
2645                 while (lws_ranges_next(rp)) {
2646                         n = lws_snprintf(cache_control, sizeof(cache_control),
2647                                         "bytes %llu-%llu/%llu",
2648                                         rp->start, rp->end, rp->extent);
2649
2650                         computed_total_content_length +=
2651                                         6 /* header _lws\r\n */ +
2652                                         14 + strlen(content_type) + 2 + /* Content-Type: xxx/xxx\r\n */
2653                                         15 + n + 2 + /* Content-Range: xxxx\r\n */
2654                                         2; /* /r/n */
2655                 }
2656
2657                 lws_ranges_reset(rp);
2658                 lws_ranges_next(rp);
2659         }
2660
2661         if (ranges == 1) {
2662                 computed_total_content_length = (lws_filepos_t)rp->agg;
2663                 n = lws_snprintf(cache_control, sizeof(cache_control), "bytes %llu-%llu/%llu",
2664                                 rp->start, rp->end, rp->extent);
2665
2666                 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_CONTENT_RANGE,
2667                                                  (unsigned char *)cache_control,
2668                                                  n, &p, end))
2669                         return -1;
2670         }
2671
2672         wsi->u.http.range.inside = 0;
2673
2674         if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_ACCEPT_RANGES,
2675                                          (unsigned char *)"bytes", 5, &p, end))
2676                 return -1;
2677 #endif
2678
2679         if (!wsi->sending_chunked) {
2680                 if (lws_add_http_header_content_length(wsi,
2681                                                        computed_total_content_length,
2682                                                        &p, end))
2683                         return -1;
2684         } else {
2685                 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_TRANSFER_ENCODING,
2686                                                  (unsigned char *)"chunked",
2687                                                  7, &p, end))
2688                         return -1;
2689         }
2690
2691         if (wsi->cache_secs && wsi->cache_reuse) {
2692                 if (wsi->cache_revalidate) {
2693                         cc = cache_control;
2694                         cclen = sprintf(cache_control, "%s max-age: %u",
2695                                     intermediates[wsi->cache_intermediaries],
2696                                     wsi->cache_secs);
2697                 } else {
2698                         cc = "no-cache";
2699                         cclen = 8;
2700                 }
2701         }
2702
2703         if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_CACHE_CONTROL,
2704                         (unsigned char *)cc, cclen, &p, end))
2705                 return -1;
2706
2707         if (wsi->u.http.connection_type == HTTP_CONNECTION_KEEP_ALIVE)
2708                 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_CONNECTION,
2709                                 (unsigned char *)"keep-alive", 10, &p, end))
2710                         return -1;
2711
2712         if (other_headers) {
2713                 if ((end - p) < other_headers_len)
2714                         return -1;
2715                 memcpy(p, other_headers, other_headers_len);
2716                 p += other_headers_len;
2717         }
2718
2719         if (lws_finalize_http_header(wsi, &p, end))
2720                 return -1;
2721
2722         ret = lws_write(wsi, response, p - response, LWS_WRITE_HTTP_HEADERS);
2723         if (ret != (p - response)) {
2724                 lwsl_err("_write returned %d from %ld\n", ret, (long)(p - response));
2725                 return -1;
2726         }
2727
2728         wsi->u.http.filepos = 0;
2729         wsi->state = LWSS_HTTP_ISSUING_FILE;
2730
2731         return lws_serve_http_file_fragment(wsi);
2732 }
2733
2734 int
2735 lws_interpret_incoming_packet(struct lws *wsi, unsigned char **buf, size_t len)
2736 {
2737         int m;
2738
2739         lwsl_parser("%s: received %d byte packet\n", __func__, (int)len);
2740 #if 0
2741         lwsl_hexdump(*buf, len);
2742 #endif
2743
2744         /* let the rx protocol state machine have as much as it needs */
2745
2746         while (len) {
2747                 /*
2748                  * we were accepting input but now we stopped doing so
2749                  */
2750                 if (!(wsi->rxflow_change_to & LWS_RXFLOW_ALLOW)) {
2751                         lws_rxflow_cache(wsi, *buf, 0, len);
2752                         lwsl_parser("%s: cached %ld\n", __func__, (long)len);
2753                         return 1;
2754                 }
2755
2756                 if (wsi->u.ws.rx_draining_ext) {
2757                         // lwsl_notice("draining with 0\n");
2758                         m = lws_rx_sm(wsi, 0);
2759                         if (m < 0)
2760                                 return -1;
2761                         continue;
2762                 }
2763
2764                 /* account for what we're using in rxflow buffer */
2765                 if (wsi->rxflow_buffer)
2766                         wsi->rxflow_pos++;
2767
2768                 /* consume payload bytes efficiently */
2769                 if (
2770                     wsi->lws_rx_parse_state ==
2771                     LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED) {
2772                         m = lws_payload_until_length_exhausted(wsi, buf, &len);
2773                         if (wsi->rxflow_buffer)
2774                                 wsi->rxflow_pos += m;
2775                 }
2776
2777                 /* process the byte */
2778                 m = lws_rx_sm(wsi, *(*buf)++);
2779                 if (m < 0)
2780                         return -1;
2781                 len--;
2782         }
2783
2784         lwsl_parser("%s: exit with %d unused\n", __func__, (int)len);
2785
2786         return 0;
2787 }
2788
2789 LWS_VISIBLE void
2790 lws_server_get_canonical_hostname(struct lws_context *context,
2791                                   struct lws_context_creation_info *info)
2792 {
2793         if (lws_check_opt(info->options, LWS_SERVER_OPTION_SKIP_SERVER_CANONICAL_NAME))
2794                 return;
2795 #if LWS_POSIX && !defined(LWS_WITH_ESP32)
2796         /* find canonical hostname */
2797         gethostname((char *)context->canonical_hostname,
2798                     sizeof(context->canonical_hostname) - 1);
2799
2800         lwsl_notice(" canonical_hostname = %s\n", context->canonical_hostname);
2801 #else
2802         (void)context;
2803 #endif
2804 }
2805
2806 #define LWS_MAX_ELEM_NAME 32
2807
2808 enum urldecode_stateful {
2809         US_NAME,
2810         US_IDLE,
2811         US_PC1,
2812         US_PC2,
2813
2814         MT_LOOK_BOUND_IN,
2815         MT_HNAME,
2816         MT_DISP,
2817         MT_TYPE,
2818         MT_IGNORE1,
2819         MT_IGNORE2,
2820 };
2821
2822 static const char * const mp_hdr[] = {
2823         "content-disposition: ",
2824         "content-type: ",
2825         "\x0d\x0a"
2826 };
2827
2828 typedef int (*lws_urldecode_stateful_cb)(void *data,
2829                 const char *name, char **buf, int len, int final);
2830
2831 struct lws_urldecode_stateful {
2832         char *out;
2833         void *data;
2834         char name[LWS_MAX_ELEM_NAME];
2835         char temp[LWS_MAX_ELEM_NAME];
2836         char content_type[32];
2837         char content_disp[32];
2838         char content_disp_filename[256];
2839         char mime_boundary[128];
2840         int out_len;
2841         int pos;
2842         int hdr_idx;
2843         int mp;
2844         int sum;
2845
2846         unsigned int multipart_form_data:1;
2847         unsigned int inside_quote:1;
2848         unsigned int subname:1;
2849         unsigned int boundary_real_crlf:1;
2850
2851         enum urldecode_stateful state;
2852
2853         lws_urldecode_stateful_cb output;
2854 };
2855
2856 static struct lws_urldecode_stateful *
2857 lws_urldecode_s_create(struct lws *wsi, char *out, int out_len, void *data,
2858                        lws_urldecode_stateful_cb output)
2859 {
2860         struct lws_urldecode_stateful *s = lws_zalloc(sizeof(*s));
2861         char buf[200], *p;
2862         int m = 0;
2863
2864         if (!s)
2865                 return NULL;
2866
2867         s->out = out;
2868         s->out_len  = out_len;
2869         s->output = output;
2870         s->pos = 0;
2871         s->sum = 0;
2872         s->mp = 0;
2873         s->state = US_NAME;
2874         s->name[0] = '\0';
2875         s->data = data;
2876
2877         if (lws_hdr_copy(wsi, buf, sizeof(buf), WSI_TOKEN_HTTP_CONTENT_TYPE) > 0) {
2878                 /* multipart/form-data; boundary=----WebKitFormBoundarycc7YgAPEIHvgE9Bf */
2879
2880                 if (!strncmp(buf, "multipart/form-data", 19)) {
2881                         s->multipart_form_data = 1;
2882                         s->state = MT_LOOK_BOUND_IN;
2883                         s->mp = 2;
2884                         p = strstr(buf, "boundary=");
2885                         if (p) {
2886                                 p += 9;
2887                                 s->mime_boundary[m++] = '\x0d';
2888                                 s->mime_boundary[m++] = '\x0a';
2889                                 s->mime_boundary[m++] = '-';
2890                                 s->mime_boundary[m++] = '-';
2891                                 while (m < sizeof(s->mime_boundary) - 1 &&
2892                                        *p && *p != ' ')
2893                                         s->mime_boundary[m++] = *p++;
2894
2895                                 s->mime_boundary[m] = '\0';
2896
2897                                 lwsl_notice("boundary '%s'\n", s->mime_boundary);
2898                         }
2899                 }
2900         }
2901
2902         return s;
2903 }
2904
2905 static int
2906 lws_urldecode_s_process(struct lws_urldecode_stateful *s, const char *in, int len)
2907 {
2908         int n, m, hit = 0;
2909         char c, was_end = 0;
2910
2911         while (len--) {
2912                 if (s->pos == s->out_len - s->mp - 1) {
2913                         if (s->output(s->data, s->name, &s->out, s->pos, 0))
2914                                 return -1;
2915
2916                         was_end = s->pos;
2917                         s->pos = 0;
2918                 }
2919                 switch (s->state) {
2920
2921                 /* states for url arg style */
2922
2923                 case US_NAME:
2924                         s->inside_quote = 0;
2925                         if (*in == '=') {
2926                                 s->name[s->pos] = '\0';
2927                                 s->pos = 0;
2928                                 s->state = US_IDLE;
2929                                 in++;
2930                                 continue;
2931                         }
2932                         if (*in == '&') {
2933                                 s->name[s->pos] = '\0';
2934                                 if (s->output(s->data, s->name, &s->out, s->pos, 1))
2935                                         return -1;
2936                                 s->pos = 0;
2937                                 s->state = US_IDLE;
2938                                 in++;
2939                                 continue;
2940                         }
2941                         if (s->pos >= sizeof(s->name) - 1) {
2942                                 lwsl_notice("Name too long\n");
2943                                 return -1;
2944                         }
2945                         s->name[s->pos++] = *in++;
2946                         break;
2947                 case US_IDLE:
2948                         if (*in == '%') {
2949                                 s->state++;
2950                                 in++;
2951                                 continue;
2952                         }
2953                         if (*in == '&') {
2954                                 s->out[s->pos] = '\0';
2955                                 if (s->output(s->data, s->name, &s->out, s->pos, 1))
2956                                         return -1;
2957                                 s->pos = 0;
2958                                 s->state = US_NAME;
2959                                 in++;
2960                                 continue;
2961                         }
2962                         if (*in == '+') {
2963                                 in++;
2964                                 s->out[s->pos++] = ' ';
2965                                 continue;
2966                         }
2967                         s->out[s->pos++] = *in++;
2968                         break;
2969                 case US_PC1:
2970                         n = char_to_hex(*in);
2971                         if (n < 0)
2972                                 return -1;
2973
2974                         in++;
2975                         s->sum = n << 4;
2976                         s->state++;
2977                         break;
2978
2979                 case US_PC2:
2980                         n = char_to_hex(*in);
2981                         if (n < 0)
2982                                 return -1;
2983
2984                         in++;
2985                         s->out[s->pos++] = s->sum | n;
2986                         s->state = US_IDLE;
2987                         break;
2988
2989
2990                 /* states for multipart / mime style */
2991
2992                 case MT_LOOK_BOUND_IN:
2993 retry_as_first:
2994                         if (*in == s->mime_boundary[s->mp] &&
2995                             s->mime_boundary[s->mp]) {
2996                                 in++;
2997                                 s->mp++;
2998                                 if (!s->mime_boundary[s->mp]) {
2999                                         s->mp = 0;
3000                                         s->state = MT_IGNORE1;
3001
3002                                         if (s->pos || was_end)
3003                                                 if (s->output(s->data, s->name,
3004                                                       &s->out, s->pos, 1))
3005                                                         return -1;
3006
3007                                         s->pos = 0;
3008
3009                                         s->content_disp[0] = '\0';
3010                                         s->name[0] = '\0';
3011                                         s->content_disp_filename[0] = '\0';
3012                                         s->boundary_real_crlf = 1;
3013                                 }
3014                                 continue;
3015                         }
3016                         if (s->mp) {
3017                                 n = 0;
3018                                 if (!s->boundary_real_crlf)
3019                                         n = 2;
3020
3021                                 memcpy(s->out + s->pos, s->mime_boundary + n, s->mp - n);
3022                                 s->pos += s->mp;
3023                                 s->mp = 0;
3024                                 goto retry_as_first;
3025                         }
3026
3027                         s->out[s->pos++] = *in;
3028                         in++;
3029                         s->mp = 0;
3030                         break;
3031
3032                 case MT_HNAME:
3033                         m = 0;
3034                         c =*in;
3035                         if (c >= 'A' && c <= 'Z')
3036                                 c += 'a' - 'A';
3037                         for (n = 0; n < ARRAY_SIZE(mp_hdr); n++)
3038                                 if (c == mp_hdr[n][s->mp]) {
3039                                         m++;
3040                                         hit = n;
3041                                 }
3042                         in++;
3043                         if (!m) {
3044                                 s->mp = 0;
3045                                 continue;
3046                         }
3047
3048                         s->mp++;
3049                         if (m != 1)
3050                                 continue;
3051
3052                         if (mp_hdr[hit][s->mp])
3053                                 continue;
3054
3055                         s->mp = 0;
3056                         s->temp[0] = '\0';
3057                         s->subname = 0;
3058
3059                         if (hit == 2)
3060                                 s->state = MT_LOOK_BOUND_IN;
3061                         else
3062                                 s->state += hit + 1;
3063                         break;
3064
3065                 case MT_DISP:
3066                         /* form-data; name="file"; filename="t.txt" */
3067
3068                         if (*in == '\x0d') {
3069 //                              lwsl_notice("disp: '%s', '%s', '%s'\n",
3070 //                                 s->content_disp, s->name,
3071 //                                 s->content_disp_filename);
3072
3073                                 if (s->content_disp_filename[0])
3074                                         if (s->output(s->data, s->name,
3075                                                       &s->out, s->pos, LWS_UFS_OPEN))
3076                                                 return -1;
3077                                 s->state = MT_IGNORE2;
3078                                 goto done;
3079                         }
3080                         if (*in == ';') {
3081                                 s->subname = 1;
3082                                 s->temp[0] = '\0';
3083                                 s->mp = 0;
3084                                 goto done;
3085                         }
3086
3087                         if (*in == '\"') {
3088                                 s->inside_quote ^= 1;
3089                                 goto done;
3090                         }
3091
3092                         if (s->subname) {
3093                                 if (*in == '=') {
3094                                         s->temp[s->mp] = '\0';
3095                                         s->subname = 0;
3096                                         s->mp = 0;
3097                                         goto done;
3098                                 }
3099                                 if (s->mp < sizeof(s->temp) - 1 &&
3100                                     (*in != ' ' || s->inside_quote))
3101                                         s->temp[s->mp++] = *in;
3102                                 goto done;
3103                         }
3104
3105                         if (!s->temp[0]) {
3106                                 if (s->mp < sizeof(s->content_disp) - 1)
3107                                         s->content_disp[s->mp++] = *in;
3108                                 s->content_disp[s->mp] = '\0';
3109                                 goto done;
3110                         }
3111
3112                         if (!strcmp(s->temp, "name")) {
3113                                 if (s->mp < sizeof(s->name) - 1)
3114                                         s->name[s->mp++] = *in;
3115                                 s->name[s->mp] = '\0';
3116                                 goto done;
3117                         }
3118
3119                         if (!strcmp(s->temp, "filename")) {
3120                                 if (s->mp < sizeof(s->content_disp_filename) - 1)
3121                                         s->content_disp_filename[s->mp++] = *in;
3122                                 s->content_disp_filename[s->mp] = '\0';
3123                                 goto done;
3124                         }
3125 done:
3126                         in++;
3127                         break;
3128
3129                 case MT_TYPE:
3130                         if (*in == '\x0d')
3131                                 s->state = MT_IGNORE2;
3132                         else {
3133                                 if (s->mp < sizeof(s->content_type) - 1)
3134                                         s->content_type[s->mp++] = *in;
3135                                 s->content_type[s->mp] = '\0';
3136                         }
3137                         in++;
3138                         break;
3139
3140                 case MT_IGNORE1:
3141                         if (*in == '\x0d')
3142                                 s->state = MT_IGNORE2;
3143                         in++;
3144                         break;
3145
3146                 case MT_IGNORE2:
3147                         s->mp = 0;
3148                         if (*in == '\x0a')
3149                                 s->state = MT_HNAME;
3150                         in++;
3151                         break;
3152                 }
3153         }
3154
3155         return 0;
3156 }
3157
3158 static int
3159 lws_urldecode_s_destroy(struct lws_urldecode_stateful *s)
3160 {
3161         int ret = 0;
3162
3163         if (s->state != US_IDLE)
3164                 ret = -1;
3165
3166         if (!ret)
3167                 if (s->output(s->data, s->name, &s->out, s->pos, 1))
3168                         ret = -1;
3169
3170         lws_free(s);
3171
3172         return ret;
3173 }
3174
3175 struct lws_spa {
3176         struct lws_urldecode_stateful *s;
3177         lws_spa_fileupload_cb opt_cb;
3178         const char * const *param_names;
3179         int count_params;
3180         char **params;
3181         int *param_length;
3182         void *opt_data;
3183
3184         char *storage;
3185         char *end;
3186         int max_storage;
3187
3188         char finalized;
3189 };
3190
3191 static int
3192 lws_urldecode_spa_lookup(struct lws_spa *spa,
3193                          const char *name)
3194 {
3195         int n;
3196
3197         for (n = 0; n < spa->count_params; n++)
3198                 if (!strcmp(spa->param_names[n], name))
3199                         return n;
3200
3201         return -1;
3202 }
3203
3204 static int
3205 lws_urldecode_spa_cb(void *data, const char *name, char **buf, int len,
3206                      int final)
3207 {
3208         struct lws_spa *spa =
3209                         (struct lws_spa *)data;
3210         int n;
3211
3212         if (spa->s->content_disp_filename[0]) {
3213                 if (spa->opt_cb) {
3214                         n = spa->opt_cb(spa->opt_data, name,
3215                                         spa->s->content_disp_filename,
3216                                         *buf, len, final);
3217
3218                         if (n < 0)
3219                                 return -1;
3220                 }
3221                 return 0;
3222         }
3223         n = lws_urldecode_spa_lookup(spa, name);
3224
3225         if (n == -1 || !len) /* unrecognized */
3226                 return 0;
3227
3228         if (!spa->params[n])
3229                 spa->params[n] = *buf;
3230
3231         if ((*buf) + len >= spa->end) {
3232                 lwsl_notice("%s: exceeded storage\n", __func__);
3233                 return -1;
3234         }
3235
3236         spa->param_length[n] += len;
3237
3238         /* move it on inside storage */
3239         (*buf) += len;
3240         *((*buf)++) = '\0';
3241
3242         spa->s->out_len -= len + 1;
3243
3244         return 0;
3245 }
3246
3247 LWS_VISIBLE LWS_EXTERN struct lws_spa *
3248 lws_spa_create(struct lws *wsi, const char * const *param_names,
3249                          int count_params, int max_storage,
3250                          lws_spa_fileupload_cb opt_cb, void *opt_data)
3251 {
3252         struct lws_spa *spa = lws_zalloc(sizeof(*spa));
3253
3254         if (!spa)
3255                 return NULL;
3256
3257         spa->param_names = param_names;
3258         spa->count_params = count_params;
3259         spa->max_storage = max_storage;
3260         spa->opt_cb = opt_cb;
3261         spa->opt_data = opt_data;
3262
3263         spa->storage = lws_malloc(max_storage);
3264         if (!spa->storage)
3265                 goto bail2;
3266         spa->end = spa->storage + max_storage - 1;
3267
3268         spa->params = lws_zalloc(sizeof(char *) * count_params);
3269         if (!spa->params)
3270                 goto bail3;
3271
3272         spa->s = lws_urldecode_s_create(wsi, spa->storage, max_storage, spa,
3273                                         lws_urldecode_spa_cb);
3274         if (!spa->s)
3275                 goto bail4;
3276
3277         spa->param_length = lws_zalloc(sizeof(int) * count_params);
3278         if (!spa->param_length)
3279                 goto bail5;
3280
3281         lwsl_info("%s: Created SPA %p\n", __func__, spa);
3282
3283         return spa;
3284
3285 bail5:
3286         lws_urldecode_s_destroy(spa->s);
3287 bail4:
3288         lws_free(spa->params);
3289 bail3:
3290         lws_free(spa->storage);
3291 bail2:
3292         lws_free(spa);
3293
3294         return NULL;
3295 }
3296
3297 LWS_VISIBLE LWS_EXTERN int
3298 lws_spa_process(struct lws_spa *ludspa, const char *in, int len)
3299 {
3300         if (!ludspa) {
3301                 lwsl_err("%s: NULL spa\n", __func__);
3302                 return -1;
3303         }
3304         /* we reject any junk after the last part arrived and we finalized */
3305         if (ludspa->finalized)
3306                 return 0;
3307
3308         return lws_urldecode_s_process(ludspa->s, in, len);
3309 }
3310
3311 LWS_VISIBLE LWS_EXTERN int
3312 lws_spa_get_length(struct lws_spa *ludspa, int n)
3313 {
3314         if (n >= ludspa->count_params)
3315                 return 0;
3316
3317         return ludspa->param_length[n];
3318 }
3319
3320 LWS_VISIBLE LWS_EXTERN const char *
3321 lws_spa_get_string(struct lws_spa *ludspa, int n)
3322 {
3323         if (n >= ludspa->count_params)
3324                 return NULL;
3325
3326         return ludspa->params[n];
3327 }
3328
3329 LWS_VISIBLE LWS_EXTERN int
3330 lws_spa_finalize(struct lws_spa *spa)
3331 {
3332         if (spa->s) {
3333                 lws_urldecode_s_destroy(spa->s);
3334                 spa->s = NULL;
3335         }
3336
3337         spa->finalized = 1;
3338
3339         return 0;
3340 }
3341
3342 LWS_VISIBLE LWS_EXTERN int
3343 lws_spa_destroy(struct lws_spa *spa)
3344 {
3345         int n = 0;
3346
3347         lwsl_notice("%s: destroy spa %p\n", __func__, spa);
3348
3349         if (spa->s)
3350                 lws_urldecode_s_destroy(spa->s);
3351
3352         lwsl_debug("%s %p %p %p %p\n", __func__,
3353                         spa->param_length,
3354                         spa->params,
3355                         spa->storage,
3356                         spa
3357                         );
3358
3359         lws_free(spa->param_length);
3360         lws_free(spa->params);
3361         lws_free(spa->storage);
3362         lws_free(spa);
3363
3364         return n;
3365 }
3366
3367 #if 0
3368 LWS_VISIBLE LWS_EXTERN int
3369 lws_spa_destroy(struct lws_spa *spa)
3370 {
3371         int n = 0;
3372
3373         lwsl_info("%s: destroy spa %p\n", __func__, spa);
3374
3375         if (spa->s)
3376                 lws_urldecode_s_destroy(spa->s);
3377
3378         lwsl_debug("%s\n", __func__);
3379
3380         lws_free(spa->param_length);
3381         lws_free(spa->params);
3382         lws_free(spa->storage);
3383         lws_free(spa);
3384
3385         return n;
3386 }
3387 #endif
3388 LWS_VISIBLE LWS_EXTERN int
3389 lws_chunked_html_process(struct lws_process_html_args *args,
3390                          struct lws_process_html_state *s)
3391 {
3392         char *sp, buffer[32];
3393         const char *pc;
3394         int old_len, n;
3395
3396         /* do replacements */
3397         sp = args->p;
3398         old_len = args->len;
3399         args->len = 0;
3400         s->start = sp;
3401         while (sp < args->p + old_len) {
3402
3403                 if (args->len + 7 >= args->max_len) {
3404                         lwsl_err("Used up interpret padding\n");
3405                         return -1;
3406                 }
3407
3408                 if ((!s->pos && *sp == '$') || s->pos) {
3409                         int hits = 0, hit = 0;
3410
3411                         if (!s->pos)
3412                                 s->start = sp;
3413                         s->swallow[s->pos++] = *sp;
3414                         if (s->pos == sizeof(s->swallow) - 1)
3415                                 goto skip;
3416                         for (n = 0; n < s->count_vars; n++)
3417                                 if (!strncmp(s->swallow, s->vars[n], s->pos)) {
3418                                         hits++;
3419                                         hit = n;
3420                                 }
3421                         if (!hits) {
3422 skip:
3423                                 s->swallow[s->pos] = '\0';
3424                                 memcpy(s->start, s->swallow, s->pos);
3425                                 args->len++;
3426                                 s->pos = 0;
3427                                 sp = s->start + 1;
3428                                 continue;
3429                         }
3430                         if (hits == 1 && s->pos == strlen(s->vars[hit])) {
3431                                 pc = s->replace(s->data, hit);
3432                                 if (!pc)
3433                                         pc = "NULL";
3434                                 n = strlen(pc);
3435                                 s->swallow[s->pos] = '\0';
3436                                 if (n != s->pos) {
3437                                         memmove(s->start + n,
3438                                                 s->start + s->pos,
3439                                                 old_len - (sp - args->p));
3440                                         old_len += (n - s->pos) + 1;
3441                                 }
3442                                 memcpy(s->start, pc, n);
3443                                 args->len++;
3444                                 sp = s->start + 1;
3445
3446                                 s->pos = 0;
3447                         }
3448                         sp++;
3449                         continue;
3450                 }
3451
3452                 args->len++;
3453                 sp++;
3454         }
3455
3456         /* no space left for final chunk trailer */
3457         if (args->final && args->len + 7 >= args->max_len)
3458                 return -1;
3459
3460         n = sprintf(buffer, "%X\x0d\x0a", args->len);
3461
3462         args->p -= n;
3463         memcpy(args->p, buffer, n);
3464         args->len += n;
3465
3466         if (args->final) {
3467                 sp = args->p + args->len;
3468                 *sp++ = '\x0d';
3469                 *sp++ = '\x0a';
3470                 *sp++ = '0';
3471                 *sp++ = '\x0d';
3472                 *sp++ = '\x0a';
3473                 *sp++ = '\x0d';
3474                 *sp++ = '\x0a';
3475                 args->len += 7;
3476         } else {
3477                 sp = args->p + args->len;
3478                 *sp++ = '\x0d';
3479                 *sp++ = '\x0a';
3480                 args->len += 2;
3481         }
3482
3483         return 0;
3484 }