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