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_APP + 4)
17 struct agent_callback
{
18 void (*callback
)(void *, void *, int);
24 void fatalbox(char *p
, ...)
27 fprintf(stderr
, "FATAL ERROR: ");
29 vfprintf(stderr
, p
, ap
);
38 void modalfatalbox(char *p
, ...)
41 fprintf(stderr
, "FATAL ERROR: ");
43 vfprintf(stderr
, p
, ap
);
52 void nonfatal(char *p
, ...)
55 fprintf(stderr
, "ERROR: ");
57 vfprintf(stderr
, p
, ap
);
65 void connection_fatal(void *frontend
, char *p
, ...)
68 fprintf(stderr
, "FATAL ERROR: ");
70 vfprintf(stderr
, p
, ap
);
79 void cmdline_error(char *p
, ...)
82 fprintf(stderr
, "plink: ");
84 vfprintf(stderr
, p
, ap
);
90 HANDLE inhandle
, outhandle
, errhandle
;
91 struct handle
*stdin_handle
, *stdout_handle
, *stderr_handle
;
92 DWORD orig_console_mode
;
98 static void *backhandle
;
101 int term_ldisc(Terminal
*term
, int mode
)
105 void ldisc_update(void *frontend
, int echo
, int edit
)
107 /* Update stdin read mode to reflect changes in line discipline. */
110 mode
= ENABLE_PROCESSED_INPUT
;
112 mode
= mode
| ENABLE_ECHO_INPUT
;
114 mode
= mode
& ~ENABLE_ECHO_INPUT
;
116 mode
= mode
| ENABLE_LINE_INPUT
;
118 mode
= mode
& ~ENABLE_LINE_INPUT
;
119 SetConsoleMode(inhandle
, mode
);
122 char *get_ttymode(void *frontend
, const char *mode
) { return NULL
; }
124 int from_backend(void *frontend_handle
, int is_stderr
,
125 const char *data
, int len
)
128 handle_write(stderr_handle
, data
, len
);
130 handle_write(stdout_handle
, data
, len
);
133 return handle_backlog(stdout_handle
) + handle_backlog(stderr_handle
);
136 int from_backend_untrusted(void *frontend_handle
, const char *data
, int len
)
139 * No "untrusted" output should get here (the way the code is
140 * currently, it's all diverted by FLAG_STDERR).
142 assert(!"Unexpected call to from_backend_untrusted()");
143 return 0; /* not reached */
146 int from_backend_eof(void *frontend_handle
)
148 handle_write_eof(stdout_handle
);
149 return FALSE
; /* do not respond to incoming EOF with outgoing */
152 int get_userpass_input(prompts_t
*p
, unsigned char *in
, int inlen
)
155 ret
= cmdline_get_passwd_input(p
, in
, inlen
);
157 ret
= console_get_userpass_input(p
, in
, inlen
);
161 static DWORD main_thread_id
;
163 void agent_schedule_callback(void (*callback
)(void *, void *, int),
164 void *callback_ctx
, void *data
, int len
)
166 struct agent_callback
*c
= snew(struct agent_callback
);
167 c
->callback
= callback
;
168 c
->callback_ctx
= callback_ctx
;
171 PostThreadMessage(main_thread_id
, WM_AGENT_CALLBACK
, 0, (LPARAM
)c
);
175 * Short description of parameters.
177 static void usage(void)
179 printf("PuTTY Link: command-line connection utility\n");
181 printf("Usage: plink [options] [user@]host [command]\n");
182 printf(" (\"host\" can also be a PuTTY saved session name)\n");
183 printf("Options:\n");
184 printf(" -V print version information and exit\n");
185 printf(" -pgpfp print PGP key fingerprints and exit\n");
186 printf(" -v show verbose messages\n");
187 printf(" -load sessname Load settings from saved session\n");
188 printf(" -ssh -telnet -rlogin -raw -serial\n");
189 printf(" force use of a particular protocol\n");
190 printf(" -P port connect to specified port\n");
191 printf(" -l user connect with specified username\n");
192 printf(" -batch disable all interactive prompts\n");
193 printf("The following options only apply to SSH connections:\n");
194 printf(" -pw passw login with specified password\n");
195 printf(" -D [listen-IP:]listen-port\n");
196 printf(" Dynamic SOCKS-based port forwarding\n");
197 printf(" -L [listen-IP:]listen-port:host:port\n");
198 printf(" Forward local port to remote address\n");
199 printf(" -R [listen-IP:]listen-port:host:port\n");
200 printf(" Forward remote port to local address\n");
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(" -4 -6 force use of IPv4 or IPv6\n");
206 printf(" -C enable compression\n");
207 printf(" -i key private key file for authentication\n");
208 printf(" -noagent disable use of Pageant\n");
209 printf(" -agent enable use of Pageant\n");
210 printf(" -m file read remote command(s) from file\n");
211 printf(" -s remote command is an SSH subsystem (SSH-2 only)\n");
212 printf(" -N don't start a shell/command (SSH-2 only)\n");
213 printf(" -nc host:port\n");
214 printf(" open tunnel in place of session (SSH-2 only)\n");
215 printf(" -sercfg configuration-string (e.g. 19200,8,n,1,X)\n");
216 printf(" Specify the serial configuration (serial only)\n");
220 static void version(void)
222 printf("plink: %s\n", ver
);
226 char *do_select(SOCKET skt
, int startup
)
230 events
= (FD_CONNECT
| FD_READ
| FD_WRITE
|
231 FD_OOB
| FD_CLOSE
| FD_ACCEPT
);
235 if (p_WSAEventSelect(skt
, netevent
, events
) == SOCKET_ERROR
) {
236 switch (p_WSAGetLastError()) {
238 return "Network is down";
240 return "WSAEventSelect(): unknown error";
246 int stdin_gotdata(struct handle
*h
, void *data
, int len
)
250 * Special case: report read error.
253 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM
, NULL
, -len
, 0,
254 buf
, lenof(buf
), NULL
);
255 buf
[lenof(buf
)-1] = '\0';
256 if (buf
[strlen(buf
)-1] == '\n')
257 buf
[strlen(buf
)-1] = '\0';
258 fprintf(stderr
, "Unable to read from standard input: %s\n", buf
);
261 noise_ultralight(len
);
262 if (connopen
&& back
->connected(backhandle
)) {
264 return back
->send(backhandle
, data
, len
);
266 back
->special(backhandle
, TS_EOF
);
273 void stdouterr_sent(struct handle
*h
, int new_backlog
)
275 if (new_backlog
< 0) {
277 * Special case: report write error.
280 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM
, NULL
, -new_backlog
, 0,
281 buf
, lenof(buf
), NULL
);
282 buf
[lenof(buf
)-1] = '\0';
283 if (buf
[strlen(buf
)-1] == '\n')
284 buf
[strlen(buf
)-1] = '\0';
285 fprintf(stderr
, "Unable to write to standard %s: %s\n",
286 (h
== stdout_handle ?
"output" : "error"), buf
);
289 if (connopen
&& back
->connected(backhandle
)) {
290 back
->unthrottle(backhandle
, (handle_backlog(stdout_handle
) +
291 handle_backlog(stderr_handle
)));
295 int main(int argc
, char **argv
)
303 int got_host
= FALSE
;
304 int use_subsystem
= 0;
305 unsigned long now
, next
, then
;
308 skcount
= sksize
= 0;
310 * Initialise port and protocol to sensible defaults. (These
311 * will be overridden by more or less anything.)
313 default_protocol
= PROT_SSH
;
318 * Process the command line.
321 do_defaults(NULL
, conf
);
322 loaded_session
= FALSE
;
323 default_protocol
= conf_get_int(conf
, CONF_protocol
);
324 default_port
= conf_get_int(conf
, CONF_port
);
328 * Override the default protocol if PLINK_PROTOCOL is set.
330 char *p
= getenv("PLINK_PROTOCOL");
332 const Backend
*b
= backend_from_name(p
);
334 default_protocol
= b
->protocol
;
335 default_port
= b
->default_port
;
336 conf_set_int(conf
, CONF_protocol
, default_protocol
);
337 conf_set_int(conf
, CONF_port
, default_port
);
344 int ret
= cmdline_process_param(p
, (argc
> 1 ? argv
[1] : NULL
),
348 "plink: option \"%s\" requires an argument\n", p
);
350 } else if (ret
== 2) {
352 } else if (ret
== 1) {
354 } else if (!strcmp(p
, "-batch")) {
355 console_batch_mode
= 1;
356 } else if (!strcmp(p
, "-s")) {
357 /* Save status to write to conf later. */
359 } else if (!strcmp(p
, "-V") || !strcmp(p
, "--version")) {
361 } else if (!strcmp(p
, "--help")) {
363 } else if (!strcmp(p
, "-pgpfp")) {
367 fprintf(stderr
, "plink: unknown option \"%s\"\n", p
);
371 if (!conf_launchable(conf
) || !(got_host
|| loaded_session
)) {
374 * If the hostname starts with "telnet:", set the
375 * protocol to Telnet and process the string as a
378 if (!strncmp(q
, "telnet:", 7)) {
382 if (q
[0] == '/' && q
[1] == '/')
384 conf_set_int(conf
, CONF_protocol
, PROT_TELNET
);
386 while (*p
&& *p
!= ':' && *p
!= '/')
392 conf_set_int(conf
, CONF_port
, atoi(p
));
394 conf_set_int(conf
, CONF_port
, -1);
395 conf_set_str(conf
, CONF_host
, q
);
398 char *r
, *user
, *host
;
400 * Before we process the [user@]host string, we
401 * first check for the presence of a protocol
402 * prefix (a protocol name followed by ",").
408 b
= backend_from_name(p
);
410 default_protocol
= b
->protocol
;
411 conf_set_int(conf
, CONF_protocol
,
413 portnumber
= b
->default_port
;
419 * A nonzero length string followed by an @ is treated
420 * as a username. (We discount an _initial_ @.) The
421 * rest of the string (or the whole string if no @)
422 * is treated as a session name and/or hostname.
426 p
++, r
= NULL
; /* discount initial @ */
431 user
= NULL
, host
= p
;
435 * Now attempt to load a saved session with the
436 * same name as the hostname.
439 Conf
*conf2
= conf_new();
440 do_defaults(host
, conf2
);
441 if (loaded_session
|| !conf_launchable(conf2
)) {
442 /* No settings for this host; use defaults */
443 /* (or session was already loaded with -load) */
444 conf_set_str(conf
, CONF_host
, host
);
445 conf_set_int(conf
, CONF_port
, default_port
);
448 conf_copy_into(conf
, conf2
);
449 loaded_session
= TRUE
;
455 /* Patch in specified username. */
456 conf_set_str(conf
, CONF_username
, user
);
463 cmdlen
= cmdsize
= 0;
468 if (cmdlen
>= cmdsize
) {
469 cmdsize
= cmdlen
+ 512;
470 command
= sresize(command
, cmdsize
, char);
472 command
[cmdlen
++]=*p
++;
474 if (cmdlen
>= cmdsize
) {
475 cmdsize
= cmdlen
+ 512;
476 command
= sresize(command
, cmdsize
, char);
478 command
[cmdlen
++]=' '; /* always add trailing space */
479 if (--argc
) p
= *++argv
;
481 if (cmdlen
) command
[--cmdlen
]='\0';
482 /* change trailing blank to NUL */
483 conf_set_str(conf
, CONF_remote_cmd
, command
);
484 conf_set_str(conf
, CONF_remote_cmd2
, "");
485 conf_set_int(conf
, CONF_nopty
, TRUE
); /* command => no tty */
487 break; /* done with cmdline */
495 if (!conf_launchable(conf
) || !(got_host
|| loaded_session
)) {
500 * Muck about with the hostname in various ways.
503 char *hostbuf
= dupstr(conf_get_str(conf
, CONF_host
));
504 char *host
= hostbuf
;
508 * Trim leading whitespace.
510 host
+= strspn(host
, " \t");
513 * See if host is of the form user@host, and separate out
514 * the username if so.
516 if (host
[0] != '\0') {
517 char *atsign
= strrchr(host
, '@');
520 conf_set_str(conf
, CONF_username
, host
);
526 * Trim off a colon suffix if it's there.
528 host
[strcspn(host
, ":")] = '\0';
531 * Remove any remaining whitespace.
536 if (*q
!= ' ' && *q
!= '\t')
542 conf_set_str(conf
, CONF_host
, hostbuf
);
547 * Perform command-line overrides on session configuration.
549 cmdline_run_saved(conf
);
552 * Apply subsystem status.
555 conf_set_int(conf
, CONF_ssh_subsys
, TRUE
);
557 if (!*conf_get_str(conf
, CONF_remote_cmd
) &&
558 !*conf_get_str(conf
, CONF_remote_cmd2
) &&
559 !*conf_get_str(conf
, CONF_ssh_nc_host
))
560 flags
|= FLAG_INTERACTIVE
;
563 * Select protocol. This is farmed out into a table in a
564 * separate file to enable an ssh-free variant.
566 back
= backend_from_proto(conf_get_int(conf
, CONF_protocol
));
569 "Internal fault: Unsupported protocol found\n");
576 if (portnumber
!= -1)
577 conf_set_int(conf
, CONF_port
, portnumber
);
580 if (p_WSAEventSelect
== NULL
) {
581 fprintf(stderr
, "Plink requires WinSock 2\n");
585 logctx
= log_init(NULL
, conf
);
586 console_provide_logctx(logctx
);
589 * Start up the connection.
591 netevent
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
595 /* nodelay is only useful if stdin is a character device (console) */
596 int nodelay
= conf_get_int(conf
, CONF_tcp_nodelay
) &&
597 (GetFileType(GetStdHandle(STD_INPUT_HANDLE
)) == FILE_TYPE_CHAR
);
599 error
= back
->init(NULL
, &backhandle
, conf
,
600 conf_get_str(conf
, CONF_host
),
601 conf_get_int(conf
, CONF_port
),
603 conf_get_int(conf
, CONF_tcp_keepalives
));
605 fprintf(stderr
, "Unable to open connection:\n%s", error
);
608 back
->provide_logctx(backhandle
, logctx
);
613 inhandle
= GetStdHandle(STD_INPUT_HANDLE
);
614 outhandle
= GetStdHandle(STD_OUTPUT_HANDLE
);
615 errhandle
= GetStdHandle(STD_ERROR_HANDLE
);
618 * Turn off ECHO and LINE input modes. We don't care if this
619 * call fails, because we know we aren't necessarily running in
622 GetConsoleMode(inhandle
, &orig_console_mode
);
623 SetConsoleMode(inhandle
, ENABLE_PROCESSED_INPUT
);
626 * Pass the output handles to the handle-handling subsystem.
627 * (The input one we leave until we're through the
628 * authentication process.)
630 stdout_handle
= handle_output_new(outhandle
, stdouterr_sent
, NULL
, 0);
631 stderr_handle
= handle_output_new(errhandle
, stdouterr_sent
, NULL
, 0);
633 main_thread_id
= GetCurrentThreadId();
637 now
= GETTICKCOUNT();
645 if (!sending
&& back
->sendok(backhandle
)) {
646 stdin_handle
= handle_input_new(inhandle
, stdin_gotdata
, NULL
,
651 if (run_timers(now
, &next
)) {
653 now
= GETTICKCOUNT();
654 if (now
- then
> next
- then
)
662 handles
= handle_get_events(&nhandles
);
663 handles
= sresize(handles
, nhandles
+1, HANDLE
);
664 handles
[nhandles
] = netevent
;
665 n
= MsgWaitForMultipleObjects(nhandles
+1, handles
, FALSE
, ticks
,
667 if ((unsigned)(n
- WAIT_OBJECT_0
) < (unsigned)nhandles
) {
668 handle_got_event(handles
[n
- WAIT_OBJECT_0
]);
669 } else if (n
== WAIT_OBJECT_0
+ nhandles
) {
670 WSANETWORKEVENTS things
;
672 extern SOCKET
first_socket(int *), next_socket(int *);
673 extern int select_result(WPARAM
, LPARAM
);
677 * We must not call select_result() for any socket
678 * until we have finished enumerating within the tree.
679 * This is because select_result() may close the socket
680 * and modify the tree.
682 /* Count the active sockets. */
684 for (socket
= first_socket(&socketstate
);
685 socket
!= INVALID_SOCKET
;
686 socket
= next_socket(&socketstate
)) i
++;
688 /* Expand the buffer if necessary. */
691 sklist
= sresize(sklist
, sksize
, SOCKET
);
694 /* Retrieve the sockets into sklist. */
696 for (socket
= first_socket(&socketstate
);
697 socket
!= INVALID_SOCKET
;
698 socket
= next_socket(&socketstate
)) {
699 sklist
[skcount
++] = socket
;
702 /* Now we're done enumerating; go through the list. */
703 for (i
= 0; i
< skcount
; i
++) {
706 wp
= (WPARAM
) socket
;
707 if (!p_WSAEnumNetworkEvents(socket
, NULL
, &things
)) {
708 static const struct { int bit
, mask
; } eventtypes
[] = {
709 {FD_CONNECT_BIT
, FD_CONNECT
},
710 {FD_READ_BIT
, FD_READ
},
711 {FD_CLOSE_BIT
, FD_CLOSE
},
712 {FD_OOB_BIT
, FD_OOB
},
713 {FD_WRITE_BIT
, FD_WRITE
},
714 {FD_ACCEPT_BIT
, FD_ACCEPT
},
718 noise_ultralight(socket
);
719 noise_ultralight(things
.lNetworkEvents
);
721 for (e
= 0; e
< lenof(eventtypes
); e
++)
722 if (things
.lNetworkEvents
& eventtypes
[e
].mask
) {
724 int err
= things
.iErrorCode
[eventtypes
[e
].bit
];
725 lp
= WSAMAKESELECTREPLY(eventtypes
[e
].mask
, err
);
726 connopen
&= select_result(wp
, lp
);
730 } else if (n
== WAIT_OBJECT_0
+ nhandles
+ 1) {
732 while (PeekMessage(&msg
, INVALID_HANDLE_VALUE
,
733 WM_AGENT_CALLBACK
, WM_AGENT_CALLBACK
,
735 struct agent_callback
*c
= (struct agent_callback
*)msg
.lParam
;
736 c
->callback(c
->callback_ctx
, c
->data
, c
->len
);
741 if (n
== WAIT_TIMEOUT
) {
744 now
= GETTICKCOUNT();
750 handle_unthrottle(stdin_handle
, back
->sendbuffer(backhandle
));
752 if ((!connopen
|| !back
->connected(backhandle
)) &&
753 handle_backlog(stdout_handle
) + handle_backlog(stderr_handle
) == 0)
754 break; /* we closed the connection */
756 exitcode
= back
->exitcode(backhandle
);
758 fprintf(stderr
, "Remote process exit code unavailable\n");
759 exitcode
= 1; /* this is an error condition */
761 cleanup_exit(exitcode
);
762 return 0; /* placate compiler warning */