2 * PLink - a Windows command-line (stdin/stdout) variant of PuTTY.
10 #define PUTTY_DO_GLOBALS /* actually _define_ globals */
16 #define WM_AGENT_CALLBACK (WM_APP + 4)
18 struct agent_callback {
19 void (*callback)(void *, void *, int);
25 void fatalbox(const char *p, ...)
28 fprintf(stderr, "FATAL ERROR: ");
30 vfprintf(stderr, p, ap);
39 void modalfatalbox(const char *p, ...)
42 fprintf(stderr, "FATAL ERROR: ");
44 vfprintf(stderr, p, ap);
53 void nonfatal(const char *p, ...)
56 fprintf(stderr, "ERROR: ");
58 vfprintf(stderr, p, ap);
62 void connection_fatal(void *frontend, const char *p, ...)
65 fprintf(stderr, "FATAL ERROR: ");
67 vfprintf(stderr, p, ap);
76 void cmdline_error(const char *p, ...)
79 fprintf(stderr, "plink: ");
81 vfprintf(stderr, p, ap);
87 HANDLE inhandle, outhandle, errhandle;
88 struct handle *stdin_handle, *stdout_handle, *stderr_handle;
89 DWORD orig_console_mode;
95 static void *backhandle;
98 int term_ldisc(Terminal *term, int mode)
102 void frontend_echoedit_update(void *frontend, int echo, int edit)
104 /* Update stdin read mode to reflect changes in line discipline. */
107 mode = ENABLE_PROCESSED_INPUT;
109 mode = mode | ENABLE_ECHO_INPUT;
111 mode = mode & ~ENABLE_ECHO_INPUT;
113 mode = mode | ENABLE_LINE_INPUT;
115 mode = mode & ~ENABLE_LINE_INPUT;
116 SetConsoleMode(inhandle, mode);
119 char *get_ttymode(void *frontend, const char *mode) { return NULL; }
121 int from_backend(void *frontend_handle, int is_stderr,
122 const char *data, int len)
125 handle_write(stderr_handle, data, len);
127 handle_write(stdout_handle, data, len);
130 return handle_backlog(stdout_handle) + handle_backlog(stderr_handle);
133 int from_backend_untrusted(void *frontend_handle, const char *data, int len)
136 * No "untrusted" output should get here (the way the code is
137 * currently, it's all diverted by FLAG_STDERR).
139 assert(!"Unexpected call to from_backend_untrusted()");
140 return 0; /* not reached */
143 int from_backend_eof(void *frontend_handle)
145 handle_write_eof(stdout_handle);
146 return FALSE; /* do not respond to incoming EOF with outgoing */
149 int get_userpass_input(prompts_t *p, const unsigned char *in, int inlen)
152 ret = cmdline_get_passwd_input(p, in, inlen);
154 ret = console_get_userpass_input(p, in, inlen);
158 static DWORD main_thread_id;
160 void agent_schedule_callback(void (*callback)(void *, void *, int),
161 void *callback_ctx, void *data, int len)
163 struct agent_callback *c = snew(struct agent_callback);
164 c->callback = callback;
165 c->callback_ctx = callback_ctx;
168 PostThreadMessage(main_thread_id, WM_AGENT_CALLBACK, 0, (LPARAM)c);
172 * Short description of parameters.
174 static void usage(void)
176 printf("Plink: command-line connection utility\n");
178 printf("Usage: plink [options] [user@]host [command]\n");
179 printf(" (\"host\" can also be a PuTTY saved session name)\n");
180 printf("Options:\n");
181 printf(" -V print version information and exit\n");
182 printf(" -pgpfp print PGP key fingerprints and exit\n");
183 printf(" -v show verbose messages\n");
184 printf(" -load sessname Load settings from saved session\n");
185 printf(" -ssh -telnet -rlogin -raw -serial\n");
186 printf(" force use of a particular protocol\n");
187 printf(" -P port connect to specified port\n");
188 printf(" -l user connect with specified username\n");
189 printf(" -batch disable all interactive prompts\n");
190 printf(" -sercfg configuration-string (e.g. 19200,8,n,1,X)\n");
191 printf(" Specify the serial configuration (serial only)\n");
192 printf("The following options only apply to SSH connections:\n");
193 printf(" -pw passw login with specified password\n");
194 printf(" -D [listen-IP:]listen-port\n");
195 printf(" Dynamic SOCKS-based port forwarding\n");
196 printf(" -L [listen-IP:]listen-port:host:port\n");
197 printf(" Forward local port to remote address\n");
198 printf(" -R [listen-IP:]listen-port:host:port\n");
199 printf(" Forward remote port to local address\n");
200 printf(" -X -x enable / disable X11 forwarding\n");
201 printf(" -A -a enable / disable agent forwarding\n");
202 printf(" -t -T enable / disable pty allocation\n");
203 printf(" -1 -2 force use of particular protocol version\n");
204 printf(" -4 -6 force use of IPv4 or IPv6\n");
205 printf(" -C enable compression\n");
206 printf(" -i key private key file for user authentication\n");
207 printf(" -noagent disable use of Pageant\n");
208 printf(" -agent enable use of Pageant\n");
209 printf(" -hostkey aa:bb:cc:...\n");
210 printf(" manually specify a host key (may be repeated)\n");
211 printf(" -m file read remote command(s) from file\n");
212 printf(" -s remote command is an SSH subsystem (SSH-2 only)\n");
213 printf(" -N don't start a shell/command (SSH-2 only)\n");
214 printf(" -nc host:port\n");
215 printf(" open tunnel in place of session (SSH-2 only)\n");
216 printf(" -sshlog file\n");
217 printf(" -sshrawlog file\n");
218 printf(" log protocol details to a file\n");
219 printf(" -shareexists\n");
220 printf(" test whether a connection-sharing upstream exists\n");
224 static void version(void)
226 char *buildinfo_text = buildinfo("\n");
227 printf("plink: %s\n%s\n", ver, buildinfo_text);
228 sfree(buildinfo_text);
232 char *do_select(SOCKET skt, int startup)
236 events = (FD_CONNECT | FD_READ | FD_WRITE |
237 FD_OOB | FD_CLOSE | FD_ACCEPT);
241 if (p_WSAEventSelect(skt, netevent, events) == SOCKET_ERROR) {
242 switch (p_WSAGetLastError()) {
244 return "Network is down";
246 return "WSAEventSelect(): unknown error";
252 int stdin_gotdata(struct handle *h, void *data, int len)
256 * Special case: report read error.
259 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, -len, 0,
260 buf, lenof(buf), NULL);
261 buf[lenof(buf)-1] = '\0';
262 if (buf[strlen(buf)-1] == '\n')
263 buf[strlen(buf)-1] = '\0';
264 fprintf(stderr, "Unable to read from standard input: %s\n", buf);
267 noise_ultralight(len);
268 if (connopen && back->connected(backhandle)) {
270 return back->send(backhandle, data, len);
272 back->special(backhandle, TS_EOF);
279 void stdouterr_sent(struct handle *h, int new_backlog)
281 if (new_backlog < 0) {
283 * Special case: report write error.
286 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, -new_backlog, 0,
287 buf, lenof(buf), NULL);
288 buf[lenof(buf)-1] = '\0';
289 if (buf[strlen(buf)-1] == '\n')
290 buf[strlen(buf)-1] = '\0';
291 fprintf(stderr, "Unable to write to standard %s: %s\n",
292 (h == stdout_handle ? "output" : "error"), buf);
295 if (connopen && back->connected(backhandle)) {
296 back->unthrottle(backhandle, (handle_backlog(stdout_handle) +
297 handle_backlog(stderr_handle)));
301 const int share_can_be_downstream = TRUE;
302 const int share_can_be_upstream = TRUE;
304 int main(int argc, char **argv)
312 int got_host = FALSE;
313 int use_subsystem = 0;
314 int just_test_share_exists = FALSE;
315 unsigned long now, next, then;
317 dll_hijacking_protection();
320 skcount = sksize = 0;
322 * Initialise port and protocol to sensible defaults. (These
323 * will be overridden by more or less anything.)
325 default_protocol = PROT_SSH;
330 * Process the command line.
333 do_defaults(NULL, conf);
334 loaded_session = FALSE;
335 default_protocol = conf_get_int(conf, CONF_protocol);
336 default_port = conf_get_int(conf, CONF_port);
340 * Override the default protocol if PLINK_PROTOCOL is set.
342 char *p = getenv("PLINK_PROTOCOL");
344 const Backend *b = backend_from_name(p);
346 default_protocol = b->protocol;
347 default_port = b->default_port;
348 conf_set_int(conf, CONF_protocol, default_protocol);
349 conf_set_int(conf, CONF_port, default_port);
356 int ret = cmdline_process_param(p, (argc > 1 ? argv[1] : NULL),
360 "plink: option \"%s\" requires an argument\n", p);
362 } else if (ret == 2) {
364 } else if (ret == 1) {
366 } else if (!strcmp(p, "-batch")) {
367 console_batch_mode = 1;
368 } else if (!strcmp(p, "-s")) {
369 /* Save status to write to conf later. */
371 } else if (!strcmp(p, "-V") || !strcmp(p, "--version")) {
373 } else if (!strcmp(p, "--help")) {
375 } else if (!strcmp(p, "-pgpfp")) {
378 } else if (!strcmp(p, "-shareexists")) {
379 just_test_share_exists = TRUE;
381 fprintf(stderr, "plink: unknown option \"%s\"\n", p);
385 if (!conf_launchable(conf) || !(got_host || loaded_session)) {
388 * If the hostname starts with "telnet:", set the
389 * protocol to Telnet and process the string as a
392 if (!strncmp(q, "telnet:", 7)) {
396 if (q[0] == '/' && q[1] == '/')
398 conf_set_int(conf, CONF_protocol, PROT_TELNET);
400 p += host_strcspn(p, ":/");
405 conf_set_int(conf, CONF_port, atoi(p));
407 conf_set_int(conf, CONF_port, -1);
408 conf_set_str(conf, CONF_host, q);
411 char *r, *user, *host;
413 * Before we process the [user@]host string, we
414 * first check for the presence of a protocol
415 * prefix (a protocol name followed by ",").
421 b = backend_from_name(p);
423 default_protocol = b->protocol;
424 conf_set_int(conf, CONF_protocol,
426 portnumber = b->default_port;
432 * A nonzero length string followed by an @ is treated
433 * as a username. (We discount an _initial_ @.) The
434 * rest of the string (or the whole string if no @)
435 * is treated as a session name and/or hostname.
439 p++, r = NULL; /* discount initial @ */
444 user = NULL, host = p;
448 * Now attempt to load a saved session with the
449 * same name as the hostname.
452 Conf *conf2 = conf_new();
453 do_defaults(host, conf2);
454 if (loaded_session || !conf_launchable(conf2)) {
455 /* No settings for this host; use defaults */
456 /* (or session was already loaded with -load) */
457 conf_set_str(conf, CONF_host, host);
458 conf_set_int(conf, CONF_port, default_port);
461 conf_copy_into(conf, conf2);
462 loaded_session = TRUE;
468 /* Patch in specified username. */
469 conf_set_str(conf, CONF_username, user);
476 cmdlen = cmdsize = 0;
481 if (cmdlen >= cmdsize) {
482 cmdsize = cmdlen + 512;
483 command = sresize(command, cmdsize, char);
485 command[cmdlen++]=*p++;
487 if (cmdlen >= cmdsize) {
488 cmdsize = cmdlen + 512;
489 command = sresize(command, cmdsize, char);
491 command[cmdlen++]=' '; /* always add trailing space */
492 if (--argc) p = *++argv;
494 if (cmdlen) command[--cmdlen]='\0';
495 /* change trailing blank to NUL */
496 conf_set_str(conf, CONF_remote_cmd, command);
497 conf_set_str(conf, CONF_remote_cmd2, "");
498 conf_set_int(conf, CONF_nopty, TRUE); /* command => no tty */
500 break; /* done with cmdline */
505 #if !defined UNPROTECT && !defined NO_SECURITY
507 * Protect our process.
511 if (!setprocessacl(error)) {
512 char *message = dupprintf("Could not restrict process ACL: %s",
514 logevent(NULL, message);
524 if (!conf_launchable(conf) || !(got_host || loaded_session)) {
529 * Muck about with the hostname in various ways.
532 char *hostbuf = dupstr(conf_get_str(conf, CONF_host));
533 char *host = hostbuf;
537 * Trim leading whitespace.
539 host += strspn(host, " \t");
542 * See if host is of the form user@host, and separate out
543 * the username if so.
545 if (host[0] != '\0') {
546 char *atsign = strrchr(host, '@');
549 conf_set_str(conf, CONF_username, host);
555 * Trim a colon suffix off the hostname if it's there. In
556 * order to protect unbracketed IPv6 address literals
557 * against this treatment, we do not do this if there's
558 * _more_ than one colon.
561 char *c = host_strchr(host, ':');
564 char *d = host_strchr(c+1, ':');
571 * Remove any remaining whitespace.
576 if (*q != ' ' && *q != '\t')
582 conf_set_str(conf, CONF_host, hostbuf);
587 * Perform command-line overrides on session configuration.
589 cmdline_run_saved(conf);
592 * Apply subsystem status.
595 conf_set_int(conf, CONF_ssh_subsys, TRUE);
597 if (!*conf_get_str(conf, CONF_remote_cmd) &&
598 !*conf_get_str(conf, CONF_remote_cmd2) &&
599 !*conf_get_str(conf, CONF_ssh_nc_host))
600 flags |= FLAG_INTERACTIVE;
603 * Select protocol. This is farmed out into a table in a
604 * separate file to enable an ssh-free variant.
606 back = backend_from_proto(conf_get_int(conf, CONF_protocol));
609 "Internal fault: Unsupported protocol found\n");
616 if (portnumber != -1)
617 conf_set_int(conf, CONF_port, portnumber);
620 if (p_WSAEventSelect == NULL) {
621 fprintf(stderr, "Plink requires WinSock 2\n");
626 * Plink doesn't provide any way to add forwardings after the
627 * connection is set up, so if there are none now, we can safely set
630 if (conf_get_int(conf, CONF_protocol) == PROT_SSH &&
631 !conf_get_int(conf, CONF_x11_forward) &&
632 !conf_get_int(conf, CONF_agentfwd) &&
633 !conf_get_str_nthstrkey(conf, CONF_portfwd, 0))
634 conf_set_int(conf, CONF_ssh_simple, TRUE);
636 logctx = log_init(NULL, conf);
637 console_provide_logctx(logctx);
639 if (just_test_share_exists) {
640 if (!back->test_for_upstream) {
641 fprintf(stderr, "Connection sharing not supported for connection "
642 "type '%s'\n", back->name);
645 if (back->test_for_upstream(conf_get_str(conf, CONF_host),
646 conf_get_int(conf, CONF_port), conf))
653 * Start up the connection.
655 netevent = CreateEvent(NULL, FALSE, FALSE, NULL);
659 /* nodelay is only useful if stdin is a character device (console) */
660 int nodelay = conf_get_int(conf, CONF_tcp_nodelay) &&
661 (GetFileType(GetStdHandle(STD_INPUT_HANDLE)) == FILE_TYPE_CHAR);
663 error = back->init(NULL, &backhandle, conf,
664 conf_get_str(conf, CONF_host),
665 conf_get_int(conf, CONF_port),
667 conf_get_int(conf, CONF_tcp_keepalives));
669 fprintf(stderr, "Unable to open connection:\n%s", error);
672 back->provide_logctx(backhandle, logctx);
677 inhandle = GetStdHandle(STD_INPUT_HANDLE);
678 outhandle = GetStdHandle(STD_OUTPUT_HANDLE);
679 errhandle = GetStdHandle(STD_ERROR_HANDLE);
682 * Turn off ECHO and LINE input modes. We don't care if this
683 * call fails, because we know we aren't necessarily running in
686 GetConsoleMode(inhandle, &orig_console_mode);
687 SetConsoleMode(inhandle, ENABLE_PROCESSED_INPUT);
690 * Pass the output handles to the handle-handling subsystem.
691 * (The input one we leave until we're through the
692 * authentication process.)
694 stdout_handle = handle_output_new(outhandle, stdouterr_sent, NULL, 0);
695 stderr_handle = handle_output_new(errhandle, stdouterr_sent, NULL, 0);
697 main_thread_id = GetCurrentThreadId();
701 now = GETTICKCOUNT();
709 if (!sending && back->sendok(backhandle)) {
710 stdin_handle = handle_input_new(inhandle, stdin_gotdata, NULL,
715 if (toplevel_callback_pending()) {
718 } else if (run_timers(now, &next)) {
720 now = GETTICKCOUNT();
721 if (now - then > next - then)
727 /* no need to initialise next here because we can never
728 * get WAIT_TIMEOUT */
731 handles = handle_get_events(&nhandles);
732 handles = sresize(handles, nhandles+1, HANDLE);
733 handles[nhandles] = netevent;
734 n = MsgWaitForMultipleObjects(nhandles+1, handles, FALSE, ticks,
736 if ((unsigned)(n - WAIT_OBJECT_0) < (unsigned)nhandles) {
737 handle_got_event(handles[n - WAIT_OBJECT_0]);
738 } else if (n == WAIT_OBJECT_0 + nhandles) {
739 WSANETWORKEVENTS things;
741 extern SOCKET first_socket(int *), next_socket(int *);
742 extern int select_result(WPARAM, LPARAM);
746 * We must not call select_result() for any socket
747 * until we have finished enumerating within the tree.
748 * This is because select_result() may close the socket
749 * and modify the tree.
751 /* Count the active sockets. */
753 for (socket = first_socket(&socketstate);
754 socket != INVALID_SOCKET;
755 socket = next_socket(&socketstate)) i++;
757 /* Expand the buffer if necessary. */
760 sklist = sresize(sklist, sksize, SOCKET);
763 /* Retrieve the sockets into sklist. */
765 for (socket = first_socket(&socketstate);
766 socket != INVALID_SOCKET;
767 socket = next_socket(&socketstate)) {
768 sklist[skcount++] = socket;
771 /* Now we're done enumerating; go through the list. */
772 for (i = 0; i < skcount; i++) {
775 wp = (WPARAM) socket;
776 if (!p_WSAEnumNetworkEvents(socket, NULL, &things)) {
777 static const struct { int bit, mask; } eventtypes[] = {
778 {FD_CONNECT_BIT, FD_CONNECT},
779 {FD_READ_BIT, FD_READ},
780 {FD_CLOSE_BIT, FD_CLOSE},
781 {FD_OOB_BIT, FD_OOB},
782 {FD_WRITE_BIT, FD_WRITE},
783 {FD_ACCEPT_BIT, FD_ACCEPT},
787 noise_ultralight(socket);
788 noise_ultralight(things.lNetworkEvents);
790 for (e = 0; e < lenof(eventtypes); e++)
791 if (things.lNetworkEvents & eventtypes[e].mask) {
793 int err = things.iErrorCode[eventtypes[e].bit];
794 lp = WSAMAKESELECTREPLY(eventtypes[e].mask, err);
795 connopen &= select_result(wp, lp);
799 } else if (n == WAIT_OBJECT_0 + nhandles + 1) {
801 while (PeekMessage(&msg, INVALID_HANDLE_VALUE,
802 WM_AGENT_CALLBACK, WM_AGENT_CALLBACK,
804 struct agent_callback *c = (struct agent_callback *)msg.lParam;
805 c->callback(c->callback_ctx, c->data, c->len);
810 run_toplevel_callbacks();
812 if (n == WAIT_TIMEOUT) {
815 now = GETTICKCOUNT();
821 handle_unthrottle(stdin_handle, back->sendbuffer(backhandle));
823 if ((!connopen || !back->connected(backhandle)) &&
824 handle_backlog(stdout_handle) + handle_backlog(stderr_handle) == 0)
825 break; /* we closed the connection */
827 exitcode = back->exitcode(backhandle);
829 fprintf(stderr, "Remote process exit code unavailable\n");
830 exitcode = 1; /* this is an error condition */
832 cleanup_exit(exitcode);
833 return 0; /* placate compiler warning */