Add the DragonFly cvs id and perform general cleanups on cvs/rcs/sccs ids. Most
[dragonfly.git] / crypto / openssh / channels.c
1 /*
2  * Author: Tatu Ylonen <ylo@cs.hut.fi>
3  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
4  *                    All rights reserved
5  * This file contains functions for generic socket connection forwarding.
6  * There is also code for initiating connection forwarding for X11 connections,
7  * arbitrary tcp/ip connections, and the authentication agent connection.
8  *
9  * As far as I am concerned, the code I have written for this software
10  * can be used freely for any purpose.  Any derived versions of this
11  * software must be clearly marked as such, and if the derived work is
12  * incompatible with the protocol description in the RFC file, it must be
13  * called by a name other than "ssh" or "Secure Shell".
14  *
15  * SSH2 support added by Markus Friedl.
16  * Copyright (c) 1999, 2000, 2001, 2002 Markus Friedl.  All rights reserved.
17  * Copyright (c) 1999 Dug Song.  All rights reserved.
18  * Copyright (c) 1999 Theo de Raadt.  All rights reserved.
19  *
20  * Redistribution and use in source and binary forms, with or without
21  * modification, are permitted provided that the following conditions
22  * are met:
23  * 1. Redistributions of source code must retain the above copyright
24  *    notice, this list of conditions and the following disclaimer.
25  * 2. Redistributions in binary form must reproduce the above copyright
26  *    notice, this list of conditions and the following disclaimer in the
27  *    documentation and/or other materials provided with the distribution.
28  *
29  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
30  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
31  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
32  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
33  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
34  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
35  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
36  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
37  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
38  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39  */
40
41 #include "includes.h"
42 RCSID("$OpenBSD: channels.c,v 1.183 2002/09/17 07:47:02 itojun Exp $");
43 RCSID("$FreeBSD: src/crypto/openssh/channels.c,v 1.1.1.1.2.8 2003/02/03 17:31:06 des Exp $");
44 RCSID("$DragonFly: src/crypto/openssh/Attic/channels.c,v 1.2 2003/06/17 04:24:36 dillon Exp $");
45
46 #include "ssh.h"
47 #include "ssh1.h"
48 #include "ssh2.h"
49 #include "packet.h"
50 #include "xmalloc.h"
51 #include "log.h"
52 #include "misc.h"
53 #include "channels.h"
54 #include "compat.h"
55 #include "canohost.h"
56 #include "key.h"
57 #include "authfd.h"
58 #include "pathnames.h"
59
60
61 /* -- channel core */
62
63 /*
64  * Pointer to an array containing all allocated channels.  The array is
65  * dynamically extended as needed.
66  */
67 static Channel **channels = NULL;
68
69 /*
70  * Size of the channel array.  All slots of the array must always be
71  * initialized (at least the type field); unused slots set to NULL
72  */
73 static int channels_alloc = 0;
74
75 /*
76  * Maximum file descriptor value used in any of the channels.  This is
77  * updated in channel_new.
78  */
79 static int channel_max_fd = 0;
80
81
82 /* -- tcp forwarding */
83
84 /*
85  * Data structure for storing which hosts are permitted for forward requests.
86  * The local sides of any remote forwards are stored in this array to prevent
87  * a corrupt remote server from accessing arbitrary TCP/IP ports on our local
88  * network (which might be behind a firewall).
89  */
90 typedef struct {
91         char *host_to_connect;          /* Connect to 'host'. */
92         u_short port_to_connect;        /* Connect to 'port'. */
93         u_short listen_port;            /* Remote side should listen port number. */
94 } ForwardPermission;
95
96 /* List of all permitted host/port pairs to connect. */
97 static ForwardPermission permitted_opens[SSH_MAX_FORWARDS_PER_DIRECTION];
98
99 /* Number of permitted host/port pairs in the array. */
100 static int num_permitted_opens = 0;
101 /*
102  * If this is true, all opens are permitted.  This is the case on the server
103  * on which we have to trust the client anyway, and the user could do
104  * anything after logging in anyway.
105  */
106 static int all_opens_permitted = 0;
107
108
109 /* -- X11 forwarding */
110
111 /* Maximum number of fake X11 displays to try. */
112 #define MAX_DISPLAYS  1000
113
114 /* Saved X11 authentication protocol name. */
115 static char *x11_saved_proto = NULL;
116
117 /* Saved X11 authentication data.  This is the real data. */
118 static char *x11_saved_data = NULL;
119 static u_int x11_saved_data_len = 0;
120
121 /*
122  * Fake X11 authentication data.  This is what the server will be sending us;
123  * we should replace any occurrences of this by the real data.
124  */
125 static char *x11_fake_data = NULL;
126 static u_int x11_fake_data_len;
127
128
129 /* -- agent forwarding */
130
131 #define NUM_SOCKS       10
132
133 /* AF_UNSPEC or AF_INET or AF_INET6 */
134 static int IPv4or6 = AF_UNSPEC;
135
136 /* helper */
137 static void port_open_helper(Channel *c, char *rtype);
138
139 /* -- channel core */
140
141 Channel *
142 channel_lookup(int id)
143 {
144         Channel *c;
145
146         if (id < 0 || id >= channels_alloc) {
147                 log("channel_lookup: %d: bad id", id);
148                 return NULL;
149         }
150         c = channels[id];
151         if (c == NULL) {
152                 log("channel_lookup: %d: bad id: channel free", id);
153                 return NULL;
154         }
155         return c;
156 }
157
158 /*
159  * Register filedescriptors for a channel, used when allocating a channel or
160  * when the channel consumer/producer is ready, e.g. shell exec'd
161  */
162
163 static void
164 channel_register_fds(Channel *c, int rfd, int wfd, int efd,
165     int extusage, int nonblock)
166 {
167         /* Update the maximum file descriptor value. */
168         channel_max_fd = MAX(channel_max_fd, rfd);
169         channel_max_fd = MAX(channel_max_fd, wfd);
170         channel_max_fd = MAX(channel_max_fd, efd);
171
172         /* XXX set close-on-exec -markus */
173
174         c->rfd = rfd;
175         c->wfd = wfd;
176         c->sock = (rfd == wfd) ? rfd : -1;
177         c->efd = efd;
178         c->extended_usage = extusage;
179
180         /* XXX ugly hack: nonblock is only set by the server */
181         if (nonblock && isatty(c->rfd)) {
182                 debug("channel %d: rfd %d isatty", c->self, c->rfd);
183                 c->isatty = 1;
184                 if (!isatty(c->wfd)) {
185                         error("channel %d: wfd %d is not a tty?",
186                             c->self, c->wfd);
187                 }
188         } else {
189                 c->isatty = 0;
190         }
191         c->wfd_isatty = isatty(c->wfd);
192
193         /* enable nonblocking mode */
194         if (nonblock) {
195                 if (rfd != -1)
196                         set_nonblock(rfd);
197                 if (wfd != -1)
198                         set_nonblock(wfd);
199                 if (efd != -1)
200                         set_nonblock(efd);
201         }
202 }
203
204 /*
205  * Allocate a new channel object and set its type and socket. This will cause
206  * remote_name to be freed.
207  */
208
209 Channel *
210 channel_new(char *ctype, int type, int rfd, int wfd, int efd,
211     u_int window, u_int maxpack, int extusage, char *remote_name, int nonblock)
212 {
213         int i, found;
214         Channel *c;
215
216         /* Do initial allocation if this is the first call. */
217         if (channels_alloc == 0) {
218                 channels_alloc = 10;
219                 channels = xmalloc(channels_alloc * sizeof(Channel *));
220                 for (i = 0; i < channels_alloc; i++)
221                         channels[i] = NULL;
222                 fatal_add_cleanup((void (*) (void *)) channel_free_all, NULL);
223         }
224         /* Try to find a free slot where to put the new channel. */
225         for (found = -1, i = 0; i < channels_alloc; i++)
226                 if (channels[i] == NULL) {
227                         /* Found a free slot. */
228                         found = i;
229                         break;
230                 }
231         if (found == -1) {
232                 /* There are no free slots.  Take last+1 slot and expand the array.  */
233                 found = channels_alloc;
234                 channels_alloc += 10;
235                 if (channels_alloc > 10000)
236                         fatal("channel_new: internal error: channels_alloc %d "
237                             "too big.", channels_alloc);
238                 debug2("channel: expanding %d", channels_alloc);
239                 channels = xrealloc(channels, channels_alloc * sizeof(Channel *));
240                 for (i = found; i < channels_alloc; i++)
241                         channels[i] = NULL;
242         }
243         /* Initialize and return new channel. */
244         c = channels[found] = xmalloc(sizeof(Channel));
245         memset(c, 0, sizeof(Channel));
246         buffer_init(&c->input);
247         buffer_init(&c->output);
248         buffer_init(&c->extended);
249         c->ostate = CHAN_OUTPUT_OPEN;
250         c->istate = CHAN_INPUT_OPEN;
251         c->flags = 0;
252         channel_register_fds(c, rfd, wfd, efd, extusage, nonblock);
253         c->self = found;
254         c->type = type;
255         c->ctype = ctype;
256         c->local_window = window;
257         c->local_window_max = window;
258         c->local_consumed = 0;
259         c->local_maxpacket = maxpack;
260         c->remote_id = -1;
261         c->remote_name = remote_name;
262         c->remote_window = 0;
263         c->remote_maxpacket = 0;
264         c->force_drain = 0;
265         c->single_connection = 0;
266         c->detach_user = NULL;
267         c->confirm = NULL;
268         c->input_filter = NULL;
269         debug("channel %d: new [%s]", found, remote_name);
270         return c;
271 }
272
273 static int
274 channel_find_maxfd(void)
275 {
276         int i, max = 0;
277         Channel *c;
278
279         for (i = 0; i < channels_alloc; i++) {
280                 c = channels[i];
281                 if (c != NULL) {
282                         max = MAX(max, c->rfd);
283                         max = MAX(max, c->wfd);
284                         max = MAX(max, c->efd);
285                 }
286         }
287         return max;
288 }
289
290 int
291 channel_close_fd(int *fdp)
292 {
293         int ret = 0, fd = *fdp;
294
295         if (fd != -1) {
296                 ret = close(fd);
297                 *fdp = -1;
298                 if (fd == channel_max_fd)
299                         channel_max_fd = channel_find_maxfd();
300         }
301         return ret;
302 }
303
304 /* Close all channel fd/socket. */
305
306 static void
307 channel_close_fds(Channel *c)
308 {
309         debug3("channel_close_fds: channel %d: r %d w %d e %d",
310             c->self, c->rfd, c->wfd, c->efd);
311
312         channel_close_fd(&c->sock);
313         channel_close_fd(&c->rfd);
314         channel_close_fd(&c->wfd);
315         channel_close_fd(&c->efd);
316 }
317
318 /* Free the channel and close its fd/socket. */
319
320 void
321 channel_free(Channel *c)
322 {
323         char *s;
324         int i, n;
325
326         for (n = 0, i = 0; i < channels_alloc; i++)
327                 if (channels[i])
328                         n++;
329         debug("channel_free: channel %d: %s, nchannels %d", c->self,
330             c->remote_name ? c->remote_name : "???", n);
331
332         s = channel_open_message();
333         debug3("channel_free: status: %s", s);
334         xfree(s);
335
336         if (c->sock != -1)
337                 shutdown(c->sock, SHUT_RDWR);
338         channel_close_fds(c);
339         buffer_free(&c->input);
340         buffer_free(&c->output);
341         buffer_free(&c->extended);
342         if (c->remote_name) {
343                 xfree(c->remote_name);
344                 c->remote_name = NULL;
345         }
346         channels[c->self] = NULL;
347         xfree(c);
348 }
349
350 void
351 channel_free_all(void)
352 {
353         int i;
354
355         for (i = 0; i < channels_alloc; i++)
356                 if (channels[i] != NULL)
357                         channel_free(channels[i]);
358 }
359
360 /*
361  * Closes the sockets/fds of all channels.  This is used to close extra file
362  * descriptors after a fork.
363  */
364
365 void
366 channel_close_all(void)
367 {
368         int i;
369
370         for (i = 0; i < channels_alloc; i++)
371                 if (channels[i] != NULL)
372                         channel_close_fds(channels[i]);
373 }
374
375 /*
376  * Stop listening to channels.
377  */
378
379 void
380 channel_stop_listening(void)
381 {
382         int i;
383         Channel *c;
384
385         for (i = 0; i < channels_alloc; i++) {
386                 c = channels[i];
387                 if (c != NULL) {
388                         switch (c->type) {
389                         case SSH_CHANNEL_AUTH_SOCKET:
390                         case SSH_CHANNEL_PORT_LISTENER:
391                         case SSH_CHANNEL_RPORT_LISTENER:
392                         case SSH_CHANNEL_X11_LISTENER:
393                                 channel_close_fd(&c->sock);
394                                 channel_free(c);
395                                 break;
396                         }
397                 }
398         }
399 }
400
401 /*
402  * Returns true if no channel has too much buffered data, and false if one or
403  * more channel is overfull.
404  */
405
406 int
407 channel_not_very_much_buffered_data(void)
408 {
409         u_int i;
410         Channel *c;
411
412         for (i = 0; i < channels_alloc; i++) {
413                 c = channels[i];
414                 if (c != NULL && c->type == SSH_CHANNEL_OPEN) {
415 #if 0
416                         if (!compat20 &&
417                             buffer_len(&c->input) > packet_get_maxsize()) {
418                                 debug("channel %d: big input buffer %d",
419                                     c->self, buffer_len(&c->input));
420                                 return 0;
421                         }
422 #endif
423                         if (buffer_len(&c->output) > packet_get_maxsize()) {
424                                 debug("channel %d: big output buffer %d > %d",
425                                     c->self, buffer_len(&c->output),
426                                     packet_get_maxsize());
427                                 return 0;
428                         }
429                 }
430         }
431         return 1;
432 }
433
434 /* Returns true if any channel is still open. */
435
436 int
437 channel_still_open(void)
438 {
439         int i;
440         Channel *c;
441
442         for (i = 0; i < channels_alloc; i++) {
443                 c = channels[i];
444                 if (c == NULL)
445                         continue;
446                 switch (c->type) {
447                 case SSH_CHANNEL_X11_LISTENER:
448                 case SSH_CHANNEL_PORT_LISTENER:
449                 case SSH_CHANNEL_RPORT_LISTENER:
450                 case SSH_CHANNEL_CLOSED:
451                 case SSH_CHANNEL_AUTH_SOCKET:
452                 case SSH_CHANNEL_DYNAMIC:
453                 case SSH_CHANNEL_CONNECTING:
454                 case SSH_CHANNEL_ZOMBIE:
455                         continue;
456                 case SSH_CHANNEL_LARVAL:
457                         if (!compat20)
458                                 fatal("cannot happen: SSH_CHANNEL_LARVAL");
459                         continue;
460                 case SSH_CHANNEL_OPENING:
461                 case SSH_CHANNEL_OPEN:
462                 case SSH_CHANNEL_X11_OPEN:
463                         return 1;
464                 case SSH_CHANNEL_INPUT_DRAINING:
465                 case SSH_CHANNEL_OUTPUT_DRAINING:
466                         if (!compat13)
467                                 fatal("cannot happen: OUT_DRAIN");
468                         return 1;
469                 default:
470                         fatal("channel_still_open: bad channel type %d", c->type);
471                         /* NOTREACHED */
472                 }
473         }
474         return 0;
475 }
476
477 /* Returns the id of an open channel suitable for keepaliving */
478
479 int
480 channel_find_open(void)
481 {
482         int i;
483         Channel *c;
484
485         for (i = 0; i < channels_alloc; i++) {
486                 c = channels[i];
487                 if (c == NULL)
488                         continue;
489                 switch (c->type) {
490                 case SSH_CHANNEL_CLOSED:
491                 case SSH_CHANNEL_DYNAMIC:
492                 case SSH_CHANNEL_X11_LISTENER:
493                 case SSH_CHANNEL_PORT_LISTENER:
494                 case SSH_CHANNEL_RPORT_LISTENER:
495                 case SSH_CHANNEL_OPENING:
496                 case SSH_CHANNEL_CONNECTING:
497                 case SSH_CHANNEL_ZOMBIE:
498                         continue;
499                 case SSH_CHANNEL_LARVAL:
500                 case SSH_CHANNEL_AUTH_SOCKET:
501                 case SSH_CHANNEL_OPEN:
502                 case SSH_CHANNEL_X11_OPEN:
503                         return i;
504                 case SSH_CHANNEL_INPUT_DRAINING:
505                 case SSH_CHANNEL_OUTPUT_DRAINING:
506                         if (!compat13)
507                                 fatal("cannot happen: OUT_DRAIN");
508                         return i;
509                 default:
510                         fatal("channel_find_open: bad channel type %d", c->type);
511                         /* NOTREACHED */
512                 }
513         }
514         return -1;
515 }
516
517
518 /*
519  * Returns a message describing the currently open forwarded connections,
520  * suitable for sending to the client.  The message contains crlf pairs for
521  * newlines.
522  */
523
524 char *
525 channel_open_message(void)
526 {
527         Buffer buffer;
528         Channel *c;
529         char buf[1024], *cp;
530         int i;
531
532         buffer_init(&buffer);
533         snprintf(buf, sizeof buf, "The following connections are open:\r\n");
534         buffer_append(&buffer, buf, strlen(buf));
535         for (i = 0; i < channels_alloc; i++) {
536                 c = channels[i];
537                 if (c == NULL)
538                         continue;
539                 switch (c->type) {
540                 case SSH_CHANNEL_X11_LISTENER:
541                 case SSH_CHANNEL_PORT_LISTENER:
542                 case SSH_CHANNEL_RPORT_LISTENER:
543                 case SSH_CHANNEL_CLOSED:
544                 case SSH_CHANNEL_AUTH_SOCKET:
545                 case SSH_CHANNEL_ZOMBIE:
546                         continue;
547                 case SSH_CHANNEL_LARVAL:
548                 case SSH_CHANNEL_OPENING:
549                 case SSH_CHANNEL_CONNECTING:
550                 case SSH_CHANNEL_DYNAMIC:
551                 case SSH_CHANNEL_OPEN:
552                 case SSH_CHANNEL_X11_OPEN:
553                 case SSH_CHANNEL_INPUT_DRAINING:
554                 case SSH_CHANNEL_OUTPUT_DRAINING:
555                         snprintf(buf, sizeof buf, "  #%d %.300s (t%d r%d i%d/%d o%d/%d fd %d/%d)\r\n",
556                             c->self, c->remote_name,
557                             c->type, c->remote_id,
558                             c->istate, buffer_len(&c->input),
559                             c->ostate, buffer_len(&c->output),
560                             c->rfd, c->wfd);
561                         buffer_append(&buffer, buf, strlen(buf));
562                         continue;
563                 default:
564                         fatal("channel_open_message: bad channel type %d", c->type);
565                         /* NOTREACHED */
566                 }
567         }
568         buffer_append(&buffer, "\0", 1);
569         cp = xstrdup(buffer_ptr(&buffer));
570         buffer_free(&buffer);
571         return cp;
572 }
573
574 void
575 channel_send_open(int id)
576 {
577         Channel *c = channel_lookup(id);
578
579         if (c == NULL) {
580                 log("channel_send_open: %d: bad id", id);
581                 return;
582         }
583         debug("send channel open %d", id);
584         packet_start(SSH2_MSG_CHANNEL_OPEN);
585         packet_put_cstring(c->ctype);
586         packet_put_int(c->self);
587         packet_put_int(c->local_window);
588         packet_put_int(c->local_maxpacket);
589         packet_send();
590 }
591
592 void
593 channel_request_start(int local_id, char *service, int wantconfirm)
594 {
595         Channel *c = channel_lookup(local_id);
596
597         if (c == NULL) {
598                 log("channel_request_start: %d: unknown channel id", local_id);
599                 return;
600         }
601         debug("channel request %d: %s", local_id, service) ;
602         packet_start(SSH2_MSG_CHANNEL_REQUEST);
603         packet_put_int(c->remote_id);
604         packet_put_cstring(service);
605         packet_put_char(wantconfirm);
606 }
607 void
608 channel_register_confirm(int id, channel_callback_fn *fn)
609 {
610         Channel *c = channel_lookup(id);
611
612         if (c == NULL) {
613                 log("channel_register_comfirm: %d: bad id", id);
614                 return;
615         }
616         c->confirm = fn;
617 }
618 void
619 channel_register_cleanup(int id, channel_callback_fn *fn)
620 {
621         Channel *c = channel_lookup(id);
622
623         if (c == NULL) {
624                 log("channel_register_cleanup: %d: bad id", id);
625                 return;
626         }
627         c->detach_user = fn;
628 }
629 void
630 channel_cancel_cleanup(int id)
631 {
632         Channel *c = channel_lookup(id);
633
634         if (c == NULL) {
635                 log("channel_cancel_cleanup: %d: bad id", id);
636                 return;
637         }
638         c->detach_user = NULL;
639 }
640 void
641 channel_register_filter(int id, channel_filter_fn *fn)
642 {
643         Channel *c = channel_lookup(id);
644
645         if (c == NULL) {
646                 log("channel_register_filter: %d: bad id", id);
647                 return;
648         }
649         c->input_filter = fn;
650 }
651
652 void
653 channel_set_fds(int id, int rfd, int wfd, int efd,
654     int extusage, int nonblock, u_int window_max)
655 {
656         Channel *c = channel_lookup(id);
657
658         if (c == NULL || c->type != SSH_CHANNEL_LARVAL)
659                 fatal("channel_activate for non-larval channel %d.", id);
660         channel_register_fds(c, rfd, wfd, efd, extusage, nonblock);
661         c->type = SSH_CHANNEL_OPEN;
662         c->local_window = c->local_window_max = window_max;
663         packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
664         packet_put_int(c->remote_id);
665         packet_put_int(c->local_window);
666         packet_send();
667 }
668
669 /*
670  * 'channel_pre*' are called just before select() to add any bits relevant to
671  * channels in the select bitmasks.
672  */
673 /*
674  * 'channel_post*': perform any appropriate operations for channels which
675  * have events pending.
676  */
677 typedef void chan_fn(Channel *c, fd_set * readset, fd_set * writeset);
678 chan_fn *channel_pre[SSH_CHANNEL_MAX_TYPE];
679 chan_fn *channel_post[SSH_CHANNEL_MAX_TYPE];
680
681 static void
682 channel_pre_listener(Channel *c, fd_set * readset, fd_set * writeset)
683 {
684         FD_SET(c->sock, readset);
685 }
686
687 static void
688 channel_pre_connecting(Channel *c, fd_set * readset, fd_set * writeset)
689 {
690         debug3("channel %d: waiting for connection", c->self);
691         FD_SET(c->sock, writeset);
692 }
693
694 static void
695 channel_pre_open_13(Channel *c, fd_set * readset, fd_set * writeset)
696 {
697         if (buffer_len(&c->input) < packet_get_maxsize())
698                 FD_SET(c->sock, readset);
699         if (buffer_len(&c->output) > 0)
700                 FD_SET(c->sock, writeset);
701 }
702
703 static void
704 channel_pre_open(Channel *c, fd_set * readset, fd_set * writeset)
705 {
706         u_int limit = compat20 ? c->remote_window : packet_get_maxsize();
707
708         if (c->istate == CHAN_INPUT_OPEN &&
709             limit > 0 &&
710             buffer_len(&c->input) < limit)
711                 FD_SET(c->rfd, readset);
712         if (c->ostate == CHAN_OUTPUT_OPEN ||
713             c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
714                 if (buffer_len(&c->output) > 0) {
715                         FD_SET(c->wfd, writeset);
716                 } else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
717                         if (CHANNEL_EFD_OUTPUT_ACTIVE(c))
718                                debug2("channel %d: obuf_empty delayed efd %d/(%d)",
719                                    c->self, c->efd, buffer_len(&c->extended));
720                         else
721                                 chan_obuf_empty(c);
722                 }
723         }
724         /** XXX check close conditions, too */
725         if (compat20 && c->efd != -1) {
726                 if (c->extended_usage == CHAN_EXTENDED_WRITE &&
727                     buffer_len(&c->extended) > 0)
728                         FD_SET(c->efd, writeset);
729                 else if (!(c->flags & CHAN_EOF_SENT) &&
730                     c->extended_usage == CHAN_EXTENDED_READ &&
731                     buffer_len(&c->extended) < c->remote_window)
732                         FD_SET(c->efd, readset);
733         }
734 }
735
736 static void
737 channel_pre_input_draining(Channel *c, fd_set * readset, fd_set * writeset)
738 {
739         if (buffer_len(&c->input) == 0) {
740                 packet_start(SSH_MSG_CHANNEL_CLOSE);
741                 packet_put_int(c->remote_id);
742                 packet_send();
743                 c->type = SSH_CHANNEL_CLOSED;
744                 debug("channel %d: closing after input drain.", c->self);
745         }
746 }
747
748 static void
749 channel_pre_output_draining(Channel *c, fd_set * readset, fd_set * writeset)
750 {
751         if (buffer_len(&c->output) == 0)
752                 chan_mark_dead(c);
753         else
754                 FD_SET(c->sock, writeset);
755 }
756
757 /*
758  * This is a special state for X11 authentication spoofing.  An opened X11
759  * connection (when authentication spoofing is being done) remains in this
760  * state until the first packet has been completely read.  The authentication
761  * data in that packet is then substituted by the real data if it matches the
762  * fake data, and the channel is put into normal mode.
763  * XXX All this happens at the client side.
764  * Returns: 0 = need more data, -1 = wrong cookie, 1 = ok
765  */
766 static int
767 x11_open_helper(Buffer *b)
768 {
769         u_char *ucp;
770         u_int proto_len, data_len;
771
772         /* Check if the fixed size part of the packet is in buffer. */
773         if (buffer_len(b) < 12)
774                 return 0;
775
776         /* Parse the lengths of variable-length fields. */
777         ucp = buffer_ptr(b);
778         if (ucp[0] == 0x42) {   /* Byte order MSB first. */
779                 proto_len = 256 * ucp[6] + ucp[7];
780                 data_len = 256 * ucp[8] + ucp[9];
781         } else if (ucp[0] == 0x6c) {    /* Byte order LSB first. */
782                 proto_len = ucp[6] + 256 * ucp[7];
783                 data_len = ucp[8] + 256 * ucp[9];
784         } else {
785                 debug("Initial X11 packet contains bad byte order byte: 0x%x",
786                     ucp[0]);
787                 return -1;
788         }
789
790         /* Check if the whole packet is in buffer. */
791         if (buffer_len(b) <
792             12 + ((proto_len + 3) & ~3) + ((data_len + 3) & ~3))
793                 return 0;
794
795         /* Check if authentication protocol matches. */
796         if (proto_len != strlen(x11_saved_proto) ||
797             memcmp(ucp + 12, x11_saved_proto, proto_len) != 0) {
798                 debug("X11 connection uses different authentication protocol.");
799                 return -1;
800         }
801         /* Check if authentication data matches our fake data. */
802         if (data_len != x11_fake_data_len ||
803             memcmp(ucp + 12 + ((proto_len + 3) & ~3),
804                 x11_fake_data, x11_fake_data_len) != 0) {
805                 debug("X11 auth data does not match fake data.");
806                 return -1;
807         }
808         /* Check fake data length */
809         if (x11_fake_data_len != x11_saved_data_len) {
810                 error("X11 fake_data_len %d != saved_data_len %d",
811                     x11_fake_data_len, x11_saved_data_len);
812                 return -1;
813         }
814         /*
815          * Received authentication protocol and data match
816          * our fake data. Substitute the fake data with real
817          * data.
818          */
819         memcpy(ucp + 12 + ((proto_len + 3) & ~3),
820             x11_saved_data, x11_saved_data_len);
821         return 1;
822 }
823
824 static void
825 channel_pre_x11_open_13(Channel *c, fd_set * readset, fd_set * writeset)
826 {
827         int ret = x11_open_helper(&c->output);
828
829         if (ret == 1) {
830                 /* Start normal processing for the channel. */
831                 c->type = SSH_CHANNEL_OPEN;
832                 channel_pre_open_13(c, readset, writeset);
833         } else if (ret == -1) {
834                 /*
835                  * We have received an X11 connection that has bad
836                  * authentication information.
837                  */
838                 log("X11 connection rejected because of wrong authentication.");
839                 buffer_clear(&c->input);
840                 buffer_clear(&c->output);
841                 channel_close_fd(&c->sock);
842                 c->sock = -1;
843                 c->type = SSH_CHANNEL_CLOSED;
844                 packet_start(SSH_MSG_CHANNEL_CLOSE);
845                 packet_put_int(c->remote_id);
846                 packet_send();
847         }
848 }
849
850 static void
851 channel_pre_x11_open(Channel *c, fd_set * readset, fd_set * writeset)
852 {
853         int ret = x11_open_helper(&c->output);
854
855         /* c->force_drain = 1; */
856
857         if (ret == 1) {
858                 c->type = SSH_CHANNEL_OPEN;
859                 channel_pre_open(c, readset, writeset);
860         } else if (ret == -1) {
861                 log("X11 connection rejected because of wrong authentication.");
862                 debug("X11 rejected %d i%d/o%d", c->self, c->istate, c->ostate);
863                 chan_read_failed(c);
864                 buffer_clear(&c->input);
865                 chan_ibuf_empty(c);
866                 buffer_clear(&c->output);
867                 /* for proto v1, the peer will send an IEOF */
868                 if (compat20)
869                         chan_write_failed(c);
870                 else
871                         c->type = SSH_CHANNEL_OPEN;
872                 debug("X11 closed %d i%d/o%d", c->self, c->istate, c->ostate);
873         }
874 }
875
876 /* try to decode a socks4 header */
877 static int
878 channel_decode_socks4(Channel *c, fd_set * readset, fd_set * writeset)
879 {
880         char *p, *host;
881         int len, have, i, found;
882         char username[256];
883         struct {
884                 u_int8_t version;
885                 u_int8_t command;
886                 u_int16_t dest_port;
887                 struct in_addr dest_addr;
888         } s4_req, s4_rsp;
889
890         debug2("channel %d: decode socks4", c->self);
891
892         have = buffer_len(&c->input);
893         len = sizeof(s4_req);
894         if (have < len)
895                 return 0;
896         p = buffer_ptr(&c->input);
897         for (found = 0, i = len; i < have; i++) {
898                 if (p[i] == '\0') {
899                         found = 1;
900                         break;
901                 }
902                 if (i > 1024) {
903                         /* the peer is probably sending garbage */
904                         debug("channel %d: decode socks4: too long",
905                             c->self);
906                         return -1;
907                 }
908         }
909         if (!found)
910                 return 0;
911         buffer_get(&c->input, (char *)&s4_req.version, 1);
912         buffer_get(&c->input, (char *)&s4_req.command, 1);
913         buffer_get(&c->input, (char *)&s4_req.dest_port, 2);
914         buffer_get(&c->input, (char *)&s4_req.dest_addr, 4);
915         have = buffer_len(&c->input);
916         p = buffer_ptr(&c->input);
917         len = strlen(p);
918         debug2("channel %d: decode socks4: user %s/%d", c->self, p, len);
919         if (len > have)
920                 fatal("channel %d: decode socks4: len %d > have %d",
921                     c->self, len, have);
922         strlcpy(username, p, sizeof(username));
923         buffer_consume(&c->input, len);
924         buffer_consume(&c->input, 1);           /* trailing '\0' */
925
926         host = inet_ntoa(s4_req.dest_addr);
927         strlcpy(c->path, host, sizeof(c->path));
928         c->host_port = ntohs(s4_req.dest_port);
929
930         debug("channel %d: dynamic request: socks4 host %s port %u command %u",
931             c->self, host, c->host_port, s4_req.command);
932
933         if (s4_req.command != 1) {
934                 debug("channel %d: cannot handle: socks4 cn %d",
935                     c->self, s4_req.command);
936                 return -1;
937         }
938         s4_rsp.version = 0;                     /* vn: 0 for reply */
939         s4_rsp.command = 90;                    /* cd: req granted */
940         s4_rsp.dest_port = 0;                   /* ignored */
941         s4_rsp.dest_addr.s_addr = INADDR_ANY;   /* ignored */
942         buffer_append(&c->output, (char *)&s4_rsp, sizeof(s4_rsp));
943         return 1;
944 }
945
946 /* dynamic port forwarding */
947 static void
948 channel_pre_dynamic(Channel *c, fd_set * readset, fd_set * writeset)
949 {
950         u_char *p;
951         int have, ret;
952
953         have = buffer_len(&c->input);
954         c->delayed = 0;
955         debug2("channel %d: pre_dynamic: have %d", c->self, have);
956         /* buffer_dump(&c->input); */
957         /* check if the fixed size part of the packet is in buffer. */
958         if (have < 4) {
959                 /* need more */
960                 FD_SET(c->sock, readset);
961                 return;
962         }
963         /* try to guess the protocol */
964         p = buffer_ptr(&c->input);
965         switch (p[0]) {
966         case 0x04:
967                 ret = channel_decode_socks4(c, readset, writeset);
968                 break;
969         default:
970                 ret = -1;
971                 break;
972         }
973         if (ret < 0) {
974                 chan_mark_dead(c);
975         } else if (ret == 0) {
976                 debug2("channel %d: pre_dynamic: need more", c->self);
977                 /* need more */
978                 FD_SET(c->sock, readset);
979         } else {
980                 /* switch to the next state */
981                 c->type = SSH_CHANNEL_OPENING;
982                 port_open_helper(c, "direct-tcpip");
983         }
984 }
985
986 /* This is our fake X11 server socket. */
987 static void
988 channel_post_x11_listener(Channel *c, fd_set * readset, fd_set * writeset)
989 {
990         Channel *nc;
991         struct sockaddr addr;
992         int newsock;
993         socklen_t addrlen;
994         char buf[16384], *remote_ipaddr;
995         int remote_port;
996
997         if (FD_ISSET(c->sock, readset)) {
998                 debug("X11 connection requested.");
999                 addrlen = sizeof(addr);
1000                 newsock = accept(c->sock, &addr, &addrlen);
1001                 if (c->single_connection) {
1002                         debug("single_connection: closing X11 listener.");
1003                         channel_close_fd(&c->sock);
1004                         chan_mark_dead(c);
1005                 }
1006                 if (newsock < 0) {
1007                         error("accept: %.100s", strerror(errno));
1008                         return;
1009                 }
1010                 set_nodelay(newsock);
1011                 remote_ipaddr = get_peer_ipaddr(newsock);
1012                 remote_port = get_peer_port(newsock);
1013                 snprintf(buf, sizeof buf, "X11 connection from %.200s port %d",
1014                     remote_ipaddr, remote_port);
1015
1016                 nc = channel_new("accepted x11 socket",
1017                     SSH_CHANNEL_OPENING, newsock, newsock, -1,
1018                     c->local_window_max, c->local_maxpacket,
1019                     0, xstrdup(buf), 1);
1020                 if (compat20) {
1021                         packet_start(SSH2_MSG_CHANNEL_OPEN);
1022                         packet_put_cstring("x11");
1023                         packet_put_int(nc->self);
1024                         packet_put_int(nc->local_window_max);
1025                         packet_put_int(nc->local_maxpacket);
1026                         /* originator ipaddr and port */
1027                         packet_put_cstring(remote_ipaddr);
1028                         if (datafellows & SSH_BUG_X11FWD) {
1029                                 debug("ssh2 x11 bug compat mode");
1030                         } else {
1031                                 packet_put_int(remote_port);
1032                         }
1033                         packet_send();
1034                 } else {
1035                         packet_start(SSH_SMSG_X11_OPEN);
1036                         packet_put_int(nc->self);
1037                         if (packet_get_protocol_flags() &
1038                             SSH_PROTOFLAG_HOST_IN_FWD_OPEN)
1039                                 packet_put_cstring(buf);
1040                         packet_send();
1041                 }
1042                 xfree(remote_ipaddr);
1043         }
1044 }
1045
1046 static void
1047 port_open_helper(Channel *c, char *rtype)
1048 {
1049         int direct;
1050         char buf[1024];
1051         char *remote_ipaddr = get_peer_ipaddr(c->sock);
1052         u_short remote_port = get_peer_port(c->sock);
1053
1054         direct = (strcmp(rtype, "direct-tcpip") == 0);
1055
1056         snprintf(buf, sizeof buf,
1057             "%s: listening port %d for %.100s port %d, "
1058             "connect from %.200s port %d",
1059             rtype, c->listening_port, c->path, c->host_port,
1060             remote_ipaddr, remote_port);
1061
1062         xfree(c->remote_name);
1063         c->remote_name = xstrdup(buf);
1064
1065         if (compat20) {
1066                 packet_start(SSH2_MSG_CHANNEL_OPEN);
1067                 packet_put_cstring(rtype);
1068                 packet_put_int(c->self);
1069                 packet_put_int(c->local_window_max);
1070                 packet_put_int(c->local_maxpacket);
1071                 if (direct) {
1072                         /* target host, port */
1073                         packet_put_cstring(c->path);
1074                         packet_put_int(c->host_port);
1075                 } else {
1076                         /* listen address, port */
1077                         packet_put_cstring(c->path);
1078                         packet_put_int(c->listening_port);
1079                 }
1080                 /* originator host and port */
1081                 packet_put_cstring(remote_ipaddr);
1082                 packet_put_int(remote_port);
1083                 packet_send();
1084         } else {
1085                 packet_start(SSH_MSG_PORT_OPEN);
1086                 packet_put_int(c->self);
1087                 packet_put_cstring(c->path);
1088                 packet_put_int(c->host_port);
1089                 if (packet_get_protocol_flags() &
1090                     SSH_PROTOFLAG_HOST_IN_FWD_OPEN)
1091                         packet_put_cstring(c->remote_name);
1092                 packet_send();
1093         }
1094         xfree(remote_ipaddr);
1095 }
1096
1097 /*
1098  * This socket is listening for connections to a forwarded TCP/IP port.
1099  */
1100 static void
1101 channel_post_port_listener(Channel *c, fd_set * readset, fd_set * writeset)
1102 {
1103         Channel *nc;
1104         struct sockaddr addr;
1105         int newsock, nextstate;
1106         socklen_t addrlen;
1107         char *rtype;
1108
1109         if (FD_ISSET(c->sock, readset)) {
1110                 debug("Connection to port %d forwarding "
1111                     "to %.100s port %d requested.",
1112                     c->listening_port, c->path, c->host_port);
1113
1114                 if (c->type == SSH_CHANNEL_RPORT_LISTENER) {
1115                         nextstate = SSH_CHANNEL_OPENING;
1116                         rtype = "forwarded-tcpip";
1117                 } else {
1118                         if (c->host_port == 0) {
1119                                 nextstate = SSH_CHANNEL_DYNAMIC;
1120                                 rtype = "dynamic-tcpip";
1121                         } else {
1122                                 nextstate = SSH_CHANNEL_OPENING;
1123                                 rtype = "direct-tcpip";
1124                         }
1125                 }
1126
1127                 addrlen = sizeof(addr);
1128                 newsock = accept(c->sock, &addr, &addrlen);
1129                 if (newsock < 0) {
1130                         error("accept: %.100s", strerror(errno));
1131                         return;
1132                 }
1133                 set_nodelay(newsock);
1134                 nc = channel_new(rtype,
1135                     nextstate, newsock, newsock, -1,
1136                     c->local_window_max, c->local_maxpacket,
1137                     0, xstrdup(rtype), 1);
1138                 nc->listening_port = c->listening_port;
1139                 nc->host_port = c->host_port;
1140                 strlcpy(nc->path, c->path, sizeof(nc->path));
1141
1142                 if (nextstate == SSH_CHANNEL_DYNAMIC) {
1143                         /*
1144                          * do not call the channel_post handler until
1145                          * this flag has been reset by a pre-handler.
1146                          * otherwise the FD_ISSET calls might overflow
1147                          */
1148                         nc->delayed = 1;
1149                 } else {
1150                         port_open_helper(nc, rtype);
1151                 }
1152         }
1153 }
1154
1155 /*
1156  * This is the authentication agent socket listening for connections from
1157  * clients.
1158  */
1159 static void
1160 channel_post_auth_listener(Channel *c, fd_set * readset, fd_set * writeset)
1161 {
1162         Channel *nc;
1163         char *name;
1164         int newsock;
1165         struct sockaddr addr;
1166         socklen_t addrlen;
1167
1168         if (FD_ISSET(c->sock, readset)) {
1169                 addrlen = sizeof(addr);
1170                 newsock = accept(c->sock, &addr, &addrlen);
1171                 if (newsock < 0) {
1172                         error("accept from auth socket: %.100s", strerror(errno));
1173                         return;
1174                 }
1175                 name = xstrdup("accepted auth socket");
1176                 nc = channel_new("accepted auth socket",
1177                     SSH_CHANNEL_OPENING, newsock, newsock, -1,
1178                     c->local_window_max, c->local_maxpacket,
1179                     0, name, 1);
1180                 if (compat20) {
1181                         packet_start(SSH2_MSG_CHANNEL_OPEN);
1182                         packet_put_cstring("auth-agent@openssh.com");
1183                         packet_put_int(nc->self);
1184                         packet_put_int(c->local_window_max);
1185                         packet_put_int(c->local_maxpacket);
1186                 } else {
1187                         packet_start(SSH_SMSG_AGENT_OPEN);
1188                         packet_put_int(nc->self);
1189                 }
1190                 packet_send();
1191         }
1192 }
1193
1194 static void
1195 channel_post_connecting(Channel *c, fd_set * readset, fd_set * writeset)
1196 {
1197         int err = 0;
1198         socklen_t sz = sizeof(err);
1199
1200         if (FD_ISSET(c->sock, writeset)) {
1201                 if (getsockopt(c->sock, SOL_SOCKET, SO_ERROR, &err, &sz) < 0) {
1202                         err = errno;
1203                         error("getsockopt SO_ERROR failed");
1204                 }
1205                 if (err == 0) {
1206                         debug("channel %d: connected", c->self);
1207                         c->type = SSH_CHANNEL_OPEN;
1208                         if (compat20) {
1209                                 packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
1210                                 packet_put_int(c->remote_id);
1211                                 packet_put_int(c->self);
1212                                 packet_put_int(c->local_window);
1213                                 packet_put_int(c->local_maxpacket);
1214                         } else {
1215                                 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1216                                 packet_put_int(c->remote_id);
1217                                 packet_put_int(c->self);
1218                         }
1219                 } else {
1220                         debug("channel %d: not connected: %s",
1221                             c->self, strerror(err));
1222                         if (compat20) {
1223                                 packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE);
1224                                 packet_put_int(c->remote_id);
1225                                 packet_put_int(SSH2_OPEN_CONNECT_FAILED);
1226                                 if (!(datafellows & SSH_BUG_OPENFAILURE)) {
1227                                         packet_put_cstring(strerror(err));
1228                                         packet_put_cstring("");
1229                                 }
1230                         } else {
1231                                 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1232                                 packet_put_int(c->remote_id);
1233                         }
1234                         chan_mark_dead(c);
1235                 }
1236                 packet_send();
1237         }
1238 }
1239
1240 static int
1241 channel_handle_rfd(Channel *c, fd_set * readset, fd_set * writeset)
1242 {
1243         char buf[16*1024];
1244         int len;
1245
1246         if (c->rfd != -1 &&
1247             FD_ISSET(c->rfd, readset)) {
1248                 len = read(c->rfd, buf, sizeof(buf));
1249                 if (len < 0 && (errno == EINTR || errno == EAGAIN))
1250                         return 1;
1251                 if (len <= 0) {
1252                         debug("channel %d: read<=0 rfd %d len %d",
1253                             c->self, c->rfd, len);
1254                         if (c->type != SSH_CHANNEL_OPEN) {
1255                                 debug("channel %d: not open", c->self);
1256                                 chan_mark_dead(c);
1257                                 return -1;
1258                         } else if (compat13) {
1259                                 buffer_clear(&c->output);
1260                                 c->type = SSH_CHANNEL_INPUT_DRAINING;
1261                                 debug("channel %d: input draining.", c->self);
1262                         } else {
1263                                 chan_read_failed(c);
1264                         }
1265                         return -1;
1266                 }
1267                 if (c->input_filter != NULL) {
1268                         if (c->input_filter(c, buf, len) == -1) {
1269                                 debug("channel %d: filter stops", c->self);
1270                                 chan_read_failed(c);
1271                         }
1272                 } else {
1273                         buffer_append(&c->input, buf, len);
1274                 }
1275         }
1276         return 1;
1277 }
1278 static int
1279 channel_handle_wfd(Channel *c, fd_set * readset, fd_set * writeset)
1280 {
1281         struct termios tio;
1282         u_char *data;
1283         u_int dlen;
1284         int len;
1285
1286         /* Send buffered output data to the socket. */
1287         if (c->wfd != -1 &&
1288             FD_ISSET(c->wfd, writeset) &&
1289             buffer_len(&c->output) > 0) {
1290                 data = buffer_ptr(&c->output);
1291                 dlen = buffer_len(&c->output);
1292 #ifdef _AIX
1293                 /* XXX: Later AIX versions can't push as much data to tty */ 
1294                 if (compat20 && c->wfd_isatty && dlen > 8*1024)
1295                         dlen = 8*1024;
1296 #endif
1297                 len = write(c->wfd, data, dlen);
1298                 if (len < 0 && (errno == EINTR || errno == EAGAIN))
1299                         return 1;
1300                 if (len <= 0) {
1301                         if (c->type != SSH_CHANNEL_OPEN) {
1302                                 debug("channel %d: not open", c->self);
1303                                 chan_mark_dead(c);
1304                                 return -1;
1305                         } else if (compat13) {
1306                                 buffer_clear(&c->output);
1307                                 debug("channel %d: input draining.", c->self);
1308                                 c->type = SSH_CHANNEL_INPUT_DRAINING;
1309                         } else {
1310                                 chan_write_failed(c);
1311                         }
1312                         return -1;
1313                 }
1314                 if (compat20 && c->isatty && dlen >= 1 && data[0] != '\r') {
1315                         if (tcgetattr(c->wfd, &tio) == 0 &&
1316                             !(tio.c_lflag & ECHO) && (tio.c_lflag & ICANON)) {
1317                                 /*
1318                                  * Simulate echo to reduce the impact of
1319                                  * traffic analysis. We need to match the
1320                                  * size of a SSH2_MSG_CHANNEL_DATA message
1321                                  * (4 byte channel id + data)
1322                                  */
1323                                 packet_send_ignore(4 + len);
1324                                 packet_send();
1325                         }
1326                 }
1327                 buffer_consume(&c->output, len);
1328                 if (compat20 && len > 0) {
1329                         c->local_consumed += len;
1330                 }
1331         }
1332         return 1;
1333 }
1334 static int
1335 channel_handle_efd(Channel *c, fd_set * readset, fd_set * writeset)
1336 {
1337         char buf[16*1024];
1338         int len;
1339
1340 /** XXX handle drain efd, too */
1341         if (c->efd != -1) {
1342                 if (c->extended_usage == CHAN_EXTENDED_WRITE &&
1343                     FD_ISSET(c->efd, writeset) &&
1344                     buffer_len(&c->extended) > 0) {
1345                         len = write(c->efd, buffer_ptr(&c->extended),
1346                             buffer_len(&c->extended));
1347                         debug2("channel %d: written %d to efd %d",
1348                             c->self, len, c->efd);
1349                         if (len < 0 && (errno == EINTR || errno == EAGAIN))
1350                                 return 1;
1351                         if (len <= 0) {
1352                                 debug2("channel %d: closing write-efd %d",
1353                                     c->self, c->efd);
1354                                 channel_close_fd(&c->efd);
1355                         } else {
1356                                 buffer_consume(&c->extended, len);
1357                                 c->local_consumed += len;
1358                         }
1359                 } else if (c->extended_usage == CHAN_EXTENDED_READ &&
1360                     FD_ISSET(c->efd, readset)) {
1361                         len = read(c->efd, buf, sizeof(buf));
1362                         debug2("channel %d: read %d from efd %d",
1363                             c->self, len, c->efd);
1364                         if (len < 0 && (errno == EINTR || errno == EAGAIN))
1365                                 return 1;
1366                         if (len <= 0) {
1367                                 debug2("channel %d: closing read-efd %d",
1368                                     c->self, c->efd);
1369                                 channel_close_fd(&c->efd);
1370                         } else {
1371                                 buffer_append(&c->extended, buf, len);
1372                         }
1373                 }
1374         }
1375         return 1;
1376 }
1377 static int
1378 channel_check_window(Channel *c)
1379 {
1380         if (c->type == SSH_CHANNEL_OPEN &&
1381             !(c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD)) &&
1382             c->local_window < c->local_window_max/2 &&
1383             c->local_consumed > 0) {
1384                 packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
1385                 packet_put_int(c->remote_id);
1386                 packet_put_int(c->local_consumed);
1387                 packet_send();
1388                 debug2("channel %d: window %d sent adjust %d",
1389                     c->self, c->local_window,
1390                     c->local_consumed);
1391                 c->local_window += c->local_consumed;
1392                 c->local_consumed = 0;
1393         }
1394         return 1;
1395 }
1396
1397 static void
1398 channel_post_open(Channel *c, fd_set * readset, fd_set * writeset)
1399 {
1400         if (c->delayed)
1401                 return;
1402         channel_handle_rfd(c, readset, writeset);
1403         channel_handle_wfd(c, readset, writeset);
1404         if (!compat20)
1405                 return;
1406         channel_handle_efd(c, readset, writeset);
1407         channel_check_window(c);
1408 }
1409
1410 static void
1411 channel_post_output_drain_13(Channel *c, fd_set * readset, fd_set * writeset)
1412 {
1413         int len;
1414
1415         /* Send buffered output data to the socket. */
1416         if (FD_ISSET(c->sock, writeset) && buffer_len(&c->output) > 0) {
1417                 len = write(c->sock, buffer_ptr(&c->output),
1418                             buffer_len(&c->output));
1419                 if (len <= 0)
1420                         buffer_clear(&c->output);
1421                 else
1422                         buffer_consume(&c->output, len);
1423         }
1424 }
1425
1426 static void
1427 channel_handler_init_20(void)
1428 {
1429         channel_pre[SSH_CHANNEL_OPEN] =                 &channel_pre_open;
1430         channel_pre[SSH_CHANNEL_X11_OPEN] =             &channel_pre_x11_open;
1431         channel_pre[SSH_CHANNEL_PORT_LISTENER] =        &channel_pre_listener;
1432         channel_pre[SSH_CHANNEL_RPORT_LISTENER] =       &channel_pre_listener;
1433         channel_pre[SSH_CHANNEL_X11_LISTENER] =         &channel_pre_listener;
1434         channel_pre[SSH_CHANNEL_AUTH_SOCKET] =          &channel_pre_listener;
1435         channel_pre[SSH_CHANNEL_CONNECTING] =           &channel_pre_connecting;
1436         channel_pre[SSH_CHANNEL_DYNAMIC] =              &channel_pre_dynamic;
1437
1438         channel_post[SSH_CHANNEL_OPEN] =                &channel_post_open;
1439         channel_post[SSH_CHANNEL_PORT_LISTENER] =       &channel_post_port_listener;
1440         channel_post[SSH_CHANNEL_RPORT_LISTENER] =      &channel_post_port_listener;
1441         channel_post[SSH_CHANNEL_X11_LISTENER] =        &channel_post_x11_listener;
1442         channel_post[SSH_CHANNEL_AUTH_SOCKET] =         &channel_post_auth_listener;
1443         channel_post[SSH_CHANNEL_CONNECTING] =          &channel_post_connecting;
1444         channel_post[SSH_CHANNEL_DYNAMIC] =             &channel_post_open;
1445 }
1446
1447 static void
1448 channel_handler_init_13(void)
1449 {
1450         channel_pre[SSH_CHANNEL_OPEN] =                 &channel_pre_open_13;
1451         channel_pre[SSH_CHANNEL_X11_OPEN] =             &channel_pre_x11_open_13;
1452         channel_pre[SSH_CHANNEL_X11_LISTENER] =         &channel_pre_listener;
1453         channel_pre[SSH_CHANNEL_PORT_LISTENER] =        &channel_pre_listener;
1454         channel_pre[SSH_CHANNEL_AUTH_SOCKET] =          &channel_pre_listener;
1455         channel_pre[SSH_CHANNEL_INPUT_DRAINING] =       &channel_pre_input_draining;
1456         channel_pre[SSH_CHANNEL_OUTPUT_DRAINING] =      &channel_pre_output_draining;
1457         channel_pre[SSH_CHANNEL_CONNECTING] =           &channel_pre_connecting;
1458         channel_pre[SSH_CHANNEL_DYNAMIC] =              &channel_pre_dynamic;
1459
1460         channel_post[SSH_CHANNEL_OPEN] =                &channel_post_open;
1461         channel_post[SSH_CHANNEL_X11_LISTENER] =        &channel_post_x11_listener;
1462         channel_post[SSH_CHANNEL_PORT_LISTENER] =       &channel_post_port_listener;
1463         channel_post[SSH_CHANNEL_AUTH_SOCKET] =         &channel_post_auth_listener;
1464         channel_post[SSH_CHANNEL_OUTPUT_DRAINING] =     &channel_post_output_drain_13;
1465         channel_post[SSH_CHANNEL_CONNECTING] =          &channel_post_connecting;
1466         channel_post[SSH_CHANNEL_DYNAMIC] =             &channel_post_open;
1467 }
1468
1469 static void
1470 channel_handler_init_15(void)
1471 {
1472         channel_pre[SSH_CHANNEL_OPEN] =                 &channel_pre_open;
1473         channel_pre[SSH_CHANNEL_X11_OPEN] =             &channel_pre_x11_open;
1474         channel_pre[SSH_CHANNEL_X11_LISTENER] =         &channel_pre_listener;
1475         channel_pre[SSH_CHANNEL_PORT_LISTENER] =        &channel_pre_listener;
1476         channel_pre[SSH_CHANNEL_AUTH_SOCKET] =          &channel_pre_listener;
1477         channel_pre[SSH_CHANNEL_CONNECTING] =           &channel_pre_connecting;
1478         channel_pre[SSH_CHANNEL_DYNAMIC] =              &channel_pre_dynamic;
1479
1480         channel_post[SSH_CHANNEL_X11_LISTENER] =        &channel_post_x11_listener;
1481         channel_post[SSH_CHANNEL_PORT_LISTENER] =       &channel_post_port_listener;
1482         channel_post[SSH_CHANNEL_AUTH_SOCKET] =         &channel_post_auth_listener;
1483         channel_post[SSH_CHANNEL_OPEN] =                &channel_post_open;
1484         channel_post[SSH_CHANNEL_CONNECTING] =          &channel_post_connecting;
1485         channel_post[SSH_CHANNEL_DYNAMIC] =             &channel_post_open;
1486 }
1487
1488 static void
1489 channel_handler_init(void)
1490 {
1491         int i;
1492
1493         for (i = 0; i < SSH_CHANNEL_MAX_TYPE; i++) {
1494                 channel_pre[i] = NULL;
1495                 channel_post[i] = NULL;
1496         }
1497         if (compat20)
1498                 channel_handler_init_20();
1499         else if (compat13)
1500                 channel_handler_init_13();
1501         else
1502                 channel_handler_init_15();
1503 }
1504
1505 /* gc dead channels */
1506 static void
1507 channel_garbage_collect(Channel *c)
1508 {
1509         if (c == NULL)
1510                 return;
1511         if (c->detach_user != NULL) {
1512                 if (!chan_is_dead(c, 0))
1513                         return;
1514                 debug("channel %d: gc: notify user", c->self);
1515                 c->detach_user(c->self, NULL);
1516                 /* if we still have a callback */
1517                 if (c->detach_user != NULL)
1518                         return;
1519                 debug("channel %d: gc: user detached", c->self);
1520         }
1521         if (!chan_is_dead(c, 1))
1522                 return;
1523         debug("channel %d: garbage collecting", c->self);
1524         channel_free(c);
1525 }
1526
1527 static void
1528 channel_handler(chan_fn *ftab[], fd_set * readset, fd_set * writeset)
1529 {
1530         static int did_init = 0;
1531         int i;
1532         Channel *c;
1533
1534         if (!did_init) {
1535                 channel_handler_init();
1536                 did_init = 1;
1537         }
1538         for (i = 0; i < channels_alloc; i++) {
1539                 c = channels[i];
1540                 if (c == NULL)
1541                         continue;
1542                 if (ftab[c->type] != NULL)
1543                         (*ftab[c->type])(c, readset, writeset);
1544                 channel_garbage_collect(c);
1545         }
1546 }
1547
1548 /*
1549  * Allocate/update select bitmasks and add any bits relevant to channels in
1550  * select bitmasks.
1551  */
1552 void
1553 channel_prepare_select(fd_set **readsetp, fd_set **writesetp, int *maxfdp,
1554     int *nallocp, int rekeying)
1555 {
1556         int n;
1557         u_int sz;
1558
1559         n = MAX(*maxfdp, channel_max_fd);
1560
1561         sz = howmany(n+1, NFDBITS) * sizeof(fd_mask);
1562         /* perhaps check sz < nalloc/2 and shrink? */
1563         if (*readsetp == NULL || sz > *nallocp) {
1564                 *readsetp = xrealloc(*readsetp, sz);
1565                 *writesetp = xrealloc(*writesetp, sz);
1566                 *nallocp = sz;
1567         }
1568         *maxfdp = n;
1569         memset(*readsetp, 0, sz);
1570         memset(*writesetp, 0, sz);
1571
1572         if (!rekeying)
1573                 channel_handler(channel_pre, *readsetp, *writesetp);
1574 }
1575
1576 /*
1577  * After select, perform any appropriate operations for channels which have
1578  * events pending.
1579  */
1580 void
1581 channel_after_select(fd_set * readset, fd_set * writeset)
1582 {
1583         channel_handler(channel_post, readset, writeset);
1584 }
1585
1586
1587 /* If there is data to send to the connection, enqueue some of it now. */
1588
1589 void
1590 channel_output_poll(void)
1591 {
1592         Channel *c;
1593         int i;
1594         u_int len;
1595
1596         for (i = 0; i < channels_alloc; i++) {
1597                 c = channels[i];
1598                 if (c == NULL)
1599                         continue;
1600
1601                 /*
1602                  * We are only interested in channels that can have buffered
1603                  * incoming data.
1604                  */
1605                 if (compat13) {
1606                         if (c->type != SSH_CHANNEL_OPEN &&
1607                             c->type != SSH_CHANNEL_INPUT_DRAINING)
1608                                 continue;
1609                 } else {
1610                         if (c->type != SSH_CHANNEL_OPEN)
1611                                 continue;
1612                 }
1613                 if (compat20 &&
1614                     (c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD))) {
1615                         /* XXX is this true? */
1616                         debug3("channel %d: will not send data after close", c->self);
1617                         continue;
1618                 }
1619
1620                 /* Get the amount of buffered data for this channel. */
1621                 if ((c->istate == CHAN_INPUT_OPEN ||
1622                     c->istate == CHAN_INPUT_WAIT_DRAIN) &&
1623                     (len = buffer_len(&c->input)) > 0) {
1624                         /*
1625                          * Send some data for the other side over the secure
1626                          * connection.
1627                          */
1628                         if (compat20) {
1629                                 if (len > c->remote_window)
1630                                         len = c->remote_window;
1631                                 if (len > c->remote_maxpacket)
1632                                         len = c->remote_maxpacket;
1633                         } else {
1634                                 if (packet_is_interactive()) {
1635                                         if (len > 1024)
1636                                                 len = 512;
1637                                 } else {
1638                                         /* Keep the packets at reasonable size. */
1639                                         if (len > packet_get_maxsize()/2)
1640                                                 len = packet_get_maxsize()/2;
1641                                 }
1642                         }
1643                         if (len > 0) {
1644                                 packet_start(compat20 ?
1645                                     SSH2_MSG_CHANNEL_DATA : SSH_MSG_CHANNEL_DATA);
1646                                 packet_put_int(c->remote_id);
1647                                 packet_put_string(buffer_ptr(&c->input), len);
1648                                 packet_send();
1649                                 buffer_consume(&c->input, len);
1650                                 c->remote_window -= len;
1651                         }
1652                 } else if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
1653                         if (compat13)
1654                                 fatal("cannot happen: istate == INPUT_WAIT_DRAIN for proto 1.3");
1655                         /*
1656                          * input-buffer is empty and read-socket shutdown:
1657                          * tell peer, that we will not send more data: send IEOF.
1658                          * hack for extended data: delay EOF if EFD still in use.
1659                          */
1660                         if (CHANNEL_EFD_INPUT_ACTIVE(c))
1661                                debug2("channel %d: ibuf_empty delayed efd %d/(%d)",
1662                                    c->self, c->efd, buffer_len(&c->extended));
1663                         else
1664                                 chan_ibuf_empty(c);
1665                 }
1666                 /* Send extended data, i.e. stderr */
1667                 if (compat20 &&
1668                     !(c->flags & CHAN_EOF_SENT) &&
1669                     c->remote_window > 0 &&
1670                     (len = buffer_len(&c->extended)) > 0 &&
1671                     c->extended_usage == CHAN_EXTENDED_READ) {
1672                         debug2("channel %d: rwin %u elen %u euse %d",
1673                             c->self, c->remote_window, buffer_len(&c->extended),
1674                             c->extended_usage);
1675                         if (len > c->remote_window)
1676                                 len = c->remote_window;
1677                         if (len > c->remote_maxpacket)
1678                                 len = c->remote_maxpacket;
1679                         packet_start(SSH2_MSG_CHANNEL_EXTENDED_DATA);
1680                         packet_put_int(c->remote_id);
1681                         packet_put_int(SSH2_EXTENDED_DATA_STDERR);
1682                         packet_put_string(buffer_ptr(&c->extended), len);
1683                         packet_send();
1684                         buffer_consume(&c->extended, len);
1685                         c->remote_window -= len;
1686                         debug2("channel %d: sent ext data %d", c->self, len);
1687                 }
1688         }
1689 }
1690
1691
1692 /* -- protocol input */
1693
1694 void
1695 channel_input_data(int type, u_int32_t seq, void *ctxt)
1696 {
1697         int id;
1698         char *data;
1699         u_int data_len;
1700         Channel *c;
1701
1702         /* Get the channel number and verify it. */
1703         id = packet_get_int();
1704         c = channel_lookup(id);
1705         if (c == NULL)
1706                 packet_disconnect("Received data for nonexistent channel %d.", id);
1707
1708         /* Ignore any data for non-open channels (might happen on close) */
1709         if (c->type != SSH_CHANNEL_OPEN &&
1710             c->type != SSH_CHANNEL_X11_OPEN)
1711                 return;
1712
1713         /* same for protocol 1.5 if output end is no longer open */
1714         if (!compat13 && c->ostate != CHAN_OUTPUT_OPEN)
1715                 return;
1716
1717         /* Get the data. */
1718         data = packet_get_string(&data_len);
1719
1720         if (compat20) {
1721                 if (data_len > c->local_maxpacket) {
1722                         log("channel %d: rcvd big packet %d, maxpack %d",
1723                             c->self, data_len, c->local_maxpacket);
1724                 }
1725                 if (data_len > c->local_window) {
1726                         log("channel %d: rcvd too much data %d, win %d",
1727                             c->self, data_len, c->local_window);
1728                         xfree(data);
1729                         return;
1730                 }
1731                 c->local_window -= data_len;
1732         }
1733         packet_check_eom();
1734         buffer_append(&c->output, data, data_len);
1735         xfree(data);
1736 }
1737
1738 void
1739 channel_input_extended_data(int type, u_int32_t seq, void *ctxt)
1740 {
1741         int id;
1742         char *data;
1743         u_int data_len, tcode;
1744         Channel *c;
1745
1746         /* Get the channel number and verify it. */
1747         id = packet_get_int();
1748         c = channel_lookup(id);
1749
1750         if (c == NULL)
1751                 packet_disconnect("Received extended_data for bad channel %d.", id);
1752         if (c->type != SSH_CHANNEL_OPEN) {
1753                 log("channel %d: ext data for non open", id);
1754                 return;
1755         }
1756         if (c->flags & CHAN_EOF_RCVD) {
1757                 if (datafellows & SSH_BUG_EXTEOF)
1758                         debug("channel %d: accepting ext data after eof", id);
1759                 else
1760                         packet_disconnect("Received extended_data after EOF "
1761                             "on channel %d.", id);
1762         }
1763         tcode = packet_get_int();
1764         if (c->efd == -1 ||
1765             c->extended_usage != CHAN_EXTENDED_WRITE ||
1766             tcode != SSH2_EXTENDED_DATA_STDERR) {
1767                 log("channel %d: bad ext data", c->self);
1768                 return;
1769         }
1770         data = packet_get_string(&data_len);
1771         packet_check_eom();
1772         if (data_len > c->local_window) {
1773                 log("channel %d: rcvd too much extended_data %d, win %d",
1774                     c->self, data_len, c->local_window);
1775                 xfree(data);
1776                 return;
1777         }
1778         debug2("channel %d: rcvd ext data %d", c->self, data_len);
1779         c->local_window -= data_len;
1780         buffer_append(&c->extended, data, data_len);
1781         xfree(data);
1782 }
1783
1784 void
1785 channel_input_ieof(int type, u_int32_t seq, void *ctxt)
1786 {
1787         int id;
1788         Channel *c;
1789
1790         id = packet_get_int();
1791         packet_check_eom();
1792         c = channel_lookup(id);
1793         if (c == NULL)
1794                 packet_disconnect("Received ieof for nonexistent channel %d.", id);
1795         chan_rcvd_ieof(c);
1796
1797         /* XXX force input close */
1798         if (c->force_drain && c->istate == CHAN_INPUT_OPEN) {
1799                 debug("channel %d: FORCE input drain", c->self);
1800                 c->istate = CHAN_INPUT_WAIT_DRAIN;
1801                 if (buffer_len(&c->input) == 0)
1802                         chan_ibuf_empty(c);
1803         }
1804
1805 }
1806
1807 void
1808 channel_input_close(int type, u_int32_t seq, void *ctxt)
1809 {
1810         int id;
1811         Channel *c;
1812
1813         id = packet_get_int();
1814         packet_check_eom();
1815         c = channel_lookup(id);
1816         if (c == NULL)
1817                 packet_disconnect("Received close for nonexistent channel %d.", id);
1818
1819         /*
1820          * Send a confirmation that we have closed the channel and no more
1821          * data is coming for it.
1822          */
1823         packet_start(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION);
1824         packet_put_int(c->remote_id);
1825         packet_send();
1826
1827         /*
1828          * If the channel is in closed state, we have sent a close request,
1829          * and the other side will eventually respond with a confirmation.
1830          * Thus, we cannot free the channel here, because then there would be
1831          * no-one to receive the confirmation.  The channel gets freed when
1832          * the confirmation arrives.
1833          */
1834         if (c->type != SSH_CHANNEL_CLOSED) {
1835                 /*
1836                  * Not a closed channel - mark it as draining, which will
1837                  * cause it to be freed later.
1838                  */
1839                 buffer_clear(&c->input);
1840                 c->type = SSH_CHANNEL_OUTPUT_DRAINING;
1841         }
1842 }
1843
1844 /* proto version 1.5 overloads CLOSE_CONFIRMATION with OCLOSE */
1845 void
1846 channel_input_oclose(int type, u_int32_t seq, void *ctxt)
1847 {
1848         int id = packet_get_int();
1849         Channel *c = channel_lookup(id);
1850
1851         packet_check_eom();
1852         if (c == NULL)
1853                 packet_disconnect("Received oclose for nonexistent channel %d.", id);
1854         chan_rcvd_oclose(c);
1855 }
1856
1857 void
1858 channel_input_close_confirmation(int type, u_int32_t seq, void *ctxt)
1859 {
1860         int id = packet_get_int();
1861         Channel *c = channel_lookup(id);
1862
1863         packet_check_eom();
1864         if (c == NULL)
1865                 packet_disconnect("Received close confirmation for "
1866                     "out-of-range channel %d.", id);
1867         if (c->type != SSH_CHANNEL_CLOSED)
1868                 packet_disconnect("Received close confirmation for "
1869                     "non-closed channel %d (type %d).", id, c->type);
1870         channel_free(c);
1871 }
1872
1873 void
1874 channel_input_open_confirmation(int type, u_int32_t seq, void *ctxt)
1875 {
1876         int id, remote_id;
1877         Channel *c;
1878
1879         id = packet_get_int();
1880         c = channel_lookup(id);
1881
1882         if (c==NULL || c->type != SSH_CHANNEL_OPENING)
1883                 packet_disconnect("Received open confirmation for "
1884                     "non-opening channel %d.", id);
1885         remote_id = packet_get_int();
1886         /* Record the remote channel number and mark that the channel is now open. */
1887         c->remote_id = remote_id;
1888         c->type = SSH_CHANNEL_OPEN;
1889
1890         if (compat20) {
1891                 c->remote_window = packet_get_int();
1892                 c->remote_maxpacket = packet_get_int();
1893                 if (c->confirm) {
1894                         debug2("callback start");
1895                         c->confirm(c->self, NULL);
1896                         debug2("callback done");
1897                 }
1898                 debug("channel %d: open confirm rwindow %u rmax %u", c->self,
1899                     c->remote_window, c->remote_maxpacket);
1900         }
1901         packet_check_eom();
1902 }
1903
1904 static char *
1905 reason2txt(int reason)
1906 {
1907         switch (reason) {
1908         case SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED:
1909                 return "administratively prohibited";
1910         case SSH2_OPEN_CONNECT_FAILED:
1911                 return "connect failed";
1912         case SSH2_OPEN_UNKNOWN_CHANNEL_TYPE:
1913                 return "unknown channel type";
1914         case SSH2_OPEN_RESOURCE_SHORTAGE:
1915                 return "resource shortage";
1916         }
1917         return "unknown reason";
1918 }
1919
1920 void
1921 channel_input_open_failure(int type, u_int32_t seq, void *ctxt)
1922 {
1923         int id, reason;
1924         char *msg = NULL, *lang = NULL;
1925         Channel *c;
1926
1927         id = packet_get_int();
1928         c = channel_lookup(id);
1929
1930         if (c==NULL || c->type != SSH_CHANNEL_OPENING)
1931                 packet_disconnect("Received open failure for "
1932                     "non-opening channel %d.", id);
1933         if (compat20) {
1934                 reason = packet_get_int();
1935                 if (!(datafellows & SSH_BUG_OPENFAILURE)) {
1936                         msg  = packet_get_string(NULL);
1937                         lang = packet_get_string(NULL);
1938                 }
1939                 log("channel %d: open failed: %s%s%s", id,
1940                     reason2txt(reason), msg ? ": ": "", msg ? msg : "");
1941                 if (msg != NULL)
1942                         xfree(msg);
1943                 if (lang != NULL)
1944                         xfree(lang);
1945         }
1946         packet_check_eom();
1947         /* Free the channel.  This will also close the socket. */
1948         channel_free(c);
1949 }
1950
1951 void
1952 channel_input_window_adjust(int type, u_int32_t seq, void *ctxt)
1953 {
1954         Channel *c;
1955         int id;
1956         u_int adjust;
1957
1958         if (!compat20)
1959                 return;
1960
1961         /* Get the channel number and verify it. */
1962         id = packet_get_int();
1963         c = channel_lookup(id);
1964
1965         if (c == NULL || c->type != SSH_CHANNEL_OPEN) {
1966                 log("Received window adjust for "
1967                     "non-open channel %d.", id);
1968                 return;
1969         }
1970         adjust = packet_get_int();
1971         packet_check_eom();
1972         debug2("channel %d: rcvd adjust %u", id, adjust);
1973         c->remote_window += adjust;
1974 }
1975
1976 void
1977 channel_input_port_open(int type, u_int32_t seq, void *ctxt)
1978 {
1979         Channel *c = NULL;
1980         u_short host_port;
1981         char *host, *originator_string;
1982         int remote_id, sock = -1;
1983
1984         remote_id = packet_get_int();
1985         host = packet_get_string(NULL);
1986         host_port = packet_get_int();
1987
1988         if (packet_get_protocol_flags() & SSH_PROTOFLAG_HOST_IN_FWD_OPEN) {
1989                 originator_string = packet_get_string(NULL);
1990         } else {
1991                 originator_string = xstrdup("unknown (remote did not supply name)");
1992         }
1993         packet_check_eom();
1994         sock = channel_connect_to(host, host_port);
1995         if (sock != -1) {
1996                 c = channel_new("connected socket",
1997                     SSH_CHANNEL_CONNECTING, sock, sock, -1, 0, 0, 0,
1998                     originator_string, 1);
1999                 c->remote_id = remote_id;
2000         }
2001         if (c == NULL) {
2002                 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
2003                 packet_put_int(remote_id);
2004                 packet_send();
2005         }
2006         xfree(host);
2007 }
2008
2009
2010 /* -- tcp forwarding */
2011
2012 void
2013 channel_set_af(int af)
2014 {
2015         IPv4or6 = af;
2016 }
2017
2018 static int
2019 channel_setup_fwd_listener(int type, const char *listen_addr, u_short listen_port,
2020     const char *host_to_connect, u_short port_to_connect, int gateway_ports)
2021 {
2022         Channel *c;
2023         int success, sock, on = 1;
2024         struct addrinfo hints, *ai, *aitop;
2025         const char *host;
2026         char ntop[NI_MAXHOST], strport[NI_MAXSERV];
2027
2028         success = 0;
2029         host = (type == SSH_CHANNEL_RPORT_LISTENER) ?
2030             listen_addr : host_to_connect;
2031
2032         if (host == NULL) {
2033                 error("No forward host name.");
2034                 return success;
2035         }
2036         if (strlen(host) > SSH_CHANNEL_PATH_LEN - 1) {
2037                 error("Forward host name too long.");
2038                 return success;
2039         }
2040
2041         /*
2042          * getaddrinfo returns a loopback address if the hostname is
2043          * set to NULL and hints.ai_flags is not AI_PASSIVE
2044          */
2045         memset(&hints, 0, sizeof(hints));
2046         hints.ai_family = IPv4or6;
2047         hints.ai_flags = gateway_ports ? AI_PASSIVE : 0;
2048         hints.ai_socktype = SOCK_STREAM;
2049         snprintf(strport, sizeof strport, "%d", listen_port);
2050         if (getaddrinfo(NULL, strport, &hints, &aitop) != 0)
2051                 packet_disconnect("getaddrinfo: fatal error");
2052
2053         for (ai = aitop; ai; ai = ai->ai_next) {
2054                 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
2055                         continue;
2056                 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
2057                     strport, sizeof(strport), NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
2058                         error("channel_setup_fwd_listener: getnameinfo failed");
2059                         continue;
2060                 }
2061                 /* Create a port to listen for the host. */
2062                 sock = socket(ai->ai_family, SOCK_STREAM, 0);
2063                 if (sock < 0) {
2064                         /* this is no error since kernel may not support ipv6 */
2065                         verbose("socket: %.100s", strerror(errno));
2066                         continue;
2067                 }
2068                 /*
2069                  * Set socket options.
2070                  * Allow local port reuse in TIME_WAIT.
2071                  */
2072                 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &on,
2073                     sizeof(on)) == -1)
2074                         error("setsockopt SO_REUSEADDR: %s", strerror(errno));
2075
2076                 debug("Local forwarding listening on %s port %s.", ntop, strport);
2077
2078                 /* Bind the socket to the address. */
2079                 if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
2080                         /* address can be in use ipv6 address is already bound */
2081                         if (!ai->ai_next)
2082                                 error("bind: %.100s", strerror(errno));
2083                         else
2084                                 verbose("bind: %.100s", strerror(errno));
2085
2086                         close(sock);
2087                         continue;
2088                 }
2089                 /* Start listening for connections on the socket. */
2090                 if (listen(sock, 5) < 0) {
2091                         error("listen: %.100s", strerror(errno));
2092                         close(sock);
2093                         continue;
2094                 }
2095                 /* Allocate a channel number for the socket. */
2096                 c = channel_new("port listener", type, sock, sock, -1,
2097                     CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
2098                     0, xstrdup("port listener"), 1);
2099                 strlcpy(c->path, host, sizeof(c->path));
2100                 c->host_port = port_to_connect;
2101                 c->listening_port = listen_port;
2102                 success = 1;
2103         }
2104         if (success == 0)
2105                 error("channel_setup_fwd_listener: cannot listen to port: %d",
2106                     listen_port);
2107         freeaddrinfo(aitop);
2108         return success;
2109 }
2110
2111 /* protocol local port fwd, used by ssh (and sshd in v1) */
2112 int
2113 channel_setup_local_fwd_listener(u_short listen_port,
2114     const char *host_to_connect, u_short port_to_connect, int gateway_ports)
2115 {
2116         return channel_setup_fwd_listener(SSH_CHANNEL_PORT_LISTENER,
2117             NULL, listen_port, host_to_connect, port_to_connect, gateway_ports);
2118 }
2119
2120 /* protocol v2 remote port fwd, used by sshd */
2121 int
2122 channel_setup_remote_fwd_listener(const char *listen_address,
2123     u_short listen_port, int gateway_ports)
2124 {
2125         return channel_setup_fwd_listener(SSH_CHANNEL_RPORT_LISTENER,
2126             listen_address, listen_port, NULL, 0, gateway_ports);
2127 }
2128
2129 /*
2130  * Initiate forwarding of connections to port "port" on remote host through
2131  * the secure channel to host:port from local side.
2132  */
2133
2134 void
2135 channel_request_remote_forwarding(u_short listen_port,
2136     const char *host_to_connect, u_short port_to_connect)
2137 {
2138         int type, success = 0;
2139
2140         /* Record locally that connection to this host/port is permitted. */
2141         if (num_permitted_opens >= SSH_MAX_FORWARDS_PER_DIRECTION)
2142                 fatal("channel_request_remote_forwarding: too many forwards");
2143
2144         /* Send the forward request to the remote side. */
2145         if (compat20) {
2146                 const char *address_to_bind = "0.0.0.0";
2147                 packet_start(SSH2_MSG_GLOBAL_REQUEST);
2148                 packet_put_cstring("tcpip-forward");
2149                 packet_put_char(1);                     /* boolean: want reply */
2150                 packet_put_cstring(address_to_bind);
2151                 packet_put_int(listen_port);
2152                 packet_send();
2153                 packet_write_wait();
2154                 /* Assume that server accepts the request */
2155                 success = 1;
2156         } else {
2157                 packet_start(SSH_CMSG_PORT_FORWARD_REQUEST);
2158                 packet_put_int(listen_port);
2159                 packet_put_cstring(host_to_connect);
2160                 packet_put_int(port_to_connect);
2161                 packet_send();
2162                 packet_write_wait();
2163
2164                 /* Wait for response from the remote side. */
2165                 type = packet_read();
2166                 switch (type) {
2167                 case SSH_SMSG_SUCCESS:
2168                         success = 1;
2169                         break;
2170                 case SSH_SMSG_FAILURE:
2171                         log("Warning: Server denied remote port forwarding.");
2172                         break;
2173                 default:
2174                         /* Unknown packet */
2175                         packet_disconnect("Protocol error for port forward request:"
2176                             "received packet type %d.", type);
2177                 }
2178         }
2179         if (success) {
2180                 permitted_opens[num_permitted_opens].host_to_connect = xstrdup(host_to_connect);
2181                 permitted_opens[num_permitted_opens].port_to_connect = port_to_connect;
2182                 permitted_opens[num_permitted_opens].listen_port = listen_port;
2183                 num_permitted_opens++;
2184         }
2185 }
2186
2187 /*
2188  * This is called after receiving CHANNEL_FORWARDING_REQUEST.  This initates
2189  * listening for the port, and sends back a success reply (or disconnect
2190  * message if there was an error).  This never returns if there was an error.
2191  */
2192
2193 void
2194 channel_input_port_forward_request(int is_root, int gateway_ports)
2195 {
2196         u_short port, host_port;
2197         char *hostname;
2198
2199         /* Get arguments from the packet. */
2200         port = packet_get_int();
2201         hostname = packet_get_string(NULL);
2202         host_port = packet_get_int();
2203
2204 #ifndef HAVE_CYGWIN
2205         /*
2206          * Check that an unprivileged user is not trying to forward a
2207          * privileged port.
2208          */
2209         if (port < IPPORT_RESERVED && !is_root)
2210                 packet_disconnect("Requested forwarding of port %d but user is not root.",
2211                                   port);
2212 #endif
2213         /* Initiate forwarding */
2214         channel_setup_local_fwd_listener(port, hostname, host_port, gateway_ports);
2215
2216         /* Free the argument string. */
2217         xfree(hostname);
2218 }
2219
2220 /*
2221  * Permits opening to any host/port if permitted_opens[] is empty.  This is
2222  * usually called by the server, because the user could connect to any port
2223  * anyway, and the server has no way to know but to trust the client anyway.
2224  */
2225 void
2226 channel_permit_all_opens(void)
2227 {
2228         if (num_permitted_opens == 0)
2229                 all_opens_permitted = 1;
2230 }
2231
2232 void
2233 channel_add_permitted_opens(char *host, int port)
2234 {
2235         if (num_permitted_opens >= SSH_MAX_FORWARDS_PER_DIRECTION)
2236                 fatal("channel_request_remote_forwarding: too many forwards");
2237         debug("allow port forwarding to host %s port %d", host, port);
2238
2239         permitted_opens[num_permitted_opens].host_to_connect = xstrdup(host);
2240         permitted_opens[num_permitted_opens].port_to_connect = port;
2241         num_permitted_opens++;
2242
2243         all_opens_permitted = 0;
2244 }
2245
2246 void
2247 channel_clear_permitted_opens(void)
2248 {
2249         int i;
2250
2251         for (i = 0; i < num_permitted_opens; i++)
2252                 xfree(permitted_opens[i].host_to_connect);
2253         num_permitted_opens = 0;
2254
2255 }
2256
2257
2258 /* return socket to remote host, port */
2259 static int
2260 connect_to(const char *host, u_short port)
2261 {
2262         struct addrinfo hints, *ai, *aitop;
2263         char ntop[NI_MAXHOST], strport[NI_MAXSERV];
2264         int gaierr;
2265         int sock = -1;
2266
2267         memset(&hints, 0, sizeof(hints));
2268         hints.ai_family = IPv4or6;
2269         hints.ai_socktype = SOCK_STREAM;
2270         snprintf(strport, sizeof strport, "%d", port);
2271         if ((gaierr = getaddrinfo(host, strport, &hints, &aitop)) != 0) {
2272                 error("connect_to %.100s: unknown host (%s)", host,
2273                     gai_strerror(gaierr));
2274                 return -1;
2275         }
2276         for (ai = aitop; ai; ai = ai->ai_next) {
2277                 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
2278                         continue;
2279                 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
2280                     strport, sizeof(strport), NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
2281                         error("connect_to: getnameinfo failed");
2282                         continue;
2283                 }
2284                 sock = socket(ai->ai_family, SOCK_STREAM, 0);
2285                 if (sock < 0) {
2286                         error("socket: %.100s", strerror(errno));
2287                         continue;
2288                 }
2289                 if (fcntl(sock, F_SETFL, O_NONBLOCK) < 0)
2290                         fatal("connect_to: F_SETFL: %s", strerror(errno));
2291                 if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0 &&
2292                     errno != EINPROGRESS) {
2293                         error("connect_to %.100s port %s: %.100s", ntop, strport,
2294                             strerror(errno));
2295                         close(sock);
2296                         continue;       /* fail -- try next */
2297                 }
2298                 break; /* success */
2299
2300         }
2301         freeaddrinfo(aitop);
2302         if (!ai) {
2303                 error("connect_to %.100s port %d: failed.", host, port);
2304                 return -1;
2305         }
2306         /* success */
2307         set_nodelay(sock);
2308         return sock;
2309 }
2310
2311 int
2312 channel_connect_by_listen_address(u_short listen_port)
2313 {
2314         int i;
2315
2316         for (i = 0; i < num_permitted_opens; i++)
2317                 if (permitted_opens[i].listen_port == listen_port)
2318                         return connect_to(
2319                             permitted_opens[i].host_to_connect,
2320                             permitted_opens[i].port_to_connect);
2321         error("WARNING: Server requests forwarding for unknown listen_port %d",
2322             listen_port);
2323         return -1;
2324 }
2325
2326 /* Check if connecting to that port is permitted and connect. */
2327 int
2328 channel_connect_to(const char *host, u_short port)
2329 {
2330         int i, permit;
2331
2332         permit = all_opens_permitted;
2333         if (!permit) {
2334                 for (i = 0; i < num_permitted_opens; i++)
2335                         if (permitted_opens[i].port_to_connect == port &&
2336                             strcmp(permitted_opens[i].host_to_connect, host) == 0)
2337                                 permit = 1;
2338
2339         }
2340         if (!permit) {
2341                 log("Received request to connect to host %.100s port %d, "
2342                     "but the request was denied.", host, port);
2343                 return -1;
2344         }
2345         return connect_to(host, port);
2346 }
2347
2348 /* -- X11 forwarding */
2349
2350 /*
2351  * Creates an internet domain socket for listening for X11 connections.
2352  * Returns 0 and a suitable display number for the DISPLAY variable
2353  * stored in display_numberp , or -1 if an error occurs.
2354  */
2355 int
2356 x11_create_display_inet(int x11_display_offset, int x11_use_localhost,
2357     int single_connection, u_int *display_numberp)
2358 {
2359         Channel *nc = NULL;
2360         int display_number, sock;
2361         u_short port;
2362         struct addrinfo hints, *ai, *aitop;
2363         char strport[NI_MAXSERV];
2364         int gaierr, n, num_socks = 0, socks[NUM_SOCKS];
2365
2366         for (display_number = x11_display_offset;
2367             display_number < MAX_DISPLAYS;
2368             display_number++) {
2369                 port = 6000 + display_number;
2370                 memset(&hints, 0, sizeof(hints));
2371                 hints.ai_family = IPv4or6;
2372                 hints.ai_flags = x11_use_localhost ? 0: AI_PASSIVE;
2373                 hints.ai_socktype = SOCK_STREAM;
2374                 snprintf(strport, sizeof strport, "%d", port);
2375                 if ((gaierr = getaddrinfo(NULL, strport, &hints, &aitop)) != 0) {
2376                         error("getaddrinfo: %.100s", gai_strerror(gaierr));
2377                         return -1;
2378                 }
2379                 for (ai = aitop; ai; ai = ai->ai_next) {
2380                         if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
2381                                 continue;
2382                         sock = socket(ai->ai_family, SOCK_STREAM, 0);
2383                         if (sock < 0) {
2384                                 if ((errno != EINVAL) && (errno != EAFNOSUPPORT)) {
2385                                         error("socket: %.100s", strerror(errno));
2386                                         return -1;
2387                                 } else {
2388                                         debug("x11_create_display_inet: Socket family %d not supported",
2389                                                  ai->ai_family);
2390                                         continue;
2391                                 }
2392                         }
2393 #ifdef IPV6_V6ONLY
2394                         if (ai->ai_family == AF_INET6) {
2395                                 int on = 1;
2396                                 if (setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)) < 0)
2397                                         error("setsockopt IPV6_V6ONLY: %.100s", strerror(errno));
2398                         }
2399 #endif
2400                         if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
2401                                 debug("bind port %d: %.100s", port, strerror(errno));
2402                                 close(sock);
2403
2404                                 if (ai->ai_next)
2405                                         continue;
2406
2407                                 for (n = 0; n < num_socks; n++) {
2408                                         close(socks[n]);
2409                                 }
2410                                 num_socks = 0;
2411                                 break;
2412                         }
2413                         socks[num_socks++] = sock;
2414 #ifndef DONT_TRY_OTHER_AF
2415                         if (num_socks == NUM_SOCKS)
2416                                 break;
2417 #else
2418                         if (x11_use_localhost) {
2419                                 if (num_socks == NUM_SOCKS)
2420                                         break;
2421                         } else {
2422                                 break;
2423                         }
2424 #endif
2425                 }
2426                 freeaddrinfo(aitop);
2427                 if (num_socks > 0)
2428                         break;
2429         }
2430         if (display_number >= MAX_DISPLAYS) {
2431                 error("Failed to allocate internet-domain X11 display socket.");
2432                 return -1;
2433         }
2434         /* Start listening for connections on the socket. */
2435         for (n = 0; n < num_socks; n++) {
2436                 sock = socks[n];
2437                 if (listen(sock, 5) < 0) {
2438                         error("listen: %.100s", strerror(errno));
2439                         close(sock);
2440                         return -1;
2441                 }
2442         }
2443
2444         /* Allocate a channel for each socket. */
2445         for (n = 0; n < num_socks; n++) {
2446                 sock = socks[n];
2447                 nc = channel_new("x11 listener",
2448                     SSH_CHANNEL_X11_LISTENER, sock, sock, -1,
2449                     CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
2450                     0, xstrdup("X11 inet listener"), 1);
2451                 nc->single_connection = single_connection;
2452         }
2453
2454         /* Return the display number for the DISPLAY environment variable. */
2455         *display_numberp = display_number;
2456         return (0);
2457 }
2458
2459 static int
2460 connect_local_xsocket(u_int dnr)
2461 {
2462         int sock;
2463         struct sockaddr_un addr;
2464
2465         sock = socket(AF_UNIX, SOCK_STREAM, 0);
2466         if (sock < 0)
2467                 error("socket: %.100s", strerror(errno));
2468         memset(&addr, 0, sizeof(addr));
2469         addr.sun_family = AF_UNIX;
2470         snprintf(addr.sun_path, sizeof addr.sun_path, _PATH_UNIX_X, dnr);
2471         if (connect(sock, (struct sockaddr *) & addr, sizeof(addr)) == 0)
2472                 return sock;
2473         close(sock);
2474         error("connect %.100s: %.100s", addr.sun_path, strerror(errno));
2475         return -1;
2476 }
2477
2478 int
2479 x11_connect_display(void)
2480 {
2481         int display_number, sock = 0;
2482         const char *display;
2483         char buf[1024], *cp;
2484         struct addrinfo hints, *ai, *aitop;
2485         char strport[NI_MAXSERV];
2486         int gaierr;
2487
2488         /* Try to open a socket for the local X server. */
2489         display = getenv("DISPLAY");
2490         if (!display) {
2491                 error("DISPLAY not set.");
2492                 return -1;
2493         }
2494         /*
2495          * Now we decode the value of the DISPLAY variable and make a
2496          * connection to the real X server.
2497          */
2498
2499         /*
2500          * Check if it is a unix domain socket.  Unix domain displays are in
2501          * one of the following formats: unix:d[.s], :d[.s], ::d[.s]
2502          */
2503         if (strncmp(display, "unix:", 5) == 0 ||
2504             display[0] == ':') {
2505                 /* Connect to the unix domain socket. */
2506                 if (sscanf(strrchr(display, ':') + 1, "%d", &display_number) != 1) {
2507                         error("Could not parse display number from DISPLAY: %.100s",
2508                             display);
2509                         return -1;
2510                 }
2511                 /* Create a socket. */
2512                 sock = connect_local_xsocket(display_number);
2513                 if (sock < 0)
2514                         return -1;
2515
2516                 /* OK, we now have a connection to the display. */
2517                 return sock;
2518         }
2519         /*
2520          * Connect to an inet socket.  The DISPLAY value is supposedly
2521          * hostname:d[.s], where hostname may also be numeric IP address.
2522          */
2523         strlcpy(buf, display, sizeof(buf));
2524         cp = strchr(buf, ':');
2525         if (!cp) {
2526                 error("Could not find ':' in DISPLAY: %.100s", display);
2527                 return -1;
2528         }
2529         *cp = 0;
2530         /* buf now contains the host name.  But first we parse the display number. */
2531         if (sscanf(cp + 1, "%d", &display_number) != 1) {
2532                 error("Could not parse display number from DISPLAY: %.100s",
2533                     display);
2534                 return -1;
2535         }
2536
2537         /* Look up the host address */
2538         memset(&hints, 0, sizeof(hints));
2539         hints.ai_family = IPv4or6;
2540         hints.ai_socktype = SOCK_STREAM;
2541         snprintf(strport, sizeof strport, "%d", 6000 + display_number);
2542         if ((gaierr = getaddrinfo(buf, strport, &hints, &aitop)) != 0) {
2543                 error("%.100s: unknown host. (%s)", buf, gai_strerror(gaierr));
2544                 return -1;
2545         }
2546         for (ai = aitop; ai; ai = ai->ai_next) {
2547                 /* Create a socket. */
2548                 sock = socket(ai->ai_family, SOCK_STREAM, 0);
2549                 if (sock < 0) {
2550                         debug("socket: %.100s", strerror(errno));
2551                         continue;
2552                 }
2553                 /* Connect it to the display. */
2554                 if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
2555                         debug("connect %.100s port %d: %.100s", buf,
2556                             6000 + display_number, strerror(errno));
2557                         close(sock);
2558                         continue;
2559                 }
2560                 /* Success */
2561                 break;
2562         }
2563         freeaddrinfo(aitop);
2564         if (!ai) {
2565                 error("connect %.100s port %d: %.100s", buf, 6000 + display_number,
2566                     strerror(errno));
2567                 return -1;
2568         }
2569         set_nodelay(sock);
2570         return sock;
2571 }
2572
2573 /*
2574  * This is called when SSH_SMSG_X11_OPEN is received.  The packet contains
2575  * the remote channel number.  We should do whatever we want, and respond
2576  * with either SSH_MSG_OPEN_CONFIRMATION or SSH_MSG_OPEN_FAILURE.
2577  */
2578
2579 void
2580 x11_input_open(int type, u_int32_t seq, void *ctxt)
2581 {
2582         Channel *c = NULL;
2583         int remote_id, sock = 0;
2584         char *remote_host;
2585
2586         debug("Received X11 open request.");
2587
2588         remote_id = packet_get_int();
2589
2590         if (packet_get_protocol_flags() & SSH_PROTOFLAG_HOST_IN_FWD_OPEN) {
2591                 remote_host = packet_get_string(NULL);
2592         } else {
2593                 remote_host = xstrdup("unknown (remote did not supply name)");
2594         }
2595         packet_check_eom();
2596
2597         /* Obtain a connection to the real X display. */
2598         sock = x11_connect_display();
2599         if (sock != -1) {
2600                 /* Allocate a channel for this connection. */
2601                 c = channel_new("connected x11 socket",
2602                     SSH_CHANNEL_X11_OPEN, sock, sock, -1, 0, 0, 0,
2603                     remote_host, 1);
2604                 c->remote_id = remote_id;
2605                 c->force_drain = 1;
2606         }
2607         if (c == NULL) {
2608                 /* Send refusal to the remote host. */
2609                 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
2610                 packet_put_int(remote_id);
2611         } else {
2612                 /* Send a confirmation to the remote host. */
2613                 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
2614                 packet_put_int(remote_id);
2615                 packet_put_int(c->self);
2616         }
2617         packet_send();
2618 }
2619
2620 /* dummy protocol handler that denies SSH-1 requests (agent/x11) */
2621 void
2622 deny_input_open(int type, u_int32_t seq, void *ctxt)
2623 {
2624         int rchan = packet_get_int();
2625
2626         switch (type) {
2627         case SSH_SMSG_AGENT_OPEN:
2628                 error("Warning: ssh server tried agent forwarding.");
2629                 break;
2630         case SSH_SMSG_X11_OPEN:
2631                 error("Warning: ssh server tried X11 forwarding.");
2632                 break;
2633         default:
2634                 error("deny_input_open: type %d", type);
2635                 break;
2636         }
2637         error("Warning: this is probably a break in attempt by a malicious server.");
2638         packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
2639         packet_put_int(rchan);
2640         packet_send();
2641 }
2642
2643 /*
2644  * Requests forwarding of X11 connections, generates fake authentication
2645  * data, and enables authentication spoofing.
2646  * This should be called in the client only.
2647  */
2648 void
2649 x11_request_forwarding_with_spoofing(int client_session_id,
2650     const char *proto, const char *data)
2651 {
2652         u_int data_len = (u_int) strlen(data) / 2;
2653         u_int i, value, len;
2654         char *new_data;
2655         int screen_number;
2656         const char *cp;
2657         u_int32_t rand = 0;
2658
2659         cp = getenv("DISPLAY");
2660         if (cp)
2661                 cp = strchr(cp, ':');
2662         if (cp)
2663                 cp = strchr(cp, '.');
2664         if (cp)
2665                 screen_number = atoi(cp + 1);
2666         else
2667                 screen_number = 0;
2668
2669         /* Save protocol name. */
2670         x11_saved_proto = xstrdup(proto);
2671
2672         /*
2673          * Extract real authentication data and generate fake data of the
2674          * same length.
2675          */
2676         x11_saved_data = xmalloc(data_len);
2677         x11_fake_data = xmalloc(data_len);
2678         for (i = 0; i < data_len; i++) {
2679                 if (sscanf(data + 2 * i, "%2x", &value) != 1)
2680                         fatal("x11_request_forwarding: bad authentication data: %.100s", data);
2681                 if (i % 4 == 0)
2682                         rand = arc4random();
2683                 x11_saved_data[i] = value;
2684                 x11_fake_data[i] = rand & 0xff;
2685                 rand >>= 8;
2686         }
2687         x11_saved_data_len = data_len;
2688         x11_fake_data_len = data_len;
2689
2690         /* Convert the fake data into hex. */
2691         len = 2 * data_len + 1;
2692         new_data = xmalloc(len);
2693         for (i = 0; i < data_len; i++)
2694                 snprintf(new_data + 2 * i, len - 2 * i,
2695                     "%02x", (u_char) x11_fake_data[i]);
2696
2697         /* Send the request packet. */
2698         if (compat20) {
2699                 channel_request_start(client_session_id, "x11-req", 0);
2700                 packet_put_char(0);     /* XXX bool single connection */
2701         } else {
2702                 packet_start(SSH_CMSG_X11_REQUEST_FORWARDING);
2703         }
2704         packet_put_cstring(proto);
2705         packet_put_cstring(new_data);
2706         packet_put_int(screen_number);
2707         packet_send();
2708         packet_write_wait();
2709         xfree(new_data);
2710 }
2711
2712
2713 /* -- agent forwarding */
2714
2715 /* Sends a message to the server to request authentication fd forwarding. */
2716
2717 void
2718 auth_request_forwarding(void)
2719 {
2720         packet_start(SSH_CMSG_AGENT_REQUEST_FORWARDING);
2721         packet_send();
2722         packet_write_wait();
2723 }
2724
2725 /* This is called to process an SSH_SMSG_AGENT_OPEN message. */
2726
2727 void
2728 auth_input_open_request(int type, u_int32_t seq, void *ctxt)
2729 {
2730         Channel *c = NULL;
2731         int remote_id, sock;
2732         char *name;
2733
2734         /* Read the remote channel number from the message. */
2735         remote_id = packet_get_int();
2736         packet_check_eom();
2737
2738         /*
2739          * Get a connection to the local authentication agent (this may again
2740          * get forwarded).
2741          */
2742         sock = ssh_get_authentication_socket();
2743
2744         /*
2745          * If we could not connect the agent, send an error message back to
2746          * the server. This should never happen unless the agent dies,
2747          * because authentication forwarding is only enabled if we have an
2748          * agent.
2749          */
2750         if (sock >= 0) {
2751                 name = xstrdup("authentication agent connection");
2752                 c = channel_new("", SSH_CHANNEL_OPEN, sock, sock,
2753                     -1, 0, 0, 0, name, 1);
2754                 c->remote_id = remote_id;
2755                 c->force_drain = 1;
2756         }
2757         if (c == NULL) {
2758                 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
2759                 packet_put_int(remote_id);
2760         } else {
2761                 /* Send a confirmation to the remote host. */
2762                 debug("Forwarding authentication connection.");
2763                 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
2764                 packet_put_int(remote_id);
2765                 packet_put_int(c->self);
2766         }
2767         packet_send();
2768 }