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);
38 void modalfatalbox(char *p, ...)
41 fprintf(stderr, "FATAL ERROR: ");
43 vfprintf(stderr, p, ap);
52 void nonfatal(char *p, ...)
55 fprintf(stderr, "ERROR: ");
57 vfprintf(stderr, p, ap);
61 void connection_fatal(void *frontend, char *p, ...)
64 fprintf(stderr, "FATAL ERROR: ");
66 vfprintf(stderr, p, ap);
75 void cmdline_error(char *p, ...)
78 fprintf(stderr, "plink: ");
80 vfprintf(stderr, p, ap);
86 HANDLE inhandle, outhandle, errhandle;
87 struct handle *stdin_handle, *stdout_handle, *stderr_handle;
88 DWORD orig_console_mode;
94 static void *backhandle;
97 int term_ldisc(Terminal *term, int mode)
101 void ldisc_update(void *frontend, int echo, int edit)
103 /* Update stdin read mode to reflect changes in line discipline. */
106 mode = ENABLE_PROCESSED_INPUT;
108 mode = mode | ENABLE_ECHO_INPUT;
110 mode = mode & ~ENABLE_ECHO_INPUT;
112 mode = mode | ENABLE_LINE_INPUT;
114 mode = mode & ~ENABLE_LINE_INPUT;
115 SetConsoleMode(inhandle, mode);
118 char *get_ttymode(void *frontend, const char *mode) { return NULL; }
120 int from_backend(void *frontend_handle, int is_stderr,
121 const char *data, int len)
124 handle_write(stderr_handle, data, len);
126 handle_write(stdout_handle, data, len);
129 return handle_backlog(stdout_handle) + handle_backlog(stderr_handle);
132 int from_backend_untrusted(void *frontend_handle, const char *data, int len)
135 * No "untrusted" output should get here (the way the code is
136 * currently, it's all diverted by FLAG_STDERR).
138 assert(!"Unexpected call to from_backend_untrusted()");
139 return 0; /* not reached */
142 int from_backend_eof(void *frontend_handle)
144 handle_write_eof(stdout_handle);
145 return FALSE; /* do not respond to incoming EOF with outgoing */
148 int get_userpass_input(prompts_t *p, unsigned char *in, int inlen)
151 ret = cmdline_get_passwd_input(p, in, inlen);
153 ret = console_get_userpass_input(p, in, inlen);
157 static DWORD main_thread_id;
159 void agent_schedule_callback(void (*callback)(void *, void *, int),
160 void *callback_ctx, void *data, int len)
162 struct agent_callback *c = snew(struct agent_callback);
163 c->callback = callback;
164 c->callback_ctx = callback_ctx;
167 PostThreadMessage(main_thread_id, WM_AGENT_CALLBACK, 0, (LPARAM)c);
171 * Short description of parameters.
173 static void usage(void)
175 printf("PuTTY Link: command-line connection utility\n");
177 printf("Usage: plink [options] [user@]host [command]\n");
178 printf(" (\"host\" can also be a PuTTY saved session name)\n");
179 printf("Options:\n");
180 printf(" -V print version information and exit\n");
181 printf(" -pgpfp print PGP key fingerprints and exit\n");
182 printf(" -v show verbose messages\n");
183 printf(" -load sessname Load settings from saved session\n");
184 printf(" -ssh -telnet -rlogin -raw -serial\n");
185 printf(" force use of a particular protocol\n");
186 printf(" -P port connect to specified port\n");
187 printf(" -l user connect with specified username\n");
188 printf(" -batch disable all interactive prompts\n");
189 printf("The following options only apply to SSH connections:\n");
190 printf(" -pw passw login with specified password\n");
191 printf(" -D [listen-IP:]listen-port\n");
192 printf(" Dynamic SOCKS-based port forwarding\n");
193 printf(" -L [listen-IP:]listen-port:host:port\n");
194 printf(" Forward local port to remote address\n");
195 printf(" -R [listen-IP:]listen-port:host:port\n");
196 printf(" Forward remote port to local address\n");
197 printf(" -X -x enable / disable X11 forwarding\n");
198 printf(" -A -a enable / disable agent forwarding\n");
199 printf(" -t -T enable / disable pty allocation\n");
200 printf(" -1 -2 force use of particular protocol version\n");
201 printf(" -4 -6 force use of IPv4 or IPv6\n");
202 printf(" -C enable compression\n");
203 printf(" -i key private key file for authentication\n");
204 printf(" -noagent disable use of Pageant\n");
205 printf(" -agent enable use of Pageant\n");
206 printf(" -m file read remote command(s) from file\n");
207 printf(" -s remote command is an SSH subsystem (SSH-2 only)\n");
208 printf(" -N don't start a shell/command (SSH-2 only)\n");
209 printf(" -nc host:port\n");
210 printf(" open tunnel in place of session (SSH-2 only)\n");
211 printf(" -sercfg configuration-string (e.g. 19200,8,n,1,X)\n");
212 printf(" Specify the serial configuration (serial only)\n");
216 static void version(void)
218 printf("plink: %s\n", ver);
222 char *do_select(SOCKET skt, int startup)
226 events = (FD_CONNECT | FD_READ | FD_WRITE |
227 FD_OOB | FD_CLOSE | FD_ACCEPT);
231 if (p_WSAEventSelect(skt, netevent, events) == SOCKET_ERROR) {
232 switch (p_WSAGetLastError()) {
234 return "Network is down";
236 return "WSAEventSelect(): unknown error";
242 int stdin_gotdata(struct handle *h, void *data, int len)
246 * Special case: report read error.
249 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, -len, 0,
250 buf, lenof(buf), NULL);
251 buf[lenof(buf)-1] = '\0';
252 if (buf[strlen(buf)-1] == '\n')
253 buf[strlen(buf)-1] = '\0';
254 fprintf(stderr, "Unable to read from standard input: %s\n", buf);
257 noise_ultralight(len);
258 if (connopen && back->connected(backhandle)) {
260 return back->send(backhandle, data, len);
262 back->special(backhandle, TS_EOF);
269 void stdouterr_sent(struct handle *h, int new_backlog)
271 if (new_backlog < 0) {
273 * Special case: report write error.
276 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, -new_backlog, 0,
277 buf, lenof(buf), NULL);
278 buf[lenof(buf)-1] = '\0';
279 if (buf[strlen(buf)-1] == '\n')
280 buf[strlen(buf)-1] = '\0';
281 fprintf(stderr, "Unable to write to standard %s: %s\n",
282 (h == stdout_handle ? "output" : "error"), buf);
285 if (connopen && back->connected(backhandle)) {
286 back->unthrottle(backhandle, (handle_backlog(stdout_handle) +
287 handle_backlog(stderr_handle)));
291 int main(int argc, char **argv)
299 int got_host = FALSE;
300 int use_subsystem = 0;
301 unsigned long now, next, then;
304 skcount = sksize = 0;
306 * Initialise port and protocol to sensible defaults. (These
307 * will be overridden by more or less anything.)
309 default_protocol = PROT_SSH;
314 * Process the command line.
317 do_defaults(NULL, conf);
318 loaded_session = FALSE;
319 default_protocol = conf_get_int(conf, CONF_protocol);
320 default_port = conf_get_int(conf, CONF_port);
324 * Override the default protocol if PLINK_PROTOCOL is set.
326 char *p = getenv("PLINK_PROTOCOL");
328 const Backend *b = backend_from_name(p);
330 default_protocol = b->protocol;
331 default_port = b->default_port;
332 conf_set_int(conf, CONF_protocol, default_protocol);
333 conf_set_int(conf, CONF_port, default_port);
340 int ret = cmdline_process_param(p, (argc > 1 ? argv[1] : NULL),
344 "plink: option \"%s\" requires an argument\n", p);
346 } else if (ret == 2) {
348 } else if (ret == 1) {
350 } else if (!strcmp(p, "-batch")) {
351 console_batch_mode = 1;
352 } else if (!strcmp(p, "-s")) {
353 /* Save status to write to conf later. */
355 } else if (!strcmp(p, "-V") || !strcmp(p, "--version")) {
357 } else if (!strcmp(p, "--help")) {
359 } else if (!strcmp(p, "-pgpfp")) {
363 fprintf(stderr, "plink: unknown option \"%s\"\n", p);
367 if (!conf_launchable(conf) || !(got_host || loaded_session)) {
370 * If the hostname starts with "telnet:", set the
371 * protocol to Telnet and process the string as a
374 if (!strncmp(q, "telnet:", 7)) {
378 if (q[0] == '/' && q[1] == '/')
380 conf_set_int(conf, CONF_protocol, PROT_TELNET);
382 while (*p && *p != ':' && *p != '/')
388 conf_set_int(conf, CONF_port, atoi(p));
390 conf_set_int(conf, CONF_port, -1);
391 conf_set_str(conf, CONF_host, q);
394 char *r, *user, *host;
396 * Before we process the [user@]host string, we
397 * first check for the presence of a protocol
398 * prefix (a protocol name followed by ",").
404 b = backend_from_name(p);
406 default_protocol = b->protocol;
407 conf_set_int(conf, CONF_protocol,
409 portnumber = b->default_port;
415 * A nonzero length string followed by an @ is treated
416 * as a username. (We discount an _initial_ @.) The
417 * rest of the string (or the whole string if no @)
418 * is treated as a session name and/or hostname.
422 p++, r = NULL; /* discount initial @ */
427 user = NULL, host = p;
431 * Now attempt to load a saved session with the
432 * same name as the hostname.
435 Conf *conf2 = conf_new();
436 do_defaults(host, conf2);
437 if (loaded_session || !conf_launchable(conf2)) {
438 /* No settings for this host; use defaults */
439 /* (or session was already loaded with -load) */
440 conf_set_str(conf, CONF_host, host);
441 conf_set_int(conf, CONF_port, default_port);
444 conf_copy_into(conf, conf2);
445 loaded_session = TRUE;
451 /* Patch in specified username. */
452 conf_set_str(conf, CONF_username, user);
459 cmdlen = cmdsize = 0;
464 if (cmdlen >= cmdsize) {
465 cmdsize = cmdlen + 512;
466 command = sresize(command, cmdsize, char);
468 command[cmdlen++]=*p++;
470 if (cmdlen >= cmdsize) {
471 cmdsize = cmdlen + 512;
472 command = sresize(command, cmdsize, char);
474 command[cmdlen++]=' '; /* always add trailing space */
475 if (--argc) p = *++argv;
477 if (cmdlen) command[--cmdlen]='\0';
478 /* change trailing blank to NUL */
479 conf_set_str(conf, CONF_remote_cmd, command);
480 conf_set_str(conf, CONF_remote_cmd2, "");
481 conf_set_int(conf, CONF_nopty, TRUE); /* command => no tty */
483 break; /* done with cmdline */
491 if (!conf_launchable(conf) || !(got_host || loaded_session)) {
496 * Muck about with the hostname in various ways.
499 char *hostbuf = dupstr(conf_get_str(conf, CONF_host));
500 char *host = hostbuf;
504 * Trim leading whitespace.
506 host += strspn(host, " \t");
509 * See if host is of the form user@host, and separate out
510 * the username if so.
512 if (host[0] != '\0') {
513 char *atsign = strrchr(host, '@');
516 conf_set_str(conf, CONF_username, host);
522 * Trim off a colon suffix if it's there.
524 host[strcspn(host, ":")] = '\0';
527 * Remove any remaining whitespace.
532 if (*q != ' ' && *q != '\t')
538 conf_set_str(conf, CONF_host, hostbuf);
543 * Perform command-line overrides on session configuration.
545 cmdline_run_saved(conf);
548 * Apply subsystem status.
551 conf_set_int(conf, CONF_ssh_subsys, TRUE);
553 if (!*conf_get_str(conf, CONF_remote_cmd) &&
554 !*conf_get_str(conf, CONF_remote_cmd2) &&
555 !*conf_get_str(conf, CONF_ssh_nc_host))
556 flags |= FLAG_INTERACTIVE;
559 * Select protocol. This is farmed out into a table in a
560 * separate file to enable an ssh-free variant.
562 back = backend_from_proto(conf_get_int(conf, CONF_protocol));
565 "Internal fault: Unsupported protocol found\n");
572 if (portnumber != -1)
573 conf_set_int(conf, CONF_port, portnumber);
576 if (p_WSAEventSelect == NULL) {
577 fprintf(stderr, "Plink requires WinSock 2\n");
581 logctx = log_init(NULL, conf);
582 console_provide_logctx(logctx);
585 * Start up the connection.
587 netevent = CreateEvent(NULL, FALSE, FALSE, NULL);
591 /* nodelay is only useful if stdin is a character device (console) */
592 int nodelay = conf_get_int(conf, CONF_tcp_nodelay) &&
593 (GetFileType(GetStdHandle(STD_INPUT_HANDLE)) == FILE_TYPE_CHAR);
595 error = back->init(NULL, &backhandle, conf,
596 conf_get_str(conf, CONF_host),
597 conf_get_int(conf, CONF_port),
599 conf_get_int(conf, CONF_tcp_keepalives));
601 fprintf(stderr, "Unable to open connection:\n%s", error);
604 back->provide_logctx(backhandle, logctx);
609 inhandle = GetStdHandle(STD_INPUT_HANDLE);
610 outhandle = GetStdHandle(STD_OUTPUT_HANDLE);
611 errhandle = GetStdHandle(STD_ERROR_HANDLE);
614 * Turn off ECHO and LINE input modes. We don't care if this
615 * call fails, because we know we aren't necessarily running in
618 GetConsoleMode(inhandle, &orig_console_mode);
619 SetConsoleMode(inhandle, ENABLE_PROCESSED_INPUT);
622 * Pass the output handles to the handle-handling subsystem.
623 * (The input one we leave until we're through the
624 * authentication process.)
626 stdout_handle = handle_output_new(outhandle, stdouterr_sent, NULL, 0);
627 stderr_handle = handle_output_new(errhandle, stdouterr_sent, NULL, 0);
629 main_thread_id = GetCurrentThreadId();
633 now = GETTICKCOUNT();
641 if (!sending && back->sendok(backhandle)) {
642 stdin_handle = handle_input_new(inhandle, stdin_gotdata, NULL,
647 if (toplevel_callback_pending()) {
649 } else if (run_timers(now, &next)) {
651 now = GETTICKCOUNT();
652 if (now - then > next - then)
660 handles = handle_get_events(&nhandles);
661 handles = sresize(handles, nhandles+1, HANDLE);
662 handles[nhandles] = netevent;
663 n = MsgWaitForMultipleObjects(nhandles+1, handles, FALSE, ticks,
665 if ((unsigned)(n - WAIT_OBJECT_0) < (unsigned)nhandles) {
666 handle_got_event(handles[n - WAIT_OBJECT_0]);
667 } else if (n == WAIT_OBJECT_0 + nhandles) {
668 WSANETWORKEVENTS things;
670 extern SOCKET first_socket(int *), next_socket(int *);
671 extern int select_result(WPARAM, LPARAM);
675 * We must not call select_result() for any socket
676 * until we have finished enumerating within the tree.
677 * This is because select_result() may close the socket
678 * and modify the tree.
680 /* Count the active sockets. */
682 for (socket = first_socket(&socketstate);
683 socket != INVALID_SOCKET;
684 socket = next_socket(&socketstate)) i++;
686 /* Expand the buffer if necessary. */
689 sklist = sresize(sklist, sksize, SOCKET);
692 /* Retrieve the sockets into sklist. */
694 for (socket = first_socket(&socketstate);
695 socket != INVALID_SOCKET;
696 socket = next_socket(&socketstate)) {
697 sklist[skcount++] = socket;
700 /* Now we're done enumerating; go through the list. */
701 for (i = 0; i < skcount; i++) {
704 wp = (WPARAM) socket;
705 if (!p_WSAEnumNetworkEvents(socket, NULL, &things)) {
706 static const struct { int bit, mask; } eventtypes[] = {
707 {FD_CONNECT_BIT, FD_CONNECT},
708 {FD_READ_BIT, FD_READ},
709 {FD_CLOSE_BIT, FD_CLOSE},
710 {FD_OOB_BIT, FD_OOB},
711 {FD_WRITE_BIT, FD_WRITE},
712 {FD_ACCEPT_BIT, FD_ACCEPT},
716 noise_ultralight(socket);
717 noise_ultralight(things.lNetworkEvents);
719 for (e = 0; e < lenof(eventtypes); e++)
720 if (things.lNetworkEvents & eventtypes[e].mask) {
722 int err = things.iErrorCode[eventtypes[e].bit];
723 lp = WSAMAKESELECTREPLY(eventtypes[e].mask, err);
724 connopen &= select_result(wp, lp);
728 } else if (n == WAIT_OBJECT_0 + nhandles + 1) {
730 while (PeekMessage(&msg, INVALID_HANDLE_VALUE,
731 WM_AGENT_CALLBACK, WM_AGENT_CALLBACK,
733 struct agent_callback *c = (struct agent_callback *)msg.lParam;
734 c->callback(c->callback_ctx, c->data, c->len);
739 run_toplevel_callbacks();
741 if (n == WAIT_TIMEOUT) {
744 now = GETTICKCOUNT();
750 handle_unthrottle(stdin_handle, back->sendbuffer(backhandle));
752 if ((!connopen || !back->connected(backhandle)) &&
753 handle_backlog(stdout_handle) + handle_backlog(stderr_handle) == 0)
754 break; /* we closed the connection */
756 exitcode = back->exitcode(backhandle);
758 fprintf(stderr, "Remote process exit code unavailable\n");
759 exitcode = 1; /* this is an error condition */
761 cleanup_exit(exitcode);
762 return 0; /* placate compiler warning */