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