]> andersk Git - openssh.git/blob - ssh.c
- reyk@cvs.openbsd.org 2005/12/06 22:38:28
[openssh.git] / ssh.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  * Ssh client program.  This program can be used to log into a remote machine.
6  * The software supports strong authentication, encryption, and forwarding
7  * of X11, TCP/IP, and authentication connections.
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  * Copyright (c) 1999 Niels Provos.  All rights reserved.
16  * Copyright (c) 2000, 2001, 2002, 2003 Markus Friedl.  All rights reserved.
17  *
18  * Modified to work with SSL by Niels Provos <provos@citi.umich.edu>
19  * in Canada (German citizen).
20  *
21  * Redistribution and use in source and binary forms, with or without
22  * modification, are permitted provided that the following conditions
23  * are met:
24  * 1. Redistributions of source code must retain the above copyright
25  *    notice, this list of conditions and the following disclaimer.
26  * 2. Redistributions in binary form must reproduce the above copyright
27  *    notice, this list of conditions and the following disclaimer in the
28  *    documentation and/or other materials provided with the distribution.
29  *
30  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
31  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
32  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
33  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
34  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
35  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
36  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
37  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
38  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
39  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40  */
41
42 #include "includes.h"
43 RCSID("$OpenBSD: ssh.c,v 1.255 2005/12/06 22:38:27 reyk Exp $");
44
45 #include <openssl/evp.h>
46 #include <openssl/err.h>
47
48 #include "ssh.h"
49 #include "ssh1.h"
50 #include "ssh2.h"
51 #include "compat.h"
52 #include "cipher.h"
53 #include "xmalloc.h"
54 #include "packet.h"
55 #include "buffer.h"
56 #include "bufaux.h"
57 #include "channels.h"
58 #include "key.h"
59 #include "authfd.h"
60 #include "authfile.h"
61 #include "pathnames.h"
62 #include "dispatch.h"
63 #include "clientloop.h"
64 #include "log.h"
65 #include "readconf.h"
66 #include "sshconnect.h"
67 #include "misc.h"
68 #include "kex.h"
69 #include "mac.h"
70 #include "sshpty.h"
71 #include "match.h"
72 #include "msg.h"
73 #include "monitor_fdpass.h"
74 #include "uidswap.h"
75
76 #ifdef SMARTCARD
77 #include "scard.h"
78 #endif
79
80 extern char *__progname;
81
82 /* Flag indicating whether debug mode is on.  This can be set on the command line. */
83 int debug_flag = 0;
84
85 /* Flag indicating whether a tty should be allocated */
86 int tty_flag = 0;
87 int no_tty_flag = 0;
88 int force_tty_flag = 0;
89
90 /* don't exec a shell */
91 int no_shell_flag = 0;
92
93 /*
94  * Flag indicating that nothing should be read from stdin.  This can be set
95  * on the command line.
96  */
97 int stdin_null_flag = 0;
98
99 /*
100  * Flag indicating that ssh should fork after authentication.  This is useful
101  * so that the passphrase can be entered manually, and then ssh goes to the
102  * background.
103  */
104 int fork_after_authentication_flag = 0;
105
106 /*
107  * General data structure for command line options and options configurable
108  * in configuration files.  See readconf.h.
109  */
110 Options options;
111
112 /* optional user configfile */
113 char *config = NULL;
114
115 /*
116  * Name of the host we are connecting to.  This is the name given on the
117  * command line, or the HostName specified for the user-supplied name in a
118  * configuration file.
119  */
120 char *host;
121
122 /* socket address the host resolves to */
123 struct sockaddr_storage hostaddr;
124
125 /* Private host keys. */
126 Sensitive sensitive_data;
127
128 /* Original real UID. */
129 uid_t original_real_uid;
130 uid_t original_effective_uid;
131
132 /* command to be executed */
133 Buffer command;
134
135 /* Should we execute a command or invoke a subsystem? */
136 int subsystem_flag = 0;
137
138 /* # of replies received for global requests */
139 static int client_global_request_id = 0;
140
141 /* pid of proxycommand child process */
142 pid_t proxy_command_pid = 0;
143
144 /* fd to control socket */
145 int control_fd = -1;
146
147 /* Multiplexing control command */
148 static u_int mux_command = 0;
149
150 /* Only used in control client mode */
151 volatile sig_atomic_t control_client_terminate = 0;
152 u_int control_server_pid = 0;
153
154 /* Prints a help message to the user.  This function never returns. */
155
156 static void
157 usage(void)
158 {
159         fprintf(stderr,
160 "usage: ssh [-1246AaCfgkMNnqsTtVvXxY] [-b bind_address] [-c cipher_spec]\n"
161 "           [-D [bind_address:]port] [-e escape_char] [-F configfile]\n"
162 "           [-i identity_file] [-L [bind_address:]port:host:hostport]\n"
163 "           [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]\n"
164 "           [-R [bind_address:]port:host:hostport] [-S ctl_path]\n"
165 "           [-w tunnel:tunnel] [user@]hostname [command]\n"
166         );
167         exit(1);
168 }
169
170 static int ssh_session(void);
171 static int ssh_session2(void);
172 static void load_public_identity_files(void);
173 static void control_client(const char *path);
174
175 /*
176  * Main program for the ssh client.
177  */
178 int
179 main(int ac, char **av)
180 {
181         int i, opt, exit_status;
182         char *p, *cp, *line, buf[256];
183         struct stat st;
184         struct passwd *pw;
185         int dummy;
186         extern int optind, optreset;
187         extern char *optarg;
188         struct servent *sp;
189         Forward fwd;
190
191         /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
192         sanitise_stdfd();
193
194         __progname = ssh_get_progname(av[0]);
195         init_rng();
196
197         /*
198          * Save the original real uid.  It will be needed later (uid-swapping
199          * may clobber the real uid).
200          */
201         original_real_uid = getuid();
202         original_effective_uid = geteuid();
203
204         /*
205          * Use uid-swapping to give up root privileges for the duration of
206          * option processing.  We will re-instantiate the rights when we are
207          * ready to create the privileged port, and will permanently drop
208          * them when the port has been created (actually, when the connection
209          * has been made, as we may need to create the port several times).
210          */
211         PRIV_END;
212
213 #ifdef HAVE_SETRLIMIT
214         /* If we are installed setuid root be careful to not drop core. */
215         if (original_real_uid != original_effective_uid) {
216                 struct rlimit rlim;
217                 rlim.rlim_cur = rlim.rlim_max = 0;
218                 if (setrlimit(RLIMIT_CORE, &rlim) < 0)
219                         fatal("setrlimit failed: %.100s", strerror(errno));
220         }
221 #endif
222         /* Get user data. */
223         pw = getpwuid(original_real_uid);
224         if (!pw) {
225                 logit("You don't exist, go away!");
226                 exit(1);
227         }
228         /* Take a copy of the returned structure. */
229         pw = pwcopy(pw);
230
231         /*
232          * Set our umask to something reasonable, as some files are created
233          * with the default umask.  This will make them world-readable but
234          * writable only by the owner, which is ok for all files for which we
235          * don't set the modes explicitly.
236          */
237         umask(022);
238
239         /* Initialize option structure to indicate that no values have been set. */
240         initialize_options(&options);
241
242         /* Parse command-line arguments. */
243         host = NULL;
244
245 again:
246         while ((opt = getopt(ac, av,
247             "1246ab:c:e:fgi:kl:m:no:p:qstvxACD:F:I:L:MNO:PR:S:TVw:XY")) != -1) {
248                 switch (opt) {
249                 case '1':
250                         options.protocol = SSH_PROTO_1;
251                         break;
252                 case '2':
253                         options.protocol = SSH_PROTO_2;
254                         break;
255                 case '4':
256                         options.address_family = AF_INET;
257                         break;
258                 case '6':
259                         options.address_family = AF_INET6;
260                         break;
261                 case 'n':
262                         stdin_null_flag = 1;
263                         break;
264                 case 'f':
265                         fork_after_authentication_flag = 1;
266                         stdin_null_flag = 1;
267                         break;
268                 case 'x':
269                         options.forward_x11 = 0;
270                         break;
271                 case 'X':
272                         options.forward_x11 = 1;
273                         break;
274                 case 'Y':
275                         options.forward_x11 = 1;
276                         options.forward_x11_trusted = 1;
277                         break;
278                 case 'g':
279                         options.gateway_ports = 1;
280                         break;
281                 case 'O':
282                         if (strcmp(optarg, "check") == 0)
283                                 mux_command = SSHMUX_COMMAND_ALIVE_CHECK;
284                         else if (strcmp(optarg, "exit") == 0)
285                                 mux_command = SSHMUX_COMMAND_TERMINATE;
286                         else
287                                 fatal("Invalid multiplex command.");
288                         break;
289                 case 'P':       /* deprecated */
290                         options.use_privileged_port = 0;
291                         break;
292                 case 'a':
293                         options.forward_agent = 0;
294                         break;
295                 case 'A':
296                         options.forward_agent = 1;
297                         break;
298                 case 'k':
299                         options.gss_deleg_creds = 0;
300                         break;
301                 case 'i':
302                         if (stat(optarg, &st) < 0) {
303                                 fprintf(stderr, "Warning: Identity file %s "
304                                     "not accessible: %s.\n", optarg,
305                                     strerror(errno));
306                                 break;
307                         }
308                         if (options.num_identity_files >=
309                             SSH_MAX_IDENTITY_FILES)
310                                 fatal("Too many identity files specified "
311                                     "(max %d)", SSH_MAX_IDENTITY_FILES);
312                         options.identity_files[options.num_identity_files++] =
313                             xstrdup(optarg);
314                         break;
315                 case 'I':
316 #ifdef SMARTCARD
317                         options.smartcard_device = xstrdup(optarg);
318 #else
319                         fprintf(stderr, "no support for smartcards.\n");
320 #endif
321                         break;
322                 case 't':
323                         if (tty_flag)
324                                 force_tty_flag = 1;
325                         tty_flag = 1;
326                         break;
327                 case 'v':
328                         if (debug_flag == 0) {
329                                 debug_flag = 1;
330                                 options.log_level = SYSLOG_LEVEL_DEBUG1;
331                         } else {
332                                 if (options.log_level < SYSLOG_LEVEL_DEBUG3)
333                                         options.log_level++;
334                                 break;
335                         }
336                         /* FALLTHROUGH */
337                 case 'V':
338                         fprintf(stderr, "%s, %s\n",
339                             SSH_RELEASE, SSLeay_version(SSLEAY_VERSION));
340                         if (opt == 'V')
341                                 exit(0);
342                         break;
343                 case 'w':
344                         options.tun_open = 1;
345                         options.tun_local = a2tun(optarg, &options.tun_remote);
346                         if (options.tun_local < -1) {
347                                 fprintf(stderr, "Bad tun device '%s'\n", optarg);
348                                 exit(1);
349                         }
350                         break;
351                 case 'q':
352                         options.log_level = SYSLOG_LEVEL_QUIET;
353                         break;
354                 case 'e':
355                         if (optarg[0] == '^' && optarg[2] == 0 &&
356                             (u_char) optarg[1] >= 64 &&
357                             (u_char) optarg[1] < 128)
358                                 options.escape_char = (u_char) optarg[1] & 31;
359                         else if (strlen(optarg) == 1)
360                                 options.escape_char = (u_char) optarg[0];
361                         else if (strcmp(optarg, "none") == 0)
362                                 options.escape_char = SSH_ESCAPECHAR_NONE;
363                         else {
364                                 fprintf(stderr, "Bad escape character '%s'.\n",
365                                     optarg);
366                                 exit(1);
367                         }
368                         break;
369                 case 'c':
370                         if (ciphers_valid(optarg)) {
371                                 /* SSH2 only */
372                                 options.ciphers = xstrdup(optarg);
373                                 options.cipher = SSH_CIPHER_INVALID;
374                         } else {
375                                 /* SSH1 only */
376                                 options.cipher = cipher_number(optarg);
377                                 if (options.cipher == -1) {
378                                         fprintf(stderr,
379                                             "Unknown cipher type '%s'\n",
380                                             optarg);
381                                         exit(1);
382                                 }
383                                 if (options.cipher == SSH_CIPHER_3DES)
384                                         options.ciphers = "3des-cbc";
385                                 else if (options.cipher == SSH_CIPHER_BLOWFISH)
386                                         options.ciphers = "blowfish-cbc";
387                                 else
388                                         options.ciphers = (char *)-1;
389                         }
390                         break;
391                 case 'm':
392                         if (mac_valid(optarg))
393                                 options.macs = xstrdup(optarg);
394                         else {
395                                 fprintf(stderr, "Unknown mac type '%s'\n",
396                                     optarg);
397                                 exit(1);
398                         }
399                         break;
400                 case 'M':
401                         if (options.control_master == SSHCTL_MASTER_YES)
402                                 options.control_master = SSHCTL_MASTER_ASK;
403                         else
404                                 options.control_master = SSHCTL_MASTER_YES;
405                         break;
406                 case 'p':
407                         options.port = a2port(optarg);
408                         if (options.port == 0) {
409                                 fprintf(stderr, "Bad port '%s'\n", optarg);
410                                 exit(1);
411                         }
412                         break;
413                 case 'l':
414                         options.user = optarg;
415                         break;
416
417                 case 'L':
418                         if (parse_forward(&fwd, optarg))
419                                 add_local_forward(&options, &fwd);
420                         else {
421                                 fprintf(stderr,
422                                     "Bad local forwarding specification '%s'\n",
423                                     optarg);
424                                 exit(1);
425                         }
426                         break;
427
428                 case 'R':
429                         if (parse_forward(&fwd, optarg)) {
430                                 add_remote_forward(&options, &fwd);
431                         } else {
432                                 fprintf(stderr,
433                                     "Bad remote forwarding specification "
434                                     "'%s'\n", optarg);
435                                 exit(1);
436                         }
437                         break;
438
439                 case 'D':
440                         cp = p = xstrdup(optarg);
441                         memset(&fwd, '\0', sizeof(fwd));
442                         fwd.connect_host = "socks";
443                         if ((fwd.listen_host = hpdelim(&cp)) == NULL) {
444                                 fprintf(stderr, "Bad dynamic forwarding "
445                                     "specification '%.100s'\n", optarg);
446                                 exit(1);
447                         }
448                         if (cp != NULL) {
449                                 fwd.listen_port = a2port(cp);
450                                 fwd.listen_host = cleanhostname(fwd.listen_host);
451                         } else {
452                                 fwd.listen_port = a2port(fwd.listen_host);
453                                 fwd.listen_host = NULL;
454                         }
455
456                         if (fwd.listen_port == 0) {
457                                 fprintf(stderr, "Bad dynamic port '%s'\n",
458                                     optarg);
459                                 exit(1);
460                         }
461                         add_local_forward(&options, &fwd);
462                         xfree(p);
463                         break;
464
465                 case 'C':
466                         options.compression = 1;
467                         break;
468                 case 'N':
469                         no_shell_flag = 1;
470                         no_tty_flag = 1;
471                         break;
472                 case 'T':
473                         no_tty_flag = 1;
474                         break;
475                 case 'o':
476                         dummy = 1;
477                         line = xstrdup(optarg);
478                         if (process_config_line(&options, host ? host : "",
479                             line, "command-line", 0, &dummy) != 0)
480                                 exit(1);
481                         xfree(line);
482                         break;
483                 case 's':
484                         subsystem_flag = 1;
485                         break;
486                 case 'S':
487                         if (options.control_path != NULL)
488                                 free(options.control_path);
489                         options.control_path = xstrdup(optarg);
490                         break;
491                 case 'b':
492                         options.bind_address = optarg;
493                         break;
494                 case 'F':
495                         config = optarg;
496                         break;
497                 default:
498                         usage();
499                 }
500         }
501
502         ac -= optind;
503         av += optind;
504
505         if (ac > 0 && !host && **av != '-') {
506                 if (strrchr(*av, '@')) {
507                         p = xstrdup(*av);
508                         cp = strrchr(p, '@');
509                         if (cp == NULL || cp == p)
510                                 usage();
511                         options.user = p;
512                         *cp = '\0';
513                         host = ++cp;
514                 } else
515                         host = *av;
516                 if (ac > 1) {
517                         optind = optreset = 1;
518                         goto again;
519                 }
520                 ac--, av++;
521         }
522
523         /* Check that we got a host name. */
524         if (!host)
525                 usage();
526
527         SSLeay_add_all_algorithms();
528         ERR_load_crypto_strings();
529
530         /* Initialize the command to execute on remote host. */
531         buffer_init(&command);
532
533         /*
534          * Save the command to execute on the remote host in a buffer. There
535          * is no limit on the length of the command, except by the maximum
536          * packet size.  Also sets the tty flag if there is no command.
537          */
538         if (!ac) {
539                 /* No command specified - execute shell on a tty. */
540                 tty_flag = 1;
541                 if (subsystem_flag) {
542                         fprintf(stderr,
543                             "You must specify a subsystem to invoke.\n");
544                         usage();
545                 }
546         } else {
547                 /* A command has been specified.  Store it into the buffer. */
548                 for (i = 0; i < ac; i++) {
549                         if (i)
550                                 buffer_append(&command, " ", 1);
551                         buffer_append(&command, av[i], strlen(av[i]));
552                 }
553         }
554
555         /* Cannot fork to background if no command. */
556         if (fork_after_authentication_flag && buffer_len(&command) == 0 && !no_shell_flag)
557                 fatal("Cannot fork into background without a command to execute.");
558
559         /* Allocate a tty by default if no command specified. */
560         if (buffer_len(&command) == 0)
561                 tty_flag = 1;
562
563         /* Force no tty */
564         if (no_tty_flag)
565                 tty_flag = 0;
566         /* Do not allocate a tty if stdin is not a tty. */
567         if ((!isatty(fileno(stdin)) || stdin_null_flag) && !force_tty_flag) {
568                 if (tty_flag)
569                         logit("Pseudo-terminal will not be allocated because stdin is not a terminal.");
570                 tty_flag = 0;
571         }
572
573         /*
574          * Initialize "log" output.  Since we are the client all output
575          * actually goes to stderr.
576          */
577         log_init(av[0], options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
578             SYSLOG_FACILITY_USER, 1);
579
580         /*
581          * Read per-user configuration file.  Ignore the system wide config
582          * file if the user specifies a config file on the command line.
583          */
584         if (config != NULL) {
585                 if (!read_config_file(config, host, &options, 0))
586                         fatal("Can't open user config file %.100s: "
587                             "%.100s", config, strerror(errno));
588         } else  {
589                 snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir,
590                     _PATH_SSH_USER_CONFFILE);
591                 (void)read_config_file(buf, host, &options, 1);
592
593                 /* Read systemwide configuration file after use config. */
594                 (void)read_config_file(_PATH_HOST_CONFIG_FILE, host,
595                     &options, 0);
596         }
597
598         /* Fill configuration defaults. */
599         fill_default_options(&options);
600
601         channel_set_af(options.address_family);
602
603         /* reinit */
604         log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, 1);
605
606         seed_rng();
607
608         if (options.user == NULL)
609                 options.user = xstrdup(pw->pw_name);
610
611         if (options.hostname != NULL)
612                 host = options.hostname;
613
614         /* force lowercase for hostkey matching */
615         if (options.host_key_alias != NULL) {
616                 for (p = options.host_key_alias; *p; p++)
617                         if (isupper(*p))
618                                 *p = tolower(*p);
619         }
620
621         /* Get default port if port has not been set. */
622         if (options.port == 0) {
623                 sp = getservbyname(SSH_SERVICE_NAME, "tcp");
624                 options.port = sp ? ntohs(sp->s_port) : SSH_DEFAULT_PORT;
625         }
626
627         if (options.proxy_command != NULL &&
628             strcmp(options.proxy_command, "none") == 0)
629                 options.proxy_command = NULL;
630         if (options.control_path != NULL &&
631             strcmp(options.control_path, "none") == 0)
632                 options.control_path = NULL;
633
634         if (options.control_path != NULL) {
635                 snprintf(buf, sizeof(buf), "%d", options.port);
636                 cp = tilde_expand_filename(options.control_path,
637                     original_real_uid);
638                 options.control_path = percent_expand(cp, "p", buf, "h", host,
639                     "r", options.user, (char *)NULL);
640                 xfree(cp);
641         }
642         if (mux_command != 0 && options.control_path == NULL)
643                 fatal("No ControlPath specified for \"-O\" command");
644         if (options.control_path != NULL)
645                 control_client(options.control_path);
646
647         /* Open a connection to the remote host. */
648         if (ssh_connect(host, &hostaddr, options.port,
649             options.address_family, options.connection_attempts,
650 #ifdef HAVE_CYGWIN
651             options.use_privileged_port,
652 #else
653             original_effective_uid == 0 && options.use_privileged_port,
654 #endif
655             options.proxy_command) != 0)
656                 exit(1);
657
658         /*
659          * If we successfully made the connection, load the host private key
660          * in case we will need it later for combined rsa-rhosts
661          * authentication. This must be done before releasing extra
662          * privileges, because the file is only readable by root.
663          * If we cannot access the private keys, load the public keys
664          * instead and try to execute the ssh-keysign helper instead.
665          */
666         sensitive_data.nkeys = 0;
667         sensitive_data.keys = NULL;
668         sensitive_data.external_keysign = 0;
669         if (options.rhosts_rsa_authentication ||
670             options.hostbased_authentication) {
671                 sensitive_data.nkeys = 3;
672                 sensitive_data.keys = xmalloc(sensitive_data.nkeys *
673                     sizeof(Key));
674
675                 PRIV_START;
676                 sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
677                     _PATH_HOST_KEY_FILE, "", NULL);
678                 sensitive_data.keys[1] = key_load_private_type(KEY_DSA,
679                     _PATH_HOST_DSA_KEY_FILE, "", NULL);
680                 sensitive_data.keys[2] = key_load_private_type(KEY_RSA,
681                     _PATH_HOST_RSA_KEY_FILE, "", NULL);
682                 PRIV_END;
683
684                 if (options.hostbased_authentication == 1 &&
685                     sensitive_data.keys[0] == NULL &&
686                     sensitive_data.keys[1] == NULL &&
687                     sensitive_data.keys[2] == NULL) {
688                         sensitive_data.keys[1] = key_load_public(
689                             _PATH_HOST_DSA_KEY_FILE, NULL);
690                         sensitive_data.keys[2] = key_load_public(
691                             _PATH_HOST_RSA_KEY_FILE, NULL);
692                         sensitive_data.external_keysign = 1;
693                 }
694         }
695         /*
696          * Get rid of any extra privileges that we may have.  We will no
697          * longer need them.  Also, extra privileges could make it very hard
698          * to read identity files and other non-world-readable files from the
699          * user's home directory if it happens to be on a NFS volume where
700          * root is mapped to nobody.
701          */
702         if (original_effective_uid == 0) {
703                 PRIV_START;
704                 permanently_set_uid(pw);
705         }
706
707         /*
708          * Now that we are back to our own permissions, create ~/.ssh
709          * directory if it doesn't already exist.
710          */
711         snprintf(buf, sizeof buf, "%.100s%s%.100s", pw->pw_dir, strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
712         if (stat(buf, &st) < 0)
713                 if (mkdir(buf, 0700) < 0)
714                         error("Could not create directory '%.200s'.", buf);
715
716         /* load options.identity_files */
717         load_public_identity_files();
718
719         /* Expand ~ in known host file names. */
720         /* XXX mem-leaks: */
721         options.system_hostfile =
722             tilde_expand_filename(options.system_hostfile, original_real_uid);
723         options.user_hostfile =
724             tilde_expand_filename(options.user_hostfile, original_real_uid);
725         options.system_hostfile2 =
726             tilde_expand_filename(options.system_hostfile2, original_real_uid);
727         options.user_hostfile2 =
728             tilde_expand_filename(options.user_hostfile2, original_real_uid);
729
730         signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
731
732         /* Log into the remote system.  This never returns if the login fails. */
733         ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr, pw);
734
735         /* We no longer need the private host keys.  Clear them now. */
736         if (sensitive_data.nkeys != 0) {
737                 for (i = 0; i < sensitive_data.nkeys; i++) {
738                         if (sensitive_data.keys[i] != NULL) {
739                                 /* Destroys contents safely */
740                                 debug3("clear hostkey %d", i);
741                                 key_free(sensitive_data.keys[i]);
742                                 sensitive_data.keys[i] = NULL;
743                         }
744                 }
745                 xfree(sensitive_data.keys);
746         }
747         for (i = 0; i < options.num_identity_files; i++) {
748                 if (options.identity_files[i]) {
749                         xfree(options.identity_files[i]);
750                         options.identity_files[i] = NULL;
751                 }
752                 if (options.identity_keys[i]) {
753                         key_free(options.identity_keys[i]);
754                         options.identity_keys[i] = NULL;
755                 }
756         }
757
758         exit_status = compat20 ? ssh_session2() : ssh_session();
759         packet_close();
760
761         if (options.control_path != NULL && control_fd != -1)
762                 unlink(options.control_path);
763
764         /*
765          * Send SIGHUP to proxy command if used. We don't wait() in
766          * case it hangs and instead rely on init to reap the child
767          */
768         if (proxy_command_pid > 1)
769                 kill(proxy_command_pid, SIGHUP);
770
771         return exit_status;
772 }
773
774 static void
775 ssh_init_forwarding(void)
776 {
777         int success = 0;
778         int i;
779
780         /* Initiate local TCP/IP port forwardings. */
781         for (i = 0; i < options.num_local_forwards; i++) {
782                 debug("Local connections to %.200s:%d forwarded to remote "
783                     "address %.200s:%d",
784                     (options.local_forwards[i].listen_host == NULL) ?
785                     (options.gateway_ports ? "*" : "LOCALHOST") :
786                     options.local_forwards[i].listen_host,
787                     options.local_forwards[i].listen_port,
788                     options.local_forwards[i].connect_host,
789                     options.local_forwards[i].connect_port);
790                 success += channel_setup_local_fwd_listener(
791                     options.local_forwards[i].listen_host,
792                     options.local_forwards[i].listen_port,
793                     options.local_forwards[i].connect_host,
794                     options.local_forwards[i].connect_port,
795                     options.gateway_ports);
796         }
797         if (i > 0 && success == 0)
798                 error("Could not request local forwarding.");
799
800         /* Initiate remote TCP/IP port forwardings. */
801         for (i = 0; i < options.num_remote_forwards; i++) {
802                 debug("Remote connections from %.200s:%d forwarded to "
803                     "local address %.200s:%d",
804                     (options.remote_forwards[i].listen_host == NULL) ?
805                     "LOCALHOST" : options.remote_forwards[i].listen_host,
806                     options.remote_forwards[i].listen_port,
807                     options.remote_forwards[i].connect_host,
808                     options.remote_forwards[i].connect_port);
809                 channel_request_remote_forwarding(
810                     options.remote_forwards[i].listen_host,
811                     options.remote_forwards[i].listen_port,
812                     options.remote_forwards[i].connect_host,
813                     options.remote_forwards[i].connect_port);
814         }
815 }
816
817 static void
818 check_agent_present(void)
819 {
820         if (options.forward_agent) {
821                 /* Clear agent forwarding if we don't have an agent. */
822                 if (!ssh_agent_present())
823                         options.forward_agent = 0;
824         }
825 }
826
827 static int
828 ssh_session(void)
829 {
830         int type;
831         int interactive = 0;
832         int have_tty = 0;
833         struct winsize ws;
834         char *cp;
835         const char *display;
836
837         /* Enable compression if requested. */
838         if (options.compression) {
839                 debug("Requesting compression at level %d.", options.compression_level);
840
841                 if (options.compression_level < 1 || options.compression_level > 9)
842                         fatal("Compression level must be from 1 (fast) to 9 (slow, best).");
843
844                 /* Send the request. */
845                 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
846                 packet_put_int(options.compression_level);
847                 packet_send();
848                 packet_write_wait();
849                 type = packet_read();
850                 if (type == SSH_SMSG_SUCCESS)
851                         packet_start_compression(options.compression_level);
852                 else if (type == SSH_SMSG_FAILURE)
853                         logit("Warning: Remote host refused compression.");
854                 else
855                         packet_disconnect("Protocol error waiting for compression response.");
856         }
857         /* Allocate a pseudo tty if appropriate. */
858         if (tty_flag) {
859                 debug("Requesting pty.");
860
861                 /* Start the packet. */
862                 packet_start(SSH_CMSG_REQUEST_PTY);
863
864                 /* Store TERM in the packet.  There is no limit on the
865                    length of the string. */
866                 cp = getenv("TERM");
867                 if (!cp)
868                         cp = "";
869                 packet_put_cstring(cp);
870
871                 /* Store window size in the packet. */
872                 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
873                         memset(&ws, 0, sizeof(ws));
874                 packet_put_int(ws.ws_row);
875                 packet_put_int(ws.ws_col);
876                 packet_put_int(ws.ws_xpixel);
877                 packet_put_int(ws.ws_ypixel);
878
879                 /* Store tty modes in the packet. */
880                 tty_make_modes(fileno(stdin), NULL);
881
882                 /* Send the packet, and wait for it to leave. */
883                 packet_send();
884                 packet_write_wait();
885
886                 /* Read response from the server. */
887                 type = packet_read();
888                 if (type == SSH_SMSG_SUCCESS) {
889                         interactive = 1;
890                         have_tty = 1;
891                 } else if (type == SSH_SMSG_FAILURE)
892                         logit("Warning: Remote host failed or refused to allocate a pseudo tty.");
893                 else
894                         packet_disconnect("Protocol error waiting for pty request response.");
895         }
896         /* Request X11 forwarding if enabled and DISPLAY is set. */
897         display = getenv("DISPLAY");
898         if (options.forward_x11 && display != NULL) {
899                 char *proto, *data;
900                 /* Get reasonable local authentication information. */
901                 client_x11_get_proto(display, options.xauth_location,
902                     options.forward_x11_trusted, &proto, &data);
903                 /* Request forwarding with authentication spoofing. */
904                 debug("Requesting X11 forwarding with authentication spoofing.");
905                 x11_request_forwarding_with_spoofing(0, display, proto, data);
906
907                 /* Read response from the server. */
908                 type = packet_read();
909                 if (type == SSH_SMSG_SUCCESS) {
910                         interactive = 1;
911                 } else if (type == SSH_SMSG_FAILURE) {
912                         logit("Warning: Remote host denied X11 forwarding.");
913                 } else {
914                         packet_disconnect("Protocol error waiting for X11 forwarding");
915                 }
916         }
917         /* Tell the packet module whether this is an interactive session. */
918         packet_set_interactive(interactive);
919
920         /* Request authentication agent forwarding if appropriate. */
921         check_agent_present();
922
923         if (options.forward_agent) {
924                 debug("Requesting authentication agent forwarding.");
925                 auth_request_forwarding();
926
927                 /* Read response from the server. */
928                 type = packet_read();
929                 packet_check_eom();
930                 if (type != SSH_SMSG_SUCCESS)
931                         logit("Warning: Remote host denied authentication agent forwarding.");
932         }
933
934         /* Initiate port forwardings. */
935         ssh_init_forwarding();
936
937         /* If requested, let ssh continue in the background. */
938         if (fork_after_authentication_flag)
939                 if (daemon(1, 1) < 0)
940                         fatal("daemon() failed: %.200s", strerror(errno));
941
942         /*
943          * If a command was specified on the command line, execute the
944          * command now. Otherwise request the server to start a shell.
945          */
946         if (buffer_len(&command) > 0) {
947                 int len = buffer_len(&command);
948                 if (len > 900)
949                         len = 900;
950                 debug("Sending command: %.*s", len, (u_char *)buffer_ptr(&command));
951                 packet_start(SSH_CMSG_EXEC_CMD);
952                 packet_put_string(buffer_ptr(&command), buffer_len(&command));
953                 packet_send();
954                 packet_write_wait();
955         } else {
956                 debug("Requesting shell.");
957                 packet_start(SSH_CMSG_EXEC_SHELL);
958                 packet_send();
959                 packet_write_wait();
960         }
961
962         /* Enter the interactive session. */
963         return client_loop(have_tty, tty_flag ?
964             options.escape_char : SSH_ESCAPECHAR_NONE, 0);
965 }
966
967 static void
968 ssh_subsystem_reply(int type, u_int32_t seq, void *ctxt)
969 {
970         int id, len;
971
972         id = packet_get_int();
973         len = buffer_len(&command);
974         if (len > 900)
975                 len = 900;
976         packet_check_eom();
977         if (type == SSH2_MSG_CHANNEL_FAILURE)
978                 fatal("Request for subsystem '%.*s' failed on channel %d",
979                     len, (u_char *)buffer_ptr(&command), id);
980 }
981
982 void
983 client_global_request_reply_fwd(int type, u_int32_t seq, void *ctxt)
984 {
985         int i;
986
987         i = client_global_request_id++;
988         if (i >= options.num_remote_forwards)
989                 return;
990         debug("remote forward %s for: listen %d, connect %s:%d",
991             type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
992             options.remote_forwards[i].listen_port,
993             options.remote_forwards[i].connect_host,
994             options.remote_forwards[i].connect_port);
995         if (type == SSH2_MSG_REQUEST_FAILURE)
996                 logit("Warning: remote port forwarding failed for listen "
997                     "port %d", options.remote_forwards[i].listen_port);
998 }
999
1000 static void
1001 ssh_control_listener(void)
1002 {
1003         struct sockaddr_un addr;
1004         mode_t old_umask;
1005         int addr_len;
1006
1007         if (options.control_path == NULL ||
1008             options.control_master == SSHCTL_MASTER_NO)
1009                 return;
1010
1011         debug("setting up multiplex master socket");
1012
1013         memset(&addr, '\0', sizeof(addr));
1014         addr.sun_family = AF_UNIX;
1015         addr_len = offsetof(struct sockaddr_un, sun_path) +
1016             strlen(options.control_path) + 1;
1017
1018         if (strlcpy(addr.sun_path, options.control_path,
1019             sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1020                 fatal("ControlPath too long");
1021
1022         if ((control_fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1023                 fatal("%s socket(): %s", __func__, strerror(errno));
1024
1025         old_umask = umask(0177);
1026         if (bind(control_fd, (struct sockaddr*)&addr, addr_len) == -1) {
1027                 control_fd = -1;
1028                 if (errno == EINVAL || errno == EADDRINUSE)
1029                         fatal("ControlSocket %s already exists",
1030                             options.control_path);
1031                 else
1032                         fatal("%s bind(): %s", __func__, strerror(errno));
1033         }
1034         umask(old_umask);
1035
1036         if (listen(control_fd, 64) == -1)
1037                 fatal("%s listen(): %s", __func__, strerror(errno));
1038
1039         set_nonblock(control_fd);
1040 }
1041
1042 /* request pty/x11/agent/tcpfwd/shell for channel */
1043 static void
1044 ssh_session2_setup(int id, void *arg)
1045 {
1046         extern char **environ;
1047         const char *display;
1048         int interactive = tty_flag;
1049
1050         display = getenv("DISPLAY");
1051         if (options.forward_x11 && display != NULL) {
1052                 char *proto, *data;
1053                 /* Get reasonable local authentication information. */
1054                 client_x11_get_proto(display, options.xauth_location,
1055                     options.forward_x11_trusted, &proto, &data);
1056                 /* Request forwarding with authentication spoofing. */
1057                 debug("Requesting X11 forwarding with authentication spoofing.");
1058                 x11_request_forwarding_with_spoofing(id, display, proto, data);
1059                 interactive = 1;
1060                 /* XXX wait for reply */
1061         }
1062
1063         check_agent_present();
1064         if (options.forward_agent) {
1065                 debug("Requesting authentication agent forwarding.");
1066                 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1067                 packet_send();
1068         }
1069
1070         if (options.tun_open) {
1071                 Channel *c;
1072                 int fd;
1073
1074                 debug("Requesting tun.");
1075                 if ((fd = tun_open(options.tun_local)) >= 0) {
1076                         c = channel_new("tun", SSH_CHANNEL_OPENING, fd, fd, -1,
1077                             CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1078                             0, "tun", 1);
1079                         c->datagram = 1;
1080                         packet_start(SSH2_MSG_CHANNEL_OPEN);
1081                         packet_put_cstring("tun@openssh.com");
1082                         packet_put_int(c->self);
1083                         packet_put_int(c->local_window_max);
1084                         packet_put_int(c->local_maxpacket);
1085                         packet_put_int(options.tun_remote);
1086                         packet_send();
1087                 }
1088         }
1089
1090         client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1091             NULL, fileno(stdin), &command, environ, &ssh_subsystem_reply);
1092
1093         packet_set_interactive(interactive);
1094 }
1095
1096 /* open new channel for a session */
1097 static int
1098 ssh_session2_open(void)
1099 {
1100         Channel *c;
1101         int window, packetmax, in, out, err;
1102
1103         if (stdin_null_flag) {
1104                 in = open(_PATH_DEVNULL, O_RDONLY);
1105         } else {
1106                 in = dup(STDIN_FILENO);
1107         }
1108         out = dup(STDOUT_FILENO);
1109         err = dup(STDERR_FILENO);
1110
1111         if (in < 0 || out < 0 || err < 0)
1112                 fatal("dup() in/out/err failed");
1113
1114         /* enable nonblocking unless tty */
1115         if (!isatty(in))
1116                 set_nonblock(in);
1117         if (!isatty(out))
1118                 set_nonblock(out);
1119         if (!isatty(err))
1120                 set_nonblock(err);
1121
1122         window = CHAN_SES_WINDOW_DEFAULT;
1123         packetmax = CHAN_SES_PACKET_DEFAULT;
1124         if (tty_flag) {
1125                 window >>= 1;
1126                 packetmax >>= 1;
1127         }
1128         c = channel_new(
1129             "session", SSH_CHANNEL_OPENING, in, out, err,
1130             window, packetmax, CHAN_EXTENDED_WRITE,
1131             "client-session", /*nonblock*/0);
1132
1133         debug3("ssh_session2_open: channel_new: %d", c->self);
1134
1135         channel_send_open(c->self);
1136         if (!no_shell_flag)
1137                 channel_register_confirm(c->self, ssh_session2_setup, NULL);
1138
1139         return c->self;
1140 }
1141
1142 static int
1143 ssh_session2(void)
1144 {
1145         int id = -1;
1146
1147         /* XXX should be pre-session */
1148         ssh_init_forwarding();
1149         ssh_control_listener();
1150
1151         if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1152                 id = ssh_session2_open();
1153
1154         /* Execute a local command */
1155         if (options.local_command != NULL &&
1156             options.permit_local_command)
1157                 ssh_local_cmd(options.local_command);
1158
1159         /* If requested, let ssh continue in the background. */
1160         if (fork_after_authentication_flag)
1161                 if (daemon(1, 1) < 0)
1162                         fatal("daemon() failed: %.200s", strerror(errno));
1163
1164         return client_loop(tty_flag, tty_flag ?
1165             options.escape_char : SSH_ESCAPECHAR_NONE, id);
1166 }
1167
1168 static void
1169 load_public_identity_files(void)
1170 {
1171         char *filename;
1172         int i = 0;
1173         Key *public;
1174 #ifdef SMARTCARD
1175         Key **keys;
1176
1177         if (options.smartcard_device != NULL &&
1178             options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1179             (keys = sc_get_keys(options.smartcard_device, NULL)) != NULL ) {
1180                 int count = 0;
1181                 for (i = 0; keys[i] != NULL; i++) {
1182                         count++;
1183                         memmove(&options.identity_files[1], &options.identity_files[0],
1184                             sizeof(char *) * (SSH_MAX_IDENTITY_FILES - 1));
1185                         memmove(&options.identity_keys[1], &options.identity_keys[0],
1186                             sizeof(Key *) * (SSH_MAX_IDENTITY_FILES - 1));
1187                         options.num_identity_files++;
1188                         options.identity_keys[0] = keys[i];
1189                         options.identity_files[0] = sc_get_key_label(keys[i]);
1190                 }
1191                 if (options.num_identity_files > SSH_MAX_IDENTITY_FILES)
1192                         options.num_identity_files = SSH_MAX_IDENTITY_FILES;
1193                 i = count;
1194                 xfree(keys);
1195         }
1196 #endif /* SMARTCARD */
1197         for (; i < options.num_identity_files; i++) {
1198                 filename = tilde_expand_filename(options.identity_files[i],
1199                     original_real_uid);
1200                 public = key_load_public(filename, NULL);
1201                 debug("identity file %s type %d", filename,
1202                     public ? public->type : -1);
1203                 xfree(options.identity_files[i]);
1204                 options.identity_files[i] = filename;
1205                 options.identity_keys[i] = public;
1206         }
1207 }
1208
1209 static void
1210 control_client_sighandler(int signo)
1211 {
1212         control_client_terminate = signo;
1213 }
1214
1215 static void
1216 control_client_sigrelay(int signo)
1217 {
1218         if (control_server_pid > 1)
1219                 kill(control_server_pid, signo);
1220 }
1221
1222 static int
1223 env_permitted(char *env)
1224 {
1225         int i;
1226         char name[1024], *cp;
1227
1228         strlcpy(name, env, sizeof(name));
1229         if ((cp = strchr(name, '=')) == NULL)
1230                 return (0);
1231
1232         *cp = '\0';
1233
1234         for (i = 0; i < options.num_send_env; i++)
1235                 if (match_pattern(name, options.send_env[i]))
1236                         return (1);
1237
1238         return (0);
1239 }
1240
1241 static void
1242 control_client(const char *path)
1243 {
1244         struct sockaddr_un addr;
1245         int i, r, fd, sock, exitval, num_env, addr_len;
1246         Buffer m;
1247         char *term;
1248         extern char **environ;
1249         u_int  flags;
1250
1251         if (mux_command == 0)
1252                 mux_command = SSHMUX_COMMAND_OPEN;
1253
1254         switch (options.control_master) {
1255         case SSHCTL_MASTER_AUTO:
1256         case SSHCTL_MASTER_AUTO_ASK:
1257                 debug("auto-mux: Trying existing master");
1258                 /* FALLTHROUGH */
1259         case SSHCTL_MASTER_NO:
1260                 break;
1261         default:
1262                 return;
1263         }
1264
1265         memset(&addr, '\0', sizeof(addr));
1266         addr.sun_family = AF_UNIX;
1267         addr_len = offsetof(struct sockaddr_un, sun_path) +
1268             strlen(path) + 1;
1269
1270         if (strlcpy(addr.sun_path, path,
1271             sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1272                 fatal("ControlPath too long");
1273
1274         if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1275                 fatal("%s socket(): %s", __func__, strerror(errno));
1276
1277         if (connect(sock, (struct sockaddr*)&addr, addr_len) == -1) {
1278                 if (mux_command != SSHMUX_COMMAND_OPEN) {
1279                         fatal("Control socket connect(%.100s): %s", path,
1280                             strerror(errno));
1281                 }
1282                 if (errno == ENOENT)
1283                         debug("Control socket \"%.100s\" does not exist", path);
1284                 else {
1285                         error("Control socket connect(%.100s): %s", path,
1286                             strerror(errno));
1287                 }
1288                 close(sock);
1289                 return;
1290         }
1291
1292         if (stdin_null_flag) {
1293                 if ((fd = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1294                         fatal("open(/dev/null): %s", strerror(errno));
1295                 if (dup2(fd, STDIN_FILENO) == -1)
1296                         fatal("dup2: %s", strerror(errno));
1297                 if (fd > STDERR_FILENO)
1298                         close(fd);
1299         }
1300
1301         term = getenv("TERM");
1302
1303         flags = 0;
1304         if (tty_flag)
1305                 flags |= SSHMUX_FLAG_TTY;
1306         if (subsystem_flag)
1307                 flags |= SSHMUX_FLAG_SUBSYS;
1308         if (options.forward_x11)
1309                 flags |= SSHMUX_FLAG_X11_FWD;
1310         if (options.forward_agent)
1311                 flags |= SSHMUX_FLAG_AGENT_FWD;
1312
1313         buffer_init(&m);
1314
1315         /* Send our command to server */
1316         buffer_put_int(&m, mux_command);
1317         buffer_put_int(&m, flags);
1318         if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1319                 fatal("%s: msg_send", __func__);
1320         buffer_clear(&m);
1321
1322         /* Get authorisation status and PID of controlee */
1323         if (ssh_msg_recv(sock, &m) == -1)
1324                 fatal("%s: msg_recv", __func__);
1325         if (buffer_get_char(&m) != SSHMUX_VER)
1326                 fatal("%s: wrong version", __func__);
1327         if (buffer_get_int(&m) != 1)
1328                 fatal("Connection to master denied");
1329         control_server_pid = buffer_get_int(&m);
1330
1331         buffer_clear(&m);
1332
1333         switch (mux_command) {
1334         case SSHMUX_COMMAND_ALIVE_CHECK:
1335                 fprintf(stderr, "Master running (pid=%d)\r\n",
1336                     control_server_pid);
1337                 exit(0);
1338         case SSHMUX_COMMAND_TERMINATE:
1339                 fprintf(stderr, "Exit request sent.\r\n");
1340                 exit(0);
1341         case SSHMUX_COMMAND_OPEN:
1342                 /* continue below */
1343                 break;
1344         default:
1345                 fatal("silly mux_command %d", mux_command);
1346         }
1347
1348         /* SSHMUX_COMMAND_OPEN */
1349         buffer_put_cstring(&m, term ? term : "");
1350         buffer_append(&command, "\0", 1);
1351         buffer_put_cstring(&m, buffer_ptr(&command));
1352
1353         if (options.num_send_env == 0 || environ == NULL) {
1354                 buffer_put_int(&m, 0);
1355         } else {
1356                 /* Pass environment */
1357                 num_env = 0;
1358                 for (i = 0; environ[i] != NULL; i++)
1359                         if (env_permitted(environ[i]))
1360                                 num_env++; /* Count */
1361
1362                 buffer_put_int(&m, num_env);
1363
1364                 for (i = 0; environ[i] != NULL && num_env >= 0; i++)
1365                         if (env_permitted(environ[i])) {
1366                                 num_env--;
1367                                 buffer_put_cstring(&m, environ[i]);
1368                         }
1369         }
1370
1371         if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1372                 fatal("%s: msg_send", __func__);
1373
1374         mm_send_fd(sock, STDIN_FILENO);
1375         mm_send_fd(sock, STDOUT_FILENO);
1376         mm_send_fd(sock, STDERR_FILENO);
1377
1378         /* Wait for reply, so master has a chance to gather ttymodes */
1379         buffer_clear(&m);
1380         if (ssh_msg_recv(sock, &m) == -1)
1381                 fatal("%s: msg_recv", __func__);
1382         if (buffer_get_char(&m) != SSHMUX_VER)
1383                 fatal("%s: wrong version", __func__);
1384         buffer_free(&m);
1385
1386         signal(SIGHUP, control_client_sighandler);
1387         signal(SIGINT, control_client_sighandler);
1388         signal(SIGTERM, control_client_sighandler);
1389         signal(SIGWINCH, control_client_sigrelay);
1390
1391         if (tty_flag)
1392                 enter_raw_mode();
1393
1394         /* Stick around until the controlee closes the client_fd */
1395         exitval = 0;
1396         for (;!control_client_terminate;) {
1397                 r = read(sock, &exitval, sizeof(exitval));
1398                 if (r == 0) {
1399                         debug2("Received EOF from master");
1400                         break;
1401                 }
1402                 if (r > 0)
1403                         debug2("Received exit status from master %d", exitval);
1404                 if (r == -1 && errno != EINTR)
1405                         fatal("%s: read %s", __func__, strerror(errno));
1406         }
1407
1408         if (control_client_terminate)
1409                 debug2("Exiting on signal %d", control_client_terminate);
1410
1411         close(sock);
1412
1413         leave_raw_mode();
1414
1415         if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
1416                 fprintf(stderr, "Connection to master closed.\r\n");
1417
1418         exit(exitval);
1419 }
This page took 0.305183 seconds and 5 git commands to generate.