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