16351ae9d774de3c3bce1ce539833fc5ccca42f2
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");
185 static void version(void)
187 printf("plink: %s\n", ver
);
191 char *do_select(SOCKET skt
, int startup
)
195 events
= (FD_CONNECT
| FD_READ
| FD_WRITE
|
196 FD_OOB
| FD_CLOSE
| FD_ACCEPT
);
200 if (p_WSAEventSelect(skt
, netevent
, events
) == SOCKET_ERROR
) {
201 switch (p_WSAGetLastError()) {
203 return "Network is down";
205 return "WSAEventSelect(): unknown error";
211 int stdin_gotdata(struct handle
*h
, void *data
, int len
)
215 * Special case: report read error.
217 fprintf(stderr
, "Unable to read from standard input\n");
220 noise_ultralight(len
);
221 if (connopen
&& back
->connected(backhandle
)) {
223 return back
->send(backhandle
, data
, len
);
225 back
->special(backhandle
, TS_EOF
);
232 void stdouterr_sent(struct handle
*h
, int new_backlog
)
234 if (new_backlog
< 0) {
236 * Special case: report write error.
238 fprintf(stderr
, "Unable to write to standard %s\n",
239 (h
== stdout_handle ?
"output" : "error"));
242 if (connopen
&& back
->connected(backhandle
)) {
243 back
->unthrottle(backhandle
, (handle_backlog(stdout_handle
) +
244 handle_backlog(stderr_handle
)));
248 int main(int argc
, char **argv
)
256 int use_subsystem
= 0;
260 skcount
= sksize
= 0;
262 * Initialise port and protocol to sensible defaults. (These
263 * will be overridden by more or less anything.)
265 default_protocol
= PROT_SSH
;
270 * Process the command line.
272 do_defaults(NULL
, &cfg
);
273 loaded_session
= FALSE
;
274 default_protocol
= cfg
.protocol
;
275 default_port
= cfg
.port
;
279 * Override the default protocol if PLINK_PROTOCOL is set.
281 char *p
= getenv("PLINK_PROTOCOL");
284 for (i
= 0; backends
[i
].backend
!= NULL
; i
++) {
285 if (!strcmp(backends
[i
].name
, p
)) {
286 default_protocol
= cfg
.protocol
= backends
[i
].protocol
;
287 default_port
= cfg
.port
=
288 backends
[i
].backend
->default_port
;
297 int ret
= cmdline_process_param(p
, (argc
> 1 ? argv
[1] : NULL
),
301 "plink: option \"%s\" requires an argument\n", p
);
303 } else if (ret
== 2) {
305 } else if (ret
== 1) {
307 } else if (!strcmp(p
, "-batch")) {
308 console_batch_mode
= 1;
309 } else if (!strcmp(p
, "-s")) {
310 /* Save status to write to cfg later. */
312 } else if (!strcmp(p
, "-V")) {
314 } else if (!strcmp(p
, "-pgpfp")) {
318 fprintf(stderr
, "plink: unknown option \"%s\"\n", p
);
325 * If the hostname starts with "telnet:", set the
326 * protocol to Telnet and process the string as a
329 if (!strncmp(q
, "telnet:", 7)) {
333 if (q
[0] == '/' && q
[1] == '/')
335 cfg
.protocol
= PROT_TELNET
;
337 while (*p
&& *p
!= ':' && *p
!= '/')
346 strncpy(cfg
.host
, q
, sizeof(cfg
.host
) - 1);
347 cfg
.host
[sizeof(cfg
.host
) - 1] = '\0';
349 char *r
, *user
, *host
;
351 * Before we process the [user@]host string, we
352 * first check for the presence of a protocol
353 * prefix (a protocol name followed by ",").
358 for (i
= 0; backends
[i
].backend
!= NULL
; i
++) {
359 j
= strlen(backends
[i
].name
);
361 !memcmp(backends
[i
].name
, p
, j
)) {
362 default_protocol
= cfg
.protocol
=
363 backends
[i
].protocol
;
365 backends
[i
].backend
->default_port
;
373 * A nonzero length string followed by an @ is treated
374 * as a username. (We discount an _initial_ @.) The
375 * rest of the string (or the whole string if no @)
376 * is treated as a session name and/or hostname.
380 p
++, r
= NULL
; /* discount initial @ */
385 user
= NULL
, host
= p
;
389 * Now attempt to load a saved session with the
390 * same name as the hostname.
394 do_defaults(host
, &cfg2
);
395 if (loaded_session
|| cfg2
.host
[0] == '\0') {
396 /* No settings for this host; use defaults */
397 /* (or session was already loaded with -load) */
398 strncpy(cfg
.host
, host
, sizeof(cfg
.host
) - 1);
399 cfg
.host
[sizeof(cfg
.host
) - 1] = '\0';
400 cfg
.port
= default_port
;
407 /* Patch in specified username. */
408 strncpy(cfg
.username
, user
,
409 sizeof(cfg
.username
) - 1);
410 cfg
.username
[sizeof(cfg
.username
) - 1] = '\0';
417 cmdlen
= cmdsize
= 0;
422 if (cmdlen
>= cmdsize
) {
423 cmdsize
= cmdlen
+ 512;
424 command
= sresize(command
, cmdsize
, char);
426 command
[cmdlen
++]=*p
++;
428 if (cmdlen
>= cmdsize
) {
429 cmdsize
= cmdlen
+ 512;
430 command
= sresize(command
, cmdsize
, char);
432 command
[cmdlen
++]=' '; /* always add trailing space */
433 if (--argc
) p
= *++argv
;
435 if (cmdlen
) command
[--cmdlen
]='\0';
436 /* change trailing blank to NUL */
437 cfg
.remote_cmd_ptr
= command
;
438 cfg
.remote_cmd_ptr2
= NULL
;
439 cfg
.nopty
= TRUE
; /* command => no terminal */
441 break; /* done with cmdline */
454 * Trim leading whitespace off the hostname if it's there.
457 int space
= strspn(cfg
.host
, " \t");
458 memmove(cfg
.host
, cfg
.host
+space
, 1+strlen(cfg
.host
)-space
);
461 /* See if host is of the form user@host */
462 if (cfg
.host
[0] != '\0') {
463 char *atsign
= strrchr(cfg
.host
, '@');
464 /* Make sure we're not overflowing the user field */
466 if (atsign
- cfg
.host
< sizeof cfg
.username
) {
467 strncpy(cfg
.username
, cfg
.host
, atsign
- cfg
.host
);
468 cfg
.username
[atsign
- cfg
.host
] = '\0';
470 memmove(cfg
.host
, atsign
+ 1, 1 + strlen(atsign
+ 1));
475 * Perform command-line overrides on session configuration.
477 cmdline_run_saved(&cfg
);
480 * Apply subsystem status.
483 cfg
.ssh_subsys
= TRUE
;
486 * Trim a colon suffix off the hostname if it's there.
488 cfg
.host
[strcspn(cfg
.host
, ":")] = '\0';
491 * Remove any remaining whitespace from the hostname.
495 while (cfg
.host
[p2
] != '\0') {
496 if (cfg
.host
[p2
] != ' ' && cfg
.host
[p2
] != '\t') {
497 cfg
.host
[p1
] = cfg
.host
[p2
];
505 if (!cfg
.remote_cmd_ptr
&& !*cfg
.remote_cmd
)
506 flags
|= FLAG_INTERACTIVE
;
509 * Select protocol. This is farmed out into a table in a
510 * separate file to enable an ssh-free variant.
515 for (i
= 0; backends
[i
].backend
!= NULL
; i
++)
516 if (backends
[i
].protocol
== cfg
.protocol
) {
517 back
= backends
[i
].backend
;
522 "Internal fault: Unsupported protocol found\n");
530 if (portnumber
!= -1)
531 cfg
.port
= portnumber
;
534 if (p_WSAEventSelect
== NULL
) {
535 fprintf(stderr
, "Plink requires WinSock 2\n");
540 * Start up the connection.
542 netevent
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
546 /* nodelay is only useful if stdin is a character device (console) */
547 int nodelay
= cfg
.tcp_nodelay
&&
548 (GetFileType(GetStdHandle(STD_INPUT_HANDLE
)) == FILE_TYPE_CHAR
);
550 error
= back
->init(NULL
, &backhandle
, &cfg
, cfg
.host
, cfg
.port
,
551 &realhost
, nodelay
, cfg
.tcp_keepalives
);
553 fprintf(stderr
, "Unable to open connection:\n%s", error
);
556 logctx
= log_init(NULL
, &cfg
);
557 back
->provide_logctx(backhandle
, logctx
);
558 console_provide_logctx(logctx
);
563 inhandle
= GetStdHandle(STD_INPUT_HANDLE
);
564 outhandle
= GetStdHandle(STD_OUTPUT_HANDLE
);
565 errhandle
= GetStdHandle(STD_ERROR_HANDLE
);
568 * Turn off ECHO and LINE input modes. We don't care if this
569 * call fails, because we know we aren't necessarily running in
572 GetConsoleMode(inhandle
, &orig_console_mode
);
573 SetConsoleMode(inhandle
, ENABLE_PROCESSED_INPUT
);
576 * Pass the output handles to the handle-handling subsystem.
577 * (The input one we leave until we're through the
578 * authentication process.)
580 stdout_handle
= handle_output_new(outhandle
, stdouterr_sent
, NULL
);
581 stderr_handle
= handle_output_new(errhandle
, stdouterr_sent
, NULL
);
583 main_thread_id
= GetCurrentThreadId();
587 now
= GETTICKCOUNT();
595 if (!sending
&& back
->sendok(backhandle
)) {
596 stdin_handle
= handle_input_new(inhandle
, stdin_gotdata
, NULL
);
600 if (run_timers(now
, &next
)) {
601 ticks
= next
- GETTICKCOUNT();
602 if (ticks
< 0) ticks
= 0; /* just in case */
607 handles
= handle_get_events(&nhandles
);
608 handles
= sresize(handles
, nhandles
+1, HANDLE
);
609 handles
[nhandles
] = netevent
;
610 n
= MsgWaitForMultipleObjects(nhandles
+1, handles
, FALSE
, ticks
,
612 if ((unsigned)(n
- WAIT_OBJECT_0
) < (unsigned)nhandles
) {
613 handle_got_event(handles
[n
- WAIT_OBJECT_0
]);
614 } else if (n
== WAIT_OBJECT_0
+ nhandles
) {
615 WSANETWORKEVENTS things
;
617 extern SOCKET
first_socket(int *), next_socket(int *);
618 extern int select_result(WPARAM
, LPARAM
);
622 * We must not call select_result() for any socket
623 * until we have finished enumerating within the tree.
624 * This is because select_result() may close the socket
625 * and modify the tree.
627 /* Count the active sockets. */
629 for (socket
= first_socket(&socketstate
);
630 socket
!= INVALID_SOCKET
;
631 socket
= next_socket(&socketstate
)) i
++;
633 /* Expand the buffer if necessary. */
636 sklist
= sresize(sklist
, sksize
, SOCKET
);
639 /* Retrieve the sockets into sklist. */
641 for (socket
= first_socket(&socketstate
);
642 socket
!= INVALID_SOCKET
;
643 socket
= next_socket(&socketstate
)) {
644 sklist
[skcount
++] = socket
;
647 /* Now we're done enumerating; go through the list. */
648 for (i
= 0; i
< skcount
; i
++) {
651 wp
= (WPARAM
) socket
;
652 if (!p_WSAEnumNetworkEvents(socket
, NULL
, &things
)) {
653 static const struct { int bit
, mask
; } eventtypes
[] = {
654 {FD_CONNECT_BIT
, FD_CONNECT
},
655 {FD_READ_BIT
, FD_READ
},
656 {FD_CLOSE_BIT
, FD_CLOSE
},
657 {FD_OOB_BIT
, FD_OOB
},
658 {FD_WRITE_BIT
, FD_WRITE
},
659 {FD_ACCEPT_BIT
, FD_ACCEPT
},
663 noise_ultralight(socket
);
664 noise_ultralight(things
.lNetworkEvents
);
666 for (e
= 0; e
< lenof(eventtypes
); e
++)
667 if (things
.lNetworkEvents
& eventtypes
[e
].mask
) {
669 int err
= things
.iErrorCode
[eventtypes
[e
].bit
];
670 lp
= WSAMAKESELECTREPLY(eventtypes
[e
].mask
, err
);
671 connopen
&= select_result(wp
, lp
);
675 } else if (n
== WAIT_OBJECT_0
+ nhandles
+ 1) {
677 while (PeekMessage(&msg
, INVALID_HANDLE_VALUE
,
678 WM_AGENT_CALLBACK
, WM_AGENT_CALLBACK
,
680 struct agent_callback
*c
= (struct agent_callback
*)msg
.lParam
;
681 c
->callback(c
->callback_ctx
, c
->data
, c
->len
);
686 if (n
== WAIT_TIMEOUT
) {
689 now
= GETTICKCOUNT();
695 handle_unthrottle(stdin_handle
, back
->sendbuffer(backhandle
));
697 if ((!connopen
|| !back
->connected(backhandle
)) &&
698 handle_backlog(stdout_handle
) + handle_backlog(stderr_handle
) == 0)
699 break; /* we closed the connection */
701 exitcode
= back
->exitcode(backhandle
);
703 fprintf(stderr
, "Remote process exit code unavailable\n");
704 exitcode
= 1; /* this is an error condition */
706 cleanup_exit(exitcode
);
707 return 0; /* placate compiler warning */