01cf46954f6c689eba3316c20dc0d4e5e99bfa7a
[platform/upstream/libwebsockets.git] / lib / libwebsockets.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 #include "private-libwebsockets.h"
23
24 #ifdef LWS_HAVE_SYS_TYPES_H
25 #include <sys/types.h>
26 #endif
27
28 #if defined(WIN32) || defined(_WIN32)
29 #else
30 #include <sys/wait.h>
31 #endif
32
33 #ifdef LWS_USE_IPV6
34 #if defined(WIN32) || defined(_WIN32)
35 #include <Iphlpapi.h>
36 #else
37 #include <net/if.h>
38 #endif
39 #endif
40
41 int log_level = LLL_ERR | LLL_WARN | LLL_NOTICE;
42 static void (*lwsl_emit)(int level, const char *line)
43 #ifndef LWS_PLAT_OPTEE
44         = lwsl_emit_stderr
45 #endif
46         ;
47 #ifndef LWS_PLAT_OPTEE
48 static const char * const log_level_names[] = {
49         "ERR",
50         "WARN",
51         "NOTICE",
52         "INFO",
53         "DEBUG",
54         "PARSER",
55         "HEADER",
56         "EXTENSION",
57         "CLIENT",
58         "LATENCY",
59         "USER",
60         "?",
61         "?"
62 };
63 #endif
64
65 void
66 lws_free_wsi(struct lws *wsi)
67 {
68         if (!wsi)
69                 return;
70         
71         /* Protocol user data may be allocated either internally by lws
72          * or by specified the user.
73          * We should only free what we allocated. */
74         if (wsi->protocol && wsi->protocol->per_session_data_size &&
75             wsi->user_space && !wsi->user_space_externally_allocated)
76                 lws_free(wsi->user_space);
77
78         lws_free_set_NULL(wsi->rxflow_buffer);
79         lws_free_set_NULL(wsi->trunc_alloc);
80
81         /* we may not have an ah, but may be on the waiting list... */
82         lwsl_info("ah det due to close\n");
83         lws_header_table_detach(wsi, 0);
84
85         wsi->context->count_wsi_allocated--;
86         lwsl_debug("%s: %p, remaining wsi %d\n", __func__, wsi,
87                         wsi->context->count_wsi_allocated);
88
89         lws_free(wsi);
90 }
91
92 void
93 lws_remove_from_timeout_list(struct lws *wsi)
94 {
95         struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
96
97         if (!wsi->timeout_list_prev) /* ie, not part of the list */
98                 return;
99
100         lws_pt_lock(pt);
101         /* if we have a next guy, set his prev to our prev */
102         if (wsi->timeout_list)
103                 wsi->timeout_list->timeout_list_prev = wsi->timeout_list_prev;
104         /* set our prev guy to our next guy instead of us */
105         *wsi->timeout_list_prev = wsi->timeout_list;
106
107         /* we're out of the list, we should not point anywhere any more */
108         wsi->timeout_list_prev = NULL;
109         wsi->timeout_list = NULL;
110         lws_pt_unlock(pt);
111 }
112
113 LWS_VISIBLE void
114 lws_set_timeout(struct lws *wsi, enum pending_timeout reason, int secs)
115 {
116         struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
117         time_t now;
118
119         if (secs == LWS_TO_KILL_SYNC) {
120                 lws_remove_from_timeout_list(wsi);
121                 lwsl_debug("synchronously killing %p\n", wsi);
122                 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
123                 return;
124         }
125
126         lws_pt_lock(pt);
127
128         time(&now);
129
130         if (reason && !wsi->timeout_list_prev) {
131                 /* our next guy is current first guy */
132                 wsi->timeout_list = pt->timeout_list;
133                 /* if there is a next guy, set his prev ptr to our next ptr */
134                 if (wsi->timeout_list)
135                         wsi->timeout_list->timeout_list_prev = &wsi->timeout_list;
136                 /* our prev ptr is first ptr */
137                 wsi->timeout_list_prev = &pt->timeout_list;
138                 /* set the first guy to be us */
139                 *wsi->timeout_list_prev = wsi;
140         }
141
142         lwsl_debug("%s: %p: %d secs\n", __func__, wsi, secs);
143         wsi->pending_timeout_limit = now + secs;
144         wsi->pending_timeout = reason;
145
146         lws_pt_unlock(pt);
147
148         if (!reason)
149                 lws_remove_from_timeout_list(wsi);
150 }
151
152 static void
153 lws_remove_child_from_any_parent(struct lws *wsi)
154 {
155         struct lws **pwsi;
156         int seen = 0;
157
158         if (!wsi->parent)
159                 return;
160
161         /* detach ourselves from parent's child list */
162         pwsi = &wsi->parent->child_list;
163         while (*pwsi) {
164                 if (*pwsi == wsi) {
165                         lwsl_info("%s: detach %p from parent %p\n",
166                                         __func__, wsi, wsi->parent);
167
168                         if (wsi->parent->protocol)
169                                 wsi->parent->protocol->callback(wsi,
170                                                 LWS_CALLBACK_CHILD_CLOSING,
171                                                wsi->parent->user_space, wsi, 0);
172
173                         *pwsi = wsi->sibling_list;
174                         seen = 1;
175                         break;
176                 }
177                 pwsi = &(*pwsi)->sibling_list;
178         }
179         if (!seen)
180                 lwsl_err("%s: failed to detach from parent\n", __func__);
181
182         wsi->parent = NULL;
183 }
184
185 int
186 lws_bind_protocol(struct lws *wsi, const struct lws_protocols *p)
187 {
188 //      if (wsi->protocol == p)
189 //              return 0;
190         const struct lws_protocols *vp = wsi->vhost->protocols, *vpo;
191
192         if (wsi->protocol)
193                 wsi->protocol->callback(wsi, LWS_CALLBACK_HTTP_DROP_PROTOCOL,
194                                         wsi->user_space, NULL, 0);
195         if (!wsi->user_space_externally_allocated)
196                 lws_free_set_NULL(wsi->user_space);
197
198         lws_same_vh_protocol_remove(wsi);
199
200         wsi->protocol = p;
201         if (!p)
202                 return 0;
203
204         if (lws_ensure_user_space(wsi))
205                 return 1;
206
207         if (p > vp && p < &vp[wsi->vhost->count_protocols])
208                 lws_same_vh_protocol_insert(wsi, p - vp);
209         else {
210                 int n = wsi->vhost->count_protocols;
211                 int hit = 0;
212
213                 vpo = vp;
214
215                 while (n--) {
216                         if (p->name && vp->name && !strcmp(p->name, vp->name)) {
217                                 hit = 1;
218                                 lws_same_vh_protocol_insert(wsi, vp - vpo);
219                                 break;
220                         }
221                         vp++;
222                 }
223                 if (!hit)
224                         lwsl_err("%s: protocol %p is not in vhost %s protocols list\n",
225                          __func__, p, wsi->vhost->name);
226         }
227
228         if (wsi->protocol->callback(wsi, LWS_CALLBACK_HTTP_BIND_PROTOCOL,
229                                     wsi->user_space, NULL, 0))
230                 return 1;
231
232         return 0;
233 }
234
235 void
236 lws_close_free_wsi(struct lws *wsi, enum lws_close_status reason)
237 {
238         struct lws_context_per_thread *pt;
239         struct lws *wsi1, *wsi2;
240         struct lws_context *context;
241         struct lws_tokens eff_buf;
242         int n, m, ret;
243
244         lwsl_debug("%s: %p\n", __func__, wsi);
245
246         if (!wsi)
247                 return;
248
249         lws_access_log(wsi);
250 #if defined(LWS_WITH_ESP8266)
251         if (wsi->premature_rx)
252                 lws_free(wsi->premature_rx);
253
254         if (wsi->pending_send_completion && !wsi->close_is_pending_send_completion) {
255                 lwsl_notice("delaying close\n");
256                 wsi->close_is_pending_send_completion = 1;
257                 return;
258         }
259 #endif
260
261         /* we're closing, losing some rx is OK */
262         lws_header_table_force_to_detachable_state(wsi);
263
264         context = wsi->context;
265         pt = &context->pt[(int)wsi->tsi];
266         lws_stats_atomic_bump(wsi->context, pt, LWSSTATS_C_API_CLOSE, 1);
267
268         /* if we have children, close them first */
269         if (wsi->child_list) {
270                 wsi2 = wsi->child_list;
271                 while (wsi2) {
272                         //lwsl_notice("%s: closing %p: close child %p\n",
273                         //              __func__, wsi, wsi2);
274                         wsi1 = wsi2->sibling_list;
275                         //lwsl_notice("%s: closing %p: next sibling %p\n",
276                         //              __func__, wsi2, wsi1);
277                         wsi2->parent = NULL;
278                         /* stop it doing shutdown processing */
279                         wsi2->socket_is_permanently_unusable = 1;
280                         lws_close_free_wsi(wsi2, reason);
281                         wsi2 = wsi1;
282                 }
283                 wsi->child_list = NULL;
284         }
285
286         if (wsi->mode == LWSCM_RAW_FILEDESC) {
287                         lws_remove_child_from_any_parent(wsi);
288                         remove_wsi_socket_from_fds(wsi);
289                         wsi->protocol->callback(wsi,
290                                                 LWS_CALLBACK_RAW_CLOSE_FILE,
291                                                 wsi->user_space, NULL, 0);
292                         goto async_close;
293         }
294
295 #ifdef LWS_WITH_CGI
296         if (wsi->mode == LWSCM_CGI) {
297                 /* we are not a network connection, but a handler for CGI io */
298                 if (wsi->parent && wsi->parent->cgi)
299                         /* end the binding between us and master */
300                         wsi->parent->cgi->stdwsi[(int)wsi->cgi_channel] = NULL;
301                 wsi->socket_is_permanently_unusable = 1;
302
303                 lwsl_debug("------ %s: detected cgi fdhandler wsi %p\n", __func__, wsi);
304                 goto just_kill_connection;
305         }
306
307         if (wsi->cgi) {
308                 struct lws_cgi **pcgi = &pt->cgi_list;
309                 /* remove us from the cgi list */
310                 lwsl_debug("%s: remove cgi %p from list\n", __func__, wsi->cgi);
311                 while (*pcgi) {
312                         if (*pcgi == wsi->cgi) {
313                                 /* drop us from the pt cgi list */
314                                 *pcgi = (*pcgi)->cgi_list;
315                                 break;
316                         }
317                         pcgi = &(*pcgi)->cgi_list;
318                 }
319                 if (wsi->cgi->headers_buf) {
320                         lwsl_debug("close: freed cgi headers\n");
321                         lws_free_set_NULL(wsi->cgi->headers_buf);
322                 }
323                 /* we have a cgi going, we must kill it */
324                 wsi->cgi->being_closed = 1;
325                 lws_cgi_kill(wsi);
326         }
327 #endif
328
329 #if !defined(LWS_NO_CLIENT)
330         if (wsi->mode == LWSCM_HTTP_CLIENT ||
331             wsi->mode == LWSCM_WSCL_WAITING_CONNECT ||
332             wsi->mode == LWSCM_WSCL_WAITING_PROXY_REPLY ||
333             wsi->mode == LWSCM_WSCL_ISSUE_HANDSHAKE ||
334             wsi->mode == LWSCM_WSCL_ISSUE_HANDSHAKE2 ||
335             wsi->mode == LWSCM_WSCL_WAITING_SSL ||
336             wsi->mode == LWSCM_WSCL_WAITING_SERVER_REPLY ||
337             wsi->mode == LWSCM_WSCL_WAITING_EXTENSION_CONNECT ||
338             wsi->mode == LWSCM_WSCL_WAITING_SOCKS_GREETING_REPLY ||
339             wsi->mode == LWSCM_WSCL_WAITING_SOCKS_CONNECT_REPLY ||
340             wsi->mode == LWSCM_WSCL_WAITING_SOCKS_AUTH_REPLY)
341                 if (wsi->u.hdr.stash)
342                         lws_free_set_NULL(wsi->u.hdr.stash);
343 #endif
344
345         if (wsi->mode == LWSCM_RAW) {
346                 wsi->protocol->callback(wsi,
347                         LWS_CALLBACK_RAW_CLOSE, wsi->user_space, NULL, 0);
348                 wsi->socket_is_permanently_unusable = 1;
349                 goto just_kill_connection;
350         }
351
352         if (wsi->mode == LWSCM_HTTP_SERVING_ACCEPTED &&
353             wsi->u.http.fop_fd != NULL) {
354                 lws_vfs_file_close(&wsi->u.http.fop_fd);
355                 wsi->vhost->protocols->callback(wsi,
356                         LWS_CALLBACK_CLOSED_HTTP, wsi->user_space, NULL, 0);
357                 wsi->told_user_closed = 1;
358         }
359         if (wsi->socket_is_permanently_unusable ||
360             reason == LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY ||
361             wsi->state == LWSS_SHUTDOWN)
362                 goto just_kill_connection;
363
364         wsi->state_pre_close = wsi->state;
365
366         switch (wsi->state_pre_close) {
367         case LWSS_DEAD_SOCKET:
368                 return;
369
370         /* we tried the polite way... */
371         case LWSS_WAITING_TO_SEND_CLOSE_NOTIFICATION:
372         case LWSS_AWAITING_CLOSE_ACK:
373                 goto just_kill_connection;
374
375         case LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE:
376                 if (wsi->trunc_len) {
377                         lws_callback_on_writable(wsi);
378                         return;
379                 }
380                 lwsl_info("wsi %p completed LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE\n", wsi);
381                 goto just_kill_connection;
382         default:
383                 if (wsi->trunc_len) {
384                         lwsl_info("wsi %p entering LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE\n", wsi);
385                         wsi->state = LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE;
386                         lws_set_timeout(wsi, PENDING_FLUSH_STORED_SEND_BEFORE_CLOSE, 5);
387                         return;
388                 }
389                 break;
390         }
391
392         if (wsi->mode == LWSCM_WSCL_WAITING_CONNECT ||
393             wsi->mode == LWSCM_WSCL_ISSUE_HANDSHAKE)
394                 goto just_kill_connection;
395
396         if (wsi->mode == LWSCM_HTTP_SERVING) {
397                 if (wsi->user_space)
398                         wsi->vhost->protocols->callback(wsi,
399                                                 LWS_CALLBACK_HTTP_DROP_PROTOCOL,
400                                                wsi->user_space, NULL, 0);
401                 wsi->vhost->protocols->callback(wsi, LWS_CALLBACK_CLOSED_HTTP,
402                                                wsi->user_space, NULL, 0);
403                 wsi->told_user_closed = 1;
404         }
405         if (wsi->mode & LWSCM_FLAG_IMPLIES_CALLBACK_CLOSED_CLIENT_HTTP) {
406                 wsi->vhost->protocols[0].callback(wsi, LWS_CALLBACK_CLOSED_CLIENT_HTTP,
407                                                wsi->user_space, NULL, 0);
408                 wsi->told_user_closed = 1;
409         }
410
411         /*
412          * are his extensions okay with him closing?  Eg he might be a mux
413          * parent and just his ch1 aspect is closing?
414          */
415
416         if (lws_ext_cb_active(wsi,
417                       LWS_EXT_CB_CHECK_OK_TO_REALLY_CLOSE, NULL, 0) > 0) {
418                 lwsl_ext("extension vetoed close\n");
419                 return;
420         }
421
422         /*
423          * flush any tx pending from extensions, since we may send close packet
424          * if there are problems with send, just nuke the connection
425          */
426
427         do {
428                 ret = 0;
429                 eff_buf.token = NULL;
430                 eff_buf.token_len = 0;
431
432                 /* show every extension the new incoming data */
433
434                 m = lws_ext_cb_active(wsi,
435                           LWS_EXT_CB_FLUSH_PENDING_TX, &eff_buf, 0);
436                 if (m < 0) {
437                         lwsl_ext("Extension reports fatal error\n");
438                         goto just_kill_connection;
439                 }
440                 if (m)
441                         /*
442                          * at least one extension told us he has more
443                          * to spill, so we will go around again after
444                          */
445                         ret = 1;
446
447                 /* assuming they left us something to send, send it */
448
449                 if (eff_buf.token_len)
450                         if (lws_issue_raw(wsi, (unsigned char *)eff_buf.token,
451                                           eff_buf.token_len) !=
452                             eff_buf.token_len) {
453                                 lwsl_debug("close: ext spill failed\n");
454                                 goto just_kill_connection;
455                         }
456         } while (ret);
457
458         /*
459          * signal we are closing, lws_write will
460          * add any necessary version-specific stuff.  If the write fails,
461          * no worries we are closing anyway.  If we didn't initiate this
462          * close, then our state has been changed to
463          * LWSS_RETURNED_CLOSE_ALREADY and we will skip this.
464          *
465          * Likewise if it's a second call to close this connection after we
466          * sent the close indication to the peer already, we are in state
467          * LWSS_AWAITING_CLOSE_ACK and will skip doing this a second time.
468          */
469
470         if (wsi->state_pre_close == LWSS_ESTABLISHED &&
471             (wsi->u.ws.close_in_ping_buffer_len || /* already a reason */
472              (reason != LWS_CLOSE_STATUS_NOSTATUS &&
473              (reason != LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY)))) {
474                 lwsl_debug("sending close indication...\n");
475
476                 /* if no prepared close reason, use 1000 and no aux data */
477                 if (!wsi->u.ws.close_in_ping_buffer_len) {
478                         wsi->u.ws.close_in_ping_buffer_len = 2;
479                         wsi->u.ws.ping_payload_buf[LWS_PRE] =
480                                (reason >> 8) & 0xff;
481                         wsi->u.ws.ping_payload_buf[LWS_PRE + 1] =
482                                 reason & 0xff;
483                 }
484
485 #if defined (LWS_WITH_ESP8266)
486                 wsi->close_is_pending_send_completion = 1;
487 #endif
488
489                 lwsl_debug("waiting for chance to send close\n");
490                 wsi->waiting_to_send_close_frame = 1;
491                 wsi->state = LWSS_WAITING_TO_SEND_CLOSE_NOTIFICATION;
492                 lws_set_timeout(wsi, PENDING_TIMEOUT_CLOSE_SEND, 2);
493                 lws_callback_on_writable(wsi);
494
495                 return;
496         }
497
498 just_kill_connection:
499
500         lws_remove_child_from_any_parent(wsi);
501
502 #if 0
503         /* manage the vhost same protocol list entry */
504
505         if (wsi->same_vh_protocol_prev) { // we are on the vh list
506
507                 // make guy who pointed to us, point to what our next was pointing to
508                 *wsi->same_vh_protocol_prev = wsi->same_vh_protocol_next;
509
510                 // if we had a next guy...
511                 if (wsi->same_vh_protocol_next)
512                         // have him point back to our prev
513                         wsi->same_vh_protocol_next->same_vh_protocol_prev =
514                                         wsi->same_vh_protocol_prev;
515         }
516 #endif
517
518 #if LWS_POSIX
519         /*
520          * Testing with ab shows that we have to stage the socket close when
521          * the system is under stress... shutdown any further TX, change the
522          * state to one that won't emit anything more, and wait with a timeout
523          * for the POLLIN to show a zero-size rx before coming back and doing
524          * the actual close.
525          */
526         if (wsi->mode != LWSCM_RAW &&
527             !(wsi->mode & LWSCM_FLAG_IMPLIES_CALLBACK_CLOSED_CLIENT_HTTP) &&
528             wsi->state != LWSS_SHUTDOWN &&
529             wsi->state != LWSS_CLIENT_UNCONNECTED &&
530             reason != LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY &&
531             !wsi->socket_is_permanently_unusable) {
532 #ifdef LWS_OPENSSL_SUPPORT
533                 if (lws_is_ssl(wsi) && wsi->ssl)
534                 {
535                         lwsl_info("%s: shutting down SSL connection: %p (ssl %p, sock %d, state %d)\n", __func__, wsi, wsi->ssl, (int)(long)wsi->desc.sockfd, wsi->state);
536                         n = SSL_shutdown(wsi->ssl);
537                         if (n == 1) /* If finished the SSL shutdown, then do socket shutdown, else need to retry SSL shutdown */
538                                 n = shutdown(wsi->desc.sockfd, SHUT_WR);
539                         else if (n == 0)
540                                 lws_change_pollfd(wsi, LWS_POLLOUT, LWS_POLLIN);
541                         else /* n < 0 */
542                         {
543                                 int shutdown_error = SSL_get_error(wsi->ssl, n);
544                                 lwsl_debug("SSL_shutdown returned %d, SSL_get_error: %d\n", n, shutdown_error);
545                                 if (shutdown_error == SSL_ERROR_WANT_READ) {
546                                         lws_change_pollfd(wsi, LWS_POLLOUT, LWS_POLLIN);
547                                         n = 0;
548                                 } else if (shutdown_error == SSL_ERROR_WANT_WRITE) {
549                                         lws_change_pollfd(wsi, LWS_POLLOUT, LWS_POLLOUT);
550                                         n = 0;
551                                 } else { // actual error occurred, just close the connection
552                                         n = shutdown(wsi->desc.sockfd, SHUT_WR);
553                                 }
554                         }
555                 }
556                 else
557 #endif
558                 {
559                         lwsl_info("%s: shutting down connection: %p (sock %d, state %d)\n", __func__, wsi, (int)(long)wsi->desc.sockfd, wsi->state);
560                         n = shutdown(wsi->desc.sockfd, SHUT_WR);
561                 }
562                 if (n)
563                         lwsl_debug("closing: shutdown (state %d) ret %d\n", wsi->state, LWS_ERRNO);
564
565 // This causes problems with disconnection when the events are half closing connection
566 // FD_READ | FD_CLOSE (33)
567 #if !defined(_WIN32_WCE) && !defined(LWS_WITH_ESP32)
568                 /* libuv: no event available to guarantee completion */
569                 if (!LWS_LIBUV_ENABLED(context)) {
570
571                         lws_change_pollfd(wsi, LWS_POLLOUT, LWS_POLLIN);
572                         wsi->state = LWSS_SHUTDOWN;
573                         lws_set_timeout(wsi, PENDING_TIMEOUT_SHUTDOWN_FLUSH,
574                                         context->timeout_secs);
575
576                         return;
577                 }
578 #endif
579         }
580 #endif
581
582         lwsl_info("%s: real just_kill_connection: %p (sockfd %d)\n", __func__,
583                   wsi, wsi->desc.sockfd);
584         
585 #ifdef LWS_WITH_HTTP_PROXY
586         if (wsi->rw) {
587                 lws_rewrite_destroy(wsi->rw);
588                 wsi->rw = NULL;
589         }
590 #endif
591         /*
592          * we won't be servicing or receiving anything further from this guy
593          * delete socket from the internal poll list if still present
594          */
595         lws_ssl_remove_wsi_from_buffered_list(wsi);
596
597         lws_remove_from_timeout_list(wsi);
598
599         /* checking return redundant since we anyway close */
600         if (wsi->desc.sockfd != LWS_SOCK_INVALID)
601                 remove_wsi_socket_from_fds(wsi);
602         else
603                 lws_same_vh_protocol_remove(wsi);
604
605 #if defined(LWS_WITH_ESP8266)
606         espconn_disconnect(wsi->desc.sockfd);
607 #endif
608
609         wsi->state = LWSS_DEAD_SOCKET;
610
611         lws_free_set_NULL(wsi->rxflow_buffer);
612         if (wsi->state_pre_close == LWSS_ESTABLISHED ||
613             wsi->mode == LWSCM_WS_SERVING ||
614             wsi->mode == LWSCM_WS_CLIENT) {
615
616                 if (wsi->u.ws.rx_draining_ext) {
617                         struct lws **w = &pt->rx_draining_ext_list;
618
619                         wsi->u.ws.rx_draining_ext = 0;
620                         /* remove us from context draining ext list */
621                         while (*w) {
622                                 if (*w == wsi) {
623                                         *w = wsi->u.ws.rx_draining_ext_list;
624                                         break;
625                                 }
626                                 w = &((*w)->u.ws.rx_draining_ext_list);
627                         }
628                         wsi->u.ws.rx_draining_ext_list = NULL;
629                 }
630
631                 if (wsi->u.ws.tx_draining_ext) {
632                         struct lws **w = &pt->tx_draining_ext_list;
633
634                         wsi->u.ws.tx_draining_ext = 0;
635                         /* remove us from context draining ext list */
636                         while (*w) {
637                                 if (*w == wsi) {
638                                         *w = wsi->u.ws.tx_draining_ext_list;
639                                         break;
640                                 }
641                                 w = &((*w)->u.ws.tx_draining_ext_list);
642                         }
643                         wsi->u.ws.tx_draining_ext_list = NULL;
644                 }
645                 lws_free_set_NULL(wsi->u.ws.rx_ubuf);
646
647                 if (wsi->trunc_alloc)
648                         /* not going to be completed... nuke it */
649                         lws_free_set_NULL(wsi->trunc_alloc);
650
651                 wsi->u.ws.ping_payload_len = 0;
652                 wsi->u.ws.ping_pending_flag = 0;
653         }
654
655         /* tell the user it's all over for this guy */
656
657         if (wsi->mode != LWSCM_RAW && wsi->protocol && wsi->protocol->callback &&
658             ((wsi->state_pre_close == LWSS_ESTABLISHED) ||
659             (wsi->state_pre_close == LWSS_RETURNED_CLOSE_ALREADY) ||
660             (wsi->state_pre_close == LWSS_AWAITING_CLOSE_ACK) ||
661             (wsi->state_pre_close == LWSS_WAITING_TO_SEND_CLOSE_NOTIFICATION) ||
662             (wsi->state_pre_close == LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE) ||
663             (wsi->mode == LWSCM_WS_CLIENT && wsi->state_pre_close == LWSS_HTTP) ||
664             (wsi->mode == LWSCM_WS_SERVING && wsi->state_pre_close == LWSS_HTTP))) {
665
666                 if (wsi->user_space) {
667                        lwsl_debug("%s: doing LWS_CALLBACK_HTTP_DROP_PROTOCOL for %p prot %s\n", __func__, wsi, wsi->protocol->name);
668                         wsi->protocol->callback(wsi,
669                                         LWS_CALLBACK_HTTP_DROP_PROTOCOL,
670                                                wsi->user_space, NULL, 0);
671                 }
672                 lwsl_debug("calling back CLOSED\n");
673                 wsi->protocol->callback(wsi, LWS_CALLBACK_CLOSED,
674                                         wsi->user_space, NULL, 0);
675         } else if (wsi->mode == LWSCM_HTTP_SERVING_ACCEPTED) {
676                 lwsl_debug("calling back CLOSED_HTTP\n");
677                 wsi->vhost->protocols->callback(wsi, LWS_CALLBACK_CLOSED_HTTP,
678                                                wsi->user_space, NULL, 0 );
679         } else if ((wsi->mode == LWSCM_WSCL_WAITING_SERVER_REPLY ||
680                    wsi->mode == LWSCM_WSCL_WAITING_CONNECT) &&
681                    !wsi->already_did_cce) {
682                         wsi->vhost->protocols[0].callback(wsi,
683                                         LWS_CALLBACK_CLIENT_CONNECTION_ERROR,
684                                         wsi->user_space, NULL, 0);
685         } else
686                 lwsl_debug("not calling back closed mode=%d state=%d\n",
687                            wsi->mode, wsi->state_pre_close);
688
689         /* deallocate any active extension contexts */
690
691         if (lws_ext_cb_active(wsi, LWS_EXT_CB_DESTROY, NULL, 0) < 0)
692                 lwsl_warn("extension destruction failed\n");
693         /*
694          * inform all extensions in case they tracked this guy out of band
695          * even though not active on him specifically
696          */
697         if (lws_ext_cb_all_exts(context, wsi,
698                        LWS_EXT_CB_DESTROY_ANY_WSI_CLOSING, NULL, 0) < 0)
699                 lwsl_warn("ext destroy wsi failed\n");
700
701 async_close:
702
703         wsi->socket_is_permanently_unusable = 1;
704
705 #ifdef LWS_USE_LIBUV
706         if (!wsi->parent_carries_io)
707                 if (LWS_LIBUV_ENABLED(context)) {
708                         if (wsi->listener) {
709                                 lwsl_debug("%s: stopping listner libuv poll\n", __func__);
710                                 uv_poll_stop(&wsi->w_read.uv_watcher);
711                         }
712                         lwsl_debug("%s: lws_libuv_closehandle: wsi %p\n", __func__, wsi);
713                         /* libuv has to do his own close handle processing asynchronously */
714                         lws_libuv_closehandle(wsi);
715
716                         return;
717                 }
718 #endif
719
720         lws_close_free_wsi_final(wsi);
721 }
722
723 void
724 lws_close_free_wsi_final(struct lws *wsi)
725 {
726         int n;
727
728         if (!lws_ssl_close(wsi) && lws_socket_is_valid(wsi->desc.sockfd)) {
729 #if LWS_POSIX
730                 //lwsl_err("*** closing sockfd %d\n", wsi->desc.sockfd);
731                 n = compatible_close(wsi->desc.sockfd);
732                 if (n)
733                         lwsl_debug("closing: close ret %d\n", LWS_ERRNO);
734
735 #else
736                 compatible_close(wsi->desc.sockfd);
737                 (void)n;
738 #endif
739                 wsi->desc.sockfd = LWS_SOCK_INVALID;
740         }
741
742         /* outermost destroy notification for wsi (user_space still intact) */
743         wsi->vhost->protocols[0].callback(wsi, LWS_CALLBACK_WSI_DESTROY,
744                                        wsi->user_space, NULL, 0);
745
746 #ifdef LWS_WITH_CGI
747         if (wsi->cgi) {
748                 for (n = 0; n < 6; n++) {
749                         if (wsi->cgi->pipe_fds[n / 2][n & 1] == 0)
750                                 lwsl_err("ZERO FD IN CGI CLOSE");
751
752                         if (wsi->cgi->pipe_fds[n / 2][n & 1] >= 0)
753                                 close(wsi->cgi->pipe_fds[n / 2][n & 1]);
754                 }
755
756                 lws_free(wsi->cgi);
757         }
758 #endif
759
760         lws_free_wsi(wsi);
761 }
762
763 LWS_VISIBLE LWS_EXTERN const char *
764 lws_get_urlarg_by_name(struct lws *wsi, const char *name, char *buf, int len)
765 {
766         int n = 0, sl = strlen(name);
767
768         while (lws_hdr_copy_fragment(wsi, buf, len,
769                           WSI_TOKEN_HTTP_URI_ARGS, n) >= 0) {
770
771                 if (!strncmp(buf, name, sl))
772                         return buf + sl;
773
774                 n++;
775         }
776
777         return NULL;
778 }
779
780 #if LWS_POSIX && !defined(LWS_WITH_ESP32)
781 LWS_VISIBLE int
782 interface_to_sa(struct lws_vhost *vh, const char *ifname, struct sockaddr_in *addr, size_t addrlen)
783 {
784         int ipv6 = 0;
785 #ifdef LWS_USE_IPV6
786         ipv6 = LWS_IPV6_ENABLED(vh);
787 #endif
788         (void)vh;
789
790         return lws_interface_to_sa(ipv6, ifname, addr, addrlen);
791 }
792 #endif
793
794 #ifndef LWS_PLAT_OPTEE
795 #if LWS_POSIX
796 static int
797 lws_get_addresses(struct lws_vhost *vh, void *ads, char *name,
798                   int name_len, char *rip, int rip_len)
799 {
800 #if LWS_POSIX
801         struct addrinfo ai, *res;
802         struct sockaddr_in addr4;
803
804         if (rip)
805                 rip[0] = '\0';
806         name[0] = '\0';
807         addr4.sin_family = AF_UNSPEC;
808
809 #ifdef LWS_USE_IPV6
810         if (LWS_IPV6_ENABLED(vh)) {
811                 if (!lws_plat_inet_ntop(AF_INET6, &((struct sockaddr_in6 *)ads)->sin6_addr, rip, rip_len)) {
812                         lwsl_err("inet_ntop: %s", strerror(LWS_ERRNO));
813                         return -1;
814                 }
815
816                 // Strip off the IPv4 to IPv6 header if one exists
817                 if (strncmp(rip, "::ffff:", 7) == 0)
818                         memmove(rip, rip + 7, strlen(rip) - 6);
819
820                 getnameinfo((struct sockaddr *)ads,
821                                 sizeof(struct sockaddr_in6), name,
822                                                         name_len, NULL, 0, 0);
823
824                 return 0;
825         } else
826 #endif
827         {
828                 struct addrinfo *result;
829
830                 memset(&ai, 0, sizeof ai);
831                 ai.ai_family = PF_UNSPEC;
832                 ai.ai_socktype = SOCK_STREAM;
833                 ai.ai_flags = AI_CANONNAME;
834 #if !defined(LWS_WITH_ESP32)
835                 if (getnameinfo((struct sockaddr *)ads,
836                                 sizeof(struct sockaddr_in),
837                                 name, name_len, NULL, 0, 0))
838                         return -1;
839 #endif
840                 if (!rip)
841                         return 0;
842
843                 if (getaddrinfo(name, NULL, &ai, &result))
844                         return -1;
845
846                 res = result;
847                 while (addr4.sin_family == AF_UNSPEC && res) {
848                         switch (res->ai_family) {
849                         case AF_INET:
850                                 addr4.sin_addr = ((struct sockaddr_in *)res->ai_addr)->sin_addr;
851                                 addr4.sin_family = AF_INET;
852                                 break;
853                         }
854
855                         res = res->ai_next;
856                 }
857                 freeaddrinfo(result);
858         }
859
860         if (addr4.sin_family == AF_UNSPEC)
861                 return -1;
862
863         if (lws_plat_inet_ntop(AF_INET, &addr4.sin_addr, rip, rip_len) == NULL)
864                 return -1;
865
866         return 0;
867 #else
868         (void)vh;
869         (void)ads;
870         (void)name;
871         (void)name_len;
872         (void)rip;
873         (void)rip_len;
874
875         return -1;
876 #endif
877 }
878 #endif
879
880
881 LWS_VISIBLE const char *
882 lws_get_peer_simple(struct lws *wsi, char *name, int namelen)
883 {
884 #if LWS_POSIX
885         socklen_t len, olen;
886 #ifdef LWS_USE_IPV6
887         struct sockaddr_in6 sin6;
888 #endif
889         struct sockaddr_in sin4;
890         int af = AF_INET;
891         void *p, *q;
892
893         if (wsi->parent_carries_io)
894                 wsi = wsi->parent;
895
896 #ifdef LWS_USE_IPV6
897         if (LWS_IPV6_ENABLED(wsi->vhost)) {
898                 len = sizeof(sin6);
899                 p = &sin6;
900                 af = AF_INET6;
901                 q = &sin6.sin6_addr;
902         } else
903 #endif
904         {
905                 len = sizeof(sin4);
906                 p = &sin4;
907                 q = &sin4.sin_addr;
908         }
909
910         olen = len;
911         if (getpeername(wsi->desc.sockfd, p, &len) < 0 || len > olen) {
912                 lwsl_warn("getpeername: %s\n", strerror(LWS_ERRNO));
913                 return NULL;
914         }
915
916         return lws_plat_inet_ntop(af, q, name, namelen);
917 #else
918 #if defined(LWS_WITH_ESP8266)
919         return lws_plat_get_peer_simple(wsi, name, namelen);
920 #else
921         return NULL;
922 #endif
923 #endif
924 }
925 #endif
926
927 LWS_VISIBLE void
928 lws_get_peer_addresses(struct lws *wsi, lws_sockfd_type fd, char *name,
929                        int name_len, char *rip, int rip_len)
930 {
931 #ifndef LWS_PLAT_OPTEE
932 #if LWS_POSIX
933         socklen_t len;
934 #ifdef LWS_USE_IPV6
935         struct sockaddr_in6 sin6;
936 #endif
937         struct sockaddr_in sin4;
938         struct lws_context *context = wsi->context;
939         int ret = -1;
940         void *p;
941
942         rip[0] = '\0';
943         name[0] = '\0';
944
945         lws_latency_pre(context, wsi);
946
947 #ifdef LWS_USE_IPV6
948         if (LWS_IPV6_ENABLED(wsi->vhost)) {
949                 len = sizeof(sin6);
950                 p = &sin6;
951         } else
952 #endif
953         {
954                 len = sizeof(sin4);
955                 p = &sin4;
956         }
957
958         if (getpeername(fd, p, &len) < 0) {
959                 lwsl_warn("getpeername: %s\n", strerror(LWS_ERRNO));
960                 goto bail;
961         }
962
963         ret = lws_get_addresses(wsi->vhost, p, name, name_len, rip, rip_len);
964
965 bail:
966         lws_latency(context, wsi, "lws_get_peer_addresses", ret, 1);
967 #endif
968 #endif
969         (void)wsi;
970         (void)fd;
971         (void)name;
972         (void)name_len;
973         (void)rip;
974         (void)rip_len;
975
976 }
977
978 LWS_EXTERN void *
979 lws_context_user(struct lws_context *context)
980 {
981         return context->user_space;
982 }
983
984 LWS_VISIBLE struct lws_vhost *
985 lws_vhost_get(struct lws *wsi)
986 {
987         return wsi->vhost;
988 }
989
990 LWS_VISIBLE struct lws_vhost *
991 lws_get_vhost(struct lws *wsi)
992 {
993         return wsi->vhost;
994 }
995
996 LWS_VISIBLE const struct lws_protocols *
997 lws_protocol_get(struct lws *wsi)
998 {
999         return wsi->protocol;
1000 }
1001
1002 LWS_VISIBLE LWS_EXTERN const struct lws_protocols *
1003 lws_vhost_name_to_protocol(struct lws_vhost *vh, const char *name)
1004 {
1005         int n;
1006
1007         for (n = 0; n < vh->count_protocols; n++)
1008                 if (!strcmp(name, vh->protocols[n].name))
1009                         return &vh->protocols[n];
1010
1011         return NULL;
1012 }
1013
1014 LWS_VISIBLE int
1015 lws_callback_all_protocol(struct lws_context *context,
1016                           const struct lws_protocols *protocol, int reason)
1017 {
1018         struct lws_context_per_thread *pt = &context->pt[0];
1019         unsigned int n, m = context->count_threads;
1020         struct lws *wsi;
1021
1022         while (m--) {
1023                 for (n = 0; n < pt->fds_count; n++) {
1024                         wsi = wsi_from_fd(context, pt->fds[n].fd);
1025                         if (!wsi)
1026                                 continue;
1027                         if (wsi->protocol == protocol)
1028                                 protocol->callback(wsi, reason, wsi->user_space,
1029                                                    NULL, 0);
1030                 }
1031                 pt++;
1032         }
1033
1034         return 0;
1035 }
1036
1037 LWS_VISIBLE int
1038 lws_callback_all_protocol_vhost(struct lws_vhost *vh,
1039                           const struct lws_protocols *protocol, int reason)
1040 {
1041         struct lws_context *context = vh->context;
1042         struct lws_context_per_thread *pt = &context->pt[0];
1043         unsigned int n, m = context->count_threads;
1044         struct lws *wsi;
1045
1046         while (m--) {
1047                 for (n = 0; n < pt->fds_count; n++) {
1048                         wsi = wsi_from_fd(context, pt->fds[n].fd);
1049                         if (!wsi)
1050                                 continue;
1051                         if (wsi->vhost == vh && wsi->protocol == protocol)
1052                                 protocol->callback(wsi, reason, wsi->user_space,
1053                                                    NULL, 0);
1054                 }
1055                 pt++;
1056         }
1057
1058         return 0;
1059 }
1060
1061 LWS_VISIBLE LWS_EXTERN int
1062 lws_callback_vhost_protocols(struct lws *wsi, int reason, void *in, int len)
1063 {
1064         int n;
1065
1066         for (n = 0; n < wsi->vhost->count_protocols; n++)
1067                 if (wsi->vhost->protocols[n].callback(wsi, reason, NULL, in, len))
1068                         return 1;
1069
1070         return 0;
1071 }
1072
1073 LWS_VISIBLE LWS_EXTERN void
1074 lws_set_fops(struct lws_context *context, const struct lws_plat_file_ops *fops)
1075 {
1076         context->fops = fops;
1077 }
1078
1079 LWS_VISIBLE LWS_EXTERN lws_filepos_t
1080 lws_vfs_tell(lws_fop_fd_t fop_fd)
1081 {
1082         return fop_fd->pos;
1083 }
1084
1085 LWS_VISIBLE LWS_EXTERN lws_filepos_t
1086 lws_vfs_get_length(lws_fop_fd_t fop_fd)
1087 {
1088         return fop_fd->len;
1089 }
1090
1091 LWS_VISIBLE LWS_EXTERN uint32_t
1092 lws_vfs_get_mod_time(lws_fop_fd_t fop_fd)
1093 {
1094         return fop_fd->mod_time;
1095 }
1096
1097 LWS_VISIBLE lws_fileofs_t
1098 lws_vfs_file_seek_set(lws_fop_fd_t fop_fd, lws_fileofs_t offset)
1099 {
1100         lws_fileofs_t ofs;
1101         lwsl_debug("%s: seeking to %ld, len %ld\n", __func__, (long)offset, (long)fop_fd->len);
1102         ofs = fop_fd->fops->LWS_FOP_SEEK_CUR(fop_fd, offset - fop_fd->pos);
1103         lwsl_debug("%s: result %ld, fop_fd pos %ld\n", __func__, (long)ofs, (long)fop_fd->pos);
1104         return ofs;
1105 }
1106
1107
1108 LWS_VISIBLE lws_fileofs_t
1109 lws_vfs_file_seek_end(lws_fop_fd_t fop_fd, lws_fileofs_t offset)
1110 {
1111         return fop_fd->fops->LWS_FOP_SEEK_CUR(fop_fd, fop_fd->len + fop_fd->pos + offset);
1112 }
1113
1114
1115 const struct lws_plat_file_ops *
1116 lws_vfs_select_fops(const struct lws_plat_file_ops *fops, const char *vfs_path,
1117                     const char **vpath)
1118 {
1119         const struct lws_plat_file_ops *pf;
1120         const char *p = vfs_path;
1121         int n;
1122
1123         *vpath = NULL;
1124
1125         /* no non-platform fops, just use that */
1126
1127         if (!fops->next)
1128                 return fops;
1129
1130         /*
1131          *  scan the vfs path looking for indications we are to be
1132          * handled by a specific fops
1133          */
1134
1135         while (p && *p) {
1136                 if (*p != '/') {
1137                         p++;
1138                         continue;
1139                 }
1140                 /* the first one is always platform fops, so skip */
1141                 pf = fops->next;
1142                 while (pf) {
1143                         n = 0;
1144                         while (n < ARRAY_SIZE(pf->fi) && pf->fi[n].sig) {
1145                                 if (p >= vfs_path + pf->fi[n].len)
1146                                         if (!strncmp(p - (pf->fi[n].len - 1),
1147                                                     pf->fi[n].sig,
1148                                                     pf->fi[n].len - 1)) {
1149                                                 *vpath = p + 1;
1150                                                 return pf;
1151                                         }
1152
1153                                 n++;
1154                         }
1155                         pf = pf->next;
1156                 }
1157                 p++;
1158         }
1159
1160         return fops;
1161 }
1162
1163 LWS_VISIBLE LWS_EXTERN lws_fop_fd_t LWS_WARN_UNUSED_RESULT
1164 lws_vfs_file_open(const struct lws_plat_file_ops *fops, const char *vfs_path,
1165                   lws_fop_flags_t *flags)
1166 {
1167         const char *vpath = "";
1168         const struct lws_plat_file_ops *selected = lws_vfs_select_fops(
1169                         fops, vfs_path, &vpath);
1170
1171         return selected->LWS_FOP_OPEN(fops, vfs_path, vpath, flags);
1172 }
1173
1174
1175 /**
1176  * lws_now_secs() - seconds since 1970-1-1
1177  *
1178  */
1179 LWS_VISIBLE LWS_EXTERN unsigned long
1180 lws_now_secs(void)
1181 {
1182         struct timeval tv;
1183
1184         gettimeofday(&tv, NULL);
1185
1186         return tv.tv_sec;
1187 }
1188
1189
1190 #if LWS_POSIX
1191
1192 LWS_VISIBLE int
1193 lws_get_socket_fd(struct lws *wsi)
1194 {
1195         return wsi->desc.sockfd;
1196 }
1197
1198 #endif
1199
1200 #ifdef LWS_LATENCY
1201 void
1202 lws_latency(struct lws_context *context, struct lws *wsi, const char *action,
1203             int ret, int completed)
1204 {
1205         unsigned long long u;
1206         char buf[256];
1207
1208         u = time_in_microseconds();
1209
1210         if (!action) {
1211                 wsi->latency_start = u;
1212                 if (!wsi->action_start)
1213                         wsi->action_start = u;
1214                 return;
1215         }
1216         if (completed) {
1217                 if (wsi->action_start == wsi->latency_start)
1218                         sprintf(buf,
1219                           "Completion first try lat %lluus: %p: ret %d: %s\n",
1220                                         u - wsi->latency_start,
1221                                                       (void *)wsi, ret, action);
1222                 else
1223                         sprintf(buf,
1224                           "Completion %lluus: lat %lluus: %p: ret %d: %s\n",
1225                                 u - wsi->action_start,
1226                                         u - wsi->latency_start,
1227                                                       (void *)wsi, ret, action);
1228                 wsi->action_start = 0;
1229         } else
1230                 sprintf(buf, "lat %lluus: %p: ret %d: %s\n",
1231                               u - wsi->latency_start, (void *)wsi, ret, action);
1232
1233         if (u - wsi->latency_start > context->worst_latency) {
1234                 context->worst_latency = u - wsi->latency_start;
1235                 strcpy(context->worst_latency_info, buf);
1236         }
1237         lwsl_latency("%s", buf);
1238 }
1239 #endif
1240
1241 LWS_VISIBLE int
1242 lws_rx_flow_control(struct lws *wsi, int enable)
1243 {
1244         if (enable == (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW))
1245                 return 0;
1246
1247         lwsl_info("%s: (0x%p, %d)\n", __func__, wsi, enable);
1248         wsi->rxflow_change_to = LWS_RXFLOW_PENDING_CHANGE | !!enable;
1249
1250         return 0;
1251 }
1252
1253 LWS_VISIBLE void
1254 lws_rx_flow_allow_all_protocol(const struct lws_context *context,
1255                                const struct lws_protocols *protocol)
1256 {
1257         const struct lws_context_per_thread *pt = &context->pt[0];
1258         struct lws *wsi;
1259         unsigned int n, m = context->count_threads;
1260
1261         while (m--) {
1262                 for (n = 0; n < pt->fds_count; n++) {
1263                         wsi = wsi_from_fd(context, pt->fds[n].fd);
1264                         if (!wsi)
1265                                 continue;
1266                         if (wsi->protocol == protocol)
1267                                 lws_rx_flow_control(wsi, LWS_RXFLOW_ALLOW);
1268                 }
1269                 pt++;
1270         }
1271 }
1272
1273 LWS_VISIBLE extern const char *
1274 lws_canonical_hostname(struct lws_context *context)
1275 {
1276         return (const char *)context->canonical_hostname;
1277 }
1278
1279 int user_callback_handle_rxflow(lws_callback_function callback_function,
1280                                 struct lws *wsi,
1281                                 enum lws_callback_reasons reason, void *user,
1282                                 void *in, size_t len)
1283 {
1284         int n;
1285
1286         n = callback_function(wsi, reason, user, in, len);
1287         if (!n)
1288                 n = _lws_rx_flow_control(wsi);
1289
1290         return n;
1291 }
1292
1293 #if defined(LWS_WITH_ESP8266)
1294 #undef strchr
1295 #define strchr ets_strchr
1296 #endif
1297
1298 LWS_VISIBLE int
1299 lws_set_proxy(struct lws_vhost *vhost, const char *proxy)
1300 {
1301 #if !defined(LWS_WITH_ESP8266)
1302         char *p;
1303         char authstring[96];
1304
1305         if (!proxy)
1306                 return -1;
1307
1308         /* we have to deal with a possible redundant leading http:// */
1309         if (!strncmp(proxy, "http://", 7))
1310                 proxy += 7;
1311
1312         p = strchr(proxy, '@');
1313         if (p) { /* auth is around */
1314
1315                 if ((unsigned int)(p - proxy) > sizeof(authstring) - 1)
1316                         goto auth_too_long;
1317
1318                 strncpy(authstring, proxy, p - proxy);
1319                 // null termination not needed on input
1320                 if (lws_b64_encode_string(authstring, (p - proxy),
1321                                 vhost->proxy_basic_auth_token,
1322                     sizeof vhost->proxy_basic_auth_token) < 0)
1323                         goto auth_too_long;
1324
1325                 lwsl_info(" Proxy auth in use\n");
1326
1327                 proxy = p + 1;
1328         } else
1329                 vhost->proxy_basic_auth_token[0] = '\0';
1330
1331         strncpy(vhost->http_proxy_address, proxy,
1332                                 sizeof(vhost->http_proxy_address) - 1);
1333         vhost->http_proxy_address[
1334                                 sizeof(vhost->http_proxy_address) - 1] = '\0';
1335
1336         p = strchr(vhost->http_proxy_address, ':');
1337         if (!p && !vhost->http_proxy_port) {
1338                 lwsl_err("http_proxy needs to be ads:port\n");
1339
1340                 return -1;
1341         } else {
1342                 if (p) {
1343                         *p = '\0';
1344                         vhost->http_proxy_port = atoi(p + 1);
1345                 }
1346         }
1347
1348         lwsl_info(" Proxy %s:%u\n", vhost->http_proxy_address,
1349                         vhost->http_proxy_port);
1350
1351         return 0;
1352
1353 auth_too_long:
1354         lwsl_err("proxy auth too long\n");
1355 #endif
1356         return -1;
1357 }
1358
1359 #if defined(LWS_WITH_SOCKS5)
1360 LWS_VISIBLE int
1361 lws_set_socks(struct lws_vhost *vhost, const char *socks)
1362 {
1363 #if !defined(LWS_WITH_ESP8266)
1364         char *p_at, *p_colon;
1365         char user[96];
1366         char password[96];
1367
1368         if (!socks)
1369                 return -1;
1370
1371         vhost->socks_user[0] = '\0';
1372         vhost->socks_password[0] = '\0';
1373
1374         p_at = strchr(socks, '@');
1375         if (p_at) { /* auth is around */
1376                 if ((unsigned int)(p_at - socks) > (sizeof(user)
1377                         + sizeof(password) - 2)) {
1378                         lwsl_err("Socks auth too long\n");
1379                         goto bail;
1380                 }
1381
1382                 p_colon = strchr(socks, ':');
1383                 if (p_colon) {
1384                         if ((unsigned int)(p_colon - socks) > (sizeof(user)
1385                                 - 1) ) {
1386                                 lwsl_err("Socks user too long\n");
1387                                 goto bail;
1388                         }
1389                         if ((unsigned int)(p_at - p_colon) > (sizeof(password)
1390                                 - 1) ) {
1391                                 lwsl_err("Socks password too long\n");
1392                                 goto bail;
1393                         }
1394                 }
1395                 strncpy(vhost->socks_user, socks, p_colon - socks);
1396                 strncpy(vhost->socks_password, p_colon + 1,
1397                         p_at - (p_colon + 1));
1398
1399                 lwsl_info(" Socks auth, user: %s, password: %s\n",
1400                         vhost->socks_user, vhost->socks_password );
1401
1402                 socks = p_at + 1;
1403         }
1404
1405         strncpy(vhost->socks_proxy_address, socks,
1406                                 sizeof(vhost->socks_proxy_address) - 1);
1407         vhost->socks_proxy_address[sizeof(vhost->socks_proxy_address) - 1]
1408                 = '\0';
1409
1410         p_colon = strchr(vhost->socks_proxy_address, ':');
1411         if (!p_colon && !vhost->socks_proxy_port) {
1412                 lwsl_err("socks_proxy needs to be address:port\n");
1413                 return -1;
1414         } else {
1415                 if (p_colon) {
1416                         *p_colon = '\0';
1417                         vhost->socks_proxy_port = atoi(p_colon + 1);
1418                 }
1419         }
1420
1421         lwsl_info(" Socks %s:%u\n", vhost->socks_proxy_address,
1422                         vhost->socks_proxy_port);
1423
1424         return 0;
1425
1426 bail:
1427 #endif
1428         return -1;
1429 }
1430 #endif
1431
1432 LWS_VISIBLE const struct lws_protocols *
1433 lws_get_protocol(struct lws *wsi)
1434 {
1435         return wsi->protocol;
1436 }
1437
1438 LWS_VISIBLE int
1439 lws_is_final_fragment(struct lws *wsi)
1440 {
1441        lwsl_info("%s: final %d, rx pk length %ld, draining %ld\n", __func__,
1442                         wsi->u.ws.final, (long)wsi->u.ws.rx_packet_length,
1443                         (long)wsi->u.ws.rx_draining_ext);
1444         return wsi->u.ws.final && !wsi->u.ws.rx_packet_length && !wsi->u.ws.rx_draining_ext;
1445 }
1446
1447 LWS_VISIBLE int
1448 lws_is_first_fragment(struct lws *wsi)
1449 {
1450         return wsi->u.ws.first_fragment;
1451 }
1452
1453 LWS_VISIBLE unsigned char
1454 lws_get_reserved_bits(struct lws *wsi)
1455 {
1456         return wsi->u.ws.rsv;
1457 }
1458
1459 int
1460 lws_ensure_user_space(struct lws *wsi)
1461 {
1462         lwsl_info("%s: %p protocol %p\n", __func__, wsi, wsi->protocol);
1463         if (!wsi->protocol)
1464                 return 1;
1465
1466         /* allocate the per-connection user memory (if any) */
1467
1468         if (wsi->protocol->per_session_data_size && !wsi->user_space) {
1469                 wsi->user_space = lws_zalloc(wsi->protocol->per_session_data_size);
1470                 if (wsi->user_space  == NULL) {
1471                         lwsl_err("Out of memory for conn user space\n");
1472                         return 1;
1473                 }
1474         } else
1475                 lwsl_info("%s: %p protocol pss %lu, user_space=%p\n",
1476                           __func__, wsi, (long)wsi->protocol->per_session_data_size,
1477                           wsi->user_space);
1478         return 0;
1479 }
1480
1481 LWS_VISIBLE int
1482 lwsl_timestamp(int level, char *p, int len)
1483 {
1484 #ifndef LWS_PLAT_OPTEE
1485         time_t o_now = time(NULL);
1486         unsigned long long now;
1487         struct tm *ptm = NULL;
1488 #ifndef WIN32
1489         struct tm tm;
1490 #endif
1491         int n;
1492
1493 #ifndef _WIN32_WCE
1494 #ifdef WIN32
1495         ptm = localtime(&o_now);
1496 #else
1497         if (localtime_r(&o_now, &tm))
1498                 ptm = &tm;
1499 #endif
1500 #endif
1501         p[0] = '\0';
1502         for (n = 0; n < LLL_COUNT; n++) {
1503                 if (level != (1 << n))
1504                         continue;
1505                 now = time_in_microseconds() / 100;
1506                 if (ptm)
1507                         n = lws_snprintf(p, len,
1508                                 "[%04d/%02d/%02d %02d:%02d:%02d:%04d] %s: ",
1509                                 ptm->tm_year + 1900,
1510                                 ptm->tm_mon + 1,
1511                                 ptm->tm_mday,
1512                                 ptm->tm_hour,
1513                                 ptm->tm_min,
1514                                 ptm->tm_sec,
1515                                 (int)(now % 10000), log_level_names[n]);
1516                 else
1517                         n = lws_snprintf(p, len, "[%llu:%04d] %s: ",
1518                                         (unsigned long long) now / 10000,
1519                                         (int)(now % 10000), log_level_names[n]);
1520                 return n;
1521         }
1522 #endif
1523         return 0;
1524 }
1525
1526 #ifndef LWS_PLAT_OPTEE
1527 LWS_VISIBLE void lwsl_emit_stderr(int level, const char *line)
1528 {
1529 #if !defined(LWS_WITH_ESP8266)
1530         char buf[50];
1531
1532         lwsl_timestamp(level, buf, sizeof(buf));
1533         fprintf(stderr, "%s%s", buf, line);
1534 #endif
1535 }
1536 #endif
1537
1538 LWS_VISIBLE void _lws_logv(int filter, const char *format, va_list vl)
1539 {
1540 #if defined(LWS_WITH_ESP8266)
1541         char buf[128];
1542 #else
1543         char buf[256];
1544 #endif
1545         int n;
1546
1547         if (!(log_level & filter))
1548                 return;
1549
1550         n = vsnprintf(buf, sizeof(buf) - 1, format, vl);
1551         (void)n;
1552 #if defined(LWS_WITH_ESP8266)
1553         buf[sizeof(buf) - 1] = '\0';
1554 #else
1555         /* vnsprintf returns what it would have written, even if truncated */
1556         if (n > sizeof(buf) - 1)
1557                 n = sizeof(buf) - 1;
1558         if (n > 0)
1559                 buf[n] = '\0';
1560 #endif
1561
1562         lwsl_emit(filter, buf);
1563 }
1564
1565 LWS_VISIBLE void _lws_log(int filter, const char *format, ...)
1566 {
1567         va_list ap;
1568
1569         va_start(ap, format);
1570         _lws_logv(filter, format, ap);
1571         va_end(ap);
1572 }
1573
1574 LWS_VISIBLE void lws_set_log_level(int level,
1575                                    void (*func)(int level, const char *line))
1576 {
1577         log_level = level;
1578         if (func)
1579                 lwsl_emit = func;
1580 }
1581
1582 LWS_VISIBLE int lwsl_visible(int level)
1583 {
1584         return log_level & level;
1585 }
1586
1587 LWS_VISIBLE int
1588 lws_is_ssl(struct lws *wsi)
1589 {
1590 #ifdef LWS_OPENSSL_SUPPORT
1591         return wsi->use_ssl;
1592 #else
1593         (void)wsi;
1594         return 0;
1595 #endif
1596 }
1597
1598 #ifdef LWS_OPENSSL_SUPPORT
1599 LWS_VISIBLE SSL*
1600 lws_get_ssl(struct lws *wsi)
1601 {
1602         return wsi->ssl;
1603 }
1604 #endif
1605
1606 LWS_VISIBLE int
1607 lws_partial_buffered(struct lws *wsi)
1608 {
1609         return !!wsi->trunc_len;
1610 }
1611
1612 void lws_set_protocol_write_pending(struct lws *wsi,
1613                                     enum lws_pending_protocol_send pend)
1614 {
1615         lwsl_info("setting pps %d\n", pend);
1616
1617         if (wsi->pps)
1618                 lwsl_err("pps overwrite\n");
1619         wsi->pps = pend;
1620         lws_rx_flow_control(wsi, 0);
1621         lws_callback_on_writable(wsi);
1622 }
1623
1624 LWS_VISIBLE size_t
1625 lws_get_peer_write_allowance(struct lws *wsi)
1626 {
1627 #ifdef LWS_USE_HTTP2
1628         /* only if we are using HTTP2 on this connection */
1629         if (wsi->mode != LWSCM_HTTP2_SERVING)
1630                 return -1;
1631         /* user is only interested in how much he can send, or that he can't  */
1632         if (wsi->u.http2.tx_credit <= 0)
1633                 return 0;
1634
1635         return wsi->u.http2.tx_credit;
1636 #else
1637         (void)wsi;
1638         return -1;
1639 #endif
1640 }
1641
1642 LWS_VISIBLE void
1643 lws_union_transition(struct lws *wsi, enum connection_mode mode)
1644 {
1645         lwsl_debug("%s: %p: mode %d\n", __func__, wsi, mode);
1646         memset(&wsi->u, 0, sizeof(wsi->u));
1647         wsi->mode = mode;
1648 }
1649
1650 LWS_VISIBLE struct lws_plat_file_ops *
1651 lws_get_fops(struct lws_context *context)
1652 {
1653         return (struct lws_plat_file_ops *)context->fops;
1654 }
1655
1656 LWS_VISIBLE LWS_EXTERN struct lws_context *
1657 lws_get_context(const struct lws *wsi)
1658 {
1659         return wsi->context;
1660 }
1661
1662 LWS_VISIBLE LWS_EXTERN int
1663 lws_get_count_threads(struct lws_context *context)
1664 {
1665         return context->count_threads;
1666 }
1667
1668 LWS_VISIBLE LWS_EXTERN void *
1669 lws_wsi_user(struct lws *wsi)
1670 {
1671         return wsi->user_space;
1672 }
1673
1674 LWS_VISIBLE LWS_EXTERN void
1675 lws_set_wsi_user(struct lws *wsi, void *data)
1676 {
1677         if (wsi->user_space_externally_allocated)
1678                 wsi->user_space = data;
1679         else
1680                 lwsl_err("%s: Cannot set internally-allocated user_space\n",
1681                          __func__);
1682 }
1683
1684 LWS_VISIBLE LWS_EXTERN struct lws *
1685 lws_get_parent(const struct lws *wsi)
1686 {
1687         return wsi->parent;
1688 }
1689
1690 LWS_VISIBLE LWS_EXTERN struct lws *
1691 lws_get_child(const struct lws *wsi)
1692 {
1693         return wsi->child_list;
1694 }
1695
1696 LWS_VISIBLE LWS_EXTERN void
1697 lws_set_parent_carries_io(struct lws *wsi)
1698 {
1699         wsi->parent_carries_io = 1;
1700 }
1701
1702 LWS_VISIBLE LWS_EXTERN void *
1703 lws_get_opaque_parent_data(const struct lws *wsi)
1704 {
1705         return wsi->opaque_parent_data;
1706 }
1707
1708 LWS_VISIBLE LWS_EXTERN void
1709 lws_set_opaque_parent_data(struct lws *wsi, void *data)
1710 {
1711         wsi->opaque_parent_data = data;
1712 }
1713
1714 LWS_VISIBLE LWS_EXTERN int
1715 lws_get_child_pending_on_writable(const struct lws *wsi)
1716 {
1717         return wsi->parent_pending_cb_on_writable;
1718 }
1719
1720 LWS_VISIBLE LWS_EXTERN void
1721 lws_clear_child_pending_on_writable(struct lws *wsi)
1722 {
1723         wsi->parent_pending_cb_on_writable = 0;
1724 }
1725
1726 LWS_VISIBLE LWS_EXTERN int
1727 lws_get_close_length(struct lws *wsi)
1728 {
1729         return wsi->u.ws.close_in_ping_buffer_len;
1730 }
1731
1732 LWS_VISIBLE LWS_EXTERN unsigned char *
1733 lws_get_close_payload(struct lws *wsi)
1734 {
1735         return &wsi->u.ws.ping_payload_buf[LWS_PRE];
1736 }
1737
1738 LWS_VISIBLE LWS_EXTERN void
1739 lws_close_reason(struct lws *wsi, enum lws_close_status status,
1740                  unsigned char *buf, size_t len)
1741 {
1742         unsigned char *p, *start;
1743         int budget = sizeof(wsi->u.ws.ping_payload_buf) - LWS_PRE;
1744
1745         assert(wsi->mode == LWSCM_WS_SERVING || wsi->mode == LWSCM_WS_CLIENT);
1746
1747         start = p = &wsi->u.ws.ping_payload_buf[LWS_PRE];
1748
1749         *p++ = (((int)status) >> 8) & 0xff;
1750         *p++ = ((int)status) & 0xff;
1751
1752         if (buf)
1753                 while (len-- && p < start + budget)
1754                         *p++ = *buf++;
1755
1756         wsi->u.ws.close_in_ping_buffer_len = p - start;
1757 }
1758
1759 LWS_EXTERN int
1760 _lws_rx_flow_control(struct lws *wsi)
1761 {
1762         struct lws *wsic = wsi->child_list;
1763
1764         /* if he has children, do those if they were changed */
1765         while (wsic) {
1766                 if (wsic->rxflow_change_to & LWS_RXFLOW_PENDING_CHANGE)
1767                         _lws_rx_flow_control(wsic);
1768
1769                 wsic = wsic->sibling_list;
1770         }
1771
1772         /* there is no pending change */
1773         if (!(wsi->rxflow_change_to & LWS_RXFLOW_PENDING_CHANGE)) {
1774 //              lwsl_debug("%s: no pending change\n", __func__);
1775                 return 0;
1776         }
1777
1778         /* stuff is still buffered, not ready to really accept new input */
1779         if (wsi->rxflow_buffer) {
1780                 /* get ourselves called back to deal with stashed buffer */
1781                 lws_callback_on_writable(wsi);
1782                 return 0;
1783         }
1784
1785         /* pending is cleared, we can change rxflow state */
1786
1787         wsi->rxflow_change_to &= ~LWS_RXFLOW_PENDING_CHANGE;
1788
1789         lwsl_info("rxflow: wsi %p change_to %d\n", wsi,
1790                               wsi->rxflow_change_to & LWS_RXFLOW_ALLOW);
1791
1792         /* adjust the pollfd for this wsi */
1793
1794         if (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW) {
1795                 if (lws_change_pollfd(wsi, 0, LWS_POLLIN)) {
1796                         lwsl_info("%s: fail\n", __func__);
1797                         return -1;
1798                 }
1799         } else
1800                 if (lws_change_pollfd(wsi, LWS_POLLIN, 0))
1801                         return -1;
1802
1803         return 0;
1804 }
1805
1806 LWS_EXTERN int
1807 lws_check_utf8(unsigned char *state, unsigned char *buf, size_t len)
1808 {
1809         static const unsigned char e0f4[] = {
1810                 0xa0 | ((2 - 1) << 2) | 1, /* e0 */
1811                 0x80 | ((4 - 1) << 2) | 1, /* e1 */
1812                 0x80 | ((4 - 1) << 2) | 1, /* e2 */
1813                 0x80 | ((4 - 1) << 2) | 1, /* e3 */
1814                 0x80 | ((4 - 1) << 2) | 1, /* e4 */
1815                 0x80 | ((4 - 1) << 2) | 1, /* e5 */
1816                 0x80 | ((4 - 1) << 2) | 1, /* e6 */
1817                 0x80 | ((4 - 1) << 2) | 1, /* e7 */
1818                 0x80 | ((4 - 1) << 2) | 1, /* e8 */
1819                 0x80 | ((4 - 1) << 2) | 1, /* e9 */
1820                 0x80 | ((4 - 1) << 2) | 1, /* ea */
1821                 0x80 | ((4 - 1) << 2) | 1, /* eb */
1822                 0x80 | ((4 - 1) << 2) | 1, /* ec */
1823                 0x80 | ((2 - 1) << 2) | 1, /* ed */
1824                 0x80 | ((4 - 1) << 2) | 1, /* ee */
1825                 0x80 | ((4 - 1) << 2) | 1, /* ef */
1826                 0x90 | ((3 - 1) << 2) | 2, /* f0 */
1827                 0x80 | ((4 - 1) << 2) | 2, /* f1 */
1828                 0x80 | ((4 - 1) << 2) | 2, /* f2 */
1829                 0x80 | ((4 - 1) << 2) | 2, /* f3 */
1830                 0x80 | ((1 - 1) << 2) | 2, /* f4 */
1831
1832                 0,                         /* s0 */
1833                 0x80 | ((4 - 1) << 2) | 0, /* s2 */
1834                 0x80 | ((4 - 1) << 2) | 1, /* s3 */
1835         };
1836         unsigned char s = *state;
1837
1838         while (len--) {
1839                 unsigned char c = *buf++;
1840
1841                 if (!s) {
1842                         if (c >= 0x80) {
1843                                 if (c < 0xc2 || c > 0xf4)
1844                                         return 1;
1845                                 if (c < 0xe0)
1846                                         s = 0x80 | ((4 - 1) << 2);
1847                                 else
1848                                         s = e0f4[c - 0xe0];
1849                         }
1850                 } else {
1851                         if (c < (s & 0xf0) ||
1852                             c >= (s & 0xf0) + 0x10 + ((s << 2) & 0x30))
1853                                 return 1;
1854                         s = e0f4[21 + (s & 3)];
1855                 }
1856         }
1857
1858         *state = s;
1859
1860         return 0;
1861 }
1862
1863 LWS_VISIBLE LWS_EXTERN int
1864 lws_parse_uri(char *p, const char **prot, const char **ads, int *port,
1865               const char **path)
1866 {
1867         const char *end;
1868         static const char *slash = "/";
1869
1870         /* cut up the location into address, port and path */
1871         *prot = p;
1872         while (*p && (*p != ':' || p[1] != '/' || p[2] != '/'))
1873                 p++;
1874         if (!*p) {
1875                 end = p;
1876                 p = (char *)*prot;
1877                 *prot = end;
1878         } else {
1879                 *p = '\0';
1880                 p += 3;
1881         }
1882         *ads = p;
1883         if (!strcmp(*prot, "http") || !strcmp(*prot, "ws"))
1884                 *port = 80;
1885         else if (!strcmp(*prot, "https") || !strcmp(*prot, "wss"))
1886                 *port = 443;
1887
1888        if (*p == '[')
1889        {
1890                ++(*ads);
1891                while (*p && *p != ']')
1892                        p++;
1893                if (*p)
1894                        *p++ = '\0';
1895        }
1896        else
1897        {
1898                while (*p && *p != ':' && *p != '/')
1899                        p++;
1900        }
1901         if (*p == ':') {
1902                 *p++ = '\0';
1903                 *port = atoi(p);
1904                 while (*p && *p != '/')
1905                         p++;
1906         }
1907         *path = slash;
1908         if (*p) {
1909                 *p++ = '\0';
1910                 if (*p)
1911                         *path = p;
1912         }
1913
1914         return 0;
1915 }
1916
1917 #ifdef LWS_NO_EXTENSIONS
1918
1919 /* we need to provide dummy callbacks for internal exts
1920  * so user code runs when faced with a lib compiled with
1921  * extensions disabled.
1922  */
1923
1924 int
1925 lws_extension_callback_pm_deflate(struct lws_context *context,
1926                                   const struct lws_extension *ext,
1927                                   struct lws *wsi,
1928                                   enum lws_extension_callback_reasons reason,
1929                                   void *user, void *in, size_t len)
1930 {
1931         (void)context;
1932         (void)ext;
1933         (void)wsi;
1934         (void)reason;
1935         (void)user;
1936         (void)in;
1937         (void)len;
1938
1939         return 0;
1940 }
1941 #endif
1942
1943 LWS_EXTERN int
1944 lws_socket_bind(struct lws_vhost *vhost, lws_sockfd_type sockfd, int port,
1945                 const char *iface)
1946 {
1947 #if LWS_POSIX
1948 #ifdef LWS_USE_UNIX_SOCK
1949         struct sockaddr_un serv_unix;
1950 #endif
1951 #ifdef LWS_USE_IPV6
1952         struct sockaddr_in6 serv_addr6;
1953 #endif
1954         struct sockaddr_in serv_addr4;
1955 #ifndef LWS_PLAT_OPTEE
1956         socklen_t len = sizeof(struct sockaddr_storage);
1957 #endif
1958         int n;
1959         struct sockaddr_storage sin;
1960         struct sockaddr *v;
1961
1962 #ifdef LWS_USE_UNIX_SOCK
1963         if (LWS_UNIX_SOCK_ENABLED(vhost)) {
1964                 v = (struct sockaddr *)&serv_unix;
1965                 n = sizeof(struct sockaddr_un);
1966                 bzero((char *) &serv_unix, sizeof(serv_unix));
1967                 serv_unix.sun_family = AF_UNIX;
1968                 if (sizeof(serv_unix.sun_path) <= strlen(iface)) {
1969                         lwsl_err("\"%s\" too long for UNIX domain socket\n",
1970                                  iface);
1971                         return -1;
1972                 }
1973                 strcpy(serv_unix.sun_path, iface);
1974                 if (serv_unix.sun_path[0] == '@')
1975                         serv_unix.sun_path[0] = '\0';
1976
1977         } else
1978 #endif
1979 #if defined(LWS_USE_IPV6) && !defined(LWS_WITH_ESP32)
1980         if (LWS_IPV6_ENABLED(vhost)) {
1981                 v = (struct sockaddr *)&serv_addr6;
1982                 n = sizeof(struct sockaddr_in6);
1983                 bzero((char *) &serv_addr6, sizeof(serv_addr6));
1984                 if (iface) {
1985                         if (interface_to_sa(vhost, iface,
1986                                     (struct sockaddr_in *)v, n) < 0) {
1987                                 lwsl_err("Unable to find interface %s\n", iface);
1988                                 return -1;
1989                         }
1990                         serv_addr6.sin6_scope_id = lws_get_addr_scope(iface);
1991                 }
1992
1993                 serv_addr6.sin6_family = AF_INET6;
1994                 serv_addr6.sin6_port = htons(port);
1995         } else
1996 #endif
1997         {
1998                 v = (struct sockaddr *)&serv_addr4;
1999                 n = sizeof(serv_addr4);
2000                 bzero((char *) &serv_addr4, sizeof(serv_addr4));
2001                 serv_addr4.sin_addr.s_addr = INADDR_ANY;
2002                 serv_addr4.sin_family = AF_INET;
2003 #if !defined(LWS_WITH_ESP32)
2004
2005                 if (iface &&
2006                     interface_to_sa(vhost, iface,
2007                                     (struct sockaddr_in *)v, n) < 0) {
2008                         lwsl_err("Unable to find interface %s\n", iface);
2009                         return -1;
2010                 }
2011 #endif
2012                 serv_addr4.sin_port = htons(port);
2013         } /* ipv4 */
2014
2015         n = bind(sockfd, v, n);
2016 #ifdef LWS_USE_UNIX_SOCK
2017         if (n < 0 && LWS_UNIX_SOCK_ENABLED(vhost)) {
2018                 lwsl_err("ERROR on binding fd %d to \"%s\" (%d %d)\n",
2019                                 sockfd, iface, n, LWS_ERRNO);
2020                 return -1;
2021         } else
2022 #endif
2023         if (n < 0) {
2024                 lwsl_err("ERROR on binding fd %d to port %d (%d %d)\n",
2025                                 sockfd, port, n, LWS_ERRNO);
2026                 return -1;
2027         }
2028
2029 #ifndef LWS_PLAT_OPTEE
2030         if (getsockname(sockfd, (struct sockaddr *)&sin, &len) == -1)
2031                 lwsl_warn("getsockname: %s\n", strerror(LWS_ERRNO));
2032         else
2033 #endif
2034 #if defined(LWS_USE_IPV6)
2035                 port = (sin.ss_family == AF_INET6) ?
2036                                   ntohs(((struct sockaddr_in6 *) &sin)->sin6_port) :
2037                                   ntohs(((struct sockaddr_in *) &sin)->sin_port);
2038 #else
2039                 port = ntohs(((struct sockaddr_in *) &sin)->sin_port);
2040 #endif
2041 #endif
2042
2043         return port;
2044 }
2045
2046 #if defined(LWS_USE_IPV6)
2047 LWS_EXTERN unsigned long
2048 lws_get_addr_scope(const char *ipaddr)
2049 {
2050         unsigned long scope = 0;
2051
2052 #ifndef WIN32
2053         struct ifaddrs *addrs, *addr;
2054         char ip[NI_MAXHOST];
2055         unsigned int i;
2056
2057         getifaddrs(&addrs);
2058         for (addr = addrs; addr; addr = addr->ifa_next) {
2059                 if (!addr->ifa_addr ||
2060                         addr->ifa_addr->sa_family != AF_INET6)
2061                         continue;
2062
2063                 getnameinfo(addr->ifa_addr,
2064                                 sizeof(struct sockaddr_in6),
2065                                 ip, sizeof(ip),
2066                                 NULL, 0, NI_NUMERICHOST);
2067
2068                 i = 0;
2069                 while (ip[i])
2070                         if (ip[i++] == '%') {
2071                                 ip[i - 1] = '\0';
2072                                 break;
2073                         }
2074
2075                 if (!strcmp(ip, ipaddr)) {
2076                         scope = if_nametoindex(addr->ifa_name);
2077                         break;
2078                 }
2079         }
2080         freeifaddrs(addrs);
2081 #else
2082         PIP_ADAPTER_ADDRESSES adapter, addrs = NULL;
2083         PIP_ADAPTER_UNICAST_ADDRESS addr;
2084         ULONG size = 0;
2085         DWORD ret;
2086         struct sockaddr_in6 *sockaddr;
2087         char ip[NI_MAXHOST];
2088         unsigned int i;
2089         int found = 0;
2090
2091         for (i = 0; i < 5; i++)
2092         {
2093                 ret = GetAdaptersAddresses(AF_INET6, GAA_FLAG_INCLUDE_PREFIX,
2094                                 NULL, addrs, &size);
2095                 if ((ret == NO_ERROR) || (ret == ERROR_NO_DATA)) {
2096                         break;
2097                 } else if (ret == ERROR_BUFFER_OVERFLOW)
2098                 {
2099                         if (addrs)
2100                                 free(addrs);
2101                         addrs = (IP_ADAPTER_ADDRESSES *) malloc(size);
2102                 } else
2103                 {
2104                         if (addrs)
2105                         {
2106                                 free(addrs);
2107                                 addrs = NULL;
2108                         }
2109                         lwsl_err("Failed to get IPv6 address table (%d)", ret);
2110                         break;
2111                 }
2112         }
2113
2114         if ((ret == NO_ERROR) && (addrs))
2115         {
2116                 adapter = addrs;
2117                 while ((adapter) && (!found))
2118                 {
2119                         addr = adapter->FirstUnicastAddress;
2120                         while ((addr) && (!found))
2121                         {
2122                                 if (addr->Address.lpSockaddr->sa_family == AF_INET6)
2123                                 {
2124                                         sockaddr = (struct sockaddr_in6 *) (addr->Address.lpSockaddr);
2125
2126                                         lws_plat_inet_ntop(sockaddr->sin6_family, &sockaddr->sin6_addr,
2127                                                         ip, sizeof(ip));
2128
2129                                         if (!strcmp(ip, ipaddr)) {
2130                                                 scope = sockaddr->sin6_scope_id;
2131                                                 found = 1;
2132                                                 break;
2133                                         }
2134                                 }
2135                                 addr = addr->Next;
2136                         }
2137                         adapter = adapter->Next;
2138                 }
2139         }
2140         if (addrs)
2141                 free(addrs);
2142 #endif
2143
2144         return scope;
2145 }
2146 #endif
2147
2148 LWS_EXTERN void
2149 lws_restart_ws_ping_pong_timer(struct lws *wsi)
2150 {
2151         if (!wsi->context->ws_ping_pong_interval)
2152                 return;
2153         if (wsi->state != LWSS_ESTABLISHED)
2154                 return;
2155
2156         wsi->u.ws.time_next_ping_check = (time_t)lws_now_secs() +
2157                                     wsi->context->ws_ping_pong_interval;
2158 }
2159
2160 static const char *hex = "0123456789ABCDEF";
2161
2162 LWS_VISIBLE LWS_EXTERN const char *
2163 lws_sql_purify(char *escaped, const char *string, int len)
2164 {
2165         const char *p = string;
2166         char *q = escaped;
2167
2168         while (*p && len-- > 2) {
2169                 if (*p == '\'') {
2170                         *q++ = '\'';
2171                         *q++ = '\'';
2172                         len --;
2173                         p++;
2174                 } else
2175                         *q++ = *p++;
2176         }
2177         *q = '\0';
2178
2179         return escaped;
2180 }
2181
2182 LWS_VISIBLE LWS_EXTERN const char *
2183 lws_json_purify(char *escaped, const char *string, int len)
2184 {
2185         const char *p = string;
2186         char *q = escaped;
2187
2188         if (!p) {
2189                 escaped[0] = '\0';
2190                 return escaped;
2191         }
2192
2193         while (*p && len-- > 6) {
2194                 if (*p == '\"' || *p == '\\' || *p < 0x20) {
2195                         *q++ = '\\';
2196                         *q++ = 'u';
2197                         *q++ = '0';
2198                         *q++ = '0';
2199                         *q++ = hex[((*p) >> 4) & 15];
2200                         *q++ = hex[(*p) & 15];
2201                         len -= 5;
2202                         p++;
2203                 } else
2204                         *q++ = *p++;
2205         }
2206         *q = '\0';
2207
2208         return escaped;
2209 }
2210
2211 LWS_VISIBLE LWS_EXTERN const char *
2212 lws_urlencode(char *escaped, const char *string, int len)
2213 {
2214         const char *p = string;
2215         char *q = escaped;
2216
2217         while (*p && len-- > 3) {
2218                 if (*p == ' ') {
2219                         *q++ = '+';
2220                         p++;
2221                         continue;
2222                 }
2223                 if ((*p >= '0' && *p <= '9') ||
2224                     (*p >= 'A' && *p <= 'Z') ||
2225                     (*p >= 'a' && *p <= 'z')) {
2226                         *q++ = *p++;
2227                         continue;
2228                 }
2229                 *q++ = '%';
2230                 *q++ = hex[(*p >> 4) & 0xf];
2231                 *q++ = hex[*p & 0xf];
2232
2233                 len -= 2;
2234                 p++;
2235         }
2236         *q = '\0';
2237
2238         return escaped;
2239 }
2240
2241 LWS_VISIBLE LWS_EXTERN int
2242 lws_urldecode(char *string, const char *escaped, int len)
2243 {
2244         int state = 0, n;
2245         char sum = 0;
2246
2247         while (*escaped && len) {
2248                 switch (state) {
2249                 case 0:
2250                         if (*escaped == '%') {
2251                                 state++;
2252                                 escaped++;
2253                                 continue;
2254                         }
2255                         if (*escaped == '+') {
2256                                 escaped++;
2257                                 *string++ = ' ';
2258                                 len--;
2259                                 continue;
2260                         }
2261                         *string++ = *escaped++;
2262                         len--;
2263                         break;
2264                 case 1:
2265                         n = char_to_hex(*escaped);
2266                         if (n < 0)
2267                                 return -1;
2268                         escaped++;
2269                         sum = n << 4;
2270                         state++;
2271                         break;
2272
2273                 case 2:
2274                         n = char_to_hex(*escaped);
2275                         if (n < 0)
2276                                 return -1;
2277                         escaped++;
2278                         *string++ = sum | n;
2279                         len--;
2280                         state = 0;
2281                         break;
2282                 }
2283
2284         }
2285         *string = '\0';
2286
2287         return 0;
2288 }
2289
2290 LWS_VISIBLE LWS_EXTERN int
2291 lws_finalize_startup(struct lws_context *context)
2292 {
2293         struct lws_context_creation_info info;
2294
2295         info.uid = context->uid;
2296         info.gid = context->gid;
2297
2298 #if defined(LWS_HAVE_SYS_CAPABILITY_H) && defined(LWS_HAVE_LIBCAP)
2299         memcpy(info.caps, context->caps, sizeof(info.caps));
2300         info.count_caps = context->count_caps;
2301 #endif
2302
2303         if (lws_check_opt(context->options, LWS_SERVER_OPTION_EXPLICIT_VHOSTS))
2304                 lws_plat_drop_app_privileges(&info);
2305
2306         return 0;
2307 }
2308
2309 int
2310 lws_snprintf(char *str, size_t size, const char *format, ...)
2311 {
2312         va_list ap;
2313         int n;
2314
2315         if (!size)
2316                 return 0;
2317
2318         va_start(ap, format);
2319         n = vsnprintf(str, size, format, ap);
2320         va_end(ap);
2321
2322         if (n >= (int)size)
2323                 return size;
2324
2325         return n;
2326 }
2327
2328
2329 LWS_VISIBLE LWS_EXTERN int
2330 lws_is_cgi(struct lws *wsi) {
2331 #ifdef LWS_WITH_CGI
2332         return !!wsi->cgi;
2333 #else
2334         return 0;
2335 #endif
2336 }
2337
2338 #ifdef LWS_WITH_CGI
2339
2340 static int
2341 urlencode(const char *in, int inlen, char *out, int outlen)
2342 {
2343         char *start = out, *end = out + outlen;
2344
2345         while (inlen-- && out < end - 4) {
2346                 if ((*in >= 'A' && *in <= 'Z') ||
2347                     (*in >= 'a' && *in <= 'z') ||
2348                     (*in >= '0' && *in <= '9') ||
2349                     *in == '-' ||
2350                     *in == '_' ||
2351                     *in == '.' ||
2352                     *in == '~') {
2353                         *out++ = *in++;
2354                         continue;
2355                 }
2356                 if (*in == ' ') {
2357                         *out++ = '+';
2358                         in++;
2359                         continue;
2360                 }
2361                 *out++ = '%';
2362                 *out++ = hex[(*in) >> 4];
2363                 *out++ = hex[(*in++) & 15];
2364         }
2365         *out = '\0';
2366
2367         if (out >= end - 4)
2368                 return -1;
2369
2370         return out - start;
2371 }
2372
2373 static struct lws *
2374 lws_create_basic_wsi(struct lws_context *context, int tsi)
2375 {
2376         struct lws *new_wsi;
2377
2378         if ((unsigned int)context->pt[tsi].fds_count ==
2379             context->fd_limit_per_thread - 1) {
2380                 lwsl_err("no space for new conn\n");
2381                 return NULL;
2382         }
2383
2384         new_wsi = lws_zalloc(sizeof(struct lws));
2385         if (new_wsi == NULL) {
2386                 lwsl_err("Out of memory for new connection\n");
2387                 return NULL;
2388         }
2389
2390         new_wsi->tsi = tsi;
2391         new_wsi->context = context;
2392         new_wsi->pending_timeout = NO_PENDING_TIMEOUT;
2393         new_wsi->rxflow_change_to = LWS_RXFLOW_ALLOW;
2394
2395         /* initialize the instance struct */
2396
2397         new_wsi->state = LWSS_CGI;
2398         new_wsi->mode = LWSCM_CGI;
2399         new_wsi->hdr_parsing_completed = 0;
2400         new_wsi->position_in_fds_table = -1;
2401
2402         /*
2403          * these can only be set once the protocol is known
2404          * we set an unestablished connection's protocol pointer
2405          * to the start of the defauly vhost supported list, so it can look
2406          * for matching ones during the handshake
2407          */
2408         new_wsi->protocol = context->vhost_list->protocols;
2409         new_wsi->user_space = NULL;
2410         new_wsi->ietf_spec_revision = 0;
2411         new_wsi->desc.sockfd = LWS_SOCK_INVALID;
2412         context->count_wsi_allocated++;
2413
2414         return new_wsi;
2415 }
2416
2417 LWS_VISIBLE LWS_EXTERN int
2418 lws_cgi(struct lws *wsi, const char * const *exec_array, int script_uri_path_len,
2419         int timeout_secs, const struct lws_protocol_vhost_options *mp_cgienv)
2420 {
2421         struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
2422         char *env_array[30], cgi_path[400], e[1024], *p = e,
2423              *end = p + sizeof(e) - 1, tok[256], *t;
2424         struct lws_cgi *cgi;
2425         int n, m, i, uritok = -1;
2426
2427         /*
2428          * give the master wsi a cgi struct
2429          */
2430
2431         wsi->cgi = lws_zalloc(sizeof(*wsi->cgi));
2432         if (!wsi->cgi) {
2433                 lwsl_err("%s: OOM\n", __func__);
2434                 return -1;
2435         }
2436
2437         wsi->cgi->response_code = HTTP_STATUS_OK;
2438
2439         cgi = wsi->cgi;
2440         cgi->wsi = wsi; /* set cgi's owning wsi */
2441
2442         /* create pipes for [stdin|stdout] and [stderr] */
2443
2444         for (n = 0; n < 3; n++)
2445                 if (pipe(cgi->pipe_fds[n]) == -1)
2446                         goto bail1;
2447
2448         /* create cgi wsis for each stdin/out/err fd */
2449
2450         for (n = 0; n < 3; n++) {
2451                 cgi->stdwsi[n] = lws_create_basic_wsi(wsi->context, wsi->tsi);
2452                 if (!cgi->stdwsi[n])
2453                         goto bail2;
2454                 cgi->stdwsi[n]->cgi_channel = n;
2455                 cgi->stdwsi[n]->vhost = wsi->vhost;
2456
2457 //              lwsl_err("%s: cgi %p: pipe fd %d -> fd %d / %d\n", __func__, wsi, n,
2458 //                       cgi->pipe_fds[n][!!(n == 0)], cgi->pipe_fds[n][!(n == 0)]);
2459
2460                 /* read side is 0, stdin we want the write side, others read */
2461                 cgi->stdwsi[n]->desc.sockfd = cgi->pipe_fds[n][!!(n == 0)];
2462                 if (fcntl(cgi->pipe_fds[n][!!(n == 0)], F_SETFL, O_NONBLOCK) < 0) {
2463                         lwsl_err("%s: setting NONBLOCK failed\n", __func__);
2464                         goto bail2;
2465                 }
2466         }
2467
2468         for (n = 0; n < 3; n++) {
2469                 lws_libuv_accept(cgi->stdwsi[n], cgi->stdwsi[n]->desc);
2470                 if (insert_wsi_socket_into_fds(wsi->context, cgi->stdwsi[n]))
2471                         goto bail3;
2472                 cgi->stdwsi[n]->parent = wsi;
2473                 cgi->stdwsi[n]->sibling_list = wsi->child_list;
2474                 wsi->child_list = cgi->stdwsi[n];
2475         }
2476
2477         lws_change_pollfd(cgi->stdwsi[LWS_STDIN], LWS_POLLIN, LWS_POLLOUT);
2478         lws_change_pollfd(cgi->stdwsi[LWS_STDOUT], LWS_POLLOUT, LWS_POLLIN);
2479         lws_change_pollfd(cgi->stdwsi[LWS_STDERR], LWS_POLLOUT, LWS_POLLIN);
2480
2481         lwsl_debug("%s: fds in %d, out %d, err %d\n", __func__,
2482                    cgi->stdwsi[LWS_STDIN]->desc.sockfd,
2483                    cgi->stdwsi[LWS_STDOUT]->desc.sockfd,
2484                    cgi->stdwsi[LWS_STDERR]->desc.sockfd);
2485
2486         lws_set_timeout(wsi, PENDING_TIMEOUT_CGI, timeout_secs);
2487
2488         /* the cgi stdout is always sending us http1.x header data first */
2489         wsi->hdr_state = LCHS_HEADER;
2490
2491         /* add us to the pt list of active cgis */
2492         lwsl_debug("%s: adding cgi %p to list\n", __func__, wsi->cgi);
2493         cgi->cgi_list = pt->cgi_list;
2494         pt->cgi_list = cgi;
2495
2496         /* prepare his CGI env */
2497
2498         n = 0;
2499
2500         if (lws_is_ssl(wsi))
2501                 env_array[n++] = "HTTPS=ON";
2502         if (wsi->u.hdr.ah) {
2503                 static const unsigned char meths[] = {
2504                         WSI_TOKEN_GET_URI,
2505                         WSI_TOKEN_POST_URI,
2506                         WSI_TOKEN_OPTIONS_URI,
2507                         WSI_TOKEN_PUT_URI,
2508                         WSI_TOKEN_PATCH_URI,
2509                         WSI_TOKEN_DELETE_URI,
2510                 };
2511                 static const char * const meth_names[] = {
2512                         "GET", "POST", "OPTIONS", "PUT", "PATCH", "DELETE",
2513                 };
2514
2515                 for (m = 0; m < ARRAY_SIZE(meths); m++)
2516                         if (lws_hdr_total_length(wsi, meths[m]) >=
2517                                         script_uri_path_len) {
2518                                 uritok = meths[m];
2519                                 break;
2520                         }
2521
2522                 if (uritok < 0)
2523                         goto bail3;
2524
2525                 lws_snprintf(cgi_path, sizeof(cgi_path) - 1, "REQUEST_URI=%s",
2526                          lws_hdr_simple_ptr(wsi, uritok));
2527                 cgi_path[sizeof(cgi_path) - 1] = '\0';
2528                 env_array[n++] = cgi_path;
2529
2530                 env_array[n++] = p;
2531                 p += lws_snprintf(p, end - p, "REQUEST_METHOD=%s",
2532                               meth_names[m]);
2533                 p++;
2534
2535                 env_array[n++] = p;
2536                 p += lws_snprintf(p, end - p, "QUERY_STRING=");
2537                 /* dump the individual URI Arg parameters */
2538                 m = 0;
2539                 while (1) {
2540                         i = lws_hdr_copy_fragment(wsi, tok, sizeof(tok),
2541                                              WSI_TOKEN_HTTP_URI_ARGS, m);
2542                         if (i < 0)
2543                                 break;
2544                         t = tok;
2545                         while (*t && *t != '=' && p < end - 4)
2546                                 *p++ = *t++;
2547                         if (*t == '=')
2548                                 *p++ = *t++;
2549                         i = urlencode(t, i- (t - tok), p, end - p);
2550                         if (i > 0) {
2551                                 p += i;
2552                                 *p++ = '&';
2553                         }
2554                         m++;
2555                 }
2556                 if (m)
2557                         p--;
2558                 *p++ = '\0';
2559
2560                 env_array[n++] = p;
2561                 p += lws_snprintf(p, end - p, "PATH_INFO=%s",
2562                               lws_hdr_simple_ptr(wsi, uritok) +
2563                               script_uri_path_len);
2564                 p++;
2565         }
2566         if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_REFERER)) {
2567                 env_array[n++] = p;
2568                 p += lws_snprintf(p, end - p, "HTTP_REFERER=%s",
2569                               lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_REFERER));
2570                 p++;
2571         }
2572         if (lws_hdr_total_length(wsi, WSI_TOKEN_HOST)) {
2573                 env_array[n++] = p;
2574                 p += lws_snprintf(p, end - p, "HTTP_HOST=%s",
2575                               lws_hdr_simple_ptr(wsi, WSI_TOKEN_HOST));
2576                 p++;
2577         }
2578         if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_COOKIE)) {
2579                 env_array[n++] = p;
2580                 p += lws_snprintf(p, end - p, "HTTP_COOKIE=%s",
2581                               lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_COOKIE));
2582                 p++;
2583         }
2584         if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_USER_AGENT)) {
2585                 env_array[n++] = p;
2586                 p += lws_snprintf(p, end - p, "USER_AGENT=%s",
2587                               lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_USER_AGENT));
2588                 p++;
2589         }
2590         if (uritok == WSI_TOKEN_POST_URI) {
2591                 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE)) {
2592                         env_array[n++] = p;
2593                         p += lws_snprintf(p, end - p, "CONTENT_TYPE=%s",
2594                                       lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE));
2595                         p++;
2596                 }
2597                 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH)) {
2598                         env_array[n++] = p;
2599                         p += lws_snprintf(p, end - p, "CONTENT_LENGTH=%s",
2600                                       lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH));
2601                         p++;
2602                 }
2603         }
2604         env_array[n++] = p;
2605         p += lws_snprintf(p, end - p, "SCRIPT_PATH=%s", exec_array[0]) + 1;
2606
2607         while (mp_cgienv) {
2608                 env_array[n++] = p;
2609                 p += lws_snprintf(p, end - p, "%s=%s", mp_cgienv->name,
2610                               mp_cgienv->value);
2611                 lwsl_debug("   Applying mount-specific cgi env '%s'\n",
2612                            env_array[n - 1]);
2613                 p++;
2614                 mp_cgienv = mp_cgienv->next;
2615         }
2616
2617         env_array[n++] = "SERVER_SOFTWARE=libwebsockets";
2618         env_array[n++] = "PATH=/bin:/usr/bin:/usr/local/bin:/var/www/cgi-bin";
2619         env_array[n] = NULL;
2620
2621 #if 0
2622         for (m = 0; m < n; m++)
2623                 lwsl_err("    %s\n", env_array[m]);
2624 #endif
2625
2626         /*
2627          * Actually having made the env, as a cgi we don't need the ah
2628          * any more
2629          */
2630         if (lws_header_table_is_in_detachable_state(wsi))
2631                 lws_header_table_detach(wsi, 0);
2632
2633         /* we are ready with the redirection pipes... run the thing */
2634 #if !defined(LWS_HAVE_VFORK) || !defined(LWS_HAVE_EXECVPE)
2635         cgi->pid = fork();
2636 #else
2637         cgi->pid = vfork();
2638 #endif
2639         if (cgi->pid < 0) {
2640                 lwsl_err("fork failed, errno %d", errno);
2641                 goto bail3;
2642         }
2643
2644 #if defined(__linux__)
2645         prctl(PR_SET_PDEATHSIG, SIGTERM);
2646 #endif
2647         setpgrp(); /* stops on-daemonized main processess getting SIGINT from TTY */
2648
2649         if (cgi->pid) {
2650                 /* we are the parent process */
2651                 wsi->context->count_cgi_spawned++;
2652                 lwsl_debug("%s: cgi %p spawned PID %d\n", __func__, cgi, cgi->pid);
2653                 return 0;
2654         }
2655
2656         /* somewhere we can at least read things and enter it */
2657         if (chdir("/tmp"))
2658                 lwsl_notice("%s: Failed to chdir\n", __func__);
2659
2660         /* We are the forked process, redirect and kill inherited things.
2661          *
2662          * Because of vfork(), we cannot do anything that changes pages in
2663          * the parent environment.  Stuff that changes kernel state for the
2664          * process is OK.  Stuff that happens after the execvpe() is OK.
2665          */
2666
2667         for (n = 0; n < 3; n++) {
2668                 if (dup2(cgi->pipe_fds[n][!(n == 0)], n) < 0) {
2669                         lwsl_err("%s: stdin dup2 failed\n", __func__);
2670                         goto bail3;
2671                 }
2672                 close(cgi->pipe_fds[n][!(n == 0)]);
2673         }
2674
2675 #if !defined(LWS_HAVE_VFORK) || !defined(LWS_HAVE_EXECVPE)
2676         for (m = 0; m < n; m++) {
2677                 p = strchr(env_array[m], '=');
2678                 *p++ = '\0';
2679                 setenv(env_array[m], p, 1);
2680         }
2681         execvp(exec_array[0], (char * const *)&exec_array[0]);
2682 #else
2683         execvpe(exec_array[0], (char * const *)&exec_array[0], &env_array[0]);
2684 #endif
2685
2686         exit(1);
2687
2688 bail3:
2689         /* drop us from the pt cgi list */
2690         pt->cgi_list = cgi->cgi_list;
2691
2692         while (--n >= 0)
2693                 remove_wsi_socket_from_fds(wsi->cgi->stdwsi[n]);
2694 bail2:
2695         for (n = 0; n < 3; n++)
2696                 if (wsi->cgi->stdwsi[n])
2697                         lws_free_wsi(cgi->stdwsi[n]);
2698
2699 bail1:
2700         for (n = 0; n < 3; n++) {
2701                 if (cgi->pipe_fds[n][0])
2702                         close(cgi->pipe_fds[n][0]);
2703                 if (cgi->pipe_fds[n][1])
2704                         close(cgi->pipe_fds[n][1]);
2705         }
2706
2707         lws_free_set_NULL(wsi->cgi);
2708
2709         lwsl_err("%s: failed\n", __func__);
2710
2711         return -1;
2712 }
2713
2714 /* we have to parse out these headers in the CGI output */
2715
2716 static const char * const significant_hdr[SIGNIFICANT_HDR_COUNT] = {
2717         "content-length: ",
2718         "location: ",
2719         "status: ",
2720         "transfer-encoding: chunked",
2721 };
2722
2723 LWS_VISIBLE LWS_EXTERN int
2724 lws_cgi_write_split_stdout_headers(struct lws *wsi)
2725 {
2726         int n, m;
2727         unsigned char buf[LWS_PRE + 1024], *start = &buf[LWS_PRE], *p = start,
2728              *end = &buf[sizeof(buf) - 1 - LWS_PRE];
2729         char c;
2730
2731         if (!wsi->cgi)
2732                 return -1;
2733
2734         while (wsi->hdr_state != LHCS_PAYLOAD) {
2735                 /* we have to separate header / finalize and
2736                  * payload chunks, since they need to be
2737                  * handled separately
2738                  */
2739
2740                 switch (wsi->hdr_state) {
2741
2742                 case LHCS_RESPONSE:
2743                         lwsl_info("LHCS_RESPONSE: issuing response %d\n",
2744                                         wsi->cgi->response_code);
2745                         if (lws_add_http_header_status(wsi, wsi->cgi->response_code, &p, end))
2746                                 return 1;
2747                         if (lws_add_http_header_by_token(wsi, WSI_TOKEN_CONNECTION,
2748                                         (unsigned char *)"close", 5, &p, end))
2749                                 return 1;
2750                         n = lws_write(wsi, start, p - start,
2751                                       LWS_WRITE_HTTP_HEADERS);
2752
2753                         /* finalize cached headers before dumping them */
2754                         if (lws_finalize_http_header(wsi,
2755                                         (unsigned char **)&wsi->cgi->headers_pos,
2756                                         (unsigned char *)wsi->cgi->headers_end)) {
2757
2758                                 lwsl_notice("finalize failed\n");
2759                                 return -1;
2760                         }
2761
2762                         wsi->hdr_state = LHCS_DUMP_HEADERS;
2763                         wsi->reason_bf |= 8;
2764                         lws_callback_on_writable(wsi);
2765                         /* back to the loop for writeability again */
2766                         return 0;
2767
2768                 case LHCS_DUMP_HEADERS:
2769
2770                         n = wsi->cgi->headers_pos - wsi->cgi->headers_dumped;
2771                         if (n > 512)
2772                                 n = 512;
2773
2774                         lwsl_debug("LHCS_DUMP_HEADERS: %d\n", n);
2775
2776                         m = lws_write(wsi, (unsigned char *)wsi->cgi->headers_dumped,
2777                                       n, LWS_WRITE_HTTP_HEADERS);
2778                         if (m < 0) {
2779                                 lwsl_debug("%s: write says %d\n", __func__, m);
2780                                 return -1;
2781                         }
2782                         wsi->cgi->headers_dumped += n;
2783                         if (wsi->cgi->headers_dumped == wsi->cgi->headers_pos) {
2784                                 wsi->hdr_state = LHCS_PAYLOAD;
2785                                 lws_free_set_NULL(wsi->cgi->headers_buf);
2786                                 lwsl_debug("freed cgi headers\n");
2787                         } else {
2788                                 wsi->reason_bf |= 8;
2789                                 lws_callback_on_writable(wsi);
2790                         }
2791
2792                         /* writeability becomes uncertain now we wrote
2793                          * something, we must return to the event loop
2794                          */
2795                         return 0;
2796                 }
2797
2798                 if (!wsi->cgi->headers_buf) {
2799                         /* if we don't already have a headers buf, cook one up */
2800                         n = 2048;
2801                         wsi->cgi->headers_buf = malloc(n);
2802                         if (!wsi->cgi->headers_buf) {
2803                                 lwsl_err("OOM\n");
2804                                 return -1;
2805                         }
2806
2807                         lwsl_debug("allocated cgi hdrs\n");
2808                         wsi->cgi->headers_pos = wsi->cgi->headers_buf;
2809                         wsi->cgi->headers_dumped = wsi->cgi->headers_pos;
2810                         wsi->cgi->headers_end = wsi->cgi->headers_buf + n - 1;
2811
2812                         for (n = 0; n < SIGNIFICANT_HDR_COUNT; n++) {
2813                                 wsi->cgi->match[n] = 0;
2814                                 wsi->cgi->lp = 0;
2815                         }
2816                 }
2817
2818                 n = read(lws_get_socket_fd(wsi->cgi->stdwsi[LWS_STDOUT]), &c, 1);
2819                 if (n < 0) {
2820                         if (errno != EAGAIN) {
2821                                 lwsl_debug("%s: read says %d\n", __func__, n);
2822                                 return -1;
2823                         }
2824                         else
2825                                 n = 0;
2826
2827                         if (wsi->cgi->headers_pos >= wsi->cgi->headers_end - 4) {
2828                                 lwsl_notice("CGI headers larger than buffer size\n");
2829
2830                                 return -1;
2831                         }
2832                 }
2833                 if (n) {
2834                         lwsl_debug("-- 0x%02X %c %d %d\n", (unsigned char)c, c, wsi->cgi->match[1], wsi->hdr_state);
2835                         if (!c)
2836                                 return -1;
2837                         switch (wsi->hdr_state) {
2838                         case LCHS_HEADER:
2839                                 hdr:
2840                                 for (n = 0; n < SIGNIFICANT_HDR_COUNT; n++) {
2841                                         /* significant headers with numeric decimal payloads */
2842                                         if (!significant_hdr[n][wsi->cgi->match[n]] &&
2843                                             (c >= '0' && c <= '9') &&
2844                                             wsi->cgi->lp < sizeof(wsi->cgi->l) - 1) {
2845                                                 wsi->cgi->l[wsi->cgi->lp++] = c;
2846                                                 wsi->cgi->l[wsi->cgi->lp] = '\0';
2847                                                 switch (n) {
2848                                                 case SIGNIFICANT_HDR_CONTENT_LENGTH:
2849                                                         wsi->cgi->content_length = atoll(wsi->cgi->l);
2850                                                         break;
2851                                                 case SIGNIFICANT_HDR_STATUS:
2852                                                         wsi->cgi->response_code = atol(wsi->cgi->l);
2853                                                         lwsl_debug("Status set to %d\n", wsi->cgi->response_code);
2854                                                         break;
2855                                                 default:
2856                                                         break;
2857                                                 }
2858                                         }
2859                                         /* hits up to the NUL are sticky until next hdr */
2860                                         if (significant_hdr[n][wsi->cgi->match[n]]) {
2861                                                 if (tolower(c) == significant_hdr[n][wsi->cgi->match[n]])
2862                                                         wsi->cgi->match[n]++;
2863                                                 else
2864                                                         wsi->cgi->match[n] = 0;
2865                                         }
2866                                 }
2867
2868                                 /* some cgi only send us \x0a for EOL */
2869                                 if (c == '\x0a') {
2870                                         wsi->hdr_state = LCHS_SINGLE_0A;
2871                                         *wsi->cgi->headers_pos++ = '\x0d';
2872                                 }
2873                                 *wsi->cgi->headers_pos++ = c;
2874                                 if (c == '\x0d')
2875                                         wsi->hdr_state = LCHS_LF1;
2876
2877                                 if (wsi->hdr_state != LCHS_HEADER &&
2878                                     !significant_hdr[SIGNIFICANT_HDR_TRANSFER_ENCODING][wsi->cgi->match[SIGNIFICANT_HDR_TRANSFER_ENCODING]]) {
2879                                         lwsl_debug("cgi produced chunked\n");
2880                                         wsi->cgi->explicitly_chunked = 1;
2881                                 }
2882
2883                                 /* presence of Location: mandates 302 retcode */
2884                                 if (wsi->hdr_state != LCHS_HEADER &&
2885                                     !significant_hdr[SIGNIFICANT_HDR_LOCATION][wsi->cgi->match[SIGNIFICANT_HDR_LOCATION]]) {
2886                                         lwsl_debug("CGI: Location hdr seen\n");
2887                                         wsi->cgi->response_code = 302;
2888                                 }
2889
2890                                 break;
2891                         case LCHS_LF1:
2892                                 *wsi->cgi->headers_pos++ = c;
2893                                 if (c == '\x0a') {
2894                                         wsi->hdr_state = LCHS_CR2;
2895                                         break;
2896                                 }
2897                                 /* we got \r[^\n]... it's unreasonable */
2898                                 lwsl_debug("%s: funny CRLF 0x%02X\n", __func__, (unsigned char)c);
2899                                 return -1;
2900
2901                         case LCHS_CR2:
2902                                 if (c == '\x0d') {
2903                                         /* drop the \x0d */
2904                                         wsi->hdr_state = LCHS_LF2;
2905                                         break;
2906                                 }
2907                                 wsi->hdr_state = LCHS_HEADER;
2908                                 for (n = 0; n < SIGNIFICANT_HDR_COUNT; n++)
2909                                         wsi->cgi->match[n] = 0;
2910                                 wsi->cgi->lp = 0;
2911                                 goto hdr;
2912
2913                         case LCHS_LF2:
2914                         case LCHS_SINGLE_0A:
2915                                 m = wsi->hdr_state;
2916                                 if (c == '\x0a') {
2917                                         lwsl_debug("Content-Length: %lld\n", (unsigned long long)wsi->cgi->content_length);
2918                                         wsi->hdr_state = LHCS_RESPONSE;
2919                                         /* drop the \0xa ... finalize will add it if needed */
2920                                         break;
2921                                 }
2922                                 if (m == LCHS_LF2)
2923                                         /* we got \r\n\r[^\n]... it's unreasonable */
2924                                         return -1;
2925                                 /* we got \x0anext header, it's reasonable */
2926                                 *wsi->cgi->headers_pos++ = c;
2927                                 wsi->hdr_state = LCHS_HEADER;
2928                                 for (n = 0; n < SIGNIFICANT_HDR_COUNT; n++)
2929                                         wsi->cgi->match[n] = 0;
2930                                 wsi->cgi->lp = 0;
2931                                 break;
2932                         case LHCS_PAYLOAD:
2933                                 break;
2934                         }
2935                 }
2936
2937                 /* ran out of input, ended the headers, or filled up the headers buf */
2938                 if (!n || wsi->hdr_state == LHCS_PAYLOAD)
2939                         return 0;
2940         }
2941
2942         /* payload processing */
2943
2944         n = read(lws_get_socket_fd(wsi->cgi->stdwsi[LWS_STDOUT]),
2945                  start, sizeof(buf) - LWS_PRE);
2946
2947         if (n < 0 && errno != EAGAIN) {
2948                 lwsl_debug("%s: stdout read says %d\n", __func__, n);
2949                 return -1;
2950         }
2951         if (n > 0) {
2952                 m = lws_write(wsi, (unsigned char *)start, n, LWS_WRITE_HTTP);
2953                 //lwsl_notice("write %d\n", m);
2954                 if (m < 0) {
2955                         lwsl_debug("%s: stdout write says %d\n", __func__, m);
2956                         return -1;
2957                 }
2958                 wsi->cgi->content_length_seen += m;
2959         }
2960
2961         return 0;
2962 }
2963
2964 LWS_VISIBLE LWS_EXTERN int
2965 lws_cgi_kill(struct lws *wsi)
2966 {
2967         struct lws_cgi_args args;
2968         int status, n;
2969
2970         lwsl_debug("%s: %p\n", __func__, wsi);
2971
2972         if (!wsi->cgi)
2973                 return 0;
2974
2975         if (wsi->cgi->pid > 0) {
2976                 n = waitpid(wsi->cgi->pid, &status, WNOHANG);
2977                 if (n > 0) {
2978                         lwsl_debug("%s: PID %d reaped\n", __func__,
2979                                     wsi->cgi->pid);
2980                         goto handled;
2981                 }
2982                 /* kill the process group */
2983                 n = kill(-wsi->cgi->pid, SIGTERM);
2984                 lwsl_debug("%s: SIGTERM child PID %d says %d (errno %d)\n", __func__,
2985                                 wsi->cgi->pid, n, errno);
2986                 if (n < 0) {
2987                         /*
2988                          * hum seen errno=3 when process is listed in ps,
2989                          * it seems we don't always retain process grouping
2990                          *
2991                          * Direct these fallback attempt to the exact child
2992                          */
2993                         n = kill(wsi->cgi->pid, SIGTERM);
2994                         if (n < 0) {
2995                                 n = kill(wsi->cgi->pid, SIGPIPE);
2996                                 if (n < 0) {
2997                                         n = kill(wsi->cgi->pid, SIGKILL);
2998                                         if (n < 0)
2999                                                 lwsl_err("%s: SIGKILL PID %d failed errno %d (maybe zombie)\n",
3000                                                                 __func__, wsi->cgi->pid, errno);
3001                                 }
3002                         }
3003                 }
3004                 /* He could be unkillable because he's a zombie */
3005                 n = 1;
3006                 while (n > 0) {
3007                         n = waitpid(-wsi->cgi->pid, &status, WNOHANG);
3008                         if (n > 0)
3009                                 lwsl_debug("%s: reaped PID %d\n", __func__, n);
3010                         if (n <= 0) {
3011                                 n = waitpid(wsi->cgi->pid, &status, WNOHANG);
3012                                 if (n > 0)
3013                                         lwsl_debug("%s: reaped PID %d\n", __func__, n);
3014                         }
3015                 }
3016         }
3017
3018 handled:
3019         args.stdwsi = &wsi->cgi->stdwsi[0];
3020
3021         if (wsi->cgi->pid != -1 && user_callback_handle_rxflow(
3022                         wsi->protocol->callback,
3023                         wsi, LWS_CALLBACK_CGI_TERMINATED,
3024                         wsi->user_space,
3025                         (void *)&args, 0)) {
3026                 wsi->cgi->pid = -1;
3027                 if (!wsi->cgi->being_closed)
3028                         lws_close_free_wsi(wsi, 0);
3029         }
3030
3031         return 0;
3032 }
3033
3034 LWS_EXTERN int
3035 lws_cgi_kill_terminated(struct lws_context_per_thread *pt)
3036 {
3037         struct lws_cgi **pcgi, *cgi = NULL;
3038         int status, n = 1;
3039
3040         while (n > 0) {
3041                 /* find finished guys but don't reap yet */
3042                 n = waitpid(-1, &status, WNOHANG);
3043                 if (n <= 0)
3044                         continue;
3045                 lwsl_debug("%s: observed PID %d terminated\n", __func__, n);
3046
3047                 pcgi = &pt->cgi_list;
3048
3049                 /* check all the subprocesses on the cgi list */
3050                 while (*pcgi) {
3051                         /* get the next one first as list may change */
3052                         cgi = *pcgi;
3053                         pcgi = &(*pcgi)->cgi_list;
3054
3055                         if (cgi->pid <= 0)
3056                                 continue;
3057
3058                         /* finish sending cached headers */
3059                         if (cgi->headers_buf)
3060                                 continue;
3061
3062                         /* wait for stdout to be drained */
3063                         if (cgi->content_length > cgi->content_length_seen)
3064                                 continue;
3065
3066                         if (cgi->content_length) {
3067                                 lwsl_debug("%s: wsi %p: expected content length seen: %lld\n",
3068                                         __func__, cgi->wsi, (unsigned long long)cgi->content_length_seen);
3069                         }
3070
3071                         /* reap it */
3072                         waitpid(n, &status, WNOHANG);
3073                         /*
3074                          * he's already terminated so no need for kill()
3075                          * but we should do the terminated cgi callback
3076                          * and close him if he's not already closing
3077                          */
3078                         if (n == cgi->pid) {
3079                                 lwsl_debug("%s: found PID %d on cgi list\n",
3080                                             __func__, n);
3081
3082                                 if (!cgi->content_length && cgi->explicitly_chunked) {
3083                                         /*
3084                                          * well, if he sends chunked... give him 5s after the
3085                                          * cgi terminated to send buffered
3086                                          */
3087                                         cgi->chunked_grace++;
3088                                         continue;
3089                                 }
3090
3091                                 /* defeat kill() */
3092                                 cgi->pid = 0;
3093                                 lws_cgi_kill(cgi->wsi);
3094
3095                                 break;
3096                         }
3097                         cgi = NULL;
3098                 }
3099                 /* if not found on the cgi list, as he's one of ours, reap */
3100                 if (!cgi) {
3101                         lwsl_debug("%s: reading PID %d although no cgi match\n",
3102                                         __func__, n);
3103                         waitpid(n, &status, WNOHANG);
3104                 }
3105         }
3106
3107 /* disable this to confirm timeout cgi cleanup flow */
3108 #if 1
3109         pcgi = &pt->cgi_list;
3110
3111         /* check all the subprocesses on the cgi list */
3112         while (*pcgi) {
3113                 /* get the next one first as list may change */
3114                 cgi = *pcgi;
3115                 pcgi = &(*pcgi)->cgi_list;
3116
3117                 if (cgi->pid <= 0)
3118                         continue;
3119
3120                 /* we deferred killing him after reaping his PID */
3121                 if (cgi->chunked_grace) {
3122                         cgi->chunked_grace++;
3123                         if (cgi->chunked_grace < 5)
3124                                 continue;
3125                         goto finish_him;
3126                 }
3127
3128                 /* finish sending cached headers */
3129                 if (cgi->headers_buf)
3130                         continue;
3131
3132                 /* wait for stdout to be drained */
3133                 if (cgi->content_length > cgi->content_length_seen)
3134                         continue;
3135
3136                 if (cgi->content_length)
3137                         lwsl_debug("%s: wsi %p: expected content length seen: %lld\n",
3138                                 __func__, cgi->wsi, (unsigned long long)cgi->content_length_seen);
3139
3140                 /* reap it */
3141                 if (waitpid(cgi->pid, &status, WNOHANG) > 0) {
3142
3143                         if (!cgi->content_length) {
3144                                 /*
3145                                  * well, if he sends chunked... give him 5s after the
3146                                  * cgi terminated to send buffered
3147                                  */
3148                                 cgi->chunked_grace++;
3149                                 continue;
3150                         }
3151 finish_him:
3152                         lwsl_debug("%s: found PID %d on cgi list\n",
3153                                     __func__, cgi->pid);
3154                         /* defeat kill() */
3155                         cgi->pid = 0;
3156                         lws_cgi_kill(cgi->wsi);
3157
3158                         break;
3159                 }
3160         }
3161 #endif
3162
3163         /* general anti zombie defence */
3164 //      n = waitpid(-1, &status, WNOHANG);
3165         //if (n > 0)
3166         //      lwsl_notice("%s: anti-zombie wait says %d\n", __func__, n);
3167
3168         return 0;
3169 }
3170 #endif
3171
3172 #ifdef LWS_NO_EXTENSIONS
3173 LWS_EXTERN int
3174 lws_set_extension_option(struct lws *wsi, const char *ext_name,
3175                          const char *opt_name, const char *opt_val)
3176 {
3177         return -1;
3178 }
3179 #endif
3180
3181 #ifdef LWS_WITH_ACCESS_LOG
3182 int
3183 lws_access_log(struct lws *wsi)
3184 {
3185         char *p = wsi->access_log.user_agent, ass[512];
3186         int l;
3187
3188         if (!wsi->access_log_pending)
3189                 return 0;
3190
3191         if (!wsi->access_log.header_log)
3192                 return 0;
3193
3194         if (!p)
3195                 p = "";
3196
3197         l = lws_snprintf(ass, sizeof(ass) - 1, "%s %d %lu %s\n",
3198                      wsi->access_log.header_log,
3199                      wsi->access_log.response, wsi->access_log.sent, p);
3200
3201         if (wsi->vhost->log_fd != (int)LWS_INVALID_FILE) {
3202                 if (write(wsi->vhost->log_fd, ass, l) != l)
3203                         lwsl_err("Failed to write log\n");
3204         } else
3205                 lwsl_err("%s", ass);
3206
3207         if (wsi->access_log.header_log) {
3208                 lws_free(wsi->access_log.header_log);
3209                 wsi->access_log.header_log = NULL;
3210         }
3211         if (wsi->access_log.user_agent) {
3212                 lws_free(wsi->access_log.user_agent);
3213                 wsi->access_log.user_agent = NULL;
3214         }
3215         wsi->access_log_pending = 0;
3216
3217         return 0;
3218 }
3219 #endif
3220
3221 void
3222 lws_sum_stats(const struct lws_context *ctx, struct lws_conn_stats *cs)
3223 {
3224         const struct lws_vhost *vh = ctx->vhost_list;
3225
3226         while (vh) {
3227
3228                 cs->rx += vh->conn_stats.rx;
3229                 cs->tx += vh->conn_stats.tx;
3230                 cs->conn += vh->conn_stats.conn;
3231                 cs->trans += vh->conn_stats.trans;
3232                 cs->ws_upg += vh->conn_stats.ws_upg;
3233                 cs->http2_upg += vh->conn_stats.http2_upg;
3234                 cs->rejected += vh->conn_stats.rejected;
3235
3236                 vh = vh->vhost_next;
3237         }
3238 }
3239
3240 #ifdef LWS_WITH_SERVER_STATUS
3241
3242 LWS_EXTERN int
3243 lws_json_dump_vhost(const struct lws_vhost *vh, char *buf, int len)
3244 {
3245         static const char * const prots[] = {
3246                 "http://",
3247                 "https://",
3248                 "file://",
3249                 "cgi://",
3250                 ">http://",
3251                 ">https://",
3252                 "callback://"
3253         };
3254         char *orig = buf, *end = buf + len - 1, first = 1;
3255         int n = 0;
3256
3257         if (len < 100)
3258                 return 0;
3259
3260         buf += lws_snprintf(buf, end - buf,
3261                         "{\n \"name\":\"%s\",\n"
3262                         " \"port\":\"%d\",\n"
3263                         " \"use_ssl\":\"%d\",\n"
3264                         " \"sts\":\"%d\",\n"
3265                         " \"rx\":\"%llu\",\n"
3266                         " \"tx\":\"%llu\",\n"
3267                         " \"conn\":\"%lu\",\n"
3268                         " \"trans\":\"%lu\",\n"
3269                         " \"ws_upg\":\"%lu\",\n"
3270                         " \"rejected\":\"%lu\",\n"
3271                         " \"http2_upg\":\"%lu\""
3272                         ,
3273                         vh->name, vh->listen_port,
3274 #ifdef LWS_OPENSSL_SUPPORT
3275                         vh->use_ssl,
3276 #else
3277                         0,
3278 #endif
3279                         !!(vh->options & LWS_SERVER_OPTION_STS),
3280                         vh->conn_stats.rx, vh->conn_stats.tx,
3281                         vh->conn_stats.conn, vh->conn_stats.trans,
3282                         vh->conn_stats.ws_upg,
3283                         vh->conn_stats.rejected,
3284                         vh->conn_stats.http2_upg
3285         );
3286
3287         if (vh->mount_list) {
3288                 const struct lws_http_mount *m = vh->mount_list;
3289
3290                 buf += lws_snprintf(buf, end - buf, ",\n \"mounts\":[");
3291                 while (m) {
3292                         if (!first)
3293                                 buf += lws_snprintf(buf, end - buf, ",");
3294                         buf += lws_snprintf(buf, end - buf,
3295                                         "\n  {\n   \"mountpoint\":\"%s\",\n"
3296                                         "  \"origin\":\"%s%s\",\n"
3297                                         "  \"cache_max_age\":\"%d\",\n"
3298                                         "  \"cache_reuse\":\"%d\",\n"
3299                                         "  \"cache_revalidate\":\"%d\",\n"
3300                                         "  \"cache_intermediaries\":\"%d\"\n"
3301                                         ,
3302                                         m->mountpoint,
3303                                         prots[m->origin_protocol],
3304                                         m->origin,
3305                                         m->cache_max_age,
3306                                         m->cache_reusable,
3307                                         m->cache_revalidate,
3308                                         m->cache_intermediaries);
3309                         if (m->def)
3310                                 buf += lws_snprintf(buf, end - buf,
3311                                                 ",\n  \"default\":\"%s\"",
3312                                                 m->def);
3313                         buf += lws_snprintf(buf, end - buf, "\n  }");
3314                         first = 0;
3315                         m = m->mount_next;
3316                 }
3317                 buf += lws_snprintf(buf, end - buf, "\n ]");
3318         }
3319
3320         if (vh->protocols) {
3321                 n = 0;
3322                 first = 1;
3323
3324                 buf += lws_snprintf(buf, end - buf, ",\n \"ws-protocols\":[");
3325                 while (n < vh->count_protocols) {
3326                         if (!first)
3327                                 buf += lws_snprintf(buf, end - buf, ",");
3328                         buf += lws_snprintf(buf, end - buf,
3329                                         "\n  {\n   \"%s\":{\n"
3330                                         "    \"status\":\"ok\"\n   }\n  }"
3331                                         ,
3332                                         vh->protocols[n].name);
3333                         first = 0;
3334                         n++;
3335                 }
3336                 buf += lws_snprintf(buf, end - buf, "\n ]");
3337         }
3338
3339         buf += lws_snprintf(buf, end - buf, "\n}");
3340
3341         return buf - orig;
3342 }
3343
3344
3345 LWS_EXTERN LWS_VISIBLE int
3346 lws_json_dump_context(const struct lws_context *context, char *buf, int len,
3347                 int hide_vhosts)
3348 {
3349         char *orig = buf, *end = buf + len - 1, first = 1;
3350         const struct lws_vhost *vh = context->vhost_list;
3351         const struct lws_context_per_thread *pt;
3352         time_t t = time(NULL);
3353         int n, listening = 0, cgi_count = 0;
3354         struct lws_conn_stats cs;
3355         double d = 0;
3356 #ifdef LWS_WITH_CGI
3357         struct lws_cgi * const *pcgi;
3358 #endif
3359
3360 #ifdef LWS_USE_LIBUV
3361         uv_uptime(&d);
3362 #endif
3363
3364         buf += lws_snprintf(buf, end - buf, "{ "
3365                             "\"version\":\"%s\",\n"
3366                             "\"uptime\":\"%ld\",\n",
3367                             lws_get_library_version(),
3368                             (long)d);
3369
3370 #ifdef LWS_HAVE_GETLOADAVG
3371         {
3372                 double d[3];
3373                 int m;
3374
3375                 m = getloadavg(d, 3);
3376                 for (n = 0; n < m; n++) {
3377                         buf += lws_snprintf(buf, end - buf,
3378                                 "\"l%d\":\"%.2f\",\n",
3379                                 n + 1, d[n]);
3380                 }
3381         }
3382 #endif
3383
3384         buf += lws_snprintf(buf, end - buf, "\"contexts\":[\n");
3385
3386         buf += lws_snprintf(buf, end - buf, "{ "
3387                                 "\"context_uptime\":\"%ld\",\n"
3388                                 "\"cgi_spawned\":\"%d\",\n"
3389                                 "\"pt_fd_max\":\"%d\",\n"
3390                                 "\"ah_pool_max\":\"%d\",\n"
3391                                 "\"deprecated\":\"%d\",\n"
3392                                 "\"wsi_alive\":\"%d\",\n",
3393                                 (unsigned long)(t - context->time_up),
3394                                 context->count_cgi_spawned,
3395                                 context->fd_limit_per_thread,
3396                                 context->max_http_header_pool,
3397                                 context->deprecated,
3398                                 context->count_wsi_allocated);
3399
3400         buf += lws_snprintf(buf, end - buf, "\"pt\":[\n ");
3401         for (n = 0; n < context->count_threads; n++) {
3402                 pt = &context->pt[n];
3403                 if (n)
3404                         buf += lws_snprintf(buf, end - buf, ",");
3405                 buf += lws_snprintf(buf, end - buf,
3406                                 "\n  {\n"
3407                                 "    \"fds_count\":\"%d\",\n"
3408                                 "    \"ah_pool_inuse\":\"%d\",\n"
3409                                 "    \"ah_wait_list\":\"%d\"\n"
3410                                 "    }",
3411                                 pt->fds_count,
3412                                 pt->ah_count_in_use,
3413                                 pt->ah_wait_list_length);
3414         }
3415
3416         buf += lws_snprintf(buf, end - buf, "]");
3417
3418         buf += lws_snprintf(buf, end - buf, ", \"vhosts\":[\n ");
3419
3420         first = 1;
3421         vh = context->vhost_list;
3422         listening = 0;
3423         cs = context->conn_stats;
3424         lws_sum_stats(context, &cs);
3425         while (vh) {
3426
3427                 if (!hide_vhosts) {
3428                         if (!first)
3429                                 if(buf != end)
3430                                         *buf++ = ',';
3431                         buf += lws_json_dump_vhost(vh, buf, end - buf);
3432                         first = 0;
3433                 }
3434                 if (vh->lserv_wsi)
3435                         listening++;
3436                 vh = vh->vhost_next;
3437         }
3438
3439         buf += lws_snprintf(buf, end - buf,
3440                         "],\n\"listen_wsi\":\"%d\",\n"
3441                         " \"rx\":\"%llu\",\n"
3442                         " \"tx\":\"%llu\",\n"
3443                         " \"conn\":\"%lu\",\n"
3444                         " \"trans\":\"%lu\",\n"
3445                         " \"ws_upg\":\"%lu\",\n"
3446                         " \"rejected\":\"%lu\",\n"
3447                         " \"http2_upg\":\"%lu\"",
3448                         listening,
3449                         cs.rx, cs.tx, cs.conn, cs.trans,
3450                         cs.ws_upg, cs.rejected, cs.http2_upg);
3451
3452 #ifdef LWS_WITH_CGI
3453         for (n = 0; n < context->count_threads; n++) {
3454                 pt = &context->pt[n];
3455                 pcgi = &pt->cgi_list;
3456
3457                 while (*pcgi) {
3458                         pcgi = &(*pcgi)->cgi_list;
3459
3460                         cgi_count++;
3461                 }
3462         }
3463 #endif
3464         buf += lws_snprintf(buf, end - buf, ",\n \"cgi_alive\":\"%d\"\n ",
3465                         cgi_count);
3466
3467         buf += lws_snprintf(buf, end - buf, "}");
3468
3469
3470         buf += lws_snprintf(buf, end - buf, "]}\n ");
3471
3472         return buf - orig;
3473 }
3474
3475 #endif
3476
3477 #if defined(LWS_WITH_STATS)
3478
3479 LWS_VISIBLE LWS_EXTERN uint64_t
3480 lws_stats_get(struct lws_context *context, int index)
3481 {
3482         if (index >= LWSSTATS_SIZE)
3483                 return 0;
3484
3485         return context->lws_stats[index];
3486 }
3487
3488 LWS_VISIBLE LWS_EXTERN void
3489 lws_stats_log_dump(struct lws_context *context)
3490 {
3491         struct lws_vhost *v = context->vhost_list;
3492         int n;
3493
3494         if (!context->updated)
3495                 return;
3496
3497         context->updated = 0;
3498
3499         lwsl_notice("\n");
3500         lwsl_notice("LWS internal statistics dump ----->\n");
3501         lwsl_notice("LWSSTATS_C_CONNECTIONS:                     %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_CONNECTIONS));
3502         lwsl_notice("LWSSTATS_C_API_CLOSE:                       %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_API_CLOSE));
3503         lwsl_notice("LWSSTATS_C_API_READ:                        %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_API_READ));
3504         lwsl_notice("LWSSTATS_C_API_LWS_WRITE:                   %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_API_LWS_WRITE));
3505         lwsl_notice("LWSSTATS_C_API_WRITE:                       %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_API_WRITE));
3506         lwsl_notice("LWSSTATS_C_WRITE_PARTIALS:                  %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_WRITE_PARTIALS));
3507         lwsl_notice("LWSSTATS_C_WRITEABLE_CB_REQ:                %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_WRITEABLE_CB_REQ));
3508         lwsl_notice("LWSSTATS_C_WRITEABLE_CB_EFF_REQ:            %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_WRITEABLE_CB_EFF_REQ));
3509         lwsl_notice("LWSSTATS_C_WRITEABLE_CB:                    %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_WRITEABLE_CB));
3510         lwsl_notice("LWSSTATS_C_SSL_CONNECTIONS_FAILED:          %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_SSL_CONNECTIONS_FAILED));
3511         lwsl_notice("LWSSTATS_C_SSL_CONNECTIONS_ACCEPTED:        %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_SSL_CONNECTIONS_ACCEPTED));
3512         lwsl_notice("LWSSTATS_C_SSL_CONNS_HAD_RX:                %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_SSL_CONNS_HAD_RX));
3513
3514         lwsl_notice("LWSSTATS_C_TIMEOUTS:                        %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_TIMEOUTS));
3515         lwsl_notice("LWSSTATS_C_SERVICE_ENTRY:                   %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_SERVICE_ENTRY));
3516         lwsl_notice("LWSSTATS_B_READ:                            %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_B_READ));
3517         lwsl_notice("LWSSTATS_B_WRITE:                           %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_B_WRITE));
3518         lwsl_notice("LWSSTATS_B_PARTIALS_ACCEPTED_PARTS:         %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_B_PARTIALS_ACCEPTED_PARTS));
3519         lwsl_notice("LWSSTATS_MS_SSL_CONNECTIONS_ACCEPTED_DELAY: %8llums\n", (unsigned long long)lws_stats_get(context, LWSSTATS_MS_SSL_CONNECTIONS_ACCEPTED_DELAY) / 1000);
3520         if (lws_stats_get(context, LWSSTATS_C_SSL_CONNECTIONS_ACCEPTED))
3521                 lwsl_notice("  Avg accept delay:                         %8llums\n",
3522                         (unsigned long long)(lws_stats_get(context, LWSSTATS_MS_SSL_CONNECTIONS_ACCEPTED_DELAY) /
3523                         lws_stats_get(context, LWSSTATS_C_SSL_CONNECTIONS_ACCEPTED)) / 1000);
3524         lwsl_notice("LWSSTATS_MS_SSL_RX_DELAY:                   %8llums\n", (unsigned long long)lws_stats_get(context, LWSSTATS_MS_SSL_RX_DELAY) / 1000);
3525         if (lws_stats_get(context, LWSSTATS_C_SSL_CONNS_HAD_RX))
3526                 lwsl_notice("  Avg accept-rx delay:                      %8llums\n",
3527                         (unsigned long long)(lws_stats_get(context, LWSSTATS_MS_SSL_RX_DELAY) /
3528                         lws_stats_get(context, LWSSTATS_C_SSL_CONNS_HAD_RX)) / 1000);
3529
3530         lwsl_notice("LWSSTATS_MS_WRITABLE_DELAY:                 %8lluus\n",
3531                         (unsigned long long)lws_stats_get(context, LWSSTATS_MS_WRITABLE_DELAY));
3532         lwsl_notice("LWSSTATS_MS_WORST_WRITABLE_DELAY:           %8lluus\n",
3533                                 (unsigned long long)lws_stats_get(context, LWSSTATS_MS_WORST_WRITABLE_DELAY));
3534         if (lws_stats_get(context, LWSSTATS_C_WRITEABLE_CB))
3535                 lwsl_notice("  Avg writable delay:                       %8lluus\n",
3536                         (unsigned long long)(lws_stats_get(context, LWSSTATS_MS_WRITABLE_DELAY) /
3537                         lws_stats_get(context, LWSSTATS_C_WRITEABLE_CB)));
3538         lwsl_notice("Simultaneous SSL restriction:               %8d/%d/%d\n", context->simultaneous_ssl,
3539                 context->simultaneous_ssl_restriction, context->ssl_gate_accepts);
3540
3541         lwsl_notice("Live wsi:                                   %8d\n", context->count_wsi_allocated);
3542
3543 #if defined(LWS_WITH_STATS)
3544         context->updated = 1;
3545 #endif
3546
3547         while (v) {
3548                 if (v->lserv_wsi) {
3549
3550                         struct lws_context_per_thread *pt = &context->pt[(int)v->lserv_wsi->tsi];
3551                         struct lws_pollfd *pfd;
3552
3553                         pfd = &pt->fds[v->lserv_wsi->position_in_fds_table];
3554
3555                         lwsl_notice("  Listen port %d actual POLLIN:   %d\n",
3556                                         v->listen_port, (int)pfd->events & LWS_POLLIN);
3557                 }
3558
3559                 v = v->vhost_next;
3560         }
3561
3562         for (n = 0; n < context->count_threads; n++) {
3563                 struct lws_context_per_thread *pt = &context->pt[n];
3564                 struct lws *wl;
3565                 int m = 0;
3566
3567                 lwsl_notice("PT %d\n", n + 1);
3568
3569                 lws_pt_lock(pt);
3570
3571                 lwsl_notice("  AH in use / max:                  %d / %d\n",
3572                                 pt->ah_count_in_use,
3573                                 context->max_http_header_pool);
3574
3575                 wl = pt->ah_wait_list;
3576                 while (wl) {
3577                         m++;
3578                         wl = wl->u.hdr.ah_wait_list;
3579                 }
3580
3581                 lwsl_notice("  AH wait list count / actual:      %d / %d\n",
3582                                 pt->ah_wait_list_length, m);
3583
3584                 lws_pt_unlock(pt);
3585         }
3586
3587         lwsl_notice("\n");
3588 }
3589
3590 void
3591 lws_stats_atomic_bump(struct lws_context * context,
3592                 struct lws_context_per_thread *pt, int index, uint64_t bump)
3593 {
3594         lws_pt_lock(pt);
3595         context->lws_stats[index] += bump;
3596         if (index != LWSSTATS_C_SERVICE_ENTRY)
3597                 context->updated = 1;
3598         lws_pt_unlock(pt);
3599 }
3600
3601 void
3602 lws_stats_atomic_max(struct lws_context * context,
3603                 struct lws_context_per_thread *pt, int index, uint64_t val)
3604 {
3605         lws_pt_lock(pt);
3606         if (val > context->lws_stats[index]) {
3607                 context->lws_stats[index] = val;
3608                 context->updated = 1;
3609         }
3610         lws_pt_unlock(pt);
3611 }
3612
3613 #endif