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