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