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