capture.c 32.2 KB
Newer Older
Leigh Stoller's avatar
Leigh Stoller committed
1 2
/*
 * EMULAB-COPYRIGHT
3
 * Copyright (c) 2000-2004 University of Utah and the Flux Group.
Leigh Stoller's avatar
Leigh Stoller committed
4
 * All rights reserved.
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
 */

/*
 * Testbed note:  This code has developed over the last several
 * years in RCS.  This is an import of the current version of
 * capture from the /usr/src/utah RCS repository into the testbed,
 * with some new hacks to port it to Linux.
 *
 * - dga, 10/10/2000
 */

/*
 * A LITTLE hack to record output from a tty device to a file, and still
 * have it available to tip using a pty/tty pair.
 */
20 21

#define SAFEMODE
22 23 24 25 26 27 28 29 30
	
#include <sys/param.h>

#include <stdio.h>
#include <ctype.h>
#include <strings.h>
#include <syslog.h>
#include <termios.h>
#include <errno.h>
31 32
#include <stdlib.h>
#include <stdarg.h>
33 34 35 36 37 38 39 40 41

#include <sys/param.h>
#include <sys/file.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <signal.h>
#include <sys/ioctl.h>
#include <sys/termios.h>
42 43 44 45 46
#ifdef USESOCKETS
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
47 48
#include <setjmp.h>
#include <netdb.h>
49 50 51 52
#ifdef WITHSSL
#include <openssl/ssl.h>
#include <openssl/err.h>
#endif /* WITHSSL */
53
#include "config.h"
54
#endif /* USESOCKETS */
55
#include "capdecls.h"
56 57 58 59 60

#define geterr(e)	strerror(e)

void quit(int);
void reinit(int);
61
void newrun(int);
62
void terminate(int);
63
void cleanup(void);
64 65 66
void capture(void);

void usage(void);
67
void warning(char *format, ...);
68 69
void die(char *format, ...);
void dolog(int level, char *format, ...);
70 71 72

#ifdef __linux__
#define _POSIX_VDISABLE '\0'
73 74 75
#define revoke(tty)	(0)
#endif

76 77 78 79
#ifndef LOG_TESTBED
#define LOG_TESTBED	LOG_USER
#endif

80 81 82 83 84
/*
 *  Configurable things.
 */
#define PIDNAME		"%s/%s.pid"
#define LOGNAME		"%s/%s.log"
85
#define RUNNAME		"%s/%s.run"
86 87 88
#define TTYNAME		"%s/%s"
#define PTYNAME		"%s/%s-pty"
#define ACLNAME		"%s/%s.acl"
89
#define DEVNAME		"%s/%s"
90
#define BUFSIZE		4096
91
#define DROP_THRESH	(32*1024)
92

93
#define DEFAULT_CERTFILE PREFIX"/etc/capture.pem"
94

95 96 97
char 	*Progname;
char 	*Pidname;
char	*Logname;
98
char	*Runname;
99
char	*Ttyname;
100 101 102
char	*Ptyname;
char	*Devname;
char	*Machine;
103
int	logfd, runfd, devfd, ptyfd;
104
int	hwflow = 0, speed = B9600, debug = 0, runfile = 0, standalone = 0;
105
int	stampinterval = -1;
106 107
sigset_t actionsigmask;
sigset_t allsigmask;
108
#ifdef  USESOCKETS
109
char		  *Bossnode = BOSSNODE;
Mike Hibler's avatar
Mike Hibler committed
110
struct sockaddr_in Bossaddr;
111 112
char		  *Aclname;
int		   serverport = SERVERPORT;
113
int		   sockfd, tipactive, portnum;
114
struct sockaddr_in tipclient;
115 116 117
secretkey_t	   secretkey;
char		   ourhostname[MAXHOSTNAMELEN];
int		   needshake;
118 119
gid_t		   tipgid;
uid_t		   tipuid;
120 121 122 123 124 125 126 127 128 129 130 131 132

#ifdef  WITHSSL

SSL_CTX * ctx;
SSL * sslCon;

int initializedSSL = 0;
int usingSSL = 0;

const char * certfile = NULL;

#endif /* WITHSSL */ 
#endif /* USESOCKETS */
133 134

int
135
main(int argc, char **argv)
136 137 138
{
	char strbuf[MAXPATHLEN], *newstr();
	int flags, op, i;
139
	struct sigaction sa;
140 141
	extern int optind;
	extern char *optarg;
142 143 144
#ifdef  USESOCKETS
	struct sockaddr_in name;
#endif
145 146 147

	Progname = (Progname = rindex(argv[0], '/')) ? ++Progname : *argv;

148
	while ((op = getopt(argc, argv, "rds:Hb:ip:c:T:")) != EOF)
149
		switch (op) {
150
#ifdef	USESOCKETS
151 152 153 154 155
#ifdef  WITHSSL
		case 'c':
		        certfile = optarg;
		        break;
#endif  WITHSSL
156 157 158
		case 'b':
			Bossnode = optarg;
			break;
159 160 161 162

		case 'p':
			serverport = atoi(optarg);
			break;
163 164 165 166

		case 'i':
			standalone = 1;
			break;
167
#endif /* USESOCKETS */
168 169 170 171
		case 'H':
			++hwflow;
			break;

172 173 174 175 176 177 178 179
		case 'd':
			debug++;
			break;

		case 'r':
			runfile++;
			break;

180 181 182 183 184
		case 's':
			if ((i = atoi(optarg)) == 0 ||
			    (speed = val2speed(i)) == 0)
				usage();
			break;
185 186 187 188 189
		case 'T':
			stampinterval = atoi(optarg);
			if (stampinterval < 0)
				usage();
			break;
190 191 192 193 194 195 196 197
		}

	argc -= optind;
	argv += optind;

	if (argc != 2)
		usage();

198 199 200
	if (!debug)
		(void)daemon(0, 0);

201 202 203 204 205 206
	Machine = argv[0];

	(void) sprintf(strbuf, PIDNAME, LOGPATH, argv[0]);
	Pidname = newstr(strbuf);
	(void) sprintf(strbuf, LOGNAME, LOGPATH, argv[0]);
	Logname = newstr(strbuf);
207 208
	(void) sprintf(strbuf, RUNNAME, LOGPATH, argv[0]);
	Runname = newstr(strbuf);
209
	(void) sprintf(strbuf, TTYNAME, TIPPATH, argv[0]);
210
	Ttyname = newstr(strbuf);
211
	(void) sprintf(strbuf, PTYNAME, TIPPATH, argv[0]);
212 213 214 215
	Ptyname = newstr(strbuf);
	(void) sprintf(strbuf, DEVNAME, DEVPATH, argv[1]);
	Devname = newstr(strbuf);

216
	openlog(Progname, LOG_PID, LOG_TESTBED);
217 218
	dolog(LOG_NOTICE, "starting");

219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
	/*
	 * We process the "action" signals sequentially, there are just
	 * too many interdependencies.  We block em while we shut down too.
	 */
	sigemptyset(&actionsigmask);
	sigaddset(&actionsigmask, SIGHUP);
	sigaddset(&actionsigmask, SIGUSR1);
	sigaddset(&actionsigmask, SIGUSR2);
	allsigmask = actionsigmask;
	sigaddset(&allsigmask, SIGINT);
	sigaddset(&allsigmask, SIGTERM);
	memset(&sa, 0, sizeof sa);
	sa.sa_handler = quit;
	sa.sa_mask = allsigmask;
	sigaction(SIGINT, &sa, NULL);
	sigaction(SIGTERM, &sa, NULL);
	sa.sa_handler = reinit;
	sa.sa_mask = actionsigmask;
	sigaction(SIGHUP, &sa, NULL);
	if (runfile) {
		sa.sa_handler = newrun;
		sigaction(SIGUSR1, &sa, NULL);
	}
	sa.sa_handler = terminate;
	sigaction(SIGUSR2, &sa, NULL);

245 246
	srandomdev();
	
247
	/*
248
	 * Open up run/log file, console tty, and controlling pty.
249
	 */
250
	if ((logfd = open(Logname, O_WRONLY|O_CREAT|O_APPEND, 0640)) < 0)
251
		die("%s: open: %s", Logname, geterr(errno));
252
	if (chmod(Logname, 0640) < 0)
253
		die("%s: chmod: %s", Logname, geterr(errno));
254 255

	if (runfile) {
256 257 258
		unlink(Runname);
		
		if ((runfd = open(Runname,O_WRONLY|O_CREAT|O_APPEND,0600)) < 0)
259
			die("%s: open: %s", Runname, geterr(errno));
260 261
		if (fchmod(runfd, 0640) < 0)
			die("%s: fchmod: %s", Runname, geterr(errno));
262
	}
263
#ifdef  USESOCKETS
Mike Hibler's avatar
Mike Hibler committed
264 265 266
	/*
	 * Verify the bossnode and stash the address info
	 */
Mike Hibler's avatar
Mike Hibler committed
267 268 269 270 271 272 273 274 275 276 277
	{
		struct hostent *he;

		he = gethostbyname(Bossnode);
		if (he == 0) {
			die("gethostbyname(%s): %s",
			    Bossnode, hstrerror(h_errno));
		}
		memcpy ((char *)&Bossaddr.sin_addr, he->h_addr, he->h_length);
		Bossaddr.sin_family = AF_INET;
		Bossaddr.sin_port   = htons(serverport);
Mike Hibler's avatar
Mike Hibler committed
278 279
	}

280 281 282
	(void) sprintf(strbuf, ACLNAME, ACLPATH, Machine);
	Aclname = newstr(strbuf);
	
283 284 285 286 287 288 289 290 291 292 293
	/*
	 * Create and bind our socket.
	 */
	sockfd = socket(AF_INET, SOCK_STREAM, 0);
	if (sockfd < 0)
		die("socket(): opening stream socket: %s", geterr(errno));

	i = 1;
	if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
		       (char *)&i, sizeof(i)) < 0)
		die("setsockopt(): SO_REUSEADDR: %s", geterr(errno));
294
	
295 296 297 298 299 300 301 302 303 304 305 306 307 308
	/* Create wildcard name. */
	name.sin_family = AF_INET;
	name.sin_addr.s_addr = INADDR_ANY;
	name.sin_port = 0;
	if (bind(sockfd, (struct sockaddr *) &name, sizeof(name)))
		die("bind(): binding stream socket: %s", geterr(errno));

	/* Find assigned port value and print it out. */
	i = sizeof(name);
	if (getsockname(sockfd, (struct sockaddr *)&name, &i))
		die("getsockname(): %s", geterr(errno));
	portnum = ntohs(name.sin_port);

	if (listen(sockfd, 1) < 0)
309
		die("listen(): %s", geterr(errno));
310

311 312
	if (gethostname(ourhostname, sizeof(ourhostname)) < 0)
		die("gethostname(): %s", geterr(errno));
313

314 315
	createkey();
	dolog(LOG_NOTICE, "Ready! Listening on TCP port %d", portnum);
316
#else
317
	if ((ptyfd = open(Ptyname, O_RDWR)) < 0)
318
		die("%s: open: %s", Ptyname, geterr(errno));
319
#endif
320
	if ((devfd = open(Devname, O_RDWR|O_NONBLOCK)) < 0)
321
		die("%s: open: %s", Devname, geterr(errno));
322 323

	if (ioctl(devfd, TIOCEXCL, 0) < 0)
324
		warning("TIOCEXCL %s: %s", Devname, geterr(errno));
325 326 327 328 329 330 331 332 333 334

	writepid();
	rawmode(speed);

	capture();

	cleanup();
	exit(0);
}

335 336 337
#ifdef TWOPROCESS
int	pid;

338
void
339
capture(void)
340 341 342 343 344 345 346 347 348 349 350 351 352 353
{
	flags = FNDELAY;
	(void) fcntl(ptyfd, F_SETFL, &flags);

	if (pid = fork())
		in();
	else
		out();
}

/*
 * Loop reading from the console device, writing data to log file and
 * to the pty for tip to pick up.
 */
354
in(void)
355
{
356
	char buf[BUFSIZE];
357 358
	int cc;
	sigset_t omask;
359 360
	
	while (1) {
361
		if ((cc = read(devfd, buf, BUFSIZE)) < 0) {
362 363 364
			if ((errno == EWOULDBLOCK) || (errno == EINTR))
				continue;
			else
365
				die("%s: read: %s", Devname, geterr(errno));
366
		}
367
		sigprocmask(SIG_BLOCK, &actionsigmask, &omask);
368 369

		if (write(logfd, buf, cc) < 0)
370
			die("%s: write: %s", Logname, geterr(errno));
371

372 373
		if (runfile) {
			if (write(runfd, buf, cc) < 0)
374
				die("%s: write: %s", Runname, geterr(errno));
375 376
		}

377 378
		if (write(ptyfd, buf, cc) < 0) {
			if ((errno != EIO) && (errno != EWOULDBLOCK))
379
				die("%s: write: %s", Ptyname, geterr(errno));
380
		}
381
		sigprocmask(SIG_SETMASK, &omask, NULL);
382 383 384 385 386 387
	}
}

/*
 * Loop reading input from pty (tip), and send off to the console device.
 */
388
out(void)
389
{
390
	char buf[BUFSIZE];
391 392
	int cc;
	sigset_t omask;
393 394 395 396 397 398
	struct timeval timeout;

	timeout.tv_sec  = 0;
	timeout.tv_usec = 100000;
	
	while (1) {
399
		sigprocmask(SIG_BLOCK, &actionsigmask, &omask);
400
		if ((cc = read(ptyfd, buf, BUFSIZE)) < 0) {
401
			sigprocmask(SIG_SETMASK, &omask, NULL);
402 403 404 405 406 407
			if ((errno == EIO) || (errno == EWOULDBLOCK) ||
			    (errno == EINTR)) {
				select(0, 0, 0, 0, &timeout);
				continue;
			}
			else
408
				die("%s: read: %s", Ptyname, geterr(errno));
409 410 411
		}

		if (write(devfd, buf, cc) < 0)
412
			die("%s: write: %s", Devname, geterr(errno));
413
		
414
		sigprocmask(SIG_SETMASK, &omask, NULL);
415 416 417
	}
}
#else
418 419
static fd_set	sfds;
static int	fdcount;
420
void
421
capture(void)
422
{
423
	fd_set fds;
424 425
	int i, cc, lcc;
	sigset_t omask;
426
	char buf[BUFSIZE];
427
	struct timeval timeout;
428 429 430 431
#ifdef LOG_DROPS
	int drop_topty_chars = 0;
	int drop_todev_chars = 0;
#endif
432

433 434 435 436 437 438 439 440 441 442 443 444 445
	/*
	 * XXX for now we make both directions non-blocking.  This is a
	 * quick hack to achieve the goal that capture never block
	 * uninterruptably for long periods of time (use threads).
	 * This has the unfortunate side-effect that we may drop chars
	 * from the perspective of the user (use threads).  A more exotic
	 * solution would be to poll the readiness of output (use threads)
	 * as well as input and not read from one end unless we can write
	 * the other (use threads).
	 *
	 * I keep thinking (use threads) that there is a better way to do
	 * this (use threads).  Hmm...
	 */
Mike Hibler's avatar
Mike Hibler committed
446
	if (fcntl(devfd, F_SETFL, O_NONBLOCK) < 0)
447
		die("%s: fcntl(O_NONBLOCK): %s", Devname, geterr(errno));
448
#ifndef USESOCKETS
449 450 451 452 453 454 455 456 457 458 459 460
	/*
	 * It gets better!
	 * In FreeBSD 4.0 and beyond, the fcntl fails because the slave
	 * side is not open even though the only effect of this call is
	 * to set the file description's FNONBLOCK flag (i.e. the pty and
	 * tty code do nothing additional).  Turns out that we could use
	 * ioctl instead of fcntl to set the flag.  The call will still
	 * fail, but the flag will be left set.  Rather than rely on that
	 * dubious behavior, I temporarily open the slave, do the fcntl
	 * and close the slave again.
	 */
#ifdef __FreeBSD__
461
	if ((i = open(Ttyname, O_RDONLY)) < 0)
462 463 464 465 466
		die("%s: open: %s", Ttyname, geterr(errno));
#endif
	if (fcntl(ptyfd, F_SETFL, O_NONBLOCK) < 0)
		die("%s: fcntl(O_NONBLOCK): %s", Ptyname, geterr(errno));
#ifdef __FreeBSD__
467
	close(i);
468
#endif
469
#endif /* USESOCKETS */
470 471 472

	FD_ZERO(&sfds);
	FD_SET(devfd, &sfds);
473 474 475 476 477 478 479 480
	fdcount = devfd;
#ifdef  USESOCKETS
	if (devfd < sockfd)
		fdcount = sockfd;
	FD_SET(sockfd, &sfds);
#else
	if (devfd < ptyfd)
		fdcount = ptyfd;
481
	FD_SET(ptyfd, &sfds);
482 483 484 485
#endif	/* USESOCKETS */

	fdcount++;

486
	for (;;) {
487 488
#ifdef LOG_DROPS
		if (drop_topty_chars >= DROP_THRESH) {
489 490
			warning("%d dev -> pty chars dropped",
				drop_topty_chars);
491 492 493
			drop_topty_chars = 0;
		}
		if (drop_todev_chars >= DROP_THRESH) {
494 495
			warning("%d pty -> dev chars dropped",
				drop_todev_chars);
496
			drop_todev_chars = 0;
497
		}
498
#endif
499
		fds = sfds;
500
		timeout.tv_usec = 0;
501
		timeout.tv_sec  = 30;
502
#ifdef	USESOCKETS
503 504 505
		if (needshake) {
			timeout.tv_sec += (random() % 60);
		}
506 507
#endif
		i = select(fdcount, &fds, NULL, NULL, &timeout);
508 509
		if (i < 0) {
			if (errno == EINTR) {
510
				warning("input select interrupted, continuing");
511 512
				continue;
			}
513
			die("%s: select: %s", Devname, geterr(errno));
514
		}
515
		if (i == 0) {
516 517 518 519 520 521
#ifdef	USESOCKETS
			if (needshake) {
				handshake();
				continue;
			}
#endif
522 523
			continue;
		}
524 525
#ifdef	USESOCKETS
		if (FD_ISSET(sockfd, &fds)) {
526
			clientconnect();
527 528
		}
#endif	/* USESOCKETS */
529 530 531 532
		if (FD_ISSET(devfd, &fds)) {
			errno = 0;
			cc = read(devfd, buf, sizeof(buf));
			if (cc < 0)
533
				die("%s: read: %s", Devname, geterr(errno));
534
			if (cc == 0)
535
				die("%s: read: EOF", Devname);
536 537
			errno = 0;

538
			sigprocmask(SIG_BLOCK, &actionsigmask, &omask);
539 540 541 542
#ifdef	USESOCKETS
			if (!tipactive)
				goto dropped;
#endif
543
			for (lcc = 0; lcc < cc; lcc += i) {
544 545 546 547 548 549 550 551 552
#ifdef  WITHSSL
			        if (usingSSL) {
				        i = SSL_write(sslCon, &buf[lcc], cc-lcc);
					if (i < 0) { i = 0; } /* XXX Hack */
			        } else
#endif /* WITHSSL */ 
			        {
				        i = write(ptyfd, &buf[lcc], cc-lcc);
				}
553
				if (i < 0) {
554 555 556 557 558 559 560
					/*
					 * Either tip is blocked (^S) or
					 * not running (the latter should
					 * return EIO but doesn't due to a
					 * pty bug).  Note that we have
					 * dropped some chars.
					 */
561
					if (errno == EIO || errno == EAGAIN) {
562 563
#ifdef LOG_DROPS
						drop_topty_chars += (cc-lcc);
564 565 566
#endif
						goto dropped;
					}
567
					die("%s: write: %s",
568 569
					    Ptyname, geterr(errno));
				}
570 571 572 573
				if (i == 0) {
#ifdef	USESOCKETS
					goto disconnected;
#else
574
					die("%s: write: zero-length", Ptyname);
575 576
#endif
				}
577 578
			}
dropped:
579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597
			if (stampinterval >= 0) {
				static time_t laststamp;
				struct timeval tv;
				char stampbuf[40], *cts;
				time_t now;

				gettimeofday(&tv, 0);
				now = tv.tv_sec;
				if (stampinterval == 0 ||
				    now > laststamp + stampinterval) {
					cts = ctime(&now);
					cts[24] = 0;
					snprintf(stampbuf, sizeof stampbuf,
						 "\nSTAMP{%s}\n", cts);
					write(logfd, stampbuf,
					      strlen(stampbuf));
				}
				laststamp = now;
			}
598 599
			i = write(logfd, buf, cc);
			if (i < 0)
600
				die("%s: write: %s", Logname, geterr(errno));
601
			if (i != cc)
602
				die("%s: write: incomplete", Logname);
603 604 605
			if (runfile) {
				i = write(runfd, buf, cc);
				if (i < 0)
606
					die("%s: write: %s",
607 608
					    Runname, geterr(errno));
				if (i != cc)
609
					die("%s: write: incomplete", Runname);
610
			}
611
			sigprocmask(SIG_SETMASK, &omask, NULL);
612 613 614

		}
		if (FD_ISSET(ptyfd, &fds)) {
615 616
			int lerrno;

617
			sigprocmask(SIG_BLOCK, &actionsigmask, &omask);
618
			errno = 0;
619 620 621 622 623 624 625 626 627
#ifdef WITHSSL
			if (usingSSL) {
			        cc = SSL_read( sslCon, buf, sizeof(buf) );
				if (cc < 0) { cc = 0; } /* XXX hack */
			} else
#endif /* WITHSSL */ 
			{
			        cc = read(ptyfd, buf, sizeof(buf), 0);
			}
628
			lerrno = errno;
629
			sigprocmask(SIG_SETMASK, &omask, NULL);
630 631
			if (cc < 0) {
				/* XXX commonly observed */
632
				if (lerrno == EIO || lerrno == EAGAIN)
633
					continue;
634
#ifdef	USESOCKETS
635
				if (lerrno == ECONNRESET || lerrno == ETIMEDOUT)
636
					goto disconnected;
637 638 639 640
				die("%s: socket read: %s",
				    Machine, geterr(lerrno));
#else
				die("%s: read: %s", Ptyname, geterr(lerrno));
641
#endif
642 643
			}
			if (cc == 0) {
644 645 646 647 648 649 650 651 652 653 654
#ifdef	USESOCKETS
			disconnected:
				/*
				 * Other end disconnected.
				 */
				dolog(LOG_INFO, "%s disconnecting",
				      inet_ntoa(tipclient.sin_addr));
				FD_CLR(ptyfd, &sfds);
				close(ptyfd);
				tipactive = 0;
				continue;
655
#else
656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673
				/*
				 * Delay after reading 0 bytes from the pty.
				 * At least under FreeBSD, select on a
				 * disconnected pty (control half) always
				 * return ready and the subsequent read always
				 * returns 0.  To keep capture from eating up
				 * CPU constantly when no one is connected to
				 * the pty (i.e., most of the time) we delay
				 * after doing a zero length read.
				 *
				 * Note we keep tabs on the device so that we
				 * will wake up early if it goes active.
				 */
				timeout.tv_sec  = 1;
				timeout.tv_usec = 0;
				FD_ZERO(&fds);
				FD_SET(devfd, &fds);
				select(devfd+1, &fds, 0, 0, &timeout);
674
				continue;
675
#endif
676 677 678
			}
			errno = 0;

679
			sigprocmask(SIG_BLOCK, &actionsigmask, &omask);
680 681 682
			for (lcc = 0; lcc < cc; lcc += i) {
				i = write(devfd, &buf[lcc], cc-lcc);
				if (i < 0) {
683 684 685 686
					/*
					 * Device backed up (or FUBARed)
					 * Note that we dropped some chars.
					 */
687
					if (errno == EAGAIN) {
688 689 690
#ifdef LOG_DROPS
						drop_todev_chars += (cc-lcc);
#endif
691 692
						goto dropped2;
					}
693
					die("%s: write: %s",
694 695 696
					    Devname, geterr(errno));
				}
				if (i == 0)
697
					die("%s: write: zero-length", Devname);
698 699
			}
dropped2:
700
			sigprocmask(SIG_SETMASK, &omask, NULL);
701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718
		}
	}
}
#endif

/*
 * SIGHUP means we want to close the old log file (because it has probably
 * been moved) and start a new version of it.
 */
void
reinit(int sig)
{
	/*
	 * We know that the any pending write to the log file completed
	 * because we blocked SIGHUP during the write.
	 */
	close(logfd);
	
719
	if ((logfd = open(Logname, O_WRONLY|O_CREAT|O_APPEND, 0640)) < 0)
720
		die("%s: open: %s", Logname, geterr(errno));
721
	if (chmod(Logname, 0640) < 0)
722
		die("%s: chmod: %s", Logname, geterr(errno));
723 724 725 726 727 728 729 730
	
	dolog(LOG_NOTICE, "new log started");

	if (runfile)
		newrun(sig);
}

/*
731 732 733
 * SIGUSR1 means we want to close the old run file and start a new version
 * of it. The run file is not rolled or saved, so we unlink it to make sure
 * that no one can hang onto an open fd.
734 735 736 737 738 739 740 741 742
 */
void
newrun(int sig)
{
	/*
	 * We know that the any pending write to the log file completed
	 * because we blocked SIGUSR1 during the write.
	 */
	close(runfd);
743
	unlink(Runname);
744

745
	if ((runfd = open(Runname, O_WRONLY|O_CREAT|O_APPEND, 0600)) < 0)
746
		die("%s: open: %s", Runname, geterr(errno));
747 748 749 750 751 752 753 754 755 756 757 758

#ifdef  USESOCKETS
	/*
	 * Set owner/group of the new run file. Avoid race in which a
	 * user can get the new file before the chmod, by creating 0600
	 * and doing the chmod below.
	 */
	if (fchown(runfd, tipuid, tipgid) < 0)
		die("%s: fchown: %s", Runname, geterr(errno));
#endif
	if (fchmod(runfd, 0640) < 0)
		die("%s: fchmod: %s", Runname, geterr(errno));
759 760 761
	
	dolog(LOG_NOTICE, "new run started");
}
762

763 764
/*
 * SIGUSR2 means we want to revoke the other side of the pty to close the
765 766 767
 * tip down gracefully.  We flush all input/output pending on the pty,
 * do a revoke on the tty and then close and reopen the pty just to make
 * sure everyone is gone.
768 769
 */
void
770
terminate(int sig)
771
{
772
#ifdef	USESOCKETS
773 774 775 776 777 778 779 780 781 782
	if (tipactive) {
		shutdown(ptyfd, SHUT_RDWR);
		close(ptyfd);
		FD_CLR(ptyfd, &sfds);
		ptyfd = 0;
		tipactive = 0;
		dolog(LOG_INFO, "%s revoked", inet_ntoa(tipclient.sin_addr));
	}
	else
		dolog(LOG_INFO, "revoked");
783

784 785 786 787
	tipuid = tipgid = 0;
	if (runfile)
		newrun(sig);

788 789
	/* Must be done *after* all the above stuff is done! */
	createkey();
790
#else
791 792 793 794 795 796
	int ofd = ptyfd;
	
	/*
	 * We know that the any pending access to the pty completed
	 * because we blocked SIGUSR2 during the operation.
	 */
797 798 799
	tcflush(ptyfd, TCIOFLUSH);
	if (revoke(Ttyname) < 0)
		dolog(LOG_WARNING, "could not revoke access to tty");
800 801
	close(ptyfd);
	
802
	if ((ptyfd = open(Ptyname, O_RDWR)) < 0)
803
		die("%s: open: %s", Ptyname, geterr(errno));
804 805 806 807 808 809 810 811

	/* XXX so we don't have to recompute the select mask */
	if (ptyfd != ofd) {
		dup2(ptyfd, ofd);
		close(ptyfd);
		ptyfd = ofd;
	}

812 813
#ifdef __FreeBSD__
	/* see explanation in capture() above */
814
	if ((ofd = open(Ttyname, O_RDONLY)) < 0)
815 816
		die("%s: open: %s", Ttyname, geterr(errno));
#endif
817
	if (fcntl(ptyfd, F_SETFL, O_NONBLOCK) < 0)
818 819 820 821
		die("%s: fcntl(O_NONBLOCK): %s", Ptyname, geterr(errno));
#ifdef __FreeBSD__
	close(ofd);
#endif
822 823
	
	dolog(LOG_NOTICE, "pty reset");
824
#endif	/* USESOCKETS */
825 826 827 828 829
}

/*
 *  Display proper usage / error message and exit.
 */
830 831 832 833 834 835 836 837
char *optstr =
#ifdef USESOCKETS
#ifdef WITHSSL
"[-c certfile] "
#endif
"[-b bossnode] [-p bossport] [-i] "
#endif
"-Hdr [-s speed] [-T stampinterval]";
838
void
839
usage(void)
840
{
841
	fprintf(stderr, "usage: %s %s machine tty\n", Progname, optstr);
842 843 844
	exit(1);
}

845
void
846
warning(char *format, ...)
847
{
848
	char msgbuf[BUFSIZE];
849
	va_list ap;
850

851 852 853
	va_start(ap, format);
	vsnprintf(msgbuf, BUFSIZE, format, ap);
	va_end(ap);
854
	dolog(LOG_WARNING, msgbuf);
855 856
}

857 858
void
die(char *format, ...)
859
{
860
	char msgbuf[BUFSIZE];
861
	va_list ap;
862

863 864 865
	va_start(ap, format);
	vsnprintf(msgbuf, BUFSIZE, format, ap);
	va_end(ap);
866 867 868 869
	dolog(LOG_ERR, msgbuf);
	quit(0);
}

870 871
void
dolog(int level, char *format, ...)
872
{
873
	char msgbuf[BUFSIZE];
874
	va_list ap;
875

876 877 878
	va_start(ap, format);
	vsnprintf(msgbuf, BUFSIZE, format, ap);
	va_end(ap);
879 880 881 882 883
	if (debug) {
		fprintf(stderr, "%s - %s\n", Machine, msgbuf);
		fflush(stderr);
	}
	syslog(level, "%s - %s\n", Machine, msgbuf);
884 885 886 887 888 889 890 891 892 893
}

void
quit(int sig)
{
	cleanup();
	exit(1);
}

void
894
cleanup(void)
895
{
896 897
	dolog(LOG_NOTICE, "exiting");
#ifdef TWOPROCESS
898 899
	if (pid)
		(void) kill(pid, SIGTERM);
900
#endif
901 902 903 904
	(void) unlink(Pidname);
}

char *
905
newstr(char *str)
906
{
907
	char *np;
908

909
	if ((np = malloc((unsigned) strlen(str) + 1)) == NULL)
910
		die("malloc: out of memory");
911 912 913 914 915 916 917

	return(strcpy(np, str));
}

/*
 * Open up PID file and write our pid into it.
 */
918
writepid(void)
919 920 921 922
{
	int fd;
	char buf[8];
	
923
	if ((fd = open(Pidname, O_WRONLY|O_CREAT|O_TRUNC, 0644)) < 0)
924
		die("%s: open: %s", Pidname, geterr(errno));
925 926

	if (chmod(Pidname, 0644) < 0)
927
		die("%s: chmod: %s", Pidname, geterr(errno));
928 929 930 931
	
	(void) sprintf(buf, "%d\n", getpid());
	
	if (write(fd, buf, strlen(buf)) < 0)
932
		die("%s: write: %s", Pidname, geterr(errno));
933 934 935 936 937 938 939
	
	(void) close(fd);
}

/*
 * Put the console line into raw mode.
 */
940
rawmode(int speed)
941 942 943 944
{
	struct termios t;

	if (tcgetattr(devfd, &t) < 0)
945
		die("%s: tcgetattr: %s", Devname, geterr(errno));
946 947 948 949 950 951 952 953 954 955 956 957
	(void) cfsetispeed(&t, speed);
	(void) cfsetospeed(&t, speed);
	cfmakeraw(&t);
	t.c_cflag |= CLOCAL;
	if (hwflow)
#ifdef __linux__
	        t.c_cflag |= CRTSCTS;
#else
		t.c_cflag |= CCTS_OFLOW | CRTS_IFLOW;
#endif
	t.c_cc[VSTART] = t.c_cc[VSTOP] = _POSIX_VDISABLE;
	if (tcsetattr(devfd, TCSAFLUSH, &t) < 0)
958
		die("%s: tcsetattr: %s", Devname, geterr(errno));
959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 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
}

/*
 * From kgdbtunnel
 */
static struct speeds {
	int speed;		/* symbolic speed */
	int val;		/* numeric value */
} speeds[] = {
#ifdef B50
	{ B50,	50 },
#endif
#ifdef B75
	{ B75,	75 },
#endif
#ifdef B110
	{ B110,	110 },
#endif
#ifdef B134
	{ B134,	134 },
#endif
#ifdef B150
	{ B150,	150 },
#endif
#ifdef B200
	{ B200,	200 },
#endif
#ifdef B300
	{ B300,	300 },
#endif
#ifdef B600
	{ B600,	600 },
#endif
#ifdef B1200
	{ B1200, 1200 },
#endif
#ifdef B1800
	{ B1800, 1800 },
#endif
#ifdef B2400
	{ B2400, 2400 },
#endif
#ifdef B4800
	{ B4800, 4800 },
#endif
#ifdef B7200
	{ B7200, 7200 },
#endif
#ifdef B9600
	{ B9600, 9600 },
#endif
#ifdef B14400
	{ B14400, 14400 },
#endif
#ifdef B19200
	{ B19200, 19200 },
#endif
#ifdef B38400
	{ B38400, 38400 },
#endif
#ifdef B28800
	{ B28800, 28800 },
#endif
#ifdef B57600
	{ B57600, 57600 },
#endif
#ifdef B76800
	{ B76800, 76800 },
#endif
#ifdef B115200
	{ B115200, 115200 },
#endif
#ifdef B230400
	{ B230400, 230400 },
#endif
};
#define NSPEEDS (sizeof(speeds) / sizeof(speeds[0]))

int
1038
val2speed(int val)
1039
{
1040 1041
	int n;
	struct speeds *sp;
1042 1043 1044 1045 1046 1047 1048

	for (sp = speeds, n = NSPEEDS; n > 0; ++sp, --n)
		if (val == sp->val)
			return (sp->speed);

	return (0);
}
1049 1050 1051

#ifdef USESOCKETS
int
1052
clientconnect(void)
1053
{
1054
	int		cc, length = sizeof(tipclient);
1055
	int             ret;
1056 1057
	int		newfd;
	secretkey_t     key;
1058
	capret_t	capret;
1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070

	newfd = accept(sockfd, (struct sockaddr *)&tipclient, &length);
	if (newfd < 0)
		die("accept(): accepting new client: %s", geterr(errno));

	/*
	 * Is there a better way to do this? I suppose we
	 * could shut the main socket down, and recreate
	 * it later when the client disconnects, but that
	 * sounds horribly brutish!
	 */
	if (tipactive) {
1071 1072 1073 1074 1075
		capret = CAPBUSY;
		if ((cc = write(newfd, &capret, sizeof(capret))) <= 0) {
			dolog(LOG_NOTICE, "%s refusing. error writing status",
			      inet_ntoa(tipclient.sin_addr));
		}
1076 1077
		dolog(LOG_NOTICE, "%s connecting, but tip is active",
		      inet_ntoa(tipclient.sin_addr));
1078 1079
		
		close(newfd);
1080 1081 1082 1083 1084
		return 1;
	}
	ptyfd = newfd;

	/*
1085 1086
	 * Read the first part to verify the key. We must get the
	 * proper bits or this is not a valid tip connection.
1087
	 */
1088
	if ((cc = read(ptyfd, &key, sizeof(key))) <= 0) {
1089
		close(ptyfd);
1090
		dolog(LOG_NOTICE, "%s connecting, error reading key",
1091 1092 1093
		      inet_ntoa(tipclient.sin_addr));
		return 1;
	}
1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120

#ifdef WITHSSL
	usingSSL = 0;

	if (cc == sizeof(key) && 
	    0 == strncmp( key.key, "USESSL", 6 )) {
	  usingSSL = 1;
	  /* 
	     dolog(LOG_NOTICE, "Client %s wants to use SSL",
		inet_ntoa(tipclient.sin_addr) );
	  */

	  if (!initializedSSL) {
	    SSL_load_error_strings();
	    SSL_library_init();

	    ctx = SSL_CTX_new( SSLv23_method() );
	    if (ctx == NULL) {
	      dolog( LOG_NOTICE, "Failed to create context.");
	      close( ptyfd );
	      return 1;
	    }

#ifndef PREFIX
#define PREFIX
#endif

1121
	    if (!certfile) { certfile = DEFAULT_CERTFILE; }
1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193

	    if (SSL_CTX_use_certificate_file( ctx, certfile, SSL_FILETYPE_PEM )
		<= 0) {
	      dolog(LOG_NOTICE, 
		    "Could not load %s as certificate file.",
		    certfile );
	      close(ptyfd);
	      return 1;
	    }

	    if (SSL_CTX_use_PrivateKey_file( ctx, certfile, SSL_FILETYPE_PEM )
		<= 0) {
	      dolog(LOG_NOTICE, 
		    "Could not load %s as key file.",
		    certfile );
	      close(ptyfd);
	      return 1;
	    }

	    initializedSSL = 1;
	  }
	  /*
	  if ( write( ptyfd, "OKAY", 4 ) <= 0) {
	    dolog( LOG_NOTICE, "Failed to send OKAY to client." );
	    close( ptyfd );
	    return 1;
	  }
	  */

	  sslCon = SSL_new( ctx );
	  if (!sslCon) {
	    dolog(LOG_NOTICE, "SSL_new failed.");
	    close(ptyfd);
	    return 1;
	  }	    
	    
	  if ((ret = SSL_set_fd( sslCon, ptyfd )) <= 0) {
	    dolog(LOG_NOTICE, "SSL_set_fd failed.");
	    close(ptyfd);
	    return 1;
	  }

	  dolog(LOG_NOTICE, "going to accept" );

	  if ((ret = SSL_accept( sslCon )) <= 0) {
	    dolog(LOG_NOTICE, "%s connecting, SSL_accept error.",
		  inet_ntoa(tipclient.sin_addr));
	    goto sslerror;
	  }

	  dolog(LOG_NOTICE, "going to read key" );

	  if ((cc = SSL_read(sslCon, (void *)&key, sizeof(key))) <= 0) {
	    ret = cc;
	    close(ptyfd);
	    dolog(LOG_NOTICE, "%s connecting, error reading capturekey.",
		  inet_ntoa(tipclient.sin_addr));
	  sslerror:
	    /*
	    {
	      FILE * foo = fopen("/tmp/err.txt", "w");
	      ERR_print_errors_fp( foo );
	      fclose( foo );
	    }
	    */
	    close(ptyfd);
	    return 1;
	  }

	  dolog(LOG_NOTICE, "got key" );
	}
#endif /* WITHSSL */
1194 1195 1196 1197
	/* Verify size of the key is sane */
	if (cc != sizeof(key) ||
	    key.keylen != strlen(key.key) ||
	    strncmp(secretkey.key, key.key, key.keylen)) {
1198
		/*
1199
		 * Tell the other side that their key is bad.
1200 1201
		 */
		capret = CAPNOPERM;
1202 1203 1204 1205
#ifdef WITHSSL
		if (usingSSL) {
		    if ((cc = SSL_write(sslCon, (void *)&capret, sizeof(capret))) <= 0) {
		        dolog(LOG_NOTICE, "%s connecting, error perm status",
1206
			      inet_ntoa(tipclient.sin_addr));
1207 1208 1209 1210 1211 1212 1213 1214
		    }
		} else
#endif /* WITHSSL */
		{
		    if ((cc = write(ptyfd, &capret, sizeof(capret))) <= 0) {
		        dolog(LOG_NOTICE, "%s connecting, error perm status",
			      inet_ntoa(tipclient.sin_addr));
		    }
1215
		}
1216
		close(ptyfd);
1217 1218
		dolog(LOG_NOTICE,
		      "%s connecting, secret key does not match",
1219 1220 1221
		      inet_ntoa(tipclient.sin_addr));
		return 1;
	}
1222 1223 1224 1225 1226
#ifndef SAFEMODE
	/* Do not spit this out into a public log file */
	dolog(LOG_INFO, "Key: %d: %s",
	      secretkey.keylen, secretkey.key);
#endif
1227 1228 1229 1230
	/*
	 * Tell the other side that all is okay.
	 */
	capret = CAPOK;
1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242
#ifdef WITHSSL
	if (usingSSL) {
	    if ((cc = SSL_write(sslCon, (void *)&capret, sizeof(capret))) <= 0) {
		close(ptyfd);
		dolog(LOG_NOTICE, "%s connecting, error writing status",
		      inet_ntoa(tipclient.sin_addr));
		return 1;
	    }
	} else
#endif /* WITHSSL */
	{
	    if ((cc = write(ptyfd, &capret, sizeof(capret))) <= 0) {
1243 1244 1245 1246
		close(ptyfd);
		dolog(LOG_NOTICE, "%s connecting, error writing status",
		      inet_ntoa(tipclient.sin_addr));
		return 1;
1247
	    }
1248
	}
1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267
	
	/*
	 * See Mike comments (use threads) above.
	 */
	if (fcntl(ptyfd, F_SETFL, O_NONBLOCK) < 0)
		die("fcntl(O_NONBLOCK): %s", geterr(errno));

	FD_SET(ptyfd, &sfds);
	if (ptyfd >= fdcount) {
		fdcount = ptyfd;
		fdcount++;
	}
	tipactive = 1;

	dolog(LOG_INFO, "%s connecting", inet_ntoa(tipclient.sin_addr));
	return 0;
}

/*
1268 1269
 * Generate our secret key and write out the file that local tip uses
 * to do a secure connect.
1270
 */
1271
int
1272
createkey(void)
1273
{
1274
	int			cc, i, fd;
1275
	unsigned char		buf[BUFSIZ];
1276
	FILE		       *fp;
1277

1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293
	/*
	 * Generate the key. Should probably generate a random
	 * number of random bits ...
	 */
	if ((fd = open("/dev/urandom", O_RDONLY)) < 0) {
		syslog(LOG_ERR, "opening /dev/urandom: %m");
		exit(1);
	}
	
	if ((cc = read(fd, buf, DEFAULTKEYLEN)) != DEFAULTKEYLEN) {
		if (cc < 0)
			syslog(LOG_ERR, "Reading random bits: %m");
		else
			syslog(LOG_ERR, "Reading random bits");
		exit(1);
	}
1294
	close(fd);
1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308
	
	/*
	 * Convert into ascii text string since that is easier to
	 * deal with all around.
	 */
	secretkey.key[0] = 0;
	for (i = 0; i < DEFAULTKEYLEN; i++) {
		int len = strlen(secretkey.key);
		
		snprintf(&secretkey.key[len],
			 sizeof(secretkey.key) - len,
			 "%x", (unsigned int) buf[i]);
	}
	secretkey.keylen = strlen(secretkey.key);
1309

1310 1311 1312 1313 1314 1315 1316 1317 1318 1319
#ifndef SAFEMODE
	/* Do not spit this out into a public log file */
	dolog(LOG_INFO, "NewKey: %d: %s", secretkey.keylen, secretkey.key);
#endif
	
	/*
	 * First write out the info locally so local tip can connect.
	 * This is still secure in that we rely on unix permission, which
	 * is how most of our security is based anyway.
	 */
1320

1321 1322 1323 1324
	/*
	 * We want to control the mode bits when this file is created.
	 * Sure, could change the umask, but I hate that function.
	 */
1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338
	(void) unlink(Aclname);
	if ((fd = open(Aclname, O_WRONLY|O_CREAT|O_TRUNC, 0600)) < 0)
		die("%s: open: %s", Aclname, geterr(errno));

	/*
	 * Set owner/group of the new run file. Avoid race in which a
	 * user can get the new file before the chmod, by creating 0600
	 * and doing the chmod after.
	 */
	if (fchown(fd, tipuid, tipgid) < 0)
		die("%s: fchown: %s", Runname, geterr(errno));
	if (fchmod(fd, 0640) < 0)
		die("%s: fchmod: %s", Runname, geterr(errno));
	
1339
	if ((fp = fdopen(fd, "w")) == NULL)
1340
		die("fdopen(%s)", Aclname, geterr(errno));
1341

1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353
	fprintf(fp, "host:   %s\n", ourhostname);
	fprintf(fp, "port:   %d\n", portnum);
	fprintf(fp, "keylen: %d\n", secretkey.keylen);
	fprintf(fp, "key:    %s\n", secretkey.key);
	fclose(fp);

	/*
	 * Send the info over.
	 */
	handshake();
	return 1;
}
1354

1355 1356 1357 1358 1359 1360 1361 1362
/*
 * Contact the boss node and tell it our local port number and the secret
 * key we are using.
 */
static	jmp_buf deadline;
static	int	deadbossflag;

void
1363
deadboss(int sig)
1364 1365 1366 1367 1368
{
	deadbossflag = 1;
	longjmp(deadline, 1);
}

1369 1370 1371 1372 1373 1374
/*
 * Tell the capserver our new secret key, and receive the setup info
 * back (owner/group of the tty/acl/run file). The handshake might be
 * delayed, so we continue to operate, and when we do handshake, set
 * the files properly.
 */
1375
int
1376
handshake(void)
1377 1378 1379
{
	int			sock, cc, err = 0;
	whoami_t		whoami;
1380
	tipowner_t		tipown;
1381

1382 1383 1384 1385 1386 1387
	/*
	 * In standalone, do not contact the capserver.
	 */
	if (standalone)
		return err;

1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405
	/*
	 * Global. If we fail, we keep trying from the main loop. This
	 * allows local tip to operate while still trying to contact the
	 * server periodically so remote tip can connect.
	 */
	needshake = 1;

	/*
	 * Don't do this if a local tip session is active. Typically, it
	 * means something is wrong, and that it would be a bad idea to
	 * interrupt a tip session without a potentially blocking operation,
	 * as that would really annoy the user. When the tip goes inactive,
	 * we will try again normally. 
	 */
	if (tipactive)
	    return 0;

	/* Our whoami info. */
1406
	strcpy(whoami.name, Machine);
1407 1408 1409 1410 1411 1412 1413 1414
	whoami.portnum = portnum;
	memcpy(&whoami.key, &secretkey, sizeof(secretkey));

	sock = socket(AF_INET, SOCK_STREAM, 0);
	if (sock < 0) {
		die("socket(): %s", geterr(errno));
	}

1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425
	/*
	 * Bind to a reserved port so that capserver can verify integrity
	 * of the sender by looking at the port number. The actual port
	 * number does not matter.
	 */
	if (bindresvport(sock, NULL) < 0) {
		warnc("Could not bind reserved port");
		close(sock);
		return -1;
	}

1426 1427 1428 1429 1430 1431
	/* For alarm. */
	deadbossflag = 0;
	signal(SIGALRM, deadboss);
	if (setjmp(deadline)) {
		alarm(0);
		signal(SIGALRM, SIG_DFL);
1432
		warning("Timed out connecting to %s\n", Bossnode);
1433 1434 1435 1436 1437
		close(sock);
		return -1;
	}
	alarm(5);

1438
	if (connect(sock, (struct sockaddr *)&Bossaddr, sizeof(Bossaddr)) < 0){
1439
		warning("connect(%s): %s", Bossnode, geterr(errno));
1440
		err = -1;
Mike Hibler's avatar
Mike Hibler committed
1441
		close(sock);
1442 1443 1444 1445 1446
		goto done;
	}

	if ((cc = write(sock, &whoami, sizeof(whoami))) != sizeof(whoami)) {
		if (cc < 0)
1447
			warning("write(%s): %s", Bossnode, geterr(errno));
1448
		else
1449
			warning("write(%s): Failed", Bossnode);
1450 1451 1452 1453
		err = -1;
		close(sock);
		goto done;
	}
1454 1455 1456
	
	if ((cc = read(sock, &tipown, sizeof(tipown))) != sizeof(tipown)) {
		if (cc < 0)
1457
			warning("read(%s): %s", Bossnode, geterr(errno));
1458
		else
1459
			warning("read(%s): Failed", Bossnode);
1460 1461 1462 1463
		err = -1;
		close(sock);
		goto done;
	}
1464
	close(sock);
1465 1466 1467 1468

	/*
	 * Now that we have owner/group info, set the runfile and aclfile.
	 */
Mike Hibler's avatar
Mike Hibler committed
1469 1470 1471
	tipuid = tipown.uid;
	tipgid = tipown.gid;
	if (runfile && chown(Runname, tipuid, tipgid) < 0)
1472 1473 1474 1475 1476
		die("%s: chown: %s", Runname, geterr(errno));

	if (chown(Aclname, tipuid, tipgid) < 0)
		die("%s: chown: %s", Aclname, geterr(errno));

Mike Hibler's avatar
Mike Hibler committed
1477 1478 1479 1480
	dolog(LOG_INFO,
	      "Handshake complete. Owner %d, Group %d", tipuid, tipgid);
	needshake = 0;

1481 1482 1483 1484
 done:
	alarm(0);
	signal(SIGALRM, SIG_DFL);
	return err;
1485 1486
}
#endif