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