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 connection_fatal(void *frontend, char *p, ...)
55 fprintf(stderr, "FATAL ERROR: ");
57 vfprintf(stderr, p, ap);
66 void cmdline_error(char *p, ...)
69 fprintf(stderr, "plink: ");
71 vfprintf(stderr, p, ap);
77 HANDLE inhandle, outhandle, errhandle;
78 struct handle *stdin_handle, *stdout_handle, *stderr_handle;
79 DWORD orig_console_mode;
85 static void *backhandle;
88 int term_ldisc(Terminal *term, int mode)
92 void ldisc_update(void *frontend, int echo, int edit)
94 /* Update stdin read mode to reflect changes in line discipline. */
97 mode = ENABLE_PROCESSED_INPUT;
99 mode = mode | ENABLE_ECHO_INPUT;
101 mode = mode & ~ENABLE_ECHO_INPUT;
103 mode = mode | ENABLE_LINE_INPUT;
105 mode = mode & ~ENABLE_LINE_INPUT;
106 SetConsoleMode(inhandle, mode);
109 char *get_ttymode(void *frontend, const char *mode) { return NULL; }
111 int from_backend(void *frontend_handle, int is_stderr,
112 const char *data, int len)
115 handle_write(stderr_handle, data, len);
117 handle_write(stdout_handle, data, len);
120 return handle_backlog(stdout_handle) + handle_backlog(stderr_handle);
123 int from_backend_untrusted(void *frontend_handle, const char *data, int len)
126 * No "untrusted" output should get here (the way the code is
127 * currently, it's all diverted by FLAG_STDERR).
129 assert(!"Unexpected call to from_backend_untrusted()");
130 return 0; /* not reached */
133 int from_backend_eof(void *frontend_handle)
135 handle_write_eof(stdout_handle);
136 return FALSE; /* do not respond to incoming EOF with outgoing */
139 int get_userpass_input(prompts_t *p, unsigned char *in, int inlen)
142 ret = cmdline_get_passwd_input(p, in, inlen);
144 ret = console_get_userpass_input(p, in, inlen);
148 static DWORD main_thread_id;
150 void agent_schedule_callback(void (*callback)(void *, void *, int),
151 void *callback_ctx, void *data, int len)
153 struct agent_callback *c = snew(struct agent_callback);
154 c->callback = callback;
155 c->callback_ctx = callback_ctx;
158 PostThreadMessage(main_thread_id, WM_AGENT_CALLBACK, 0, (LPARAM)c);
162 * Short description of parameters.
164 static void usage(void)
166 printf("PuTTY Link: command-line connection utility\n");
168 printf("Usage: plink [options] [user@]host [command]\n");
169 printf(" (\"host\" can also be a PuTTY saved session name)\n");
170 printf("Options:\n");
171 printf(" -V print version information and exit\n");
172 printf(" -pgpfp print PGP key fingerprints and exit\n");
173 printf(" -v show verbose messages\n");
174 printf(" -load sessname Load settings from saved session\n");
175 printf(" -ssh -telnet -rlogin -raw -serial\n");
176 printf(" force use of a particular protocol\n");
177 printf(" -P port connect to specified port\n");
178 printf(" -l user connect with specified username\n");
179 printf(" -batch disable all interactive prompts\n");
180 printf("The following options only apply to SSH connections:\n");
181 printf(" -pw passw login with specified password\n");
182 printf(" -D [listen-IP:]listen-port\n");
183 printf(" Dynamic SOCKS-based port forwarding\n");
184 printf(" -L [listen-IP:]listen-port:host:port\n");
185 printf(" Forward local port to remote address\n");
186 printf(" -R [listen-IP:]listen-port:host:port\n");
187 printf(" Forward remote port to local address\n");
188 printf(" -X -x enable / disable X11 forwarding\n");
189 printf(" -A -a enable / disable agent forwarding\n");
190 printf(" -t -T enable / disable pty allocation\n");
191 printf(" -1 -2 force use of particular protocol version\n");
192 printf(" -4 -6 force use of IPv4 or IPv6\n");
193 printf(" -C enable compression\n");
194 printf(" -i key private key file for authentication\n");
195 printf(" -noagent disable use of Pageant\n");
196 printf(" -agent enable use of Pageant\n");
197 printf(" -m file read remote command(s) from file\n");
198 printf(" -s remote command is an SSH subsystem (SSH-2 only)\n");
199 printf(" -N don't start a shell/command (SSH-2 only)\n");
200 printf(" -nc host:port\n");
201 printf(" open tunnel in place of session (SSH-2 only)\n");
202 printf(" -sercfg configuration-string (e.g. 19200,8,n,1,X)\n");
203 printf(" Specify the serial configuration (serial only)\n");
207 static void version(void)
209 printf("plink: %s\n", ver);
213 char *do_select(SOCKET skt, int startup)
217 events = (FD_CONNECT | FD_READ | FD_WRITE |
218 FD_OOB | FD_CLOSE | FD_ACCEPT);
222 if (p_WSAEventSelect(skt, netevent, events) == SOCKET_ERROR) {
223 switch (p_WSAGetLastError()) {
225 return "Network is down";
227 return "WSAEventSelect(): unknown error";
233 int stdin_gotdata(struct handle *h, void *data, int len)
237 * Special case: report read error.
240 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, -len, 0,
241 buf, lenof(buf), NULL);
242 buf[lenof(buf)-1] = '\0';
243 if (buf[strlen(buf)-1] == '\n')
244 buf[strlen(buf)-1] = '\0';
245 fprintf(stderr, "Unable to read from standard input: %s\n", buf);
248 noise_ultralight(len);
249 if (connopen && back->connected(backhandle)) {
251 return back->send(backhandle, data, len);
253 back->special(backhandle, TS_EOF);
260 void stdouterr_sent(struct handle *h, int new_backlog)
262 if (new_backlog < 0) {
264 * Special case: report write error.
267 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, -new_backlog, 0,
268 buf, lenof(buf), NULL);
269 buf[lenof(buf)-1] = '\0';
270 if (buf[strlen(buf)-1] == '\n')
271 buf[strlen(buf)-1] = '\0';
272 fprintf(stderr, "Unable to write to standard %s: %s\n",
273 (h == stdout_handle ? "output" : "error"), buf);
276 if (connopen && back->connected(backhandle)) {
277 back->unthrottle(backhandle, (handle_backlog(stdout_handle) +
278 handle_backlog(stderr_handle)));
282 int main(int argc, char **argv)
290 int got_host = FALSE;
291 int use_subsystem = 0;
295 skcount = sksize = 0;
297 * Initialise port and protocol to sensible defaults. (These
298 * will be overridden by more or less anything.)
300 default_protocol = PROT_SSH;
305 * Process the command line.
308 do_defaults(NULL, conf);
309 loaded_session = FALSE;
310 default_protocol = conf_get_int(conf, CONF_protocol);
311 default_port = conf_get_int(conf, CONF_port);
315 * Override the default protocol if PLINK_PROTOCOL is set.
317 char *p = getenv("PLINK_PROTOCOL");
319 const Backend *b = backend_from_name(p);
321 default_protocol = b->protocol;
322 default_port = b->default_port;
323 conf_set_int(conf, CONF_protocol, default_protocol);
324 conf_set_int(conf, CONF_port, default_port);
331 int ret = cmdline_process_param(p, (argc > 1 ? argv[1] : NULL),
335 "plink: option \"%s\" requires an argument\n", p);
337 } else if (ret == 2) {
339 } else if (ret == 1) {
341 } else if (!strcmp(p, "-batch")) {
342 console_batch_mode = 1;
343 } else if (!strcmp(p, "-s")) {
344 /* Save status to write to conf later. */
346 } else if (!strcmp(p, "-V")) {
348 } else if (!strcmp(p, "-pgpfp")) {
352 fprintf(stderr, "plink: unknown option \"%s\"\n", p);
356 if (!conf_launchable(conf) || !(got_host || loaded_session)) {
359 * If the hostname starts with "telnet:", set the
360 * protocol to Telnet and process the string as a
363 if (!strncmp(q, "telnet:", 7)) {
367 if (q[0] == '/' && q[1] == '/')
369 conf_set_int(conf, CONF_protocol, PROT_TELNET);
371 while (*p && *p != ':' && *p != '/')
377 conf_set_int(conf, CONF_port, atoi(p));
379 conf_set_int(conf, CONF_port, -1);
380 conf_set_str(conf, CONF_host, q);
383 char *r, *user, *host;
385 * Before we process the [user@]host string, we
386 * first check for the presence of a protocol
387 * prefix (a protocol name followed by ",").
393 b = backend_from_name(p);
395 default_protocol = b->protocol;
396 conf_set_int(conf, CONF_protocol,
398 portnumber = b->default_port;
404 * A nonzero length string followed by an @ is treated
405 * as a username. (We discount an _initial_ @.) The
406 * rest of the string (or the whole string if no @)
407 * is treated as a session name and/or hostname.
411 p++, r = NULL; /* discount initial @ */
416 user = NULL, host = p;
420 * Now attempt to load a saved session with the
421 * same name as the hostname.
424 Conf *conf2 = conf_new();
425 do_defaults(host, conf2);
426 if (loaded_session || !conf_launchable(conf2)) {
427 /* No settings for this host; use defaults */
428 /* (or session was already loaded with -load) */
429 conf_set_str(conf, CONF_host, host);
430 conf_set_int(conf, CONF_port, default_port);
433 conf_copy_into(conf, conf2);
434 loaded_session = TRUE;
440 /* Patch in specified username. */
441 conf_set_str(conf, CONF_username, user);
448 cmdlen = cmdsize = 0;
453 if (cmdlen >= cmdsize) {
454 cmdsize = cmdlen + 512;
455 command = sresize(command, cmdsize, char);
457 command[cmdlen++]=*p++;
459 if (cmdlen >= cmdsize) {
460 cmdsize = cmdlen + 512;
461 command = sresize(command, cmdsize, char);
463 command[cmdlen++]=' '; /* always add trailing space */
464 if (--argc) p = *++argv;
466 if (cmdlen) command[--cmdlen]='\0';
467 /* change trailing blank to NUL */
468 conf_set_str(conf, CONF_remote_cmd, command);
469 conf_set_str(conf, CONF_remote_cmd2, "");
470 conf_set_int(conf, CONF_nopty, TRUE); /* command => no tty */
472 break; /* done with cmdline */
480 if (!conf_launchable(conf) || !(got_host || loaded_session)) {
485 * Muck about with the hostname in various ways.
488 char *hostbuf = dupstr(conf_get_str(conf, CONF_host));
489 char *host = hostbuf;
493 * Trim leading whitespace.
495 host += strspn(host, " \t");
498 * See if host is of the form user@host, and separate out
499 * the username if so.
501 if (host[0] != '\0') {
502 char *atsign = strrchr(host, '@');
505 conf_set_str(conf, CONF_username, host);
511 * Trim off a colon suffix if it's there.
513 host[strcspn(host, ":")] = '\0';
516 * Remove any remaining whitespace.
521 if (*q != ' ' && *q != '\t')
527 conf_set_str(conf, CONF_host, hostbuf);
532 * Perform command-line overrides on session configuration.
534 cmdline_run_saved(conf);
537 * Apply subsystem status.
540 conf_set_int(conf, CONF_ssh_subsys, TRUE);
542 if (!*conf_get_str(conf, CONF_remote_cmd) &&
543 !*conf_get_str(conf, CONF_remote_cmd2) &&
544 !*conf_get_str(conf, CONF_ssh_nc_host))
545 flags |= FLAG_INTERACTIVE;
548 * Select protocol. This is farmed out into a table in a
549 * separate file to enable an ssh-free variant.
551 back = backend_from_proto(conf_get_int(conf, CONF_protocol));
554 "Internal fault: Unsupported protocol found\n");
561 if (portnumber != -1)
562 conf_set_int(conf, CONF_port, portnumber);
565 if (p_WSAEventSelect == NULL) {
566 fprintf(stderr, "Plink requires WinSock 2\n");
570 logctx = log_init(NULL, conf);
571 console_provide_logctx(logctx);
574 * Start up the connection.
576 netevent = CreateEvent(NULL, FALSE, FALSE, NULL);
580 /* nodelay is only useful if stdin is a character device (console) */
581 int nodelay = conf_get_int(conf, CONF_tcp_nodelay) &&
582 (GetFileType(GetStdHandle(STD_INPUT_HANDLE)) == FILE_TYPE_CHAR);
584 error = back->init(NULL, &backhandle, conf,
585 conf_get_str(conf, CONF_host),
586 conf_get_int(conf, CONF_port),
588 conf_get_int(conf, CONF_tcp_keepalives));
590 fprintf(stderr, "Unable to open connection:\n%s", error);
593 back->provide_logctx(backhandle, logctx);
598 inhandle = GetStdHandle(STD_INPUT_HANDLE);
599 outhandle = GetStdHandle(STD_OUTPUT_HANDLE);
600 errhandle = GetStdHandle(STD_ERROR_HANDLE);
603 * Turn off ECHO and LINE input modes. We don't care if this
604 * call fails, because we know we aren't necessarily running in
607 GetConsoleMode(inhandle, &orig_console_mode);
608 SetConsoleMode(inhandle, ENABLE_PROCESSED_INPUT);
611 * Pass the output handles to the handle-handling subsystem.
612 * (The input one we leave until we're through the
613 * authentication process.)
615 stdout_handle = handle_output_new(outhandle, stdouterr_sent, NULL, 0);
616 stderr_handle = handle_output_new(errhandle, stdouterr_sent, NULL, 0);
618 main_thread_id = GetCurrentThreadId();
622 now = GETTICKCOUNT();
630 if (!sending && back->sendok(backhandle)) {
631 stdin_handle = handle_input_new(inhandle, stdin_gotdata, NULL,
636 if (run_timers(now, &next)) {
637 ticks = next - GETTICKCOUNT();
638 if (ticks < 0) ticks = 0; /* just in case */
643 handles = handle_get_events(&nhandles);
644 handles = sresize(handles, nhandles+1, HANDLE);
645 handles[nhandles] = netevent;
646 n = MsgWaitForMultipleObjects(nhandles+1, handles, FALSE, ticks,
648 if ((unsigned)(n - WAIT_OBJECT_0) < (unsigned)nhandles) {
649 handle_got_event(handles[n - WAIT_OBJECT_0]);
650 } else if (n == WAIT_OBJECT_0 + nhandles) {
651 WSANETWORKEVENTS things;
653 extern SOCKET first_socket(int *), next_socket(int *);
654 extern int select_result(WPARAM, LPARAM);
658 * We must not call select_result() for any socket
659 * until we have finished enumerating within the tree.
660 * This is because select_result() may close the socket
661 * and modify the tree.
663 /* Count the active sockets. */
665 for (socket = first_socket(&socketstate);
666 socket != INVALID_SOCKET;
667 socket = next_socket(&socketstate)) i++;
669 /* Expand the buffer if necessary. */
672 sklist = sresize(sklist, sksize, SOCKET);
675 /* Retrieve the sockets into sklist. */
677 for (socket = first_socket(&socketstate);
678 socket != INVALID_SOCKET;
679 socket = next_socket(&socketstate)) {
680 sklist[skcount++] = socket;
683 /* Now we're done enumerating; go through the list. */
684 for (i = 0; i < skcount; i++) {
687 wp = (WPARAM) socket;
688 if (!p_WSAEnumNetworkEvents(socket, NULL, &things)) {
689 static const struct { int bit, mask; } eventtypes[] = {
690 {FD_CONNECT_BIT, FD_CONNECT},
691 {FD_READ_BIT, FD_READ},
692 {FD_CLOSE_BIT, FD_CLOSE},
693 {FD_OOB_BIT, FD_OOB},
694 {FD_WRITE_BIT, FD_WRITE},
695 {FD_ACCEPT_BIT, FD_ACCEPT},
699 noise_ultralight(socket);
700 noise_ultralight(things.lNetworkEvents);
702 for (e = 0; e < lenof(eventtypes); e++)
703 if (things.lNetworkEvents & eventtypes[e].mask) {
705 int err = things.iErrorCode[eventtypes[e].bit];
706 lp = WSAMAKESELECTREPLY(eventtypes[e].mask, err);
707 connopen &= select_result(wp, lp);
711 } else if (n == WAIT_OBJECT_0 + nhandles + 1) {
713 while (PeekMessage(&msg, INVALID_HANDLE_VALUE,
714 WM_AGENT_CALLBACK, WM_AGENT_CALLBACK,
716 struct agent_callback *c = (struct agent_callback *)msg.lParam;
717 c->callback(c->callback_ctx, c->data, c->len);
722 if (n == WAIT_TIMEOUT) {
725 now = GETTICKCOUNT();
731 handle_unthrottle(stdin_handle, back->sendbuffer(backhandle));
733 if ((!connopen || !back->connected(backhandle)) &&
734 handle_backlog(stdout_handle) + handle_backlog(stderr_handle) == 0)
735 break; /* we closed the connection */
737 exitcode = back->exitcode(backhandle);
739 fprintf(stderr, "Remote process exit code unavailable\n");
740 exitcode = 1; /* this is an error condition */
742 cleanup_exit(exitcode);
743 return 0; /* placate compiler warning */