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