2 * PLink - a Windows command-line (stdin/stdout) variant of PuTTY.
\r
10 #define PUTTY_DO_GLOBALS /* actually _define_ globals */
\r
12 #include "storage.h"
\r
13 #include "tree234.h"
\r
15 #define WM_AGENT_CALLBACK (WM_APP + 4)
\r
17 struct agent_callback {
\r
18 void (*callback)(void *, void *, int);
\r
24 void fatalbox(char *p, ...)
\r
27 char *stuff, morestuff[100];
\r
30 stuff = dupvprintf(p, ap);
\r
32 sprintf(morestuff, "%.70s Fatal Error", appname);
\r
33 MessageBox(GetParentHwnd(), stuff, morestuff, MB_ICONERROR | MB_OK);
\r
41 void modalfatalbox(char *p, ...)
\r
44 char *stuff, morestuff[100];
\r
47 stuff = dupvprintf(p, ap);
\r
49 sprintf(morestuff, "%.70s Fatal Error", appname);
\r
50 MessageBox(GetParentHwnd(), stuff, morestuff,
\r
51 MB_SYSTEMMODAL | MB_ICONERROR | MB_OK);
\r
59 void connection_fatal(void *frontend, char *p, ...)
\r
62 char *stuff, morestuff[100];
\r
65 stuff = dupvprintf(p, ap);
\r
67 sprintf(morestuff, "%.70s Fatal Error", appname);
\r
68 MessageBox(GetParentHwnd(), stuff, morestuff,
\r
69 MB_SYSTEMMODAL | MB_ICONERROR | MB_OK);
\r
77 void cmdline_error(char *p, ...)
\r
80 char *stuff, morestuff[100];
\r
83 stuff = dupvprintf(p, ap);
\r
85 sprintf(morestuff, "%.70s Command Line Error", appname);
\r
86 MessageBox(GetParentHwnd(), stuff, morestuff, MB_ICONERROR | MB_OK);
\r
91 HANDLE inhandle, outhandle, errhandle;
\r
92 struct handle *stdin_handle, *stdout_handle, *stderr_handle;
\r
93 DWORD orig_console_mode;
\r
98 static Backend *back;
\r
99 static void *backhandle;
\r
102 int term_ldisc(Terminal *term, int mode)
\r
106 void ldisc_update(void *frontend, int echo, int edit)
\r
108 /* Update stdin read mode to reflect changes in line discipline. */
\r
111 mode = ENABLE_PROCESSED_INPUT;
\r
113 mode = mode | ENABLE_ECHO_INPUT;
\r
115 mode = mode & ~ENABLE_ECHO_INPUT;
\r
117 mode = mode | ENABLE_LINE_INPUT;
\r
119 mode = mode & ~ENABLE_LINE_INPUT;
\r
120 SetConsoleMode(inhandle, mode);
\r
123 char *get_ttymode(void *frontend, const char *mode) { return NULL; }
\r
125 int from_backend(void *frontend_handle, int is_stderr,
\r
126 const char *data, int len)
\r
129 handle_write(stderr_handle, data, len);
\r
131 handle_write(stdout_handle, data, len);
\r
134 return handle_backlog(stdout_handle) + handle_backlog(stderr_handle);
\r
137 int from_backend_untrusted(void *frontend_handle, const char *data, int len)
\r
140 * No "untrusted" output should get here (the way the code is
\r
141 * currently, it's all diverted by FLAG_STDERR).
\r
143 assert(!"Unexpected call to from_backend_untrusted()");
\r
144 return 0; /* not reached */
\r
147 int get_userpass_input(prompts_t *p, unsigned char *in, int inlen)
\r
150 ret = cmdline_get_passwd_input(p, in, inlen);
\r
152 ret = console_get_userpass_input(p, in, inlen);
\r
156 static DWORD main_thread_id;
\r
158 void agent_schedule_callback(void (*callback)(void *, void *, int),
\r
159 void *callback_ctx, void *data, int len)
\r
161 struct agent_callback *c = snew(struct agent_callback);
\r
162 c->callback = callback;
\r
163 c->callback_ctx = callback_ctx;
\r
166 PostThreadMessage(main_thread_id, WM_AGENT_CALLBACK, 0, (LPARAM)c);
\r
170 * Short description of parameters.
\r
172 static void usage(void)
\r
177 j += sprintf(buf+j, "PuTTY Link: command-line connection utility\n");
\r
178 j += sprintf(buf+j, "%s\n", ver);
\r
179 j += sprintf(buf+j, "Usage: plink [options] [user@]host [command]\n");
\r
180 j += sprintf(buf+j, " (\"host\" can also be a PuTTY saved session name)\n");
\r
181 j += sprintf(buf+j, "Options:\n");
\r
182 j += sprintf(buf+j, " -V print version information and exit\n");
\r
183 j += sprintf(buf+j, " -pgpfp print PGP key fingerprints and exit\n");
\r
184 j += sprintf(buf+j, " -v show verbose messages\n");
\r
185 j += sprintf(buf+j, " -load sessname Load settings from saved session\n");
\r
186 j += sprintf(buf+j, " -ssh -telnet -rlogin -raw\n");
\r
187 j += sprintf(buf+j, " force use of a particular protocol\n");
\r
188 j += sprintf(buf+j, " -P port connect to specified port\n");
\r
189 j += sprintf(buf+j, " -l user connect with specified username\n");
\r
190 j += sprintf(buf+j, " -batch disable all interactive prompts\n");
\r
191 j += sprintf(buf+j, "The following options only apply to SSH connections:\n");
\r
192 j += sprintf(buf+j, " -pw passw login with specified password\n");
\r
193 j += sprintf(buf+j, " -D [listen-IP:]listen-port\n");
\r
194 j += sprintf(buf+j, " Dynamic SOCKS-based port forwarding\n");
\r
195 j += sprintf(buf+j, " -L [listen-IP:]listen-port:host:port\n");
\r
196 j += sprintf(buf+j, " Forward local port to remote address\n");
\r
197 j += sprintf(buf+j, " -R [listen-IP:]listen-port:host:port\n");
\r
198 j += sprintf(buf+j, " Forward remote port to local address\n");
\r
199 j += sprintf(buf+j, " -X -x enable / disable X11 forwarding\n");
\r
200 j += sprintf(buf+j, " -A -a enable / disable agent forwarding\n");
\r
201 j += sprintf(buf+j, " -t -T enable / disable pty allocation\n");
\r
202 j += sprintf(buf+j, " -1 -2 force use of particular protocol version\n");
\r
203 j += sprintf(buf+j, " -4 -6 force use of IPv4 or IPv6\n");
\r
204 j += sprintf(buf+j, " -C enable compression\n");
\r
205 j += sprintf(buf+j, " -i key private key file for authentication\n");
\r
206 j += sprintf(buf+j, " -noagent disable use of Pageant\n");
\r
207 j += sprintf(buf+j, " -agent enable use of Pageant\n");
\r
208 j += sprintf(buf+j, " -m file read remote command(s) from file\n");
\r
209 j += sprintf(buf+j, " -s remote command is an SSH subsystem (SSH-2 only)\n");
\r
210 j += sprintf(buf+j, " -N don't start a shell/command (SSH-2 only)\n");
\r
211 j += sprintf(buf+j, " -nc host:port\n");
\r
212 j += sprintf(buf+j, " open tunnel in place of session (SSH-2 only)\n");
\r
213 MessageBox(NULL, buf, "TortoisePlink", MB_ICONINFORMATION);
\r
217 static void version(void)
\r
219 printf("TortoisePlink: %s\n", ver);
\r
223 char *do_select(SOCKET skt, int startup)
\r
227 events = (FD_CONNECT | FD_READ | FD_WRITE |
\r
228 FD_OOB | FD_CLOSE | FD_ACCEPT);
\r
232 if (p_WSAEventSelect(skt, netevent, events) == SOCKET_ERROR) {
\r
233 switch (p_WSAGetLastError()) {
\r
235 return "Network is down";
\r
237 return "WSAEventSelect(): unknown error";
\r
243 int stdin_gotdata(struct handle *h, void *data, int len)
\r
247 * Special case: report read error.
\r
250 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, -len, 0,
\r
251 buf, lenof(buf), NULL);
\r
252 buf[lenof(buf)-1] = '\0';
\r
253 if (buf[strlen(buf)-1] == '\n')
\r
254 buf[strlen(buf)-1] = '\0';
\r
255 fprintf(stderr, "Unable to read from standard input: %s\n", buf);
\r
258 noise_ultralight(len);
\r
259 if (connopen && back->connected(backhandle)) {
\r
261 return back->send(backhandle, data, len);
\r
263 back->special(backhandle, TS_EOF);
\r
270 void stdouterr_sent(struct handle *h, int new_backlog)
\r
272 if (new_backlog < 0) {
\r
274 * Special case: report write error.
\r
277 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, -new_backlog, 0,
\r
278 buf, lenof(buf), NULL);
\r
279 buf[lenof(buf)-1] = '\0';
\r
280 if (buf[strlen(buf)-1] == '\n')
\r
281 buf[strlen(buf)-1] = '\0';
\r
282 fprintf(stderr, "Unable to write to standard %s: %s\n",
\r
283 (h == stdout_handle ? "output" : "error"), buf);
\r
286 if (connopen && back->connected(backhandle)) {
\r
287 back->unthrottle(backhandle, (handle_backlog(stdout_handle) +
\r
288 handle_backlog(stderr_handle)));
\r
292 int main(int argc, char **argv)
\r
295 int portnumber = -1;
\r
297 int skcount, sksize;
\r
300 int got_host = FALSE;
\r
301 int use_subsystem = 0;
\r
305 skcount = sksize = 0;
\r
307 * Initialise port and protocol to sensible defaults. (These
\r
308 * will be overridden by more or less anything.)
\r
310 default_protocol = PROT_SSH;
\r
313 flags = FLAG_STDERR;
\r
315 * Process the command line.
\r
317 do_defaults(NULL, &cfg);
\r
318 loaded_session = FALSE;
\r
319 default_protocol = cfg.protocol;
\r
320 default_port = cfg.port;
\r
324 * Override the default protocol if PLINK_PROTOCOL is set.
\r
326 char *p = getenv("PLINK_PROTOCOL");
\r
328 const Backend *b = backend_from_name(p);
\r
330 default_protocol = cfg.protocol = b->protocol;
\r
331 default_port = cfg.port = b->default_port;
\r
338 int ret = cmdline_process_param(p, (argc > 1 ? argv[1] : NULL),
\r
342 "plink: option \"%s\" requires an argument\n", p);
\r
344 } else if (ret == 2) {
\r
346 } else if (ret == 1) {
\r
348 } else if (!strcmp(p, "-batch")) {
\r
349 console_batch_mode = 1;
\r
350 } else if (!strcmp(p, "-s")) {
\r
351 /* Save status to write to cfg later. */
\r
353 } else if (!strcmp(p, "-V")) {
\r
355 } else if (!strcmp(p, "-pgpfp")) {
\r
356 pgp_fingerprints();
\r
359 fprintf(stderr, "plink: unknown option \"%s\"\n", p);
\r
363 if (!cfg_launchable(&cfg) || !(got_host || loaded_session)) {
\r
366 * If the hostname starts with "telnet:", set the
\r
367 * protocol to Telnet and process the string as a
\r
370 if (!strncmp(q, "telnet:", 7)) {
\r
374 if (q[0] == '/' && q[1] == '/')
\r
376 cfg.protocol = PROT_TELNET;
\r
378 while (*p && *p != ':' && *p != '/')
\r
384 cfg.port = atoi(p);
\r
387 strncpy(cfg.host, q, sizeof(cfg.host) - 1);
\r
388 cfg.host[sizeof(cfg.host) - 1] = '\0';
\r
391 char *r, *user, *host;
\r
393 * Before we process the [user@]host string, we
\r
394 * first check for the presence of a protocol
\r
395 * prefix (a protocol name followed by ",").
\r
397 r = strchr(p, ',');
\r
401 b = backend_from_name(p);
\r
403 default_protocol = cfg.protocol = b->protocol;
\r
404 portnumber = b->default_port;
\r
410 * A nonzero length string followed by an @ is treated
\r
411 * as a username. (We discount an _initial_ @.) The
\r
412 * rest of the string (or the whole string if no @)
\r
413 * is treated as a session name and/or hostname.
\r
415 r = strrchr(p, '@');
\r
417 p++, r = NULL; /* discount initial @ */
\r
420 user = p, host = r;
\r
422 user = NULL, host = p;
\r
426 * Now attempt to load a saved session with the
\r
427 * same name as the hostname.
\r
431 do_defaults(host, &cfg2);
\r
432 if (loaded_session || !cfg_launchable(&cfg2)) {
\r
433 /* No settings for this host; use defaults */
\r
434 /* (or session was already loaded with -load) */
\r
435 strncpy(cfg.host, host, sizeof(cfg.host) - 1);
\r
436 cfg.host[sizeof(cfg.host) - 1] = '\0';
\r
437 cfg.port = default_port;
\r
441 loaded_session = TRUE;
\r
446 /* Patch in specified username. */
\r
447 strncpy(cfg.username, user,
\r
448 sizeof(cfg.username) - 1);
\r
449 cfg.username[sizeof(cfg.username) - 1] = '\0';
\r
455 int cmdlen, cmdsize;
\r
456 cmdlen = cmdsize = 0;
\r
461 if (cmdlen >= cmdsize) {
\r
462 cmdsize = cmdlen + 512;
\r
463 command = sresize(command, cmdsize, char);
\r
465 command[cmdlen++]=*p++;
\r
467 if (cmdlen >= cmdsize) {
\r
468 cmdsize = cmdlen + 512;
\r
469 command = sresize(command, cmdsize, char);
\r
471 command[cmdlen++]=' '; /* always add trailing space */
\r
472 if (--argc) p = *++argv;
\r
474 if (cmdlen) command[--cmdlen]='\0';
\r
475 /* change trailing blank to NUL */
\r
476 cfg.remote_cmd_ptr = command;
\r
477 cfg.remote_cmd_ptr2 = NULL;
\r
478 cfg.nopty = TRUE; /* command => no terminal */
\r
480 break; /* done with cmdline */
\r
488 if (!cfg_launchable(&cfg) || !(got_host || loaded_session)) {
\r
493 * Trim leading whitespace off the hostname if it's there.
\r
496 int space = strspn(cfg.host, " \t");
\r
497 memmove(cfg.host, cfg.host+space, 1+strlen(cfg.host)-space);
\r
500 /* See if host is of the form user@host */
\r
501 if (cfg_launchable(&cfg)) {
\r
502 char *atsign = strrchr(cfg.host, '@');
\r
503 /* Make sure we're not overflowing the user field */
\r
505 if (atsign - cfg.host < sizeof cfg.username) {
\r
506 strncpy(cfg.username, cfg.host, atsign - cfg.host);
\r
507 cfg.username[atsign - cfg.host] = '\0';
\r
509 memmove(cfg.host, atsign + 1, 1 + strlen(atsign + 1));
\r
514 * Perform command-line overrides on session configuration.
\r
516 cmdline_run_saved(&cfg);
\r
519 * Apply subsystem status.
\r
522 cfg.ssh_subsys = TRUE;
\r
525 * Trim a colon suffix off the hostname if it's there.
\r
527 cfg.host[strcspn(cfg.host, ":")] = '\0';
\r
530 * Remove any remaining whitespace from the hostname.
\r
533 int p1 = 0, p2 = 0;
\r
534 while (cfg.host[p2] != '\0') {
\r
535 if (cfg.host[p2] != ' ' && cfg.host[p2] != '\t') {
\r
536 cfg.host[p1] = cfg.host[p2];
\r
541 cfg.host[p1] = '\0';
\r
544 if (!cfg.remote_cmd_ptr && !*cfg.remote_cmd && !*cfg.ssh_nc_host)
\r
545 flags |= FLAG_INTERACTIVE;
\r
548 * Select protocol. This is farmed out into a table in a
\r
549 * separate file to enable an ssh-free variant.
\r
551 back = backend_from_proto(cfg.protocol);
\r
552 if (back == NULL) {
\r
554 "Internal fault: Unsupported protocol found\n");
\r
561 if (portnumber != -1)
\r
562 cfg.port = portnumber;
\r
565 if (p_WSAEventSelect == NULL) {
\r
566 fprintf(stderr, "Plink requires WinSock 2\n");
\r
570 logctx = log_init(NULL, &cfg);
\r
571 console_provide_logctx(logctx);
\r
574 * Start up the connection.
\r
576 netevent = CreateEvent(NULL, FALSE, FALSE, NULL);
\r
580 /* nodelay is only useful if stdin is a character device (console) */
\r
581 int nodelay = cfg.tcp_nodelay &&
\r
582 (GetFileType(GetStdHandle(STD_INPUT_HANDLE)) == FILE_TYPE_CHAR);
\r
584 error = back->init(NULL, &backhandle, &cfg, cfg.host, cfg.port,
\r
585 &realhost, nodelay, cfg.tcp_keepalives);
\r
587 fprintf(stderr, "Unable to open connection:\n%s", error);
\r
590 back->provide_logctx(backhandle, logctx);
\r
595 inhandle = GetStdHandle(STD_INPUT_HANDLE);
\r
596 outhandle = GetStdHandle(STD_OUTPUT_HANDLE);
\r
597 errhandle = GetStdHandle(STD_ERROR_HANDLE);
\r
600 * Turn off ECHO and LINE input modes. We don't care if this
\r
601 * call fails, because we know we aren't necessarily running in
\r
604 GetConsoleMode(inhandle, &orig_console_mode);
\r
605 SetConsoleMode(inhandle, ENABLE_PROCESSED_INPUT);
\r
608 * Pass the output handles to the handle-handling subsystem.
\r
609 * (The input one we leave until we're through the
\r
610 * authentication process.)
\r
612 stdout_handle = handle_output_new(outhandle, stdouterr_sent, NULL, 0);
\r
613 stderr_handle = handle_output_new(errhandle, stdouterr_sent, NULL, 0);
\r
615 main_thread_id = GetCurrentThreadId();
\r
619 now = GETTICKCOUNT();
\r
627 if (!sending && back->sendok(backhandle)) {
\r
628 stdin_handle = handle_input_new(inhandle, stdin_gotdata, NULL,
\r
633 if (run_timers(now, &next)) {
\r
634 ticks = next - GETTICKCOUNT();
\r
635 if (ticks < 0) ticks = 0; /* just in case */
\r
640 handles = handle_get_events(&nhandles);
\r
641 handles = sresize(handles, nhandles+1, HANDLE);
\r
642 handles[nhandles] = netevent;
\r
643 n = MsgWaitForMultipleObjects(nhandles+1, handles, FALSE, ticks,
\r
645 if ((unsigned)(n - WAIT_OBJECT_0) < (unsigned)nhandles) {
\r
646 handle_got_event(handles[n - WAIT_OBJECT_0]);
\r
647 } else if (n == WAIT_OBJECT_0 + nhandles) {
\r
648 WSANETWORKEVENTS things;
\r
650 extern SOCKET first_socket(int *), next_socket(int *);
\r
651 extern int select_result(WPARAM, LPARAM);
\r
652 int i, socketstate;
\r
655 * We must not call select_result() for any socket
\r
656 * until we have finished enumerating within the tree.
\r
657 * This is because select_result() may close the socket
\r
658 * and modify the tree.
\r
660 /* Count the active sockets. */
\r
662 for (socket = first_socket(&socketstate);
\r
663 socket != INVALID_SOCKET;
\r
664 socket = next_socket(&socketstate)) i++;
\r
666 /* Expand the buffer if necessary. */
\r
669 sklist = sresize(sklist, sksize, SOCKET);
\r
672 /* Retrieve the sockets into sklist. */
\r
674 for (socket = first_socket(&socketstate);
\r
675 socket != INVALID_SOCKET;
\r
676 socket = next_socket(&socketstate)) {
\r
677 sklist[skcount++] = socket;
\r
680 /* Now we're done enumerating; go through the list. */
\r
681 for (i = 0; i < skcount; i++) {
\r
683 socket = sklist[i];
\r
684 wp = (WPARAM) socket;
\r
685 if (!p_WSAEnumNetworkEvents(socket, NULL, &things)) {
\r
686 static const struct { int bit, mask; } eventtypes[] = {
\r
687 {FD_CONNECT_BIT, FD_CONNECT},
\r
688 {FD_READ_BIT, FD_READ},
\r
689 {FD_CLOSE_BIT, FD_CLOSE},
\r
690 {FD_OOB_BIT, FD_OOB},
\r
691 {FD_WRITE_BIT, FD_WRITE},
\r
692 {FD_ACCEPT_BIT, FD_ACCEPT},
\r
696 noise_ultralight(socket);
\r
697 noise_ultralight(things.lNetworkEvents);
\r
699 for (e = 0; e < lenof(eventtypes); e++)
\r
700 if (things.lNetworkEvents & eventtypes[e].mask) {
\r
702 int err = things.iErrorCode[eventtypes[e].bit];
\r
703 lp = WSAMAKESELECTREPLY(eventtypes[e].mask, err);
\r
704 connopen &= select_result(wp, lp);
\r
708 } else if (n == WAIT_OBJECT_0 + nhandles + 1) {
\r
710 while (PeekMessage(&msg, INVALID_HANDLE_VALUE,
\r
711 WM_AGENT_CALLBACK, WM_AGENT_CALLBACK,
\r
713 struct agent_callback *c = (struct agent_callback *)msg.lParam;
\r
714 c->callback(c->callback_ctx, c->data, c->len);
\r
719 if (n == WAIT_TIMEOUT) {
\r
722 now = GETTICKCOUNT();
\r
728 handle_unthrottle(stdin_handle, back->sendbuffer(backhandle));
\r
730 if ((!connopen || !back->connected(backhandle)) &&
\r
731 handle_backlog(stdout_handle) + handle_backlog(stderr_handle) == 0)
\r
732 break; /* we closed the connection */
\r
734 exitcode = back->exitcode(backhandle);
\r
735 if (exitcode < 0) {
\r
736 fprintf(stderr, "Remote process exit code unavailable\n");
\r
737 exitcode = 1; /* this is an error condition */
\r
739 cleanup_exit(exitcode);
\r
740 return 0; /* placate compiler warning */
\r
743 int WinMain(hInstance, hPrevInstance, lpCmdLine, nCmdShow)
\r
745 main(__argc,__argv);
\r