2 * PLink - a command-line (stdin/stdout) variant of PuTTY.
13 #include <sys/ioctl.h>
15 /* More helpful version of the FD_SET macro, to also handle maxfd. */
16 #define FD_SET_MAX(fd, max, set) do { \
18 if (max < fd + 1) max = fd + 1; \
21 #define PUTTY_DO_GLOBALS /* actually _define_ globals */
26 #define MAX_STDIN_BACKLOG 4096
28 void fatalbox(char *p, ...)
31 fprintf(stderr, "FATAL ERROR: ");
33 vfprintf(stderr, p, ap);
38 void modalfatalbox(char *p, ...)
41 fprintf(stderr, "FATAL ERROR: ");
43 vfprintf(stderr, p, ap);
48 void connection_fatal(void *frontend, char *p, ...)
51 fprintf(stderr, "FATAL ERROR: ");
53 vfprintf(stderr, p, ap);
58 void cmdline_error(char *p, ...)
61 fprintf(stderr, "plink: ");
63 vfprintf(stderr, p, ap);
69 struct termios orig_termios;
72 static void *backhandle;
75 * Default settings that are specific to pterm.
77 char *platform_default_s(char *name)
79 if (!strcmp(name, "X11Display"))
80 return getenv("DISPLAY");
81 if (!strcmp(name, "TermType"))
82 return getenv("TERM");
83 if (!strcmp(name, "UserName")) {
85 * Remote login username will default to the local username.
89 char *user, *ret = NULL;
92 * First, find who we think we are using getlogin. If this
93 * agrees with our uid, we'll go along with it. This should
94 * allow sharing of uids between several login names whilst
95 * coping correctly with people who have su'ed.
103 if (p && p->pw_uid == uid) {
105 * The result of getlogin() really does correspond to
111 * If that didn't work, for whatever reason, we'll do
112 * the simpler version: look up our uid in the password
113 * file and map it straight to a name.
125 int platform_default_i(char *name, int def)
127 if (!strcmp(name, "TermWidth") ||
128 !strcmp(name, "TermHeight")) {
130 if (ioctl(0, TIOCGWINSZ, (void *)&size) >= 0)
131 return (!strcmp(name, "TermWidth") ? size.ws_col : size.ws_row);
136 char *x_get_default(char *key)
138 return NULL; /* this is a stub */
140 int term_ldisc(Terminal *term, int mode)
144 void ldisc_update(void *frontend, int echo, int edit)
146 /* Update stdin read mode to reflect changes in line discipline. */
152 mode.c_lflag |= ECHO;
154 mode.c_lflag &= ~ECHO;
157 mode.c_lflag |= ISIG | ICANON;
159 mode.c_lflag &= ~(ISIG | ICANON);
161 tcsetattr(0, TCSANOW, &mode);
164 void cleanup_termios(void)
166 tcsetattr(0, TCSANOW, &orig_termios);
169 bufchain stdout_data, stderr_data;
171 void try_output(int is_stderr)
173 bufchain *chain = (is_stderr ? &stderr_data : &stdout_data);
174 int fd = (is_stderr ? 2 : 1);
178 if (bufchain_size(chain) == 0)
181 bufchain_prefix(chain, &senddata, &sendlen);
182 ret = write(fd, senddata, sendlen);
184 bufchain_consume(chain, ret);
186 perror(is_stderr ? "stderr: write" : "stdout: write");
191 int from_backend(void *frontend_handle, int is_stderr, char *data, int len)
198 bufchain_add(&stderr_data, data, len);
201 bufchain_add(&stdout_data, data, len);
205 osize = bufchain_size(&stdout_data);
206 esize = bufchain_size(&stderr_data);
208 return osize + esize;
212 * Short description of parameters.
214 static void usage(void)
216 printf("PuTTY Link: command-line connection utility\n");
218 printf("Usage: plink [options] [user@]host [command]\n");
219 printf(" (\"host\" can also be a PuTTY saved session name)\n");
220 printf("Options:\n");
221 printf(" -v show verbose messages\n");
222 printf(" -load sessname Load settings from saved session\n");
223 printf(" -ssh -telnet -rlogin -raw\n");
224 printf(" force use of a particular protocol (default SSH)\n");
225 printf(" -P port connect to specified port\n");
226 printf(" -l user connect with specified username\n");
227 printf(" -m file read remote command(s) from file\n");
228 printf(" -batch disable all interactive prompts\n");
229 printf("The following options only apply to SSH connections:\n");
230 printf(" -pw passw login with specified password\n");
231 printf(" -L listen-port:host:port Forward local port to "
233 printf(" -R listen-port:host:port Forward remote port to"
235 printf(" -X -x enable / disable X11 forwarding\n");
236 printf(" -A -a enable / disable agent forwarding\n");
237 printf(" -t -T enable / disable pty allocation\n");
238 printf(" -1 -2 force use of particular protocol version\n");
239 printf(" -C enable compression\n");
240 printf(" -i key private key file for authentication\n");
244 int main(int argc, char **argv)
250 int i, skcount, sksize, socketstate;
256 ssh_get_line = console_get_line;
259 skcount = sksize = 0;
261 * Initialise port and protocol to sensible defaults. (These
262 * will be overridden by more or less anything.)
264 default_protocol = PROT_SSH;
269 * Process the command line.
271 do_defaults(NULL, &cfg);
272 default_protocol = cfg.protocol;
273 default_port = cfg.port;
277 * Override the default protocol if PLINK_PROTOCOL is set.
279 char *p = getenv("PLINK_PROTOCOL");
282 for (i = 0; backends[i].backend != NULL; i++) {
283 if (!strcmp(backends[i].name, p)) {
284 default_protocol = cfg.protocol = backends[i].protocol;
285 default_port = cfg.port =
286 backends[i].backend->default_port;
295 int ret = cmdline_process_param(p, (argc > 1 ? argv[1] : NULL), 1);
298 "plink: option \"%s\" requires an argument\n", p);
300 } else if (ret == 2) {
302 } else if (ret == 1) {
304 } else if (!strcmp(p, "-batch")) {
305 console_batch_mode = 1;
306 } else if (!strcmp(p, "-o")) {
309 "plink: option \"-o\" requires an argument\n");
313 provide_xrm_string(*++argv);
316 fprintf(stderr, "plink: unknown option \"%s\"\n", p);
323 do_defaults(NULL, &cfg);
326 * If the hostname starts with "telnet:", set the
327 * protocol to Telnet and process the string as a
330 if (!strncmp(q, "telnet:", 7)) {
334 if (q[0] == '/' && q[1] == '/')
336 cfg.protocol = PROT_TELNET;
338 while (*p && *p != ':' && *p != '/')
347 strncpy(cfg.host, q, sizeof(cfg.host) - 1);
348 cfg.host[sizeof(cfg.host) - 1] = '\0';
352 * Before we process the [user@]host string, we
353 * first check for the presence of a protocol
354 * prefix (a protocol name followed by ",").
359 for (i = 0; backends[i].backend != NULL; i++) {
360 j = strlen(backends[i].name);
362 !memcmp(backends[i].name, p, j)) {
363 default_protocol = cfg.protocol =
364 backends[i].protocol;
366 backends[i].backend->default_port;
374 * Three cases. Either (a) there's a nonzero
375 * length string followed by an @, in which
376 * case that's user and the remainder is host.
377 * Or (b) there's only one string, not counting
378 * a potential initial @, and it exists in the
379 * saved-sessions database. Or (c) only one
380 * string and it _doesn't_ exist in the
385 p++, r = NULL; /* discount initial @ */
391 do_defaults(p, &cfg2);
392 if (cfg2.host[0] == '\0') {
393 /* No settings for this host; use defaults */
394 strncpy(cfg.host, p, sizeof(cfg.host) - 1);
395 cfg.host[sizeof(cfg.host) - 1] = '\0';
396 cfg.port = default_port;
399 cfg.remote_cmd_ptr = cfg.remote_cmd;
403 strncpy(cfg.username, p, sizeof(cfg.username) - 1);
404 cfg.username[sizeof(cfg.username) - 1] = '\0';
405 strncpy(cfg.host, r, sizeof(cfg.host) - 1);
406 cfg.host[sizeof(cfg.host) - 1] = '\0';
407 cfg.port = default_port;
413 cmdlen = cmdsize = 0;
418 if (cmdlen >= cmdsize) {
419 cmdsize = cmdlen + 512;
420 command = srealloc(command, cmdsize);
422 command[cmdlen++]=*p++;
424 if (cmdlen >= cmdsize) {
425 cmdsize = cmdlen + 512;
426 command = srealloc(command, cmdsize);
428 command[cmdlen++]=' '; /* always add trailing space */
429 if (--argc) p = *++argv;
431 if (cmdlen) command[--cmdlen]='\0';
432 /* change trailing blank to NUL */
433 cfg.remote_cmd_ptr = command;
434 cfg.remote_cmd_ptr2 = NULL;
435 cfg.nopty = TRUE; /* command => no terminal */
437 break; /* done with cmdline */
450 * Trim leading whitespace off the hostname if it's there.
453 int space = strspn(cfg.host, " \t");
454 memmove(cfg.host, cfg.host+space, 1+strlen(cfg.host)-space);
457 /* See if host is of the form user@host */
458 if (cfg.host[0] != '\0') {
459 char *atsign = strchr(cfg.host, '@');
460 /* Make sure we're not overflowing the user field */
462 if (atsign - cfg.host < sizeof cfg.username) {
463 strncpy(cfg.username, cfg.host, atsign - cfg.host);
464 cfg.username[atsign - cfg.host] = '\0';
466 memmove(cfg.host, atsign + 1, 1 + strlen(atsign + 1));
471 * Perform command-line overrides on session configuration.
476 * Trim a colon suffix off the hostname if it's there.
478 cfg.host[strcspn(cfg.host, ":")] = '\0';
481 * Remove any remaining whitespace from the hostname.
485 while (cfg.host[p2] != '\0') {
486 if (cfg.host[p2] != ' ' && cfg.host[p2] != '\t') {
487 cfg.host[p1] = cfg.host[p2];
495 if (!*cfg.remote_cmd_ptr)
496 flags |= FLAG_INTERACTIVE;
499 * Select protocol. This is farmed out into a table in a
500 * separate file to enable an ssh-free variant.
505 for (i = 0; backends[i].backend != NULL; i++)
506 if (backends[i].protocol == cfg.protocol) {
507 back = backends[i].backend;
512 "Internal fault: Unsupported protocol found\n");
520 if (portnumber != -1)
521 cfg.port = portnumber;
526 * Start up the connection.
528 logctx = log_init(NULL);
532 /* nodelay is only useful if stdin is a terminal device */
533 int nodelay = cfg.tcp_nodelay && isatty(0);
535 error = back->init(NULL, &backhandle, cfg.host, cfg.port,
538 fprintf(stderr, "Unable to open connection:\n%s\n", error);
541 back->provide_logctx(backhandle, logctx);
542 ldisc = ldisc_create(&cfg, NULL, back, backhandle, NULL);
548 * Set up the initial console mode. We don't care if this call
549 * fails, because we know we aren't necessarily running in a
552 tcgetattr(0, &orig_termios);
553 atexit(cleanup_termios);
554 ldisc_update(NULL, 1, 1);
558 fd_set rset, wset, xset;
568 if (connopen && !sending &&
569 back->socket(backhandle) != NULL &&
570 back->sendok(backhandle) &&
571 back->sendbuffer(backhandle) < MAX_STDIN_BACKLOG) {
572 /* If we're OK to send, then try to read from stdin. */
573 FD_SET_MAX(0, maxfd, rset);
576 if (bufchain_size(&stdout_data) > 0) {
577 /* If we have data for stdout, try to write to stdout. */
578 FD_SET_MAX(1, maxfd, wset);
581 if (bufchain_size(&stderr_data) > 0) {
582 /* If we have data for stderr, try to write to stderr. */
583 FD_SET_MAX(2, maxfd, wset);
586 /* Count the currently active sockets. */
588 for (socket = first_socket(&socketstate, &rwx); socket >= 0;
589 socket = next_socket(&socketstate, &rwx)) i++;
591 /* Expand the sklist buffer if necessary. */
594 sklist = srealloc(sklist, sksize * sizeof(*sklist));
598 * Add all currently open sockets to the select sets, and
599 * store them in sklist as well.
602 for (socket = first_socket(&socketstate, &rwx); socket >= 0;
603 socket = next_socket(&socketstate, &rwx)) {
604 sklist[skcount++] = socket;
606 FD_SET_MAX(socket, maxfd, rset);
608 FD_SET_MAX(socket, maxfd, wset);
610 FD_SET_MAX(socket, maxfd, xset);
613 ret = select(maxfd, &rset, &wset, &xset, NULL);
620 for (i = 0; i < skcount; i++) {
623 * We must process exceptional notifications before
624 * ordinary readability ones, or we may go straight
625 * past the urgent marker.
627 if (FD_ISSET(socket, &xset))
628 select_result(socket, 4);
629 if (FD_ISSET(socket, &rset))
630 select_result(socket, 1);
631 if (FD_ISSET(socket, &wset))
632 select_result(socket, 2);
635 if (FD_ISSET(0, &rset)) {
639 if (connopen && back->socket(backhandle) != NULL) {
640 ret = read(0, buf, sizeof(buf));
642 perror("stdin: read");
644 } else if (ret == 0) {
645 back->special(backhandle, TS_EOF);
646 sending = FALSE; /* send nothing further after this */
648 back->send(backhandle, buf, ret);
653 if (FD_ISSET(1, &wset)) {
657 if (FD_ISSET(2, &wset)) {
661 if ((!connopen || back->socket(backhandle) == NULL) &&
662 bufchain_size(&stdout_data) == 0 &&
663 bufchain_size(&stderr_data) == 0)
664 break; /* we closed the connection */
666 exitcode = back->exitcode(backhandle);
668 fprintf(stderr, "Remote process exit code unavailable\n");
669 exitcode = 1; /* this is an error condition */
671 cleanup_exit(exitcode);
672 return exitcode; /* shouldn't happen, but placates gcc */