]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - unix/uxplink.c
X forwarding changes:
[PuTTY.git] / unix / uxplink.c
1 /*
2  * PLink - a command-line (stdin/stdout) variant of PuTTY.
3  */
4
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <errno.h>
8 #include <assert.h>
9 #include <stdarg.h>
10 #include <signal.h>
11 #include <unistd.h>
12 #include <fcntl.h>
13 #include <termios.h>
14 #include <pwd.h>
15 #include <sys/ioctl.h>
16
17 #define PUTTY_DO_GLOBALS               /* actually _define_ globals */
18 #include "putty.h"
19 #include "storage.h"
20 #include "tree234.h"
21
22 #define MAX_STDIN_BACKLOG 4096
23
24 void fatalbox(char *p, ...)
25 {
26     va_list ap;
27     fprintf(stderr, "FATAL ERROR: ");
28     va_start(ap, p);
29     vfprintf(stderr, p, ap);
30     va_end(ap);
31     fputc('\n', stderr);
32     cleanup_exit(1);
33 }
34 void modalfatalbox(char *p, ...)
35 {
36     va_list ap;
37     fprintf(stderr, "FATAL ERROR: ");
38     va_start(ap, p);
39     vfprintf(stderr, p, ap);
40     va_end(ap);
41     fputc('\n', stderr);
42     cleanup_exit(1);
43 }
44 void connection_fatal(void *frontend, char *p, ...)
45 {
46     va_list ap;
47     fprintf(stderr, "FATAL ERROR: ");
48     va_start(ap, p);
49     vfprintf(stderr, p, ap);
50     va_end(ap);
51     fputc('\n', stderr);
52     cleanup_exit(1);
53 }
54 void cmdline_error(char *p, ...)
55 {
56     va_list ap;
57     fprintf(stderr, "plink: ");
58     va_start(ap, p);
59     vfprintf(stderr, p, ap);
60     va_end(ap);
61     fputc('\n', stderr);
62     exit(1);
63 }
64
65 struct termios orig_termios;
66
67 static Backend *back;
68 static void *backhandle;
69 static Config cfg;
70
71 /*
72  * Default settings that are specific to pterm.
73  */
74 char *platform_default_s(const char *name)
75 {
76     if (!strcmp(name, "TermType"))
77         return dupstr(getenv("TERM"));
78     if (!strcmp(name, "UserName"))
79         return get_username();
80     return NULL;
81 }
82
83 int platform_default_i(const char *name, int def)
84 {
85     if (!strcmp(name, "TermWidth") ||
86         !strcmp(name, "TermHeight")) {
87         struct winsize size;
88         if (ioctl(0, TIOCGWINSZ, (void *)&size) >= 0)
89             return (!strcmp(name, "TermWidth") ? size.ws_col : size.ws_row);
90     }
91     return def;
92 }
93
94 FontSpec platform_default_fontspec(const char *name)
95 {
96     FontSpec ret;
97     *ret.name = '\0';
98     return ret;
99 }
100
101 Filename platform_default_filename(const char *name)
102 {
103     Filename ret;
104     if (!strcmp(name, "LogFileName"))
105         strcpy(ret.path, "putty.log");
106     else
107         *ret.path = '\0';
108     return ret;
109 }
110
111 char *x_get_default(const char *key)
112 {
113     return NULL;                       /* this is a stub */
114 }
115 int term_ldisc(Terminal *term, int mode)
116 {
117     return FALSE;
118 }
119 void ldisc_update(void *frontend, int echo, int edit)
120 {
121     /* Update stdin read mode to reflect changes in line discipline. */
122     struct termios mode;
123
124     mode = orig_termios;
125
126     if (echo)
127         mode.c_lflag |= ECHO;
128     else
129         mode.c_lflag &= ~ECHO;
130
131     if (edit)
132         mode.c_lflag |= ISIG | ICANON;
133     else
134         mode.c_lflag &= ~(ISIG | ICANON);
135
136     tcsetattr(0, TCSANOW, &mode);
137 }
138
139 void cleanup_termios(void)
140 {
141     tcsetattr(0, TCSANOW, &orig_termios);
142 }
143
144 bufchain stdout_data, stderr_data;
145
146 void try_output(int is_stderr)
147 {
148     bufchain *chain = (is_stderr ? &stderr_data : &stdout_data);
149     int fd = (is_stderr ? 2 : 1);
150     void *senddata;
151     int sendlen, ret;
152
153     if (bufchain_size(chain) == 0)
154         return;
155
156     bufchain_prefix(chain, &senddata, &sendlen);
157     ret = write(fd, senddata, sendlen);
158     if (ret > 0)
159         bufchain_consume(chain, ret);
160     else if (ret < 0) {
161         perror(is_stderr ? "stderr: write" : "stdout: write");
162         exit(1);
163     }
164 }
165
166 int from_backend(void *frontend_handle, int is_stderr,
167                  const char *data, int len)
168 {
169     int osize, esize;
170
171     if (is_stderr) {
172         bufchain_add(&stderr_data, data, len);
173         try_output(1);
174     } else {
175         bufchain_add(&stdout_data, data, len);
176         try_output(0);
177     }
178
179     osize = bufchain_size(&stdout_data);
180     esize = bufchain_size(&stderr_data);
181
182     return osize + esize;
183 }
184
185 int signalpipe[2];
186
187 void sigwinch(int signum)
188 {
189     write(signalpipe[1], "x", 1);
190 }
191
192 /*
193  * In Plink our selects are synchronous, so these functions are
194  * empty stubs.
195  */
196 int uxsel_input_add(int fd, int rwx) { return 0; }
197 void uxsel_input_remove(int id) { }
198
199 /*
200  * Short description of parameters.
201  */
202 static void usage(void)
203 {
204     printf("PuTTY Link: command-line connection utility\n");
205     printf("%s\n", ver);
206     printf("Usage: plink [options] [user@]host [command]\n");
207     printf("       (\"host\" can also be a PuTTY saved session name)\n");
208     printf("Options:\n");
209     printf("  -V        print version information\n");
210     printf("  -v        show verbose messages\n");
211     printf("  -load sessname  Load settings from saved session\n");
212     printf("  -ssh -telnet -rlogin -raw\n");
213     printf("            force use of a particular protocol\n");
214     printf("  -P port   connect to specified port\n");
215     printf("  -l user   connect with specified username\n");
216     printf("  -m file   read remote command(s) from file\n");
217     printf("  -batch    disable all interactive prompts\n");
218     printf("The following options only apply to SSH connections:\n");
219     printf("  -pw passw login with specified password\n");
220     printf("  -D [listen-IP:]listen-port\n");
221     printf("            Dynamic SOCKS-based port forwarding\n");
222     printf("  -L [listen-IP:]listen-port:host:port\n");
223     printf("            Forward local port to remote address\n");
224     printf("  -R [listen-IP:]listen-port:host:port\n");
225     printf("            Forward remote port to local address\n");
226     printf("  -X -x     enable / disable X11 forwarding\n");
227     printf("  -A -a     enable / disable agent forwarding\n");
228     printf("  -t -T     enable / disable pty allocation\n");
229     printf("  -1 -2     force use of particular protocol version\n");
230     printf("  -C        enable compression\n");
231     printf("  -i key    private key file for authentication\n");
232     printf("  -s        remote command is an SSH subsystem (SSH-2 only)\n");
233     exit(1);
234 }
235
236 static void version(void)
237 {
238     printf("plink: %s\n", ver);
239     exit(1);
240 }
241
242 int main(int argc, char **argv)
243 {
244     int sending;
245     int portnumber = -1;
246     int *fdlist;
247     int fd;
248     int i, fdcount, fdsize, fdstate;
249     int connopen;
250     int exitcode;
251     int errors;
252     int use_subsystem = 0;
253     void *ldisc, *logctx;
254
255     ssh_get_line = console_get_line;
256
257     fdlist = NULL;
258     fdcount = fdsize = 0;
259     /*
260      * Initialise port and protocol to sensible defaults. (These
261      * will be overridden by more or less anything.)
262      */
263     default_protocol = PROT_SSH;
264     default_port = 22;
265
266     flags = FLAG_STDERR;
267     /*
268      * Process the command line.
269      */
270     do_defaults(NULL, &cfg);
271     loaded_session = FALSE;
272     default_protocol = cfg.protocol;
273     default_port = cfg.port;
274     errors = 0;
275     {
276         /*
277          * Override the default protocol if PLINK_PROTOCOL is set.
278          */
279         char *p = getenv("PLINK_PROTOCOL");
280         int i;
281         if (p) {
282             for (i = 0; backends[i].backend != NULL; i++) {
283                 if (!strcmp(backends[i].name, p)) {
284                     default_protocol = cfg.protocol = backends[i].protocol;
285                     default_port = cfg.port =
286                         backends[i].backend->default_port;
287                     break;
288                 }
289             }
290         }
291     }
292     while (--argc) {
293         char *p = *++argv;
294         if (*p == '-') {
295             int ret = cmdline_process_param(p, (argc > 1 ? argv[1] : NULL),
296                                             1, &cfg);
297             if (ret == -2) {
298                 fprintf(stderr,
299                         "plink: option \"%s\" requires an argument\n", p);
300                 errors = 1;
301             } else if (ret == 2) {
302                 --argc, ++argv;
303             } else if (ret == 1) {
304                 continue;
305             } else if (!strcmp(p, "-batch")) {
306                 console_batch_mode = 1;
307             } else if (!strcmp(p, "-s")) {
308                 /* Save status to write to cfg later. */
309                 use_subsystem = 1;
310             } else if (!strcmp(p, "-V")) {
311                 version();
312             } else if (!strcmp(p, "-o")) {
313                 if (argc <= 1) {
314                     fprintf(stderr,
315                             "plink: option \"-o\" requires an argument\n");
316                     errors = 1;
317                 } else {
318                     --argc;
319                     provide_xrm_string(*++argv);
320                 }
321             } else {
322                 fprintf(stderr, "plink: unknown option \"%s\"\n", p);
323                 errors = 1;
324             }
325         } else if (*p) {
326             if (!*cfg.host) {
327                 char *q = p;
328
329                 do_defaults(NULL, &cfg);
330
331                 /*
332                  * If the hostname starts with "telnet:", set the
333                  * protocol to Telnet and process the string as a
334                  * Telnet URL.
335                  */
336                 if (!strncmp(q, "telnet:", 7)) {
337                     char c;
338
339                     q += 7;
340                     if (q[0] == '/' && q[1] == '/')
341                         q += 2;
342                     cfg.protocol = PROT_TELNET;
343                     p = q;
344                     while (*p && *p != ':' && *p != '/')
345                         p++;
346                     c = *p;
347                     if (*p)
348                         *p++ = '\0';
349                     if (c == ':')
350                         cfg.port = atoi(p);
351                     else
352                         cfg.port = -1;
353                     strncpy(cfg.host, q, sizeof(cfg.host) - 1);
354                     cfg.host[sizeof(cfg.host) - 1] = '\0';
355                 } else {
356                     char *r, *user, *host;
357                     /*
358                      * Before we process the [user@]host string, we
359                      * first check for the presence of a protocol
360                      * prefix (a protocol name followed by ",").
361                      */
362                     r = strchr(p, ',');
363                     if (r) {
364                         int i, j;
365                         for (i = 0; backends[i].backend != NULL; i++) {
366                             j = strlen(backends[i].name);
367                             if (j == r - p &&
368                                 !memcmp(backends[i].name, p, j)) {
369                                 default_protocol = cfg.protocol =
370                                     backends[i].protocol;
371                                 portnumber =
372                                     backends[i].backend->default_port;
373                                 p = r + 1;
374                                 break;
375                             }
376                         }
377                     }
378
379                     /*
380                      * A nonzero length string followed by an @ is treated
381                      * as a username. (We discount an _initial_ @.) The
382                      * rest of the string (or the whole string if no @)
383                      * is treated as a session name and/or hostname.
384                      */
385                     r = strrchr(p, '@');
386                     if (r == p)
387                         p++, r = NULL; /* discount initial @ */
388                     if (r) {
389                         *r++ = '\0';
390                         user = p, host = r;
391                     } else {
392                         user = NULL, host = p;
393                     }
394
395                     /*
396                      * Now attempt to load a saved session with the
397                      * same name as the hostname.
398                      */
399                     {
400                         Config cfg2;
401                         do_defaults(host, &cfg2);
402                         if (loaded_session || cfg2.host[0] == '\0') {
403                             /* No settings for this host; use defaults */
404                             /* (or session was already loaded with -load) */
405                             strncpy(cfg.host, host, sizeof(cfg.host) - 1);
406                             cfg.host[sizeof(cfg.host) - 1] = '\0';
407                             cfg.port = default_port;
408                         } else {
409                             cfg = cfg2;
410                             /* Ick: patch up internal pointer after copy */
411                             cfg.remote_cmd_ptr = cfg.remote_cmd;
412                         }
413                     }
414
415                     if (user) {
416                         /* Patch in specified username. */
417                         strncpy(cfg.username, user,
418                                 sizeof(cfg.username) - 1);
419                         cfg.username[sizeof(cfg.username) - 1] = '\0';
420                     }
421
422                 }
423             } else {
424                 char *command;
425                 int cmdlen, cmdsize;
426                 cmdlen = cmdsize = 0;
427                 command = NULL;
428
429                 while (argc) {
430                     while (*p) {
431                         if (cmdlen >= cmdsize) {
432                             cmdsize = cmdlen + 512;
433                             command = sresize(command, cmdsize, char);
434                         }
435                         command[cmdlen++]=*p++;
436                     }
437                     if (cmdlen >= cmdsize) {
438                         cmdsize = cmdlen + 512;
439                         command = sresize(command, cmdsize, char);
440                     }
441                     command[cmdlen++]=' '; /* always add trailing space */
442                     if (--argc) p = *++argv;
443                 }
444                 if (cmdlen) command[--cmdlen]='\0';
445                                        /* change trailing blank to NUL */
446                 cfg.remote_cmd_ptr = command;
447                 cfg.remote_cmd_ptr2 = NULL;
448                 cfg.nopty = TRUE;      /* command => no terminal */
449
450                 break;                 /* done with cmdline */
451             }
452         }
453     }
454
455     if (errors)
456         return 1;
457
458     if (!*cfg.host) {
459         usage();
460     }
461
462     /*
463      * Trim leading whitespace off the hostname if it's there.
464      */
465     {
466         int space = strspn(cfg.host, " \t");
467         memmove(cfg.host, cfg.host+space, 1+strlen(cfg.host)-space);
468     }
469
470     /* See if host is of the form user@host */
471     if (cfg.host[0] != '\0') {
472         char *atsign = strrchr(cfg.host, '@');
473         /* Make sure we're not overflowing the user field */
474         if (atsign) {
475             if (atsign - cfg.host < sizeof cfg.username) {
476                 strncpy(cfg.username, cfg.host, atsign - cfg.host);
477                 cfg.username[atsign - cfg.host] = '\0';
478             }
479             memmove(cfg.host, atsign + 1, 1 + strlen(atsign + 1));
480         }
481     }
482
483     /*
484      * Perform command-line overrides on session configuration.
485      */
486     cmdline_run_saved(&cfg);
487
488     /*
489      * Apply subsystem status.
490      */
491     if (use_subsystem)
492         cfg.ssh_subsys = TRUE;
493
494     /*
495      * Trim a colon suffix off the hostname if it's there.
496      */
497     cfg.host[strcspn(cfg.host, ":")] = '\0';
498
499     /*
500      * Remove any remaining whitespace from the hostname.
501      */
502     {
503         int p1 = 0, p2 = 0;
504         while (cfg.host[p2] != '\0') {
505             if (cfg.host[p2] != ' ' && cfg.host[p2] != '\t') {
506                 cfg.host[p1] = cfg.host[p2];
507                 p1++;
508             }
509             p2++;
510         }
511         cfg.host[p1] = '\0';
512     }
513
514     if (!*cfg.remote_cmd_ptr)
515         flags |= FLAG_INTERACTIVE;
516
517     /*
518      * Select protocol. This is farmed out into a table in a
519      * separate file to enable an ssh-free variant.
520      */
521     {
522         int i;
523         back = NULL;
524         for (i = 0; backends[i].backend != NULL; i++)
525             if (backends[i].protocol == cfg.protocol) {
526                 back = backends[i].backend;
527                 break;
528             }
529         if (back == NULL) {
530             fprintf(stderr,
531                     "Internal fault: Unsupported protocol found\n");
532             return 1;
533         }
534     }
535
536     /*
537      * Select port.
538      */
539     if (portnumber != -1)
540         cfg.port = portnumber;
541
542     /*
543      * Set up the pipe we'll use to tell us about SIGWINCH.
544      */
545     if (pipe(signalpipe) < 0) {
546         perror("pipe");
547         exit(1);
548     }
549     putty_signal(SIGWINCH, sigwinch);
550
551     sk_init();
552     uxsel_init();
553
554     /*
555      * Start up the connection.
556      */
557     logctx = log_init(NULL, &cfg);
558     console_provide_logctx(logctx);
559     {
560         const char *error;
561         char *realhost;
562         /* nodelay is only useful if stdin is a terminal device */
563         int nodelay = cfg.tcp_nodelay && isatty(0);
564
565         error = back->init(NULL, &backhandle, &cfg, cfg.host, cfg.port,
566                            &realhost, nodelay, cfg.tcp_keepalives);
567         if (error) {
568             fprintf(stderr, "Unable to open connection:\n%s\n", error);
569             return 1;
570         }
571         back->provide_logctx(backhandle, logctx);
572         ldisc = ldisc_create(&cfg, NULL, back, backhandle, NULL);
573         sfree(realhost);
574     }
575     connopen = 1;
576
577     /*
578      * Set up the initial console mode. We don't care if this call
579      * fails, because we know we aren't necessarily running in a
580      * console.
581      */
582     tcgetattr(0, &orig_termios);
583     atexit(cleanup_termios);
584     ldisc_update(NULL, 1, 1);
585     sending = FALSE;
586
587     while (1) {
588         fd_set rset, wset, xset;
589         int maxfd;
590         int rwx;
591         int ret;
592
593         FD_ZERO(&rset);
594         FD_ZERO(&wset);
595         FD_ZERO(&xset);
596         maxfd = 0;
597
598         FD_SET_MAX(signalpipe[0], maxfd, rset);
599
600         if (connopen && !sending &&
601             back->socket(backhandle) != NULL &&
602             back->sendok(backhandle) &&
603             back->sendbuffer(backhandle) < MAX_STDIN_BACKLOG) {
604             /* If we're OK to send, then try to read from stdin. */
605             FD_SET_MAX(0, maxfd, rset);
606         }
607
608         if (bufchain_size(&stdout_data) > 0) {
609             /* If we have data for stdout, try to write to stdout. */
610             FD_SET_MAX(1, maxfd, wset);
611         }
612
613         if (bufchain_size(&stderr_data) > 0) {
614             /* If we have data for stderr, try to write to stderr. */
615             FD_SET_MAX(2, maxfd, wset);
616         }
617
618         /* Count the currently active fds. */
619         i = 0;
620         for (fd = first_fd(&fdstate, &rwx); fd >= 0;
621              fd = next_fd(&fdstate, &rwx)) i++;
622
623         /* Expand the fdlist buffer if necessary. */
624         if (i > fdsize) {
625             fdsize = i + 16;
626             fdlist = sresize(fdlist, fdsize, int);
627         }
628
629         /*
630          * Add all currently open fds to the select sets, and store
631          * them in fdlist as well.
632          */
633         fdcount = 0;
634         for (fd = first_fd(&fdstate, &rwx); fd >= 0;
635              fd = next_fd(&fdstate, &rwx)) {
636             fdlist[fdcount++] = fd;
637             if (rwx & 1)
638                 FD_SET_MAX(fd, maxfd, rset);
639             if (rwx & 2)
640                 FD_SET_MAX(fd, maxfd, wset);
641             if (rwx & 4)
642                 FD_SET_MAX(fd, maxfd, xset);
643         }
644
645         do {
646             ret = select(maxfd, &rset, &wset, &xset, NULL);
647         } while (ret < 0 && errno == EINTR);
648
649         if (ret < 0) {
650             perror("select");
651             exit(1);
652         }
653
654         for (i = 0; i < fdcount; i++) {
655             fd = fdlist[i];
656             /*
657              * We must process exceptional notifications before
658              * ordinary readability ones, or we may go straight
659              * past the urgent marker.
660              */
661             if (FD_ISSET(fd, &xset))
662                 select_result(fd, 4);
663             if (FD_ISSET(fd, &rset))
664                 select_result(fd, 1);
665             if (FD_ISSET(fd, &wset))
666                 select_result(fd, 2);
667         }
668
669         if (FD_ISSET(signalpipe[0], &rset)) {
670             char c[1];
671             struct winsize size;
672             read(signalpipe[0], c, 1); /* ignore its value; it'll be `x' */
673             if (ioctl(0, TIOCGWINSZ, (void *)&size) >= 0)
674                 back->size(backhandle, size.ws_col, size.ws_row);
675         }
676
677         if (FD_ISSET(0, &rset)) {
678             char buf[4096];
679             int ret;
680
681             if (connopen && back->socket(backhandle) != NULL) {
682                 ret = read(0, buf, sizeof(buf));
683                 if (ret < 0) {
684                     perror("stdin: read");
685                     exit(1);
686                 } else if (ret == 0) {
687                     back->special(backhandle, TS_EOF);
688                     sending = FALSE;   /* send nothing further after this */
689                 } else {
690                     back->send(backhandle, buf, ret);
691                 }
692             }
693         }
694
695         if (FD_ISSET(1, &wset)) {
696             try_output(0);
697         }
698
699         if (FD_ISSET(2, &wset)) {
700             try_output(1);
701         }
702
703         if ((!connopen || back->socket(backhandle) == NULL) &&
704             bufchain_size(&stdout_data) == 0 &&
705             bufchain_size(&stderr_data) == 0)
706             break;                     /* we closed the connection */
707     }
708     exitcode = back->exitcode(backhandle);
709     if (exitcode < 0) {
710         fprintf(stderr, "Remote process exit code unavailable\n");
711         exitcode = 1;                  /* this is an error condition */
712     }
713     cleanup_exit(exitcode);
714     return exitcode;                   /* shouldn't happen, but placates gcc */
715 }