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