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