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