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