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