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