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