pcapper.c 40.9 KB
Newer Older
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1
2
/*
 * EMULAB-COPYRIGHT
3
 * Copyright (c) 2000-2006 University of Utah and the Flux Group.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
4
5
6
 * All rights reserved.
 */

Robert Ricci's avatar
Robert Ricci committed
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/*
 * pcapper.c - Program to count the number of various types of IP packets
 * traveling accross a node's interfaces.
 *
 * TODO:
 *     Allow counting packets based upon tcpdump-style filter expressions
 *     More fine-grained locking
 */

/*
 * These seem to make things happier when compiling on Linux
 */
#ifdef __linux__
#define __PREFER_BSD
#define __USE_BSD
22
23
24
#define __FAVOR_BSD
#define uh_ulen len
#define th_off doff
Robert Ricci's avatar
Robert Ricci committed
25
26
27
28
29
30
31
32
33
34
35
36
37
#endif

#include <sys/types.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/ioctl.h>

#ifdef __linux__
#include <linux/sockios.h>
#else
#include <sys/sockio.h>
#endif

38
#include <netinet/in_systm.h>
Robert Ricci's avatar
Robert Ricci committed
39
40
41
#include <net/ethernet.h>
#include <net/if.h>
#include <netinet/in.h>
42
43
44
#include <netinet/ip.h>
#include <netinet/tcp.h>
#include <netinet/udp.h>
Robert Ricci's avatar
Robert Ricci committed
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <arpa/inet.h>

#include <err.h>
#include <errno.h>
#include <fcntl.h>
#include <netdb.h>
#include <pcap.h>
#include <pthread.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

59
60
61
62
63
64
#ifdef EVENTSYS
#include "event.h"
#include "tbdefs.h"
#include "log.h"
#endif

Robert Ricci's avatar
Robert Ricci committed
65
#define PORT 4242
66
67
68
#define MAX_INTERFACES 16
#define MAX_FILES 16
#define MAX_CLIENTS 8
Robert Ricci's avatar
Robert Ricci committed
69
70
71
72

/*
 * Program run to determine the control interface.
 */
73
#define CONTROL_IFACE CLIENT_BINDIR "/control_interface"
Robert Ricci's avatar
Robert Ricci committed
74

75
76
77
78
79
80
/*
 * Wire overhead not seen by pcapper:
 *	interframe gap (12) + preamble (8) + CRC (4)
 */
#define INVISIBLE_ETHSIZE	24

Robert Ricci's avatar
Robert Ricci committed
81
/*
82
 * A struct definitions shamelessly stolen from tcpdump.org
Robert Ricci's avatar
Robert Ricci committed
83
84
85
86
87
88
89
90
91
 */

/* Ethernet header */
struct sniff_ethernet {
	u_char ether_dhost[ETHER_ADDR_LEN]; /* Destination host address */
	u_char ether_shost[ETHER_ADDR_LEN]; /* Source host address */
	u_short ether_type; /* IP? ARP? RARP? etc */
};

92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
#ifdef __linux__
#undef VETH
#endif

#ifdef VETH

#ifndef ETHERTYPE_VETH
#define ETHERTYPE_VETH	0x80FF
#endif

/* Encapsulated ethernet header */
struct sniff_veth {
	/* physical info */
	u_char ether_dhost[ETHER_ADDR_LEN]; /* Destination host address */
	u_char ether_shost[ETHER_ADDR_LEN]; /* Source host address */
	u_short ether_type; /* VETH */
	/* virtual info */
	u_short veth_tag;
	u_char veth_dhost[ETHER_ADDR_LEN]; /* Destination host address */
	u_char veth_shost[ETHER_ADDR_LEN]; /* Source host address */
	u_short veth_type; /* IP? ARP? RARP? etc */
};
#endif

Robert Ricci's avatar
Robert Ricci committed
116
117
118
119
120
121
122
/*
 * Arguments to the readpackets function - passed in a struct since
 * pthread-starting functions take a single void* as a parameter.
 */
struct readpackets_args {
	u_char index;
	char *devname;
123
	char *bpf_filter;
124
	pcap_dumper_t *pdumper;
Robert Ricci's avatar
Robert Ricci committed
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
};

/*
 * Arguments to the feedclient function.
 */
struct feedclient_args {
	int cli;
	int fd;
	int interval;
};

/*
 * Counts that we keep per-interface, per-interval.
 */
struct counter {
	unsigned int icmp_bytes;
	unsigned int tcp_bytes;
	unsigned int udp_bytes;
143
144
145
#ifdef VETH
	unsigned int veth_bytes;
#endif
Robert Ricci's avatar
Robert Ricci committed
146
147
148
149
150
	unsigned int other_bytes;

	unsigned int icmp_packets;
	unsigned int tcp_packets;
	unsigned int udp_packets;
151
152
153
#ifdef VETH
	unsigned int veth_packets;
#endif
Robert Ricci's avatar
Robert Ricci committed
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
	unsigned int other_packets;
};

/*
 * Per-interface, per-interval structure, that keeps track of the next
 * interval as where, and when they begin and end.
 */
struct interface_counter {
	/*
	 * The start and end times for this interval, so that we can tell if
	 * a packet got noticed way too late, or if the client-feeding thread
	 * has missed its deadline, and we need to roll over into the next
	 * interval.
	 */
	struct timeval start_time;
	struct timeval rollover;

	/*
	 * Client-feeding threads report data from this_interval. But, if the
	 * interface-watching thread notices that the rollover time has passed,
	 * it counts the packets toward the next_interval. Rather than zeroing
	 * out this_interval after reporting it, the client-feeding threads
	 * copy in next_interval.
	 */
	struct counter this_interval;
	struct counter next_interval;
};

/*
 * Forward declarations
 */
void *readpackets(void *args);
void *feedclient(void *args);
187
void *runeventsys(void *args);
Robert Ricci's avatar
Robert Ricci committed
188
189
190
void got_packet(u_char *args, const struct pcap_pkthdr *header,
	const u_char *packet);
int getaddr(char *dev, struct in_addr *addr);
191
192
193
194
195
#ifdef EVENTSYS
static void
callback(event_handle_t handle,
	event_notification_t notification, void *data);
#endif
Robert Ricci's avatar
Robert Ricci committed
196
197
198
199
200
201
202
203
204
205
206
207
208
209

/*
 * Number of interfaces we've detected, and their names.
 */
int interfaces = 0;
char interface_names[MAX_INTERFACES][1024];

/*
 * Number of packets that are discovered in the correct interval, and those
 * that come in "early" (ie. after the rollover time, but before the client-
 * feeding thread has woken up.) For statistical purposes.
 */
int ontime_packets = 0, early_packets = 0;

210
211
212
213
214
215
216
217
218
219
/*
 * Nonzero if we're supposed to count payload only
 */
int payload_only = 0;

/*
 * Nonzero if we're supposed to add ethernet headers to the packet size
 */
int add_ethernet = 0;

220
221
222
223
224
/*
 * Nonzero if we're supposed to add ALL ethernet overhead to the packet size
 */
int add_all_ethernet = 0;

225
226
227
228
229
230
/*
 * Nonzero if we're supposed to _not_ count zero-sized packets in the
 * packet counts (obviously, they're already ignored in the byte counts.
 */
int no_zero = 0;

231
232
233
234
235
/*
 * Whether we should include or skip interfaces that have no IP address
 */
int include_ipless_interfaces = 0;

Leigh B. Stoller's avatar
Leigh B. Stoller committed
236
237
238
239
240
/*
 * For "capture" mode (-c option).
 */
int capture_mode    = 0;
int capture_snaplen = 64;
241
242
243
244
245

/*
 * For the event system control function.
 */
volatile int killme = 0;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
246
247
volatile int stop   = 0;
volatile int reload = 0;
248
char *reload_tag = NULL;
249
unsigned int reload_token = ~0;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
250

251
252
253
254
255
256
257
258
259
260
261
#ifdef EVENTSYS
/*
 * Time to subtract out of each timestamp reported to clients - this allows
 * us to report times relative to event system time start events.
 */
struct timeval start_time;

/*
 * 1 if we're adjusting timestamps by start_time, 0 otherwise
 */
int adjust_time = 0;
262
263
264

/* For the subscription. */
char *pideid;
265
266
#endif

Robert Ricci's avatar
Robert Ricci committed
267
268
269
270
271
272
273
274
275
276
/*
 * For getopt()
 */
extern char *optarg;
extern int optind;
extern int optopt;
extern int opterr;
extern int optreset;

/*
277
 * Lock used to make sure that the threads don't clobber the packet counts.
Robert Ricci's avatar
Robert Ricci committed
278
279
280
281
 * We just use one big fat lock for all of them.
 */
pthread_mutex_t lock;

282
/*
283
 * A libc and libpcap lock, since we are using linuxthreads and plain libc.
284
 */
285
pthread_mutex_t lib_lock;
286

287
288
289
290
291
/*
 * Condition variable for device threads to wait on for activity.
 */
pthread_cond_t cond;

Robert Ricci's avatar
Robert Ricci committed
292
293
294
295
296
297
298
299
300
301
302
/*
 * Pakcet counts for the three types of packets that we care about. 
 */
struct interface_counter counters[MAX_CLIENTS][MAX_INTERFACES];

/*
 * Keep track of the pcap devices, since we need them for things like
 * getting counts of packets dropped by the kernel.
 */
pcap_t *pcap_devs[MAX_INTERFACES];

Leigh B. Stoller's avatar
Leigh B. Stoller committed
303
304
305
306
307
/*
 * Also keep track of packet reader threads so we can kill them.
 */
pthread_t getpacket_threads[MAX_INTERFACES];

Robert Ricci's avatar
Robert Ricci committed
308
309
310
311
312
/*
 * An array of 'bools', indicating if any client is using that number.
 */
int client_connected[MAX_CLIENTS];

Leigh B. Stoller's avatar
Leigh B. Stoller committed
313
314
315
316
317
/*
 * An array of output filenames.
 */
char *filenames[MAX_FILES];

318
319
320
321
322
/*
 * Number of active clients.  When count is zero, the device is closed.
 */
volatile int active;

Leigh B. Stoller's avatar
Leigh B. Stoller committed
323
324
325
/* A debugging flag */
int debug = 0;

Robert Ricci's avatar
Robert Ricci committed
326
327
int MAX(int a, int b) { if ((a) > (b)) return (a); else return (b); }

328
329
330
331
332
void usage(char *progname) {
    char *short_usage = "Usage: %s [-f filename] [-i interval] [-p] "
#ifdef EVENTSYS
			"[-e eid/pid] "
#endif
333
334
			"[interfaces...]\n"
                        "       %s [options] -t interface 'filter' ... ";
335
336
337
338
339
    char *long_usage = "-f filename   Log output to a file\n"
    		       "-i interval   When logging to a file, the interval "
			   "(in ms) to report\n"
		       "-p            Count only payload (not header) size\n"
		       "-n            Add in ethernet header size\n"
340
		       "-N            Add in all ethernet overhead\n"
341
342
		       "-z            Don't count zero-length packets\n"
		       "-o            Print output to stdout\n"
343
344
		       "-t            tcpdump mode\n"
		       "-b filter     Use the given bpf filter\n"
345
346
		       "-I            Include interfaces that have no IP "
			             "address\n"
347
348
349
#ifdef EVENTSYS
		       "-e pid/eid    Wait for a time start for experiment\n"
		       "-s server     Use <server> for event server\n"
Leigh B. Stoller's avatar
Leigh B. Stoller committed
350
	               "-L objname    Link/Lan object name\n"
351
	               "-a            Adjust timestamps for start event\n"
352
#endif
Leigh B. Stoller's avatar
Leigh B. Stoller committed
353
	               "-c            Capture mode; capture packets\n"
354
355
                       "-l            Capture snaplen (only with -c)\n"
	               "-P portnum    Port to listen on\n"
356
357
		       "interfaces... A list of interfaces to monitor\n";

358
    fprintf(stderr,short_usage,progname,progname);
359
360
361
362
    fprintf(stderr,long_usage);
    exit(-1);
}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
363
364
static void cleanup(int sig)
{
365
	killme = 1;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
366
367
}

Robert Ricci's avatar
Robert Ricci committed
368
/*
369
 * XXX: Break up into smaller chunks
Robert Ricci's avatar
Robert Ricci committed
370
371
372
373
374
375
376
377
378
 */
int main (int argc, char **argv) {
	pthread_t thread;
	int sock;
	struct protoent *proto;
	struct sockaddr_in address;
	struct in_addr ifaddr;
	struct hostent *host;
	int i;
379
	int port = PORT;
Robert Ricci's avatar
Robert Ricci committed
380
381
382
383
384
	struct sigaction action;
	int limit_interfaces;
	struct ifconf ifc;
	void  *ptr;
	char lastname[IFNAMSIZ];
Leigh B. Stoller's avatar
Leigh B. Stoller committed
385
	int filename_count = 0;
Robert Ricci's avatar
Robert Ricci committed
386
387
	int filetime;
	char ch;
388
	char *event_server;
389
390
391
	char *global_bpf_filter;
	int tcpdump_mode;
	int interface_it;
392
393
#ifdef EVENTSYS
	address_tuple_t tuple;
394
395
396
	char *keyfile = NULL;
	char *objname = NULL;
	event_handle_t ehandle;
397
#endif
Robert Ricci's avatar
Robert Ricci committed
398
#ifdef EMULAB
399
	FILE *control_interface;
Robert Ricci's avatar
Robert Ricci committed
400
	char control[1024];
401
402
403
#endif
#ifdef DROPROOT
	uid_t uid;
Robert Ricci's avatar
Robert Ricci committed
404
405
406
407
#endif
	/*
	 * Defaults for command-line arugments
	 */
408
	bzero(filenames,sizeof(filenames));
Robert Ricci's avatar
Robert Ricci committed
409
	filetime = 1000;
410
#ifdef EMULAB
411
	event_server = "localhost";
412
413
414
415
#else
	event_server = NULL;
#endif

416
417
418
	tcpdump_mode = 0;
	global_bpf_filter = NULL;

Robert Ricci's avatar
Robert Ricci committed
419
420
421
	/*
	 * Process command-line arguments
	 */
422
	while ((ch = getopt(argc,argv, "f:i:e:hpnNzs:otb:Icl:L:dP:ak:")) != -1)
Robert Ricci's avatar
Robert Ricci committed
423
		switch(ch) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
424
425
426
		case 'd':
			debug++;
			break;
Robert Ricci's avatar
Robert Ricci committed
427
		case 'f':
Leigh B. Stoller's avatar
Leigh B. Stoller committed
428
			filenames[filename_count++] = optarg;
Robert Ricci's avatar
Robert Ricci committed
429
430
431
432
			break;
		case 'i':
			filetime = atoi(optarg);
			break;
433
434
435
436
437
438
		case 'p':
			payload_only = 1;
			break;
		case 'n':
			add_ethernet = 1;
			break;
439
440
441
		case 'N':
			add_all_ethernet = 1;
			break;
442
443
444
		case 'z':
			no_zero = 1;
			break;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
445
446
447
448
449
450
		case 'c':
			capture_mode = 1;
			break;
		case 'l':
			capture_snaplen = atoi(optarg);
			break;
451
452
453
454
455
456
		case 't':
			tcpdump_mode = 1;
			break;
		case 'b':
			global_bpf_filter = optarg;
			break;
457
		case 'o':
Leigh B. Stoller's avatar
Leigh B. Stoller committed
458
			filenames[filename_count++] = "-";
459
460
461
			break;
#ifdef EVENTSYS
		case 'e':
462
			pideid = optarg;
463
			break;
464
465
466
		case 'a':
			adjust_time = 1;
			break;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
467
468
469
		case 'L':
			objname = optarg;
			break;
470
471
472
		case 's':
			event_server = optarg;
			break;
473
474
475
		case 'k':
			keyfile = optarg;
			break;
476
477
478
479
#endif
		case 'h':
			usage(argv[0]);
			break;
480
481
482
		case 'I':
			include_ipless_interfaces = 1;
			break;
483
484
485
		case 'P':
			port = atoi(optarg);
			break;
Robert Ricci's avatar
Robert Ricci committed
486
487
		default:
			fprintf(stderr,"Bad argument\n");
488
489
			usage(argv[0]);
			break;
Robert Ricci's avatar
Robert Ricci committed
490
491
492
493
494
495
496
497
		}
	argc -= optind;
	argv += optind;

	/*
	 * If they give any more arguments, we take those as interface/hostname
	 * names to match against, and skip all others.
	 */
498
	if (argc > 0) {
Robert Ricci's avatar
Robert Ricci committed
499
500
501
502
503
	    	limit_interfaces = 1;
	} else {
	    	limit_interfaces = 0;
	}

504
505
506
507
	if (tcpdump_mode && (!argc || (argc % 2))) {
	    usage(argv[0]);
	}

Robert Ricci's avatar
Robert Ricci committed
508
509
510
511
512
513
514
515
	/*
	 * Zero out all packet counts and other arrays.
	 */
	bzero(counters,sizeof(counters));
	bzero(pcap_devs,sizeof(pcap_devs));
	bzero(client_connected,sizeof(client_connected));

	pthread_mutex_init(&lock,NULL);
516
	pthread_mutex_init(&lib_lock,NULL);
517
	pthread_cond_init(&cond,NULL);
Robert Ricci's avatar
Robert Ricci committed
518
519
520
521
522

#ifdef EMULAB
	/*
	 * Find out which interface is the control net
	 */
523
524
	if (access(CONTROL_IFACE, X_OK) == 0 &&
	    (control_interface = popen(CONTROL_IFACE,"r")) >= 0) {
Robert Ricci's avatar
Robert Ricci committed
525
526
527
528
529
530
531
532
533
534
535
		if (!fgets(control,1024,control_interface)) {
			fprintf(stderr,"Unable to determine control "
					"interface\n");
			control[0] = '\0';
		}

		pclose(control_interface);

		/*
		 * Chomp off the newline
		 */
536
		if (control[0] && control[strlen(control) -1] == '\n') {
Robert Ricci's avatar
Robert Ricci committed
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
			control[strlen(control) -1] = '\0';
		}
		
	} else {
		fprintf(stderr,"Unable to determine control interface\n");
		control[0] = '\0';
	}

#endif

	/*
	 * Open a socket to do our ioctl()s on
	 */

	if ((sock = socket(PF_INET, SOCK_DGRAM, 0)) < 0) {
		perror("socket");
		return (1);
	}

	/*
	 * Use the SIOCGIFCONF ioctl to get a list of all interfaces on
	 * this system.
	 * XXX: The size used is totally arbitrary - this should be done in
	 * a loop with increasing sizes, as in Stevens' book.
	 * NOTE: Linux (oh so helpfully) only gives back interfaces that
	 * are up in response to SIOCGIFCONF
	 */
	ifc.ifc_buf = malloc(MAX_INTERFACES * 100 * sizeof (struct ifreq));
565
	ifc.ifc_len = MAX_INTERFACES * 100 * sizeof (struct ifreq);
Robert Ricci's avatar
Robert Ricci committed
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
	if (ioctl(sock,SIOCGIFCONF,&ifc) < 0) {
		perror("SIOCGIFCONF");
		exit(1);
	}

	strcpy(lastname,"");

	/*
	 * Go through the list of interfaces, and fork off packet-reading
	 * threads, etc. as appropriate.
	 */
	for (ptr = ifc.ifc_buf; ptr < (void*)(ifc.ifc_buf + ifc.ifc_len); ) {
		char hostname[1024];
		char *name;
		struct ifreq *ifr, flag_ifr;

		/*
		 * Save the current position, and move ptr along
		 */
		ifr = (struct ifreq *)ptr;

		/*
		 * Great, no sa_len in Linux. This will be broken for things
		 * other than IPv4
		 */
#ifdef __linux__
		ptr = ptr + sizeof(ifr->ifr_name) +
			MAX(sizeof(struct sockaddr),sizeof(ifr->ifr_addr));
#else
		ptr = ptr + sizeof(ifr->ifr_name) +
			MAX(sizeof(struct sockaddr),ifr->ifr_addr.sa_len);
#endif

599
600
601
		/*
		 * Only care about INET4 interfaces
		 */
602
603
604
605
		if (!include_ipless_interfaces) {
		    if (ifr->ifr_addr.sa_family != AF_INET)
			    continue;
		}
606

Robert Ricci's avatar
Robert Ricci committed
607
608
609
		name = ifr->ifr_name;
		if (!strcmp(name,lastname)) {
			/*
610
			 * If we get duplicates (IP aliases), skip them
Robert Ricci's avatar
Robert Ricci committed
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
			 */
			continue;
		} else {
			strcpy(lastname,name);
		}

		/*
		 * Get interface flags
		 */
		bzero(&flag_ifr,sizeof(flag_ifr));
		strcpy(flag_ifr.ifr_name, name);
		if (ioctl(sock,SIOCGIFFLAGS, (caddr_t)&flag_ifr) < 0) {
			perror("Getting interface flags");
			exit(1);
		}

		printf("Interface %s is ... ",name);

#ifdef EMULAB
630
		if (control[0] && !strcmp(control,name)) {
Robert Ricci's avatar
Robert Ricci committed
631
632
633
634
635
636
			/* Skip control net */
			printf("control\n");
		} else
#endif
		if (flag_ifr.ifr_flags & IFF_LOOPBACK) {
			/* Skip loopback */
637
			printf("skipped (loopback)\n");
Robert Ricci's avatar
Robert Ricci committed
638
639
		} else if (flag_ifr.ifr_flags & IFF_UP) {
			struct readpackets_args *args;
640
			struct sockaddr_in *sin;
641
			int matched_filters = 0;
Robert Ricci's avatar
Robert Ricci committed
642
643
644
645

			/*
			 * Get theIP address for the interface.
			 */
646
647
648
649
#if 1
			sin = (struct sockaddr_in *) &ifr->ifr_addr;
			ifaddr = sin->sin_addr;
#else
Robert Ricci's avatar
Robert Ricci committed
650
651
			if (getaddr(name,&ifaddr)) {
				/* Has carrier, but no IP */
652
				if (!include_ipless_interfaces) {
653
					printf("skipped (no IP address)\n");
654
655
					continue;
				}
Robert Ricci's avatar
Robert Ricci committed
656
			}
657
#endif
Robert Ricci's avatar
Robert Ricci committed
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672

			/*
			 * Grab the 'hostname' for the interface, but fallback
			 * to IP if we can't get it.
			 */
			host = gethostbyaddr((char*)&ifaddr,
					     sizeof(ifaddr),AF_INET);

			if (host) {
				strcpy(hostname,host->h_name);
			} else {
				strcpy(hostname,inet_ntoa(ifaddr));
			}

			/*
673
			 * If we're in 'tcpdump mode' we may have to do this
674
			 * more than once
Robert Ricci's avatar
Robert Ricci committed
675
			 */
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
			interface_it = 0;
			do {
				char *bpf_filter = global_bpf_filter;

				/*
				 * In 'tcpdump mode', we find out if this is
				 * one of the interfaces we're dealing with,
				 * and if so, grab its bpf filter string
				 */
				if (tcpdump_mode) {
					int matched = 0;
					if (!(strcmp(name,argv[interface_it]))) {
						matched = 1;
						bpf_filter = argv[interface_it +1];
						matched_filters++;
Robert Ricci's avatar
Robert Ricci committed
691
					}
692
693
694
695
					interface_it+= 2;
					if (!matched) {
						continue;
					}
696
					
697
698
699
700
701
702
703
704
					/*
					 * Copy it into the global interfaces list
					 */
					strcpy(interface_names[interfaces],hostname);
					strcat(interface_names[interfaces]," '");
					strcat(interface_names[interfaces],bpf_filter);
					strcat(interface_names[interfaces],"'");
					strcat(interface_names[interfaces],"\n");
705

706
					printf("watched ");
707
708
					if (bpf_filter[0])
						printf("(%s) ", bpf_filter);
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725

				} else { 
					/*
					 * If we're limiting the interfaces we
					 * look at, skip this one unless it
					 * matches one of the arguments given
					 * by the user
					 */
					if (limit_interfaces) {
						int j;
						for (j = 0; j < argc; j++) {
							if (!(strcmp(name,argv[j])) ||
						             (strstr(hostname,argv[j]))) {
								break;
							}
						}
						if (j == argc) {
726
							printf("skipped (not specified)\n");
727
728
729
730
731
732
733
734
735
							continue;
						}
					}
					/*
					 * Copy it into the global interfaces list
					 */
					strcpy(interface_names[interfaces],hostname);
					strcat(interface_names[interfaces],"\n");

736
					printf("watched\n");
Robert Ricci's avatar
Robert Ricci committed
737
				}
738
739

				if (interfaces >= MAX_INTERFACES) {
740
					printf("skipped (too many interfaces)\n");
Robert Ricci's avatar
Robert Ricci committed
741
742
743
					continue;
				}

744
				/*
745
746
				 * Start up a new thread to read packets from 
				 * this interface.
747
				 */
748
				pthread_mutex_lock(&lib_lock);
749
750
751
752
753

				fprintf(stderr, "Starting thread for %s(%d): %s",
					name, interfaces, interface_names[interfaces]);
				fflush(stderr);

754
755
756
757
				args = (struct readpackets_args*)
					malloc(sizeof(struct  readpackets_args));
				args->devname = (char*)malloc(strlen(name) + 1);
				args->bpf_filter = bpf_filter;
758
				
759
760
				strcpy(args->devname,name);
				args->index = interfaces;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
761
762
				if (pthread_create(&getpacket_threads[interfaces],
						   NULL,readpackets,args)) {
763
764
765
					fprintf(stderr,"Unable to start thread!\n");
					exit(1);
				}
766
				pthread_mutex_unlock(&lib_lock);
Robert Ricci's avatar
Robert Ricci committed
767

768
769
				interfaces++;
			} while (tcpdump_mode && (interface_it < argc));
Robert Ricci's avatar
Robert Ricci committed
770

771
772
			if (tcpdump_mode) {
				if (matched_filters == 0) {
773
					printf("skipped (not specified)");
774
775
				}
				printf("\n");
Robert Ricci's avatar
Robert Ricci committed
776
777
778
779
			}

		} else {
			/* Skip interfaces that don't have carrier */
780
			printf("skipped (down)\n");
Robert Ricci's avatar
Robert Ricci committed
781
782
783
		}
	}
	close(sock);
784
	fflush(stdout);
Robert Ricci's avatar
Robert Ricci committed
785

786
787
788
789
790
	if (interfaces <= 0) {
		fprintf(stderr,"No interfaces to monitor!\n");
		exit(-1);
	}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
791
792
793
794
795
796
797
798
799
800
	/*
	 * In capture mode, there must be as many files as interfaces.
	 * Each interface goes to its own file.
	 */
	if (capture_mode && interfaces != filename_count) {
		fprintf(stderr,
			"Must supply a unique filename per interface!\n");
		exit(-1);
	}

801
802
803
804
805
806
807
#ifdef DROPROOT
	if (geteuid() == 0) {
	    uid = getuid();
	    seteuid(uid);
	}
#endif

Robert Ricci's avatar
Robert Ricci committed
808
	/*
809
	 * Wait for time to start
Robert Ricci's avatar
Robert Ricci committed
810
	 */
811
#ifdef EVENTSYS
812
	if (pideid) {
813
814
	    char server_string[1024];

815
	    pthread_mutex_lock(&lib_lock);
816
	    printf("Waiting for time start in experiment %s\n", pideid);
817
818
819
820
821
822
823
	    tuple = address_tuple_alloc();
	    if (tuple == NULL) {
		fatal("could not allocate an address tuple");
	    }      
	    tuple->host      = ADDRESSTUPLE_ANY;
	    tuple->site      = ADDRESSTUPLE_ANY;
	    tuple->group     = ADDRESSTUPLE_ANY;
824
	    tuple->expt      = pideid ? pideid : ADDRESSTUPLE_ANY;
825
826
827
828
829
830
831
832
833
834
835
	    tuple->objtype   = TBDB_OBJECTTYPE_TIME;
	    tuple->objname   = ADDRESSTUPLE_ANY;
	    tuple->eventtype = TBDB_EVENTTYPE_START;

	    if (event_server) {
		snprintf(server_string,sizeof(server_string),"elvin://%s",
			event_server);
	    } else {
		server_string[0] = '\0';
	    }

836
	    ehandle = event_register_withkeyfile(server_string, 0, keyfile);
837
838
839
840
841
842
	    if (ehandle == NULL) {
		fatal("could not register with event system");
	    }
	    if (!event_subscribe(ehandle, callback, tuple, NULL)) {
		fatal("could not subscribe to TIME events");
	    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
843
844
845
846
847
848

	    tuple->objtype   = TBDB_OBJECTTYPE_LINKTRACE;
	    tuple->objname   = (objname ? objname : ADDRESSTUPLE_ANY);
	    tuple->eventtype = TBDB_EVENTTYPE_START ","
	                       TBDB_EVENTTYPE_STOP ","
	                       TBDB_EVENTTYPE_RELOAD ","
849
	                       TBDB_EVENTTYPE_SNAPSHOT ","
Leigh B. Stoller's avatar
Leigh B. Stoller committed
850
851
852
853
854
855
	                       TBDB_EVENTTYPE_KILL;

	    if (!event_subscribe(ehandle, callback, tuple, NULL)) {
		fatal("could not subscribe to LINKTRACE events");
	    }
	    
856
857
858
859
860
861
862
863
864
865
	    address_tuple_free(tuple);

	    /*
	     * We put the event system main loop into a new thread, since
	     * we can't use the threaded API with linuxthreads
	     */
	    if (pthread_create(&thread,NULL,runeventsys,&ehandle)) {
		fprintf(stderr,"Unable to start thread!\n");
		exit(1);
	    }
866
	    pthread_mutex_unlock(&lib_lock);
867
868
869
870
871
872
	}
#endif

	/*
	 * If they gave us filenames to log to, open them up.
	 */
Leigh B. Stoller's avatar
Leigh B. Stoller committed
873
874
875
876
	if (! capture_mode) {
		for (i = 0; filenames[i] != NULL; i++) {
			int fd;
			struct feedclient_args *args;
Robert Ricci's avatar
Robert Ricci committed
877

Leigh B. Stoller's avatar
Leigh B. Stoller committed
878
879
880
881
882
883
884
885
886
887
888
889
890
			/*
			 * Allow use the of '-' for stdout
			 */
			if (!strcmp(filenames[i],"-")) {
				fd = 1;
			} else {
				fd = open(filenames[i],
					  O_WRONLY | O_CREAT | O_TRUNC);
				if (fd < 0) {
					perror("Opening savefile");
					exit(1);
				}
			}
Robert Ricci's avatar
Robert Ricci committed
891

Leigh B. Stoller's avatar
Leigh B. Stoller committed
892
893
894
			/*
			 * Start a new thread to feed the file
			 */
895
			pthread_mutex_lock(&lib_lock);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
896
897
898
899
900
901
902
903
			args = (struct feedclient_args*)
				malloc(sizeof(struct feedclient_args));
			args->fd = fd;
			args->cli = 0;
			args->interval = filetime;
			client_connected[i] = 1;
			active = 1;
			pthread_create(&thread,NULL,feedclient,args);
904
			pthread_mutex_unlock(&lib_lock);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
905
906
			pthread_cond_broadcast(&cond);
		}
Robert Ricci's avatar
Robert Ricci committed
907
908
909
910
911
912
913
914
915
916
917
918
919
	}

	/*
	 * Create a socket to listen on, so that we can tell remote
	 * applications about the counts we're getting.
	 */
	proto = getprotobyname("TCP");
	sock = socket(AF_INET,SOCK_STREAM,proto->p_proto);
	if (sock < 0) {
		perror("Creating socket");
		exit(1);
	}

920
	//i++;
Robert Ricci's avatar
Robert Ricci committed
921
922
923
924
	if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(int)) < 0)
		perror("SO_REUSEADDR");

	address.sin_family = AF_INET;
925
	address.sin_port = htons(port);
Robert Ricci's avatar
Robert Ricci committed
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
	address.sin_addr.s_addr = INADDR_ANY;

	if (bind(sock,(struct sockaddr*)(&address),sizeof(address))) {
		perror("Binding socket");
		exit(1);
	}

	if (listen(sock,-1)) {
		perror("Listening on socket");
		exit(1);
	}

	/*
	 * Ignore SIGPIPE - we'll detect the remote end closing the connection
	 * by a failed write() .
	 */
	action.sa_handler = SIG_IGN;
	sigaction(SIGPIPE,&action,NULL);

Leigh B. Stoller's avatar
Leigh B. Stoller committed
945
946
947
948
949
950
951
952
953
954
955
956
	/*
	 * In capture mode we just wait for a signal
	 */
	if (capture_mode) {
		/*
		 * Insert a handler to kill the threads cleanly.
		 */
		action.sa_handler = cleanup;
		sigaction(SIGTERM, &action, NULL);
		sigaction(SIGINT, &action, NULL);
	}

Robert Ricci's avatar
Robert Ricci committed
957
958
959
	/*
	 * Loop forever, so that we can handle multiple clients connecting
	 */
960
	while (!killme) {
Robert Ricci's avatar
Robert Ricci committed
961
962
963
964
965
966
967
968
		int fd;
		struct feedclient_args *args;
		struct sockaddr client_addr;
		size_t client_addrlen;

		fd = accept(sock,&client_addr,&client_addrlen);

		if (fd < 0) {
969
970
			if (errno == EINTR)
				break;
Robert Ricci's avatar
Robert Ricci committed
971
			perror("accept");
972
			fflush(stderr);
Robert Ricci's avatar
Robert Ricci committed
973
974
975
976
977
978
979
980
981
982
			continue;
		}
		/*
		 * Pick a client number
		 */
		pthread_mutex_lock(&lock);
		for (i = 0; i < MAX_CLIENTS; i++) {
			if (!client_connected[i]) {
				/* printf("New client is %i\n",i); */
				client_connected[i] = 1;
983
984
985
986
987
988
				if (active >= MAX_CLIENTS) {
					fprintf(stderr, "active count screwed\n");
					exit(1);
				}
				if (++active == 1)
					pthread_cond_broadcast(&cond);
989
990
991
#if 0
				printf("Now have %d clients\n", active);
#endif
Robert Ricci's avatar
Robert Ricci committed
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
				break;
			}
		}
		pthread_mutex_unlock(&lock);
		
		if (i == MAX_CLIENTS) {
			/*
			 * Didn't find a free slot
			 */
			fprintf(stderr,"Too many clients\n");
			close(fd);
		} else {
			args = (struct feedclient_args*)
				malloc(sizeof(struct feedclient_args));
			args->fd = fd;
			args->cli = i;
			args->interval = 0;
			pthread_create(&thread,NULL,feedclient,args);
		}
	}
1012
1013
1014
1015
1016
1017
1018
1019
1020
	if (capture_mode) {
		/*
		 * Wait for the packet readers to exit.
		 */
		for (i = 0; i < interfaces; i++) {
			pthread_join(getpacket_threads[i], NULL);
		}
	}
	exit(0);
Robert Ricci's avatar
Robert Ricci committed
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
}

/*
 * Feed data back to a client - since this is done through a file
 * descriptor, the client can be a socket, a file, etc.
 */
void *feedclient(void *args) {
	struct feedclient_args *s_args;
	int cli;
	int fd;
	char inbuf[1024];
	char outbuf[1024];
	int interval;
	int i;
	struct timeval next_time, now, interval_tv;
	int dropped;
1037
	int called = 0;
Robert Ricci's avatar
Robert Ricci committed
1038
1039
1040
1041
1042
1043

	s_args = (struct feedclient_args*)args;
	cli = s_args->cli;
	fd = s_args->fd;
	interval = s_args->interval;

Leigh B. Stoller's avatar
Leigh B. Stoller committed
1044
	pthread_mutex_lock(&lib_lock);
Robert Ricci's avatar
Robert Ricci committed
1045
	free(args);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1046
	pthread_mutex_unlock(&lib_lock);
Robert Ricci's avatar
Robert Ricci committed
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093

	dropped = 0;
	
	/*
	 * The first thing we send is the number of interfaces,
	 * followed by the name of each one (1 per line)
	 */
	sprintf(outbuf,"%i\n",interfaces);
	write(fd,outbuf,strlen(outbuf));

	for (i  = 0; i < interfaces; i++) {
		write(fd,interface_names[i],strlen(interface_names[i]));
	}

	/*
	 * Now, we wait for the client to tell us how long, in ms, they
	 * want to wait in between reports. If we were given an interval in
	 * our arguments (presumably because the output fd is write-only),
	 * forgo this step.
	 */
	if (!interval) {
		read(fd,inbuf,1024);
		interval = atoi(inbuf);
	}

	/*
	 * Convert to microseconds.
	 */
	interval *= 1000;

	interval_tv.tv_usec = interval % 1000000;
	interval_tv.tv_sec = interval / 1000000;

	/*
	 * Zero out the packet counts before the first report
	 */
	pthread_mutex_lock(&lock);
	bzero(counters[cli], sizeof(counters[cli]));
	pthread_mutex_unlock(&lock);

	gettimeofday(&now,NULL);
	timeradd(&now,&interval_tv,&next_time);

	while (1) { /* Repeat until client disconnects */
		int used = 0;
		int writerv;
		struct timeval sleepintr;
1094
		struct timeval timestamp;
Robert Ricci's avatar
Robert Ricci committed
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
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
		struct timespec sleepintr_ts;
		struct pcap_stat ps;

		/*
		 * Zero out the packet counts, and set up the times in the
		 *
		 */
		pthread_mutex_lock(&lock);
		gettimeofday(&now,NULL);
		for (i  = 0; i < interfaces; i++) {
			bcopy(&(counters[cli][i].next_interval),
			      &(counters[cli][i].this_interval),
			      sizeof(counters[cli][i].next_interval));
			bzero(&(counters[cli][i].next_interval),
			      sizeof(counters[cli][i].next_interval));
			bcopy(&(next_time),&(counters[cli][i].start_time),
			      sizeof(now));
			bcopy(&(next_time),&(counters[cli][i].rollover),
			      sizeof(next_time));
		}
		pthread_mutex_unlock(&lock);

		/*
		 * Figure out how long to sleep for
		 */
		gettimeofday(&now,NULL);
		timersub(&next_time,&now,&sleepintr);

		/*
		 * Have to convert to a timespec, since nanosleep takes a
		 * timespec, but all the other functions I want to use deal
		 * in timeval's
		 */
		sleepintr_ts.tv_sec = sleepintr.tv_sec;
		sleepintr_ts.tv_nsec = sleepintr.tv_usec * 1000;

		nanosleep(&sleepintr_ts,NULL);
		gettimeofday(&now,NULL);

		/*
		 * Figure out the next time we'll be waking up
		 */
		timeradd(&next_time,&interval_tv,&next_time);

1139
1140
1141
1142
1143
1144
1145
1146
		timestamp.tv_sec = now.tv_sec;
		timestamp.tv_usec = now.tv_usec;

#ifdef EVENTSYS
		if (adjust_time) {
		    timersub(&now,&start_time,&timestamp);
		}
#endif
1147
1148
1149
1150
1151
		/*
		 * If tracing was paused, pause this too.
		 */
		if (stop)
		    continue;
1152

Robert Ricci's avatar
Robert Ricci committed
1153
1154
1155
		/*
		 * Put a timestamp on the beginning of each line
		 */
1156
1157
		used += sprintf((outbuf +used),"%li.%06li ", timestamp.tv_sec,
				timestamp.tv_usec);
Robert Ricci's avatar
Robert Ricci committed
1158
1159
1160
1161
1162
1163
1164
1165

		/*
		 * Gather up the counts for each interface into
		 * a string.
		 */
		pthread_mutex_lock(&lock);
		for (i  = 0; i < interfaces; i++) {
			used += sprintf((outbuf +used),
1166
1167
1168
#ifdef VETH
				"(icmp:%i,%i tcp:%i,%i udp:%i,%i other:%i,%i veth:%i,%i) ",
#else
Robert Ricci's avatar
Robert Ricci committed
1169
				"(icmp:%i,%i tcp:%i,%i udp:%i,%i other:%i,%i) ",
1170
#endif
Robert Ricci's avatar
Robert Ricci committed
1171
1172
1173
1174
1175
1176
1177
				counters[cli][i].this_interval.icmp_bytes,
				counters[cli][i].this_interval.icmp_packets,
				counters[cli][i].this_interval.tcp_bytes,
				counters[cli][i].this_interval.tcp_packets,
				counters[cli][i].this_interval.udp_bytes,
				counters[cli][i].this_interval.udp_packets,
				counters[cli][i].this_interval.other_bytes,
1178
1179
1180
1181
1182
1183
				counters[cli][i].this_interval.other_packets
#ifdef VETH
				,counters[cli][i].this_interval.veth_bytes
				,counters[cli][i].this_interval.veth_packets
#endif
					);
Robert Ricci's avatar
Robert Ricci committed
1184
1185
1186
1187
1188
		}
		pthread_mutex_unlock(&lock);

		/*
		 * Drop information is not kept per-interface, so we just
1189
1190
1191
1192
		 * grab it from one of them.  Note that since we close all
		 * devices when no one is active, it is possible that the
		 * device threads have not yet reopened their devices when
		 * we reach here.
Robert Ricci's avatar
Robert Ricci committed
1193
		 */
1194
1195
1196
1197
1198
1199
		if (pcap_devs[0] == 0 || pcap_stats(pcap_devs[0], &ps)) {
			if (!called) {
				fprintf(stderr,
					"WARNING: unable to get drop stats\n");
				called = 1;
			}
Robert Ricci's avatar
Robert Ricci committed
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
		}

		/*
		 * Put the difference between the last and current kernel drop
		 * count on the end of the line.
		 */
		used += sprintf((outbuf + used),"(dropped:%i)",
				ps.ps_drop - dropped);
		dropped = ps.ps_drop;

		/*
		 * Make it more human-readable
		 */
		strcat(outbuf,"\n");

		writerv = write(fd,outbuf,strlen(outbuf));
		if (writerv < 0) {
			if (errno != EPIPE) {
				perror("write");
			}
			/* printf("Client %i disconnected\n",cli);*/
1221
1222
1223
1224
1225
			pthread_mutex_lock(&lock);
			if (client_connected[cli] == 0 || active <= 0) {
				fprintf(stderr, "active count screwed\n");
				exit(1);
			}
Robert Ricci's avatar
Robert Ricci committed
1226
			client_connected[cli] = 0;
1227
			active--;
1228
			/* printf("Now have %d clients\n", active); */
1229
			pthread_mutex_unlock(&lock);
Robert Ricci's avatar
Robert Ricci committed
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
			/*
			 * Client disconnected - exit the loop
			 */
			break;
		}
	}

	return NULL;
}

/*
 * Start the pcap_loop for an interface
 */
void *readpackets(void *args) {
	char ebuf[1024];
	pcap_t *dev;
	struct readpackets_args *sargs;
	int size;
	bpf_u_int32 mask, net;
	struct bpf_program filter;
1250
	char *bpf_filter;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1251
	void *readpackets_capturemode(void * args);
Robert Ricci's avatar
Robert Ricci committed
1252

Leigh B. Stoller's avatar
Leigh B. Stoller committed
1253
1254
1255
	if (capture_mode)
		return readpackets_capturemode(args);
	
Robert Ricci's avatar
Robert Ricci committed
1256
	/*
1257
	 * How much of the packet we want to grab.
Robert Ricci's avatar
Robert Ricci committed
1258
	 */
1259
1260
1261
1262
1263
1264
1265
#ifdef VETH
	size = sizeof(struct sniff_veth);
#else
	size = sizeof(struct sniff_ethernet);
#endif
	size += sizeof(struct ip) + sizeof(struct tcphdr);
	    
Robert Ricci's avatar
Robert Ricci committed
1266
1267
	sargs = (struct readpackets_args*)args;

1268
1269
 again:
	pthread_mutex_lock(&lock);
1270
	while (active == 0 || stop)
1271
1272
1273
		pthread_cond_wait(&cond, &lock);
	pthread_mutex_unlock(&lock);

Leigh B. Stoller's avatar
Leigh B. Stoller committed
1274
	pthread_mutex_lock(&lib_lock);
Robert Ricci's avatar
Robert Ricci committed
1275
1276
1277
1278
1279
	/*
	 * NOTE: We set the timeout to a full second - if we set it lower, we
	 * don't get to see packets until a certain number have been buffered
	 * up, for some reason.
	 */
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1280
	dev = pcap_open_live(sargs->devname, size, 1, 1000, ebuf);
Robert Ricci's avatar
Robert Ricci committed
1281
	if (!dev) {
1282
1283
		fprintf(stderr, "Failed to open %s: %s\n",
			sargs->devname, ebuf);
Robert Ricci's avatar
Robert Ricci committed
1284
1285
1286
1287
1288
1289
1290
1291
1292
		exit(1);
	}

	/*
	 * Record our pcap device into the global array, so that it can be
	 * found by other processes.
	 */
	pcap_devs[sargs->index] = dev;

1293
1294
	bpf_filter = sargs->bpf_filter;

Robert Ricci's avatar
Robert Ricci committed
1295
1296
1297
1298
1299
	/*
	 * Put an empty filter on the device, or we get nothing (but only
	 * in Linux) - how frustrating!
	 */
#ifdef __linux__
1300
1301
1302
	if (!bpf_filter) {
	    bpf_filter = "";
	}
Robert Ricci's avatar
Robert Ricci committed
1303
1304
#endif

1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
	if (bpf_filter) {
	    pcap_lookupnet(sargs->devname, &net, &mask, ebuf);
	    if (pcap_compile(dev, &filter, bpf_filter, 0, net)) {
		    fprintf(stderr,"Error compiling BPF filter '%s'\n",
				    bpf_filter);
		    exit(1);
	    }
	    pcap_setfilter(dev, &filter);
	    pcap_freecode(&filter);
	}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1315
	pthread_mutex_unlock(&lib_lock);
1316

1317
1318
1319
1320
1321
1322
	/*
	 * We don't bother to lock the access to active.  If it gets cleared
	 * immediately after a test, we make an extra loop.  If it gets set
	 * immediately after, we do an extra open/close of the device.
	 * Neither case is life threatening.
	 */
1323
1324
	while (active && !(stop || killme)) {
		if (pcap_dispatch(dev, -1, got_packet, args) < 0) {
1325
			pcap_perror(dev,"pcap_dispatch failed: ");
1326
1327
			exit(1);
		}
Robert Ricci's avatar
Robert Ricci committed
1328
	}
1329
	pcap_close(dev);
1330
	if (killme)
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1331
		return 0;
1332
	goto again;
Robert Ricci's avatar
Robert Ricci committed
1333
1334
}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
/*
 * Special version for just capturing packets.
 */
void *readpackets_capturemode(void *args)
{
	struct readpackets_args *sargs = (struct readpackets_args*) args;
	char ebuf[1024];
	pcap_t *dev;
	int size;
	bpf_u_int32 mask, net;
	struct bpf_program filter;
	char *bpf_filter;
	pcap_dumper_t *pdumper;
	void dump_packet(u_char *, const struct pcap_pkthdr *, const u_char *);

	/*
	 * How much of the packet we want to grab.
	 */
	size = capture_snaplen;

1355
1356
1357
	/* Lock the pcap stuff */
	pthread_mutex_lock(&lib_lock);

Leigh B. Stoller's avatar
Leigh B. Stoller committed
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
	/*
	 * NOTE: We set the timeout to a full second - if we set it lower, we
	 * don't get to see packets until a certain number have been buffered
	 * up, for some reason.
	 */
	dev = pcap_open_live(sargs->devname, size, 1, 1000, ebuf);
	if (!dev) {
		fprintf(stderr, "Failed to open %s: %s\n",
			sargs->devname, ebuf);
		exit(1);
	}
	bpf_filter = sargs->bpf_filter;

	/*
	 * Put an empty filter on the device, or we get nothing (but only
	 * in Linux) - how frustrating!
	 */
#ifdef __linux__
	if (!bpf_filter) {
	    bpf_filter = "";
	}
#endif

	if (bpf_filter) {
	    pcap_lookupnet(sargs->devname, &net, &mask, ebuf);
	    if (pcap_compile(dev, &filter, bpf_filter, 0, net)) {
		    fprintf(stderr,"Error compiling BPF filter '%s'\n",
				    bpf_filter);
		    exit(1);
	    }
	    pcap_setfilter(dev, &filter);
	    pcap_freecode(&filter);
	}
1391
	pthread_mutex_unlock(&lib_lock);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1392
1393
1394
1395
1396
1397
	
	/*
	 * In capture mode, we need to open up the dump file for this
	 * interface.
	 */
 again:
1398
	pthread_mutex_lock(&lib_lock);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1399
	pdumper = pcap_dump_open(dev, filenames[sargs->index]);
1400
	pthread_mutex_unlock(&lib_lock);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1401
1402
1403
1404
	if (pdumper == NULL) {
		fprintf(stderr, "%s\n", pcap_geterr(dev));
		exit(1);
	}
1405
	sargs->pdumper = pdumper;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1406

1407
	while (!killme && !reload) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1408
		if (debug) {
1409
			fprintf(stderr, "packet(%d)\n", getpid());
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1410
1411
			fflush(stderr);
		}
1412
		if (pcap_dispatch(dev, -1, dump_packet, (u_char *)sargs)
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1413
1414
1415
1416
1417
1418
1419
1420
		    < 0) {
			pcap_perror(dev,"pcap_dispatch failed: ");
			fflush(stderr);
			exit(1);
		}
	}
	pcap_dump_close(pdumper);
	if (reload) {
1421
1422
1423
1424
1425
		/*
		 * Save off the current file.
		 */
		char buf[BUFSIZ];

1426
1427
1428
1429
1430
1431
1432
1433
		if (reload_tag != NULL) {
		  snprintf(buf, BUFSIZ,
			   "%s.%s",
			   filenames[sargs->index], reload_tag);
		}
		else {
		  snprintf(buf, BUFSIZ, "%s.0", filenames[sargs->index]);
		}
1434
1435
		rename(filenames[sargs->index], buf);

1436
1437
		pthread_mutex_lock(&lock);

1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
		fprintf(stderr, "reload=%d (%d)\n", reload, getpid());
		fflush(stderr);

		reload--;
		if (reload == 0) {
			pthread_mutex_unlock(&lock);
			stop = 0;
			pthread_cond_broadcast(&cond);
		}
		else {
			while (reload)
				pthread_cond_wait(&cond, &lock);
			pthread_mutex_unlock(&lock);
		}
		fprintf(stderr, "reload=%d (%d)\n", reload, getpid());
		fflush(stderr);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
		goto again;
	}
	pcap_close(dev);
	return 0;
}

/*
 * Callback for above; simply dumps the packet. 
 */
void dump_packet(u_char *args, const struct pcap_pkthdr *header,
		const u_char *packet)
{
1466
1467
	struct readpackets_args *sargs = (struct readpackets_args*) args;
	
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1468
	if (debug) {
1469
		fprintf(stderr, "got packet\n");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1470
1471
		fflush(stderr);
	}
1472
1473
	if (!stop)
		pcap_dump((u_char *)(sargs->pdumper), header, packet);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1474
	if (active)
1475
	        got_packet(args, header, packet);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1476
1477
}

Robert Ricci's avatar
Robert Ricci committed
1478
1479
1480
1481
1482
/*
 * Callback for pcap_loop - gets called every time a packet is recieved, and
 * adds its byte count to the total.
 */
void got_packet(u_char *args, const struct pcap_pkthdr *header,
1483
		const u_char *packet) {
Robert Ricci's avatar
Robert Ricci committed
1484

1485
	struct readpackets_args *sargs = (struct readpackets_args*) args;
Robert Ricci's avatar
Robert Ricci committed
1486
	struct sniff_ethernet *ether_pkt;
1487
	struct ip *ip_pkt; 
Robert Ricci's avatar
Robert Ricci committed
1488
	int length;
1489
	int type = 0;
Robert Ricci's avatar
Robert Ricci committed
1490
1491
	int index;
	int i;
1492
	int hdrsize;
Robert Ricci's avatar
Robert Ricci committed
1493
1494
1495
1496
1497

	/*
	 * We only care about IP packets
	 */
	ether_pkt = (struct sniff_ethernet*)packet;
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
	switch (ntohs(ether_pkt->ether_type)) {
	case ETHERTYPE_IP:
		hdrsize = sizeof(struct sniff_ethernet);
		break;
#ifdef VETH
	case ETHERTYPE_VETH:
		/* XXX one level only */
		if (ntohs(((struct sniff_veth *)packet)->veth_type) !=
		    ETHERTYPE_IP)
			return;
		hdrsize = sizeof(struct sniff_veth);
		type = -1;
		break;
#endif
	default: