fops: refactor around lws_fops_fd_t
[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         lws_pt_lock(pt);
120
121         time(&now);
122
123         if (reason && !wsi->timeout_list_prev) {
124                 /* our next guy is current first guy */
125                 wsi->timeout_list = pt->timeout_list;
126                 /* if there is a next guy, set his prev ptr to our next ptr */
127                 if (wsi->timeout_list)
128                         wsi->timeout_list->timeout_list_prev = &wsi->timeout_list;
129                 /* our prev ptr is first ptr */
130                 wsi->timeout_list_prev = &pt->timeout_list;
131                 /* set the first guy to be us */
132                 *wsi->timeout_list_prev = wsi;
133         }
134
135         lwsl_debug("%s: %p: %d secs\n", __func__, wsi, secs);
136         wsi->pending_timeout_limit = now + secs;
137         wsi->pending_timeout = reason;
138
139         lws_pt_unlock(pt);
140
141         if (!reason)
142                 lws_remove_from_timeout_list(wsi);
143 }
144
145 void
146 lws_close_free_wsi(struct lws *wsi, enum lws_close_status reason)
147 {
148         struct lws_context_per_thread *pt;
149         struct lws **pwsi, *wsi1, *wsi2;
150         struct lws_context *context;
151         struct lws_tokens eff_buf;
152         int n, m, ret;
153
154         if (!wsi)
155                 return;
156
157         lws_access_log(wsi);
158 #if defined(LWS_WITH_ESP8266)
159         if (wsi->premature_rx)
160                 lws_free(wsi->premature_rx);
161
162         if (wsi->pending_send_completion && !wsi->close_is_pending_send_completion) {
163                 lwsl_notice("delaying close\n");
164                 wsi->close_is_pending_send_completion = 1;
165                 return;
166         }
167 #endif
168
169         if (wsi->u.hdr.ah)
170                 /* we're closing, losing some rx is OK */
171                 wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
172
173         context = wsi->context;
174         pt = &context->pt[(int)wsi->tsi];
175
176         /* if we have children, close them first */
177         if (wsi->child_list) {
178                 wsi2 = wsi->child_list;
179                 while (wsi2) {
180                         //lwsl_notice("%s: closing %p: close child %p\n",
181                         //              __func__, wsi, wsi2);
182                         wsi1 = wsi2->sibling_list;
183                         //lwsl_notice("%s: closing %p: next sibling %p\n",
184                         //              __func__, wsi2, wsi1);
185                         wsi2->parent = NULL;
186                         /* stop it doing shutdown processing */
187                         wsi2->socket_is_permanently_unusable = 1;
188                         lws_close_free_wsi(wsi2, reason);
189                         wsi2 = wsi1;
190                 }
191                 wsi->child_list = NULL;
192         }
193
194 #ifdef LWS_WITH_CGI
195         if (wsi->mode == LWSCM_CGI) {
196                 /* we are not a network connection, but a handler for CGI io */
197                 if (wsi->parent && wsi->parent->cgi)
198                         /* end the binding between us and master */
199                         wsi->parent->cgi->stdwsi[(int)wsi->cgi_channel] = NULL;
200                 wsi->socket_is_permanently_unusable = 1;
201
202                 lwsl_debug("------ %s: detected cgi fdhandler wsi %p\n", __func__, wsi);
203                 goto just_kill_connection;
204         }
205
206         if (wsi->cgi) {
207                 struct lws_cgi **pcgi = &pt->cgi_list;
208                 /* remove us from the cgi list */
209                 lwsl_debug("%s: remove cgi %p from list\n", __func__, wsi->cgi);
210                 while (*pcgi) {
211                         if (*pcgi == wsi->cgi) {
212                                 /* drop us from the pt cgi list */
213                                 *pcgi = (*pcgi)->cgi_list;
214                                 break;
215                         }
216                         pcgi = &(*pcgi)->cgi_list;
217                 }
218                 /* we have a cgi going, we must kill it */
219                 wsi->cgi->being_closed = 1;
220                 lws_cgi_kill(wsi);
221         }
222 #endif
223
224         if (wsi->mode == LWSCM_RAW) {
225                 wsi->vhost->protocols->callback(wsi,
226                         LWS_CALLBACK_RAW_CLOSE, wsi->user_space, NULL, 0);
227                 wsi->socket_is_permanently_unusable = 1;
228                 goto just_kill_connection;
229         }
230
231         if (wsi->mode == LWSCM_HTTP_SERVING_ACCEPTED &&
232             wsi->u.http.fop_fd != NULL) {
233                 lws_plat_file_close(wsi->u.http.fop_fd);
234                 wsi->u.http.fop_fd = NULL;
235                 wsi->vhost->protocols->callback(wsi,
236                         LWS_CALLBACK_CLOSED_HTTP, wsi->user_space, NULL, 0);
237                 wsi->told_user_closed = 1;
238         }
239         if (wsi->socket_is_permanently_unusable ||
240             reason == LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY ||
241             wsi->state == LWSS_SHUTDOWN)
242                 goto just_kill_connection;
243
244         wsi->state_pre_close = wsi->state;
245
246         switch (wsi->state_pre_close) {
247         case LWSS_DEAD_SOCKET:
248                 return;
249
250         /* we tried the polite way... */
251         case LWSS_AWAITING_CLOSE_ACK:
252                 goto just_kill_connection;
253
254         case LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE:
255                 if (wsi->trunc_len) {
256                         lws_callback_on_writable(wsi);
257                         return;
258                 }
259                 lwsl_info("wsi %p completed LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE\n", wsi);
260                 goto just_kill_connection;
261         default:
262                 if (wsi->trunc_len) {
263                         lwsl_info("wsi %p entering LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE\n", wsi);
264                         wsi->state = LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE;
265                         lws_set_timeout(wsi, PENDING_FLUSH_STORED_SEND_BEFORE_CLOSE, 5);
266                         return;
267                 }
268                 break;
269         }
270
271         if (wsi->mode == LWSCM_WSCL_WAITING_CONNECT ||
272             wsi->mode == LWSCM_WSCL_ISSUE_HANDSHAKE)
273                 goto just_kill_connection;
274
275         if (wsi->mode == LWSCM_HTTP_SERVING) {
276                 if (wsi->user_space)
277                         wsi->vhost->protocols->callback(wsi,
278                                                 LWS_CALLBACK_HTTP_DROP_PROTOCOL,
279                                                wsi->user_space, NULL, 0);
280                 wsi->vhost->protocols->callback(wsi, LWS_CALLBACK_CLOSED_HTTP,
281                                                wsi->user_space, NULL, 0);
282                 wsi->told_user_closed = 1;
283         }
284         if (wsi->mode & LWSCM_FLAG_IMPLIES_CALLBACK_CLOSED_CLIENT_HTTP) {
285                 wsi->vhost->protocols[0].callback(wsi, LWS_CALLBACK_CLOSED_CLIENT_HTTP,
286                                                wsi->user_space, NULL, 0);
287                 wsi->told_user_closed = 1;
288         }
289
290         /*
291          * are his extensions okay with him closing?  Eg he might be a mux
292          * parent and just his ch1 aspect is closing?
293          */
294
295         if (lws_ext_cb_active(wsi,
296                       LWS_EXT_CB_CHECK_OK_TO_REALLY_CLOSE, NULL, 0) > 0) {
297                 lwsl_ext("extension vetoed close\n");
298                 return;
299         }
300
301         /*
302          * flush any tx pending from extensions, since we may send close packet
303          * if there are problems with send, just nuke the connection
304          */
305
306         do {
307                 ret = 0;
308                 eff_buf.token = NULL;
309                 eff_buf.token_len = 0;
310
311                 /* show every extension the new incoming data */
312
313                 m = lws_ext_cb_active(wsi,
314                           LWS_EXT_CB_FLUSH_PENDING_TX, &eff_buf, 0);
315                 if (m < 0) {
316                         lwsl_ext("Extension reports fatal error\n");
317                         goto just_kill_connection;
318                 }
319                 if (m)
320                         /*
321                          * at least one extension told us he has more
322                          * to spill, so we will go around again after
323                          */
324                         ret = 1;
325
326                 /* assuming they left us something to send, send it */
327
328                 if (eff_buf.token_len)
329                         if (lws_issue_raw(wsi, (unsigned char *)eff_buf.token,
330                                           eff_buf.token_len) !=
331                             eff_buf.token_len) {
332                                 lwsl_debug("close: ext spill failed\n");
333                                 goto just_kill_connection;
334                         }
335         } while (ret);
336
337         /*
338          * signal we are closing, lws_write will
339          * add any necessary version-specific stuff.  If the write fails,
340          * no worries we are closing anyway.  If we didn't initiate this
341          * close, then our state has been changed to
342          * LWSS_RETURNED_CLOSE_ALREADY and we will skip this.
343          *
344          * Likewise if it's a second call to close this connection after we
345          * sent the close indication to the peer already, we are in state
346          * LWSS_AWAITING_CLOSE_ACK and will skip doing this a second time.
347          */
348
349         if (wsi->state_pre_close == LWSS_ESTABLISHED &&
350             (wsi->u.ws.close_in_ping_buffer_len || /* already a reason */
351              (reason != LWS_CLOSE_STATUS_NOSTATUS &&
352              (reason != LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY)))) {
353                 lwsl_debug("sending close indication...\n");
354
355                 /* if no prepared close reason, use 1000 and no aux data */
356                 if (!wsi->u.ws.close_in_ping_buffer_len) {
357                         wsi->u.ws.close_in_ping_buffer_len = 2;
358                         wsi->u.ws.ping_payload_buf[LWS_PRE] =
359                                (reason >> 8) & 0xff;
360                         wsi->u.ws.ping_payload_buf[LWS_PRE + 1] =
361                                 reason & 0xff;
362                 }
363
364 #if defined (LWS_WITH_ESP8266)
365                 wsi->close_is_pending_send_completion = 1;
366 #endif
367                 n = lws_write(wsi, &wsi->u.ws.ping_payload_buf[LWS_PRE],
368                               wsi->u.ws.close_in_ping_buffer_len,
369                               LWS_WRITE_CLOSE);
370                 if (n >= 0) {
371                         /*
372                          * we have sent a nice protocol level indication we
373                          * now wish to close, we should not send anything more
374                          */
375                         wsi->state = LWSS_AWAITING_CLOSE_ACK;
376
377                         /*
378                          * ...and we should wait for a reply for a bit
379                          * out of politeness
380                          */
381                         lws_set_timeout(wsi, PENDING_TIMEOUT_CLOSE_ACK, 1);
382                         lwsl_debug("sent close indication, awaiting ack\n");
383
384                         return;
385                 }
386
387                 lwsl_info("close: sending close packet failed, hanging up\n");
388
389                 /* else, the send failed and we should just hang up */
390         }
391
392 just_kill_connection:
393
394         if (wsi->parent) {
395                 /* detach ourselves from parent's child list */
396                 pwsi = &wsi->parent->child_list;
397                 while (*pwsi) {
398                         if (*pwsi == wsi) {
399                                 //lwsl_notice("%s: detach %p from parent %p\n",
400                                 //              __func__, wsi, wsi->parent);
401                                 *pwsi = wsi->sibling_list;
402                                 break;
403                         }
404                         pwsi = &(*pwsi)->sibling_list;
405                 }
406                 if (*pwsi)
407                         lwsl_err("%s: failed to detach from parent\n",
408                                         __func__);
409         }
410 #if 0
411         /* manage the vhost same protocol list entry */
412
413         if (wsi->same_vh_protocol_prev) { // we are on the vh list
414
415                 // make guy who pointed to us, point to what our next was pointing to
416                 *wsi->same_vh_protocol_prev = wsi->same_vh_protocol_next;
417
418                 // if we had a next guy...
419                 if (wsi->same_vh_protocol_next)
420                         // have him point back to our prev
421                         wsi->same_vh_protocol_next->same_vh_protocol_prev =
422                                         wsi->same_vh_protocol_prev;
423         }
424 #endif
425
426 #if LWS_POSIX
427         /*
428          * Testing with ab shows that we have to stage the socket close when
429          * the system is under stress... shutdown any further TX, change the
430          * state to one that won't emit anything more, and wait with a timeout
431          * for the POLLIN to show a zero-size rx before coming back and doing
432          * the actual close.
433          */
434         if (wsi->mode != LWSCM_RAW && wsi->state != LWSS_SHUTDOWN &&
435             wsi->state != LWSS_CLIENT_UNCONNECTED &&
436             reason != LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY &&
437             !wsi->socket_is_permanently_unusable) {
438 #ifdef LWS_OPENSSL_SUPPORT
439                 if (lws_is_ssl(wsi) && wsi->ssl)
440                {
441                        lwsl_info("%s: shutting down SSL connection: %p (ssl %p, sock %d, state %d)\n", __func__, wsi, wsi->ssl, (int)(long)wsi->sock, wsi->state);
442                         n = SSL_shutdown(wsi->ssl);
443                        if (n == 0) /* Complete bidirectional SSL shutdown */
444                                n = SSL_shutdown(wsi->ssl);
445                        n = shutdown(wsi->sock, SHUT_WR);
446                }
447                 else
448 #endif
449                 {
450                         lwsl_info("%s: shutting down connection: %p (sock %d, state %d)\n", __func__, wsi, (int)(long)wsi->sock, wsi->state);
451                         n = shutdown(wsi->sock, SHUT_WR);
452                 }
453                 if (n)
454                         lwsl_debug("closing: shutdown (state %d) ret %d\n", wsi->state, LWS_ERRNO);
455
456 // This causes problems with disconnection when the events are half closing connection
457 // FD_READ | FD_CLOSE (33)
458 #ifndef _WIN32_WCE
459                 /* libuv: no event available to guarantee completion */
460                 if (!LWS_LIBUV_ENABLED(context)) {
461
462                         lws_change_pollfd(wsi, LWS_POLLOUT, LWS_POLLIN);
463                         wsi->state = LWSS_SHUTDOWN;
464                         lws_set_timeout(wsi, PENDING_TIMEOUT_SHUTDOWN_FLUSH,
465                                         context->timeout_secs);
466                         return;
467                 }
468 #endif
469         }
470 #endif
471
472         lwsl_info("%s: real just_kill_connection: %p (sockfd %d)\n", __func__,
473                   wsi, wsi->sock);
474         
475 #ifdef LWS_WITH_HTTP_PROXY
476         if (wsi->rw) {
477                 lws_rewrite_destroy(wsi->rw);
478                 wsi->rw = NULL;
479         }
480 #endif
481         /*
482          * we won't be servicing or receiving anything further from this guy
483          * delete socket from the internal poll list if still present
484          */
485         lws_ssl_remove_wsi_from_buffered_list(wsi);
486
487         lws_remove_from_timeout_list(wsi);
488
489         /* checking return redundant since we anyway close */
490         if (wsi->sock != LWS_SOCK_INVALID)
491                 remove_wsi_socket_from_fds(wsi);
492
493 #if defined(LWS_WITH_ESP8266)
494         espconn_disconnect(wsi->sock);
495 #endif
496
497         wsi->state = LWSS_DEAD_SOCKET;
498
499         lws_free_set_NULL(wsi->rxflow_buffer);
500
501         if (wsi->state_pre_close == LWSS_ESTABLISHED ||
502             wsi->mode == LWSCM_WS_SERVING ||
503             wsi->mode == LWSCM_WS_CLIENT) {
504
505                 if (wsi->u.ws.rx_draining_ext) {
506                         struct lws **w = &pt->rx_draining_ext_list;
507
508                         wsi->u.ws.rx_draining_ext = 0;
509                         /* remove us from context draining ext list */
510                         while (*w) {
511                                 if (*w == wsi) {
512                                         *w = wsi->u.ws.rx_draining_ext_list;
513                                         break;
514                                 }
515                                 w = &((*w)->u.ws.rx_draining_ext_list);
516                         }
517                         wsi->u.ws.rx_draining_ext_list = NULL;
518                 }
519
520                 if (wsi->u.ws.tx_draining_ext) {
521                         struct lws **w = &pt->tx_draining_ext_list;
522
523                         wsi->u.ws.tx_draining_ext = 0;
524                         /* remove us from context draining ext list */
525                         while (*w) {
526                                 if (*w == wsi) {
527                                         *w = wsi->u.ws.tx_draining_ext_list;
528                                         break;
529                                 }
530                                 w = &((*w)->u.ws.tx_draining_ext_list);
531                         }
532                         wsi->u.ws.tx_draining_ext_list = NULL;
533                 }
534                 lws_free_set_NULL(wsi->u.ws.rx_ubuf);
535
536                 if (wsi->trunc_alloc)
537                         /* not going to be completed... nuke it */
538                         lws_free_set_NULL(wsi->trunc_alloc);
539
540                 wsi->u.ws.ping_payload_len = 0;
541                 wsi->u.ws.ping_pending_flag = 0;
542         }
543
544         /* tell the user it's all over for this guy */
545
546         if (wsi->mode != LWSCM_RAW && wsi->protocol && wsi->protocol->callback &&
547             ((wsi->state_pre_close == LWSS_ESTABLISHED) ||
548             (wsi->state_pre_close == LWSS_RETURNED_CLOSE_ALREADY) ||
549             (wsi->state_pre_close == LWSS_AWAITING_CLOSE_ACK) ||
550             (wsi->state_pre_close == LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE) ||
551             (wsi->mode == LWSCM_WS_CLIENT && wsi->state_pre_close == LWSS_HTTP) ||
552             (wsi->mode == LWSCM_WS_SERVING && wsi->state_pre_close == LWSS_HTTP))) {
553
554                 if (wsi->user_space) {
555                         lwsl_debug("%s: doing LWS_CALLBACK_HTTP_DROP_PROTOCOL for %p prot %s", __func__, wsi, wsi->protocol->name);
556                         wsi->protocol->callback(wsi,
557                                         LWS_CALLBACK_HTTP_DROP_PROTOCOL,
558                                                wsi->user_space, NULL, 0);
559                 }
560                 lwsl_debug("calling back CLOSED\n");
561                 wsi->protocol->callback(wsi, LWS_CALLBACK_CLOSED,
562                                         wsi->user_space, NULL, 0);
563         } else if (wsi->mode == LWSCM_HTTP_SERVING_ACCEPTED) {
564                 lwsl_debug("calling back CLOSED_HTTP\n");
565                 wsi->vhost->protocols->callback(wsi, LWS_CALLBACK_CLOSED_HTTP,
566                                                wsi->user_space, NULL, 0 );
567         } else if ((wsi->mode == LWSCM_WSCL_WAITING_SERVER_REPLY ||
568                    wsi->mode == LWSCM_WSCL_WAITING_CONNECT) &&
569                    !wsi->already_did_cce) {
570                         wsi->vhost->protocols[0].callback(wsi,
571                                         LWS_CALLBACK_CLIENT_CONNECTION_ERROR,
572                                         wsi->user_space, NULL, 0);
573         } else
574                 lwsl_debug("not calling back closed mode=%d state=%d\n",
575                            wsi->mode, wsi->state_pre_close);
576
577         /* deallocate any active extension contexts */
578
579         if (lws_ext_cb_active(wsi, LWS_EXT_CB_DESTROY, NULL, 0) < 0)
580                 lwsl_warn("extension destruction failed\n");
581         /*
582          * inform all extensions in case they tracked this guy out of band
583          * even though not active on him specifically
584          */
585         if (lws_ext_cb_all_exts(context, wsi,
586                        LWS_EXT_CB_DESTROY_ANY_WSI_CLOSING, NULL, 0) < 0)
587                 lwsl_warn("ext destroy wsi failed\n");
588
589         wsi->socket_is_permanently_unusable = 1;
590
591 #ifdef LWS_USE_LIBUV
592         if (LWS_LIBUV_ENABLED(context)) {
593                 lwsl_debug("%s: lws_libuv_closehandle: wsi %p\n", __func__, wsi);
594                 /* libuv has to do his own close handle processing asynchronously */
595                 lws_libuv_closehandle(wsi);
596
597                 return;
598         }
599 #endif
600
601         lws_close_free_wsi_final(wsi);
602 }
603
604 void
605 lws_close_free_wsi_final(struct lws *wsi)
606 {
607         int n;
608
609         if (!lws_ssl_close(wsi) && lws_socket_is_valid(wsi->sock)) {
610 #if LWS_POSIX
611                 //lwsl_err("*** closing sockfd %d\n", wsi->sock);
612                 n = compatible_close(wsi->sock);
613                 if (n)
614                         lwsl_debug("closing: close ret %d\n", LWS_ERRNO);
615
616 #else
617                 compatible_close(wsi->sock);
618                 (void)n;
619 #endif
620                 wsi->sock = LWS_SOCK_INVALID;
621         }
622
623         /* outermost destroy notification for wsi (user_space still intact) */
624         wsi->vhost->protocols[0].callback(wsi, LWS_CALLBACK_WSI_DESTROY,
625                                        wsi->user_space, NULL, 0);
626
627 #ifdef LWS_WITH_CGI
628         if (wsi->cgi) {
629                 for (n = 0; n < 6; n++) {
630                         if (wsi->cgi->pipe_fds[n / 2][n & 1] == 0)
631                                 lwsl_err("ZERO FD IN CGI CLOSE");
632
633                         if (wsi->cgi->pipe_fds[n / 2][n & 1] >= 0)
634                                 close(wsi->cgi->pipe_fds[n / 2][n & 1]);
635                 }
636
637                 lws_free(wsi->cgi);
638         }
639 #endif
640
641         lws_free_wsi(wsi);
642 }
643
644 LWS_VISIBLE LWS_EXTERN const char *
645 lws_get_urlarg_by_name(struct lws *wsi, const char *name, char *buf, int len)
646 {
647         int n = 0, sl = strlen(name);
648
649         while (lws_hdr_copy_fragment(wsi, buf, len,
650                           WSI_TOKEN_HTTP_URI_ARGS, n) >= 0) {
651
652                 if (!strncmp(buf, name, sl))
653                         return buf + sl;
654
655                 n++;
656         }
657
658         return NULL;
659 }
660
661 #if LWS_POSIX && !defined(LWS_WITH_ESP32)
662 LWS_VISIBLE int
663 interface_to_sa(struct lws_vhost *vh, const char *ifname, struct sockaddr_in *addr, size_t addrlen)
664 {
665         int ipv6 = 0;
666 #ifdef LWS_USE_IPV6
667         ipv6 = LWS_IPV6_ENABLED(vh);
668 #endif
669         (void)vh;
670
671         return lws_interface_to_sa(ipv6, ifname, addr, addrlen);
672 }
673 #endif
674
675 #ifndef LWS_PLAT_OPTEE
676 #if LWS_POSIX
677 static int
678 lws_get_addresses(struct lws_vhost *vh, void *ads, char *name,
679                   int name_len, char *rip, int rip_len)
680 {
681 #if LWS_POSIX
682         struct addrinfo ai, *res;
683         struct sockaddr_in addr4;
684
685         if (rip)
686                 rip[0] = '\0';
687         name[0] = '\0';
688         addr4.sin_family = AF_UNSPEC;
689
690 #ifdef LWS_USE_IPV6
691         if (LWS_IPV6_ENABLED(vh)) {
692                 if (!lws_plat_inet_ntop(AF_INET6, &((struct sockaddr_in6 *)ads)->sin6_addr, rip, rip_len)) {
693                         lwsl_err("inet_ntop: %s", strerror(LWS_ERRNO));
694                         return -1;
695                 }
696
697                 // Strip off the IPv4 to IPv6 header if one exists
698                 if (strncmp(rip, "::ffff:", 7) == 0)
699                         memmove(rip, rip + 7, strlen(rip) - 6);
700
701                 getnameinfo((struct sockaddr *)ads,
702                                 sizeof(struct sockaddr_in6), name,
703                                                         name_len, NULL, 0, 0);
704
705                 return 0;
706         } else
707 #endif
708         {
709                 struct addrinfo *result;
710
711                 memset(&ai, 0, sizeof ai);
712                 ai.ai_family = PF_UNSPEC;
713                 ai.ai_socktype = SOCK_STREAM;
714                 ai.ai_flags = AI_CANONNAME;
715 #if !defined(LWS_WITH_ESP32)
716                 if (getnameinfo((struct sockaddr *)ads,
717                                 sizeof(struct sockaddr_in),
718                                 name, name_len, NULL, 0, 0))
719                         return -1;
720 #endif
721                 if (!rip)
722                         return 0;
723
724                 if (getaddrinfo(name, NULL, &ai, &result))
725                         return -1;
726
727                 res = result;
728                 while (addr4.sin_family == AF_UNSPEC && res) {
729                         switch (res->ai_family) {
730                         case AF_INET:
731                                 addr4.sin_addr = ((struct sockaddr_in *)res->ai_addr)->sin_addr;
732                                 addr4.sin_family = AF_INET;
733                                 break;
734                         }
735
736                         res = res->ai_next;
737                 }
738                 freeaddrinfo(result);
739         }
740
741         if (addr4.sin_family == AF_UNSPEC)
742                 return -1;
743
744         if (lws_plat_inet_ntop(AF_INET, &addr4.sin_addr, rip, rip_len) == NULL)
745                 return -1;
746
747         return 0;
748 #else
749         (void)vh;
750         (void)ads;
751         (void)name;
752         (void)name_len;
753         (void)rip;
754         (void)rip_len;
755
756         return -1;
757 #endif
758 }
759 #endif
760
761
762 LWS_VISIBLE const char *
763 lws_get_peer_simple(struct lws *wsi, char *name, int namelen)
764 {
765 #if LWS_POSIX
766         socklen_t len, olen;
767 #ifdef LWS_USE_IPV6
768         struct sockaddr_in6 sin6;
769 #endif
770         struct sockaddr_in sin4;
771         int af = AF_INET;
772         void *p, *q;
773
774 #ifdef LWS_USE_IPV6
775         if (LWS_IPV6_ENABLED(wsi->vhost)) {
776                 len = sizeof(sin6);
777                 p = &sin6;
778                 af = AF_INET6;
779                 q = &sin6.sin6_addr;
780         } else
781 #endif
782         {
783                 len = sizeof(sin4);
784                 p = &sin4;
785                 q = &sin4.sin_addr;
786         }
787
788         olen = len;
789         if (getpeername(wsi->sock, p, &len) < 0 || len > olen) {
790                 lwsl_warn("getpeername: %s\n", strerror(LWS_ERRNO));
791                 return NULL;
792         }
793
794         return lws_plat_inet_ntop(af, q, name, namelen);
795 #else
796 #if defined(LWS_WITH_ESP8266)
797         return lws_plat_get_peer_simple(wsi, name, namelen);
798 #else
799         return NULL;
800 #endif
801 #endif
802 }
803 #endif
804
805 LWS_VISIBLE void
806 lws_get_peer_addresses(struct lws *wsi, lws_sockfd_type fd, char *name,
807                        int name_len, char *rip, int rip_len)
808 {
809 #ifndef LWS_PLAT_OPTEE
810 #if LWS_POSIX
811         socklen_t len;
812 #ifdef LWS_USE_IPV6
813         struct sockaddr_in6 sin6;
814 #endif
815         struct sockaddr_in sin4;
816         struct lws_context *context = wsi->context;
817         int ret = -1;
818         void *p;
819
820         rip[0] = '\0';
821         name[0] = '\0';
822
823         lws_latency_pre(context, wsi);
824
825 #ifdef LWS_USE_IPV6
826         if (LWS_IPV6_ENABLED(wsi->vhost)) {
827                 len = sizeof(sin6);
828                 p = &sin6;
829         } else
830 #endif
831         {
832                 len = sizeof(sin4);
833                 p = &sin4;
834         }
835
836         if (getpeername(fd, p, &len) < 0) {
837                 lwsl_warn("getpeername: %s\n", strerror(LWS_ERRNO));
838                 goto bail;
839         }
840
841         ret = lws_get_addresses(wsi->vhost, p, name, name_len, rip, rip_len);
842
843 bail:
844         lws_latency(context, wsi, "lws_get_peer_addresses", ret, 1);
845 #endif
846 #endif
847         (void)wsi;
848         (void)fd;
849         (void)name;
850         (void)name_len;
851         (void)rip;
852         (void)rip_len;
853
854 }
855
856 LWS_EXTERN void *
857 lws_context_user(struct lws_context *context)
858 {
859         return context->user_space;
860 }
861
862 LWS_VISIBLE struct lws_vhost *
863 lws_vhost_get(struct lws *wsi)
864 {
865         return wsi->vhost;
866 }
867
868 LWS_VISIBLE struct lws_vhost *
869 lws_get_vhost(struct lws *wsi)
870 {
871         return wsi->vhost;
872 }
873
874 LWS_VISIBLE const struct lws_protocols *
875 lws_protocol_get(struct lws *wsi)
876 {
877         return wsi->protocol;
878 }
879
880 LWS_VISIBLE LWS_EXTERN const struct lws_protocols *
881 lws_vhost_name_to_protocol(struct lws_vhost *vh, const char *name)
882 {
883         int n;
884
885         for (n = 0; n < vh->count_protocols; n++)
886                 if (!strcmp(name, vh->protocols[n].name))
887                         return &vh->protocols[n];
888
889         return NULL;
890 }
891
892 LWS_VISIBLE int
893 lws_callback_all_protocol(struct lws_context *context,
894                           const struct lws_protocols *protocol, int reason)
895 {
896         struct lws_context_per_thread *pt = &context->pt[0];
897         unsigned int n, m = context->count_threads;
898         struct lws *wsi;
899
900         while (m--) {
901                 for (n = 0; n < pt->fds_count; n++) {
902                         wsi = wsi_from_fd(context, pt->fds[n].fd);
903                         if (!wsi)
904                                 continue;
905                         if (wsi->protocol == protocol)
906                                 protocol->callback(wsi, reason, wsi->user_space,
907                                                    NULL, 0);
908                 }
909                 pt++;
910         }
911
912         return 0;
913 }
914
915 LWS_VISIBLE int
916 lws_callback_all_protocol_vhost(struct lws_vhost *vh,
917                           const struct lws_protocols *protocol, int reason)
918 {
919         struct lws_context *context = vh->context;
920         struct lws_context_per_thread *pt = &context->pt[0];
921         unsigned int n, m = context->count_threads;
922         struct lws *wsi;
923
924         while (m--) {
925                 for (n = 0; n < pt->fds_count; n++) {
926                         wsi = wsi_from_fd(context, pt->fds[n].fd);
927                         if (!wsi)
928                                 continue;
929                         if (wsi->vhost == vh && wsi->protocol == protocol)
930                                 protocol->callback(wsi, reason, wsi->user_space,
931                                                    NULL, 0);
932                 }
933                 pt++;
934         }
935
936         return 0;
937 }
938
939 LWS_VISIBLE LWS_EXTERN int
940 lws_callback_vhost_protocols(struct lws *wsi, int reason, void *in, int len)
941 {
942         int n;
943
944         for (n = 0; n < wsi->vhost->count_protocols; n++)
945                 if (wsi->vhost->protocols[n].callback(wsi, reason, NULL, in, len))
946                         return 1;
947
948         return 0;
949 }
950
951 LWS_VISIBLE LWS_EXTERN void
952 lws_set_fops(struct lws_context *context, struct lws_plat_file_ops *fops)
953 {
954         memcpy(&context->fops, fops, sizeof *fops);
955 }
956
957 /**
958  * lws_now_secs() - seconds since 1970-1-1
959  *
960  */
961 LWS_VISIBLE LWS_EXTERN unsigned long
962 lws_now_secs(void)
963 {
964         struct timeval tv;
965
966         gettimeofday(&tv, NULL);
967
968         return tv.tv_sec;
969 }
970
971
972 #if LWS_POSIX
973
974 LWS_VISIBLE int
975 lws_get_socket_fd(struct lws *wsi)
976 {
977         return wsi->sock;
978 }
979
980 #endif
981
982 #ifdef LWS_LATENCY
983 void
984 lws_latency(struct lws_context *context, struct lws *wsi, const char *action,
985             int ret, int completed)
986 {
987         unsigned long long u;
988         char buf[256];
989
990         u = time_in_microseconds();
991
992         if (!action) {
993                 wsi->latency_start = u;
994                 if (!wsi->action_start)
995                         wsi->action_start = u;
996                 return;
997         }
998         if (completed) {
999                 if (wsi->action_start == wsi->latency_start)
1000                         sprintf(buf,
1001                           "Completion first try lat %lluus: %p: ret %d: %s\n",
1002                                         u - wsi->latency_start,
1003                                                       (void *)wsi, ret, action);
1004                 else
1005                         sprintf(buf,
1006                           "Completion %lluus: lat %lluus: %p: ret %d: %s\n",
1007                                 u - wsi->action_start,
1008                                         u - wsi->latency_start,
1009                                                       (void *)wsi, ret, action);
1010                 wsi->action_start = 0;
1011         } else
1012                 sprintf(buf, "lat %lluus: %p: ret %d: %s\n",
1013                               u - wsi->latency_start, (void *)wsi, ret, action);
1014
1015         if (u - wsi->latency_start > context->worst_latency) {
1016                 context->worst_latency = u - wsi->latency_start;
1017                 strcpy(context->worst_latency_info, buf);
1018         }
1019         lwsl_latency("%s", buf);
1020 }
1021 #endif
1022
1023 LWS_VISIBLE int
1024 lws_rx_flow_control(struct lws *wsi, int enable)
1025 {
1026         if (enable == (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW))
1027                 return 0;
1028
1029         lwsl_info("%s: (0x%p, %d)\n", __func__, wsi, enable);
1030         wsi->rxflow_change_to = LWS_RXFLOW_PENDING_CHANGE | !!enable;
1031
1032         return 0;
1033 }
1034
1035 LWS_VISIBLE void
1036 lws_rx_flow_allow_all_protocol(const struct lws_context *context,
1037                                const struct lws_protocols *protocol)
1038 {
1039         const struct lws_context_per_thread *pt = &context->pt[0];
1040         struct lws *wsi;
1041         unsigned int n, m = context->count_threads;
1042
1043         while (m--) {
1044                 for (n = 0; n < pt->fds_count; n++) {
1045                         wsi = wsi_from_fd(context, pt->fds[n].fd);
1046                         if (!wsi)
1047                                 continue;
1048                         if (wsi->protocol == protocol)
1049                                 lws_rx_flow_control(wsi, LWS_RXFLOW_ALLOW);
1050                 }
1051                 pt++;
1052         }
1053 }
1054
1055 LWS_VISIBLE extern const char *
1056 lws_canonical_hostname(struct lws_context *context)
1057 {
1058         return (const char *)context->canonical_hostname;
1059 }
1060
1061 int user_callback_handle_rxflow(lws_callback_function callback_function,
1062                                 struct lws *wsi,
1063                                 enum lws_callback_reasons reason, void *user,
1064                                 void *in, size_t len)
1065 {
1066         int n;
1067
1068         n = callback_function(wsi, reason, user, in, len);
1069         if (!n)
1070                 n = _lws_rx_flow_control(wsi);
1071
1072         return n;
1073 }
1074
1075 #if defined(LWS_WITH_ESP8266)
1076 #undef strchr
1077 #define strchr ets_strchr
1078 #endif
1079
1080 LWS_VISIBLE int
1081 lws_set_proxy(struct lws_vhost *vhost, const char *proxy)
1082 {
1083 #if !defined(LWS_WITH_ESP8266)
1084         char *p;
1085         char authstring[96];
1086
1087         if (!proxy)
1088                 return -1;
1089
1090         /* we have to deal with a possible redundant leading http:// */
1091         if (!strncmp(proxy, "http://", 7))
1092                 proxy += 7;
1093
1094         p = strchr(proxy, '@');
1095         if (p) { /* auth is around */
1096
1097                 if ((unsigned int)(p - proxy) > sizeof(authstring) - 1)
1098                         goto auth_too_long;
1099
1100                 strncpy(authstring, proxy, p - proxy);
1101                 // null termination not needed on input
1102                 if (lws_b64_encode_string(authstring, (p - proxy),
1103                                 vhost->proxy_basic_auth_token,
1104                     sizeof vhost->proxy_basic_auth_token) < 0)
1105                         goto auth_too_long;
1106
1107                 lwsl_info(" Proxy auth in use\n");
1108
1109                 proxy = p + 1;
1110         } else
1111                 vhost->proxy_basic_auth_token[0] = '\0';
1112
1113         strncpy(vhost->http_proxy_address, proxy,
1114                                 sizeof(vhost->http_proxy_address) - 1);
1115         vhost->http_proxy_address[
1116                                 sizeof(vhost->http_proxy_address) - 1] = '\0';
1117
1118         p = strchr(vhost->http_proxy_address, ':');
1119         if (!p && !vhost->http_proxy_port) {
1120                 lwsl_err("http_proxy needs to be ads:port\n");
1121
1122                 return -1;
1123         } else {
1124                 if (p) {
1125                         *p = '\0';
1126                         vhost->http_proxy_port = atoi(p + 1);
1127                 }
1128         }
1129
1130         lwsl_info(" Proxy %s:%u\n", vhost->http_proxy_address,
1131                         vhost->http_proxy_port);
1132
1133         return 0;
1134
1135 auth_too_long:
1136         lwsl_err("proxy auth too long\n");
1137 #endif
1138         return -1;
1139 }
1140
1141 LWS_VISIBLE const struct lws_protocols *
1142 lws_get_protocol(struct lws *wsi)
1143 {
1144         return wsi->protocol;
1145 }
1146
1147 LWS_VISIBLE int
1148 lws_is_final_fragment(struct lws *wsi)
1149 {
1150         lwsl_info("%s: final %d, rx pk length %ld, draining %ld", __func__,
1151                         wsi->u.ws.final, (long)wsi->u.ws.rx_packet_length,
1152                         (long)wsi->u.ws.rx_draining_ext);
1153         return wsi->u.ws.final && !wsi->u.ws.rx_packet_length && !wsi->u.ws.rx_draining_ext;
1154 }
1155
1156 LWS_VISIBLE unsigned char
1157 lws_get_reserved_bits(struct lws *wsi)
1158 {
1159         return wsi->u.ws.rsv;
1160 }
1161
1162 int
1163 lws_ensure_user_space(struct lws *wsi)
1164 {
1165         lwsl_info("%s: %p protocol %p\n", __func__, wsi, wsi->protocol);
1166         if (!wsi->protocol)
1167                 return 1;
1168
1169         /* allocate the per-connection user memory (if any) */
1170
1171         if (wsi->protocol->per_session_data_size && !wsi->user_space) {
1172                 wsi->user_space = lws_zalloc(wsi->protocol->per_session_data_size);
1173                 if (wsi->user_space  == NULL) {
1174                         lwsl_err("Out of memory for conn user space\n");
1175                         return 1;
1176                 }
1177         } else
1178                 lwsl_info("%s: %p protocol pss %lu, user_space=%p\n",
1179                           __func__, wsi, (long)wsi->protocol->per_session_data_size,
1180                           wsi->user_space);
1181         return 0;
1182 }
1183
1184 LWS_VISIBLE int
1185 lwsl_timestamp(int level, char *p, int len)
1186 {
1187 #ifndef LWS_PLAT_OPTEE
1188         time_t o_now = time(NULL);
1189         unsigned long long now;
1190         struct tm *ptm = NULL;
1191 #ifndef WIN32
1192         struct tm tm;
1193 #endif
1194         int n;
1195
1196 #ifndef _WIN32_WCE
1197 #ifdef WIN32
1198         ptm = localtime(&o_now);
1199 #else
1200         if (localtime_r(&o_now, &tm))
1201                 ptm = &tm;
1202 #endif
1203 #endif
1204         p[0] = '\0';
1205         for (n = 0; n < LLL_COUNT; n++) {
1206                 if (level != (1 << n))
1207                         continue;
1208                 now = time_in_microseconds() / 100;
1209                 if (ptm)
1210                         n = lws_snprintf(p, len,
1211                                 "[%04d/%02d/%02d %02d:%02d:%02d:%04d] %s: ",
1212                                 ptm->tm_year + 1900,
1213                                 ptm->tm_mon + 1,
1214                                 ptm->tm_mday,
1215                                 ptm->tm_hour,
1216                                 ptm->tm_min,
1217                                 ptm->tm_sec,
1218                                 (int)(now % 10000), log_level_names[n]);
1219                 else
1220                         n = lws_snprintf(p, len, "[%llu:%04d] %s: ",
1221                                         (unsigned long long) now / 10000,
1222                                         (int)(now % 10000), log_level_names[n]);
1223                 return n;
1224         }
1225 #endif
1226         return 0;
1227 }
1228
1229 #ifndef LWS_PLAT_OPTEE
1230 LWS_VISIBLE void lwsl_emit_stderr(int level, const char *line)
1231 {
1232 #if !defined(LWS_WITH_ESP8266)
1233         char buf[50];
1234
1235         lwsl_timestamp(level, buf, sizeof(buf));
1236         fprintf(stderr, "%s%s", buf, line);
1237 #endif
1238 }
1239 #endif
1240
1241 LWS_VISIBLE void _lws_logv(int filter, const char *format, va_list vl)
1242 {
1243 #if defined(LWS_WITH_ESP8266)
1244         char buf[128];
1245 #else
1246         char buf[256];
1247 #endif
1248         int n;
1249
1250         if (!(log_level & filter))
1251                 return;
1252
1253         n = vsnprintf(buf, sizeof(buf) - 1, format, vl);
1254         (void)n;
1255 #if defined(LWS_WITH_ESP8266)
1256         buf[sizeof(buf) - 1] = '\0';
1257 #else
1258         /* vnsprintf returns what it would have written, even if truncated */
1259         if (n > sizeof(buf) - 1)
1260                 n = sizeof(buf) - 1;
1261         if (n > 0)
1262                 buf[n] = '\0';
1263 #endif
1264
1265         lwsl_emit(filter, buf);
1266 }
1267
1268 LWS_VISIBLE void _lws_log(int filter, const char *format, ...)
1269 {
1270         va_list ap;
1271
1272         va_start(ap, format);
1273         _lws_logv(filter, format, ap);
1274         va_end(ap);
1275 }
1276
1277 LWS_VISIBLE void lws_set_log_level(int level,
1278                                    void (*func)(int level, const char *line))
1279 {
1280         log_level = level;
1281         if (func)
1282                 lwsl_emit = func;
1283 }
1284
1285 LWS_VISIBLE int lwsl_visible(int level)
1286 {
1287         return log_level & level;
1288 }
1289
1290 LWS_VISIBLE int
1291 lws_is_ssl(struct lws *wsi)
1292 {
1293 #ifdef LWS_OPENSSL_SUPPORT
1294         return wsi->use_ssl;
1295 #else
1296         (void)wsi;
1297         return 0;
1298 #endif
1299 }
1300
1301 #ifdef LWS_OPENSSL_SUPPORT
1302 LWS_VISIBLE SSL*
1303 lws_get_ssl(struct lws *wsi)
1304 {
1305         return wsi->ssl;
1306 }
1307 #endif
1308
1309 LWS_VISIBLE int
1310 lws_partial_buffered(struct lws *wsi)
1311 {
1312         return !!wsi->trunc_len;
1313 }
1314
1315 void lws_set_protocol_write_pending(struct lws *wsi,
1316                                     enum lws_pending_protocol_send pend)
1317 {
1318         lwsl_info("setting pps %d\n", pend);
1319
1320         if (wsi->pps)
1321                 lwsl_err("pps overwrite\n");
1322         wsi->pps = pend;
1323         lws_rx_flow_control(wsi, 0);
1324         lws_callback_on_writable(wsi);
1325 }
1326
1327 LWS_VISIBLE size_t
1328 lws_get_peer_write_allowance(struct lws *wsi)
1329 {
1330 #ifdef LWS_USE_HTTP2
1331         /* only if we are using HTTP2 on this connection */
1332         if (wsi->mode != LWSCM_HTTP2_SERVING)
1333                 return -1;
1334         /* user is only interested in how much he can send, or that he can't  */
1335         if (wsi->u.http2.tx_credit <= 0)
1336                 return 0;
1337
1338         return wsi->u.http2.tx_credit;
1339 #else
1340         (void)wsi;
1341         return -1;
1342 #endif
1343 }
1344
1345 LWS_VISIBLE void
1346 lws_union_transition(struct lws *wsi, enum connection_mode mode)
1347 {
1348         lwsl_debug("%s: %p: mode %d\n", __func__, wsi, mode);
1349         memset(&wsi->u, 0, sizeof(wsi->u));
1350         wsi->mode = mode;
1351 }
1352
1353 LWS_VISIBLE struct lws_plat_file_ops *
1354 lws_get_fops(struct lws_context *context)
1355 {
1356         return &context->fops;
1357 }
1358
1359 LWS_VISIBLE LWS_EXTERN struct lws_context *
1360 lws_get_context(const struct lws *wsi)
1361 {
1362         return wsi->context;
1363 }
1364
1365 LWS_VISIBLE LWS_EXTERN int
1366 lws_get_count_threads(struct lws_context *context)
1367 {
1368         return context->count_threads;
1369 }
1370
1371 LWS_VISIBLE LWS_EXTERN void *
1372 lws_wsi_user(struct lws *wsi)
1373 {
1374         return wsi->user_space;
1375 }
1376
1377 LWS_VISIBLE LWS_EXTERN struct lws *
1378 lws_get_parent(const struct lws *wsi)
1379 {
1380         return wsi->parent;
1381 }
1382
1383 LWS_VISIBLE LWS_EXTERN struct lws *
1384 lws_get_child(const struct lws *wsi)
1385 {
1386         return wsi->child_list;
1387 }
1388
1389 LWS_VISIBLE LWS_EXTERN void
1390 lws_close_reason(struct lws *wsi, enum lws_close_status status,
1391                  unsigned char *buf, size_t len)
1392 {
1393         unsigned char *p, *start;
1394         int budget = sizeof(wsi->u.ws.ping_payload_buf) - LWS_PRE;
1395
1396         assert(wsi->mode == LWSCM_WS_SERVING || wsi->mode == LWSCM_WS_CLIENT);
1397
1398         start = p = &wsi->u.ws.ping_payload_buf[LWS_PRE];
1399
1400         *p++ = (((int)status) >> 8) & 0xff;
1401         *p++ = ((int)status) & 0xff;
1402
1403         if (buf)
1404                 while (len-- && p < start + budget)
1405                         *p++ = *buf++;
1406
1407         wsi->u.ws.close_in_ping_buffer_len = p - start;
1408 }
1409
1410 LWS_EXTERN int
1411 _lws_rx_flow_control(struct lws *wsi)
1412 {
1413         /* there is no pending change */
1414         if (!(wsi->rxflow_change_to & LWS_RXFLOW_PENDING_CHANGE)) {
1415                 lwsl_debug("%s: no pending change\n", __func__);
1416                 return 0;
1417         }
1418
1419         /* stuff is still buffered, not ready to really accept new input */
1420         if (wsi->rxflow_buffer) {
1421                 /* get ourselves called back to deal with stashed buffer */
1422                 lws_callback_on_writable(wsi);
1423                 return 0;
1424         }
1425
1426         /* pending is cleared, we can change rxflow state */
1427
1428         wsi->rxflow_change_to &= ~LWS_RXFLOW_PENDING_CHANGE;
1429
1430         lwsl_info("rxflow: wsi %p change_to %d\n", wsi,
1431                               wsi->rxflow_change_to & LWS_RXFLOW_ALLOW);
1432
1433         /* adjust the pollfd for this wsi */
1434
1435         if (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW) {
1436                 if (lws_change_pollfd(wsi, 0, LWS_POLLIN)) {
1437                         lwsl_info("%s: fail\n", __func__);
1438                         return -1;
1439                 }
1440         } else
1441                 if (lws_change_pollfd(wsi, LWS_POLLIN, 0))
1442                         return -1;
1443
1444         return 0;
1445 }
1446
1447 LWS_EXTERN int
1448 lws_check_utf8(unsigned char *state, unsigned char *buf, size_t len)
1449 {
1450         static const unsigned char e0f4[] = {
1451                 0xa0 | ((2 - 1) << 2) | 1, /* e0 */
1452                 0x80 | ((4 - 1) << 2) | 1, /* e1 */
1453                 0x80 | ((4 - 1) << 2) | 1, /* e2 */
1454                 0x80 | ((4 - 1) << 2) | 1, /* e3 */
1455                 0x80 | ((4 - 1) << 2) | 1, /* e4 */
1456                 0x80 | ((4 - 1) << 2) | 1, /* e5 */
1457                 0x80 | ((4 - 1) << 2) | 1, /* e6 */
1458                 0x80 | ((4 - 1) << 2) | 1, /* e7 */
1459                 0x80 | ((4 - 1) << 2) | 1, /* e8 */
1460                 0x80 | ((4 - 1) << 2) | 1, /* e9 */
1461                 0x80 | ((4 - 1) << 2) | 1, /* ea */
1462                 0x80 | ((4 - 1) << 2) | 1, /* eb */
1463                 0x80 | ((4 - 1) << 2) | 1, /* ec */
1464                 0x80 | ((2 - 1) << 2) | 1, /* ed */
1465                 0x80 | ((4 - 1) << 2) | 1, /* ee */
1466                 0x80 | ((4 - 1) << 2) | 1, /* ef */
1467                 0x90 | ((3 - 1) << 2) | 2, /* f0 */
1468                 0x80 | ((4 - 1) << 2) | 2, /* f1 */
1469                 0x80 | ((4 - 1) << 2) | 2, /* f2 */
1470                 0x80 | ((4 - 1) << 2) | 2, /* f3 */
1471                 0x80 | ((1 - 1) << 2) | 2, /* f4 */
1472
1473                 0,                         /* s0 */
1474                 0x80 | ((4 - 1) << 2) | 0, /* s2 */
1475                 0x80 | ((4 - 1) << 2) | 1, /* s3 */
1476         };
1477         unsigned char s = *state;
1478
1479         while (len--) {
1480                 unsigned char c = *buf++;
1481
1482                 if (!s) {
1483                         if (c >= 0x80) {
1484                                 if (c < 0xc2 || c > 0xf4)
1485                                         return 1;
1486                                 if (c < 0xe0)
1487                                         s = 0x80 | ((4 - 1) << 2);
1488                                 else
1489                                         s = e0f4[c - 0xe0];
1490                         }
1491                 } else {
1492                         if (c < (s & 0xf0) ||
1493                             c >= (s & 0xf0) + 0x10 + ((s << 2) & 0x30))
1494                                 return 1;
1495                         s = e0f4[21 + (s & 3)];
1496                 }
1497         }
1498
1499         *state = s;
1500
1501         return 0;
1502 }
1503
1504 LWS_VISIBLE LWS_EXTERN int
1505 lws_parse_uri(char *p, const char **prot, const char **ads, int *port,
1506               const char **path)
1507 {
1508         const char *end;
1509         static const char *slash = "/";
1510
1511         /* cut up the location into address, port and path */
1512         *prot = p;
1513         while (*p && (*p != ':' || p[1] != '/' || p[2] != '/'))
1514                 p++;
1515         if (!*p) {
1516                 end = p;
1517                 p = (char *)*prot;
1518                 *prot = end;
1519         } else {
1520                 *p = '\0';
1521                 p += 3;
1522         }
1523         *ads = p;
1524         if (!strcmp(*prot, "http") || !strcmp(*prot, "ws"))
1525                 *port = 80;
1526         else if (!strcmp(*prot, "https") || !strcmp(*prot, "wss"))
1527                 *port = 443;
1528
1529        if (*p == '[')
1530        {
1531                ++(*ads);
1532                while (*p && *p != ']')
1533                        p++;
1534                if (*p)
1535                        *p++ = '\0';
1536        }
1537        else
1538        {
1539                while (*p && *p != ':' && *p != '/')
1540                        p++;
1541        }
1542         if (*p == ':') {
1543                 *p++ = '\0';
1544                 *port = atoi(p);
1545                 while (*p && *p != '/')
1546                         p++;
1547         }
1548         *path = slash;
1549         if (*p) {
1550                 *p++ = '\0';
1551                 if (*p)
1552                         *path = p;
1553         }
1554
1555         return 0;
1556 }
1557
1558 #ifdef LWS_NO_EXTENSIONS
1559
1560 /* we need to provide dummy callbacks for internal exts
1561  * so user code runs when faced with a lib compiled with
1562  * extensions disabled.
1563  */
1564
1565 int
1566 lws_extension_callback_pm_deflate(struct lws_context *context,
1567                                   const struct lws_extension *ext,
1568                                   struct lws *wsi,
1569                                   enum lws_extension_callback_reasons reason,
1570                                   void *user, void *in, size_t len)
1571 {
1572         (void)context;
1573         (void)ext;
1574         (void)wsi;
1575         (void)reason;
1576         (void)user;
1577         (void)in;
1578         (void)len;
1579
1580         return 0;
1581 }
1582 #endif
1583
1584 LWS_EXTERN int
1585 lws_socket_bind(struct lws_vhost *vhost, lws_sockfd_type sockfd, int port,
1586                 const char *iface)
1587 {
1588 #if LWS_POSIX
1589 #ifdef LWS_USE_UNIX_SOCK
1590         struct sockaddr_un serv_unix;
1591 #endif
1592 #ifdef LWS_USE_IPV6
1593         struct sockaddr_in6 serv_addr6;
1594 #endif
1595         struct sockaddr_in serv_addr4;
1596 #ifndef LWS_PLAT_OPTEE
1597         socklen_t len = sizeof(struct sockaddr);
1598 #endif
1599         int n;
1600         struct sockaddr_in sin;
1601         struct sockaddr *v;
1602
1603 #ifdef LWS_USE_UNIX_SOCK
1604         if (LWS_UNIX_SOCK_ENABLED(vhost)) {
1605                 v = (struct sockaddr *)&serv_unix;
1606                 n = sizeof(struct sockaddr_un);
1607                 bzero((char *) &serv_unix, sizeof(serv_unix));
1608                 serv_unix.sun_family = AF_UNIX;
1609                 if (sizeof(serv_unix.sun_path) <= strlen(iface)) {
1610                         lwsl_err("\"%s\" too long for UNIX domain socket\n",
1611                                  iface);
1612                         return -1;
1613                 }
1614                 strcpy(serv_unix.sun_path, iface);
1615                 if (serv_unix.sun_path[0] == '@')
1616                         serv_unix.sun_path[0] = '\0';
1617
1618         } else
1619 #endif
1620 #if defined(LWS_USE_IPV6) && !defined(LWS_WITH_ESP32)
1621         if (LWS_IPV6_ENABLED(vhost)) {
1622                 v = (struct sockaddr *)&serv_addr6;
1623                 n = sizeof(struct sockaddr_in6);
1624                 bzero((char *) &serv_addr6, sizeof(serv_addr6));
1625                 if (iface &&
1626                     interface_to_sa(vhost, iface,
1627                                     (struct sockaddr_in *)v, n) < 0) {
1628                         lwsl_err("Unable to find interface %s\n", iface);
1629                         return -1;
1630                 }
1631
1632                 if (iface) {
1633                         struct ifaddrs *addrs, *addr;
1634                         char ip[NI_MAXHOST];
1635                         unsigned int i;
1636
1637                         getifaddrs(&addrs);
1638                         for (addr = addrs; addr; addr = addr->ifa_next) {
1639                                 if (!addr->ifa_addr ||
1640                                     addr->ifa_addr->sa_family != AF_INET6)
1641                                         continue;
1642
1643                                 getnameinfo(addr->ifa_addr,
1644                                             sizeof(struct sockaddr_in6),
1645                                             ip, sizeof(ip),
1646                                             NULL, 0, NI_NUMERICHOST);
1647
1648                                 i = 0;
1649                                 while (ip[i])
1650                                         if (ip[i++] == '%') {
1651                                                 ip[i - 1] = '\0';
1652                                                 break;
1653                                         }
1654
1655                                 if (!strcmp(ip, iface)) {
1656                                         serv_addr6.sin6_scope_id =
1657                                                 if_nametoindex(addr->ifa_name);
1658                                         break;
1659                                 }
1660                         }
1661                         freeifaddrs(addrs);
1662                 }
1663
1664                 serv_addr6.sin6_family = AF_INET6;
1665                 serv_addr6.sin6_port = htons(port);
1666         } else
1667 #endif
1668         {
1669                 v = (struct sockaddr *)&serv_addr4;
1670                 n = sizeof(serv_addr4);
1671                 bzero((char *) &serv_addr4, sizeof(serv_addr4));
1672                 serv_addr4.sin_addr.s_addr = INADDR_ANY;
1673                 serv_addr4.sin_family = AF_INET;
1674 #if !defined(LWS_WITH_ESP32)
1675
1676                 if (iface &&
1677                     interface_to_sa(vhost, iface,
1678                                     (struct sockaddr_in *)v, n) < 0) {
1679                         lwsl_err("Unable to find interface %s\n", iface);
1680                         return -1;
1681                 }
1682 #endif
1683                 serv_addr4.sin_port = htons(port);
1684         } /* ipv4 */
1685
1686         n = bind(sockfd, v, n);
1687 #ifdef LWS_USE_UNIX_SOCK
1688         if (n < 0 && LWS_UNIX_SOCK_ENABLED(vhost)) {
1689                 lwsl_err("ERROR on binding fd %d to \"%s\" (%d %d)\n",
1690                                 sockfd, iface, n, LWS_ERRNO);
1691                 return -1;
1692         } else
1693 #endif
1694         if (n < 0) {
1695                 lwsl_err("ERROR on binding fd %d to port %d (%d %d)\n",
1696                                 sockfd, port, n, LWS_ERRNO);
1697                 return -1;
1698         }
1699
1700 #ifndef LWS_PLAT_OPTEE
1701         if (getsockname(sockfd, (struct sockaddr *)&sin, &len) == -1)
1702                 lwsl_warn("getsockname: %s\n", strerror(LWS_ERRNO));
1703         else
1704 #endif
1705                 port = ntohs(sin.sin_port);
1706 #endif
1707
1708         return port;
1709 }
1710
1711 LWS_EXTERN void
1712 lws_restart_ws_ping_pong_timer(struct lws *wsi)
1713 {
1714         if (!wsi->context->ws_ping_pong_interval)
1715                 return;
1716         if (wsi->state != LWSS_ESTABLISHED)
1717                 return;
1718
1719         wsi->u.ws.time_next_ping_check = (time_t)lws_now_secs() +
1720                                     wsi->context->ws_ping_pong_interval;
1721 }
1722
1723 static const char *hex = "0123456789ABCDEF";
1724
1725 LWS_VISIBLE LWS_EXTERN const char *
1726 lws_sql_purify(char *escaped, const char *string, int len)
1727 {
1728         const char *p = string;
1729         char *q = escaped;
1730
1731         while (*p && len-- > 2) {
1732                 if (*p == '\'') {
1733                         *q++ = '\'';
1734                         *q++ = '\'';
1735                         len --;
1736                         p++;
1737                 } else
1738                         *q++ = *p++;
1739         }
1740         *q = '\0';
1741
1742         return escaped;
1743 }
1744
1745 LWS_VISIBLE LWS_EXTERN const char *
1746 lws_json_purify(char *escaped, const char *string, int len)
1747 {
1748         const char *p = string;
1749         char *q = escaped;
1750
1751         if (!p) {
1752                 escaped[0] = '\0';
1753                 return escaped;
1754         }
1755
1756         while (*p && len-- > 6) {
1757                 if (*p == '\"' || *p == '\\' || *p < 0x20) {
1758                         *q++ = '\\';
1759                         *q++ = 'u';
1760                         *q++ = '0';
1761                         *q++ = '0';
1762                         *q++ = hex[((*p) >> 4) & 15];
1763                         *q++ = hex[(*p) & 15];
1764                         len -= 5;
1765                         p++;
1766                 } else
1767                         *q++ = *p++;
1768         }
1769         *q = '\0';
1770
1771         return escaped;
1772 }
1773
1774 LWS_VISIBLE LWS_EXTERN const char *
1775 lws_urlencode(char *escaped, const char *string, int len)
1776 {
1777         const char *p = string;
1778         char *q = escaped;
1779
1780         while (*p && len-- > 3) {
1781                 if (*p == ' ') {
1782                         *q++ = '+';
1783                         p++;
1784                         continue;
1785                 }
1786                 if ((*p >= '0' && *p <= '9') ||
1787                     (*p >= 'A' && *p <= 'Z') ||
1788                     (*p >= 'a' && *p <= 'z')) {
1789                         *q++ = *p++;
1790                         continue;
1791                 }
1792                 *q++ = '%';
1793                 *q++ = hex[(*p >> 4) & 0xf];
1794                 *q++ = hex[*p & 0xf];
1795
1796                 len -= 2;
1797                 p++;
1798         }
1799         *q = '\0';
1800
1801         return escaped;
1802 }
1803
1804 LWS_VISIBLE LWS_EXTERN int
1805 lws_urldecode(char *string, const char *escaped, int len)
1806 {
1807         int state = 0, n;
1808         char sum = 0;
1809
1810         while (*escaped && len) {
1811                 switch (state) {
1812                 case 0:
1813                         if (*escaped == '%') {
1814                                 state++;
1815                                 escaped++;
1816                                 continue;
1817                         }
1818                         if (*escaped == '+') {
1819                                 escaped++;
1820                                 *string++ = ' ';
1821                                 len--;
1822                                 continue;
1823                         }
1824                         *string++ = *escaped++;
1825                         len--;
1826                         break;
1827                 case 1:
1828                         n = char_to_hex(*escaped);
1829                         if (n < 0)
1830                                 return -1;
1831                         escaped++;
1832                         sum = n << 4;
1833                         state++;
1834                         break;
1835
1836                 case 2:
1837                         n = char_to_hex(*escaped);
1838                         if (n < 0)
1839                                 return -1;
1840                         escaped++;
1841                         *string++ = sum | n;
1842                         len--;
1843                         state = 0;
1844                         break;
1845                 }
1846
1847         }
1848         *string = '\0';
1849
1850         return 0;
1851 }
1852
1853 LWS_VISIBLE LWS_EXTERN int
1854 lws_finalize_startup(struct lws_context *context)
1855 {
1856         struct lws_context_creation_info info;
1857
1858         info.uid = context->uid;
1859         info.gid = context->gid;
1860
1861         if (lws_check_opt(context->options, LWS_SERVER_OPTION_EXPLICIT_VHOSTS))
1862                 lws_plat_drop_app_privileges(&info);
1863
1864         return 0;
1865 }
1866
1867 int
1868 lws_snprintf(char *str, size_t size, const char *format, ...)
1869 {
1870         va_list ap;
1871         int n;
1872
1873         if (!size)
1874                 return 0;
1875
1876         va_start(ap, format);
1877         n = vsnprintf(str, size, format, ap);
1878         va_end(ap);
1879
1880         if (n >= size)
1881                 return size;
1882
1883         return n;
1884 }
1885
1886
1887 LWS_VISIBLE LWS_EXTERN int
1888 lws_is_cgi(struct lws *wsi) {
1889 #ifdef LWS_WITH_CGI
1890         return !!wsi->cgi;
1891 #else
1892         return 0;
1893 #endif
1894 }
1895
1896 #ifdef LWS_WITH_CGI
1897
1898 static int
1899 urlencode(const char *in, int inlen, char *out, int outlen)
1900 {
1901         char *start = out, *end = out + outlen;
1902
1903         while (inlen-- && out < end - 4) {
1904                 if ((*in >= 'A' && *in <= 'Z') ||
1905                     (*in >= 'a' && *in <= 'z') ||
1906                     (*in >= '0' && *in <= '9') ||
1907                     *in == '-' ||
1908                     *in == '_' ||
1909                     *in == '.' ||
1910                     *in == '~') {
1911                         *out++ = *in++;
1912                         continue;
1913                 }
1914                 if (*in == ' ') {
1915                         *out++ = '+';
1916                         in++;
1917                         continue;
1918                 }
1919                 *out++ = '%';
1920                 *out++ = hex[(*in) >> 4];
1921                 *out++ = hex[(*in++) & 15];
1922         }
1923         *out = '\0';
1924
1925         if (out >= end - 4)
1926                 return -1;
1927
1928         return out - start;
1929 }
1930
1931 static struct lws *
1932 lws_create_basic_wsi(struct lws_context *context, int tsi)
1933 {
1934         struct lws *new_wsi;
1935
1936         if ((unsigned int)context->pt[tsi].fds_count ==
1937             context->fd_limit_per_thread - 1) {
1938                 lwsl_err("no space for new conn\n");
1939                 return NULL;
1940         }
1941
1942         new_wsi = lws_zalloc(sizeof(struct lws));
1943         if (new_wsi == NULL) {
1944                 lwsl_err("Out of memory for new connection\n");
1945                 return NULL;
1946         }
1947
1948         new_wsi->tsi = tsi;
1949         new_wsi->context = context;
1950         new_wsi->pending_timeout = NO_PENDING_TIMEOUT;
1951         new_wsi->rxflow_change_to = LWS_RXFLOW_ALLOW;
1952
1953         /* initialize the instance struct */
1954
1955         new_wsi->state = LWSS_CGI;
1956         new_wsi->mode = LWSCM_CGI;
1957         new_wsi->hdr_parsing_completed = 0;
1958         new_wsi->position_in_fds_table = -1;
1959
1960         /*
1961          * these can only be set once the protocol is known
1962          * we set an unestablished connection's protocol pointer
1963          * to the start of the defauly vhost supported list, so it can look
1964          * for matching ones during the handshake
1965          */
1966         new_wsi->protocol = context->vhost_list->protocols;
1967         new_wsi->user_space = NULL;
1968         new_wsi->ietf_spec_revision = 0;
1969         new_wsi->sock = LWS_SOCK_INVALID;
1970         context->count_wsi_allocated++;
1971
1972         return new_wsi;
1973 }
1974
1975 LWS_VISIBLE LWS_EXTERN int
1976 lws_cgi(struct lws *wsi, const char * const *exec_array, int script_uri_path_len,
1977         int timeout_secs, const struct lws_protocol_vhost_options *mp_cgienv)
1978 {
1979         struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
1980         char *env_array[30], cgi_path[400], e[1024], *p = e,
1981              *end = p + sizeof(e) - 1, tok[256], *t;
1982         struct lws_cgi *cgi;
1983         int n, m, i, uritok = -1;
1984
1985         /*
1986          * give the master wsi a cgi struct
1987          */
1988
1989         wsi->cgi = lws_zalloc(sizeof(*wsi->cgi));
1990         if (!wsi->cgi) {
1991                 lwsl_err("%s: OOM\n", __func__);
1992                 return -1;
1993         }
1994
1995         cgi = wsi->cgi;
1996         cgi->wsi = wsi; /* set cgi's owning wsi */
1997
1998         /* create pipes for [stdin|stdout] and [stderr] */
1999
2000         for (n = 0; n < 3; n++)
2001                 if (pipe(cgi->pipe_fds[n]) == -1)
2002                         goto bail1;
2003
2004         /* create cgi wsis for each stdin/out/err fd */
2005
2006         for (n = 0; n < 3; n++) {
2007                 cgi->stdwsi[n] = lws_create_basic_wsi(wsi->context, wsi->tsi);
2008                 if (!cgi->stdwsi[n])
2009                         goto bail2;
2010                 cgi->stdwsi[n]->cgi_channel = n;
2011                 cgi->stdwsi[n]->vhost = wsi->vhost;
2012
2013 //              lwsl_err("%s: cgi %p: pipe fd %d -> fd %d / %d\n", __func__, wsi, n,
2014 //                       cgi->pipe_fds[n][!!(n == 0)], cgi->pipe_fds[n][!(n == 0)]);
2015
2016                 /* read side is 0, stdin we want the write side, others read */
2017                 cgi->stdwsi[n]->sock = cgi->pipe_fds[n][!!(n == 0)];
2018                 if (fcntl(cgi->pipe_fds[n][!!(n == 0)], F_SETFL, O_NONBLOCK) < 0) {
2019                         lwsl_err("%s: setting NONBLOCK failed\n", __func__);
2020                         goto bail2;
2021                 }
2022         }
2023
2024         for (n = 0; n < 3; n++) {
2025                 lws_libuv_accept(cgi->stdwsi[n], cgi->stdwsi[n]->sock);
2026                 if (insert_wsi_socket_into_fds(wsi->context, cgi->stdwsi[n]))
2027                         goto bail3;
2028                 cgi->stdwsi[n]->parent = wsi;
2029                 cgi->stdwsi[n]->sibling_list = wsi->child_list;
2030                 wsi->child_list = cgi->stdwsi[n];
2031         }
2032
2033         lws_change_pollfd(cgi->stdwsi[LWS_STDIN], LWS_POLLIN, LWS_POLLOUT);
2034         lws_change_pollfd(cgi->stdwsi[LWS_STDOUT], LWS_POLLOUT, LWS_POLLIN);
2035         lws_change_pollfd(cgi->stdwsi[LWS_STDERR], LWS_POLLOUT, LWS_POLLIN);
2036
2037         lwsl_debug("%s: fds in %d, out %d, err %d\n", __func__,
2038                    cgi->stdwsi[LWS_STDIN]->sock, cgi->stdwsi[LWS_STDOUT]->sock,
2039                    cgi->stdwsi[LWS_STDERR]->sock);
2040
2041         lws_set_timeout(wsi, PENDING_TIMEOUT_CGI, timeout_secs);
2042
2043         /* the cgi stdout is always sending us http1.x header data first */
2044         wsi->hdr_state = LCHS_HEADER;
2045
2046         /* add us to the pt list of active cgis */
2047         lwsl_debug("%s: adding cgi %p to list\n", __func__, wsi->cgi);
2048         cgi->cgi_list = pt->cgi_list;
2049         pt->cgi_list = cgi;
2050
2051         /* prepare his CGI env */
2052
2053         n = 0;
2054
2055         if (lws_is_ssl(wsi))
2056                 env_array[n++] = "HTTPS=ON";
2057         if (wsi->u.hdr.ah) {
2058                 static const unsigned char meths[] = {
2059                         WSI_TOKEN_GET_URI,
2060                         WSI_TOKEN_POST_URI,
2061                         WSI_TOKEN_OPTIONS_URI,
2062                         WSI_TOKEN_PUT_URI,
2063                         WSI_TOKEN_PATCH_URI,
2064                         WSI_TOKEN_DELETE_URI,
2065                 };
2066                 static const char * const meth_names[] = {
2067                         "GET", "POST", "OPTIONS", "PUT", "PATCH", "DELETE",
2068                 };
2069
2070                 for (m = 0; m < ARRAY_SIZE(meths); m++)
2071                         if (lws_hdr_total_length(wsi, meths[m]) >=
2072                                         script_uri_path_len) {
2073                                 uritok = meths[m];
2074                                 break;
2075                         }
2076
2077                 if (uritok < 0)
2078                         goto bail3;
2079
2080                 lws_snprintf(cgi_path, sizeof(cgi_path) - 1, "REQUEST_URI=%s",
2081                          lws_hdr_simple_ptr(wsi, uritok));
2082                 cgi_path[sizeof(cgi_path) - 1] = '\0';
2083                 env_array[n++] = cgi_path;
2084
2085                 env_array[n++] = p;
2086                 p += lws_snprintf(p, end - p, "REQUEST_METHOD=%s",
2087                               meth_names[m]);
2088                 p++;
2089
2090                 env_array[n++] = p;
2091                 p += lws_snprintf(p, end - p, "QUERY_STRING=");
2092                 /* dump the individual URI Arg parameters */
2093                 m = 0;
2094                 while (1) {
2095                         i = lws_hdr_copy_fragment(wsi, tok, sizeof(tok),
2096                                              WSI_TOKEN_HTTP_URI_ARGS, m);
2097                         if (i < 0)
2098                                 break;
2099                         t = tok;
2100                         while (*t && *t != '=' && p < end - 4)
2101                                 *p++ = *t++;
2102                         if (*t == '=')
2103                                 *p++ = *t++;
2104                         i = urlencode(t, i- (t - tok), p, end - p);
2105                         if (i > 0) {
2106                                 p += i;
2107                                 *p++ = '&';
2108                         }
2109                         m++;
2110                 }
2111                 if (m)
2112                         p--;
2113                 *p++ = '\0';
2114
2115                 env_array[n++] = p;
2116                 p += lws_snprintf(p, end - p, "PATH_INFO=%s",
2117                               lws_hdr_simple_ptr(wsi, uritok) +
2118                               script_uri_path_len);
2119                 p++;
2120         }
2121         if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_REFERER)) {
2122                 env_array[n++] = p;
2123                 p += lws_snprintf(p, end - p, "HTTP_REFERER=%s",
2124                               lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_REFERER));
2125                 p++;
2126         }
2127         if (lws_hdr_total_length(wsi, WSI_TOKEN_HOST)) {
2128                 env_array[n++] = p;
2129                 p += lws_snprintf(p, end - p, "HTTP_HOST=%s",
2130                               lws_hdr_simple_ptr(wsi, WSI_TOKEN_HOST));
2131                 p++;
2132         }
2133         if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_COOKIE)) {
2134                 env_array[n++] = p;
2135                 p += lws_snprintf(p, end - p, "HTTP_COOKIE=%s",
2136                               lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_COOKIE));
2137                 p++;
2138         }
2139         if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_USER_AGENT)) {
2140                 env_array[n++] = p;
2141                 p += lws_snprintf(p, end - p, "USER_AGENT=%s",
2142                               lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_USER_AGENT));
2143                 p++;
2144         }
2145         if (uritok == WSI_TOKEN_POST_URI) {
2146                 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE)) {
2147                         env_array[n++] = p;
2148                         p += lws_snprintf(p, end - p, "CONTENT_TYPE=%s",
2149                                       lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE));
2150                         p++;
2151                 }
2152                 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH)) {
2153                         env_array[n++] = p;
2154                         p += lws_snprintf(p, end - p, "CONTENT_LENGTH=%s",
2155                                       lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH));
2156                         p++;
2157                 }
2158         }
2159         env_array[n++] = p;
2160         p += lws_snprintf(p, end - p, "SCRIPT_PATH=%s", exec_array[0]) + 1;
2161
2162         while (mp_cgienv) {
2163                 env_array[n++] = p;
2164                 p += lws_snprintf(p, end - p, "%s=%s", mp_cgienv->name,
2165                               mp_cgienv->value);
2166                 lwsl_debug("   Applying mount-specific cgi env '%s'\n",
2167                            env_array[n - 1]);
2168                 p++;
2169                 mp_cgienv = mp_cgienv->next;
2170         }
2171
2172         env_array[n++] = "SERVER_SOFTWARE=libwebsockets";
2173         env_array[n++] = "PATH=/bin:/usr/bin:/usr/local/bin:/var/www/cgi-bin";
2174         env_array[n] = NULL;
2175
2176 #if 0
2177         for (m = 0; m < n; m++)
2178                 lwsl_err("    %s\n", env_array[m]);
2179 #endif
2180
2181         /*
2182          * Actually having made the env, as a cgi we don't need the ah
2183          * any more
2184          */
2185         if (wsi->u.hdr.ah->rxpos == wsi->u.hdr.ah->rxlen)
2186                 lws_header_table_detach(wsi, 0);
2187
2188         /* we are ready with the redirection pipes... run the thing */
2189 #if !defined(LWS_HAVE_VFORK) || !defined(LWS_HAVE_EXECVPE)
2190         cgi->pid = fork();
2191 #else
2192         cgi->pid = vfork();
2193 #endif
2194         if (cgi->pid < 0) {
2195                 lwsl_err("fork failed, errno %d", errno);
2196                 goto bail3;
2197         }
2198
2199 #if defined(__linux__)
2200         prctl(PR_SET_PDEATHSIG, SIGTERM);
2201 #endif
2202         setpgrp(); /* stops on-daemonized main processess getting SIGINT from TTY */
2203
2204         if (cgi->pid) {
2205                 /* we are the parent process */
2206                 wsi->context->count_cgi_spawned++;
2207                 lwsl_debug("%s: cgi %p spawned PID %d\n", __func__, cgi, cgi->pid);
2208                 return 0;
2209         }
2210
2211         /* somewhere we can at least read things and enter it */
2212         if (chdir("/tmp"))
2213                 lwsl_notice("%s: Failed to chdir\n", __func__);
2214
2215         /* We are the forked process, redirect and kill inherited things.
2216          *
2217          * Because of vfork(), we cannot do anything that changes pages in
2218          * the parent environment.  Stuff that changes kernel state for the
2219          * process is OK.  Stuff that happens after the execvpe() is OK.
2220          */
2221
2222         for (n = 0; n < 3; n++)
2223                 if (dup2(cgi->pipe_fds[n][!(n == 0)], n) < 0) {
2224                         lwsl_err("%s: stdin dup2 failed\n", __func__);
2225                         goto bail3;
2226                 }
2227
2228 #if !defined(LWS_HAVE_VFORK) || !defined(LWS_HAVE_EXECVPE)
2229         for (m = 0; m < n; m++) {
2230                 p = strchr(env_array[m], '=');
2231                 *p++ = '\0';
2232                 setenv(env_array[m], p, 1);
2233         }
2234         execvp(exec_array[0], (char * const *)&exec_array[0]);
2235 #else
2236         execvpe(exec_array[0], (char * const *)&exec_array[0], &env_array[0]);
2237 #endif
2238
2239         exit(1);
2240
2241 bail3:
2242         /* drop us from the pt cgi list */
2243         pt->cgi_list = cgi->cgi_list;
2244
2245         while (--n >= 0)
2246                 remove_wsi_socket_from_fds(wsi->cgi->stdwsi[n]);
2247 bail2:
2248         for (n = 0; n < 3; n++)
2249                 if (wsi->cgi->stdwsi[n])
2250                         lws_free_wsi(cgi->stdwsi[n]);
2251
2252 bail1:
2253         for (n = 0; n < 3; n++) {
2254                 if (cgi->pipe_fds[n][0])
2255                         close(cgi->pipe_fds[n][0]);
2256                 if (cgi->pipe_fds[n][1])
2257                         close(cgi->pipe_fds[n][1]);
2258         }
2259
2260         lws_free_set_NULL(wsi->cgi);
2261
2262         lwsl_err("%s: failed\n", __func__);
2263
2264         return -1;
2265 }
2266
2267 LWS_VISIBLE LWS_EXTERN int
2268 lws_cgi_write_split_stdout_headers(struct lws *wsi)
2269 {
2270         int n, m, match = 0, lp = 0;
2271         static const char * const content_length = "content-length: ";
2272         char buf[LWS_PRE + 1024], *start = &buf[LWS_PRE], *p = start,
2273              *end = &buf[sizeof(buf) - 1 - LWS_PRE], c, l[12];
2274
2275         if (!wsi->cgi)
2276                 return -1;
2277
2278         while (wsi->hdr_state != LHCS_PAYLOAD) {
2279                 /* we have to separate header / finalize and
2280                  * payload chunks, since they need to be
2281                  * handled separately
2282                  */
2283                 n = read(lws_get_socket_fd(wsi->cgi->stdwsi[LWS_STDOUT]), &c, 1);
2284                 if (n < 0) {
2285                         if (errno != EAGAIN) {
2286                                 lwsl_debug("%s: read says %d\n", __func__, n);
2287                                 return -1;
2288                         }
2289                         else
2290                                 n = 0;
2291                 }
2292                 if (n) {
2293                         lwsl_debug("-- 0x%02X %c\n", (unsigned char)c, c);
2294                         switch (wsi->hdr_state) {
2295                         case LCHS_HEADER:
2296                                 if (!content_length[match] &&
2297                                     (c >= '0' && c <= '9') &&
2298                                     lp < sizeof(l) - 1) {
2299                                         l[lp++] = c;
2300                                         l[lp] = '\0';
2301                                         wsi->cgi->content_length = atol(l);
2302                                 }
2303                                 if (tolower(c) == content_length[match])
2304                                         match++;
2305                                 else
2306                                         match = 0;
2307
2308                                 /* some cgi only send us \x0a for EOL */
2309                                 if (c == '\x0a') {
2310                                         wsi->hdr_state = LCHS_SINGLE_0A;
2311                                         *p++ = '\x0d';
2312                                 }
2313                                 *p++ = c;
2314                                 if (c == '\x0d') {
2315                                         wsi->hdr_state = LCHS_LF1;
2316                                         break;
2317                                 }
2318
2319                                 break;
2320                         case LCHS_LF1:
2321                                 *p++ = c;
2322                                 if (c == '\x0a') {
2323                                         wsi->hdr_state = LCHS_CR2;
2324                                         break;
2325                                 }
2326                                 /* we got \r[^\n]... it's unreasonable */
2327                                 lwsl_debug("%s: funny CRLF 0x%02X\n", __func__, (unsigned char)c);
2328                                 return -1;
2329
2330                         case LCHS_CR2:
2331                                 if (c == '\x0d') {
2332                                         /* drop the \x0d */
2333                                         wsi->hdr_state = LCHS_LF2;
2334                                         break;
2335                                 }
2336                                 wsi->hdr_state = LCHS_HEADER;
2337                                 match = 0;
2338                                 *p++ = c;
2339                                 break;
2340                         case LCHS_LF2:
2341                         case LCHS_SINGLE_0A:
2342                                 m = wsi->hdr_state;
2343                                 if (c == '\x0a') {
2344                                         lwsl_debug("Content-Length: %ld\n", wsi->cgi->content_length);
2345                                         wsi->hdr_state = LHCS_PAYLOAD;
2346                                         /* drop the \0xa ... finalize will add it if needed */
2347                                         if (lws_finalize_http_header(wsi,
2348                                                         (unsigned char **)&p,
2349                                                         (unsigned char *)end))
2350                                                 return -1;
2351                                         break;
2352                                 }
2353                                 if (m == LCHS_LF2)
2354                                         /* we got \r\n\r[^\n]... it's unreasonable */
2355                                         return -1;
2356                                 /* we got \x0anext header, it's reasonable */
2357                                 *p++ = c;
2358                                 wsi->hdr_state = LCHS_HEADER;
2359                                 break;
2360                         case LHCS_PAYLOAD:
2361                                 break;
2362                         }
2363                 }
2364
2365                 /* ran out of input, ended the headers, or filled up the headers buf */
2366                 if (!n || wsi->hdr_state == LHCS_PAYLOAD || (p + 4) == end) {
2367
2368                         m = lws_write(wsi, (unsigned char *)start,
2369                                       p - start, LWS_WRITE_HTTP_HEADERS);
2370                         if (m < 0) {
2371                                 lwsl_debug("%s: write says %d\n", __func__, m);
2372                                 return -1;
2373                         }
2374                         /* writeability becomes uncertain now we wrote
2375                          * something, we must return to the event loop
2376                          */
2377
2378                         return 0;
2379                 }
2380         }
2381
2382         n = read(lws_get_socket_fd(wsi->cgi->stdwsi[LWS_STDOUT]),
2383                  start, sizeof(buf) - LWS_PRE);
2384
2385         if (n < 0 && errno != EAGAIN) {
2386                 lwsl_debug("%s: stdout read says %d\n", __func__, n);
2387                 return -1;
2388         }
2389         if (n > 0) {
2390                 m = lws_write(wsi, (unsigned char *)start, n, LWS_WRITE_HTTP);
2391                 //lwsl_notice("write %d\n", m);
2392                 if (m < 0) {
2393                         lwsl_debug("%s: stdout write says %d\n", __func__, m);
2394                         return -1;
2395                 }
2396                 wsi->cgi->content_length_seen += m;
2397         }
2398
2399         return 0;
2400 }
2401
2402 LWS_VISIBLE LWS_EXTERN int
2403 lws_cgi_kill(struct lws *wsi)
2404 {
2405         struct lws_cgi_args args;
2406         int status, n;
2407
2408         lwsl_debug("%s: %p\n", __func__, wsi);
2409
2410         if (!wsi->cgi)
2411                 return 0;
2412
2413         if (wsi->cgi->pid > 0) {
2414                 n = waitpid(wsi->cgi->pid, &status, WNOHANG);
2415                 if (n > 0) {
2416                         lwsl_debug("%s: PID %d reaped\n", __func__,
2417                                     wsi->cgi->pid);
2418                         goto handled;
2419                 }
2420                 /* kill the process group */
2421                 n = kill(-wsi->cgi->pid, SIGTERM);
2422                 lwsl_debug("%s: SIGTERM child PID %d says %d (errno %d)\n", __func__,
2423                                 wsi->cgi->pid, n, errno);
2424                 if (n < 0) {
2425                         /*
2426                          * hum seen errno=3 when process is listed in ps,
2427                          * it seems we don't always retain process grouping
2428                          *
2429                          * Direct these fallback attempt to the exact child
2430                          */
2431                         n = kill(wsi->cgi->pid, SIGTERM);
2432                         if (n < 0) {
2433                                 n = kill(wsi->cgi->pid, SIGPIPE);
2434                                 if (n < 0) {
2435                                         n = kill(wsi->cgi->pid, SIGKILL);
2436                                         if (n < 0)
2437                                                 lwsl_err("%s: SIGKILL PID %d failed errno %d (maybe zombie)\n",
2438                                                                 __func__, wsi->cgi->pid, errno);
2439                                 }
2440                         }
2441                 }
2442                 /* He could be unkillable because he's a zombie */
2443                 n = 1;
2444                 while (n > 0) {
2445                         n = waitpid(-wsi->cgi->pid, &status, WNOHANG);
2446                         if (n > 0)
2447                                 lwsl_debug("%s: reaped PID %d\n", __func__, n);
2448                         if (n <= 0) {
2449                                 n = waitpid(wsi->cgi->pid, &status, WNOHANG);
2450                                 if (n > 0)
2451                                         lwsl_debug("%s: reaped PID %d\n", __func__, n);
2452                         }
2453                 }
2454         }
2455
2456 handled:
2457         args.stdwsi = &wsi->cgi->stdwsi[0];
2458
2459         if (wsi->cgi->pid != -1 && user_callback_handle_rxflow(
2460                         wsi->protocol->callback,
2461                         wsi, LWS_CALLBACK_CGI_TERMINATED,
2462                         wsi->user_space,
2463                         (void *)&args, 0)) {
2464                 wsi->cgi->pid = -1;
2465                 if (!wsi->cgi->being_closed)
2466                         lws_close_free_wsi(wsi, 0);
2467         }
2468
2469         return 0;
2470 }
2471
2472 LWS_EXTERN int
2473 lws_cgi_kill_terminated(struct lws_context_per_thread *pt)
2474 {
2475         struct lws_cgi **pcgi, *cgi = NULL;
2476         int status, n = 1;
2477
2478         while (n > 0) {
2479                 /* find finished guys but don't reap yet */
2480                 n = waitpid(-1, &status, WNOHANG);
2481                 if (n <= 0)
2482                         continue;
2483                 lwsl_debug("%s: observed PID %d terminated\n", __func__, n);
2484
2485                 pcgi = &pt->cgi_list;
2486
2487                 /* check all the subprocesses on the cgi list */
2488                 while (*pcgi) {
2489                         /* get the next one first as list may change */
2490                         cgi = *pcgi;
2491                         pcgi = &(*pcgi)->cgi_list;
2492
2493                         if (cgi->pid <= 0)
2494                                 continue;
2495
2496                         /* wait for stdout to be drained */
2497                         if (cgi->content_length > cgi->content_length_seen)
2498                                 continue;
2499
2500                         if (cgi->content_length) {
2501                                 lwsl_debug("%s: wsi %p: expected content length seen: %ld\n",
2502                                         __func__, cgi->wsi, cgi->content_length_seen);
2503                         }
2504
2505                         /* reap it */
2506                         waitpid(n, &status, WNOHANG);
2507                         /*
2508                          * he's already terminated so no need for kill()
2509                          * but we should do the terminated cgi callback
2510                          * and close him if he's not already closing
2511                          */
2512                         if (n == cgi->pid) {
2513                                 lwsl_debug("%s: found PID %d on cgi list\n",
2514                                             __func__, n);
2515
2516                                 if (!cgi->content_length) {
2517                                         /*
2518                                          * well, if he sends chunked... give him 5s after the
2519                                          * cgi terminated to send buffered
2520                                          */
2521                                         cgi->chunked_grace++;
2522                                         continue;
2523                                 }
2524
2525                                 /* defeat kill() */
2526                                 cgi->pid = 0;
2527                                 lws_cgi_kill(cgi->wsi);
2528
2529                                 break;
2530                         }
2531                         cgi = NULL;
2532                 }
2533                 /* if not found on the cgi list, as he's one of ours, reap */
2534                 if (!cgi) {
2535                         lwsl_debug("%s: reading PID %d although no cgi match\n",
2536                                         __func__, n);
2537                         waitpid(n, &status, WNOHANG);
2538                 }
2539         }
2540
2541 /* disable this to confirm timeout cgi cleanup flow */
2542 #if 1
2543         pcgi = &pt->cgi_list;
2544
2545         /* check all the subprocesses on the cgi list */
2546         while (*pcgi) {
2547                 /* get the next one first as list may change */
2548                 cgi = *pcgi;
2549                 pcgi = &(*pcgi)->cgi_list;
2550
2551                 if (cgi->pid <= 0)
2552                         continue;
2553
2554                 /* we deferred killing him after reaping his PID */
2555                 if (cgi->chunked_grace) {
2556                         cgi->chunked_grace++;
2557                         if (cgi->chunked_grace < 5)
2558                                 continue;
2559                         goto finish_him;
2560                 }
2561
2562                 /* wait for stdout to be drained */
2563                 if (cgi->content_length > cgi->content_length_seen)
2564                         continue;
2565
2566                 if (cgi->content_length)
2567                         lwsl_debug("%s: wsi %p: expected content length seen: %ld\n",
2568                                 __func__, cgi->wsi, cgi->content_length_seen);
2569
2570                 /* reap it */
2571                 if (waitpid(cgi->pid, &status, WNOHANG) > 0) {
2572
2573                         if (!cgi->content_length) {
2574                                 /*
2575                                  * well, if he sends chunked... give him 5s after the
2576                                  * cgi terminated to send buffered
2577                                  */
2578                                 cgi->chunked_grace++;
2579                                 continue;
2580                         }
2581 finish_him:
2582                         lwsl_debug("%s: found PID %d on cgi list\n",
2583                                     __func__, cgi->pid);
2584                         /* defeat kill() */
2585                         cgi->pid = 0;
2586                         lws_cgi_kill(cgi->wsi);
2587
2588                         break;
2589                 }
2590         }
2591 #endif
2592
2593         /* general anti zombie defence */
2594 //      n = waitpid(-1, &status, WNOHANG);
2595         //if (n > 0)
2596         //      lwsl_notice("%s: anti-zombie wait says %d\n", __func__, n);
2597
2598         return 0;
2599 }
2600 #endif
2601
2602 #ifdef LWS_NO_EXTENSIONS
2603 LWS_EXTERN int
2604 lws_set_extension_option(struct lws *wsi, const char *ext_name,
2605                          const char *opt_name, const char *opt_val)
2606 {
2607         return -1;
2608 }
2609 #endif
2610
2611 #ifdef LWS_WITH_ACCESS_LOG
2612 int
2613 lws_access_log(struct lws *wsi)
2614 {
2615         char *p = wsi->access_log.user_agent, ass[512];
2616         int l;
2617
2618         if (!wsi->access_log_pending)
2619                 return 0;
2620
2621         if (!wsi->access_log.header_log)
2622                 return 0;
2623
2624         if (!p)
2625                 p = "";
2626
2627         l = lws_snprintf(ass, sizeof(ass) - 1, "%s %d %lu %s\n",
2628                      wsi->access_log.header_log,
2629                      wsi->access_log.response, wsi->access_log.sent, p);
2630
2631         if (wsi->vhost->log_fd != (int)LWS_INVALID_FILE) {
2632                 if (write(wsi->vhost->log_fd, ass, l) != l)
2633                         lwsl_err("Failed to write log\n");
2634         } else
2635                 lwsl_err("%s", ass);
2636
2637         if (wsi->access_log.header_log) {
2638                 lws_free(wsi->access_log.header_log);
2639                 wsi->access_log.header_log = NULL;
2640         }
2641         if (wsi->access_log.user_agent) {
2642                 lws_free(wsi->access_log.user_agent);
2643                 wsi->access_log.user_agent = NULL;
2644         }
2645         wsi->access_log_pending = 0;
2646
2647         return 0;
2648 }
2649 #endif
2650
2651 void
2652 lws_sum_stats(const struct lws_context *ctx, struct lws_conn_stats *cs)
2653 {
2654         const struct lws_vhost *vh = ctx->vhost_list;
2655
2656         while (vh) {
2657
2658                 cs->rx += vh->conn_stats.rx;
2659                 cs->tx += vh->conn_stats.tx;
2660                 cs->conn += vh->conn_stats.conn;
2661                 cs->trans += vh->conn_stats.trans;
2662                 cs->ws_upg += vh->conn_stats.ws_upg;
2663                 cs->http2_upg += vh->conn_stats.http2_upg;
2664                 cs->rejected += vh->conn_stats.rejected;
2665
2666                 vh = vh->vhost_next;
2667         }
2668 }
2669
2670 #ifdef LWS_WITH_SERVER_STATUS
2671
2672 LWS_EXTERN int
2673 lws_json_dump_vhost(const struct lws_vhost *vh, char *buf, int len)
2674 {
2675         static const char * const prots[] = {
2676                 "http://",
2677                 "https://",
2678                 "file://",
2679                 "cgi://",
2680                 ">http://",
2681                 ">https://",
2682                 "callback://"
2683         };
2684         char *orig = buf, *end = buf + len - 1, first = 1;
2685         int n = 0;
2686
2687         if (len < 100)
2688                 return 0;
2689
2690         buf += lws_snprintf(buf, end - buf,
2691                         "{\n \"name\":\"%s\",\n"
2692                         " \"port\":\"%d\",\n"
2693                         " \"use_ssl\":\"%d\",\n"
2694                         " \"sts\":\"%d\",\n"
2695                         " \"rx\":\"%llu\",\n"
2696                         " \"tx\":\"%llu\",\n"
2697                         " \"conn\":\"%lu\",\n"
2698                         " \"trans\":\"%lu\",\n"
2699                         " \"ws_upg\":\"%lu\",\n"
2700                         " \"rejected\":\"%lu\",\n"
2701                         " \"http2_upg\":\"%lu\""
2702                         ,
2703                         vh->name, vh->listen_port,
2704 #ifdef LWS_OPENSSL_SUPPORT
2705                         vh->use_ssl,
2706 #else
2707                         0,
2708 #endif
2709                         !!(vh->options & LWS_SERVER_OPTION_STS),
2710                         vh->conn_stats.rx, vh->conn_stats.tx,
2711                         vh->conn_stats.conn, vh->conn_stats.trans,
2712                         vh->conn_stats.ws_upg,
2713                         vh->conn_stats.rejected,
2714                         vh->conn_stats.http2_upg
2715         );
2716
2717         if (vh->mount_list) {
2718                 const struct lws_http_mount *m = vh->mount_list;
2719
2720                 buf += lws_snprintf(buf, end - buf, ",\n \"mounts\":[");
2721                 while (m) {
2722                         if (!first)
2723                                 buf += lws_snprintf(buf, end - buf, ",");
2724                         buf += lws_snprintf(buf, end - buf,
2725                                         "\n  {\n   \"mountpoint\":\"%s\",\n"
2726                                         "  \"origin\":\"%s%s\",\n"
2727                                         "  \"cache_max_age\":\"%d\",\n"
2728                                         "  \"cache_reuse\":\"%d\",\n"
2729                                         "  \"cache_revalidate\":\"%d\",\n"
2730                                         "  \"cache_intermediaries\":\"%d\"\n"
2731                                         ,
2732                                         m->mountpoint,
2733                                         prots[m->origin_protocol],
2734                                         m->origin,
2735                                         m->cache_max_age,
2736                                         m->cache_reusable,
2737                                         m->cache_revalidate,
2738                                         m->cache_intermediaries);
2739                         if (m->def)
2740                                 buf += lws_snprintf(buf, end - buf,
2741                                                 ",\n  \"default\":\"%s\"",
2742                                                 m->def);
2743                         buf += lws_snprintf(buf, end - buf, "\n  }");
2744                         first = 0;
2745                         m = m->mount_next;
2746                 }
2747                 buf += lws_snprintf(buf, end - buf, "\n ]");
2748         }
2749
2750         if (vh->protocols) {
2751                 n = 0;
2752                 first = 1;
2753
2754                 buf += lws_snprintf(buf, end - buf, ",\n \"ws-protocols\":[");
2755                 while (n < vh->count_protocols) {
2756                         if (!first)
2757                                 buf += lws_snprintf(buf, end - buf, ",");
2758                         buf += lws_snprintf(buf, end - buf,
2759                                         "\n  {\n   \"%s\":{\n"
2760                                         "    \"status\":\"ok\"\n   }\n  }"
2761                                         ,
2762                                         vh->protocols[n].name);
2763                         first = 0;
2764                         n++;
2765                 }
2766                 buf += lws_snprintf(buf, end - buf, "\n ]");
2767         }
2768
2769         buf += lws_snprintf(buf, end - buf, "\n}");
2770
2771         return buf - orig;
2772 }
2773
2774
2775 LWS_EXTERN LWS_VISIBLE int
2776 lws_json_dump_context(const struct lws_context *context, char *buf, int len,
2777                 int hide_vhosts)
2778 {
2779         char *orig = buf, *end = buf + len - 1, first = 1;
2780         const struct lws_vhost *vh = context->vhost_list;
2781         const struct lws_context_per_thread *pt;
2782         time_t t = time(NULL);
2783         int n, listening = 0, cgi_count = 0;
2784         struct lws_conn_stats cs;
2785         double d = 0;
2786 #ifdef LWS_WITH_CGI
2787         struct lws_cgi * const *pcgi;
2788 #endif
2789
2790 #ifdef LWS_USE_LIBUV
2791         uv_uptime(&d);
2792 #endif
2793
2794         buf += lws_snprintf(buf, end - buf, "{ "
2795                             "\"version\":\"%s\",\n"
2796                             "\"uptime\":\"%ld\",\n",
2797                             lws_get_library_version(),
2798                             (long)d);
2799
2800 #ifdef LWS_HAVE_GETLOADAVG
2801         {
2802                 double d[3];
2803                 int m;
2804
2805                 m = getloadavg(d, 3);
2806                 for (n = 0; n < m; n++) {
2807                         buf += lws_snprintf(buf, end - buf,
2808                                 "\"l%d\":\"%.2f\",\n",
2809                                 n + 1, d[n]);
2810                 }
2811         }
2812 #endif
2813
2814         buf += lws_snprintf(buf, end - buf, "\"contexts\":[\n");
2815
2816         buf += lws_snprintf(buf, end - buf, "{ "
2817                                 "\"context_uptime\":\"%ld\",\n"
2818                                 "\"cgi_spawned\":\"%d\",\n"
2819                                 "\"pt_fd_max\":\"%d\",\n"
2820                                 "\"ah_pool_max\":\"%d\",\n"
2821                                 "\"deprecated\":\"%d\",\n"
2822                                 "\"wsi_alive\":\"%d\",\n",
2823                                 (unsigned long)(t - context->time_up),
2824                                 context->count_cgi_spawned,
2825                                 context->fd_limit_per_thread,
2826                                 context->max_http_header_pool,
2827                                 context->deprecated,
2828                                 context->count_wsi_allocated);
2829
2830         buf += lws_snprintf(buf, end - buf, "\"pt\":[\n ");
2831         for (n = 0; n < context->count_threads; n++) {
2832                 pt = &context->pt[n];
2833                 if (n)
2834                         buf += lws_snprintf(buf, end - buf, ",");
2835                 buf += lws_snprintf(buf, end - buf,
2836                                 "\n  {\n"
2837                                 "    \"fds_count\":\"%d\",\n"
2838                                 "    \"ah_pool_inuse\":\"%d\",\n"
2839                                 "    \"ah_wait_list\":\"%d\"\n"
2840                                 "    }",
2841                                 pt->fds_count,
2842                                 pt->ah_count_in_use,
2843                                 pt->ah_wait_list_length);
2844         }
2845
2846         buf += lws_snprintf(buf, end - buf, "]");
2847
2848         buf += lws_snprintf(buf, end - buf, ", \"vhosts\":[\n ");
2849
2850         first = 1;
2851         vh = context->vhost_list;
2852         listening = 0;
2853         cs = context->conn_stats;
2854         lws_sum_stats(context, &cs);
2855         while (vh) {
2856
2857                 if (!hide_vhosts) {
2858                         if (!first)
2859                                 if(buf != end)
2860                                         *buf++ = ',';
2861                         buf += lws_json_dump_vhost(vh, buf, end - buf);
2862                         first = 0;
2863                 }
2864                 if (vh->lserv_wsi)
2865                         listening++;
2866                 vh = vh->vhost_next;
2867         }
2868
2869         buf += lws_snprintf(buf, end - buf,
2870                         "],\n\"listen_wsi\":\"%d\",\n"
2871                         " \"rx\":\"%llu\",\n"
2872                         " \"tx\":\"%llu\",\n"
2873                         " \"conn\":\"%lu\",\n"
2874                         " \"trans\":\"%lu\",\n"
2875                         " \"ws_upg\":\"%lu\",\n"
2876                         " \"rejected\":\"%lu\",\n"
2877                         " \"http2_upg\":\"%lu\"",
2878                         listening,
2879                         cs.rx, cs.tx, cs.conn, cs.trans,
2880                         cs.ws_upg, cs.rejected, cs.http2_upg);
2881
2882 #ifdef LWS_WITH_CGI
2883         for (n = 0; n < context->count_threads; n++) {
2884                 pt = &context->pt[n];
2885                 pcgi = &pt->cgi_list;
2886
2887                 while (*pcgi) {
2888                         pcgi = &(*pcgi)->cgi_list;
2889
2890                         cgi_count++;
2891                 }
2892         }
2893 #endif
2894         buf += lws_snprintf(buf, end - buf, ",\n \"cgi_alive\":\"%d\"\n ",
2895                         cgi_count);
2896
2897         buf += lws_snprintf(buf, end - buf, "}");
2898
2899
2900         buf += lws_snprintf(buf, end - buf, "]}\n ");
2901
2902         return buf - orig;
2903 }
2904
2905 #endif