dfbb80d84de3eb352de6c9a10b932ab16b0db66e
[u/mdw/putty] / windows / winplink.c
1 /*
2 * PLink - a Windows command-line (stdin/stdout) variant of PuTTY.
3 */
4
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <assert.h>
8 #include <stdarg.h>
9
10 #define PUTTY_DO_GLOBALS /* actually _define_ globals */
11 #include "putty.h"
12 #include "storage.h"
13 #include "tree234.h"
14
15 #define WM_AGENT_CALLBACK (WM_APP + 4)
16
17 struct agent_callback {
18 void (*callback)(void *, void *, int);
19 void *callback_ctx;
20 void *data;
21 int len;
22 };
23
24 void fatalbox(char *p, ...)
25 {
26 va_list ap;
27 fprintf(stderr, "FATAL ERROR: ");
28 va_start(ap, p);
29 vfprintf(stderr, p, ap);
30 va_end(ap);
31 fputc('\n', stderr);
32 if (logctx) {
33 log_free(logctx);
34 logctx = NULL;
35 }
36 cleanup_exit(1);
37 }
38 void modalfatalbox(char *p, ...)
39 {
40 va_list ap;
41 fprintf(stderr, "FATAL ERROR: ");
42 va_start(ap, p);
43 vfprintf(stderr, p, ap);
44 va_end(ap);
45 fputc('\n', stderr);
46 if (logctx) {
47 log_free(logctx);
48 logctx = NULL;
49 }
50 cleanup_exit(1);
51 }
52 void connection_fatal(void *frontend, char *p, ...)
53 {
54 va_list ap;
55 fprintf(stderr, "FATAL ERROR: ");
56 va_start(ap, p);
57 vfprintf(stderr, p, ap);
58 va_end(ap);
59 fputc('\n', stderr);
60 if (logctx) {
61 log_free(logctx);
62 logctx = NULL;
63 }
64 cleanup_exit(1);
65 }
66 void cmdline_error(char *p, ...)
67 {
68 va_list ap;
69 fprintf(stderr, "plink: ");
70 va_start(ap, p);
71 vfprintf(stderr, p, ap);
72 va_end(ap);
73 fputc('\n', stderr);
74 exit(1);
75 }
76
77 HANDLE inhandle, outhandle, errhandle;
78 struct handle *stdin_handle, *stdout_handle, *stderr_handle;
79 DWORD orig_console_mode;
80 int connopen;
81
82 WSAEVENT netevent;
83
84 static Backend *back;
85 static void *backhandle;
86 static Conf *conf;
87
88 int term_ldisc(Terminal *term, int mode)
89 {
90 return FALSE;
91 }
92 void ldisc_update(void *frontend, int echo, int edit)
93 {
94 /* Update stdin read mode to reflect changes in line discipline. */
95 DWORD mode;
96
97 mode = ENABLE_PROCESSED_INPUT;
98 if (echo)
99 mode = mode | ENABLE_ECHO_INPUT;
100 else
101 mode = mode & ~ENABLE_ECHO_INPUT;
102 if (edit)
103 mode = mode | ENABLE_LINE_INPUT;
104 else
105 mode = mode & ~ENABLE_LINE_INPUT;
106 SetConsoleMode(inhandle, mode);
107 }
108
109 char *get_ttymode(void *frontend, const char *mode) { return NULL; }
110
111 int from_backend(void *frontend_handle, int is_stderr,
112 const char *data, int len)
113 {
114 if (is_stderr) {
115 handle_write(stderr_handle, data, len);
116 } else {
117 handle_write(stdout_handle, data, len);
118 }
119
120 return handle_backlog(stdout_handle) + handle_backlog(stderr_handle);
121 }
122
123 int from_backend_untrusted(void *frontend_handle, const char *data, int len)
124 {
125 /*
126 * No "untrusted" output should get here (the way the code is
127 * currently, it's all diverted by FLAG_STDERR).
128 */
129 assert(!"Unexpected call to from_backend_untrusted()");
130 return 0; /* not reached */
131 }
132
133 int from_backend_eof(void *frontend_handle)
134 {
135 handle_write_eof(stdout_handle);
136 return FALSE; /* do not respond to incoming EOF with outgoing */
137 }
138
139 int get_userpass_input(prompts_t *p, unsigned char *in, int inlen)
140 {
141 int ret;
142 ret = cmdline_get_passwd_input(p, in, inlen);
143 if (ret == -1)
144 ret = console_get_userpass_input(p, in, inlen);
145 return ret;
146 }
147
148 static DWORD main_thread_id;
149
150 void agent_schedule_callback(void (*callback)(void *, void *, int),
151 void *callback_ctx, void *data, int len)
152 {
153 struct agent_callback *c = snew(struct agent_callback);
154 c->callback = callback;
155 c->callback_ctx = callback_ctx;
156 c->data = data;
157 c->len = len;
158 PostThreadMessage(main_thread_id, WM_AGENT_CALLBACK, 0, (LPARAM)c);
159 }
160
161 /*
162 * Short description of parameters.
163 */
164 static void usage(void)
165 {
166 printf("PuTTY Link: command-line connection utility\n");
167 printf("%s\n", ver);
168 printf("Usage: plink [options] [user@]host [command]\n");
169 printf(" (\"host\" can also be a PuTTY saved session name)\n");
170 printf("Options:\n");
171 printf(" -V print version information and exit\n");
172 printf(" -pgpfp print PGP key fingerprints and exit\n");
173 printf(" -v show verbose messages\n");
174 printf(" -load sessname Load settings from saved session\n");
175 printf(" -ssh -telnet -rlogin -raw -serial\n");
176 printf(" force use of a particular protocol\n");
177 printf(" -P port connect to specified port\n");
178 printf(" -l user connect with specified username\n");
179 printf(" -batch disable all interactive prompts\n");
180 printf("The following options only apply to SSH connections:\n");
181 printf(" -pw passw login with specified password\n");
182 printf(" -D [listen-IP:]listen-port\n");
183 printf(" Dynamic SOCKS-based port forwarding\n");
184 printf(" -L [listen-IP:]listen-port:host:port\n");
185 printf(" Forward local port to remote address\n");
186 printf(" -R [listen-IP:]listen-port:host:port\n");
187 printf(" Forward remote port to local address\n");
188 printf(" -X -x enable / disable X11 forwarding\n");
189 printf(" -A -a enable / disable agent forwarding\n");
190 printf(" -t -T enable / disable pty allocation\n");
191 printf(" -1 -2 force use of particular protocol version\n");
192 printf(" -4 -6 force use of IPv4 or IPv6\n");
193 printf(" -C enable compression\n");
194 printf(" -i key private key file for authentication\n");
195 printf(" -noagent disable use of Pageant\n");
196 printf(" -agent enable use of Pageant\n");
197 printf(" -m file read remote command(s) from file\n");
198 printf(" -s remote command is an SSH subsystem (SSH-2 only)\n");
199 printf(" -N don't start a shell/command (SSH-2 only)\n");
200 printf(" -nc host:port\n");
201 printf(" open tunnel in place of session (SSH-2 only)\n");
202 printf(" -sercfg configuration-string (e.g. 19200,8,n,1,X)\n");
203 printf(" Specify the serial configuration (serial only)\n");
204 exit(1);
205 }
206
207 static void version(void)
208 {
209 printf("plink: %s\n", ver);
210 exit(1);
211 }
212
213 char *do_select(SOCKET skt, int startup)
214 {
215 int events;
216 if (startup) {
217 events = (FD_CONNECT | FD_READ | FD_WRITE |
218 FD_OOB | FD_CLOSE | FD_ACCEPT);
219 } else {
220 events = 0;
221 }
222 if (p_WSAEventSelect(skt, netevent, events) == SOCKET_ERROR) {
223 switch (p_WSAGetLastError()) {
224 case WSAENETDOWN:
225 return "Network is down";
226 default:
227 return "WSAEventSelect(): unknown error";
228 }
229 }
230 return NULL;
231 }
232
233 int stdin_gotdata(struct handle *h, void *data, int len)
234 {
235 if (len < 0) {
236 /*
237 * Special case: report read error.
238 */
239 char buf[4096];
240 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, -len, 0,
241 buf, lenof(buf), NULL);
242 buf[lenof(buf)-1] = '\0';
243 if (buf[strlen(buf)-1] == '\n')
244 buf[strlen(buf)-1] = '\0';
245 fprintf(stderr, "Unable to read from standard input: %s\n", buf);
246 cleanup_exit(0);
247 }
248 noise_ultralight(len);
249 if (connopen && back->connected(backhandle)) {
250 if (len > 0) {
251 return back->send(backhandle, data, len);
252 } else {
253 back->special(backhandle, TS_EOF);
254 return 0;
255 }
256 } else
257 return 0;
258 }
259
260 void stdouterr_sent(struct handle *h, int new_backlog)
261 {
262 if (new_backlog < 0) {
263 /*
264 * Special case: report write error.
265 */
266 char buf[4096];
267 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, -new_backlog, 0,
268 buf, lenof(buf), NULL);
269 buf[lenof(buf)-1] = '\0';
270 if (buf[strlen(buf)-1] == '\n')
271 buf[strlen(buf)-1] = '\0';
272 fprintf(stderr, "Unable to write to standard %s: %s\n",
273 (h == stdout_handle ? "output" : "error"), buf);
274 cleanup_exit(0);
275 }
276 if (connopen && back->connected(backhandle)) {
277 back->unthrottle(backhandle, (handle_backlog(stdout_handle) +
278 handle_backlog(stderr_handle)));
279 }
280 }
281
282 int main(int argc, char **argv)
283 {
284 int sending;
285 int portnumber = -1;
286 SOCKET *sklist;
287 int skcount, sksize;
288 int exitcode;
289 int errors;
290 int got_host = FALSE;
291 int use_subsystem = 0;
292 unsigned long now, next, then;
293
294 sklist = NULL;
295 skcount = sksize = 0;
296 /*
297 * Initialise port and protocol to sensible defaults. (These
298 * will be overridden by more or less anything.)
299 */
300 default_protocol = PROT_SSH;
301 default_port = 22;
302
303 flags = FLAG_STDERR;
304 /*
305 * Process the command line.
306 */
307 conf = conf_new();
308 do_defaults(NULL, conf);
309 loaded_session = FALSE;
310 default_protocol = conf_get_int(conf, CONF_protocol);
311 default_port = conf_get_int(conf, CONF_port);
312 errors = 0;
313 {
314 /*
315 * Override the default protocol if PLINK_PROTOCOL is set.
316 */
317 char *p = getenv("PLINK_PROTOCOL");
318 if (p) {
319 const Backend *b = backend_from_name(p);
320 if (b) {
321 default_protocol = b->protocol;
322 default_port = b->default_port;
323 conf_set_int(conf, CONF_protocol, default_protocol);
324 conf_set_int(conf, CONF_port, default_port);
325 }
326 }
327 }
328 while (--argc) {
329 char *p = *++argv;
330 if (*p == '-') {
331 int ret = cmdline_process_param(p, (argc > 1 ? argv[1] : NULL),
332 1, conf);
333 if (ret == -2) {
334 fprintf(stderr,
335 "plink: option \"%s\" requires an argument\n", p);
336 errors = 1;
337 } else if (ret == 2) {
338 --argc, ++argv;
339 } else if (ret == 1) {
340 continue;
341 } else if (!strcmp(p, "-batch")) {
342 console_batch_mode = 1;
343 } else if (!strcmp(p, "-s")) {
344 /* Save status to write to conf later. */
345 use_subsystem = 1;
346 } else if (!strcmp(p, "-V") || !strcmp(p, "--version")) {
347 version();
348 } else if (!strcmp(p, "--help")) {
349 usage();
350 } else if (!strcmp(p, "-pgpfp")) {
351 pgp_fingerprints();
352 exit(1);
353 } else {
354 fprintf(stderr, "plink: unknown option \"%s\"\n", p);
355 errors = 1;
356 }
357 } else if (*p) {
358 if (!conf_launchable(conf) || !(got_host || loaded_session)) {
359 char *q = p;
360 /*
361 * If the hostname starts with "telnet:", set the
362 * protocol to Telnet and process the string as a
363 * Telnet URL.
364 */
365 if (!strncmp(q, "telnet:", 7)) {
366 char c;
367
368 q += 7;
369 if (q[0] == '/' && q[1] == '/')
370 q += 2;
371 conf_set_int(conf, CONF_protocol, PROT_TELNET);
372 p = q;
373 while (*p && *p != ':' && *p != '/')
374 p++;
375 c = *p;
376 if (*p)
377 *p++ = '\0';
378 if (c == ':')
379 conf_set_int(conf, CONF_port, atoi(p));
380 else
381 conf_set_int(conf, CONF_port, -1);
382 conf_set_str(conf, CONF_host, q);
383 got_host = TRUE;
384 } else {
385 char *r, *user, *host;
386 /*
387 * Before we process the [user@]host string, we
388 * first check for the presence of a protocol
389 * prefix (a protocol name followed by ",").
390 */
391 r = strchr(p, ',');
392 if (r) {
393 const Backend *b;
394 *r = '\0';
395 b = backend_from_name(p);
396 if (b) {
397 default_protocol = b->protocol;
398 conf_set_int(conf, CONF_protocol,
399 default_protocol);
400 portnumber = b->default_port;
401 }
402 p = r + 1;
403 }
404
405 /*
406 * A nonzero length string followed by an @ is treated
407 * as a username. (We discount an _initial_ @.) The
408 * rest of the string (or the whole string if no @)
409 * is treated as a session name and/or hostname.
410 */
411 r = strrchr(p, '@');
412 if (r == p)
413 p++, r = NULL; /* discount initial @ */
414 if (r) {
415 *r++ = '\0';
416 user = p, host = r;
417 } else {
418 user = NULL, host = p;
419 }
420
421 /*
422 * Now attempt to load a saved session with the
423 * same name as the hostname.
424 */
425 {
426 Conf *conf2 = conf_new();
427 do_defaults(host, conf2);
428 if (loaded_session || !conf_launchable(conf2)) {
429 /* No settings for this host; use defaults */
430 /* (or session was already loaded with -load) */
431 conf_set_str(conf, CONF_host, host);
432 conf_set_int(conf, CONF_port, default_port);
433 got_host = TRUE;
434 } else {
435 conf_copy_into(conf, conf2);
436 loaded_session = TRUE;
437 }
438 conf_free(conf2);
439 }
440
441 if (user) {
442 /* Patch in specified username. */
443 conf_set_str(conf, CONF_username, user);
444 }
445
446 }
447 } else {
448 char *command;
449 int cmdlen, cmdsize;
450 cmdlen = cmdsize = 0;
451 command = NULL;
452
453 while (argc) {
454 while (*p) {
455 if (cmdlen >= cmdsize) {
456 cmdsize = cmdlen + 512;
457 command = sresize(command, cmdsize, char);
458 }
459 command[cmdlen++]=*p++;
460 }
461 if (cmdlen >= cmdsize) {
462 cmdsize = cmdlen + 512;
463 command = sresize(command, cmdsize, char);
464 }
465 command[cmdlen++]=' '; /* always add trailing space */
466 if (--argc) p = *++argv;
467 }
468 if (cmdlen) command[--cmdlen]='\0';
469 /* change trailing blank to NUL */
470 conf_set_str(conf, CONF_remote_cmd, command);
471 conf_set_str(conf, CONF_remote_cmd2, "");
472 conf_set_int(conf, CONF_nopty, TRUE); /* command => no tty */
473
474 break; /* done with cmdline */
475 }
476 }
477 }
478
479 if (errors)
480 return 1;
481
482 if (!conf_launchable(conf) || !(got_host || loaded_session)) {
483 usage();
484 }
485
486 /*
487 * Muck about with the hostname in various ways.
488 */
489 {
490 char *hostbuf = dupstr(conf_get_str(conf, CONF_host));
491 char *host = hostbuf;
492 char *p, *q;
493
494 /*
495 * Trim leading whitespace.
496 */
497 host += strspn(host, " \t");
498
499 /*
500 * See if host is of the form user@host, and separate out
501 * the username if so.
502 */
503 if (host[0] != '\0') {
504 char *atsign = strrchr(host, '@');
505 if (atsign) {
506 *atsign = '\0';
507 conf_set_str(conf, CONF_username, host);
508 host = atsign + 1;
509 }
510 }
511
512 /*
513 * Trim off a colon suffix if it's there.
514 */
515 host[strcspn(host, ":")] = '\0';
516
517 /*
518 * Remove any remaining whitespace.
519 */
520 p = hostbuf;
521 q = host;
522 while (*q) {
523 if (*q != ' ' && *q != '\t')
524 *p++ = *q;
525 q++;
526 }
527 *p = '\0';
528
529 conf_set_str(conf, CONF_host, hostbuf);
530 sfree(hostbuf);
531 }
532
533 /*
534 * Perform command-line overrides on session configuration.
535 */
536 cmdline_run_saved(conf);
537
538 /*
539 * Apply subsystem status.
540 */
541 if (use_subsystem)
542 conf_set_int(conf, CONF_ssh_subsys, TRUE);
543
544 if (!*conf_get_str(conf, CONF_remote_cmd) &&
545 !*conf_get_str(conf, CONF_remote_cmd2) &&
546 !*conf_get_str(conf, CONF_ssh_nc_host))
547 flags |= FLAG_INTERACTIVE;
548
549 /*
550 * Select protocol. This is farmed out into a table in a
551 * separate file to enable an ssh-free variant.
552 */
553 back = backend_from_proto(conf_get_int(conf, CONF_protocol));
554 if (back == NULL) {
555 fprintf(stderr,
556 "Internal fault: Unsupported protocol found\n");
557 return 1;
558 }
559
560 /*
561 * Select port.
562 */
563 if (portnumber != -1)
564 conf_set_int(conf, CONF_port, portnumber);
565
566 sk_init();
567 if (p_WSAEventSelect == NULL) {
568 fprintf(stderr, "Plink requires WinSock 2\n");
569 return 1;
570 }
571
572 logctx = log_init(NULL, conf);
573 console_provide_logctx(logctx);
574
575 /*
576 * Start up the connection.
577 */
578 netevent = CreateEvent(NULL, FALSE, FALSE, NULL);
579 {
580 const char *error;
581 char *realhost;
582 /* nodelay is only useful if stdin is a character device (console) */
583 int nodelay = conf_get_int(conf, CONF_tcp_nodelay) &&
584 (GetFileType(GetStdHandle(STD_INPUT_HANDLE)) == FILE_TYPE_CHAR);
585
586 error = back->init(NULL, &backhandle, conf,
587 conf_get_str(conf, CONF_host),
588 conf_get_int(conf, CONF_port),
589 &realhost, nodelay,
590 conf_get_int(conf, CONF_tcp_keepalives));
591 if (error) {
592 fprintf(stderr, "Unable to open connection:\n%s", error);
593 return 1;
594 }
595 back->provide_logctx(backhandle, logctx);
596 sfree(realhost);
597 }
598 connopen = 1;
599
600 inhandle = GetStdHandle(STD_INPUT_HANDLE);
601 outhandle = GetStdHandle(STD_OUTPUT_HANDLE);
602 errhandle = GetStdHandle(STD_ERROR_HANDLE);
603
604 /*
605 * Turn off ECHO and LINE input modes. We don't care if this
606 * call fails, because we know we aren't necessarily running in
607 * a console.
608 */
609 GetConsoleMode(inhandle, &orig_console_mode);
610 SetConsoleMode(inhandle, ENABLE_PROCESSED_INPUT);
611
612 /*
613 * Pass the output handles to the handle-handling subsystem.
614 * (The input one we leave until we're through the
615 * authentication process.)
616 */
617 stdout_handle = handle_output_new(outhandle, stdouterr_sent, NULL, 0);
618 stderr_handle = handle_output_new(errhandle, stdouterr_sent, NULL, 0);
619
620 main_thread_id = GetCurrentThreadId();
621
622 sending = FALSE;
623
624 now = GETTICKCOUNT();
625
626 while (1) {
627 int nhandles;
628 HANDLE *handles;
629 int n;
630 DWORD ticks;
631
632 if (!sending && back->sendok(backhandle)) {
633 stdin_handle = handle_input_new(inhandle, stdin_gotdata, NULL,
634 0);
635 sending = TRUE;
636 }
637
638 if (run_timers(now, &next)) {
639 then = now;
640 now = GETTICKCOUNT();
641 if (now - then > next - then)
642 ticks = 0;
643 else
644 ticks = next - now;
645 } else {
646 ticks = INFINITE;
647 }
648
649 handles = handle_get_events(&nhandles);
650 handles = sresize(handles, nhandles+1, HANDLE);
651 handles[nhandles] = netevent;
652 n = MsgWaitForMultipleObjects(nhandles+1, handles, FALSE, ticks,
653 QS_POSTMESSAGE);
654 if ((unsigned)(n - WAIT_OBJECT_0) < (unsigned)nhandles) {
655 handle_got_event(handles[n - WAIT_OBJECT_0]);
656 } else if (n == WAIT_OBJECT_0 + nhandles) {
657 WSANETWORKEVENTS things;
658 SOCKET socket;
659 extern SOCKET first_socket(int *), next_socket(int *);
660 extern int select_result(WPARAM, LPARAM);
661 int i, socketstate;
662
663 /*
664 * We must not call select_result() for any socket
665 * until we have finished enumerating within the tree.
666 * This is because select_result() may close the socket
667 * and modify the tree.
668 */
669 /* Count the active sockets. */
670 i = 0;
671 for (socket = first_socket(&socketstate);
672 socket != INVALID_SOCKET;
673 socket = next_socket(&socketstate)) i++;
674
675 /* Expand the buffer if necessary. */
676 if (i > sksize) {
677 sksize = i + 16;
678 sklist = sresize(sklist, sksize, SOCKET);
679 }
680
681 /* Retrieve the sockets into sklist. */
682 skcount = 0;
683 for (socket = first_socket(&socketstate);
684 socket != INVALID_SOCKET;
685 socket = next_socket(&socketstate)) {
686 sklist[skcount++] = socket;
687 }
688
689 /* Now we're done enumerating; go through the list. */
690 for (i = 0; i < skcount; i++) {
691 WPARAM wp;
692 socket = sklist[i];
693 wp = (WPARAM) socket;
694 if (!p_WSAEnumNetworkEvents(socket, NULL, &things)) {
695 static const struct { int bit, mask; } eventtypes[] = {
696 {FD_CONNECT_BIT, FD_CONNECT},
697 {FD_READ_BIT, FD_READ},
698 {FD_CLOSE_BIT, FD_CLOSE},
699 {FD_OOB_BIT, FD_OOB},
700 {FD_WRITE_BIT, FD_WRITE},
701 {FD_ACCEPT_BIT, FD_ACCEPT},
702 };
703 int e;
704
705 noise_ultralight(socket);
706 noise_ultralight(things.lNetworkEvents);
707
708 for (e = 0; e < lenof(eventtypes); e++)
709 if (things.lNetworkEvents & eventtypes[e].mask) {
710 LPARAM lp;
711 int err = things.iErrorCode[eventtypes[e].bit];
712 lp = WSAMAKESELECTREPLY(eventtypes[e].mask, err);
713 connopen &= select_result(wp, lp);
714 }
715 }
716 }
717 } else if (n == WAIT_OBJECT_0 + nhandles + 1) {
718 MSG msg;
719 while (PeekMessage(&msg, INVALID_HANDLE_VALUE,
720 WM_AGENT_CALLBACK, WM_AGENT_CALLBACK,
721 PM_REMOVE)) {
722 struct agent_callback *c = (struct agent_callback *)msg.lParam;
723 c->callback(c->callback_ctx, c->data, c->len);
724 sfree(c);
725 }
726 }
727
728 if (n == WAIT_TIMEOUT) {
729 now = next;
730 } else {
731 now = GETTICKCOUNT();
732 }
733
734 sfree(handles);
735
736 if (sending)
737 handle_unthrottle(stdin_handle, back->sendbuffer(backhandle));
738
739 if ((!connopen || !back->connected(backhandle)) &&
740 handle_backlog(stdout_handle) + handle_backlog(stderr_handle) == 0)
741 break; /* we closed the connection */
742 }
743 exitcode = back->exitcode(backhandle);
744 if (exitcode < 0) {
745 fprintf(stderr, "Remote process exit code unavailable\n");
746 exitcode = 1; /* this is an error condition */
747 }
748 cleanup_exit(exitcode);
749 return 0; /* placate compiler warning */
750 }