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