2 * PLink - a command-line (stdin/stdout) variant of PuTTY.
15 #include <sys/ioctl.h>
17 /* More helpful version of the FD_SET macro, to also handle maxfd. */
18 #define FD_SET_MAX(fd, max, set) do { \
20 if (max < fd + 1) max = fd + 1; \
23 #define PUTTY_DO_GLOBALS /* actually _define_ globals */
28 #define MAX_STDIN_BACKLOG 4096
30 void fatalbox(char *p, ...)
33 fprintf(stderr, "FATAL ERROR: ");
35 vfprintf(stderr, p, ap);
40 void modalfatalbox(char *p, ...)
43 fprintf(stderr, "FATAL ERROR: ");
45 vfprintf(stderr, p, ap);
50 void connection_fatal(void *frontend, char *p, ...)
53 fprintf(stderr, "FATAL ERROR: ");
55 vfprintf(stderr, p, ap);
60 void cmdline_error(char *p, ...)
63 fprintf(stderr, "plink: ");
65 vfprintf(stderr, p, ap);
71 struct termios orig_termios;
74 static void *backhandle;
78 * Default settings that are specific to pterm.
80 char *platform_default_s(char *name)
82 if (!strcmp(name, "X11Display"))
83 return getenv("DISPLAY");
84 if (!strcmp(name, "TermType"))
85 return getenv("TERM");
86 if (!strcmp(name, "UserName")) {
88 * Remote login username will default to the local username.
92 char *user, *ret = NULL;
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.
106 if (p && p->pw_uid == uid) {
108 * The result of getlogin() really does correspond to
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.
128 int platform_default_i(char *name, int def)
130 if (!strcmp(name, "TermWidth") ||
131 !strcmp(name, "TermHeight")) {
133 if (ioctl(0, TIOCGWINSZ, (void *)&size) >= 0)
134 return (!strcmp(name, "TermWidth") ? size.ws_col : size.ws_row);
139 char *x_get_default(char *key)
141 return NULL; /* this is a stub */
143 int term_ldisc(Terminal *term, int mode)
147 void ldisc_update(void *frontend, int echo, int edit)
149 /* Update stdin read mode to reflect changes in line discipline. */
155 mode.c_lflag |= ECHO;
157 mode.c_lflag &= ~ECHO;
160 mode.c_lflag |= ISIG | ICANON;
162 mode.c_lflag &= ~(ISIG | ICANON);
164 tcsetattr(0, TCSANOW, &mode);
167 void cleanup_termios(void)
169 tcsetattr(0, TCSANOW, &orig_termios);
172 bufchain stdout_data, stderr_data;
174 void try_output(int is_stderr)
176 bufchain *chain = (is_stderr ? &stderr_data : &stdout_data);
177 int fd = (is_stderr ? 2 : 1);
181 if (bufchain_size(chain) == 0)
184 bufchain_prefix(chain, &senddata, &sendlen);
185 ret = write(fd, senddata, sendlen);
187 bufchain_consume(chain, ret);
189 perror(is_stderr ? "stderr: write" : "stdout: write");
194 int from_backend(void *frontend_handle, int is_stderr, char *data, int len)
201 bufchain_add(&stderr_data, data, len);
204 bufchain_add(&stdout_data, data, len);
208 osize = bufchain_size(&stdout_data);
209 esize = bufchain_size(&stderr_data);
211 return osize + esize;
216 void sigwinch(int signum)
218 write(signalpipe[1], "x", 1);
222 * Short description of parameters.
224 static void usage(void)
226 printf("PuTTY Link: command-line connection utility\n");
228 printf("Usage: plink [options] [user@]host [command]\n");
229 printf(" (\"host\" can also be a PuTTY saved session name)\n");
230 printf("Options:\n");
231 printf(" -v show verbose messages\n");
232 printf(" -load sessname Load settings from saved session\n");
233 printf(" -ssh -telnet -rlogin -raw\n");
234 printf(" force use of a particular protocol (default SSH)\n");
235 printf(" -P port connect to specified port\n");
236 printf(" -l user connect with specified username\n");
237 printf(" -m file read remote command(s) from file\n");
238 printf(" -batch disable all interactive prompts\n");
239 printf("The following options only apply to SSH connections:\n");
240 printf(" -pw passw login with specified password\n");
241 printf(" -L listen-port:host:port Forward local port to "
243 printf(" -R listen-port:host:port Forward remote port to"
245 printf(" -X -x enable / disable X11 forwarding\n");
246 printf(" -A -a enable / disable agent forwarding\n");
247 printf(" -t -T enable / disable pty allocation\n");
248 printf(" -1 -2 force use of particular protocol version\n");
249 printf(" -C enable compression\n");
250 printf(" -i key private key file for authentication\n");
254 int main(int argc, char **argv)
260 int i, skcount, sksize, socketstate;
266 ssh_get_line = console_get_line;
269 skcount = sksize = 0;
271 * Initialise port and protocol to sensible defaults. (These
272 * will be overridden by more or less anything.)
274 default_protocol = PROT_SSH;
279 * Process the command line.
281 do_defaults(NULL, &cfg);
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, "-o")) {
320 "plink: option \"-o\" requires an argument\n");
324 provide_xrm_string(*++argv);
327 fprintf(stderr, "plink: unknown option \"%s\"\n", p);
334 do_defaults(NULL, &cfg);
337 * If the hostname starts with "telnet:", set the
338 * protocol to Telnet and process the string as a
341 if (!strncmp(q, "telnet:", 7)) {
345 if (q[0] == '/' && q[1] == '/')
347 cfg.protocol = PROT_TELNET;
349 while (*p && *p != ':' && *p != '/')
358 strncpy(cfg.host, q, sizeof(cfg.host) - 1);
359 cfg.host[sizeof(cfg.host) - 1] = '\0';
363 * Before we process the [user@]host string, we
364 * first check for the presence of a protocol
365 * prefix (a protocol name followed by ",").
370 for (i = 0; backends[i].backend != NULL; i++) {
371 j = strlen(backends[i].name);
373 !memcmp(backends[i].name, p, j)) {
374 default_protocol = cfg.protocol =
375 backends[i].protocol;
377 backends[i].backend->default_port;
385 * Three cases. Either (a) there's a nonzero
386 * length string followed by an @, in which
387 * case that's user and the remainder is host.
388 * Or (b) there's only one string, not counting
389 * a potential initial @, and it exists in the
390 * saved-sessions database. Or (c) only one
391 * string and it _doesn't_ exist in the
396 p++, r = NULL; /* discount initial @ */
402 do_defaults(p, &cfg2);
403 if (cfg2.host[0] == '\0') {
404 /* No settings for this host; use defaults */
405 strncpy(cfg.host, p, sizeof(cfg.host) - 1);
406 cfg.host[sizeof(cfg.host) - 1] = '\0';
407 cfg.port = default_port;
410 cfg.remote_cmd_ptr = cfg.remote_cmd;
414 strncpy(cfg.username, p, sizeof(cfg.username) - 1);
415 cfg.username[sizeof(cfg.username) - 1] = '\0';
416 strncpy(cfg.host, r, sizeof(cfg.host) - 1);
417 cfg.host[sizeof(cfg.host) - 1] = '\0';
418 cfg.port = default_port;
424 cmdlen = cmdsize = 0;
429 if (cmdlen >= cmdsize) {
430 cmdsize = cmdlen + 512;
431 command = srealloc(command, cmdsize);
433 command[cmdlen++]=*p++;
435 if (cmdlen >= cmdsize) {
436 cmdsize = cmdlen + 512;
437 command = srealloc(command, cmdsize);
439 command[cmdlen++]=' '; /* always add trailing space */
440 if (--argc) p = *++argv;
442 if (cmdlen) command[--cmdlen]='\0';
443 /* change trailing blank to NUL */
444 cfg.remote_cmd_ptr = command;
445 cfg.remote_cmd_ptr2 = NULL;
446 cfg.nopty = TRUE; /* command => no terminal */
448 break; /* done with cmdline */
461 * Trim leading whitespace off the hostname if it's there.
464 int space = strspn(cfg.host, " \t");
465 memmove(cfg.host, cfg.host+space, 1+strlen(cfg.host)-space);
468 /* See if host is of the form user@host */
469 if (cfg.host[0] != '\0') {
470 char *atsign = strchr(cfg.host, '@');
471 /* Make sure we're not overflowing the user field */
473 if (atsign - cfg.host < sizeof cfg.username) {
474 strncpy(cfg.username, cfg.host, atsign - cfg.host);
475 cfg.username[atsign - cfg.host] = '\0';
477 memmove(cfg.host, atsign + 1, 1 + strlen(atsign + 1));
482 * Perform command-line overrides on session configuration.
484 cmdline_run_saved(&cfg);
487 * Trim a colon suffix off the hostname if it's there.
489 cfg.host[strcspn(cfg.host, ":")] = '\0';
492 * Remove any remaining whitespace from the hostname.
496 while (cfg.host[p2] != '\0') {
497 if (cfg.host[p2] != ' ' && cfg.host[p2] != '\t') {
498 cfg.host[p1] = cfg.host[p2];
506 if (!*cfg.remote_cmd_ptr)
507 flags |= FLAG_INTERACTIVE;
510 * Select protocol. This is farmed out into a table in a
511 * separate file to enable an ssh-free variant.
516 for (i = 0; backends[i].backend != NULL; i++)
517 if (backends[i].protocol == cfg.protocol) {
518 back = backends[i].backend;
523 "Internal fault: Unsupported protocol found\n");
531 if (portnumber != -1)
532 cfg.port = portnumber;
535 * Set up the pipe we'll use to tell us about SIGWINCH.
537 if (pipe(signalpipe) < 0) {
541 putty_signal(SIGWINCH, sigwinch);
546 * Start up the connection.
548 logctx = log_init(NULL, &cfg);
552 /* nodelay is only useful if stdin is a terminal device */
553 int nodelay = cfg.tcp_nodelay && isatty(0);
555 error = back->init(NULL, &backhandle, &cfg, cfg.host, cfg.port,
558 fprintf(stderr, "Unable to open connection:\n%s\n", error);
561 back->provide_logctx(backhandle, logctx);
562 ldisc = ldisc_create(&cfg, NULL, back, backhandle, NULL);
568 * Set up the initial console mode. We don't care if this call
569 * fails, because we know we aren't necessarily running in a
572 tcgetattr(0, &orig_termios);
573 atexit(cleanup_termios);
574 ldisc_update(NULL, 1, 1);
578 fd_set rset, wset, xset;
588 FD_SET_MAX(signalpipe[0], maxfd, rset);
590 if (connopen && !sending &&
591 back->socket(backhandle) != NULL &&
592 back->sendok(backhandle) &&
593 back->sendbuffer(backhandle) < MAX_STDIN_BACKLOG) {
594 /* If we're OK to send, then try to read from stdin. */
595 FD_SET_MAX(0, maxfd, rset);
598 if (bufchain_size(&stdout_data) > 0) {
599 /* If we have data for stdout, try to write to stdout. */
600 FD_SET_MAX(1, maxfd, wset);
603 if (bufchain_size(&stderr_data) > 0) {
604 /* If we have data for stderr, try to write to stderr. */
605 FD_SET_MAX(2, maxfd, wset);
608 /* Count the currently active sockets. */
610 for (socket = first_socket(&socketstate, &rwx); socket >= 0;
611 socket = next_socket(&socketstate, &rwx)) i++;
613 /* Expand the sklist buffer if necessary. */
616 sklist = srealloc(sklist, sksize * sizeof(*sklist));
620 * Add all currently open sockets to the select sets, and
621 * store them in sklist as well.
624 for (socket = first_socket(&socketstate, &rwx); socket >= 0;
625 socket = next_socket(&socketstate, &rwx)) {
626 sklist[skcount++] = socket;
628 FD_SET_MAX(socket, maxfd, rset);
630 FD_SET_MAX(socket, maxfd, wset);
632 FD_SET_MAX(socket, maxfd, xset);
636 ret = select(maxfd, &rset, &wset, &xset, NULL);
637 } while (ret < 0 && errno == EINTR);
644 for (i = 0; i < skcount; i++) {
647 * We must process exceptional notifications before
648 * ordinary readability ones, or we may go straight
649 * past the urgent marker.
651 if (FD_ISSET(socket, &xset))
652 select_result(socket, 4);
653 if (FD_ISSET(socket, &rset))
654 select_result(socket, 1);
655 if (FD_ISSET(socket, &wset))
656 select_result(socket, 2);
659 if (FD_ISSET(signalpipe[0], &rset)) {
662 read(signalpipe[0], c, 1); /* ignore its value; it'll be `x' */
663 if (ioctl(0, TIOCGWINSZ, (void *)&size) >= 0)
664 back->size(backhandle, size.ws_col, size.ws_row);
667 if (FD_ISSET(0, &rset)) {
671 if (connopen && back->socket(backhandle) != NULL) {
672 ret = read(0, buf, sizeof(buf));
674 perror("stdin: read");
676 } else if (ret == 0) {
677 back->special(backhandle, TS_EOF);
678 sending = FALSE; /* send nothing further after this */
680 back->send(backhandle, buf, ret);
685 if (FD_ISSET(1, &wset)) {
689 if (FD_ISSET(2, &wset)) {
693 if ((!connopen || back->socket(backhandle) == NULL) &&
694 bufchain_size(&stdout_data) == 0 &&
695 bufchain_size(&stderr_data) == 0)
696 break; /* we closed the connection */
698 exitcode = back->exitcode(backhandle);
700 fprintf(stderr, "Remote process exit code unavailable\n");
701 exitcode = 1; /* this is an error condition */
703 cleanup_exit(exitcode);
704 return exitcode; /* shouldn't happen, but placates gcc */