Dynamic port forwarding by means of a local SOCKS server. Fully
[u/mdw/putty] / plink.c
1 /*
2 * PLink - a command-line (stdin/stdout) variant of PuTTY.
3 */
4
5 #ifndef AUTO_WINSOCK
6 #include <winsock2.h>
7 #endif
8 #include <windows.h>
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <assert.h>
12 #include <stdarg.h>
13
14 #define PUTTY_DO_GLOBALS /* actually _define_ globals */
15 #include "putty.h"
16 #include "storage.h"
17 #include "tree234.h"
18
19 #define MAX_STDIN_BACKLOG 4096
20
21 void fatalbox(char *p, ...)
22 {
23 va_list ap;
24 fprintf(stderr, "FATAL ERROR: ");
25 va_start(ap, p);
26 vfprintf(stderr, p, ap);
27 va_end(ap);
28 fputc('\n', stderr);
29 WSACleanup();
30 cleanup_exit(1);
31 }
32 void modalfatalbox(char *p, ...)
33 {
34 va_list ap;
35 fprintf(stderr, "FATAL ERROR: ");
36 va_start(ap, p);
37 vfprintf(stderr, p, ap);
38 va_end(ap);
39 fputc('\n', stderr);
40 WSACleanup();
41 cleanup_exit(1);
42 }
43 void connection_fatal(void *frontend, char *p, ...)
44 {
45 va_list ap;
46 fprintf(stderr, "FATAL ERROR: ");
47 va_start(ap, p);
48 vfprintf(stderr, p, ap);
49 va_end(ap);
50 fputc('\n', stderr);
51 WSACleanup();
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 DWORD orig_console_mode;
67
68 WSAEVENT netevent;
69
70 static Backend *back;
71 static void *backhandle;
72 static Config cfg;
73
74 int term_ldisc(Terminal *term, int mode)
75 {
76 return FALSE;
77 }
78 void ldisc_update(void *frontend, int echo, int edit)
79 {
80 /* Update stdin read mode to reflect changes in line discipline. */
81 DWORD mode;
82
83 mode = ENABLE_PROCESSED_INPUT;
84 if (echo)
85 mode = mode | ENABLE_ECHO_INPUT;
86 else
87 mode = mode & ~ENABLE_ECHO_INPUT;
88 if (edit)
89 mode = mode | ENABLE_LINE_INPUT;
90 else
91 mode = mode & ~ENABLE_LINE_INPUT;
92 SetConsoleMode(inhandle, mode);
93 }
94
95 struct input_data {
96 DWORD len;
97 char buffer[4096];
98 HANDLE event, eventback;
99 };
100
101 static DWORD WINAPI stdin_read_thread(void *param)
102 {
103 struct input_data *idata = (struct input_data *) param;
104 HANDLE inhandle;
105
106 inhandle = GetStdHandle(STD_INPUT_HANDLE);
107
108 while (ReadFile(inhandle, idata->buffer, sizeof(idata->buffer),
109 &idata->len, NULL) && idata->len > 0) {
110 SetEvent(idata->event);
111 WaitForSingleObject(idata->eventback, INFINITE);
112 }
113
114 idata->len = 0;
115 SetEvent(idata->event);
116
117 return 0;
118 }
119
120 struct output_data {
121 DWORD len, lenwritten;
122 int writeret;
123 char *buffer;
124 int is_stderr, done;
125 HANDLE event, eventback;
126 int busy;
127 };
128
129 static DWORD WINAPI stdout_write_thread(void *param)
130 {
131 struct output_data *odata = (struct output_data *) param;
132 HANDLE outhandle, errhandle;
133
134 outhandle = GetStdHandle(STD_OUTPUT_HANDLE);
135 errhandle = GetStdHandle(STD_ERROR_HANDLE);
136
137 while (1) {
138 WaitForSingleObject(odata->eventback, INFINITE);
139 if (odata->done)
140 break;
141 odata->writeret =
142 WriteFile(odata->is_stderr ? errhandle : outhandle,
143 odata->buffer, odata->len, &odata->lenwritten, NULL);
144 SetEvent(odata->event);
145 }
146
147 return 0;
148 }
149
150 bufchain stdout_data, stderr_data;
151 struct output_data odata, edata;
152
153 void try_output(int is_stderr)
154 {
155 struct output_data *data = (is_stderr ? &edata : &odata);
156 void *senddata;
157 int sendlen;
158
159 if (!data->busy) {
160 bufchain_prefix(is_stderr ? &stderr_data : &stdout_data,
161 &senddata, &sendlen);
162 data->buffer = senddata;
163 data->len = sendlen;
164 SetEvent(data->eventback);
165 data->busy = 1;
166 }
167 }
168
169 int from_backend(void *frontend_handle, int is_stderr,
170 const char *data, int len)
171 {
172 int osize, esize;
173
174 assert(len > 0);
175
176 if (is_stderr) {
177 bufchain_add(&stderr_data, data, len);
178 try_output(1);
179 } else {
180 bufchain_add(&stdout_data, data, len);
181 try_output(0);
182 }
183
184 osize = bufchain_size(&stdout_data);
185 esize = bufchain_size(&stderr_data);
186
187 return osize + esize;
188 }
189
190 /*
191 * Short description of parameters.
192 */
193 static void usage(void)
194 {
195 printf("PuTTY Link: command-line connection utility\n");
196 printf("%s\n", ver);
197 printf("Usage: plink [options] [user@]host [command]\n");
198 printf(" (\"host\" can also be a PuTTY saved session name)\n");
199 printf("Options:\n");
200 printf(" -v show verbose messages\n");
201 printf(" -load sessname Load settings from saved session\n");
202 printf(" -ssh -telnet -rlogin -raw\n");
203 printf(" force use of a particular protocol (default SSH)\n");
204 printf(" -P port connect to specified port\n");
205 printf(" -l user connect with specified username\n");
206 printf(" -m file read remote command(s) from file\n");
207 printf(" -batch disable all interactive prompts\n");
208 printf("The following options only apply to SSH connections:\n");
209 printf(" -pw passw login with specified password\n");
210 printf(" -D listen-port Dynamic SOCKS-based port forwarding\n");
211 printf(" -L listen-port:host:port Forward local port to "
212 "remote address\n");
213 printf(" -R listen-port:host:port Forward remote port to"
214 " local address\n");
215 printf(" -X -x enable / disable X11 forwarding\n");
216 printf(" -A -a enable / disable agent forwarding\n");
217 printf(" -t -T enable / disable pty allocation\n");
218 printf(" -1 -2 force use of particular protocol version\n");
219 printf(" -C enable compression\n");
220 printf(" -i key private key file for authentication\n");
221 exit(1);
222 }
223
224 char *do_select(SOCKET skt, int startup)
225 {
226 int events;
227 if (startup) {
228 events = (FD_CONNECT | FD_READ | FD_WRITE |
229 FD_OOB | FD_CLOSE | FD_ACCEPT);
230 } else {
231 events = 0;
232 }
233 if (WSAEventSelect(skt, netevent, events) == SOCKET_ERROR) {
234 switch (WSAGetLastError()) {
235 case WSAENETDOWN:
236 return "Network is down";
237 default:
238 return "WSAAsyncSelect(): unknown error";
239 }
240 }
241 return NULL;
242 }
243
244 int main(int argc, char **argv)
245 {
246 WSADATA wsadata;
247 WORD winsock_ver;
248 WSAEVENT stdinevent, stdoutevent, stderrevent;
249 HANDLE handles[4];
250 DWORD in_threadid, out_threadid, err_threadid;
251 struct input_data idata;
252 int reading;
253 int sending;
254 int portnumber = -1;
255 SOCKET *sklist;
256 int skcount, sksize;
257 int connopen;
258 int exitcode;
259 int errors;
260
261 ssh_get_line = console_get_line;
262
263 sklist = NULL;
264 skcount = sksize = 0;
265 /*
266 * Initialise port and protocol to sensible defaults. (These
267 * will be overridden by more or less anything.)
268 */
269 default_protocol = PROT_SSH;
270 default_port = 22;
271
272 flags = FLAG_STDERR;
273 /*
274 * Process the command line.
275 */
276 do_defaults(NULL, &cfg);
277 default_protocol = cfg.protocol;
278 default_port = cfg.port;
279 errors = 0;
280 {
281 /*
282 * Override the default protocol if PLINK_PROTOCOL is set.
283 */
284 char *p = getenv("PLINK_PROTOCOL");
285 int i;
286 if (p) {
287 for (i = 0; backends[i].backend != NULL; i++) {
288 if (!strcmp(backends[i].name, p)) {
289 default_protocol = cfg.protocol = backends[i].protocol;
290 default_port = cfg.port =
291 backends[i].backend->default_port;
292 break;
293 }
294 }
295 }
296 }
297 while (--argc) {
298 char *p = *++argv;
299 if (*p == '-') {
300 int ret = cmdline_process_param(p, (argc > 1 ? argv[1] : NULL),
301 1, &cfg);
302 if (ret == -2) {
303 fprintf(stderr,
304 "plink: option \"%s\" requires an argument\n", p);
305 errors = 1;
306 } else if (ret == 2) {
307 --argc, ++argv;
308 } else if (ret == 1) {
309 continue;
310 } else if (!strcmp(p, "-batch")) {
311 console_batch_mode = 1;
312 } else {
313 fprintf(stderr, "plink: unknown option \"%s\"\n", p);
314 errors = 1;
315 }
316 } else if (*p) {
317 if (!*cfg.host) {
318 char *q = p;
319 /*
320 * If the hostname starts with "telnet:", set the
321 * protocol to Telnet and process the string as a
322 * Telnet URL.
323 */
324 if (!strncmp(q, "telnet:", 7)) {
325 char c;
326
327 q += 7;
328 if (q[0] == '/' && q[1] == '/')
329 q += 2;
330 cfg.protocol = PROT_TELNET;
331 p = q;
332 while (*p && *p != ':' && *p != '/')
333 p++;
334 c = *p;
335 if (*p)
336 *p++ = '\0';
337 if (c == ':')
338 cfg.port = atoi(p);
339 else
340 cfg.port = -1;
341 strncpy(cfg.host, q, sizeof(cfg.host) - 1);
342 cfg.host[sizeof(cfg.host) - 1] = '\0';
343 } else {
344 char *r;
345 /*
346 * Before we process the [user@]host string, we
347 * first check for the presence of a protocol
348 * prefix (a protocol name followed by ",").
349 */
350 r = strchr(p, ',');
351 if (r) {
352 int i, j;
353 for (i = 0; backends[i].backend != NULL; i++) {
354 j = strlen(backends[i].name);
355 if (j == r - p &&
356 !memcmp(backends[i].name, p, j)) {
357 default_protocol = cfg.protocol =
358 backends[i].protocol;
359 portnumber =
360 backends[i].backend->default_port;
361 p = r + 1;
362 break;
363 }
364 }
365 }
366
367 /*
368 * Three cases. Either (a) there's a nonzero
369 * length string followed by an @, in which
370 * case that's user and the remainder is host.
371 * Or (b) there's only one string, not counting
372 * a potential initial @, and it exists in the
373 * saved-sessions database. Or (c) only one
374 * string and it _doesn't_ exist in the
375 * database.
376 */
377 r = strrchr(p, '@');
378 if (r == p)
379 p++, r = NULL; /* discount initial @ */
380 if (r == NULL) {
381 /*
382 * One string.
383 */
384 Config cfg2;
385 do_defaults(p, &cfg2);
386 if (cfg2.host[0] == '\0') {
387 /* No settings for this host; use defaults */
388 strncpy(cfg.host, p, sizeof(cfg.host) - 1);
389 cfg.host[sizeof(cfg.host) - 1] = '\0';
390 cfg.port = default_port;
391 } else {
392 cfg = cfg2;
393 cfg.remote_cmd_ptr = cfg.remote_cmd;
394 }
395 } else {
396 *r++ = '\0';
397 strncpy(cfg.username, p, sizeof(cfg.username) - 1);
398 cfg.username[sizeof(cfg.username) - 1] = '\0';
399 strncpy(cfg.host, r, sizeof(cfg.host) - 1);
400 cfg.host[sizeof(cfg.host) - 1] = '\0';
401 cfg.port = default_port;
402 }
403 }
404 } else {
405 char *command;
406 int cmdlen, cmdsize;
407 cmdlen = cmdsize = 0;
408 command = NULL;
409
410 while (argc) {
411 while (*p) {
412 if (cmdlen >= cmdsize) {
413 cmdsize = cmdlen + 512;
414 command = sresize(command, cmdsize, char);
415 }
416 command[cmdlen++]=*p++;
417 }
418 if (cmdlen >= cmdsize) {
419 cmdsize = cmdlen + 512;
420 command = sresize(command, cmdsize, char);
421 }
422 command[cmdlen++]=' '; /* always add trailing space */
423 if (--argc) p = *++argv;
424 }
425 if (cmdlen) command[--cmdlen]='\0';
426 /* change trailing blank to NUL */
427 cfg.remote_cmd_ptr = command;
428 cfg.remote_cmd_ptr2 = NULL;
429 cfg.nopty = TRUE; /* command => no terminal */
430
431 break; /* done with cmdline */
432 }
433 }
434 }
435
436 if (errors)
437 return 1;
438
439 if (!*cfg.host) {
440 usage();
441 }
442
443 /*
444 * Trim leading whitespace off the hostname if it's there.
445 */
446 {
447 int space = strspn(cfg.host, " \t");
448 memmove(cfg.host, cfg.host+space, 1+strlen(cfg.host)-space);
449 }
450
451 /* See if host is of the form user@host */
452 if (cfg.host[0] != '\0') {
453 char *atsign = strchr(cfg.host, '@');
454 /* Make sure we're not overflowing the user field */
455 if (atsign) {
456 if (atsign - cfg.host < sizeof cfg.username) {
457 strncpy(cfg.username, cfg.host, atsign - cfg.host);
458 cfg.username[atsign - cfg.host] = '\0';
459 }
460 memmove(cfg.host, atsign + 1, 1 + strlen(atsign + 1));
461 }
462 }
463
464 /*
465 * Perform command-line overrides on session configuration.
466 */
467 cmdline_run_saved(&cfg);
468
469 /*
470 * Trim a colon suffix off the hostname if it's there.
471 */
472 cfg.host[strcspn(cfg.host, ":")] = '\0';
473
474 /*
475 * Remove any remaining whitespace from the hostname.
476 */
477 {
478 int p1 = 0, p2 = 0;
479 while (cfg.host[p2] != '\0') {
480 if (cfg.host[p2] != ' ' && cfg.host[p2] != '\t') {
481 cfg.host[p1] = cfg.host[p2];
482 p1++;
483 }
484 p2++;
485 }
486 cfg.host[p1] = '\0';
487 }
488
489 if (!*cfg.remote_cmd_ptr)
490 flags |= FLAG_INTERACTIVE;
491
492 /*
493 * Select protocol. This is farmed out into a table in a
494 * separate file to enable an ssh-free variant.
495 */
496 {
497 int i;
498 back = NULL;
499 for (i = 0; backends[i].backend != NULL; i++)
500 if (backends[i].protocol == cfg.protocol) {
501 back = backends[i].backend;
502 break;
503 }
504 if (back == NULL) {
505 fprintf(stderr,
506 "Internal fault: Unsupported protocol found\n");
507 return 1;
508 }
509 }
510
511 /*
512 * Select port.
513 */
514 if (portnumber != -1)
515 cfg.port = portnumber;
516
517 /*
518 * Initialise WinSock.
519 */
520 winsock_ver = MAKEWORD(2, 0);
521 if (WSAStartup(winsock_ver, &wsadata)) {
522 MessageBox(NULL, "Unable to initialise WinSock", "WinSock Error",
523 MB_OK | MB_ICONEXCLAMATION);
524 return 1;
525 }
526 if (LOBYTE(wsadata.wVersion) != 2 || HIBYTE(wsadata.wVersion) != 0) {
527 MessageBox(NULL, "WinSock version is incompatible with 2.0",
528 "WinSock Error", MB_OK | MB_ICONEXCLAMATION);
529 WSACleanup();
530 return 1;
531 }
532 sk_init();
533
534 /*
535 * Start up the connection.
536 */
537 netevent = CreateEvent(NULL, FALSE, FALSE, NULL);
538 {
539 char *error;
540 char *realhost;
541 /* nodelay is only useful if stdin is a character device (console) */
542 int nodelay = cfg.tcp_nodelay &&
543 (GetFileType(GetStdHandle(STD_INPUT_HANDLE)) == FILE_TYPE_CHAR);
544
545 error = back->init(NULL, &backhandle, &cfg, cfg.host, cfg.port,
546 &realhost, nodelay);
547 if (error) {
548 fprintf(stderr, "Unable to open connection:\n%s", error);
549 return 1;
550 }
551 logctx = log_init(NULL, &cfg);
552 back->provide_logctx(backhandle, logctx);
553 console_provide_logctx(logctx);
554 sfree(realhost);
555 }
556 connopen = 1;
557
558 stdinevent = CreateEvent(NULL, FALSE, FALSE, NULL);
559 stdoutevent = CreateEvent(NULL, FALSE, FALSE, NULL);
560 stderrevent = CreateEvent(NULL, FALSE, FALSE, NULL);
561
562 inhandle = GetStdHandle(STD_INPUT_HANDLE);
563 outhandle = GetStdHandle(STD_OUTPUT_HANDLE);
564 errhandle = GetStdHandle(STD_ERROR_HANDLE);
565 GetConsoleMode(inhandle, &orig_console_mode);
566 SetConsoleMode(inhandle, ENABLE_PROCESSED_INPUT);
567
568 /*
569 * Turn off ECHO and LINE input modes. We don't care if this
570 * call fails, because we know we aren't necessarily running in
571 * a console.
572 */
573 handles[0] = netevent;
574 handles[1] = stdinevent;
575 handles[2] = stdoutevent;
576 handles[3] = stderrevent;
577 sending = FALSE;
578
579 /*
580 * Create spare threads to write to stdout and stderr, so we
581 * can arrange asynchronous writes.
582 */
583 odata.event = stdoutevent;
584 odata.eventback = CreateEvent(NULL, FALSE, FALSE, NULL);
585 odata.is_stderr = 0;
586 odata.busy = odata.done = 0;
587 if (!CreateThread(NULL, 0, stdout_write_thread,
588 &odata, 0, &out_threadid)) {
589 fprintf(stderr, "Unable to create output thread\n");
590 cleanup_exit(1);
591 }
592 edata.event = stderrevent;
593 edata.eventback = CreateEvent(NULL, FALSE, FALSE, NULL);
594 edata.is_stderr = 1;
595 edata.busy = edata.done = 0;
596 if (!CreateThread(NULL, 0, stdout_write_thread,
597 &edata, 0, &err_threadid)) {
598 fprintf(stderr, "Unable to create error output thread\n");
599 cleanup_exit(1);
600 }
601
602 while (1) {
603 int n;
604
605 if (!sending && back->sendok(backhandle)) {
606 /*
607 * Create a separate thread to read from stdin. This is
608 * a total pain, but I can't find another way to do it:
609 *
610 * - an overlapped ReadFile or ReadFileEx just doesn't
611 * happen; we get failure from ReadFileEx, and
612 * ReadFile blocks despite being given an OVERLAPPED
613 * structure. Perhaps we can't do overlapped reads
614 * on consoles. WHY THE HELL NOT?
615 *
616 * - WaitForMultipleObjects(netevent, console) doesn't
617 * work, because it signals the console when
618 * _anything_ happens, including mouse motions and
619 * other things that don't cause data to be readable
620 * - so we're back to ReadFile blocking.
621 */
622 idata.event = stdinevent;
623 idata.eventback = CreateEvent(NULL, FALSE, FALSE, NULL);
624 if (!CreateThread(NULL, 0, stdin_read_thread,
625 &idata, 0, &in_threadid)) {
626 fprintf(stderr, "Unable to create input thread\n");
627 cleanup_exit(1);
628 }
629 sending = TRUE;
630 }
631
632 n = WaitForMultipleObjects(4, handles, FALSE, INFINITE);
633 if (n == 0) {
634 WSANETWORKEVENTS things;
635 SOCKET socket;
636 extern SOCKET first_socket(int *), next_socket(int *);
637 extern int select_result(WPARAM, LPARAM);
638 int i, socketstate;
639
640 /*
641 * We must not call select_result() for any socket
642 * until we have finished enumerating within the tree.
643 * This is because select_result() may close the socket
644 * and modify the tree.
645 */
646 /* Count the active sockets. */
647 i = 0;
648 for (socket = first_socket(&socketstate);
649 socket != INVALID_SOCKET;
650 socket = next_socket(&socketstate)) i++;
651
652 /* Expand the buffer if necessary. */
653 if (i > sksize) {
654 sksize = i + 16;
655 sklist = sresize(sklist, sksize, SOCKET);
656 }
657
658 /* Retrieve the sockets into sklist. */
659 skcount = 0;
660 for (socket = first_socket(&socketstate);
661 socket != INVALID_SOCKET;
662 socket = next_socket(&socketstate)) {
663 sklist[skcount++] = socket;
664 }
665
666 /* Now we're done enumerating; go through the list. */
667 for (i = 0; i < skcount; i++) {
668 WPARAM wp;
669 socket = sklist[i];
670 wp = (WPARAM) socket;
671 if (!WSAEnumNetworkEvents(socket, NULL, &things)) {
672 static const struct { int bit, mask; } eventtypes[] = {
673 {FD_CONNECT_BIT, FD_CONNECT},
674 {FD_READ_BIT, FD_READ},
675 {FD_CLOSE_BIT, FD_CLOSE},
676 {FD_OOB_BIT, FD_OOB},
677 {FD_WRITE_BIT, FD_WRITE},
678 {FD_ACCEPT_BIT, FD_ACCEPT},
679 };
680 int e;
681
682 noise_ultralight(socket);
683 noise_ultralight(things.lNetworkEvents);
684
685 for (e = 0; e < lenof(eventtypes); e++)
686 if (things.lNetworkEvents & eventtypes[e].mask) {
687 LPARAM lp;
688 int err = things.iErrorCode[eventtypes[e].bit];
689 lp = WSAMAKESELECTREPLY(eventtypes[e].mask, err);
690 connopen &= select_result(wp, lp);
691 }
692 }
693 }
694 } else if (n == 1) {
695 reading = 0;
696 noise_ultralight(idata.len);
697 if (connopen && back->socket(backhandle) != NULL) {
698 if (idata.len > 0) {
699 back->send(backhandle, idata.buffer, idata.len);
700 } else {
701 back->special(backhandle, TS_EOF);
702 }
703 }
704 } else if (n == 2) {
705 odata.busy = 0;
706 if (!odata.writeret) {
707 fprintf(stderr, "Unable to write to standard output\n");
708 cleanup_exit(0);
709 }
710 bufchain_consume(&stdout_data, odata.lenwritten);
711 if (bufchain_size(&stdout_data) > 0)
712 try_output(0);
713 if (connopen && back->socket(backhandle) != NULL) {
714 back->unthrottle(backhandle, bufchain_size(&stdout_data) +
715 bufchain_size(&stderr_data));
716 }
717 } else if (n == 3) {
718 edata.busy = 0;
719 if (!edata.writeret) {
720 fprintf(stderr, "Unable to write to standard output\n");
721 cleanup_exit(0);
722 }
723 bufchain_consume(&stderr_data, edata.lenwritten);
724 if (bufchain_size(&stderr_data) > 0)
725 try_output(1);
726 if (connopen && back->socket(backhandle) != NULL) {
727 back->unthrottle(backhandle, bufchain_size(&stdout_data) +
728 bufchain_size(&stderr_data));
729 }
730 }
731 if (!reading && back->sendbuffer(backhandle) < MAX_STDIN_BACKLOG) {
732 SetEvent(idata.eventback);
733 reading = 1;
734 }
735 if ((!connopen || back->socket(backhandle) == NULL) &&
736 bufchain_size(&stdout_data) == 0 &&
737 bufchain_size(&stderr_data) == 0)
738 break; /* we closed the connection */
739 }
740 WSACleanup();
741 exitcode = back->exitcode(backhandle);
742 if (exitcode < 0) {
743 fprintf(stderr, "Remote process exit code unavailable\n");
744 exitcode = 1; /* this is an error condition */
745 }
746 return exitcode;
747 }