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