File: format_bpf.c

package info (click to toggle)
libtrace3 3.0.14-1
  • links: PTS
  • area: main
  • in suites: wheezy
  • size: 11,492 kB
  • sloc: ansic: 21,584; sh: 10,236; cpp: 1,765; makefile: 454; yacc: 96; lex: 50
file content (545 lines) | stat: -rw-r--r-- 16,282 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
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
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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
/*
 * This file is part of libtrace
 *
 * Copyright (c) 2007,2008,2009,2010 The University of Waikato, Hamilton, 
 * New Zealand.
 *
 * Authors: Daniel Lawson 
 *          Perry Lorier
 *          Shane Alcock 
 *          
 * All rights reserved.
 *
 * This code has been developed by the University of Waikato WAND 
 * research group. For further information please see http://www.wand.net.nz/
 *
 * libtrace is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * libtrace is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with libtrace; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * $Id: format_bpf.c 1607 2010-07-16 02:36:48Z salcock $
 *
 */

#include "libtrace.h"
#include "libtrace_int.h"
#include "format_helper.h"
#include "config.h"
#include "stdlib.h"

#ifdef HAVE_INTTYPES_H
#  include <inttypes.h>
#else
# error "Can't find inttypes.h"
#endif 

#include <sys/socket.h>

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

#include <string.h>
#include <net/if.h>
#include <sys/ioctl.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>

/* This format deals with the BSD Native capture format, perhaps better
 * known as BPF, which is the equivalent of the Linux Native format for
 * *BSD systems.
 *
 * This is a LIVE capture format - we're always dealing with reading from an
 * interface.
 *
 * This format does not support writing, but BPF packet records can be easily
 * converted to PCAP or ERF.
 */ 

/* "Global" data that is stored for each BPF input trace */
struct libtrace_format_data_t {
	/* The file descriptor that is being captured from */
	int fd;	
	/* The snap length for the capture */
	int snaplen;
	/* A boolean flag indicating whether the capture interface should be
	 * in promiscuous mode */ 
	int promisc;
	/* A buffer to write captured data into */
	void *buffer;
	/* The current read location in the capture buffer */
	void *bufptr;
	/* The total size of the capture buffer */
	unsigned int buffersize;
	/* The amount of space remaining before the capture buffer is full */
	int remaining;
	/* The linktype of the capture interface */ 
	unsigned int linktype;
	/* Statistics about how many packets have been dropped, received etc. */
	struct bpf_stat stats;
	/* A boolean flag indicating whether the statistics are up-to-date */
	int stats_valid;
};

#define FORMATIN(x) ((struct libtrace_format_data_t*)((x->format_data)))

#define BPFHDR(x) ((struct bpf_hdr *)((x)->header))

/* Attempts to determine if a given filename could refer to a BPF interface */
static int bpf_probe_filename(const char *filename)
{
	return (if_nametoindex(filename) != 0);
}

/* Initialises a BPF input trace */
static int bpf_init_input(libtrace_t *libtrace) 
{
	libtrace->format_data = (struct libtrace_format_data_t *)
		malloc(sizeof(struct libtrace_format_data_t));
	
	/* Throw some default values into the format data */
	FORMATIN(libtrace)->fd = -1;
	FORMATIN(libtrace)->promisc = 0;
	FORMATIN(libtrace)->snaplen = 65536;
	FORMATIN(libtrace)->stats_valid = 0;

	return 0;
}

/* Starts a BPF input trace */
static int bpf_start_input(libtrace_t *libtrace)
{
	int bpfid=0;
	struct bpf_version bv;
	struct ifreq ifr;
	unsigned int v;

	/* Find and open a bpf device */
	do {
		char buffer[64];
		snprintf(buffer,sizeof(buffer),"/dev/bpf%d", bpfid);
		bpfid++;
		
		FORMATIN(libtrace)->fd = open(buffer, O_RDONLY);
	} while(FORMATIN(libtrace)->fd == -1 && errno == EBUSY);

	if (FORMATIN(libtrace)->fd == -1) {
		trace_set_err(libtrace,TRACE_ERR_INIT_FAILED,
				"No free bpf devices");
		return -1;
	}

	/* Check the BPF Version is ok */
	if (ioctl(FORMATIN(libtrace)->fd, BIOCVERSION, &bv) == -1) {
		trace_set_err(libtrace,errno,
				"Failed to read the bpf version");
		close(FORMATIN(libtrace)->fd);
		return -1;
	}

	if (bv.bv_major != BPF_MAJOR_VERSION) {
		trace_set_err(libtrace,errno, 
			"Unknown kernel BPF version (%d.%d, libtrace requires at least %d.%d)",
			bv.bv_major,
			bv.bv_minor,
			BPF_MAJOR_VERSION,
			BPF_MINOR_VERSION);
		close(FORMATIN(libtrace)->fd);
		return -1;
	}

	if (bv.bv_minor < BPF_MINOR_VERSION) {
		trace_set_err(libtrace,errno, "Kernel version too old (%d.%d, libtrace requires at least %d.%d)",
			bv.bv_major,
			bv.bv_minor,
			BPF_MAJOR_VERSION,
			BPF_MINOR_VERSION);
		close(FORMATIN(libtrace)->fd);
		return -1;
	}

	/* We assume the default kernel buffer size is sufficient. */
	if (ioctl(FORMATIN(libtrace)->fd, BIOCGBLEN,
			&FORMATIN(libtrace)->buffersize)==-1) {
		trace_set_err(libtrace,errno,"Failed to find buffer length");
		close(FORMATIN(libtrace)->fd);
		return -1;
	}

	FORMATIN(libtrace)->buffer = malloc(FORMATIN(libtrace)->buffersize);
	FORMATIN(libtrace)->bufptr = FORMATIN(libtrace)->buffer;
	FORMATIN(libtrace)->remaining = 0;

	/* Attach to the device */
	strncpy(ifr.ifr_name, libtrace->uridata, sizeof(ifr.ifr_name));
	if (ioctl(FORMATIN(libtrace)->fd, BIOCSETIF, &ifr) == -1) {
		trace_set_err(libtrace,errno,"Failed to attach");
		close(FORMATIN(libtrace)->fd);
		return -1;
	}

	/* Set the link type */
	if (ioctl(FORMATIN(libtrace)->fd, BIOCGDLT,
			 &FORMATIN(libtrace)->linktype) == -1) {
		trace_set_err(libtrace,errno,"Failed to retrieve link type");
		close(FORMATIN(libtrace)->fd);
		return -1;
	}
	
	/* TODO: If BIOCGDLTLIST exists then we should perhaps do something
	 *       with it.  We don't have the same concept of multiple DLT's
         *       as pcap does.  We grab the rawest possible thing and then
	 *	 decode packets by understanding the protocols.  So perhaps
	 *	 we should setup a rating of DLT's that we'll prefer in order.
	 *       For example we should try and get 802.11 frames rather than
	 *       802.3 frames.  The general rule should be "whatever actually
	 *       went over the air", although of course if we don't support
	 *       what went over the air we should fall back to something we
	 *       /do/ support.
	 */
	
	/* Using timeouts seems sucky.  We'll always use immediate mode.  We
         * pray the kernel is smart enough that if a another packet arrives
         * while we're processing this one that it will buffer them into it's
	 * kernel buffer so we can receive packets later. (It'll need to do this
	 * to deal with us spending time processing the last 'n' packets anyway)
	 */
	
	v=1;
	if (ioctl(FORMATIN(libtrace)->fd, BIOCIMMEDIATE, &v) == -1) {
		trace_set_err(libtrace,errno,"Failed to set immediate mode");
		close(FORMATIN(libtrace)->fd);
		return -1;
	}

	/* Set promiscous mode, if the user has asked us to do so */
	if (FORMATIN(libtrace)->promisc) {
		if (ioctl(FORMATIN(libtrace)->fd, BIOCPROMISC, NULL) == -1) {
			trace_set_err(libtrace,errno,
				"Failed to set promisc mode");
			close(FORMATIN(libtrace)->fd);
			return -1;

		}
	}

	FORMATIN(libtrace)->stats_valid = 0;

	/* TODO: we should always set a bpf filter for snapping */

	/* We're done! */
	return 0;
}

/* Gets a count of the number of packets received on the BPF interface */
static uint64_t bpf_get_received_packets(libtrace_t *trace)
{
	if (trace->format_data == NULL)
		return (uint64_t)-1;

	if (FORMATIN(trace)->fd == -1) {
		/* Almost certainly a 'dead' trace so there is no socket
		 * for us to query */
		return (uint64_t) -1;
	}
	/* If we're called with stats_valid == 0, or we're called again
	 * then refresh the stats.  Don't refresh the stats if we're called
	 * immediately after get_dropped_packets
	 */
	if ((FORMATIN(trace)->stats_valid & 1)
		|| (FORMATIN(trace)->stats_valid == 0)) {
		ioctl(FORMATIN(trace)->fd, BIOCGSTATS, &FORMATIN(trace)->stats);
		FORMATIN(trace)->stats_valid |= 1;
	}

	return FORMATIN(trace)->stats.bs_recv;
}

/* Gets a count of the number of packets dropped on the BPF interface */
static uint64_t bpf_get_dropped_packets(libtrace_t *trace)
{
	if (trace->format_data == NULL)
		return (uint64_t)-1;

	if (FORMATIN(trace)->fd == -1) {
		/* Almost certainly a 'dead' trace so there is no socket
		 * for us to query */
		return (uint64_t) -1;
	}
	/* If we're called with stats_valid == 0, or we're called again
	 * then refresh the stats.  Don't refresh the stats if we're called
	 * immediately after get_received_packets
	 */
	if ((FORMATIN(trace)->stats_valid & 2) 
		|| (FORMATIN(trace)->stats_valid == 0)) {
		ioctl(FORMATIN(trace)->fd, BIOCGSTATS, &FORMATIN(trace)->stats);
		FORMATIN(trace)->stats_valid |= 2;
	}

	return FORMATIN(trace)->stats.bs_drop;
}

/* Pauses a BPF input trace */
static int bpf_pause_input(libtrace_t *libtrace)
{
	close(FORMATIN(libtrace)->fd);
	FORMATIN(libtrace)->fd=-1;

	return 0;
}

/* Closes a BPF input trace */
static int bpf_fin_input(libtrace_t *libtrace) 
{
	free(libtrace->format_data);
	return 0;
}

/* Configures a BPF input trace */
static int bpf_config_input(libtrace_t *libtrace,
		trace_option_t option,
		void *data)
{
	switch(option) {
		case TRACE_OPTION_SNAPLEN:
			FORMATIN(libtrace)->snaplen=*(int*)data;
			return 0;
		case TRACE_OPTION_PROMISC:
			FORMATIN(libtrace)->promisc=*(int*)data;
			return 0;
		case TRACE_OPTION_FILTER:
			/* We don't support bpf filters in any special way
			 * so return an error and let libtrace deal with
			 * emulating it
			 */
			break;
		case TRACE_OPTION_META_FREQ:
			/* No meta-data for this format */
			break;
		case TRACE_OPTION_EVENT_REALTIME:
			/* Captures are always realtime */
			break;

		/* Avoid default: so that future options will cause a warning
		 * here to remind us to implement it, or flag it as
		 * unimplementable
		 */
	}
	trace_set_err(libtrace,TRACE_ERR_UNKNOWN_OPTION,
			"Unknown option %i", option);
	return -1;
}

/* Converts a buffer containing a recently read BPF packet record into a
 * libtrace packet */
static int bpf_prepare_packet(libtrace_t *libtrace, libtrace_packet_t *packet,
		void *buffer, libtrace_rt_types_t rt_type, uint32_t flags) {
        
	/* If the packet previously owned a buffer that is not the buffer
	 * that contains the new packet data, we're going to need to free the
	 * old one to avoid memory leaks */
	if (packet->buffer != buffer &&
                        packet->buf_control == TRACE_CTRL_PACKET) {
                free(packet->buffer);
        }

	/* Set the buffer owner appropriately */
        if ((flags & TRACE_PREP_OWN_BUFFER) == TRACE_PREP_OWN_BUFFER) {
                packet->buf_control = TRACE_CTRL_PACKET;
        } else
                packet->buf_control = TRACE_CTRL_EXTERNAL;

	/* Update the packet pointers and type appropriately */
        packet->buffer = buffer;
        packet->header = buffer;
	packet->type = rt_type;

	/* Find the payload */
	/* TODO: Pcap deals with a padded FDDI linktype here */
	packet->payload=(char *)buffer + BPFHDR(packet)->bh_hdrlen;

	if (libtrace->format_data == NULL) {
		if (bpf_init_input(libtrace))
			return -1;
	}

	return 0;
}

/* Reads the next packet record from a BPF interface and writes it into a 
 * libtrace packet */	
static int bpf_read_packet(libtrace_t *libtrace, libtrace_packet_t *packet) 
{
	uint32_t flags = 0;
	
	/* Read from the BPF interface into our capture buffer */
	if (FORMATIN(libtrace)->remaining<=0) {
		int ret;

		ret=read(FORMATIN(libtrace)->fd,
			FORMATIN(libtrace)->buffer,
			FORMATIN(libtrace)->buffersize);

		if (ret == -1) {
			trace_set_err(libtrace,errno,"Failed to read");
			return -1;
		}

		if (ret == 0) {
			/* EOF */
			return 0;
		}

		FORMATIN(libtrace)->remaining=ret;
		FORMATIN(libtrace)->bufptr=
				FORMATIN(libtrace)->buffer;
	}

	/* We do NOT want anything trying to free the memory the packet is
	 * stored in */
	flags |= TRACE_PREP_DO_NOT_OWN_BUFFER;

	if (packet->buf_control == TRACE_CTRL_PACKET)
		free(packet->buffer);

	/* Update 'packet' to point to the first packet in our capture
	 * buffer */
	if (bpf_prepare_packet(libtrace, packet, FORMATIN(libtrace)->bufptr,
		TRACE_RT_DATA_BPF, flags)) {
		return -1;
	}
	

	/* Skip past the packet record we're going to return, making sure
	 * that we deal with padding correctly */
	FORMATIN(libtrace)->bufptr+=
		BPF_WORDALIGN(BPFHDR(packet)->bh_hdrlen
		+BPFHDR(packet)->bh_caplen);
	FORMATIN(libtrace)->remaining-=
		BPF_WORDALIGN(BPFHDR(packet)->bh_hdrlen
		+BPFHDR(packet)->bh_caplen);

	return BPFHDR(packet)->bh_datalen+BPFHDR(packet)->bh_hdrlen;
}

/* Returns the linktype for the interface that we are capturing from */
static libtrace_linktype_t bpf_get_link_type(const libtrace_packet_t *packet) {
	/* Convert the linktype that we recorded when we started the trace
	 * into a suitable libtrace linktype */
	return pcap_linktype_to_libtrace(FORMATIN(packet->trace)->linktype);
}

/* Returns the direction for a given BPF packet record */
static libtrace_direction_t bpf_get_direction(const libtrace_packet_t *packet UNUSED) {
	/* BPF sadly can't do direction tagging */
	return ~0;
}

/* Returns the timestamp for a given BPF packet record, in the form of a 
 * struct timeval */
static struct timeval bpf_get_timeval(const libtrace_packet_t *packet) 
{
	struct timeval tv;
	/* OpenBSD uses a bpf_timeval rather than a timeval so we must copy
	 * each timeval element individually rather than doing a structure
	 * assignment */
	tv.tv_sec = BPFHDR(packet)->bh_tstamp.tv_sec;
	tv.tv_usec = BPFHDR(packet)->bh_tstamp.tv_usec;

	return tv;
}

/* Returns the capture length for a given BPF packet record */
static int bpf_get_capture_length(const libtrace_packet_t *packet)
{
	/* BPF doesn't include the FCS in its caplen field, but libtrace
	 * does so we need to add this extra 4 bytes */
	return BPFHDR(packet)->bh_caplen+4;
}

/* Returns the wire length for a given BPF packet record */
static int bpf_get_wire_length(const libtrace_packet_t *packet) 
{

	/* BPF doesn't include the FCS in its datalen field, but libtrace
	 * does so we need to add this extra 4 bytes */
	return BPFHDR(packet)->bh_datalen+4;
}

/* Returns the framing length for a given BPF packet record */
static int bpf_get_framing_length(UNUSED 
		const libtrace_packet_t *packet) 
{
	return BPFHDR(packet)->bh_hdrlen;
}

/* Returns the file descriptor that the capture interface is operating on */
static int bpf_get_fd(const libtrace_t *trace) {
	return FORMATIN(trace)->fd;
}

/* Prints some slightly useful help text for the BPF capture format */
static void bpf_help() {
	printf("bpf format module: $Revision: 1607 $\n");
	printf("Supported input URIs:\n");
	printf("\tbpf:\n");
	printf("\n");
	return;
}
static struct libtrace_format_t bpf = {
	"bpf",
	"$Id: format_bpf.c 1607 2010-07-16 02:36:48Z salcock $",
	TRACE_FORMAT_BPF,
	bpf_probe_filename,	/* probe filename */
	NULL,			/* probe magic */
	bpf_init_input,	 	/* init_input */
	bpf_config_input,	/* config_input */
	bpf_start_input,	/* start_input */
	bpf_pause_input,	/* pause_input */
	NULL,			/* init_output */
	NULL,			/* config_output */
	NULL,			/* start_ouput */
	bpf_fin_input,		/* fin_input */
	NULL,			/* fin_output */
	bpf_read_packet,	/* read_packet */
	bpf_prepare_packet, 	/* prepare_packet */
	NULL,			/* fin_packet */
	NULL,			/* write_packet */
	bpf_get_link_type,	/* get_link_type */
	bpf_get_direction,	/* get_direction */
	NULL,			/* set_direction */
	NULL,			/* get_erf_timestamp */
	bpf_get_timeval,	/* get_timeval */
	NULL,			/* get_timespec */
	NULL,			/* get_seconds */
	NULL,			/* seek_erf */
	NULL,			/* seek_timeval */
	NULL,			/* seek_seconds */
	bpf_get_capture_length,	/* get_capture_length */
	bpf_get_wire_length,	/* get_wire_length */
	bpf_get_framing_length,	/* get_framing_length */
	NULL,			/* set_capture_length */
	bpf_get_received_packets,/* get_received_packets */
	NULL,			/* get_filtered_packets */
	bpf_get_dropped_packets,/* get_dropped_packets */
	NULL,			/* get_captured_packets */
	bpf_get_fd,		/* get_fd */
	trace_event_device,	/* trace_event */
	bpf_help,		/* help */
	NULL
};

void bpf_constructor() {
	register_format(&bpf);
}