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