capture.c 47.8 KB
Newer Older
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1
2
/*
 * EMULAB-COPYRIGHT
3
 * Copyright (c) 2000-2012 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
int	stamplast = 0;
128
129
sigset_t actionsigmask;
sigset_t allsigmask;
130
int	 powermon = 0;
Timothy Stack's avatar
   
Timothy Stack committed
131
132
133
#ifndef  USESOCKETS
#define relay_snd 0
#define relay_rcv 0
134
#define remotemode 0
Timothy Stack's avatar
   
Timothy Stack committed
135
#else
136
char		  *Bossnode = BOSSNODE;
Mike Hibler's avatar
Mike Hibler committed
137
struct sockaddr_in Bossaddr;
138
139
char		  *Aclname;
int		   serverport = SERVERPORT;
Timothy Stack's avatar
   
Timothy Stack committed
140
int		   sockfd, tipactive, portnum, relay_snd, relay_rcv;
141
int		   remotemode;
Timothy Stack's avatar
   
Timothy Stack committed
142
143
144
int		   upportnum = -1, upfd = -1, upfilefd = -1;
char		   uptmpnam[64];
size_t		   upfilesize = 0;
145
struct sockaddr_in tipclient;
Timothy Stack's avatar
   
Timothy Stack committed
146
147
struct sockaddr_in relayclient;
struct in_addr	   relayaddr;
148
149
150
secretkey_t	   secretkey;
char		   ourhostname[MAXHOSTNAMELEN];
int		   needshake;
151
152
gid_t		   tipgid;
uid_t		   tipuid;
Timothy Stack's avatar
   
Timothy Stack committed
153
char		  *uploadCommand;
154
155
156
157
158

#ifdef  WITHSSL

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

int initializedSSL = 0;

const char * certfile = NULL;
Timothy Stack's avatar
   
Timothy Stack committed
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
294
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;
	}
295

Timothy Stack's avatar
   
Timothy Stack committed
296
297
298
299
300
301
302
303
304
305
306
307
308
	/*
	 * 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;
}
309
310
#endif /* WITHSSL */ 
#endif /* USESOCKETS */
311
312

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

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

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

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

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

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

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

		case 'r':
			runfile++;
			break;

365
366
367
368
369
		case 's':
			if ((i = atoi(optarg)) == 0 ||
			    (speed = val2speed(i)) == 0)
				usage();
			break;
370
371
372
		case 'L':
			stamplast = 1;
			break;
373
374
375
376
377
		case 'T':
			stampinterval = atoi(optarg);
			if (stampinterval < 0)
				usage();
			break;
378
379
380
		case 'P':
			powermon = 1;
			break;
Timothy Stack's avatar
   
Timothy Stack committed
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
#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
398
399
400
401
402
403
404
405
		}

	argc -= optind;
	argv += optind;

	if (argc != 2)
		usage();

406
407
408
	if (!debug)
		(void)daemon(0, 0);

409
410
	Machine = argv[0];

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

428
	openlog(Progname, LOG_PID, LOG_TESTBED);
429
430
	dolog(LOG_NOTICE, "starting");

431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
	/*
	 * 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
447
448
449
450
451
	if (!relay_snd) {
		sa.sa_handler = reinit;
		sa.sa_mask = actionsigmask;
		sigaction(SIGHUP, &sa, NULL);
	}
452
453
454
455
456
457
458
	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
459
#ifdef HAVE_SRANDOMDEV
460
	srandomdev();
Timothy Stack's avatar
   
Timothy Stack committed
461
462
463
#else
	srand(time(NULL));
#endif
464
	
465
	/*
466
	 * Open up run/log file, console tty, and controlling pty.
467
	 */
468
	if (runfile) {
469
470
471
		unlink(Runname);
		
		if ((runfd = open(Runname,O_WRONLY|O_CREAT|O_APPEND,0600)) < 0)
472
			die("%s: open: %s", Runname, geterr(errno));
473
474
		if (fchmod(runfd, 0640) < 0)
			die("%s: fchmod: %s", Runname, geterr(errno));
475
	}
476
#ifdef  USESOCKETS
Mike Hibler's avatar
Mike Hibler committed
477
478
479
	/*
	 * Verify the bossnode and stash the address info
	 */
Mike Hibler's avatar
Mike Hibler committed
480
481
482
483
484
485
486
487
488
489
490
	{
		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
491
492
	}

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

524
525
	if (gethostname(ourhostname, sizeof(ourhostname)) < 0)
		die("gethostname(): %s", geterr(errno));
526

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

	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
557
		snprintf(key.key, sizeof(key.key), "RELAY %d", portnum);
Timothy Stack's avatar
   
Timothy Stack committed
558
559
560
		key.keylen = strlen(key.key);
		if (write(ptyfd, &key, sizeof(key)) != sizeof(key))
			die("write(): %s", geterr(errno));
561
#ifdef  WITHSSL
Timothy Stack's avatar
   
Timothy Stack committed
562
563
564
565
566
567
568
569
570
571
		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");
572
#endif
Timothy Stack's avatar
   
Timothy Stack committed
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
		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);
	}
588
#else
589
	if ((ptyfd = open(Ptyname, O_RDWR)) < 0)
590
		die("%s: open: %s", Ptyname, geterr(errno));
591
#endif
Timothy Stack's avatar
   
Timothy Stack committed
592
593
594
595
596
597
598
599
600
	
	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) {
601
#ifdef  USESOCKETS
602
603
604
605
	    if (remotemode) {
		if (netmode() != 0)
		    die("Could not establish connection to %s\n", Devname);
	    }
606
607
	    else
#endif
608
		    rawmode(Devname, speed);
Timothy Stack's avatar
   
Timothy Stack committed
609
	}
610
611
612
613
614
615
	writepid();
	capture();
	cleanup();
	exit(0);
}

616
617
618
#ifdef TWOPROCESS
int	pid;

619
void
620
capture(void)
621
{
Mike Hibler's avatar
Mike Hibler committed
622
623
	int flags = FNDELAY;

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

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

654
655
		if (runfile) {
			if (write(runfd, buf, cc) < 0)
656
				die("%s: write: %s", Runname, geterr(errno));
657
658
		}

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

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

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

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

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

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

	fdcount++;

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

853
			sigprocmask(SIG_BLOCK, &actionsigmask, &omask);
854
855
856
857
#ifdef	USESOCKETS
			if (!tipactive)
				goto dropped;
#endif
858
			for (lcc = 0; lcc < cc; lcc += i) {
859
#ifdef  WITHSSL
Timothy Stack's avatar
   
Timothy Stack committed
860
861
862
863
				if (relay_snd) {
					i = SSL_write(sslRelay, &buf[lcc], cc-lcc);
				}
			        else if (sslCon != NULL) {
864
865
866
867
868
869
870
				        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);
				}
871
				if (i < 0) {
872
873
874
875
876
877
878
					/*
					 * 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.
					 */
879
					if (errno == EIO || errno == EAGAIN) {
880
881
#ifdef LOG_DROPS
						drop_topty_chars += (cc-lcc);
882
883
884
#endif
						goto dropped;
					}
885
					die("%s: write: %s",
886
887
					    Ptyname, geterr(errno));
				}
888
889
				if (i == 0) {
#ifdef	USESOCKETS
890
					sigprocmask(SIG_SETMASK, &omask, NULL);
891
892
					goto disconnected;
#else
893
					die("%s: write: zero-length", Ptyname);
894
895
#endif
				}
896
897
			}
dropped:
898
899
900
			if (stampinterval >= 0) {
				static time_t laststamp;
				struct timeval tv;
901
902
				char stampbuf[64], *cts;
				time_t now, delta;
903
904
905

				gettimeofday(&tv, 0);
				now = tv.tv_sec;
906
				delta = now - laststamp;
907
				if (stampinterval == 0 ||
908
				    delta > stampinterval) {
909
910
					cts = ctime(&now);
					cts[24] = 0;
911
912
913
914
915
916
917
918
919
920
					if (stamplast && laststamp)
						snprintf(stampbuf,
							 sizeof stampbuf,
							 "\nSTAMP{%u@%s}\n",
							 (unsigned)delta, cts);
					else
						snprintf(stampbuf,
							 sizeof stampbuf,
							 "\nSTAMP{%s}\n",
							 cts);
921
922
923
924
925
					write(logfd, stampbuf,
					      strlen(stampbuf));
				}
				laststamp = now;
			}
Timothy Stack's avatar
   
Timothy Stack committed
926
927
928
929
930
931
932
			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);
			}
933
934
935
			if (runfile) {
				i = write(runfd, buf, cc);
				if (i < 0)
936
					die("%s: write: %s",
937
938
					    Runname, geterr(errno));
				if (i != cc)
939
					die("%s: write: incomplete", Runname);
940
			}
941
			sigprocmask(SIG_SETMASK, &omask, NULL);
942
943

		}
Timothy Stack's avatar
   
Timothy Stack committed
944
		if ((ptyfd >= 0) && FD_ISSET(ptyfd, &fds)) {
945
946
			int lerrno;

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

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

	if (runfile)
		newrun(sig);
}

/*
1092
1093
1094
 * 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.
1095
1096
1097
1098
1099
1100
1101
1102
1103
 */
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);
1104
	unlink(Runname);
1105

1106
	if ((runfd = open(Runname, O_WRONLY|O_CREAT|O_APPEND, 0600)) < 0)
1107
		die("%s: open: %s", Runname, geterr(errno));
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119

#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));
1120
1121
1122
	
	dolog(LOG_NOTICE, "new run started");
}
1123

1124
1125
/*
 * SIGUSR2 means we want to revoke the other side of the pty to close the
1126
1127
1128
 * 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.
1129
1130
 */
void
1131
terminate(int sig)
1132
{
1133
#ifdef	USESOCKETS
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
	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");
1144

1145
1146
1147
1148
	tipuid = tipgid = 0;
	if (runfile)
		newrun(sig);

1149
1150
	/* Must be done *after* all the above stuff is done! */
	createkey();
1151
#else
1152
1153
1154
1155
1156
1157
	int ofd = ptyfd;
	
	/*
	 * We know that the any pending access to the pty completed
	 * because we blocked SIGUSR2 during the operation.
	 */
1158
1159
1160
	tcflush(ptyfd, TCIOFLUSH);
	if (revoke(Ttyname) < 0)
		dolog(LOG_WARNING, "could not revoke access to tty");
1161
1162
	close(ptyfd);
	
1163
	if ((ptyfd = open(Ptyname, O_RDWR)) < 0)
1164
		die("%s: open: %s", Ptyname, geterr(errno));
1165
1166
1167
1168
1169
1170
1171
1172

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

1173
1174
#ifdef __FreeBSD__
	/* see explanation in capture() above */
1175
	if ((ofd = open(Ttyname, O_RDONLY)) < 0)
1176
1177
		die("%s: open: %s", Ttyname, geterr(errno));
#endif
1178
	if (fcntl(ptyfd, F_SETFL, O_NONBLOCK) < 0)
1179
1180
1181
1182
		die("%s: fcntl(O_NONBLOCK): %s", Ptyname, geterr(errno));
#ifdef __FreeBSD__
	close(ofd);
#endif
1183
1184
	
	dolog(LOG_NOTICE, "pty reset");
1185
#endif	/* USESOCKETS */
1186
1187
1188
1189
1190
}

/*
 *  Display proper usage / error message and exit.
 */
1191
1192
1193
char *optstr =
#ifdef USESOCKETS
#ifdef WITHSSL
Timothy Stack's avatar
   
Timothy Stack committed
1194
"[-c certfile] [-v calist] [-u uploadcmd] "
1195
1196
1197
#endif
"[-b bossnode] [-p bossport] [-i] "
#endif
1198
"-HdraoPL [-s speed] [-T stampinterval]";
1199
void
1200
usage(void)
1201
{
1202
	fprintf(stderr, "usage: %s %s machine tty\n", Progname, optstr);
1203
1204
1205
	exit(1);
}

1206
void
1207
warning(char *format, ...)
1208
{
1209
	char msgbuf[BUFSIZE];
1210
	va_list ap;
1211

1212
1213
1214
	va_start(ap, format);
	vsnprintf(msgbuf, BUFSIZE, format, ap);
	va_end(ap);
1215