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_XUSER + 4)
17 #define MAX_STDIN_BACKLOG 4096
19 struct agent_callback
{
20 void (*callback
)(void *, void *, int);
26 void fatalbox(char *p
, ...)
29 fprintf(stderr
, "FATAL ERROR: ");
31 vfprintf(stderr
, p
, ap
);
36 void modalfatalbox(char *p
, ...)
39 fprintf(stderr
, "FATAL ERROR: ");
41 vfprintf(stderr
, p
, ap
);
46 void connection_fatal(void *frontend
, char *p
, ...)
49 fprintf(stderr
, "FATAL ERROR: ");
51 vfprintf(stderr
, p
, ap
);
56 void cmdline_error(char *p
, ...)
59 fprintf(stderr
, "plink: ");
61 vfprintf(stderr
, p
, ap
);
67 HANDLE inhandle
, outhandle
, errhandle
;
68 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
);
100 HANDLE event
, eventback
;
103 static DWORD WINAPI
stdin_read_thread(void *param
)
105 struct input_data
*idata
= (struct input_data
*) param
;
108 inhandle
= GetStdHandle(STD_INPUT_HANDLE
);
110 while (ReadFile(inhandle
, idata
->buffer
, sizeof(idata
->buffer
),
111 &idata
->len
, NULL
) && idata
->len
> 0) {
112 SetEvent(idata
->event
);
113 WaitForSingleObject(idata
->eventback
, INFINITE
);
117 SetEvent(idata
->event
);
123 DWORD len
, lenwritten
;
127 HANDLE event
, eventback
;
131 static DWORD WINAPI
stdout_write_thread(void *param
)
133 struct output_data
*odata
= (struct output_data
*) param
;
134 HANDLE outhandle
, errhandle
;
136 outhandle
= GetStdHandle(STD_OUTPUT_HANDLE
);
137 errhandle
= GetStdHandle(STD_ERROR_HANDLE
);
140 WaitForSingleObject(odata
->eventback
, INFINITE
);
144 WriteFile(odata
->is_stderr ? errhandle
: outhandle
,
145 odata
->buffer
, odata
->len
, &odata
->lenwritten
, NULL
);
146 SetEvent(odata
->event
);
152 bufchain stdout_data
, stderr_data
;
153 struct output_data odata
, edata
;
155 void try_output(int is_stderr
)
157 struct output_data
*data
= (is_stderr ?
&edata
: &odata
);
162 bufchain_prefix(is_stderr ?
&stderr_data
: &stdout_data
,
163 &senddata
, &sendlen
);
164 data
->buffer
= senddata
;
166 SetEvent(data
->eventback
);
171 int from_backend(void *frontend_handle
, int is_stderr
,
172 const char *data
, int len
)
177 bufchain_add(&stderr_data
, data
, len
);
180 bufchain_add(&stdout_data
, data
, len
);
184 osize
= bufchain_size(&stdout_data
);
185 esize
= bufchain_size(&stderr_data
);
187 return osize
+ esize
;
190 static DWORD main_thread_id
;
192 void agent_schedule_callback(void (*callback
)(void *, void *, int),
193 void *callback_ctx
, void *data
, int len
)
195 struct agent_callback
*c
= snew(struct agent_callback
);
196 c
->callback
= callback
;
197 c
->callback_ctx
= callback_ctx
;
200 PostThreadMessage(main_thread_id
, WM_AGENT_CALLBACK
, 0, (LPARAM
)c
);
204 * Short description of parameters.
206 static void usage(void)
208 printf("PuTTY Link: command-line connection utility\n");
210 printf("Usage: plink [options] [user@]host [command]\n");
211 printf(" (\"host\" can also be a PuTTY saved session name)\n");
212 printf("Options:\n");
213 printf(" -V print version information\n");
214 printf(" -v show verbose messages\n");
215 printf(" -load sessname Load settings from saved session\n");
216 printf(" -ssh -telnet -rlogin -raw\n");
217 printf(" force use of a particular protocol\n");
218 printf(" -P port connect to specified port\n");
219 printf(" -l user connect with specified username\n");
220 printf(" -m file read remote command(s) from file\n");
221 printf(" -batch disable all interactive prompts\n");
222 printf("The following options only apply to SSH connections:\n");
223 printf(" -pw passw login with specified password\n");
224 printf(" -D [listen-IP:]listen-port\n");
225 printf(" Dynamic SOCKS-based port forwarding\n");
226 printf(" -L [listen-IP:]listen-port:host:port\n");
227 printf(" Forward local port to remote address\n");
228 printf(" -R [listen-IP:]listen-port:host:port\n");
229 printf(" Forward remote port to local address\n");
230 printf(" -X -x enable / disable X11 forwarding\n");
231 printf(" -A -a enable / disable agent forwarding\n");
232 printf(" -t -T enable / disable pty allocation\n");
233 printf(" -1 -2 force use of particular protocol version\n");
234 printf(" -4 -6 force use of IPv4 or IPv6\n");
235 printf(" -C enable compression\n");
236 printf(" -i key private key file for authentication\n");
237 printf(" -s remote command is an SSH subsystem (SSH-2 only)\n");
238 printf(" -N don't start a shell/command (SSH-2 only)\n");
242 static void version(void)
244 printf("plink: %s\n", ver
);
248 char *do_select(SOCKET skt
, int startup
)
252 events
= (FD_CONNECT
| FD_READ
| FD_WRITE
|
253 FD_OOB
| FD_CLOSE
| FD_ACCEPT
);
257 if (p_WSAEventSelect(skt
, netevent
, events
) == SOCKET_ERROR
) {
258 switch (p_WSAGetLastError()) {
260 return "Network is down";
262 return "WSAEventSelect(): unknown error";
268 int main(int argc
, char **argv
)
270 WSAEVENT stdinevent
, stdoutevent
, stderrevent
;
272 DWORD in_threadid
, out_threadid
, err_threadid
;
273 struct input_data idata
;
282 int use_subsystem
= 0;
285 ssh_get_line
= console_get_line
;
288 skcount
= sksize
= 0;
290 * Initialise port and protocol to sensible defaults. (These
291 * will be overridden by more or less anything.)
293 default_protocol
= PROT_SSH
;
298 * Process the command line.
300 do_defaults(NULL
, &cfg
);
301 loaded_session
= FALSE
;
302 default_protocol
= cfg
.protocol
;
303 default_port
= cfg
.port
;
307 * Override the default protocol if PLINK_PROTOCOL is set.
309 char *p
= getenv("PLINK_PROTOCOL");
312 for (i
= 0; backends
[i
].backend
!= NULL
; i
++) {
313 if (!strcmp(backends
[i
].name
, p
)) {
314 default_protocol
= cfg
.protocol
= backends
[i
].protocol
;
315 default_port
= cfg
.port
=
316 backends
[i
].backend
->default_port
;
325 int ret
= cmdline_process_param(p
, (argc
> 1 ? argv
[1] : NULL
),
329 "plink: option \"%s\" requires an argument\n", p
);
331 } else if (ret
== 2) {
333 } else if (ret
== 1) {
335 } else if (!strcmp(p
, "-batch")) {
336 console_batch_mode
= 1;
337 } else if (!strcmp(p
, "-s")) {
338 /* Save status to write to cfg later. */
340 } else if (!strcmp(p
, "-V")) {
343 fprintf(stderr
, "plink: unknown option \"%s\"\n", p
);
350 * If the hostname starts with "telnet:", set the
351 * protocol to Telnet and process the string as a
354 if (!strncmp(q
, "telnet:", 7)) {
358 if (q
[0] == '/' && q
[1] == '/')
360 cfg
.protocol
= PROT_TELNET
;
362 while (*p
&& *p
!= ':' && *p
!= '/')
371 strncpy(cfg
.host
, q
, sizeof(cfg
.host
) - 1);
372 cfg
.host
[sizeof(cfg
.host
) - 1] = '\0';
374 char *r
, *user
, *host
;
376 * Before we process the [user@]host string, we
377 * first check for the presence of a protocol
378 * prefix (a protocol name followed by ",").
383 for (i
= 0; backends
[i
].backend
!= NULL
; i
++) {
384 j
= strlen(backends
[i
].name
);
386 !memcmp(backends
[i
].name
, p
, j
)) {
387 default_protocol
= cfg
.protocol
=
388 backends
[i
].protocol
;
390 backends
[i
].backend
->default_port
;
398 * A nonzero length string followed by an @ is treated
399 * as a username. (We discount an _initial_ @.) The
400 * rest of the string (or the whole string if no @)
401 * is treated as a session name and/or hostname.
405 p
++, r
= NULL
; /* discount initial @ */
410 user
= NULL
, host
= p
;
414 * Now attempt to load a saved session with the
415 * same name as the hostname.
419 do_defaults(host
, &cfg2
);
420 if (loaded_session
|| cfg2
.host
[0] == '\0') {
421 /* No settings for this host; use defaults */
422 /* (or session was already loaded with -load) */
423 strncpy(cfg
.host
, host
, sizeof(cfg
.host
) - 1);
424 cfg
.host
[sizeof(cfg
.host
) - 1] = '\0';
425 cfg
.port
= default_port
;
428 /* Ick: patch up internal pointer after copy */
429 cfg
.remote_cmd_ptr
= cfg
.remote_cmd
;
434 /* Patch in specified username. */
435 strncpy(cfg
.username
, user
,
436 sizeof(cfg
.username
) - 1);
437 cfg
.username
[sizeof(cfg
.username
) - 1] = '\0';
444 cmdlen
= cmdsize
= 0;
449 if (cmdlen
>= cmdsize
) {
450 cmdsize
= cmdlen
+ 512;
451 command
= sresize(command
, cmdsize
, char);
453 command
[cmdlen
++]=*p
++;
455 if (cmdlen
>= cmdsize
) {
456 cmdsize
= cmdlen
+ 512;
457 command
= sresize(command
, cmdsize
, char);
459 command
[cmdlen
++]=' '; /* always add trailing space */
460 if (--argc
) p
= *++argv
;
462 if (cmdlen
) command
[--cmdlen
]='\0';
463 /* change trailing blank to NUL */
464 cfg
.remote_cmd_ptr
= command
;
465 cfg
.remote_cmd_ptr2
= NULL
;
466 cfg
.nopty
= TRUE
; /* command => no terminal */
468 break; /* done with cmdline */
481 * Trim leading whitespace off the hostname if it's there.
484 int space
= strspn(cfg
.host
, " \t");
485 memmove(cfg
.host
, cfg
.host
+space
, 1+strlen(cfg
.host
)-space
);
488 /* See if host is of the form user@host */
489 if (cfg
.host
[0] != '\0') {
490 char *atsign
= strrchr(cfg
.host
, '@');
491 /* Make sure we're not overflowing the user field */
493 if (atsign
- cfg
.host
< sizeof cfg
.username
) {
494 strncpy(cfg
.username
, cfg
.host
, atsign
- cfg
.host
);
495 cfg
.username
[atsign
- cfg
.host
] = '\0';
497 memmove(cfg
.host
, atsign
+ 1, 1 + strlen(atsign
+ 1));
502 * Perform command-line overrides on session configuration.
504 cmdline_run_saved(&cfg
);
507 * Apply subsystem status.
510 cfg
.ssh_subsys
= TRUE
;
513 * Trim a colon suffix off the hostname if it's there.
515 cfg
.host
[strcspn(cfg
.host
, ":")] = '\0';
518 * Remove any remaining whitespace from the hostname.
522 while (cfg
.host
[p2
] != '\0') {
523 if (cfg
.host
[p2
] != ' ' && cfg
.host
[p2
] != '\t') {
524 cfg
.host
[p1
] = cfg
.host
[p2
];
532 if (!*cfg
.remote_cmd_ptr
)
533 flags
|= FLAG_INTERACTIVE
;
536 * Select protocol. This is farmed out into a table in a
537 * separate file to enable an ssh-free variant.
542 for (i
= 0; backends
[i
].backend
!= NULL
; i
++)
543 if (backends
[i
].protocol
== cfg
.protocol
) {
544 back
= backends
[i
].backend
;
549 "Internal fault: Unsupported protocol found\n");
557 if (portnumber
!= -1)
558 cfg
.port
= portnumber
;
561 if (p_WSAEventSelect
== NULL
) {
562 fprintf(stderr
, "Plink requires WinSock 2\n");
567 * Start up the connection.
569 netevent
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
573 /* nodelay is only useful if stdin is a character device (console) */
574 int nodelay
= cfg
.tcp_nodelay
&&
575 (GetFileType(GetStdHandle(STD_INPUT_HANDLE
)) == FILE_TYPE_CHAR
);
577 error
= back
->init(NULL
, &backhandle
, &cfg
, cfg
.host
, cfg
.port
,
578 &realhost
, nodelay
, cfg
.tcp_keepalives
);
580 fprintf(stderr
, "Unable to open connection:\n%s", error
);
583 logctx
= log_init(NULL
, &cfg
);
584 back
->provide_logctx(backhandle
, logctx
);
585 console_provide_logctx(logctx
);
590 stdinevent
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
591 stdoutevent
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
592 stderrevent
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
594 inhandle
= GetStdHandle(STD_INPUT_HANDLE
);
595 outhandle
= GetStdHandle(STD_OUTPUT_HANDLE
);
596 errhandle
= GetStdHandle(STD_ERROR_HANDLE
);
597 GetConsoleMode(inhandle
, &orig_console_mode
);
598 SetConsoleMode(inhandle
, ENABLE_PROCESSED_INPUT
);
600 main_thread_id
= GetCurrentThreadId();
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 handles
[0] = netevent
;
608 handles
[1] = stdinevent
;
609 handles
[2] = stdoutevent
;
610 handles
[3] = stderrevent
;
614 * Create spare threads to write to stdout and stderr, so we
615 * can arrange asynchronous writes.
617 odata
.event
= stdoutevent
;
618 odata
.eventback
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
620 odata
.busy
= odata
.done
= 0;
621 if (!CreateThread(NULL
, 0, stdout_write_thread
,
622 &odata
, 0, &out_threadid
)) {
623 fprintf(stderr
, "Unable to create output thread\n");
626 edata
.event
= stderrevent
;
627 edata
.eventback
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
629 edata
.busy
= edata
.done
= 0;
630 if (!CreateThread(NULL
, 0, stdout_write_thread
,
631 &edata
, 0, &err_threadid
)) {
632 fprintf(stderr
, "Unable to create error output thread\n");
636 now
= GETTICKCOUNT();
642 if (!sending
&& back
->sendok(backhandle
)) {
644 * Create a separate thread to read from stdin. This is
645 * a total pain, but I can't find another way to do it:
647 * - an overlapped ReadFile or ReadFileEx just doesn't
648 * happen; we get failure from ReadFileEx, and
649 * ReadFile blocks despite being given an OVERLAPPED
650 * structure. Perhaps we can't do overlapped reads
651 * on consoles. WHY THE HELL NOT?
653 * - WaitForMultipleObjects(netevent, console) doesn't
654 * work, because it signals the console when
655 * _anything_ happens, including mouse motions and
656 * other things that don't cause data to be readable
657 * - so we're back to ReadFile blocking.
659 idata
.event
= stdinevent
;
660 idata
.eventback
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
661 if (!CreateThread(NULL
, 0, stdin_read_thread
,
662 &idata
, 0, &in_threadid
)) {
663 fprintf(stderr
, "Unable to create input thread\n");
670 if (run_timers(now
, &next
)) {
671 ticks
= next
- GETTICKCOUNT();
672 if (ticks
< 0) ticks
= 0; /* just in case */
677 n
= MsgWaitForMultipleObjects(4, handles
, FALSE
, ticks
,
679 if (n
== WAIT_OBJECT_0
+ 0) {
680 WSANETWORKEVENTS things
;
682 extern SOCKET
first_socket(int *), next_socket(int *);
683 extern int select_result(WPARAM
, LPARAM
);
687 * We must not call select_result() for any socket
688 * until we have finished enumerating within the tree.
689 * This is because select_result() may close the socket
690 * and modify the tree.
692 /* Count the active sockets. */
694 for (socket
= first_socket(&socketstate
);
695 socket
!= INVALID_SOCKET
;
696 socket
= next_socket(&socketstate
)) i
++;
698 /* Expand the buffer if necessary. */
701 sklist
= sresize(sklist
, sksize
, SOCKET
);
704 /* Retrieve the sockets into sklist. */
706 for (socket
= first_socket(&socketstate
);
707 socket
!= INVALID_SOCKET
;
708 socket
= next_socket(&socketstate
)) {
709 sklist
[skcount
++] = socket
;
712 /* Now we're done enumerating; go through the list. */
713 for (i
= 0; i
< skcount
; i
++) {
716 wp
= (WPARAM
) socket
;
717 if (!p_WSAEnumNetworkEvents(socket
, NULL
, &things
)) {
718 static const struct { int bit
, mask
; } eventtypes
[] = {
719 {FD_CONNECT_BIT
, FD_CONNECT
},
720 {FD_READ_BIT
, FD_READ
},
721 {FD_CLOSE_BIT
, FD_CLOSE
},
722 {FD_OOB_BIT
, FD_OOB
},
723 {FD_WRITE_BIT
, FD_WRITE
},
724 {FD_ACCEPT_BIT
, FD_ACCEPT
},
728 noise_ultralight(socket
);
729 noise_ultralight(things
.lNetworkEvents
);
731 for (e
= 0; e
< lenof(eventtypes
); e
++)
732 if (things
.lNetworkEvents
& eventtypes
[e
].mask
) {
734 int err
= things
.iErrorCode
[eventtypes
[e
].bit
];
735 lp
= WSAMAKESELECTREPLY(eventtypes
[e
].mask
, err
);
736 connopen
&= select_result(wp
, lp
);
740 } else if (n
== WAIT_OBJECT_0
+ 1) {
742 noise_ultralight(idata
.len
);
743 if (connopen
&& back
->socket(backhandle
) != NULL
) {
745 back
->send(backhandle
, idata
.buffer
, idata
.len
);
747 back
->special(backhandle
, TS_EOF
);
750 } else if (n
== WAIT_OBJECT_0
+ 2) {
752 if (!odata
.writeret
) {
753 fprintf(stderr
, "Unable to write to standard output\n");
756 bufchain_consume(&stdout_data
, odata
.lenwritten
);
757 if (bufchain_size(&stdout_data
) > 0)
759 if (connopen
&& back
->socket(backhandle
) != NULL
) {
760 back
->unthrottle(backhandle
, bufchain_size(&stdout_data
) +
761 bufchain_size(&stderr_data
));
763 } else if (n
== WAIT_OBJECT_0
+ 3) {
765 if (!edata
.writeret
) {
766 fprintf(stderr
, "Unable to write to standard output\n");
769 bufchain_consume(&stderr_data
, edata
.lenwritten
);
770 if (bufchain_size(&stderr_data
) > 0)
772 if (connopen
&& back
->socket(backhandle
) != NULL
) {
773 back
->unthrottle(backhandle
, bufchain_size(&stdout_data
) +
774 bufchain_size(&stderr_data
));
776 } else if (n
== WAIT_OBJECT_0
+ 4) {
778 while (PeekMessage(&msg
, INVALID_HANDLE_VALUE
,
779 WM_AGENT_CALLBACK
, WM_AGENT_CALLBACK
,
781 struct agent_callback
*c
= (struct agent_callback
*)msg
.lParam
;
782 c
->callback(c
->callback_ctx
, c
->data
, c
->len
);
787 if (n
== WAIT_TIMEOUT
) {
790 now
= GETTICKCOUNT();
793 if (!reading
&& back
->sendbuffer(backhandle
) < MAX_STDIN_BACKLOG
) {
794 SetEvent(idata
.eventback
);
797 if ((!connopen
|| back
->socket(backhandle
) == NULL
) &&
798 bufchain_size(&stdout_data
) == 0 &&
799 bufchain_size(&stderr_data
) == 0)
800 break; /* we closed the connection */
802 exitcode
= back
->exitcode(backhandle
);
804 fprintf(stderr
, "Remote process exit code unavailable\n");
805 exitcode
= 1; /* this is an error condition */
807 cleanup_exit(exitcode
);
808 return 0; /* placate compiler warning */