fbeb538f4658bcd3e6397fdcd69658350ab7e1e7
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");
182 printf(" -nc host:port\n");
183 printf(" open tunnel in place of session (SSH-2 only)\n");
187 static void version(void)
189 printf("plink: %s\n", ver
);
193 char *do_select(SOCKET skt
, int startup
)
197 events
= (FD_CONNECT
| FD_READ
| FD_WRITE
|
198 FD_OOB
| FD_CLOSE
| FD_ACCEPT
);
202 if (p_WSAEventSelect(skt
, netevent
, events
) == SOCKET_ERROR
) {
203 switch (p_WSAGetLastError()) {
205 return "Network is down";
207 return "WSAEventSelect(): unknown error";
213 int stdin_gotdata(struct handle
*h
, void *data
, int len
)
217 * Special case: report read error.
219 fprintf(stderr
, "Unable to read from standard input\n");
222 noise_ultralight(len
);
223 if (connopen
&& back
->connected(backhandle
)) {
225 return back
->send(backhandle
, data
, len
);
227 back
->special(backhandle
, TS_EOF
);
234 void stdouterr_sent(struct handle
*h
, int new_backlog
)
236 if (new_backlog
< 0) {
238 * Special case: report write error.
240 fprintf(stderr
, "Unable to write to standard %s\n",
241 (h
== stdout_handle ?
"output" : "error"));
244 if (connopen
&& back
->connected(backhandle
)) {
245 back
->unthrottle(backhandle
, (handle_backlog(stdout_handle
) +
246 handle_backlog(stderr_handle
)));
250 int main(int argc
, char **argv
)
258 int use_subsystem
= 0;
262 skcount
= sksize
= 0;
264 * Initialise port and protocol to sensible defaults. (These
265 * will be overridden by more or less anything.)
267 default_protocol
= PROT_SSH
;
272 * Process the command line.
274 do_defaults(NULL
, &cfg
);
275 loaded_session
= FALSE
;
276 default_protocol
= cfg
.protocol
;
277 default_port
= cfg
.port
;
281 * Override the default protocol if PLINK_PROTOCOL is set.
283 char *p
= getenv("PLINK_PROTOCOL");
286 for (i
= 0; backends
[i
].backend
!= NULL
; i
++) {
287 if (!strcmp(backends
[i
].name
, p
)) {
288 default_protocol
= cfg
.protocol
= backends
[i
].protocol
;
289 default_port
= cfg
.port
=
290 backends
[i
].backend
->default_port
;
299 int ret
= cmdline_process_param(p
, (argc
> 1 ? argv
[1] : NULL
),
303 "plink: option \"%s\" requires an argument\n", p
);
305 } else if (ret
== 2) {
307 } else if (ret
== 1) {
309 } else if (!strcmp(p
, "-batch")) {
310 console_batch_mode
= 1;
311 } else if (!strcmp(p
, "-s")) {
312 /* Save status to write to cfg later. */
314 } else if (!strcmp(p
, "-V")) {
316 } else if (!strcmp(p
, "-pgpfp")) {
320 fprintf(stderr
, "plink: unknown option \"%s\"\n", p
);
324 if (!cfg_launchable(&cfg
)) {
327 * If the hostname starts with "telnet:", set the
328 * protocol to Telnet and process the string as a
331 if (!strncmp(q
, "telnet:", 7)) {
335 if (q
[0] == '/' && q
[1] == '/')
337 cfg
.protocol
= PROT_TELNET
;
339 while (*p
&& *p
!= ':' && *p
!= '/')
348 strncpy(cfg
.host
, q
, sizeof(cfg
.host
) - 1);
349 cfg
.host
[sizeof(cfg
.host
) - 1] = '\0';
351 char *r
, *user
, *host
;
353 * Before we process the [user@]host string, we
354 * first check for the presence of a protocol
355 * prefix (a protocol name followed by ",").
360 for (i
= 0; backends
[i
].backend
!= NULL
; i
++) {
361 j
= strlen(backends
[i
].name
);
363 !memcmp(backends
[i
].name
, p
, j
)) {
364 default_protocol
= cfg
.protocol
=
365 backends
[i
].protocol
;
367 backends
[i
].backend
->default_port
;
375 * A nonzero length string followed by an @ is treated
376 * as a username. (We discount an _initial_ @.) The
377 * rest of the string (or the whole string if no @)
378 * is treated as a session name and/or hostname.
382 p
++, r
= NULL
; /* discount initial @ */
387 user
= NULL
, host
= p
;
391 * Now attempt to load a saved session with the
392 * same name as the hostname.
396 do_defaults(host
, &cfg2
);
397 if (loaded_session
|| !cfg_launchable(&cfg2
)) {
398 /* No settings for this host; use defaults */
399 /* (or session was already loaded with -load) */
400 strncpy(cfg
.host
, host
, sizeof(cfg
.host
) - 1);
401 cfg
.host
[sizeof(cfg
.host
) - 1] = '\0';
402 cfg
.port
= default_port
;
409 /* Patch in specified username. */
410 strncpy(cfg
.username
, user
,
411 sizeof(cfg
.username
) - 1);
412 cfg
.username
[sizeof(cfg
.username
) - 1] = '\0';
419 cmdlen
= cmdsize
= 0;
424 if (cmdlen
>= cmdsize
) {
425 cmdsize
= cmdlen
+ 512;
426 command
= sresize(command
, cmdsize
, char);
428 command
[cmdlen
++]=*p
++;
430 if (cmdlen
>= cmdsize
) {
431 cmdsize
= cmdlen
+ 512;
432 command
= sresize(command
, cmdsize
, char);
434 command
[cmdlen
++]=' '; /* always add trailing space */
435 if (--argc
) p
= *++argv
;
437 if (cmdlen
) command
[--cmdlen
]='\0';
438 /* change trailing blank to NUL */
439 cfg
.remote_cmd_ptr
= command
;
440 cfg
.remote_cmd_ptr2
= NULL
;
441 cfg
.nopty
= TRUE
; /* command => no terminal */
443 break; /* done with cmdline */
451 if (!cfg_launchable(&cfg
)) {
456 * Trim leading whitespace off the hostname if it's there.
459 int space
= strspn(cfg
.host
, " \t");
460 memmove(cfg
.host
, cfg
.host
+space
, 1+strlen(cfg
.host
)-space
);
463 /* See if host is of the form user@host */
464 if (cfg_launchable(&cfg
)) {
465 char *atsign
= strrchr(cfg
.host
, '@');
466 /* Make sure we're not overflowing the user field */
468 if (atsign
- cfg
.host
< sizeof cfg
.username
) {
469 strncpy(cfg
.username
, cfg
.host
, atsign
- cfg
.host
);
470 cfg
.username
[atsign
- cfg
.host
] = '\0';
472 memmove(cfg
.host
, atsign
+ 1, 1 + strlen(atsign
+ 1));
477 * Perform command-line overrides on session configuration.
479 cmdline_run_saved(&cfg
);
482 * Apply subsystem status.
485 cfg
.ssh_subsys
= TRUE
;
488 * Trim a colon suffix off the hostname if it's there.
490 cfg
.host
[strcspn(cfg
.host
, ":")] = '\0';
493 * Remove any remaining whitespace from the hostname.
497 while (cfg
.host
[p2
] != '\0') {
498 if (cfg
.host
[p2
] != ' ' && cfg
.host
[p2
] != '\t') {
499 cfg
.host
[p1
] = cfg
.host
[p2
];
507 if (!cfg
.remote_cmd_ptr
&& !*cfg
.remote_cmd
&& !*cfg
.ssh_nc_host
)
508 flags
|= FLAG_INTERACTIVE
;
511 * Select protocol. This is farmed out into a table in a
512 * separate file to enable an ssh-free variant.
517 for (i
= 0; backends
[i
].backend
!= NULL
; i
++)
518 if (backends
[i
].protocol
== cfg
.protocol
) {
519 back
= backends
[i
].backend
;
524 "Internal fault: Unsupported protocol found\n");
532 if (portnumber
!= -1)
533 cfg
.port
= portnumber
;
536 if (p_WSAEventSelect
== NULL
) {
537 fprintf(stderr
, "Plink requires WinSock 2\n");
541 logctx
= log_init(NULL
, &cfg
);
542 console_provide_logctx(logctx
);
545 * Start up the connection.
547 netevent
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
551 /* nodelay is only useful if stdin is a character device (console) */
552 int nodelay
= cfg
.tcp_nodelay
&&
553 (GetFileType(GetStdHandle(STD_INPUT_HANDLE
)) == FILE_TYPE_CHAR
);
555 error
= back
->init(NULL
, &backhandle
, &cfg
, cfg
.host
, cfg
.port
,
556 &realhost
, nodelay
, cfg
.tcp_keepalives
);
558 fprintf(stderr
, "Unable to open connection:\n%s", error
);
561 back
->provide_logctx(backhandle
, logctx
);
566 inhandle
= GetStdHandle(STD_INPUT_HANDLE
);
567 outhandle
= GetStdHandle(STD_OUTPUT_HANDLE
);
568 errhandle
= GetStdHandle(STD_ERROR_HANDLE
);
571 * Turn off ECHO and LINE input modes. We don't care if this
572 * call fails, because we know we aren't necessarily running in
575 GetConsoleMode(inhandle
, &orig_console_mode
);
576 SetConsoleMode(inhandle
, ENABLE_PROCESSED_INPUT
);
579 * Pass the output handles to the handle-handling subsystem.
580 * (The input one we leave until we're through the
581 * authentication process.)
583 stdout_handle
= handle_output_new(outhandle
, stdouterr_sent
, NULL
, 0);
584 stderr_handle
= handle_output_new(errhandle
, stdouterr_sent
, NULL
, 0);
586 main_thread_id
= GetCurrentThreadId();
590 now
= GETTICKCOUNT();
598 if (!sending
&& back
->sendok(backhandle
)) {
599 stdin_handle
= handle_input_new(inhandle
, stdin_gotdata
, NULL
,
604 if (run_timers(now
, &next
)) {
605 ticks
= next
- GETTICKCOUNT();
606 if (ticks
< 0) ticks
= 0; /* just in case */
611 handles
= handle_get_events(&nhandles
);
612 handles
= sresize(handles
, nhandles
+1, HANDLE
);
613 handles
[nhandles
] = netevent
;
614 n
= MsgWaitForMultipleObjects(nhandles
+1, handles
, FALSE
, ticks
,
616 if ((unsigned)(n
- WAIT_OBJECT_0
) < (unsigned)nhandles
) {
617 handle_got_event(handles
[n
- WAIT_OBJECT_0
]);
618 } else if (n
== WAIT_OBJECT_0
+ nhandles
) {
619 WSANETWORKEVENTS things
;
621 extern SOCKET
first_socket(int *), next_socket(int *);
622 extern int select_result(WPARAM
, LPARAM
);
626 * We must not call select_result() for any socket
627 * until we have finished enumerating within the tree.
628 * This is because select_result() may close the socket
629 * and modify the tree.
631 /* Count the active sockets. */
633 for (socket
= first_socket(&socketstate
);
634 socket
!= INVALID_SOCKET
;
635 socket
= next_socket(&socketstate
)) i
++;
637 /* Expand the buffer if necessary. */
640 sklist
= sresize(sklist
, sksize
, SOCKET
);
643 /* Retrieve the sockets into sklist. */
645 for (socket
= first_socket(&socketstate
);
646 socket
!= INVALID_SOCKET
;
647 socket
= next_socket(&socketstate
)) {
648 sklist
[skcount
++] = socket
;
651 /* Now we're done enumerating; go through the list. */
652 for (i
= 0; i
< skcount
; i
++) {
655 wp
= (WPARAM
) socket
;
656 if (!p_WSAEnumNetworkEvents(socket
, NULL
, &things
)) {
657 static const struct { int bit
, mask
; } eventtypes
[] = {
658 {FD_CONNECT_BIT
, FD_CONNECT
},
659 {FD_READ_BIT
, FD_READ
},
660 {FD_CLOSE_BIT
, FD_CLOSE
},
661 {FD_OOB_BIT
, FD_OOB
},
662 {FD_WRITE_BIT
, FD_WRITE
},
663 {FD_ACCEPT_BIT
, FD_ACCEPT
},
667 noise_ultralight(socket
);
668 noise_ultralight(things
.lNetworkEvents
);
670 for (e
= 0; e
< lenof(eventtypes
); e
++)
671 if (things
.lNetworkEvents
& eventtypes
[e
].mask
) {
673 int err
= things
.iErrorCode
[eventtypes
[e
].bit
];
674 lp
= WSAMAKESELECTREPLY(eventtypes
[e
].mask
, err
);
675 connopen
&= select_result(wp
, lp
);
679 } else if (n
== WAIT_OBJECT_0
+ nhandles
+ 1) {
681 while (PeekMessage(&msg
, INVALID_HANDLE_VALUE
,
682 WM_AGENT_CALLBACK
, WM_AGENT_CALLBACK
,
684 struct agent_callback
*c
= (struct agent_callback
*)msg
.lParam
;
685 c
->callback(c
->callback_ctx
, c
->data
, c
->len
);
690 if (n
== WAIT_TIMEOUT
) {
693 now
= GETTICKCOUNT();
699 handle_unthrottle(stdin_handle
, back
->sendbuffer(backhandle
));
701 if ((!connopen
|| !back
->connected(backhandle
)) &&
702 handle_backlog(stdout_handle
) + handle_backlog(stderr_handle
) == 0)
703 break; /* we closed the connection */
705 exitcode
= back
->exitcode(backhandle
);
707 fprintf(stderr
, "Remote process exit code unavailable\n");
708 exitcode
= 1; /* this is an error condition */
710 cleanup_exit(exitcode
);
711 return 0; /* placate compiler warning */