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_lflag
|= ISIG
| ICANON
;
135 mode
.c_lflag
&= ~(ISIG
| ICANON
);
137 tcsetattr(0, TCSANOW
, &mode
);
140 void cleanup_termios(void)
142 tcsetattr(0, TCSANOW
, &orig_termios
);
145 bufchain stdout_data
, stderr_data
;
147 void try_output(int is_stderr
)
149 bufchain
*chain
= (is_stderr ?
&stderr_data
: &stdout_data
);
150 int fd
= (is_stderr ?
2 : 1);
154 if (bufchain_size(chain
) == 0)
157 bufchain_prefix(chain
, &senddata
, &sendlen
);
158 ret
= write(fd
, senddata
, sendlen
);
160 bufchain_consume(chain
, ret
);
162 perror(is_stderr ?
"stderr: write" : "stdout: write");
167 int from_backend(void *frontend_handle
, int is_stderr
,
168 const char *data
, int len
)
173 bufchain_add(&stderr_data
, data
, len
);
176 bufchain_add(&stdout_data
, data
, len
);
180 osize
= bufchain_size(&stdout_data
);
181 esize
= bufchain_size(&stderr_data
);
183 return osize
+ esize
;
188 void sigwinch(int signum
)
190 write(signalpipe
[1], "x", 1);
194 * In Plink our selects are synchronous, so these functions are
197 int uxsel_input_add(int fd
, int rwx
) { return 0; }
198 void uxsel_input_remove(int id
) { }
201 * Short description of parameters.
203 static void usage(void)
205 printf("PuTTY Link: command-line connection utility\n");
207 printf("Usage: plink [options] [user@]host [command]\n");
208 printf(" (\"host\" can also be a PuTTY saved session name)\n");
209 printf("Options:\n");
210 printf(" -V print version information\n");
211 printf(" -v show verbose messages\n");
212 printf(" -load sessname Load settings from saved session\n");
213 printf(" -ssh -telnet -rlogin -raw\n");
214 printf(" force use of a particular protocol\n");
215 printf(" -P port connect to specified port\n");
216 printf(" -l user connect with specified username\n");
217 printf(" -m file read remote command(s) from file\n");
218 printf(" -batch disable all interactive prompts\n");
219 printf("The following options only apply to SSH connections:\n");
220 printf(" -pw passw login with specified password\n");
221 printf(" -D [listen-IP:]listen-port\n");
222 printf(" Dynamic SOCKS-based port forwarding\n");
223 printf(" -L [listen-IP:]listen-port:host:port\n");
224 printf(" Forward local port to remote address\n");
225 printf(" -R [listen-IP:]listen-port:host:port\n");
226 printf(" Forward remote port to local address\n");
227 printf(" -X -x enable / disable X11 forwarding\n");
228 printf(" -A -a enable / disable agent forwarding\n");
229 printf(" -t -T enable / disable pty allocation\n");
230 printf(" -1 -2 force use of particular protocol version\n");
231 printf(" -4 -6 force use of IPv4 or IPv6\n");
232 printf(" -C enable compression\n");
233 printf(" -i key private key file for authentication\n");
234 printf(" -s remote command is an SSH subsystem (SSH-2 only)\n");
235 printf(" -N don't start a shell/command (SSH-2 only)\n");
239 static void version(void)
241 printf("plink: %s\n", ver
);
245 int main(int argc
, char **argv
)
251 int i
, fdcount
, fdsize
, fdstate
;
255 int use_subsystem
= 0;
256 void *ldisc
, *logctx
;
259 ssh_get_line
= console_get_line
;
262 fdcount
= fdsize
= 0;
264 * Initialise port and protocol to sensible defaults. (These
265 * will be overridden by more or less anything.)
267 default_protocol
= PROT_SSH
;
272 * Process the command line.
274 do_defaults(NULL
, &cfg
);
275 loaded_session
= FALSE
;
276 default_protocol
= cfg
.protocol
;
277 default_port
= cfg
.port
;
281 * Override the default protocol if PLINK_PROTOCOL is set.
283 char *p
= getenv("PLINK_PROTOCOL");
286 for (i
= 0; backends
[i
].backend
!= NULL
; i
++) {
287 if (!strcmp(backends
[i
].name
, p
)) {
288 default_protocol
= cfg
.protocol
= backends
[i
].protocol
;
289 default_port
= cfg
.port
=
290 backends
[i
].backend
->default_port
;
299 int ret
= cmdline_process_param(p
, (argc
> 1 ? argv
[1] : NULL
),
303 "plink: option \"%s\" requires an argument\n", p
);
305 } else if (ret
== 2) {
307 } else if (ret
== 1) {
309 } else if (!strcmp(p
, "-batch")) {
310 console_batch_mode
= 1;
311 } else if (!strcmp(p
, "-s")) {
312 /* Save status to write to cfg later. */
314 } else if (!strcmp(p
, "-V")) {
316 } else if (!strcmp(p
, "-o")) {
319 "plink: option \"-o\" requires an argument\n");
323 provide_xrm_string(*++argv
);
326 fprintf(stderr
, "plink: unknown option \"%s\"\n", p
);
333 do_defaults(NULL
, &cfg
);
336 * If the hostname starts with "telnet:", set the
337 * protocol to Telnet and process the string as a
340 if (!strncmp(q
, "telnet:", 7)) {
344 if (q
[0] == '/' && q
[1] == '/')
346 cfg
.protocol
= PROT_TELNET
;
348 while (*p
&& *p
!= ':' && *p
!= '/')
357 strncpy(cfg
.host
, q
, sizeof(cfg
.host
) - 1);
358 cfg
.host
[sizeof(cfg
.host
) - 1] = '\0';
360 char *r
, *user
, *host
;
362 * Before we process the [user@]host string, we
363 * first check for the presence of a protocol
364 * prefix (a protocol name followed by ",").
369 for (i
= 0; backends
[i
].backend
!= NULL
; i
++) {
370 j
= strlen(backends
[i
].name
);
372 !memcmp(backends
[i
].name
, p
, j
)) {
373 default_protocol
= cfg
.protocol
=
374 backends
[i
].protocol
;
376 backends
[i
].backend
->default_port
;
384 * A nonzero length string followed by an @ is treated
385 * as a username. (We discount an _initial_ @.) The
386 * rest of the string (or the whole string if no @)
387 * is treated as a session name and/or hostname.
391 p
++, r
= NULL
; /* discount initial @ */
396 user
= NULL
, host
= p
;
400 * Now attempt to load a saved session with the
401 * same name as the hostname.
405 do_defaults(host
, &cfg2
);
406 if (loaded_session
|| cfg2
.host
[0] == '\0') {
407 /* No settings for this host; use defaults */
408 /* (or session was already loaded with -load) */
409 strncpy(cfg
.host
, host
, sizeof(cfg
.host
) - 1);
410 cfg
.host
[sizeof(cfg
.host
) - 1] = '\0';
411 cfg
.port
= default_port
;
414 /* Ick: patch up internal pointer after copy */
415 cfg
.remote_cmd_ptr
= cfg
.remote_cmd
;
420 /* Patch in specified username. */
421 strncpy(cfg
.username
, user
,
422 sizeof(cfg
.username
) - 1);
423 cfg
.username
[sizeof(cfg
.username
) - 1] = '\0';
430 cmdlen
= cmdsize
= 0;
435 if (cmdlen
>= cmdsize
) {
436 cmdsize
= cmdlen
+ 512;
437 command
= sresize(command
, cmdsize
, char);
439 command
[cmdlen
++]=*p
++;
441 if (cmdlen
>= cmdsize
) {
442 cmdsize
= cmdlen
+ 512;
443 command
= sresize(command
, cmdsize
, char);
445 command
[cmdlen
++]=' '; /* always add trailing space */
446 if (--argc
) p
= *++argv
;
448 if (cmdlen
) command
[--cmdlen
]='\0';
449 /* change trailing blank to NUL */
450 cfg
.remote_cmd_ptr
= command
;
451 cfg
.remote_cmd_ptr2
= NULL
;
452 cfg
.nopty
= TRUE
; /* command => no terminal */
454 break; /* done with cmdline */
467 * Trim leading whitespace off the hostname if it's there.
470 int space
= strspn(cfg
.host
, " \t");
471 memmove(cfg
.host
, cfg
.host
+space
, 1+strlen(cfg
.host
)-space
);
474 /* See if host is of the form user@host */
475 if (cfg
.host
[0] != '\0') {
476 char *atsign
= strrchr(cfg
.host
, '@');
477 /* Make sure we're not overflowing the user field */
479 if (atsign
- cfg
.host
< sizeof cfg
.username
) {
480 strncpy(cfg
.username
, cfg
.host
, atsign
- cfg
.host
);
481 cfg
.username
[atsign
- cfg
.host
] = '\0';
483 memmove(cfg
.host
, atsign
+ 1, 1 + strlen(atsign
+ 1));
488 * Perform command-line overrides on session configuration.
490 cmdline_run_saved(&cfg
);
493 * Apply subsystem status.
496 cfg
.ssh_subsys
= TRUE
;
499 * Trim a colon suffix off the hostname if it's there.
501 cfg
.host
[strcspn(cfg
.host
, ":")] = '\0';
504 * Remove any remaining whitespace from the hostname.
508 while (cfg
.host
[p2
] != '\0') {
509 if (cfg
.host
[p2
] != ' ' && cfg
.host
[p2
] != '\t') {
510 cfg
.host
[p1
] = cfg
.host
[p2
];
518 if (!*cfg
.remote_cmd_ptr
)
519 flags
|= FLAG_INTERACTIVE
;
522 * Select protocol. This is farmed out into a table in a
523 * separate file to enable an ssh-free variant.
528 for (i
= 0; backends
[i
].backend
!= NULL
; i
++)
529 if (backends
[i
].protocol
== cfg
.protocol
) {
530 back
= backends
[i
].backend
;
535 "Internal fault: Unsupported protocol found\n");
543 if (portnumber
!= -1)
544 cfg
.port
= portnumber
;
547 * Set up the pipe we'll use to tell us about SIGWINCH.
549 if (pipe(signalpipe
) < 0) {
553 putty_signal(SIGWINCH
, sigwinch
);
559 * Start up the connection.
561 logctx
= log_init(NULL
, &cfg
);
562 console_provide_logctx(logctx
);
566 /* nodelay is only useful if stdin is a terminal device */
567 int nodelay
= cfg
.tcp_nodelay
&& isatty(0);
569 error
= back
->init(NULL
, &backhandle
, &cfg
, cfg
.host
, cfg
.port
,
570 &realhost
, nodelay
, cfg
.tcp_keepalives
);
572 fprintf(stderr
, "Unable to open connection:\n%s\n", error
);
575 back
->provide_logctx(backhandle
, logctx
);
576 ldisc
= ldisc_create(&cfg
, NULL
, back
, backhandle
, NULL
);
582 * Set up the initial console mode. We don't care if this call
583 * fails, because we know we aren't necessarily running in a
586 tcgetattr(0, &orig_termios
);
587 atexit(cleanup_termios
);
588 ldisc_update(NULL
, 1, 1);
590 now
= GETTICKCOUNT();
593 fd_set rset
, wset
, xset
;
603 FD_SET_MAX(signalpipe
[0], maxfd
, rset
);
605 if (connopen
&& !sending
&&
606 back
->socket(backhandle
) != NULL
&&
607 back
->sendok(backhandle
) &&
608 back
->sendbuffer(backhandle
) < MAX_STDIN_BACKLOG
) {
609 /* If we're OK to send, then try to read from stdin. */
610 FD_SET_MAX(0, maxfd
, rset
);
613 if (bufchain_size(&stdout_data
) > 0) {
614 /* If we have data for stdout, try to write to stdout. */
615 FD_SET_MAX(1, maxfd
, wset
);
618 if (bufchain_size(&stderr_data
) > 0) {
619 /* If we have data for stderr, try to write to stderr. */
620 FD_SET_MAX(2, maxfd
, wset
);
623 /* Count the currently active fds. */
625 for (fd
= first_fd(&fdstate
, &rwx
); fd
>= 0;
626 fd
= next_fd(&fdstate
, &rwx
)) i
++;
628 /* Expand the fdlist buffer if necessary. */
631 fdlist
= sresize(fdlist
, fdsize
, int);
635 * Add all currently open fds to the select sets, and store
636 * them in fdlist as well.
639 for (fd
= first_fd(&fdstate
, &rwx
); fd
>= 0;
640 fd
= next_fd(&fdstate
, &rwx
)) {
641 fdlist
[fdcount
++] = fd
;
643 FD_SET_MAX(fd
, maxfd
, rset
);
645 FD_SET_MAX(fd
, maxfd
, wset
);
647 FD_SET_MAX(fd
, maxfd
, xset
);
652 struct timeval tv
, *ptv
;
654 if (run_timers(now
, &next
)) {
655 ticks
= next
- GETTICKCOUNT();
656 if (ticks
< 0) ticks
= 0; /* just in case */
657 tv
.tv_sec
= ticks
/ 1000;
658 tv
.tv_usec
= ticks
% 1000 * 1000;
663 ret
= select(maxfd
, &rset
, &wset
, &xset
, ptv
);
667 now
= GETTICKCOUNT();
668 } while (ret
< 0 && errno
== EINTR
);
675 for (i
= 0; i
< fdcount
; i
++) {
678 * We must process exceptional notifications before
679 * ordinary readability ones, or we may go straight
680 * past the urgent marker.
682 if (FD_ISSET(fd
, &xset
))
683 select_result(fd
, 4);
684 if (FD_ISSET(fd
, &rset
))
685 select_result(fd
, 1);
686 if (FD_ISSET(fd
, &wset
))
687 select_result(fd
, 2);
690 if (FD_ISSET(signalpipe
[0], &rset
)) {
693 read(signalpipe
[0], c
, 1); /* ignore its value; it'll be `x' */
694 if (ioctl(0, TIOCGWINSZ
, (void *)&size
) >= 0)
695 back
->size(backhandle
, size
.ws_col
, size
.ws_row
);
698 if (FD_ISSET(0, &rset
)) {
702 if (connopen
&& back
->socket(backhandle
) != NULL
) {
703 ret
= read(0, buf
, sizeof(buf
));
705 perror("stdin: read");
707 } else if (ret
== 0) {
708 back
->special(backhandle
, TS_EOF
);
709 sending
= FALSE
; /* send nothing further after this */
711 back
->send(backhandle
, buf
, ret
);
716 if (FD_ISSET(1, &wset
)) {
720 if (FD_ISSET(2, &wset
)) {
724 if ((!connopen
|| back
->socket(backhandle
) == NULL
) &&
725 bufchain_size(&stdout_data
) == 0 &&
726 bufchain_size(&stderr_data
) == 0)
727 break; /* we closed the connection */
729 exitcode
= back
->exitcode(backhandle
);
731 fprintf(stderr
, "Remote process exit code unavailable\n");
732 exitcode
= 1; /* this is an error condition */
734 cleanup_exit(exitcode
);
735 return exitcode
; /* shouldn't happen, but placates gcc */