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