8 #if defined(HAVE_PCAP_H)
10 #elif defined(HAVE_PCAP_PCAP_H)
11 # include <pcap/pcap.h>
18 #include <sys/types.h>
19 #include <sys/ioctl.h>
20 #include <sys/socket.h>
31 #include "addr_hash.h"
37 #endif /* DLT_LINUX_SLL */
38 #include "threadprof.h"
45 #include "ethertype.h"
49 #include <netinet/ip6.h>
51 /* ethernet address of interface. */
53 unsigned char if_hw_addr[6];
55 /* IP address of interface */
57 int have_ip6_addr = 0;
58 struct in_addr if_ip_addr;
59 struct in6_addr if_ip6_addr;
61 extern options_t options;
64 history_type history_totals;
65 time_t last_timestamp;
68 pthread_mutex_t tick_mutex;
70 pcap_t* pd; /* pcap descriptor */
71 struct bpf_program pcap_filter;
72 pcap_handler packet_handler;
76 static void finish(int sig) {
83 /* Only need ethernet (plus optional 4 byte VLAN) and IP headers (48) + first 2 bytes of tcp/udp header */
84 /* Increase with a further 20 to account for IPv6 header length. */
85 #define CAPTURE_LENGTH 92
88 history = addr_hash_create();
89 last_timestamp = time(NULL);
90 memset(&history_totals, 0, sizeof history_totals);
93 history_type* history_create() {
95 h = xcalloc(1, sizeof *h);
99 void history_rotate() {
100 hash_node_type* n = NULL;
101 history_pos = (history_pos + 1) % HISTORY_LENGTH;
102 hash_next_item(history, &n);
104 hash_node_type* next = n;
105 history_type* d = (history_type*)n->rec;
106 hash_next_item(history, &next);
108 if(d->last_write == history_pos) {
109 addr_pair key = *(addr_pair*)(n->key);
110 hash_delete(history, &key);
114 d->recv[history_pos] = 0;
115 d->sent[history_pos] = 0;
120 history_totals.sent[history_pos] = 0;
121 history_totals.recv[history_pos] = 0;
123 if(history_len < HISTORY_LENGTH) {
129 void tick(int print) {
132 pthread_mutex_lock(&tick_mutex);
135 if(t - last_timestamp >= RESOLUTION) {
136 //printf("TICKING\n");
146 pthread_mutex_unlock(&tick_mutex);
149 int in_filter_net(struct in_addr addr) {
151 ret = ((addr.s_addr & options.netfiltermask.s_addr) == options.netfilternet.s_addr);
155 int __inline__ ip_addr_match(struct in_addr addr) {
156 return addr.s_addr == if_ip_addr.s_addr;
159 int __inline__ ip6_addr_match(struct in6_addr *addr) {
160 return IN6_ARE_ADDR_EQUAL(addr, &if_ip6_addr);
164 * Creates an addr_pair from an ip (and tcp/udp) header, swapping src and dst
167 void assign_addr_pair(addr_pair* ap, struct ip* iptr, int flip) {
168 unsigned short int src_port = 0;
169 unsigned short int dst_port = 0;
171 /* Arrange for predictable values. */
172 memset(ap, '\0', sizeof(*ap));
174 if(IP_V(iptr) == 4) {
176 /* Does this protocol use ports? */
177 if(iptr->ip_p == IPPROTO_TCP || iptr->ip_p == IPPROTO_UDP) {
178 /* We take a slight liberty here by treating UDP the same as TCP */
180 /* Find the TCP/UDP header */
181 struct tcphdr* thdr = ((void*)iptr) + IP_HL(iptr) * 4;
182 src_port = ntohs(thdr->th_sport);
183 dst_port = ntohs(thdr->th_dport);
187 ap->src = iptr->ip_src;
188 ap->src_port = src_port;
189 ap->dst = iptr->ip_dst;
190 ap->dst_port = dst_port;
193 ap->src = iptr->ip_dst;
194 ap->src_port = dst_port;
195 ap->dst = iptr->ip_src;
196 ap->dst_port = src_port;
199 else if (IP_V(iptr) == 6) {
200 /* IPv6 packet seen. */
201 struct ip6_hdr *ip6tr = (struct ip6_hdr *) iptr;
205 if( (ip6tr->ip6_nxt == IPPROTO_TCP) || (ip6tr->ip6_nxt == IPPROTO_UDP) ) {
206 struct tcphdr *thdr = ((void *) ip6tr) + 40;
208 src_port = ntohs(thdr->th_sport);
209 dst_port = ntohs(thdr->th_dport);
213 memcpy(&ap->src6, &ip6tr->ip6_src, sizeof(ap->src6));
214 ap->src_port = src_port;
215 memcpy(&ap->dst6, &ip6tr->ip6_dst, sizeof(ap->dst6));
216 ap->dst_port = dst_port;
219 memcpy(&ap->src6, &ip6tr->ip6_dst, sizeof(ap->src6));
220 ap->src_port = dst_port;
221 memcpy(&ap->dst6, &ip6tr->ip6_src, sizeof(ap->dst6));
222 ap->dst_port = src_port;
227 static void handle_ip_packet(struct ip* iptr, int hw_dir)
229 int direction = 0; /* incoming */
232 history_type **ht_pp;
236 unsigned int len = 0;
237 struct in6_addr scribdst; /* Scratch pad. */
238 struct in6_addr scribsrc; /* Scratch pad. */
239 /* Reinterpret packet type. */
240 struct ip6_hdr* ip6tr = (struct ip6_hdr *) iptr;
242 memset(&ap, '\0', sizeof(ap));
244 if( (IP_V(iptr) ==4 && options.netfilter == 0)
245 || (IP_V(iptr) == 6 && options.netfilter6 == 0) ) {
247 * Net filter is off, so assign direction based on MAC address
250 /* Packet leaving this interface. */
251 assign_addr_pair(&ap, iptr, 0);
254 else if(hw_dir == 0) {
255 /* Packet incoming */
256 assign_addr_pair(&ap, iptr, 1);
259 /* Packet direction is not given away by h/ware layer. Try IP
262 else if((IP_V(iptr) == 4) && have_ip_addr && ip_addr_match(iptr->ip_src)) {
264 assign_addr_pair(&ap, iptr, 0);
267 else if((IP_V(iptr) == 4) && have_ip_addr && ip_addr_match(iptr->ip_dst)) {
269 assign_addr_pair(&ap, iptr, 1);
272 else if((IP_V(iptr) == 6) && have_ip6_addr && ip6_addr_match(&ip6tr->ip6_src)) {
274 assign_addr_pair(&ap, iptr, 0);
277 else if((IP_V(iptr) == 6) && have_ip6_addr && ip6_addr_match(&ip6tr->ip6_dst)) {
279 assign_addr_pair(&ap, iptr, 1);
283 * Cannot determine direction from hardware or IP levels. Therefore
284 * assume that it was a packet between two other machines, assign
285 * source and dest arbitrarily (by numerical value) and account as
288 else if (options.promiscuous_but_choosy) {
289 return; /* junk it */
291 else if((IP_V(iptr) == 4) && (iptr->ip_src.s_addr < iptr->ip_dst.s_addr)) {
292 assign_addr_pair(&ap, iptr, 1);
295 else if(IP_V(iptr) == 4) {
296 assign_addr_pair(&ap, iptr, 0);
299 /* Drop other uncertain packages. */
302 if(IP_V(iptr) == 4 && options.netfilter != 0) {
304 * Net filter on, assign direction according to netmask
306 if(in_filter_net(iptr->ip_src) && !in_filter_net(iptr->ip_dst)) {
308 assign_addr_pair(&ap, iptr, 0);
311 else if(in_filter_net(iptr->ip_dst) && !in_filter_net(iptr->ip_src)) {
313 assign_addr_pair(&ap, iptr, 1);
322 if(IP_V(iptr) == 6 && options.netfilter6 != 0) {
324 * Net filter IPv6 active.
327 //else if((IP_V(iptr) == 6) && have_ip6_addr && ip6_addr_match(&ip6tr->ip6_dst)) {
328 /* First reduce the participating addresses using the netfilter prefix.
329 * We need scratch pads to do this.
331 for (j=0; j < 4; ++j) {
332 scribdst.s6_addr32[j] = ip6tr->ip6_dst.s6_addr32[j]
333 & options.netfilter6mask.s6_addr32[j];
334 scribsrc.s6_addr32[j] = ip6tr->ip6_src.s6_addr32[j]
335 & options.netfilter6mask.s6_addr32[j];
338 /* Now look for any hits. */
339 //if(in_filter_net(iptr->ip_src) && !in_filter_net(iptr->ip_dst)) {
340 if (IN6_ARE_ADDR_EQUAL(&scribsrc, &options.netfilter6net)
341 && ! IN6_ARE_ADDR_EQUAL(&scribdst, &options.netfilter6net)) {
343 assign_addr_pair(&ap, iptr, 0);
346 //else if(in_filter_net(iptr->ip_dst) && !in_filter_net(iptr->ip_src)) {
347 else if (! IN6_ARE_ADDR_EQUAL(&scribsrc, &options.netfilter6net)
348 && IN6_ARE_ADDR_EQUAL(&scribdst, &options.netfilter6net)) {
350 assign_addr_pair(&ap, iptr, 1);
360 /* Test if link-local IPv6 packets should be dropped. */
361 if( IP_V(iptr) == 6 && !options.link_local
362 && (IN6_IS_ADDR_LINKLOCAL(&ip6tr->ip6_dst)
363 || IN6_IS_ADDR_LINKLOCAL(&ip6tr->ip6_src)) )
367 /* Do address resolving. */
368 switch (IP_V(iptr)) {
370 ap.protocol = iptr->ip_p;
371 /* Add the addresses to be resolved */
372 /* The IPv4 address is embedded in a in6_addr structure,
373 * so it need be copied, and delivered to resolve(). */
374 memset(&scribdst, '\0', sizeof(scribdst));
375 memcpy(&scribdst, &iptr->ip_dst, sizeof(struct in_addr));
376 resolve(ap.af, &scribdst, NULL, 0);
377 memset(&scribsrc, '\0', sizeof(scribsrc));
378 memcpy(&scribsrc, &iptr->ip_src, sizeof(struct in_addr));
379 resolve(ap.af, &scribsrc, NULL, 0);
382 ap.protocol = ip6tr->ip6_nxt;
383 /* Add the addresses to be resolved */
384 resolve(ap.af, &ip6tr->ip6_dst, NULL, 0);
385 resolve(ap.af, &ip6tr->ip6_src, NULL, 0);
391 if(hash_find(history, &ap, u_ht.void_pp) == HASH_STATUS_KEY_NOT_FOUND) {
392 ht = history_create();
393 hash_insert(history, &ap, ht);
397 switch (IP_V(iptr)) {
399 len = ntohs(iptr->ip_len);
402 len = ntohs(ip6tr->ip6_plen) + 40;
408 ht->last_write = history_pos;
409 if( ((IP_V(iptr) == 4) && (iptr->ip_src.s_addr == ap.src.s_addr))
410 || ((IP_V(iptr) == 6) && !memcmp(&ip6tr->ip6_src, &ap.src6, sizeof(ap.src6))) )
412 ht->sent[history_pos] += len;
413 ht->total_sent += len;
416 ht->recv[history_pos] += len;
417 ht->total_recv += len;
422 history_totals.recv[history_pos] += len;
423 history_totals.total_recv += len;
426 history_totals.sent[history_pos] += len;
427 history_totals.total_sent += len;
432 static void handle_raw_packet(unsigned char* args, const struct pcap_pkthdr* pkthdr, const unsigned char* packet)
434 handle_ip_packet((struct ip*)packet, -1);
438 static void handle_pflog_packet(unsigned char* args, const struct pcap_pkthdr* pkthdr, const unsigned char* packet)
440 register u_int length = pkthdr->len;
442 const struct pfloghdr *hdr;
444 hdr = (struct pfloghdr *)packet;
445 hdrlen = BPF_WORDALIGN(hdr->length);
448 handle_ip_packet((struct ip*)packet, length);
452 static void handle_llc_packet(const struct llc* llc, int dir) {
454 struct ip* ip = (struct ip*)((void*)llc + sizeof(struct llc));
456 /* Taken from tcpdump/print-llc.c */
457 if(llc->ssap == LLCSAP_SNAP && llc->dsap == LLCSAP_SNAP
458 && llc->llcui == LLC_UI) {
461 orgcode = EXTRACT_24BITS(&llc->llc_orgcode[0]);
462 et = EXTRACT_16BITS(&llc->llc_ethertype[0]);
464 case OUI_ENCAP_ETHER:
466 handle_ip_packet(ip, dir);
469 if(et == ETHERTYPE_ATALK) {
470 handle_ip_packet(ip, dir);
474 /* Not a lot we can do */
479 static void handle_tokenring_packet(unsigned char* args, const struct pcap_pkthdr* pkthdr, const unsigned char* packet)
481 struct token_header *trp;
483 trp = (struct token_header *)packet;
485 if(IS_SOURCE_ROUTED(trp)) {
486 packet += RIF_LENGTH(trp);
488 packet += TOKEN_HDRLEN;
490 if(memcmp(trp->token_shost, if_hw_addr, 6) == 0 ) {
491 /* packet leaving this i/f */
494 else if(memcmp(trp->token_dhost, if_hw_addr, 6) == 0 || memcmp("\xFF\xFF\xFF\xFF\xFF\xFF", trp->token_dhost, 6) == 0) {
495 /* packet entering this i/f */
499 /* Only know how to deal with LLC encapsulated packets */
500 if(FRAME_TYPE(trp) == TOKEN_FC_LLC) {
501 handle_llc_packet((struct llc*)packet, dir);
505 static void handle_ppp_packet(unsigned char* args, const struct pcap_pkthdr* pkthdr, const unsigned char* packet)
507 register u_int length = pkthdr->len;
508 register u_int caplen = pkthdr->caplen;
514 if(packet[0] == PPP_ADDRESS) {
521 proto = EXTRACT_16BITS(packet);
525 if(proto == PPP_IP || proto == ETHERTYPE_IP || proto == ETHERTYPE_IPV6) {
526 handle_ip_packet((struct ip*)packet, -1);
532 static void handle_cooked_packet(unsigned char *args, const struct pcap_pkthdr * thdr, const unsigned char * packet)
534 struct sll_header *sptr;
536 sptr = (struct sll_header *) packet;
538 switch (ntohs(sptr->sll_pkttype))
541 /*entering this interface*/
544 case LINUX_SLL_OUTGOING:
545 /*leaving this interface */
549 handle_ip_packet((struct ip*)(packet+SLL_HDR_LEN), dir);
551 #endif /* DLT_LINUX_SLL */
553 static void handle_eth_packet(unsigned char* args, const struct pcap_pkthdr* pkthdr, const unsigned char* packet)
555 struct ether_header *eptr;
557 const unsigned char *payload;
558 eptr = (struct ether_header*)packet;
559 ether_type = ntohs(eptr->ether_type);
560 payload = packet + sizeof(struct ether_header);
564 if(ether_type == ETHERTYPE_8021Q) {
565 struct vlan_8021q_header* vptr;
566 vptr = (struct vlan_8021q_header*)payload;
567 ether_type = ntohs(vptr->ether_type);
568 payload += sizeof(struct vlan_8021q_header);
571 if(ether_type == ETHERTYPE_IP || ether_type == ETHERTYPE_IPV6) {
576 * Is a direction implied by the MAC addresses?
578 if(have_hw_addr && memcmp(eptr->ether_shost, if_hw_addr, 6) == 0 ) {
579 /* packet leaving this i/f */
582 else if(have_hw_addr && memcmp(eptr->ether_dhost, if_hw_addr, 6) == 0 ) {
583 /* packet entering this i/f */
586 else if (memcmp("\xFF\xFF\xFF\xFF\xFF\xFF", eptr->ether_dhost, 6) == 0) {
587 /* broadcast packet, count as incoming */
591 /* Distinguishing ip_hdr and ip6_hdr will be done later. */
592 iptr = (struct ip*)(payload); /* alignment? */
593 handle_ip_packet(iptr, dir);
599 * Install some filter code. Returns NULL on success or an error message on
601 char *set_filter_code(const char *filter) {
604 x = xmalloc(strlen(filter) + sizeof "() and (ip or ip6)");
605 sprintf(x, "(%s) and (ip or ip6)", filter);
607 x = xstrdup("ip or ip6");
608 if (pcap_compile(pd, &pcap_filter, x, 1, 0) == -1) {
610 return pcap_geterr(pd);
613 if (pcap_setfilter(pd, &pcap_filter) == -1)
614 return pcap_geterr(pd);
624 * performs pcap initialisation, called before ui is initialised
627 char errbuf[PCAP_ERRBUF_SIZE];
635 result = get_addrs_dlpi(options.interface, if_hw_addr, &if_ip_addr);
637 result = get_addrs_ioctl(options.interface, if_hw_addr,
638 &if_ip_addr, &if_ip6_addr);
645 have_hw_addr = result & 0x01;
646 have_ip_addr = result & 0x02;
647 have_ip6_addr = result & 0x04;
650 fprintf(stderr, "IP address is: %s\n", inet_ntoa(if_ip_addr));
653 char ip6str[INET6_ADDRSTRLEN];
656 inet_ntop(AF_INET6, &if_ip6_addr, ip6str, sizeof(ip6str));
657 fprintf(stderr, "IPv6 address is: %s\n", ip6str);
661 fprintf(stderr, "MAC address is:");
662 for (i = 0; i < 6; ++i)
663 fprintf(stderr, "%c%02x", i ? ':' : ' ', (unsigned int)if_hw_addr[i]);
664 fprintf(stderr, "\n");
668 resolver_initialise();
670 pd = pcap_open_live(options.interface, CAPTURE_LENGTH, options.promiscuous, 1000, errbuf);
671 // DEBUG: pd = pcap_open_offline("tcpdump.out", errbuf);
673 fprintf(stderr, "pcap_open_live(%s): %s\n", options.interface, errbuf);
676 dlt = pcap_datalink(pd);
677 if(dlt == DLT_EN10MB) {
678 packet_handler = handle_eth_packet;
681 else if (dlt == DLT_PFLOG) {
682 packet_handler = handle_pflog_packet;
685 else if(dlt == DLT_RAW || dlt == DLT_NULL) {
686 packet_handler = handle_raw_packet;
688 else if(dlt == DLT_IEEE802) {
689 packet_handler = handle_tokenring_packet;
691 else if(dlt == DLT_PPP) {
692 packet_handler = handle_ppp_packet;
695 * SLL support not available in older libpcaps
698 else if(dlt == DLT_LINUX_SLL) {
699 packet_handler = handle_cooked_packet;
703 fprintf(stderr, "Unsupported datalink type: %d\n"
704 "Please email pdw@ex-parrot.com, quoting the datalink type and what you were\n"
705 "trying to do at the time\n.", dlt);
709 if ((m = set_filter_code(options.filtercode))) {
710 fprintf(stderr, "set_filter_code: %s\n", m);
717 * Worker function for packet capture thread. */
718 void packet_loop(void* ptr) {
719 pcap_loop(pd,-1,(pcap_handler)packet_handler,NULL);
724 * Entry point. See usage(). */
725 int main(int argc, char **argv) {
727 struct sigaction sa = {};
729 /* TODO: tidy this up */
730 /* read command line options and config file */
732 options_set_defaults();
733 options_read_args(argc, argv);
734 /* If a config was explicitly specified, whinge if it can't be found */
735 read_config(options.config_file, options.config_file_specified);
738 sa.sa_handler = finish;
739 sigaction(SIGINT, &sa, NULL);
741 pthread_mutex_init(&tick_mutex, NULL);
749 pthread_create(&thread, NULL, (void*)&packet_loop, NULL);
753 pthread_cancel(thread);