108321d153dc648b5779cb5c67ad1ef7a9672f82
[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 || 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                         me = method_names[meth];
917
918                         lws_snprintf(wsi->access_log.header_log, l,
919                                  "%s - - [%s] \"%s %s %s\"",
920                                  pa, da, me, uri_ptr,
921                                  hver[wsi->u.http.request_version]);
922
923                         l = lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_USER_AGENT);
924                         if (l) {
925                                 wsi->access_log.user_agent = lws_malloc(l + 2);
926                                 if (wsi->access_log.user_agent)
927                                         lws_hdr_copy(wsi, wsi->access_log.user_agent,
928                                                         l + 1, WSI_TOKEN_HTTP_USER_AGENT);
929                                 else
930                                         lwsl_err("OOM getting user agent\n");
931                         }
932                         wsi->access_log_pending = 1;
933                 }
934         }
935 #endif
936
937         /* can we serve it from the mount list? */
938
939         hit = lws_find_mount(wsi, uri_ptr, uri_len);
940         if (!hit) {
941                 /* deferred cleanup and reset to protocols[0] */
942
943                 lwsl_info("no hit\n");
944
945                 if (lws_bind_protocol(wsi, &wsi->vhost->protocols[0]))
946                         return 1;
947
948                 n = wsi->protocol->callback(wsi, LWS_CALLBACK_HTTP,
949                                     wsi->user_space, uri_ptr, uri_len);
950
951                 goto after;
952         }
953
954         s = uri_ptr + hit->mountpoint_len;
955
956         /*
957          * if we have a mountpoint like https://xxx.com/yyy
958          * there is an implied / at the end for our purposes since
959          * we can only mount on a "directory".
960          *
961          * But if we just go with that, the browser cannot understand
962          * that he is actually looking down one "directory level", so
963          * even though we give him /yyy/abc.html he acts like the
964          * current directory level is /.  So relative urls like "x.png"
965          * wrongly look outside the mountpoint.
966          *
967          * Therefore if we didn't come in on a url with an explicit
968          * / at the end, we must redirect to add it so the browser
969          * understands he is one "directory level" down.
970          */
971         if ((hit->mountpoint_len > 1 ||
972              (hit->origin_protocol == LWSMPRO_REDIR_HTTP ||
973               hit->origin_protocol == LWSMPRO_REDIR_HTTPS)) &&
974             (*s != '/' ||
975              (hit->origin_protocol == LWSMPRO_REDIR_HTTP ||
976               hit->origin_protocol == LWSMPRO_REDIR_HTTPS)) &&
977             (hit->origin_protocol != LWSMPRO_CGI &&
978              hit->origin_protocol != LWSMPRO_CALLBACK //&&
979              //hit->protocol == NULL
980              )) {
981                 unsigned char *start = pt->serv_buf + LWS_PRE,
982                               *p = start, *end = p + 512;
983
984                 lwsl_debug("Doing 301 '%s' org %s\n", s, hit->origin);
985
986                 if (!lws_hdr_total_length(wsi, WSI_TOKEN_HOST))
987                         goto bail_nuke_ah;
988
989                 /* > at start indicates deal with by redirect */
990                 if (hit->origin_protocol == LWSMPRO_REDIR_HTTP ||
991                     hit->origin_protocol == LWSMPRO_REDIR_HTTPS)
992                         n = lws_snprintf((char *)end, 256, "%s%s",
993                                     oprot[hit->origin_protocol & 1],
994                                     hit->origin);
995                 else
996                         n = lws_snprintf((char *)end, 256,
997                             "%s%s%s/", oprot[!!lws_is_ssl(wsi)],
998                             lws_hdr_simple_ptr(wsi, WSI_TOKEN_HOST),
999                             uri_ptr);
1000                 lws_clean_url((char *)end);
1001
1002                 n = lws_http_redirect(wsi, HTTP_STATUS_MOVED_PERMANENTLY,
1003                                       end, n, &p, end);
1004                 if ((int)n < 0)
1005                         goto bail_nuke_ah;
1006
1007                 return lws_http_transaction_completed(wsi);
1008         }
1009
1010 #if LWS_POSIX
1011         /* basic auth? */
1012
1013         if (hit->basic_auth_login_file) {
1014                 char b64[160], plain[(sizeof(b64) * 3) / 4];
1015                 int m;
1016
1017                 /* Did he send auth? */
1018                 if (!lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_AUTHORIZATION))
1019                         return lws_unauthorised_basic_auth(wsi);
1020
1021                 n = HTTP_STATUS_FORBIDDEN;
1022
1023                 m = lws_hdr_copy(wsi, b64, sizeof(b64), WSI_TOKEN_HTTP_AUTHORIZATION);
1024                 if (m < 7) {
1025                         lwsl_err("b64 auth too long\n");
1026                         goto transaction_result_n;
1027                 }
1028
1029                 b64[5] = '\0';
1030                 if (strcasecmp(b64, "Basic")) {
1031                         lwsl_err("auth missing basic: %s\n", b64);
1032                         goto transaction_result_n;
1033                 }
1034
1035                 /* It'll be like Authorization: Basic QWxhZGRpbjpPcGVuU2VzYW1l */
1036
1037                 m = lws_b64_decode_string(b64 + 6, plain, sizeof(plain));
1038                 if (m < 0) {
1039                         lwsl_err("plain auth too long\n");
1040                         goto transaction_result_n;
1041                 }
1042
1043 //              lwsl_notice(plain);
1044
1045                 if (!lws_find_string_in_file(hit->basic_auth_login_file, plain, m)) {
1046                         lwsl_err("basic auth lookup failed\n");
1047                         return lws_unauthorised_basic_auth(wsi);
1048                 }
1049
1050                 lwsl_notice("basic auth accepted\n");
1051
1052                 /* accept the auth */
1053         }
1054 #endif
1055
1056 #if defined(LWS_WITH_HTTP_PROXY)
1057         /*
1058          * The mount is a reverse proxy?
1059          */
1060
1061         if (hit->origin_protocol == LWSMPRO_HTTPS ||
1062             hit->origin_protocol == LWSMPRO_HTTP)  {
1063                 struct lws_client_connect_info i;
1064                 char ads[96], rpath[256], *pcolon, *pslash, *p;
1065                 int n, na;
1066
1067                 memset(&i, 0, sizeof(i));
1068                 i.context = lws_get_context(wsi);
1069
1070                 pcolon = strchr(hit->origin, ':');
1071                 pslash = strchr(hit->origin, '/');
1072                 if (!pslash) {
1073                         lwsl_err("Proxy mount origin '%s' must have /\n", hit->origin);
1074                         return -1;
1075                 }
1076                 if (pcolon > pslash)
1077                         pcolon = NULL;
1078                 
1079                 if (pcolon)
1080                         n = pcolon - hit->origin;
1081                 else
1082                         n = pslash - hit->origin;
1083
1084                 if (n >= sizeof(ads) - 2)
1085                         n = sizeof(ads) - 2;
1086
1087                 memcpy(ads, hit->origin, n);
1088                 ads[n] = '\0';
1089
1090                 i.address = ads;
1091                 i.port = 80;
1092                 if (hit->origin_protocol == LWSMPRO_HTTPS) { 
1093                         i.port = 443;
1094                         i.ssl_connection = 1;
1095                 }
1096                 if (pcolon)
1097                         i.port = atoi(pcolon + 1);
1098                 
1099                 lws_snprintf(rpath, sizeof(rpath) - 1, "/%s/%s", pslash + 1, uri_ptr + hit->mountpoint_len);
1100                 lws_clean_url(rpath);
1101                 na = lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_URI_ARGS);
1102                 if (na) {
1103                         p = rpath + strlen(rpath);
1104                         *p++ = '?';
1105                         lws_hdr_copy(wsi, p, &rpath[sizeof(rpath) - 1] - p, WSI_TOKEN_HTTP_URI_ARGS);
1106                         while (--na) {
1107                                 if (*p == '\0')
1108                                         *p = '&';
1109                                 p++;
1110                         }
1111                 }
1112                                 
1113
1114                 i.path = rpath;
1115                 i.host = i.address;
1116                 i.origin = NULL;
1117                 i.method = "GET";
1118                 i.parent_wsi = wsi;
1119                 i.uri_replace_from = hit->origin;
1120                 i.uri_replace_to = hit->mountpoint;
1121
1122                 lwsl_notice("proxying to %s port %d url %s, ssl %d, from %s, to %s\n",
1123                                 i.address, i.port, i.path, i.ssl_connection, i.uri_replace_from, i.uri_replace_to);
1124         
1125                 if (!lws_client_connect_via_info(&i)) {
1126                         lwsl_err("proxy connect fail\n");
1127                         return 1;
1128                 }
1129
1130                 return 0;
1131         }
1132 #endif
1133
1134         /*
1135          * A particular protocol callback is mounted here?
1136          *
1137          * For the duration of this http transaction, bind us to the
1138          * associated protocol
1139          */
1140         if (hit->origin_protocol == LWSMPRO_CALLBACK || hit->protocol) {
1141                 const struct lws_protocols *pp;
1142                 const char *name = hit->origin;
1143                 if (hit->protocol)
1144                         name = hit->protocol;
1145
1146                 pp = lws_vhost_name_to_protocol(wsi->vhost, name);
1147                 if (!pp) {
1148                         n = -1;
1149                         lwsl_err("Unable to find plugin '%s'\n",
1150                                  hit->origin);
1151                         return 1;
1152                 }
1153
1154                 if (lws_bind_protocol(wsi, pp))
1155                         return 1;
1156
1157                 args.p = uri_ptr;
1158                 args.len = uri_len;
1159                 args.max_len = hit->auth_mask;
1160                 args.final = 0; /* used to signal callback dealt with it */
1161
1162                 n = wsi->protocol->callback(wsi, LWS_CALLBACK_CHECK_ACCESS_RIGHTS,
1163                                             wsi->user_space, &args, 0);
1164                 if (n) {
1165                         lws_return_http_status(wsi, HTTP_STATUS_UNAUTHORIZED,
1166                                                NULL);
1167                         goto bail_nuke_ah;
1168                 }
1169                 if (args.final) /* callback completely handled it well */
1170                         return 0;
1171
1172                 if (hit->cgienv && wsi->protocol->callback(wsi,
1173                                 LWS_CALLBACK_HTTP_PMO,
1174                                 wsi->user_space, (void *)hit->cgienv, 0))
1175                         return 1;
1176
1177                 if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI)) {
1178                         n = wsi->protocol->callback(wsi, LWS_CALLBACK_HTTP,
1179                                             wsi->user_space,
1180                                             uri_ptr + hit->mountpoint_len,
1181                                             uri_len - hit->mountpoint_len);
1182                         goto after;
1183                 }
1184         }
1185
1186 #ifdef LWS_WITH_CGI
1187         /* did we hit something with a cgi:// origin? */
1188         if (hit->origin_protocol == LWSMPRO_CGI) {
1189                 const char *cmd[] = {
1190                         NULL, /* replace with cgi path */
1191                         NULL
1192                 };
1193
1194                 lwsl_debug("%s: cgi\n", __func__);
1195                 cmd[0] = hit->origin;
1196
1197                 n = 5;
1198                 if (hit->cgi_timeout)
1199                         n = hit->cgi_timeout;
1200
1201                 n = lws_cgi(wsi, cmd, hit->mountpoint_len, n,
1202                             hit->cgienv);
1203                 if (n) {
1204                         lwsl_err("%s: cgi failed\n", __func__);
1205                         return -1;
1206                 }
1207
1208                 goto deal_body;
1209         }
1210 #endif
1211
1212         n = strlen(s);
1213         if (s[0] == '\0' || (n == 1 && s[n - 1] == '/'))
1214                 s = (char *)hit->def;
1215         if (!s)
1216                 s = "index.html";
1217
1218         wsi->cache_secs = hit->cache_max_age;
1219         wsi->cache_reuse = hit->cache_reusable;
1220         wsi->cache_revalidate = hit->cache_revalidate;
1221         wsi->cache_intermediaries = hit->cache_intermediaries;
1222
1223         n = lws_http_serve(wsi, s, hit->origin, hit);
1224         if (n) {
1225                 /*
1226                  *      lws_return_http_status(wsi, HTTP_STATUS_NOT_FOUND, NULL);
1227                  */
1228                 if (hit->protocol) {
1229                         const struct lws_protocols *pp = lws_vhost_name_to_protocol(
1230                                         wsi->vhost, hit->protocol);
1231
1232                         if (lws_bind_protocol(wsi, pp))
1233                                 return 1;
1234
1235                         n = pp->callback(wsi, LWS_CALLBACK_HTTP,
1236                                          wsi->user_space,
1237                                          uri_ptr + hit->mountpoint_len,
1238                                          uri_len - hit->mountpoint_len);
1239                 } else
1240                         n = wsi->protocol->callback(wsi, LWS_CALLBACK_HTTP,
1241                                     wsi->user_space, uri_ptr, uri_len);
1242         }
1243
1244 after:
1245         if (n) {
1246                 lwsl_info("LWS_CALLBACK_HTTP closing\n");
1247
1248                 return 1;
1249         }
1250
1251 #ifdef LWS_WITH_CGI
1252 deal_body:
1253 #endif
1254         /*
1255          * If we're not issuing a file, check for content_length or
1256          * HTTP keep-alive. No keep-alive header allocation for
1257          * ISSUING_FILE, as this uses HTTP/1.0.
1258          *
1259          * In any case, return 0 and let lws_read decide how to
1260          * proceed based on state
1261          */
1262         if (wsi->state != LWSS_HTTP_ISSUING_FILE)
1263                 /* Prepare to read body if we have a content length: */
1264                 if (wsi->u.http.content_length > 0)
1265                         wsi->state = LWSS_HTTP_BODY;
1266
1267         return 0;
1268
1269 bail_nuke_ah:
1270         /* we're closing, losing some rx is OK */
1271         lws_header_table_force_to_detachable_state(wsi);
1272         // lwsl_notice("%s: drop1\n", __func__);
1273         lws_header_table_detach(wsi, 1);
1274
1275         return 1;
1276 #if LWS_POSIX
1277 transaction_result_n:
1278         lws_return_http_status(wsi, n, NULL);
1279
1280         return lws_http_transaction_completed(wsi);
1281 #endif
1282 }
1283
1284 static int
1285 lws_server_init_wsi_for_ws(struct lws *wsi)
1286 {
1287         int n;
1288
1289         wsi->state = LWSS_ESTABLISHED;
1290         lws_restart_ws_ping_pong_timer(wsi);
1291
1292         /*
1293          * create the frame buffer for this connection according to the
1294          * size mentioned in the protocol definition.  If 0 there, use
1295          * a big default for compatibility
1296          */
1297
1298         n = wsi->protocol->rx_buffer_size;
1299         if (!n)
1300                 n = wsi->context->pt_serv_buf_size;
1301         n += LWS_PRE;
1302         wsi->u.ws.rx_ubuf = lws_malloc(n + 4 /* 0x0000ffff zlib */);
1303         if (!wsi->u.ws.rx_ubuf) {
1304                 lwsl_err("Out of Mem allocating rx buffer %d\n", n);
1305                 return 1;
1306         }
1307         wsi->u.ws.rx_ubuf_alloc = n;
1308         lwsl_debug("Allocating RX buffer %d\n", n);
1309
1310 #if LWS_POSIX && !defined(LWS_WITH_ESP32)
1311         if (!wsi->parent_carries_io)
1312                 if (setsockopt(wsi->desc.sockfd, SOL_SOCKET, SO_SNDBUF,
1313                        (const char *)&n, sizeof n)) {
1314                         lwsl_warn("Failed to set SNDBUF to %d", n);
1315                         return 1;
1316                 }
1317 #endif
1318
1319         /* notify user code that we're ready to roll */
1320
1321         if (wsi->protocol->callback)
1322                 if (wsi->protocol->callback(wsi, LWS_CALLBACK_ESTABLISHED,
1323                                             wsi->user_space,
1324 #ifdef LWS_OPENSSL_SUPPORT
1325                                             wsi->ssl,
1326 #else
1327                                             NULL,
1328 #endif
1329                                             0))
1330                         return 1;
1331
1332         return 0;
1333 }
1334
1335 int
1336 lws_handshake_server(struct lws *wsi, unsigned char **buf, size_t len)
1337 {
1338         int protocol_len, n = 0, hit, non_space_char_found = 0, m;
1339         struct lws_context *context = lws_get_context(wsi);
1340         struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
1341         struct _lws_header_related hdr;
1342         struct allocated_headers *ah;
1343         unsigned char *obuf = *buf;
1344         char protocol_list[128];
1345         char protocol_name[64];
1346         size_t olen = len;
1347         char *p;
1348
1349         if (len >= 10000000) {
1350                 lwsl_err("%s: assert: len %ld\n", __func__, (long)len);
1351                 assert(0);
1352         }
1353
1354         if (!wsi->u.hdr.ah) {
1355                 lwsl_err("%s: assert: NULL ah\n", __func__);
1356                 assert(0);
1357         }
1358
1359         while (len--) {
1360                 wsi->more_rx_waiting = !!len;
1361
1362                 if (wsi->mode != LWSCM_HTTP_SERVING &&
1363                     wsi->mode != LWSCM_HTTP_SERVING_ACCEPTED) {
1364                         lwsl_err("%s: bad wsi mode %d\n", __func__, wsi->mode);
1365                         goto bail_nuke_ah;
1366                 }
1367
1368                 m = lws_parse(wsi, *(*buf)++);
1369                 if (m) {
1370                         if (m == 2) {
1371                                 /*
1372                                  * we are transitioning from http with
1373                                  * an AH, to raw.  Drop the ah and set
1374                                  * the mode.
1375                                  */
1376 raw_transition:
1377                                 lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
1378                                 lws_bind_protocol(wsi, &wsi->vhost->protocols[
1379                                                         wsi->vhost->
1380                                                         raw_protocol_index]);
1381                                 lwsl_info("transition to raw vh %s prot %d\n",
1382                                           wsi->vhost->name,
1383                                           wsi->vhost->raw_protocol_index);
1384                                 if ((wsi->protocol->callback)(wsi,
1385                                                 LWS_CALLBACK_RAW_ADOPT,
1386                                                 wsi->user_space, NULL, 0))
1387                                         goto bail_nuke_ah;
1388
1389                                 lws_header_table_force_to_detachable_state(wsi);
1390                                 lws_union_transition(wsi, LWSCM_RAW);
1391                                 lws_header_table_detach(wsi, 1);
1392
1393                                 if (m == 2 && (wsi->protocol->callback)(wsi,
1394                                                 LWS_CALLBACK_RAW_RX,
1395                                                 wsi->user_space, obuf, olen))
1396                                         return 1;
1397
1398                                 return 0;
1399                         }
1400                         lwsl_info("lws_parse failed\n");
1401                         goto bail_nuke_ah;
1402                 }
1403
1404                 if (wsi->u.hdr.parser_state != WSI_PARSING_COMPLETE)
1405                         continue;
1406
1407                 lwsl_parser("%s: lws_parse sees parsing complete\n", __func__);
1408                 lwsl_debug("%s: wsi->more_rx_waiting=%d\n", __func__,
1409                                 wsi->more_rx_waiting);
1410
1411                 /* check for unwelcome guests */
1412
1413                 if (wsi->context->reject_service_keywords) {
1414                         const struct lws_protocol_vhost_options *rej =
1415                                         wsi->context->reject_service_keywords;
1416                         char ua[384], *msg = NULL;
1417
1418                         if (lws_hdr_copy(wsi, ua, sizeof(ua) - 1,
1419                                           WSI_TOKEN_HTTP_USER_AGENT) > 0) {
1420                                 ua[sizeof(ua) - 1] = '\0';
1421                                 while (rej) {
1422                                         if (strstr(ua, rej->name)) {
1423                                                 msg = strchr(rej->value, ' ');
1424                                                 if (msg)
1425                                                         msg++;
1426                                                 lws_return_http_status(wsi, atoi(rej->value), msg);
1427
1428                                                 wsi->vhost->conn_stats.rejected++;
1429
1430                                                 goto bail_nuke_ah;
1431                                         }
1432                                         rej = rej->next;
1433                                 }
1434                         }
1435                 }
1436
1437                 /* select vhost */
1438
1439                 if (lws_hdr_total_length(wsi, WSI_TOKEN_HOST)) {
1440                         struct lws_vhost *vhost = lws_select_vhost(
1441                                 context, wsi->vhost->listen_port,
1442                                 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HOST));
1443
1444                         if (vhost)
1445                                 wsi->vhost = vhost;
1446                 } else
1447                         lwsl_info("no host\n");
1448
1449                 wsi->vhost->conn_stats.trans++;
1450                 if (!wsi->conn_stat_done) {
1451                         wsi->vhost->conn_stats.conn++;
1452                         wsi->conn_stat_done = 1;
1453                 }
1454
1455                 if (lws_hdr_total_length(wsi, WSI_TOKEN_CONNECT)) {
1456                         lwsl_info("Changing to RAW mode\n");
1457                         m = 0;
1458                         goto raw_transition;
1459                 }
1460
1461                 wsi->mode = LWSCM_PRE_WS_SERVING_ACCEPT;
1462                 lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
1463
1464                 /* is this websocket protocol or normal http 1.0? */
1465
1466                 if (lws_hdr_total_length(wsi, WSI_TOKEN_UPGRADE)) {
1467                         if (!strcasecmp(lws_hdr_simple_ptr(wsi, WSI_TOKEN_UPGRADE),
1468                                         "websocket")) {
1469                                 wsi->vhost->conn_stats.ws_upg++;
1470                                 lwsl_info("Upgrade to ws\n");
1471                                 goto upgrade_ws;
1472                         }
1473 #ifdef LWS_USE_HTTP2
1474                         if (!strcasecmp(lws_hdr_simple_ptr(wsi, WSI_TOKEN_UPGRADE),
1475                                         "h2c")) {
1476                                 wsi->vhost->conn_stats.http2_upg++;
1477                                 lwsl_info("Upgrade to h2c\n");
1478                                 goto upgrade_h2c;
1479                         }
1480 #endif
1481                         lwsl_info("Unknown upgrade\n");
1482                         /* dunno what he wanted to upgrade to */
1483                         goto bail_nuke_ah;
1484                 }
1485
1486                 /* no upgrade ack... he remained as HTTP */
1487
1488                 lwsl_info("No upgrade\n");
1489                 ah = wsi->u.hdr.ah;
1490
1491                 lws_union_transition(wsi, LWSCM_HTTP_SERVING_ACCEPTED);
1492                 wsi->state = LWSS_HTTP;
1493                 wsi->u.http.fop_fd = NULL;
1494
1495                 /* expose it at the same offset as u.hdr */
1496                 wsi->u.http.ah = ah;
1497                 lwsl_debug("%s: wsi %p: ah %p\n", __func__, (void *)wsi,
1498                            (void *)wsi->u.hdr.ah);
1499
1500                 n = lws_http_action(wsi);
1501
1502                 return n;
1503
1504 #ifdef LWS_USE_HTTP2
1505 upgrade_h2c:
1506                 if (!lws_hdr_total_length(wsi, WSI_TOKEN_HTTP2_SETTINGS)) {
1507                         lwsl_info("missing http2_settings\n");
1508                         goto bail_nuke_ah;
1509                 }
1510
1511                 lwsl_info("h2c upgrade...\n");
1512
1513                 p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP2_SETTINGS);
1514                 /* convert the peer's HTTP-Settings */
1515                 n = lws_b64_decode_string(p, protocol_list,
1516                                           sizeof(protocol_list));
1517                 if (n < 0) {
1518                         lwsl_parser("HTTP2_SETTINGS too long\n");
1519                         return 1;
1520                 }
1521
1522                 /* adopt the header info */
1523
1524                 ah = wsi->u.hdr.ah;
1525
1526                 lws_union_transition(wsi, LWSCM_HTTP2_SERVING);
1527
1528                 /* http2 union member has http union struct at start */
1529                 wsi->u.http.ah = ah;
1530
1531                 lws_http2_init(&wsi->u.http2.peer_settings);
1532                 lws_http2_init(&wsi->u.http2.my_settings);
1533
1534                 /* HTTP2 union */
1535
1536                 lws_http2_interpret_settings_payload(&wsi->u.http2.peer_settings,
1537                                 (unsigned char *)protocol_list, n);
1538
1539                 strcpy(protocol_list,
1540                        "HTTP/1.1 101 Switching Protocols\x0d\x0a"
1541                       "Connection: Upgrade\x0d\x0a"
1542                       "Upgrade: h2c\x0d\x0a\x0d\x0a");
1543                 n = lws_issue_raw(wsi, (unsigned char *)protocol_list,
1544                                         strlen(protocol_list));
1545                 if (n != strlen(protocol_list)) {
1546                         lwsl_debug("http2 switch: ERROR writing to socket\n");
1547                         return 1;
1548                 }
1549
1550                 wsi->state = LWSS_HTTP2_AWAIT_CLIENT_PREFACE;
1551
1552                 return 0;
1553 #endif
1554
1555 upgrade_ws:
1556                 if (!wsi->protocol)
1557                         lwsl_err("NULL protocol at lws_read\n");
1558
1559                 /*
1560                  * It's websocket
1561                  *
1562                  * Select the first protocol we support from the list
1563                  * the client sent us.
1564                  *
1565                  * Copy it to remove header fragmentation
1566                  */
1567
1568                 if (lws_hdr_copy(wsi, protocol_list, sizeof(protocol_list) - 1,
1569                                  WSI_TOKEN_PROTOCOL) < 0) {
1570                         lwsl_err("protocol list too long");
1571                         goto bail_nuke_ah;
1572                 }
1573
1574                 protocol_len = lws_hdr_total_length(wsi, WSI_TOKEN_PROTOCOL);
1575                 protocol_list[protocol_len] = '\0';
1576                 p = protocol_list;
1577                 hit = 0;
1578
1579                 while (*p && !hit) {
1580                         n = 0;
1581                         non_space_char_found = 0;
1582                         while (n < sizeof(protocol_name) - 1 && *p &&
1583                                *p != ',') {
1584                                 // ignore leading spaces
1585                                 if (!non_space_char_found && *p == ' ') {
1586                                         n++;
1587                                         continue;
1588                                 }
1589                                 non_space_char_found = 1;
1590                                 protocol_name[n++] = *p++;
1591                         }
1592                         protocol_name[n] = '\0';
1593                         if (*p)
1594                                 p++;
1595
1596                         lwsl_info("checking %s\n", protocol_name);
1597
1598                         n = 0;
1599                         while (wsi->vhost->protocols[n].callback) {
1600                                 lwsl_info("try %s\n", wsi->vhost->protocols[n].name);
1601
1602                                 if (wsi->vhost->protocols[n].name &&
1603                                     !strcmp(wsi->vhost->protocols[n].name,
1604                                             protocol_name)) {
1605                                         wsi->protocol = &wsi->vhost->protocols[n];
1606                                         hit = 1;
1607                                         break;
1608                                 }
1609
1610                                 n++;
1611                         }
1612                 }
1613
1614                 /* we didn't find a protocol he wanted? */
1615
1616                 if (!hit) {
1617                         if (lws_hdr_simple_ptr(wsi, WSI_TOKEN_PROTOCOL)) {
1618                                 lwsl_info("No protocol from \"%s\" supported\n",
1619                                          protocol_list);
1620                                 goto bail_nuke_ah;
1621                         }
1622                         /*
1623                          * some clients only have one protocol and
1624                          * do not send the protocol list header...
1625                          * allow it and match to the vhost's default
1626                          * protocol (which itself defaults to zero)
1627                          */
1628                         lwsl_info("defaulting to prot handler %d\n",
1629                                 wsi->vhost->default_protocol_index);
1630                         n = wsi->vhost->default_protocol_index;
1631                         wsi->protocol = &wsi->vhost->protocols[
1632                                       (int)wsi->vhost->default_protocol_index];
1633                 }
1634
1635                 /* allocate wsi->user storage */
1636                 if (lws_ensure_user_space(wsi))
1637                         goto bail_nuke_ah;
1638
1639                 /*
1640                  * Give the user code a chance to study the request and
1641                  * have the opportunity to deny it
1642                  */
1643                 if ((wsi->protocol->callback)(wsi,
1644                                 LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION,
1645                                 wsi->user_space,
1646                               lws_hdr_simple_ptr(wsi, WSI_TOKEN_PROTOCOL), 0)) {
1647                         lwsl_warn("User code denied connection\n");
1648                         goto bail_nuke_ah;
1649                 }
1650
1651                 /*
1652                  * Perform the handshake according to the protocol version the
1653                  * client announced
1654                  */
1655
1656                 switch (wsi->ietf_spec_revision) {
1657                 case 13:
1658                         lwsl_parser("lws_parse calling handshake_04\n");
1659                         if (handshake_0405(context, wsi)) {
1660                                 lwsl_info("hs0405 has failed the connection\n");
1661                                 goto bail_nuke_ah;
1662                         }
1663                         break;
1664
1665                 default:
1666                         lwsl_info("Unknown client spec version %d\n",
1667                                   wsi->ietf_spec_revision);
1668                         goto bail_nuke_ah;
1669                 }
1670
1671                 lws_same_vh_protocol_insert(wsi, n);
1672
1673                 /* we are upgrading to ws, so http/1.1 and keepalive +
1674                  * pipelined header considerations about keeping the ah around
1675                  * no longer apply.  However it's common for the first ws
1676                  * protocol data to have been coalesced with the browser
1677                  * upgrade request and to already be in the ah rx buffer.
1678                  */
1679
1680                 lwsl_info("%s: %p: inheriting ah in ws mode (rxpos:%d, rxlen:%d)\n",
1681                           __func__, wsi, wsi->u.hdr.ah->rxpos,
1682                           wsi->u.hdr.ah->rxlen);
1683                 lws_pt_lock(pt);
1684                 hdr = wsi->u.hdr;
1685
1686                 lws_union_transition(wsi, LWSCM_WS_SERVING);
1687                 /*
1688                  * first service is WS mode will notice this, use the RX and
1689                  * then detach the ah (caution: we are not in u.hdr union
1690                  * mode any more then... ah_temp member is at start the same
1691                  * though)
1692                  *
1693                  * Because rxpos/rxlen shows something in the ah, we will get
1694                  * service guaranteed next time around the event loop
1695                  *
1696                  * All union members begin with hdr, so we can use it even
1697                  * though we transitioned to ws union mode (the ah detach
1698                  * code uses it anyway).
1699                  */
1700                 wsi->u.hdr = hdr;
1701                 lws_pt_unlock(pt);
1702
1703                 lws_server_init_wsi_for_ws(wsi);
1704                 lwsl_parser("accepted v%02d connection\n",
1705                             wsi->ietf_spec_revision);
1706
1707                 /* !!! drop ah unreservedly after ESTABLISHED */
1708                 if (!wsi->more_rx_waiting) {
1709                         lws_header_table_force_to_detachable_state(wsi);
1710
1711                         //lwsl_notice("%p: dropping ah EST\n", wsi);
1712                         lws_header_table_detach(wsi, 1);
1713                 }
1714
1715                 return 0;
1716         } /* while all chars are handled */
1717
1718         return 0;
1719
1720 bail_nuke_ah:
1721         /* drop the header info */
1722         /* we're closing, losing some rx is OK */
1723         lws_header_table_force_to_detachable_state(wsi);
1724         //lwsl_notice("%s: drop2\n", __func__);
1725         lws_header_table_detach(wsi, 1);
1726
1727         return 1;
1728 }
1729
1730 static int
1731 lws_get_idlest_tsi(struct lws_context *context)
1732 {
1733         unsigned int lowest = ~0;
1734         int n = 0, hit = -1;
1735
1736         for (; n < context->count_threads; n++) {
1737                 if ((unsigned int)context->pt[n].fds_count !=
1738                     context->fd_limit_per_thread - 1 &&
1739                     (unsigned int)context->pt[n].fds_count < lowest) {
1740                         lowest = context->pt[n].fds_count;
1741                         hit = n;
1742                 }
1743         }
1744
1745         return hit;
1746 }
1747
1748 struct lws *
1749 lws_create_new_server_wsi(struct lws_vhost *vhost)
1750 {
1751         struct lws *new_wsi;
1752         int n = lws_get_idlest_tsi(vhost->context);
1753
1754         if (n < 0) {
1755                 lwsl_err("no space for new conn\n");
1756                 return NULL;
1757         }
1758
1759         new_wsi = lws_zalloc(sizeof(struct lws));
1760         if (new_wsi == NULL) {
1761                 lwsl_err("Out of memory for new connection\n");
1762                 return NULL;
1763         }
1764
1765         new_wsi->tsi = n;
1766         lwsl_debug("Accepted wsi %p to context %p, tsi %d\n", new_wsi,
1767                     vhost->context, new_wsi->tsi);
1768
1769         new_wsi->vhost = vhost;
1770         new_wsi->context = vhost->context;
1771         new_wsi->pending_timeout = NO_PENDING_TIMEOUT;
1772         new_wsi->rxflow_change_to = LWS_RXFLOW_ALLOW;
1773
1774         /* initialize the instance struct */
1775
1776         new_wsi->state = LWSS_HTTP;
1777         new_wsi->mode = LWSCM_HTTP_SERVING;
1778         new_wsi->hdr_parsing_completed = 0;
1779
1780 #ifdef LWS_OPENSSL_SUPPORT
1781         new_wsi->use_ssl = LWS_SSL_ENABLED(vhost);
1782 #endif
1783
1784         /*
1785          * these can only be set once the protocol is known
1786          * we set an unestablished connection's protocol pointer
1787          * to the start of the supported list, so it can look
1788          * for matching ones during the handshake
1789          */
1790         new_wsi->protocol = vhost->protocols;
1791         new_wsi->user_space = NULL;
1792         new_wsi->ietf_spec_revision = 0;
1793         new_wsi->desc.sockfd = LWS_SOCK_INVALID;
1794         new_wsi->position_in_fds_table = -1;
1795
1796         vhost->context->count_wsi_allocated++;
1797
1798         /*
1799          * outermost create notification for wsi
1800          * no user_space because no protocol selection
1801          */
1802         vhost->protocols[0].callback(new_wsi, LWS_CALLBACK_WSI_CREATE,
1803                                        NULL, NULL, 0);
1804
1805         return new_wsi;
1806 }
1807
1808 LWS_VISIBLE int LWS_WARN_UNUSED_RESULT
1809 lws_http_transaction_completed(struct lws *wsi)
1810 {
1811         int n = NO_PENDING_TIMEOUT;
1812
1813         lws_access_log(wsi);
1814
1815         if (!wsi->hdr_parsing_completed) {
1816                 lwsl_notice("%s: ignoring, ah parsing incomplete\n", __func__);
1817                 return 0;
1818         }
1819
1820         lwsl_debug("%s: wsi %p\n", __func__, wsi);
1821         /* if we can't go back to accept new headers, drop the connection */
1822         if (wsi->u.http.connection_type != HTTP_CONNECTION_KEEP_ALIVE) {
1823                 lwsl_info("%s: %p: close connection\n", __func__, wsi);
1824                 return 1;
1825         }
1826
1827         if (lws_bind_protocol(wsi, &wsi->vhost->protocols[0]))
1828                 return 1;
1829
1830         /* otherwise set ourselves up ready to go again */
1831         wsi->state = LWSS_HTTP;
1832         wsi->mode = LWSCM_HTTP_SERVING;
1833         wsi->u.http.content_length = 0;
1834         wsi->u.http.content_remain = 0;
1835         wsi->hdr_parsing_completed = 0;
1836 #ifdef LWS_WITH_ACCESS_LOG
1837         wsi->access_log.sent = 0;
1838 #endif
1839
1840         if (wsi->vhost->keepalive_timeout)
1841                 n = PENDING_TIMEOUT_HTTP_KEEPALIVE_IDLE;
1842         lws_set_timeout(wsi, n, wsi->vhost->keepalive_timeout);
1843
1844         /*
1845          * We already know we are on http1.1 / keepalive and the next thing
1846          * coming will be another header set.
1847          *
1848          * If there is no pending rx and we still have the ah, drop it and
1849          * reacquire a new ah when the new headers start to arrive.  (Otherwise
1850          * we needlessly hog an ah indefinitely.)
1851          *
1852          * However if there is pending rx and we know from the keepalive state
1853          * that is already at least the start of another header set, simply
1854          * reset the existing header table and keep it.
1855          */
1856         if (wsi->u.hdr.ah) {
1857                 lwsl_info("%s: wsi->more_rx_waiting=%d\n", __func__,
1858                                 wsi->more_rx_waiting);
1859
1860                 if (!wsi->more_rx_waiting) {
1861                         lws_header_table_force_to_detachable_state(wsi);
1862                         lws_header_table_detach(wsi, 1);
1863 #ifdef LWS_OPENSSL_SUPPORT
1864                         /*
1865                          * additionally... if we are hogging an SSL instance
1866                          * with no pending pipelined headers (or ah now), and
1867                          * SSL is scarce, drop this connection without waiting
1868                          */
1869
1870                         if (wsi->vhost->use_ssl &&
1871                             wsi->context->simultaneous_ssl_restriction &&
1872                             wsi->context->simultaneous_ssl ==
1873                                    wsi->context->simultaneous_ssl_restriction) {
1874                                 lwsl_info("%s: simultaneous_ssl_restriction and nothing pipelined\n", __func__);
1875                                 return 1;
1876                         }
1877 #endif
1878                 } else
1879                         lws_header_table_reset(wsi, 1);
1880         }
1881
1882         /* If we're (re)starting on headers, need other implied init */
1883         wsi->u.hdr.ues = URIES_IDLE;
1884
1885         lwsl_info("%s: %p: keep-alive await new transaction\n", __func__, wsi);
1886
1887         return 0;
1888 }
1889
1890 /* if not a socket, it's a raw, non-ssl file descriptor */
1891
1892 LWS_VISIBLE struct lws *
1893 lws_adopt_descriptor_vhost(struct lws_vhost *vh, lws_adoption_type type,
1894                            lws_sock_file_fd_type fd, const char *vh_prot_name,
1895                            struct lws *parent)
1896 {
1897         struct lws_context *context = vh->context;
1898         struct lws *new_wsi = lws_create_new_server_wsi(vh);
1899         struct lws_context_per_thread *pt;
1900         int n, ssl = 0;
1901
1902         if (!new_wsi) {
1903                 if (type & LWS_ADOPT_SOCKET && !(type & LWS_ADOPT_WS_PARENTIO))
1904                         compatible_close(fd.sockfd);
1905                 return NULL;
1906         }
1907         pt = &context->pt[(int)new_wsi->tsi];
1908         lws_stats_atomic_bump(context, pt, LWSSTATS_C_CONNECTIONS, 1);
1909
1910         if (parent) {
1911                 new_wsi->parent = parent;
1912                 new_wsi->sibling_list = parent->child_list;
1913                 parent->child_list = new_wsi;
1914
1915                 if (type & LWS_ADOPT_WS_PARENTIO)
1916                         new_wsi->parent_carries_io = 1;
1917         }
1918
1919         new_wsi->desc = fd;
1920
1921         if (vh_prot_name) {
1922                 new_wsi->protocol = lws_vhost_name_to_protocol(new_wsi->vhost,
1923                                                                vh_prot_name);
1924                 if (!new_wsi->protocol) {
1925                         lwsl_err("Protocol %s not enabled on vhost %s\n",
1926                                  vh_prot_name, new_wsi->vhost->name);
1927                         goto bail;
1928                 }
1929                if (lws_ensure_user_space(new_wsi)) {
1930                        lwsl_notice("OOM trying to get user_space\n");
1931                         goto bail;
1932                }
1933                if (type & LWS_ADOPT_WS_PARENTIO) {
1934                         new_wsi->desc.sockfd = LWS_SOCK_INVALID;
1935                         lwsl_debug("binding to %s\n", new_wsi->protocol->name);
1936                         lws_bind_protocol(new_wsi, new_wsi->protocol);
1937                         lws_union_transition(new_wsi, LWSCM_WS_SERVING);
1938                         lws_server_init_wsi_for_ws(new_wsi);
1939
1940                         return new_wsi;
1941                }
1942         } else
1943                 if (type & LWS_ADOPT_HTTP) /* he will transition later */
1944                         new_wsi->protocol =
1945                                 &vh->protocols[vh->default_protocol_index];
1946                 else { /* this is the only time he will transition */
1947                         lws_bind_protocol(new_wsi,
1948                                 &vh->protocols[vh->raw_protocol_index]);
1949                         lws_union_transition(new_wsi, LWSCM_RAW);
1950                 }
1951
1952         if (type & LWS_ADOPT_SOCKET) { /* socket desc */
1953                 lwsl_debug("%s: new wsi %p, sockfd %d\n", __func__, new_wsi,
1954                            (int)(lws_intptr_t)fd.sockfd);
1955
1956                 if (type & LWS_ADOPT_HTTP)
1957                         /* the transport is accepted...
1958                          * give him time to negotiate */
1959                         lws_set_timeout(new_wsi,
1960                                         PENDING_TIMEOUT_ESTABLISH_WITH_SERVER,
1961                                         context->timeout_secs);
1962
1963 #if LWS_POSIX == 0
1964 #if defined(LWS_WITH_ESP8266)
1965                 esp8266_tcp_stream_accept(accept_fd, new_wsi);
1966 #endif
1967 #endif
1968         } else /* file desc */
1969                 lwsl_debug("%s: new wsi %p, filefd %d\n", __func__, new_wsi,
1970                            (int)(lws_intptr_t)fd.filefd);
1971
1972         /*
1973          * A new connection was accepted. Give the user a chance to
1974          * set properties of the newly created wsi. There's no protocol
1975          * selected yet so we issue this to the vhosts's default protocol,
1976          * itself by default protocols[0]
1977          */
1978         n = LWS_CALLBACK_SERVER_NEW_CLIENT_INSTANTIATED;
1979         if (!(type & LWS_ADOPT_HTTP)) {
1980                 if (!(type & LWS_ADOPT_SOCKET))
1981                         n = LWS_CALLBACK_RAW_ADOPT_FILE;
1982                 else
1983                         n = LWS_CALLBACK_RAW_ADOPT;
1984         }
1985
1986         if (!LWS_SSL_ENABLED(new_wsi->vhost) || !(type & LWS_ADOPT_ALLOW_SSL) ||
1987             !(type & LWS_ADOPT_SOCKET)) {
1988                 /* non-SSL */
1989                 if (!(type & LWS_ADOPT_HTTP)) {
1990                         if (!(type & LWS_ADOPT_SOCKET))
1991                                 new_wsi->mode = LWSCM_RAW_FILEDESC;
1992                         else
1993                                 new_wsi->mode = LWSCM_RAW;
1994                 }
1995         } else {
1996                 /* SSL */
1997                 if (!(type & LWS_ADOPT_HTTP))
1998                         new_wsi->mode = LWSCM_SSL_INIT_RAW;
1999                 else
2000                         new_wsi->mode = LWSCM_SSL_INIT;
2001
2002                 ssl = 1;
2003         }
2004
2005         lws_libev_accept(new_wsi, new_wsi->desc);
2006         lws_libuv_accept(new_wsi, new_wsi->desc);
2007         lws_libevent_accept(new_wsi, new_wsi->desc);
2008
2009         if (!ssl) {
2010                 if (insert_wsi_socket_into_fds(context, new_wsi)) {
2011                         lwsl_err("%s: fail inserting socket\n", __func__);
2012                         goto fail;
2013                 }
2014         } else
2015                 if (lws_server_socket_service_ssl(new_wsi, fd.sockfd)) {
2016                         lwsl_err("%s: fail ssl negotiation\n", __func__);
2017                         goto fail;
2018                 }
2019
2020         /*
2021          *  by deferring callback to this point, after insertion to fds,
2022          * lws_callback_on_writable() can work from the callback
2023          */
2024         if ((new_wsi->protocol->callback)(
2025                         new_wsi, n, new_wsi->user_space, NULL, 0))
2026                 goto fail;
2027
2028         if (type & LWS_ADOPT_HTTP) {
2029                 if (!lws_header_table_attach(new_wsi, 0)) {
2030                         lwsl_debug("Attached ah immediately\n");
2031                 } else {
2032                         lwsl_notice("%s: waiting for ah\n", __func__);
2033                 }
2034         }
2035
2036         return new_wsi;
2037
2038 fail:
2039         if (type & LWS_ADOPT_SOCKET)
2040                 lws_close_free_wsi(new_wsi, LWS_CLOSE_STATUS_NOSTATUS);
2041
2042         return NULL;
2043
2044 bail:
2045        lwsl_notice("%s: exiting on bail\n", __func__);
2046         if (parent)
2047                 parent->child_list = new_wsi->sibling_list;
2048         if (new_wsi->user_space)
2049                 lws_free(new_wsi->user_space);
2050         lws_free(new_wsi);
2051        compatible_close(fd.sockfd);
2052
2053         return NULL;
2054 }
2055
2056 LWS_VISIBLE struct lws *
2057 lws_adopt_socket_vhost(struct lws_vhost *vh, lws_sockfd_type accept_fd)
2058 {
2059         lws_sock_file_fd_type fd;
2060
2061         fd.sockfd = accept_fd;
2062         return lws_adopt_descriptor_vhost(vh, LWS_ADOPT_SOCKET |
2063                         LWS_ADOPT_HTTP | LWS_ADOPT_ALLOW_SSL, fd, NULL, NULL);
2064 }
2065
2066 LWS_VISIBLE struct lws *
2067 lws_adopt_socket(struct lws_context *context, lws_sockfd_type accept_fd)
2068 {
2069         return lws_adopt_socket_vhost(context->vhost_list, accept_fd);
2070 }
2071
2072 /* Common read-buffer adoption for lws_adopt_*_readbuf */
2073 static struct lws*
2074 adopt_socket_readbuf(struct lws *wsi, const char *readbuf, size_t len)
2075 {
2076         struct lws_context_per_thread *pt;
2077         struct allocated_headers *ah;
2078         struct lws_pollfd *pfd;
2079
2080         if (!wsi)
2081                 return NULL;
2082
2083         if (!readbuf || len == 0)
2084                 return wsi;
2085
2086         if (len > sizeof(ah->rx)) {
2087                 lwsl_err("%s: rx in too big\n", __func__);
2088                 goto bail;
2089         }
2090
2091         /*
2092          * we can't process the initial read data until we can attach an ah.
2093          *
2094          * if one is available, get it and place the data in his ah rxbuf...
2095          * wsi with ah that have pending rxbuf get auto-POLLIN service.
2096          *
2097          * no autoservice because we didn't get a chance to attach the
2098          * readbuf data to wsi or ah yet, and we will do it next if we get
2099          * the ah.
2100          */
2101         if (wsi->u.hdr.ah || !lws_header_table_attach(wsi, 0)) {
2102                 ah = wsi->u.hdr.ah;
2103                 memcpy(ah->rx, readbuf, len);
2104                 ah->rxpos = 0;
2105                 ah->rxlen = len;
2106
2107                 lwsl_notice("%s: calling service on readbuf ah\n", __func__);
2108                 pt = &wsi->context->pt[(int)wsi->tsi];
2109
2110                 /* unlike a normal connect, we have the headers already
2111                  * (or the first part of them anyway).
2112                  * libuv won't come back and service us without a network
2113                  * event, so we need to do the header service right here.
2114                  */
2115                 pfd = &pt->fds[wsi->position_in_fds_table];
2116                 pfd->revents |= LWS_POLLIN;
2117                 lwsl_err("%s: calling service\n", __func__);
2118                 if (lws_service_fd_tsi(wsi->context, pfd, wsi->tsi))
2119                         /* service closed us */
2120                         return NULL;
2121
2122                 return wsi;
2123         }
2124         lwsl_err("%s: deferring handling ah\n", __func__);
2125         /*
2126          * hum if no ah came, we are on the wait list and must defer
2127          * dealing with this until the ah arrives.
2128          *
2129          * later successful lws_header_table_attach() will apply the
2130          * below to the rx buffer (via lws_header_table_reset()).
2131          */
2132         wsi->u.hdr.preamble_rx = lws_malloc(len);
2133         if (!wsi->u.hdr.preamble_rx) {
2134                 lwsl_err("OOM\n");
2135                 goto bail;
2136         }
2137         memcpy(wsi->u.hdr.preamble_rx, readbuf, len);
2138         wsi->u.hdr.preamble_rx_len = len;
2139
2140         return wsi;
2141
2142 bail:
2143         lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
2144
2145         return NULL;
2146 }
2147
2148 LWS_VISIBLE struct lws *
2149 lws_adopt_socket_readbuf(struct lws_context *context, lws_sockfd_type accept_fd,
2150                          const char *readbuf, size_t len)
2151 {
2152         return adopt_socket_readbuf(lws_adopt_socket(context, accept_fd), readbuf, len);
2153 }
2154
2155 LWS_VISIBLE struct lws *
2156 lws_adopt_socket_vhost_readbuf(struct lws_vhost *vhost, lws_sockfd_type accept_fd,
2157                          const char *readbuf, size_t len)
2158 {
2159         return adopt_socket_readbuf(lws_adopt_socket_vhost(vhost, accept_fd), readbuf, len);
2160 }
2161
2162 LWS_VISIBLE int
2163 lws_server_socket_service(struct lws_context *context, struct lws *wsi,
2164                           struct lws_pollfd *pollfd)
2165 {
2166         struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
2167         lws_sockfd_type accept_fd = LWS_SOCK_INVALID;
2168         struct allocated_headers *ah;
2169         lws_sock_file_fd_type fd;
2170         int opts = LWS_ADOPT_SOCKET | LWS_ADOPT_ALLOW_SSL;
2171 #if LWS_POSIX
2172         struct sockaddr_storage cli_addr;
2173         socklen_t clilen;
2174 #endif
2175         int n, len;
2176         
2177         // lwsl_notice("%s: mode %d\n", __func__, wsi->mode);
2178
2179         switch (wsi->mode) {
2180
2181         case LWSCM_HTTP_SERVING:
2182         case LWSCM_HTTP_SERVING_ACCEPTED:
2183         case LWSCM_HTTP2_SERVING:
2184         case LWSCM_RAW:
2185
2186                 /* handle http headers coming in */
2187
2188                 /* pending truncated sends have uber priority */
2189
2190                 if (wsi->trunc_len) {
2191                         if (!(pollfd->revents & LWS_POLLOUT))
2192                                 break;
2193
2194                         if (lws_issue_raw(wsi, wsi->trunc_alloc +
2195                                                wsi->trunc_offset,
2196                                           wsi->trunc_len) < 0)
2197                                 goto fail;
2198                         /*
2199                          * we can't afford to allow input processing to send
2200                          * something new, so spin around he event loop until
2201                          * he doesn't have any partials
2202                          */
2203                         break;
2204                 }
2205
2206                 /* any incoming data ready? */
2207
2208                 if (!(pollfd->revents & pollfd->events & LWS_POLLIN))
2209                         goto try_pollout;
2210
2211                 /*
2212                  * If we previously just did POLLIN when IN and OUT were
2213                  * signalled (because POLLIN processing may have used up
2214                  * the POLLOUT), don't let that happen twice in a row...
2215                  * next time we see the situation favour POLLOUT
2216                  */
2217 #if !defined(LWS_WITH_ESP8266)
2218                 if (wsi->favoured_pollin &&
2219                     (pollfd->revents & pollfd->events & LWS_POLLOUT)) {
2220                         wsi->favoured_pollin = 0;
2221                         goto try_pollout;
2222                 }
2223 #endif
2224
2225                 /* these states imply we MUST have an ah attached */
2226
2227                 if (wsi->mode != LWSCM_RAW && (wsi->state == LWSS_HTTP ||
2228                     wsi->state == LWSS_HTTP_ISSUING_FILE ||
2229                     wsi->state == LWSS_HTTP_HEADERS)) {
2230                         if (!wsi->u.hdr.ah) {
2231                                 
2232                                 //lwsl_err("wsi %p: missing ah\n", wsi);
2233                                 /* no autoservice beacuse we will do it next */
2234                                 if (lws_header_table_attach(wsi, 0)) {
2235                                         lwsl_info("wsi %p: failed to acquire ah\n", wsi);
2236                                         goto try_pollout;
2237                                 }
2238                         }
2239                         ah = wsi->u.hdr.ah;
2240
2241                         //lwsl_notice("%s: %p: rxpos:%d rxlen:%d\n", __func__, wsi,
2242                         //         ah->rxpos, ah->rxlen);
2243
2244                         /* if nothing in ah rx buffer, get some fresh rx */
2245                         if (ah->rxpos == ah->rxlen) {
2246                                 ah->rxlen = lws_ssl_capable_read(wsi, ah->rx,
2247                                                    sizeof(ah->rx));
2248                                 ah->rxpos = 0;
2249                                 //lwsl_notice("%s: wsi %p, ah->rxlen = %d\r\n",
2250                                 //         __func__, wsi, ah->rxlen);
2251                                 switch (ah->rxlen) {
2252                                 case 0:
2253                                         lwsl_info("%s: read 0 len\n", __func__);
2254                                         /* lwsl_info("   state=%d\n", wsi->state); */
2255 //                                      if (!wsi->hdr_parsing_completed)
2256 //                                              lws_header_table_detach(wsi);
2257                                         /* fallthru */
2258                                 case LWS_SSL_CAPABLE_ERROR:
2259                                         goto fail;
2260                                 case LWS_SSL_CAPABLE_MORE_SERVICE:
2261                                         ah->rxlen = ah->rxpos = 0;
2262                                         goto try_pollout;
2263                                 }
2264
2265                                 /*
2266                                  *  make sure ah does not get detached if we
2267                                  * have live data in the rx
2268                                  */
2269                                 if (ah->rxlen)
2270                                         wsi->more_rx_waiting = 1;
2271                         }
2272
2273                         if (!(ah->rxpos != ah->rxlen && ah->rxlen)) {
2274                                 lwsl_err("%s: assert: rxpos %d, rxlen %d\n",
2275                                          __func__, ah->rxpos, ah->rxlen);
2276
2277                                 assert(0);
2278                         }
2279                         
2280                         /* just ignore incoming if waiting for close */
2281                         if (wsi->state != LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE &&
2282                             wsi->state != LWSS_HTTP_ISSUING_FILE) {
2283                                 n = lws_read(wsi, ah->rx + ah->rxpos,
2284                                              ah->rxlen - ah->rxpos);
2285                                 if (n < 0) /* we closed wsi */
2286                                         return 1;
2287                                 if (wsi->u.hdr.ah) {
2288                                         if ( wsi->u.hdr.ah->rxlen)
2289                                                  wsi->u.hdr.ah->rxpos += n;
2290
2291                                         lwsl_debug("%s: wsi %p: ah read rxpos %d, rxlen %d\n", __func__, wsi, wsi->u.hdr.ah->rxpos, wsi->u.hdr.ah->rxlen);
2292
2293                                         if (lws_header_table_is_in_detachable_state(wsi) &&
2294                                             (wsi->mode != LWSCM_HTTP_SERVING &&
2295                                              wsi->mode != LWSCM_HTTP_SERVING_ACCEPTED &&
2296                                              wsi->mode != LWSCM_HTTP2_SERVING))
2297                                                 lws_header_table_detach(wsi, 1);
2298                                 }
2299                                 break;
2300                         }
2301
2302                         goto try_pollout;
2303                 }
2304
2305                 len = lws_ssl_capable_read(wsi, pt->serv_buf,
2306                                            context->pt_serv_buf_size);
2307                 lwsl_debug("%s: wsi %p read %d\r\n", __func__, wsi, len);
2308                 switch (len) {
2309                 case 0:
2310                         lwsl_info("%s: read 0 len\n", __func__);
2311                         /* lwsl_info("   state=%d\n", wsi->state); */
2312 //                      if (!wsi->hdr_parsing_completed)
2313 //                              lws_header_table_detach(wsi);
2314                         /* fallthru */
2315                 case LWS_SSL_CAPABLE_ERROR:
2316                         goto fail;
2317                 case LWS_SSL_CAPABLE_MORE_SERVICE:
2318                         goto try_pollout;
2319                 }
2320                 
2321                 if (wsi->mode == LWSCM_RAW) {
2322                         n = user_callback_handle_rxflow(wsi->protocol->callback,
2323                                         wsi, LWS_CALLBACK_RAW_RX,
2324                                         wsi->user_space, pt->serv_buf, len);
2325                         if (n < 0) {
2326                                 lwsl_info("LWS_CALLBACK_RAW_RX_fail\n");
2327                                 goto fail;
2328                         }
2329                         goto try_pollout;
2330                 }
2331
2332                 /* just ignore incoming if waiting for close */
2333                 if (wsi->state != LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE &&
2334                     wsi->state != LWSS_HTTP_ISSUING_FILE) {
2335                         /*
2336                          * this may want to send
2337                          * (via HTTP callback for example)
2338                          */
2339                         n = lws_read(wsi, pt->serv_buf, len);
2340                         if (n < 0) /* we closed wsi */
2341                                 return 1;
2342                         /*
2343                          *  he may have used up the
2344                          * writability above, if we will defer POLLOUT
2345                          * processing in favour of POLLIN, note it
2346                          */
2347                         if (pollfd->revents & LWS_POLLOUT)
2348                                 wsi->favoured_pollin = 1;
2349                         break;
2350                 }
2351
2352 try_pollout:
2353                 
2354                 /* this handles POLLOUT for http serving fragments */
2355
2356                 if (!(pollfd->revents & LWS_POLLOUT))
2357                         break;
2358
2359                 /* one shot */
2360                 if (lws_change_pollfd(wsi, LWS_POLLOUT, 0)) {
2361                         lwsl_notice("%s a\n", __func__);
2362                         goto fail;
2363                 }
2364
2365                 if (wsi->mode == LWSCM_RAW) {
2366                         lws_stats_atomic_bump(wsi->context, pt, LWSSTATS_C_WRITEABLE_CB, 1);
2367 #if defined(LWS_WITH_STATS)
2368                         {
2369                                 uint64_t ul = time_in_microseconds() - wsi->active_writable_req_us;
2370
2371                                 lws_stats_atomic_bump(wsi->context, pt, LWSSTATS_MS_WRITABLE_DELAY, ul);
2372                                 lws_stats_atomic_max(wsi->context, pt, LWSSTATS_MS_WORST_WRITABLE_DELAY, ul);
2373                                 wsi->active_writable_req_us = 0;
2374                         }
2375 #endif
2376                         n = user_callback_handle_rxflow(wsi->protocol->callback,
2377                                         wsi, LWS_CALLBACK_RAW_WRITEABLE,
2378                                         wsi->user_space, NULL, 0);
2379                         if (n < 0) {
2380                                 lwsl_info("writeable_fail\n");
2381                                 goto fail;
2382                         }
2383                         break;
2384                 }
2385
2386                 if (!wsi->hdr_parsing_completed)
2387                         break;
2388
2389                 if (wsi->state != LWSS_HTTP_ISSUING_FILE) {
2390
2391                         lws_stats_atomic_bump(wsi->context, pt, LWSSTATS_C_WRITEABLE_CB, 1);
2392 #if defined(LWS_WITH_STATS)
2393                         {
2394                                 uint64_t ul = time_in_microseconds() - wsi->active_writable_req_us;
2395
2396                                 lws_stats_atomic_bump(wsi->context, pt, LWSSTATS_MS_WRITABLE_DELAY, ul);
2397                                 lws_stats_atomic_max(wsi->context, pt, LWSSTATS_MS_WORST_WRITABLE_DELAY, ul);
2398                                 wsi->active_writable_req_us = 0;
2399                         }
2400 #endif
2401
2402                         n = user_callback_handle_rxflow(wsi->protocol->callback,
2403                                         wsi, LWS_CALLBACK_HTTP_WRITEABLE,
2404                                         wsi->user_space, NULL, 0);
2405                         if (n < 0) {
2406                                 lwsl_info("writeable_fail\n");
2407                                 goto fail;
2408                         }
2409                         break;
2410                 }
2411
2412                 /* >0 == completion, <0 == error
2413                  *
2414                  * We'll get a LWS_CALLBACK_HTTP_FILE_COMPLETION callback when
2415                  * it's done.  That's the case even if we just completed the
2416                  * send, so wait for that.
2417                  */
2418                 n = lws_serve_http_file_fragment(wsi);
2419                 if (n < 0)
2420                         goto fail;
2421
2422                 break;
2423
2424         case LWSCM_SERVER_LISTENER:
2425
2426 #if LWS_POSIX
2427                 /* pollin means a client has connected to us then */
2428
2429                 do {
2430                         if (!(pollfd->revents & LWS_POLLIN) || !(pollfd->events & LWS_POLLIN))
2431                                 break;
2432
2433 #ifdef LWS_OPENSSL_SUPPORT
2434                         /*
2435                          * can we really accept it, with regards to SSL limit?
2436                          * another vhost may also have had POLLIN on his listener this
2437                          * round and used it up already
2438                          */
2439
2440                         if (wsi->vhost->use_ssl &&
2441                             context->simultaneous_ssl_restriction &&
2442                             context->simultaneous_ssl ==
2443                                           context->simultaneous_ssl_restriction)
2444                                 /* no... ignore it, he won't come again until we are
2445                                  * below the simultaneous_ssl_restriction limit and
2446                                  * POLLIN is enabled on him again
2447                                  */
2448                                 break;
2449 #endif
2450                         /* listen socket got an unencrypted connection... */
2451
2452                         clilen = sizeof(cli_addr);
2453                         lws_latency_pre(context, wsi);
2454                         accept_fd  = accept(pollfd->fd, (struct sockaddr *)&cli_addr,
2455                                             &clilen);
2456                         lws_latency(context, wsi, "listener accept", accept_fd,
2457                                     accept_fd >= 0);
2458                         if (accept_fd < 0) {
2459                                 if (LWS_ERRNO == LWS_EAGAIN ||
2460                                     LWS_ERRNO == LWS_EWOULDBLOCK) {
2461 //                                      lwsl_err("accept asks to try again\n");
2462                                         break;
2463                                 }
2464                                 lwsl_err("ERROR on accept: %s\n", strerror(LWS_ERRNO));
2465                                 break;
2466                         }
2467
2468                         lws_plat_set_socket_options(wsi->vhost, accept_fd);
2469
2470 #if defined(LWS_USE_IPV6)
2471                         lwsl_debug("accepted new conn port %u on fd=%d\n",
2472                                           ((cli_addr.ss_family == AF_INET6) ?
2473                                           ntohs(((struct sockaddr_in6 *) &cli_addr)->sin6_port) :
2474                                           ntohs(((struct sockaddr_in *) &cli_addr)->sin_port)),
2475                                           accept_fd);
2476 #else
2477                         lwsl_debug("accepted new conn port %u on fd=%d\n",
2478                                           ntohs(((struct sockaddr_in *) &cli_addr)->sin_port),
2479                                           accept_fd);
2480 #endif
2481
2482 #else
2483                         /* not very beautiful... */
2484                         accept_fd = (lws_sockfd_type)pollfd;
2485 #endif
2486                         /*
2487                          * look at who we connected to and give user code a chance
2488                          * to reject based on client IP.  There's no protocol selected
2489                          * yet so we issue this to protocols[0]
2490                          */
2491                         if ((wsi->vhost->protocols[0].callback)(wsi,
2492                                         LWS_CALLBACK_FILTER_NETWORK_CONNECTION,
2493                                         NULL, (void *)(lws_intptr_t)accept_fd, 0)) {
2494                                 lwsl_debug("Callback denied network connection\n");
2495                                 compatible_close(accept_fd);
2496                                 break;
2497                         }
2498
2499                         if (!(wsi->vhost->options & LWS_SERVER_OPTION_ONLY_RAW))
2500                                 opts |= LWS_ADOPT_HTTP;
2501
2502                         fd.sockfd = accept_fd;
2503                         if (!lws_adopt_descriptor_vhost(wsi->vhost, opts, fd,
2504                                                         NULL, NULL))
2505                                 /* already closed cleanly as necessary */
2506                                 return 1;
2507
2508 #if LWS_POSIX
2509                 } while (pt->fds_count < context->fd_limit_per_thread - 1 &&
2510                          lws_poll_listen_fd(&pt->fds[wsi->position_in_fds_table]) > 0);
2511 #endif
2512                 return 0;
2513
2514         default:
2515                 break;
2516         }
2517
2518         if (!lws_server_socket_service_ssl(wsi, accept_fd))
2519                 return 0;
2520
2521 fail:
2522         lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
2523
2524         return 1;
2525 }
2526
2527 LWS_VISIBLE int
2528 lws_serve_http_file(struct lws *wsi, const char *file, const char *content_type,
2529                     const char *other_headers, int other_headers_len)
2530 {
2531         static const char * const intermediates[] = { "private", "public" };
2532         struct lws_context *context = lws_get_context(wsi);
2533         struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
2534 #if defined(LWS_WITH_RANGES)
2535         struct lws_range_parsing *rp = &wsi->u.http.range;
2536 #endif
2537         char cache_control[50], *cc = "no-store";
2538         unsigned char *response = pt->serv_buf + LWS_PRE;
2539         unsigned char *p = response;
2540         unsigned char *end = p + context->pt_serv_buf_size - LWS_PRE;
2541         lws_filepos_t computed_total_content_length;
2542         int ret = 0, cclen = 8, n = HTTP_STATUS_OK;
2543         lws_fop_flags_t fflags = LWS_O_RDONLY;
2544 #if defined(LWS_WITH_RANGES)
2545         int ranges;
2546 #endif
2547         const struct lws_plat_file_ops *fops;
2548         const char *vpath;
2549
2550         /*
2551          * We either call the platform fops .open with first arg platform fops,
2552          * or we call fops_zip .open with first arg platform fops, and fops_zip
2553          * open will decide whether to switch to fops_zip or stay with fops_def.
2554          *
2555          * If wsi->u.http.fop_fd is already set, the caller already opened it
2556          */
2557         if (!wsi->u.http.fop_fd) {
2558                 fops = lws_vfs_select_fops(wsi->context->fops, file, &vpath);
2559                 fflags |= lws_vfs_prepare_flags(wsi);
2560                 wsi->u.http.fop_fd = fops->LWS_FOP_OPEN(wsi->context->fops,
2561                                                         file, vpath, &fflags);
2562                 if (!wsi->u.http.fop_fd) {
2563                         lwsl_err("Unable to open '%s'\n", file);
2564
2565                         return -1;
2566                 }
2567         }
2568         wsi->u.http.filelen = lws_vfs_get_length(wsi->u.http.fop_fd);
2569         computed_total_content_length = wsi->u.http.filelen;
2570
2571 #if defined(LWS_WITH_RANGES)
2572         ranges = lws_ranges_init(wsi, rp, wsi->u.http.filelen);
2573
2574         lwsl_debug("Range count %d\n", ranges);
2575         /*
2576          * no ranges -> 200;
2577          *  1 range  -> 206 + Content-Type: normal; Content-Range;
2578          *  more     -> 206 + Content-Type: multipart/byteranges
2579          *              Repeat the true Content-Type in each multipart header
2580          *              along with Content-Range
2581          */
2582         if (ranges < 0) {
2583                 /* it means he expressed a range in Range:, but it was illegal */
2584                 lws_return_http_status(wsi, HTTP_STATUS_REQ_RANGE_NOT_SATISFIABLE, NULL);
2585                 if (lws_http_transaction_completed(wsi))
2586                         return -1; /* <0 means just hang up */
2587
2588                 lws_vfs_file_close(&wsi->u.http.fop_fd);
2589
2590                 return 0; /* == 0 means we dealt with the transaction complete */
2591         }
2592         if (ranges)
2593                 n = HTTP_STATUS_PARTIAL_CONTENT;
2594 #endif
2595
2596         if (lws_add_http_header_status(wsi, n, &p, end))
2597                 return -1;
2598
2599         if ((wsi->u.http.fop_fd->flags & (LWS_FOP_FLAG_COMPR_ACCEPTABLE_GZIP |
2600                        LWS_FOP_FLAG_COMPR_IS_GZIP)) ==
2601             (LWS_FOP_FLAG_COMPR_ACCEPTABLE_GZIP | LWS_FOP_FLAG_COMPR_IS_GZIP)) {
2602                 if (lws_add_http_header_by_token(wsi,
2603                         WSI_TOKEN_HTTP_CONTENT_ENCODING,
2604                         (unsigned char *)"gzip", 4, &p, end))
2605                         return -1;
2606                 lwsl_info("file is being provided in gzip\n");
2607         }
2608
2609 #if defined(LWS_WITH_RANGES)
2610         if (ranges < 2 && content_type && content_type[0])
2611                 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE,
2612                                                  (unsigned char *)content_type,
2613                                                  strlen(content_type), &p, end))
2614                         return -1;
2615
2616         if (ranges >= 2) { /* multipart byteranges */
2617                 strncpy(wsi->u.http.multipart_content_type, content_type,
2618                         sizeof(wsi->u.http.multipart_content_type) - 1);
2619                 wsi->u.http.multipart_content_type[
2620                          sizeof(wsi->u.http.multipart_content_type) - 1] = '\0';
2621                 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE,
2622                                                  (unsigned char *)"multipart/byteranges; boundary=_lws",
2623                                                  20, &p, end))
2624                         return -1;
2625
2626                 /*
2627                  *  our overall content length has to include
2628                  *
2629                  *  - (n + 1) x "_lws\r\n"
2630                  *  - n x Content-Type: xxx/xxx\r\n
2631                  *  - n x Content-Range: bytes xxx-yyy/zzz\r\n
2632                  *  - n x /r/n
2633                  *  - the actual payloads (aggregated in rp->agg)
2634                  *
2635                  *  Precompute it for the main response header
2636                  */
2637
2638                 computed_total_content_length = (lws_filepos_t)rp->agg +
2639                                                 6 /* final _lws\r\n */;
2640
2641                 lws_ranges_reset(rp);
2642                 while (lws_ranges_next(rp)) {
2643                         n = lws_snprintf(cache_control, sizeof(cache_control),
2644                                         "bytes %llu-%llu/%llu",
2645                                         rp->start, rp->end, rp->extent);
2646
2647                         computed_total_content_length +=
2648                                         6 /* header _lws\r\n */ +
2649                                         14 + strlen(content_type) + 2 + /* Content-Type: xxx/xxx\r\n */
2650                                         15 + n + 2 + /* Content-Range: xxxx\r\n */
2651                                         2; /* /r/n */
2652                 }
2653
2654                 lws_ranges_reset(rp);
2655                 lws_ranges_next(rp);
2656         }
2657
2658         if (ranges == 1) {
2659                 computed_total_content_length = (lws_filepos_t)rp->agg;
2660                 n = lws_snprintf(cache_control, sizeof(cache_control), "bytes %llu-%llu/%llu",
2661                                 rp->start, rp->end, rp->extent);
2662
2663                 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_CONTENT_RANGE,
2664                                                  (unsigned char *)cache_control,
2665                                                  n, &p, end))
2666                         return -1;
2667         }
2668
2669         wsi->u.http.range.inside = 0;
2670
2671         if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_ACCEPT_RANGES,
2672                                          (unsigned char *)"bytes", 5, &p, end))
2673                 return -1;
2674 #endif
2675
2676         if (!wsi->sending_chunked) {
2677                 if (lws_add_http_header_content_length(wsi,
2678                                                        computed_total_content_length,
2679                                                        &p, end))
2680                         return -1;
2681         } else {
2682                 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_TRANSFER_ENCODING,
2683                                                  (unsigned char *)"chunked",
2684                                                  7, &p, end))
2685                         return -1;
2686         }
2687
2688         if (wsi->cache_secs && wsi->cache_reuse) {
2689                 if (wsi->cache_revalidate) {
2690                         cc = cache_control;
2691                         cclen = sprintf(cache_control, "%s max-age: %u",
2692                                     intermediates[wsi->cache_intermediaries],
2693                                     wsi->cache_secs);
2694                 } else {
2695                         cc = "no-cache";
2696                         cclen = 8;
2697                 }
2698         }
2699
2700         if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_CACHE_CONTROL,
2701                         (unsigned char *)cc, cclen, &p, end))
2702                 return -1;
2703
2704         if (wsi->u.http.connection_type == HTTP_CONNECTION_KEEP_ALIVE)
2705                 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_CONNECTION,
2706                                 (unsigned char *)"keep-alive", 10, &p, end))
2707                         return -1;
2708
2709         if (other_headers) {
2710                 if ((end - p) < other_headers_len)
2711                         return -1;
2712                 memcpy(p, other_headers, other_headers_len);
2713                 p += other_headers_len;
2714         }
2715
2716         if (lws_finalize_http_header(wsi, &p, end))
2717                 return -1;
2718
2719         ret = lws_write(wsi, response, p - response, LWS_WRITE_HTTP_HEADERS);
2720         if (ret != (p - response)) {
2721                 lwsl_err("_write returned %d from %ld\n", ret, (long)(p - response));
2722                 return -1;
2723         }
2724
2725         wsi->u.http.filepos = 0;
2726         wsi->state = LWSS_HTTP_ISSUING_FILE;
2727
2728         return lws_serve_http_file_fragment(wsi);
2729 }
2730
2731 int
2732 lws_interpret_incoming_packet(struct lws *wsi, unsigned char **buf, size_t len)
2733 {
2734         int m;
2735
2736         lwsl_parser("%s: received %d byte packet\n", __func__, (int)len);
2737 #if 0
2738         lwsl_hexdump(*buf, len);
2739 #endif
2740
2741         /* let the rx protocol state machine have as much as it needs */
2742
2743         while (len) {
2744                 /*
2745                  * we were accepting input but now we stopped doing so
2746                  */
2747                 if (!(wsi->rxflow_change_to & LWS_RXFLOW_ALLOW)) {
2748                         lws_rxflow_cache(wsi, *buf, 0, len);
2749                         lwsl_parser("%s: cached %ld\n", __func__, (long)len);
2750                         return 1;
2751                 }
2752
2753                 if (wsi->u.ws.rx_draining_ext) {
2754                         // lwsl_notice("draining with 0\n");
2755                         m = lws_rx_sm(wsi, 0);
2756                         if (m < 0)
2757                                 return -1;
2758                         continue;
2759                 }
2760
2761                 /* account for what we're using in rxflow buffer */
2762                 if (wsi->rxflow_buffer)
2763                         wsi->rxflow_pos++;
2764
2765                 /* consume payload bytes efficiently */
2766                 if (
2767                     wsi->lws_rx_parse_state ==
2768                     LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED) {
2769                         m = lws_payload_until_length_exhausted(wsi, buf, &len);
2770                         if (wsi->rxflow_buffer)
2771                                 wsi->rxflow_pos += m;
2772                 }
2773
2774                 /* process the byte */
2775                 m = lws_rx_sm(wsi, *(*buf)++);
2776                 if (m < 0)
2777                         return -1;
2778                 len--;
2779         }
2780
2781         lwsl_parser("%s: exit with %d unused\n", __func__, (int)len);
2782
2783         return 0;
2784 }
2785
2786 LWS_VISIBLE void
2787 lws_server_get_canonical_hostname(struct lws_context *context,
2788                                   struct lws_context_creation_info *info)
2789 {
2790         if (lws_check_opt(info->options, LWS_SERVER_OPTION_SKIP_SERVER_CANONICAL_NAME))
2791                 return;
2792 #if LWS_POSIX && !defined(LWS_WITH_ESP32)
2793         /* find canonical hostname */
2794         gethostname((char *)context->canonical_hostname,
2795                     sizeof(context->canonical_hostname) - 1);
2796
2797         lwsl_notice(" canonical_hostname = %s\n", context->canonical_hostname);
2798 #else
2799         (void)context;
2800 #endif
2801 }
2802
2803 #define LWS_MAX_ELEM_NAME 32
2804
2805 enum urldecode_stateful {
2806         US_NAME,
2807         US_IDLE,
2808         US_PC1,
2809         US_PC2,
2810
2811         MT_LOOK_BOUND_IN,
2812         MT_HNAME,
2813         MT_DISP,
2814         MT_TYPE,
2815         MT_IGNORE1,
2816         MT_IGNORE2,
2817 };
2818
2819 static const char * const mp_hdr[] = {
2820         "content-disposition: ",
2821         "content-type: ",
2822         "\x0d\x0a"
2823 };
2824
2825 typedef int (*lws_urldecode_stateful_cb)(void *data,
2826                 const char *name, char **buf, int len, int final);
2827
2828 struct lws_urldecode_stateful {
2829         char *out;
2830         void *data;
2831         char name[LWS_MAX_ELEM_NAME];
2832         char temp[LWS_MAX_ELEM_NAME];
2833         char content_type[32];
2834         char content_disp[32];
2835         char content_disp_filename[256];
2836         char mime_boundary[128];
2837         int out_len;
2838         int pos;
2839         int hdr_idx;
2840         int mp;
2841         int sum;
2842
2843         unsigned int multipart_form_data:1;
2844         unsigned int inside_quote:1;
2845         unsigned int subname:1;
2846         unsigned int boundary_real_crlf:1;
2847
2848         enum urldecode_stateful state;
2849
2850         lws_urldecode_stateful_cb output;
2851 };
2852
2853 static struct lws_urldecode_stateful *
2854 lws_urldecode_s_create(struct lws *wsi, char *out, int out_len, void *data,
2855                        lws_urldecode_stateful_cb output)
2856 {
2857         struct lws_urldecode_stateful *s = lws_zalloc(sizeof(*s));
2858         char buf[200], *p;
2859         int m = 0;
2860
2861         if (!s)
2862                 return NULL;
2863
2864         s->out = out;
2865         s->out_len  = out_len;
2866         s->output = output;
2867         s->pos = 0;
2868         s->sum = 0;
2869         s->mp = 0;
2870         s->state = US_NAME;
2871         s->name[0] = '\0';
2872         s->data = data;
2873
2874         if (lws_hdr_copy(wsi, buf, sizeof(buf), WSI_TOKEN_HTTP_CONTENT_TYPE) > 0) {
2875                 /* multipart/form-data; boundary=----WebKitFormBoundarycc7YgAPEIHvgE9Bf */
2876
2877                 if (!strncmp(buf, "multipart/form-data", 19)) {
2878                         s->multipart_form_data = 1;
2879                         s->state = MT_LOOK_BOUND_IN;
2880                         s->mp = 2;
2881                         p = strstr(buf, "boundary=");
2882                         if (p) {
2883                                 p += 9;
2884                                 s->mime_boundary[m++] = '\x0d';
2885                                 s->mime_boundary[m++] = '\x0a';
2886                                 s->mime_boundary[m++] = '-';
2887                                 s->mime_boundary[m++] = '-';
2888                                 while (m < sizeof(s->mime_boundary) - 1 &&
2889                                        *p && *p != ' ')
2890                                         s->mime_boundary[m++] = *p++;
2891
2892                                 s->mime_boundary[m] = '\0';
2893
2894                                 lwsl_notice("boundary '%s'\n", s->mime_boundary);
2895                         }
2896                 }
2897         }
2898
2899         return s;
2900 }
2901
2902 static int
2903 lws_urldecode_s_process(struct lws_urldecode_stateful *s, const char *in, int len)
2904 {
2905         int n, m, hit = 0;
2906         char c, was_end = 0;
2907
2908         while (len--) {
2909                 if (s->pos == s->out_len - s->mp - 1) {
2910                         if (s->output(s->data, s->name, &s->out, s->pos, 0))
2911                                 return -1;
2912
2913                         was_end = s->pos;
2914                         s->pos = 0;
2915                 }
2916                 switch (s->state) {
2917
2918                 /* states for url arg style */
2919
2920                 case US_NAME:
2921                         s->inside_quote = 0;
2922                         if (*in == '=') {
2923                                 s->name[s->pos] = '\0';
2924                                 s->pos = 0;
2925                                 s->state = US_IDLE;
2926                                 in++;
2927                                 continue;
2928                         }
2929                         if (*in == '&') {
2930                                 s->name[s->pos] = '\0';
2931                                 if (s->output(s->data, s->name, &s->out, s->pos, 1))
2932                                         return -1;
2933                                 s->pos = 0;
2934                                 s->state = US_IDLE;
2935                                 in++;
2936                                 continue;
2937                         }
2938                         if (s->pos >= sizeof(s->name) - 1) {
2939                                 lwsl_notice("Name too long\n");
2940                                 return -1;
2941                         }
2942                         s->name[s->pos++] = *in++;
2943                         break;
2944                 case US_IDLE:
2945                         if (*in == '%') {
2946                                 s->state++;
2947                                 in++;
2948                                 continue;
2949                         }
2950                         if (*in == '&') {
2951                                 s->out[s->pos] = '\0';
2952                                 if (s->output(s->data, s->name, &s->out, s->pos, 1))
2953                                         return -1;
2954                                 s->pos = 0;
2955                                 s->state = US_NAME;
2956                                 in++;
2957                                 continue;
2958                         }
2959                         if (*in == '+') {
2960                                 in++;
2961                                 s->out[s->pos++] = ' ';
2962                                 continue;
2963                         }
2964                         s->out[s->pos++] = *in++;
2965                         break;
2966                 case US_PC1:
2967                         n = char_to_hex(*in);
2968                         if (n < 0)
2969                                 return -1;
2970
2971                         in++;
2972                         s->sum = n << 4;
2973                         s->state++;
2974                         break;
2975
2976                 case US_PC2:
2977                         n = char_to_hex(*in);
2978                         if (n < 0)
2979                                 return -1;
2980
2981                         in++;
2982                         s->out[s->pos++] = s->sum | n;
2983                         s->state = US_IDLE;
2984                         break;
2985
2986
2987                 /* states for multipart / mime style */
2988
2989                 case MT_LOOK_BOUND_IN:
2990 retry_as_first:
2991                         if (*in == s->mime_boundary[s->mp] &&
2992                             s->mime_boundary[s->mp]) {
2993                                 in++;
2994                                 s->mp++;
2995                                 if (!s->mime_boundary[s->mp]) {
2996                                         s->mp = 0;
2997                                         s->state = MT_IGNORE1;
2998
2999                                         if (s->pos || was_end)
3000                                                 if (s->output(s->data, s->name,
3001                                                       &s->out, s->pos, 1))
3002                                                         return -1;
3003
3004                                         s->pos = 0;
3005
3006                                         s->content_disp[0] = '\0';
3007                                         s->name[0] = '\0';
3008                                         s->content_disp_filename[0] = '\0';
3009                                         s->boundary_real_crlf = 1;
3010                                 }
3011                                 continue;
3012                         }
3013                         if (s->mp) {
3014                                 n = 0;
3015                                 if (!s->boundary_real_crlf)
3016                                         n = 2;
3017
3018                                 memcpy(s->out + s->pos, s->mime_boundary + n, s->mp - n);
3019                                 s->pos += s->mp;
3020                                 s->mp = 0;
3021                                 goto retry_as_first;
3022                         }
3023
3024                         s->out[s->pos++] = *in;
3025                         in++;
3026                         s->mp = 0;
3027                         break;
3028
3029                 case MT_HNAME:
3030                         m = 0;
3031                         c =*in;
3032                         if (c >= 'A' && c <= 'Z')
3033                                 c += 'a' - 'A';
3034                         for (n = 0; n < ARRAY_SIZE(mp_hdr); n++)
3035                                 if (c == mp_hdr[n][s->mp]) {
3036                                         m++;
3037                                         hit = n;
3038                                 }
3039                         in++;
3040                         if (!m) {
3041                                 s->mp = 0;
3042                                 continue;
3043                         }
3044
3045                         s->mp++;
3046                         if (m != 1)
3047                                 continue;
3048
3049                         if (mp_hdr[hit][s->mp])
3050                                 continue;
3051
3052                         s->mp = 0;
3053                         s->temp[0] = '\0';
3054                         s->subname = 0;
3055
3056                         if (hit == 2)
3057                                 s->state = MT_LOOK_BOUND_IN;
3058                         else
3059                                 s->state += hit + 1;
3060                         break;
3061
3062                 case MT_DISP:
3063                         /* form-data; name="file"; filename="t.txt" */
3064
3065                         if (*in == '\x0d') {
3066 //                              lwsl_notice("disp: '%s', '%s', '%s'\n",
3067 //                                 s->content_disp, s->name,
3068 //                                 s->content_disp_filename);
3069
3070                                 if (s->content_disp_filename[0])
3071                                         if (s->output(s->data, s->name,
3072                                                       &s->out, s->pos, LWS_UFS_OPEN))
3073                                                 return -1;
3074                                 s->state = MT_IGNORE2;
3075                                 goto done;
3076                         }
3077                         if (*in == ';') {
3078                                 s->subname = 1;
3079                                 s->temp[0] = '\0';
3080                                 s->mp = 0;
3081                                 goto done;
3082                         }
3083
3084                         if (*in == '\"') {
3085                                 s->inside_quote ^= 1;
3086                                 goto done;
3087                         }
3088
3089                         if (s->subname) {
3090                                 if (*in == '=') {
3091                                         s->temp[s->mp] = '\0';
3092                                         s->subname = 0;
3093                                         s->mp = 0;
3094                                         goto done;
3095                                 }
3096                                 if (s->mp < sizeof(s->temp) - 1 &&
3097                                     (*in != ' ' || s->inside_quote))
3098                                         s->temp[s->mp++] = *in;
3099                                 goto done;
3100                         }
3101
3102                         if (!s->temp[0]) {
3103                                 if (s->mp < sizeof(s->content_disp) - 1)
3104                                         s->content_disp[s->mp++] = *in;
3105                                 s->content_disp[s->mp] = '\0';
3106                                 goto done;
3107                         }
3108
3109                         if (!strcmp(s->temp, "name")) {
3110                                 if (s->mp < sizeof(s->name) - 1)
3111                                         s->name[s->mp++] = *in;
3112                                 s->name[s->mp] = '\0';
3113                                 goto done;
3114                         }
3115
3116                         if (!strcmp(s->temp, "filename")) {
3117                                 if (s->mp < sizeof(s->content_disp_filename) - 1)
3118                                         s->content_disp_filename[s->mp++] = *in;
3119                                 s->content_disp_filename[s->mp] = '\0';
3120                                 goto done;
3121                         }
3122 done:
3123                         in++;
3124                         break;
3125
3126                 case MT_TYPE:
3127                         if (*in == '\x0d')
3128                                 s->state = MT_IGNORE2;
3129                         else {
3130                                 if (s->mp < sizeof(s->content_type) - 1)
3131                                         s->content_type[s->mp++] = *in;
3132                                 s->content_type[s->mp] = '\0';
3133                         }
3134                         in++;
3135                         break;
3136
3137                 case MT_IGNORE1:
3138                         if (*in == '\x0d')
3139                                 s->state = MT_IGNORE2;
3140                         in++;
3141                         break;
3142
3143                 case MT_IGNORE2:
3144                         s->mp = 0;
3145                         if (*in == '\x0a')
3146                                 s->state = MT_HNAME;
3147                         in++;
3148                         break;
3149                 }
3150         }
3151
3152         return 0;
3153 }
3154
3155 static int
3156 lws_urldecode_s_destroy(struct lws_urldecode_stateful *s)
3157 {
3158         int ret = 0;
3159
3160         if (s->state != US_IDLE)
3161                 ret = -1;
3162
3163         if (!ret)
3164                 if (s->output(s->data, s->name, &s->out, s->pos, 1))
3165                         ret = -1;
3166
3167         lws_free(s);
3168
3169         return ret;
3170 }
3171
3172 struct lws_spa {
3173         struct lws_urldecode_stateful *s;
3174         lws_spa_fileupload_cb opt_cb;
3175         const char * const *param_names;
3176         int count_params;
3177         char **params;
3178         int *param_length;
3179         void *opt_data;
3180
3181         char *storage;
3182         char *end;
3183         int max_storage;
3184
3185         char finalized;
3186 };
3187
3188 static int
3189 lws_urldecode_spa_lookup(struct lws_spa *spa,
3190                          const char *name)
3191 {
3192         int n;
3193
3194         for (n = 0; n < spa->count_params; n++)
3195                 if (!strcmp(spa->param_names[n], name))
3196                         return n;
3197
3198         return -1;
3199 }
3200
3201 static int
3202 lws_urldecode_spa_cb(void *data, const char *name, char **buf, int len,
3203                      int final)
3204 {
3205         struct lws_spa *spa =
3206                         (struct lws_spa *)data;
3207         int n;
3208
3209         if (spa->s->content_disp_filename[0]) {
3210                 if (spa->opt_cb) {
3211                         n = spa->opt_cb(spa->opt_data, name,
3212                                         spa->s->content_disp_filename,
3213                                         *buf, len, final);
3214
3215                         if (n < 0)
3216                                 return -1;
3217                 }
3218                 return 0;
3219         }
3220         n = lws_urldecode_spa_lookup(spa, name);
3221
3222         if (n == -1 || !len) /* unrecognized */
3223                 return 0;
3224
3225         if (!spa->params[n])
3226                 spa->params[n] = *buf;
3227
3228         if ((*buf) + len >= spa->end) {
3229                 lwsl_notice("%s: exceeded storage\n", __func__);
3230                 return -1;
3231         }
3232
3233         spa->param_length[n] += len;
3234
3235         /* move it on inside storage */
3236         (*buf) += len;
3237         *((*buf)++) = '\0';
3238
3239         spa->s->out_len -= len + 1;
3240
3241         return 0;
3242 }
3243
3244 LWS_VISIBLE LWS_EXTERN struct lws_spa *
3245 lws_spa_create(struct lws *wsi, const char * const *param_names,
3246                          int count_params, int max_storage,
3247                          lws_spa_fileupload_cb opt_cb, void *opt_data)
3248 {
3249         struct lws_spa *spa = lws_zalloc(sizeof(*spa));
3250
3251         if (!spa)
3252                 return NULL;
3253
3254         spa->param_names = param_names;
3255         spa->count_params = count_params;
3256         spa->max_storage = max_storage;
3257         spa->opt_cb = opt_cb;
3258         spa->opt_data = opt_data;
3259
3260         spa->storage = lws_malloc(max_storage);
3261         if (!spa->storage)
3262                 goto bail2;
3263         spa->end = spa->storage + max_storage - 1;
3264
3265         spa->params = lws_zalloc(sizeof(char *) * count_params);
3266         if (!spa->params)
3267                 goto bail3;
3268
3269         spa->s = lws_urldecode_s_create(wsi, spa->storage, max_storage, spa,
3270                                         lws_urldecode_spa_cb);
3271         if (!spa->s)
3272                 goto bail4;
3273
3274         spa->param_length = lws_zalloc(sizeof(int) * count_params);
3275         if (!spa->param_length)
3276                 goto bail5;
3277
3278         lwsl_info("%s: Created SPA %p\n", __func__, spa);
3279
3280         return spa;
3281
3282 bail5:
3283         lws_urldecode_s_destroy(spa->s);
3284 bail4:
3285         lws_free(spa->params);
3286 bail3:
3287         lws_free(spa->storage);
3288 bail2:
3289         lws_free(spa);
3290
3291         return NULL;
3292 }
3293
3294 LWS_VISIBLE LWS_EXTERN int
3295 lws_spa_process(struct lws_spa *ludspa, const char *in, int len)
3296 {
3297         if (!ludspa) {
3298                 lwsl_err("%s: NULL spa\n", __func__);
3299                 return -1;
3300         }
3301         /* we reject any junk after the last part arrived and we finalized */
3302         if (ludspa->finalized)
3303                 return 0;
3304
3305         return lws_urldecode_s_process(ludspa->s, in, len);
3306 }
3307
3308 LWS_VISIBLE LWS_EXTERN int
3309 lws_spa_get_length(struct lws_spa *ludspa, int n)
3310 {
3311         if (n >= ludspa->count_params)
3312                 return 0;
3313
3314         return ludspa->param_length[n];
3315 }
3316
3317 LWS_VISIBLE LWS_EXTERN const char *
3318 lws_spa_get_string(struct lws_spa *ludspa, int n)
3319 {
3320         if (n >= ludspa->count_params)
3321                 return NULL;
3322
3323         return ludspa->params[n];
3324 }
3325
3326 LWS_VISIBLE LWS_EXTERN int
3327 lws_spa_finalize(struct lws_spa *spa)
3328 {
3329         if (spa->s) {
3330                 lws_urldecode_s_destroy(spa->s);
3331                 spa->s = NULL;
3332         }
3333
3334         spa->finalized = 1;
3335
3336         return 0;
3337 }
3338
3339 LWS_VISIBLE LWS_EXTERN int
3340 lws_spa_destroy(struct lws_spa *spa)
3341 {
3342         int n = 0;
3343
3344         lwsl_notice("%s: destroy spa %p\n", __func__, spa);
3345
3346         if (spa->s)
3347                 lws_urldecode_s_destroy(spa->s);
3348
3349         lwsl_debug("%s %p %p %p %p\n", __func__,
3350                         spa->param_length,
3351                         spa->params,
3352                         spa->storage,
3353                         spa
3354                         );
3355
3356         lws_free(spa->param_length);
3357         lws_free(spa->params);
3358         lws_free(spa->storage);
3359         lws_free(spa);
3360
3361         return n;
3362 }
3363
3364 #if 0
3365 LWS_VISIBLE LWS_EXTERN int
3366 lws_spa_destroy(struct lws_spa *spa)
3367 {
3368         int n = 0;
3369
3370         lwsl_info("%s: destroy spa %p\n", __func__, spa);
3371
3372         if (spa->s)
3373                 lws_urldecode_s_destroy(spa->s);
3374
3375         lwsl_debug("%s\n", __func__);
3376
3377         lws_free(spa->param_length);
3378         lws_free(spa->params);
3379         lws_free(spa->storage);
3380         lws_free(spa);
3381
3382         return n;
3383 }
3384 #endif
3385 LWS_VISIBLE LWS_EXTERN int
3386 lws_chunked_html_process(struct lws_process_html_args *args,
3387                          struct lws_process_html_state *s)
3388 {
3389         char *sp, buffer[32];
3390         const char *pc;
3391         int old_len, n;
3392
3393         /* do replacements */
3394         sp = args->p;
3395         old_len = args->len;
3396         args->len = 0;
3397         s->start = sp;
3398         while (sp < args->p + old_len) {
3399
3400                 if (args->len + 7 >= args->max_len) {
3401                         lwsl_err("Used up interpret padding\n");
3402                         return -1;
3403                 }
3404
3405                 if ((!s->pos && *sp == '$') || s->pos) {
3406                         int hits = 0, hit = 0;
3407
3408                         if (!s->pos)
3409                                 s->start = sp;
3410                         s->swallow[s->pos++] = *sp;
3411                         if (s->pos == sizeof(s->swallow) - 1)
3412                                 goto skip;
3413                         for (n = 0; n < s->count_vars; n++)
3414                                 if (!strncmp(s->swallow, s->vars[n], s->pos)) {
3415                                         hits++;
3416                                         hit = n;
3417                                 }
3418                         if (!hits) {
3419 skip:
3420                                 s->swallow[s->pos] = '\0';
3421                                 memcpy(s->start, s->swallow, s->pos);
3422                                 args->len++;
3423                                 s->pos = 0;
3424                                 sp = s->start + 1;
3425                                 continue;
3426                         }
3427                         if (hits == 1 && s->pos == strlen(s->vars[hit])) {
3428                                 pc = s->replace(s->data, hit);
3429                                 if (!pc)
3430                                         pc = "NULL";
3431                                 n = strlen(pc);
3432                                 s->swallow[s->pos] = '\0';
3433                                 if (n != s->pos) {
3434                                         memmove(s->start + n,
3435                                                 s->start + s->pos,
3436                                                 old_len - (sp - args->p));
3437                                         old_len += (n - s->pos) + 1;
3438                                 }
3439                                 memcpy(s->start, pc, n);
3440                                 args->len++;
3441                                 sp = s->start + 1;
3442
3443                                 s->pos = 0;
3444                         }
3445                         sp++;
3446                         continue;
3447                 }
3448
3449                 args->len++;
3450                 sp++;
3451         }
3452
3453         /* no space left for final chunk trailer */
3454         if (args->final && args->len + 7 >= args->max_len)
3455                 return -1;
3456
3457         n = sprintf(buffer, "%X\x0d\x0a", args->len);
3458
3459         args->p -= n;
3460         memcpy(args->p, buffer, n);
3461         args->len += n;
3462
3463         if (args->final) {
3464                 sp = args->p + args->len;
3465                 *sp++ = '\x0d';
3466                 *sp++ = '\x0a';
3467                 *sp++ = '0';
3468                 *sp++ = '\x0d';
3469                 *sp++ = '\x0a';
3470                 *sp++ = '\x0d';
3471                 *sp++ = '\x0a';
3472                 args->len += 7;
3473         } else {
3474                 sp = args->p + args->len;
3475                 *sp++ = '\x0d';
3476                 *sp++ = '\x0a';
3477                 args->len += 2;
3478         }
3479
3480         return 0;
3481 }