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