tmcc.c 15 KB
Newer Older
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1 2
/*
 * EMULAB-COPYRIGHT
3
 * Copyright (c) 2000-2003 University of Utah and the Flux Group.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
4 5
 * All rights reserved.
 */
6 7 8
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
9 10
#include <sys/un.h>
#include <sys/fcntl.h>
11 12 13 14 15 16
#include <stdio.h>
#include <errno.h>
#include <syslog.h>
#include <unistd.h>
#include <signal.h>
#include <stdarg.h>
Mike Hibler's avatar
Mike Hibler committed
17 18
#include <stdlib.h>
#include <string.h>
19 20 21
#include <sys/time.h>
#include <time.h>
#include <assert.h>
22 23 24 25
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
26
#include "decls.h"
27
#include "ssl.h"
28 29 30
#ifndef STANDALONE
#include "config.h"
#endif
31
#undef  BOSSNODE
32 33 34 35
#ifndef BOSSNODE
#include <resolv.h>
#endif

36 37
#ifndef KEYFILE
#define KEYFILE		"/etc/emulab.pkey"
38
#endif
39
#define UNIXSOCKVAR	"TMCCUNIXPATH"
40

41 42 43 44 45
/*
 * We search a couple of dirs for the bossnode file.
 */
static char *bossnodedirs[] = {
	"/etc/testbed",
46
	"/etc/emulab",
47 48 49 50 51 52
	"/etc/rc.d/testbed",
	"/usr/local/etc/testbed",
	"/usr/local/etc/emulab",
	0
};

53 54 55 56 57 58 59
/*
 * Need to try several ports cause of firewalling. 
 */
static int portlist[] = {
	TBSERVER_PORT,
	TBSERVER_PORT2,
};
60 61 62 63 64 65
/* Locals */
static int	numports = sizeof(portlist)/sizeof(int);
static int	debug = 0;
static char    *logfile = NULL;

/* Forward decls */
66
static int	getbossnode(char **, int *);
67 68 69 70 71
static int	doudp(char *, int, struct in_addr, int);
static int	dotcp(char *, int, struct in_addr);
static int	dounix(char *, int, char *);
static void	beproxy(char *, struct in_addr, char *);
static int	dooutput(int, char *, int);
72

73
char *usagestr = 
74 75
 "usage: tmcc [options] <command>\n"
 " -d		   Turn on debugging\n"
76
 " -s server	   Specify a tmcd server to connect to\n"
77
 " -p portnum	   Specify a port number to connect to\n"
78
 " -v versnum	   Specify a version number for tmcd\n"
79
 " -n vnodeid	   Specify the vnodeid\n"
80
 " -k keyfile	   Specify the private keyfile\n"
81
 " -u		   Use UDP instead of TCP\n"
82
 " -l path	   Use named unix domain socket instead of TCP\n"
83
 " -t timeout	   Timeout waiting for the controller.\n"
84
 " -x path	   Be a tmcc proxy, using the named unix domain socket\n"
85 86 87 88 89 90 91 92 93
 "\n";

void
usage()
{
	fprintf(stderr, usagestr);
	exit(1);
}

94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
/*
 * We cannot let remote nodes hang, but they can be slow. If we get connected
 * we give it an extra timeout, and if we make any progress at all, keep
 * giving it extra timeouts.
 */
static int connected = 0;
static int progress  = 0;
static int waitfor   = 0;

static void
tooktoolong()
{
	static int	lastprogress = 0;

	/* If we made progress, keep going (reset timer too) */
	if (connected && progress > lastprogress) {
		lastprogress = progress;
		alarm(waitfor);
		return;
	}

	fprintf(stderr, "Timed out cause there was no progress!\n");
	exit(-1);
}
118

Mike Hibler's avatar
Mike Hibler committed
119
int
120 121
main(int argc, char **argv)
{
122
	int			n, ch;
123 124
	struct hostent		*he;
	struct in_addr		serverip;
125
	char			buf[MYBUFSIZE], *bp;
126
	FILE			*fp;
127 128 129 130 131 132 133 134 135 136
	int			useudp    = 0;
	char			*unixpath = NULL;
	char			*bossnode = NULL;
	int			version   = CURRENT_VERSION;
	char			*vnodeid  = NULL;
	char			*keyfile  = NULL;
	char			*privkey  = NULL;
	char			*proxypath= NULL;

	while ((ch = getopt(argc, argv, "v:s:p:un:t:k:x:l:do:")) != -1)
137
		switch(ch) {
138 139 140
		case 'd':
			debug++;
			break;
141
		case 'p':
142 143
			portlist[0] = atoi(optarg);
			numports    = 1;
144
			break;
145 146 147
		case 's':
			bossnode = optarg;
			break;
148 149 150
		case 'n':
			vnodeid = optarg;
			break;
151 152 153
		case 'k':
			keyfile = optarg;
			break;
154 155 156
		case 'v':
			version = atoi(optarg);
			break;
157 158 159
		case 't':
			waitfor = atoi(optarg);
			break;
160 161 162
		case 'u':
			useudp = 1;
			break;
163 164 165 166 167 168 169 170 171
		case 'x':
			proxypath = optarg;
			break;
		case 'l':
			unixpath  = optarg;
			break;
		case 'o':
			logfile  = optarg;
			break;
172 173 174 175
		default:
			usage();
		}

176
	argv += optind;
177
	argc -= optind;
178
	if (!proxypath && (argc < 1 || argc > 5)) {
179
		usage();
180
	}
181 182
	if (unixpath && proxypath)
		usage();
183

184
	/*
185 186 187
	 * Allow for environment to specify a unix socket, which is a
	 * connection to a tmcc proxy. Note that a specific -l option
	 * overrides the environment variable.
188
	 */
189 190
	if (!unixpath && !proxypath && (bp = getenv(UNIXSOCKVAR)))
		unixpath = bp;
191

192 193 194 195
	if (unixpath && (keyfile || bossnode)) {
		fprintf(stderr,
			"You may not use the -k or -s with the -l option\n");
		usage();
196
	}
197

198 199 200 201 202 203 204 205 206 207
	if (!bossnode) {
		int	port = 0;
		
		getbossnode(&bossnode, &port);
		/* In other words, do not override command line port spec! */
		if (port && numports > 1) {
			portlist[0] = port;
			numports    = 1;
		}
	}
208
	
209 210 211 212 213 214 215 216
	he = gethostbyname(bossnode);
	if (he)
		memcpy((char *)&serverip, he->h_addr, he->h_length);
	else {
		fprintf(stderr, "gethostbyname(%s) failed\n", bossnode); 
		exit(1);
	}

217 218 219 220 221 222 223 224
	/*
	 * Handle built-in "bossinfo" command
	 */
	if (!proxypath && (strcmp(argv[0], "bossinfo") == 0)) {
		printf("%s %s\n", bossnode, inet_ntoa(serverip));
		exit(0);
	}

225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
	/*
	 * Grab the key. Its not an error if we do not find it.
	 */
	if (keyfile) {
		/* Well, if one was specifed it has to exist. */
		if (access(keyfile, R_OK) < 0) {
			perror("keyfile"); 
			exit(1);
		}
	}
	else
		keyfile = KEYFILE;

	if ((fp = fopen(keyfile, "r")) != NULL) {
	    if (fgets(buf, sizeof(buf), fp)) {
		if ((bp = strchr(buf, '\n')))
		    *bp = (char) NULL;
		privkey = strdup(buf);
	    }
	    fclose(fp);
	}

247 248 249 250 251 252 253 254 255 256 257 258 259
	/*
	 * Build up the command request string.
	 */
	buf[0] = '\0';
	
	/* Tack on vnodeid */
	if (vnodeid) {
		sprintf(&buf[strlen(buf)], "VNODEID=%s ", vnodeid);
	}

	/* Tack on privkey */
	if (privkey) {
		sprintf(&buf[strlen(buf)], "PRIVKEY=%s ", privkey);
260 261
	}

262
	/*
263 264
	 * If specified udp with unixpath, then pass through a UDP flag
	 * to the proxy, which will do what it thinks is appropriate.
265
	 */
266 267 268 269 270 271 272 273 274 275
	if (useudp && unixpath) {
		sprintf(&buf[strlen(buf)], "USEUDP=1 ");
		useudp = 0;
	}

	/*
	 * In proxy mode ...
	 */
	if (proxypath) {
		beproxy(proxypath, serverip, buf);
276 277 278
		exit(0);
	}

279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
	/* Tack on version number */
	sprintf(&buf[strlen(buf)], "VERSION=%d ", version);

	/*
	 * Since we've gone through a getopt() pass, argv[0] is now the
	 * first argument
	 */
	n = strlen(buf);
	while (argc && n < sizeof(buf)) {
		n += snprintf(&buf[n], sizeof(buf) - (n + 1), "%s ", argv[0]);
		argc--;
		argv++;
	}
	if (n >= sizeof(buf)) {
		fprintf(stderr, "Command too large!\n");
		exit(-1);
	}
	buf[n] = '\0';

	/*
	 * When a timeout is requested, just let the signal kill us.
	 */
	if (waitfor) {
302
		signal(SIGALRM, tooktoolong);
303
		alarm(waitfor);
304
	}
305 306 307 308 309 310 311 312 313 314 315 316 317

	if (useudp)
		n = doudp(buf, fileno(stdout), serverip, portlist[0]);
	else if (unixpath)
		n = dounix(buf, fileno(stdout), unixpath);
	else
		n = dotcp(buf, fileno(stdout), serverip);
	exit(n);
}

/*
 * Find the bossnode name if one was not specified on the command line.
 */
318 319
static int
getbossnode(char **bossnode, int *portp)
320 321
{
#ifdef BOSSNODE
322 323
	*bossnode = strdup(BOSSNODE);
	return 0;
324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344
#else
	struct hostent	*he;
	FILE		*fp;
	char		buf[BUFSIZ], **cp = bossnodedirs, *bp;

	/*
	 * Search for the file.
	 */
	while (*cp) {
		sprintf(buf, "%s/%s", *cp, BOSSNODE_FILENAME);

		if (access(buf, R_OK) == 0)
			break;
		cp++;
	}
	if (*cp) {
		if ((fp = fopen(buf, "r")) != NULL) {
			if (fgets(buf, sizeof(buf), fp)) {
				if ((bp = strchr(buf, '\n')))
					*bp = (char) NULL;
				fclose(fp);
345 346 347 348 349 350 351 352 353
				/*
				 * Look for port spec
				 */
				if ((bp = strchr(buf, ':'))) {
					*bp++  = NULL;
					*portp = atoi(bp);
				}
				*bossnode = strdup(buf);
				return 0;
354 355 356 357 358 359 360 361 362 363 364
			}
			fclose(fp);
		}
	}
	
	/*
	 * Nameserver goo 
	 */
	res_init();
	he = gethostbyaddr((char *)&_res.nsaddr.sin_addr,
			   sizeof(struct in_addr), AF_INET);
365 366 367 368 369
	if (he && he->h_name) 
		*bossnode = strdup(he->h_name);
	else
		*bossnode = strdup("UNKNOWN");
	return 0;
370
#endif
371 372 373 374 375 376 377 378 379 380 381 382
}

/*
 * TCP version, which uses ssl if compiled in.
 */
static int
dotcp(char *data, int outfd, struct in_addr serverip)
{
	int			n, sock, cc;
	struct sockaddr_in	name;
	char			*bp, buf[MYBUFSIZE];
	
383 384 385
#ifdef  WITHSSL
	if (tmcd_client_sslinit()) {
		printf("SSL initialization failed!\n");
386
		return -1;
387 388
	}
#endif
389
	while (1) {
390 391 392 393 394
		for (n = 0; n < numports; n++) {
			/* Create socket from which to read. */
			sock = socket(AF_INET, SOCK_STREAM, 0);
			if (sock < 0) {
				perror("creating stream socket:");
395
				return -1;
396
			}
397

398 399 400 401
			/* Create name. */
			name.sin_family = AF_INET;
			name.sin_addr   = serverip;
			name.sin_port   = htons(portlist[n]);
402

403 404 405 406 407 408 409
			if (CONNECT(sock, (struct sockaddr *) &name,
				    sizeof(name)) == 0) {
				goto foundit;
			}
			if (errno != ECONNREFUSED) {
				perror("connecting stream socket");
				CLOSE(sock);
410
				return -1;
411
			}
412
			CLOSE(sock);
413
		}
414 415 416
		if (debug) 
			fprintf(stderr,
				"Connection to TMCD refused. Waiting ...\n");
417
		sleep(10);
418
	}
419
 foundit:
420
	connected = 1;
421

422 423
	n = 1;
	if (setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, &n, sizeof(n)) < 0) {
424
		perror("setsockopt SO_KEEPALIVE");
425
		goto bad;
426
	}
427

428
	/*
429
	 * Write the command to the socket and wait for the response.
430
	 */
431 432
	bp = data;
	n  = strlen(data);
433
	while (n) {
434
		if ((cc = WRITE(sock, bp, n)) <= 0) {
435 436
			if (cc < 0) {
				perror("Writing to socket:");
437
				goto bad;
438 439
			}
			fprintf(stderr, "write aborted");
440
			goto bad;
441 442 443 444 445 446
		}
		bp += cc;
		n  -= cc;
	}

	while (1) {
447
		if ((cc = READ(sock, buf, sizeof(buf) - 1)) <= 0) {
448 449
			if (cc < 0) {
				perror("Reading from socket:");
450
				goto bad;
451 452 453
			}
			break;
		}
454
		progress += cc;
455 456
		if (dooutput(outfd, buf, cc) < 0)
			goto bad;
457
	}
458
	CLOSE(sock);
459
	return 0;
460 461
 bad:
	CLOSE(sock);
462
	return -1;
463 464
}

Mike Hibler's avatar
Mike Hibler committed
465 466 467
/*
 * Not very robust, send a single request, read a single reply. 
 */
468 469
static int
doudp(char *data, int outfd, struct in_addr serverip, int portnum)
Mike Hibler's avatar
Mike Hibler committed
470 471 472
{
	int			sock, length, n, cc;
	struct sockaddr_in	name, client;
473
	char			buf[MYBUFSIZE];
Mike Hibler's avatar
Mike Hibler committed
474 475 476 477 478

	/* Create socket from which to read. */
	sock = socket(AF_INET, SOCK_DGRAM, 0);
	if (sock < 0) {
		perror("creating dgram socket:");
479
		return -1;
Mike Hibler's avatar
Mike Hibler committed
480 481 482 483 484
	}

	/* Create name. */
	name.sin_family = AF_INET;
	name.sin_addr   = serverip;
485
	name.sin_port   = htons(portnum);
Mike Hibler's avatar
Mike Hibler committed
486 487 488 489

	/*
	 * Write the command to the socket and wait for the response
	 */
490 491
	n  = strlen(data);
	cc = sendto(sock, data, n, 0, (struct sockaddr *)&name, sizeof(name));
Mike Hibler's avatar
Mike Hibler committed
492 493 494
	if (cc != n) {
		if (cc < 0) {
			perror("Writing to socket:");
495
			return -1;
Mike Hibler's avatar
Mike Hibler committed
496 497
		}
		fprintf(stderr, "short write (%d != %d)\n", cc, n);
498
		return -1;
Mike Hibler's avatar
Mike Hibler committed
499
	}
500
	connected = 1;
Mike Hibler's avatar
Mike Hibler committed
501

502
	cc = recvfrom(sock, buf, sizeof(buf) - 1, 0,
Mike Hibler's avatar
Mike Hibler committed
503
		      (struct sockaddr *)&client, &length);
504
	progress += cc;
505

Mike Hibler's avatar
Mike Hibler committed
506 507
	if (cc < 0) {
		perror("Reading from socket:");
508
		return -1;
Mike Hibler's avatar
Mike Hibler committed
509
	}
510 511 512 513 514
	close(sock);
	if (dooutput(outfd, buf, cc) < 0)
		return -1;
	return 0;
}
Mike Hibler's avatar
Mike Hibler committed
515

516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545
/*
 * Unix domain version.
 */
static int
dounix(char *data, int outfd, char *unixpath)
{
#ifdef  linux
	fprintf(stderr, "unix domain socket mode not supported on linux!\n");
	return -1;
#else
	int			n, sock, cc, length;
	struct sockaddr_un	sunaddr;
	char			*bp, buf[MYBUFSIZE];

	sunaddr.sun_family = AF_UNIX;
	strlcpy(sunaddr.sun_path, unixpath, sizeof(sunaddr.sun_path));
	sunaddr.sun_len = length = SUN_LEN(&sunaddr)+1;

	/* Create socket from which to read. */
	sock = socket(AF_UNIX, SOCK_STREAM, 0);
	if (sock < 0) {
		perror("creating stream socket:");
		return -1;
	}

	if (connect(sock, (struct sockaddr *) &sunaddr, length) < 0) {
		perror("connecting unix domain socket");
		close(sock);
		return -1;
	}
546
	connected = 1;
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573

	/*
	 * Write the command to the socket and wait for the response.
	 */
	bp = data;
	n  = strlen(data);
	while (n) {
		if ((cc = write(sock, bp, n)) <= 0) {
			if (cc < 0) {
				perror("Writing to socket:");
				goto bad;
			}
			fprintf(stderr, "write aborted");
			goto bad;
		}
		bp += cc;
		n  -= cc;
	}

	while (1) {
		if ((cc = read(sock, buf, sizeof(buf) - 1)) <= 0) {
			if (cc < 0) {
				perror("Reading from socket:");
				goto bad;
			}
			break;
		}
574
		progress += cc;
575 576 577 578 579 580
		if (dooutput(outfd, buf, cc) < 0)
			goto bad;
	}
	close(sock);
	return 0;
 bad:
Mike Hibler's avatar
Mike Hibler committed
581
	close(sock);
582 583
	return -1;
#endif
Mike Hibler's avatar
Mike Hibler committed
584
}
585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715

/*
 * Be a proxy. Basically, listen for requests from the localhost and
 * forward. At the moment this is strictly for the benefit of jailed
 * environments on FreeBSD, hence we use a unix domain socket to provide
 * the security (the socket is visible to the jail only).
 *
 * Note that only TCP traffic goes through the proxy. The jailed tmcc
 * can speak directly to tmcd over udp since it never returns anything
 * sensitive that way.
 */
static void
beproxy(char *localpath, struct in_addr serverip, char *partial)
{
#ifdef  linux
	fprintf(stderr, "proxy mode not supported on linux!\n");
	exit(-1);
#else
	int			sock, newsock, cc, length;
	struct sockaddr_un	sunaddr, client;
	char			command[MYBUFSIZE], buf[MYBUFSIZE];
	char			*bp, *cp;
	
	sock = socket(AF_UNIX, SOCK_STREAM, 0);
	if (sock < 0) {
		perror("creating unix domain socket");
		exit(-1);
	}

	unlink(localpath);
	memset(&sunaddr, 0, sizeof(sunaddr));
	sunaddr.sun_family = AF_UNIX;
	strlcpy(sunaddr.sun_path, localpath, sizeof(sunaddr.sun_path));
	sunaddr.sun_len = SUN_LEN(&sunaddr) + 1;
	if (bind(sock, (struct sockaddr *)&sunaddr, sunaddr.sun_len) < 0) {
		perror("binding unix domain socket");
		exit(-1);
	}
	if (listen(sock, 5) < 0) {
		perror("listen on unix domain socket");
		exit(-1);
	}

	if (logfile) {
		int	fd;

		/*
		 * Detach, but do not daemonize. The caller tracks the
		 * pid and kills us. Needs to be fixed at some point ...
		 */
		if ((fd = open("/dev/null", O_RDONLY, 0)) < 0) {
			perror("Could not open /dev/null");
			exit(-1);
		}
		(void)dup2(fd, STDIN_FILENO);
		if (fd != STDIN_FILENO)
			(void)close(fd);
		
		if ((fd = open(logfile, O_WRONLY|O_CREAT|O_APPEND,0640)) < 0) {
			perror("Could not open logfile");
			exit(-1);
		}
		(void)dup2(fd, STDOUT_FILENO);
		(void)dup2(fd, STDERR_FILENO);
		if (fd > STDERR_FILENO)
			(void)close(fd);
	}

	/*
	 * Wait for TCP connections.
	 */
	while (1) {
		int	rval, useudp = 0;
		
		length  = sizeof(client);
		newsock = accept(sock, (struct sockaddr *)&client, &length);
		if (newsock < 0) {
			perror("accepting Unix domain connection");
			continue;
		}

		/*
		 * Read in the command request.
		 */
		if ((cc = read(newsock, buf, sizeof(buf) - 1)) <= 0) {
			if (cc < 0)
				perror("Reading Unix domain request");
			fprintf(stderr, "Unix domain connection aborted\n");
			close(newsock);
			continue;
		}
		buf[cc] = '\0';

		/*
		 * Do not allow PRIVKEY or VNODE options to be specified
		 * by the proxy user. 
		 */
		strcpy(command, partial);
		bp = cp = buf;
		while ((bp = strsep(&cp, " ")) != NULL) {
			if (strstr(bp, "PRIVKEY=") ||
			    strstr(bp, "VNODE=")) {
				if (debug)
					fprintf(stderr,
						"Ignoring option: %s\n", bp);
				continue;
			}
			if (strstr(bp, "USEUDP=1")) {
				useudp = 1;
				continue;
			}
			strcat(command, bp);
			strcat(command, " ");
		}

		if (debug) {
			fprintf(stderr, "%s\n", command);
			fflush(stderr);
		}

		if (useudp)
			rval = doudp(command, newsock, serverip, portlist[0]);
		else
			rval = dotcp(command, newsock, serverip);
		
		if (rval < 0 && debug) {
			fprintf(stderr, "Request failed!\n");
			fflush(stderr);
		}
		close(newsock);
	}
Mike Hibler's avatar
Mike Hibler committed
716
#endif
717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744
}

/*
 * Little helper to write tmcd response to output. 
 */
static int
dooutput(int fd, char *buf, int len)
{
	int		cc, count = len;

	if (debug) {
		write(fileno(stderr), buf, len);
	}
	
	while (count) {
		if ((cc = write(fd, buf, count)) <= 0) {
			if (cc < 0) {
				perror("Writing to output stream:");
				return -1;
			}
			fprintf(stderr, "write to socket aborted");
			return -1;
		}
		buf   += cc;
		count -= cc;
	}
	return len;
}