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