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