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