post example in test server
[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 int
26 lws_context_init_server(struct lws_context_creation_info *info,
27                         struct lws_vhost *vhost)
28 {
29 #ifdef LWS_POSIX
30         int n, opt = 1, limit = 1;
31 #endif
32         lws_sockfd_type sockfd;
33         struct lws_vhost *vh;
34         struct lws *wsi;
35         int m = 0;
36
37         /* set up our external listening socket we serve on */
38
39         if (info->port == CONTEXT_PORT_NO_LISTEN)
40                 return 0;
41
42         vh = vhost->context->vhost_list;
43         while (vh) {
44                 if (vh->listen_port == info->port) {
45                         if ((!info->iface && !vh->iface) ||
46                             (info->iface && vh->iface &&
47                             !strcmp(info->iface, vh->iface))) {
48                                 vhost->listen_port = info->port;
49                                 vhost->iface = info->iface;
50                                 lwsl_notice(" using listen skt from vhost %s\n",
51                                             vh->name);
52                                 return 0;
53                         }
54                 }
55                 vh = vh->vhost_next;
56         }
57
58 #if LWS_POSIX
59 #if defined(__linux__)
60         limit = vhost->context->count_threads;
61 #endif
62
63         for (m = 0; m < limit; m++) {
64 #ifdef LWS_USE_UNIX_SOCK
65         if (LWS_UNIX_SOCK_ENABLED(vhost))
66                 sockfd = socket(AF_UNIX, SOCK_STREAM, 0);
67         else
68 #endif
69 #ifdef LWS_USE_IPV6
70         if (LWS_IPV6_ENABLED(context))
71                 sockfd = socket(AF_INET6, SOCK_STREAM, 0);
72         else
73 #endif
74                 sockfd = socket(AF_INET, SOCK_STREAM, 0);
75
76         if (sockfd == -1) {
77 #else
78         sockfd = mbed3_create_tcp_stream_socket();
79         if (!lws_sockfd_valid(sockfd)) {
80 #endif
81                 lwsl_err("ERROR opening socket\n");
82                 return 1;
83         }
84
85 #if LWS_POSIX
86         /*
87          * allow us to restart even if old sockets in TIME_WAIT
88          */
89         if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
90                        (const void *)&opt, sizeof(opt)) < 0) {
91                 compatible_close(sockfd);
92                 return 1;
93         }
94 #if defined(__linux__) && defined(SO_REUSEPORT) && LWS_MAX_SMP > 1
95         if (vhost->context->count_threads > 1)
96                 if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEPORT,
97                                 (const void *)&opt, sizeof(opt)) < 0) {
98                         compatible_close(sockfd);
99                         return 1;
100                 }
101 #endif
102 #endif
103         lws_plat_set_socket_options(vhost, sockfd);
104
105 #if LWS_POSIX
106         n = lws_socket_bind(vhost, sockfd, info->port, info->iface);
107         if (n < 0)
108                 goto bail;
109         info->port = n;
110 #endif
111         vhost->listen_port = info->port;
112         vhost->iface = info->iface;
113
114         wsi = lws_zalloc(sizeof(struct lws));
115         if (wsi == NULL) {
116                 lwsl_err("Out of mem\n");
117                 goto bail;
118         }
119         wsi->context = vhost->context;
120         wsi->sock = sockfd;
121         wsi->mode = LWSCM_SERVER_LISTENER;
122         wsi->protocol = vhost->protocols;
123         wsi->tsi = m;
124         wsi->vhost = vhost;
125         wsi->listener = 1;
126
127         vhost->context->pt[m].wsi_listening = wsi;
128         if (insert_wsi_socket_into_fds(vhost->context, wsi))
129                 goto bail;
130
131         vhost->context->count_wsi_allocated++;
132         vhost->lserv_wsi = wsi;
133
134 #if LWS_POSIX
135         listen(wsi->sock, LWS_SOMAXCONN);
136         } /* for each thread able to independently listen */
137 #else
138         mbed3_tcp_stream_bind(wsi->sock, info->port, wsi);
139 #endif
140         if (!lws_check_opt(info->options, LWS_SERVER_OPTION_EXPLICIT_VHOSTS)) {
141 #ifdef LWS_USE_UNIX_SOCK
142                 if (LWS_UNIX_SOCK_ENABLED(vhost))
143                         lwsl_notice(" Listening on \"%s\"\n", info->iface);
144                 else
145 #endif
146                         lwsl_notice(" Listening on port %d\n", info->port);
147         }
148
149         return 0;
150
151 bail:
152         compatible_close(sockfd);
153
154         return 1;
155 }
156
157 int
158 _lws_server_listen_accept_flow_control(struct lws *twsi, int on)
159 {
160         struct lws_context_per_thread *pt = &twsi->context->pt[(int)twsi->tsi];
161         struct lws *wsi = pt->wsi_listening;
162         int n;
163
164         if (!wsi || twsi->context->being_destroyed)
165                 return 0;
166
167         lwsl_debug("%s: Thr %d: LISTEN wsi %p: state %d\n",
168                    __func__, twsi->tsi, (void *)wsi, on);
169
170         if (on)
171                 n = lws_change_pollfd(wsi, 0, LWS_POLLIN);
172         else
173                 n = lws_change_pollfd(wsi, LWS_POLLIN, 0);
174
175         return n;
176 }
177
178 struct lws_vhost *
179 lws_select_vhost(struct lws_context *context, int port, const char *servername)
180 {
181         struct lws_vhost *vhost = context->vhost_list;
182
183         while (vhost) {
184                 if (port == vhost->listen_port &&
185                     !strcmp(vhost->name, servername)) {
186                         lwsl_info("SNI: Found: %s\n", servername);
187                         return vhost;
188                 }
189                 vhost = vhost->vhost_next;
190         }
191
192         return NULL;
193 }
194
195 static const char * get_mimetype(const char *file)
196 {
197         int n = strlen(file);
198
199         if (n < 5)
200                 return NULL;
201
202         if (!strcmp(&file[n - 4], ".ico"))
203                 return "image/x-icon";
204
205         if (!strcmp(&file[n - 4], ".gif"))
206                 return "image/gif";
207
208         if (!strcmp(&file[n - 3], ".js"))
209                 return "text/javascript";
210
211         if (!strcmp(&file[n - 4], ".png"))
212                 return "image/png";
213
214         if (!strcmp(&file[n - 4], ".jpg"))
215                 return "image/jpeg";
216
217         if (!strcmp(&file[n - 5], ".html"))
218                 return "text/html";
219
220         if (!strcmp(&file[n - 4], ".css"))
221                 return "text/css";
222
223         if (!strcmp(&file[n - 4], ".ttf"))
224                 return "application/x-font-ttf";
225
226         return NULL;
227 }
228
229 int lws_http_serve(struct lws *wsi, char *uri, const char *origin)
230 {
231         const char *mimetype;
232         struct stat st;
233         char path[256], sym[256];
234         unsigned char *p = (unsigned char *)sym + 32 + LWS_PRE, *start = p;
235         unsigned char *end = p + sizeof(sym) - 32 - LWS_PRE;
236         size_t len;
237         int n, spin = 0;
238
239         snprintf(path, sizeof(path) - 1, "%s/%s", origin, uri);
240
241         do {
242                 spin++;
243
244                 if (stat(path, &st)) {
245                         lwsl_info("unable to stat %s\n", path);
246                         goto bail;
247                 }
248
249                 lwsl_debug(" %s mode %d\n", path, S_IFMT & st.st_mode);
250 #if !defined(WIN32)
251                 if ((S_IFMT & st.st_mode) == S_IFLNK) {
252                         len = readlink(path, sym, sizeof(sym) - 1);
253                         if (len) {
254                                 lwsl_err("Failed to read link %s\n", path);
255                                 goto bail;
256                         }
257                         sym[len] = '\0';
258                         lwsl_debug("symlink %s -> %s\n", path, sym);
259                         snprintf(path, sizeof(path) - 1, "%s", sym);
260                 }
261 #endif
262                 if ((S_IFMT & st.st_mode) == S_IFDIR) {
263                         lwsl_debug("default filename append to dir\n");
264                         snprintf(path, sizeof(path) - 1, "%s/%s/index.html",
265                                  origin, uri);
266                 }
267
268         } while ((S_IFMT & st.st_mode) != S_IFREG && spin < 5);
269
270         if (spin == 5)
271                 lwsl_err("symlink loop %s \n", path);
272
273         n = sprintf(sym, "%08lX%08lX", (unsigned long)st.st_size,
274                                    (unsigned long)st.st_mtime);
275
276         if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_IF_NONE_MATCH)) {
277                 /*
278                  * he thinks he has some version of it already,
279                  * check if the tag matches
280                  */
281                 if (!strcmp(sym, lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_IF_NONE_MATCH))) {
282
283                         lwsl_debug("%s: ETAG match %s %s\n", __func__,
284                                    uri, origin);
285
286                         /* we don't need to send the payload */
287                         if (lws_add_http_header_status(wsi, 304, &p, end))
288                                 return -1;
289                         if (lws_add_http_header_by_token(wsi,
290                                         WSI_TOKEN_HTTP_ETAG,
291                                         (unsigned char *)sym, n, &p, end))
292                                 return -1;
293                         if (lws_finalize_http_header(wsi, &p, end))
294                                 return -1;
295
296                         n = lws_write(wsi, start, p - start,
297                                         LWS_WRITE_HTTP_HEADERS);
298                         if (n != (p - start)) {
299                                 lwsl_err("_write returned %d from %d\n", n, p - start);
300                                 return -1;
301                         }
302
303                         return lws_http_transaction_completed(wsi);
304                 }
305         }
306
307         if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_ETAG,
308                         (unsigned char *)sym, n, &p, end))
309                 return -1;
310
311         mimetype = get_mimetype(path);
312         if (!mimetype) {
313                 lwsl_err("unknown mimetype for %s", path);
314                 goto bail;
315         }
316
317         n = lws_serve_http_file(wsi, path, mimetype, (char *)start, p - start);
318
319         if (n < 0 || ((n > 0) && lws_http_transaction_completed(wsi)))
320                 return -1; /* error or can't reuse connection: close the socket */
321
322         return 0;
323 bail:
324
325         return -1;
326 }
327
328 int
329 lws_http_action(struct lws *wsi)
330 {
331         struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
332         enum http_connection_type connection_type;
333         enum http_version request_version;
334         char content_length_str[32];
335         struct lws_http_mount *hm, *hit = NULL;
336         unsigned int n, count = 0;
337         char http_version_str[10];
338         char http_conn_str[20];
339         int http_version_len;
340         char *uri_ptr = NULL;
341         int uri_len = 0, best = 0;
342         int meth = -1;
343
344         static const unsigned char methods[] = {
345                 WSI_TOKEN_GET_URI,
346                 WSI_TOKEN_POST_URI,
347                 WSI_TOKEN_OPTIONS_URI,
348                 WSI_TOKEN_PUT_URI,
349                 WSI_TOKEN_PATCH_URI,
350                 WSI_TOKEN_DELETE_URI,
351 #ifdef LWS_USE_HTTP2
352                 WSI_TOKEN_HTTP_COLON_PATH,
353 #endif
354         };
355 #if defined(_DEBUG) || defined(LWS_WITH_ACCESS_LOG)
356         static const char * const method_names[] = {
357                 "GET", "POST", "OPTIONS", "PUT", "PATCH", "DELETE",
358 #ifdef LWS_USE_HTTP2
359                 ":path",
360 #endif
361         };
362 #endif
363
364         /* it's not websocket.... shall we accept it as http? */
365
366         for (n = 0; n < ARRAY_SIZE(methods); n++)
367                 if (lws_hdr_total_length(wsi, methods[n]))
368                         count++;
369         if (!count) {
370                 lwsl_warn("Missing URI in HTTP request\n");
371                 goto bail_nuke_ah;
372         }
373
374         if (count != 1) {
375                 lwsl_warn("multiple methods?\n");
376                 goto bail_nuke_ah;
377         }
378
379         if (lws_ensure_user_space(wsi))
380                 goto bail_nuke_ah;
381
382         for (n = 0; n < ARRAY_SIZE(methods); n++)
383                 if (lws_hdr_total_length(wsi, methods[n])) {
384                         uri_ptr = lws_hdr_simple_ptr(wsi, methods[n]);
385                         uri_len = lws_hdr_total_length(wsi, methods[n]);
386                         lwsl_info("Method: %s request for '%s'\n",
387                                         method_names[n], uri_ptr);
388                         meth = n;
389                         break;
390                 }
391
392         (void)meth;
393
394         /* we insist on absolute paths */
395
396         if (uri_ptr[0] != '/') {
397                 lws_return_http_status(wsi, HTTP_STATUS_FORBIDDEN, NULL);
398
399                 goto bail_nuke_ah;
400         }
401
402         /* HTTP header had a content length? */
403
404         wsi->u.http.content_length = 0;
405         if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI) ||
406                 lws_hdr_total_length(wsi, WSI_TOKEN_PATCH_URI) ||
407                 lws_hdr_total_length(wsi, WSI_TOKEN_PUT_URI))
408                 wsi->u.http.content_length = 100 * 1024 * 1024;
409
410         if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH)) {
411                 lws_hdr_copy(wsi, content_length_str,
412                              sizeof(content_length_str) - 1,
413                              WSI_TOKEN_HTTP_CONTENT_LENGTH);
414                 wsi->u.http.content_length = atoi(content_length_str);
415         }
416
417         if (wsi->http2_substream) {
418                 wsi->u.http.request_version = HTTP_VERSION_2;
419         } else {
420                 /* http_version? Default to 1.0, override with token: */
421                 request_version = HTTP_VERSION_1_0;
422
423                 /* Works for single digit HTTP versions. : */
424                 http_version_len = lws_hdr_total_length(wsi, WSI_TOKEN_HTTP);
425                 if (http_version_len > 7) {
426                         lws_hdr_copy(wsi, http_version_str,
427                                         sizeof(http_version_str) - 1, WSI_TOKEN_HTTP);
428                         if (http_version_str[5] == '1' && http_version_str[7] == '1')
429                                 request_version = HTTP_VERSION_1_1;
430                 }
431                 wsi->u.http.request_version = request_version;
432
433                 /* HTTP/1.1 defaults to "keep-alive", 1.0 to "close" */
434                 if (request_version == HTTP_VERSION_1_1)
435                         connection_type = HTTP_CONNECTION_KEEP_ALIVE;
436                 else
437                         connection_type = HTTP_CONNECTION_CLOSE;
438
439                 /* Override default if http "Connection:" header: */
440                 if (lws_hdr_total_length(wsi, WSI_TOKEN_CONNECTION)) {
441                         lws_hdr_copy(wsi, http_conn_str, sizeof(http_conn_str) - 1,
442                                      WSI_TOKEN_CONNECTION);
443                         http_conn_str[sizeof(http_conn_str) - 1] = '\0';
444                         if (!strcasecmp(http_conn_str, "keep-alive"))
445                                 connection_type = HTTP_CONNECTION_KEEP_ALIVE;
446                         else
447                                 if (!strcasecmp(http_conn_str, "close"))
448                                         connection_type = HTTP_CONNECTION_CLOSE;
449                 }
450                 wsi->u.http.connection_type = connection_type;
451         }
452
453         n = wsi->protocol->callback(wsi, LWS_CALLBACK_FILTER_HTTP_CONNECTION,
454                                     wsi->user_space, uri_ptr, uri_len);
455         if (n) {
456                 lwsl_info("LWS_CALLBACK_HTTP closing\n");
457
458                 return 1;
459         }
460         /*
461          * if there is content supposed to be coming,
462          * put a timeout on it having arrived
463          */
464         lws_set_timeout(wsi, PENDING_TIMEOUT_HTTP_CONTENT,
465                         wsi->context->timeout_secs);
466 #ifdef LWS_OPENSSL_SUPPORT
467         if (wsi->redirect_to_https) {
468                 /*
469                  * we accepted http:// only so we could redirect to
470                  * https://, so issue the redirect.  Create the redirection
471                  * URI from the host: header and ignore the path part
472                  */
473                 unsigned char *start = pt->serv_buf + LWS_PRE, *p = start,
474                               *end = p + 512;
475
476                 if (!lws_hdr_total_length(wsi, WSI_TOKEN_HOST))
477                         goto bail_nuke_ah;
478
479                 n = sprintf((char *)end, "https://%s/",
480                             lws_hdr_simple_ptr(wsi, WSI_TOKEN_HOST));
481
482                 n = lws_http_redirect(wsi, HTTP_STATUS_MOVED_PERMANENTLY,
483                                       end, n, &p, end);
484                 if ((int)n < 0)
485                         goto bail_nuke_ah;
486
487                 return lws_http_transaction_completed(wsi);
488         }
489 #endif
490
491 #ifdef LWS_WITH_ACCESS_LOG
492         /*
493          * Produce Apache-compatible log string for wsi, like this:
494          *
495          * 2.31.234.19 - - [27/Mar/2016:03:22:44 +0800]
496          * "GET /aep-screen.png HTTP/1.1"
497          * 200 152987 "https://libwebsockets.org/index.html"
498          * "Mozilla/5.0 (Macint... Chrome/49.0.2623.87 Safari/537.36"
499          *
500          */
501         {
502                 static const char * const hver[] = {
503                         "http/1.0", "http/1.1", "http/2"
504                 };
505 #ifdef LWS_USE_IPV6
506                 char ads[INET6_ADDRSTRLEN];
507 #else
508                 char ads[INET_ADDRSTRLEN];
509 #endif
510                 char da[64];
511                 const char *pa, *me;
512                 struct tm *tmp;
513                 time_t t = time(NULL);
514                 int l = 256;
515
516                 if (wsi->access_log_pending)
517                         lws_access_log(wsi);
518
519                 wsi->access_log.header_log = lws_malloc(l);
520
521                 tmp = localtime(&t);
522                 if (tmp)
523                         strftime(da, sizeof(da), "%d/%b/%Y:%H:%M:%S %z", tmp);
524                 else
525                         strcpy(da, "01/Jan/1970:00:00:00 +0000");
526
527                 pa = lws_get_peer_simple(wsi, ads, sizeof(ads));
528                 if (!pa)
529                         pa = "(unknown)";
530
531                 if (meth >= 0)
532                         me = method_names[meth];
533                 else
534                         me = "unknown";
535
536                 snprintf(wsi->access_log.header_log, l,
537                          "%s - - [%s] \"%s %s %s\"",
538                          pa, da, me, uri_ptr,
539                          hver[wsi->u.http.request_version]);
540
541                 l = lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_USER_AGENT);
542                 if (l) {
543                         wsi->access_log.user_agent = lws_malloc(l + 2);
544                         lws_hdr_copy(wsi, wsi->access_log.user_agent,
545                                      l + 1, WSI_TOKEN_HTTP_USER_AGENT);
546                 }
547                 wsi->access_log_pending = 1;
548         }
549 #endif
550
551         /* can we serve it from the mount list? */
552
553         hm = wsi->vhost->mount_list;
554         while (hm) {
555                 if (uri_len >= hm->mountpoint_len &&
556                     !strncmp(uri_ptr, hm->mountpoint, hm->mountpoint_len) &&
557                     (uri_ptr[hm->mountpoint_len] == '\0' ||
558                      uri_ptr[hm->mountpoint_len] == '/' ||
559                      hm->mountpoint_len == 1)
560                     ) {
561                         if ((hm->origin_protocol == LWSMPRO_CGI ||
562                              lws_hdr_total_length(wsi, WSI_TOKEN_GET_URI)) &&
563                             hm->mountpoint_len > best) {
564                                 best = hm->mountpoint_len;
565                                 hit = hm;
566                         }
567                 }
568                 hm = hm->mount_next;
569         }
570         if (hit) {
571                 char *s = uri_ptr + hit->mountpoint_len;
572
573                 lwsl_debug("*** hit %d %d %s\n", hit->mountpoint_len,
574                            hit->origin_protocol , hit->origin);
575
576                 /*
577                  * if we have a mountpoint like https://xxx.com/yyy
578                  * there is an implied / at the end for our purposes since
579                  * we can only mount on a "directory".
580                  *
581                  * But if we just go with that, the browser cannot understand
582                  * that he is actually looking down one "directory level", so
583                  * even though we give him /yyy/abc.html he acts like the
584                  * current directory level is /.  So relative urls like "x.png"
585                  * wrongly look outside the mountpoint.
586                  *
587                  * Therefore if we didn't come in on a url with an explicit
588                  * / at the end, we must redirect to add it so the browser
589                  * understands he is one "directory level" down.
590                  */
591                 if ((hit->mountpoint_len > 1 || (hit->origin_protocol & 4)) &&
592                     (*s != '/' || (hit->origin_protocol & 4)) &&
593                     (hit->origin_protocol != LWSMPRO_CGI)) {
594                         unsigned char *start = pt->serv_buf + LWS_PRE,
595                                               *p = start, *end = p + 512;
596                         static const char *oprot[] = {
597                                 "http://", "https://"
598                         };
599
600                         lwsl_debug("Doing 301 '%s' org %s\n", s, hit->origin);
601
602                         if (!lws_hdr_total_length(wsi, WSI_TOKEN_HOST))
603                                 goto bail_nuke_ah;
604
605                         /* > at start indicates deal with by redirect */
606                         if (hit->origin_protocol & 4)
607                                 n = snprintf((char *)end, 256, "%s%s",
608                                             oprot[hit->origin_protocol & 1],
609                                             hit->origin);
610                         else
611                                 n = snprintf((char *)end, 256,
612                                     "https://%s/%s/",
613                                     lws_hdr_simple_ptr(wsi, WSI_TOKEN_HOST),
614                                     uri_ptr);
615
616                         n = lws_http_redirect(wsi, HTTP_STATUS_MOVED_PERMANENTLY,
617                                               end, n, &p, end);
618                         if ((int)n < 0)
619                                 goto bail_nuke_ah;
620
621                         return lws_http_transaction_completed(wsi);
622                 }
623
624 #ifdef LWS_WITH_CGI
625                 /* did we hit something with a cgi:// origin? */
626                 if (hit->origin_protocol == LWSMPRO_CGI) {
627                         const char *cmd[] = {
628                                 NULL, /* replace with cgi path */
629                                 NULL
630                         };
631                         unsigned char *p, *end, buffer[256];
632
633                         lwsl_debug("%s: cgi\n", __func__);
634                         cmd[0] = hit->origin;
635
636                         n = 5;
637                         if (hit->cgi_timeout)
638                                 n = hit->cgi_timeout;
639
640                         n = lws_cgi(wsi, cmd, hit->mountpoint_len, n,
641                                     hit->cgienv);
642                         if (n) {
643                                 lwsl_err("%s: cgi failed\n");
644                                 return -1;
645                         }
646                         p = buffer + LWS_PRE;
647                         end = p + sizeof(buffer) - LWS_PRE;
648
649                         if (lws_add_http_header_status(wsi, 200, &p, end))
650                                 return 1;
651                         if (lws_add_http_header_by_token(wsi, WSI_TOKEN_CONNECTION,
652                                         (unsigned char *)"close", 5, &p, end))
653                                 return 1;
654                         n = lws_write(wsi, buffer + LWS_PRE,
655                                       p - (buffer + LWS_PRE),
656                                       LWS_WRITE_HTTP_HEADERS);
657
658                         goto deal_body;
659                 }
660 #endif
661
662                 n = strlen(s);
663                 if (s[0] == '\0' || (n == 1 && s[n - 1] == '/'))
664                         s = (char *)hit->def;
665                 if (!s)
666                         s = "index.html";
667
668                 wsi->cache_secs = hit->cache_max_age;
669                 wsi->cache_reuse = hit->cache_reusable;
670                 wsi->cache_revalidate = hit->cache_revalidate;
671                 wsi->cache_intermediaries = hit->cache_intermediaries;
672
673                 n = lws_http_serve(wsi, s, hit->origin);
674                 if (n) {
675                         /*
676                          *      lws_return_http_status(wsi, HTTP_STATUS_NOT_FOUND, NULL);
677                          */
678                         n = wsi->protocol->callback(wsi, LWS_CALLBACK_HTTP,
679                                             wsi->user_space, uri_ptr, uri_len);
680                 }
681         } else
682                 n = wsi->protocol->callback(wsi, LWS_CALLBACK_HTTP,
683                                     wsi->user_space, uri_ptr, uri_len);
684
685         if (n) {
686                 lwsl_info("LWS_CALLBACK_HTTP closing\n");
687
688                 return 1;
689         }
690
691 #ifdef LWS_WITH_CGI
692 deal_body:
693 #endif
694         /*
695          * If we're not issuing a file, check for content_length or
696          * HTTP keep-alive. No keep-alive header allocation for
697          * ISSUING_FILE, as this uses HTTP/1.0.
698          *
699          * In any case, return 0 and let lws_read decide how to
700          * proceed based on state
701          */
702         if (wsi->state != LWSS_HTTP_ISSUING_FILE)
703                 /* Prepare to read body if we have a content length: */
704                 if (wsi->u.http.content_length > 0)
705                         wsi->state = LWSS_HTTP_BODY;
706
707         return 0;
708
709 bail_nuke_ah:
710         /* we're closing, losing some rx is OK */
711         wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
712         lws_header_table_detach(wsi, 1);
713
714         return 1;
715 }
716
717
718 int
719 lws_handshake_server(struct lws *wsi, unsigned char **buf, size_t len)
720 {
721         struct lws_context *context = lws_get_context(wsi);
722         struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
723         struct _lws_header_related hdr;
724         struct allocated_headers *ah;
725         int protocol_len, n, hit;
726         char protocol_list[128];
727         char protocol_name[32];
728         char *p;
729
730         assert(len < 10000000);
731         assert(wsi->u.hdr.ah);
732
733         while (len--) {
734                 wsi->more_rx_waiting = !!len;
735
736                 if (wsi->mode != LWSCM_HTTP_SERVING &&
737                     wsi->mode != LWSCM_HTTP_SERVING_ACCEPTED) {
738                         lwsl_err("%s: bad wsi mode %d\n", __func__, wsi->mode);
739                         goto bail_nuke_ah;
740                 }
741
742                 if (lws_parse(wsi, *(*buf)++)) {
743                         lwsl_info("lws_parse failed\n");
744                         goto bail_nuke_ah;
745                 }
746
747                 if (wsi->u.hdr.parser_state != WSI_PARSING_COMPLETE)
748                         continue;
749
750                 lwsl_parser("%s: lws_parse sees parsing complete\n", __func__);
751                 lwsl_debug("%s: wsi->more_rx_waiting=%d\n", __func__,
752                                 wsi->more_rx_waiting);
753
754                 /* select vhost */
755
756                 if (lws_hdr_total_length(wsi, WSI_TOKEN_HOST)) {
757                         struct lws_vhost *vhost = lws_select_vhost(
758                                 context, wsi->vhost->listen_port,
759                                 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HOST));
760
761                         if (vhost)
762                                 wsi->vhost = vhost;
763                 }
764
765                 wsi->vhost->trans++;
766                 if (!wsi->conn_stat_done) {
767                         wsi->vhost->conn++;
768                         wsi->conn_stat_done = 1;
769                 }
770
771                 wsi->mode = LWSCM_PRE_WS_SERVING_ACCEPT;
772                 lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
773
774                 /* is this websocket protocol or normal http 1.0? */
775
776                 if (lws_hdr_total_length(wsi, WSI_TOKEN_UPGRADE)) {
777                         if (!strcasecmp(lws_hdr_simple_ptr(wsi, WSI_TOKEN_UPGRADE),
778                                         "websocket")) {
779                                 wsi->vhost->ws_upgrades++;
780                                 lwsl_info("Upgrade to ws\n");
781                                 goto upgrade_ws;
782                         }
783 #ifdef LWS_USE_HTTP2
784                         if (!strcasecmp(lws_hdr_simple_ptr(wsi, WSI_TOKEN_UPGRADE),
785                                         "h2c")) {
786                                 wsi->vhost->http2_upgrades++;
787                                 lwsl_info("Upgrade to h2c\n");
788                                 goto upgrade_h2c;
789                         }
790 #endif
791                         lwsl_err("Unknown upgrade\n");
792                         /* dunno what he wanted to upgrade to */
793                         goto bail_nuke_ah;
794                 }
795
796                 /* no upgrade ack... he remained as HTTP */
797
798                 lwsl_info("No upgrade\n");
799                 ah = wsi->u.hdr.ah;
800
801                 lws_union_transition(wsi, LWSCM_HTTP_SERVING_ACCEPTED);
802                 wsi->state = LWSS_HTTP;
803                 wsi->u.http.fd = LWS_INVALID_FILE;
804
805                 /* expose it at the same offset as u.hdr */
806                 wsi->u.http.ah = ah;
807                 lwsl_debug("%s: wsi %p: ah %p\n", __func__, (void *)wsi,
808                            (void *)wsi->u.hdr.ah);
809
810                 n = lws_http_action(wsi);
811
812                 return n;
813
814 #ifdef LWS_USE_HTTP2
815 upgrade_h2c:
816                 if (!lws_hdr_total_length(wsi, WSI_TOKEN_HTTP2_SETTINGS)) {
817                         lwsl_err("missing http2_settings\n");
818                         goto bail_nuke_ah;
819                 }
820
821                 lwsl_err("h2c upgrade...\n");
822
823                 p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP2_SETTINGS);
824                 /* convert the peer's HTTP-Settings */
825                 n = lws_b64_decode_string(p, protocol_list,
826                                           sizeof(protocol_list));
827                 if (n < 0) {
828                         lwsl_parser("HTTP2_SETTINGS too long\n");
829                         return 1;
830                 }
831
832                 /* adopt the header info */
833
834                 ah = wsi->u.hdr.ah;
835
836                 lws_union_transition(wsi, LWSCM_HTTP2_SERVING);
837
838                 /* http2 union member has http union struct at start */
839                 wsi->u.http.ah = ah;
840
841                 lws_http2_init(&wsi->u.http2.peer_settings);
842                 lws_http2_init(&wsi->u.http2.my_settings);
843
844                 /* HTTP2 union */
845
846                 lws_http2_interpret_settings_payload(&wsi->u.http2.peer_settings,
847                                 (unsigned char *)protocol_list, n);
848
849                 strcpy(protocol_list,
850                        "HTTP/1.1 101 Switching Protocols\x0d\x0a"
851                       "Connection: Upgrade\x0d\x0a"
852                       "Upgrade: h2c\x0d\x0a\x0d\x0a");
853                 n = lws_issue_raw(wsi, (unsigned char *)protocol_list,
854                                         strlen(protocol_list));
855                 if (n != strlen(protocol_list)) {
856                         lwsl_debug("http2 switch: ERROR writing to socket\n");
857                         return 1;
858                 }
859
860                 wsi->state = LWSS_HTTP2_AWAIT_CLIENT_PREFACE;
861
862                 return 0;
863 #endif
864
865 upgrade_ws:
866                 if (!wsi->protocol)
867                         lwsl_err("NULL protocol at lws_read\n");
868
869                 /*
870                  * It's websocket
871                  *
872                  * Select the first protocol we support from the list
873                  * the client sent us.
874                  *
875                  * Copy it to remove header fragmentation
876                  */
877
878                 if (lws_hdr_copy(wsi, protocol_list, sizeof(protocol_list) - 1,
879                                  WSI_TOKEN_PROTOCOL) < 0) {
880                         lwsl_err("protocol list too long");
881                         goto bail_nuke_ah;
882                 }
883
884                 protocol_len = lws_hdr_total_length(wsi, WSI_TOKEN_PROTOCOL);
885                 protocol_list[protocol_len] = '\0';
886                 p = protocol_list;
887                 hit = 0;
888
889                 while (*p && !hit) {
890                         n = 0;
891                         while (n < sizeof(protocol_name) - 1 && *p && *p !=',')
892                                 protocol_name[n++] = *p++;
893                         protocol_name[n] = '\0';
894                         if (*p)
895                                 p++;
896
897                         lwsl_info("checking %s\n", protocol_name);
898
899                         n = 0;
900                         while (wsi->vhost->protocols[n].callback) {
901                                 if (wsi->vhost->protocols[n].name &&
902                                     !strcmp(wsi->vhost->protocols[n].name,
903                                             protocol_name)) {
904                                         wsi->protocol = &wsi->vhost->protocols[n];
905                                         hit = 1;
906                                         break;
907                                 }
908
909                                 n++;
910                         }
911                 }
912
913                 /* we didn't find a protocol he wanted? */
914
915                 if (!hit) {
916                         if (lws_hdr_simple_ptr(wsi, WSI_TOKEN_PROTOCOL)) {
917                                 lwsl_err("No protocol from \"%s\" supported\n",
918                                          protocol_list);
919                                 goto bail_nuke_ah;
920                         }
921                         /*
922                          * some clients only have one protocol and
923                          * do not send the protocol list header...
924                          * allow it and match to protocol 0
925                          */
926                         lwsl_info("defaulting to prot 0 handler\n");
927                         n = 0;
928                         wsi->protocol = &wsi->vhost->protocols[0];
929                 }
930
931                 /* allocate wsi->user storage */
932                 if (lws_ensure_user_space(wsi))
933                         goto bail_nuke_ah;
934
935                 /*
936                  * Give the user code a chance to study the request and
937                  * have the opportunity to deny it
938                  */
939                 if ((wsi->protocol->callback)(wsi,
940                                 LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION,
941                                 wsi->user_space,
942                               lws_hdr_simple_ptr(wsi, WSI_TOKEN_PROTOCOL), 0)) {
943                         lwsl_warn("User code denied connection\n");
944                         goto bail_nuke_ah;
945                 }
946
947                 /*
948                  * Perform the handshake according to the protocol version the
949                  * client announced
950                  */
951
952                 switch (wsi->ietf_spec_revision) {
953                 case 13:
954                         lwsl_parser("lws_parse calling handshake_04\n");
955                         if (handshake_0405(context, wsi)) {
956                                 lwsl_info("hs0405 has failed the connection\n");
957                                 goto bail_nuke_ah;
958                         }
959                         break;
960
961                 default:
962                         lwsl_warn("Unknown client spec version %d\n",
963                                   wsi->ietf_spec_revision);
964                         goto bail_nuke_ah;
965                 }
966
967                 /*
968                  * stitch protocol choice into the vh protocol linked list
969                  * We always insert ourselves at the start of the list
970                  *
971                  * X <-> B
972                  * X <-> pAn <-> pB
973                  */
974                 //lwsl_err("%s: pre insert vhost start wsi %p, that wsi prev == %p\n",
975                 //              __func__,
976                 //              wsi->vhost->same_vh_protocol_list[n],
977                 //              wsi->same_vh_protocol_prev);
978                 wsi->same_vh_protocol_prev = /* guy who points to us */
979                         &wsi->vhost->same_vh_protocol_list[n];
980                 wsi->same_vh_protocol_next = /* old first guy is our next */
981                                 wsi->vhost->same_vh_protocol_list[n];
982                 /* we become the new first guy */
983                 wsi->vhost->same_vh_protocol_list[n] = wsi;
984
985                 if (wsi->same_vh_protocol_next)
986                         /* old first guy points back to us now */
987                         wsi->same_vh_protocol_next->same_vh_protocol_prev =
988                                         &wsi->same_vh_protocol_next;
989
990
991
992                 /* we are upgrading to ws, so http/1.1 and keepalive +
993                  * pipelined header considerations about keeping the ah around
994                  * no longer apply.  However it's common for the first ws
995                  * protocol data to have been coalesced with the browser
996                  * upgrade request and to already be in the ah rx buffer.
997                  */
998
999                 lwsl_info("%s: %p: inheriting ah in ws mode (rxpos:%d, rxlen:%d)\n",
1000                           __func__, wsi, wsi->u.hdr.ah->rxpos,
1001                           wsi->u.hdr.ah->rxlen);
1002                 lws_pt_lock(pt);
1003                 hdr = wsi->u.hdr;
1004
1005                 lws_union_transition(wsi, LWSCM_WS_SERVING);
1006                 /*
1007                  * first service is WS mode will notice this, use the RX and
1008                  * then detach the ah (caution: we are not in u.hdr union
1009                  * mode any more then... ah_temp member is at start the same
1010                  * though)
1011                  *
1012                  * Because rxpos/rxlen shows something in the ah, we will get
1013                  * service guaranteed next time around the event loop
1014                  *
1015                  * All union members begin with hdr, so we can use it even
1016                  * though we transitioned to ws union mode (the ah detach
1017                  * code uses it anyway).
1018                  */
1019                 wsi->u.hdr = hdr;
1020                 lws_pt_unlock(pt);
1021
1022                 /*
1023                  * create the frame buffer for this connection according to the
1024                  * size mentioned in the protocol definition.  If 0 there, use
1025                  * a big default for compatibility
1026                  */
1027
1028                 n = wsi->protocol->rx_buffer_size;
1029                 if (!n)
1030                         n = LWS_MAX_SOCKET_IO_BUF;
1031                 n += LWS_PRE;
1032                 wsi->u.ws.rx_ubuf = lws_malloc(n + 4 /* 0x0000ffff zlib */);
1033                 if (!wsi->u.ws.rx_ubuf) {
1034                         lwsl_err("Out of Mem allocating rx buffer %d\n", n);
1035                         return 1;
1036                 }
1037                 wsi->u.ws.rx_ubuf_alloc = n;
1038                 lwsl_info("Allocating RX buffer %d\n", n);
1039 #if LWS_POSIX
1040                 if (setsockopt(wsi->sock, SOL_SOCKET, SO_SNDBUF,
1041                                (const char *)&n, sizeof n)) {
1042                         lwsl_warn("Failed to set SNDBUF to %d", n);
1043                         return 1;
1044                 }
1045 #endif
1046                 lwsl_parser("accepted v%02d connection\n",
1047                             wsi->ietf_spec_revision);
1048
1049                 return 0;
1050         } /* while all chars are handled */
1051
1052         return 0;
1053
1054 bail_nuke_ah:
1055         /* drop the header info */
1056         /* we're closing, losing some rx is OK */
1057         wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
1058         lws_header_table_detach(wsi, 1);
1059
1060         return 1;
1061 }
1062
1063 static int
1064 lws_get_idlest_tsi(struct lws_context *context)
1065 {
1066         unsigned int lowest = ~0;
1067         int n = 0, hit = -1;
1068
1069         for (; n < context->count_threads; n++) {
1070                 if ((unsigned int)context->pt[n].fds_count !=
1071                     context->fd_limit_per_thread - 1 &&
1072                     (unsigned int)context->pt[n].fds_count < lowest) {
1073                         lowest = context->pt[n].fds_count;
1074                         hit = n;
1075                 }
1076         }
1077
1078         return hit;
1079 }
1080
1081 struct lws *
1082 lws_create_new_server_wsi(struct lws_vhost *vhost)
1083 {
1084         struct lws *new_wsi;
1085         int n = lws_get_idlest_tsi(vhost->context);
1086
1087         if (n < 0) {
1088                 lwsl_err("no space for new conn\n");
1089                 return NULL;
1090         }
1091
1092         new_wsi = lws_zalloc(sizeof(struct lws));
1093         if (new_wsi == NULL) {
1094                 lwsl_err("Out of memory for new connection\n");
1095                 return NULL;
1096         }
1097
1098         new_wsi->tsi = n;
1099         lwsl_info("Accepted %p to tsi %d\n", new_wsi, new_wsi->tsi);
1100
1101         new_wsi->vhost = vhost;
1102         new_wsi->context = vhost->context;
1103         new_wsi->pending_timeout = NO_PENDING_TIMEOUT;
1104         new_wsi->rxflow_change_to = LWS_RXFLOW_ALLOW;
1105
1106         /* intialize the instance struct */
1107
1108         new_wsi->state = LWSS_HTTP;
1109         new_wsi->mode = LWSCM_HTTP_SERVING;
1110         new_wsi->hdr_parsing_completed = 0;
1111
1112 #ifdef LWS_OPENSSL_SUPPORT
1113         new_wsi->use_ssl = LWS_SSL_ENABLED(vhost);
1114 #endif
1115
1116         /*
1117          * these can only be set once the protocol is known
1118          * we set an unestablished connection's protocol pointer
1119          * to the start of the supported list, so it can look
1120          * for matching ones during the handshake
1121          */
1122         new_wsi->protocol = vhost->protocols;
1123         new_wsi->user_space = NULL;
1124         new_wsi->ietf_spec_revision = 0;
1125         new_wsi->sock = LWS_SOCK_INVALID;
1126         vhost->context->count_wsi_allocated++;
1127
1128         /*
1129          * outermost create notification for wsi
1130          * no user_space because no protocol selection
1131          */
1132         vhost->protocols[0].callback(new_wsi, LWS_CALLBACK_WSI_CREATE,
1133                                        NULL, NULL, 0);
1134
1135         return new_wsi;
1136 }
1137
1138 /**
1139  * lws_http_transaction_completed() - wait for new http transaction or close
1140  * @wsi:        websocket connection
1141  *
1142  *      Returns 1 if the HTTP connection must close now
1143  *      Returns 0 and resets connection to wait for new HTTP header /
1144  *        transaction if possible
1145  */
1146
1147 LWS_VISIBLE int LWS_WARN_UNUSED_RESULT
1148 lws_http_transaction_completed(struct lws *wsi)
1149 {
1150         int n = NO_PENDING_TIMEOUT;
1151
1152         lws_access_log(wsi);
1153
1154         lwsl_debug("%s: wsi %p\n", __func__, wsi);
1155         /* if we can't go back to accept new headers, drop the connection */
1156         if (wsi->u.http.connection_type != HTTP_CONNECTION_KEEP_ALIVE) {
1157                 lwsl_info("%s: %p: close connection\n", __func__, wsi);
1158                 return 1;
1159         }
1160
1161         /* otherwise set ourselves up ready to go again */
1162         wsi->state = LWSS_HTTP;
1163         wsi->mode = LWSCM_HTTP_SERVING;
1164         wsi->u.http.content_length = 0;
1165         wsi->hdr_parsing_completed = 0;
1166 #ifdef LWS_WITH_ACCESS_LOG
1167         wsi->access_log.sent = 0;
1168 #endif
1169
1170         if (wsi->vhost->keepalive_timeout)
1171                 n = PENDING_TIMEOUT_HTTP_KEEPALIVE_IDLE;
1172         lws_set_timeout(wsi, n, wsi->vhost->keepalive_timeout);
1173
1174         /*
1175          * We already know we are on http1.1 / keepalive and the next thing
1176          * coming will be another header set.
1177          *
1178          * If there is no pending rx and we still have the ah, drop it and
1179          * reacquire a new ah when the new headers start to arrive.  (Otherwise
1180          * we needlessly hog an ah indefinitely.)
1181          *
1182          * However if there is pending rx and we know from the keepalive state
1183          * that is already at least the start of another header set, simply
1184          * reset the existing header table and keep it.
1185          */
1186         if (wsi->u.hdr.ah) {
1187                 lwsl_info("%s: wsi->more_rx_waiting=%d\n", __func__,
1188                                 wsi->more_rx_waiting);
1189
1190                 if (!wsi->more_rx_waiting) {
1191                         wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
1192                         lws_header_table_detach(wsi, 1);
1193                 } else
1194                         lws_header_table_reset(wsi, 1);
1195         }
1196
1197         /* If we're (re)starting on headers, need other implied init */
1198         wsi->u.hdr.ues = URIES_IDLE;
1199
1200         lwsl_info("%s: %p: keep-alive await new transaction\n", __func__, wsi);
1201
1202         return 0;
1203 }
1204
1205 static struct lws *
1206 lws_adopt_socket_vhost(struct lws_vhost *vh, lws_sockfd_type accept_fd)
1207 {
1208         struct lws_context *context = vh->context;
1209         struct lws *new_wsi = lws_create_new_server_wsi(vh);
1210
1211         if (!new_wsi) {
1212                 compatible_close(accept_fd);
1213                 return NULL;
1214         }
1215
1216         lwsl_info("%s: new wsi %p, sockfd %d\n", __func__, new_wsi, accept_fd);
1217
1218         new_wsi->sock = accept_fd;
1219
1220         /* the transport is accepted... give him time to negotiate */
1221         lws_set_timeout(new_wsi, PENDING_TIMEOUT_ESTABLISH_WITH_SERVER,
1222                         context->timeout_secs);
1223
1224 #if LWS_POSIX == 0
1225         mbed3_tcp_stream_accept(accept_fd, new_wsi);
1226 #endif
1227
1228         /*
1229          * A new connection was accepted. Give the user a chance to
1230          * set properties of the newly created wsi. There's no protocol
1231          * selected yet so we issue this to protocols[0]
1232          */
1233         if ((context->vhost_list->protocols[0].callback)(new_wsi,
1234              LWS_CALLBACK_SERVER_NEW_CLIENT_INSTANTIATED, NULL, NULL, 0)) {
1235                 compatible_close(new_wsi->sock);
1236                 lws_free(new_wsi);
1237                 return NULL;
1238         }
1239
1240         lws_libev_accept(new_wsi, new_wsi->sock);
1241         lws_libuv_accept(new_wsi, new_wsi->sock);
1242
1243         if (!LWS_SSL_ENABLED(new_wsi->vhost)) {
1244                 if (insert_wsi_socket_into_fds(context, new_wsi)) {
1245                         lwsl_err("%s: fail inserting socket\n", __func__);
1246                         goto fail;
1247                 }
1248         } else {
1249                 new_wsi->mode = LWSCM_SSL_INIT;
1250                 if (lws_server_socket_service_ssl(new_wsi, accept_fd)) {
1251                         lwsl_err("%s: fail ssl negotiation\n", __func__);
1252                         goto fail;
1253                 }
1254         }
1255
1256         if (!lws_header_table_attach(new_wsi, 0))
1257                 lwsl_debug("Attached ah immediately\n");
1258
1259         return new_wsi;
1260
1261 fail:
1262         lws_close_free_wsi(new_wsi, LWS_CLOSE_STATUS_NOSTATUS);
1263
1264         return NULL;
1265 }
1266
1267 /**
1268  * lws_adopt_socket() - adopt foreign socket as if listen socket accepted it
1269  * @context: lws context
1270  * @accept_fd: fd of already-accepted socket to adopt
1271  *
1272  * Either returns new wsi bound to accept_fd, or closes accept_fd and
1273  * returns NULL, having cleaned up any new wsi pieces.
1274  *
1275  * LWS adopts the socket in http serving mode, it's ready to accept an upgrade
1276  * to ws or just serve http.
1277  */
1278
1279 LWS_VISIBLE struct lws *
1280 lws_adopt_socket(struct lws_context *context, lws_sockfd_type accept_fd)
1281 {
1282         return lws_adopt_socket_vhost(context->vhost_list, accept_fd);
1283 }
1284
1285
1286 /**
1287  * lws_adopt_socket_readbuf() - adopt foreign socket and first rx as if listen socket accepted it
1288  * @context:    lws context
1289  * @accept_fd:  fd of already-accepted socket to adopt
1290  * @readbuf:    NULL or pointer to data that must be drained before reading from
1291  *              accept_fd
1292  * @len:        The length of the data held at @readbuf
1293  *
1294  * Either returns new wsi bound to accept_fd, or closes accept_fd and
1295  * returns NULL, having cleaned up any new wsi pieces.
1296  *
1297  * LWS adopts the socket in http serving mode, it's ready to accept an upgrade
1298  * to ws or just serve http.
1299  *
1300  * If your external code did not already read from the socket, you can use
1301  * lws_adopt_socket() instead.
1302  *
1303  * This api is guaranteed to use the data at @readbuf first, before reading from
1304  * the socket.
1305  *
1306  * @readbuf is limited to the size of the ah rx buf, currently 2048 bytes.
1307  */
1308
1309 LWS_VISIBLE LWS_EXTERN struct lws *
1310 lws_adopt_socket_readbuf(struct lws_context *context, lws_sockfd_type accept_fd,
1311                          const char *readbuf, size_t len)
1312 {
1313         struct lws *wsi = lws_adopt_socket(context, accept_fd);
1314         struct lws_context_per_thread *pt;
1315         struct allocated_headers *ah;
1316         struct lws_pollfd *pfd;
1317
1318         if (!wsi)
1319                 return NULL;
1320
1321         if (!readbuf)
1322                 return wsi;
1323
1324         if (len > sizeof(ah->rx)) {
1325                 lwsl_err("%s: rx in too big\n", __func__);
1326                 goto bail;
1327         }
1328         /*
1329          * we can't process the initial read data until we can attach an ah.
1330          *
1331          * if one is available, get it and place the data in his ah rxbuf...
1332          * wsi with ah that have pending rxbuf get auto-POLLIN service.
1333          *
1334          * no autoservice because we didn't get a chance to attach the
1335          * readbuf data to wsi or ah yet, and we will do it next if we get
1336          * the ah.
1337          */
1338         if (wsi->u.hdr.ah || !lws_header_table_attach(wsi, 0)) {
1339                 ah = wsi->u.hdr.ah;
1340                 memcpy(ah->rx, readbuf, len);
1341                 ah->rxpos = 0;
1342                 ah->rxlen = len;
1343
1344                 lwsl_notice("%s: calling service on readbuf ah\n", __func__);
1345                 pt = &context->pt[(int)wsi->tsi];
1346
1347                 /* unlike a normal connect, we have the headers already
1348                  * (or the first part of them anyway).
1349                  * libuv won't come back and service us without a network
1350                  * event, so we need to do the header service right here.
1351                  */
1352                 pfd = &pt->fds[wsi->position_in_fds_table];
1353                 pfd->revents |= LWS_POLLIN;
1354                 lwsl_err("%s: calling service\n", __func__);
1355                 if (lws_service_fd_tsi(context, pfd, wsi->tsi))
1356                         /* service closed us */
1357                         return NULL;
1358
1359                 return wsi;
1360         }
1361         lwsl_err("%s: deferring handling ah\n", __func__);
1362         /*
1363          * hum if no ah came, we are on the wait list and must defer
1364          * dealing with this until the ah arrives.
1365          *
1366          * later successful lws_header_table_attach() will apply the
1367          * below to the rx buffer (via lws_header_table_reset()).
1368          */
1369         wsi->u.hdr.preamble_rx = lws_malloc(len);
1370         memcpy(wsi->u.hdr.preamble_rx, readbuf, len);
1371         wsi->u.hdr.preamble_rx_len = len;
1372
1373         return wsi;
1374
1375 bail:
1376         lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
1377
1378         return NULL;
1379 }
1380
1381 LWS_VISIBLE int
1382 lws_server_socket_service(struct lws_context *context, struct lws *wsi,
1383                           struct lws_pollfd *pollfd)
1384 {
1385         struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
1386         lws_sockfd_type accept_fd = LWS_SOCK_INVALID;
1387         struct allocated_headers *ah;
1388 #if LWS_POSIX
1389         struct sockaddr_in cli_addr;
1390         socklen_t clilen;
1391 #endif
1392         int n, len;
1393
1394         switch (wsi->mode) {
1395
1396         case LWSCM_HTTP_SERVING:
1397         case LWSCM_HTTP_SERVING_ACCEPTED:
1398         case LWSCM_HTTP2_SERVING:
1399
1400                 /* handle http headers coming in */
1401
1402                 /* pending truncated sends have uber priority */
1403
1404                 if (wsi->trunc_len) {
1405                         if (!(pollfd->revents & LWS_POLLOUT))
1406                                 break;
1407
1408                         if (lws_issue_raw(wsi, wsi->trunc_alloc +
1409                                                wsi->trunc_offset,
1410                                           wsi->trunc_len) < 0)
1411                                 goto fail;
1412                         /*
1413                          * we can't afford to allow input processing to send
1414                          * something new, so spin around he event loop until
1415                          * he doesn't have any partials
1416                          */
1417                         break;
1418                 }
1419
1420                 /* any incoming data ready? */
1421
1422                 if (!(pollfd->revents & pollfd->events & LWS_POLLIN))
1423                         goto try_pollout;
1424
1425                 /*
1426                  * If we previously just did POLLIN when IN and OUT were
1427                  * signalled (because POLLIN processing may have used up
1428                  * the POLLOUT), don't let that happen twice in a row...
1429                  * next time we see the situation favour POLLOUT
1430                  */
1431
1432                 if (wsi->favoured_pollin &&
1433                     (pollfd->revents & pollfd->events & LWS_POLLOUT)) {
1434                         wsi->favoured_pollin = 0;
1435                         goto try_pollout;
1436                 }
1437
1438                 /* these states imply we MUST have an ah attached */
1439
1440                 if (wsi->state == LWSS_HTTP ||
1441                     wsi->state == LWSS_HTTP_ISSUING_FILE ||
1442                     wsi->state == LWSS_HTTP_HEADERS) {
1443                         if (!wsi->u.hdr.ah)
1444                                 /* no autoservice beacuse we will do it next */
1445                                 if (lws_header_table_attach(wsi, 0))
1446                                         goto try_pollout;
1447
1448                         ah = wsi->u.hdr.ah;
1449
1450                         lwsl_debug("%s: %p: rxpos:%d rxlen:%d\n", __func__, wsi,
1451                                    ah->rxpos, ah->rxlen);
1452
1453                         /* if nothing in ah rx buffer, get some fresh rx */
1454                         if (ah->rxpos == ah->rxlen) {
1455                                 ah->rxlen = lws_ssl_capable_read(wsi, ah->rx,
1456                                                    sizeof(ah->rx));
1457                                 ah->rxpos = 0;
1458                                 lwsl_debug("%s: wsi %p, ah->rxlen = %d\r\n",
1459                                            __func__, wsi, ah->rxlen);
1460                                 switch (ah->rxlen) {
1461                                 case 0:
1462                                         lwsl_info("%s: read 0 len\n", __func__);
1463                                         /* lwsl_info("   state=%d\n", wsi->state); */
1464 //                                      if (!wsi->hdr_parsing_completed)
1465 //                                              lws_header_table_detach(wsi);
1466                                         /* fallthru */
1467                                 case LWS_SSL_CAPABLE_ERROR:
1468                                         goto fail;
1469                                 case LWS_SSL_CAPABLE_MORE_SERVICE:
1470                                         ah->rxlen = ah->rxpos = 0;
1471                                         goto try_pollout;
1472                                 }
1473                         }
1474                         assert(ah->rxpos != ah->rxlen && ah->rxlen);
1475                         /* just ignore incoming if waiting for close */
1476                         if (wsi->state != LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE) {
1477                                 n = lws_read(wsi, ah->rx + ah->rxpos,
1478                                              ah->rxlen - ah->rxpos);
1479                                 if (n < 0) /* we closed wsi */
1480                                         return 1;
1481                                 if (wsi->u.hdr.ah) {
1482                                         if ( wsi->u.hdr.ah->rxlen)
1483                                                  wsi->u.hdr.ah->rxpos += n;
1484
1485                                         if (wsi->u.hdr.ah->rxpos == wsi->u.hdr.ah->rxlen &&
1486                                             (wsi->mode != LWSCM_HTTP_SERVING &&
1487                                              wsi->mode != LWSCM_HTTP_SERVING_ACCEPTED &&
1488                                              wsi->mode != LWSCM_HTTP2_SERVING))
1489                                                 lws_header_table_detach(wsi, 1);
1490                                 }
1491                                 break;
1492                         }
1493
1494                         goto try_pollout;
1495                 }
1496
1497                 len = lws_ssl_capable_read(wsi, pt->serv_buf,
1498                                            LWS_MAX_SOCKET_IO_BUF);
1499                 lwsl_debug("%s: wsi %p read %d\r\n", __func__, wsi, len);
1500                 switch (len) {
1501                 case 0:
1502                         lwsl_info("%s: read 0 len\n", __func__);
1503                         /* lwsl_info("   state=%d\n", wsi->state); */
1504 //                      if (!wsi->hdr_parsing_completed)
1505 //                              lws_header_table_detach(wsi);
1506                         /* fallthru */
1507                 case LWS_SSL_CAPABLE_ERROR:
1508                         goto fail;
1509                 case LWS_SSL_CAPABLE_MORE_SERVICE:
1510                         goto try_pollout;
1511                 }
1512
1513                 /* just ignore incoming if waiting for close */
1514                 if (wsi->state != LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE) {
1515                         /*
1516                          * this may want to send
1517                          * (via HTTP callback for example)
1518                          */
1519                         n = lws_read(wsi, pt->serv_buf, len);
1520                         if (n < 0) /* we closed wsi */
1521                                 return 1;
1522                         /*
1523                          *  he may have used up the
1524                          * writability above, if we will defer POLLOUT
1525                          * processing in favour of POLLIN, note it
1526                          */
1527                         if (pollfd->revents & LWS_POLLOUT)
1528                                 wsi->favoured_pollin = 1;
1529                         break;
1530                 }
1531
1532 try_pollout:
1533                 /* this handles POLLOUT for http serving fragments */
1534
1535                 if (!(pollfd->revents & LWS_POLLOUT))
1536                         break;
1537
1538                 /* one shot */
1539                 if (lws_change_pollfd(wsi, LWS_POLLOUT, 0)) {
1540                         lwsl_notice("%s a\n", __func__);
1541                         goto fail;
1542                 }
1543
1544                 if (!wsi->hdr_parsing_completed)
1545                         break;
1546
1547                 if (wsi->state != LWSS_HTTP_ISSUING_FILE) {
1548                         n = user_callback_handle_rxflow(wsi->protocol->callback,
1549                                         wsi, LWS_CALLBACK_HTTP_WRITEABLE,
1550                                         wsi->user_space, NULL, 0);
1551                         if (n < 0) {
1552                                 lwsl_info("writeable_fail\n");
1553                                 goto fail;
1554                         }
1555                         break;
1556                 }
1557
1558                 /* >0 == completion, <0 == error */
1559                 n = lws_serve_http_file_fragment(wsi);
1560                 if (n < 0 || (n > 0 && lws_http_transaction_completed(wsi))) {
1561                         lwsl_info("completed\n");
1562                         goto fail;
1563                 }
1564                 break;
1565
1566         case LWSCM_SERVER_LISTENER:
1567
1568 #if LWS_POSIX
1569                 /* pollin means a client has connected to us then */
1570
1571                 do {
1572                         if (!(pollfd->revents & LWS_POLLIN) || !(pollfd->events & LWS_POLLIN))
1573                                 break;
1574
1575                         /* listen socket got an unencrypted connection... */
1576
1577                         clilen = sizeof(cli_addr);
1578                         lws_latency_pre(context, wsi);
1579                         accept_fd  = accept(pollfd->fd, (struct sockaddr *)&cli_addr,
1580                                             &clilen);
1581                         lws_latency(context, wsi, "listener accept", accept_fd,
1582                                     accept_fd >= 0);
1583                         if (accept_fd < 0) {
1584                                 if (LWS_ERRNO == LWS_EAGAIN ||
1585                                     LWS_ERRNO == LWS_EWOULDBLOCK) {
1586                                         lwsl_err("accept asks to try again\n");
1587                                         break;
1588                                 }
1589                                 lwsl_err("ERROR on accept: %s\n", strerror(LWS_ERRNO));
1590                                 break;
1591                         }
1592
1593                         lws_plat_set_socket_options(wsi->vhost, accept_fd);
1594
1595                         lwsl_debug("accepted new conn  port %u on fd=%d\n",
1596                                           ntohs(cli_addr.sin_port), accept_fd);
1597
1598 #else
1599                         /* not very beautiful... */
1600                         accept_fd = (lws_sockfd_type)pollfd;
1601 #endif
1602                         /*
1603                          * look at who we connected to and give user code a chance
1604                          * to reject based on client IP.  There's no protocol selected
1605                          * yet so we issue this to protocols[0]
1606                          */
1607                         if ((wsi->vhost->protocols[0].callback)(wsi,
1608                                         LWS_CALLBACK_FILTER_NETWORK_CONNECTION,
1609                                         NULL, (void *)(long)accept_fd, 0)) {
1610                                 lwsl_debug("Callback denied network connection\n");
1611                                 compatible_close(accept_fd);
1612                                 break;
1613                         }
1614
1615                         if (!lws_adopt_socket_vhost(wsi->vhost, accept_fd))
1616                                 /* already closed cleanly as necessary */
1617                                 return 1;
1618
1619 #if LWS_POSIX
1620                 } while (pt->fds_count < context->fd_limit_per_thread - 1 &&
1621                          lws_poll_listen_fd(&pt->fds[wsi->position_in_fds_table]) > 0);
1622 #endif
1623                 return 0;
1624
1625         default:
1626                 break;
1627         }
1628
1629         if (!lws_server_socket_service_ssl(wsi, accept_fd))
1630                 return 0;
1631
1632 fail:
1633         lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
1634
1635         return 1;
1636 }
1637
1638 /**
1639  * lws_serve_http_file() - Send a file back to the client using http
1640  * @wsi:                Websocket instance (available from user callback)
1641  * @file:               The file to issue over http
1642  * @content_type:       The http content type, eg, text/html
1643  * @other_headers:      NULL or pointer to header string
1644  * @other_headers_len:  length of the other headers if non-NULL
1645  *
1646  *      This function is intended to be called from the callback in response
1647  *      to http requests from the client.  It allows the callback to issue
1648  *      local files down the http link in a single step.
1649  *
1650  *      Returning <0 indicates error and the wsi should be closed.  Returning
1651  *      >0 indicates the file was completely sent and
1652  *      lws_http_transaction_completed() called on the wsi (and close if != 0)
1653  *      ==0 indicates the file transfer is started and needs more service later,
1654  *      the wsi should be left alone.
1655  */
1656
1657 LWS_VISIBLE int
1658 lws_serve_http_file(struct lws *wsi, const char *file, const char *content_type,
1659                     const char *other_headers, int other_headers_len)
1660 {
1661         static const char * const intermediates[] = { "private", "public" };
1662         struct lws_context *context = lws_get_context(wsi);
1663         struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
1664         char cache_control[50], *cc = "no-store";
1665         unsigned char *response = pt->serv_buf + LWS_PRE;
1666         unsigned char *p = response;
1667         unsigned char *end = p + LWS_MAX_SOCKET_IO_BUF - LWS_PRE;
1668         int ret = 0, cclen = 8;
1669
1670         wsi->u.http.fd = lws_plat_file_open(wsi, file, &wsi->u.http.filelen,
1671                                             O_RDONLY);
1672
1673         if (wsi->u.http.fd == LWS_INVALID_FILE) {
1674                 lwsl_err("Unable to open '%s'\n", file);
1675                 lws_return_http_status(wsi, HTTP_STATUS_NOT_FOUND, NULL);
1676
1677                 return -1;
1678         }
1679
1680         if (lws_add_http_header_status(wsi, 200, &p, end))
1681                 return -1;
1682         if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE,
1683                                          (unsigned char *)content_type,
1684                                          strlen(content_type), &p, end))
1685                 return -1;
1686         if (lws_add_http_header_content_length(wsi, wsi->u.http.filelen, &p, end))
1687                 return -1;
1688
1689         if (wsi->cache_secs && wsi->cache_reuse) {
1690                 if (wsi->cache_revalidate) {
1691                         cc = cache_control;
1692                         cclen = sprintf(cache_control, "%s max-age: %u",
1693                                     intermediates[wsi->cache_intermediaries],
1694                                     wsi->cache_secs);
1695                 } else {
1696                         cc = "no-cache";
1697                         cclen = 8;
1698                 }
1699         }
1700
1701         if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_CACHE_CONTROL,
1702                         (unsigned char *)cc, cclen, &p, end))
1703                 return -1;
1704
1705         if (other_headers) {
1706                 if ((end - p) < other_headers_len)
1707                         return -1;
1708                 memcpy(p, other_headers, other_headers_len);
1709                 p += other_headers_len;
1710         }
1711
1712         if (lws_finalize_http_header(wsi, &p, end))
1713                 return -1;
1714
1715         ret = lws_write(wsi, response, p - response, LWS_WRITE_HTTP_HEADERS);
1716         if (ret != (p - response)) {
1717                 lwsl_err("_write returned %d from %d\n", ret, (p - response));
1718                 return -1;
1719         }
1720
1721         wsi->u.http.filepos = 0;
1722         wsi->state = LWSS_HTTP_ISSUING_FILE;
1723
1724         return lws_serve_http_file_fragment(wsi);
1725 }
1726
1727 int
1728 lws_interpret_incoming_packet(struct lws *wsi, unsigned char **buf, size_t len)
1729 {
1730         int m;
1731
1732         lwsl_parser("%s: received %d byte packet\n", __func__, (int)len);
1733 #if 0
1734         lwsl_hexdump(*buf, len);
1735 #endif
1736
1737         /* let the rx protocol state machine have as much as it needs */
1738
1739         while (len) {
1740                 /*
1741                  * we were accepting input but now we stopped doing so
1742                  */
1743                 if (!(wsi->rxflow_change_to & LWS_RXFLOW_ALLOW)) {
1744                         lws_rxflow_cache(wsi, *buf, 0, len);
1745                         lwsl_parser("%s: cached %d\n", __func__, len);
1746                         return 1;
1747                 }
1748
1749                 if (wsi->u.ws.rx_draining_ext) {
1750                         m = lws_rx_sm(wsi, 0);
1751                         if (m < 0)
1752                                 return -1;
1753                         continue;
1754                 }
1755
1756                 /* account for what we're using in rxflow buffer */
1757                 if (wsi->rxflow_buffer)
1758                         wsi->rxflow_pos++;
1759
1760                 /* consume payload bytes efficiently */
1761                 if (wsi->lws_rx_parse_state ==
1762                     LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED)
1763                         lws_payload_until_length_exhausted(wsi, buf, &len);
1764
1765                 /* process the byte */
1766                 m = lws_rx_sm(wsi, *(*buf)++);
1767                 if (m < 0)
1768                         return -1;
1769                 len--;
1770         }
1771
1772         lwsl_parser("%s: exit with %d unused\n", __func__, (int)len);
1773
1774         return 0;
1775 }
1776
1777 LWS_VISIBLE void
1778 lws_server_get_canonical_hostname(struct lws_context *context,
1779                                   struct lws_context_creation_info *info)
1780 {
1781         if (lws_check_opt(info->options, LWS_SERVER_OPTION_SKIP_SERVER_CANONICAL_NAME))
1782                 return;
1783 #if LWS_POSIX
1784         /* find canonical hostname */
1785         gethostname((char *)context->canonical_hostname,
1786                     sizeof(context->canonical_hostname) - 1);
1787
1788         lwsl_notice(" canonical_hostname = %s\n", context->canonical_hostname);
1789 #else
1790         (void)context;
1791 #endif
1792 }