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;
77 * Default settings that are specific to pterm.
79 char *platform_default_s(char *name)
81 if (!strcmp(name, "X11Display"))
82 return getenv("DISPLAY");
83 if (!strcmp(name, "TermType"))
84 return getenv("TERM");
85 if (!strcmp(name, "UserName")) {
87 * Remote login username will default to the local username.
91 char *user, *ret = NULL;
94 * First, find who we think we are using getlogin. If this
95 * agrees with our uid, we'll go along with it. This should
96 * allow sharing of uids between several login names whilst
97 * coping correctly with people who have su'ed.
105 if (p && p->pw_uid == uid) {
107 * The result of getlogin() really does correspond to
113 * If that didn't work, for whatever reason, we'll do
114 * the simpler version: look up our uid in the password
115 * file and map it straight to a name.
127 int platform_default_i(char *name, int def)
129 if (!strcmp(name, "TermWidth") ||
130 !strcmp(name, "TermHeight")) {
132 if (ioctl(0, TIOCGWINSZ, (void *)&size) >= 0)
133 return (!strcmp(name, "TermWidth") ? size.ws_col : size.ws_row);
138 char *x_get_default(char *key)
140 return NULL; /* this is a stub */
142 int term_ldisc(Terminal *term, int mode)
146 void ldisc_update(void *frontend, int echo, int edit)
148 /* Update stdin read mode to reflect changes in line discipline. */
154 mode.c_lflag |= ECHO;
156 mode.c_lflag &= ~ECHO;
159 mode.c_lflag |= ISIG | ICANON;
161 mode.c_lflag &= ~(ISIG | ICANON);
163 tcsetattr(0, TCSANOW, &mode);
166 void cleanup_termios(void)
168 tcsetattr(0, TCSANOW, &orig_termios);
171 bufchain stdout_data, stderr_data;
173 void try_output(int is_stderr)
175 bufchain *chain = (is_stderr ? &stderr_data : &stdout_data);
176 int fd = (is_stderr ? 2 : 1);
180 if (bufchain_size(chain) == 0)
183 bufchain_prefix(chain, &senddata, &sendlen);
184 ret = write(fd, senddata, sendlen);
186 bufchain_consume(chain, ret);
188 perror(is_stderr ? "stderr: write" : "stdout: write");
193 int from_backend(void *frontend_handle, int is_stderr, char *data, int len)
200 bufchain_add(&stderr_data, data, len);
203 bufchain_add(&stdout_data, data, len);
207 osize = bufchain_size(&stdout_data);
208 esize = bufchain_size(&stderr_data);
210 return osize + esize;
215 void sigwinch(int signum)
217 write(signalpipe[1], "x", 1);
221 * Short description of parameters.
223 static void usage(void)
225 printf("PuTTY Link: command-line connection utility\n");
227 printf("Usage: plink [options] [user@]host [command]\n");
228 printf(" (\"host\" can also be a PuTTY saved session name)\n");
229 printf("Options:\n");
230 printf(" -v show verbose messages\n");
231 printf(" -load sessname Load settings from saved session\n");
232 printf(" -ssh -telnet -rlogin -raw\n");
233 printf(" force use of a particular protocol (default SSH)\n");
234 printf(" -P port connect to specified port\n");
235 printf(" -l user connect with specified username\n");
236 printf(" -m file read remote command(s) from file\n");
237 printf(" -batch disable all interactive prompts\n");
238 printf("The following options only apply to SSH connections:\n");
239 printf(" -pw passw login with specified password\n");
240 printf(" -L listen-port:host:port Forward local port to "
242 printf(" -R listen-port:host:port Forward remote port to"
244 printf(" -X -x enable / disable X11 forwarding\n");
245 printf(" -A -a enable / disable agent forwarding\n");
246 printf(" -t -T enable / disable pty allocation\n");
247 printf(" -1 -2 force use of particular protocol version\n");
248 printf(" -C enable compression\n");
249 printf(" -i key private key file for authentication\n");
253 int main(int argc, char **argv)
259 int i, skcount, sksize, socketstate;
265 ssh_get_line = console_get_line;
268 skcount = sksize = 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 default_protocol = cfg.protocol;
282 default_port = cfg.port;
286 * Override the default protocol if PLINK_PROTOCOL is set.
288 char *p = getenv("PLINK_PROTOCOL");
291 for (i = 0; backends[i].backend != NULL; i++) {
292 if (!strcmp(backends[i].name, p)) {
293 default_protocol = cfg.protocol = backends[i].protocol;
294 default_port = cfg.port =
295 backends[i].backend->default_port;
304 int ret = cmdline_process_param(p, (argc > 1 ? argv[1] : NULL), 1);
307 "plink: option \"%s\" requires an argument\n", p);
309 } else if (ret == 2) {
311 } else if (ret == 1) {
313 } else if (!strcmp(p, "-batch")) {
314 console_batch_mode = 1;
315 } else if (!strcmp(p, "-o")) {
318 "plink: option \"-o\" requires an argument\n");
322 provide_xrm_string(*++argv);
325 fprintf(stderr, "plink: unknown option \"%s\"\n", p);
332 do_defaults(NULL, &cfg);
335 * If the hostname starts with "telnet:", set the
336 * protocol to Telnet and process the string as a
339 if (!strncmp(q, "telnet:", 7)) {
343 if (q[0] == '/' && q[1] == '/')
345 cfg.protocol = PROT_TELNET;
347 while (*p && *p != ':' && *p != '/')
356 strncpy(cfg.host, q, sizeof(cfg.host) - 1);
357 cfg.host[sizeof(cfg.host) - 1] = '\0';
361 * Before we process the [user@]host string, we
362 * first check for the presence of a protocol
363 * prefix (a protocol name followed by ",").
368 for (i = 0; backends[i].backend != NULL; i++) {
369 j = strlen(backends[i].name);
371 !memcmp(backends[i].name, p, j)) {
372 default_protocol = cfg.protocol =
373 backends[i].protocol;
375 backends[i].backend->default_port;
383 * Three cases. Either (a) there's a nonzero
384 * length string followed by an @, in which
385 * case that's user and the remainder is host.
386 * Or (b) there's only one string, not counting
387 * a potential initial @, and it exists in the
388 * saved-sessions database. Or (c) only one
389 * string and it _doesn't_ exist in the
394 p++, r = NULL; /* discount initial @ */
400 do_defaults(p, &cfg2);
401 if (cfg2.host[0] == '\0') {
402 /* No settings for this host; use defaults */
403 strncpy(cfg.host, p, sizeof(cfg.host) - 1);
404 cfg.host[sizeof(cfg.host) - 1] = '\0';
405 cfg.port = default_port;
408 cfg.remote_cmd_ptr = cfg.remote_cmd;
412 strncpy(cfg.username, p, sizeof(cfg.username) - 1);
413 cfg.username[sizeof(cfg.username) - 1] = '\0';
414 strncpy(cfg.host, r, sizeof(cfg.host) - 1);
415 cfg.host[sizeof(cfg.host) - 1] = '\0';
416 cfg.port = default_port;
422 cmdlen = cmdsize = 0;
427 if (cmdlen >= cmdsize) {
428 cmdsize = cmdlen + 512;
429 command = srealloc(command, cmdsize);
431 command[cmdlen++]=*p++;
433 if (cmdlen >= cmdsize) {
434 cmdsize = cmdlen + 512;
435 command = srealloc(command, cmdsize);
437 command[cmdlen++]=' '; /* always add trailing space */
438 if (--argc) p = *++argv;
440 if (cmdlen) command[--cmdlen]='\0';
441 /* change trailing blank to NUL */
442 cfg.remote_cmd_ptr = command;
443 cfg.remote_cmd_ptr2 = NULL;
444 cfg.nopty = TRUE; /* command => no terminal */
446 break; /* done with cmdline */
459 * Trim leading whitespace off the hostname if it's there.
462 int space = strspn(cfg.host, " \t");
463 memmove(cfg.host, cfg.host+space, 1+strlen(cfg.host)-space);
466 /* See if host is of the form user@host */
467 if (cfg.host[0] != '\0') {
468 char *atsign = strchr(cfg.host, '@');
469 /* Make sure we're not overflowing the user field */
471 if (atsign - cfg.host < sizeof cfg.username) {
472 strncpy(cfg.username, cfg.host, atsign - cfg.host);
473 cfg.username[atsign - cfg.host] = '\0';
475 memmove(cfg.host, atsign + 1, 1 + strlen(atsign + 1));
480 * Perform command-line overrides on session configuration.
485 * Trim a colon suffix off the hostname if it's there.
487 cfg.host[strcspn(cfg.host, ":")] = '\0';
490 * Remove any remaining whitespace from the hostname.
494 while (cfg.host[p2] != '\0') {
495 if (cfg.host[p2] != ' ' && cfg.host[p2] != '\t') {
496 cfg.host[p1] = cfg.host[p2];
504 if (!*cfg.remote_cmd_ptr)
505 flags |= FLAG_INTERACTIVE;
508 * Select protocol. This is farmed out into a table in a
509 * separate file to enable an ssh-free variant.
514 for (i = 0; backends[i].backend != NULL; i++)
515 if (backends[i].protocol == cfg.protocol) {
516 back = backends[i].backend;
521 "Internal fault: Unsupported protocol found\n");
529 if (portnumber != -1)
530 cfg.port = portnumber;
533 * Set up the pipe we'll use to tell us about SIGWINCH.
535 if (pipe(signalpipe) < 0) {
539 putty_signal(SIGWINCH, sigwinch);
544 * Start up the connection.
546 logctx = log_init(NULL);
550 /* nodelay is only useful if stdin is a terminal device */
551 int nodelay = cfg.tcp_nodelay && isatty(0);
553 error = back->init(NULL, &backhandle, cfg.host, cfg.port,
556 fprintf(stderr, "Unable to open connection:\n%s\n", error);
559 back->provide_logctx(backhandle, logctx);
560 ldisc = ldisc_create(&cfg, NULL, back, backhandle, NULL);
566 * Set up the initial console mode. We don't care if this call
567 * fails, because we know we aren't necessarily running in a
570 tcgetattr(0, &orig_termios);
571 atexit(cleanup_termios);
572 ldisc_update(NULL, 1, 1);
576 fd_set rset, wset, xset;
586 FD_SET_MAX(signalpipe[0], maxfd, rset);
588 if (connopen && !sending &&
589 back->socket(backhandle) != NULL &&
590 back->sendok(backhandle) &&
591 back->sendbuffer(backhandle) < MAX_STDIN_BACKLOG) {
592 /* If we're OK to send, then try to read from stdin. */
593 FD_SET_MAX(0, maxfd, rset);
596 if (bufchain_size(&stdout_data) > 0) {
597 /* If we have data for stdout, try to write to stdout. */
598 FD_SET_MAX(1, maxfd, wset);
601 if (bufchain_size(&stderr_data) > 0) {
602 /* If we have data for stderr, try to write to stderr. */
603 FD_SET_MAX(2, maxfd, wset);
606 /* Count the currently active sockets. */
608 for (socket = first_socket(&socketstate, &rwx); socket >= 0;
609 socket = next_socket(&socketstate, &rwx)) i++;
611 /* Expand the sklist buffer if necessary. */
614 sklist = srealloc(sklist, sksize * sizeof(*sklist));
618 * Add all currently open sockets to the select sets, and
619 * store them in sklist as well.
622 for (socket = first_socket(&socketstate, &rwx); socket >= 0;
623 socket = next_socket(&socketstate, &rwx)) {
624 sklist[skcount++] = socket;
626 FD_SET_MAX(socket, maxfd, rset);
628 FD_SET_MAX(socket, maxfd, wset);
630 FD_SET_MAX(socket, maxfd, xset);
634 ret = select(maxfd, &rset, &wset, &xset, NULL);
635 } while (ret < 0 && errno == EINTR);
642 for (i = 0; i < skcount; i++) {
645 * We must process exceptional notifications before
646 * ordinary readability ones, or we may go straight
647 * past the urgent marker.
649 if (FD_ISSET(socket, &xset))
650 select_result(socket, 4);
651 if (FD_ISSET(socket, &rset))
652 select_result(socket, 1);
653 if (FD_ISSET(socket, &wset))
654 select_result(socket, 2);
657 if (FD_ISSET(signalpipe[0], &rset)) {
660 read(signalpipe[0], c, 1); /* ignore its value; it'll be `x' */
661 if (ioctl(0, TIOCGWINSZ, (void *)&size) >= 0)
662 back->size(backhandle, size.ws_col, size.ws_row);
665 if (FD_ISSET(0, &rset)) {
669 if (connopen && back->socket(backhandle) != NULL) {
670 ret = read(0, buf, sizeof(buf));
672 perror("stdin: read");
674 } else if (ret == 0) {
675 back->special(backhandle, TS_EOF);
676 sending = FALSE; /* send nothing further after this */
678 back->send(backhandle, buf, ret);
683 if (FD_ISSET(1, &wset)) {
687 if (FD_ISSET(2, &wset)) {
691 if ((!connopen || back->socket(backhandle) == NULL) &&
692 bufchain_size(&stdout_data) == 0 &&
693 bufchain_size(&stderr_data) == 0)
694 break; /* we closed the connection */
696 exitcode = back->exitcode(backhandle);
698 fprintf(stderr, "Remote process exit code unavailable\n");
699 exitcode = 1; /* this is an error condition */
701 cleanup_exit(exitcode);
702 return exitcode; /* shouldn't happen, but placates gcc */