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