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 connection_fatal(char *p
, ...)
35 fprintf(stderr
, "FATAL ERROR: ");
37 vfprintf(stderr
, p
, ap
);
43 void cmdline_error(char *p
, ...)
46 fprintf(stderr
, "plink: ");
48 vfprintf(stderr
, p
, ap
);
54 static char *password
= NULL
;
56 HANDLE inhandle
, outhandle
, errhandle
;
57 DWORD orig_console_mode
;
61 int term_ldisc(int mode
)
65 void ldisc_update(int echo
, int edit
)
67 /* Update stdin read mode to reflect changes in line discipline. */
70 mode
= ENABLE_PROCESSED_INPUT
;
72 mode
= mode
| ENABLE_ECHO_INPUT
;
74 mode
= mode
& ~ENABLE_ECHO_INPUT
;
76 mode
= mode
| ENABLE_LINE_INPUT
;
78 mode
= mode
& ~ENABLE_LINE_INPUT
;
79 SetConsoleMode(inhandle
, mode
);
85 HANDLE event
, eventback
;
88 static DWORD WINAPI
stdin_read_thread(void *param
)
90 struct input_data
*idata
= (struct input_data
*) param
;
93 inhandle
= GetStdHandle(STD_INPUT_HANDLE
);
95 while (ReadFile(inhandle
, idata
->buffer
, sizeof(idata
->buffer
),
96 &idata
->len
, NULL
) && idata
->len
> 0) {
97 SetEvent(idata
->event
);
98 WaitForSingleObject(idata
->eventback
, INFINITE
);
102 SetEvent(idata
->event
);
108 DWORD len
, lenwritten
;
112 HANDLE event
, eventback
;
116 static DWORD WINAPI
stdout_write_thread(void *param
)
118 struct output_data
*odata
= (struct output_data
*) param
;
119 HANDLE outhandle
, errhandle
;
121 outhandle
= GetStdHandle(STD_OUTPUT_HANDLE
);
122 errhandle
= GetStdHandle(STD_ERROR_HANDLE
);
125 WaitForSingleObject(odata
->eventback
, INFINITE
);
129 WriteFile(odata
->is_stderr ? errhandle
: outhandle
,
130 odata
->buffer
, odata
->len
, &odata
->lenwritten
, NULL
);
131 SetEvent(odata
->event
);
137 bufchain stdout_data
, stderr_data
;
138 struct output_data odata
, edata
;
140 void try_output(int is_stderr
)
142 struct output_data
*data
= (is_stderr ?
&edata
: &odata
);
147 bufchain_prefix(is_stderr ?
&stderr_data
: &stdout_data
,
148 &senddata
, &sendlen
);
149 data
->buffer
= senddata
;
151 SetEvent(data
->eventback
);
156 int from_backend(int is_stderr
, char *data
, int len
)
158 HANDLE h
= (is_stderr ? errhandle
: outhandle
);
164 bufchain_add(&stderr_data
, data
, len
);
167 bufchain_add(&stdout_data
, data
, len
);
171 osize
= bufchain_size(&stdout_data
);
172 esize
= bufchain_size(&stderr_data
);
174 return osize
+ esize
;
178 * Short description of parameters.
180 static void usage(void)
182 printf("PuTTY Link: command-line connection utility\n");
184 printf("Usage: plink [options] [user@]host [command]\n");
185 printf(" (\"host\" can also be a PuTTY saved session name)\n");
186 printf("Options:\n");
187 printf(" -v show verbose messages\n");
188 printf(" -load sessname Load settings from saved session\n");
189 printf(" -ssh -telnet -rlogin -raw\n");
190 printf(" force use of a particular protocol (default SSH)\n");
191 printf(" -P port connect to specified port\n");
192 printf(" -l user connect with specified username\n");
193 printf(" -m file read remote command(s) from file\n");
194 printf(" -batch disable all interactive prompts\n");
195 printf("The following options only apply to SSH connections:\n");
196 printf(" -pw passw login with specified password\n");
197 printf(" -L listen-port:host:port Forward local port to "
199 printf(" -R listen-port:host:port Forward remote port to"
201 printf(" -X -x enable / disable X11 forwarding\n");
202 printf(" -A -a enable / disable agent forwarding\n");
203 printf(" -t -T enable / disable pty allocation\n");
204 printf(" -1 -2 force use of particular protocol version\n");
205 printf(" -C enable compression\n");
206 printf(" -i key private key file for authentication\n");
210 char *do_select(SOCKET skt
, int startup
)
214 events
= (FD_CONNECT
| FD_READ
| FD_WRITE
|
215 FD_OOB
| FD_CLOSE
| FD_ACCEPT
);
219 if (WSAEventSelect(skt
, netevent
, events
) == SOCKET_ERROR
) {
220 switch (WSAGetLastError()) {
222 return "Network is down";
224 return "WSAAsyncSelect(): unknown error";
230 int main(int argc
, char **argv
)
234 WSAEVENT stdinevent
, stdoutevent
, stderrevent
;
236 DWORD in_threadid
, out_threadid
, err_threadid
;
237 struct input_data idata
;
246 ssh_get_line
= console_get_line
;
249 skcount
= sksize
= 0;
251 * Initialise port and protocol to sensible defaults. (These
252 * will be overridden by more or less anything.)
254 default_protocol
= PROT_SSH
;
259 * Process the command line.
261 do_defaults(NULL
, &cfg
);
262 default_protocol
= cfg
.protocol
;
263 default_port
= cfg
.port
;
266 * Override the default protocol if PLINK_PROTOCOL is set.
268 char *p
= getenv("PLINK_PROTOCOL");
271 for (i
= 0; backends
[i
].backend
!= NULL
; i
++) {
272 if (!strcmp(backends
[i
].name
, p
)) {
273 default_protocol
= cfg
.protocol
= backends
[i
].protocol
;
274 default_port
= cfg
.port
=
275 backends
[i
].backend
->default_port
;
284 int ret
= cmdline_process_param(p
, (argc
> 1 ? argv
[1] : NULL
), 1);
287 "plink: option \"%s\" requires an argument\n", p
);
288 } else if (ret
== 2) {
290 } else if (ret
== 1) {
292 } else if (!strcmp(p
, "-batch")) {
293 console_batch_mode
= 1;
294 } else if (!strcmp(p
, "-log")) {
295 logfile
= "putty.log";
301 * If the hostname starts with "telnet:", set the
302 * protocol to Telnet and process the string as a
305 if (!strncmp(q
, "telnet:", 7)) {
309 if (q
[0] == '/' && q
[1] == '/')
311 cfg
.protocol
= PROT_TELNET
;
313 while (*p
&& *p
!= ':' && *p
!= '/')
322 strncpy(cfg
.host
, q
, sizeof(cfg
.host
) - 1);
323 cfg
.host
[sizeof(cfg
.host
) - 1] = '\0';
327 * Before we process the [user@]host string, we
328 * first check for the presence of a protocol
329 * prefix (a protocol name followed by ",").
334 for (i
= 0; backends
[i
].backend
!= NULL
; i
++) {
335 j
= strlen(backends
[i
].name
);
337 !memcmp(backends
[i
].name
, p
, j
)) {
338 default_protocol
= cfg
.protocol
=
339 backends
[i
].protocol
;
341 backends
[i
].backend
->default_port
;
349 * Three cases. Either (a) there's a nonzero
350 * length string followed by an @, in which
351 * case that's user and the remainder is host.
352 * Or (b) there's only one string, not counting
353 * a potential initial @, and it exists in the
354 * saved-sessions database. Or (c) only one
355 * string and it _doesn't_ exist in the
360 p
++, r
= NULL
; /* discount initial @ */
366 do_defaults(p
, &cfg2
);
367 if (cfg2
.host
[0] == '\0') {
368 /* No settings for this host; use defaults */
369 strncpy(cfg
.host
, p
, sizeof(cfg
.host
) - 1);
370 cfg
.host
[sizeof(cfg
.host
) - 1] = '\0';
371 cfg
.port
= default_port
;
374 cfg
.remote_cmd_ptr
= cfg
.remote_cmd
;
378 strncpy(cfg
.username
, p
, sizeof(cfg
.username
) - 1);
379 cfg
.username
[sizeof(cfg
.username
) - 1] = '\0';
380 strncpy(cfg
.host
, r
, sizeof(cfg
.host
) - 1);
381 cfg
.host
[sizeof(cfg
.host
) - 1] = '\0';
382 cfg
.port
= default_port
;
388 cmdlen
= cmdsize
= 0;
393 if (cmdlen
>= cmdsize
) {
394 cmdsize
= cmdlen
+ 512;
395 command
= srealloc(command
, cmdsize
);
397 command
[cmdlen
++]=*p
++;
399 if (cmdlen
>= cmdsize
) {
400 cmdsize
= cmdlen
+ 512;
401 command
= srealloc(command
, cmdsize
);
403 command
[cmdlen
++]=' '; /* always add trailing space */
404 if (--argc
) p
= *++argv
;
406 if (cmdlen
) command
[--cmdlen
]='\0';
407 /* change trailing blank to NUL */
408 cfg
.remote_cmd_ptr
= command
;
409 cfg
.remote_cmd_ptr2
= NULL
;
410 cfg
.nopty
= TRUE
; /* command => no terminal */
412 break; /* done with cmdline */
422 * Trim leading whitespace off the hostname if it's there.
425 int space
= strspn(cfg
.host
, " \t");
426 memmove(cfg
.host
, cfg
.host
+space
, 1+strlen(cfg
.host
)-space
);
429 /* See if host is of the form user@host */
430 if (cfg
.host
[0] != '\0') {
431 char *atsign
= strchr(cfg
.host
, '@');
432 /* Make sure we're not overflowing the user field */
434 if (atsign
- cfg
.host
< sizeof cfg
.username
) {
435 strncpy(cfg
.username
, cfg
.host
, atsign
- cfg
.host
);
436 cfg
.username
[atsign
- cfg
.host
] = '\0';
438 memmove(cfg
.host
, atsign
+ 1, 1 + strlen(atsign
+ 1));
443 * Perform command-line overrides on session configuration.
448 * Trim a colon suffix off the hostname if it's there.
450 cfg
.host
[strcspn(cfg
.host
, ":")] = '\0';
452 if (!*cfg
.remote_cmd_ptr
)
453 flags
|= FLAG_INTERACTIVE
;
456 * Select protocol. This is farmed out into a table in a
457 * separate file to enable an ssh-free variant.
462 for (i
= 0; backends
[i
].backend
!= NULL
; i
++)
463 if (backends
[i
].protocol
== cfg
.protocol
) {
464 back
= backends
[i
].backend
;
469 "Internal fault: Unsupported protocol found\n");
477 if (portnumber
!= -1)
478 cfg
.port
= portnumber
;
481 * Initialise WinSock.
483 winsock_ver
= MAKEWORD(2, 0);
484 if (WSAStartup(winsock_ver
, &wsadata
)) {
485 MessageBox(NULL
, "Unable to initialise WinSock", "WinSock Error",
486 MB_OK
| MB_ICONEXCLAMATION
);
489 if (LOBYTE(wsadata
.wVersion
) != 2 || HIBYTE(wsadata
.wVersion
) != 0) {
490 MessageBox(NULL
, "WinSock version is incompatible with 2.0",
491 "WinSock Error", MB_OK
| MB_ICONEXCLAMATION
);
498 * Start up the connection.
500 netevent
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
504 /* nodelay is only useful if stdin is a character device (console) */
505 int nodelay
= cfg
.tcp_nodelay
&&
506 (GetFileType(GetStdHandle(STD_INPUT_HANDLE
)) == FILE_TYPE_CHAR
);
508 error
= back
->init(cfg
.host
, cfg
.port
, &realhost
, nodelay
);
510 fprintf(stderr
, "Unable to open connection:\n%s", error
);
517 stdinevent
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
518 stdoutevent
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
519 stderrevent
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
521 inhandle
= GetStdHandle(STD_INPUT_HANDLE
);
522 outhandle
= GetStdHandle(STD_OUTPUT_HANDLE
);
523 errhandle
= GetStdHandle(STD_ERROR_HANDLE
);
524 GetConsoleMode(inhandle
, &orig_console_mode
);
525 SetConsoleMode(inhandle
, ENABLE_PROCESSED_INPUT
);
528 * Turn off ECHO and LINE input modes. We don't care if this
529 * call fails, because we know we aren't necessarily running in
532 handles
[0] = netevent
;
533 handles
[1] = stdinevent
;
534 handles
[2] = stdoutevent
;
535 handles
[3] = stderrevent
;
539 * Create spare threads to write to stdout and stderr, so we
540 * can arrange asynchronous writes.
542 odata
.event
= stdoutevent
;
543 odata
.eventback
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
545 odata
.busy
= odata
.done
= 0;
546 if (!CreateThread(NULL
, 0, stdout_write_thread
,
547 &odata
, 0, &out_threadid
)) {
548 fprintf(stderr
, "Unable to create output thread\n");
551 edata
.event
= stderrevent
;
552 edata
.eventback
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
554 edata
.busy
= edata
.done
= 0;
555 if (!CreateThread(NULL
, 0, stdout_write_thread
,
556 &edata
, 0, &err_threadid
)) {
557 fprintf(stderr
, "Unable to create error output thread\n");
564 if (!sending
&& back
->sendok()) {
566 * Create a separate thread to read from stdin. This is
567 * a total pain, but I can't find another way to do it:
569 * - an overlapped ReadFile or ReadFileEx just doesn't
570 * happen; we get failure from ReadFileEx, and
571 * ReadFile blocks despite being given an OVERLAPPED
572 * structure. Perhaps we can't do overlapped reads
573 * on consoles. WHY THE HELL NOT?
575 * - WaitForMultipleObjects(netevent, console) doesn't
576 * work, because it signals the console when
577 * _anything_ happens, including mouse motions and
578 * other things that don't cause data to be readable
579 * - so we're back to ReadFile blocking.
581 idata
.event
= stdinevent
;
582 idata
.eventback
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
583 if (!CreateThread(NULL
, 0, stdin_read_thread
,
584 &idata
, 0, &in_threadid
)) {
585 fprintf(stderr
, "Unable to create input thread\n");
591 n
= WaitForMultipleObjects(4, handles
, FALSE
, INFINITE
);
593 WSANETWORKEVENTS things
;
595 extern SOCKET
first_socket(int *), next_socket(int *);
596 extern int select_result(WPARAM
, LPARAM
);
600 * We must not call select_result() for any socket
601 * until we have finished enumerating within the tree.
602 * This is because select_result() may close the socket
603 * and modify the tree.
605 /* Count the active sockets. */
607 for (socket
= first_socket(&socketstate
);
608 socket
!= INVALID_SOCKET
;
609 socket
= next_socket(&socketstate
)) i
++;
611 /* Expand the buffer if necessary. */
614 sklist
= srealloc(sklist
, sksize
* sizeof(*sklist
));
617 /* Retrieve the sockets into sklist. */
619 for (socket
= first_socket(&socketstate
);
620 socket
!= INVALID_SOCKET
;
621 socket
= next_socket(&socketstate
)) {
622 sklist
[skcount
++] = socket
;
625 /* Now we're done enumerating; go through the list. */
626 for (i
= 0; i
< skcount
; i
++) {
629 wp
= (WPARAM
) socket
;
630 if (!WSAEnumNetworkEvents(socket
, NULL
, &things
)) {
631 static const struct { int bit
, mask
; } eventtypes
[] = {
632 {FD_CONNECT_BIT
, FD_CONNECT
},
633 {FD_READ_BIT
, FD_READ
},
634 {FD_CLOSE_BIT
, FD_CLOSE
},
635 {FD_OOB_BIT
, FD_OOB
},
636 {FD_WRITE_BIT
, FD_WRITE
},
637 {FD_ACCEPT_BIT
, FD_ACCEPT
},
641 noise_ultralight(socket
);
642 noise_ultralight(things
.lNetworkEvents
);
644 for (e
= 0; e
< lenof(eventtypes
); e
++)
645 if (things
.lNetworkEvents
& eventtypes
[e
].mask
) {
647 int err
= things
.iErrorCode
[eventtypes
[e
].bit
];
648 lp
= WSAMAKESELECTREPLY(eventtypes
[e
].mask
, err
);
649 connopen
&= select_result(wp
, lp
);
655 noise_ultralight(idata
.len
);
656 if (connopen
&& back
->socket() != NULL
) {
658 back
->send(idata
.buffer
, idata
.len
);
660 back
->special(TS_EOF
);
665 if (!odata
.writeret
) {
666 fprintf(stderr
, "Unable to write to standard output\n");
669 bufchain_consume(&stdout_data
, odata
.lenwritten
);
670 if (bufchain_size(&stdout_data
) > 0)
672 if (connopen
&& back
->socket() != NULL
) {
673 back
->unthrottle(bufchain_size(&stdout_data
) +
674 bufchain_size(&stderr_data
));
678 if (!edata
.writeret
) {
679 fprintf(stderr
, "Unable to write to standard output\n");
682 bufchain_consume(&stderr_data
, edata
.lenwritten
);
683 if (bufchain_size(&stderr_data
) > 0)
685 if (connopen
&& back
->socket() != NULL
) {
686 back
->unthrottle(bufchain_size(&stdout_data
) +
687 bufchain_size(&stderr_data
));
690 if (!reading
&& back
->sendbuffer() < MAX_STDIN_BACKLOG
) {
691 SetEvent(idata
.eventback
);
694 if ((!connopen
|| back
->socket() == NULL
) &&
695 bufchain_size(&stdout_data
) == 0 &&
696 bufchain_size(&stderr_data
) == 0)
697 break; /* we closed the connection */
700 exitcode
= back
->exitcode();
702 fprintf(stderr
, "Remote process exit code unavailable\n");
703 exitcode
= 1; /* this is an error condition */