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