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, "X11Display"))
77 return getenv("DISPLAY");
78 if (!strcmp(name, "TermType"))
79 return getenv("TERM");
80 if (!strcmp(name, "UserName")) {
82 * Remote login username will default to the local username.
86 char *user, *ret = NULL;
89 * First, find who we think we are using getlogin. If this
90 * agrees with our uid, we'll go along with it. This should
91 * allow sharing of uids between several login names whilst
92 * coping correctly with people who have su'ed.
100 if (p && p->pw_uid == uid) {
102 * The result of getlogin() really does correspond to
108 * If that didn't work, for whatever reason, we'll do
109 * the simpler version: look up our uid in the password
110 * file and map it straight to a name.
122 int platform_default_i(const char *name, int def)
124 if (!strcmp(name, "TermWidth") ||
125 !strcmp(name, "TermHeight")) {
127 if (ioctl(0, TIOCGWINSZ, (void *)&size) >= 0)
128 return (!strcmp(name, "TermWidth") ? size.ws_col : size.ws_row);
133 FontSpec platform_default_fontspec(const char *name)
140 Filename platform_default_filename(const char *name)
143 if (!strcmp(name, "LogFileName"))
144 strcpy(ret.path, "putty.log");
150 char *x_get_default(const char *key)
152 return NULL; /* this is a stub */
154 int term_ldisc(Terminal *term, int mode)
158 void ldisc_update(void *frontend, int echo, int edit)
160 /* Update stdin read mode to reflect changes in line discipline. */
166 mode.c_lflag |= ECHO;
168 mode.c_lflag &= ~ECHO;
171 mode.c_lflag |= ISIG | ICANON;
173 mode.c_lflag &= ~(ISIG | ICANON);
175 tcsetattr(0, TCSANOW, &mode);
178 void cleanup_termios(void)
180 tcsetattr(0, TCSANOW, &orig_termios);
183 bufchain stdout_data, stderr_data;
185 void try_output(int is_stderr)
187 bufchain *chain = (is_stderr ? &stderr_data : &stdout_data);
188 int fd = (is_stderr ? 2 : 1);
192 if (bufchain_size(chain) == 0)
195 bufchain_prefix(chain, &senddata, &sendlen);
196 ret = write(fd, senddata, sendlen);
198 bufchain_consume(chain, ret);
200 perror(is_stderr ? "stderr: write" : "stdout: write");
205 int from_backend(void *frontend_handle, int is_stderr,
206 const char *data, int len)
213 bufchain_add(&stderr_data, data, len);
216 bufchain_add(&stdout_data, data, len);
220 osize = bufchain_size(&stdout_data);
221 esize = bufchain_size(&stderr_data);
223 return osize + esize;
228 void sigwinch(int signum)
230 write(signalpipe[1], "x", 1);
234 * In Plink our selects are synchronous, so these functions are
237 int uxsel_input_add(int fd, int rwx) { return 0; }
238 void uxsel_input_remove(int id) { }
241 * Short description of parameters.
243 static void usage(void)
245 printf("PuTTY Link: command-line connection utility\n");
247 printf("Usage: plink [options] [user@]host [command]\n");
248 printf(" (\"host\" can also be a PuTTY saved session name)\n");
249 printf("Options:\n");
250 printf(" -v show verbose messages\n");
251 printf(" -load sessname Load settings from saved session\n");
252 printf(" -ssh -telnet -rlogin -raw\n");
253 printf(" force use of a particular protocol (default SSH)\n");
254 printf(" -P port connect to specified port\n");
255 printf(" -l user connect with specified username\n");
256 printf(" -m file read remote command(s) from file\n");
257 printf(" -batch disable all interactive prompts\n");
258 printf("The following options only apply to SSH connections:\n");
259 printf(" -pw passw login with specified password\n");
260 printf(" -D listen-port Dynamic SOCKS-based port forwarding\n");
261 printf(" -L listen-port:host:port Forward local port to "
263 printf(" -R listen-port:host:port Forward remote port to"
265 printf(" -X -x enable / disable X11 forwarding\n");
266 printf(" -A -a enable / disable agent forwarding\n");
267 printf(" -t -T enable / disable pty allocation\n");
268 printf(" -1 -2 force use of particular protocol version\n");
269 printf(" -C enable compression\n");
270 printf(" -i key private key file for authentication\n");
274 int main(int argc, char **argv)
280 int i, fdcount, fdsize, fdstate;
284 void *ldisc, *logctx;
286 ssh_get_line = console_get_line;
289 fdcount = fdsize = 0;
291 * Initialise port and protocol to sensible defaults. (These
292 * will be overridden by more or less anything.)
294 default_protocol = PROT_SSH;
299 * Process the command line.
301 do_defaults(NULL, &cfg);
302 default_protocol = cfg.protocol;
303 default_port = cfg.port;
307 * Override the default protocol if PLINK_PROTOCOL is set.
309 char *p = getenv("PLINK_PROTOCOL");
312 for (i = 0; backends[i].backend != NULL; i++) {
313 if (!strcmp(backends[i].name, p)) {
314 default_protocol = cfg.protocol = backends[i].protocol;
315 default_port = cfg.port =
316 backends[i].backend->default_port;
325 int ret = cmdline_process_param(p, (argc > 1 ? argv[1] : NULL),
329 "plink: option \"%s\" requires an argument\n", p);
331 } else if (ret == 2) {
333 } else if (ret == 1) {
335 } else if (!strcmp(p, "-batch")) {
336 console_batch_mode = 1;
337 } else if (!strcmp(p, "-o")) {
340 "plink: option \"-o\" requires an argument\n");
344 provide_xrm_string(*++argv);
347 fprintf(stderr, "plink: unknown option \"%s\"\n", p);
354 do_defaults(NULL, &cfg);
357 * If the hostname starts with "telnet:", set the
358 * protocol to Telnet and process the string as a
361 if (!strncmp(q, "telnet:", 7)) {
365 if (q[0] == '/' && q[1] == '/')
367 cfg.protocol = PROT_TELNET;
369 while (*p && *p != ':' && *p != '/')
378 strncpy(cfg.host, q, sizeof(cfg.host) - 1);
379 cfg.host[sizeof(cfg.host) - 1] = '\0';
383 * Before we process the [user@]host string, we
384 * first check for the presence of a protocol
385 * prefix (a protocol name followed by ",").
390 for (i = 0; backends[i].backend != NULL; i++) {
391 j = strlen(backends[i].name);
393 !memcmp(backends[i].name, p, j)) {
394 default_protocol = cfg.protocol =
395 backends[i].protocol;
397 backends[i].backend->default_port;
405 * Three cases. Either (a) there's a nonzero
406 * length string followed by an @, in which
407 * case that's user and the remainder is host.
408 * Or (b) there's only one string, not counting
409 * a potential initial @, and it exists in the
410 * saved-sessions database. Or (c) only one
411 * string and it _doesn't_ exist in the
416 p++, r = NULL; /* discount initial @ */
422 do_defaults(p, &cfg2);
423 if (cfg2.host[0] == '\0') {
424 /* No settings for this host; use defaults */
425 strncpy(cfg.host, p, sizeof(cfg.host) - 1);
426 cfg.host[sizeof(cfg.host) - 1] = '\0';
427 cfg.port = default_port;
430 cfg.remote_cmd_ptr = cfg.remote_cmd;
434 strncpy(cfg.username, p, sizeof(cfg.username) - 1);
435 cfg.username[sizeof(cfg.username) - 1] = '\0';
436 strncpy(cfg.host, r, sizeof(cfg.host) - 1);
437 cfg.host[sizeof(cfg.host) - 1] = '\0';
438 cfg.port = default_port;
444 cmdlen = cmdsize = 0;
449 if (cmdlen >= cmdsize) {
450 cmdsize = cmdlen + 512;
451 command = sresize(command, cmdsize, char);
453 command[cmdlen++]=*p++;
455 if (cmdlen >= cmdsize) {
456 cmdsize = cmdlen + 512;
457 command = sresize(command, cmdsize, char);
459 command[cmdlen++]=' '; /* always add trailing space */
460 if (--argc) p = *++argv;
462 if (cmdlen) command[--cmdlen]='\0';
463 /* change trailing blank to NUL */
464 cfg.remote_cmd_ptr = command;
465 cfg.remote_cmd_ptr2 = NULL;
466 cfg.nopty = TRUE; /* command => no terminal */
468 break; /* done with cmdline */
481 * Trim leading whitespace off the hostname if it's there.
484 int space = strspn(cfg.host, " \t");
485 memmove(cfg.host, cfg.host+space, 1+strlen(cfg.host)-space);
488 /* See if host is of the form user@host */
489 if (cfg.host[0] != '\0') {
490 char *atsign = strchr(cfg.host, '@');
491 /* Make sure we're not overflowing the user field */
493 if (atsign - cfg.host < sizeof cfg.username) {
494 strncpy(cfg.username, cfg.host, atsign - cfg.host);
495 cfg.username[atsign - cfg.host] = '\0';
497 memmove(cfg.host, atsign + 1, 1 + strlen(atsign + 1));
502 * Perform command-line overrides on session configuration.
504 cmdline_run_saved(&cfg);
507 * Trim a colon suffix off the hostname if it's there.
509 cfg.host[strcspn(cfg.host, ":")] = '\0';
512 * Remove any remaining whitespace from the hostname.
516 while (cfg.host[p2] != '\0') {
517 if (cfg.host[p2] != ' ' && cfg.host[p2] != '\t') {
518 cfg.host[p1] = cfg.host[p2];
526 if (!*cfg.remote_cmd_ptr)
527 flags |= FLAG_INTERACTIVE;
530 * Select protocol. This is farmed out into a table in a
531 * separate file to enable an ssh-free variant.
536 for (i = 0; backends[i].backend != NULL; i++)
537 if (backends[i].protocol == cfg.protocol) {
538 back = backends[i].backend;
543 "Internal fault: Unsupported protocol found\n");
551 if (portnumber != -1)
552 cfg.port = portnumber;
555 * Set up the pipe we'll use to tell us about SIGWINCH.
557 if (pipe(signalpipe) < 0) {
561 putty_signal(SIGWINCH, sigwinch);
567 * Start up the connection.
569 logctx = log_init(NULL, &cfg);
570 console_provide_logctx(logctx);
574 /* nodelay is only useful if stdin is a terminal device */
575 int nodelay = cfg.tcp_nodelay && isatty(0);
577 error = back->init(NULL, &backhandle, &cfg, cfg.host, cfg.port,
580 fprintf(stderr, "Unable to open connection:\n%s\n", error);
583 back->provide_logctx(backhandle, logctx);
584 ldisc = ldisc_create(&cfg, NULL, back, backhandle, NULL);
590 * Set up the initial console mode. We don't care if this call
591 * fails, because we know we aren't necessarily running in a
594 tcgetattr(0, &orig_termios);
595 atexit(cleanup_termios);
596 ldisc_update(NULL, 1, 1);
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);
658 ret = select(maxfd, &rset, &wset, &xset, NULL);
659 } while (ret < 0 && errno == EINTR);
666 for (i = 0; i < fdcount; i++) {
669 * We must process exceptional notifications before
670 * ordinary readability ones, or we may go straight
671 * past the urgent marker.
673 if (FD_ISSET(fd, &xset))
674 select_result(fd, 4);
675 if (FD_ISSET(fd, &rset))
676 select_result(fd, 1);
677 if (FD_ISSET(fd, &wset))
678 select_result(fd, 2);
681 if (FD_ISSET(signalpipe[0], &rset)) {
684 read(signalpipe[0], c, 1); /* ignore its value; it'll be `x' */
685 if (ioctl(0, TIOCGWINSZ, (void *)&size) >= 0)
686 back->size(backhandle, size.ws_col, size.ws_row);
689 if (FD_ISSET(0, &rset)) {
693 if (connopen && back->socket(backhandle) != NULL) {
694 ret = read(0, buf, sizeof(buf));
696 perror("stdin: read");
698 } else if (ret == 0) {
699 back->special(backhandle, TS_EOF);
700 sending = FALSE; /* send nothing further after this */
702 back->send(backhandle, buf, ret);
707 if (FD_ISSET(1, &wset)) {
711 if (FD_ISSET(2, &wset)) {
715 if ((!connopen || back->socket(backhandle) == NULL) &&
716 bufchain_size(&stdout_data) == 0 &&
717 bufchain_size(&stderr_data) == 0)
718 break; /* we closed the connection */
720 exitcode = back->exitcode(backhandle);
722 fprintf(stderr, "Remote process exit code unavailable\n");
723 exitcode = 1; /* this is an error condition */
725 cleanup_exit(exitcode);
726 return exitcode; /* shouldn't happen, but placates gcc */