xref: /netbsd-src/external/bsd/libpcap/dist/pcap-dag.c (revision d16b7486a53dcb8072b60ec6fcb4373a2d0c27b7)
1 /*	$NetBSD: pcap-dag.c,v 1.6 2019/10/01 16:02:12 christos Exp $	*/
2 
3 /*
4  * pcap-dag.c: Packet capture interface for Endace DAG cards.
5  *
6  * Authors: Richard Littin, Sean Irvine ({richard,sean}@reeltwo.com)
7  * Modifications: Jesper Peterson
8  *                Koryn Grant
9  *                Stephen Donnelly <stephen.donnelly@endace.com>
10  */
11 
12 #include <sys/cdefs.h>
13 __RCSID("$NetBSD: pcap-dag.c,v 1.6 2019/10/01 16:02:12 christos Exp $");
14 
15 #ifdef HAVE_CONFIG_H
16 #include <config.h>
17 #endif
18 
19 #include <sys/param.h>			/* optionally get BSD define */
20 
21 #include <stdlib.h>
22 #include <string.h>
23 #include <errno.h>
24 
25 #include "pcap-int.h"
26 
27 #include <ctype.h>
28 #include <netinet/in.h>
29 #include <sys/mman.h>
30 #include <sys/socket.h>
31 #include <sys/types.h>
32 #include <unistd.h>
33 
34 struct mbuf;		/* Squelch compiler warnings on some platforms for */
35 struct rtentry;		/* declarations in <net/if.h> */
36 #include <net/if.h>
37 
38 #include "dagnew.h"
39 #include "dagapi.h"
40 #include "dagpci.h"
41 #include "dag_config_api.h"
42 
43 #include "pcap-dag.h"
44 
45 /*
46  * DAG devices have names beginning with "dag", followed by a number
47  * from 0 to DAG_MAX_BOARDS, then optionally a colon and a stream number
48  * from 0 to DAG_STREAM_MAX.
49  */
50 #ifndef DAG_MAX_BOARDS
51 #define DAG_MAX_BOARDS 32
52 #endif
53 
54 
55 #ifndef ERF_TYPE_AAL5
56 #define ERF_TYPE_AAL5               4
57 #endif
58 
59 #ifndef ERF_TYPE_MC_HDLC
60 #define ERF_TYPE_MC_HDLC            5
61 #endif
62 
63 #ifndef ERF_TYPE_MC_RAW
64 #define ERF_TYPE_MC_RAW             6
65 #endif
66 
67 #ifndef ERF_TYPE_MC_ATM
68 #define ERF_TYPE_MC_ATM             7
69 #endif
70 
71 #ifndef ERF_TYPE_MC_RAW_CHANNEL
72 #define ERF_TYPE_MC_RAW_CHANNEL     8
73 #endif
74 
75 #ifndef ERF_TYPE_MC_AAL5
76 #define ERF_TYPE_MC_AAL5            9
77 #endif
78 
79 #ifndef ERF_TYPE_COLOR_HDLC_POS
80 #define ERF_TYPE_COLOR_HDLC_POS     10
81 #endif
82 
83 #ifndef ERF_TYPE_COLOR_ETH
84 #define ERF_TYPE_COLOR_ETH          11
85 #endif
86 
87 #ifndef ERF_TYPE_MC_AAL2
88 #define ERF_TYPE_MC_AAL2            12
89 #endif
90 
91 #ifndef ERF_TYPE_IP_COUNTER
92 #define ERF_TYPE_IP_COUNTER         13
93 #endif
94 
95 #ifndef ERF_TYPE_TCP_FLOW_COUNTER
96 #define ERF_TYPE_TCP_FLOW_COUNTER   14
97 #endif
98 
99 #ifndef ERF_TYPE_DSM_COLOR_HDLC_POS
100 #define ERF_TYPE_DSM_COLOR_HDLC_POS 15
101 #endif
102 
103 #ifndef ERF_TYPE_DSM_COLOR_ETH
104 #define ERF_TYPE_DSM_COLOR_ETH      16
105 #endif
106 
107 #ifndef ERF_TYPE_COLOR_MC_HDLC_POS
108 #define ERF_TYPE_COLOR_MC_HDLC_POS  17
109 #endif
110 
111 #ifndef ERF_TYPE_AAL2
112 #define ERF_TYPE_AAL2               18
113 #endif
114 
115 #ifndef ERF_TYPE_COLOR_HASH_POS
116 #define ERF_TYPE_COLOR_HASH_POS     19
117 #endif
118 
119 #ifndef ERF_TYPE_COLOR_HASH_ETH
120 #define ERF_TYPE_COLOR_HASH_ETH     20
121 #endif
122 
123 #ifndef ERF_TYPE_INFINIBAND
124 #define ERF_TYPE_INFINIBAND         21
125 #endif
126 
127 #ifndef ERF_TYPE_IPV4
128 #define ERF_TYPE_IPV4               22
129 #endif
130 
131 #ifndef ERF_TYPE_IPV6
132 #define ERF_TYPE_IPV6               23
133 #endif
134 
135 #ifndef ERF_TYPE_RAW_LINK
136 #define ERF_TYPE_RAW_LINK           24
137 #endif
138 
139 #ifndef ERF_TYPE_INFINIBAND_LINK
140 #define ERF_TYPE_INFINIBAND_LINK    25
141 #endif
142 
143 #ifndef ERF_TYPE_META
144 #define ERF_TYPE_META               27
145 #endif
146 
147 #ifndef ERF_TYPE_PAD
148 #define ERF_TYPE_PAD                48
149 #endif
150 
151 #define ATM_CELL_SIZE		52
152 #define ATM_HDR_SIZE		4
153 
154 /*
155  * A header containing additional MTP information.
156  */
157 #define MTP2_SENT_OFFSET		0	/* 1 byte */
158 #define MTP2_ANNEX_A_USED_OFFSET	1	/* 1 byte */
159 #define MTP2_LINK_NUMBER_OFFSET		2	/* 2 bytes */
160 #define MTP2_HDR_LEN			4	/* length of the header */
161 
162 #define MTP2_ANNEX_A_NOT_USED      0
163 #define MTP2_ANNEX_A_USED          1
164 #define MTP2_ANNEX_A_USED_UNKNOWN  2
165 
166 /* SunATM pseudo header */
167 struct sunatm_hdr {
168 	unsigned char	flags;		/* destination and traffic type */
169 	unsigned char	vpi;		/* VPI */
170 	unsigned short	vci;		/* VCI */
171 };
172 
173 /*
174  * Private data for capturing on DAG devices.
175  */
176 struct pcap_dag {
177 	struct pcap_stat stat;
178 	u_char	*dag_mem_bottom;	/* DAG card current memory bottom pointer */
179 	u_char	*dag_mem_top;	/* DAG card current memory top pointer */
180 	int	dag_fcs_bits;	/* Number of checksum bits from link layer */
181 	int	dag_flags;	/* Flags */
182 	int	dag_stream;	/* DAG stream number */
183 	int	dag_timeout;	/* timeout specified to pcap_open_live.
184 				 * Same as in linux above, introduce
185 				 * generally? */
186 	dag_card_ref_t dag_ref; /* DAG Configuration/Status API card reference */
187 	dag_component_t dag_root;	/* DAG CSAPI Root component */
188 	attr_uuid_t drop_attr;  /* DAG Stream Drop Attribute handle, if available */
189 	struct timeval required_select_timeout;
190 				/* Timeout caller must use in event loops */
191 };
192 
193 typedef struct pcap_dag_node {
194 	struct pcap_dag_node *next;
195 	pcap_t *p;
196 	pid_t pid;
197 } pcap_dag_node_t;
198 
199 static pcap_dag_node_t *pcap_dags = NULL;
200 static int atexit_handler_installed = 0;
201 static const unsigned short endian_test_word = 0x0100;
202 
203 #define IS_BIGENDIAN() (*((unsigned char *)&endian_test_word))
204 
205 #define MAX_DAG_PACKET 65536
206 
207 static unsigned char TempPkt[MAX_DAG_PACKET];
208 
209 #ifndef HAVE_DAG_LARGE_STREAMS_API
210 #define dag_attach_stream64(a, b, c, d) dag_attach_stream(a, b, c, d)
211 #define dag_get_stream_poll64(a, b, c, d, e) dag_get_stream_poll(a, b, c, d, e)
212 #define dag_set_stream_poll64(a, b, c, d, e) dag_set_stream_poll(a, b, c, d, e)
213 #define dag_size_t uint32_t
214 #endif
215 
216 static int dag_setfilter(pcap_t *p, struct bpf_program *fp);
217 static int dag_stats(pcap_t *p, struct pcap_stat *ps);
218 static int dag_set_datalink(pcap_t *p, int dlt);
219 static int dag_get_datalink(pcap_t *p);
220 static int dag_setnonblock(pcap_t *p, int nonblock);
221 
222 static void
223 delete_pcap_dag(pcap_t *p)
224 {
225 	pcap_dag_node_t *curr = NULL, *prev = NULL;
226 
227 	for (prev = NULL, curr = pcap_dags; curr != NULL && curr->p != p; prev = curr, curr = curr->next) {
228 		/* empty */
229 	}
230 
231 	if (curr != NULL && curr->p == p) {
232 		if (prev != NULL) {
233 			prev->next = curr->next;
234 		} else {
235 			pcap_dags = curr->next;
236 		}
237 	}
238 }
239 
240 /*
241  * Performs a graceful shutdown of the DAG card, frees dynamic memory held
242  * in the pcap_t structure, and closes the file descriptor for the DAG card.
243  */
244 
245 static void
246 dag_platform_cleanup(pcap_t *p)
247 {
248 	struct pcap_dag *pd = p->priv;
249 
250 	if(dag_stop_stream(p->fd, pd->dag_stream) < 0)
251 		fprintf(stderr,"dag_stop_stream: %s\n", strerror(errno));
252 
253 	if(dag_detach_stream(p->fd, pd->dag_stream) < 0)
254 		fprintf(stderr,"dag_detach_stream: %s\n", strerror(errno));
255 
256 	if(pd->dag_ref != NULL) {
257 		dag_config_dispose(pd->dag_ref);
258 		/*
259 		 * Note: we don't need to call close(p->fd) or
260 		 * dag_close(p->fd), as dag_config_dispose(pd->dag_ref)
261 		 * does this.
262 		 *
263 		 * Set p->fd to -1 to make sure that's not done.
264 		 */
265 		p->fd = -1;
266 		pd->dag_ref = NULL;
267 	}
268 	delete_pcap_dag(p);
269 	pcap_cleanup_live_common(p);
270 }
271 
272 static void
273 atexit_handler(void)
274 {
275 	while (pcap_dags != NULL) {
276 		if (pcap_dags->pid == getpid()) {
277 			if (pcap_dags->p != NULL)
278 				dag_platform_cleanup(pcap_dags->p);
279 		} else {
280 			delete_pcap_dag(pcap_dags->p);
281 		}
282 	}
283 }
284 
285 static int
286 new_pcap_dag(pcap_t *p)
287 {
288 	pcap_dag_node_t *node = NULL;
289 
290 	if ((node = malloc(sizeof(pcap_dag_node_t))) == NULL) {
291 		return -1;
292 	}
293 
294 	if (!atexit_handler_installed) {
295 		atexit(atexit_handler);
296 		atexit_handler_installed = 1;
297 	}
298 
299 	node->next = pcap_dags;
300 	node->p = p;
301 	node->pid = getpid();
302 
303 	pcap_dags = node;
304 
305 	return 0;
306 }
307 
308 static unsigned int
309 dag_erf_ext_header_count(uint8_t * erf, size_t len)
310 {
311 	uint32_t hdr_num = 0;
312 	uint8_t  hdr_type;
313 
314 	/* basic sanity checks */
315 	if ( erf == NULL )
316 		return 0;
317 	if ( len < 16 )
318 		return 0;
319 
320 	/* check if we have any extension headers */
321 	if ( (erf[8] & 0x80) == 0x00 )
322 		return 0;
323 
324 	/* loop over the extension headers */
325 	do {
326 
327 		/* sanity check we have enough bytes */
328 		if ( len < (24 + (hdr_num * 8)) )
329 			return hdr_num;
330 
331 		/* get the header type */
332 		hdr_type = erf[(16 + (hdr_num * 8))];
333 		hdr_num++;
334 
335 	} while ( hdr_type & 0x80 );
336 
337 	return hdr_num;
338 }
339 
340 /*
341  *  Read at most max_packets from the capture stream and call the callback
342  *  for each of them. Returns the number of packets handled, -1 if an
343  *  error occured, or -2 if we were told to break out of the loop.
344  */
345 static int
346 dag_read(pcap_t *p, int cnt, pcap_handler callback, u_char *user)
347 {
348 	struct pcap_dag *pd = p->priv;
349 	unsigned int processed = 0;
350 	unsigned int nonblocking = pd->dag_flags & DAGF_NONBLOCK;
351 	unsigned int num_ext_hdr = 0;
352 	unsigned int ticks_per_second;
353 
354 	/* Get the next bufferful of packets (if necessary). */
355 	while (pd->dag_mem_top - pd->dag_mem_bottom < dag_record_size) {
356 
357 		/*
358 		 * Has "pcap_breakloop()" been called?
359 		 */
360 		if (p->break_loop) {
361 			/*
362 			 * Yes - clear the flag that indicates that
363 			 * it has, and return -2 to indicate that
364 			 * we were told to break out of the loop.
365 			 */
366 			p->break_loop = 0;
367 			return -2;
368 		}
369 
370 		/* dag_advance_stream() will block (unless nonblock is called)
371 		 * until 64kB of data has accumulated.
372 		 * If to_ms is set, it will timeout before 64kB has accumulated.
373 		 * We wait for 64kB because processing a few packets at a time
374 		 * can cause problems at high packet rates (>200kpps) due
375 		 * to inefficiencies.
376 		 * This does mean if to_ms is not specified the capture may 'hang'
377 		 * for long periods if the data rate is extremely slow (<64kB/sec)
378 		 * If non-block is specified it will return immediately. The user
379 		 * is then responsible for efficiency.
380 		 */
381 		if ( NULL == (pd->dag_mem_top = dag_advance_stream(p->fd, pd->dag_stream, &(pd->dag_mem_bottom))) ) {
382 		     return -1;
383 		}
384 
385 		if (nonblocking && (pd->dag_mem_top - pd->dag_mem_bottom < dag_record_size))
386 		{
387 			/* Pcap is configured to process only available packets, and there aren't any, return immediately. */
388 			return 0;
389 		}
390 
391 		if(!nonblocking &&
392 		   pd->dag_timeout &&
393 		   (pd->dag_mem_top - pd->dag_mem_bottom < dag_record_size))
394 		{
395 			/* Blocking mode, but timeout set and no data has arrived, return anyway.*/
396 			return 0;
397 		}
398 
399 	}
400 
401 	/* Process the packets. */
402 	while (pd->dag_mem_top - pd->dag_mem_bottom >= dag_record_size) {
403 
404 		unsigned short packet_len = 0;
405 		int caplen = 0;
406 		struct pcap_pkthdr	pcap_header;
407 
408 		dag_record_t *header = (dag_record_t *)(pd->dag_mem_bottom);
409 
410 		u_char *dp = ((u_char *)header); /* + dag_record_size; */
411 		unsigned short rlen;
412 
413 		/*
414 		 * Has "pcap_breakloop()" been called?
415 		 */
416 		if (p->break_loop) {
417 			/*
418 			 * Yes - clear the flag that indicates that
419 			 * it has, and return -2 to indicate that
420 			 * we were told to break out of the loop.
421 			 */
422 			p->break_loop = 0;
423 			return -2;
424 		}
425 
426 		rlen = ntohs(header->rlen);
427 		if (rlen < dag_record_size)
428 		{
429 			strncpy(p->errbuf, "dag_read: record too small", PCAP_ERRBUF_SIZE);
430 			return -1;
431 		}
432 		pd->dag_mem_bottom += rlen;
433 
434 		/* Count lost packets. */
435 		switch((header->type & 0x7f)) {
436 			/* in these types the color value overwrites the lctr */
437 		case ERF_TYPE_COLOR_HDLC_POS:
438 		case ERF_TYPE_COLOR_ETH:
439 		case ERF_TYPE_DSM_COLOR_HDLC_POS:
440 		case ERF_TYPE_DSM_COLOR_ETH:
441 		case ERF_TYPE_COLOR_MC_HDLC_POS:
442 		case ERF_TYPE_COLOR_HASH_ETH:
443 		case ERF_TYPE_COLOR_HASH_POS:
444 			break;
445 
446 		default:
447 			if ( (pd->drop_attr == kNullAttributeUuid) && (header->lctr) ) {
448 				pd->stat.ps_drop += ntohs(header->lctr);
449 			}
450 		}
451 
452 		if ((header->type & 0x7f) == ERF_TYPE_PAD) {
453 			continue;
454 		}
455 
456 		num_ext_hdr = dag_erf_ext_header_count(dp, rlen);
457 
458 		/* ERF encapsulation */
459 		/* The Extensible Record Format is not dropped for this kind of encapsulation,
460 		 * and will be handled as a pseudo header by the decoding application.
461 		 * The information carried in the ERF header and in the optional subheader (if present)
462 		 * could be merged with the libpcap information, to offer a better decoding.
463 		 * The packet length is
464 		 * o the length of the packet on the link (header->wlen),
465 		 * o plus the length of the ERF header (dag_record_size), as the length of the
466 		 *   pseudo header will be adjusted during the decoding,
467 		 * o plus the length of the optional subheader (if present).
468 		 *
469 		 * The capture length is header.rlen and the byte stuffing for alignment will be dropped
470 		 * if the capture length is greater than the packet length.
471 		 */
472 		if (p->linktype == DLT_ERF) {
473 			packet_len = ntohs(header->wlen) + dag_record_size;
474 			caplen = rlen;
475 			switch ((header->type & 0x7f)) {
476 			case ERF_TYPE_MC_AAL5:
477 			case ERF_TYPE_MC_ATM:
478 			case ERF_TYPE_MC_HDLC:
479 			case ERF_TYPE_MC_RAW_CHANNEL:
480 			case ERF_TYPE_MC_RAW:
481 			case ERF_TYPE_MC_AAL2:
482 			case ERF_TYPE_COLOR_MC_HDLC_POS:
483 				packet_len += 4; /* MC header */
484 				break;
485 
486 			case ERF_TYPE_COLOR_HASH_ETH:
487 			case ERF_TYPE_DSM_COLOR_ETH:
488 			case ERF_TYPE_COLOR_ETH:
489 			case ERF_TYPE_ETH:
490 				packet_len += 2; /* ETH header */
491 				break;
492 			} /* switch type */
493 
494 			/* Include ERF extension headers */
495 			packet_len += (8 * num_ext_hdr);
496 
497 			if (caplen > packet_len) {
498 				caplen = packet_len;
499 			}
500 		} else {
501 			/* Other kind of encapsulation according to the header Type */
502 
503 			/* Skip over generic ERF header */
504 			dp += dag_record_size;
505 			/* Skip over extension headers */
506 			dp += 8 * num_ext_hdr;
507 
508 			switch((header->type & 0x7f)) {
509 			case ERF_TYPE_ATM:
510 			case ERF_TYPE_AAL5:
511 				if ((header->type & 0x7f) == ERF_TYPE_AAL5) {
512 					packet_len = ntohs(header->wlen);
513 					caplen = rlen - dag_record_size;
514 				}
515 			case ERF_TYPE_MC_ATM:
516 				if ((header->type & 0x7f) == ERF_TYPE_MC_ATM) {
517 					caplen = packet_len = ATM_CELL_SIZE;
518 					dp+=4;
519 				}
520 			case ERF_TYPE_MC_AAL5:
521 				if ((header->type & 0x7f) == ERF_TYPE_MC_AAL5) {
522 					packet_len = ntohs(header->wlen);
523 					caplen = rlen - dag_record_size - 4;
524 					dp+=4;
525 				}
526 				/* Skip over extension headers */
527 				caplen -= (8 * num_ext_hdr);
528 
529 				if ((header->type & 0x7f) == ERF_TYPE_ATM) {
530 					caplen = packet_len = ATM_CELL_SIZE;
531 				}
532 				if (p->linktype == DLT_SUNATM) {
533 					struct sunatm_hdr *sunatm = (struct sunatm_hdr *)dp;
534 					unsigned long rawatm;
535 
536 					rawatm = ntohl(*((unsigned long *)dp));
537 					sunatm->vci = htons((rawatm >>  4) & 0xffff);
538 					sunatm->vpi = (rawatm >> 20) & 0x00ff;
539 					sunatm->flags = ((header->flags.iface & 1) ? 0x80 : 0x00) |
540 						((sunatm->vpi == 0 && sunatm->vci == htons(5)) ? 6 :
541 						 ((sunatm->vpi == 0 && sunatm->vci == htons(16)) ? 5 :
542 						  ((dp[ATM_HDR_SIZE] == 0xaa &&
543 						    dp[ATM_HDR_SIZE+1] == 0xaa &&
544 						    dp[ATM_HDR_SIZE+2] == 0x03) ? 2 : 1)));
545 
546 				} else if (p->linktype == DLT_ATM_RFC1483) {
547 					packet_len -= ATM_HDR_SIZE;
548 					caplen -= ATM_HDR_SIZE;
549 					dp += ATM_HDR_SIZE;
550 				} else
551 					continue;
552 				break;
553 
554 			case ERF_TYPE_COLOR_HASH_ETH:
555 			case ERF_TYPE_DSM_COLOR_ETH:
556 			case ERF_TYPE_COLOR_ETH:
557 			case ERF_TYPE_ETH:
558 				if ((p->linktype != DLT_EN10MB) &&
559 				    (p->linktype != DLT_DOCSIS))
560 					continue;
561 				packet_len = ntohs(header->wlen);
562 				packet_len -= (pd->dag_fcs_bits >> 3);
563 				caplen = rlen - dag_record_size - 2;
564 				/* Skip over extension headers */
565 				caplen -= (8 * num_ext_hdr);
566 				if (caplen > packet_len) {
567 					caplen = packet_len;
568 				}
569 				dp += 2;
570 				break;
571 
572 			case ERF_TYPE_COLOR_HASH_POS:
573 			case ERF_TYPE_DSM_COLOR_HDLC_POS:
574 			case ERF_TYPE_COLOR_HDLC_POS:
575 			case ERF_TYPE_HDLC_POS:
576 				if ((p->linktype != DLT_CHDLC) &&
577 				    (p->linktype != DLT_PPP_SERIAL) &&
578 				    (p->linktype != DLT_FRELAY))
579 					continue;
580 				packet_len = ntohs(header->wlen);
581 				packet_len -= (pd->dag_fcs_bits >> 3);
582 				caplen = rlen - dag_record_size;
583 				/* Skip over extension headers */
584 				caplen -= (8 * num_ext_hdr);
585 				if (caplen > packet_len) {
586 					caplen = packet_len;
587 				}
588 				break;
589 
590 			case ERF_TYPE_COLOR_MC_HDLC_POS:
591 			case ERF_TYPE_MC_HDLC:
592 				if ((p->linktype != DLT_CHDLC) &&
593 				    (p->linktype != DLT_PPP_SERIAL) &&
594 				    (p->linktype != DLT_FRELAY) &&
595 				    (p->linktype != DLT_MTP2) &&
596 				    (p->linktype != DLT_MTP2_WITH_PHDR) &&
597 				    (p->linktype != DLT_LAPD))
598 					continue;
599 				packet_len = ntohs(header->wlen);
600 				packet_len -= (pd->dag_fcs_bits >> 3);
601 				caplen = rlen - dag_record_size - 4;
602 				/* Skip over extension headers */
603 				caplen -= (8 * num_ext_hdr);
604 				if (caplen > packet_len) {
605 					caplen = packet_len;
606 				}
607 				/* jump the MC_HDLC_HEADER */
608 				dp += 4;
609 #ifdef DLT_MTP2_WITH_PHDR
610 				if (p->linktype == DLT_MTP2_WITH_PHDR) {
611 					/* Add the MTP2 Pseudo Header */
612 					caplen += MTP2_HDR_LEN;
613 					packet_len += MTP2_HDR_LEN;
614 
615 					TempPkt[MTP2_SENT_OFFSET] = 0;
616 					TempPkt[MTP2_ANNEX_A_USED_OFFSET] = MTP2_ANNEX_A_USED_UNKNOWN;
617 					*(TempPkt+MTP2_LINK_NUMBER_OFFSET) = ((header->rec.mc_hdlc.mc_header>>16)&0x01);
618 					*(TempPkt+MTP2_LINK_NUMBER_OFFSET+1) = ((header->rec.mc_hdlc.mc_header>>24)&0xff);
619 					memcpy(TempPkt+MTP2_HDR_LEN, dp, caplen);
620 					dp = TempPkt;
621 				}
622 #endif
623 				break;
624 
625 			case ERF_TYPE_IPV4:
626 				if ((p->linktype != DLT_RAW) &&
627 				    (p->linktype != DLT_IPV4))
628 					continue;
629 				packet_len = ntohs(header->wlen);
630 				caplen = rlen - dag_record_size;
631 				/* Skip over extension headers */
632 				caplen -= (8 * num_ext_hdr);
633 				if (caplen > packet_len) {
634 					caplen = packet_len;
635 				}
636 				break;
637 
638 			case ERF_TYPE_IPV6:
639 				if ((p->linktype != DLT_RAW) &&
640 				    (p->linktype != DLT_IPV6))
641 					continue;
642 				packet_len = ntohs(header->wlen);
643 				caplen = rlen - dag_record_size;
644 				/* Skip over extension headers */
645 				caplen -= (8 * num_ext_hdr);
646 				if (caplen > packet_len) {
647 					caplen = packet_len;
648 				}
649 				break;
650 
651 			/* These types have no matching 'native' DLT, but can be used with DLT_ERF above */
652 			case ERF_TYPE_MC_RAW:
653 			case ERF_TYPE_MC_RAW_CHANNEL:
654 			case ERF_TYPE_IP_COUNTER:
655 			case ERF_TYPE_TCP_FLOW_COUNTER:
656 			case ERF_TYPE_INFINIBAND:
657 			case ERF_TYPE_RAW_LINK:
658 			case ERF_TYPE_INFINIBAND_LINK:
659 			default:
660 				/* Unhandled ERF type.
661 				 * Ignore rather than generating error
662 				 */
663 				continue;
664 			} /* switch type */
665 
666 		} /* ERF encapsulation */
667 
668 		if (caplen > p->snapshot)
669 			caplen = p->snapshot;
670 
671 		/* Run the packet filter if there is one. */
672 		if ((p->fcode.bf_insns == NULL) || bpf_filter(p->fcode.bf_insns, dp, packet_len, caplen)) {
673 
674 			/* convert between timestamp formats */
675 			register unsigned long long ts;
676 
677 			if (IS_BIGENDIAN()) {
678 				ts = SWAPLL(header->ts);
679 			} else {
680 				ts = header->ts;
681 			}
682 
683 			switch (p->opt.tstamp_precision) {
684 			case PCAP_TSTAMP_PRECISION_NANO:
685 				ticks_per_second = 1000000000;
686 				break;
687 			case PCAP_TSTAMP_PRECISION_MICRO:
688 			default:
689 				ticks_per_second = 1000000;
690 				break;
691 
692 			}
693 			pcap_header.ts.tv_sec = ts >> 32;
694 			ts = (ts & 0xffffffffULL) * ticks_per_second;
695 			ts += 0x80000000; /* rounding */
696 			pcap_header.ts.tv_usec = ts >> 32;
697 			if (pcap_header.ts.tv_usec >= ticks_per_second) {
698 				pcap_header.ts.tv_usec -= ticks_per_second;
699 				pcap_header.ts.tv_sec++;
700 			}
701 
702 			/* Fill in our own header data */
703 			pcap_header.caplen = caplen;
704 			pcap_header.len = packet_len;
705 
706 			/* Count the packet. */
707 			pd->stat.ps_recv++;
708 
709 			/* Call the user supplied callback function */
710 			callback(user, &pcap_header, dp);
711 
712 			/* Only count packets that pass the filter, for consistency with standard Linux behaviour. */
713 			processed++;
714 			if (processed == cnt && !PACKET_COUNT_IS_UNLIMITED(cnt))
715 			{
716 				/* Reached the user-specified limit. */
717 				return cnt;
718 			}
719 		}
720 	}
721 
722 	return processed;
723 }
724 
725 static int
726 dag_inject(pcap_t *p, const void *buf _U_, size_t size _U_)
727 {
728 	pcap_strlcpy(p->errbuf, "Sending packets isn't supported on DAG cards",
729 	    PCAP_ERRBUF_SIZE);
730 	return (-1);
731 }
732 
733 /*
734  *  Get a handle for a live capture from the given DAG device.  Passing a NULL
735  *  device will result in a failure.  The promisc flag is ignored because DAG
736  *  cards are always promiscuous.  The to_ms parameter is used in setting the
737  *  API polling parameters.
738  *
739  *  snaplen is now also ignored, until we get per-stream slen support. Set
740  *  slen with approprite DAG tool BEFORE pcap_activate().
741  *
742  *  See also pcap(3).
743  */
744 static int dag_activate(pcap_t* p)
745 {
746 	struct pcap_dag *pd = p->priv;
747 	char *s;
748 	int n;
749 	daginf_t* daginf;
750 	char * newDev = NULL;
751 	char * device = p->opt.device;
752 	int ret;
753 	dag_size_t mindata;
754 	struct timeval maxwait;
755 	struct timeval poll;
756 
757 	if (device == NULL) {
758 		pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "device is NULL");
759 		return PCAP_ERROR;
760 	}
761 
762 	/* Initialize some components of the pcap structure. */
763 	newDev = (char *)malloc(strlen(device) + 16);
764 	if (newDev == NULL) {
765 		ret = PCAP_ERROR;
766 		pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
767 		    errno, "Can't allocate string for device name");
768 		goto fail;
769 	}
770 
771 	/* Parse input name to get dag device and stream number if provided */
772 	if (dag_parse_name(device, newDev, strlen(device) + 16, &pd->dag_stream) < 0) {
773 		/*
774 		 * XXX - it'd be nice if this indicated what was wrong
775 		 * with the name.  Does this reliably set errno?
776 		 * Should this return PCAP_ERROR_NO_SUCH_DEVICE in some
777 		 * cases?
778 		 */
779 		ret = PCAP_ERROR;
780 		pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
781 		    errno, "dag_parse_name");
782 		goto fail;
783 	}
784 	device = newDev;
785 
786 	if (pd->dag_stream%2) {
787 		ret = PCAP_ERROR;
788 		pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "dag_parse_name: tx (even numbered) streams not supported for capture");
789 		goto fail;
790 	}
791 
792 	/* setup device parameters */
793 	if((pd->dag_ref = dag_config_init((char *)device)) == NULL) {
794 		/*
795 		 * XXX - does this reliably set errno?
796 		 */
797 		if (errno == ENOENT)
798 			ret = PCAP_ERROR_NO_SUCH_DEVICE;
799 		else if (errno == EPERM || errno == EACCES)
800 			ret = PCAP_ERROR_PERM_DENIED;
801 		else
802 			ret = PCAP_ERROR;
803 		pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
804 		    errno, "dag_config_init %s", device);
805 		goto fail;
806 	}
807 
808 	if((p->fd = dag_config_get_card_fd(pd->dag_ref)) < 0) {
809 		/*
810 		 * XXX - does this reliably set errno?
811 		 */
812 		ret = PCAP_ERROR;
813 		pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
814 		    errno, "dag_config_get_card_fd %s", device);
815 		goto failclose;
816 	}
817 
818 	/* Open requested stream. Can fail if already locked or on error */
819 	if (dag_attach_stream64(p->fd, pd->dag_stream, 0, 0) < 0) {
820 		ret = PCAP_ERROR;
821 		pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
822 		    errno, "dag_attach_stream");
823 		goto failclose;
824 	}
825 
826 	/* Try to find Stream Drop attribute */
827 	pd->drop_attr = kNullAttributeUuid;
828 	pd->dag_root = dag_config_get_root_component(pd->dag_ref);
829 	if ( dag_component_get_subcomponent(pd->dag_root, kComponentStreamFeatures, 0) )
830 	{
831 		pd->drop_attr = dag_config_get_indexed_attribute_uuid(pd->dag_ref, kUint32AttributeStreamDropCount, pd->dag_stream/2);
832 	}
833 
834 	/* Set up default poll parameters for stream
835 	 * Can be overridden by pcap_set_nonblock()
836 	 */
837 	if (dag_get_stream_poll64(p->fd, pd->dag_stream,
838 				&mindata, &maxwait, &poll) < 0) {
839 		ret = PCAP_ERROR;
840 		pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
841 		    errno, "dag_get_stream_poll");
842 		goto faildetach;
843 	}
844 
845 	/* Use the poll time as the required select timeout for callers
846 	 * who are using select()/etc. in an event loop waiting for
847 	 * packets to arrive.
848 	 */
849 	pd->required_select_timeout = poll;
850 	p->required_select_timeout = &pd->required_select_timeout;
851 
852 	/*
853 	 * Turn a negative snapshot value (invalid), a snapshot value of
854 	 * 0 (unspecified), or a value bigger than the normal maximum
855 	 * value, into the maximum allowed value.
856 	 *
857 	 * If some application really *needs* a bigger snapshot
858 	 * length, we should just increase MAXIMUM_SNAPLEN.
859 	 */
860 	if (p->snapshot <= 0 || p->snapshot > MAXIMUM_SNAPLEN)
861 		p->snapshot = MAXIMUM_SNAPLEN;
862 
863 	if (p->opt.immediate) {
864 		/* Call callback immediately.
865 		 * XXX - is this the right way to p this?
866 		 */
867 		mindata = 0;
868 	} else {
869 		/* Amount of data to collect in Bytes before calling callbacks.
870 		 * Important for efficiency, but can introduce latency
871 		 * at low packet rates if to_ms not set!
872 		 */
873 		mindata = 65536;
874 	}
875 
876 	/* Obey opt.timeout (was to_ms) if supplied. This is a good idea!
877 	 * Recommend 10-100ms. Calls will time out even if no data arrived.
878 	 */
879 	maxwait.tv_sec = p->opt.timeout/1000;
880 	maxwait.tv_usec = (p->opt.timeout%1000) * 1000;
881 
882 	if (dag_set_stream_poll64(p->fd, pd->dag_stream,
883 				mindata, &maxwait, &poll) < 0) {
884 		ret = PCAP_ERROR;
885 		pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
886 		    errno, "dag_set_stream_poll");
887 		goto faildetach;
888 	}
889 
890         /* XXX Not calling dag_configure() to set slen; this is unsafe in
891 	 * multi-stream environments as the gpp config is global.
892          * Once the firmware provides 'per-stream slen' this can be supported
893 	 * again via the Config API without side-effects */
894 #if 0
895 	/* set the card snap length to the specified snaplen parameter */
896 	/* This is a really bad idea, as different cards have different
897 	 * valid slen ranges. Should fix in Config API. */
898 	if (p->snapshot == 0 || p->snapshot > MAX_DAG_SNAPLEN) {
899 		p->snapshot = MAX_DAG_SNAPLEN;
900 	} else if (snaplen < MIN_DAG_SNAPLEN) {
901 		p->snapshot = MIN_DAG_SNAPLEN;
902 	}
903 	/* snap len has to be a multiple of 4 */
904 #endif
905 
906 	if(dag_start_stream(p->fd, pd->dag_stream) < 0) {
907 		ret = PCAP_ERROR;
908 		pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
909 		    errno, "dag_start_stream %s", device);
910 		goto faildetach;
911 	}
912 
913 	/*
914 	 * Important! You have to ensure bottom is properly
915 	 * initialized to zero on startup, it won't give you
916 	 * a compiler warning if you make this mistake!
917 	 */
918 	pd->dag_mem_bottom = 0;
919 	pd->dag_mem_top = 0;
920 
921 	/*
922 	 * Find out how many FCS bits we should strip.
923 	 * First, query the card to see if it strips the FCS.
924 	 */
925 	daginf = dag_info(p->fd);
926 	if ((0x4200 == daginf->device_code) || (0x4230 == daginf->device_code))	{
927 		/* DAG 4.2S and 4.23S already strip the FCS.  Stripping the final word again truncates the packet. */
928 		pd->dag_fcs_bits = 0;
929 
930 		/* Note that no FCS will be supplied. */
931 		p->linktype_ext = LT_FCS_DATALINK_EXT(0);
932 	} else {
933 		/*
934 		 * Start out assuming it's 32 bits.
935 		 */
936 		pd->dag_fcs_bits = 32;
937 
938 		/* Allow an environment variable to override. */
939 		if ((s = getenv("ERF_FCS_BITS")) != NULL) {
940 			if ((n = atoi(s)) == 0 || n == 16 || n == 32) {
941 				pd->dag_fcs_bits = n;
942 			} else {
943 				ret = PCAP_ERROR;
944 				pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
945 					"pcap_activate %s: bad ERF_FCS_BITS value (%d) in environment", device, n);
946 				goto failstop;
947 			}
948 		}
949 
950 		/*
951 		 * Did the user request that they not be stripped?
952 		 */
953 		if ((s = getenv("ERF_DONT_STRIP_FCS")) != NULL) {
954 			/* Yes.  Note the number of bytes that will be
955 			   supplied. */
956 			p->linktype_ext = LT_FCS_DATALINK_EXT(pd->dag_fcs_bits/16);
957 
958 			/* And don't strip them. */
959 			pd->dag_fcs_bits = 0;
960 		}
961 	}
962 
963 	pd->dag_timeout	= p->opt.timeout;
964 
965 	p->linktype = -1;
966 	if (dag_get_datalink(p) < 0) {
967 		ret = PCAP_ERROR;
968 		goto failstop;
969 	}
970 
971 	p->bufsize = 0;
972 
973 	if (new_pcap_dag(p) < 0) {
974 		ret = PCAP_ERROR;
975 		pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
976 		    errno, "new_pcap_dag %s", device);
977 		goto failstop;
978 	}
979 
980 	/*
981 	 * "select()" and "poll()" don't work on DAG device descriptors.
982 	 */
983 	p->selectable_fd = -1;
984 
985 	if (newDev != NULL) {
986 		free((char *)newDev);
987 	}
988 
989 	p->read_op = dag_read;
990 	p->inject_op = dag_inject;
991 	p->setfilter_op = dag_setfilter;
992 	p->setdirection_op = NULL; /* Not implemented.*/
993 	p->set_datalink_op = dag_set_datalink;
994 	p->getnonblock_op = pcap_getnonblock_fd;
995 	p->setnonblock_op = dag_setnonblock;
996 	p->stats_op = dag_stats;
997 	p->cleanup_op = dag_platform_cleanup;
998 	pd->stat.ps_drop = 0;
999 	pd->stat.ps_recv = 0;
1000 	pd->stat.ps_ifdrop = 0;
1001 	return 0;
1002 
1003 failstop:
1004 	if (dag_stop_stream(p->fd, pd->dag_stream) < 0) {
1005 		fprintf(stderr,"dag_stop_stream: %s\n", strerror(errno));
1006 	}
1007 
1008 faildetach:
1009 	if (dag_detach_stream(p->fd, pd->dag_stream) < 0)
1010 		fprintf(stderr,"dag_detach_stream: %s\n", strerror(errno));
1011 
1012 failclose:
1013 	dag_config_dispose(pd->dag_ref);
1014 	/*
1015 	 * Note: we don't need to call close(p->fd) or dag_close(p->fd),
1016 	 * as dag_config_dispose(pd->dag_ref) does this.
1017 	 *
1018 	 * Set p->fd to -1 to make sure that's not done.
1019 	 */
1020 	p->fd = -1;
1021 	pd->dag_ref = NULL;
1022 	delete_pcap_dag(p);
1023 
1024 fail:
1025 	pcap_cleanup_live_common(p);
1026 	if (newDev != NULL) {
1027 		free((char *)newDev);
1028 	}
1029 
1030 	return ret;
1031 }
1032 
1033 pcap_t *dag_create(const char *device, char *ebuf, int *is_ours)
1034 {
1035 	const char *cp;
1036 	char *cpend;
1037 	long devnum;
1038 	pcap_t *p;
1039 	long stream = 0;
1040 
1041 	/* Does this look like a DAG device? */
1042 	cp = strrchr(device, '/');
1043 	if (cp == NULL)
1044 		cp = device;
1045 	/* Does it begin with "dag"? */
1046 	if (strncmp(cp, "dag", 3) != 0) {
1047 		/* Nope, doesn't begin with "dag" */
1048 		*is_ours = 0;
1049 		return NULL;
1050 	}
1051 	/* Yes - is "dag" followed by a number from 0 to DAG_MAX_BOARDS-1 */
1052 	cp += 3;
1053 	devnum = strtol(cp, &cpend, 10);
1054 	if (*cpend == ':') {
1055 		/* Followed by a stream number. */
1056 		stream = strtol(++cpend, &cpend, 10);
1057 	}
1058 
1059 	if (cpend == cp || *cpend != '\0') {
1060 		/* Not followed by a number. */
1061 		*is_ours = 0;
1062 		return NULL;
1063 	}
1064 
1065 	if (devnum < 0 || devnum >= DAG_MAX_BOARDS) {
1066 		/* Followed by a non-valid number. */
1067 		*is_ours = 0;
1068 		return NULL;
1069 	}
1070 
1071 	if (stream <0 || stream >= DAG_STREAM_MAX) {
1072 		/* Followed by a non-valid stream number. */
1073 		*is_ours = 0;
1074 		return NULL;
1075 	}
1076 
1077 	/* OK, it's probably ours. */
1078 	*is_ours = 1;
1079 
1080 	p = pcap_create_common(ebuf, sizeof (struct pcap_dag));
1081 	if (p == NULL)
1082 		return NULL;
1083 
1084 	p->activate_op = dag_activate;
1085 
1086 	/*
1087 	 * We claim that we support microsecond and nanosecond time
1088 	 * stamps.
1089 	 *
1090 	 * XXX Our native precision is 2^-32s, but libpcap doesn't support
1091 	 * power of two precisions yet. We can convert to either MICRO or NANO.
1092 	 */
1093 	p->tstamp_precision_count = 2;
1094 	p->tstamp_precision_list = malloc(2 * sizeof(u_int));
1095 	if (p->tstamp_precision_list == NULL) {
1096 		pcap_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
1097 		    errno, "malloc");
1098 		pcap_close(p);
1099 		return NULL;
1100 	}
1101 	p->tstamp_precision_list[0] = PCAP_TSTAMP_PRECISION_MICRO;
1102 	p->tstamp_precision_list[1] = PCAP_TSTAMP_PRECISION_NANO;
1103 	return p;
1104 }
1105 
1106 static int
1107 dag_stats(pcap_t *p, struct pcap_stat *ps) {
1108 	struct pcap_dag *pd = p->priv;
1109 	uint32_t stream_drop;
1110 	dag_err_t dag_error;
1111 
1112 	/*
1113 	 * Packet records received (ps_recv) are counted in dag_read().
1114 	 * Packet records dropped (ps_drop) are read from Stream Drop attribute if present,
1115 	 * otherwise integrate the ERF Header lctr counts (if available) in dag_read().
1116 	 * We are reporting that no records are dropped by the card/driver (ps_ifdrop).
1117 	 */
1118 
1119 	if(pd->drop_attr != kNullAttributeUuid) {
1120 		/* Note this counter is cleared at start of capture and will wrap at UINT_MAX.
1121 		 * The application is responsible for polling ps_drop frequently enough
1122 		 * to detect each wrap and integrate total drop with a wider counter */
1123 		if ((dag_error = dag_config_get_uint32_attribute_ex(pd->dag_ref, pd->drop_attr, &stream_drop) == kDagErrNone)) {
1124 			pd->stat.ps_drop = stream_drop;
1125 		} else {
1126 			pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "reading stream drop attribute: %s",
1127 				 dag_config_strerror(dag_error));
1128 			return -1;
1129 		}
1130 	}
1131 
1132 	*ps = pd->stat;
1133 
1134 	return 0;
1135 }
1136 
1137 /*
1138  * Add all DAG devices.
1139  */
1140 int
1141 dag_findalldevs(pcap_if_list_t *devlistp, char *errbuf)
1142 {
1143 	char name[12];	/* XXX - pick a size */
1144 	int c;
1145 	char dagname[DAGNAME_BUFSIZE];
1146 	int dagstream;
1147 	int dagfd;
1148 	dag_card_inf_t *inf;
1149 	char *description;
1150 	int stream, rxstreams;
1151 
1152 	/* Try all the DAGs 0-DAG_MAX_BOARDS */
1153 	for (c = 0; c < DAG_MAX_BOARDS; c++) {
1154 		pcap_snprintf(name, 12, "dag%d", c);
1155 		if (-1 == dag_parse_name(name, dagname, DAGNAME_BUFSIZE, &dagstream))
1156 		{
1157 			(void) pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
1158 			    "dag: device name %s can't be parsed", name);
1159 			return (-1);
1160 		}
1161 		if ( (dagfd = dag_open(dagname)) >= 0 ) {
1162 			description = NULL;
1163 			if ((inf = dag_pciinfo(dagfd)))
1164 				description = dag_device_name(inf->device_code, 1);
1165 			/*
1166 			 * XXX - is there a way to determine whether
1167 			 * the card is plugged into a network or not?
1168 			 * If so, we should check that and set
1169 			 * PCAP_IF_CONNECTION_STATUS_CONNECTED or
1170 			 * PCAP_IF_CONNECTION_STATUS_DISCONNECTED.
1171 			 *
1172 			 * Also, are there notions of "up" and "running"?
1173 			 */
1174 			if (add_dev(devlistp, name, 0, description, errbuf) == NULL) {
1175 				/*
1176 				 * Failure.
1177 				 */
1178 				return (-1);
1179 			}
1180 			rxstreams = dag_rx_get_stream_count(dagfd);
1181 			for(stream=0;stream<DAG_STREAM_MAX;stream+=2) {
1182 				if (0 == dag_attach_stream64(dagfd, stream, 0, 0)) {
1183 					dag_detach_stream(dagfd, stream);
1184 
1185 					pcap_snprintf(name,  10, "dag%d:%d", c, stream);
1186 					if (add_dev(devlistp, name, 0, description, errbuf) == NULL) {
1187 						/*
1188 						 * Failure.
1189 						 */
1190 						return (-1);
1191 					}
1192 
1193 					rxstreams--;
1194 					if(rxstreams <= 0) {
1195 						break;
1196 					}
1197 				}
1198 			}
1199 			dag_close(dagfd);
1200 		}
1201 
1202 	}
1203 	return (0);
1204 }
1205 
1206 /*
1207  * Installs the given bpf filter program in the given pcap structure.  There is
1208  * no attempt to store the filter in kernel memory as that is not supported
1209  * with DAG cards.
1210  */
1211 static int
1212 dag_setfilter(pcap_t *p, struct bpf_program *fp)
1213 {
1214 	if (!p)
1215 		return -1;
1216 	if (!fp) {
1217 		strncpy(p->errbuf, "setfilter: No filter specified",
1218 			sizeof(p->errbuf));
1219 		return -1;
1220 	}
1221 
1222 	/* Make our private copy of the filter */
1223 
1224 	if (install_bpf_program(p, fp) < 0)
1225 		return -1;
1226 
1227 	return (0);
1228 }
1229 
1230 static int
1231 dag_set_datalink(pcap_t *p, int dlt)
1232 {
1233 	p->linktype = dlt;
1234 
1235 	return (0);
1236 }
1237 
1238 static int
1239 dag_setnonblock(pcap_t *p, int nonblock)
1240 {
1241 	struct pcap_dag *pd = p->priv;
1242 	dag_size_t mindata;
1243 	struct timeval maxwait;
1244 	struct timeval poll;
1245 
1246 	/*
1247 	 * Set non-blocking mode on the FD.
1248 	 * XXX - is that necessary?  If not, don't bother calling it,
1249 	 * and have a "dag_getnonblock()" function that looks at
1250 	 * "pd->dag_flags".
1251 	 */
1252 	if (pcap_setnonblock_fd(p, nonblock) < 0)
1253 		return (-1);
1254 
1255 	if (dag_get_stream_poll64(p->fd, pd->dag_stream,
1256 				&mindata, &maxwait, &poll) < 0) {
1257 		pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
1258 		    errno, "dag_get_stream_poll");
1259 		return -1;
1260 	}
1261 
1262 	/* Amount of data to collect in Bytes before calling callbacks.
1263 	 * Important for efficiency, but can introduce latency
1264 	 * at low packet rates if to_ms not set!
1265 	 */
1266 	if(nonblock)
1267 		mindata = 0;
1268 	else
1269 		mindata = 65536;
1270 
1271 	if (dag_set_stream_poll64(p->fd, pd->dag_stream,
1272 				mindata, &maxwait, &poll) < 0) {
1273 		pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
1274 		    errno, "dag_set_stream_poll");
1275 		return -1;
1276 	}
1277 
1278 	if (nonblock) {
1279 		pd->dag_flags |= DAGF_NONBLOCK;
1280 	} else {
1281 		pd->dag_flags &= ~DAGF_NONBLOCK;
1282 	}
1283 	return (0);
1284 }
1285 
1286 static int
1287 dag_get_datalink(pcap_t *p)
1288 {
1289 	struct pcap_dag *pd = p->priv;
1290 	int index=0, dlt_index=0;
1291 	uint8_t types[255];
1292 
1293 	memset(types, 0, 255);
1294 
1295 	if (p->dlt_list == NULL && (p->dlt_list = malloc(255*sizeof(*(p->dlt_list)))) == NULL) {
1296 		pcap_fmt_errmsg_for_errno(p->errbuf, sizeof(p->errbuf),
1297 		    errno, "malloc");
1298 		return (-1);
1299 	}
1300 
1301 	p->linktype = 0;
1302 
1303 #ifdef HAVE_DAG_GET_STREAM_ERF_TYPES
1304 	/* Get list of possible ERF types for this card */
1305 	if (dag_get_stream_erf_types(p->fd, pd->dag_stream, types, 255) < 0) {
1306 		pcap_fmt_errmsg_for_errno(p->errbuf, sizeof(p->errbuf),
1307 		    errno, "dag_get_stream_erf_types");
1308 		return (-1);
1309 	}
1310 
1311 	while (types[index]) {
1312 
1313 #elif defined HAVE_DAG_GET_ERF_TYPES
1314 	/* Get list of possible ERF types for this card */
1315 	if (dag_get_erf_types(p->fd, types, 255) < 0) {
1316 		pcap_fmt_errmsg_for_errno(p->errbuf, sizeof(p->errbuf),
1317 		    errno, "dag_get_erf_types");
1318 		return (-1);
1319 	}
1320 
1321 	while (types[index]) {
1322 #else
1323 	/* Check the type through a dagapi call. */
1324 	types[index] = dag_linktype(p->fd);
1325 
1326 	{
1327 #endif
1328 		switch((types[index] & 0x7f)) {
1329 
1330 		case ERF_TYPE_HDLC_POS:
1331 		case ERF_TYPE_COLOR_HDLC_POS:
1332 		case ERF_TYPE_DSM_COLOR_HDLC_POS:
1333 		case ERF_TYPE_COLOR_HASH_POS:
1334 
1335 			if (p->dlt_list != NULL) {
1336 				p->dlt_list[dlt_index++] = DLT_CHDLC;
1337 				p->dlt_list[dlt_index++] = DLT_PPP_SERIAL;
1338 				p->dlt_list[dlt_index++] = DLT_FRELAY;
1339 			}
1340 			if(!p->linktype)
1341 				p->linktype = DLT_CHDLC;
1342 			break;
1343 
1344 		case ERF_TYPE_ETH:
1345 		case ERF_TYPE_COLOR_ETH:
1346 		case ERF_TYPE_DSM_COLOR_ETH:
1347 		case ERF_TYPE_COLOR_HASH_ETH:
1348 			/*
1349 			 * This is (presumably) a real Ethernet capture; give it a
1350 			 * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
1351 			 * that an application can let you choose it, in case you're
1352 			 * capturing DOCSIS traffic that a Cisco Cable Modem
1353 			 * Termination System is putting out onto an Ethernet (it
1354 			 * doesn't put an Ethernet header onto the wire, it puts raw
1355 			 * DOCSIS frames out on the wire inside the low-level
1356 			 * Ethernet framing).
1357 			 */
1358 			if (p->dlt_list != NULL) {
1359 				p->dlt_list[dlt_index++] = DLT_EN10MB;
1360 				p->dlt_list[dlt_index++] = DLT_DOCSIS;
1361 			}
1362 			if(!p->linktype)
1363 				p->linktype = DLT_EN10MB;
1364 			break;
1365 
1366 		case ERF_TYPE_ATM:
1367 		case ERF_TYPE_AAL5:
1368 		case ERF_TYPE_MC_ATM:
1369 		case ERF_TYPE_MC_AAL5:
1370 			if (p->dlt_list != NULL) {
1371 				p->dlt_list[dlt_index++] = DLT_ATM_RFC1483;
1372 				p->dlt_list[dlt_index++] = DLT_SUNATM;
1373 			}
1374 			if(!p->linktype)
1375 				p->linktype = DLT_ATM_RFC1483;
1376 			break;
1377 
1378 		case ERF_TYPE_COLOR_MC_HDLC_POS:
1379 		case ERF_TYPE_MC_HDLC:
1380 			if (p->dlt_list != NULL) {
1381 				p->dlt_list[dlt_index++] = DLT_CHDLC;
1382 				p->dlt_list[dlt_index++] = DLT_PPP_SERIAL;
1383 				p->dlt_list[dlt_index++] = DLT_FRELAY;
1384 				p->dlt_list[dlt_index++] = DLT_MTP2;
1385 				p->dlt_list[dlt_index++] = DLT_MTP2_WITH_PHDR;
1386 				p->dlt_list[dlt_index++] = DLT_LAPD;
1387 			}
1388 			if(!p->linktype)
1389 				p->linktype = DLT_CHDLC;
1390 			break;
1391 
1392 		case ERF_TYPE_IPV4:
1393 			if (p->dlt_list != NULL) {
1394 				p->dlt_list[dlt_index++] = DLT_RAW;
1395 				p->dlt_list[dlt_index++] = DLT_IPV4;
1396 			}
1397 			if(!p->linktype)
1398 				p->linktype = DLT_RAW;
1399 			break;
1400 
1401 		case ERF_TYPE_IPV6:
1402 			if (p->dlt_list != NULL) {
1403 				p->dlt_list[dlt_index++] = DLT_RAW;
1404 				p->dlt_list[dlt_index++] = DLT_IPV6;
1405 			}
1406 			if(!p->linktype)
1407 				p->linktype = DLT_RAW;
1408 			break;
1409 
1410 		case ERF_TYPE_LEGACY:
1411 		case ERF_TYPE_MC_RAW:
1412 		case ERF_TYPE_MC_RAW_CHANNEL:
1413 		case ERF_TYPE_IP_COUNTER:
1414 		case ERF_TYPE_TCP_FLOW_COUNTER:
1415 		case ERF_TYPE_INFINIBAND:
1416 		case ERF_TYPE_RAW_LINK:
1417 		case ERF_TYPE_INFINIBAND_LINK:
1418 		case ERF_TYPE_META:
1419 		default:
1420 			/* Libpcap cannot deal with these types yet */
1421 			/* Add no 'native' DLTs, but still covered by DLT_ERF */
1422 			break;
1423 
1424 		} /* switch */
1425 		index++;
1426 	}
1427 
1428 	p->dlt_list[dlt_index++] = DLT_ERF;
1429 
1430 	p->dlt_count = dlt_index;
1431 
1432 	if(!p->linktype)
1433 		p->linktype = DLT_ERF;
1434 
1435 	return p->linktype;
1436 }
1437 
1438 #ifdef DAG_ONLY
1439 /*
1440  * This libpcap build supports only DAG cards, not regular network
1441  * interfaces.
1442  */
1443 
1444 /*
1445  * There are no regular interfaces, just DAG interfaces.
1446  */
1447 int
1448 pcap_platform_finddevs(pcap_if_list_t *devlistp _U_, char *errbuf)
1449 {
1450 	return (0);
1451 }
1452 
1453 /*
1454  * Attempts to open a regular interface fail.
1455  */
1456 pcap_t *
1457 pcap_create_interface(const char *device, char *errbuf)
1458 {
1459 	pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
1460 	    "This version of libpcap only supports DAG cards");
1461 	return NULL;
1462 }
1463 
1464 /*
1465  * Libpcap version string.
1466  */
1467 const char *
1468 pcap_lib_version(void)
1469 {
1470 	return (PCAP_VERSION_STRING " (DAG-only)");
1471 }
1472 #endif
1473