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