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