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