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