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(" -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");
237 printf(" -N don't start a shell/command (SSH-2 only)\n");
241 static void version(void)
243 printf("plink: %s\n", ver
);
247 char *do_select(SOCKET skt
, int startup
)
251 events
= (FD_CONNECT
| FD_READ
| FD_WRITE
|
252 FD_OOB
| FD_CLOSE
| FD_ACCEPT
);
256 if (p_WSAEventSelect(skt
, netevent
, events
) == SOCKET_ERROR
) {
257 switch (p_WSAGetLastError()) {
259 return "Network is down";
261 return "WSAEventSelect(): unknown error";
267 int main(int argc
, char **argv
)
269 WSAEVENT stdinevent
, stdoutevent
, stderrevent
;
271 DWORD in_threadid
, out_threadid
, err_threadid
;
272 struct input_data idata
;
281 int use_subsystem
= 0;
283 ssh_get_line
= console_get_line
;
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")) {
341 fprintf(stderr
, "plink: unknown option \"%s\"\n", p
);
348 * If the hostname starts with "telnet:", set the
349 * protocol to Telnet and process the string as a
352 if (!strncmp(q
, "telnet:", 7)) {
356 if (q
[0] == '/' && q
[1] == '/')
358 cfg
.protocol
= PROT_TELNET
;
360 while (*p
&& *p
!= ':' && *p
!= '/')
369 strncpy(cfg
.host
, q
, sizeof(cfg
.host
) - 1);
370 cfg
.host
[sizeof(cfg
.host
) - 1] = '\0';
372 char *r
, *user
, *host
;
374 * Before we process the [user@]host string, we
375 * first check for the presence of a protocol
376 * prefix (a protocol name followed by ",").
381 for (i
= 0; backends
[i
].backend
!= NULL
; i
++) {
382 j
= strlen(backends
[i
].name
);
384 !memcmp(backends
[i
].name
, p
, j
)) {
385 default_protocol
= cfg
.protocol
=
386 backends
[i
].protocol
;
388 backends
[i
].backend
->default_port
;
396 * A nonzero length string followed by an @ is treated
397 * as a username. (We discount an _initial_ @.) The
398 * rest of the string (or the whole string if no @)
399 * is treated as a session name and/or hostname.
403 p
++, r
= NULL
; /* discount initial @ */
408 user
= NULL
, host
= p
;
412 * Now attempt to load a saved session with the
413 * same name as the hostname.
417 do_defaults(host
, &cfg2
);
418 if (loaded_session
|| cfg2
.host
[0] == '\0') {
419 /* No settings for this host; use defaults */
420 /* (or session was already loaded with -load) */
421 strncpy(cfg
.host
, host
, sizeof(cfg
.host
) - 1);
422 cfg
.host
[sizeof(cfg
.host
) - 1] = '\0';
423 cfg
.port
= default_port
;
426 /* Ick: patch up internal pointer after copy */
427 cfg
.remote_cmd_ptr
= cfg
.remote_cmd
;
432 /* Patch in specified username. */
433 strncpy(cfg
.username
, user
,
434 sizeof(cfg
.username
) - 1);
435 cfg
.username
[sizeof(cfg
.username
) - 1] = '\0';
442 cmdlen
= cmdsize
= 0;
447 if (cmdlen
>= cmdsize
) {
448 cmdsize
= cmdlen
+ 512;
449 command
= sresize(command
, cmdsize
, char);
451 command
[cmdlen
++]=*p
++;
453 if (cmdlen
>= cmdsize
) {
454 cmdsize
= cmdlen
+ 512;
455 command
= sresize(command
, cmdsize
, char);
457 command
[cmdlen
++]=' '; /* always add trailing space */
458 if (--argc
) p
= *++argv
;
460 if (cmdlen
) command
[--cmdlen
]='\0';
461 /* change trailing blank to NUL */
462 cfg
.remote_cmd_ptr
= command
;
463 cfg
.remote_cmd_ptr2
= NULL
;
464 cfg
.nopty
= TRUE
; /* command => no terminal */
466 break; /* done with cmdline */
479 * Trim leading whitespace off the hostname if it's there.
482 int space
= strspn(cfg
.host
, " \t");
483 memmove(cfg
.host
, cfg
.host
+space
, 1+strlen(cfg
.host
)-space
);
486 /* See if host is of the form user@host */
487 if (cfg
.host
[0] != '\0') {
488 char *atsign
= strrchr(cfg
.host
, '@');
489 /* Make sure we're not overflowing the user field */
491 if (atsign
- cfg
.host
< sizeof cfg
.username
) {
492 strncpy(cfg
.username
, cfg
.host
, atsign
- cfg
.host
);
493 cfg
.username
[atsign
- cfg
.host
] = '\0';
495 memmove(cfg
.host
, atsign
+ 1, 1 + strlen(atsign
+ 1));
500 * Perform command-line overrides on session configuration.
502 cmdline_run_saved(&cfg
);
505 * Apply subsystem status.
508 cfg
.ssh_subsys
= TRUE
;
511 * Trim a colon suffix off the hostname if it's there.
513 cfg
.host
[strcspn(cfg
.host
, ":")] = '\0';
516 * Remove any remaining whitespace from the hostname.
520 while (cfg
.host
[p2
] != '\0') {
521 if (cfg
.host
[p2
] != ' ' && cfg
.host
[p2
] != '\t') {
522 cfg
.host
[p1
] = cfg
.host
[p2
];
530 if (!*cfg
.remote_cmd_ptr
)
531 flags
|= FLAG_INTERACTIVE
;
534 * Select protocol. This is farmed out into a table in a
535 * separate file to enable an ssh-free variant.
540 for (i
= 0; backends
[i
].backend
!= NULL
; i
++)
541 if (backends
[i
].protocol
== cfg
.protocol
) {
542 back
= backends
[i
].backend
;
547 "Internal fault: Unsupported protocol found\n");
555 if (portnumber
!= -1)
556 cfg
.port
= portnumber
;
559 if (p_WSAEventSelect
== NULL
) {
560 fprintf(stderr
, "Plink requires WinSock 2\n");
565 * Start up the connection.
567 netevent
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
571 /* nodelay is only useful if stdin is a character device (console) */
572 int nodelay
= cfg
.tcp_nodelay
&&
573 (GetFileType(GetStdHandle(STD_INPUT_HANDLE
)) == FILE_TYPE_CHAR
);
575 error
= back
->init(NULL
, &backhandle
, &cfg
, cfg
.host
, cfg
.port
,
576 &realhost
, nodelay
, cfg
.tcp_keepalives
);
578 fprintf(stderr
, "Unable to open connection:\n%s", error
);
581 logctx
= log_init(NULL
, &cfg
);
582 back
->provide_logctx(backhandle
, logctx
);
583 console_provide_logctx(logctx
);
588 stdinevent
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
589 stdoutevent
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
590 stderrevent
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
592 inhandle
= GetStdHandle(STD_INPUT_HANDLE
);
593 outhandle
= GetStdHandle(STD_OUTPUT_HANDLE
);
594 errhandle
= GetStdHandle(STD_ERROR_HANDLE
);
595 GetConsoleMode(inhandle
, &orig_console_mode
);
596 SetConsoleMode(inhandle
, ENABLE_PROCESSED_INPUT
);
598 main_thread_id
= GetCurrentThreadId();
601 * Turn off ECHO and LINE input modes. We don't care if this
602 * call fails, because we know we aren't necessarily running in
605 handles
[0] = netevent
;
606 handles
[1] = stdinevent
;
607 handles
[2] = stdoutevent
;
608 handles
[3] = stderrevent
;
612 * Create spare threads to write to stdout and stderr, so we
613 * can arrange asynchronous writes.
615 odata
.event
= stdoutevent
;
616 odata
.eventback
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
618 odata
.busy
= odata
.done
= 0;
619 if (!CreateThread(NULL
, 0, stdout_write_thread
,
620 &odata
, 0, &out_threadid
)) {
621 fprintf(stderr
, "Unable to create output thread\n");
624 edata
.event
= stderrevent
;
625 edata
.eventback
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
627 edata
.busy
= edata
.done
= 0;
628 if (!CreateThread(NULL
, 0, stdout_write_thread
,
629 &edata
, 0, &err_threadid
)) {
630 fprintf(stderr
, "Unable to create error output thread\n");
637 if (!sending
&& back
->sendok(backhandle
)) {
639 * Create a separate thread to read from stdin. This is
640 * a total pain, but I can't find another way to do it:
642 * - an overlapped ReadFile or ReadFileEx just doesn't
643 * happen; we get failure from ReadFileEx, and
644 * ReadFile blocks despite being given an OVERLAPPED
645 * structure. Perhaps we can't do overlapped reads
646 * on consoles. WHY THE HELL NOT?
648 * - WaitForMultipleObjects(netevent, console) doesn't
649 * work, because it signals the console when
650 * _anything_ happens, including mouse motions and
651 * other things that don't cause data to be readable
652 * - so we're back to ReadFile blocking.
654 idata
.event
= stdinevent
;
655 idata
.eventback
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
656 if (!CreateThread(NULL
, 0, stdin_read_thread
,
657 &idata
, 0, &in_threadid
)) {
658 fprintf(stderr
, "Unable to create input thread\n");
664 n
= MsgWaitForMultipleObjects(4, handles
, FALSE
, INFINITE
,
667 WSANETWORKEVENTS things
;
669 extern SOCKET
first_socket(int *), next_socket(int *);
670 extern int select_result(WPARAM
, LPARAM
);
674 * We must not call select_result() for any socket
675 * until we have finished enumerating within the tree.
676 * This is because select_result() may close the socket
677 * and modify the tree.
679 /* Count the active sockets. */
681 for (socket
= first_socket(&socketstate
);
682 socket
!= INVALID_SOCKET
;
683 socket
= next_socket(&socketstate
)) i
++;
685 /* Expand the buffer if necessary. */
688 sklist
= sresize(sklist
, sksize
, SOCKET
);
691 /* Retrieve the sockets into sklist. */
693 for (socket
= first_socket(&socketstate
);
694 socket
!= INVALID_SOCKET
;
695 socket
= next_socket(&socketstate
)) {
696 sklist
[skcount
++] = socket
;
699 /* Now we're done enumerating; go through the list. */
700 for (i
= 0; i
< skcount
; i
++) {
703 wp
= (WPARAM
) socket
;
704 if (!p_WSAEnumNetworkEvents(socket
, NULL
, &things
)) {
705 static const struct { int bit
, mask
; } eventtypes
[] = {
706 {FD_CONNECT_BIT
, FD_CONNECT
},
707 {FD_READ_BIT
, FD_READ
},
708 {FD_CLOSE_BIT
, FD_CLOSE
},
709 {FD_OOB_BIT
, FD_OOB
},
710 {FD_WRITE_BIT
, FD_WRITE
},
711 {FD_ACCEPT_BIT
, FD_ACCEPT
},
715 noise_ultralight(socket
);
716 noise_ultralight(things
.lNetworkEvents
);
718 for (e
= 0; e
< lenof(eventtypes
); e
++)
719 if (things
.lNetworkEvents
& eventtypes
[e
].mask
) {
721 int err
= things
.iErrorCode
[eventtypes
[e
].bit
];
722 lp
= WSAMAKESELECTREPLY(eventtypes
[e
].mask
, err
);
723 connopen
&= select_result(wp
, lp
);
729 noise_ultralight(idata
.len
);
730 if (connopen
&& back
->socket(backhandle
) != NULL
) {
732 back
->send(backhandle
, idata
.buffer
, idata
.len
);
734 back
->special(backhandle
, TS_EOF
);
739 if (!odata
.writeret
) {
740 fprintf(stderr
, "Unable to write to standard output\n");
743 bufchain_consume(&stdout_data
, odata
.lenwritten
);
744 if (bufchain_size(&stdout_data
) > 0)
746 if (connopen
&& back
->socket(backhandle
) != NULL
) {
747 back
->unthrottle(backhandle
, bufchain_size(&stdout_data
) +
748 bufchain_size(&stderr_data
));
752 if (!edata
.writeret
) {
753 fprintf(stderr
, "Unable to write to standard output\n");
756 bufchain_consume(&stderr_data
, edata
.lenwritten
);
757 if (bufchain_size(&stderr_data
) > 0)
759 if (connopen
&& back
->socket(backhandle
) != NULL
) {
760 back
->unthrottle(backhandle
, bufchain_size(&stdout_data
) +
761 bufchain_size(&stderr_data
));
765 while (PeekMessage(&msg
, INVALID_HANDLE_VALUE
,
766 WM_AGENT_CALLBACK
, WM_AGENT_CALLBACK
,
768 struct agent_callback
*c
= (struct agent_callback
*)msg
.lParam
;
769 c
->callback(c
->callback_ctx
, c
->data
, c
->len
);
773 if (!reading
&& back
->sendbuffer(backhandle
) < MAX_STDIN_BACKLOG
) {
774 SetEvent(idata
.eventback
);
777 if ((!connopen
|| back
->socket(backhandle
) == NULL
) &&
778 bufchain_size(&stdout_data
) == 0 &&
779 bufchain_size(&stderr_data
) == 0)
780 break; /* we closed the connection */
782 exitcode
= back
->exitcode(backhandle
);
784 fprintf(stderr
, "Remote process exit code unavailable\n");
785 exitcode
= 1; /* this is an error condition */
787 cleanup_exit(exitcode
);
788 return 0; /* placate compiler warning */