Imported Upstream version 1.6.1
[platform/upstream/libpcap.git] / pcap-dag.c
1 /*
2  * pcap-dag.c: Packet capture interface for Endace DAG card.
3  *
4  * The functionality of this code attempts to mimic that of pcap-linux as much
5  * as possible.  This code is compiled in several different ways depending on
6  * whether DAG_ONLY and HAVE_DAG_API are defined.  If HAVE_DAG_API is not
7  * defined it should not get compiled in, otherwise if DAG_ONLY is defined then
8  * the 'dag_' function calls are renamed to 'pcap_' equivalents.  If DAG_ONLY
9  * is not defined then nothing is altered - the dag_ functions will be
10  * called as required from their pcap-linux/bpf equivalents.
11  *
12  * Authors: Richard Littin, Sean Irvine ({richard,sean}@reeltwo.com)
13  * Modifications: Jesper Peterson  <support@endace.com>
14  *                Koryn Grant      <support@endace.com>
15  *                Stephen Donnelly <support@endace.com>
16  */
17
18 #ifdef HAVE_CONFIG_H
19 #include "config.h"
20 #endif
21
22 #include <sys/param.h>                  /* optionally get BSD define */
23
24 #include <stdlib.h>
25 #include <string.h>
26 #include <errno.h>
27
28 #include "pcap-int.h"
29
30 #include <ctype.h>
31 #include <netinet/in.h>
32 #include <sys/mman.h>
33 #include <sys/socket.h>
34 #include <sys/types.h>
35 #include <unistd.h>
36
37 struct mbuf;            /* Squelch compiler warnings on some platforms for */
38 struct rtentry;         /* declarations in <net/if.h> */
39 #include <net/if.h>
40
41 #include "dagnew.h"
42 #include "dagapi.h"
43
44 #include "pcap-dag.h"
45
46 /*
47  * DAG devices have names beginning with "dag", followed by a number
48  * from 0 to DAG_MAX_BOARDS, then optionally a colon and a stream number
49  * from 0 to DAG_STREAM_MAX.
50  */
51 #ifndef DAG_MAX_BOARDS
52 #define DAG_MAX_BOARDS 32
53 #endif
54
55 #define ATM_CELL_SIZE           52
56 #define ATM_HDR_SIZE            4
57
58 /*
59  * A header containing additional MTP information.
60  */
61 #define MTP2_SENT_OFFSET                0       /* 1 byte */
62 #define MTP2_ANNEX_A_USED_OFFSET        1       /* 1 byte */
63 #define MTP2_LINK_NUMBER_OFFSET         2       /* 2 bytes */
64 #define MTP2_HDR_LEN                    4       /* length of the header */
65
66 #define MTP2_ANNEX_A_NOT_USED      0
67 #define MTP2_ANNEX_A_USED          1
68 #define MTP2_ANNEX_A_USED_UNKNOWN  2
69
70 /* SunATM pseudo header */
71 struct sunatm_hdr {
72         unsigned char   flags;          /* destination and traffic type */
73         unsigned char   vpi;            /* VPI */
74         unsigned short  vci;            /* VCI */
75 };
76
77 /*
78  * Private data for capturing on DAG devices.
79  */
80 struct pcap_dag {
81         struct pcap_stat stat;
82 #ifdef HAVE_DAG_STREAMS_API
83         u_char  *dag_mem_bottom;        /* DAG card current memory bottom pointer */
84         u_char  *dag_mem_top;   /* DAG card current memory top pointer */
85 #else /* HAVE_DAG_STREAMS_API */
86         void    *dag_mem_base;  /* DAG card memory base address */
87         u_int   dag_mem_bottom; /* DAG card current memory bottom offset */
88         u_int   dag_mem_top;    /* DAG card current memory top offset */
89 #endif /* HAVE_DAG_STREAMS_API */
90         int     dag_fcs_bits;   /* Number of checksum bits from link layer */
91         int     dag_offset_flags; /* Flags to pass to dag_offset(). */
92         int     dag_stream;     /* DAG stream number */
93         int     dag_timeout;    /* timeout specified to pcap_open_live.
94                                  * Same as in linux above, introduce
95                                  * generally? */
96 };
97
98 typedef struct pcap_dag_node {
99         struct pcap_dag_node *next;
100         pcap_t *p;
101         pid_t pid;
102 } pcap_dag_node_t;
103
104 static pcap_dag_node_t *pcap_dags = NULL;
105 static int atexit_handler_installed = 0;
106 static const unsigned short endian_test_word = 0x0100;
107
108 #define IS_BIGENDIAN() (*((unsigned char *)&endian_test_word))
109
110 #define MAX_DAG_PACKET 65536
111
112 static unsigned char TempPkt[MAX_DAG_PACKET];
113
114 static int dag_setfilter(pcap_t *p, struct bpf_program *fp);
115 static int dag_stats(pcap_t *p, struct pcap_stat *ps);
116 static int dag_set_datalink(pcap_t *p, int dlt);
117 static int dag_get_datalink(pcap_t *p);
118 static int dag_setnonblock(pcap_t *p, int nonblock, char *errbuf);
119
120 static void
121 delete_pcap_dag(pcap_t *p)
122 {
123         pcap_dag_node_t *curr = NULL, *prev = NULL;
124
125         for (prev = NULL, curr = pcap_dags; curr != NULL && curr->p != p; prev = curr, curr = curr->next) {
126                 /* empty */
127         }
128
129         if (curr != NULL && curr->p == p) {
130                 if (prev != NULL) {
131                         prev->next = curr->next;
132                 } else {
133                         pcap_dags = curr->next;
134                 }
135         }
136 }
137
138 /*
139  * Performs a graceful shutdown of the DAG card, frees dynamic memory held
140  * in the pcap_t structure, and closes the file descriptor for the DAG card.
141  */
142
143 static void
144 dag_platform_cleanup(pcap_t *p)
145 {
146         struct pcap_dag *pd;
147
148         if (p != NULL) {
149                 pd = p->priv;
150 #ifdef HAVE_DAG_STREAMS_API
151                 if(dag_stop_stream(p->fd, pd->dag_stream) < 0)
152                         fprintf(stderr,"dag_stop_stream: %s\n", strerror(errno));
153                 
154                 if(dag_detach_stream(p->fd, pd->dag_stream) < 0)
155                         fprintf(stderr,"dag_detach_stream: %s\n", strerror(errno));
156 #else
157                 if(dag_stop(p->fd) < 0)
158                         fprintf(stderr,"dag_stop: %s\n", strerror(errno));
159 #endif /* HAVE_DAG_STREAMS_API */
160                 if(p->fd != -1) {
161                         if(dag_close(p->fd) < 0)
162                                 fprintf(stderr,"dag_close: %s\n", strerror(errno));
163                         p->fd = -1;
164                 }
165                 delete_pcap_dag(p);
166                 pcap_cleanup_live_common(p);
167         }
168         /* Note: don't need to call close(p->fd) here as dag_close(p->fd) does this. */
169 }
170
171 static void
172 atexit_handler(void)
173 {
174         while (pcap_dags != NULL) {
175                 if (pcap_dags->pid == getpid()) {
176                         dag_platform_cleanup(pcap_dags->p);
177                 } else {
178                         delete_pcap_dag(pcap_dags->p);
179                 }
180         }
181 }
182
183 static int
184 new_pcap_dag(pcap_t *p)
185 {
186         pcap_dag_node_t *node = NULL;
187
188         if ((node = malloc(sizeof(pcap_dag_node_t))) == NULL) {
189                 return -1;
190         }
191
192         if (!atexit_handler_installed) {
193                 atexit(atexit_handler);
194                 atexit_handler_installed = 1;
195         }
196
197         node->next = pcap_dags;
198         node->p = p;
199         node->pid = getpid();
200
201         pcap_dags = node;
202
203         return 0;
204 }
205
206 static unsigned int
207 dag_erf_ext_header_count(uint8_t * erf, size_t len)
208 {
209         uint32_t hdr_num = 0;
210         uint8_t  hdr_type;
211
212         /* basic sanity checks */
213         if ( erf == NULL )
214                 return 0;
215         if ( len < 16 )
216                 return 0;
217
218         /* check if we have any extension headers */
219         if ( (erf[8] & 0x80) == 0x00 )
220                 return 0;
221
222         /* loop over the extension headers */
223         do {
224         
225                 /* sanity check we have enough bytes */
226                 if ( len < (24 + (hdr_num * 8)) )
227                         return hdr_num;
228
229                 /* get the header type */
230                 hdr_type = erf[(16 + (hdr_num * 8))];
231                 hdr_num++;
232
233         } while ( hdr_type & 0x80 );
234
235         return hdr_num;
236 }
237
238 /*
239  *  Read at most max_packets from the capture stream and call the callback
240  *  for each of them. Returns the number of packets handled, -1 if an
241  *  error occured, or -2 if we were told to break out of the loop.
242  */
243 static int
244 dag_read(pcap_t *p, int cnt, pcap_handler callback, u_char *user)
245 {
246         struct pcap_dag *pd = p->priv;
247         unsigned int processed = 0;
248         int flags = pd->dag_offset_flags;
249         unsigned int nonblocking = flags & DAGF_NONBLOCK;
250         unsigned int num_ext_hdr = 0;
251
252         /* Get the next bufferful of packets (if necessary). */
253         while (pd->dag_mem_top - pd->dag_mem_bottom < dag_record_size) {
254  
255                 /*
256                  * Has "pcap_breakloop()" been called?
257                  */
258                 if (p->break_loop) {
259                         /*
260                          * Yes - clear the flag that indicates that
261                          * it has, and return -2 to indicate that
262                          * we were told to break out of the loop.
263                          */
264                         p->break_loop = 0;
265                         return -2;
266                 }
267
268 #ifdef HAVE_DAG_STREAMS_API
269                 /* dag_advance_stream() will block (unless nonblock is called)
270                  * until 64kB of data has accumulated.
271                  * If to_ms is set, it will timeout before 64kB has accumulated.
272                  * We wait for 64kB because processing a few packets at a time
273                  * can cause problems at high packet rates (>200kpps) due
274                  * to inefficiencies.
275                  * This does mean if to_ms is not specified the capture may 'hang'
276                  * for long periods if the data rate is extremely slow (<64kB/sec)
277                  * If non-block is specified it will return immediately. The user
278                  * is then responsible for efficiency.
279                  */
280                 if ( NULL == (pd->dag_mem_top = dag_advance_stream(p->fd, pd->dag_stream, &(pd->dag_mem_bottom))) ) {
281                      return -1;
282                 }
283 #else
284                 /* dag_offset does not support timeouts */
285                 pd->dag_mem_top = dag_offset(p->fd, &(pd->dag_mem_bottom), flags);
286 #endif /* HAVE_DAG_STREAMS_API */
287
288                 if (nonblocking && (pd->dag_mem_top - pd->dag_mem_bottom < dag_record_size))
289                 {
290                         /* Pcap is configured to process only available packets, and there aren't any, return immediately. */
291                         return 0;
292                 }
293                 
294                 if(!nonblocking &&
295                    pd->dag_timeout &&
296                    (pd->dag_mem_top - pd->dag_mem_bottom < dag_record_size))
297                 {
298                         /* Blocking mode, but timeout set and no data has arrived, return anyway.*/
299                         return 0;
300                 }
301
302         }
303         
304         /* Process the packets. */
305         while (pd->dag_mem_top - pd->dag_mem_bottom >= dag_record_size) {
306                 
307                 unsigned short packet_len = 0;
308                 int caplen = 0;
309                 struct pcap_pkthdr      pcap_header;
310                 
311 #ifdef HAVE_DAG_STREAMS_API
312                 dag_record_t *header = (dag_record_t *)(pd->dag_mem_bottom);
313 #else
314                 dag_record_t *header = (dag_record_t *)(pd->dag_mem_base + pd->dag_mem_bottom);
315 #endif /* HAVE_DAG_STREAMS_API */
316
317                 u_char *dp = ((u_char *)header); /* + dag_record_size; */
318                 unsigned short rlen;
319  
320                 /*
321                  * Has "pcap_breakloop()" been called?
322                  */
323                 if (p->break_loop) {
324                         /*
325                          * Yes - clear the flag that indicates that
326                          * it has, and return -2 to indicate that
327                          * we were told to break out of the loop.
328                          */
329                         p->break_loop = 0;
330                         return -2;
331                 }
332  
333                 rlen = ntohs(header->rlen);
334                 if (rlen < dag_record_size)
335                 {
336                         strncpy(p->errbuf, "dag_read: record too small", PCAP_ERRBUF_SIZE);
337                         return -1;
338                 }
339                 pd->dag_mem_bottom += rlen;
340
341                 /* Count lost packets. */
342                 switch((header->type & 0x7f)) {
343                         /* in these types the color value overwrites the lctr */
344                 case TYPE_COLOR_HDLC_POS:
345                 case TYPE_COLOR_ETH:
346                 case TYPE_DSM_COLOR_HDLC_POS:
347                 case TYPE_DSM_COLOR_ETH:
348                 case TYPE_COLOR_MC_HDLC_POS:
349                 case TYPE_COLOR_HASH_ETH:
350                 case TYPE_COLOR_HASH_POS:
351                         break;
352
353                 default:
354                         if (header->lctr) {
355                                 if (pd->stat.ps_drop > (UINT_MAX - ntohs(header->lctr))) {
356                                         pd->stat.ps_drop = UINT_MAX;
357                                 } else {
358                                         pd->stat.ps_drop += ntohs(header->lctr);
359                                 }
360                         }
361                 }
362                 
363                 if ((header->type & 0x7f) == TYPE_PAD) {
364                         continue;
365                 }
366
367                 num_ext_hdr = dag_erf_ext_header_count(dp, rlen);
368
369                 /* ERF encapsulation */
370                 /* The Extensible Record Format is not dropped for this kind of encapsulation, 
371                  * and will be handled as a pseudo header by the decoding application.
372                  * The information carried in the ERF header and in the optional subheader (if present)
373                  * could be merged with the libpcap information, to offer a better decoding.
374                  * The packet length is
375                  * o the length of the packet on the link (header->wlen),
376                  * o plus the length of the ERF header (dag_record_size), as the length of the 
377                  *   pseudo header will be adjusted during the decoding,
378                  * o plus the length of the optional subheader (if present).
379                  *
380                  * The capture length is header.rlen and the byte stuffing for alignment will be dropped
381                  * if the capture length is greater than the packet length.
382                  */
383                 if (p->linktype == DLT_ERF) {
384                         packet_len = ntohs(header->wlen) + dag_record_size;
385                         caplen = rlen;
386                         switch ((header->type & 0x7f)) {
387                         case TYPE_MC_AAL5:
388                         case TYPE_MC_ATM:
389                         case TYPE_MC_HDLC:
390                         case TYPE_MC_RAW_CHANNEL:
391                         case TYPE_MC_RAW:
392                         case TYPE_MC_AAL2:
393                         case TYPE_COLOR_MC_HDLC_POS:
394                                 packet_len += 4; /* MC header */
395                                 break;
396
397                         case TYPE_COLOR_HASH_ETH:
398                         case TYPE_DSM_COLOR_ETH:
399                         case TYPE_COLOR_ETH:
400                         case TYPE_ETH:
401                                 packet_len += 2; /* ETH header */
402                                 break;
403                         } /* switch type */
404
405                         /* Include ERF extension headers */
406                         packet_len += (8 * num_ext_hdr);
407
408                         if (caplen > packet_len) {
409                                 caplen = packet_len;
410                         }
411                 } else {
412                         /* Other kind of encapsulation according to the header Type */
413
414                         /* Skip over generic ERF header */
415                         dp += dag_record_size;
416                         /* Skip over extension headers */
417                         dp += 8 * num_ext_hdr;
418                         
419                         switch((header->type & 0x7f)) {
420                         case TYPE_ATM:
421                         case TYPE_AAL5:
422                                 if (header->type == TYPE_AAL5) {
423                                         packet_len = ntohs(header->wlen);
424                                         caplen = rlen - dag_record_size;
425                                 }
426                         case TYPE_MC_ATM:
427                                 if (header->type == TYPE_MC_ATM) {
428                                         caplen = packet_len = ATM_CELL_SIZE;
429                                         dp+=4;
430                                 }
431                         case TYPE_MC_AAL5:
432                                 if (header->type == TYPE_MC_AAL5) {
433                                         packet_len = ntohs(header->wlen);
434                                         caplen = rlen - dag_record_size - 4;
435                                         dp+=4;
436                                 }
437                                 if (header->type == TYPE_ATM) {
438                                         caplen = packet_len = ATM_CELL_SIZE;
439                                 }
440                                 if (p->linktype == DLT_SUNATM) {
441                                         struct sunatm_hdr *sunatm = (struct sunatm_hdr *)dp;
442                                         unsigned long rawatm;
443                                         
444                                         rawatm = ntohl(*((unsigned long *)dp));
445                                         sunatm->vci = htons((rawatm >>  4) & 0xffff);
446                                         sunatm->vpi = (rawatm >> 20) & 0x00ff;
447                                         sunatm->flags = ((header->flags.iface & 1) ? 0x80 : 0x00) | 
448                                                 ((sunatm->vpi == 0 && sunatm->vci == htons(5)) ? 6 :
449                                                  ((sunatm->vpi == 0 && sunatm->vci == htons(16)) ? 5 : 
450                                                   ((dp[ATM_HDR_SIZE] == 0xaa &&
451                                                     dp[ATM_HDR_SIZE+1] == 0xaa &&
452                                                     dp[ATM_HDR_SIZE+2] == 0x03) ? 2 : 1)));
453
454                                 } else {
455                                         packet_len -= ATM_HDR_SIZE;
456                                         caplen -= ATM_HDR_SIZE;
457                                         dp += ATM_HDR_SIZE;
458                                 }
459                                 break;
460
461                         case TYPE_COLOR_HASH_ETH:
462                         case TYPE_DSM_COLOR_ETH:
463                         case TYPE_COLOR_ETH:
464                         case TYPE_ETH:
465                                 packet_len = ntohs(header->wlen);
466                                 packet_len -= (pd->dag_fcs_bits >> 3);
467                                 caplen = rlen - dag_record_size - 2;
468                                 if (caplen > packet_len) {
469                                         caplen = packet_len;
470                                 }
471                                 dp += 2;
472                                 break;
473
474                         case TYPE_COLOR_HASH_POS:
475                         case TYPE_DSM_COLOR_HDLC_POS:
476                         case TYPE_COLOR_HDLC_POS:
477                         case TYPE_HDLC_POS:
478                                 packet_len = ntohs(header->wlen);
479                                 packet_len -= (pd->dag_fcs_bits >> 3);
480                                 caplen = rlen - dag_record_size;
481                                 if (caplen > packet_len) {
482                                         caplen = packet_len;
483                                 }
484                                 break;
485
486                         case TYPE_COLOR_MC_HDLC_POS:
487                         case TYPE_MC_HDLC:
488                                 packet_len = ntohs(header->wlen);
489                                 packet_len -= (pd->dag_fcs_bits >> 3);
490                                 caplen = rlen - dag_record_size - 4;
491                                 if (caplen > packet_len) {
492                                         caplen = packet_len;
493                                 }
494                                 /* jump the MC_HDLC_HEADER */
495                                 dp += 4;
496 #ifdef DLT_MTP2_WITH_PHDR
497                                 if (p->linktype == DLT_MTP2_WITH_PHDR) {
498                                         /* Add the MTP2 Pseudo Header */
499                                         caplen += MTP2_HDR_LEN;
500                                         packet_len += MTP2_HDR_LEN;
501                                         
502                                         TempPkt[MTP2_SENT_OFFSET] = 0;
503                                         TempPkt[MTP2_ANNEX_A_USED_OFFSET] = MTP2_ANNEX_A_USED_UNKNOWN;
504                                         *(TempPkt+MTP2_LINK_NUMBER_OFFSET) = ((header->rec.mc_hdlc.mc_header>>16)&0x01);
505                                         *(TempPkt+MTP2_LINK_NUMBER_OFFSET+1) = ((header->rec.mc_hdlc.mc_header>>24)&0xff);
506                                         memcpy(TempPkt+MTP2_HDR_LEN, dp, caplen);
507                                         dp = TempPkt;
508                                 }
509 #endif
510                                 break;
511
512                         case TYPE_IPV4:
513                         case TYPE_IPV6:
514                                 packet_len = ntohs(header->wlen);
515                                 caplen = rlen - dag_record_size;
516                                 if (caplen > packet_len) {
517                                         caplen = packet_len;
518                                 }
519                                 break;
520
521                         /* These types have no matching 'native' DLT, but can be used with DLT_ERF above */
522                         case TYPE_MC_RAW:
523                         case TYPE_MC_RAW_CHANNEL:
524                         case TYPE_IP_COUNTER:
525                         case TYPE_TCP_FLOW_COUNTER:
526                         case TYPE_INFINIBAND:
527                         case TYPE_RAW_LINK:
528                         case TYPE_INFINIBAND_LINK:
529                         default:
530                                 /* Unhandled ERF type.
531                                  * Ignore rather than generating error
532                                  */
533                                 continue;
534                         } /* switch type */
535
536                         /* Skip over extension headers */
537                         caplen -= (8 * num_ext_hdr);
538
539                 } /* ERF encapsulation */
540                 
541                 if (caplen > p->snapshot)
542                         caplen = p->snapshot;
543
544                 /* Run the packet filter if there is one. */
545                 if ((p->fcode.bf_insns == NULL) || bpf_filter(p->fcode.bf_insns, dp, packet_len, caplen)) {
546                         
547                         /* convert between timestamp formats */
548                         register unsigned long long ts;
549                                 
550                         if (IS_BIGENDIAN()) {
551                                 ts = SWAPLL(header->ts);
552                         } else {
553                                 ts = header->ts;
554                         }
555
556                         pcap_header.ts.tv_sec = ts >> 32;
557                         ts = (ts & 0xffffffffULL) * 1000000;
558                         ts += 0x80000000; /* rounding */
559                         pcap_header.ts.tv_usec = ts >> 32;              
560                         if (pcap_header.ts.tv_usec >= 1000000) {
561                                 pcap_header.ts.tv_usec -= 1000000;
562                                 pcap_header.ts.tv_sec++;
563                         }
564
565                         /* Fill in our own header data */
566                         pcap_header.caplen = caplen;
567                         pcap_header.len = packet_len;
568         
569                         /* Count the packet. */
570                         pd->stat.ps_recv++;
571         
572                         /* Call the user supplied callback function */
573                         callback(user, &pcap_header, dp);
574         
575                         /* Only count packets that pass the filter, for consistency with standard Linux behaviour. */
576                         processed++;
577                         if (processed == cnt && !PACKET_COUNT_IS_UNLIMITED(cnt))
578                         {
579                                 /* Reached the user-specified limit. */
580                                 return cnt;
581                         }
582                 }
583         }
584
585         return processed;
586 }
587
588 static int
589 dag_inject(pcap_t *p, const void *buf _U_, size_t size _U_)
590 {
591         strlcpy(p->errbuf, "Sending packets isn't supported on DAG cards",
592             PCAP_ERRBUF_SIZE);
593         return (-1);
594 }
595
596 /*
597  *  Get a handle for a live capture from the given DAG device.  Passing a NULL
598  *  device will result in a failure.  The promisc flag is ignored because DAG
599  *  cards are always promiscuous.  The to_ms parameter is used in setting the
600  *  API polling parameters.
601  *  
602  *  snaplen is now also ignored, until we get per-stream slen support. Set
603  *  slen with approprite DAG tool BEFORE pcap_activate().
604  *
605  *  See also pcap(3).
606  */
607 static int dag_activate(pcap_t* handle)
608 {
609         struct pcap_dag *handlep = handle->priv;
610 #if 0
611         char conf[30]; /* dag configure string */
612 #endif
613         char *s;
614         int n;
615         daginf_t* daginf;
616         char * newDev = NULL;
617         char * device = handle->opt.source;
618 #ifdef HAVE_DAG_STREAMS_API
619         uint32_t mindata;
620         struct timeval maxwait;
621         struct timeval poll;
622 #endif
623
624         if (device == NULL) {
625                 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "device is NULL: %s", pcap_strerror(errno));
626                 return -1;
627         }
628
629         /* Initialize some components of the pcap structure. */
630
631 #ifdef HAVE_DAG_STREAMS_API
632         newDev = (char *)malloc(strlen(device) + 16);
633         if (newDev == NULL) {
634                 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "Can't allocate string for device name: %s\n", pcap_strerror(errno));
635                 goto fail;
636         }
637         
638         /* Parse input name to get dag device and stream number if provided */
639         if (dag_parse_name(device, newDev, strlen(device) + 16, &handlep->dag_stream) < 0) {
640                 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "dag_parse_name: %s\n", pcap_strerror(errno));
641                 goto fail;
642         }
643         device = newDev;
644
645         if (handlep->dag_stream%2) {
646                 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "dag_parse_name: tx (even numbered) streams not supported for capture\n");
647                 goto fail;
648         }
649 #else
650         if (strncmp(device, "/dev/", 5) != 0) {
651                 newDev = (char *)malloc(strlen(device) + 5);
652                 if (newDev == NULL) {
653                         snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "Can't allocate string for device name: %s\n", pcap_strerror(errno));
654                         goto fail;
655                 }
656                 strcpy(newDev, "/dev/");
657                 strcat(newDev, device);
658                 device = newDev;
659         }
660 #endif /* HAVE_DAG_STREAMS_API */
661
662         /* setup device parameters */
663         if((handle->fd = dag_open((char *)device)) < 0) {
664                 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "dag_open %s: %s", device, pcap_strerror(errno));
665                 goto fail;
666         }
667
668 #ifdef HAVE_DAG_STREAMS_API
669         /* Open requested stream. Can fail if already locked or on error */
670         if (dag_attach_stream(handle->fd, handlep->dag_stream, 0, 0) < 0) {
671                 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "dag_attach_stream: %s\n", pcap_strerror(errno));
672                 goto failclose;
673         }
674
675         /* Set up default poll parameters for stream
676          * Can be overridden by pcap_set_nonblock()
677          */
678         if (dag_get_stream_poll(handle->fd, handlep->dag_stream,
679                                 &mindata, &maxwait, &poll) < 0) {
680                 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "dag_get_stream_poll: %s\n", pcap_strerror(errno));
681                 goto faildetach;
682         }
683         
684         if (handle->opt.immediate) {
685                 /* Call callback immediately.
686                  * XXX - is this the right way to handle this?
687                  */
688                 mindata = 0;
689         } else {
690                 /* Amount of data to collect in Bytes before calling callbacks.
691                  * Important for efficiency, but can introduce latency
692                  * at low packet rates if to_ms not set!
693                  */
694                 mindata = 65536;
695         }
696
697         /* Obey opt.timeout (was to_ms) if supplied. This is a good idea!
698          * Recommend 10-100ms. Calls will time out even if no data arrived.
699          */
700         maxwait.tv_sec = handle->opt.timeout/1000;
701         maxwait.tv_usec = (handle->opt.timeout%1000) * 1000;
702
703         if (dag_set_stream_poll(handle->fd, handlep->dag_stream,
704                                 mindata, &maxwait, &poll) < 0) {
705                 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "dag_set_stream_poll: %s\n", pcap_strerror(errno));
706                 goto faildetach;
707         }
708                 
709 #else
710         if((handlep->dag_mem_base = dag_mmap(handle->fd)) == MAP_FAILED) {
711                 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,"dag_mmap %s: %s\n", device, pcap_strerror(errno));
712                 goto failclose;
713         }
714
715 #endif /* HAVE_DAG_STREAMS_API */
716
717         /* XXX Not calling dag_configure() to set slen; this is unsafe in
718          * multi-stream environments as the gpp config is global.
719          * Once the firmware provides 'per-stream slen' this can be supported
720          * again via the Config API without side-effects */
721 #if 0
722         /* set the card snap length to the specified snaplen parameter */
723         /* This is a really bad idea, as different cards have different
724          * valid slen ranges. Should fix in Config API. */
725         if (handle->snapshot == 0 || handle->snapshot > MAX_DAG_SNAPLEN) {
726                 handle->snapshot = MAX_DAG_SNAPLEN;
727         } else if (snaplen < MIN_DAG_SNAPLEN) {
728                 handle->snapshot = MIN_DAG_SNAPLEN;
729         }
730         /* snap len has to be a multiple of 4 */
731         snprintf(conf, 30, "varlen slen=%d", (snaplen + 3) & ~3); 
732
733         if(dag_configure(handle->fd, conf) < 0) {
734                 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,"dag_configure %s: %s\n", device, pcap_strerror(errno));
735                 goto faildetach;
736         }
737 #endif  
738         
739 #ifdef HAVE_DAG_STREAMS_API
740         if(dag_start_stream(handle->fd, handlep->dag_stream) < 0) {
741                 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "dag_start_stream %s: %s\n", device, pcap_strerror(errno));
742                 goto faildetach;
743         }
744 #else
745         if(dag_start(handle->fd) < 0) {
746                 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "dag_start %s: %s\n", device, pcap_strerror(errno));
747                 goto failclose;
748         }
749 #endif /* HAVE_DAG_STREAMS_API */
750
751         /*
752          * Important! You have to ensure bottom is properly
753          * initialized to zero on startup, it won't give you
754          * a compiler warning if you make this mistake!
755          */
756         handlep->dag_mem_bottom = 0;
757         handlep->dag_mem_top = 0;
758
759         /*
760          * Find out how many FCS bits we should strip.
761          * First, query the card to see if it strips the FCS.
762          */
763         daginf = dag_info(handle->fd);
764         if ((0x4200 == daginf->device_code) || (0x4230 == daginf->device_code)) {
765                 /* DAG 4.2S and 4.23S already strip the FCS.  Stripping the final word again truncates the packet. */
766                 handlep->dag_fcs_bits = 0;
767
768                 /* Note that no FCS will be supplied. */
769                 handle->linktype_ext = LT_FCS_DATALINK_EXT(0);
770         } else {
771                 /*
772                  * Start out assuming it's 32 bits.
773                  */
774                 handlep->dag_fcs_bits = 32;
775
776                 /* Allow an environment variable to override. */
777                 if ((s = getenv("ERF_FCS_BITS")) != NULL) {
778                         if ((n = atoi(s)) == 0 || n == 16 || n == 32) {
779                                 handlep->dag_fcs_bits = n;
780                         } else {
781                                 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
782                                         "pcap_activate %s: bad ERF_FCS_BITS value (%d) in environment\n", device, n);
783                                 goto failstop;
784                         }
785                 }
786
787                 /*
788                  * Did the user request that they not be stripped?
789                  */
790                 if ((s = getenv("ERF_DONT_STRIP_FCS")) != NULL) {
791                         /* Yes.  Note the number of bytes that will be
792                            supplied. */
793                         handle->linktype_ext = LT_FCS_DATALINK_EXT(handlep->dag_fcs_bits/16);
794
795                         /* And don't strip them. */
796                         handlep->dag_fcs_bits = 0;
797                 }
798         }
799
800         handlep->dag_timeout    = handle->opt.timeout;
801
802         handle->linktype = -1;
803         if (dag_get_datalink(handle) < 0)
804                 goto failstop;
805         
806         handle->bufsize = 0;
807
808         if (new_pcap_dag(handle) < 0) {
809                 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "new_pcap_dag %s: %s\n", device, pcap_strerror(errno));
810                 goto failstop;
811         }
812
813         /*
814          * "select()" and "poll()" don't work on DAG device descriptors.
815          */
816         handle->selectable_fd = -1;
817
818         if (newDev != NULL) {
819                 free((char *)newDev);
820         }
821
822         handle->read_op = dag_read;
823         handle->inject_op = dag_inject;
824         handle->setfilter_op = dag_setfilter;
825         handle->setdirection_op = NULL; /* Not implemented.*/
826         handle->set_datalink_op = dag_set_datalink;
827         handle->getnonblock_op = pcap_getnonblock_fd;
828         handle->setnonblock_op = dag_setnonblock;
829         handle->stats_op = dag_stats;
830         handle->cleanup_op = dag_platform_cleanup;
831         handlep->stat.ps_drop = 0;
832         handlep->stat.ps_recv = 0;
833         handlep->stat.ps_ifdrop = 0;
834         return 0;
835
836 #ifdef HAVE_DAG_STREAMS_API 
837 failstop:
838         if (dag_stop_stream(handle->fd, handlep->dag_stream) < 0) {
839                 fprintf(stderr,"dag_stop_stream: %s\n", strerror(errno));
840         }
841         
842 faildetach:
843         if (dag_detach_stream(handle->fd, handlep->dag_stream) < 0)
844                 fprintf(stderr,"dag_detach_stream: %s\n", strerror(errno));
845 #else
846 failstop:
847         if (dag_stop(handle->fd) < 0)
848                 fprintf(stderr,"dag_stop: %s\n", strerror(errno));
849 #endif /* HAVE_DAG_STREAMS_API */
850         
851 failclose:
852         if (dag_close(handle->fd) < 0)
853                 fprintf(stderr,"dag_close: %s\n", strerror(errno));
854         delete_pcap_dag(handle);
855
856 fail:
857         pcap_cleanup_live_common(handle);
858         if (newDev != NULL) {
859                 free((char *)newDev);
860         }
861
862         return PCAP_ERROR;
863 }
864
865 pcap_t *dag_create(const char *device, char *ebuf, int *is_ours)
866 {
867         const char *cp;
868         char *cpend;
869         long devnum;
870         pcap_t *p;
871 #ifdef HAVE_DAG_STREAMS_API
872         long stream = 0;
873 #endif
874
875         /* Does this look like a DAG device? */
876         cp = strrchr(device, '/');
877         if (cp == NULL)
878                 cp = device;
879         /* Does it begin with "dag"? */
880         if (strncmp(cp, "dag", 3) != 0) {
881                 /* Nope, doesn't begin with "dag" */
882                 *is_ours = 0;
883                 return NULL;
884         }
885         /* Yes - is "dag" followed by a number from 0 to DAG_MAX_BOARDS-1 */
886         cp += 3;
887         devnum = strtol(cp, &cpend, 10);
888 #ifdef HAVE_DAG_STREAMS_API
889         if (*cpend == ':') {
890                 /* Followed by a stream number. */
891                 stream = strtol(++cpend, &cpend, 10);
892         }
893 #endif
894         if (cpend == cp || *cpend != '\0') {
895                 /* Not followed by a number. */
896                 *is_ours = 0;
897                 return NULL;
898         }
899         if (devnum < 0 || devnum >= DAG_MAX_BOARDS) {
900                 /* Followed by a non-valid number. */
901                 *is_ours = 0;
902                 return NULL;
903         }
904 #ifdef HAVE_DAG_STREAMS_API
905         if (stream <0 || stream >= DAG_STREAM_MAX) {
906                 /* Followed by a non-valid stream number. */
907                 *is_ours = 0;
908                 return NULL;
909         }
910 #endif
911
912         /* OK, it's probably ours. */
913         *is_ours = 1;
914
915         p = pcap_create_common(device, ebuf, sizeof (struct pcap_dag));
916         if (p == NULL)
917                 return NULL;
918
919         p->activate_op = dag_activate;
920         return p;
921 }
922
923 static int
924 dag_stats(pcap_t *p, struct pcap_stat *ps) {
925         struct pcap_dag *pd = p->priv;
926
927         /* This needs to be filled out correctly.  Hopefully a dagapi call will
928                  provide all necessary information.
929         */
930         /*pd->stat.ps_recv = 0;*/
931         /*pd->stat.ps_drop = 0;*/
932         
933         *ps = pd->stat;
934  
935         return 0;
936 }
937
938 /*
939  * Previously we just generated a list of all possible names and let
940  * pcap_add_if() attempt to open each one, but with streams this adds up
941  * to 81 possibilities which is inefficient.
942  *
943  * Since we know more about the devices we can prune the tree here.
944  * pcap_add_if() will still retest each device but the total number of
945  * open attempts will still be much less than the naive approach.
946  */
947 int
948 dag_findalldevs(pcap_if_t **devlistp, char *errbuf)
949 {
950         char name[12];  /* XXX - pick a size */
951         int ret = 0;
952         int c;
953         char dagname[DAGNAME_BUFSIZE];
954         int dagstream;
955         int dagfd;
956
957         /* Try all the DAGs 0-DAG_MAX_BOARDS */
958         for (c = 0; c < DAG_MAX_BOARDS; c++) {
959                 snprintf(name, 12, "dag%d", c);
960                 if (-1 == dag_parse_name(name, dagname, DAGNAME_BUFSIZE, &dagstream))
961                 {
962                         return -1;
963                 }
964                 if ( (dagfd = dag_open(dagname)) >= 0 ) {
965                         if (pcap_add_if(devlistp, name, 0, NULL, errbuf) == -1) {
966                                 /*
967                                  * Failure.
968                                  */
969                                 ret = -1;
970                         }
971 #ifdef HAVE_DAG_STREAMS_API
972                         {
973                                 int stream, rxstreams;
974                                 rxstreams = dag_rx_get_stream_count(dagfd);
975                                 for(stream=0;stream<DAG_STREAM_MAX;stream+=2) {
976                                         if (0 == dag_attach_stream(dagfd, stream, 0, 0)) {
977                                                 dag_detach_stream(dagfd, stream);
978
979                                                 snprintf(name,  10, "dag%d:%d", c, stream);
980                                                 if (pcap_add_if(devlistp, name, 0, NULL, errbuf) == -1) {
981                                                         /*
982                                                          * Failure.
983                                                          */
984                                                         ret = -1;
985                                                 }
986                                                 
987                                                 rxstreams--;
988                                                 if(rxstreams <= 0) {
989                                                         break;
990                                                 }
991                                         }
992                                 }                               
993                         }
994 #endif  /* HAVE_DAG_STREAMS_API */
995                         dag_close(dagfd);
996                 }
997
998         }
999         return (ret);
1000 }
1001
1002 /*
1003  * Installs the given bpf filter program in the given pcap structure.  There is
1004  * no attempt to store the filter in kernel memory as that is not supported
1005  * with DAG cards.
1006  */
1007 static int
1008 dag_setfilter(pcap_t *p, struct bpf_program *fp)
1009 {
1010         if (!p)
1011                 return -1;
1012         if (!fp) {
1013                 strncpy(p->errbuf, "setfilter: No filter specified",
1014                         sizeof(p->errbuf));
1015                 return -1;
1016         }
1017
1018         /* Make our private copy of the filter */
1019
1020         if (install_bpf_program(p, fp) < 0)
1021                 return -1;
1022
1023         return (0);
1024 }
1025
1026 static int
1027 dag_set_datalink(pcap_t *p, int dlt)
1028 {
1029         p->linktype = dlt;
1030
1031         return (0);
1032 }
1033
1034 static int
1035 dag_setnonblock(pcap_t *p, int nonblock, char *errbuf)
1036 {
1037         struct pcap_dag *pd = p->priv;
1038
1039         /*
1040          * Set non-blocking mode on the FD.
1041          * XXX - is that necessary?  If not, don't bother calling it,
1042          * and have a "dag_getnonblock()" function that looks at
1043          * "pd->dag_offset_flags".
1044          */
1045         if (pcap_setnonblock_fd(p, nonblock, errbuf) < 0)
1046                 return (-1);
1047 #ifdef HAVE_DAG_STREAMS_API
1048         {
1049                 uint32_t mindata;
1050                 struct timeval maxwait;
1051                 struct timeval poll;
1052                 
1053                 if (dag_get_stream_poll(p->fd, pd->dag_stream,
1054                                         &mindata, &maxwait, &poll) < 0) {
1055                         snprintf(errbuf, PCAP_ERRBUF_SIZE, "dag_get_stream_poll: %s\n", pcap_strerror(errno));
1056                         return -1;
1057                 }
1058                 
1059                 /* Amount of data to collect in Bytes before calling callbacks.
1060                  * Important for efficiency, but can introduce latency
1061                  * at low packet rates if to_ms not set!
1062                  */
1063                 if(nonblock)
1064                         mindata = 0;
1065                 else
1066                         mindata = 65536;
1067                 
1068                 if (dag_set_stream_poll(p->fd, pd->dag_stream,
1069                                         mindata, &maxwait, &poll) < 0) {
1070                         snprintf(errbuf, PCAP_ERRBUF_SIZE, "dag_set_stream_poll: %s\n", pcap_strerror(errno));
1071                         return -1;
1072                 }
1073         }
1074 #endif /* HAVE_DAG_STREAMS_API */
1075         if (nonblock) {
1076                 pd->dag_offset_flags |= DAGF_NONBLOCK;
1077         } else {
1078                 pd->dag_offset_flags &= ~DAGF_NONBLOCK;
1079         }
1080         return (0);
1081 }
1082                 
1083 static int
1084 dag_get_datalink(pcap_t *p)
1085 {
1086         struct pcap_dag *pd = p->priv;
1087         int index=0, dlt_index=0;
1088         uint8_t types[255];
1089
1090         memset(types, 0, 255);
1091
1092         if (p->dlt_list == NULL && (p->dlt_list = malloc(255*sizeof(*(p->dlt_list)))) == NULL) {
1093                 (void)snprintf(p->errbuf, sizeof(p->errbuf), "malloc: %s", pcap_strerror(errno));
1094                 return (-1);
1095         }
1096
1097         p->linktype = 0;
1098
1099 #ifdef HAVE_DAG_GET_STREAM_ERF_TYPES
1100         /* Get list of possible ERF types for this card */
1101         if (dag_get_stream_erf_types(p->fd, pd->dag_stream, types, 255) < 0) {
1102                 snprintf(p->errbuf, sizeof(p->errbuf), "dag_get_stream_erf_types: %s", pcap_strerror(errno));
1103                 return (-1);            
1104         }
1105         
1106         while (types[index]) {
1107
1108 #elif defined HAVE_DAG_GET_ERF_TYPES
1109         /* Get list of possible ERF types for this card */
1110         if (dag_get_erf_types(p->fd, types, 255) < 0) {
1111                 snprintf(p->errbuf, sizeof(p->errbuf), "dag_get_erf_types: %s", pcap_strerror(errno));
1112                 return (-1);            
1113         }
1114         
1115         while (types[index]) {
1116 #else
1117         /* Check the type through a dagapi call. */
1118         types[index] = dag_linktype(p->fd);
1119
1120         {
1121 #endif
1122                 switch((types[index] & 0x7f)) {
1123
1124                 case TYPE_HDLC_POS:
1125                 case TYPE_COLOR_HDLC_POS:
1126                 case TYPE_DSM_COLOR_HDLC_POS:
1127                 case TYPE_COLOR_HASH_POS:
1128
1129                         if (p->dlt_list != NULL) {
1130                                 p->dlt_list[dlt_index++] = DLT_CHDLC;
1131                                 p->dlt_list[dlt_index++] = DLT_PPP_SERIAL;
1132                                 p->dlt_list[dlt_index++] = DLT_FRELAY;
1133                         }
1134                         if(!p->linktype)
1135                                 p->linktype = DLT_CHDLC;
1136                         break;
1137
1138                 case TYPE_ETH:
1139                 case TYPE_COLOR_ETH:
1140                 case TYPE_DSM_COLOR_ETH:
1141                 case TYPE_COLOR_HASH_ETH:
1142                         /*
1143                          * This is (presumably) a real Ethernet capture; give it a
1144                          * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
1145                          * that an application can let you choose it, in case you're
1146                          * capturing DOCSIS traffic that a Cisco Cable Modem
1147                          * Termination System is putting out onto an Ethernet (it
1148                          * doesn't put an Ethernet header onto the wire, it puts raw
1149                          * DOCSIS frames out on the wire inside the low-level
1150                          * Ethernet framing).
1151                          */
1152                         if (p->dlt_list != NULL) {
1153                                 p->dlt_list[dlt_index++] = DLT_EN10MB;
1154                                 p->dlt_list[dlt_index++] = DLT_DOCSIS;
1155                         }
1156                         if(!p->linktype)
1157                                 p->linktype = DLT_EN10MB;
1158                         break;
1159
1160                 case TYPE_ATM: 
1161                 case TYPE_AAL5:
1162                 case TYPE_MC_ATM:
1163                 case TYPE_MC_AAL5:
1164                         if (p->dlt_list != NULL) {
1165                                 p->dlt_list[dlt_index++] = DLT_ATM_RFC1483;
1166                                 p->dlt_list[dlt_index++] = DLT_SUNATM;
1167                         }
1168                         if(!p->linktype)
1169                                 p->linktype = DLT_ATM_RFC1483;
1170                         break;
1171
1172                 case TYPE_COLOR_MC_HDLC_POS:
1173                 case TYPE_MC_HDLC:
1174                         if (p->dlt_list != NULL) {
1175                                 p->dlt_list[dlt_index++] = DLT_CHDLC;
1176                                 p->dlt_list[dlt_index++] = DLT_PPP_SERIAL;
1177                                 p->dlt_list[dlt_index++] = DLT_FRELAY;
1178                                 p->dlt_list[dlt_index++] = DLT_MTP2;
1179                                 p->dlt_list[dlt_index++] = DLT_MTP2_WITH_PHDR;
1180                                 p->dlt_list[dlt_index++] = DLT_LAPD;
1181                         }
1182                         if(!p->linktype)
1183                                 p->linktype = DLT_CHDLC;
1184                         break;
1185
1186                 case TYPE_IPV4:
1187                 case TYPE_IPV6:
1188                         if(!p->linktype)
1189                                 p->linktype = DLT_RAW;
1190                         break;
1191
1192                 case TYPE_LEGACY:
1193                 case TYPE_MC_RAW:
1194                 case TYPE_MC_RAW_CHANNEL:
1195                 case TYPE_IP_COUNTER:
1196                 case TYPE_TCP_FLOW_COUNTER:
1197                 case TYPE_INFINIBAND:
1198                 case TYPE_RAW_LINK:
1199                 case TYPE_INFINIBAND_LINK:
1200                 default:
1201                         /* Libpcap cannot deal with these types yet */
1202                         /* Add no 'native' DLTs, but still covered by DLT_ERF */
1203                         break;
1204
1205                 } /* switch */
1206                 index++;
1207         }
1208
1209         p->dlt_list[dlt_index++] = DLT_ERF;
1210
1211         p->dlt_count = dlt_index;
1212
1213         if(!p->linktype)
1214                 p->linktype = DLT_ERF;
1215
1216         return p->linktype;
1217 }