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