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