tmcc.c 29.6 KB
Newer Older
Leigh Stoller's avatar
Leigh Stoller committed
1
/*
2
 * Copyright (c) 2000-2014, 2018 University of Utah and the Flux Group.
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
 * 
 * {{{EMULAB-LICENSE
 * 
 * This file is part of the Emulab network testbed software.
 * 
 * This file is free software: you can redistribute it and/or modify it
 * under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or (at
 * your option) any later version.
 * 
 * This file is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
 * License for more details.
 * 
 * You should have received a copy of the GNU Affero General Public License
 * along with this file.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * }}}
Leigh Stoller's avatar
Leigh Stoller committed
22
 */
23

24
#include <sys/types.h>
25 26
#include <sys/socket.h>
#include <netinet/in.h>
27 28
#include <sys/un.h>
#include <sys/fcntl.h>
29 30 31 32 33
#include <stdio.h>
#include <errno.h>
#include <syslog.h>
#include <unistd.h>
#include <signal.h>
34
#ifdef __CYGWIN__
35 36 37 38
#  include <w32api/windef.h>
#  include <w32api/winbase.h>
#  include <w32api/iphlpapi.h>
  /* XXX: May no longer be required. */
39 40
  typedef _sig_func_ptr sig_t;
#endif /* __CYGWIN__ */
41
#include <stdarg.h>
Mike Hibler's avatar
Mike Hibler committed
42
#include <stdlib.h>
43
#include <ctype.h>
Mike Hibler's avatar
Mike Hibler committed
44
#include <string.h>
45
#include <sys/time.h>
46
#include <sys/stat.h>
47 48
#include <time.h>
#include <assert.h>
49
#include <sys/types.h>
50 51 52
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
53
#include "tmcd.h"
54
#include "ssl.h"
55
#ifndef STANDALONE
56
#  include "config.h"
57
#endif
58 59 60 61 62 63 64
/* 
 * XXX: This seems strange.  Unless something modifies this file, the
 * next "if" statment will always be true.
 */
#undef  BOSSNODE
#if !defined(BOSSNODE)
#  include <resolv.h>
65
#endif
66
#include <setjmp.h>
67 68 69
#ifdef linux
#define strlcpy strncpy
#endif
70

71
#ifndef KEYFILE
72
#  define KEYFILE		"/etc/emulab.pkey"
73
#endif
74

75 76 77 78 79
/*
 * We search a couple of dirs for the bossnode file.
 */
static char *bossnodedirs[] = {
	"/etc/testbed",
80
	"/etc/emulab",
81 82 83 84 85 86
	"/etc/rc.d/testbed",
	"/usr/local/etc/testbed",
	"/usr/local/etc/emulab",
	0
};

87 88 89 90 91 92 93
/*
 * Need to try several ports cause of firewalling. 
 */
static int portlist[] = {
	TBSERVER_PORT,
	TBSERVER_PORT2,
};
94 95 96 97
/* Locals */
static int	numports = sizeof(portlist)/sizeof(int);
static int	debug = 0;
static char    *logfile = NULL;
98
static int	do_proxy_retries = 1;
99 100

/* Forward decls */
101
static int	getbossnode(char **, int *);
102 103 104
static int	doudp(char *, int, struct in_addr, int);
static int	dotcp(char *, int, struct in_addr);
static int	dounix(char *, int, char *);
105 106 107
static void	beudproxy(char *, struct in_addr, char *);
static void	beidproxy(struct in_addr, int, struct in_addr, char *);
static void	beproxy(int, int, struct in_addr, char *);
108
static int	dooutput(int, char *, int);
Mike Hibler's avatar
Mike Hibler committed
109
static int	rewritecommand(char *, char *, char **);
110

111
char *usagestr = 
112 113
 "usage: tmcc [options] <command>\n"
 " -d		   Turn on debugging\n"
114
 " -s server	   Specify a tmcd server to connect to\n"
115
 " -p portnum	   Specify a port number to connect to\n"
116
 " -v versnum	   Specify a version number for tmcd\n"
117
 " -n vnodeid	   Specify the vnodeid\n"
118
 " -k keyfile	   Specify the private keyfile\n"
119
 " -u		   Use UDP instead of TCP\n"
120
 " -l path	   Use named unix domain socket instead of TCP\n"
121
 " -t timeout	   Timeout waiting for the controller.\n"
122 123
 " -x path	   Be a unix domain proxy listening on the named socket\n"
 " -X ip:port	   Be an inet domain proxy listening on the given IP:port\n"
124
 " -o logfile      Specify log file name for -x option\n"
125
 " -f datafile     Extra stuff to send to tmcd (tcp mode only)\n"
126
 " -i              Do not use SSL protocol\n"
127
 " -T              Use the TPM for SSL negotiation\n"
128
 " -R              Do not retry failed proxy request forwarding\n"
129 130 131 132 133
 "\n";

void
usage()
{
134
	fprintf(stderr, "%s", usagestr);
135 136 137
	exit(1);
}

138 139 140 141 142 143 144 145
/*
 * 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;
146
static sigjmp_buf progtimo;
147

148 149 150 151 152 153 154 155 156 157
/*
 * do{tcp,udp} all open a socket for sending a request and getting a reply.
 * If we timeout during one of those functions, that socket will be left open.
 * For a normal use of tmcc, we will immediately exit if a timeout happens so
 * this is not a problem. However, in the proxy case, a timeout is not fatal,
 * so we will have to close the socket. Note that the proxy does not use
 * dounix, so we do not augment that function.
 */
volatile int reqsock = -1;

158
static void
159
tooktoolong(void)
160 161 162 163 164 165 166 167 168 169
{
	static int	lastprogress = 0;

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

170
	siglongjmp(progtimo, 1);
171
}
172

173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
/*
 * We do not want to fail outright if we cannot resolve. Lets retry
 * a few times. This is imperfect of course; the caller should deal
 * with this, but most cases can be dealt with more easily here.
 */
struct hostent *
gethostbyname_retry(const char *name)
{
	int		count = 5;

	while (count) {
		struct hostent *he = gethostbyname(name);
		if (he)
			return he;
		if (debug) {
			herror("gethostbyname failed");
		}
		count--;
		if (count)
			sleep(5);
	}
	return (struct hostent *) NULL;
}

struct hostent *
gethostbyaddr_retry(const void *addr, socklen_t len, int type)
{
	int		count = 5;

	while (count) {
		struct hostent *he = gethostbyaddr(addr, len, type);
		if (he)
			return he;
		if (debug) {
			herror("gethostbyaddr failed");
		}
		count--;
		if (count)
			sleep(5);
	}
	return (struct hostent *) NULL;
}
#define gethostbyname gethostbyname_retry
#define gethostbyaddr gethostbyaddr_retry

Mike Hibler's avatar
Mike Hibler committed
218
int
219 220
main(int argc, char **argv)
{
221
	int			n, ch;
222 223
	struct hostent		*he;
	struct in_addr		serverip;
224
	char			buf[MAXTMCDPACKET], *bp;
225
	FILE			*fp;
226 227
	volatile int		useudp    = 0;
	char			* volatile unixpath = NULL;
228 229 230 231 232 233
	char			*bossnode = NULL;
	int			version   = CURRENT_VERSION;
	char			*vnodeid  = NULL;
	char			*keyfile  = NULL;
	char			*privkey  = NULL;
	char			*proxypath= NULL;
234 235
	struct in_addr		proxyaddr;
	int			proxyport = 0;
236
	char			*datafile = NULL;
237

238
	while ((ch = getopt(argc, argv, "v:s:p:un:t:k:x:X:l:do:if:TR")) != -1)
239
		switch(ch) {
240 241 242
		case 'd':
			debug++;
			break;
243
		case 'p':
244 245
			portlist[0] = atoi(optarg);
			numports    = 1;
246
			break;
247 248 249
		case 's':
			bossnode = optarg;
			break;
250 251 252
		case 'n':
			vnodeid = optarg;
			break;
253 254 255
		case 'k':
			keyfile = optarg;
			break;
256 257 258
		case 'v':
			version = atoi(optarg);
			break;
259 260 261
		case 't':
			waitfor = atoi(optarg);
			break;
262 263 264
		case 'u':
			useudp = 1;
			break;
265 266 267
		case 'x':
			proxypath = optarg;
			break;
268 269 270 271 272 273 274 275 276
		case 'X':
		{
			char *ap, *pp = optarg;
			ap = strsep(&pp, ":");
			if (!inet_aton(*ap ? ap : "127.0.0.1", &proxyaddr))
				usage();
			proxyport = pp ? atoi(pp) : TBSERVER_PORT+1;
			break;
		}
277 278 279 280 281 282
		case 'l':
			unixpath  = optarg;
			break;
		case 'o':
			logfile  = optarg;
			break;
283 284 285
		case 'f':
			datafile  = optarg;
			break;
286 287 288 289 290
		case 'i':
#ifdef WITHSSL
			nousessl = 1;
#endif
			break;
291 292 293
		case 'T':
			usetpm = 1;
			break;
294 295 296
		case 'R':
			do_proxy_retries = 0;
			break;
297 298 299 300
		default:
			usage();
		}

301
	argv += optind;
302
	argc -= optind;
303 304 305 306 307 308
	if (!(proxypath || proxyport) && (argc < 1 || argc > 5)) {
		usage();
	}
	if (unixpath && proxypath) {
		fprintf(stderr,
			"Cannot be both proxy server (-x) and client (-l)\n");
309
		usage();
310
	}
311 312 313 314

	if (proxypath && proxyport) {
		fprintf(stderr,
			"Cannot be both unix (-x) and inet (-X) domain proxy\n");
315
		usage();
316
	}
317

318 319 320
	if (useudp && datafile) {
		fprintf(stderr,
			"Cannot send a file (-f) in UDP mode (-u)\n");
321
		usage();
322
	}
323

324 325 326 327
	if (unixpath && (keyfile || bossnode)) {
		fprintf(stderr,
			"You may not use the -k or -s with the -l option\n");
		usage();
328
	}
329 330 331 332 333 334 335 336 337 338 339
	if (usetpm && nousessl) {
		fprintf(stderr, "You cannot use -T and -i together\n");
		usage();
	}
#ifndef	WITHSSL
	if (usetpm) {
		fprintf(stderr,
		    "You used -T but compiled without WITHSSL.  Bailing!\n");
		exit(1);
	}
#endif
340 341 342
	if( (! unixpath) && (0==access("/etc/emulab/emulab-privkey", R_OK)) ) {
		keyfile = strdup("/etc/emulab/emulab-privkey");
	}
343 344 345 346 347 348 349
#ifdef WITHSSL
	/*
	 * Brutal hack for inner elab; see rc.inelab.
	 */
	if (getenv("TMCCNOSSL") != NULL)
		nousessl = 1;
#endif
350 351 352 353 354 355 356 357 358 359
	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;
		}
	}
360

361 362 363 364 365 366 367 368
	he = gethostbyname(bossnode);
	if (he)
		memcpy((char *)&serverip, he->h_addr, he->h_length);
	else {
		fprintf(stderr, "gethostbyname(%s) failed\n", bossnode); 
		exit(1);
	}

369 370 371
	/*
	 * Handle built-in "bossinfo" command
	 */
372 373
	if (!(proxypath || proxyport) &&
	    argc > 0 && (strcmp(argv[0], "bossinfo") == 0)) {
374 375 376 377
		printf("%s %s\n", bossnode, inet_ntoa(serverip));
		exit(0);
	}

378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393
	/*
	 * 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')))
394
		    *bp = '\0';
395 396 397 398 399
		privkey = strdup(buf);
	    }
	    fclose(fp);
	}

400 401 402 403 404 405 406
	/*
	 * Build up the command request string.
	 */
	buf[0] = '\0';
	
	/* Tack on vnodeid */
	if (vnodeid) {
407 408 409 410 411 412
		if (proxypath || proxyport) {
			sprintf(&buf[strlen(buf)], "PROXYFOR=%s ", vnodeid);
		}
		else {
			sprintf(&buf[strlen(buf)], "VNODEID=%s ", vnodeid);
		}
413 414 415 416 417
	}

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

420
	/*
421 422
	 * If specified udp with unixpath, then pass through a UDP flag
	 * to the proxy, which will do what it thinks is appropriate.
423
	 */
424 425 426 427 428 429 430 431 432
	if (useudp && unixpath) {
		sprintf(&buf[strlen(buf)], "USEUDP=1 ");
		useudp = 0;
	}

	/*
	 * In proxy mode ...
	 */
	if (proxypath) {
433 434 435 436 437
		beudproxy(proxypath, serverip, buf);
		exit(0);
	}
	if (proxyport != 0) {
		beidproxy(proxyaddr, proxyport, serverip, buf);
438 439 440
		exit(0);
	}

441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457
	/* 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);
	}
458 459 460 461 462 463 464 465 466 467 468 469 470 471 472
	if (!useudp && datafile) {
		int len;
		
		if ((fp = fopen(datafile, "r")) == NULL) {
			perror("accessing datafile");
			exit(-1);
		}
		len = fread(&buf[n], sizeof(char), sizeof(buf) - (n + 1), fp);
		if (!len) {
			perror("reading datafile");
			exit(-1);
		}
		n += len;
		fclose(fp);
	}
473 474 475
	buf[n] = '\0';

	/*
476
	 * When a timeout is requested, setup the alarm and die if it triggers.
477 478
	 */
	if (waitfor) {
479 480 481 482 483 484
		if (sigsetjmp(progtimo, 1) != 0) {
			fprintf(stderr,
				"Timed out because there was no progress!\n");
			exit(-1);
		}
		signal(SIGALRM, (sig_t)tooktoolong);
485
		alarm(waitfor);
486
	}
487 488 489 490 491 492 493

	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);
494 495
	if (waitfor)
		alarm(0);
496
	fflush(stderr);
497 498 499 500 501 502
	exit(n);
}

/*
 * Find the bossnode name if one was not specified on the command line.
 */
503 504
static int
getbossnode(char **bossnode, int *portp)
505 506
{
#ifdef BOSSNODE
507 508
	*bossnode = strdup(BOSSNODE);
	return 0;
509 510 511 512
#else
	FILE		*fp;
	char		buf[BUFSIZ], **cp = bossnodedirs, *bp;

513 514 515
	/*
	 * Brutal hack for inner elab; see rc.inelab.
	 */
516 517 518 519 520 521 522
	if ((bp = getenv("BOSSNAME")) != NULL) {
		strcpy(buf, bp);
		
		/*
		 * Look for port spec
		 */
		if ((bp = strchr(buf, ':'))) {
523
			*bp++  = '\0';
524 525 526 527 528
			*portp = atoi(bp);
		}
		*bossnode = strdup(buf);
		return 0;
	}
529
	
530 531 532 533 534 535 536 537 538 539 540 541 542 543
	/*
	 * 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')))
544
					*bp = '\0';
545
				fclose(fp);
546 547 548 549
				/*
				 * Look for port spec
				 */
				if ((bp = strchr(buf, ':'))) {
550
					*bp++  = '\0'; 
551 552 553 554
					*portp = atoi(bp);
				}
				*bossnode = strdup(buf);
				return 0;
555 556 557 558
			}
			fclose(fp);
		}
	}
559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606
#ifdef __CYGWIN__
/*
 * Cygwin discourages the use of resolv.conf and provides no mechanism to 
 * automatically generate it.  We instead use of the "IP Helper" 
 * Windows API functions to get the IP address of the DNS server. This host
 * is assumed to also be the boss node.
 *
 * A good chunk of the code here was lifted from examples in the API reference.
 */
	{
		FIXED_INFO *pFixedInfo;
		struct in_addr dnsAddr;
		struct hostent *he;
		char *pIPAddrStr;
		unsigned long ulOutBufLen;
		int dwRetVal;

		/* Typical Windows trick for right-sizing the output buffer. */
		pFixedInfo = (FIXED_INFO *) malloc(sizeof (FIXED_INFO));
		ulOutBufLen = sizeof (FIXED_INFO);
		if (GetNetworkParams(pFixedInfo, &ulOutBufLen) == 
		    ERROR_BUFFER_OVERFLOW) {
			free(pFixedInfo);
			pFixedInfo = (FIXED_INFO *) malloc(ulOutBufLen);
		}

		/* Actually perform the call to get network configuration. */
		if ((dwRetVal = GetNetworkParams(pFixedInfo, &ulOutBufLen)) != 
		    NO_ERROR) {
			fprintf(stderr, 
				"GetNetworkParams failed with error %08x\n", 
				dwRetVal);
			if (pFixedInfo) {
				free(pFixedInfo);
			}
		} else {
			/* 
			 * The IP address of the DNS server is presented as a 
			 * decimal dot notation string. Convert it and do a 
			 * reverse lookup to get the hostname.
			 */
			pIPAddrStr = pFixedInfo->DnsServerList.IpAddress.String;
			if (pIPAddrStr && inet_aton(pIPAddrStr, &dnsAddr)) {
				he = gethostbyaddr((char *)&dnsAddr,
						   sizeof(struct in_addr), 
						   AF_INET);
				if (he && he->h_name) {
					*bossnode = strdup(he->h_name);
607 608
				} else {
				  herror("gethostbyaddr failed");
609
				}
610 611 612 613
			} else {
			  fprintf(stderr,
				  "No value returned for DNS server or can't" 
				  " convert to network byte representation.\n");
614 615 616 617 618 619 620 621 622 623 624 625 626 627
			}

			if (pFixedInfo) {
				free(pFixedInfo);
				pFixedInfo = NULL;
			}
		}

		if (!bossnode) {
			*bossnode = strdup("UNKNOWN");
		}
		return 0;
	}
#else
628 629 630 631 632 633 634 635 636 637 638 639 640 641
	{
		/*
		 * Nameserver goo 
		 */
		struct hostent	*he;
		res_init();
		he = gethostbyaddr((char *)&_res.nsaddr.sin_addr,
				   sizeof(struct in_addr), AF_INET);
		if (he && he->h_name) 
			*bossnode = strdup(he->h_name);
		else
			*bossnode = strdup("UNKNOWN");
		return 0;
	}
642
#endif /* __CYGWIN__ */
643
	*bossnode = strdup("UNKNOWN");
644
	return 0;
645
#endif /* BOSSNODE */
646 647 648 649 650 651 652 653 654 655 656
}

/*
 * 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];
657
	int			redirectlimit = 5;
658
	
659
#ifdef  WITHSSL
660
	if (!nousessl && tmcd_client_sslinit()) {
661
		printf("SSL initialization failed!\n");
662
		return -1;
663 664
	}
#endif
665
 again:
666
	while (1) {
667 668 669 670
		for (n = 0; n < numports; n++) {
			/* Create socket from which to read. */
			sock = socket(AF_INET, SOCK_STREAM, 0);
			if (sock < 0) {
671
				perror("creating stream socket");
672
				return -1;
673
			}
674

675 676 677
			/* XXX see comment on declaration of reqsock */
			reqsock = sock;

678 679 680 681
			/* Create name. */
			name.sin_family = AF_INET;
			name.sin_addr   = serverip;
			name.sin_port   = htons(portlist[n]);
682

683 684 685 686
			if (CONNECT(sock, (struct sockaddr *) &name,
				    sizeof(name)) == 0) {
				goto foundit;
			}
687 688 689 690 691 692
			if (errno == ECONNRESET || errno == ETIMEDOUT
			    || errno == EAGAIN || errno == EINTR) {
				fprintf(stderr,"retrying failed connect (%s)\n",
					strerror(errno));
			}
			else if (errno != ECONNREFUSED) {
693 694
				perror("connecting stream socket");
				CLOSE(sock);
695
				reqsock = -1;
696
				return -1;
697
			}
698
			CLOSE(sock);
699
			reqsock = -1;
700
		}
701 702 703
		if (debug) 
			fprintf(stderr,
				"Connection to TMCD refused. Waiting ...\n");
704
		sleep(10);
705
	}
706
 foundit:
707
	connected = 1;
708

709
	n = 1;
710
	if (setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, (void *)&n, sizeof(n)) < 0) {
711
		perror("setsockopt SO_KEEPALIVE");
712
		goto bad;
713
	}
714

715
	/*
716
	 * Write the command to the socket and wait for the response.
717
	 */
718 719
	bp = data;
	n  = strlen(data);
720
	while (n) {
721
		if ((cc = WRITE(sock, bp, n)) <= 0) {
722
			if (cc < 0) {
723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743
				if (errno == EAGAIN || errno == ECONNRESET
				    || errno == EINTR || errno == EPIPE) {
					if (bp == data) {
						fprintf(stderr,
							"write error (nothing "
							"written): %s; retrying\n",
							strerror(errno));
						CLOSE(sock);
						reqsock = -1;
						goto again;
					}
					else {
						fprintf(stderr,
							"write error (sent %ld "
							" bytes): %s, not "
							" retrying\n",
							bp-data,strerror(errno));
					}
				}
				else
				    perror("Writing to socket");
744
				goto bad;
745 746
			}
			fprintf(stderr, "write aborted");
747
			goto bad;
748 749 750 751
		}
		bp += cc;
		n  -= cc;
	}
752 753 754 755 756 757 758 759 760
	if (! isssl) {
		/*
		 * Send EOF to server so it knows it has all the data.
		 * SSL mode takes care of this for us by making sure the
		 * the server gets all the data when it reads. Still, its
		 * a terrible way to do this. 
		 */
		shutdown(sock, SHUT_WR);
	}
761 762

	while (1) {
763
		if ((cc = READ(sock, buf, sizeof(buf) - 1)) <= 0) {
764
			if (cc < 0) {
765
				perror("Reading from socket");
766
				goto bad;
767 768 769
			}
			break;
		}
770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791
		if (strncmp(buf, "REDIRECT=", strlen("REDIRECT=")) == 0) {
			struct hostent	*he;

			redirectlimit--;
			if (redirectlimit == 0) {
				fprintf(stderr, "Redirect limit reached\n");
				goto bad;
			}
			buf[cc] = '\0';
			if (rewritecommand(buf, data, &bp)) {
				goto bad;
			}
			he = gethostbyname(bp);
			if (he)
				memcpy((char *)&serverip,
				       he->h_addr, he->h_length);
			else {
				fprintf(stderr,
					"gethostbyname(%s) failed\n", buf); 
				goto bad;
			}
			CLOSE(sock);
792
			reqsock = -1;
793 794
			goto again;
		}
795
		progress += cc;
796 797
		if (dooutput(outfd, buf, cc) < 0)
			goto bad;
798
	}
799
	CLOSE(sock);
800
	reqsock = -1;
801
	return 0;
802 803
 bad:
	CLOSE(sock);
804
	reqsock = -1;
805
	return -1;
806 807
}

Mike Hibler's avatar
Mike Hibler committed
808 809 810
/*
 * Not very robust, send a single request, read a single reply. 
 */
811 812
static int
doudp(char *data, int outfd, struct in_addr serverip, int portnum)
Mike Hibler's avatar
Mike Hibler committed
813
{
Mike Hibler's avatar
Mike Hibler committed
814
	int			sock, n, cc;
Mike Hibler's avatar
Mike Hibler committed
815
	struct sockaddr_in	name, client;
Mike Hibler's avatar
Mike Hibler committed
816
	socklen_t		length;
817
	char			buf[MYBUFSIZE];
Mike Hibler's avatar
Mike Hibler committed
818 819 820 821

	/* Create socket from which to read. */
	sock = socket(AF_INET, SOCK_DGRAM, 0);
	if (sock < 0) {
822
		perror("creating dgram socket");
823
		return -1;
Mike Hibler's avatar
Mike Hibler committed
824 825
	}

826 827 828
	/* XXX see comment on declaration of reqsock */
	reqsock = sock;

Mike Hibler's avatar
Mike Hibler committed
829 830 831
	/* Create name. */
	name.sin_family = AF_INET;
	name.sin_addr   = serverip;
832
	name.sin_port   = htons(portnum);
Mike Hibler's avatar
Mike Hibler committed
833 834 835 836

	/*
	 * Write the command to the socket and wait for the response
	 */
837 838
	n  = strlen(data);
	cc = sendto(sock, data, n, 0, (struct sockaddr *)&name, sizeof(name));
Mike Hibler's avatar
Mike Hibler committed
839
	if (cc != n) {
840
		if (cc < 0)
841
			perror("Writing to socket");
842 843 844
		else
			fprintf(stderr, "short write (%d != %d)\n", cc, n);
		close(sock);
845
		reqsock = -1;
846
		return -1;
Mike Hibler's avatar
Mike Hibler committed
847
	}
848
	connected = 1;
Mike Hibler's avatar
Mike Hibler committed
849

Mike Hibler's avatar
Mike Hibler committed
850
	length = sizeof(client);
851
	cc = recvfrom(sock, buf, sizeof(buf) - 1, 0,
Mike Hibler's avatar
Mike Hibler committed
852 853
		      (struct sockaddr *)&client, &length);
	if (cc < 0) {
854
		perror("Reading from socket");
855
		close(sock);
856
		reqsock = -1;
857
		return -1;
Mike Hibler's avatar
Mike Hibler committed
858
	}
859
	close(sock);
860
	reqsock = -1;
861
	progress += cc;
862 863 864 865
	if (dooutput(outfd, buf, cc) < 0)
		return -1;
	return 0;
}
Mike Hibler's avatar
Mike Hibler committed
866

867 868 869 870 871 872 873 874 875 876 877 878
/*
 * Unix domain version.
 */
static int
dounix(char *data, int outfd, char *unixpath)
{
	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));
879
	length = SUN_LEN(&sunaddr)+1;
880
#if !defined(__CYGWIN__) && !defined(linux)
881 882
	sunaddr.sun_len = length;
#  endif /* __CYGWIN__ */
883 884 885 886

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

891 892 893 894 895 896 897
	/*
	 * Retry if the unixpath does not exist. Caller must use timeout option.
	 */
	while (1) {
		if (connect(sock, (struct sockaddr *) &sunaddr, length) == 0)
			break;

898
		if (errno != ENOENT && errno != ECONNREFUSED) {
899 900 901 902 903 904 905 906
			perror("connecting unix domain socket");
			close(sock);
			return -1;
		}

		if (debug) 
			fprintf(stderr,
				"Connection to TMCD refused. Waiting ...\n");
907
		sleep(1);
908
	}
909
	connected = 1;
910 911 912 913 914 915 916 917 918

	/*
	 * 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) {
919
				perror("Writing to socket");
920 921 922 923 924 925 926 927 928 929 930 931
				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) {
932
				perror("Reading from socket");
933 934 935 936
				goto bad;
			}
			break;
		}
937
		progress += cc;
938 939 940 941 942 943
		if (dooutput(outfd, buf, cc) < 0)
			goto bad;
	}
	close(sock);
	return 0;
 bad:
Mike Hibler's avatar
Mike Hibler committed
944
	close(sock);
945
	return -1;
Mike Hibler's avatar
Mike Hibler committed
946
}
947 948 949 950 951 952 953 954 955 956 957 958

/*
 * 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
959
beudproxy(char *localpath, struct in_addr serverip, char *partial)
960
{
961
	int			sock;
Mike Hibler's avatar
Mike Hibler committed
962
	socklen_t		length;
963
	struct sockaddr_un	sunaddr;
964
	
965 966 967
	/* don't let a client kill us */
	signal(SIGPIPE, SIG_IGN);

968 969 970 971 972 973 974 975 976 977
	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));
978
	length = SUN_LEN(&sunaddr) + 1;
979
#if !defined(__CYGWIN__) && !defined(linux)
980
	sunaddr.sun_len = length;
981
#endif /* __CYGWIN__ */
982
	if (bind(sock, (struct sockaddr *)&sunaddr, length) < 0) {
983 984 985
		perror("binding unix domain socket");
		exit(-1);
	}
986
	chmod(localpath, S_IRWXU|S_IRWXG|S_IRWXO);
987

988 989 990 991 992
	if (listen(sock, 5) < 0) {
		perror("listen on unix domain socket");
		exit(-1);
	}

993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056
	beproxy(sock, -1, serverip, partial);
}

static void
beidproxy(struct in_addr ip, int port, struct in_addr serverip, char *partial)
{
	int			tcpsock, udpsock;
	socklen_t		length;
	struct sockaddr_in	name;

	/* don't let a client kill us */
	signal(SIGPIPE, SIG_IGN);

	/* get a TCP socket */
	tcpsock = socket(AF_INET, SOCK_STREAM, 0);
	if (tcpsock < 0) {
		perror("creating TCP socket");
		exit(-1);
	}

	name.sin_family = AF_INET;
	name.sin_addr = ip;
	name.sin_port = htons(port);
	length = sizeof(name);
	if (bind(tcpsock, (struct sockaddr *)&name, length) < 0) {
		perror("binding TCP socket");
		exit(-1);
	}

	if (listen(tcpsock, 5) < 0) {
		perror("listen on TCP socket");
		exit(-1);
	}

	/* and a UDP socket */
	udpsock = socket(AF_INET, SOCK_DGRAM, 0);
	if (udpsock < 0) {
		perror("creating UDP socket");
		exit(-1);
	}

	name.sin_family = AF_INET;
	name.sin_addr = ip;
	name.sin_port = htons(port);
	length = sizeof(name);
	if (bind(udpsock, (struct sockaddr *)&name, length) < 0) {
		perror("binding UDP socket");
		exit(-1);
	}
	beproxy(tcpsock, udpsock, serverip, partial);
}

static int proxymode = 0;

static void
beproxy(int tcpsock, int udpsock, struct in_addr serverip, char *partial)
{
	int			newsock, cc;
	struct sockaddr_in	client;
	socklen_t		length;
	char			command[MAXTMCDPACKET], buf[MAXTMCDPACKET];
	char			*bp, *cp;
	fd_set			rfds;
	int			fdcount = 0;
1057
	int			retries = 0;
1058 1059
	
	proxymode = 1;
1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084
	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);
	}

1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096
	FD_ZERO(&rfds);
	if (tcpsock >= 0) {
		FD_SET(tcpsock, &rfds);
		fdcount = tcpsock;
	}
	if (udpsock >= 0) {
		FD_SET(udpsock, &rfds);
		if (udpsock > fdcount)
			fdcount = udpsock;
	}
	fdcount++;

1097
	/*
1098
	 * Wait for messages.
1099 1100
	 */
	while (1) {
1101
		int	rval;
1102
		volatile int usingudp = 0;
1103
		fd_set	fds;
1104
		
1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119
		fds = rfds;
		rval = select(fdcount, &fds, NULL, NULL, NULL);
		if (rval < 0) {
			if (errno == EINTR)
				continue;
			perror("proxy: select failed");
			exit(1);
		}

		/*
		 * Yes, we only handle one request per loop, even if both
		 * FDs were ready.  This is potentially unfair to UDP
		 * clients but there really shouldn't be much UDP traffic.
		 */
		if (tcpsock >= 0 && FD_ISSET(tcpsock, &fds)) {
1120
			retries = 0;
1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132
			/*
			 * Accept and read the message
			 */
			length  = sizeof(client);
			newsock = accept(tcpsock, (struct sockaddr *)&client,
					 &length);
			if (newsock < 0) {
				perror("proxy: accepting connection");
				continue;
			}
			cc = read(newsock, buf, sizeof(buf) - 1);
		} else if (udpsock >= 0 && FD_ISSET(udpsock, &fds)) {
1133
			retries = 0;
1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152
			/*
			 * Read the message and create a reply socket
			 */
			length = sizeof(client);
			cc = recvfrom(udpsock, buf, sizeof(buf) - 1, 0,
				      (struct sockaddr *)&client, &length);
			if (cc > 0) {
				newsock = socket(AF_INET, SOCK_DGRAM, 0);
				if (newsock < 0) {
					perror("creating UDP reply socket");
					continue;
				}
				if (connect(newsock,
					    (struct sockaddr *)&client,
					    length) < 0) {
					perror("connecting UDP reply socket");
					close(newsock);
					continue;
				}
1153
				usingudp = 1;
1154 1155 1156 1157 1158 1159
			} else
				newsock = -1;
		} else {
			fprintf(stderr,
				"proxy: select returned with no fd!\n");
			sleep(5);
1160 1161 1162 1163
			continue;
		}

		/*
1164
		 * Check read
1165
		 */
1166
		if (cc <= 0) {
1167
			if (cc < 0)
1168 1169 1170 1171
				perror("proxy: reading request");
			fprintf(stderr, "proxy: connection aborted\n");
			if (newsock >= 0)
				close(newsock);
1172 1173 1174 1175 1176
			continue;
		}
		buf[cc] = '\0';

		/*
1177
		 * Do not allow PRIVKEY or VNODEID options to be specified
1178 1179 1180 1181 1182 1183
		 * by the proxy user. 
		 */
		strcpy(command, partial);
		bp = cp = buf;
		while ((bp = strsep(&cp, " ")) != NULL) {
			if (strstr(bp, "PRIVKEY=") ||
1184
			    strstr(bp, "VNODEID="))
1185 1186
				continue;
			if (strstr(bp, "USEUDP=1")) {
1187
				usingudp = 1;
1188 1189 1190 1191 1192 1193 1194
				continue;
			}
			strcat(command, bp);
			strcat(command, " ");
		}

		if (debug) {
1195
			fprintf(stderr, "%sREQ: %s\n",
1196
				usingudp ? "UDP " : "TCP ", command);
1197 1198 1199
			fflush(stderr);
		}

1200 1201 1202
		/*
		 * Set a timeout for the server-side operation
		 */
1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263
	retry:
		if (retries) {
			int count = 10;
			/*
			 * If we are retrying, check to see if we have a
			 * new incoming request, and quit retrying if we
			 * do.  In the udp case, we cannot know if the
			 * client has given up on us.  In the tcp case,
			 * we can see if we get a 0-length read and then
			 * give up, so we expand the select rfds to
			 * handle that.  Note, either a new tcp OR udp
			 * request will scuttle our retry attempts, due
			 * to the nature of this loop!
			 */
			fprintf(stderr, "Request failed, will retry (%d)!\n",
				retries);
			rval = 0;
			while (!rval && count--) {
				fd_set retry_rfds;
				int retry_fdcount = 0;
				struct timeval notime = { 1, 0 };
				struct timespec timerem = { 0, 0 };
				FD_ZERO(&retry_rfds);
				if (tcpsock >= 0) {
					FD_SET(tcpsock, &retry_rfds);
					retry_fdcount = tcpsock;
				}
				if (udpsock >= 0) {
					FD_SET(udpsock, &retry_rfds);
					if (udpsock > retry_fdcount)
						retry_fdcount = udpsock;
				}
				if (!usingudp && newsock >= 0) {
					FD_SET(newsock, &retry_rfds);
					if (newsock > retry_fdcount)
						retry_fdcount = newsock;
				}
				retry_fdcount++;

				rval = select(retry_fdcount, &retry_rfds,
					      NULL, NULL, &notime);
				if (rval > 0) {
					if ((tcpsock >= 0
					     && FD_ISSET(tcpsock, &retry_rfds))
					    || (udpsock >= 0
						&& FD_ISSET(udpsock, &retry_rfds))) {
						fprintf(stderr,
							"new request; halting "
							" proxy retry (%d)\n",
							retries);
						close(newsock);
						retries = 0;
						continue;
					}
				}
				timerem.tv_nsec = notime.tv_usec * 1000;
				nanosleep(&timerem,NULL);
			}
			if (retries == 0)
				continue;
		}
1264 1265 1266
		if (waitfor) {
			if (sigsetjmp(progtimo, 1) != 0) {
				fprintf(stderr,
1267 1268
					"Server %s request timeout on: %s\n",
					usingudp ? "UDP" : "TCP", command);
1269 1270
				if (do_proxy_retries)
					goto retry_init;
1271 1272
				if (newsock >= 0)
					close(newsock);
1273 1274 1275 1276 1277 1278 1279 1280 1281 1282
				if (reqsock >= 0) {
					fprintf(stderr,
						"Closing service socket %d\n",
						reqsock);
					if (usingudp)
						close(reqsock);
					else
						CLOSE(reqsock);
					reqsock = -1;
				}
1283 1284 1285 1286 1287
				continue;
			}
			signal(SIGALRM, (sig_t)tooktoolong);
			alarm(waitfor);
		}
1288
		if (usingudp)
1289 1290 1291
			rval = doudp(command, newsock, serverip, portlist[0]);
		else
			rval = dotcp(command, newsock, serverip);
1292 1293
		if (waitfor)
			alarm(0);
1294 1295 1296 1297
		if (rval < 0 && debug) {
			fprintf(stderr, "Request failed!\n");
			fflush(stderr);
		}
1298 1299 1300 1301 1302
		if (rval < 0 && do_proxy_retries) {
		retry_init:
			++retries;
			goto retry;
		}
1303 1304
		if (newsock >= 0)
			close(newsock);
1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316
	}
}

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

	if (debug) {
1317 1318 1319
		if (proxymode)
			fprintf(stderr, "REP: ");
		fwrite(buf, 1, len, stderr);
1320 1321 1322 1323 1324
	}
	
	while (count) {
		if ((cc = write(fd, buf, count)) <= 0) {
			if (cc < 0) {
1325
				perror("Writing to output stream");
1326 1327 1328 1329 1330 1331 1332 1333 1334 1335
				return -1;
			}
			fprintf(stderr, "write to socket aborted");
			return -1;
		}
		buf   += cc;
		count -= cc;
	}
	return len;
}
1336 1337 1338 1339 1340 1341 1342 1343 1344

static int
rewritecommand(char *redirect, char *command, char **server)
{
	char	*bp;
	char	buf[MAXTMCDPACKET];
			
	bp = strchr(redirect, '\n');
	if (bp)
1345
		*bp = '\0';
1346 1347 1348 1349 1350 1351 1352 1353 1354
	bp = strchr(redirect, '=');
	if (!bp)
		return -1;
	bp++;
	*server = bp;

	bp = strchr(bp, ':');
	if (!bp)
		return 0;
1355
	*bp++ = '\0';
1356 1357 1358 1359 1360 1361 1362 1363 1364 1365

	sprintf(buf, "VNODEID=%s ", bp);

	bp = command;
	if (strncmp(bp, "VNODEID=", strlen("VNODEID=")) == 0) {
		bp = strchr(bp, ' ');
		if (!bp)
			return -1;
		bp++;
	}
1366
	strncat(buf, bp, sizeof(buf) - strlen(buf) - 1);
1367 1368 1369 1370
	strcpy(command, buf);
	fprintf(stderr, "%s, %s\n", command, *server);
	return 0;
}