c0261578eb2b7e1727305adfe724a8c5fafc8fc5
2 * PLink - a command-line (stdin/stdout) variant of PuTTY.
15 #include <sys/ioctl.h>
16 #include <sys/select.h>
18 #define PUTTY_DO_GLOBALS /* actually _define_ globals */
23 #define MAX_STDIN_BACKLOG 4096
25 void fatalbox(char *p
, ...)
28 fprintf(stderr
, "FATAL ERROR: ");
30 vfprintf(stderr
, p
, ap
);
35 void modalfatalbox(char *p
, ...)
38 fprintf(stderr
, "FATAL ERROR: ");
40 vfprintf(stderr
, p
, ap
);
45 void connection_fatal(void *frontend
, char *p
, ...)
48 fprintf(stderr
, "FATAL ERROR: ");
50 vfprintf(stderr
, p
, ap
);
55 void cmdline_error(char *p
, ...)
58 fprintf(stderr
, "plink: ");
60 vfprintf(stderr
, p
, ap
);
66 struct termios orig_termios
;
69 static void *backhandle
;
73 * Default settings that are specific to pterm.
75 char *platform_default_s(const char *name
)
77 if (!strcmp(name
, "TermType"))
78 return dupstr(getenv("TERM"));
79 if (!strcmp(name
, "UserName"))
80 return get_username();
84 int platform_default_i(const char *name
, int def
)
86 if (!strcmp(name
, "TermWidth") ||
87 !strcmp(name
, "TermHeight")) {
89 if (ioctl(0, TIOCGWINSZ
, (void *)&size
) >= 0)
90 return (!strcmp(name
, "TermWidth") ? size
.ws_col
: size
.ws_row
);
95 FontSpec
platform_default_fontspec(const char *name
)
102 Filename
platform_default_filename(const char *name
)
105 if (!strcmp(name
, "LogFileName"))
106 strcpy(ret
.path
, "putty.log");
112 char *x_get_default(const char *key
)
114 return NULL
; /* this is a stub */
116 int term_ldisc(Terminal
*term
, int mode
)
120 void ldisc_update(void *frontend
, int echo
, int edit
)
122 /* Update stdin read mode to reflect changes in line discipline. */
128 mode
.c_lflag
|= ECHO
;
130 mode
.c_lflag
&= ~ECHO
;
133 mode
.c_iflag
|= ICRNL
;
134 mode
.c_lflag
|= ISIG
| ICANON
;
136 mode
.c_iflag
&= ~ICRNL
;
137 mode
.c_lflag
&= ~(ISIG
| ICANON
);
139 mode
.c_cc
[VTIME
] = 0;
142 tcsetattr(0, TCSANOW
, &mode
);
145 void cleanup_termios(void)
147 tcsetattr(0, TCSANOW
, &orig_termios
);
150 bufchain stdout_data
, stderr_data
;
152 void try_output(int is_stderr
)
154 bufchain
*chain
= (is_stderr ?
&stderr_data
: &stdout_data
);
155 int fd
= (is_stderr ?
2 : 1);
159 if (bufchain_size(chain
) == 0)
162 bufchain_prefix(chain
, &senddata
, &sendlen
);
163 ret
= write(fd
, senddata
, sendlen
);
165 bufchain_consume(chain
, ret
);
167 perror(is_stderr ?
"stderr: write" : "stdout: write");
172 int from_backend(void *frontend_handle
, int is_stderr
,
173 const char *data
, int len
)
178 bufchain_add(&stderr_data
, data
, len
);
181 bufchain_add(&stdout_data
, data
, len
);
185 osize
= bufchain_size(&stdout_data
);
186 esize
= bufchain_size(&stderr_data
);
188 return osize
+ esize
;
193 void sigwinch(int signum
)
195 write(signalpipe
[1], "x", 1);
199 * In Plink our selects are synchronous, so these functions are
202 int uxsel_input_add(int fd
, int rwx
) { return 0; }
203 void uxsel_input_remove(int id
) { }
206 * Short description of parameters.
208 static void usage(void)
210 printf("PuTTY Link: command-line connection utility\n");
212 printf("Usage: plink [options] [user@]host [command]\n");
213 printf(" (\"host\" can also be a PuTTY saved session name)\n");
214 printf("Options:\n");
215 printf(" -V print version information and exit\n");
216 printf(" -pgpfp print PGP key fingerprints and exit\n");
217 printf(" -v show verbose messages\n");
218 printf(" -load sessname Load settings from saved session\n");
219 printf(" -ssh -telnet -rlogin -raw\n");
220 printf(" force use of a particular protocol\n");
221 printf(" -P port connect to specified port\n");
222 printf(" -l user connect with specified username\n");
223 printf(" -batch disable all interactive prompts\n");
224 printf("The following options only apply to SSH connections:\n");
225 printf(" -pw passw login with specified password\n");
226 printf(" -D [listen-IP:]listen-port\n");
227 printf(" Dynamic SOCKS-based port forwarding\n");
228 printf(" -L [listen-IP:]listen-port:host:port\n");
229 printf(" Forward local port to remote address\n");
230 printf(" -R [listen-IP:]listen-port:host:port\n");
231 printf(" Forward remote port to local address\n");
232 printf(" -X -x enable / disable X11 forwarding\n");
233 printf(" -A -a enable / disable agent forwarding\n");
234 printf(" -t -T enable / disable pty allocation\n");
235 printf(" -1 -2 force use of particular protocol version\n");
236 printf(" -4 -6 force use of IPv4 or IPv6\n");
237 printf(" -C enable compression\n");
238 printf(" -i key private key file for authentication\n");
239 printf(" -m file read remote command(s) from file\n");
240 printf(" -s remote command is an SSH subsystem (SSH-2 only)\n");
241 printf(" -N don't start a shell/command (SSH-2 only)\n");
245 static void version(void)
247 printf("plink: %s\n", ver
);
251 int main(int argc
, char **argv
)
257 int i
, fdcount
, fdsize
, fdstate
;
261 int use_subsystem
= 0;
262 void *ldisc
, *logctx
;
265 ssh_get_line
= console_get_line
;
268 fdcount
= fdsize
= 0;
270 * Initialise port and protocol to sensible defaults. (These
271 * will be overridden by more or less anything.)
273 default_protocol
= PROT_SSH
;
278 * Process the command line.
280 do_defaults(NULL
, &cfg
);
281 loaded_session
= FALSE
;
282 default_protocol
= cfg
.protocol
;
283 default_port
= cfg
.port
;
287 * Override the default protocol if PLINK_PROTOCOL is set.
289 char *p
= getenv("PLINK_PROTOCOL");
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
;
305 int ret
= cmdline_process_param(p
, (argc
> 1 ? argv
[1] : NULL
),
309 "plink: option \"%s\" requires an argument\n", p
);
311 } else if (ret
== 2) {
313 } else if (ret
== 1) {
315 } else if (!strcmp(p
, "-batch")) {
316 console_batch_mode
= 1;
317 } else if (!strcmp(p
, "-s")) {
318 /* Save status to write to cfg later. */
320 } else if (!strcmp(p
, "-V")) {
322 } else if (!strcmp(p
, "-pgpfp")) {
325 } else if (!strcmp(p
, "-o")) {
328 "plink: option \"-o\" requires an argument\n");
332 provide_xrm_string(*++argv
);
335 fprintf(stderr
, "plink: unknown option \"%s\"\n", p
);
342 do_defaults(NULL
, &cfg
);
345 * If the hostname starts with "telnet:", set the
346 * protocol to Telnet and process the string as a
349 if (!strncmp(q
, "telnet:", 7)) {
353 if (q
[0] == '/' && q
[1] == '/')
355 cfg
.protocol
= PROT_TELNET
;
357 while (*p
&& *p
!= ':' && *p
!= '/')
366 strncpy(cfg
.host
, q
, sizeof(cfg
.host
) - 1);
367 cfg
.host
[sizeof(cfg
.host
) - 1] = '\0';
369 char *r
, *user
, *host
;
371 * Before we process the [user@]host string, we
372 * first check for the presence of a protocol
373 * prefix (a protocol name followed by ",").
378 for (i
= 0; backends
[i
].backend
!= NULL
; i
++) {
379 j
= strlen(backends
[i
].name
);
381 !memcmp(backends
[i
].name
, p
, j
)) {
382 default_protocol
= cfg
.protocol
=
383 backends
[i
].protocol
;
385 backends
[i
].backend
->default_port
;
393 * A nonzero length string followed by an @ is treated
394 * as a username. (We discount an _initial_ @.) The
395 * rest of the string (or the whole string if no @)
396 * is treated as a session name and/or hostname.
400 p
++, r
= NULL
; /* discount initial @ */
405 user
= NULL
, host
= p
;
409 * Now attempt to load a saved session with the
410 * same name as the hostname.
414 do_defaults(host
, &cfg2
);
415 if (loaded_session
|| cfg2
.host
[0] == '\0') {
416 /* No settings for this host; use defaults */
417 /* (or session was already loaded with -load) */
418 strncpy(cfg
.host
, host
, sizeof(cfg
.host
) - 1);
419 cfg
.host
[sizeof(cfg
.host
) - 1] = '\0';
420 cfg
.port
= default_port
;
427 /* Patch in specified username. */
428 strncpy(cfg
.username
, user
,
429 sizeof(cfg
.username
) - 1);
430 cfg
.username
[sizeof(cfg
.username
) - 1] = '\0';
437 cmdlen
= cmdsize
= 0;
442 if (cmdlen
>= cmdsize
) {
443 cmdsize
= cmdlen
+ 512;
444 command
= sresize(command
, cmdsize
, char);
446 command
[cmdlen
++]=*p
++;
448 if (cmdlen
>= cmdsize
) {
449 cmdsize
= cmdlen
+ 512;
450 command
= sresize(command
, cmdsize
, char);
452 command
[cmdlen
++]=' '; /* always add trailing space */
453 if (--argc
) p
= *++argv
;
455 if (cmdlen
) command
[--cmdlen
]='\0';
456 /* change trailing blank to NUL */
457 cfg
.remote_cmd_ptr
= command
;
458 cfg
.remote_cmd_ptr2
= NULL
;
459 cfg
.nopty
= TRUE
; /* command => no terminal */
461 break; /* done with cmdline */
474 * Trim leading whitespace off the hostname if it's there.
477 int space
= strspn(cfg
.host
, " \t");
478 memmove(cfg
.host
, cfg
.host
+space
, 1+strlen(cfg
.host
)-space
);
481 /* See if host is of the form user@host */
482 if (cfg
.host
[0] != '\0') {
483 char *atsign
= strrchr(cfg
.host
, '@');
484 /* Make sure we're not overflowing the user field */
486 if (atsign
- cfg
.host
< sizeof cfg
.username
) {
487 strncpy(cfg
.username
, cfg
.host
, atsign
- cfg
.host
);
488 cfg
.username
[atsign
- cfg
.host
] = '\0';
490 memmove(cfg
.host
, atsign
+ 1, 1 + strlen(atsign
+ 1));
495 * Perform command-line overrides on session configuration.
497 cmdline_run_saved(&cfg
);
500 * Apply subsystem status.
503 cfg
.ssh_subsys
= TRUE
;
506 * Trim a colon suffix off the hostname if it's there.
508 cfg
.host
[strcspn(cfg
.host
, ":")] = '\0';
511 * Remove any remaining whitespace from the hostname.
515 while (cfg
.host
[p2
] != '\0') {
516 if (cfg
.host
[p2
] != ' ' && cfg
.host
[p2
] != '\t') {
517 cfg
.host
[p1
] = cfg
.host
[p2
];
525 if (!cfg
.remote_cmd_ptr
&& !*cfg
.remote_cmd
)
526 flags
|= FLAG_INTERACTIVE
;
529 * Select protocol. This is farmed out into a table in a
530 * separate file to enable an ssh-free variant.
535 for (i
= 0; backends
[i
].backend
!= NULL
; i
++)
536 if (backends
[i
].protocol
== cfg
.protocol
) {
537 back
= backends
[i
].backend
;
542 "Internal fault: Unsupported protocol found\n");
550 if (portnumber
!= -1)
551 cfg
.port
= portnumber
;
554 * Set up the pipe we'll use to tell us about SIGWINCH.
556 if (pipe(signalpipe
) < 0) {
560 putty_signal(SIGWINCH
, sigwinch
);
566 * Start up the connection.
568 logctx
= log_init(NULL
, &cfg
);
569 console_provide_logctx(logctx
);
573 /* nodelay is only useful if stdin is a terminal device */
574 int nodelay
= cfg
.tcp_nodelay
&& isatty(0);
576 error
= back
->init(NULL
, &backhandle
, &cfg
, cfg
.host
, cfg
.port
,
577 &realhost
, nodelay
, cfg
.tcp_keepalives
);
579 fprintf(stderr
, "Unable to open connection:\n%s\n", error
);
582 back
->provide_logctx(backhandle
, logctx
);
583 ldisc
= ldisc_create(&cfg
, NULL
, back
, backhandle
, NULL
);
589 * Set up the initial console mode. We don't care if this call
590 * fails, because we know we aren't necessarily running in a
593 tcgetattr(0, &orig_termios
);
594 atexit(cleanup_termios
);
595 ldisc_update(NULL
, 1, 1);
597 now
= GETTICKCOUNT();
600 fd_set rset
, wset
, xset
;
610 FD_SET_MAX(signalpipe
[0], maxfd
, rset
);
612 if (connopen
&& !sending
&&
613 back
->socket(backhandle
) != NULL
&&
614 back
->sendok(backhandle
) &&
615 back
->sendbuffer(backhandle
) < MAX_STDIN_BACKLOG
) {
616 /* If we're OK to send, then try to read from stdin. */
617 FD_SET_MAX(0, maxfd
, rset
);
620 if (bufchain_size(&stdout_data
) > 0) {
621 /* If we have data for stdout, try to write to stdout. */
622 FD_SET_MAX(1, maxfd
, wset
);
625 if (bufchain_size(&stderr_data
) > 0) {
626 /* If we have data for stderr, try to write to stderr. */
627 FD_SET_MAX(2, maxfd
, wset
);
630 /* Count the currently active fds. */
632 for (fd
= first_fd(&fdstate
, &rwx
); fd
>= 0;
633 fd
= next_fd(&fdstate
, &rwx
)) i
++;
635 /* Expand the fdlist buffer if necessary. */
638 fdlist
= sresize(fdlist
, fdsize
, int);
642 * Add all currently open fds to the select sets, and store
643 * them in fdlist as well.
646 for (fd
= first_fd(&fdstate
, &rwx
); fd
>= 0;
647 fd
= next_fd(&fdstate
, &rwx
)) {
648 fdlist
[fdcount
++] = fd
;
650 FD_SET_MAX(fd
, maxfd
, rset
);
652 FD_SET_MAX(fd
, maxfd
, wset
);
654 FD_SET_MAX(fd
, maxfd
, xset
);
659 struct timeval tv
, *ptv
;
661 if (run_timers(now
, &next
)) {
662 ticks
= next
- GETTICKCOUNT();
663 if (ticks
< 0) ticks
= 0; /* just in case */
664 tv
.tv_sec
= ticks
/ 1000;
665 tv
.tv_usec
= ticks
% 1000 * 1000;
670 ret
= select(maxfd
, &rset
, &wset
, &xset
, ptv
);
674 long newnow
= GETTICKCOUNT();
676 * Check to see whether the system clock has
677 * changed massively during the select.
679 if (newnow
- now
< 0 || newnow
- now
> next
- now
) {
681 * If so, look at the elapsed time in the
682 * select and use it to compute a new
685 long othernow
= now
+ tv
.tv_sec
* 1000 + tv
.tv_usec
/ 1000;
686 /* So we'd like GETTICKCOUNT to have returned othernow,
687 * but instead it return newnow. Hence ... */
688 tickcount_offset
+= othernow
- newnow
;
694 } while (ret
< 0 && errno
== EINTR
);
701 for (i
= 0; i
< fdcount
; i
++) {
704 * We must process exceptional notifications before
705 * ordinary readability ones, or we may go straight
706 * past the urgent marker.
708 if (FD_ISSET(fd
, &xset
))
709 select_result(fd
, 4);
710 if (FD_ISSET(fd
, &rset
))
711 select_result(fd
, 1);
712 if (FD_ISSET(fd
, &wset
))
713 select_result(fd
, 2);
716 if (FD_ISSET(signalpipe
[0], &rset
)) {
719 read(signalpipe
[0], c
, 1); /* ignore its value; it'll be `x' */
720 if (ioctl(0, TIOCGWINSZ
, (void *)&size
) >= 0)
721 back
->size(backhandle
, size
.ws_col
, size
.ws_row
);
724 if (FD_ISSET(0, &rset
)) {
728 if (connopen
&& back
->socket(backhandle
) != NULL
) {
729 ret
= read(0, buf
, sizeof(buf
));
731 perror("stdin: read");
733 } else if (ret
== 0) {
734 back
->special(backhandle
, TS_EOF
);
735 sending
= FALSE
; /* send nothing further after this */
737 back
->send(backhandle
, buf
, ret
);
742 if (FD_ISSET(1, &wset
)) {
746 if (FD_ISSET(2, &wset
)) {
750 if ((!connopen
|| back
->socket(backhandle
) == NULL
) &&
751 bufchain_size(&stdout_data
) == 0 &&
752 bufchain_size(&stderr_data
) == 0)
753 break; /* we closed the connection */
755 exitcode
= back
->exitcode(backhandle
);
757 fprintf(stderr
, "Remote process exit code unavailable\n");
758 exitcode
= 1; /* this is an error condition */
760 cleanup_exit(exitcode
);
761 return exitcode
; /* shouldn't happen, but placates gcc */