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