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