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