First attempt at a Unix port of Plink. Seems to basically work;
[u/mdw/putty] / unix / uxplink.c
1 /*
2 * PLink - a command-line (stdin/stdout) variant of PuTTY.
3 */
4
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <assert.h>
8 #include <stdarg.h>
9 #include <unistd.h>
10 #include <fcntl.h>
11 #include <termios.h>
12
13 /* More helpful version of the FD_SET macro, to also handle maxfd. */
14 #define FD_SET_MAX(fd, max, set) do { \
15 FD_SET(fd, &set); \
16 if (max < fd + 1) max = fd + 1; \
17 } while (0)
18
19 #define PUTTY_DO_GLOBALS /* actually _define_ globals */
20 #include "putty.h"
21 #include "storage.h"
22 #include "tree234.h"
23
24 #define MAX_STDIN_BACKLOG 4096
25
26 void fatalbox(char *p, ...)
27 {
28 va_list ap;
29 fprintf(stderr, "FATAL ERROR: ");
30 va_start(ap, p);
31 vfprintf(stderr, p, ap);
32 va_end(ap);
33 fputc('\n', stderr);
34 cleanup_exit(1);
35 }
36 void modalfatalbox(char *p, ...)
37 {
38 va_list ap;
39 fprintf(stderr, "FATAL ERROR: ");
40 va_start(ap, p);
41 vfprintf(stderr, p, ap);
42 va_end(ap);
43 fputc('\n', stderr);
44 cleanup_exit(1);
45 }
46 void connection_fatal(void *frontend, char *p, ...)
47 {
48 va_list ap;
49 fprintf(stderr, "FATAL ERROR: ");
50 va_start(ap, p);
51 vfprintf(stderr, p, ap);
52 va_end(ap);
53 fputc('\n', stderr);
54 cleanup_exit(1);
55 }
56 void cmdline_error(char *p, ...)
57 {
58 va_list ap;
59 fprintf(stderr, "plink: ");
60 va_start(ap, p);
61 vfprintf(stderr, p, ap);
62 va_end(ap);
63 fputc('\n', stderr);
64 exit(1);
65 }
66
67 struct termios orig_termios;
68
69 static Backend *back;
70 static void *backhandle;
71
72 char *x_get_default(char *key)
73 {
74 return NULL; /* this is a stub */
75 }
76 int term_ldisc(Terminal *term, int mode)
77 {
78 return FALSE;
79 }
80 void ldisc_update(void *frontend, int echo, int edit)
81 {
82 /* Update stdin read mode to reflect changes in line discipline. */
83 struct termios mode;
84
85 mode = orig_termios;
86
87 if (echo)
88 mode.c_lflag |= ECHO;
89 else
90 mode.c_lflag &= ~ECHO;
91
92 if (edit)
93 mode.c_lflag |= ISIG | ICANON;
94 else
95 mode.c_lflag &= ~(ISIG | ICANON);
96
97 tcsetattr(0, TCSANOW, &mode);
98 }
99
100 void cleanup_termios(void)
101 {
102 tcsetattr(0, TCSANOW, &orig_termios);
103 }
104
105 bufchain stdout_data, stderr_data;
106
107 void try_output(int is_stderr)
108 {
109 bufchain *chain = (is_stderr ? &stderr_data : &stdout_data);
110 int fd = (is_stderr ? 2 : 1);
111 void *senddata;
112 int sendlen, ret;
113
114 bufchain_prefix(chain, &senddata, &sendlen);
115 ret = write(fd, senddata, sendlen);
116 if (ret > 0)
117 bufchain_consume(chain, ret);
118 else if (ret < 0) {
119 perror(is_stderr ? "stderr: write" : "stdout: write");
120 exit(1);
121 }
122 }
123
124 int from_backend(void *frontend_handle, int is_stderr, char *data, int len)
125 {
126 int osize, esize;
127
128 assert(len > 0);
129
130 if (is_stderr) {
131 bufchain_add(&stderr_data, data, len);
132 try_output(1);
133 } else {
134 bufchain_add(&stdout_data, data, len);
135 try_output(0);
136 }
137
138 osize = bufchain_size(&stdout_data);
139 esize = bufchain_size(&stderr_data);
140
141 return osize + esize;
142 }
143
144 /*
145 * Short description of parameters.
146 */
147 static void usage(void)
148 {
149 printf("PuTTY Link: command-line connection utility\n");
150 printf("%s\n", ver);
151 printf("Usage: plink [options] [user@]host [command]\n");
152 printf(" (\"host\" can also be a PuTTY saved session name)\n");
153 printf("Options:\n");
154 printf(" -v show verbose messages\n");
155 printf(" -load sessname Load settings from saved session\n");
156 printf(" -ssh -telnet -rlogin -raw\n");
157 printf(" force use of a particular protocol (default SSH)\n");
158 printf(" -P port connect to specified port\n");
159 printf(" -l user connect with specified username\n");
160 printf(" -m file read remote command(s) from file\n");
161 printf(" -batch disable all interactive prompts\n");
162 printf("The following options only apply to SSH connections:\n");
163 printf(" -pw passw login with specified password\n");
164 printf(" -L listen-port:host:port Forward local port to "
165 "remote address\n");
166 printf(" -R listen-port:host:port Forward remote port to"
167 " local address\n");
168 printf(" -X -x enable / disable X11 forwarding\n");
169 printf(" -A -a enable / disable agent forwarding\n");
170 printf(" -t -T enable / disable pty allocation\n");
171 printf(" -1 -2 force use of particular protocol version\n");
172 printf(" -C enable compression\n");
173 printf(" -i key private key file for authentication\n");
174 exit(1);
175 }
176
177 int main(int argc, char **argv)
178 {
179 int sending;
180 int portnumber = -1;
181 int *sklist;
182 int socket;
183 int i, skcount, sksize, socketstate;
184 int connopen;
185 int exitcode;
186 void *logctx;
187 void *ldisc;
188
189 ssh_get_line = console_get_line;
190
191 sklist = NULL;
192 skcount = sksize = 0;
193 /*
194 * Initialise port and protocol to sensible defaults. (These
195 * will be overridden by more or less anything.)
196 */
197 default_protocol = PROT_SSH;
198 default_port = 22;
199
200 flags = FLAG_STDERR;
201 /*
202 * Process the command line.
203 */
204 do_defaults(NULL, &cfg);
205 default_protocol = cfg.protocol;
206 default_port = cfg.port;
207 {
208 /*
209 * Override the default protocol if PLINK_PROTOCOL is set.
210 */
211 char *p = getenv("PLINK_PROTOCOL");
212 int i;
213 if (p) {
214 for (i = 0; backends[i].backend != NULL; i++) {
215 if (!strcmp(backends[i].name, p)) {
216 default_protocol = cfg.protocol = backends[i].protocol;
217 default_port = cfg.port =
218 backends[i].backend->default_port;
219 break;
220 }
221 }
222 }
223 }
224 while (--argc) {
225 char *p = *++argv;
226 if (*p == '-') {
227 int ret = cmdline_process_param(p, (argc > 1 ? argv[1] : NULL), 1);
228 if (ret == -2) {
229 fprintf(stderr,
230 "plink: option \"%s\" requires an argument\n", p);
231 } else if (ret == 2) {
232 --argc, ++argv;
233 } else if (ret == 1) {
234 continue;
235 } else if (!strcmp(p, "-batch")) {
236 console_batch_mode = 1;
237 }
238 } else if (*p) {
239 if (!*cfg.host) {
240 char *q = p;
241 /*
242 * If the hostname starts with "telnet:", set the
243 * protocol to Telnet and process the string as a
244 * Telnet URL.
245 */
246 if (!strncmp(q, "telnet:", 7)) {
247 char c;
248
249 q += 7;
250 if (q[0] == '/' && q[1] == '/')
251 q += 2;
252 cfg.protocol = PROT_TELNET;
253 p = q;
254 while (*p && *p != ':' && *p != '/')
255 p++;
256 c = *p;
257 if (*p)
258 *p++ = '\0';
259 if (c == ':')
260 cfg.port = atoi(p);
261 else
262 cfg.port = -1;
263 strncpy(cfg.host, q, sizeof(cfg.host) - 1);
264 cfg.host[sizeof(cfg.host) - 1] = '\0';
265 } else {
266 char *r;
267 /*
268 * Before we process the [user@]host string, we
269 * first check for the presence of a protocol
270 * prefix (a protocol name followed by ",").
271 */
272 r = strchr(p, ',');
273 if (r) {
274 int i, j;
275 for (i = 0; backends[i].backend != NULL; i++) {
276 j = strlen(backends[i].name);
277 if (j == r - p &&
278 !memcmp(backends[i].name, p, j)) {
279 default_protocol = cfg.protocol =
280 backends[i].protocol;
281 portnumber =
282 backends[i].backend->default_port;
283 p = r + 1;
284 break;
285 }
286 }
287 }
288
289 /*
290 * Three cases. Either (a) there's a nonzero
291 * length string followed by an @, in which
292 * case that's user and the remainder is host.
293 * Or (b) there's only one string, not counting
294 * a potential initial @, and it exists in the
295 * saved-sessions database. Or (c) only one
296 * string and it _doesn't_ exist in the
297 * database.
298 */
299 r = strrchr(p, '@');
300 if (r == p)
301 p++, r = NULL; /* discount initial @ */
302 if (r == NULL) {
303 /*
304 * One string.
305 */
306 Config cfg2;
307 do_defaults(p, &cfg2);
308 if (cfg2.host[0] == '\0') {
309 /* No settings for this host; use defaults */
310 strncpy(cfg.host, p, sizeof(cfg.host) - 1);
311 cfg.host[sizeof(cfg.host) - 1] = '\0';
312 cfg.port = default_port;
313 } else {
314 cfg = cfg2;
315 cfg.remote_cmd_ptr = cfg.remote_cmd;
316 }
317 } else {
318 *r++ = '\0';
319 strncpy(cfg.username, p, sizeof(cfg.username) - 1);
320 cfg.username[sizeof(cfg.username) - 1] = '\0';
321 strncpy(cfg.host, r, sizeof(cfg.host) - 1);
322 cfg.host[sizeof(cfg.host) - 1] = '\0';
323 cfg.port = default_port;
324 }
325 }
326 } else {
327 char *command;
328 int cmdlen, cmdsize;
329 cmdlen = cmdsize = 0;
330 command = NULL;
331
332 while (argc) {
333 while (*p) {
334 if (cmdlen >= cmdsize) {
335 cmdsize = cmdlen + 512;
336 command = srealloc(command, cmdsize);
337 }
338 command[cmdlen++]=*p++;
339 }
340 if (cmdlen >= cmdsize) {
341 cmdsize = cmdlen + 512;
342 command = srealloc(command, cmdsize);
343 }
344 command[cmdlen++]=' '; /* always add trailing space */
345 if (--argc) p = *++argv;
346 }
347 if (cmdlen) command[--cmdlen]='\0';
348 /* change trailing blank to NUL */
349 cfg.remote_cmd_ptr = command;
350 cfg.remote_cmd_ptr2 = NULL;
351 cfg.nopty = TRUE; /* command => no terminal */
352
353 break; /* done with cmdline */
354 }
355 }
356 }
357
358 if (!*cfg.host) {
359 usage();
360 }
361
362 /*
363 * Trim leading whitespace off the hostname if it's there.
364 */
365 {
366 int space = strspn(cfg.host, " \t");
367 memmove(cfg.host, cfg.host+space, 1+strlen(cfg.host)-space);
368 }
369
370 /* See if host is of the form user@host */
371 if (cfg.host[0] != '\0') {
372 char *atsign = strchr(cfg.host, '@');
373 /* Make sure we're not overflowing the user field */
374 if (atsign) {
375 if (atsign - cfg.host < sizeof cfg.username) {
376 strncpy(cfg.username, cfg.host, atsign - cfg.host);
377 cfg.username[atsign - cfg.host] = '\0';
378 }
379 memmove(cfg.host, atsign + 1, 1 + strlen(atsign + 1));
380 }
381 }
382
383 /*
384 * Perform command-line overrides on session configuration.
385 */
386 cmdline_run_saved();
387
388 /*
389 * Trim a colon suffix off the hostname if it's there.
390 */
391 cfg.host[strcspn(cfg.host, ":")] = '\0';
392
393 /*
394 * Remove any remaining whitespace from the hostname.
395 */
396 {
397 int p1 = 0, p2 = 0;
398 while (cfg.host[p2] != '\0') {
399 if (cfg.host[p2] != ' ' && cfg.host[p2] != '\t') {
400 cfg.host[p1] = cfg.host[p2];
401 p1++;
402 }
403 p2++;
404 }
405 cfg.host[p1] = '\0';
406 }
407
408 if (!*cfg.remote_cmd_ptr)
409 flags |= FLAG_INTERACTIVE;
410
411 /*
412 * Select protocol. This is farmed out into a table in a
413 * separate file to enable an ssh-free variant.
414 */
415 {
416 int i;
417 back = NULL;
418 for (i = 0; backends[i].backend != NULL; i++)
419 if (backends[i].protocol == cfg.protocol) {
420 back = backends[i].backend;
421 break;
422 }
423 if (back == NULL) {
424 fprintf(stderr,
425 "Internal fault: Unsupported protocol found\n");
426 return 1;
427 }
428 }
429
430 /*
431 * Select port.
432 */
433 if (portnumber != -1)
434 cfg.port = portnumber;
435
436 sk_init();
437
438 /*
439 * Start up the connection.
440 */
441 {
442 char *error;
443 char *realhost;
444 /* nodelay is only useful if stdin is a terminal device */
445 int nodelay = cfg.tcp_nodelay && isatty(0);
446
447 error = back->init(NULL, &backhandle, cfg.host, cfg.port,
448 &realhost, nodelay);
449 if (error) {
450 fprintf(stderr, "Unable to open connection:\n%s", error);
451 return 1;
452 }
453 logctx = log_init(NULL);
454 back->provide_logctx(backhandle, logctx);
455 ldisc = ldisc_create(NULL, back, backhandle, NULL);
456 sfree(realhost);
457 }
458 connopen = 1;
459
460 /*
461 * Set up the initial console mode. We don't care if this call
462 * fails, because we know we aren't necessarily running in a
463 * console.
464 */
465 tcgetattr(0, &orig_termios);
466 atexit(cleanup_termios);
467 ldisc_update(NULL, 1, 1);
468 sending = FALSE;
469
470 while (1) {
471 fd_set rset, wset, xset;
472 int maxfd;
473 int rwx;
474 int ret;
475
476 FD_ZERO(&rset);
477 FD_ZERO(&wset);
478 FD_ZERO(&xset);
479 maxfd = 0;
480
481 if (connopen && !sending &&
482 back->socket(backhandle) != NULL &&
483 back->sendok(backhandle) &&
484 back->sendbuffer(backhandle) < MAX_STDIN_BACKLOG) {
485 /* If we're OK to send, then try to read from stdin. */
486 FD_SET_MAX(0, maxfd, rset);
487 }
488
489 if (bufchain_size(&stdout_data) > 0) {
490 /* If we have data for stdout, try to write to stdout. */
491 FD_SET_MAX(1, maxfd, wset);
492 }
493
494 if (bufchain_size(&stderr_data) > 0) {
495 /* If we have data for stderr, try to write to stderr. */
496 FD_SET_MAX(2, maxfd, wset);
497 }
498
499 /* Count the currently active sockets. */
500 i = 0;
501 for (socket = first_socket(&socketstate, &rwx); socket >= 0;
502 socket = next_socket(&socketstate, &rwx)) i++;
503
504 /* Expand the sklist buffer if necessary. */
505 if (i > sksize) {
506 sksize = i + 16;
507 sklist = srealloc(sklist, sksize * sizeof(*sklist));
508 }
509
510 /*
511 * Add all currently open sockets to the select sets, and
512 * store them in sklist as well.
513 */
514 skcount = 0;
515 for (socket = first_socket(&socketstate, &rwx); socket >= 0;
516 socket = next_socket(&socketstate, &rwx)) {
517 sklist[skcount++] = socket;
518 if (rwx & 1)
519 FD_SET_MAX(socket, maxfd, rset);
520 if (rwx & 2)
521 FD_SET_MAX(socket, maxfd, wset);
522 if (rwx & 4)
523 FD_SET_MAX(socket, maxfd, xset);
524 }
525
526 ret = select(maxfd, &rset, &wset, &xset, NULL);
527
528 if (ret < 0) {
529 perror("select");
530 exit(1);
531 }
532
533 for (i = 0; i < skcount; i++) {
534 socket = sklist[i];
535 if (FD_ISSET(socket, &rset))
536 select_result(socket, 1);
537 if (FD_ISSET(socket, &wset))
538 select_result(socket, 2);
539 if (FD_ISSET(socket, &xset))
540 select_result(socket, 4);
541 }
542
543 if (FD_ISSET(0, &rset)) {
544 char buf[4096];
545 int ret;
546
547 if (connopen && back->socket(backhandle) != NULL) {
548 ret = read(0, buf, sizeof(buf));
549 if (ret < 0) {
550 perror("stdin: read");
551 exit(1);
552 } else if (ret == 0) {
553 back->special(backhandle, TS_EOF);
554 sending = FALSE; /* send nothing further after this */
555 } else {
556 back->send(backhandle, buf, ret);
557 }
558 }
559 }
560
561 if (FD_ISSET(1, &wset)) {
562 try_output(0);
563 }
564
565 if (FD_ISSET(2, &wset)) {
566 try_output(1);
567 }
568
569 if ((!connopen || back->socket(backhandle) == NULL) &&
570 bufchain_size(&stdout_data) == 0 &&
571 bufchain_size(&stderr_data) == 0)
572 break; /* we closed the connection */
573 }
574 exitcode = back->exitcode(backhandle);
575 if (exitcode < 0) {
576 fprintf(stderr, "Remote process exit code unavailable\n");
577 exitcode = 1; /* this is an error condition */
578 }
579 return exitcode;
580 }