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