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