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