We now honour the PLINK_PROTOCOL environment variable if it's set.
[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 <stdarg.h>
11
12 #define PUTTY_DO_GLOBALS /* actually _define_ globals */
13 #include "putty.h"
14
15 void fatalbox (char *p, ...) {
16 va_list ap;
17 fprintf(stderr, "FATAL ERROR: ", p);
18 va_start(ap, p);
19 vfprintf(stderr, p, ap);
20 va_end(ap);
21 fputc('\n', stderr);
22 WSACleanup();
23 exit(1);
24 }
25 void connection_fatal (char *p, ...) {
26 va_list ap;
27 fprintf(stderr, "FATAL ERROR: ", p);
28 va_start(ap, p);
29 vfprintf(stderr, p, ap);
30 va_end(ap);
31 fputc('\n', stderr);
32 WSACleanup();
33 exit(1);
34 }
35
36 static char *password = NULL;
37
38 /*
39 * Stubs for linking with other modules.
40 */
41 void write_clip (void *data, int len) { }
42 void term_deselect(void) { }
43
44 HANDLE outhandle;
45 DWORD orig_console_mode;
46
47 void begin_session(void) {
48 if (!cfg.ldisc_term)
49 SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), ENABLE_PROCESSED_INPUT);
50 else
51 SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), orig_console_mode);
52 }
53
54 void term_out(void)
55 {
56 int reap;
57 DWORD ret;
58 reap = 0;
59 while (reap < inbuf_head) {
60 if (!WriteFile(outhandle, inbuf+reap, inbuf_head-reap, &ret, NULL))
61 return; /* give up in panic */
62 reap += ret;
63 }
64 inbuf_head = 0;
65 }
66
67 struct input_data {
68 DWORD len;
69 char buffer[4096];
70 HANDLE event;
71 };
72
73 static int get_password(const char *prompt, char *str, int maxlen)
74 {
75 HANDLE hin, hout;
76 DWORD savemode, i;
77
78 if (password) {
79 static int tried_once = 0;
80
81 if (tried_once) {
82 return 0;
83 } else {
84 strncpy(str, password, maxlen);
85 str[maxlen-1] = '\0';
86 tried_once = 1;
87 return 1;
88 }
89 }
90
91 hin = GetStdHandle(STD_INPUT_HANDLE);
92 hout = GetStdHandle(STD_OUTPUT_HANDLE);
93 if (hin == INVALID_HANDLE_VALUE || hout == INVALID_HANDLE_VALUE) {
94 fprintf(stderr, "Cannot get standard input/output handles");
95 return 0;
96 }
97
98 GetConsoleMode(hin, &savemode);
99 SetConsoleMode(hin, (savemode & (~ENABLE_ECHO_INPUT)) |
100 ENABLE_PROCESSED_INPUT | ENABLE_LINE_INPUT);
101
102 WriteFile(hout, prompt, strlen(prompt), &i, NULL);
103 ReadFile(hin, str, maxlen-1, &i, NULL);
104
105 SetConsoleMode(hin, savemode);
106
107 if ((int)i > maxlen) i = maxlen-1; else i = i - 2;
108 str[i] = '\0';
109
110 WriteFile(hout, "\r\n", 2, &i, NULL);
111
112 return 1;
113 }
114
115 int WINAPI stdin_read_thread(void *param) {
116 struct input_data *idata = (struct input_data *)param;
117 HANDLE inhandle;
118
119 inhandle = GetStdHandle(STD_INPUT_HANDLE);
120
121 while (ReadFile(inhandle, idata->buffer, sizeof(idata->buffer),
122 &idata->len, NULL)) {
123 SetEvent(idata->event);
124 }
125
126 idata->len = 0;
127 SetEvent(idata->event);
128
129 return 0;
130 }
131
132 /*
133 * Short description of parameters.
134 */
135 static void usage(void)
136 {
137 printf("PuTTY Link: command-line connection utility\n");
138 printf("%s\n", ver);
139 printf("Usage: plink [options] [user@]host [command]\n");
140 printf("Options:\n");
141 printf(" -v show verbose messages\n");
142 printf(" -ssh force use of ssh protocol\n");
143 printf(" -P port connect to specified port\n");
144 printf(" -pw passw login with specified password\n");
145 exit(1);
146 }
147
148 int main(int argc, char **argv) {
149 WSADATA wsadata;
150 WORD winsock_ver;
151 WSAEVENT netevent, stdinevent;
152 HANDLE handles[2];
153 SOCKET socket;
154 DWORD threadid;
155 struct input_data idata;
156 int sending;
157 int portnumber = -1;
158
159 ssh_get_password = get_password;
160
161 flags = FLAG_STDERR;
162 /*
163 * Process the command line.
164 */
165 do_defaults(NULL);
166 default_protocol = cfg.protocol;
167 default_port = cfg.port;
168 {
169 /*
170 * Override the default protocol if PLINK_PROTOCOL is set.
171 */
172 char *p = getenv("PLINK_PROTOCOL");
173 int i;
174 if (p) {
175 for (i = 0; backends[i].backend != NULL; i++) {
176 if (!strcmp(backends[i].name, p)) {
177 default_protocol = cfg.protocol = backends[i].protocol;
178 default_port = cfg.port = backends[i].backend->default_port;
179 break;
180 }
181 }
182 }
183 }
184 while (--argc) {
185 char *p = *++argv;
186 if (*p == '-') {
187 if (!strcmp(p, "-ssh")) {
188 default_protocol = cfg.protocol = PROT_SSH;
189 default_port = cfg.port = 22;
190 } else if (!strcmp(p, "-telnet")) {
191 default_protocol = cfg.protocol = PROT_TELNET;
192 default_port = cfg.port = 23;
193 } else if (!strcmp(p, "-raw")) {
194 default_protocol = cfg.protocol = PROT_RAW;
195 } else if (!strcmp(p, "-v")) {
196 flags |= FLAG_VERBOSE;
197 } else if (!strcmp(p, "-log")) {
198 logfile = "putty.log";
199 } else if (!strcmp(p, "-pw") && argc > 1) {
200 --argc, password = *++argv;
201 } else if (!strcmp(p, "-l") && argc > 1) {
202 char *username;
203 --argc, username = *++argv;
204 strncpy(cfg.username, username, sizeof(cfg.username));
205 cfg.username[sizeof(cfg.username)-1] = '\0';
206 } else if (!strcmp(p, "-P") && argc > 1) {
207 --argc, portnumber = atoi(*++argv);
208 }
209 } else if (*p) {
210 if (!*cfg.host) {
211 char *q = p;
212 /*
213 * If the hostname starts with "telnet:", set the
214 * protocol to Telnet and process the string as a
215 * Telnet URL.
216 */
217 if (!strncmp(q, "telnet:", 7)) {
218 char c;
219
220 q += 7;
221 if (q[0] == '/' && q[1] == '/')
222 q += 2;
223 cfg.protocol = PROT_TELNET;
224 p = q;
225 while (*p && *p != ':' && *p != '/') p++;
226 c = *p;
227 if (*p)
228 *p++ = '\0';
229 if (c == ':')
230 cfg.port = atoi(p);
231 else
232 cfg.port = -1;
233 strncpy (cfg.host, q, sizeof(cfg.host)-1);
234 cfg.host[sizeof(cfg.host)-1] = '\0';
235 } else {
236 char *r;
237 /*
238 * Before we process the [user@]host string, we
239 * first check for the presence of a protocol
240 * prefix (a protocol name followed by ",").
241 */
242 r = strchr(p, ',');
243 if (r) {
244 int i, j;
245 for (i = 0; backends[i].backend != NULL; i++) {
246 j = strlen(backends[i].name);
247 if (j == r-p &&
248 !memcmp(backends[i].name, p, j)) {
249 default_protocol = cfg.protocol = backends[i].protocol;
250 portnumber = backends[i].backend->default_port;
251 p = r+1;
252 break;
253 }
254 }
255 }
256
257 /*
258 * Three cases. Either (a) there's a nonzero
259 * length string followed by an @, in which
260 * case that's user and the remainder is host.
261 * Or (b) there's only one string, not counting
262 * a potential initial @, and it exists in the
263 * saved-sessions database. Or (c) only one
264 * string and it _doesn't_ exist in the
265 * database.
266 */
267 r = strrchr(p, '@');
268 if (r == p) p++, r = NULL; /* discount initial @ */
269 if (r == NULL) {
270 /*
271 * One string.
272 */
273 do_defaults (p);
274 if (cfg.host[0] == '\0') {
275 /* No settings for this host; use defaults */
276 strncpy(cfg.host, p, sizeof(cfg.host)-1);
277 cfg.host[sizeof(cfg.host)-1] = '\0';
278 cfg.port = 22;
279 }
280 } else {
281 *r++ = '\0';
282 strncpy(cfg.username, p, sizeof(cfg.username)-1);
283 cfg.username[sizeof(cfg.username)-1] = '\0';
284 strncpy(cfg.host, r, sizeof(cfg.host)-1);
285 cfg.host[sizeof(cfg.host)-1] = '\0';
286 cfg.port = 22;
287 }
288 }
289 } else {
290 int len = sizeof(cfg.remote_cmd) - 1;
291 char *cp = cfg.remote_cmd;
292 int len2;
293
294 strncpy(cp, p, len); cp[len] = '\0';
295 len2 = strlen(cp); len -= len2; cp += len2;
296 while (--argc) {
297 if (len > 0)
298 len--, *cp++ = ' ';
299 strncpy(cp, *++argv, len); cp[len] = '\0';
300 len2 = strlen(cp); len -= len2; cp += len2;
301 }
302 cfg.nopty = TRUE; /* command => no terminal */
303 cfg.ldisc_term = TRUE; /* use stdin like a line buffer */
304 break; /* done with cmdline */
305 }
306 }
307 }
308
309 if (!*cfg.host) {
310 usage();
311 }
312
313 if (!*cfg.remote_cmd)
314 flags |= FLAG_INTERACTIVE;
315
316 /*
317 * Select protocol. This is farmed out into a table in a
318 * separate file to enable an ssh-free variant.
319 */
320 {
321 int i;
322 back = NULL;
323 for (i = 0; backends[i].backend != NULL; i++)
324 if (backends[i].protocol == cfg.protocol) {
325 back = backends[i].backend;
326 break;
327 }
328 if (back == NULL) {
329 fprintf(stderr, "Internal fault: Unsupported protocol found\n");
330 return 1;
331 }
332 }
333
334 /*
335 * Select port.
336 */
337 if (portnumber != -1)
338 cfg.port = portnumber;
339
340 /*
341 * Initialise WinSock.
342 */
343 winsock_ver = MAKEWORD(2, 0);
344 if (WSAStartup(winsock_ver, &wsadata)) {
345 MessageBox(NULL, "Unable to initialise WinSock", "WinSock Error",
346 MB_OK | MB_ICONEXCLAMATION);
347 return 1;
348 }
349 if (LOBYTE(wsadata.wVersion) != 2 || HIBYTE(wsadata.wVersion) != 0) {
350 MessageBox(NULL, "WinSock version is incompatible with 2.0",
351 "WinSock Error", MB_OK | MB_ICONEXCLAMATION);
352 WSACleanup();
353 return 1;
354 }
355
356 /*
357 * Start up the connection.
358 */
359 {
360 char *error;
361 char *realhost;
362
363 error = back->init (NULL, cfg.host, cfg.port, &realhost);
364 if (error) {
365 fprintf(stderr, "Unable to open connection:\n%s", error);
366 return 1;
367 }
368 }
369
370 netevent = CreateEvent(NULL, FALSE, FALSE, NULL);
371 stdinevent = CreateEvent(NULL, FALSE, FALSE, NULL);
372
373 GetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), &orig_console_mode);
374 SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), ENABLE_PROCESSED_INPUT);
375 outhandle = GetStdHandle(STD_OUTPUT_HANDLE);
376
377 /*
378 * Now we must send the back end oodles of stuff.
379 */
380 socket = back->socket();
381 /*
382 * Turn off ECHO and LINE input modes. We don't care if this
383 * call fails, because we know we aren't necessarily running in
384 * a console.
385 */
386 WSAEventSelect(socket, netevent, FD_READ | FD_CLOSE);
387 handles[0] = netevent;
388 handles[1] = stdinevent;
389 sending = FALSE;
390 while (1) {
391 int n;
392
393 if (!sending && back->sendok()) {
394 /*
395 * Create a separate thread to read from stdin. This is
396 * a total pain, but I can't find another way to do it:
397 *
398 * - an overlapped ReadFile or ReadFileEx just doesn't
399 * happen; we get failure from ReadFileEx, and
400 * ReadFile blocks despite being given an OVERLAPPED
401 * structure. Perhaps we can't do overlapped reads
402 * on consoles. WHY THE HELL NOT?
403 *
404 * - WaitForMultipleObjects(netevent, console) doesn't
405 * work, because it signals the console when
406 * _anything_ happens, including mouse motions and
407 * other things that don't cause data to be readable
408 * - so we're back to ReadFile blocking.
409 */
410 idata.event = stdinevent;
411 if (!CreateThread(NULL, 0, stdin_read_thread,
412 &idata, 0, &threadid)) {
413 fprintf(stderr, "Unable to create second thread\n");
414 exit(1);
415 }
416 sending = TRUE;
417 }
418
419 n = WaitForMultipleObjects(2, handles, FALSE, INFINITE);
420 if (n == 0) {
421 WSANETWORKEVENTS things;
422 if (!WSAEnumNetworkEvents(socket, netevent, &things)) {
423 if (things.lNetworkEvents & FD_READ)
424 back->msg(0, FD_READ);
425 if (things.lNetworkEvents & FD_CLOSE) {
426 back->msg(0, FD_CLOSE);
427 break;
428 }
429 }
430 term_out();
431 } else if (n == 1) {
432 if (idata.len > 0) {
433 back->send(idata.buffer, idata.len);
434 } else {
435 back->special(TS_EOF);
436 }
437 }
438 }
439 WSACleanup();
440 return 0;
441 }