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