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 get_userpass_input(prompts_t
*p
, unsigned char *in
, int inlen
)
136 ret
= cmdline_get_passwd_input(p
, in
, inlen
);
138 ret
= console_get_userpass_input(p
, in
, inlen
);
142 static DWORD main_thread_id
;
144 void agent_schedule_callback(void (*callback
)(void *, void *, int),
145 void *callback_ctx
, void *data
, int len
)
147 struct agent_callback
*c
= snew(struct agent_callback
);
148 c
->callback
= callback
;
149 c
->callback_ctx
= callback_ctx
;
152 PostThreadMessage(main_thread_id
, WM_AGENT_CALLBACK
, 0, (LPARAM
)c
);
156 * Short description of parameters.
158 static void usage(void)
160 printf("PuTTY Link: command-line connection utility\n");
162 printf("Usage: plink [options] [user@]host [command]\n");
163 printf(" (\"host\" can also be a PuTTY saved session name)\n");
164 printf("Options:\n");
165 printf(" -V print version information and exit\n");
166 printf(" -pgpfp print PGP key fingerprints and exit\n");
167 printf(" -v show verbose messages\n");
168 printf(" -load sessname Load settings from saved session\n");
169 printf(" -ssh -telnet -rlogin -raw\n");
170 printf(" force use of a particular protocol\n");
171 printf(" -P port connect to specified port\n");
172 printf(" -l user connect with specified username\n");
173 printf(" -batch disable all interactive prompts\n");
174 printf("The following options only apply to SSH connections:\n");
175 printf(" -pw passw login with specified password\n");
176 printf(" -D [listen-IP:]listen-port\n");
177 printf(" Dynamic SOCKS-based port forwarding\n");
178 printf(" -L [listen-IP:]listen-port:host:port\n");
179 printf(" Forward local port to remote address\n");
180 printf(" -R [listen-IP:]listen-port:host:port\n");
181 printf(" Forward remote port to local address\n");
182 printf(" -X -x enable / disable X11 forwarding\n");
183 printf(" -A -a enable / disable agent forwarding\n");
184 printf(" -t -T enable / disable pty allocation\n");
185 printf(" -1 -2 force use of particular protocol version\n");
186 printf(" -4 -6 force use of IPv4 or IPv6\n");
187 printf(" -C enable compression\n");
188 printf(" -i key private key file for authentication\n");
189 printf(" -noagent disable use of Pageant\n");
190 printf(" -agent enable use of Pageant\n");
191 printf(" -m file read remote command(s) from file\n");
192 printf(" -s remote command is an SSH subsystem (SSH-2 only)\n");
193 printf(" -N don't start a shell/command (SSH-2 only)\n");
194 printf(" -nc host:port\n");
195 printf(" open tunnel in place of session (SSH-2 only)\n");
199 static void version(void)
201 printf("plink: %s\n", ver
);
205 char *do_select(SOCKET skt
, int startup
)
209 events
= (FD_CONNECT
| FD_READ
| FD_WRITE
|
210 FD_OOB
| FD_CLOSE
| FD_ACCEPT
);
214 if (p_WSAEventSelect(skt
, netevent
, events
) == SOCKET_ERROR
) {
215 switch (p_WSAGetLastError()) {
217 return "Network is down";
219 return "WSAEventSelect(): unknown error";
225 int stdin_gotdata(struct handle
*h
, void *data
, int len
)
229 * Special case: report read error.
232 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM
, NULL
, -len
, 0,
233 buf
, lenof(buf
), NULL
);
234 buf
[lenof(buf
)-1] = '\0';
235 if (buf
[strlen(buf
)-1] == '\n')
236 buf
[strlen(buf
)-1] = '\0';
237 fprintf(stderr
, "Unable to read from standard input: %s\n", buf
);
240 noise_ultralight(len
);
241 if (connopen
&& back
->connected(backhandle
)) {
243 return back
->send(backhandle
, data
, len
);
245 back
->special(backhandle
, TS_EOF
);
252 void stdouterr_sent(struct handle
*h
, int new_backlog
)
254 if (new_backlog
< 0) {
256 * Special case: report write error.
259 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM
, NULL
, -new_backlog
, 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 write to standard %s: %s\n",
265 (h
== stdout_handle ?
"output" : "error"), buf
);
268 if (connopen
&& back
->connected(backhandle
)) {
269 back
->unthrottle(backhandle
, (handle_backlog(stdout_handle
) +
270 handle_backlog(stderr_handle
)));
274 int main(int argc
, char **argv
)
282 int use_subsystem
= 0;
286 skcount
= sksize
= 0;
288 * Initialise port and protocol to sensible defaults. (These
289 * will be overridden by more or less anything.)
291 default_protocol
= PROT_SSH
;
296 * Process the command line.
298 do_defaults(NULL
, &cfg
);
299 loaded_session
= FALSE
;
300 default_protocol
= cfg
.protocol
;
301 default_port
= cfg
.port
;
305 * Override the default protocol if PLINK_PROTOCOL is set.
307 char *p
= getenv("PLINK_PROTOCOL");
310 for (i
= 0; backends
[i
].backend
!= NULL
; i
++) {
311 if (!strcmp(backends
[i
].name
, p
)) {
312 default_protocol
= cfg
.protocol
= backends
[i
].protocol
;
313 default_port
= cfg
.port
=
314 backends
[i
].backend
->default_port
;
323 int ret
= cmdline_process_param(p
, (argc
> 1 ? argv
[1] : NULL
),
327 "plink: option \"%s\" requires an argument\n", p
);
329 } else if (ret
== 2) {
331 } else if (ret
== 1) {
333 } else if (!strcmp(p
, "-batch")) {
334 console_batch_mode
= 1;
335 } else if (!strcmp(p
, "-s")) {
336 /* Save status to write to cfg later. */
338 } else if (!strcmp(p
, "-V")) {
340 } else if (!strcmp(p
, "-pgpfp")) {
344 fprintf(stderr
, "plink: unknown option \"%s\"\n", p
);
348 if (!cfg_launchable(&cfg
)) {
351 * If the hostname starts with "telnet:", set the
352 * protocol to Telnet and process the string as a
355 if (!strncmp(q
, "telnet:", 7)) {
359 if (q
[0] == '/' && q
[1] == '/')
361 cfg
.protocol
= PROT_TELNET
;
363 while (*p
&& *p
!= ':' && *p
!= '/')
372 strncpy(cfg
.host
, q
, sizeof(cfg
.host
) - 1);
373 cfg
.host
[sizeof(cfg
.host
) - 1] = '\0';
375 char *r
, *user
, *host
;
377 * Before we process the [user@]host string, we
378 * first check for the presence of a protocol
379 * prefix (a protocol name followed by ",").
384 for (i
= 0; backends
[i
].backend
!= NULL
; i
++) {
385 j
= strlen(backends
[i
].name
);
387 !memcmp(backends
[i
].name
, p
, j
)) {
388 default_protocol
= cfg
.protocol
=
389 backends
[i
].protocol
;
391 backends
[i
].backend
->default_port
;
399 * A nonzero length string followed by an @ is treated
400 * as a username. (We discount an _initial_ @.) The
401 * rest of the string (or the whole string if no @)
402 * is treated as a session name and/or hostname.
406 p
++, r
= NULL
; /* discount initial @ */
411 user
= NULL
, host
= p
;
415 * Now attempt to load a saved session with the
416 * same name as the hostname.
420 do_defaults(host
, &cfg2
);
421 if (loaded_session
|| !cfg_launchable(&cfg2
)) {
422 /* No settings for this host; use defaults */
423 /* (or session was already loaded with -load) */
424 strncpy(cfg
.host
, host
, sizeof(cfg
.host
) - 1);
425 cfg
.host
[sizeof(cfg
.host
) - 1] = '\0';
426 cfg
.port
= default_port
;
433 /* Patch in specified username. */
434 strncpy(cfg
.username
, user
,
435 sizeof(cfg
.username
) - 1);
436 cfg
.username
[sizeof(cfg
.username
) - 1] = '\0';
443 cmdlen
= cmdsize
= 0;
448 if (cmdlen
>= cmdsize
) {
449 cmdsize
= cmdlen
+ 512;
450 command
= sresize(command
, cmdsize
, char);
452 command
[cmdlen
++]=*p
++;
454 if (cmdlen
>= cmdsize
) {
455 cmdsize
= cmdlen
+ 512;
456 command
= sresize(command
, cmdsize
, char);
458 command
[cmdlen
++]=' '; /* always add trailing space */
459 if (--argc
) p
= *++argv
;
461 if (cmdlen
) command
[--cmdlen
]='\0';
462 /* change trailing blank to NUL */
463 cfg
.remote_cmd_ptr
= command
;
464 cfg
.remote_cmd_ptr2
= NULL
;
465 cfg
.nopty
= TRUE
; /* command => no terminal */
467 break; /* done with cmdline */
475 if (!cfg_launchable(&cfg
)) {
480 * Trim leading whitespace off the hostname if it's there.
483 int space
= strspn(cfg
.host
, " \t");
484 memmove(cfg
.host
, cfg
.host
+space
, 1+strlen(cfg
.host
)-space
);
487 /* See if host is of the form user@host */
488 if (cfg_launchable(&cfg
)) {
489 char *atsign
= strrchr(cfg
.host
, '@');
490 /* Make sure we're not overflowing the user field */
492 if (atsign
- cfg
.host
< sizeof cfg
.username
) {
493 strncpy(cfg
.username
, cfg
.host
, atsign
- cfg
.host
);
494 cfg
.username
[atsign
- cfg
.host
] = '\0';
496 memmove(cfg
.host
, atsign
+ 1, 1 + strlen(atsign
+ 1));
501 * Perform command-line overrides on session configuration.
503 cmdline_run_saved(&cfg
);
506 * Apply subsystem status.
509 cfg
.ssh_subsys
= TRUE
;
512 * Trim a colon suffix off the hostname if it's there.
514 cfg
.host
[strcspn(cfg
.host
, ":")] = '\0';
517 * Remove any remaining whitespace from the hostname.
521 while (cfg
.host
[p2
] != '\0') {
522 if (cfg
.host
[p2
] != ' ' && cfg
.host
[p2
] != '\t') {
523 cfg
.host
[p1
] = cfg
.host
[p2
];
531 if (!cfg
.remote_cmd_ptr
&& !*cfg
.remote_cmd
&& !*cfg
.ssh_nc_host
)
532 flags
|= FLAG_INTERACTIVE
;
535 * Select protocol. This is farmed out into a table in a
536 * separate file to enable an ssh-free variant.
541 for (i
= 0; backends
[i
].backend
!= NULL
; i
++)
542 if (backends
[i
].protocol
== cfg
.protocol
) {
543 back
= backends
[i
].backend
;
548 "Internal fault: Unsupported protocol found\n");
556 if (portnumber
!= -1)
557 cfg
.port
= portnumber
;
560 if (p_WSAEventSelect
== NULL
) {
561 fprintf(stderr
, "Plink requires WinSock 2\n");
565 logctx
= log_init(NULL
, &cfg
);
566 console_provide_logctx(logctx
);
569 * Start up the connection.
571 netevent
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
575 /* nodelay is only useful if stdin is a character device (console) */
576 int nodelay
= cfg
.tcp_nodelay
&&
577 (GetFileType(GetStdHandle(STD_INPUT_HANDLE
)) == FILE_TYPE_CHAR
);
579 error
= back
->init(NULL
, &backhandle
, &cfg
, cfg
.host
, cfg
.port
,
580 &realhost
, nodelay
, cfg
.tcp_keepalives
);
582 fprintf(stderr
, "Unable to open connection:\n%s", error
);
585 back
->provide_logctx(backhandle
, logctx
);
590 inhandle
= GetStdHandle(STD_INPUT_HANDLE
);
591 outhandle
= GetStdHandle(STD_OUTPUT_HANDLE
);
592 errhandle
= GetStdHandle(STD_ERROR_HANDLE
);
595 * Turn off ECHO and LINE input modes. We don't care if this
596 * call fails, because we know we aren't necessarily running in
599 GetConsoleMode(inhandle
, &orig_console_mode
);
600 SetConsoleMode(inhandle
, ENABLE_PROCESSED_INPUT
);
603 * Pass the output handles to the handle-handling subsystem.
604 * (The input one we leave until we're through the
605 * authentication process.)
607 stdout_handle
= handle_output_new(outhandle
, stdouterr_sent
, NULL
, 0);
608 stderr_handle
= handle_output_new(errhandle
, stdouterr_sent
, NULL
, 0);
610 main_thread_id
= GetCurrentThreadId();
614 now
= GETTICKCOUNT();
622 if (!sending
&& back
->sendok(backhandle
)) {
623 stdin_handle
= handle_input_new(inhandle
, stdin_gotdata
, NULL
,
628 if (run_timers(now
, &next
)) {
629 ticks
= next
- GETTICKCOUNT();
630 if (ticks
< 0) ticks
= 0; /* just in case */
635 handles
= handle_get_events(&nhandles
);
636 handles
= sresize(handles
, nhandles
+1, HANDLE
);
637 handles
[nhandles
] = netevent
;
638 n
= MsgWaitForMultipleObjects(nhandles
+1, handles
, FALSE
, ticks
,
640 if ((unsigned)(n
- WAIT_OBJECT_0
) < (unsigned)nhandles
) {
641 handle_got_event(handles
[n
- WAIT_OBJECT_0
]);
642 } else if (n
== WAIT_OBJECT_0
+ nhandles
) {
643 WSANETWORKEVENTS things
;
645 extern SOCKET
first_socket(int *), next_socket(int *);
646 extern int select_result(WPARAM
, LPARAM
);
650 * We must not call select_result() for any socket
651 * until we have finished enumerating within the tree.
652 * This is because select_result() may close the socket
653 * and modify the tree.
655 /* Count the active sockets. */
657 for (socket
= first_socket(&socketstate
);
658 socket
!= INVALID_SOCKET
;
659 socket
= next_socket(&socketstate
)) i
++;
661 /* Expand the buffer if necessary. */
664 sklist
= sresize(sklist
, sksize
, SOCKET
);
667 /* Retrieve the sockets into sklist. */
669 for (socket
= first_socket(&socketstate
);
670 socket
!= INVALID_SOCKET
;
671 socket
= next_socket(&socketstate
)) {
672 sklist
[skcount
++] = socket
;
675 /* Now we're done enumerating; go through the list. */
676 for (i
= 0; i
< skcount
; i
++) {
679 wp
= (WPARAM
) socket
;
680 if (!p_WSAEnumNetworkEvents(socket
, NULL
, &things
)) {
681 static const struct { int bit
, mask
; } eventtypes
[] = {
682 {FD_CONNECT_BIT
, FD_CONNECT
},
683 {FD_READ_BIT
, FD_READ
},
684 {FD_CLOSE_BIT
, FD_CLOSE
},
685 {FD_OOB_BIT
, FD_OOB
},
686 {FD_WRITE_BIT
, FD_WRITE
},
687 {FD_ACCEPT_BIT
, FD_ACCEPT
},
691 noise_ultralight(socket
);
692 noise_ultralight(things
.lNetworkEvents
);
694 for (e
= 0; e
< lenof(eventtypes
); e
++)
695 if (things
.lNetworkEvents
& eventtypes
[e
].mask
) {
697 int err
= things
.iErrorCode
[eventtypes
[e
].bit
];
698 lp
= WSAMAKESELECTREPLY(eventtypes
[e
].mask
, err
);
699 connopen
&= select_result(wp
, lp
);
703 } else if (n
== WAIT_OBJECT_0
+ nhandles
+ 1) {
705 while (PeekMessage(&msg
, INVALID_HANDLE_VALUE
,
706 WM_AGENT_CALLBACK
, WM_AGENT_CALLBACK
,
708 struct agent_callback
*c
= (struct agent_callback
*)msg
.lParam
;
709 c
->callback(c
->callback_ctx
, c
->data
, c
->len
);
714 if (n
== WAIT_TIMEOUT
) {
717 now
= GETTICKCOUNT();
723 handle_unthrottle(stdin_handle
, back
->sendbuffer(backhandle
));
725 if ((!connopen
|| !back
->connected(backhandle
)) &&
726 handle_backlog(stdout_handle
) + handle_backlog(stderr_handle
) == 0)
727 break; /* we closed the connection */
729 exitcode
= back
->exitcode(backhandle
);
731 fprintf(stderr
, "Remote process exit code unavailable\n");
732 exitcode
= 1; /* this is an error condition */
734 cleanup_exit(exitcode
);
735 return 0; /* placate compiler warning */