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