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