]> asedeno.scripts.mit.edu Git - PuTTY_svn.git/blob - unix/uxplink.c
a62d34eb5596e0b2e18cab7cffda268733e93c57
[PuTTY_svn.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 *fdlist;
277     int fd;
278     int i, fdcount, fdsize, fdstate;
279     int connopen;
280     int exitcode;
281     int errors;
282     void *ldisc;
283
284     ssh_get_line = console_get_line;
285
286     fdlist = NULL;
287     fdcount = fdsize = 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 = sresize(command, cmdsize, char);
450                         }
451                         command[cmdlen++]=*p++;
452                     }
453                     if (cmdlen >= cmdsize) {
454                         cmdsize = cmdlen + 512;
455                         command = sresize(command, cmdsize, char);
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     uxsel_init();
563
564     /*
565      * Start up the connection.
566      */
567     logctx = log_init(NULL, &cfg);
568     {
569         char *error;
570         char *realhost;
571         /* nodelay is only useful if stdin is a terminal device */
572         int nodelay = cfg.tcp_nodelay && isatty(0);
573
574         error = back->init(NULL, &backhandle, &cfg, cfg.host, cfg.port,
575                            &realhost, nodelay);
576         if (error) {
577             fprintf(stderr, "Unable to open connection:\n%s\n", error);
578             return 1;
579         }
580         back->provide_logctx(backhandle, logctx);
581         ldisc = ldisc_create(&cfg, NULL, back, backhandle, NULL);
582         sfree(realhost);
583     }
584     connopen = 1;
585
586     /*
587      * Set up the initial console mode. We don't care if this call
588      * fails, because we know we aren't necessarily running in a
589      * console.
590      */
591     tcgetattr(0, &orig_termios);
592     atexit(cleanup_termios);
593     ldisc_update(NULL, 1, 1);
594     sending = FALSE;
595
596     while (1) {
597         fd_set rset, wset, xset;
598         int maxfd;
599         int rwx;
600         int ret;
601
602         FD_ZERO(&rset);
603         FD_ZERO(&wset);
604         FD_ZERO(&xset);
605         maxfd = 0;
606
607         FD_SET_MAX(signalpipe[0], maxfd, rset);
608
609         if (connopen && !sending &&
610             back->socket(backhandle) != NULL &&
611             back->sendok(backhandle) &&
612             back->sendbuffer(backhandle) < MAX_STDIN_BACKLOG) {
613             /* If we're OK to send, then try to read from stdin. */
614             FD_SET_MAX(0, maxfd, rset);
615         }
616
617         if (bufchain_size(&stdout_data) > 0) {
618             /* If we have data for stdout, try to write to stdout. */
619             FD_SET_MAX(1, maxfd, wset);
620         }
621
622         if (bufchain_size(&stderr_data) > 0) {
623             /* If we have data for stderr, try to write to stderr. */
624             FD_SET_MAX(2, maxfd, wset);
625         }
626
627         /* Count the currently active fds. */
628         i = 0;
629         for (fd = first_fd(&fdstate, &rwx); fd >= 0;
630              fd = next_fd(&fdstate, &rwx)) i++;
631
632         /* Expand the fdlist buffer if necessary. */
633         if (i > fdsize) {
634             fdsize = i + 16;
635             fdlist = sresize(fdlist, fdsize, int);
636         }
637
638         /*
639          * Add all currently open fds to the select sets, and store
640          * them in fdlist as well.
641          */
642         fdcount = 0;
643         for (fd = first_fd(&fdstate, &rwx); fd >= 0;
644              fd = next_fd(&fdstate, &rwx)) {
645             fdlist[fdcount++] = fd;
646             if (rwx & 1)
647                 FD_SET_MAX(fd, maxfd, rset);
648             if (rwx & 2)
649                 FD_SET_MAX(fd, maxfd, wset);
650             if (rwx & 4)
651                 FD_SET_MAX(fd, maxfd, xset);
652         }
653
654         do {
655             ret = select(maxfd, &rset, &wset, &xset, NULL);
656         } while (ret < 0 && errno == EINTR);
657
658         if (ret < 0) {
659             perror("select");
660             exit(1);
661         }
662
663         for (i = 0; i < fdcount; i++) {
664             fd = fdlist[i];
665             /*
666              * We must process exceptional notifications before
667              * ordinary readability ones, or we may go straight
668              * past the urgent marker.
669              */
670             if (FD_ISSET(fd, &xset))
671                 select_result(fd, 4);
672             if (FD_ISSET(fd, &rset))
673                 select_result(fd, 1);
674             if (FD_ISSET(fd, &wset))
675                 select_result(fd, 2);
676         }
677
678         if (FD_ISSET(signalpipe[0], &rset)) {
679             char c[1];
680             struct winsize size;
681             read(signalpipe[0], c, 1); /* ignore its value; it'll be `x' */
682             if (ioctl(0, TIOCGWINSZ, (void *)&size) >= 0)
683                 back->size(backhandle, size.ws_col, size.ws_row);
684         }
685
686         if (FD_ISSET(0, &rset)) {
687             char buf[4096];
688             int ret;
689
690             if (connopen && back->socket(backhandle) != NULL) {
691                 ret = read(0, buf, sizeof(buf));
692                 if (ret < 0) {
693                     perror("stdin: read");
694                     exit(1);
695                 } else if (ret == 0) {
696                     back->special(backhandle, TS_EOF);
697                     sending = FALSE;   /* send nothing further after this */
698                 } else {
699                     back->send(backhandle, buf, ret);
700                 }
701             }
702         }
703
704         if (FD_ISSET(1, &wset)) {
705             try_output(0);
706         }
707
708         if (FD_ISSET(2, &wset)) {
709             try_output(1);
710         }
711
712         if ((!connopen || back->socket(backhandle) == NULL) &&
713             bufchain_size(&stdout_data) == 0 &&
714             bufchain_size(&stderr_data) == 0)
715             break;                     /* we closed the connection */
716     }
717     exitcode = back->exitcode(backhandle);
718     if (exitcode < 0) {
719         fprintf(stderr, "Remote process exit code unavailable\n");
720         exitcode = 1;                  /* this is an error condition */
721     }
722     cleanup_exit(exitcode);
723     return exitcode;                   /* shouldn't happen, but placates gcc */
724 }