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