2 * PLink - a command-line (stdin/stdout) variant of PuTTY.
14 #define PUTTY_DO_GLOBALS /* actually _define_ globals */
19 #define MAX_STDIN_BACKLOG 4096
21 void fatalbox(char *p
, ...)
24 fprintf(stderr
, "FATAL ERROR: ");
26 vfprintf(stderr
, p
, ap
);
32 void modalfatalbox(char *p
, ...)
35 fprintf(stderr
, "FATAL ERROR: ");
37 vfprintf(stderr
, p
, ap
);
43 void connection_fatal(char *p
, ...)
46 fprintf(stderr
, "FATAL ERROR: ");
48 vfprintf(stderr
, p
, ap
);
54 void cmdline_error(char *p
, ...)
57 fprintf(stderr
, "plink: ");
59 vfprintf(stderr
, p
, ap
);
65 static char *password
= NULL
;
67 HANDLE inhandle
, outhandle
, errhandle
;
68 DWORD orig_console_mode
;
72 int term_ldisc(Terminal
*term
, int mode
)
76 void ldisc_update(int echo
, int edit
)
78 /* Update stdin read mode to reflect changes in line discipline. */
81 mode
= ENABLE_PROCESSED_INPUT
;
83 mode
= mode
| ENABLE_ECHO_INPUT
;
85 mode
= mode
& ~ENABLE_ECHO_INPUT
;
87 mode
= mode
| ENABLE_LINE_INPUT
;
89 mode
= mode
& ~ENABLE_LINE_INPUT
;
90 SetConsoleMode(inhandle
, mode
);
96 HANDLE event
, eventback
;
99 static DWORD WINAPI
stdin_read_thread(void *param
)
101 struct input_data
*idata
= (struct input_data
*) param
;
104 inhandle
= GetStdHandle(STD_INPUT_HANDLE
);
106 while (ReadFile(inhandle
, idata
->buffer
, sizeof(idata
->buffer
),
107 &idata
->len
, NULL
) && idata
->len
> 0) {
108 SetEvent(idata
->event
);
109 WaitForSingleObject(idata
->eventback
, INFINITE
);
113 SetEvent(idata
->event
);
119 DWORD len
, lenwritten
;
123 HANDLE event
, eventback
;
127 static DWORD WINAPI
stdout_write_thread(void *param
)
129 struct output_data
*odata
= (struct output_data
*) param
;
130 HANDLE outhandle
, errhandle
;
132 outhandle
= GetStdHandle(STD_OUTPUT_HANDLE
);
133 errhandle
= GetStdHandle(STD_ERROR_HANDLE
);
136 WaitForSingleObject(odata
->eventback
, INFINITE
);
140 WriteFile(odata
->is_stderr ? errhandle
: outhandle
,
141 odata
->buffer
, odata
->len
, &odata
->lenwritten
, NULL
);
142 SetEvent(odata
->event
);
148 bufchain stdout_data
, stderr_data
;
149 struct output_data odata
, edata
;
151 void try_output(int is_stderr
)
153 struct output_data
*data
= (is_stderr ?
&edata
: &odata
);
158 bufchain_prefix(is_stderr ?
&stderr_data
: &stdout_data
,
159 &senddata
, &sendlen
);
160 data
->buffer
= senddata
;
162 SetEvent(data
->eventback
);
167 int from_backend(void *frontend_handle
, int is_stderr
, char *data
, int len
)
169 HANDLE h
= (is_stderr ? errhandle
: outhandle
);
175 bufchain_add(&stderr_data
, data
, len
);
178 bufchain_add(&stdout_data
, data
, len
);
182 osize
= bufchain_size(&stdout_data
);
183 esize
= bufchain_size(&stderr_data
);
185 return osize
+ esize
;
189 * Short description of parameters.
191 static void usage(void)
193 printf("PuTTY Link: command-line connection utility\n");
195 printf("Usage: plink [options] [user@]host [command]\n");
196 printf(" (\"host\" can also be a PuTTY saved session name)\n");
197 printf("Options:\n");
198 printf(" -v show verbose messages\n");
199 printf(" -load sessname Load settings from saved session\n");
200 printf(" -ssh -telnet -rlogin -raw\n");
201 printf(" force use of a particular protocol (default SSH)\n");
202 printf(" -P port connect to specified port\n");
203 printf(" -l user connect with specified username\n");
204 printf(" -m file read remote command(s) from file\n");
205 printf(" -batch disable all interactive prompts\n");
206 printf("The following options only apply to SSH connections:\n");
207 printf(" -pw passw login with specified password\n");
208 printf(" -L listen-port:host:port Forward local port to "
210 printf(" -R listen-port:host:port Forward remote port to"
212 printf(" -X -x enable / disable X11 forwarding\n");
213 printf(" -A -a enable / disable agent forwarding\n");
214 printf(" -t -T enable / disable pty allocation\n");
215 printf(" -1 -2 force use of particular protocol version\n");
216 printf(" -C enable compression\n");
217 printf(" -i key private key file for authentication\n");
221 char *do_select(SOCKET skt
, int startup
)
225 events
= (FD_CONNECT
| FD_READ
| FD_WRITE
|
226 FD_OOB
| FD_CLOSE
| FD_ACCEPT
);
230 if (WSAEventSelect(skt
, netevent
, events
) == SOCKET_ERROR
) {
231 switch (WSAGetLastError()) {
233 return "Network is down";
235 return "WSAAsyncSelect(): unknown error";
241 int main(int argc
, char **argv
)
245 WSAEVENT stdinevent
, stdoutevent
, stderrevent
;
247 DWORD in_threadid
, out_threadid
, err_threadid
;
248 struct input_data idata
;
257 ssh_get_line
= console_get_line
;
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 default_protocol
= cfg
.protocol
;
274 default_port
= cfg
.port
;
277 * Override the default protocol if PLINK_PROTOCOL is set.
279 char *p
= getenv("PLINK_PROTOCOL");
282 for (i
= 0; backends
[i
].backend
!= NULL
; i
++) {
283 if (!strcmp(backends
[i
].name
, p
)) {
284 default_protocol
= cfg
.protocol
= backends
[i
].protocol
;
285 default_port
= cfg
.port
=
286 backends
[i
].backend
->default_port
;
295 int ret
= cmdline_process_param(p
, (argc
> 1 ? argv
[1] : NULL
), 1);
298 "plink: option \"%s\" requires an argument\n", p
);
299 } else if (ret
== 2) {
301 } else if (ret
== 1) {
303 } else if (!strcmp(p
, "-batch")) {
304 console_batch_mode
= 1;
310 * If the hostname starts with "telnet:", set the
311 * protocol to Telnet and process the string as a
314 if (!strncmp(q
, "telnet:", 7)) {
318 if (q
[0] == '/' && q
[1] == '/')
320 cfg
.protocol
= PROT_TELNET
;
322 while (*p
&& *p
!= ':' && *p
!= '/')
331 strncpy(cfg
.host
, q
, sizeof(cfg
.host
) - 1);
332 cfg
.host
[sizeof(cfg
.host
) - 1] = '\0';
336 * Before we process the [user@]host string, we
337 * first check for the presence of a protocol
338 * prefix (a protocol name followed by ",").
343 for (i
= 0; backends
[i
].backend
!= NULL
; i
++) {
344 j
= strlen(backends
[i
].name
);
346 !memcmp(backends
[i
].name
, p
, j
)) {
347 default_protocol
= cfg
.protocol
=
348 backends
[i
].protocol
;
350 backends
[i
].backend
->default_port
;
358 * Three cases. Either (a) there's a nonzero
359 * length string followed by an @, in which
360 * case that's user and the remainder is host.
361 * Or (b) there's only one string, not counting
362 * a potential initial @, and it exists in the
363 * saved-sessions database. Or (c) only one
364 * string and it _doesn't_ exist in the
369 p
++, r
= NULL
; /* discount initial @ */
375 do_defaults(p
, &cfg2
);
376 if (cfg2
.host
[0] == '\0') {
377 /* No settings for this host; use defaults */
378 strncpy(cfg
.host
, p
, sizeof(cfg
.host
) - 1);
379 cfg
.host
[sizeof(cfg
.host
) - 1] = '\0';
380 cfg
.port
= default_port
;
383 cfg
.remote_cmd_ptr
= cfg
.remote_cmd
;
387 strncpy(cfg
.username
, p
, sizeof(cfg
.username
) - 1);
388 cfg
.username
[sizeof(cfg
.username
) - 1] = '\0';
389 strncpy(cfg
.host
, r
, sizeof(cfg
.host
) - 1);
390 cfg
.host
[sizeof(cfg
.host
) - 1] = '\0';
391 cfg
.port
= default_port
;
397 cmdlen
= cmdsize
= 0;
402 if (cmdlen
>= cmdsize
) {
403 cmdsize
= cmdlen
+ 512;
404 command
= srealloc(command
, cmdsize
);
406 command
[cmdlen
++]=*p
++;
408 if (cmdlen
>= cmdsize
) {
409 cmdsize
= cmdlen
+ 512;
410 command
= srealloc(command
, cmdsize
);
412 command
[cmdlen
++]=' '; /* always add trailing space */
413 if (--argc
) p
= *++argv
;
415 if (cmdlen
) command
[--cmdlen
]='\0';
416 /* change trailing blank to NUL */
417 cfg
.remote_cmd_ptr
= command
;
418 cfg
.remote_cmd_ptr2
= NULL
;
419 cfg
.nopty
= TRUE
; /* command => no terminal */
421 break; /* done with cmdline */
431 * Trim leading whitespace off the hostname if it's there.
434 int space
= strspn(cfg
.host
, " \t");
435 memmove(cfg
.host
, cfg
.host
+space
, 1+strlen(cfg
.host
)-space
);
438 /* See if host is of the form user@host */
439 if (cfg
.host
[0] != '\0') {
440 char *atsign
= strchr(cfg
.host
, '@');
441 /* Make sure we're not overflowing the user field */
443 if (atsign
- cfg
.host
< sizeof cfg
.username
) {
444 strncpy(cfg
.username
, cfg
.host
, atsign
- cfg
.host
);
445 cfg
.username
[atsign
- cfg
.host
] = '\0';
447 memmove(cfg
.host
, atsign
+ 1, 1 + strlen(atsign
+ 1));
452 * Perform command-line overrides on session configuration.
457 * Trim a colon suffix off the hostname if it's there.
459 cfg
.host
[strcspn(cfg
.host
, ":")] = '\0';
462 * Remove any remaining whitespace from the hostname.
466 while (cfg
.host
[p2
] != '\0') {
467 if (cfg
.host
[p2
] != ' ' && cfg
.host
[p2
] != '\t') {
468 cfg
.host
[p1
] = cfg
.host
[p2
];
476 if (!*cfg
.remote_cmd_ptr
)
477 flags
|= FLAG_INTERACTIVE
;
480 * Select protocol. This is farmed out into a table in a
481 * separate file to enable an ssh-free variant.
486 for (i
= 0; backends
[i
].backend
!= NULL
; i
++)
487 if (backends
[i
].protocol
== cfg
.protocol
) {
488 back
= backends
[i
].backend
;
493 "Internal fault: Unsupported protocol found\n");
501 if (portnumber
!= -1)
502 cfg
.port
= portnumber
;
505 * Initialise WinSock.
507 winsock_ver
= MAKEWORD(2, 0);
508 if (WSAStartup(winsock_ver
, &wsadata
)) {
509 MessageBox(NULL
, "Unable to initialise WinSock", "WinSock Error",
510 MB_OK
| MB_ICONEXCLAMATION
);
513 if (LOBYTE(wsadata
.wVersion
) != 2 || HIBYTE(wsadata
.wVersion
) != 0) {
514 MessageBox(NULL
, "WinSock version is incompatible with 2.0",
515 "WinSock Error", MB_OK
| MB_ICONEXCLAMATION
);
522 * Start up the connection.
524 netevent
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
528 /* nodelay is only useful if stdin is a character device (console) */
529 int nodelay
= cfg
.tcp_nodelay
&&
530 (GetFileType(GetStdHandle(STD_INPUT_HANDLE
)) == FILE_TYPE_CHAR
);
532 error
= back
->init(NULL
, &backhandle
, cfg
.host
, cfg
.port
,
535 fprintf(stderr
, "Unable to open connection:\n%s", error
);
542 stdinevent
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
543 stdoutevent
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
544 stderrevent
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
546 inhandle
= GetStdHandle(STD_INPUT_HANDLE
);
547 outhandle
= GetStdHandle(STD_OUTPUT_HANDLE
);
548 errhandle
= GetStdHandle(STD_ERROR_HANDLE
);
549 GetConsoleMode(inhandle
, &orig_console_mode
);
550 SetConsoleMode(inhandle
, ENABLE_PROCESSED_INPUT
);
553 * Turn off ECHO and LINE input modes. We don't care if this
554 * call fails, because we know we aren't necessarily running in
557 handles
[0] = netevent
;
558 handles
[1] = stdinevent
;
559 handles
[2] = stdoutevent
;
560 handles
[3] = stderrevent
;
564 * Create spare threads to write to stdout and stderr, so we
565 * can arrange asynchronous writes.
567 odata
.event
= stdoutevent
;
568 odata
.eventback
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
570 odata
.busy
= odata
.done
= 0;
571 if (!CreateThread(NULL
, 0, stdout_write_thread
,
572 &odata
, 0, &out_threadid
)) {
573 fprintf(stderr
, "Unable to create output thread\n");
576 edata
.event
= stderrevent
;
577 edata
.eventback
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
579 edata
.busy
= edata
.done
= 0;
580 if (!CreateThread(NULL
, 0, stdout_write_thread
,
581 &edata
, 0, &err_threadid
)) {
582 fprintf(stderr
, "Unable to create error output thread\n");
589 if (!sending
&& back
->sendok(backhandle
)) {
591 * Create a separate thread to read from stdin. This is
592 * a total pain, but I can't find another way to do it:
594 * - an overlapped ReadFile or ReadFileEx just doesn't
595 * happen; we get failure from ReadFileEx, and
596 * ReadFile blocks despite being given an OVERLAPPED
597 * structure. Perhaps we can't do overlapped reads
598 * on consoles. WHY THE HELL NOT?
600 * - WaitForMultipleObjects(netevent, console) doesn't
601 * work, because it signals the console when
602 * _anything_ happens, including mouse motions and
603 * other things that don't cause data to be readable
604 * - so we're back to ReadFile blocking.
606 idata
.event
= stdinevent
;
607 idata
.eventback
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
608 if (!CreateThread(NULL
, 0, stdin_read_thread
,
609 &idata
, 0, &in_threadid
)) {
610 fprintf(stderr
, "Unable to create input thread\n");
616 n
= WaitForMultipleObjects(4, handles
, FALSE
, INFINITE
);
618 WSANETWORKEVENTS things
;
620 extern SOCKET
first_socket(int *), next_socket(int *);
621 extern int select_result(WPARAM
, LPARAM
);
625 * We must not call select_result() for any socket
626 * until we have finished enumerating within the tree.
627 * This is because select_result() may close the socket
628 * and modify the tree.
630 /* Count the active sockets. */
632 for (socket
= first_socket(&socketstate
);
633 socket
!= INVALID_SOCKET
;
634 socket
= next_socket(&socketstate
)) i
++;
636 /* Expand the buffer if necessary. */
639 sklist
= srealloc(sklist
, sksize
* sizeof(*sklist
));
642 /* Retrieve the sockets into sklist. */
644 for (socket
= first_socket(&socketstate
);
645 socket
!= INVALID_SOCKET
;
646 socket
= next_socket(&socketstate
)) {
647 sklist
[skcount
++] = socket
;
650 /* Now we're done enumerating; go through the list. */
651 for (i
= 0; i
< skcount
; i
++) {
654 wp
= (WPARAM
) socket
;
655 if (!WSAEnumNetworkEvents(socket
, NULL
, &things
)) {
656 static const struct { int bit
, mask
; } eventtypes
[] = {
657 {FD_CONNECT_BIT
, FD_CONNECT
},
658 {FD_READ_BIT
, FD_READ
},
659 {FD_CLOSE_BIT
, FD_CLOSE
},
660 {FD_OOB_BIT
, FD_OOB
},
661 {FD_WRITE_BIT
, FD_WRITE
},
662 {FD_ACCEPT_BIT
, FD_ACCEPT
},
666 noise_ultralight(socket
);
667 noise_ultralight(things
.lNetworkEvents
);
669 for (e
= 0; e
< lenof(eventtypes
); e
++)
670 if (things
.lNetworkEvents
& eventtypes
[e
].mask
) {
672 int err
= things
.iErrorCode
[eventtypes
[e
].bit
];
673 lp
= WSAMAKESELECTREPLY(eventtypes
[e
].mask
, err
);
674 connopen
&= select_result(wp
, lp
);
680 noise_ultralight(idata
.len
);
681 if (connopen
&& back
->socket(backhandle
) != NULL
) {
683 back
->send(backhandle
, idata
.buffer
, idata
.len
);
685 back
->special(backhandle
, TS_EOF
);
690 if (!odata
.writeret
) {
691 fprintf(stderr
, "Unable to write to standard output\n");
694 bufchain_consume(&stdout_data
, odata
.lenwritten
);
695 if (bufchain_size(&stdout_data
) > 0)
697 if (connopen
&& back
->socket(backhandle
) != NULL
) {
698 back
->unthrottle(backhandle
, bufchain_size(&stdout_data
) +
699 bufchain_size(&stderr_data
));
703 if (!edata
.writeret
) {
704 fprintf(stderr
, "Unable to write to standard output\n");
707 bufchain_consume(&stderr_data
, edata
.lenwritten
);
708 if (bufchain_size(&stderr_data
) > 0)
710 if (connopen
&& back
->socket(backhandle
) != NULL
) {
711 back
->unthrottle(backhandle
, bufchain_size(&stdout_data
) +
712 bufchain_size(&stderr_data
));
715 if (!reading
&& back
->sendbuffer(backhandle
) < MAX_STDIN_BACKLOG
) {
716 SetEvent(idata
.eventback
);
719 if ((!connopen
|| back
->socket(backhandle
) == NULL
) &&
720 bufchain_size(&stdout_data
) == 0 &&
721 bufchain_size(&stderr_data
) == 0)
722 break; /* we closed the connection */
725 exitcode
= back
->exitcode(backhandle
);
727 fprintf(stderr
, "Remote process exit code unavailable\n");
728 exitcode
= 1; /* this is an error condition */