Store default port number in each back end
[u/mdw/putty] / plink.c
CommitLineData
12dc4ec0 1/*
2 * PLink - a command-line (stdin/stdout) variant of PuTTY.
3 */
4
4d331a77 5#ifndef AUTO_WINSOCK
12dc4ec0 6#include <winsock2.h>
4d331a77 7#endif
12dc4ec0 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
15void 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}
8d5de777 25void 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}
12dc4ec0 35
d8426c54 36static char *password = NULL;
37
989b10e9 38/*
39 * Stubs for linking with other modules.
40 */
41void write_clip (void *data, int len) { }
42void term_deselect(void) { }
43
12dc4ec0 44HANDLE outhandle;
6f34e365 45DWORD orig_console_mode;
46
47void 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}
12dc4ec0 53
54void term_out(void)
55{
56 int reap;
57 DWORD ret;
12dc4ec0 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
67struct input_data {
68 DWORD len;
69 char buffer[4096];
70 HANDLE event;
71};
72
67779be7 73static int get_password(const char *prompt, char *str, int maxlen)
74{
75 HANDLE hin, hout;
76 DWORD savemode, i;
77
67779be7 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 }
67779be7 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
12dc4ec0 115int 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
d8426c54 132/*
133 * Short description of parameters.
134 */
135static 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
12dc4ec0 148int 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;
d8426c54 157 int portnumber = -1;
12dc4ec0 158
67779be7 159 ssh_get_password = get_password;
160
161 flags = FLAG_STDERR;
12dc4ec0 162 /*
163 * Process the command line.
164 */
12dc4ec0 165 do_defaults(NULL);
e7a7383f 166 default_protocol = cfg.protocol;
167 default_port = cfg.port;
12dc4ec0 168 while (--argc) {
169 char *p = *++argv;
170 if (*p == '-') {
171 if (!strcmp(p, "-ssh")) {
172 default_protocol = cfg.protocol = PROT_SSH;
173 default_port = cfg.port = 22;
67779be7 174 } else if (!strcmp(p, "-v")) {
175 flags |= FLAG_VERBOSE;
12dc4ec0 176 } else if (!strcmp(p, "-log")) {
177 logfile = "putty.log";
d8426c54 178 } else if (!strcmp(p, "-pw") && argc > 1) {
179 --argc, password = *++argv;
e7a7383f 180 } else if (!strcmp(p, "-l") && argc > 1) {
181 char *username;
182 --argc, username = *++argv;
183 strncpy(cfg.username, username, sizeof(cfg.username));
184 cfg.username[sizeof(cfg.username)-1] = '\0';
d8426c54 185 } else if (!strcmp(p, "-P") && argc > 1) {
186 --argc, portnumber = atoi(*++argv);
187 }
12dc4ec0 188 } else if (*p) {
189 if (!*cfg.host) {
190 char *q = p;
191 /*
192 * If the hostname starts with "telnet:", set the
193 * protocol to Telnet and process the string as a
194 * Telnet URL.
195 */
196 if (!strncmp(q, "telnet:", 7)) {
197 char c;
198
199 q += 7;
200 if (q[0] == '/' && q[1] == '/')
201 q += 2;
202 cfg.protocol = PROT_TELNET;
203 p = q;
204 while (*p && *p != ':' && *p != '/') p++;
205 c = *p;
206 if (*p)
207 *p++ = '\0';
208 if (c == ':')
209 cfg.port = atoi(p);
210 else
211 cfg.port = -1;
212 strncpy (cfg.host, q, sizeof(cfg.host)-1);
213 cfg.host[sizeof(cfg.host)-1] = '\0';
214 } else {
215 /*
216 * Three cases. Either (a) there's a nonzero
217 * length string followed by an @, in which
218 * case that's user and the remainder is host.
219 * Or (b) there's only one string, not counting
220 * a potential initial @, and it exists in the
221 * saved-sessions database. Or (c) only one
222 * string and it _doesn't_ exist in the
223 * database.
224 */
225 char *r = strrchr(p, '@');
226 if (r == p) p++, r = NULL; /* discount initial @ */
227 if (r == NULL) {
228 /*
229 * One string.
230 */
231 do_defaults (p);
232 if (cfg.host[0] == '\0') {
233 /* No settings for this host; use defaults */
234 strncpy(cfg.host, p, sizeof(cfg.host)-1);
235 cfg.host[sizeof(cfg.host)-1] = '\0';
236 cfg.port = 22;
237 }
238 } else {
239 *r++ = '\0';
240 strncpy(cfg.username, p, sizeof(cfg.username)-1);
241 cfg.username[sizeof(cfg.username)-1] = '\0';
242 strncpy(cfg.host, r, sizeof(cfg.host)-1);
243 cfg.host[sizeof(cfg.host)-1] = '\0';
244 cfg.port = 22;
245 }
246 }
247 } else {
248 int len = sizeof(cfg.remote_cmd) - 1;
249 char *cp = cfg.remote_cmd;
250 int len2;
251
252 strncpy(cp, p, len); cp[len] = '\0';
253 len2 = strlen(cp); len -= len2; cp += len2;
254 while (--argc) {
255 if (len > 0)
256 len--, *cp++ = ' ';
257 strncpy(cp, *++argv, len); cp[len] = '\0';
258 len2 = strlen(cp); len -= len2; cp += len2;
259 }
260 cfg.nopty = TRUE; /* command => no terminal */
261 cfg.ldisc_term = TRUE; /* use stdin like a line buffer */
262 break; /* done with cmdline */
263 }
264 }
265 }
266
d8426c54 267 if (!*cfg.host) {
268 usage();
269 }
270 if (portnumber != -1)
271 cfg.port = portnumber;
272
67779be7 273 if (!*cfg.remote_cmd)
274 flags |= FLAG_INTERACTIVE;
275
12dc4ec0 276 /*
277 * Select protocol. This is farmed out into a table in a
278 * separate file to enable an ssh-free variant.
279 */
280 {
281 int i;
282 back = NULL;
283 for (i = 0; backends[i].backend != NULL; i++)
284 if (backends[i].protocol == cfg.protocol) {
285 back = backends[i].backend;
286 break;
287 }
288 if (back == NULL) {
289 fprintf(stderr, "Internal fault: Unsupported protocol found\n");
290 return 1;
291 }
292 }
293
294 /*
295 * Initialise WinSock.
296 */
297 winsock_ver = MAKEWORD(2, 0);
298 if (WSAStartup(winsock_ver, &wsadata)) {
299 MessageBox(NULL, "Unable to initialise WinSock", "WinSock Error",
300 MB_OK | MB_ICONEXCLAMATION);
301 return 1;
302 }
303 if (LOBYTE(wsadata.wVersion) != 2 || HIBYTE(wsadata.wVersion) != 0) {
304 MessageBox(NULL, "WinSock version is incompatible with 2.0",
305 "WinSock Error", MB_OK | MB_ICONEXCLAMATION);
306 WSACleanup();
307 return 1;
308 }
309
310 /*
311 * Start up the connection.
312 */
313 {
314 char *error;
315 char *realhost;
316
317 error = back->init (NULL, cfg.host, cfg.port, &realhost);
318 if (error) {
319 fprintf(stderr, "Unable to open connection:\n%s", error);
320 return 1;
321 }
322 }
323
324 netevent = CreateEvent(NULL, FALSE, FALSE, NULL);
325 stdinevent = CreateEvent(NULL, FALSE, FALSE, NULL);
326
6f34e365 327 GetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), &orig_console_mode);
328 SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), ENABLE_PROCESSED_INPUT);
12dc4ec0 329 outhandle = GetStdHandle(STD_OUTPUT_HANDLE);
330
331 /*
332 * Now we must send the back end oodles of stuff.
333 */
334 socket = back->socket();
335 /*
336 * Turn off ECHO and LINE input modes. We don't care if this
337 * call fails, because we know we aren't necessarily running in
338 * a console.
339 */
340 WSAEventSelect(socket, netevent, FD_READ | FD_CLOSE);
341 handles[0] = netevent;
342 handles[1] = stdinevent;
343 sending = FALSE;
344 while (1) {
345 int n;
346 n = WaitForMultipleObjects(2, handles, FALSE, INFINITE);
347 if (n == 0) {
348 WSANETWORKEVENTS things;
349 if (!WSAEnumNetworkEvents(socket, netevent, &things)) {
350 if (things.lNetworkEvents & FD_READ)
351 back->msg(0, FD_READ);
352 if (things.lNetworkEvents & FD_CLOSE) {
353 back->msg(0, FD_CLOSE);
354 break;
355 }
356 }
357 term_out();
358 if (!sending && back->sendok()) {
359 /*
360 * Create a separate thread to read from stdin.
361 * This is a total pain, but I can't find another
362 * way to do it:
363 *
364 * - an overlapped ReadFile or ReadFileEx just
365 * doesn't happen; we get failure from
366 * ReadFileEx, and ReadFile blocks despite being
367 * given an OVERLAPPED structure. Perhaps we
368 * can't do overlapped reads on consoles. WHY
369 * THE HELL NOT?
370 *
371 * - WaitForMultipleObjects(netevent, console)
372 * doesn't work, because it signals the console
373 * when _anything_ happens, including mouse
374 * motions and other things that don't cause
375 * data to be readable - so we're back to
376 * ReadFile blocking.
377 */
378 idata.event = stdinevent;
379 if (!CreateThread(NULL, 0, stdin_read_thread,
380 &idata, 0, &threadid)) {
381 fprintf(stderr, "Unable to create second thread\n");
382 exit(1);
383 }
384 sending = TRUE;
385 }
386 } else if (n == 1) {
387 if (idata.len > 0) {
388 back->send(idata.buffer, idata.len);
389 } else {
390 back->special(TS_EOF);
391 }
392 }
393 }
394 WSACleanup();
395 return 0;
396}