lwsws cgi integration
[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         context = wsi->context;
155         pt = &context->pt[(int)wsi->tsi];
156
157         /* if we have children, close them first */
158         if (wsi->child_list) {
159                 wsi2 = wsi->child_list;
160                 while (wsi2) {
161                         //lwsl_notice("%s: closing %p: close child %p\n",
162                         //              __func__, wsi, wsi2);
163                         wsi1 = wsi2->sibling_list;
164                         //lwsl_notice("%s: closing %p: next sibling %p\n",
165                         //              __func__, wsi2, wsi1);
166                         wsi2->parent = NULL;
167                         /* stop it doing shutdown processing */
168                         wsi2->socket_is_permanently_unusable = 1;
169                         lws_close_free_wsi(wsi2, reason);
170                         wsi2 = wsi1;
171                 }
172                 wsi->child_list = NULL;
173         }
174
175 #ifdef LWS_WITH_CGI
176         if (wsi->mode == LWSCM_CGI) {
177                 /* we are not a network connection, but a handler for CGI io */
178                 if (wsi->parent && wsi->parent->cgi)
179                         /* end the binding between us and master */
180                         wsi->parent->cgi->stdwsi[(int)wsi->cgi_channel] = NULL;
181                 wsi->socket_is_permanently_unusable = 1;
182
183                 lwsl_debug("------ %s: detected cgi fdhandler wsi %p\n", __func__, wsi);
184                 goto just_kill_connection;
185         }
186
187         if (wsi->cgi) {
188                 /* we have a cgi going, we must kill it */
189                 wsi->cgi->being_closed = 1;
190                 lws_cgi_kill(wsi);
191         }
192 #endif
193
194         if (wsi->mode == LWSCM_HTTP_SERVING_ACCEPTED &&
195             wsi->u.http.fd != LWS_INVALID_FILE) {
196                 lws_plat_file_close(wsi, wsi->u.http.fd);
197                 wsi->u.http.fd = LWS_INVALID_FILE;
198                 wsi->vhost->protocols[0].callback(wsi,
199                         LWS_CALLBACK_CLOSED_HTTP, wsi->user_space, NULL, 0);
200         }
201         if (wsi->socket_is_permanently_unusable ||
202             reason == LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY ||
203             wsi->state == LWSS_SHUTDOWN)
204                 goto just_kill_connection;
205
206         wsi->state_pre_close = wsi->state;
207
208         switch (wsi->state_pre_close) {
209         case LWSS_DEAD_SOCKET:
210                 return;
211
212         /* we tried the polite way... */
213         case LWSS_AWAITING_CLOSE_ACK:
214                 goto just_kill_connection;
215
216         case LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE:
217                 if (wsi->trunc_len) {
218                         lws_callback_on_writable(wsi);
219                         return;
220                 }
221                 lwsl_info("wsi %p completed LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE\n", wsi);
222                 goto just_kill_connection;
223         default:
224                 if (wsi->trunc_len) {
225                         lwsl_info("wsi %p entering LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE\n", wsi);
226                         wsi->state = LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE;
227                         lws_set_timeout(wsi, PENDING_FLUSH_STORED_SEND_BEFORE_CLOSE, 5);
228                         return;
229                 }
230                 break;
231         }
232
233         if (wsi->mode == LWSCM_WSCL_WAITING_CONNECT ||
234             wsi->mode == LWSCM_WSCL_ISSUE_HANDSHAKE)
235                 goto just_kill_connection;
236
237         if (wsi->mode == LWSCM_HTTP_SERVING)
238                 wsi->vhost->protocols[0].callback(wsi, LWS_CALLBACK_CLOSED_HTTP,
239                                                wsi->user_space, NULL, 0);
240         if (wsi->mode == LWSCM_HTTP_CLIENT)
241                 wsi->vhost->protocols[0].callback(wsi, LWS_CALLBACK_CLOSED_CLIENT_HTTP,
242                                                wsi->user_space, NULL, 0);
243
244         /*
245          * are his extensions okay with him closing?  Eg he might be a mux
246          * parent and just his ch1 aspect is closing?
247          */
248
249         if (lws_ext_cb_active(wsi,
250                       LWS_EXT_CB_CHECK_OK_TO_REALLY_CLOSE, NULL, 0) > 0) {
251                 lwsl_ext("extension vetoed close\n");
252                 return;
253         }
254
255         /*
256          * flush any tx pending from extensions, since we may send close packet
257          * if there are problems with send, just nuke the connection
258          */
259
260         do {
261                 ret = 0;
262                 eff_buf.token = NULL;
263                 eff_buf.token_len = 0;
264
265                 /* show every extension the new incoming data */
266
267                 m = lws_ext_cb_active(wsi,
268                           LWS_EXT_CB_FLUSH_PENDING_TX, &eff_buf, 0);
269                 if (m < 0) {
270                         lwsl_ext("Extension reports fatal error\n");
271                         goto just_kill_connection;
272                 }
273                 if (m)
274                         /*
275                          * at least one extension told us he has more
276                          * to spill, so we will go around again after
277                          */
278                         ret = 1;
279
280                 /* assuming they left us something to send, send it */
281
282                 if (eff_buf.token_len)
283                         if (lws_issue_raw(wsi, (unsigned char *)eff_buf.token,
284                                           eff_buf.token_len) !=
285                             eff_buf.token_len) {
286                                 lwsl_debug("close: ext spill failed\n");
287                                 goto just_kill_connection;
288                         }
289         } while (ret);
290
291         /*
292          * signal we are closing, lws_write will
293          * add any necessary version-specific stuff.  If the write fails,
294          * no worries we are closing anyway.  If we didn't initiate this
295          * close, then our state has been changed to
296          * LWSS_RETURNED_CLOSE_ALREADY and we will skip this.
297          *
298          * Likewise if it's a second call to close this connection after we
299          * sent the close indication to the peer already, we are in state
300          * LWSS_AWAITING_CLOSE_ACK and will skip doing this a second time.
301          */
302
303         if (wsi->state_pre_close == LWSS_ESTABLISHED &&
304             (wsi->u.ws.close_in_ping_buffer_len || /* already a reason */
305              (reason != LWS_CLOSE_STATUS_NOSTATUS &&
306              (reason != LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY)))) {
307                 lwsl_debug("sending close indication...\n");
308
309                 /* if no prepared close reason, use 1000 and no aux data */
310                 if (!wsi->u.ws.close_in_ping_buffer_len) {
311                         wsi->u.ws.close_in_ping_buffer_len = 2;
312                         wsi->u.ws.ping_payload_buf[LWS_PRE] =
313                                 (reason >> 16) & 0xff;
314                         wsi->u.ws.ping_payload_buf[LWS_PRE + 1] =
315                                 reason & 0xff;
316                 }
317
318                 n = lws_write(wsi, &wsi->u.ws.ping_payload_buf[LWS_PRE],
319                               wsi->u.ws.close_in_ping_buffer_len,
320                               LWS_WRITE_CLOSE);
321                 if (n >= 0) {
322                         /*
323                          * we have sent a nice protocol level indication we
324                          * now wish to close, we should not send anything more
325                          */
326                         wsi->state = LWSS_AWAITING_CLOSE_ACK;
327
328                         /*
329                          * ...and we should wait for a reply for a bit
330                          * out of politeness
331                          */
332                         lws_set_timeout(wsi, PENDING_TIMEOUT_CLOSE_ACK, 1);
333                         lwsl_debug("sent close indication, awaiting ack\n");
334
335                         return;
336                 }
337
338                 lwsl_info("close: sending close packet failed, hanging up\n");
339
340                 /* else, the send failed and we should just hang up */
341         }
342
343 just_kill_connection:
344         if (wsi->parent) {
345                 /* detach ourselves from parent's child list */
346                 pwsi = &wsi->parent->child_list;
347                 while (*pwsi) {
348                         if (*pwsi == wsi) {
349                                 lwsl_notice("%s: detach %p from parent %p\n",
350                                                 __func__, wsi, wsi->parent);
351                                 *pwsi = wsi->sibling_list;
352                                 break;
353                         }
354                         pwsi = &(*pwsi)->sibling_list;
355                 }
356                 if (*pwsi)
357                         lwsl_err("%s: failed to detach from parent\n",
358                                         __func__);
359         }
360
361 #if LWS_POSIX
362         /*
363          * Testing with ab shows that we have to stage the socket close when
364          * the system is under stress... shutdown any further TX, change the
365          * state to one that won't emit anything more, and wait with a timeout
366          * for the POLLIN to show a zero-size rx before coming back and doing
367          * the actual close.
368          */
369         if (wsi->state != LWSS_SHUTDOWN &&
370             reason != LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY &&
371             !wsi->socket_is_permanently_unusable) {
372                 lwsl_info("%s: shutting down connection: %p (sock %d)\n", __func__, wsi, wsi->sock);
373                 n = shutdown(wsi->sock, SHUT_WR);
374                 if (n)
375                         lwsl_debug("closing: shutdown ret %d\n", LWS_ERRNO);
376
377 // This causes problems with disconnection when the events are half closing connection
378 // FD_READ | FD_CLOSE (33)
379 #ifndef _WIN32_WCE
380                 /* libuv: no event available to guarantee completion */
381                 if (!LWS_LIBUV_ENABLED(context)) {
382
383                         lws_change_pollfd(wsi, LWS_POLLOUT, LWS_POLLIN);
384                         wsi->state = LWSS_SHUTDOWN;
385                         lws_set_timeout(wsi, PENDING_TIMEOUT_SHUTDOWN_FLUSH,
386                                         context->timeout_secs);
387                         return;
388                 }
389 #endif
390         }
391 #endif
392
393         lwsl_info("%s: real just_kill_connection: %p (sockfd %d)\n", __func__,
394                   wsi, wsi->sock);
395 #ifdef LWS_WITH_HTTP_PROXY
396         if (wsi->rw) {
397                 lws_rewrite_destroy(wsi->rw);
398                 wsi->rw = NULL;
399         }
400 #endif
401         /*
402          * we won't be servicing or receiving anything further from this guy
403          * delete socket from the internal poll list if still present
404          */
405         lws_ssl_remove_wsi_from_buffered_list(wsi);
406         lws_remove_from_timeout_list(wsi);
407
408         /* checking return redundant since we anyway close */
409         remove_wsi_socket_from_fds(wsi);
410
411         wsi->state = LWSS_DEAD_SOCKET;
412
413         lws_free_set_NULL(wsi->rxflow_buffer);
414
415         if (wsi->state_pre_close == LWSS_ESTABLISHED ||
416             wsi->mode == LWSCM_WS_SERVING ||
417             wsi->mode == LWSCM_WS_CLIENT) {
418
419                 if (wsi->u.ws.rx_draining_ext) {
420                         struct lws **w = &pt->rx_draining_ext_list;
421
422                         wsi->u.ws.rx_draining_ext = 0;
423                         /* remove us from context draining ext list */
424                         while (*w) {
425                                 if (*w == wsi) {
426                                         *w = wsi->u.ws.rx_draining_ext_list;
427                                         break;
428                                 }
429                                 w = &((*w)->u.ws.rx_draining_ext_list);
430                         }
431                         wsi->u.ws.rx_draining_ext_list = NULL;
432                 }
433
434                 if (wsi->u.ws.tx_draining_ext) {
435                         struct lws **w = &pt->tx_draining_ext_list;
436
437                         wsi->u.ws.tx_draining_ext = 0;
438                         /* remove us from context draining ext list */
439                         while (*w) {
440                                 if (*w == wsi) {
441                                         *w = wsi->u.ws.tx_draining_ext_list;
442                                         break;
443                                 }
444                                 w = &((*w)->u.ws.tx_draining_ext_list);
445                         }
446                         wsi->u.ws.tx_draining_ext_list = NULL;
447                 }
448                 lws_free_set_NULL(wsi->u.ws.rx_ubuf);
449
450                 if (wsi->trunc_alloc)
451                         /* not going to be completed... nuke it */
452                         lws_free_set_NULL(wsi->trunc_alloc);
453
454                 wsi->u.ws.ping_payload_len = 0;
455                 wsi->u.ws.ping_pending_flag = 0;
456         }
457
458         /* tell the user it's all over for this guy */
459
460         if (wsi->protocol && wsi->protocol->callback &&
461             ((wsi->state_pre_close == LWSS_ESTABLISHED) ||
462             (wsi->state_pre_close == LWSS_RETURNED_CLOSE_ALREADY) ||
463             (wsi->state_pre_close == LWSS_AWAITING_CLOSE_ACK) ||
464             (wsi->state_pre_close == LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE) ||
465             (wsi->mode == LWSCM_WS_CLIENT && wsi->state_pre_close == LWSS_HTTP) ||
466             (wsi->mode == LWSCM_WS_SERVING && wsi->state_pre_close == LWSS_HTTP))) {
467                 lwsl_debug("calling back CLOSED\n");
468                 wsi->protocol->callback(wsi, LWS_CALLBACK_CLOSED,
469                                         wsi->user_space, NULL, 0);
470         } else if (wsi->mode == LWSCM_HTTP_SERVING_ACCEPTED) {
471                 lwsl_debug("calling back CLOSED_HTTP\n");
472                 wsi->vhost->protocols[0].callback(wsi, LWS_CALLBACK_CLOSED_HTTP,
473                                                wsi->user_space, NULL, 0 );
474         } else if (wsi->mode == LWSCM_WSCL_WAITING_SERVER_REPLY ||
475                    wsi->mode == LWSCM_WSCL_WAITING_CONNECT) {
476                 lwsl_debug("Connection closed before server reply\n");
477                 wsi->vhost->protocols[0].callback(wsi,
478                                         LWS_CALLBACK_CLIENT_CONNECTION_ERROR,
479                                         wsi->user_space, NULL, 0);
480         } else
481                 lwsl_debug("not calling back closed mode=%d state=%d\n",
482                            wsi->mode, wsi->state_pre_close);
483
484         /* deallocate any active extension contexts */
485
486         if (lws_ext_cb_active(wsi, LWS_EXT_CB_DESTROY, NULL, 0) < 0)
487                 lwsl_warn("extension destruction failed\n");
488         /*
489          * inform all extensions in case they tracked this guy out of band
490          * even though not active on him specifically
491          */
492         if (lws_ext_cb_all_exts(context, wsi,
493                        LWS_EXT_CB_DESTROY_ANY_WSI_CLOSING, NULL, 0) < 0)
494                 lwsl_warn("ext destroy wsi failed\n");
495
496         wsi->socket_is_permanently_unusable = 1;
497
498 #ifdef LWS_USE_LIBUV
499         if (LWS_LIBUV_ENABLED(context)) {
500                 lwsl_debug("%s: lws_libuv_closehandle: wsi %p\n", __func__, wsi);
501                 /* libuv has to do his own close handle processing asynchronously */
502                 lws_libuv_closehandle(wsi);
503
504                 return;
505         }
506 #endif
507
508         lws_close_free_wsi_final(wsi);
509 }
510
511 void
512 lws_close_free_wsi_final(struct lws *wsi)
513 {
514         int n;
515
516         if (!lws_ssl_close(wsi) && lws_socket_is_valid(wsi->sock)) {
517 #if LWS_POSIX
518                 //lwsl_err("*** closing sockfd %d\n", wsi->sock);
519                 n = compatible_close(wsi->sock);
520                 if (n)
521                         lwsl_debug("closing: close ret %d\n", LWS_ERRNO);
522
523 #else
524                 compatible_close(wsi->sock);
525 #endif
526                 wsi->sock = LWS_SOCK_INVALID;
527         }
528
529         /* outermost destroy notification for wsi (user_space still intact) */
530         wsi->vhost->protocols[0].callback(wsi, LWS_CALLBACK_WSI_DESTROY,
531                                        wsi->user_space, NULL, 0);
532
533         lws_free_wsi(wsi);
534 }
535
536 #if LWS_POSIX
537 LWS_VISIBLE int
538 interface_to_sa(struct lws_context *context, const char *ifname, struct sockaddr_in *addr, size_t addrlen)
539 {
540         int ipv6 = 0;
541 #ifdef LWS_USE_IPV6
542         ipv6 = LWS_IPV6_ENABLED(context);
543 #endif
544         (void)context;
545
546         return lws_interface_to_sa(ipv6, ifname, addr, addrlen);
547 }
548 #endif
549
550 LWS_VISIBLE int
551 lws_get_addresses(struct lws_context *context, void *ads, char *name,
552                   int name_len, char *rip, int rip_len)
553 {
554 #if LWS_POSIX
555         struct addrinfo ai, *res;
556         struct sockaddr_in addr4;
557
558         if (rip)
559                 rip[0] = '\0';
560         name[0] = '\0';
561         addr4.sin_family = AF_UNSPEC;
562
563 #ifdef LWS_USE_IPV6
564         if (LWS_IPV6_ENABLED(context)) {
565                 if (!lws_plat_inet_ntop(AF_INET6, &((struct sockaddr_in6 *)ads)->sin6_addr, rip, rip_len)) {
566                         lwsl_err("inet_ntop", strerror(LWS_ERRNO));
567                         return -1;
568                 }
569
570                 // Strip off the IPv4 to IPv6 header if one exists
571                 if (strncmp(rip, "::ffff:", 7) == 0)
572                         memmove(rip, rip + 7, strlen(rip) - 6);
573
574                 getnameinfo((struct sockaddr *)ads,
575                                 sizeof(struct sockaddr_in6), name,
576                                                         name_len, NULL, 0, 0);
577
578                 return 0;
579         } else
580 #endif
581         {
582                 struct addrinfo *result;
583
584                 memset(&ai, 0, sizeof ai);
585                 ai.ai_family = PF_UNSPEC;
586                 ai.ai_socktype = SOCK_STREAM;
587                 ai.ai_flags = AI_CANONNAME;
588
589                 if (getnameinfo((struct sockaddr *)ads,
590                                 sizeof(struct sockaddr_in),
591                                 name, name_len, NULL, 0, 0))
592                         return -1;
593
594                 if (!rip)
595                         return 0;
596
597                 if (getaddrinfo(name, NULL, &ai, &result))
598                         return -1;
599
600                 res = result;
601                 while (addr4.sin_family == AF_UNSPEC && res) {
602                         switch (res->ai_family) {
603                         case AF_INET:
604                                 addr4.sin_addr = ((struct sockaddr_in *)res->ai_addr)->sin_addr;
605                                 addr4.sin_family = AF_INET;
606                                 break;
607                         }
608
609                         res = res->ai_next;
610                 }
611                 freeaddrinfo(result);
612         }
613
614         if (addr4.sin_family == AF_UNSPEC)
615                 return -1;
616
617         if (lws_plat_inet_ntop(AF_INET, &addr4.sin_addr, rip, rip_len) == NULL)
618                 return -1;
619
620         return 0;
621 #else
622         (void)context;
623         (void)ads;
624         (void)name;
625         (void)name_len;
626         (void)rip;
627         (void)rip_len;
628
629         return -1;
630 #endif
631 }
632
633 /**
634  * lws_get_peer_addresses() - Get client address information
635  * @wsi:        Local struct lws associated with
636  * @fd:         Connection socket descriptor
637  * @name:       Buffer to take client address name
638  * @name_len:   Length of client address name buffer
639  * @rip:        Buffer to take client address IP dotted quad
640  * @rip_len:    Length of client address IP buffer
641  *
642  *      This function fills in @name and @rip with the name and IP of
643  *      the client connected with socket descriptor @fd.  Names may be
644  *      truncated if there is not enough room.  If either cannot be
645  *      determined, they will be returned as valid zero-length strings.
646  */
647
648 LWS_VISIBLE void
649 lws_get_peer_addresses(struct lws *wsi, lws_sockfd_type fd, char *name,
650                        int name_len, char *rip, int rip_len)
651 {
652 #if LWS_POSIX
653         socklen_t len;
654 #ifdef LWS_USE_IPV6
655         struct sockaddr_in6 sin6;
656 #endif
657         struct sockaddr_in sin4;
658         struct lws_context *context = wsi->context;
659         int ret = -1;
660         void *p;
661
662         rip[0] = '\0';
663         name[0] = '\0';
664
665         lws_latency_pre(context, wsi);
666
667 #ifdef LWS_USE_IPV6
668         if (LWS_IPV6_ENABLED(context)) {
669                 len = sizeof(sin6);
670                 p = &sin6;
671         } else
672 #endif
673         {
674                 len = sizeof(sin4);
675                 p = &sin4;
676         }
677
678         if (getpeername(fd, p, &len) < 0) {
679                 lwsl_warn("getpeername: %s\n", strerror(LWS_ERRNO));
680                 goto bail;
681         }
682
683         ret = lws_get_addresses(context, p, name, name_len, rip, rip_len);
684
685 bail:
686         lws_latency(context, wsi, "lws_get_peer_addresses", ret, 1);
687 #else
688         (void)wsi;
689         (void)fd;
690         (void)name;
691         (void)name_len;
692         (void)rip;
693         (void)rip_len;
694 #endif
695 }
696
697 /**
698  * lws_context_user() - get the user data associated with the context
699  * @context: Websocket context
700  *
701  *      This returns the optional user allocation that can be attached to
702  *      the context the sockets live in at context_create time.  It's a way
703  *      to let all sockets serviced in the same context share data without
704  *      using globals statics in the user code.
705  */
706 LWS_EXTERN void *
707 lws_context_user(struct lws_context *context)
708 {
709         return context->user_space;
710 }
711
712 LWS_VISIBLE struct lws_vhost *
713 lws_vhost_get(struct lws *wsi)
714 {
715         return wsi->vhost;
716 }
717
718 LWS_VISIBLE const struct lws_protocols *
719 lws_protocol_get(struct lws *wsi)
720 {
721         return wsi->protocol;
722 }
723
724
725 /**
726  * lws_callback_all_protocol() - Callback all connections using
727  *                              the given protocol with the given reason
728  *
729  * @protocol:   Protocol whose connections will get callbacks
730  * @reason:     Callback reason index
731  */
732
733 LWS_VISIBLE int
734 lws_callback_all_protocol(struct lws_context *context,
735                           const struct lws_protocols *protocol, int reason)
736 {
737         struct lws_context_per_thread *pt = &context->pt[0];
738         unsigned int n, m = context->count_threads;
739         struct lws *wsi;
740
741         while (m--) {
742                 for (n = 0; n < pt->fds_count; n++) {
743                         wsi = wsi_from_fd(context, pt->fds[n].fd);
744                         if (!wsi)
745                                 continue;
746                         if (wsi->protocol == protocol)
747                                 protocol->callback(wsi, reason, wsi->user_space,
748                                                    NULL, 0);
749                 }
750                 pt++;
751         }
752
753         return 0;
754 }
755
756 /**
757  * lws_callback_all_protocol_vhost() - Callback all connections using
758  *                              the given protocol with the given reason
759  *
760  * @vh:         Vhost whose connections will get callbacks
761  * @protocol:   Which protocol to match
762  * @reason:     Callback reason index
763  */
764
765 LWS_VISIBLE int
766 lws_callback_all_protocol_vhost(struct lws_vhost *vh,
767                           const struct lws_protocols *protocol, int reason)
768 {
769         struct lws_context *context = vh->context;
770         struct lws_context_per_thread *pt = &context->pt[0];
771         unsigned int n, m = context->count_threads;
772         struct lws *wsi;
773
774         while (m--) {
775                 for (n = 0; n < pt->fds_count; n++) {
776                         wsi = wsi_from_fd(context, pt->fds[n].fd);
777                         if (!wsi)
778                                 continue;
779                         if (wsi->vhost == vh && wsi->protocol == protocol)
780                                 protocol->callback(wsi, reason, wsi->user_space,
781                                                    NULL, 0);
782                 }
783                 pt++;
784         }
785
786         return 0;
787 }
788
789 #if LWS_POSIX
790
791 /**
792  * lws_get_socket_fd() - returns the socket file descriptor
793  *
794  * You will not need this unless you are doing something special
795  *
796  * @wsi:        Websocket connection instance
797  */
798
799 LWS_VISIBLE int
800 lws_get_socket_fd(struct lws *wsi)
801 {
802         return wsi->sock;
803 }
804
805 #endif
806
807 #ifdef LWS_LATENCY
808 void
809 lws_latency(struct lws_context *context, struct lws *wsi, const char *action,
810             int ret, int completed)
811 {
812         unsigned long long u;
813         char buf[256];
814
815         u = time_in_microseconds();
816
817         if (!action) {
818                 wsi->latency_start = u;
819                 if (!wsi->action_start)
820                         wsi->action_start = u;
821                 return;
822         }
823         if (completed) {
824                 if (wsi->action_start == wsi->latency_start)
825                         sprintf(buf,
826                           "Completion first try lat %lluus: %p: ret %d: %s\n",
827                                         u - wsi->latency_start,
828                                                       (void *)wsi, ret, action);
829                 else
830                         sprintf(buf,
831                           "Completion %lluus: lat %lluus: %p: ret %d: %s\n",
832                                 u - wsi->action_start,
833                                         u - wsi->latency_start,
834                                                       (void *)wsi, ret, action);
835                 wsi->action_start = 0;
836         } else
837                 sprintf(buf, "lat %lluus: %p: ret %d: %s\n",
838                               u - wsi->latency_start, (void *)wsi, ret, action);
839
840         if (u - wsi->latency_start > context->worst_latency) {
841                 context->worst_latency = u - wsi->latency_start;
842                 strcpy(context->worst_latency_info, buf);
843         }
844         lwsl_latency("%s", buf);
845 }
846 #endif
847
848
849
850 /**
851  * lws_rx_flow_control() - Enable and disable socket servicing for
852  *                              received packets.
853  *
854  * If the output side of a server process becomes choked, this allows flow
855  * control for the input side.
856  *
857  * @wsi:        Websocket connection instance to get callback for
858  * @enable:     0 = disable read servicing for this connection, 1 = enable
859  */
860
861 LWS_VISIBLE int
862 lws_rx_flow_control(struct lws *wsi, int enable)
863 {
864         if (enable == (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW))
865                 return 0;
866
867         lwsl_info("%s: (0x%p, %d)\n", __func__, wsi, enable);
868         wsi->rxflow_change_to = LWS_RXFLOW_PENDING_CHANGE | !!enable;
869
870         return 0;
871 }
872
873 /**
874  * lws_rx_flow_allow_all_protocol() - Allow all connections with this protocol to receive
875  *
876  * When the user server code realizes it can accept more input, it can
877  * call this to have the RX flow restriction removed from all connections using
878  * the given protocol.
879  *
880  * @protocol:   all connections using this protocol will be allowed to receive
881  */
882
883 LWS_VISIBLE void
884 lws_rx_flow_allow_all_protocol(const struct lws_context *context,
885                                const struct lws_protocols *protocol)
886 {
887         const struct lws_context_per_thread *pt = &context->pt[0];
888         struct lws *wsi;
889         unsigned int n, m = context->count_threads;
890
891         while (m--) {
892                 for (n = 0; n < pt->fds_count; n++) {
893                         wsi = wsi_from_fd(context, pt->fds[n].fd);
894                         if (!wsi)
895                                 continue;
896                         if (wsi->protocol == protocol)
897                                 lws_rx_flow_control(wsi, LWS_RXFLOW_ALLOW);
898                 }
899                 pt++;
900         }
901 }
902
903
904 /**
905  * lws_canonical_hostname() - returns this host's hostname
906  *
907  * This is typically used by client code to fill in the host parameter
908  * when making a client connection.  You can only call it after the context
909  * has been created.
910  *
911  * @context:    Websocket context
912  */
913 LWS_VISIBLE extern const char *
914 lws_canonical_hostname(struct lws_context *context)
915 {
916         return (const char *)context->canonical_hostname;
917 }
918
919 int user_callback_handle_rxflow(lws_callback_function callback_function,
920                                 struct lws *wsi,
921                                 enum lws_callback_reasons reason, void *user,
922                                 void *in, size_t len)
923 {
924         int n;
925
926         n = callback_function(wsi, reason, user, in, len);
927         if (!n)
928                 n = _lws_rx_flow_control(wsi);
929
930         return n;
931 }
932
933
934 /**
935  * lws_set_proxy() - Setups proxy to lws_context.
936  * @context:    pointer to struct lws_context you want set proxy to
937  * @proxy: pointer to c string containing proxy in format address:port
938  *
939  * Returns 0 if proxy string was parsed and proxy was setup.
940  * Returns -1 if @proxy is NULL or has incorrect format.
941  *
942  * This is only required if your OS does not provide the http_proxy
943  * environment variable (eg, OSX)
944  *
945  *   IMPORTANT! You should call this function right after creation of the
946  *   lws_context and before call to connect. If you call this
947  *   function after connect behavior is undefined.
948  *   This function will override proxy settings made on lws_context
949  *   creation with genenv() call.
950  */
951
952 LWS_VISIBLE int
953 lws_set_proxy(struct lws_vhost *vhost, const char *proxy)
954 {
955         char *p;
956         char authstring[96];
957
958         if (!proxy)
959                 return -1;
960
961         p = strchr(proxy, '@');
962         if (p) { /* auth is around */
963
964                 if ((unsigned int)(p - proxy) > sizeof(authstring) - 1)
965                         goto auth_too_long;
966
967                 strncpy(authstring, proxy, p - proxy);
968                 // null termination not needed on input
969                 if (lws_b64_encode_string(authstring, (p - proxy),
970                                 vhost->proxy_basic_auth_token,
971                     sizeof vhost->proxy_basic_auth_token) < 0)
972                         goto auth_too_long;
973
974                 lwsl_notice(" Proxy auth in use\n");
975
976                 proxy = p + 1;
977         } else
978                 vhost->proxy_basic_auth_token[0] = '\0';
979
980         strncpy(vhost->http_proxy_address, proxy,
981                                 sizeof(vhost->http_proxy_address) - 1);
982         vhost->http_proxy_address[
983                                 sizeof(vhost->http_proxy_address) - 1] = '\0';
984
985         p = strchr(vhost->http_proxy_address, ':');
986         if (!p && !vhost->http_proxy_port) {
987                 lwsl_err("http_proxy needs to be ads:port\n");
988
989                 return -1;
990         } else {
991                 if (p) {
992                         *p = '\0';
993                         vhost->http_proxy_port = atoi(p + 1);
994                 }
995         }
996
997         lwsl_notice(" Proxy %s:%u\n", vhost->http_proxy_address,
998                         vhost->http_proxy_port);
999
1000         return 0;
1001
1002 auth_too_long:
1003         lwsl_err("proxy auth too long\n");
1004
1005         return -1;
1006 }
1007
1008 /**
1009  * lws_get_protocol() - Returns a protocol pointer from a websocket
1010  *                                connection.
1011  * @wsi:        pointer to struct websocket you want to know the protocol of
1012  *
1013  *
1014  *      Some apis can act on all live connections of a given protocol,
1015  *      this is how you can get a pointer to the active protocol if needed.
1016  */
1017
1018 LWS_VISIBLE const struct lws_protocols *
1019 lws_get_protocol(struct lws *wsi)
1020 {
1021         return wsi->protocol;
1022 }
1023
1024 LWS_VISIBLE int
1025 lws_is_final_fragment(struct lws *wsi)
1026 {
1027         lwsl_info("%s: final %d, rx pk length %d, draining %d", __func__,
1028                         wsi->u.ws.final, wsi->u.ws.rx_packet_length,
1029                         wsi->u.ws.rx_draining_ext);
1030         return wsi->u.ws.final && !wsi->u.ws.rx_packet_length && !wsi->u.ws.rx_draining_ext;
1031 }
1032
1033 LWS_VISIBLE unsigned char
1034 lws_get_reserved_bits(struct lws *wsi)
1035 {
1036         return wsi->u.ws.rsv;
1037 }
1038
1039 int
1040 lws_ensure_user_space(struct lws *wsi)
1041 {
1042         lwsl_info("%s: %p protocol %p\n", __func__, wsi, wsi->protocol);
1043         if (!wsi->protocol)
1044                 return 1;
1045
1046         /* allocate the per-connection user memory (if any) */
1047
1048         if (wsi->protocol->per_session_data_size && !wsi->user_space) {
1049                 wsi->user_space = lws_zalloc(wsi->protocol->per_session_data_size);
1050                 if (wsi->user_space  == NULL) {
1051                         lwsl_err("Out of memory for conn user space\n");
1052                         return 1;
1053                 }
1054         } else
1055                 lwsl_info("%s: %p protocol pss %u, user_space=%d\n",
1056                           __func__, wsi, wsi->protocol->per_session_data_size,
1057                           wsi->user_space);
1058         return 0;
1059 }
1060
1061 /**
1062  * lwsl_timestamp: generate logging timestamp string
1063  *
1064  * @level:      logging level
1065  * @p:          char * buffer to take timestamp
1066  * @len:        length of p
1067  *
1068  * returns length written in p
1069  */
1070 LWS_VISIBLE int
1071 lwsl_timestamp(int level, char *p, int len)
1072 {
1073         time_t o_now = time(NULL);
1074         unsigned long long now;
1075         struct tm *ptm = NULL;
1076 #ifndef WIN32
1077         struct tm tm;
1078 #endif
1079         int n;
1080
1081 #ifndef _WIN32_WCE
1082 #ifdef WIN32
1083         ptm = localtime(&o_now);
1084 #else
1085         if (localtime_r(&o_now, &tm))
1086                 ptm = &tm;
1087 #endif
1088 #endif
1089         p[0] = '\0';
1090         for (n = 0; n < LLL_COUNT; n++) {
1091                 if (level != (1 << n))
1092                         continue;
1093                 now = time_in_microseconds() / 100;
1094                 if (ptm)
1095                         n = snprintf(p, len,
1096                                 "[%04d/%02d/%02d %02d:%02d:%02d:%04d] %s: ",
1097                                 ptm->tm_year + 1900,
1098                                 ptm->tm_mon,
1099                                 ptm->tm_mday,
1100                                 ptm->tm_hour,
1101                                 ptm->tm_min,
1102                                 ptm->tm_sec,
1103                                 (int)(now % 10000), log_level_names[n]);
1104                 else
1105                         n = snprintf(p, len, "[%llu:%04d] %s: ",
1106                                         (unsigned long long) now / 10000,
1107                                         (int)(now % 10000), log_level_names[n]);
1108                 return n;
1109         }
1110
1111         return 0;
1112 }
1113
1114 LWS_VISIBLE void lwsl_emit_stderr(int level, const char *line)
1115 {
1116         char buf[50];
1117
1118         lwsl_timestamp(level, buf, sizeof(buf));
1119
1120         fprintf(stderr, "%s%s", buf, line);
1121 }
1122
1123 LWS_VISIBLE void _lws_logv(int filter, const char *format, va_list vl)
1124 {
1125         char buf[256];
1126
1127         if (!(log_level & filter))
1128                 return;
1129
1130         vsnprintf(buf, sizeof(buf), format, vl);
1131         buf[sizeof(buf) - 1] = '\0';
1132
1133         lwsl_emit(filter, buf);
1134 }
1135
1136 LWS_VISIBLE void _lws_log(int filter, const char *format, ...)
1137 {
1138         va_list ap;
1139
1140         va_start(ap, format);
1141         _lws_logv(filter, format, ap);
1142         va_end(ap);
1143 }
1144
1145 /**
1146  * lws_set_log_level() - Set the logging bitfield
1147  * @level:      OR together the LLL_ debug contexts you want output from
1148  * @log_emit_function:  NULL to leave it as it is, or a user-supplied
1149  *                      function to perform log string emission instead of
1150  *                      the default stderr one.
1151  *
1152  *      log level defaults to "err", "warn" and "notice" contexts enabled and
1153  *      emission on stderr.
1154  */
1155
1156 LWS_VISIBLE void lws_set_log_level(int level,
1157                                    void (*func)(int level, const char *line))
1158 {
1159         log_level = level;
1160         if (func)
1161                 lwsl_emit = func;
1162 }
1163
1164 /**
1165  * lws_use_ssl() - Find out if connection is using SSL
1166  * @wsi:        websocket connection to check
1167  *
1168  *      Returns 0 if the connection is not using SSL, 1 if using SSL and
1169  *      using verified cert, and 2 if using SSL but the cert was not
1170  *      checked (appears for client wsi told to skip check on connection)
1171  */
1172 LWS_VISIBLE int
1173 lws_is_ssl(struct lws *wsi)
1174 {
1175 #ifdef LWS_OPENSSL_SUPPORT
1176         return wsi->use_ssl;
1177 #else
1178         (void)wsi;
1179         return 0;
1180 #endif
1181 }
1182
1183 /**
1184  * lws_partial_buffered() - find out if lws buffered the last write
1185  * @wsi:        websocket connection to check
1186  *
1187  * Returns 1 if you cannot use lws_write because the last
1188  * write on this connection is still buffered, and can't be cleared without
1189  * returning to the service loop and waiting for the connection to be
1190  * writeable again.
1191  *
1192  * If you will try to do >1 lws_write call inside a single
1193  * WRITEABLE callback, you must check this after every write and bail if
1194  * set, ask for a new writeable callback and continue writing from there.
1195  *
1196  * This is never set at the start of a writeable callback, but any write
1197  * may set it.
1198  */
1199
1200 LWS_VISIBLE int
1201 lws_partial_buffered(struct lws *wsi)
1202 {
1203         return !!wsi->trunc_len;
1204 }
1205
1206 void lws_set_protocol_write_pending(struct lws *wsi,
1207                                     enum lws_pending_protocol_send pend)
1208 {
1209         lwsl_info("setting pps %d\n", pend);
1210
1211         if (wsi->pps)
1212                 lwsl_err("pps overwrite\n");
1213         wsi->pps = pend;
1214         lws_rx_flow_control(wsi, 0);
1215         lws_callback_on_writable(wsi);
1216 }
1217
1218 LWS_VISIBLE size_t
1219 lws_get_peer_write_allowance(struct lws *wsi)
1220 {
1221 #ifdef LWS_USE_HTTP2
1222         /* only if we are using HTTP2 on this connection */
1223         if (wsi->mode != LWSCM_HTTP2_SERVING)
1224                 return -1;
1225         /* user is only interested in how much he can send, or that he can't  */
1226         if (wsi->u.http2.tx_credit <= 0)
1227                 return 0;
1228
1229         return wsi->u.http2.tx_credit;
1230 #else
1231         (void)wsi;
1232         return -1;
1233 #endif
1234 }
1235
1236 LWS_VISIBLE void
1237 lws_union_transition(struct lws *wsi, enum connection_mode mode)
1238 {
1239         lwsl_debug("%s: %p: mode %d\n", __func__, wsi, mode);
1240         memset(&wsi->u, 0, sizeof(wsi->u));
1241         wsi->mode = mode;
1242 }
1243
1244 LWS_VISIBLE struct lws_plat_file_ops *
1245 lws_get_fops(struct lws_context *context)
1246 {
1247         return &context->fops;
1248 }
1249
1250 LWS_VISIBLE LWS_EXTERN struct lws_context *
1251 lws_get_context(const struct lws *wsi)
1252 {
1253         return wsi->context;
1254 }
1255
1256 LWS_VISIBLE LWS_EXTERN int
1257 lws_get_count_threads(struct lws_context *context)
1258 {
1259         return context->count_threads;
1260 }
1261
1262 LWS_VISIBLE LWS_EXTERN void *
1263 lws_wsi_user(struct lws *wsi)
1264 {
1265         return wsi->user_space;
1266 }
1267
1268 LWS_VISIBLE LWS_EXTERN struct lws *
1269 lws_get_parent(const struct lws *wsi)
1270 {
1271         return wsi->parent;
1272 }
1273
1274 LWS_VISIBLE LWS_EXTERN struct lws *
1275 lws_get_child(const struct lws *wsi)
1276 {
1277         return wsi->child_list;
1278 }
1279
1280 LWS_VISIBLE LWS_EXTERN void
1281 lws_close_reason(struct lws *wsi, enum lws_close_status status,
1282                  unsigned char *buf, size_t len)
1283 {
1284         unsigned char *p, *start;
1285         int budget = sizeof(wsi->u.ws.ping_payload_buf) - LWS_PRE;
1286
1287         assert(wsi->mode == LWSCM_WS_SERVING || wsi->mode == LWSCM_WS_CLIENT);
1288
1289         start = p = &wsi->u.ws.ping_payload_buf[LWS_PRE];
1290
1291         *p++ = (((int)status) >> 8) & 0xff;
1292         *p++ = ((int)status) & 0xff;
1293
1294         if (buf)
1295                 while (len-- && p < start + budget)
1296                         *p++ = *buf++;
1297
1298         wsi->u.ws.close_in_ping_buffer_len = p - start;
1299 }
1300
1301 LWS_EXTERN int
1302 _lws_rx_flow_control(struct lws *wsi)
1303 {
1304         /* there is no pending change */
1305         if (!(wsi->rxflow_change_to & LWS_RXFLOW_PENDING_CHANGE)) {
1306                 lwsl_debug("%s: no pending change\n", __func__);
1307                 return 0;
1308         }
1309
1310         /* stuff is still buffered, not ready to really accept new input */
1311         if (wsi->rxflow_buffer) {
1312                 /* get ourselves called back to deal with stashed buffer */
1313                 lws_callback_on_writable(wsi);
1314                 return 0;
1315         }
1316
1317         /* pending is cleared, we can change rxflow state */
1318
1319         wsi->rxflow_change_to &= ~LWS_RXFLOW_PENDING_CHANGE;
1320
1321         lwsl_info("rxflow: wsi %p change_to %d\n", wsi,
1322                               wsi->rxflow_change_to & LWS_RXFLOW_ALLOW);
1323
1324         /* adjust the pollfd for this wsi */
1325
1326         if (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW) {
1327                 if (lws_change_pollfd(wsi, 0, LWS_POLLIN)) {
1328                         lwsl_info("%s: fail\n", __func__);
1329                         return -1;
1330                 }
1331         } else
1332                 if (lws_change_pollfd(wsi, LWS_POLLIN, 0))
1333                         return -1;
1334
1335         return 0;
1336 }
1337
1338 LWS_EXTERN int
1339 lws_check_utf8(unsigned char *state, unsigned char *buf, size_t len)
1340 {
1341         static const unsigned char e0f4[] = {
1342                 0xa0 | ((2 - 1) << 2) | 1, /* e0 */
1343                 0x80 | ((4 - 1) << 2) | 1, /* e1 */
1344                 0x80 | ((4 - 1) << 2) | 1, /* e2 */
1345                 0x80 | ((4 - 1) << 2) | 1, /* e3 */
1346                 0x80 | ((4 - 1) << 2) | 1, /* e4 */
1347                 0x80 | ((4 - 1) << 2) | 1, /* e5 */
1348                 0x80 | ((4 - 1) << 2) | 1, /* e6 */
1349                 0x80 | ((4 - 1) << 2) | 1, /* e7 */
1350                 0x80 | ((4 - 1) << 2) | 1, /* e8 */
1351                 0x80 | ((4 - 1) << 2) | 1, /* e9 */
1352                 0x80 | ((4 - 1) << 2) | 1, /* ea */
1353                 0x80 | ((4 - 1) << 2) | 1, /* eb */
1354                 0x80 | ((4 - 1) << 2) | 1, /* ec */
1355                 0x80 | ((2 - 1) << 2) | 1, /* ed */
1356                 0x80 | ((4 - 1) << 2) | 1, /* ee */
1357                 0x80 | ((4 - 1) << 2) | 1, /* ef */
1358                 0x90 | ((3 - 1) << 2) | 2, /* f0 */
1359                 0x80 | ((4 - 1) << 2) | 2, /* f1 */
1360                 0x80 | ((4 - 1) << 2) | 2, /* f2 */
1361                 0x80 | ((4 - 1) << 2) | 2, /* f3 */
1362                 0x80 | ((1 - 1) << 2) | 2, /* f4 */
1363
1364                 0,                         /* s0 */
1365                 0x80 | ((4 - 1) << 2) | 0, /* s2 */
1366                 0x80 | ((4 - 1) << 2) | 1, /* s3 */
1367         };
1368         unsigned char s = *state;
1369
1370         while (len--) {
1371                 unsigned char c = *buf++;
1372
1373                 if (!s) {
1374                         if (c >= 0x80) {
1375                                 if (c < 0xc2 || c > 0xf4)
1376                                         return 1;
1377                                 if (c < 0xe0)
1378                                         s = 0x80 | ((4 - 1) << 2);
1379                                 else
1380                                         s = e0f4[c - 0xe0];
1381                         }
1382                 } else {
1383                         if (c < (s & 0xf0) ||
1384                             c >= (s & 0xf0) + 0x10 + ((s << 2) & 0x30))
1385                                 return 1;
1386                         s = e0f4[21 + (s & 3)];
1387                 }
1388         }
1389
1390         *state = s;
1391
1392         return 0;
1393 }
1394
1395 /**
1396  * lws_parse_uri:       cut up prot:/ads:port/path into pieces
1397  *                      Notice it does so by dropping '\0' into input string
1398  *                      and the leading / on the path is consequently lost
1399  *
1400  * @p:                  incoming uri string.. will get written to
1401  * @prot:               result pointer for protocol part (https://)
1402  * @ads:                result pointer for address part
1403  * @port:               result pointer for port part
1404  * @path:               result pointer for path part
1405  */
1406
1407 LWS_VISIBLE LWS_EXTERN int
1408 lws_parse_uri(char *p, const char **prot, const char **ads, int *port,
1409               const char **path)
1410 {
1411         const char *end;
1412         static const char *slash = "/";
1413
1414         /* cut up the location into address, port and path */
1415         *prot = p;
1416         while (*p && (*p != ':' || p[1] != '/' || p[2] != '/'))
1417                 p++;
1418         if (!*p) {
1419                 end = p;
1420                 p = (char *)*prot;
1421                 *prot = end;
1422         } else {
1423                 *p = '\0';
1424                 p += 3;
1425         }
1426         *ads = p;
1427         if (!strcmp(*prot, "http") || !strcmp(*prot, "ws"))
1428                 *port = 80;
1429         else if (!strcmp(*prot, "https") || !strcmp(*prot, "wss"))
1430                 *port = 443;
1431
1432         while (*p && *p != ':' && *p != '/')
1433                 p++;
1434         if (*p == ':') {
1435                 *p++ = '\0';
1436                 *port = atoi(p);
1437                 while (*p && *p != '/')
1438                         p++;
1439         }
1440         *path = slash;
1441         if (*p) {
1442                 *p++ = '\0';
1443                 if (*p)
1444                         *path = p;
1445         }
1446
1447         return 0;
1448 }
1449
1450 #ifdef LWS_NO_EXTENSIONS
1451
1452 /* we need to provide dummy callbacks for internal exts
1453  * so user code runs when faced with a lib compiled with
1454  * extensions disabled.
1455  */
1456
1457 int
1458 lws_extension_callback_pm_deflate(struct lws_context *context,
1459                                   const struct lws_extension *ext,
1460                                   struct lws *wsi,
1461                                   enum lws_extension_callback_reasons reason,
1462                                   void *user, void *in, size_t len)
1463 {
1464         (void)context;
1465         (void)ext;
1466         (void)wsi;
1467         (void)reason;
1468         (void)user;
1469         (void)in;
1470         (void)len;
1471
1472         return 0;
1473 }
1474 #endif
1475
1476 LWS_EXTERN int
1477 lws_socket_bind(struct lws_context *context, int sockfd, int port,
1478                 const char *iface)
1479 {
1480 #if LWS_POSIX
1481 #ifdef LWS_USE_IPV6
1482         struct sockaddr_in6 serv_addr6;
1483 #endif
1484         struct sockaddr_in serv_addr4;
1485         socklen_t len = sizeof(struct sockaddr);
1486         int n;
1487         struct sockaddr_in sin;
1488         struct sockaddr *v;
1489
1490 #ifdef LWS_USE_IPV6
1491         if (LWS_IPV6_ENABLED(context)) {
1492                 v = (struct sockaddr *)&serv_addr6;
1493                 n = sizeof(struct sockaddr_in6);
1494                 bzero((char *) &serv_addr6, sizeof(serv_addr6));
1495                 serv_addr6.sin6_addr = in6addr_any;
1496                 serv_addr6.sin6_family = AF_INET6;
1497                 serv_addr6.sin6_port = htons(port);
1498         } else
1499 #endif
1500         {
1501                 v = (struct sockaddr *)&serv_addr4;
1502                 n = sizeof(serv_addr4);
1503                 bzero((char *) &serv_addr4, sizeof(serv_addr4));
1504                 serv_addr4.sin_addr.s_addr = INADDR_ANY;
1505                 serv_addr4.sin_family = AF_INET;
1506
1507                 if (iface &&
1508                     interface_to_sa(context, iface,
1509                                     (struct sockaddr_in *)v, n) < 0) {
1510                         lwsl_err("Unable to find interface %s\n", iface);
1511                         return -1;
1512                 }
1513
1514                 serv_addr4.sin_port = htons(port);
1515         } /* ipv4 */
1516
1517         n = bind(sockfd, v, n);
1518         if (n < 0) {
1519                 lwsl_err("ERROR on binding fd %d to port %d (%d %d)\n",
1520                                 sockfd, port, n, LWS_ERRNO);
1521                 return -1;
1522         }
1523
1524         if (getsockname(sockfd, (struct sockaddr *)&sin, &len) == -1)
1525                 lwsl_warn("getsockname: %s\n", strerror(LWS_ERRNO));
1526         else
1527                 port = ntohs(sin.sin_port);
1528 #endif
1529
1530         return port;
1531 }
1532
1533 LWS_VISIBLE LWS_EXTERN int
1534 lws_urlencode(const char *in, int inlen, char *out, int outlen)
1535 {
1536         const char *hex = "0123456789ABCDEF";
1537         char *start = out, *end = out + outlen;
1538
1539         while (inlen-- && out < end - 4) {
1540                 if ((*in >= 'A' && *in <= 'Z') ||
1541                     (*in >= 'a' && *in <= 'z') ||
1542                     (*in >= '0' && *in <= '9') ||
1543                     *in == '-' ||
1544                     *in == '_' ||
1545                     *in == '.' ||
1546                     *in == '~')
1547                         *out++ = *in++;
1548                 else {
1549                         *out++ = '%';
1550                         *out++ = hex[(*in) >> 4];
1551                         *out++ = hex[(*in++) & 15];
1552                 }
1553         }
1554         *out = '\0';
1555
1556         if (out >= end - 4)
1557                 return -1;
1558
1559         return out - start;
1560 }
1561
1562 LWS_VISIBLE LWS_EXTERN int
1563 lws_finalize_startup(struct lws_context *context)
1564 {
1565         struct lws_context_creation_info info;
1566
1567         info.uid = context->uid;
1568         info.gid = context->gid;
1569
1570         if (lws_check_opt(context->options, LWS_SERVER_OPTION_EXPLICIT_VHOSTS))
1571                 lws_plat_drop_app_privileges(&info);
1572
1573         return 0;
1574 }
1575
1576
1577 LWS_VISIBLE LWS_EXTERN int
1578 lws_is_cgi(struct lws *wsi) {
1579 #ifdef LWS_WITH_CGI
1580         return !!wsi->cgi;
1581 #else
1582         return 0;
1583 #endif
1584 }
1585
1586 #ifdef LWS_WITH_CGI
1587
1588 static struct lws *
1589 lws_create_basic_wsi(struct lws_context *context, int tsi)
1590 {
1591         struct lws *new_wsi;
1592
1593         if ((unsigned int)context->pt[tsi].fds_count ==
1594             context->fd_limit_per_thread - 1) {
1595                 lwsl_err("no space for new conn\n");
1596                 return NULL;
1597         }
1598
1599         new_wsi = lws_zalloc(sizeof(struct lws));
1600         if (new_wsi == NULL) {
1601                 lwsl_err("Out of memory for new connection\n");
1602                 return NULL;
1603         }
1604
1605         new_wsi->tsi = tsi;
1606         new_wsi->context = context;
1607         new_wsi->pending_timeout = NO_PENDING_TIMEOUT;
1608         new_wsi->rxflow_change_to = LWS_RXFLOW_ALLOW;
1609
1610         /* intialize the instance struct */
1611
1612         new_wsi->state = LWSS_CGI;
1613         new_wsi->mode = LWSCM_CGI;
1614         new_wsi->hdr_parsing_completed = 0;
1615         new_wsi->position_in_fds_table = -1;
1616
1617         /*
1618          * these can only be set once the protocol is known
1619          * we set an unestablished connection's protocol pointer
1620          * to the start of the defauly vhost supported list, so it can look
1621          * for matching ones during the handshake
1622          */
1623         new_wsi->protocol = context->vhost_list->protocols;
1624         new_wsi->user_space = NULL;
1625         new_wsi->ietf_spec_revision = 0;
1626         new_wsi->sock = LWS_SOCK_INVALID;
1627         context->count_wsi_allocated++;
1628
1629         return new_wsi;
1630 }
1631
1632 /**
1633  * lws_cgi: spawn network-connected cgi process
1634  *
1635  * @wsi: connection to own the process
1636  * @exec_array: array of "exec-name" "arg1" ... "argn" NULL
1637  */
1638
1639 LWS_VISIBLE LWS_EXTERN int
1640 lws_cgi(struct lws *wsi, const char * const *exec_array, int script_uri_path_len,
1641         int timeout_secs, struct lws_protocol_vhost_options *mp_cgienv)
1642 {
1643         struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
1644         char *env_array[30], cgi_path[400], e[1024], *p = e,
1645              *end = p + sizeof(e) - 1, tok[256], *t;
1646         struct lws_cgi *cgi;
1647         int n, m, i;
1648
1649         /*
1650          * give the master wsi a cgi struct
1651          */
1652
1653         wsi->cgi = lws_zalloc(sizeof(*wsi->cgi));
1654         if (!wsi->cgi) {
1655                 lwsl_err("%s: OOM\n", __func__);
1656                 return -1;
1657         }
1658
1659         cgi = wsi->cgi;
1660         cgi->wsi = wsi; /* set cgi's owning wsi */
1661
1662         /* create pipes for [stdin|stdout] and [stderr] */
1663
1664         for (n = 0; n < 3; n++)
1665                 if (pipe(cgi->pipe_fds[n]) == -1)
1666                         goto bail1;
1667
1668         /* create cgi wsis for each stdin/out/err fd */
1669
1670         for (n = 0; n < 3; n++) {
1671                 cgi->stdwsi[n] = lws_create_basic_wsi(wsi->context, wsi->tsi);
1672                 if (!cgi->stdwsi[n])
1673                         goto bail2;
1674                 cgi->stdwsi[n]->cgi_channel = n;
1675                 cgi->stdwsi[n]->vhost = wsi->vhost;
1676
1677                 /* read side is 0, stdin we want the write side, others read */
1678                 cgi->stdwsi[n]->sock = cgi->pipe_fds[n][!!(n == 0)];
1679                 fcntl(cgi->pipe_fds[n][!!(n == 0)], F_SETFL, O_NONBLOCK);
1680         }
1681
1682         for (n = 0; n < 3; n++) {
1683                 lws_libuv_accept(cgi->stdwsi[n], cgi->stdwsi[n]->sock);
1684                 if (insert_wsi_socket_into_fds(wsi->context, cgi->stdwsi[n]))
1685                         goto bail3;
1686                 cgi->stdwsi[n]->parent = wsi;
1687                 cgi->stdwsi[n]->sibling_list = wsi->child_list;
1688                 wsi->child_list = cgi->stdwsi[n];
1689         }
1690
1691         lws_change_pollfd(cgi->stdwsi[LWS_STDIN], LWS_POLLIN, LWS_POLLOUT);
1692         lws_change_pollfd(cgi->stdwsi[LWS_STDOUT], LWS_POLLOUT, LWS_POLLIN);
1693         lws_change_pollfd(cgi->stdwsi[LWS_STDERR], LWS_POLLOUT, LWS_POLLIN);
1694
1695         lwsl_debug("%s: fds in %d, out %d, err %d\n", __func__,
1696                    cgi->stdwsi[LWS_STDIN]->sock, cgi->stdwsi[LWS_STDOUT]->sock,
1697                    cgi->stdwsi[LWS_STDERR]->sock);
1698
1699         lws_set_timeout(wsi, PENDING_TIMEOUT_CGI, timeout_secs);
1700
1701         /* the cgi stdout is always sending us http1.x header data first */
1702         wsi->hdr_state = LCHS_HEADER;
1703
1704         /* add us to the pt list of active cgis */
1705         cgi->cgi_list = pt->cgi_list;
1706         pt->cgi_list = cgi;
1707
1708         /* prepare his CGI env */
1709
1710         n = 0;
1711
1712         if (lws_is_ssl(wsi))
1713                 env_array[n++] = "HTTPS=ON";
1714         if (wsi->u.hdr.ah) {
1715                 snprintf(cgi_path, sizeof(cgi_path) - 1, "REQUEST_URI=%s",
1716                          lws_hdr_simple_ptr(wsi, WSI_TOKEN_GET_URI));
1717                 cgi_path[sizeof(cgi_path) - 1] = '\0';
1718                 env_array[n++] = cgi_path;
1719                 if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI))
1720                         env_array[n++] = "REQUEST_METHOD=POST";
1721                 else
1722                         env_array[n++] = "REQUEST_METHOD=GET";
1723
1724                 env_array[n++] = p;
1725                 p += snprintf(p, end - p, "QUERY_STRING=");
1726                 /* dump the individual URI Arg parameters */
1727                 m = 0;
1728                 while (1) {
1729                         i = lws_hdr_copy_fragment(wsi, tok, sizeof(tok),
1730                                              WSI_TOKEN_HTTP_URI_ARGS, m);
1731                         if (i < 0)
1732                                 break;
1733                         t = tok;
1734                         while (*t && *t != '=' && p < end - 4)
1735                                 *p++ = *t++;
1736                         if (*t == '=')
1737                                 *p++ = *t++;
1738                         i = lws_urlencode(t, i- (t - tok), p, end - p);
1739                         if (i > 0) {
1740                                 p += i;
1741                                 *p++ = '&';
1742                         }
1743                         m++;
1744                 }
1745                 if (m)
1746                         p--;
1747                 *p++ = '\0';
1748
1749                 env_array[n++] = p;
1750                 p += snprintf(p, end - p, "PATH_INFO=%s",
1751                               lws_hdr_simple_ptr(wsi, WSI_TOKEN_GET_URI) +
1752                               script_uri_path_len);
1753                 p++;
1754         }
1755         if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_REFERER)) {
1756                 env_array[n++] = p;
1757                 p += snprintf(p, end - p, "HTTP_REFERER=%s",
1758                               lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_REFERER));
1759                 p++;
1760         }
1761         if (lws_hdr_total_length(wsi, WSI_TOKEN_HOST)) {
1762                 env_array[n++] = p;
1763                 p += snprintf(p, end - p, "HTTP_HOST=%s",
1764                               lws_hdr_simple_ptr(wsi, WSI_TOKEN_HOST));
1765                 p++;
1766         }
1767         if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_USER_AGENT)) {
1768                 env_array[n++] = p;
1769                 p += snprintf(p, end - p, "USER_AGENT=%s",
1770                               lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_USER_AGENT));
1771                 p++;
1772         }
1773         env_array[n++] = p;
1774         p += snprintf(p, end - p, "SCRIPT_PATH=%s", exec_array[0]) + 1;
1775
1776         while (mp_cgienv) {
1777                 env_array[n++] = p;
1778                 p += snprintf(p, end - p, "%s=%s", mp_cgienv->name,
1779                               mp_cgienv->value);
1780                 lwsl_notice("   Applying mount-specific cgi env '%s'\n",
1781                             env_array[n - 1]);
1782                 p++;
1783                 mp_cgienv = mp_cgienv->next;
1784         }
1785
1786         env_array[n++] = "SERVER_SOFTWARE=libwebsockets";
1787         env_array[n++] = "PATH=/bin:/usr/bin:/usr/local/bin:/var/www/cgi-bin";
1788         env_array[n] = NULL;
1789
1790 #if 1
1791         for (m = 0; m < n; m++)
1792                 lwsl_err("    %s\n", env_array[m]);
1793 #endif
1794
1795         /* we are ready with the redirection pipes... run the thing */
1796 #if !defined(LWS_HAVE_VFORK) || !defined(LWS_HAVE_EXECVPE)
1797         cgi->pid = fork();
1798 #else
1799         cgi->pid = vfork();
1800 #endif
1801         if (cgi->pid < 0) {
1802                 lwsl_err("fork failed, errno %d", errno);
1803                 goto bail3;
1804         }
1805
1806         if (cgi->pid)
1807                 /* we are the parent process */
1808                 return 0;
1809
1810         /* somewhere we can at least read things and enter it */
1811         if (chdir("/"))
1812                 lwsl_notice("%s: Failed to chdir\n", __func__);
1813
1814         /* We are the forked process, redirect and kill inherited things.
1815          *
1816          * Because of vfork(), we cannot do anything that changes pages in
1817          * the parent environment.  Stuff that changes kernel state for the
1818          * process is OK.  Stuff that happens after the execvpe() is OK.
1819          */
1820
1821         for (n = 0; n < 3; n++) {
1822                 if (dup2(cgi->pipe_fds[n][!(n == 0)], n) < 0) {
1823                         lwsl_err("%s: stdin dup2 failed\n", __func__);
1824                         goto bail3;
1825                 }
1826                 close(cgi->pipe_fds[n][!(n == 0)]);
1827         }
1828
1829 #if !defined(LWS_HAVE_VFORK) || !defined(LWS_HAVE_EXECVPE)
1830         for (m = 0; m < n; m++) {
1831                 p = strchr(env_array[m], '=');
1832                 *p++ = '\0';
1833                 setenv(env_array[m], p, 1);
1834         }
1835         execvp(exec_array[0], (char * const *)&exec_array[0]);
1836 #else
1837         execvpe(exec_array[0], (char * const *)&exec_array[0], &env_array[0]);
1838 #endif
1839
1840         exit(1);
1841
1842 bail3:
1843         /* drop us from the pt cgi list */
1844         pt->cgi_list = cgi->cgi_list;
1845
1846         while (--n >= 0)
1847                 remove_wsi_socket_from_fds(wsi->cgi->stdwsi[n]);
1848 bail2:
1849         for (n = 0; n < 3; n++)
1850                 if (wsi->cgi->stdwsi[n])
1851                         lws_free_wsi(cgi->stdwsi[n]);
1852
1853 bail1:
1854         for (n = 0; n < 3; n++) {
1855                 if (cgi->pipe_fds[n][0])
1856                         close(cgi->pipe_fds[n][0]);
1857                 if (cgi->pipe_fds[n][1])
1858                         close(cgi->pipe_fds[n][1]);
1859         }
1860
1861         lws_free_set_NULL(wsi->cgi);
1862
1863         lwsl_err("%s: failed\n", __func__);
1864
1865         return -1;
1866 }
1867 /**
1868  * lws_cgi_write_split_headers: write cgi output accounting for header part
1869  *
1870  * @wsi: connection to own the process
1871  */
1872 LWS_VISIBLE LWS_EXTERN int
1873 lws_cgi_write_split_stdout_headers(struct lws *wsi)
1874 {
1875         int n, m;
1876         char buf[LWS_PRE + 1024], *start = &buf[LWS_PRE], *p = start,
1877              *end = &buf[sizeof(buf) - 1 - LWS_PRE], c;
1878
1879         while (wsi->hdr_state != LHCS_PAYLOAD) {
1880                 /* we have to separate header / finalize and
1881                  * payload chunks, since they need to be
1882                  * handled separately
1883                  */
1884                 n = read(lws_get_socket_fd(wsi->cgi->stdwsi[LWS_STDOUT]), &c, 1);
1885                 if (n < 0) {
1886                         if (errno != EAGAIN)
1887                                 return -1;
1888                         else
1889                                 n = 0;
1890                 }
1891                 if (n) {
1892                         //lwsl_err("-- %c\n", c);
1893                         switch (wsi->hdr_state) {
1894                         case LCHS_HEADER:
1895                                 *p++ = c;
1896                                 if (c == '\x0d') {
1897                                         wsi->hdr_state = LCHS_LF1;
1898                                         break;
1899                                 }
1900                                 break;
1901                         case LCHS_LF1:
1902                                 *p++ = c;
1903                                 if (c == '\x0a') {
1904                                         wsi->hdr_state = LCHS_CR2;
1905                                         break;
1906                                 }
1907                                 /* we got \r[^\n]... it's unreasonable */
1908                                 return -1;
1909                         case LCHS_CR2:
1910                                 if (c == '\x0d') {
1911                                         /* drop the \x0d */
1912                                         wsi->hdr_state = LCHS_LF2;
1913                                         break;
1914                                 }
1915                                 *p++ = c;
1916                                 break;
1917                         case LCHS_LF2:
1918                                 if (c == '\x0a') {
1919                                         wsi->hdr_state = LHCS_PAYLOAD;
1920                                         /* drop the \0xa ... finalize will add it if needed */
1921                                         lws_finalize_http_header(wsi,
1922                                                         (unsigned char **)&p,
1923                                                         (unsigned char *)end);
1924                                         break;
1925                                 }
1926                                 /* we got \r\n\r[^\n]... it's unreasonable */
1927                                 return -1;
1928                         case LHCS_PAYLOAD:
1929                                 break;
1930                         }
1931                 }
1932
1933                 /* ran out of input, ended the headers, or filled up the headers buf */
1934                 if (!n || wsi->hdr_state == LHCS_PAYLOAD || (p + 4) == end) {
1935
1936                         m = lws_write(wsi, (unsigned char *)start,
1937                                       p - start, LWS_WRITE_HTTP_HEADERS);
1938                         if (m < 0)
1939                                 return -1;
1940                         /* writeability becomes uncertain now we wrote
1941                          * something, we must return to the event loop
1942                          */
1943
1944                         return 0;
1945                 }
1946         }
1947         //lwsl_err("%s: stdout\n", __func__);
1948         n = read(lws_get_socket_fd(wsi->cgi->stdwsi[LWS_STDOUT]),
1949                  start, sizeof(buf) - LWS_PRE);
1950
1951         if (n < 0 && errno != EAGAIN)
1952                 return -1;
1953         if (n > 0) {
1954                 m = lws_write(wsi, (unsigned char *)start, n,
1955                               LWS_WRITE_HTTP);
1956                 //lwsl_notice("write %d\n", m);
1957                 if (m < 0)
1958                         return -1;
1959         }
1960
1961         return 0;
1962 }
1963
1964 /**
1965  * lws_cgi_kill: terminate cgi process associated with wsi
1966  *
1967  * @wsi: connection to own the process
1968  */
1969 LWS_VISIBLE LWS_EXTERN int
1970 lws_cgi_kill(struct lws *wsi)
1971 {
1972         struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
1973         struct lws_cgi **pcgi = &pt->cgi_list;
1974         struct lws_cgi_args args;
1975         int n, status, do_close = 0;
1976
1977         lwsl_debug("!!!!! %s: %p\n", __func__, wsi);
1978
1979         if (!wsi->cgi)
1980                 return 0;
1981
1982 //      lwsl_notice("%s: wsi %p\n", __func__, wsi);
1983
1984         assert(wsi->cgi);
1985
1986         if (wsi->cgi->pid > 0) {
1987                 /* kill the process */
1988                 n = kill(wsi->cgi->pid, SIGTERM);
1989                 if (n < 0) {
1990                         lwsl_err("%s: failed\n", __func__);
1991                         return 1;
1992                 }
1993                 waitpid(wsi->cgi->pid, &status, 0); /* !!! may hang !!! */
1994         }
1995
1996         args.stdwsi = &wsi->cgi->stdwsi[0];
1997
1998         if (wsi->cgi->pid != -1 && user_callback_handle_rxflow(
1999                         wsi->protocol->callback,
2000                         wsi, LWS_CALLBACK_CGI_TERMINATED,
2001                         wsi->user_space,
2002                         (void *)&args, 0)) {
2003                 wsi->cgi->pid = -1;
2004                 do_close = !wsi->cgi->being_closed;
2005         }
2006
2007         /* remove us from the cgi list */
2008         while (*pcgi) {
2009                 if (*pcgi == wsi->cgi) {
2010                         /* drop us from the pt cgi list */
2011                         *pcgi = (*pcgi)->cgi_list;
2012                         break;
2013                 }
2014                 pcgi = &(*pcgi)->cgi_list;
2015         }
2016
2017         if (!do_close)
2018                 for (n = 0 ; n < 3; n++) {
2019                         if (wsi->cgi->pipe_fds[n][!!(n == 0)] >= 0) {
2020                                 close(wsi->cgi->pipe_fds[n][!!(n == 0)]);
2021                                 wsi->cgi->pipe_fds[n][!!(n == 0)] = -1;
2022                         }
2023                 }
2024
2025         lws_free_set_NULL(wsi->cgi);
2026
2027         if (do_close) {
2028                 lwsl_debug("!!!!! %s: do_close\n", __func__);
2029                 lws_close_free_wsi(wsi, 0);
2030         }
2031
2032         return 0;
2033 }
2034
2035 LWS_EXTERN int
2036 lws_cgi_kill_terminated(struct lws_context_per_thread *pt)
2037 {
2038         struct lws_cgi **pcgi = &pt->cgi_list, *cgi;
2039         int status;
2040
2041         /* check all the subprocesses on the cgi list for termination */
2042         while (*pcgi) {
2043                 /* get the next one because we may close current one next */
2044                 cgi = *pcgi;
2045                 pcgi = &(*pcgi)->cgi_list;
2046
2047                 if (cgi->pid > 0 &&
2048                     waitpid(cgi->pid, &status, WNOHANG) > 0) {
2049                         cgi->pid = 0;
2050                         lws_cgi_kill(cgi->wsi);
2051                         pcgi = &pt->cgi_list;
2052                 }
2053         }
2054
2055         return 0;
2056 }
2057 #endif
2058
2059 #ifdef LWS_NO_EXTENSIONS
2060 LWS_EXTERN int
2061 lws_set_extension_option(struct lws *wsi, const char *ext_name,
2062                          const char *opt_name, const char *opt_val)
2063 {
2064         return -1;
2065 }
2066 #endif