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