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