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