All new accounts created on Gitlab now require administrator approval. If you invite any collaborators, please let Flux staff know so they can approve the accounts.

capture.c 47.6 KB
Newer Older
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1 2
/*
 * EMULAB-COPYRIGHT
3
 * Copyright (c) 2000-2008 University of Utah and the Flux Group.
Leigh B. Stoller's avatar
Leigh B. 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
	
#include <sys/param.h>

Mike Hibler's avatar
Mike Hibler committed
25 26
#include <unistd.h>
#include <string.h>
27 28 29 30 31 32
#include <stdio.h>
#include <ctype.h>
#include <strings.h>
#include <syslog.h>
#include <termios.h>
#include <errno.h>
33 34
#include <stdlib.h>
#include <stdarg.h>
Timothy Stack's avatar
 
Timothy Stack committed
35 36 37
#include <time.h>
#include <assert.h>
#include <paths.h>
38 39 40 41 42 43 44 45 46

#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>
47 48 49 50 51
#ifdef USESOCKETS
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
52 53
#include <setjmp.h>
#include <netdb.h>
Mike Hibler's avatar
Mike Hibler committed
54 55 56
#ifndef __linux__
#include <rpc/rpc.h>
#endif
57 58 59 60
#ifdef WITHSSL
#include <openssl/ssl.h>
#include <openssl/err.h>
#endif /* WITHSSL */
61
#include "config.h"
62
#endif /* USESOCKETS */
63
#include "capdecls.h"
64 65 66 67 68

#define geterr(e)	strerror(e)

void quit(int);
void reinit(int);
69
void newrun(int);
70
void terminate(int);
71
void cleanup(void);
72 73 74
void capture(void);

void usage(void);
75
void warning(char *format, ...);
76 77
void die(char *format, ...);
void dolog(int level, char *format, ...);
78

Mike Hibler's avatar
Mike Hibler committed
79 80
int val2speed(int val);
void rawmode(char *devname, int speed);
81
int netmode();
Mike Hibler's avatar
Mike Hibler committed
82 83 84 85 86 87 88 89
void writepid(void);
void createkey(void);
int handshake(void);
#ifdef USESOCKETS
int clientconnect(void);
#endif
int handleupload(void);

90 91
#ifdef __linux__
#define _POSIX_VDISABLE '\0'
92 93 94
#define revoke(tty)	(0)
#endif

95 96 97 98
#ifndef LOG_TESTBED
#define LOG_TESTBED	LOG_USER
#endif

99 100 101 102 103
/*
 *  Configurable things.
 */
#define PIDNAME		"%s/%s.pid"
#define LOGNAME		"%s/%s.log"
104
#define RUNNAME		"%s/%s.run"
105 106 107
#define TTYNAME		"%s/%s"
#define PTYNAME		"%s/%s-pty"
#define ACLNAME		"%s/%s.acl"
108
#define DEVNAME		"%s/%s"
109
#define BUFSIZE		4096
110
#define DROP_THRESH	(32*1024)
111
#define MAX_UPLOAD_SIZE	(32 * 1024 * 1024)
112
#define DEFAULT_CERTFILE PREFIX"/etc/capture.pem"
Timothy Stack's avatar
 
Timothy Stack committed
113 114
#define DEFAULT_CLIENT_CERTFILE PREFIX"/etc/client.pem"
#define DEFAULT_CAFILE	PREFIX"/etc/emulab.pem"
Chad Barb's avatar
 
Chad Barb committed
115

116 117 118
char 	*Progname;
char 	*Pidname;
char	*Logname;
119
char	*Runname;
120
char	*Ttyname;
121 122 123
char	*Ptyname;
char	*Devname;
char	*Machine;
Timothy Stack's avatar
 
Timothy Stack committed
124
int	logfd = -1, runfd, devfd = -1, ptyfd = -1;
125
int	hwflow = 0, speed = B9600, debug = 0, runfile = 0, standalone = 0;
126
int	stampinterval = -1;
127 128
sigset_t actionsigmask;
sigset_t allsigmask;
129
int	 powermon = 0;
Timothy Stack's avatar
 
Timothy Stack committed
130 131 132
#ifndef  USESOCKETS
#define relay_snd 0
#define relay_rcv 0
133
#define remotemode 0
Timothy Stack's avatar
 
Timothy Stack committed
134
#else
135
char		  *Bossnode = BOSSNODE;
Mike Hibler's avatar
Mike Hibler committed
136
struct sockaddr_in Bossaddr;
137 138
char		  *Aclname;
int		   serverport = SERVERPORT;
Timothy Stack's avatar
 
Timothy Stack committed
139
int		   sockfd, tipactive, portnum, relay_snd, relay_rcv;
140
int		   remotemode;
Timothy Stack's avatar
 
Timothy Stack committed
141 142 143
int		   upportnum = -1, upfd = -1, upfilefd = -1;
char		   uptmpnam[64];
size_t		   upfilesize = 0;
144
struct sockaddr_in tipclient;
Timothy Stack's avatar
 
Timothy Stack committed
145 146
struct sockaddr_in relayclient;
struct in_addr	   relayaddr;
147 148 149
secretkey_t	   secretkey;
char		   ourhostname[MAXHOSTNAMELEN];
int		   needshake;
150 151
gid_t		   tipgid;
uid_t		   tipuid;
Timothy Stack's avatar
 
Timothy Stack committed
152
char		  *uploadCommand;
153 154 155 156 157

#ifdef  WITHSSL

SSL_CTX * ctx;
SSL * sslCon;
Timothy Stack's avatar
 
Timothy Stack committed
158 159
SSL * sslRelay;
SSL * sslUpload;
160 161 162 163

int initializedSSL = 0;

const char * certfile = NULL;
Timothy Stack's avatar
 
Timothy Stack committed
164 165 166 167 168 169 170 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 218 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 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
const char * cafile = NULL;

int
initializessl(void)
{
	static int initializedSSL = 0;
	
	if (initializedSSL)
		return 0;
	
	SSL_load_error_strings();
	SSL_library_init();
	
	ctx = SSL_CTX_new( SSLv23_method() );
	if (ctx == NULL) {
		dolog( LOG_NOTICE, "Failed to create context.");
		return 1;
	}
	
#ifndef PREFIX
#define PREFIX
#endif
	
	if (relay_snd) {
		if (!cafile) { cafile = DEFAULT_CAFILE; }
		if (SSL_CTX_load_verify_locations(ctx, cafile, NULL) == 0) {
			die("cannot load verify locations");
		}
		
		/*
		 * Make it so the client must provide authentication.
		 */
		SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER |
				   SSL_VERIFY_FAIL_IF_NO_PEER_CERT, 0);
		
		/*
		 * No session caching! Useless and eats up memory.
		 */
		SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
		
		if (!certfile) { certfile = DEFAULT_CLIENT_CERTFILE; }
		if (SSL_CTX_use_certificate_file( ctx,
						  certfile,
						  SSL_FILETYPE_PEM ) <= 0) {
			dolog(LOG_NOTICE, 
			      "Could not load %s as certificate file.",
			      certfile );
			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 );
			return 1;
		}
	}
	else {
		if (!certfile) { certfile = DEFAULT_CERTFILE; }
		
		if (SSL_CTX_use_certificate_file( ctx,
						  certfile,
						  SSL_FILETYPE_PEM ) <= 0) {
			dolog(LOG_NOTICE, 
			      "Could not load %s as certificate file.",
			      certfile );
			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 );
			return 1;
		}
	}
		
	initializedSSL = 1;

	return 0;
}

int
sslverify(SSL *ssl, char *requiredunit)
{
	X509		*peer = NULL;
	char		cname[256], unitname[256];
	
	assert(ssl != NULL);
	assert(requiredunit != NULL);

	if (SSL_get_verify_result(ssl) != X509_V_OK) {
		dolog(LOG_NOTICE,
		      "sslverify: Certificate did not verify!\n");
		return -1;
	}
	
	if (! (peer = SSL_get_peer_certificate(ssl))) {
		dolog(LOG_NOTICE, "sslverify: No certificate presented!\n");
		return -1;
	}

	/*
	 * Grab stuff from the cert.
	 */
	X509_NAME_get_text_by_NID(X509_get_subject_name(peer),
				  NID_organizationalUnitName,
				  unitname, sizeof(unitname));

	X509_NAME_get_text_by_NID(X509_get_subject_name(peer),
				  NID_commonName,
				  cname, sizeof(cname));
	X509_free(peer);
	
	/*
	 * On the server, things are a bit more difficult since
	 * we share a common cert locally and a per group cert remotely.
	 *
	 * Make sure common name matches.
	 */
	if (strcmp(cname, BOSSNODE)) {
		dolog(LOG_NOTICE,
		      "sslverify: commonname mismatch: %s!=%s\n",
		      cname, BOSSNODE);
		return -1;
	}
294

Timothy Stack's avatar
 
Timothy Stack committed
295 296 297 298 299 300 301 302 303 304 305 306 307
	/*
	 * If the node is remote, then the unitname must match the type.
	 * Simply a convention. 
	 */
	if (strcmp(unitname, requiredunit)) {
		dolog(LOG_NOTICE,
		      "sslverify: unitname mismatch: %s!=Capture Server\n",
		      unitname);
		return -1;
	}
	
	return 0;
}
308 309
#endif /* WITHSSL */ 
#endif /* USESOCKETS */
310 311

int
312
main(int argc, char **argv)
313 314
{
	char strbuf[MAXPATHLEN], *newstr();
Mike Hibler's avatar
Mike Hibler committed
315
	int op, i;
316
	struct sigaction sa;
317 318
	extern int optind;
	extern char *optarg;
319 320 321
#ifdef  USESOCKETS
	struct sockaddr_in name;
#endif
322

Mike Hibler's avatar
Mike Hibler committed
323 324 325 326
	if ((Progname = rindex(argv[0], '/')))
		Progname++;
	else
		Progname = *argv;
327

328
	while ((op = getopt(argc, argv, "rds:Hb:ip:c:T:aou:v:Pm")) != EOF)
329
		switch (op) {
330
#ifdef	USESOCKETS
331 332 333 334
#ifdef  WITHSSL
		case 'c':
		        certfile = optarg;
		        break;
335
#endif  /* WITHSSL */
336 337 338
		case 'b':
			Bossnode = optarg;
			break;
339 340 341 342

		case 'p':
			serverport = atoi(optarg);
			break;
343 344 345 346

		case 'i':
			standalone = 1;
			break;
347 348 349 350

		case 'm':
			remotemode = 1;
			break;
351
#endif /* USESOCKETS */
352 353 354 355
		case 'H':
			++hwflow;
			break;

356 357 358 359 360 361 362 363
		case 'd':
			debug++;
			break;

		case 'r':
			runfile++;
			break;

364 365 366 367 368
		case 's':
			if ((i = atoi(optarg)) == 0 ||
			    (speed = val2speed(i)) == 0)
				usage();
			break;
369 370 371 372 373
		case 'T':
			stampinterval = atoi(optarg);
			if (stampinterval < 0)
				usage();
			break;
374 375 376
		case 'P':
			powermon = 1;
			break;
Timothy Stack's avatar
 
Timothy Stack committed
377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393
#ifdef  WITHSSL
		case 'a':
			relay_snd = 1;
			break;
			
		case 'o':
			relay_rcv = 1;
			break;
			
		case 'u':
			uploadCommand = optarg;
			break;

		case 'v':
			cafile = optarg;
			break;
#endif
394 395 396 397 398 399 400 401
		}

	argc -= optind;
	argv += optind;

	if (argc != 2)
		usage();

402 403 404
	if (!debug)
		(void)daemon(0, 0);

405 406
	Machine = argv[0];

Mike Hibler's avatar
Mike Hibler committed
407
	(void) snprintf(strbuf, sizeof(strbuf), PIDNAME, LOGPATH, argv[0]);
408
	Pidname = newstr(strbuf);
Mike Hibler's avatar
Mike Hibler committed
409
	(void) snprintf(strbuf, sizeof(strbuf), LOGNAME, LOGPATH, argv[0]);
410
	Logname = newstr(strbuf);
Mike Hibler's avatar
Mike Hibler committed
411
	(void) snprintf(strbuf, sizeof(strbuf), RUNNAME, LOGPATH, argv[0]);
412
	Runname = newstr(strbuf);
Mike Hibler's avatar
Mike Hibler committed
413
	(void) snprintf(strbuf, sizeof(strbuf), TTYNAME, TIPPATH, argv[0]);
414
	Ttyname = newstr(strbuf);
Mike Hibler's avatar
Mike Hibler committed
415
	(void) snprintf(strbuf, sizeof(strbuf), PTYNAME, TIPPATH, argv[0]);
416
	Ptyname = newstr(strbuf);
417 418 419 420 421
	if (remotemode)
		strcpy(strbuf, argv[1]);
	else
		(void) snprintf(strbuf, sizeof(strbuf),
				DEVNAME, DEVPATH, argv[1]);
422 423
	Devname = newstr(strbuf);

424
	openlog(Progname, LOG_PID, LOG_TESTBED);
425 426
	dolog(LOG_NOTICE, "starting");

427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
	/*
	 * 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);
Timothy Stack's avatar
 
Timothy Stack committed
443 444 445 446 447
	if (!relay_snd) {
		sa.sa_handler = reinit;
		sa.sa_mask = actionsigmask;
		sigaction(SIGHUP, &sa, NULL);
	}
448 449 450 451 452 453 454
	if (runfile) {
		sa.sa_handler = newrun;
		sigaction(SIGUSR1, &sa, NULL);
	}
	sa.sa_handler = terminate;
	sigaction(SIGUSR2, &sa, NULL);

Timothy Stack's avatar
 
Timothy Stack committed
455
#ifdef HAVE_SRANDOMDEV
456
	srandomdev();
Timothy Stack's avatar
 
Timothy Stack committed
457 458 459
#else
	srand(time(NULL));
#endif
460
	
461
	/*
462
	 * Open up run/log file, console tty, and controlling pty.
463
	 */
464
	if (runfile) {
465 466 467
		unlink(Runname);
		
		if ((runfd = open(Runname,O_WRONLY|O_CREAT|O_APPEND,0600)) < 0)
468
			die("%s: open: %s", Runname, geterr(errno));
469 470
		if (fchmod(runfd, 0640) < 0)
			die("%s: fchmod: %s", Runname, geterr(errno));
471
	}
472
#ifdef  USESOCKETS
Mike Hibler's avatar
Mike Hibler committed
473 474 475
	/*
	 * Verify the bossnode and stash the address info
	 */
Mike Hibler's avatar
Mike Hibler committed
476 477 478 479 480 481 482 483 484 485 486
	{
		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
487 488
	}

Mike Hibler's avatar
Mike Hibler committed
489
	(void) snprintf(strbuf, sizeof(strbuf), ACLNAME, ACLPATH, Machine);
490 491
	Aclname = newstr(strbuf);
	
492 493 494 495 496 497 498 499 500 501 502
	/*
	 * 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));
503
	
504 505 506 507 508 509 510 511 512 513 514 515 516 517
	/* 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)
518
		die("listen(): %s", geterr(errno));
519

520 521
	if (gethostname(ourhostname, sizeof(ourhostname)) < 0)
		die("gethostname(): %s", geterr(errno));
522

523 524
	createkey();
	dolog(LOG_NOTICE, "Ready! Listening on TCP port %d", portnum);
Timothy Stack's avatar
 
Timothy Stack committed
525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552

	if (relay_snd) {
		struct sockaddr_in sin;
		struct hostent *he;
		secretkey_t key;
		char *port_idx;
		int port;

		if ((port_idx = strchr(argv[0], ':')) == NULL)
			die("%s: bad format, expecting 'host:port'", argv[0]);
		*port_idx = '\0';
		port_idx += 1;
		if (sscanf(port_idx, "%d", &port) != 1)
			die("%s: bad port number", port_idx);
		he = gethostbyname(argv[0]);
		if (he == 0) {
			die("gethostbyname(%s): %s",
			    argv[0], hstrerror(h_errno));
		}
		bzero(&sin, sizeof(sin));
		memcpy ((char *)&sin.sin_addr, he->h_addr, he->h_length);
		sin.sin_family = AF_INET;
		sin.sin_port = htons(port);

		if ((ptyfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
			die("socket(): %s", geterr(errno));
		if (connect(ptyfd, (struct sockaddr *)&sin, sizeof(sin)) < 0)
			die("connect(): %s", geterr(errno));
Mike Hibler's avatar
Mike Hibler committed
553
		snprintf(key.key, sizeof(key.key), "RELAY %d", portnum);
Timothy Stack's avatar
 
Timothy Stack committed
554 555 556
		key.keylen = strlen(key.key);
		if (write(ptyfd, &key, sizeof(key)) != sizeof(key))
			die("write(): %s", geterr(errno));
557
#ifdef  WITHSSL
Timothy Stack's avatar
 
Timothy Stack committed
558 559 560 561 562 563 564 565 566 567
		initializessl();
		sslRelay = SSL_new(ctx);
		if (!sslRelay)
			die("SSL_new()");
		if (SSL_set_fd(sslRelay, ptyfd) <= 0)
			die("SSL_set_fd()");
		if (SSL_connect(sslRelay) <= 0)
			die("SSL_connect()");
		if (sslverify(sslRelay, "Capture Server"))
			die("SSL connection did not verify");
568
#endif
Timothy Stack's avatar
 
Timothy Stack committed
569 570 571 572 573 574 575 576 577 578 579 580 581 582 583
		if (fcntl(ptyfd, F_SETFL, O_NONBLOCK) < 0)
			die("fcntl(O_NONBLOCK): %s", geterr(errno));
		tipactive = 1;
	}

	if (relay_rcv) {
		struct hostent *he;

		he = gethostbyname(argv[1]);
		if (he == 0) {
			die("gethostbyname(%s): %s",
			    argv[1], hstrerror(h_errno));
		}
		memcpy ((char *)&relayaddr, he->h_addr, he->h_length);
	}
584
#else
585
	if ((ptyfd = open(Ptyname, O_RDWR)) < 0)
586
		die("%s: open: %s", Ptyname, geterr(errno));
587
#endif
Timothy Stack's avatar
 
Timothy Stack committed
588 589 590 591 592 593 594 595 596
	
	if (!relay_snd) {
		if ((logfd = open(Logname,O_WRONLY|O_CREAT|O_APPEND,0640)) < 0)
			die("%s: open: %s", Logname, geterr(errno));
		if (chmod(Logname, 0640) < 0)
			die("%s: chmod: %s", Logname, geterr(errno));
	}
	
	if (!relay_rcv) {
597
#ifdef  USESOCKETS
598 599 600 601
	    if (remotemode) {
		if (netmode() != 0)
		    die("Could not establish connection to %s\n", Devname);
	    }
602 603
	    else
#endif
604
		    rawmode(Devname, speed);
Timothy Stack's avatar
 
Timothy Stack committed
605
	}
606 607 608 609 610 611
	writepid();
	capture();
	cleanup();
	exit(0);
}

612 613 614
#ifdef TWOPROCESS
int	pid;

615
void
616
capture(void)
617
{
Mike Hibler's avatar
Mike Hibler committed
618 619
	int flags = FNDELAY;

620 621 622 623 624 625 626 627 628 629 630 631
	(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.
 */
632
in(void)
633
{
634
	char buf[BUFSIZE];
635 636
	int cc;
	sigset_t omask;
637 638
	
	while (1) {
639
		if ((cc = read(devfd, buf, BUFSIZE)) < 0) {
640 641 642
			if ((errno == EWOULDBLOCK) || (errno == EINTR))
				continue;
			else
643
				die("%s: read: %s", Devname, geterr(errno));
644
		}
645
		sigprocmask(SIG_BLOCK, &actionsigmask, &omask);
646 647

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

650 651
		if (runfile) {
			if (write(runfd, buf, cc) < 0)
652
				die("%s: write: %s", Runname, geterr(errno));
653 654
		}

655 656
		if (write(ptyfd, buf, cc) < 0) {
			if ((errno != EIO) && (errno != EWOULDBLOCK))
657
				die("%s: write: %s", Ptyname, geterr(errno));
658
		}
659
		sigprocmask(SIG_SETMASK, &omask, NULL);
660 661 662 663 664 665
	}
}

/*
 * Loop reading input from pty (tip), and send off to the console device.
 */
666
out(void)
667
{
668
	char buf[BUFSIZE];
669 670
	int cc;
	sigset_t omask;
671 672 673 674 675 676
	struct timeval timeout;

	timeout.tv_sec  = 0;
	timeout.tv_usec = 100000;
	
	while (1) {
677
		sigprocmask(SIG_BLOCK, &actionsigmask, &omask);
678
		if ((cc = read(ptyfd, buf, BUFSIZE)) < 0) {
679
			sigprocmask(SIG_SETMASK, &omask, NULL);
680 681 682 683 684 685
			if ((errno == EIO) || (errno == EWOULDBLOCK) ||
			    (errno == EINTR)) {
				select(0, 0, 0, 0, &timeout);
				continue;
			}
			else
686
				die("%s: read: %s", Ptyname, geterr(errno));
687 688 689
		}

		if (write(devfd, buf, cc) < 0)
690
			die("%s: write: %s", Devname, geterr(errno));
691
		
692
		sigprocmask(SIG_SETMASK, &omask, NULL);
693 694 695
	}
}
#else
696 697
static fd_set	sfds;
static int	fdcount;
698
void
699
capture(void)
700
{
701
	fd_set fds;
702 703
	int i, cc, lcc;
	sigset_t omask;
704
	char buf[BUFSIZE];
705
	struct timeval timeout;
706 707 708 709
#ifdef LOG_DROPS
	int drop_topty_chars = 0;
	int drop_todev_chars = 0;
#endif
710

711 712 713 714 715 716 717 718 719 720 721 722 723
	/*
	 * 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...
	 */
Timothy Stack's avatar
 
Timothy Stack committed
724
	if ((devfd >= 0) && (fcntl(devfd, F_SETFL, O_NONBLOCK) < 0))
725
		die("%s: fcntl(O_NONBLOCK): %s", Devname, geterr(errno));
726
#ifndef USESOCKETS
727 728 729 730 731 732 733 734 735 736 737 738
	/*
	 * 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__
739
	if ((i = open(Ttyname, O_RDONLY)) < 0)
740 741 742 743 744
		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__
745
	close(i);
746
#endif
747
#endif /* USESOCKETS */
748 749

	FD_ZERO(&sfds);
Timothy Stack's avatar
 
Timothy Stack committed
750 751
	if (devfd >= 0)
		FD_SET(devfd, &sfds);
752 753 754 755 756 757
	fdcount = devfd;
#ifdef  USESOCKETS
	if (devfd < sockfd)
		fdcount = sockfd;
	FD_SET(sockfd, &sfds);
#endif	/* USESOCKETS */
Timothy Stack's avatar
 
Timothy Stack committed
758 759 760 761 762
	if (ptyfd >= 0) {
		if (devfd < ptyfd)
			fdcount = ptyfd;
		FD_SET(ptyfd, &sfds);
	}
763 764 765

	fdcount++;

766
	for (;;) {
767 768
#ifdef LOG_DROPS
		if (drop_topty_chars >= DROP_THRESH) {
769 770
			warning("%d dev -> pty chars dropped",
				drop_topty_chars);
771 772 773
			drop_topty_chars = 0;
		}
		if (drop_todev_chars >= DROP_THRESH) {
774 775
			warning("%d pty -> dev chars dropped",
				drop_todev_chars);
776
			drop_todev_chars = 0;
777
		}
778
#endif
779
		fds = sfds;
780
		timeout.tv_usec = 0;
781
		timeout.tv_sec  = 30;
782
#ifdef	USESOCKETS
783 784 785
		if (needshake) {
			timeout.tv_sec += (random() % 60);
		}
786 787
#endif
		i = select(fdcount, &fds, NULL, NULL, &timeout);
788 789
		if (i < 0) {
			if (errno == EINTR) {
790
				warning("input select interrupted, continuing");
791 792
				continue;
			}
793
			die("%s: select: %s", Devname, geterr(errno));
794
		}
795
		if (i == 0) {
796 797
#ifdef	USESOCKETS
			if (needshake) {
Mike Hibler's avatar
Mike Hibler committed
798
				(void) handshake();
799 800 801
				continue;
			}
#endif
802 803
			continue;
		}
804 805
#ifdef	USESOCKETS
		if (FD_ISSET(sockfd, &fds)) {
Mike Hibler's avatar
Mike Hibler committed
806
			(void) clientconnect();
807
		}
Timothy Stack's avatar
 
Timothy Stack committed
808
		if ((upfd >=0) && FD_ISSET(upfd, &fds)) {
Mike Hibler's avatar
Mike Hibler committed
809
			(void) handleupload();
Timothy Stack's avatar
 
Timothy Stack committed
810
		}
811
#endif	/* USESOCKETS */
Timothy Stack's avatar
 
Timothy Stack committed
812
		if ((devfd >= 0) && FD_ISSET(devfd, &fds)) {
813
			errno = 0;
Timothy Stack's avatar
 
Timothy Stack committed
814 815 816 817 818 819 820 821 822 823 824 825 826
#ifdef  WITHSSL
			if (relay_rcv) {
			  cc = SSL_read(sslRelay, buf, sizeof(buf));
			  if (cc <= 0) {
			    FD_CLR(devfd, &sfds);
			    devfd = -1;
			    bzero(&relayclient, sizeof(relayclient));
			    continue;
			  }
			}
			else
#endif
			  cc = read(devfd, buf, sizeof(buf));
827 828 829 830 831
			if (cc <= 0) {
#ifdef  USESOCKETS
				if (remotemode) {
					FD_CLR(devfd, &sfds);
					close(devfd);
832 833 834 835 836
					warning("remote socket closed;"
						"attempting to reconnect");
					while (netmode() != 0) {
					    usleep(5000000);
					}
837 838 839 840 841 842 843 844 845 846
					FD_SET(devfd, &sfds);
					continue;
				}
#endif
				if (cc < 0)
					die("%s: read: %s",
					    Devname, geterr(errno));
				if (cc == 0)
					die("%s: read: EOF", Devname);
			}
847 848
			errno = 0;

849
			sigprocmask(SIG_BLOCK, &actionsigmask, &omask);
850 851 852 853
#ifdef	USESOCKETS
			if (!tipactive)
				goto dropped;
#endif
854
			for (lcc = 0; lcc < cc; lcc += i) {
855
#ifdef  WITHSSL
Timothy Stack's avatar
 
Timothy Stack committed
856 857 858 859
				if (relay_snd) {
					i = SSL_write(sslRelay, &buf[lcc], cc-lcc);
				}
			        else if (sslCon != NULL) {
860 861 862 863 864 865 866
				        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);
				}
867
				if (i < 0) {
868 869 870 871 872 873 874
					/*
					 * 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.
					 */
875
					if (errno == EIO || errno == EAGAIN) {
876 877
#ifdef LOG_DROPS
						drop_topty_chars += (cc-lcc);
878 879 880
#endif
						goto dropped;
					}
881
					die("%s: write: %s",
882 883
					    Ptyname, geterr(errno));
				}
884 885
				if (i == 0) {
#ifdef	USESOCKETS
886
					sigprocmask(SIG_SETMASK, &omask, NULL);
887 888
					goto disconnected;
#else
889
					die("%s: write: zero-length", Ptyname);
890 891
#endif
				}
892 893
			}
dropped:
894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912
			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;
			}
Timothy Stack's avatar
 
Timothy Stack committed
913 914 915 916 917 918 919
			if (logfd >= 0) {
				i = write(logfd, buf, cc);
				if (i < 0)
					die("%s: write: %s", Logname, geterr(errno));
				if (i != cc)
					die("%s: write: incomplete", Logname);
			}
920 921 922
			if (runfile) {
				i = write(runfd, buf, cc);
				if (i < 0)
923
					die("%s: write: %s",
924 925
					    Runname, geterr(errno));
				if (i != cc)
926
					die("%s: write: incomplete", Runname);
927
			}
928
			sigprocmask(SIG_SETMASK, &omask, NULL);
929 930

		}
Timothy Stack's avatar
 
Timothy Stack committed
931
		if ((ptyfd >= 0) && FD_ISSET(ptyfd, &fds)) {
932 933
			int lerrno;

934
			sigprocmask(SIG_BLOCK, &actionsigmask, &omask);
935
			errno = 0;
936
#ifdef WITHSSL
Timothy Stack's avatar
 
Timothy Stack committed
937 938 939 940 941 942 943 944 945 946
			if (relay_snd) {
				cc = SSL_read( sslRelay, buf, sizeof(buf) );
				if (cc < 0) { /* XXX hack */
					cc = 0;
					SSL_free(sslRelay);
					sslRelay = NULL;
					upportnum = -1;
				}
			}
			else if (sslCon != NULL) {
947
			        cc = SSL_read( sslCon, buf, sizeof(buf) );
Timothy Stack's avatar
 
Timothy Stack committed
948 949 950 951 952
				if (cc < 0) { /* XXX hack */
					cc = 0;
					SSL_free(sslCon);
					sslCon = NULL;
				}
953 954 955
			} else
#endif /* WITHSSL */ 
			{
Timothy Stack's avatar
 
Timothy Stack committed
956
			        cc = read(ptyfd, buf, sizeof(buf));
957
			}
958
			lerrno = errno;
959
			sigprocmask(SIG_SETMASK, &omask, NULL);
960 961
			if (cc < 0) {
				/* XXX commonly observed */
962
				if (lerrno == EIO || lerrno == EAGAIN)
963
					continue;
964
#ifdef	USESOCKETS
965
				if (lerrno == ECONNRESET || lerrno == ETIMEDOUT)
966
					goto disconnected;
967 968 969 970
				die("%s: socket read: %s",
				    Machine, geterr(lerrno));
#else
				die("%s: read: %s", Ptyname, geterr(lerrno));
971
#endif
972 973
			}
			if (cc == 0) {
974 975 976 977 978
#ifdef	USESOCKETS
			disconnected:
				/*
				 * Other end disconnected.
				 */
Timothy Stack's avatar
 
Timothy Stack committed
979 980
				if (relay_snd)
					die("relay receiver died");
981 982 983 984 985 986
				dolog(LOG_INFO, "%s disconnecting",
				      inet_ntoa(tipclient.sin_addr));
				FD_CLR(ptyfd, &sfds);
				close(ptyfd);
				tipactive = 0;
				continue;
987
#else
988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005
				/*
				 * 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);
1006
				continue;
1007
#endif
1008 1009 1010
			}
			errno = 0;

1011
			sigprocmask(SIG_BLOCK, &actionsigmask, &omask);
1012
			for (lcc = 0; lcc < cc; lcc += i) {
Timothy Stack's avatar
 
Timothy Stack committed
1013 1014
				if (relay_rcv) {
#ifdef USESOCKETS
1015
#ifdef  WITHSSL
Timothy Stack's avatar
 
Timothy Stack committed
1016 1017 1018 1019
					if (sslRelay != NULL) {
						i = SSL_write(sslRelay,
							      &buf[lcc],
							      cc - lcc);
1020 1021 1022
					} else
#endif
					{
Timothy Stack's avatar
 
Timothy Stack committed
1023 1024 1025 1026 1027 1028 1029
						i = cc - lcc;
					}
#endif
				}
				else {
					i = write(devfd, &buf[lcc], cc-lcc);
				}
1030
				if (i < 0) {
1031 1032 1033 1034
					/*
					 * Device backed up (or FUBARed)
					 * Note that we dropped some chars.
					 */
1035
					if (errno == EAGAIN) {
1036 1037 1038
#ifdef LOG_DROPS
						drop_todev_chars += (cc-lcc);
#endif
1039 1040
						goto dropped2;
					}
1041
					die("%s: write: %s",
1042 1043 1044
					    Devname, geterr(errno));
				}
				if (i == 0)
1045
					die("%s: write: zero-length", Devname);
1046 1047
			}
dropped2:
1048
			sigprocmask(SIG_SETMASK, &omask, NULL);
1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066
		}
	}
}
#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);
	
1067
	if ((logfd = open(Logname, O_WRONLY|O_CREAT|O_APPEND, 0640)) < 0)
1068
		die("%s: open: %s", Logname, geterr(errno));
1069
	if (chmod(Logname, 0640) < 0)
1070
		die("%s: chmod: %s", Logname, geterr(errno));
1071 1072 1073 1074 1075 1076 1077 1078
	
	dolog(LOG_NOTICE, "new log started");

	if (runfile)
		newrun(sig);
}

/*
1079 1080 1081
 * 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.
1082 1083 1084 1085 1086 1087 1088 1089 1090
 */
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);
1091
	unlink(Runname);
1092

1093
	if ((runfd = open(Runname, O_WRONLY|O_CREAT|O_APPEND, 0600)) < 0)
1094
		die("%s: open: %s", Runname, geterr(errno));
1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106

#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));
1107 1108 1109
	
	dolog(LOG_NOTICE, "new run started");
}
1110

1111 1112
/*
 * SIGUSR2 means we want to revoke the other side of the pty to close the
1113 1114 1115
 * 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.
1116 1117
 */
void
1118
terminate(int sig)
1119
{
1120
#ifdef	USESOCKETS
1121 1122 1123 1124 1125 1126 1127 1128 1129 1130
	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");