]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - plink.c
Miscellaneous ssh2 fixes. plink is now relatively sane
[PuTTY.git] / plink.c
1 /*
2  * PLink - a command-line (stdin/stdout) variant of PuTTY.
3  */
4
5 #include <winsock2.h>
6 #include <windows.h>
7 #include <stdio.h>
8 #include <stdarg.h>
9
10 #define PUTTY_DO_GLOBALS                       /* actually _define_ globals */
11 #include "putty.h"
12
13 void fatalbox (char *p, ...) {
14     va_list ap;
15     fprintf(stderr, "FATAL ERROR: ", p);
16     va_start(ap, p);
17     vfprintf(stderr, p, ap);
18     va_end(ap);
19     fputc('\n', stderr);
20     WSACleanup();
21     exit(1);
22 }
23
24 HANDLE outhandle;
25
26 void term_out(void)
27 {
28     int reap;
29     DWORD ret;
30
31     reap = 0;
32     while (reap < inbuf_head) {
33         if (!WriteFile(outhandle, inbuf+reap, inbuf_head-reap, &ret, NULL))
34             return;                    /* give up in panic */
35         reap += ret;
36     }
37     inbuf_head = 0;
38 }
39
40 struct input_data {
41     DWORD len;
42     char buffer[4096];
43     HANDLE event;
44 };
45
46 static int get_password(const char *prompt, char *str, int maxlen)
47 {
48     HANDLE hin, hout;
49     DWORD savemode, i;
50
51 #if 0 /* this allows specifying a password some other way */
52     if (password) {
53         static int tried_once = 0;
54
55         if (tried_once) {
56             return 0;
57         } else {
58             strncpy(str, password, maxlen);
59             str[maxlen-1] = '\0';
60             tried_once = 1;
61             return 1;
62         }
63     }
64 #endif
65
66     hin = GetStdHandle(STD_INPUT_HANDLE);
67     hout = GetStdHandle(STD_OUTPUT_HANDLE);
68     if (hin == INVALID_HANDLE_VALUE || hout == INVALID_HANDLE_VALUE) {
69         fprintf(stderr, "Cannot get standard input/output handles");
70         return 0;
71     }
72
73     GetConsoleMode(hin, &savemode);
74     SetConsoleMode(hin, (savemode & (~ENABLE_ECHO_INPUT)) |
75                    ENABLE_PROCESSED_INPUT | ENABLE_LINE_INPUT);
76
77     WriteFile(hout, prompt, strlen(prompt), &i, NULL);
78     ReadFile(hin, str, maxlen-1, &i, NULL);
79
80     SetConsoleMode(hin, savemode);
81
82     if ((int)i > maxlen) i = maxlen-1; else i = i - 2;
83     str[i] = '\0';
84
85     WriteFile(hout, "\r\n", 2, &i, NULL);
86
87     return 1;
88 }
89
90 int WINAPI stdin_read_thread(void *param) {
91     struct input_data *idata = (struct input_data *)param;
92     HANDLE inhandle;
93
94     inhandle = GetStdHandle(STD_INPUT_HANDLE);
95
96     while (ReadFile(inhandle, idata->buffer, sizeof(idata->buffer),
97                     &idata->len, NULL)) {
98         SetEvent(idata->event);
99     }
100
101     idata->len = 0;
102     SetEvent(idata->event);
103
104     return 0;
105 }
106
107 int main(int argc, char **argv) {
108     WSADATA wsadata;
109     WORD winsock_ver;
110     WSAEVENT netevent, stdinevent;
111     HANDLE handles[2];
112     SOCKET socket;
113     DWORD threadid;
114     struct input_data idata;
115     int sending;
116
117     ssh_get_password = get_password;
118
119     flags = FLAG_STDERR;
120     /*
121      * Process the command line.
122      */
123     default_protocol = DEFAULT_PROTOCOL;
124     default_port = DEFAULT_PORT;
125     do_defaults(NULL);
126     while (--argc) {
127         char *p = *++argv;
128         if (*p == '-') {
129             if (!strcmp(p, "-ssh")) {
130                 default_protocol = cfg.protocol = PROT_SSH;
131                 default_port = cfg.port = 22;
132             } else if (!strcmp(p, "-v")) {
133                 flags |= FLAG_VERBOSE;
134             } else if (!strcmp(p, "-log")) {
135                 logfile = "putty.log";
136             }
137         } else if (*p) {
138             if (!*cfg.host) {
139                 char *q = p;
140                 /*
141                  * If the hostname starts with "telnet:", set the
142                  * protocol to Telnet and process the string as a
143                  * Telnet URL.
144                  */
145                 if (!strncmp(q, "telnet:", 7)) {
146                     char c;
147
148                     q += 7;
149                     if (q[0] == '/' && q[1] == '/')
150                         q += 2;
151                     cfg.protocol = PROT_TELNET;
152                     p = q;
153                     while (*p && *p != ':' && *p != '/') p++;
154                     c = *p;
155                     if (*p)
156                         *p++ = '\0';
157                     if (c == ':')
158                         cfg.port = atoi(p);
159                     else
160                         cfg.port = -1;
161                     strncpy (cfg.host, q, sizeof(cfg.host)-1);
162                     cfg.host[sizeof(cfg.host)-1] = '\0';
163                 } else {
164                     /*
165                      * Three cases. Either (a) there's a nonzero
166                      * length string followed by an @, in which
167                      * case that's user and the remainder is host.
168                      * Or (b) there's only one string, not counting
169                      * a potential initial @, and it exists in the
170                      * saved-sessions database. Or (c) only one
171                      * string and it _doesn't_ exist in the
172                      * database.
173                      */
174                     char *r = strrchr(p, '@');
175                     if (r == p) p++, r = NULL;   /* discount initial @ */
176                     if (r == NULL) {
177                         /*
178                          * One string.
179                          */
180                         do_defaults (p);
181                         if (cfg.host[0] == '\0') {
182                             /* No settings for this host; use defaults */
183                             strncpy(cfg.host, p, sizeof(cfg.host)-1);
184                             cfg.host[sizeof(cfg.host)-1] = '\0';
185                             cfg.port = 22;
186                         }
187                     } else {
188                         *r++ = '\0';
189                         strncpy(cfg.username, p, sizeof(cfg.username)-1);
190                         cfg.username[sizeof(cfg.username)-1] = '\0';
191                         strncpy(cfg.host, r, sizeof(cfg.host)-1);
192                         cfg.host[sizeof(cfg.host)-1] = '\0';
193                         cfg.port = 22;
194                     }
195                 }
196             } else {
197                 int len = sizeof(cfg.remote_cmd) - 1;
198                 char *cp = cfg.remote_cmd;
199                 int len2;
200
201                 strncpy(cp, p, len); cp[len] = '\0';
202                 len2 = strlen(cp); len -= len2; cp += len2;
203                 while (--argc) {
204                     if (len > 0)
205                         len--, *cp++ = ' ';
206                     strncpy(cp, *++argv, len); cp[len] = '\0';
207                     len2 = strlen(cp); len -= len2; cp += len2;
208                 }
209                 cfg.nopty = TRUE;      /* command => no terminal */
210                 cfg.ldisc_term = TRUE; /* use stdin like a line buffer */
211                 break;                 /* done with cmdline */
212             }
213         }
214     }
215
216     if (!*cfg.remote_cmd)
217         flags |= FLAG_INTERACTIVE;
218
219     /*
220      * Select protocol. This is farmed out into a table in a
221      * separate file to enable an ssh-free variant.
222      */
223     {
224         int i;
225         back = NULL;
226         for (i = 0; backends[i].backend != NULL; i++)
227             if (backends[i].protocol == cfg.protocol) {
228                 back = backends[i].backend;
229                 break;
230             }
231         if (back == NULL) {
232             fprintf(stderr, "Internal fault: Unsupported protocol found\n");
233             return 1;
234         }
235     }
236
237     /*
238      * Initialise WinSock.
239      */
240     winsock_ver = MAKEWORD(2, 0);
241     if (WSAStartup(winsock_ver, &wsadata)) {
242         MessageBox(NULL, "Unable to initialise WinSock", "WinSock Error",
243                    MB_OK | MB_ICONEXCLAMATION);
244         return 1;
245     }
246     if (LOBYTE(wsadata.wVersion) != 2 || HIBYTE(wsadata.wVersion) != 0) {
247         MessageBox(NULL, "WinSock version is incompatible with 2.0",
248                    "WinSock Error", MB_OK | MB_ICONEXCLAMATION);
249         WSACleanup();
250         return 1;
251     }
252
253     /*
254      * Start up the connection.
255      */
256     {
257         char *error;
258         char *realhost;
259
260         error = back->init (NULL, cfg.host, cfg.port, &realhost);
261         if (error) {
262             fprintf(stderr, "Unable to open connection:\n%s", error);
263             return 1;
264         }
265     }
266
267     netevent = CreateEvent(NULL, FALSE, FALSE, NULL);
268     stdinevent = CreateEvent(NULL, FALSE, FALSE, NULL);
269
270     if (!cfg.ldisc_term)
271         SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), ENABLE_PROCESSED_INPUT);
272     outhandle = GetStdHandle(STD_OUTPUT_HANDLE);
273
274     /*
275      * Now we must send the back end oodles of stuff.
276      */
277     socket = back->socket();
278     /*
279      * Turn off ECHO and LINE input modes. We don't care if this
280      * call fails, because we know we aren't necessarily running in
281      * a console.
282      */
283     WSAEventSelect(socket, netevent, FD_READ | FD_CLOSE);
284     handles[0] = netevent;
285     handles[1] = stdinevent;
286     sending = FALSE;
287     while (1) {
288         int n;
289         n = WaitForMultipleObjects(2, handles, FALSE, INFINITE);
290         if (n == 0) {
291             WSANETWORKEVENTS things;
292             if (!WSAEnumNetworkEvents(socket, netevent, &things)) {
293                 if (things.lNetworkEvents & FD_READ)
294                     back->msg(0, FD_READ);
295                 if (things.lNetworkEvents & FD_CLOSE) {
296                     back->msg(0, FD_CLOSE);
297                     break;
298                 }
299             }
300             term_out();
301             if (!sending && back->sendok()) {
302                 /*
303                  * Create a separate thread to read from stdin.
304                  * This is a total pain, but I can't find another
305                  * way to do it:
306                  *
307                  *  - an overlapped ReadFile or ReadFileEx just
308                  *    doesn't happen; we get failure from
309                  *    ReadFileEx, and ReadFile blocks despite being
310                  *    given an OVERLAPPED structure. Perhaps we
311                  *    can't do overlapped reads on consoles. WHY
312                  *    THE HELL NOT?
313                  * 
314                  *  - WaitForMultipleObjects(netevent, console)
315                  *    doesn't work, because it signals the console
316                  *    when _anything_ happens, including mouse
317                  *    motions and other things that don't cause
318                  *    data to be readable - so we're back to
319                  *    ReadFile blocking.
320                  */
321                 idata.event = stdinevent;
322                 if (!CreateThread(NULL, 0, stdin_read_thread,
323                                   &idata, 0, &threadid)) {
324                     fprintf(stderr, "Unable to create second thread\n");
325                     exit(1);
326                 }
327                 sending = TRUE;
328             }
329         } else if (n == 1) {
330             if (idata.len > 0) {
331                 back->send(idata.buffer, idata.len);
332             } else {
333                 back->special(TS_EOF);
334             }
335         }
336     }
337     WSACleanup();
338     return 0;
339 }