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