2 * PLink - a command-line (stdin/stdout) variant of PuTTY.
15 #include <sys/ioctl.h>
17 #define PUTTY_DO_GLOBALS /* actually _define_ globals */
22 #define MAX_STDIN_BACKLOG 4096
24 void fatalbox(char *p
, ...)
27 fprintf(stderr
, "FATAL ERROR: ");
29 vfprintf(stderr
, p
, ap
);
34 void modalfatalbox(char *p
, ...)
37 fprintf(stderr
, "FATAL ERROR: ");
39 vfprintf(stderr
, p
, ap
);
44 void connection_fatal(void *frontend
, char *p
, ...)
47 fprintf(stderr
, "FATAL ERROR: ");
49 vfprintf(stderr
, p
, ap
);
54 void cmdline_error(char *p
, ...)
57 fprintf(stderr
, "plink: ");
59 vfprintf(stderr
, p
, ap
);
65 struct termios orig_termios
;
68 static void *backhandle
;
72 * Default settings that are specific to pterm.
74 char *platform_default_s(const char *name
)
76 if (!strcmp(name
, "TermType"))
77 return dupstr(getenv("TERM"));
78 if (!strcmp(name
, "UserName"))
79 return get_username();
83 int platform_default_i(const char *name
, int def
)
85 if (!strcmp(name
, "TermWidth") ||
86 !strcmp(name
, "TermHeight")) {
88 if (ioctl(0, TIOCGWINSZ
, (void *)&size
) >= 0)
89 return (!strcmp(name
, "TermWidth") ? size
.ws_col
: size
.ws_row
);
94 FontSpec
platform_default_fontspec(const char *name
)
101 Filename
platform_default_filename(const char *name
)
104 if (!strcmp(name
, "LogFileName"))
105 strcpy(ret
.path
, "putty.log");
111 char *x_get_default(const char *key
)
113 return NULL
; /* this is a stub */
115 int term_ldisc(Terminal
*term
, int mode
)
119 void ldisc_update(void *frontend
, int echo
, int edit
)
121 /* Update stdin read mode to reflect changes in line discipline. */
127 mode
.c_lflag
|= ECHO
;
129 mode
.c_lflag
&= ~ECHO
;
132 mode
.c_lflag
|= ISIG
| ICANON
;
134 mode
.c_lflag
&= ~(ISIG
| ICANON
);
136 tcsetattr(0, TCSANOW
, &mode
);
139 void cleanup_termios(void)
141 tcsetattr(0, TCSANOW
, &orig_termios
);
144 bufchain stdout_data
, stderr_data
;
146 void try_output(int is_stderr
)
148 bufchain
*chain
= (is_stderr ?
&stderr_data
: &stdout_data
);
149 int fd
= (is_stderr ?
2 : 1);
153 if (bufchain_size(chain
) == 0)
156 bufchain_prefix(chain
, &senddata
, &sendlen
);
157 ret
= write(fd
, senddata
, sendlen
);
159 bufchain_consume(chain
, ret
);
161 perror(is_stderr ?
"stderr: write" : "stdout: write");
166 int from_backend(void *frontend_handle
, int is_stderr
,
167 const char *data
, int len
)
172 bufchain_add(&stderr_data
, data
, len
);
175 bufchain_add(&stdout_data
, data
, len
);
179 osize
= bufchain_size(&stdout_data
);
180 esize
= bufchain_size(&stderr_data
);
182 return osize
+ esize
;
187 void sigwinch(int signum
)
189 write(signalpipe
[1], "x", 1);
193 * In Plink our selects are synchronous, so these functions are
196 int uxsel_input_add(int fd
, int rwx
) { return 0; }
197 void uxsel_input_remove(int id
) { }
200 * Short description of parameters.
202 static void usage(void)
204 printf("PuTTY Link: command-line connection utility\n");
206 printf("Usage: plink [options] [user@]host [command]\n");
207 printf(" (\"host\" can also be a PuTTY saved session name)\n");
208 printf("Options:\n");
209 printf(" -V print version information\n");
210 printf(" -v show verbose messages\n");
211 printf(" -load sessname Load settings from saved session\n");
212 printf(" -ssh -telnet -rlogin -raw\n");
213 printf(" force use of a particular protocol\n");
214 printf(" -P port connect to specified port\n");
215 printf(" -l user connect with specified username\n");
216 printf(" -m file read remote command(s) from file\n");
217 printf(" -batch disable all interactive prompts\n");
218 printf("The following options only apply to SSH connections:\n");
219 printf(" -pw passw login with specified password\n");
220 printf(" -D [listen-IP:]listen-port\n");
221 printf(" Dynamic SOCKS-based port forwarding\n");
222 printf(" -L [listen-IP:]listen-port:host:port\n");
223 printf(" Forward local port to remote address\n");
224 printf(" -R [listen-IP:]listen-port:host:port\n");
225 printf(" Forward remote port to local address\n");
226 printf(" -X -x enable / disable X11 forwarding\n");
227 printf(" -A -a enable / disable agent forwarding\n");
228 printf(" -t -T enable / disable pty allocation\n");
229 printf(" -1 -2 force use of particular protocol version\n");
230 printf(" -C enable compression\n");
231 printf(" -i key private key file for authentication\n");
232 printf(" -s remote command is an SSH subsystem (SSH-2 only)\n");
233 printf(" -N don't start a shell/command (SSH-2 only)\n");
237 static void version(void)
239 printf("plink: %s\n", ver
);
243 int main(int argc
, char **argv
)
249 int i
, fdcount
, fdsize
, fdstate
;
253 int use_subsystem
= 0;
254 void *ldisc
, *logctx
;
257 ssh_get_line
= console_get_line
;
260 fdcount
= fdsize
= 0;
262 * Initialise port and protocol to sensible defaults. (These
263 * will be overridden by more or less anything.)
265 default_protocol
= PROT_SSH
;
270 * Process the command line.
272 do_defaults(NULL
, &cfg
);
273 loaded_session
= FALSE
;
274 default_protocol
= cfg
.protocol
;
275 default_port
= cfg
.port
;
279 * Override the default protocol if PLINK_PROTOCOL is set.
281 char *p
= getenv("PLINK_PROTOCOL");
284 for (i
= 0; backends
[i
].backend
!= NULL
; i
++) {
285 if (!strcmp(backends
[i
].name
, p
)) {
286 default_protocol
= cfg
.protocol
= backends
[i
].protocol
;
287 default_port
= cfg
.port
=
288 backends
[i
].backend
->default_port
;
297 int ret
= cmdline_process_param(p
, (argc
> 1 ? argv
[1] : NULL
),
301 "plink: option \"%s\" requires an argument\n", p
);
303 } else if (ret
== 2) {
305 } else if (ret
== 1) {
307 } else if (!strcmp(p
, "-batch")) {
308 console_batch_mode
= 1;
309 } else if (!strcmp(p
, "-s")) {
310 /* Save status to write to cfg later. */
312 } else if (!strcmp(p
, "-V")) {
314 } else if (!strcmp(p
, "-o")) {
317 "plink: option \"-o\" requires an argument\n");
321 provide_xrm_string(*++argv
);
324 fprintf(stderr
, "plink: unknown option \"%s\"\n", p
);
331 do_defaults(NULL
, &cfg
);
334 * If the hostname starts with "telnet:", set the
335 * protocol to Telnet and process the string as a
338 if (!strncmp(q
, "telnet:", 7)) {
342 if (q
[0] == '/' && q
[1] == '/')
344 cfg
.protocol
= PROT_TELNET
;
346 while (*p
&& *p
!= ':' && *p
!= '/')
355 strncpy(cfg
.host
, q
, sizeof(cfg
.host
) - 1);
356 cfg
.host
[sizeof(cfg
.host
) - 1] = '\0';
358 char *r
, *user
, *host
;
360 * Before we process the [user@]host string, we
361 * first check for the presence of a protocol
362 * prefix (a protocol name followed by ",").
367 for (i
= 0; backends
[i
].backend
!= NULL
; i
++) {
368 j
= strlen(backends
[i
].name
);
370 !memcmp(backends
[i
].name
, p
, j
)) {
371 default_protocol
= cfg
.protocol
=
372 backends
[i
].protocol
;
374 backends
[i
].backend
->default_port
;
382 * A nonzero length string followed by an @ is treated
383 * as a username. (We discount an _initial_ @.) The
384 * rest of the string (or the whole string if no @)
385 * is treated as a session name and/or hostname.
389 p
++, r
= NULL
; /* discount initial @ */
394 user
= NULL
, host
= p
;
398 * Now attempt to load a saved session with the
399 * same name as the hostname.
403 do_defaults(host
, &cfg2
);
404 if (loaded_session
|| cfg2
.host
[0] == '\0') {
405 /* No settings for this host; use defaults */
406 /* (or session was already loaded with -load) */
407 strncpy(cfg
.host
, host
, sizeof(cfg
.host
) - 1);
408 cfg
.host
[sizeof(cfg
.host
) - 1] = '\0';
409 cfg
.port
= default_port
;
412 /* Ick: patch up internal pointer after copy */
413 cfg
.remote_cmd_ptr
= cfg
.remote_cmd
;
418 /* Patch in specified username. */
419 strncpy(cfg
.username
, user
,
420 sizeof(cfg
.username
) - 1);
421 cfg
.username
[sizeof(cfg
.username
) - 1] = '\0';
428 cmdlen
= cmdsize
= 0;
433 if (cmdlen
>= cmdsize
) {
434 cmdsize
= cmdlen
+ 512;
435 command
= sresize(command
, cmdsize
, char);
437 command
[cmdlen
++]=*p
++;
439 if (cmdlen
>= cmdsize
) {
440 cmdsize
= cmdlen
+ 512;
441 command
= sresize(command
, cmdsize
, char);
443 command
[cmdlen
++]=' '; /* always add trailing space */
444 if (--argc
) p
= *++argv
;
446 if (cmdlen
) command
[--cmdlen
]='\0';
447 /* change trailing blank to NUL */
448 cfg
.remote_cmd_ptr
= command
;
449 cfg
.remote_cmd_ptr2
= NULL
;
450 cfg
.nopty
= TRUE
; /* command => no terminal */
452 break; /* done with cmdline */
465 * Trim leading whitespace off the hostname if it's there.
468 int space
= strspn(cfg
.host
, " \t");
469 memmove(cfg
.host
, cfg
.host
+space
, 1+strlen(cfg
.host
)-space
);
472 /* See if host is of the form user@host */
473 if (cfg
.host
[0] != '\0') {
474 char *atsign
= strrchr(cfg
.host
, '@');
475 /* Make sure we're not overflowing the user field */
477 if (atsign
- cfg
.host
< sizeof cfg
.username
) {
478 strncpy(cfg
.username
, cfg
.host
, atsign
- cfg
.host
);
479 cfg
.username
[atsign
- cfg
.host
] = '\0';
481 memmove(cfg
.host
, atsign
+ 1, 1 + strlen(atsign
+ 1));
486 * Perform command-line overrides on session configuration.
488 cmdline_run_saved(&cfg
);
491 * Apply subsystem status.
494 cfg
.ssh_subsys
= TRUE
;
497 * Trim a colon suffix off the hostname if it's there.
499 cfg
.host
[strcspn(cfg
.host
, ":")] = '\0';
502 * Remove any remaining whitespace from the hostname.
506 while (cfg
.host
[p2
] != '\0') {
507 if (cfg
.host
[p2
] != ' ' && cfg
.host
[p2
] != '\t') {
508 cfg
.host
[p1
] = cfg
.host
[p2
];
516 if (!*cfg
.remote_cmd_ptr
)
517 flags
|= FLAG_INTERACTIVE
;
520 * Select protocol. This is farmed out into a table in a
521 * separate file to enable an ssh-free variant.
526 for (i
= 0; backends
[i
].backend
!= NULL
; i
++)
527 if (backends
[i
].protocol
== cfg
.protocol
) {
528 back
= backends
[i
].backend
;
533 "Internal fault: Unsupported protocol found\n");
541 if (portnumber
!= -1)
542 cfg
.port
= portnumber
;
545 * Set up the pipe we'll use to tell us about SIGWINCH.
547 if (pipe(signalpipe
) < 0) {
551 putty_signal(SIGWINCH
, sigwinch
);
557 * Start up the connection.
559 logctx
= log_init(NULL
, &cfg
);
560 console_provide_logctx(logctx
);
564 /* nodelay is only useful if stdin is a terminal device */
565 int nodelay
= cfg
.tcp_nodelay
&& isatty(0);
567 error
= back
->init(NULL
, &backhandle
, &cfg
, cfg
.host
, cfg
.port
,
568 &realhost
, nodelay
, cfg
.tcp_keepalives
);
570 fprintf(stderr
, "Unable to open connection:\n%s\n", error
);
573 back
->provide_logctx(backhandle
, logctx
);
574 ldisc
= ldisc_create(&cfg
, NULL
, back
, backhandle
, NULL
);
580 * Set up the initial console mode. We don't care if this call
581 * fails, because we know we aren't necessarily running in a
584 tcgetattr(0, &orig_termios
);
585 atexit(cleanup_termios
);
586 ldisc_update(NULL
, 1, 1);
588 now
= GETTICKCOUNT();
591 fd_set rset
, wset
, xset
;
601 FD_SET_MAX(signalpipe
[0], maxfd
, rset
);
603 if (connopen
&& !sending
&&
604 back
->socket(backhandle
) != NULL
&&
605 back
->sendok(backhandle
) &&
606 back
->sendbuffer(backhandle
) < MAX_STDIN_BACKLOG
) {
607 /* If we're OK to send, then try to read from stdin. */
608 FD_SET_MAX(0, maxfd
, rset
);
611 if (bufchain_size(&stdout_data
) > 0) {
612 /* If we have data for stdout, try to write to stdout. */
613 FD_SET_MAX(1, maxfd
, wset
);
616 if (bufchain_size(&stderr_data
) > 0) {
617 /* If we have data for stderr, try to write to stderr. */
618 FD_SET_MAX(2, maxfd
, wset
);
621 /* Count the currently active fds. */
623 for (fd
= first_fd(&fdstate
, &rwx
); fd
>= 0;
624 fd
= next_fd(&fdstate
, &rwx
)) i
++;
626 /* Expand the fdlist buffer if necessary. */
629 fdlist
= sresize(fdlist
, fdsize
, int);
633 * Add all currently open fds to the select sets, and store
634 * them in fdlist as well.
637 for (fd
= first_fd(&fdstate
, &rwx
); fd
>= 0;
638 fd
= next_fd(&fdstate
, &rwx
)) {
639 fdlist
[fdcount
++] = fd
;
641 FD_SET_MAX(fd
, maxfd
, rset
);
643 FD_SET_MAX(fd
, maxfd
, wset
);
645 FD_SET_MAX(fd
, maxfd
, xset
);
650 struct timeval tv
, *ptv
;
652 if (run_timers(now
, &next
)) {
653 ticks
= next
- GETTICKCOUNT();
654 if (ticks
< 0) ticks
= 0; /* just in case */
655 tv
.tv_sec
= ticks
/ 1000;
656 tv
.tv_usec
= ticks
% 1000 * 1000;
661 ret
= select(maxfd
, &rset
, &wset
, &xset
, ptv
);
665 now
= GETTICKCOUNT();
666 } while (ret
< 0 && errno
== EINTR
);
673 for (i
= 0; i
< fdcount
; i
++) {
676 * We must process exceptional notifications before
677 * ordinary readability ones, or we may go straight
678 * past the urgent marker.
680 if (FD_ISSET(fd
, &xset
))
681 select_result(fd
, 4);
682 if (FD_ISSET(fd
, &rset
))
683 select_result(fd
, 1);
684 if (FD_ISSET(fd
, &wset
))
685 select_result(fd
, 2);
688 if (FD_ISSET(signalpipe
[0], &rset
)) {
691 read(signalpipe
[0], c
, 1); /* ignore its value; it'll be `x' */
692 if (ioctl(0, TIOCGWINSZ
, (void *)&size
) >= 0)
693 back
->size(backhandle
, size
.ws_col
, size
.ws_row
);
696 if (FD_ISSET(0, &rset
)) {
700 if (connopen
&& back
->socket(backhandle
) != NULL
) {
701 ret
= read(0, buf
, sizeof(buf
));
703 perror("stdin: read");
705 } else if (ret
== 0) {
706 back
->special(backhandle
, TS_EOF
);
707 sending
= FALSE
; /* send nothing further after this */
709 back
->send(backhandle
, buf
, ret
);
714 if (FD_ISSET(1, &wset
)) {
718 if (FD_ISSET(2, &wset
)) {
722 if ((!connopen
|| back
->socket(backhandle
) == NULL
) &&
723 bufchain_size(&stdout_data
) == 0 &&
724 bufchain_size(&stderr_data
) == 0)
725 break; /* we closed the connection */
727 exitcode
= back
->exitcode(backhandle
);
729 fprintf(stderr
, "Remote process exit code unavailable\n");
730 exitcode
= 1; /* this is an error condition */
732 cleanup_exit(exitcode
);
733 return exitcode
; /* shouldn't happen, but placates gcc */