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