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 dupstr(getenv("DISPLAY"));
78 if (!strcmp(name, "TermType"))
79 return dupstr(getenv("TERM"));
80 if (!strcmp(name, "UserName"))
81 return get_username();
85 int platform_default_i(const char *name, int def)
87 if (!strcmp(name, "TermWidth") ||
88 !strcmp(name, "TermHeight")) {
90 if (ioctl(0, TIOCGWINSZ, (void *)&size) >= 0)
91 return (!strcmp(name, "TermWidth") ? size.ws_col : size.ws_row);
96 FontSpec platform_default_fontspec(const char *name)
103 Filename platform_default_filename(const char *name)
106 if (!strcmp(name, "LogFileName"))
107 strcpy(ret.path, "putty.log");
113 char *x_get_default(const char *key)
115 return NULL; /* this is a stub */
117 int term_ldisc(Terminal *term, int mode)
121 void ldisc_update(void *frontend, int echo, int edit)
123 /* Update stdin read mode to reflect changes in line discipline. */
129 mode.c_lflag |= ECHO;
131 mode.c_lflag &= ~ECHO;
134 mode.c_lflag |= ISIG | ICANON;
136 mode.c_lflag &= ~(ISIG | ICANON);
138 tcsetattr(0, TCSANOW, &mode);
141 void cleanup_termios(void)
143 tcsetattr(0, TCSANOW, &orig_termios);
146 bufchain stdout_data, stderr_data;
148 void try_output(int is_stderr)
150 bufchain *chain = (is_stderr ? &stderr_data : &stdout_data);
151 int fd = (is_stderr ? 2 : 1);
155 if (bufchain_size(chain) == 0)
158 bufchain_prefix(chain, &senddata, &sendlen);
159 ret = write(fd, senddata, sendlen);
161 bufchain_consume(chain, ret);
163 perror(is_stderr ? "stderr: write" : "stdout: write");
168 int from_backend(void *frontend_handle, int is_stderr,
169 const char *data, int len)
176 bufchain_add(&stderr_data, data, len);
179 bufchain_add(&stdout_data, data, len);
183 osize = bufchain_size(&stdout_data);
184 esize = bufchain_size(&stderr_data);
186 return osize + esize;
191 void sigwinch(int signum)
193 write(signalpipe[1], "x", 1);
197 * In Plink our selects are synchronous, so these functions are
200 int uxsel_input_add(int fd, int rwx) { return 0; }
201 void uxsel_input_remove(int id) { }
204 * Short description of parameters.
206 static void usage(void)
208 printf("PuTTY Link: command-line connection utility\n");
210 printf("Usage: plink [options] [user@]host [command]\n");
211 printf(" (\"host\" can also be a PuTTY saved session name)\n");
212 printf("Options:\n");
213 printf(" -v show verbose messages\n");
214 printf(" -load sessname Load settings from saved session\n");
215 printf(" -ssh -telnet -rlogin -raw\n");
216 printf(" force use of a particular protocol (default SSH)\n");
217 printf(" -P port connect to specified port\n");
218 printf(" -l user connect with specified username\n");
219 printf(" -m file read remote command(s) from file\n");
220 printf(" -batch disable all interactive prompts\n");
221 printf("The following options only apply to SSH connections:\n");
222 printf(" -pw passw login with specified password\n");
223 printf(" -D listen-port Dynamic SOCKS-based port forwarding\n");
224 printf(" -L listen-port:host:port Forward local port to "
226 printf(" -R listen-port:host:port Forward remote port to"
228 printf(" -X -x enable / disable X11 forwarding\n");
229 printf(" -A -a enable / disable agent forwarding\n");
230 printf(" -t -T enable / disable pty allocation\n");
231 printf(" -1 -2 force use of particular protocol version\n");
232 printf(" -C enable compression\n");
233 printf(" -i key private key file for authentication\n");
234 printf(" -s remote command is an SSH subsystem (SSH-2 only)\n");
238 int main(int argc, char **argv)
244 int i, fdcount, fdsize, fdstate;
248 int use_subsystem = 0;
249 void *ldisc, *logctx;
251 ssh_get_line = console_get_line;
254 fdcount = fdsize = 0;
256 * Initialise port and protocol to sensible defaults. (These
257 * will be overridden by more or less anything.)
259 default_protocol = PROT_SSH;
264 * Process the command line.
266 do_defaults(NULL, &cfg);
267 default_protocol = cfg.protocol;
268 default_port = cfg.port;
272 * Override the default protocol if PLINK_PROTOCOL is set.
274 char *p = getenv("PLINK_PROTOCOL");
277 for (i = 0; backends[i].backend != NULL; i++) {
278 if (!strcmp(backends[i].name, p)) {
279 default_protocol = cfg.protocol = backends[i].protocol;
280 default_port = cfg.port =
281 backends[i].backend->default_port;
290 int ret = cmdline_process_param(p, (argc > 1 ? argv[1] : NULL),
294 "plink: option \"%s\" requires an argument\n", p);
296 } else if (ret == 2) {
298 } else if (ret == 1) {
300 } else if (!strcmp(p, "-batch")) {
301 console_batch_mode = 1;
302 } else if (!strcmp(p, "-s")) {
303 /* Save status to write to cfg later. */
305 } else if (!strcmp(p, "-o")) {
308 "plink: option \"-o\" requires an argument\n");
312 provide_xrm_string(*++argv);
315 fprintf(stderr, "plink: unknown option \"%s\"\n", p);
322 do_defaults(NULL, &cfg);
325 * If the hostname starts with "telnet:", set the
326 * protocol to Telnet and process the string as a
329 if (!strncmp(q, "telnet:", 7)) {
333 if (q[0] == '/' && q[1] == '/')
335 cfg.protocol = PROT_TELNET;
337 while (*p && *p != ':' && *p != '/')
346 strncpy(cfg.host, q, sizeof(cfg.host) - 1);
347 cfg.host[sizeof(cfg.host) - 1] = '\0';
351 * Before we process the [user@]host string, we
352 * first check for the presence of a protocol
353 * prefix (a protocol name followed by ",").
358 for (i = 0; backends[i].backend != NULL; i++) {
359 j = strlen(backends[i].name);
361 !memcmp(backends[i].name, p, j)) {
362 default_protocol = cfg.protocol =
363 backends[i].protocol;
365 backends[i].backend->default_port;
373 * Three cases. Either (a) there's a nonzero
374 * length string followed by an @, in which
375 * case that's user and the remainder is host.
376 * Or (b) there's only one string, not counting
377 * a potential initial @, and it exists in the
378 * saved-sessions database. Or (c) only one
379 * string and it _doesn't_ exist in the
384 p++, r = NULL; /* discount initial @ */
390 do_defaults(p, &cfg2);
391 if (cfg2.host[0] == '\0') {
392 /* No settings for this host; use defaults */
393 strncpy(cfg.host, p, sizeof(cfg.host) - 1);
394 cfg.host[sizeof(cfg.host) - 1] = '\0';
395 cfg.port = default_port;
398 cfg.remote_cmd_ptr = cfg.remote_cmd;
402 strncpy(cfg.username, p, sizeof(cfg.username) - 1);
403 cfg.username[sizeof(cfg.username) - 1] = '\0';
404 strncpy(cfg.host, r, sizeof(cfg.host) - 1);
405 cfg.host[sizeof(cfg.host) - 1] = '\0';
406 cfg.port = default_port;
412 cmdlen = cmdsize = 0;
417 if (cmdlen >= cmdsize) {
418 cmdsize = cmdlen + 512;
419 command = sresize(command, cmdsize, char);
421 command[cmdlen++]=*p++;
423 if (cmdlen >= cmdsize) {
424 cmdsize = cmdlen + 512;
425 command = sresize(command, cmdsize, char);
427 command[cmdlen++]=' '; /* always add trailing space */
428 if (--argc) p = *++argv;
430 if (cmdlen) command[--cmdlen]='\0';
431 /* change trailing blank to NUL */
432 cfg.remote_cmd_ptr = command;
433 cfg.remote_cmd_ptr2 = NULL;
434 cfg.nopty = TRUE; /* command => no terminal */
436 break; /* done with cmdline */
449 * Trim leading whitespace off the hostname if it's there.
452 int space = strspn(cfg.host, " \t");
453 memmove(cfg.host, cfg.host+space, 1+strlen(cfg.host)-space);
456 /* See if host is of the form user@host */
457 if (cfg.host[0] != '\0') {
458 char *atsign = strchr(cfg.host, '@');
459 /* Make sure we're not overflowing the user field */
461 if (atsign - cfg.host < sizeof cfg.username) {
462 strncpy(cfg.username, cfg.host, atsign - cfg.host);
463 cfg.username[atsign - cfg.host] = '\0';
465 memmove(cfg.host, atsign + 1, 1 + strlen(atsign + 1));
470 * Perform command-line overrides on session configuration.
472 cmdline_run_saved(&cfg);
475 * Apply subsystem status.
478 cfg.ssh_subsys = TRUE;
481 * Trim a colon suffix off the hostname if it's there.
483 cfg.host[strcspn(cfg.host, ":")] = '\0';
486 * Remove any remaining whitespace from the hostname.
490 while (cfg.host[p2] != '\0') {
491 if (cfg.host[p2] != ' ' && cfg.host[p2] != '\t') {
492 cfg.host[p1] = cfg.host[p2];
500 if (!*cfg.remote_cmd_ptr)
501 flags |= FLAG_INTERACTIVE;
504 * Select protocol. This is farmed out into a table in a
505 * separate file to enable an ssh-free variant.
510 for (i = 0; backends[i].backend != NULL; i++)
511 if (backends[i].protocol == cfg.protocol) {
512 back = backends[i].backend;
517 "Internal fault: Unsupported protocol found\n");
525 if (portnumber != -1)
526 cfg.port = portnumber;
529 * Set up the pipe we'll use to tell us about SIGWINCH.
531 if (pipe(signalpipe) < 0) {
535 putty_signal(SIGWINCH, sigwinch);
541 * Start up the connection.
543 logctx = log_init(NULL, &cfg);
544 console_provide_logctx(logctx);
548 /* nodelay is only useful if stdin is a terminal device */
549 int nodelay = cfg.tcp_nodelay && isatty(0);
551 error = back->init(NULL, &backhandle, &cfg, cfg.host, cfg.port,
554 fprintf(stderr, "Unable to open connection:\n%s\n", error);
557 back->provide_logctx(backhandle, logctx);
558 ldisc = ldisc_create(&cfg, NULL, back, backhandle, NULL);
564 * Set up the initial console mode. We don't care if this call
565 * fails, because we know we aren't necessarily running in a
568 tcgetattr(0, &orig_termios);
569 atexit(cleanup_termios);
570 ldisc_update(NULL, 1, 1);
574 fd_set rset, wset, xset;
584 FD_SET_MAX(signalpipe[0], maxfd, rset);
586 if (connopen && !sending &&
587 back->socket(backhandle) != NULL &&
588 back->sendok(backhandle) &&
589 back->sendbuffer(backhandle) < MAX_STDIN_BACKLOG) {
590 /* If we're OK to send, then try to read from stdin. */
591 FD_SET_MAX(0, maxfd, rset);
594 if (bufchain_size(&stdout_data) > 0) {
595 /* If we have data for stdout, try to write to stdout. */
596 FD_SET_MAX(1, maxfd, wset);
599 if (bufchain_size(&stderr_data) > 0) {
600 /* If we have data for stderr, try to write to stderr. */
601 FD_SET_MAX(2, maxfd, wset);
604 /* Count the currently active fds. */
606 for (fd = first_fd(&fdstate, &rwx); fd >= 0;
607 fd = next_fd(&fdstate, &rwx)) i++;
609 /* Expand the fdlist buffer if necessary. */
612 fdlist = sresize(fdlist, fdsize, int);
616 * Add all currently open fds to the select sets, and store
617 * them in fdlist as well.
620 for (fd = first_fd(&fdstate, &rwx); fd >= 0;
621 fd = next_fd(&fdstate, &rwx)) {
622 fdlist[fdcount++] = fd;
624 FD_SET_MAX(fd, maxfd, rset);
626 FD_SET_MAX(fd, maxfd, wset);
628 FD_SET_MAX(fd, maxfd, xset);
632 ret = select(maxfd, &rset, &wset, &xset, NULL);
633 } while (ret < 0 && errno == EINTR);
640 for (i = 0; i < fdcount; i++) {
643 * We must process exceptional notifications before
644 * ordinary readability ones, or we may go straight
645 * past the urgent marker.
647 if (FD_ISSET(fd, &xset))
648 select_result(fd, 4);
649 if (FD_ISSET(fd, &rset))
650 select_result(fd, 1);
651 if (FD_ISSET(fd, &wset))
652 select_result(fd, 2);
655 if (FD_ISSET(signalpipe[0], &rset)) {
658 read(signalpipe[0], c, 1); /* ignore its value; it'll be `x' */
659 if (ioctl(0, TIOCGWINSZ, (void *)&size) >= 0)
660 back->size(backhandle, size.ws_col, size.ws_row);
663 if (FD_ISSET(0, &rset)) {
667 if (connopen && back->socket(backhandle) != NULL) {
668 ret = read(0, buf, sizeof(buf));
670 perror("stdin: read");
672 } else if (ret == 0) {
673 back->special(backhandle, TS_EOF);
674 sending = FALSE; /* send nothing further after this */
676 back->send(backhandle, buf, ret);
681 if (FD_ISSET(1, &wset)) {
685 if (FD_ISSET(2, &wset)) {
689 if ((!connopen || back->socket(backhandle) == NULL) &&
690 bufchain_size(&stdout_data) == 0 &&
691 bufchain_size(&stderr_data) == 0)
692 break; /* we closed the connection */
694 exitcode = back->exitcode(backhandle);
696 fprintf(stderr, "Remote process exit code unavailable\n");
697 exitcode = 1; /* this is an error condition */
699 cleanup_exit(exitcode);
700 return exitcode; /* shouldn't happen, but placates gcc */