xref: /freebsd/contrib/libpcap/pcap-dag.c (revision f0adf7f5cdd241db2f2c817683191a6ef64a4e95)
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  * Author: Richard Littin, Sean Irvine ({richard,sean}@reeltwo.com)
13  *
14  * Modifications:
15  *   2003 May - Jesper Peterson <support@endace.com>
16  *              Code shuffled around to suit fad-xxx.c structure
17  *              Added atexit() handler to stop DAG if application is too lazy
18  *   2003 September - Koryn Grant <koryn@endace.com>
19  *              Added support for nonblocking operation.
20  *              Added support for processing more than a single packet in pcap_dispatch().
21  *              Fixed bug in loss counter code.
22  *              Improved portability of loss counter code (e.g. use UINT_MAX instead of 0xffff).
23  *              Removed unused local variables.
24  *              Added required headers (ctype.h, limits.h, unistd.h, netinet/in.h).
25  *   2003 October - Koryn Grant <koryn@endace.com.>
26  *              Changed semantics to match those of standard pcap on linux.
27  *                - packets rejected by the filter are not counted.
28  */
29 
30 #ifndef lint
31 static const char rcsid[] _U_ =
32     "@(#) $Header: /tcpdump/master/libpcap/pcap-dag.c,v 1.10.2.4 2003/11/21 10:20:45 guy Exp $ (LBL)";
33 #endif
34 
35 #ifdef HAVE_CONFIG_H
36 #include "config.h"
37 #endif
38 
39 #include <sys/param.h>			/* optionally get BSD define */
40 
41 #include <stdlib.h>
42 #include <string.h>
43 #include <errno.h>
44 
45 #include "pcap-int.h"
46 
47 #include <ctype.h>
48 #include <netinet/in.h>
49 #include <sys/mman.h>
50 #include <sys/socket.h>
51 #include <sys/types.h>
52 #include <unistd.h>
53 
54 struct mbuf;		/* Squelch compiler warnings on some platforms for */
55 struct rtentry;		/* declarations in <net/if.h> */
56 #include <net/if.h>
57 
58 #include <dagnew.h>
59 #include <dagapi.h>
60 
61 #define MIN_DAG_SNAPLEN		12
62 #define MAX_DAG_SNAPLEN		2040
63 #define ATM_SNAPLEN		48
64 
65 typedef struct pcap_dag_node {
66   struct pcap_dag_node *next;
67   pcap_t *p;
68   pid_t pid;
69 } pcap_dag_node_t;
70 
71 static pcap_dag_node_t *pcap_dags = NULL;
72 static int atexit_handler_installed = 0;
73 static const unsigned short endian_test_word = 0x0100;
74 
75 #define IS_BIGENDIAN() (*((unsigned char *)&endian_test_word))
76 
77 /*
78  * Swap byte ordering of unsigned long long timestamp on a big endian
79  * machine.
80  */
81 #define SWAP_TS(ull)  ((ull & 0xff00000000000000LL) >> 56) | \
82                       ((ull & 0x00ff000000000000LL) >> 40) | \
83                       ((ull & 0x0000ff0000000000LL) >> 24) | \
84                       ((ull & 0x000000ff00000000LL) >> 8)  | \
85                       ((ull & 0x00000000ff000000LL) << 8)  | \
86                       ((ull & 0x0000000000ff0000LL) << 24) | \
87                       ((ull & 0x000000000000ff00LL) << 40) | \
88                       ((ull & 0x00000000000000ffLL) << 56)
89 
90 
91 #ifdef DAG_ONLY
92 /* This code is required when compiling for a DAG device only. */
93 #include "pcap-dag.h"
94 
95 /* Replace dag function names with pcap equivalent. */
96 #define dag_open_live pcap_open_live
97 #define dag_platform_finddevs pcap_platform_finddevs
98 #endif /* DAG_ONLY */
99 
100 static int dag_setfilter(pcap_t *p, struct bpf_program *fp);
101 static int dag_stats(pcap_t *p, struct pcap_stat *ps);
102 static int dag_set_datalink(pcap_t *p, int dlt);
103 static int dag_get_datalink(pcap_t *p);
104 static int dag_setnonblock(pcap_t *p, int nonblock, char *errbuf);
105 
106 static void delete_pcap_dag(pcap_t *p) {
107   pcap_dag_node_t *curr = NULL, *prev = NULL;
108 
109   for (prev = NULL, curr = pcap_dags;
110       curr != NULL && curr->p != p;
111       prev = curr, curr = curr->next) {
112     /* empty */
113   }
114 
115   if (curr != NULL && curr->p == p) {
116     if (prev != NULL) {
117       prev->next = curr->next;
118     } else {
119       pcap_dags = curr->next;
120     }
121   }
122 }
123 
124 /*
125  * Performs a graceful shutdown of the DAG card, frees dynamic memory held
126  * in the pcap_t structure, and closes the file descriptor for the DAG card.
127  */
128 
129 static void dag_platform_close(pcap_t *p) {
130 
131 #ifdef linux
132   if (p != NULL && p->md.device != NULL) {
133     if(dag_stop(p->fd) < 0)
134       fprintf(stderr,"dag_stop %s: %s\n", p->md.device, strerror(errno));
135     if(dag_close(p->fd) < 0)
136       fprintf(stderr,"dag_close %s: %s\n", p->md.device, strerror(errno));
137 
138     free(p->md.device);
139   }
140 #else
141   if (p != NULL) {
142     if(dag_stop(p->fd) < 0)
143       fprintf(stderr,"dag_stop: %s\n", strerror(errno));
144     if(dag_close(p->fd) < 0)
145       fprintf(stderr,"dag_close: %s\n", strerror(errno));
146   }
147 #endif
148   delete_pcap_dag(p);
149   /* Note: don't need to call close(p->fd) here as dag_close(p->fd) does this. */
150 }
151 
152 static void atexit_handler(void) {
153   while (pcap_dags != NULL) {
154     if (pcap_dags->pid == getpid()) {
155       dag_platform_close(pcap_dags->p);
156     } else {
157       delete_pcap_dag(pcap_dags->p);
158     }
159   }
160 }
161 
162 static int new_pcap_dag(pcap_t *p) {
163   pcap_dag_node_t *node = NULL;
164 
165   if ((node = malloc(sizeof(pcap_dag_node_t))) == NULL) {
166     return -1;
167   }
168 
169   if (!atexit_handler_installed) {
170     atexit(atexit_handler);
171     atexit_handler_installed = 1;
172   }
173 
174   node->next = pcap_dags;
175   node->p = p;
176   node->pid = getpid();
177 
178   pcap_dags = node;
179 
180   return 0;
181 }
182 
183 /*
184  *  Read at most max_packets from the capture stream and call the callback
185  *  for each of them. Returns the number of packets handled, -1 if an
186  *  error occured, or -2 if we were told to break out of the loop.
187  */
188 static int dag_read(pcap_t *p, int cnt, pcap_handler callback, u_char *user) {
189 	unsigned int processed = 0;
190 	int flags = p->md.dag_offset_flags;
191 	unsigned int nonblocking = flags & DAGF_NONBLOCK;
192 
193 	for (;;)
194 	{
195 		/* Get the next bufferful of packets (if necessary). */
196 		while (p->md.dag_mem_top - p->md.dag_mem_bottom < dag_record_size) {
197 
198 			/*
199 			 * Has "pcap_breakloop()" been called?
200 			 */
201 			if (p->break_loop) {
202 				/*
203 				 * Yes - clear the flag that indicates that
204 				 * it has, and return -2 to indicate that
205 				 * we were told to break out of the loop.
206 				 */
207 				p->break_loop = 0;
208 				return -2;
209 			}
210 
211 			p->md.dag_mem_top = dag_offset(p->fd, &(p->md.dag_mem_bottom), flags);
212 			if ((p->md.dag_mem_top - p->md.dag_mem_bottom < dag_record_size) && nonblocking)
213 			{
214 				/* Pcap is configured to process only available packets, and there aren't any. */
215 				return 0;
216 			}
217 		}
218 
219 		/* Process the packets. */
220 		while (p->md.dag_mem_top - p->md.dag_mem_bottom >= dag_record_size) {
221 
222 			unsigned short packet_len = 0;
223 			int caplen = 0;
224 			struct pcap_pkthdr	pcap_header;
225 
226 			dag_record_t *header = (dag_record_t *)(p->md.dag_mem_base + p->md.dag_mem_bottom);
227 			u_char *dp = ((u_char *)header) + dag_record_size;
228 			unsigned short rlen;
229 
230 			/*
231 			 * Has "pcap_breakloop()" been called?
232 			 */
233 			if (p->break_loop) {
234 				/*
235 				 * Yes - clear the flag that indicates that
236 				 * it has, and return -2 to indicate that
237 				 * we were told to break out of the loop.
238 				 */
239 				p->break_loop = 0;
240 				return -2;
241 			}
242 
243 			if (IS_BIGENDIAN())
244 			{
245 				rlen = header->rlen;
246 			}
247 			else
248 			{
249 				rlen = ntohs(header->rlen);
250 			}
251 			p->md.dag_mem_bottom += rlen;
252 
253 			switch(header->type) {
254 			case TYPE_ATM:
255 				packet_len = ATM_SNAPLEN;
256 				caplen = ATM_SNAPLEN;
257 				dp += 4;
258 				break;
259 
260 			case TYPE_ETH:
261 				if (IS_BIGENDIAN())
262 				{
263 					packet_len = header->wlen;
264 				}
265 				else
266 				{
267 					packet_len = ntohs(header->wlen);
268 				}
269 				packet_len -= (p->md.dag_fcs_bits >> 3);
270 				caplen = rlen - dag_record_size - 2;
271 				if (caplen > packet_len)
272 				{
273 					caplen = packet_len;
274 				}
275 				dp += 2;
276 				break;
277 
278 			case TYPE_HDLC_POS:
279 				if (IS_BIGENDIAN())
280 				{
281 					packet_len = header->wlen;
282 				}
283 				else
284 				{
285 					packet_len = ntohs(header->wlen);
286 				}
287 				packet_len -= (p->md.dag_fcs_bits >> 3);
288 				caplen = rlen - dag_record_size;
289 				if (caplen > packet_len)
290 				{
291 					caplen = packet_len;
292 				}
293 				break;
294 			}
295 
296 			if (caplen > p->snapshot)
297 				caplen = p->snapshot;
298 
299 			/* Count lost packets. */
300 			if (header->lctr) {
301 				if (p->md.stat.ps_drop > (UINT_MAX - header->lctr)) {
302 					p->md.stat.ps_drop = UINT_MAX;
303 				} else {
304 					p->md.stat.ps_drop += header->lctr;
305 				}
306 			}
307 
308 			/* Run the packet filter if there is one. */
309 			if ((p->fcode.bf_insns == NULL) || bpf_filter(p->fcode.bf_insns, dp, packet_len, caplen)) {
310 
311 				/* convert between timestamp formats */
312 				register unsigned long long ts;
313 
314 				if (IS_BIGENDIAN())
315 				{
316 					ts = SWAP_TS(header->ts);
317 				}
318 				else
319 				{
320 					ts = header->ts;
321 				}
322 
323 				pcap_header.ts.tv_sec  = ts >> 32;
324 				ts = (ts & 0xffffffffULL) * 1000000;
325 				ts += 0x80000000; /* rounding */
326 				pcap_header.ts.tv_usec = ts >> 32;
327 				if (pcap_header.ts.tv_usec >= 1000000) {
328 					pcap_header.ts.tv_usec -= 1000000;
329 					pcap_header.ts.tv_sec++;
330 				}
331 
332 				/* Fill in our own header data */
333 				pcap_header.caplen = caplen;
334 				pcap_header.len = packet_len;
335 
336 				/* Count the packet. */
337 				p->md.stat.ps_recv++;
338 
339 				/* Call the user supplied callback function */
340 				callback(user, &pcap_header, dp);
341 
342 				/* Only count packets that pass the filter, for consistency with standard Linux behaviour. */
343 				processed++;
344 				if (processed == cnt)
345 				{
346 					/* Reached the user-specified limit. */
347 					return cnt;
348 				}
349 			}
350 		}
351 
352 		if (nonblocking || processed)
353 		{
354 			return processed;
355 		}
356 	}
357 
358 	return processed;
359 }
360 
361 /*
362  *  Get a handle for a live capture from the given DAG device.  Passing a NULL
363  *  device will result in a failure.  The promisc flag is ignored because DAG
364  *  cards are always promiscuous.  The to_ms parameter is also ignored as it is
365  *  not supported in hardware.
366  *
367  *  See also pcap(3).
368  */
369 pcap_t *dag_open_live(const char *device, int snaplen, int promisc, int to_ms, char *ebuf) {
370   char conf[30]; /* dag configure string */
371   pcap_t *handle;
372   char *s;
373   int n;
374 
375   if (device == NULL) {
376     snprintf(ebuf, PCAP_ERRBUF_SIZE, "device is NULL: %s", pcap_strerror(errno));
377     return NULL;
378   }
379   /* Allocate a handle for this session. */
380 
381   handle = malloc(sizeof(*handle));
382   if (handle == NULL) {
383     snprintf(ebuf, PCAP_ERRBUF_SIZE, "malloc %s: %s", device, pcap_strerror(errno));
384     return NULL;
385   }
386 
387   /* Initialize some components of the pcap structure. */
388 
389   memset(handle, 0, sizeof(*handle));
390 
391   if (strstr(device, "/dev") == NULL) {
392     char * newDev = (char *)malloc(strlen(device) + 6);
393     newDev[0] = '\0';
394     strcat(newDev, "/dev/");
395     strcat(newDev,device);
396     device = newDev;
397   } else {
398 	device = strdup(device);
399   }
400 
401   if (device == NULL) {
402 	snprintf(ebuf, PCAP_ERRBUF_SIZE, "str_dup: %s\n", pcap_strerror(errno));
403 	goto fail;
404   }
405 
406   /* setup device parameters */
407   if((handle->fd = dag_open((char *)device)) < 0) {
408     snprintf(ebuf, PCAP_ERRBUF_SIZE, "dag_open %s: %s", device, pcap_strerror(errno));
409     goto fail;
410   }
411 
412   /* set the card snap length to the specified snaplen parameter */
413   if (snaplen == 0 || snaplen > MAX_DAG_SNAPLEN) {
414     snaplen = MAX_DAG_SNAPLEN;
415   } else if (snaplen < MIN_DAG_SNAPLEN) {
416     snaplen = MIN_DAG_SNAPLEN;
417   }
418   /* snap len has to be a multiple of 4 */
419   snprintf(conf, 30, "varlen slen=%d", (snaplen + 3) & ~3);
420 
421   fprintf(stderr, "Configuring DAG with '%s'.\n", conf);
422   if(dag_configure(handle->fd, conf) < 0) {
423     snprintf(ebuf, PCAP_ERRBUF_SIZE,"dag_configure %s: %s\n", device, pcap_strerror(errno));
424     goto fail;
425   }
426 
427   if((handle->md.dag_mem_base = dag_mmap(handle->fd)) == MAP_FAILED) {
428     snprintf(ebuf, PCAP_ERRBUF_SIZE,"dag_mmap %s: %s\n", device, pcap_strerror(errno));
429     goto fail;
430   }
431 
432   if(dag_start(handle->fd) < 0) {
433     snprintf(ebuf, PCAP_ERRBUF_SIZE, "dag_start %s: %s\n", device, pcap_strerror(errno));
434     goto fail;
435   }
436 
437   /*
438    * Important! You have to ensure bottom is properly
439    * initialized to zero on startup, it won't give you
440    * a compiler warning if you make this mistake!
441    */
442   handle->md.dag_mem_bottom = 0;
443   handle->md.dag_mem_top = 0;
444 
445   /* TODO: query the card */
446   handle->md.dag_fcs_bits = 32;
447   if ((s = getenv("ERF_FCS_BITS")) != NULL) {
448     if ((n = atoi(s)) == 0 || n == 16|| n == 32) {
449       handle->md.dag_fcs_bits = n;
450     } else {
451       snprintf(ebuf, PCAP_ERRBUF_SIZE,
452         "pcap_open_live %s: bad ERF_FCS_BITS value (%d) in environment\n", device, n);
453       goto fail;
454     }
455   }
456 
457   handle->snapshot	= snaplen;
458   /*handle->md.timeout	= to_ms; */
459 
460   if ((handle->linktype = dag_get_datalink(handle)) < 0) {
461     snprintf(ebuf, PCAP_ERRBUF_SIZE, "dag_get_linktype %s: unknown linktype\n", device);
462 	goto fail;
463   }
464 
465   handle->bufsize = 0;
466 
467   if (new_pcap_dag(handle) < 0) {
468     snprintf(ebuf, PCAP_ERRBUF_SIZE, "new_pcap_dag %s: %s\n", device, pcap_strerror(errno));
469 	goto fail;
470   }
471 
472   /*
473    * "select()" and "poll()" don't (yet) work on DAG device descriptors.
474    */
475   handle->selectable_fd = -1;
476 
477 #ifdef linux
478   handle->md.device = (char *)device;
479 #else
480   free((char *)device);
481   device = NULL;
482 #endif
483 
484   handle->read_op = dag_read;
485   handle->setfilter_op = dag_setfilter;
486   handle->set_datalink_op = dag_set_datalink;
487   handle->getnonblock_op = pcap_getnonblock_fd;
488   handle->setnonblock_op = dag_setnonblock;
489   handle->stats_op = dag_stats;
490   handle->close_op = dag_platform_close;
491 
492   return handle;
493 
494 fail:
495   if (device != NULL) {
496 	free((char *)device);
497   }
498   if (handle != NULL) {
499 	free(handle);
500   }
501 
502   return NULL;
503 }
504 
505 static int dag_stats(pcap_t *p, struct pcap_stat *ps) {
506   /* This needs to be filled out correctly.  Hopefully a dagapi call will
507      provide all necessary information.
508   */
509   /*p->md.stat.ps_recv = 0;*/
510   /*p->md.stat.ps_drop = 0;*/
511 
512   *ps = p->md.stat;
513 
514   return 0;
515 }
516 
517 /*
518  * Get from "/proc/dag" all interfaces listed there; if they're
519  * already in the list of interfaces we have, that won't add another
520  * instance, but if they're not, that'll add them.
521  *
522  * We don't bother getting any addresses for them.
523  *
524  * We also don't fail if we couldn't open "/proc/dag"; we just leave
525  * the list of interfaces as is.
526  */
527 int
528 dag_platform_finddevs(pcap_if_t **devlistp, char *errbuf)
529 {
530   FILE *proc_dag_f;
531   char linebuf[512];
532   int linenum;
533   unsigned char *p;
534   char name[512];	/* XXX - pick a size */
535   char *q;
536   int ret = 0;
537 
538   /* Quick exit if /proc/dag not readable */
539   proc_dag_f = fopen("/proc/dag", "r");
540   if (proc_dag_f == NULL)
541   {
542     int i;
543     char dev[16] = "dagx";
544 
545     for (i = '0'; ret == 0 && i <= '9'; i++) {
546       dev[3] = i;
547       if (pcap_add_if(devlistp, dev, 0, NULL, errbuf) == -1) {
548         /*
549          * Failure.
550          */
551         ret = -1;
552       }
553     }
554 
555     return (ret);
556   }
557 
558   for (linenum = 1;
559         fgets(linebuf, sizeof linebuf, proc_dag_f) != NULL; linenum++) {
560 
561     /*
562      * Skip the first two lines - they're headers.
563      */
564     if (linenum <= 2)
565       continue;
566 
567     p = &linebuf[0];
568 
569     if (*p == '\0' || *p == '\n' || *p != 'D')
570       continue;  /* not a Dag line */
571 
572     /*
573      * Get the interface name.
574      */
575     q = &name[0];
576     while (*p != '\0' && *p != ':') {
577       if (*p != ' ')
578         *q++ = tolower(*p++);
579       else
580         p++;
581     }
582     *q = '\0';
583 
584     /*
585      * Add an entry for this interface, with no addresses.
586      */
587     p[strlen(p) - 1] = '\0'; /* get rid of \n */
588     if (pcap_add_if(devlistp, name, 0, strdup(p + 2), errbuf) == -1) {
589       /*
590        * Failure.
591        */
592       ret = -1;
593       break;
594     }
595   }
596   if (ret != -1) {
597     /*
598      * Well, we didn't fail for any other reason; did we
599      * fail due to an error reading the file?
600      */
601     if (ferror(proc_dag_f)) {
602       (void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
603           "Error reading /proc/dag: %s",
604           pcap_strerror(errno));
605       ret = -1;
606     }
607   }
608 
609   (void)fclose(proc_dag_f);
610   return (ret);
611 }
612 
613 /*
614  * Installs the given bpf filter program in the given pcap structure.  There is
615  * no attempt to store the filter in kernel memory as that is not supported
616  * with DAG cards.
617  */
618 static int dag_setfilter(pcap_t *p, struct bpf_program *fp) {
619   if (!p)
620     return -1;
621   if (!fp) {
622     strncpy(p->errbuf, "setfilter: No filter specified",
623 	    sizeof(p->errbuf));
624     return -1;
625   }
626 
627   /* Make our private copy of the filter */
628 
629   if (install_bpf_program(p, fp) < 0) {
630     snprintf(p->errbuf, sizeof(p->errbuf),
631 	     "malloc: %s", pcap_strerror(errno));
632     return -1;
633   }
634 
635   p->md.use_bpf = 0;
636 
637   return (0);
638 }
639 
640 static int
641 dag_set_datalink(pcap_t *p, int dlt)
642 {
643 	return (0);
644 }
645 
646 static int
647 dag_setnonblock(pcap_t *p, int nonblock, char *errbuf)
648 {
649 	/*
650 	 * Set non-blocking mode on the FD.
651 	 * XXX - is that necessary?  If not, don't bother calling it,
652 	 * and have a "dag_getnonblock()" function that looks at
653 	 * "p->md.dag_offset_flags".
654 	 */
655 	if (pcap_setnonblock_fd(p, nonblock, errbuf) < 0)
656 		return (-1);
657 
658 	if (nonblock) {
659 		p->md.dag_offset_flags |= DAGF_NONBLOCK;
660 	} else {
661 		p->md.dag_offset_flags &= ~DAGF_NONBLOCK;
662 	}
663 	return (0);
664 }
665 
666 static int
667 dag_get_datalink(pcap_t *p)
668 {
669   int linktype = -1;
670 
671   /* Check the type through a dagapi call.
672   */
673   switch(dag_linktype(p->fd)) {
674   case TYPE_HDLC_POS: {
675       dag_record_t *record;
676 
677       /* peek at the first available record to see if it is PPP */
678       while ((p->md.dag_mem_top - p->md.dag_mem_bottom) < (dag_record_size + 4)) {
679         p->md.dag_mem_top = dag_offset(p->fd, &(p->md.dag_mem_bottom), 0);
680       }
681       record = (dag_record_t *)(p->md.dag_mem_base + p->md.dag_mem_bottom);
682 
683       if ((ntohl(record->rec.pos.hdlc) & 0xffff0000) == 0xff030000) {
684         linktype = DLT_PPP_SERIAL;
685         fprintf(stderr, "Set DAG linktype to %d (DLT_PPP_SERIAL)\n", linktype);
686       } else {
687         linktype = DLT_CHDLC;
688         fprintf(stderr, "Set DAG linktype to %d (DLT_CHDLC)\n", linktype);
689       }
690       break;
691     }
692   case TYPE_ETH:
693     linktype = DLT_EN10MB;
694     fprintf(stderr, "Set DAG linktype to %d (DLT_EN10MB)\n", linktype);
695     break;
696   case TYPE_ATM:
697     linktype = DLT_ATM_RFC1483;
698     fprintf(stderr, "Set DAG linktype to %d (DLT_ATM_RFC1483)\n", linktype);
699     break;
700   case TYPE_LEGACY:
701     linktype = DLT_NULL;
702     fprintf(stderr, "Set DAG linktype to %d (DLT_NULL)\n", linktype);
703     break;
704   default:
705     fprintf(stderr, "Unknown DAG linktype %d\n", dag_linktype(p->fd));
706     break;
707   }
708 
709   return linktype;
710 }
711