891e7d501bf8fc8cf08973e2c138144c2c41be04
2 * PLink - a command-line (stdin/stdout) variant of PuTTY.
13 #define PUTTY_DO_GLOBALS /* actually _define_ globals */
18 #define MAX_STDIN_BACKLOG 4096
20 void fatalbox(char *p
, ...)
23 fprintf(stderr
, "FATAL ERROR: ");
25 vfprintf(stderr
, p
, ap
);
31 void connection_fatal(char *p
, ...)
34 fprintf(stderr
, "FATAL ERROR: ");
36 vfprintf(stderr
, p
, ap
);
43 static char *password
= NULL
;
45 HANDLE inhandle
, outhandle
, errhandle
;
46 DWORD orig_console_mode
;
50 int term_ldisc(int mode
)
54 void ldisc_update(int echo
, int edit
)
56 /* Update stdin read mode to reflect changes in line discipline. */
59 mode
= ENABLE_PROCESSED_INPUT
;
61 mode
= mode
| ENABLE_ECHO_INPUT
;
63 mode
= mode
& ~ENABLE_ECHO_INPUT
;
65 mode
= mode
| ENABLE_LINE_INPUT
;
67 mode
= mode
& ~ENABLE_LINE_INPUT
;
68 SetConsoleMode(inhandle
, mode
);
74 HANDLE event
, eventback
;
77 static DWORD WINAPI
stdin_read_thread(void *param
)
79 struct input_data
*idata
= (struct input_data
*) param
;
82 inhandle
= GetStdHandle(STD_INPUT_HANDLE
);
84 while (ReadFile(inhandle
, idata
->buffer
, sizeof(idata
->buffer
),
85 &idata
->len
, NULL
) && idata
->len
> 0) {
86 SetEvent(idata
->event
);
87 WaitForSingleObject(idata
->eventback
, INFINITE
);
91 SetEvent(idata
->event
);
97 DWORD len
, lenwritten
;
101 HANDLE event
, eventback
;
105 static DWORD WINAPI
stdout_write_thread(void *param
)
107 struct output_data
*odata
= (struct output_data
*) param
;
108 HANDLE outhandle
, errhandle
;
110 outhandle
= GetStdHandle(STD_OUTPUT_HANDLE
);
111 errhandle
= GetStdHandle(STD_ERROR_HANDLE
);
114 WaitForSingleObject(odata
->eventback
, INFINITE
);
118 WriteFile(odata
->is_stderr ? errhandle
: outhandle
,
119 odata
->buffer
, odata
->len
, &odata
->lenwritten
, NULL
);
120 SetEvent(odata
->event
);
126 bufchain stdout_data
, stderr_data
;
127 struct output_data odata
, edata
;
129 void try_output(int is_stderr
)
131 struct output_data
*data
= (is_stderr ?
&edata
: &odata
);
136 bufchain_prefix(is_stderr ?
&stderr_data
: &stdout_data
,
137 &senddata
, &sendlen
);
138 data
->buffer
= senddata
;
140 SetEvent(data
->eventback
);
145 int from_backend(int is_stderr
, char *data
, int len
)
147 HANDLE h
= (is_stderr ? errhandle
: outhandle
);
151 bufchain_add(&stderr_data
, data
, len
);
154 bufchain_add(&stdout_data
, data
, len
);
158 osize
= bufchain_size(&stdout_data
);
159 esize
= bufchain_size(&stderr_data
);
161 return osize
+ esize
;
165 * Short description of parameters.
167 static void usage(void)
169 printf("PuTTY Link: command-line connection utility\n");
171 printf("Usage: plink [options] [user@]host [command]\n");
172 printf(" (\"host\" can also be a PuTTY saved session name)\n");
173 printf("Options:\n");
174 printf(" -v show verbose messages\n");
175 printf(" -ssh force use of ssh protocol\n");
176 printf(" -P port connect to specified port\n");
177 printf(" -pw passw login with specified password\n");
178 printf(" -m file read remote command(s) from file\n");
179 printf(" -L listen-port:host:port Forward local port to "
181 printf(" -R listen-port:host:port Forward remote port to"
186 char *do_select(SOCKET skt
, int startup
)
190 events
= (FD_CONNECT
| FD_READ
| FD_WRITE
|
191 FD_OOB
| FD_CLOSE
| FD_ACCEPT
);
195 if (WSAEventSelect(skt
, netevent
, events
) == SOCKET_ERROR
) {
196 switch (WSAGetLastError()) {
198 return "Network is down";
200 return "WSAAsyncSelect(): unknown error";
206 int main(int argc
, char **argv
)
210 WSAEVENT stdinevent
, stdoutevent
, stderrevent
;
212 DWORD in_threadid
, out_threadid
, err_threadid
;
213 struct input_data idata
;
221 char extra_portfwd
[sizeof(cfg
.portfwd
)];
223 ssh_get_line
= console_get_line
;
226 skcount
= sksize
= 0;
228 * Initialise port and protocol to sensible defaults. (These
229 * will be overridden by more or less anything.)
231 default_protocol
= PROT_SSH
;
236 * Process the command line.
238 do_defaults(NULL
, &cfg
);
239 default_protocol
= cfg
.protocol
;
240 default_port
= cfg
.port
;
243 * Override the default protocol if PLINK_PROTOCOL is set.
245 char *p
= getenv("PLINK_PROTOCOL");
248 for (i
= 0; backends
[i
].backend
!= NULL
; i
++) {
249 if (!strcmp(backends
[i
].name
, p
)) {
250 default_protocol
= cfg
.protocol
= backends
[i
].protocol
;
251 default_port
= cfg
.port
=
252 backends
[i
].backend
->default_port
;
261 if (!strcmp(p
, "-ssh")) {
262 default_protocol
= cfg
.protocol
= PROT_SSH
;
263 default_port
= cfg
.port
= 22;
264 } else if (!strcmp(p
, "-telnet")) {
265 default_protocol
= cfg
.protocol
= PROT_TELNET
;
266 default_port
= cfg
.port
= 23;
267 } else if (!strcmp(p
, "-rlogin")) {
268 default_protocol
= cfg
.protocol
= PROT_RLOGIN
;
269 default_port
= cfg
.port
= 513;
270 } else if (!strcmp(p
, "-raw")) {
271 default_protocol
= cfg
.protocol
= PROT_RAW
;
272 } else if (!strcmp(p
, "-batch")) {
273 console_batch_mode
= TRUE
;
274 } else if (!strcmp(p
, "-v")) {
275 flags
|= FLAG_VERBOSE
;
276 } else if (!strcmp(p
, "-log")) {
277 logfile
= "putty.log";
278 } else if (!strcmp(p
, "-pw") && argc
> 1) {
279 --argc
, console_password
= *++argv
;
280 } else if (!strcmp(p
, "-l") && argc
> 1) {
282 --argc
, username
= *++argv
;
283 strncpy(cfg
.username
, username
, sizeof(cfg
.username
));
284 cfg
.username
[sizeof(cfg
.username
) - 1] = '\0';
285 } else if ((!strcmp(p
, "-L") || !strcmp(p
, "-R")) && argc
> 1) {
288 --argc
, fwd
= *++argv
;
290 /* if multiple forwards, find end of list */
291 if (ptr
[0]=='R' || ptr
[0]=='L') {
292 for (i
= 0; i
< sizeof(extra_portfwd
) - 2; i
++)
293 if (ptr
[i
]=='\000' && ptr
[i
+1]=='\000')
295 ptr
= ptr
+ i
+ 1; /* point to next forward slot */
297 ptr
[0] = p
[1]; /* insert a 'L' or 'R' at the start */
298 strncpy(ptr
+1, fwd
, sizeof(extra_portfwd
) - i
);
299 q
= strchr(ptr
, ':');
300 if (q
) *q
= '\t'; /* replace first : with \t */
301 ptr
[strlen(ptr
)+1] = '\000'; /* append two '\000' */
302 extra_portfwd
[sizeof(extra_portfwd
) - 1] = '\0';
303 } else if (!strcmp(p
, "-m") && argc
> 1) {
304 char *filename
, *command
;
309 --argc
, filename
= *++argv
;
311 cmdlen
= cmdsize
= 0;
313 fp
= fopen(filename
, "r");
315 fprintf(stderr
, "plink: unable to open command "
316 "file \"%s\"\n", filename
);
324 if (cmdlen
>= cmdsize
) {
325 cmdsize
= cmdlen
+ 512;
326 command
= srealloc(command
, cmdsize
);
328 command
[cmdlen
++] = d
;
330 cfg
.remote_cmd_ptr
= command
;
331 cfg
.remote_cmd_ptr2
= NULL
;
332 cfg
.nopty
= TRUE
; /* command => no terminal */
333 } else if (!strcmp(p
, "-P") && argc
> 1) {
334 --argc
, portnumber
= atoi(*++argv
);
340 * If the hostname starts with "telnet:", set the
341 * protocol to Telnet and process the string as a
344 if (!strncmp(q
, "telnet:", 7)) {
348 if (q
[0] == '/' && q
[1] == '/')
350 cfg
.protocol
= PROT_TELNET
;
352 while (*p
&& *p
!= ':' && *p
!= '/')
361 strncpy(cfg
.host
, q
, sizeof(cfg
.host
) - 1);
362 cfg
.host
[sizeof(cfg
.host
) - 1] = '\0';
366 * Before we process the [user@]host string, we
367 * first check for the presence of a protocol
368 * prefix (a protocol name followed by ",").
373 for (i
= 0; backends
[i
].backend
!= NULL
; i
++) {
374 j
= strlen(backends
[i
].name
);
376 !memcmp(backends
[i
].name
, p
, j
)) {
377 default_protocol
= cfg
.protocol
=
378 backends
[i
].protocol
;
380 backends
[i
].backend
->default_port
;
388 * Three cases. Either (a) there's a nonzero
389 * length string followed by an @, in which
390 * case that's user and the remainder is host.
391 * Or (b) there's only one string, not counting
392 * a potential initial @, and it exists in the
393 * saved-sessions database. Or (c) only one
394 * string and it _doesn't_ exist in the
399 p
++, r
= NULL
; /* discount initial @ */
405 do_defaults(p
, &cfg2
);
406 if (cfg2
.host
[0] == '\0') {
407 /* No settings for this host; use defaults */
408 strncpy(cfg
.host
, p
, sizeof(cfg
.host
) - 1);
409 cfg
.host
[sizeof(cfg
.host
) - 1] = '\0';
410 cfg
.port
= default_port
;
413 cfg
.remote_cmd_ptr
= cfg
.remote_cmd
;
417 strncpy(cfg
.username
, p
, sizeof(cfg
.username
) - 1);
418 cfg
.username
[sizeof(cfg
.username
) - 1] = '\0';
419 strncpy(cfg
.host
, r
, sizeof(cfg
.host
) - 1);
420 cfg
.host
[sizeof(cfg
.host
) - 1] = '\0';
421 cfg
.port
= default_port
;
425 int len
= sizeof(cfg
.remote_cmd
) - 1;
426 char *cp
= cfg
.remote_cmd
;
437 strncpy(cp
, *++argv
, len
);
443 cfg
.nopty
= TRUE
; /* command => no terminal */
444 break; /* done with cmdline */
454 * Trim leading whitespace off the hostname if it's there.
457 int space
= strspn(cfg
.host
, " \t");
458 memmove(cfg
.host
, cfg
.host
+space
, 1+strlen(cfg
.host
)-space
);
461 /* See if host is of the form user@host */
462 if (cfg
.host
[0] != '\0') {
463 char *atsign
= strchr(cfg
.host
, '@');
464 /* Make sure we're not overflowing the user field */
466 if (atsign
- cfg
.host
< sizeof cfg
.username
) {
467 strncpy(cfg
.username
, cfg
.host
, atsign
- cfg
.host
);
468 cfg
.username
[atsign
- cfg
.host
] = '\0';
470 memmove(cfg
.host
, atsign
+ 1, 1 + strlen(atsign
+ 1));
475 * Trim a colon suffix off the hostname if it's there.
477 cfg
.host
[strcspn(cfg
.host
, ":")] = '\0';
479 if (!*cfg
.remote_cmd_ptr
)
480 flags
|= FLAG_INTERACTIVE
;
483 * Select protocol. This is farmed out into a table in a
484 * separate file to enable an ssh-free variant.
489 for (i
= 0; backends
[i
].backend
!= NULL
; i
++)
490 if (backends
[i
].protocol
== cfg
.protocol
) {
491 back
= backends
[i
].backend
;
496 "Internal fault: Unsupported protocol found\n");
502 * Add extra port forwardings (accumulated on command line) to
510 while (cfg
.portfwd
[i
])
511 i
+= strlen(cfg
.portfwd
+i
) + 1;
513 if (strlen(p
)+2 > sizeof(cfg
.portfwd
)-i
) {
514 fprintf(stderr
, "Internal fault: not enough space for all"
515 " port forwardings\n");
518 strncpy(cfg
.portfwd
+i
, p
, sizeof(cfg
.portfwd
)-i
-1);
519 i
+= strlen(cfg
.portfwd
+i
) + 1;
520 cfg
.portfwd
[i
] = '\0';
528 if (portnumber
!= -1)
529 cfg
.port
= portnumber
;
532 * Initialise WinSock.
534 winsock_ver
= MAKEWORD(2, 0);
535 if (WSAStartup(winsock_ver
, &wsadata
)) {
536 MessageBox(NULL
, "Unable to initialise WinSock", "WinSock Error",
537 MB_OK
| MB_ICONEXCLAMATION
);
540 if (LOBYTE(wsadata
.wVersion
) != 2 || HIBYTE(wsadata
.wVersion
) != 0) {
541 MessageBox(NULL
, "WinSock version is incompatible with 2.0",
542 "WinSock Error", MB_OK
| MB_ICONEXCLAMATION
);
549 * Start up the connection.
551 netevent
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
555 /* nodelay is only useful if stdin is a character device (console) */
556 int nodelay
= cfg
.tcp_nodelay
&&
557 (GetFileType(GetStdHandle(STD_INPUT_HANDLE
)) == FILE_TYPE_CHAR
);
559 error
= back
->init(cfg
.host
, cfg
.port
, &realhost
, nodelay
);
561 fprintf(stderr
, "Unable to open connection:\n%s", error
);
568 stdinevent
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
569 stdoutevent
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
570 stderrevent
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
572 inhandle
= GetStdHandle(STD_INPUT_HANDLE
);
573 outhandle
= GetStdHandle(STD_OUTPUT_HANDLE
);
574 errhandle
= GetStdHandle(STD_ERROR_HANDLE
);
575 GetConsoleMode(inhandle
, &orig_console_mode
);
576 SetConsoleMode(inhandle
, ENABLE_PROCESSED_INPUT
);
579 * Turn off ECHO and LINE input modes. We don't care if this
580 * call fails, because we know we aren't necessarily running in
583 handles
[0] = netevent
;
584 handles
[1] = stdinevent
;
585 handles
[2] = stdoutevent
;
586 handles
[3] = stderrevent
;
590 * Create spare threads to write to stdout and stderr, so we
591 * can arrange asynchronous writes.
593 odata
.event
= stdoutevent
;
594 odata
.eventback
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
596 odata
.busy
= odata
.done
= 0;
597 if (!CreateThread(NULL
, 0, stdout_write_thread
,
598 &odata
, 0, &out_threadid
)) {
599 fprintf(stderr
, "Unable to create output thread\n");
602 edata
.event
= stderrevent
;
603 edata
.eventback
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
605 edata
.busy
= edata
.done
= 0;
606 if (!CreateThread(NULL
, 0, stdout_write_thread
,
607 &edata
, 0, &err_threadid
)) {
608 fprintf(stderr
, "Unable to create error output thread\n");
615 if (!sending
&& back
->sendok()) {
617 * Create a separate thread to read from stdin. This is
618 * a total pain, but I can't find another way to do it:
620 * - an overlapped ReadFile or ReadFileEx just doesn't
621 * happen; we get failure from ReadFileEx, and
622 * ReadFile blocks despite being given an OVERLAPPED
623 * structure. Perhaps we can't do overlapped reads
624 * on consoles. WHY THE HELL NOT?
626 * - WaitForMultipleObjects(netevent, console) doesn't
627 * work, because it signals the console when
628 * _anything_ happens, including mouse motions and
629 * other things that don't cause data to be readable
630 * - so we're back to ReadFile blocking.
632 idata
.event
= stdinevent
;
633 idata
.eventback
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
634 if (!CreateThread(NULL
, 0, stdin_read_thread
,
635 &idata
, 0, &in_threadid
)) {
636 fprintf(stderr
, "Unable to create input thread\n");
642 n
= WaitForMultipleObjects(4, handles
, FALSE
, INFINITE
);
644 WSANETWORKEVENTS things
;
646 extern SOCKET
first_socket(int *), next_socket(int *);
647 extern int select_result(WPARAM
, LPARAM
);
651 * We must not call select_result() for any socket
652 * until we have finished enumerating within the tree.
653 * This is because select_result() may close the socket
654 * and modify the tree.
656 /* Count the active sockets. */
658 for (socket
= first_socket(&socketstate
);
659 socket
!= INVALID_SOCKET
;
660 socket
= next_socket(&socketstate
)) i
++;
662 /* Expand the buffer if necessary. */
665 sklist
= srealloc(sklist
, sksize
* sizeof(*sklist
));
668 /* Retrieve the sockets into sklist. */
670 for (socket
= first_socket(&socketstate
);
671 socket
!= INVALID_SOCKET
;
672 socket
= next_socket(&socketstate
)) {
673 sklist
[skcount
++] = socket
;
676 /* Now we're done enumerating; go through the list. */
677 for (i
= 0; i
< skcount
; i
++) {
680 wp
= (WPARAM
) socket
;
681 if (!WSAEnumNetworkEvents(socket
, NULL
, &things
)) {
682 static const struct { int bit
, mask
; } eventtypes
[] = {
683 {FD_CONNECT_BIT
, FD_CONNECT
},
684 {FD_READ_BIT
, FD_READ
},
685 {FD_CLOSE_BIT
, FD_CLOSE
},
686 {FD_OOB_BIT
, FD_OOB
},
687 {FD_WRITE_BIT
, FD_WRITE
},
688 {FD_ACCEPT_BIT
, FD_ACCEPT
},
692 noise_ultralight(socket
);
693 noise_ultralight(things
.lNetworkEvents
);
695 for (e
= 0; e
< lenof(eventtypes
); e
++)
696 if (things
.lNetworkEvents
& eventtypes
[e
].mask
) {
698 int err
= things
.iErrorCode
[eventtypes
[e
].bit
];
699 lp
= WSAMAKESELECTREPLY(eventtypes
[e
].mask
, err
);
700 connopen
&= select_result(wp
, lp
);
706 noise_ultralight(idata
.len
);
707 if (connopen
&& back
->socket() != NULL
) {
709 back
->send(idata
.buffer
, idata
.len
);
711 back
->special(TS_EOF
);
716 if (!odata
.writeret
) {
717 fprintf(stderr
, "Unable to write to standard output\n");
720 bufchain_consume(&stdout_data
, odata
.lenwritten
);
721 if (bufchain_size(&stdout_data
) > 0)
723 if (connopen
&& back
->socket() != NULL
) {
724 back
->unthrottle(bufchain_size(&stdout_data
) +
725 bufchain_size(&stderr_data
));
729 if (!edata
.writeret
) {
730 fprintf(stderr
, "Unable to write to standard output\n");
733 bufchain_consume(&stderr_data
, edata
.lenwritten
);
734 if (bufchain_size(&stderr_data
) > 0)
736 if (connopen
&& back
->socket() != NULL
) {
737 back
->unthrottle(bufchain_size(&stdout_data
) +
738 bufchain_size(&stderr_data
));
741 if (!reading
&& back
->sendbuffer() < MAX_STDIN_BACKLOG
) {
742 SetEvent(idata
.eventback
);
745 if ((!connopen
|| back
->socket() == NULL
) &&
746 bufchain_size(&stdout_data
) == 0 &&
747 bufchain_size(&stderr_data
) == 0)
748 break; /* we closed the connection */
751 exitcode
= back
->exitcode();
753 fprintf(stderr
, "Remote process exit code unavailable\n");
754 exitcode
= 1; /* this is an error condition */