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