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