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