2 * PLink - a Windows command-line (stdin/stdout) variant of PuTTY.
10 #define PUTTY_DO_GLOBALS /* actually _define_ globals */
15 #define WM_AGENT_CALLBACK (WM_APP + 4)
17 struct agent_callback {
18 void (*callback)(void *, void *, int);
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 HANDLE inhandle, outhandle, errhandle;
66 struct handle *stdin_handle, *stdout_handle, *stderr_handle;
67 DWORD orig_console_mode;
73 static void *backhandle;
76 int term_ldisc(Terminal *term, int mode)
80 void ldisc_update(void *frontend, int echo, int edit)
82 /* Update stdin read mode to reflect changes in line discipline. */
85 mode = ENABLE_PROCESSED_INPUT;
87 mode = mode | ENABLE_ECHO_INPUT;
89 mode = mode & ~ENABLE_ECHO_INPUT;
91 mode = mode | ENABLE_LINE_INPUT;
93 mode = mode & ~ENABLE_LINE_INPUT;
94 SetConsoleMode(inhandle, mode);
97 char *get_ttymode(void *frontend, const char *mode) { return NULL; }
99 int from_backend(void *frontend_handle, int is_stderr,
100 const char *data, int len)
103 handle_write(stderr_handle, data, len);
105 handle_write(stdout_handle, data, len);
108 return handle_backlog(stdout_handle) + handle_backlog(stderr_handle);
111 int from_backend_untrusted(void *frontend_handle, const char *data, int len)
114 * No "untrusted" output should get here (the way the code is
115 * currently, it's all diverted by FLAG_STDERR).
117 assert(!"Unexpected call to from_backend_untrusted()");
118 return 0; /* not reached */
121 int get_userpass_input(prompts_t *p, unsigned char *in, int inlen)
124 ret = cmdline_get_passwd_input(p, in, inlen);
126 ret = console_get_userpass_input(p, in, inlen);
130 static DWORD main_thread_id;
132 void agent_schedule_callback(void (*callback)(void *, void *, int),
133 void *callback_ctx, void *data, int len)
135 struct agent_callback *c = snew(struct agent_callback);
136 c->callback = callback;
137 c->callback_ctx = callback_ctx;
140 PostThreadMessage(main_thread_id, WM_AGENT_CALLBACK, 0, (LPARAM)c);
144 * Short description of parameters.
146 static void usage(void)
148 printf("PuTTY Link: command-line connection utility\n");
150 printf("Usage: plink [options] [user@]host [command]\n");
151 printf(" (\"host\" can also be a PuTTY saved session name)\n");
152 printf("Options:\n");
153 printf(" -V print version information and exit\n");
154 printf(" -pgpfp print PGP key fingerprints and exit\n");
155 printf(" -v show verbose messages\n");
156 printf(" -load sessname Load settings from saved session\n");
157 printf(" -ssh -telnet -rlogin -raw\n");
158 printf(" force use of a particular protocol\n");
159 printf(" -P port connect to specified port\n");
160 printf(" -l user connect with specified username\n");
161 printf(" -batch disable all interactive prompts\n");
162 printf("The following options only apply to SSH connections:\n");
163 printf(" -pw passw login with specified password\n");
164 printf(" -D [listen-IP:]listen-port\n");
165 printf(" Dynamic SOCKS-based port forwarding\n");
166 printf(" -L [listen-IP:]listen-port:host:port\n");
167 printf(" Forward local port to remote address\n");
168 printf(" -R [listen-IP:]listen-port:host:port\n");
169 printf(" Forward remote port to local address\n");
170 printf(" -X -x enable / disable X11 forwarding\n");
171 printf(" -A -a enable / disable agent forwarding\n");
172 printf(" -t -T enable / disable pty allocation\n");
173 printf(" -1 -2 force use of particular protocol version\n");
174 printf(" -4 -6 force use of IPv4 or IPv6\n");
175 printf(" -C enable compression\n");
176 printf(" -i key private key file for authentication\n");
177 printf(" -noagent disable use of Pageant\n");
178 printf(" -agent enable use of Pageant\n");
179 printf(" -m file read remote command(s) from file\n");
180 printf(" -s remote command is an SSH subsystem (SSH-2 only)\n");
181 printf(" -N don't start a shell/command (SSH-2 only)\n");
185 static void version(void)
187 printf("plink: %s\n", ver);
191 char *do_select(SOCKET skt, int startup)
195 events = (FD_CONNECT | FD_READ | FD_WRITE |
196 FD_OOB | FD_CLOSE | FD_ACCEPT);
200 if (p_WSAEventSelect(skt, netevent, events) == SOCKET_ERROR) {
201 switch (p_WSAGetLastError()) {
203 return "Network is down";
205 return "WSAEventSelect(): unknown error";
211 int stdin_gotdata(struct handle *h, void *data, int len)
215 * Special case: report read error.
217 fprintf(stderr, "Unable to read from standard input\n");
220 noise_ultralight(len);
221 if (connopen && back->connected(backhandle)) {
223 return back->send(backhandle, data, len);
225 back->special(backhandle, TS_EOF);
232 void stdouterr_sent(struct handle *h, int new_backlog)
234 if (new_backlog < 0) {
236 * Special case: report write error.
238 fprintf(stderr, "Unable to write to standard %s\n",
239 (h == stdout_handle ? "output" : "error"));
242 if (connopen && back->connected(backhandle)) {
243 back->unthrottle(backhandle, (handle_backlog(stdout_handle) +
244 handle_backlog(stderr_handle)));
248 int main(int argc, char **argv)
256 int use_subsystem = 0;
260 skcount = sksize = 0;
262 * Initialise port and protocol to sensible defaults. (These
263 * will be overridden by more or less anything.)
265 default_protocol = PROT_SSH;
270 * Process the command line.
272 do_defaults(NULL, &cfg);
273 loaded_session = FALSE;
274 default_protocol = cfg.protocol;
275 default_port = cfg.port;
279 * Override the default protocol if PLINK_PROTOCOL is set.
281 char *p = getenv("PLINK_PROTOCOL");
284 for (i = 0; backends[i].backend != NULL; i++) {
285 if (!strcmp(backends[i].name, p)) {
286 default_protocol = cfg.protocol = backends[i].protocol;
287 default_port = cfg.port =
288 backends[i].backend->default_port;
297 int ret = cmdline_process_param(p, (argc > 1 ? argv[1] : NULL),
301 "plink: option \"%s\" requires an argument\n", p);
303 } else if (ret == 2) {
305 } else if (ret == 1) {
307 } else if (!strcmp(p, "-batch")) {
308 console_batch_mode = 1;
309 } else if (!strcmp(p, "-s")) {
310 /* Save status to write to cfg later. */
312 } else if (!strcmp(p, "-V")) {
314 } else if (!strcmp(p, "-pgpfp")) {
318 fprintf(stderr, "plink: unknown option \"%s\"\n", p);
322 if (!cfg_launchable(&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';
349 char *r, *user, *host;
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 * A nonzero length string followed by an @ is treated
374 * as a username. (We discount an _initial_ @.) The
375 * rest of the string (or the whole string if no @)
376 * is treated as a session name and/or hostname.
380 p++, r = NULL; /* discount initial @ */
385 user = NULL, host = p;
389 * Now attempt to load a saved session with the
390 * same name as the hostname.
394 do_defaults(host, &cfg2);
395 if (loaded_session || !cfg_launchable(&cfg2)) {
396 /* No settings for this host; use defaults */
397 /* (or session was already loaded with -load) */
398 strncpy(cfg.host, host, sizeof(cfg.host) - 1);
399 cfg.host[sizeof(cfg.host) - 1] = '\0';
400 cfg.port = default_port;
407 /* Patch in specified username. */
408 strncpy(cfg.username, user,
409 sizeof(cfg.username) - 1);
410 cfg.username[sizeof(cfg.username) - 1] = '\0';
417 cmdlen = cmdsize = 0;
422 if (cmdlen >= cmdsize) {
423 cmdsize = cmdlen + 512;
424 command = sresize(command, cmdsize, char);
426 command[cmdlen++]=*p++;
428 if (cmdlen >= cmdsize) {
429 cmdsize = cmdlen + 512;
430 command = sresize(command, cmdsize, char);
432 command[cmdlen++]=' '; /* always add trailing space */
433 if (--argc) p = *++argv;
435 if (cmdlen) command[--cmdlen]='\0';
436 /* change trailing blank to NUL */
437 cfg.remote_cmd_ptr = command;
438 cfg.remote_cmd_ptr2 = NULL;
439 cfg.nopty = TRUE; /* command => no terminal */
441 break; /* done with cmdline */
449 if (!cfg_launchable(&cfg)) {
454 * Trim leading whitespace off the hostname if it's there.
457 int space = strspn(cfg.host, " \t");
458 memmove(cfg.host, cfg.host+space, 1+strlen(cfg.host)-space);
461 /* See if host is of the form user@host */
462 if (cfg_launchable(&cfg)) {
463 char *atsign = strrchr(cfg.host, '@');
464 /* Make sure we're not overflowing the user field */
466 if (atsign - cfg.host < sizeof cfg.username) {
467 strncpy(cfg.username, cfg.host, atsign - cfg.host);
468 cfg.username[atsign - cfg.host] = '\0';
470 memmove(cfg.host, atsign + 1, 1 + strlen(atsign + 1));
475 * Perform command-line overrides on session configuration.
477 cmdline_run_saved(&cfg);
480 * Apply subsystem status.
483 cfg.ssh_subsys = TRUE;
486 * Trim a colon suffix off the hostname if it's there.
488 cfg.host[strcspn(cfg.host, ":")] = '\0';
491 * Remove any remaining whitespace from the hostname.
495 while (cfg.host[p2] != '\0') {
496 if (cfg.host[p2] != ' ' && cfg.host[p2] != '\t') {
497 cfg.host[p1] = cfg.host[p2];
505 if (!cfg.remote_cmd_ptr && !*cfg.remote_cmd)
506 flags |= FLAG_INTERACTIVE;
509 * Select protocol. This is farmed out into a table in a
510 * separate file to enable an ssh-free variant.
515 for (i = 0; backends[i].backend != NULL; i++)
516 if (backends[i].protocol == cfg.protocol) {
517 back = backends[i].backend;
522 "Internal fault: Unsupported protocol found\n");
530 if (portnumber != -1)
531 cfg.port = portnumber;
534 if (p_WSAEventSelect == NULL) {
535 fprintf(stderr, "Plink requires WinSock 2\n");
539 logctx = log_init(NULL, &cfg);
540 console_provide_logctx(logctx);
543 * Start up the connection.
545 netevent = CreateEvent(NULL, FALSE, FALSE, NULL);
549 /* nodelay is only useful if stdin is a character device (console) */
550 int nodelay = cfg.tcp_nodelay &&
551 (GetFileType(GetStdHandle(STD_INPUT_HANDLE)) == FILE_TYPE_CHAR);
553 error = back->init(NULL, &backhandle, &cfg, cfg.host, cfg.port,
554 &realhost, nodelay, cfg.tcp_keepalives);
556 fprintf(stderr, "Unable to open connection:\n%s", error);
559 back->provide_logctx(backhandle, logctx);
564 inhandle = GetStdHandle(STD_INPUT_HANDLE);
565 outhandle = GetStdHandle(STD_OUTPUT_HANDLE);
566 errhandle = GetStdHandle(STD_ERROR_HANDLE);
569 * Turn off ECHO and LINE input modes. We don't care if this
570 * call fails, because we know we aren't necessarily running in
573 GetConsoleMode(inhandle, &orig_console_mode);
574 SetConsoleMode(inhandle, ENABLE_PROCESSED_INPUT);
577 * Pass the output handles to the handle-handling subsystem.
578 * (The input one we leave until we're through the
579 * authentication process.)
581 stdout_handle = handle_output_new(outhandle, stdouterr_sent, NULL, 0);
582 stderr_handle = handle_output_new(errhandle, stdouterr_sent, NULL, 0);
584 main_thread_id = GetCurrentThreadId();
588 now = GETTICKCOUNT();
596 if (!sending && back->sendok(backhandle)) {
597 stdin_handle = handle_input_new(inhandle, stdin_gotdata, NULL,
602 if (run_timers(now, &next)) {
603 ticks = next - GETTICKCOUNT();
604 if (ticks < 0) ticks = 0; /* just in case */
609 handles = handle_get_events(&nhandles);
610 handles = sresize(handles, nhandles+1, HANDLE);
611 handles[nhandles] = netevent;
612 n = MsgWaitForMultipleObjects(nhandles+1, handles, FALSE, ticks,
614 if ((unsigned)(n - WAIT_OBJECT_0) < (unsigned)nhandles) {
615 handle_got_event(handles[n - WAIT_OBJECT_0]);
616 } else if (n == WAIT_OBJECT_0 + nhandles) {
617 WSANETWORKEVENTS things;
619 extern SOCKET first_socket(int *), next_socket(int *);
620 extern int select_result(WPARAM, LPARAM);
624 * We must not call select_result() for any socket
625 * until we have finished enumerating within the tree.
626 * This is because select_result() may close the socket
627 * and modify the tree.
629 /* Count the active sockets. */
631 for (socket = first_socket(&socketstate);
632 socket != INVALID_SOCKET;
633 socket = next_socket(&socketstate)) i++;
635 /* Expand the buffer if necessary. */
638 sklist = sresize(sklist, sksize, SOCKET);
641 /* Retrieve the sockets into sklist. */
643 for (socket = first_socket(&socketstate);
644 socket != INVALID_SOCKET;
645 socket = next_socket(&socketstate)) {
646 sklist[skcount++] = socket;
649 /* Now we're done enumerating; go through the list. */
650 for (i = 0; i < skcount; i++) {
653 wp = (WPARAM) socket;
654 if (!p_WSAEnumNetworkEvents(socket, NULL, &things)) {
655 static const struct { int bit, mask; } eventtypes[] = {
656 {FD_CONNECT_BIT, FD_CONNECT},
657 {FD_READ_BIT, FD_READ},
658 {FD_CLOSE_BIT, FD_CLOSE},
659 {FD_OOB_BIT, FD_OOB},
660 {FD_WRITE_BIT, FD_WRITE},
661 {FD_ACCEPT_BIT, FD_ACCEPT},
665 noise_ultralight(socket);
666 noise_ultralight(things.lNetworkEvents);
668 for (e = 0; e < lenof(eventtypes); e++)
669 if (things.lNetworkEvents & eventtypes[e].mask) {
671 int err = things.iErrorCode[eventtypes[e].bit];
672 lp = WSAMAKESELECTREPLY(eventtypes[e].mask, err);
673 connopen &= select_result(wp, lp);
677 } else if (n == WAIT_OBJECT_0 + nhandles + 1) {
679 while (PeekMessage(&msg, INVALID_HANDLE_VALUE,
680 WM_AGENT_CALLBACK, WM_AGENT_CALLBACK,
682 struct agent_callback *c = (struct agent_callback *)msg.lParam;
683 c->callback(c->callback_ctx, c->data, c->len);
688 if (n == WAIT_TIMEOUT) {
691 now = GETTICKCOUNT();
697 handle_unthrottle(stdin_handle, back->sendbuffer(backhandle));
699 if ((!connopen || !back->connected(backhandle)) &&
700 handle_backlog(stdout_handle) + handle_backlog(stderr_handle) == 0)
701 break; /* we closed the connection */
703 exitcode = back->exitcode(backhandle);
705 fprintf(stderr, "Remote process exit code unavailable\n");
706 exitcode = 1; /* this is an error condition */
708 cleanup_exit(exitcode);
709 return 0; /* placate compiler warning */