Don't include <sys/cdefs.h> for NetBSD
[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_context *context)
28 {
29 #ifdef LWS_USE_IPV6
30         struct sockaddr_in6 serv_addr6;
31 #endif
32 #if LWS_POSIX
33         struct sockaddr_in serv_addr4;
34         socklen_t len = sizeof(struct sockaddr);
35         int n, opt = 1, limit = 1;
36         struct sockaddr_in sin;
37         struct sockaddr *v;
38 #endif
39         lws_sockfd_type sockfd;
40         struct lws *wsi;
41         int m = 0;
42
43         /* set up our external listening socket we serve on */
44
45         if (info->port == CONTEXT_PORT_NO_LISTEN)
46                 return 0;
47
48 #if LWS_POSIX
49 #if defined(__linux__)
50         limit = context->count_threads;
51 #endif
52
53         for (m = 0; m < limit; m++) {
54 #ifdef LWS_USE_IPV6
55         if (LWS_IPV6_ENABLED(context))
56                 sockfd = socket(AF_INET6, SOCK_STREAM, 0);
57         else
58 #endif
59                 sockfd = socket(AF_INET, SOCK_STREAM, 0);
60
61         if (sockfd == -1) {
62 #else
63         sockfd = mbed3_create_tcp_stream_socket();
64         if (!lws_sockfd_valid(sockfd)) {
65 #endif
66                 lwsl_err("ERROR opening socket\n");
67                 return 1;
68         }
69
70 #if LWS_POSIX
71         /*
72          * allow us to restart even if old sockets in TIME_WAIT
73          */
74         if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
75                        (const void *)&opt, sizeof(opt)) < 0) {
76                 compatible_close(sockfd);
77                 return 1;
78         }
79 #if defined(__linux__) && defined(SO_REUSEPORT) && LWS_MAX_SMP > 1
80         if (context->count_threads > 1)
81                 if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEPORT,
82                                 (const void *)&opt, sizeof(opt)) < 0) {
83                         compatible_close(sockfd);
84                         return 1;
85                 }
86 #endif
87 #endif
88         lws_plat_set_socket_options(context, sockfd);
89
90 #if LWS_POSIX
91 #ifdef LWS_USE_IPV6
92         if (LWS_IPV6_ENABLED(context)) {
93                 v = (struct sockaddr *)&serv_addr6;
94                 n = sizeof(struct sockaddr_in6);
95                 bzero((char *) &serv_addr6, sizeof(serv_addr6));
96                 serv_addr6.sin6_addr = in6addr_any;
97                 serv_addr6.sin6_family = AF_INET6;
98                 serv_addr6.sin6_port = htons(info->port);
99         } else
100 #endif
101         {
102                 v = (struct sockaddr *)&serv_addr4;
103                 n = sizeof(serv_addr4);
104                 bzero((char *) &serv_addr4, sizeof(serv_addr4));
105                 serv_addr4.sin_addr.s_addr = INADDR_ANY;
106                 serv_addr4.sin_family = AF_INET;
107
108                 if (info->iface && interface_to_sa(context, info->iface,
109                                    (struct sockaddr_in *)v, n) < 0) {
110                         lwsl_err("Unable to find interface %s\n", info->iface);
111                         goto bail;
112                 }
113
114                 serv_addr4.sin_port = htons(info->port);
115         } /* ipv4 */
116
117         n = bind(sockfd, v, n);
118         if (n < 0) {
119                 lwsl_err("ERROR on binding to port %d (%d %d)\n",
120                                               info->port, n, LWS_ERRNO);
121                 goto bail;
122         }
123
124         if (getsockname(sockfd, (struct sockaddr *)&sin, &len) == -1)
125                 lwsl_warn("getsockname: %s\n", strerror(LWS_ERRNO));
126         else
127                 info->port = ntohs(sin.sin_port);
128 #endif
129         context->listen_port = info->port;
130
131         wsi = lws_zalloc(sizeof(struct lws));
132         if (wsi == NULL) {
133                 lwsl_err("Out of mem\n");
134                 goto bail;
135         }
136         wsi->context = context;
137         wsi->sock = sockfd;
138         wsi->mode = LWSCM_SERVER_LISTENER;
139         wsi->protocol = context->protocols;
140         wsi->tsi = m;
141
142         context->pt[m].wsi_listening = wsi;
143         if (insert_wsi_socket_into_fds(context, wsi))
144                 goto bail;
145
146         context->count_wsi_allocated++;
147         context->pt[m].lserv_fd = sockfd;
148
149 #if LWS_POSIX
150         listen(wsi->sock, LWS_SOMAXCONN);
151         } /* for each thread able to independently lister */
152 #else
153         mbed3_tcp_stream_bind(wsi->sock, info->port, wsi);
154 #endif
155         lwsl_notice(" Listening on port %d\n", info->port);
156
157         return 0;
158
159 bail:
160         compatible_close(sockfd);
161
162         return 1;
163 }
164
165 int
166 _lws_server_listen_accept_flow_control(struct lws *twsi, int on)
167 {
168         struct lws_context_per_thread *pt = &twsi->context->pt[(int)twsi->tsi];
169         struct lws *wsi = pt->wsi_listening;
170         int n;
171
172         if (!wsi || twsi->context->being_destroyed)
173                 return 0;
174
175         lwsl_debug("%s: Thr %d: LISTEN wsi %p: state %d\n",
176                    __func__, twsi->tsi, (void *)wsi, on);
177
178         if (on)
179                 n = lws_change_pollfd(wsi, 0, LWS_POLLIN);
180         else
181                 n = lws_change_pollfd(wsi, LWS_POLLIN, 0);
182
183         return n;
184 }
185
186 int
187 lws_http_action(struct lws *wsi)
188 {
189         enum http_connection_type connection_type;
190         enum http_version request_version;
191         char content_length_str[32];
192         unsigned int n, count = 0;
193         char http_version_str[10];
194         char http_conn_str[20];
195         int http_version_len;
196         char *uri_ptr = NULL;
197         int uri_len = 0;
198
199         static const unsigned char methods[] = {
200                 WSI_TOKEN_GET_URI,
201                 WSI_TOKEN_POST_URI,
202                 WSI_TOKEN_OPTIONS_URI,
203                 WSI_TOKEN_PUT_URI,
204                 WSI_TOKEN_PATCH_URI,
205                 WSI_TOKEN_DELETE_URI,
206 #ifdef LWS_USE_HTTP2
207                 WSI_TOKEN_HTTP_COLON_PATH,
208 #endif
209         };
210 #ifdef _DEBUG
211         static const char * const method_names[] = {
212                 "GET", "POST", "OPTIONS", "PUT", "PATCH", "DELETE",
213 #ifdef LWS_USE_HTTP2
214                 ":path",
215 #endif
216         };
217 #endif
218
219         /* it's not websocket.... shall we accept it as http? */
220
221         for (n = 0; n < ARRAY_SIZE(methods); n++)
222                 if (lws_hdr_total_length(wsi, methods[n]))
223                         count++;
224         if (!count) {
225                 lwsl_warn("Missing URI in HTTP request\n");
226                 goto bail_nuke_ah;
227         }
228
229         if (count != 1) {
230                 lwsl_warn("multiple methods?\n");
231                 goto bail_nuke_ah;
232         }
233
234         if (lws_ensure_user_space(wsi))
235                 goto bail_nuke_ah;
236
237         for (n = 0; n < ARRAY_SIZE(methods); n++)
238                 if (lws_hdr_total_length(wsi, methods[n])) {
239                         uri_ptr = lws_hdr_simple_ptr(wsi, methods[n]);
240                         uri_len = lws_hdr_total_length(wsi, methods[n]);
241                         lwsl_info("Method: %s request for '%s'\n",
242                                         method_names[n], uri_ptr);
243                         break;
244                 }
245
246         /* HTTP header had a content length? */
247
248         wsi->u.http.content_length = 0;
249         if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI) ||
250                 lws_hdr_total_length(wsi, WSI_TOKEN_PATCH_URI) ||
251                 lws_hdr_total_length(wsi, WSI_TOKEN_PUT_URI))
252                 wsi->u.http.content_length = 100 * 1024 * 1024;
253
254         if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH)) {
255                 lws_hdr_copy(wsi, content_length_str,
256                              sizeof(content_length_str) - 1,
257                              WSI_TOKEN_HTTP_CONTENT_LENGTH);
258                 wsi->u.http.content_length = atoi(content_length_str);
259         }
260
261         /* http_version? Default to 1.0, override with token: */
262         request_version = HTTP_VERSION_1_0;
263
264         /* Works for single digit HTTP versions. : */
265         http_version_len = lws_hdr_total_length(wsi, WSI_TOKEN_HTTP);
266         if (http_version_len > 7) {
267                 lws_hdr_copy(wsi, http_version_str,
268                                 sizeof(http_version_str) - 1, WSI_TOKEN_HTTP);
269                 if (http_version_str[5] == '1' && http_version_str[7] == '1')
270                         request_version = HTTP_VERSION_1_1;
271         }
272         wsi->u.http.request_version = request_version;
273
274         /* HTTP/1.1 defaults to "keep-alive", 1.0 to "close" */
275         if (request_version == HTTP_VERSION_1_1)
276                 connection_type = HTTP_CONNECTION_KEEP_ALIVE;
277         else
278                 connection_type = HTTP_CONNECTION_CLOSE;
279
280         /* Override default if http "Connection:" header: */
281         if (lws_hdr_total_length(wsi, WSI_TOKEN_CONNECTION)) {
282                 lws_hdr_copy(wsi, http_conn_str, sizeof(http_conn_str) - 1,
283                              WSI_TOKEN_CONNECTION);
284                 http_conn_str[sizeof(http_conn_str) - 1] = '\0';
285                 if (!strcasecmp(http_conn_str, "keep-alive"))
286                         connection_type = HTTP_CONNECTION_KEEP_ALIVE;
287                 else
288                         if (!strcasecmp(http_conn_str, "close"))
289                                 connection_type = HTTP_CONNECTION_CLOSE;
290         }
291         wsi->u.http.connection_type = connection_type;
292
293         n = wsi->protocol->callback(wsi, LWS_CALLBACK_FILTER_HTTP_CONNECTION,
294                                     wsi->user_space, uri_ptr, uri_len);
295         if (n) {
296                 lwsl_info("LWS_CALLBACK_HTTP closing\n");
297
298                 return 1;
299         }
300         /*
301          * if there is content supposed to be coming,
302          * put a timeout on it having arrived
303          */
304         lws_set_timeout(wsi, PENDING_TIMEOUT_HTTP_CONTENT,
305                         wsi->context->timeout_secs);
306
307         n = wsi->protocol->callback(wsi, LWS_CALLBACK_HTTP,
308                                     wsi->user_space, uri_ptr, uri_len);
309         if (n) {
310                 lwsl_info("LWS_CALLBACK_HTTP closing\n");
311
312                 return 1;
313         }
314
315         /*
316          * If we're not issuing a file, check for content_length or
317          * HTTP keep-alive. No keep-alive header allocation for
318          * ISSUING_FILE, as this uses HTTP/1.0.
319          *
320          * In any case, return 0 and let lws_read decide how to
321          * proceed based on state
322          */
323         if (wsi->state != LWSS_HTTP_ISSUING_FILE)
324                 /* Prepare to read body if we have a content length: */
325                 if (wsi->u.http.content_length > 0)
326                         wsi->state = LWSS_HTTP_BODY;
327
328         return 0;
329
330 bail_nuke_ah:
331         /* we're closing, losing some rx is OK */
332         wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
333         lws_header_table_detach(wsi);
334
335         return 1;
336 }
337
338
339 int
340 lws_handshake_server(struct lws *wsi, unsigned char **buf, size_t len)
341 {
342         struct lws_context *context = lws_get_context(wsi);
343         struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
344         struct _lws_header_related hdr;
345         struct allocated_headers *ah;
346         int protocol_len, n, hit;
347         char protocol_list[128];
348         char protocol_name[32];
349         char *p;
350
351         assert(len < 10000000);
352         assert(wsi->u.hdr.ah);
353
354         while (len--) {
355                 wsi->u.hdr.more_rx_waiting = !!len;
356
357                 assert(wsi->mode == LWSCM_HTTP_SERVING);
358
359                 if (lws_parse(wsi, *(*buf)++)) {
360                         lwsl_info("lws_parse failed\n");
361                         goto bail_nuke_ah;
362                 }
363
364                 if (wsi->u.hdr.parser_state != WSI_PARSING_COMPLETE)
365                         continue;
366
367                 lwsl_parser("lws_parse sees parsing complete\n");
368
369                 wsi->mode = LWSCM_PRE_WS_SERVING_ACCEPT;
370                 lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
371
372                 /* is this websocket protocol or normal http 1.0? */
373
374                 if (lws_hdr_total_length(wsi, WSI_TOKEN_UPGRADE)) {
375                         if (!strcasecmp(lws_hdr_simple_ptr(wsi, WSI_TOKEN_UPGRADE),
376                                         "websocket")) {
377                                 lwsl_info("Upgrade to ws\n");
378                                 goto upgrade_ws;
379                         }
380 #ifdef LWS_USE_HTTP2
381                         if (!strcasecmp(lws_hdr_simple_ptr(wsi, WSI_TOKEN_UPGRADE),
382                                         "h2c-14")) {
383                                 lwsl_info("Upgrade to h2c-14\n");
384                                 goto upgrade_h2c;
385                         }
386 #endif
387                         lwsl_err("Unknown upgrade\n");
388                         /* dunno what he wanted to upgrade to */
389                         goto bail_nuke_ah;
390                 }
391
392                 /* no upgrade ack... he remained as HTTP */
393
394                 lwsl_info("No upgrade\n");
395                 ah = wsi->u.hdr.ah;
396
397                 lws_union_transition(wsi, LWSCM_HTTP_SERVING_ACCEPTED);
398                 wsi->state = LWSS_HTTP;
399                 wsi->u.http.fd = LWS_INVALID_FILE;
400
401                 /* expose it at the same offset as u.hdr */
402                 wsi->u.http.ah = ah;
403                 lwsl_debug("%s: wsi %p: ah %p\n", __func__, (void *)wsi, (void *)wsi->u.hdr.ah);
404
405                 n = lws_http_action(wsi);
406
407                 return n;
408
409 #ifdef LWS_USE_HTTP2
410 upgrade_h2c:
411                 if (!lws_hdr_total_length(wsi, WSI_TOKEN_HTTP2_SETTINGS)) {
412                         lwsl_err("missing http2_settings\n");
413                         goto bail_nuke_ah;
414                 }
415
416                 lwsl_err("h2c upgrade...\n");
417
418                 p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP2_SETTINGS);
419                 /* convert the peer's HTTP-Settings */
420                 n = lws_b64_decode_string(p, protocol_list,
421                                           sizeof(protocol_list));
422                 if (n < 0) {
423                         lwsl_parser("HTTP2_SETTINGS too long\n");
424                         return 1;
425                 }
426
427                 /* adopt the header info */
428
429                 ah = wsi->u.hdr.ah;
430
431                 lws_union_transition(wsi, LWSCM_HTTP2_SERVING);
432
433                 /* http2 union member has http union struct at start */
434                 wsi->u.http.ah = ah;
435
436                 lws_http2_init(&wsi->u.http2.peer_settings);
437                 lws_http2_init(&wsi->u.http2.my_settings);
438
439                 /* HTTP2 union */
440
441                 lws_http2_interpret_settings_payload(&wsi->u.http2.peer_settings,
442                                 (unsigned char *)protocol_list, n);
443
444                 strcpy(protocol_list,
445                        "HTTP/1.1 101 Switching Protocols\x0d\x0a"
446                       "Connection: Upgrade\x0d\x0a"
447                       "Upgrade: h2c\x0d\x0a\x0d\x0a");
448                 n = lws_issue_raw(wsi, (unsigned char *)protocol_list,
449                                         strlen(protocol_list));
450                 if (n != strlen(protocol_list)) {
451                         lwsl_debug("http2 switch: ERROR writing to socket\n");
452                         return 1;
453                 }
454
455                 wsi->state = LWSS_HTTP2_AWAIT_CLIENT_PREFACE;
456
457                 return 0;
458 #endif
459
460 upgrade_ws:
461                 if (!wsi->protocol)
462                         lwsl_err("NULL protocol at lws_read\n");
463
464                 /*
465                  * It's websocket
466                  *
467                  * Select the first protocol we support from the list
468                  * the client sent us.
469                  *
470                  * Copy it to remove header fragmentation
471                  */
472
473                 if (lws_hdr_copy(wsi, protocol_list, sizeof(protocol_list) - 1,
474                                  WSI_TOKEN_PROTOCOL) < 0) {
475                         lwsl_err("protocol list too long");
476                         goto bail_nuke_ah;
477                 }
478
479                 protocol_len = lws_hdr_total_length(wsi, WSI_TOKEN_PROTOCOL);
480                 protocol_list[protocol_len] = '\0';
481                 p = protocol_list;
482                 hit = 0;
483
484                 while (*p && !hit) {
485                         unsigned int n = 0;
486                         while (n < sizeof(protocol_name) - 1 && *p && *p !=',')
487                                 protocol_name[n++] = *p++;
488                         protocol_name[n] = '\0';
489                         if (*p)
490                                 p++;
491
492                         lwsl_info("checking %s\n", protocol_name);
493
494                         n = 0;
495                         while (context->protocols[n].callback) {
496                                 if (context->protocols[n].name &&
497                                     !strcmp(context->protocols[n].name,
498                                             protocol_name)) {
499                                         lwsl_info("prot match %d\n", n);
500                                         wsi->protocol = &context->protocols[n];
501                                         hit = 1;
502                                         break;
503                                 }
504
505                                 n++;
506                         }
507                 }
508
509                 /* we didn't find a protocol he wanted? */
510
511                 if (!hit) {
512                         if (lws_hdr_simple_ptr(wsi, WSI_TOKEN_PROTOCOL)) {
513                                 lwsl_err("No protocol from \"%s\" supported\n",
514                                          protocol_list);
515                                 goto bail_nuke_ah;
516                         }
517                         /*
518                          * some clients only have one protocol and
519                          * do not sent the protocol list header...
520                          * allow it and match to protocol 0
521                          */
522                         lwsl_info("defaulting to prot 0 handler\n");
523                         wsi->protocol = &context->protocols[0];
524                 }
525
526                 /* allocate wsi->user storage */
527                 if (lws_ensure_user_space(wsi))
528                         goto bail_nuke_ah;
529
530                 /*
531                  * Give the user code a chance to study the request and
532                  * have the opportunity to deny it
533                  */
534
535                 if ((wsi->protocol->callback)(wsi,
536                                 LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION,
537                                 wsi->user_space,
538                               lws_hdr_simple_ptr(wsi, WSI_TOKEN_PROTOCOL), 0)) {
539                         lwsl_warn("User code denied connection\n");
540                         goto bail_nuke_ah;
541                 }
542
543                 /*
544                  * Perform the handshake according to the protocol version the
545                  * client announced
546                  */
547
548                 switch (wsi->ietf_spec_revision) {
549                 case 13:
550                         lwsl_parser("lws_parse calling handshake_04\n");
551                         if (handshake_0405(context, wsi)) {
552                                 lwsl_info("hs0405 has failed the connection\n");
553                                 goto bail_nuke_ah;
554                         }
555                         break;
556
557                 default:
558                         lwsl_warn("Unknown client spec version %d\n",
559                                   wsi->ietf_spec_revision);
560                         goto bail_nuke_ah;
561                 }
562
563                 /* we are upgrading to ws, so http/1.1 and keepalive +
564                  * pipelined header considerations about keeping the ah around
565                  * no longer apply.  However it's common for the first ws
566                  * protocol data to have been coalesced with the browser
567                  * upgrade request and to already be in the ah rx buffer.
568                  */
569
570                 lwsl_info("%s: %p: inheriting ah in ws mode (rxpos:%d, rxlen:%d)\n",
571                           __func__, wsi, wsi->u.hdr.ah->rxpos,
572                           wsi->u.hdr.ah->rxlen);
573                 lws_pt_lock(pt);
574                 hdr = wsi->u.hdr;
575
576                 lws_union_transition(wsi, LWSCM_WS_SERVING);
577                 /*
578                  * first service is WS mode will notice this, use the RX and
579                  * then detach the ah (caution: we are not in u.hdr union
580                  * mode any more then... ah_temp member is at start the same
581                  * though)
582                  *
583                  * Because rxpos/rxlen shows something in the ah, we will get
584                  * service guaranteed next time around the event loop
585                  *
586                  * All union members begin with hdr, so we can use it even
587                  * though we transitioned to ws union mode (the ah detach
588                  * code uses it anyway).
589                  */
590                 wsi->u.hdr = hdr;
591                 lws_pt_unlock(pt);
592
593                 /*
594                  * create the frame buffer for this connection according to the
595                  * size mentioned in the protocol definition.  If 0 there, use
596                  * a big default for compatibility
597                  */
598
599                 n = wsi->protocol->rx_buffer_size;
600                 if (!n)
601                         n = LWS_MAX_SOCKET_IO_BUF;
602                 n += LWS_PRE;
603                 wsi->u.ws.rx_ubuf = lws_malloc(n + 4 /* 0x0000ffff zlib */);
604                 if (!wsi->u.ws.rx_ubuf) {
605                         lwsl_err("Out of Mem allocating rx buffer %d\n", n);
606                         return 1;
607                 }
608                 wsi->u.ws.rx_ubuf_alloc = n;
609                 lwsl_info("Allocating RX buffer %d\n", n);
610 #if LWS_POSIX
611                 if (setsockopt(wsi->sock, SOL_SOCKET, SO_SNDBUF,
612                                (const char *)&n, sizeof n)) {
613                         lwsl_warn("Failed to set SNDBUF to %d", n);
614                         return 1;
615                 }
616 #endif
617                 lwsl_parser("accepted v%02d connection\n", wsi->ietf_spec_revision);
618
619                 return 0;
620         } /* while all chars are handled */
621
622         return 0;
623
624 bail_nuke_ah:
625         /* drop the header info */
626         /* we're closing, losing some rx is OK */
627         wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
628         lws_header_table_detach(wsi);
629
630         return 1;
631 }
632
633 static int
634 lws_get_idlest_tsi(struct lws_context *context)
635 {
636         unsigned int lowest = ~0;
637         int n = 0, hit = -1;
638
639         for (; n < context->count_threads; n++) {
640                 if ((unsigned int)context->pt[n].fds_count != context->fd_limit_per_thread - 1 &&
641                     (unsigned int)context->pt[n].fds_count < lowest) {
642                         lowest = context->pt[n].fds_count;
643                         hit = n;
644                 }
645         }
646
647         return hit;
648 }
649
650 struct lws *
651 lws_create_new_server_wsi(struct lws_context *context)
652 {
653         struct lws *new_wsi;
654         int n = lws_get_idlest_tsi(context);
655
656         if (n < 0) {
657                 lwsl_err("no space for new conn\n");
658                 return NULL;
659         }
660
661         new_wsi = lws_zalloc(sizeof(struct lws));
662         if (new_wsi == NULL) {
663                 lwsl_err("Out of memory for new connection\n");
664                 return NULL;
665         }
666
667         new_wsi->tsi = n;
668         lwsl_info("Accepted %p to tsi %d\n", new_wsi, new_wsi->tsi);
669
670         new_wsi->context = context;
671         new_wsi->pending_timeout = NO_PENDING_TIMEOUT;
672         new_wsi->rxflow_change_to = LWS_RXFLOW_ALLOW;
673
674         /* intialize the instance struct */
675
676         new_wsi->state = LWSS_HTTP;
677         new_wsi->mode = LWSCM_HTTP_SERVING;
678         new_wsi->hdr_parsing_completed = 0;
679
680 #ifdef LWS_OPENSSL_SUPPORT
681         new_wsi->use_ssl = LWS_SSL_ENABLED(context);
682 #endif
683
684         /*
685          * these can only be set once the protocol is known
686          * we set an unestablished connection's protocol pointer
687          * to the start of the supported list, so it can look
688          * for matching ones during the handshake
689          */
690         new_wsi->protocol = context->protocols;
691         new_wsi->user_space = NULL;
692         new_wsi->ietf_spec_revision = 0;
693         new_wsi->sock = LWS_SOCK_INVALID;
694         context->count_wsi_allocated++;
695
696         /*
697          * outermost create notification for wsi
698          * no user_space because no protocol selection
699          */
700         context->protocols[0].callback(new_wsi, LWS_CALLBACK_WSI_CREATE,
701                                        NULL, NULL, 0);
702
703         return new_wsi;
704 }
705
706 /**
707  * lws_http_transaction_completed() - wait for new http transaction or close
708  * @wsi:        websocket connection
709  *
710  *      Returns 1 if the HTTP connection must close now
711  *      Returns 0 and resets connection to wait for new HTTP header /
712  *        transaction if possible
713  */
714
715 LWS_VISIBLE int LWS_WARN_UNUSED_RESULT
716 lws_http_transaction_completed(struct lws *wsi)
717 {
718         lwsl_debug("%s: wsi %p\n", __func__, wsi);
719         /* if we can't go back to accept new headers, drop the connection */
720         if (wsi->u.http.connection_type != HTTP_CONNECTION_KEEP_ALIVE) {
721                 lwsl_info("%s: %p: close connection\n", __func__, wsi);
722                 return 1;
723         }
724
725         /* otherwise set ourselves up ready to go again */
726         wsi->state = LWSS_HTTP;
727         wsi->mode = LWSCM_HTTP_SERVING;
728         wsi->u.http.content_length = 0;
729         wsi->hdr_parsing_completed = 0;
730
731         /* He asked for it to stay alive indefinitely */
732         lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
733
734         /*
735          * We already know we are on http1.1 / keepalive and the next thing
736          * coming will be another header set.
737          *
738          * If there is no pending rx and we still have the ah, drop it and
739          * reacquire a new ah when the new headers start to arrive.  (Otherwise
740          * we needlessly hog an ah indefinitely.)
741          *
742          * However if there is pending rx and we know from the keepalive state
743          * that is already at least the start of another header set, simply
744          * reset the existing header table and keep it.
745          */
746         if (wsi->u.hdr.ah) {
747                 if (!wsi->u.hdr.more_rx_waiting) {
748                         wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
749                         lws_header_table_detach(wsi);
750                 } else
751                         lws_header_table_reset(wsi);
752         }
753
754         /* If we're (re)starting on headers, need other implied init */
755         wsi->u.hdr.ues = URIES_IDLE;
756
757         lwsl_info("%s: %p: keep-alive await new transaction\n", __func__, wsi);
758
759         return 0;
760 }
761
762 /**
763  * lws_adopt_socket() - adopt foreign socket as if listen socket accepted it
764  * @context: lws context
765  * @accept_fd: fd of already-accepted socket to adopt
766  *
767  * Either returns new wsi bound to accept_fd, or closes accept_fd and
768  * returns NULL, having cleaned up any new wsi pieces.
769  *
770  * LWS adopts the socket in http serving mode, it's ready to accept an upgrade
771  * to ws or just serve http.
772  */
773
774 LWS_VISIBLE struct lws *
775 lws_adopt_socket(struct lws_context *context, lws_sockfd_type accept_fd)
776 {
777         struct lws *new_wsi = lws_create_new_server_wsi(context);
778
779         if (!new_wsi) {
780                 compatible_close(accept_fd);
781                 return NULL;
782         }
783
784         lwsl_debug("%s: new wsi %p\n", __func__, new_wsi);
785
786         new_wsi->sock = accept_fd;
787
788         /* the transport is accepted... give him time to negotiate */
789         lws_set_timeout(new_wsi, PENDING_TIMEOUT_ESTABLISH_WITH_SERVER,
790                         context->timeout_secs);
791
792 #if LWS_POSIX == 0
793         mbed3_tcp_stream_accept(accept_fd, new_wsi);
794 #endif
795
796         /*
797          * A new connection was accepted. Give the user a chance to
798          * set properties of the newly created wsi. There's no protocol
799          * selected yet so we issue this to protocols[0]
800          */
801         if ((context->protocols[0].callback)(new_wsi,
802              LWS_CALLBACK_SERVER_NEW_CLIENT_INSTANTIATED, NULL, NULL, 0)) {
803                 compatible_close(new_wsi->sock);
804                 lws_free(new_wsi);
805                 return NULL;
806         }
807
808         lws_libev_accept(new_wsi, new_wsi->sock);
809         lws_libuv_accept(new_wsi, new_wsi->sock);
810
811         if (!LWS_SSL_ENABLED(context)) {
812                 if (insert_wsi_socket_into_fds(context, new_wsi))
813                         goto fail;
814         } else {
815                 new_wsi->mode = LWSCM_SSL_INIT;
816                 if (lws_server_socket_service_ssl(new_wsi, accept_fd))
817                         goto fail;
818         }
819
820         return new_wsi;
821
822 fail:
823         lwsl_err("%s: fail\n", __func__);
824         lws_close_free_wsi(new_wsi, LWS_CLOSE_STATUS_NOSTATUS);
825
826         return NULL;
827 }
828
829 LWS_VISIBLE int
830 lws_server_socket_service(struct lws_context *context, struct lws *wsi,
831                           struct lws_pollfd *pollfd)
832 {
833         struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
834         lws_sockfd_type accept_fd = LWS_SOCK_INVALID;
835         struct allocated_headers *ah;
836 #if LWS_POSIX
837         struct sockaddr_in cli_addr;
838         socklen_t clilen;
839 #endif
840         int n, len;
841
842         switch (wsi->mode) {
843
844         case LWSCM_HTTP_SERVING:
845         case LWSCM_HTTP_SERVING_ACCEPTED:
846         case LWSCM_HTTP2_SERVING:
847
848                 /* handle http headers coming in */
849
850                 /* pending truncated sends have uber priority */
851
852                 if (wsi->trunc_len) {
853                         if (!(pollfd->revents & LWS_POLLOUT))
854                                 break;
855
856                         if (lws_issue_raw(wsi, wsi->trunc_alloc +
857                                                wsi->trunc_offset,
858                                           wsi->trunc_len) < 0)
859                                 goto fail;
860                         /*
861                          * we can't afford to allow input processing to send
862                          * something new, so spin around he event loop until
863                          * he doesn't have any partials
864                          */
865                         break;
866                 }
867
868                 /* any incoming data ready? */
869
870                 if (!(pollfd->revents & pollfd->events & LWS_POLLIN))
871                         goto try_pollout;
872
873                 /* these states imply we MUST have an ah attached */
874
875                 if (wsi->state == LWSS_HTTP ||
876                     wsi->state == LWSS_HTTP_ISSUING_FILE ||
877                     wsi->state == LWSS_HTTP_HEADERS) {
878                         if (!wsi->u.hdr.ah)
879                                 if (lws_header_table_attach(wsi))
880                                         goto try_pollout;
881
882                         ah = wsi->u.hdr.ah;
883
884                         lwsl_debug("%s: %p: rxpos:%d rxlen:%d\n", __func__, wsi,
885                                    ah->rxpos, ah->rxlen);
886
887                         /* if nothing in ah rx buffer, get some fresh rx */
888                         if (ah->rxpos == ah->rxlen) {
889                                 ah->rxlen = lws_ssl_capable_read(wsi, ah->rx,
890                                                    sizeof(ah->rx));
891                                 ah->rxpos = 0;
892                                 lwsl_debug("%s: wsi %p, ah->rxlen = %d\r\n",
893                                            __func__, wsi, ah->rxlen);
894                                 switch (ah->rxlen) {
895                                 case 0:
896                                         lwsl_info("%s: read 0 len\n", __func__);
897                                         /* lwsl_info("   state=%d\n", wsi->state); */
898 //                                      if (!wsi->hdr_parsing_completed)
899 //                                              lws_header_table_detach(wsi);
900                                         /* fallthru */
901                                 case LWS_SSL_CAPABLE_ERROR:
902                                         goto fail;
903                                 case LWS_SSL_CAPABLE_MORE_SERVICE:
904                                         ah->rxlen = ah->rxpos = 0;
905                                         goto try_pollout;
906                                 }
907                         }
908                         assert(ah->rxpos != ah->rxlen && ah->rxlen);
909                         /* just ignore incoming if waiting for close */
910                         if (wsi->state != LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE) {
911                                 n = lws_read(wsi, ah->rx + ah->rxpos,
912                                              ah->rxlen - ah->rxpos);
913                                 if (n < 0) /* we closed wsi */
914                                         return 1;
915                                 if (wsi->u.hdr.ah) {
916                                         if ( wsi->u.hdr.ah->rxlen)
917                                                  wsi->u.hdr.ah->rxpos += n;
918
919                                         if (wsi->u.hdr.ah->rxpos == wsi->u.hdr.ah->rxlen &&
920                                             (wsi->mode != LWSCM_HTTP_SERVING &&
921                                              wsi->mode != LWSCM_HTTP_SERVING_ACCEPTED &&
922                                              wsi->mode != LWSCM_HTTP2_SERVING))
923                                                 lws_header_table_detach(wsi);
924                                 }
925                                 break;
926                         }
927
928                         goto try_pollout;
929                 }
930
931                 len = lws_ssl_capable_read(wsi, pt->serv_buf,
932                                            LWS_MAX_SOCKET_IO_BUF);
933                 lwsl_debug("%s: wsi %p read %d\r\n", __func__, wsi, len);
934                 switch (len) {
935                 case 0:
936                         lwsl_info("%s: read 0 len\n", __func__);
937                         /* lwsl_info("   state=%d\n", wsi->state); */
938 //                      if (!wsi->hdr_parsing_completed)
939 //                              lws_header_table_detach(wsi);
940                         /* fallthru */
941                 case LWS_SSL_CAPABLE_ERROR:
942                         goto fail;
943                 case LWS_SSL_CAPABLE_MORE_SERVICE:
944                         goto try_pollout;
945                 }
946
947                 /* just ignore incoming if waiting for close */
948                 if (wsi->state != LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE) {
949                         /*
950                          * hm this may want to send
951                          * (via HTTP callback for example)
952                          */
953                         n = lws_read(wsi, pt->serv_buf, len);
954                         if (n < 0) /* we closed wsi */
955                                 return 1;
956                         /* hum he may have used up the
957                          * writability above */
958                         break;
959                 }
960
961 try_pollout:
962                 /* this handles POLLOUT for http serving fragments */
963
964                 if (!(pollfd->revents & LWS_POLLOUT))
965                         break;
966
967                 /* one shot */
968                 if (lws_change_pollfd(wsi, LWS_POLLOUT, 0)) {
969                         lwsl_notice("%s a\n", __func__);
970                         goto fail;
971                 }
972
973                 if (wsi->state != LWSS_HTTP_ISSUING_FILE) {
974                         n = user_callback_handle_rxflow(wsi->protocol->callback,
975                                         wsi, LWS_CALLBACK_HTTP_WRITEABLE,
976                                         wsi->user_space, NULL, 0);
977                         if (n < 0) {
978                                 lwsl_info("writeable_fail\n");
979                                 goto fail;
980                         }
981                         break;
982                 }
983
984                 /* >0 == completion, <0 == error */
985                 n = lws_serve_http_file_fragment(wsi);
986                 if (n < 0 || (n > 0 && lws_http_transaction_completed(wsi))) {
987                         lwsl_info("completed\n");
988                         goto fail;
989                 }
990                 break;
991
992         case LWSCM_SERVER_LISTENER:
993
994 #if LWS_POSIX
995                 /* pollin means a client has connected to us then */
996
997                 do {
998                         if (!(pollfd->revents & LWS_POLLIN) || !(pollfd->events & LWS_POLLIN))
999                                 break;
1000
1001                         /* listen socket got an unencrypted connection... */
1002
1003                         clilen = sizeof(cli_addr);
1004                         lws_latency_pre(context, wsi);
1005                         accept_fd  = accept(pollfd->fd, (struct sockaddr *)&cli_addr,
1006                                             &clilen);
1007                         lws_latency(context, wsi, "listener accept", accept_fd,
1008                                     accept_fd >= 0);
1009                         if (accept_fd < 0) {
1010                                 if (LWS_ERRNO == LWS_EAGAIN ||
1011                                     LWS_ERRNO == LWS_EWOULDBLOCK) {
1012                                         lwsl_err("accept asks to try again\n");
1013                                         break;
1014                                 }
1015                                 lwsl_err("ERROR on accept: %s\n", strerror(LWS_ERRNO));
1016                                 break;
1017                         }
1018
1019                         lws_plat_set_socket_options(context, accept_fd);
1020
1021                         lwsl_debug("accepted new conn  port %u on fd=%d\n",
1022                                           ntohs(cli_addr.sin_port), accept_fd);
1023
1024 #else
1025                         /* not very beautiful... */
1026                         accept_fd = (lws_sockfd_type)pollfd;
1027 #endif
1028                         /*
1029                          * look at who we connected to and give user code a chance
1030                          * to reject based on client IP.  There's no protocol selected
1031                          * yet so we issue this to protocols[0]
1032                          */
1033                         if ((context->protocols[0].callback)(wsi,
1034                                         LWS_CALLBACK_FILTER_NETWORK_CONNECTION,
1035                                         NULL, (void *)(long)accept_fd, 0)) {
1036                                 lwsl_debug("Callback denied network connection\n");
1037                                 compatible_close(accept_fd);
1038                                 break;
1039                         }
1040
1041                         if (!lws_adopt_socket(context, accept_fd))
1042                                 /* already closed cleanly as necessary */
1043                                 return 1;
1044
1045 #if LWS_POSIX
1046                 } while (pt->fds_count < context->fd_limit_per_thread - 1 &&
1047                          lws_poll_listen_fd(&pt->fds[wsi->position_in_fds_table]) > 0);
1048 #endif
1049                 return 0;
1050
1051         default:
1052                 break;
1053         }
1054
1055         if (!lws_server_socket_service_ssl(wsi, accept_fd))
1056                 return 0;
1057
1058 fail:
1059         lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
1060
1061         return 1;
1062 }
1063
1064 /**
1065  * lws_serve_http_file() - Send a file back to the client using http
1066  * @wsi:                Websocket instance (available from user callback)
1067  * @file:               The file to issue over http
1068  * @content_type:       The http content type, eg, text/html
1069  * @other_headers:      NULL or pointer to header string
1070  * @other_headers_len:  length of the other headers if non-NULL
1071  *
1072  *      This function is intended to be called from the callback in response
1073  *      to http requests from the client.  It allows the callback to issue
1074  *      local files down the http link in a single step.
1075  *
1076  *      Returning <0 indicates error and the wsi should be closed.  Returning
1077  *      >0 indicates the file was completely sent and
1078  *      lws_http_transaction_completed() called on the wsi (and close if != 0)
1079  *      ==0 indicates the file transfer is started and needs more service later,
1080  *      the wsi should be left alone.
1081  */
1082
1083 LWS_VISIBLE int
1084 lws_serve_http_file(struct lws *wsi, const char *file, const char *content_type,
1085                     const char *other_headers, int other_headers_len)
1086 {
1087         struct lws_context *context = lws_get_context(wsi);
1088         struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
1089         unsigned char *response = pt->serv_buf + LWS_PRE;
1090         unsigned char *p = response;
1091         unsigned char *end = p + LWS_MAX_SOCKET_IO_BUF - LWS_PRE;
1092         int ret = 0;
1093
1094         wsi->u.http.fd = lws_plat_file_open(wsi, file, &wsi->u.http.filelen,
1095                                             O_RDONLY);
1096
1097         if (wsi->u.http.fd == LWS_INVALID_FILE) {
1098                 lwsl_err("Unable to open '%s'\n", file);
1099                 lws_return_http_status(wsi, HTTP_STATUS_NOT_FOUND, NULL);
1100
1101                 return -1;
1102         }
1103
1104         if (lws_add_http_header_status(wsi, 200, &p, end))
1105                 return -1;
1106         if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_SERVER,
1107                                          (unsigned char *)"libwebsockets", 13,
1108                                          &p, end))
1109                 return -1;
1110         if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE,
1111                                          (unsigned char *)content_type,
1112                                          strlen(content_type), &p, end))
1113                 return -1;
1114         if (lws_add_http_header_content_length(wsi, wsi->u.http.filelen, &p, end))
1115                 return -1;
1116
1117         if (other_headers) {
1118                 if ((end - p) < other_headers_len)
1119                         return -1;
1120                 memcpy(p, other_headers, other_headers_len);
1121                 p += other_headers_len;
1122         }
1123
1124         if (lws_finalize_http_header(wsi, &p, end))
1125                 return -1;
1126
1127         ret = lws_write(wsi, response, p - response, LWS_WRITE_HTTP_HEADERS);
1128         if (ret != (p - response)) {
1129                 lwsl_err("_write returned %d from %d\n", ret, (p - response));
1130                 return -1;
1131         }
1132
1133         wsi->u.http.filepos = 0;
1134         wsi->state = LWSS_HTTP_ISSUING_FILE;
1135
1136         return lws_serve_http_file_fragment(wsi);
1137 }
1138
1139 int
1140 lws_interpret_incoming_packet(struct lws *wsi, unsigned char **buf, size_t len)
1141 {
1142         int m;
1143
1144         lwsl_parser("%s: received %d byte packet\n", __func__, (int)len);
1145 #if 0
1146         lwsl_hexdump(*buf, len);
1147 #endif
1148
1149         /* let the rx protocol state machine have as much as it needs */
1150
1151         while (len) {
1152                 /*
1153                  * we were accepting input but now we stopped doing so
1154                  */
1155                 if (!(wsi->rxflow_change_to & LWS_RXFLOW_ALLOW)) {
1156                         lws_rxflow_cache(wsi, *buf, 0, len);
1157                         lwsl_parser("%s: cached %d\n", __func__, len);
1158                         return 1;
1159                 }
1160
1161                 if (wsi->u.ws.rx_draining_ext) {
1162                         m = lws_rx_sm(wsi, 0);
1163                         if (m < 0)
1164                                 return -1;
1165                         continue;
1166                 }
1167
1168                 /* account for what we're using in rxflow buffer */
1169                 if (wsi->rxflow_buffer)
1170                         wsi->rxflow_pos++;
1171
1172                 /* process the byte */
1173                 m = lws_rx_sm(wsi, *(*buf)++);
1174                 if (m < 0)
1175                         return -1;
1176                 len--;
1177         }
1178
1179         lwsl_parser("%s: exit with %d unused\n", __func__, (int)len);
1180
1181         return 0;
1182 }
1183
1184 LWS_VISIBLE void
1185 lws_server_get_canonical_hostname(struct lws_context *context,
1186                                   struct lws_context_creation_info *info)
1187 {
1188         if (info->options & LWS_SERVER_OPTION_SKIP_SERVER_CANONICAL_NAME)
1189                 return;
1190 #if LWS_POSIX
1191         /* find canonical hostname */
1192         gethostname((char *)context->canonical_hostname,
1193                     sizeof(context->canonical_hostname) - 1);
1194
1195         lwsl_notice(" canonical_hostname = %s\n", context->canonical_hostname);
1196 #else
1197         (void)context;
1198 #endif
1199 }