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