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 (default SSH)\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(" -C enable compression\n");
235 printf(" -i key private key file for authentication\n");
236 printf(" -s remote command is an SSH subsystem (SSH-2 only)\n");
240 static void version(void)
242 printf("plink: %s\n", ver
);
246 char *do_select(SOCKET skt
, int startup
)
250 events
= (FD_CONNECT
| FD_READ
| FD_WRITE
|
251 FD_OOB
| FD_CLOSE
| FD_ACCEPT
);
255 if (p_WSAEventSelect(skt
, netevent
, events
) == SOCKET_ERROR
) {
256 switch (p_WSAGetLastError()) {
258 return "Network is down";
260 return "WSAEventSelect(): unknown error";
266 int main(int argc
, char **argv
)
268 WSAEVENT stdinevent
, stdoutevent
, stderrevent
;
270 DWORD in_threadid
, out_threadid
, err_threadid
;
271 struct input_data idata
;
280 int use_subsystem
= 0;
282 ssh_get_line
= console_get_line
;
285 skcount
= sksize
= 0;
287 * Initialise port and protocol to sensible defaults. (These
288 * will be overridden by more or less anything.)
290 default_protocol
= PROT_SSH
;
295 * Process the command line.
297 do_defaults(NULL
, &cfg
);
298 default_protocol
= cfg
.protocol
;
299 default_port
= cfg
.port
;
303 * Override the default protocol if PLINK_PROTOCOL is set.
305 char *p
= getenv("PLINK_PROTOCOL");
308 for (i
= 0; backends
[i
].backend
!= NULL
; i
++) {
309 if (!strcmp(backends
[i
].name
, p
)) {
310 default_protocol
= cfg
.protocol
= backends
[i
].protocol
;
311 default_port
= cfg
.port
=
312 backends
[i
].backend
->default_port
;
321 int ret
= cmdline_process_param(p
, (argc
> 1 ? argv
[1] : NULL
),
325 "plink: option \"%s\" requires an argument\n", p
);
327 } else if (ret
== 2) {
329 } else if (ret
== 1) {
331 } else if (!strcmp(p
, "-batch")) {
332 console_batch_mode
= 1;
333 } else if (!strcmp(p
, "-s")) {
334 /* Save status to write to cfg later. */
336 } else if (!strcmp(p
, "-V")) {
339 fprintf(stderr
, "plink: unknown option \"%s\"\n", p
);
346 * If the hostname starts with "telnet:", set the
347 * protocol to Telnet and process the string as a
350 if (!strncmp(q
, "telnet:", 7)) {
354 if (q
[0] == '/' && q
[1] == '/')
356 cfg
.protocol
= PROT_TELNET
;
358 while (*p
&& *p
!= ':' && *p
!= '/')
367 strncpy(cfg
.host
, q
, sizeof(cfg
.host
) - 1);
368 cfg
.host
[sizeof(cfg
.host
) - 1] = '\0';
372 * Before we process the [user@]host string, we
373 * first check for the presence of a protocol
374 * prefix (a protocol name followed by ",").
379 for (i
= 0; backends
[i
].backend
!= NULL
; i
++) {
380 j
= strlen(backends
[i
].name
);
382 !memcmp(backends
[i
].name
, p
, j
)) {
383 default_protocol
= cfg
.protocol
=
384 backends
[i
].protocol
;
386 backends
[i
].backend
->default_port
;
394 * Three cases. Either (a) there's a nonzero
395 * length string followed by an @, in which
396 * case that's user and the remainder is host.
397 * Or (b) there's only one string, not counting
398 * a potential initial @, and it exists in the
399 * saved-sessions database. Or (c) only one
400 * string and it _doesn't_ exist in the
405 p
++, r
= NULL
; /* discount initial @ */
411 do_defaults(p
, &cfg2
);
412 if (cfg2
.host
[0] == '\0') {
413 /* No settings for this host; use defaults */
414 strncpy(cfg
.host
, p
, sizeof(cfg
.host
) - 1);
415 cfg
.host
[sizeof(cfg
.host
) - 1] = '\0';
416 cfg
.port
= default_port
;
419 cfg
.remote_cmd_ptr
= cfg
.remote_cmd
;
423 strncpy(cfg
.username
, p
, sizeof(cfg
.username
) - 1);
424 cfg
.username
[sizeof(cfg
.username
) - 1] = '\0';
425 strncpy(cfg
.host
, r
, sizeof(cfg
.host
) - 1);
426 cfg
.host
[sizeof(cfg
.host
) - 1] = '\0';
427 cfg
.port
= default_port
;
433 cmdlen
= cmdsize
= 0;
438 if (cmdlen
>= cmdsize
) {
439 cmdsize
= cmdlen
+ 512;
440 command
= sresize(command
, cmdsize
, char);
442 command
[cmdlen
++]=*p
++;
444 if (cmdlen
>= cmdsize
) {
445 cmdsize
= cmdlen
+ 512;
446 command
= sresize(command
, cmdsize
, char);
448 command
[cmdlen
++]=' '; /* always add trailing space */
449 if (--argc
) p
= *++argv
;
451 if (cmdlen
) command
[--cmdlen
]='\0';
452 /* change trailing blank to NUL */
453 cfg
.remote_cmd_ptr
= command
;
454 cfg
.remote_cmd_ptr2
= NULL
;
455 cfg
.nopty
= TRUE
; /* command => no terminal */
457 break; /* done with cmdline */
470 * Trim leading whitespace off the hostname if it's there.
473 int space
= strspn(cfg
.host
, " \t");
474 memmove(cfg
.host
, cfg
.host
+space
, 1+strlen(cfg
.host
)-space
);
477 /* See if host is of the form user@host */
478 if (cfg
.host
[0] != '\0') {
479 char *atsign
= strchr(cfg
.host
, '@');
480 /* Make sure we're not overflowing the user field */
482 if (atsign
- cfg
.host
< sizeof cfg
.username
) {
483 strncpy(cfg
.username
, cfg
.host
, atsign
- cfg
.host
);
484 cfg
.username
[atsign
- cfg
.host
] = '\0';
486 memmove(cfg
.host
, atsign
+ 1, 1 + strlen(atsign
+ 1));
491 * Perform command-line overrides on session configuration.
493 cmdline_run_saved(&cfg
);
496 * Apply subsystem status.
499 cfg
.ssh_subsys
= TRUE
;
502 * Trim a colon suffix off the hostname if it's there.
504 cfg
.host
[strcspn(cfg
.host
, ":")] = '\0';
507 * Remove any remaining whitespace from the hostname.
511 while (cfg
.host
[p2
] != '\0') {
512 if (cfg
.host
[p2
] != ' ' && cfg
.host
[p2
] != '\t') {
513 cfg
.host
[p1
] = cfg
.host
[p2
];
521 if (!*cfg
.remote_cmd_ptr
)
522 flags
|= FLAG_INTERACTIVE
;
525 * Select protocol. This is farmed out into a table in a
526 * separate file to enable an ssh-free variant.
531 for (i
= 0; backends
[i
].backend
!= NULL
; i
++)
532 if (backends
[i
].protocol
== cfg
.protocol
) {
533 back
= backends
[i
].backend
;
538 "Internal fault: Unsupported protocol found\n");
546 if (portnumber
!= -1)
547 cfg
.port
= portnumber
;
550 if (p_WSAEventSelect
== NULL
) {
551 fprintf(stderr
, "Plink requires WinSock 2\n");
556 * Start up the connection.
558 netevent
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
562 /* nodelay is only useful if stdin is a character device (console) */
563 int nodelay
= cfg
.tcp_nodelay
&&
564 (GetFileType(GetStdHandle(STD_INPUT_HANDLE
)) == FILE_TYPE_CHAR
);
566 error
= back
->init(NULL
, &backhandle
, &cfg
, cfg
.host
, cfg
.port
,
567 &realhost
, nodelay
, cfg
.tcp_keepalives
);
569 fprintf(stderr
, "Unable to open connection:\n%s", error
);
572 logctx
= log_init(NULL
, &cfg
);
573 back
->provide_logctx(backhandle
, logctx
);
574 console_provide_logctx(logctx
);
579 stdinevent
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
580 stdoutevent
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
581 stderrevent
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
583 inhandle
= GetStdHandle(STD_INPUT_HANDLE
);
584 outhandle
= GetStdHandle(STD_OUTPUT_HANDLE
);
585 errhandle
= GetStdHandle(STD_ERROR_HANDLE
);
586 GetConsoleMode(inhandle
, &orig_console_mode
);
587 SetConsoleMode(inhandle
, ENABLE_PROCESSED_INPUT
);
589 main_thread_id
= GetCurrentThreadId();
592 * Turn off ECHO and LINE input modes. We don't care if this
593 * call fails, because we know we aren't necessarily running in
596 handles
[0] = netevent
;
597 handles
[1] = stdinevent
;
598 handles
[2] = stdoutevent
;
599 handles
[3] = stderrevent
;
603 * Create spare threads to write to stdout and stderr, so we
604 * can arrange asynchronous writes.
606 odata
.event
= stdoutevent
;
607 odata
.eventback
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
609 odata
.busy
= odata
.done
= 0;
610 if (!CreateThread(NULL
, 0, stdout_write_thread
,
611 &odata
, 0, &out_threadid
)) {
612 fprintf(stderr
, "Unable to create output thread\n");
615 edata
.event
= stderrevent
;
616 edata
.eventback
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
618 edata
.busy
= edata
.done
= 0;
619 if (!CreateThread(NULL
, 0, stdout_write_thread
,
620 &edata
, 0, &err_threadid
)) {
621 fprintf(stderr
, "Unable to create error output thread\n");
628 if (!sending
&& back
->sendok(backhandle
)) {
630 * Create a separate thread to read from stdin. This is
631 * a total pain, but I can't find another way to do it:
633 * - an overlapped ReadFile or ReadFileEx just doesn't
634 * happen; we get failure from ReadFileEx, and
635 * ReadFile blocks despite being given an OVERLAPPED
636 * structure. Perhaps we can't do overlapped reads
637 * on consoles. WHY THE HELL NOT?
639 * - WaitForMultipleObjects(netevent, console) doesn't
640 * work, because it signals the console when
641 * _anything_ happens, including mouse motions and
642 * other things that don't cause data to be readable
643 * - so we're back to ReadFile blocking.
645 idata
.event
= stdinevent
;
646 idata
.eventback
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
647 if (!CreateThread(NULL
, 0, stdin_read_thread
,
648 &idata
, 0, &in_threadid
)) {
649 fprintf(stderr
, "Unable to create input thread\n");
655 n
= MsgWaitForMultipleObjects(4, handles
, FALSE
, INFINITE
,
658 WSANETWORKEVENTS things
;
660 extern SOCKET
first_socket(int *), next_socket(int *);
661 extern int select_result(WPARAM
, LPARAM
);
665 * We must not call select_result() for any socket
666 * until we have finished enumerating within the tree.
667 * This is because select_result() may close the socket
668 * and modify the tree.
670 /* Count the active sockets. */
672 for (socket
= first_socket(&socketstate
);
673 socket
!= INVALID_SOCKET
;
674 socket
= next_socket(&socketstate
)) i
++;
676 /* Expand the buffer if necessary. */
679 sklist
= sresize(sklist
, sksize
, SOCKET
);
682 /* Retrieve the sockets into sklist. */
684 for (socket
= first_socket(&socketstate
);
685 socket
!= INVALID_SOCKET
;
686 socket
= next_socket(&socketstate
)) {
687 sklist
[skcount
++] = socket
;
690 /* Now we're done enumerating; go through the list. */
691 for (i
= 0; i
< skcount
; i
++) {
694 wp
= (WPARAM
) socket
;
695 if (!p_WSAEnumNetworkEvents(socket
, NULL
, &things
)) {
696 static const struct { int bit
, mask
; } eventtypes
[] = {
697 {FD_CONNECT_BIT
, FD_CONNECT
},
698 {FD_READ_BIT
, FD_READ
},
699 {FD_CLOSE_BIT
, FD_CLOSE
},
700 {FD_OOB_BIT
, FD_OOB
},
701 {FD_WRITE_BIT
, FD_WRITE
},
702 {FD_ACCEPT_BIT
, FD_ACCEPT
},
706 noise_ultralight(socket
);
707 noise_ultralight(things
.lNetworkEvents
);
709 for (e
= 0; e
< lenof(eventtypes
); e
++)
710 if (things
.lNetworkEvents
& eventtypes
[e
].mask
) {
712 int err
= things
.iErrorCode
[eventtypes
[e
].bit
];
713 lp
= WSAMAKESELECTREPLY(eventtypes
[e
].mask
, err
);
714 connopen
&= select_result(wp
, lp
);
720 noise_ultralight(idata
.len
);
721 if (connopen
&& back
->socket(backhandle
) != NULL
) {
723 back
->send(backhandle
, idata
.buffer
, idata
.len
);
725 back
->special(backhandle
, TS_EOF
);
730 if (!odata
.writeret
) {
731 fprintf(stderr
, "Unable to write to standard output\n");
734 bufchain_consume(&stdout_data
, odata
.lenwritten
);
735 if (bufchain_size(&stdout_data
) > 0)
737 if (connopen
&& back
->socket(backhandle
) != NULL
) {
738 back
->unthrottle(backhandle
, bufchain_size(&stdout_data
) +
739 bufchain_size(&stderr_data
));
743 if (!edata
.writeret
) {
744 fprintf(stderr
, "Unable to write to standard output\n");
747 bufchain_consume(&stderr_data
, edata
.lenwritten
);
748 if (bufchain_size(&stderr_data
) > 0)
750 if (connopen
&& back
->socket(backhandle
) != NULL
) {
751 back
->unthrottle(backhandle
, bufchain_size(&stdout_data
) +
752 bufchain_size(&stderr_data
));
756 while (PeekMessage(&msg
, INVALID_HANDLE_VALUE
,
757 WM_AGENT_CALLBACK
, WM_AGENT_CALLBACK
,
759 struct agent_callback
*c
= (struct agent_callback
*)msg
.lParam
;
760 c
->callback(c
->callback_ctx
, c
->data
, c
->len
);
764 if (!reading
&& back
->sendbuffer(backhandle
) < MAX_STDIN_BACKLOG
) {
765 SetEvent(idata
.eventback
);
768 if ((!connopen
|| back
->socket(backhandle
) == NULL
) &&
769 bufchain_size(&stdout_data
) == 0 &&
770 bufchain_size(&stderr_data
) == 0)
771 break; /* we closed the connection */
773 exitcode
= back
->exitcode(backhandle
);
775 fprintf(stderr
, "Remote process exit code unavailable\n");
776 exitcode
= 1; /* this is an error condition */
778 cleanup_exit(exitcode
);
779 return 0; /* placate compiler warning */