13dea4417141a688b11db2a280b60c912eb7e719
2 * PLink - a command-line (stdin/stdout) variant of PuTTY.
15 #include <sys/ioctl.h>
17 #ifndef HAVE_NO_SYS_SELECT_H
18 #include <sys/select.h>
21 #define PUTTY_DO_GLOBALS /* actually _define_ globals */
26 #define MAX_STDIN_BACKLOG 4096
28 void fatalbox(char *p
, ...)
31 fprintf(stderr
, "FATAL ERROR: ");
33 vfprintf(stderr
, p
, ap
);
38 void modalfatalbox(char *p
, ...)
41 fprintf(stderr
, "FATAL ERROR: ");
43 vfprintf(stderr
, p
, ap
);
48 void connection_fatal(void *frontend
, char *p
, ...)
51 fprintf(stderr
, "FATAL ERROR: ");
53 vfprintf(stderr
, p
, ap
);
58 void cmdline_error(char *p
, ...)
61 fprintf(stderr
, "plink: ");
63 vfprintf(stderr
, p
, ap
);
69 static int local_tty
= 0; /* do we have a local tty? */
70 static struct termios orig_termios
;
73 static void *backhandle
;
77 * Default settings that are specific to pterm.
79 char *platform_default_s(const char *name
)
81 if (!strcmp(name
, "TermType"))
82 return dupstr(getenv("TERM"));
83 if (!strcmp(name
, "UserName"))
84 return get_username();
88 int platform_default_i(const char *name
, int def
)
90 if (!strcmp(name
, "TermWidth") ||
91 !strcmp(name
, "TermHeight")) {
93 if (ioctl(0, TIOCGWINSZ
, (void *)&size
) >= 0)
94 return (!strcmp(name
, "TermWidth") ? size
.ws_col
: size
.ws_row
);
99 FontSpec
platform_default_fontspec(const char *name
)
106 Filename
platform_default_filename(const char *name
)
109 if (!strcmp(name
, "LogFileName"))
110 strcpy(ret
.path
, "putty.log");
116 char *x_get_default(const char *key
)
118 return NULL
; /* this is a stub */
120 int term_ldisc(Terminal
*term
, int mode
)
124 void ldisc_update(void *frontend
, int echo
, int edit
)
126 /* Update stdin read mode to reflect changes in line discipline. */
129 if (!local_tty
) return;
134 mode
.c_lflag
|= ECHO
;
136 mode
.c_lflag
&= ~ECHO
;
139 mode
.c_iflag
|= ICRNL
;
140 mode
.c_lflag
|= ISIG
| ICANON
;
141 mode
.c_oflag
|= OPOST
;
143 mode
.c_iflag
&= ~ICRNL
;
144 mode
.c_lflag
&= ~(ISIG
| ICANON
);
145 mode
.c_oflag
&= ~OPOST
;
146 /* Solaris sets these to unhelpful values */
148 mode
.c_cc
[VTIME
] = 0;
149 /* FIXME: perhaps what we do with IXON/IXOFF should be an
150 * argument to ldisc_update(), to allow implementation of SSH-2
151 * "xon-xoff" and Rlogin's equivalent? */
152 mode
.c_iflag
&= ~IXON
;
153 mode
.c_iflag
&= ~IXOFF
;
156 * Mark parity errors and (more important) BREAK on input. This
157 * is more complex than it need be because POSIX-2001 suggests
158 * that escaping of valid 0xff in the input stream is dependent on
159 * IGNPAR being clear even though marking of BREAK isn't. NetBSD
160 * 2.0 goes one worse and makes it dependent on INPCK too. We
161 * deal with this by forcing these flags into a useful state and
162 * then faking the state in which we found them in from_tty() if
163 * we get passed a parity or framing error.
165 mode
.c_iflag
= (mode
.c_iflag
| INPCK
| PARMRK
) & ~IGNPAR
;
167 tcsetattr(0, TCSANOW
, &mode
);
170 /* Helper function to extract a special character from a termios. */
171 static char *get_ttychar(struct termios
*t
, int index
)
173 cc_t c
= t
->c_cc
[index
];
174 #if defined(_POSIX_VDISABLE)
175 if (c
== _POSIX_VDISABLE
)
176 return dupprintf("");
178 return dupprintf("^<%d>", c
);
181 char *get_ttymode(void *frontend
, const char *mode
)
184 * Propagate appropriate terminal modes from the local terminal,
187 if (!local_tty
) return NULL
;
189 #define GET_CHAR(ourname, uxname) \
191 if (strcmp(mode, ourname) == 0) \
192 return get_ttychar(&orig_termios, uxname); \
194 #define GET_BOOL(ourname, uxname, uxmemb, transform) \
196 if (strcmp(mode, ourname) == 0) { \
197 int b = (orig_termios.uxmemb & uxname) != 0; \
199 return dupprintf("%d", b); \
204 * Modes that want to be the same on all terminal devices involved.
206 /* All the special characters supported by SSH */
208 GET_CHAR("INTR", VINTR
);
211 GET_CHAR("QUIT", VQUIT
);
214 GET_CHAR("ERASE", VERASE
);
217 GET_CHAR("KILL", VKILL
);
220 GET_CHAR("EOF", VEOF
);
223 GET_CHAR("EOL", VEOL
);
226 GET_CHAR("EOL2", VEOL2
);
229 GET_CHAR("START", VSTART
);
232 GET_CHAR("STOP", VSTOP
);
235 GET_CHAR("SUSP", VSUSP
);
238 GET_CHAR("DSUSP", VDSUSP
);
240 #if defined(VREPRINT)
241 GET_CHAR("REPRINT", VREPRINT
);
244 GET_CHAR("WERASE", VWERASE
);
247 GET_CHAR("LNEXT", VLNEXT
);
250 GET_CHAR("FLUSH", VFLUSH
);
253 GET_CHAR("SWTCH", VSWTCH
);
256 GET_CHAR("STATUS", VSTATUS
);
258 #if defined(VDISCARD)
259 GET_CHAR("DISCARD", VDISCARD
);
261 /* Modes that "configure" other major modes. These should probably be
262 * considered as user preferences. */
263 /* Configuration of ICANON */
265 GET_BOOL("ECHOK", ECHOK
, c_lflag
, );
268 GET_BOOL("ECHOKE", ECHOKE
, c_lflag
, );
271 GET_BOOL("ECHOE", ECHOE
, c_lflag
, );
274 GET_BOOL("ECHONL", ECHONL
, c_lflag
, );
277 GET_BOOL("XCASE", XCASE
, c_lflag
, );
279 /* Configuration of ECHO */
281 GET_BOOL("ECHOCTL", ECHOCTL
, c_lflag
, );
283 /* Configuration of IXON/IXOFF */
285 GET_BOOL("IXANY", IXANY
, c_iflag
, );
287 /* Configuration of OPOST */
289 GET_BOOL("OLCUC", OLCUC
, c_oflag
, );
292 GET_BOOL("ONLCR", ONLCR
, c_oflag
, );
295 GET_BOOL("OCRNL", OCRNL
, c_oflag
, );
298 GET_BOOL("ONOCR", ONOCR
, c_oflag
, );
301 GET_BOOL("ONLRET", ONLRET
, c_oflag
, );
305 * Modes that want to be set in only one place, and that we have
309 GET_BOOL("ISIG", ISIG
, c_lflag
, );
312 GET_BOOL("ICANON", ICANON
, c_lflag
, );
315 GET_BOOL("ECHO", ECHO
, c_lflag
, );
318 GET_BOOL("IXON", IXON
, c_iflag
, );
321 GET_BOOL("IXOFF", IXOFF
, c_iflag
, );
324 GET_BOOL("OPOST", OPOST
, c_oflag
, );
328 * We do not propagate the following modes:
329 * - Parity/serial settings, which are a local affair and don't
330 * make sense propagated over SSH's 8-bit byte-stream.
331 * IGNPAR PARMRK INPCK CS7 CS8 PARENB PARODD
332 * - Things that want to be enabled in one place that we don't
337 * - Things I don't know what to do with. (FIXME)
338 * ISTRIP IMAXBEL NOFLSH TOSTOP IEXTEN
345 /* Fall through to here for unrecognised names, or ones that are
346 * unsupported on this platform */
350 void cleanup_termios(void)
353 tcsetattr(0, TCSANOW
, &orig_termios
);
356 bufchain stdout_data
, stderr_data
;
358 void try_output(int is_stderr
)
360 bufchain
*chain
= (is_stderr ?
&stderr_data
: &stdout_data
);
361 int fd
= (is_stderr ?
2 : 1);
365 if (bufchain_size(chain
) == 0)
368 bufchain_prefix(chain
, &senddata
, &sendlen
);
369 ret
= write(fd
, senddata
, sendlen
);
371 bufchain_consume(chain
, ret
);
373 perror(is_stderr ?
"stderr: write" : "stdout: write");
378 int from_backend(void *frontend_handle
, int is_stderr
,
379 const char *data
, int len
)
384 bufchain_add(&stderr_data
, data
, len
);
387 bufchain_add(&stdout_data
, data
, len
);
391 osize
= bufchain_size(&stdout_data
);
392 esize
= bufchain_size(&stderr_data
);
394 return osize
+ esize
;
398 * Handle data from a local tty in PARMRK format.
400 static void from_tty(void *buf
, unsigned len
)
403 static enum {NORMAL
, FF
, FF00
} state
= NORMAL
;
405 p
= buf
; end
= buf
+ len
;
413 q
= memchr(p
, '\xff', end
- p
);
414 if (q
== NULL
) q
= end
;
415 back
->send(backhandle
, p
, q
- p
);
421 back
->send(backhandle
, p
, 1);
424 } else if (*p
== '\0') {
431 back
->special(backhandle
, TS_BRK
);
434 * Pretend that PARMRK wasn't set. This involves
435 * faking what INPCK and IGNPAR would have done if
436 * we hadn't overridden them. Unfortunately, we
437 * can't do this entirely correctly because INPCK
438 * distinguishes between framing and parity
439 * errors, but PARMRK format represents both in
440 * the same way. We assume that parity errors are
441 * more common than framing errors, and hence
442 * treat all input errors as being subject to
445 if (orig_termios
.c_iflag
& INPCK
) {
446 /* If IGNPAR is set, we throw away the character. */
447 if (!(orig_termios
.c_iflag
& IGNPAR
)) {
448 /* PE/FE get passed on as NUL. */
450 back
->send(backhandle
, p
, 1);
453 /* INPCK not set. Assume we got a parity error. */
454 back
->send(backhandle
, p
, 1);
465 void sigwinch(int signum
)
467 write(signalpipe
[1], "x", 1);
471 * In Plink our selects are synchronous, so these functions are
474 int uxsel_input_add(int fd
, int rwx
) { return 0; }
475 void uxsel_input_remove(int id
) { }
478 * Short description of parameters.
480 static void usage(void)
482 printf("PuTTY Link: command-line connection utility\n");
484 printf("Usage: plink [options] [user@]host [command]\n");
485 printf(" (\"host\" can also be a PuTTY saved session name)\n");
486 printf("Options:\n");
487 printf(" -V print version information and exit\n");
488 printf(" -pgpfp print PGP key fingerprints and exit\n");
489 printf(" -v show verbose messages\n");
490 printf(" -load sessname Load settings from saved session\n");
491 printf(" -ssh -telnet -rlogin -raw\n");
492 printf(" force use of a particular protocol\n");
493 printf(" -P port connect to specified port\n");
494 printf(" -l user connect with specified username\n");
495 printf(" -batch disable all interactive prompts\n");
496 printf("The following options only apply to SSH connections:\n");
497 printf(" -pw passw login with specified password\n");
498 printf(" -D [listen-IP:]listen-port\n");
499 printf(" Dynamic SOCKS-based port forwarding\n");
500 printf(" -L [listen-IP:]listen-port:host:port\n");
501 printf(" Forward local port to remote address\n");
502 printf(" -R [listen-IP:]listen-port:host:port\n");
503 printf(" Forward remote port to local address\n");
504 printf(" -X -x enable / disable X11 forwarding\n");
505 printf(" -A -a enable / disable agent forwarding\n");
506 printf(" -t -T enable / disable pty allocation\n");
507 printf(" -1 -2 force use of particular protocol version\n");
508 printf(" -4 -6 force use of IPv4 or IPv6\n");
509 printf(" -C enable compression\n");
510 printf(" -i key private key file for authentication\n");
511 printf(" -m file read remote command(s) from file\n");
512 printf(" -s remote command is an SSH subsystem (SSH-2 only)\n");
513 printf(" -N don't start a shell/command (SSH-2 only)\n");
517 static void version(void)
519 printf("plink: %s\n", ver
);
523 int main(int argc
, char **argv
)
529 int i
, fdcount
, fdsize
, fdstate
;
533 int use_subsystem
= 0;
534 void *ldisc
, *logctx
;
537 ssh_get_line
= console_get_line
;
540 fdcount
= fdsize
= 0;
542 * Initialise port and protocol to sensible defaults. (These
543 * will be overridden by more or less anything.)
545 default_protocol
= PROT_SSH
;
550 * Process the command line.
552 do_defaults(NULL
, &cfg
);
553 loaded_session
= FALSE
;
554 default_protocol
= cfg
.protocol
;
555 default_port
= cfg
.port
;
559 * Override the default protocol if PLINK_PROTOCOL is set.
561 char *p
= getenv("PLINK_PROTOCOL");
564 for (i
= 0; backends
[i
].backend
!= NULL
; i
++) {
565 if (!strcmp(backends
[i
].name
, p
)) {
566 default_protocol
= cfg
.protocol
= backends
[i
].protocol
;
567 default_port
= cfg
.port
=
568 backends
[i
].backend
->default_port
;
577 int ret
= cmdline_process_param(p
, (argc
> 1 ? argv
[1] : NULL
),
581 "plink: option \"%s\" requires an argument\n", p
);
583 } else if (ret
== 2) {
585 } else if (ret
== 1) {
587 } else if (!strcmp(p
, "-batch")) {
588 console_batch_mode
= 1;
589 } else if (!strcmp(p
, "-s")) {
590 /* Save status to write to cfg later. */
592 } else if (!strcmp(p
, "-V")) {
594 } else if (!strcmp(p
, "-pgpfp")) {
597 } else if (!strcmp(p
, "-o")) {
600 "plink: option \"-o\" requires an argument\n");
604 provide_xrm_string(*++argv
);
607 fprintf(stderr
, "plink: unknown option \"%s\"\n", p
);
614 do_defaults(NULL
, &cfg
);
617 * If the hostname starts with "telnet:", set the
618 * protocol to Telnet and process the string as a
621 if (!strncmp(q
, "telnet:", 7)) {
625 if (q
[0] == '/' && q
[1] == '/')
627 cfg
.protocol
= PROT_TELNET
;
629 while (*p
&& *p
!= ':' && *p
!= '/')
638 strncpy(cfg
.host
, q
, sizeof(cfg
.host
) - 1);
639 cfg
.host
[sizeof(cfg
.host
) - 1] = '\0';
641 char *r
, *user
, *host
;
643 * Before we process the [user@]host string, we
644 * first check for the presence of a protocol
645 * prefix (a protocol name followed by ",").
650 for (i
= 0; backends
[i
].backend
!= NULL
; i
++) {
651 j
= strlen(backends
[i
].name
);
653 !memcmp(backends
[i
].name
, p
, j
)) {
654 default_protocol
= cfg
.protocol
=
655 backends
[i
].protocol
;
657 backends
[i
].backend
->default_port
;
665 * A nonzero length string followed by an @ is treated
666 * as a username. (We discount an _initial_ @.) The
667 * rest of the string (or the whole string if no @)
668 * is treated as a session name and/or hostname.
672 p
++, r
= NULL
; /* discount initial @ */
677 user
= NULL
, host
= p
;
681 * Now attempt to load a saved session with the
682 * same name as the hostname.
686 do_defaults(host
, &cfg2
);
687 if (loaded_session
|| cfg2
.host
[0] == '\0') {
688 /* No settings for this host; use defaults */
689 /* (or session was already loaded with -load) */
690 strncpy(cfg
.host
, host
, sizeof(cfg
.host
) - 1);
691 cfg
.host
[sizeof(cfg
.host
) - 1] = '\0';
692 cfg
.port
= default_port
;
699 /* Patch in specified username. */
700 strncpy(cfg
.username
, user
,
701 sizeof(cfg
.username
) - 1);
702 cfg
.username
[sizeof(cfg
.username
) - 1] = '\0';
709 cmdlen
= cmdsize
= 0;
714 if (cmdlen
>= cmdsize
) {
715 cmdsize
= cmdlen
+ 512;
716 command
= sresize(command
, cmdsize
, char);
718 command
[cmdlen
++]=*p
++;
720 if (cmdlen
>= cmdsize
) {
721 cmdsize
= cmdlen
+ 512;
722 command
= sresize(command
, cmdsize
, char);
724 command
[cmdlen
++]=' '; /* always add trailing space */
725 if (--argc
) p
= *++argv
;
727 if (cmdlen
) command
[--cmdlen
]='\0';
728 /* change trailing blank to NUL */
729 cfg
.remote_cmd_ptr
= command
;
730 cfg
.remote_cmd_ptr2
= NULL
;
731 cfg
.nopty
= TRUE
; /* command => no terminal */
733 break; /* done with cmdline */
746 * Trim leading whitespace off the hostname if it's there.
749 int space
= strspn(cfg
.host
, " \t");
750 memmove(cfg
.host
, cfg
.host
+space
, 1+strlen(cfg
.host
)-space
);
753 /* See if host is of the form user@host */
754 if (cfg
.host
[0] != '\0') {
755 char *atsign
= strrchr(cfg
.host
, '@');
756 /* Make sure we're not overflowing the user field */
758 if (atsign
- cfg
.host
< sizeof cfg
.username
) {
759 strncpy(cfg
.username
, cfg
.host
, atsign
- cfg
.host
);
760 cfg
.username
[atsign
- cfg
.host
] = '\0';
762 memmove(cfg
.host
, atsign
+ 1, 1 + strlen(atsign
+ 1));
767 * Perform command-line overrides on session configuration.
769 cmdline_run_saved(&cfg
);
772 * Apply subsystem status.
775 cfg
.ssh_subsys
= TRUE
;
778 * Trim a colon suffix off the hostname if it's there.
780 cfg
.host
[strcspn(cfg
.host
, ":")] = '\0';
783 * Remove any remaining whitespace from the hostname.
787 while (cfg
.host
[p2
] != '\0') {
788 if (cfg
.host
[p2
] != ' ' && cfg
.host
[p2
] != '\t') {
789 cfg
.host
[p1
] = cfg
.host
[p2
];
797 if (!cfg
.remote_cmd_ptr
&& !*cfg
.remote_cmd
)
798 flags
|= FLAG_INTERACTIVE
;
801 * Select protocol. This is farmed out into a table in a
802 * separate file to enable an ssh-free variant.
807 for (i
= 0; backends
[i
].backend
!= NULL
; i
++)
808 if (backends
[i
].protocol
== cfg
.protocol
) {
809 back
= backends
[i
].backend
;
814 "Internal fault: Unsupported protocol found\n");
822 if (portnumber
!= -1)
823 cfg
.port
= portnumber
;
826 * Set up the pipe we'll use to tell us about SIGWINCH.
828 if (pipe(signalpipe
) < 0) {
832 putty_signal(SIGWINCH
, sigwinch
);
838 * Start up the connection.
840 logctx
= log_init(NULL
, &cfg
);
841 console_provide_logctx(logctx
);
845 /* nodelay is only useful if stdin is a terminal device */
846 int nodelay
= cfg
.tcp_nodelay
&& isatty(0);
848 error
= back
->init(NULL
, &backhandle
, &cfg
, cfg
.host
, cfg
.port
,
849 &realhost
, nodelay
, cfg
.tcp_keepalives
);
851 fprintf(stderr
, "Unable to open connection:\n%s\n", error
);
854 back
->provide_logctx(backhandle
, logctx
);
855 ldisc
= ldisc_create(&cfg
, NULL
, back
, backhandle
, NULL
);
861 * Set up the initial console mode. We don't care if this call
862 * fails, because we know we aren't necessarily running in a
865 local_tty
= (tcgetattr(0, &orig_termios
) == 0);
866 atexit(cleanup_termios
);
867 ldisc_update(NULL
, 1, 1);
869 now
= GETTICKCOUNT();
872 fd_set rset
, wset
, xset
;
882 FD_SET_MAX(signalpipe
[0], maxfd
, rset
);
884 if (connopen
&& !sending
&&
885 back
->socket(backhandle
) != NULL
&&
886 back
->sendok(backhandle
) &&
887 back
->sendbuffer(backhandle
) < MAX_STDIN_BACKLOG
) {
888 /* If we're OK to send, then try to read from stdin. */
889 FD_SET_MAX(0, maxfd
, rset
);
892 if (bufchain_size(&stdout_data
) > 0) {
893 /* If we have data for stdout, try to write to stdout. */
894 FD_SET_MAX(1, maxfd
, wset
);
897 if (bufchain_size(&stderr_data
) > 0) {
898 /* If we have data for stderr, try to write to stderr. */
899 FD_SET_MAX(2, maxfd
, wset
);
902 /* Count the currently active fds. */
904 for (fd
= first_fd(&fdstate
, &rwx
); fd
>= 0;
905 fd
= next_fd(&fdstate
, &rwx
)) i
++;
907 /* Expand the fdlist buffer if necessary. */
910 fdlist
= sresize(fdlist
, fdsize
, int);
914 * Add all currently open fds to the select sets, and store
915 * them in fdlist as well.
918 for (fd
= first_fd(&fdstate
, &rwx
); fd
>= 0;
919 fd
= next_fd(&fdstate
, &rwx
)) {
920 fdlist
[fdcount
++] = fd
;
922 FD_SET_MAX(fd
, maxfd
, rset
);
924 FD_SET_MAX(fd
, maxfd
, wset
);
926 FD_SET_MAX(fd
, maxfd
, xset
);
931 struct timeval tv
, *ptv
;
933 if (run_timers(now
, &next
)) {
934 ticks
= next
- GETTICKCOUNT();
935 if (ticks
< 0) ticks
= 0; /* just in case */
936 tv
.tv_sec
= ticks
/ 1000;
937 tv
.tv_usec
= ticks
% 1000 * 1000;
942 ret
= select(maxfd
, &rset
, &wset
, &xset
, ptv
);
946 long newnow
= GETTICKCOUNT();
948 * Check to see whether the system clock has
949 * changed massively during the select.
951 if (newnow
- now
< 0 || newnow
- now
> next
- now
) {
953 * If so, look at the elapsed time in the
954 * select and use it to compute a new
957 long othernow
= now
+ tv
.tv_sec
* 1000 + tv
.tv_usec
/ 1000;
958 /* So we'd like GETTICKCOUNT to have returned othernow,
959 * but instead it return newnow. Hence ... */
960 tickcount_offset
+= othernow
- newnow
;
966 } while (ret
< 0 && errno
== EINTR
);
973 for (i
= 0; i
< fdcount
; i
++) {
976 * We must process exceptional notifications before
977 * ordinary readability ones, or we may go straight
978 * past the urgent marker.
980 if (FD_ISSET(fd
, &xset
))
981 select_result(fd
, 4);
982 if (FD_ISSET(fd
, &rset
))
983 select_result(fd
, 1);
984 if (FD_ISSET(fd
, &wset
))
985 select_result(fd
, 2);
988 if (FD_ISSET(signalpipe
[0], &rset
)) {
991 read(signalpipe
[0], c
, 1); /* ignore its value; it'll be `x' */
992 if (ioctl(0, TIOCGWINSZ
, (void *)&size
) >= 0)
993 back
->size(backhandle
, size
.ws_col
, size
.ws_row
);
996 if (FD_ISSET(0, &rset
)) {
1000 if (connopen
&& back
->socket(backhandle
) != NULL
) {
1001 ret
= read(0, buf
, sizeof(buf
));
1003 perror("stdin: read");
1005 } else if (ret
== 0) {
1006 back
->special(backhandle
, TS_EOF
);
1007 sending
= FALSE
; /* send nothing further after this */
1012 back
->send(backhandle
, buf
, ret
);
1017 if (FD_ISSET(1, &wset
)) {
1021 if (FD_ISSET(2, &wset
)) {
1025 if ((!connopen
|| back
->socket(backhandle
) == NULL
) &&
1026 bufchain_size(&stdout_data
) == 0 &&
1027 bufchain_size(&stderr_data
) == 0)
1028 break; /* we closed the connection */
1030 exitcode
= back
->exitcode(backhandle
);
1032 fprintf(stderr
, "Remote process exit code unavailable\n");
1033 exitcode
= 1; /* this is an error condition */
1035 cleanup_exit(exitcode
);
1036 return exitcode
; /* shouldn't happen, but placates gcc */