11 #include <sys/types.h>
12 #include <sys/ioctl.h>
13 #include <sys/socket.h>
15 /* include <net/bpf.h> -- this was added by the PFLOG patch but seems
16 * superfluous and breaks on Slackware */
17 #if defined(HAVE_PCAP_H)
19 #elif defined(HAVE_PCAP_PCAP_H)
20 # include <pcap/pcap.h>
33 #include "addr_hash.h"
35 #include "ui_common.h"
41 #endif /* DLT_LINUX_SLL */
42 #include "threadprof.h"
49 #include "ethertype.h"
52 #include "addrs_ioctl.h"
54 #include <netinet/ip6.h>
56 /* ethernet address of interface. */
60 /* IP address of interface */
62 int have_ip6_addr = 0;
63 struct in_addr if_ip_addr;
64 struct in6_addr if_ip6_addr;
66 extern options_t options;
69 history_type history_totals;
70 time_t last_timestamp;
71 time_t first_timestamp;
74 pthread_mutex_t tick_mutex;
76 pcap_t* pd; /* pcap descriptor */
77 struct bpf_program pcap_filter;
78 pcap_handler packet_handler;
82 static void finish(int sig) {
89 /* Only need ethernet (plus optional 4 byte VLAN) and IP headers (48) + first 2
90 * bytes of tcp/udp header */
91 /* Increase with a further 20 to account for IPv6 header length. */
92 /* IEEE 802.11 radiotap throws in a variable length header plus 8 (radiotap
93 * header header) plus 34 (802.11 MAC) plus 40 (IPv6) = 78, plus whatever's in
94 * the radiotap payload */
95 /*#define CAPTURE_LENGTH 92 */
96 #define CAPTURE_LENGTH 256
99 history = addr_hash_create();
100 last_timestamp = time(NULL);
101 memset(&history_totals, 0, sizeof history_totals);
104 history_type* history_create() {
106 h = xcalloc(1, sizeof *h);
110 void history_rotate() {
111 hash_node_type* n = NULL;
112 history_pos = (history_pos + 1) % HISTORY_LENGTH;
113 hash_next_item(history, &n);
115 hash_node_type* next = n;
116 history_type* d = (history_type*)n->rec;
117 hash_next_item(history, &next);
119 if(d->last_write == history_pos) {
120 addr_pair key = *(addr_pair*)(n->key);
121 hash_delete(history, &key);
125 d->recv[history_pos] = 0;
126 d->sent[history_pos] = 0;
131 history_totals.sent[history_pos] = 0;
132 history_totals.recv[history_pos] = 0;
134 if(history_len < HISTORY_LENGTH) {
140 void tick(int print) {
143 pthread_mutex_lock(&tick_mutex);
146 if(t - last_timestamp >= RESOLUTION) {
148 if (options.no_curses) {
149 if (!options.timed_output || (options.timed_output && t - first_timestamp >= options.timed_output)) {
151 if (options.timed_output) {
163 if (options.no_curses) {
171 pthread_mutex_unlock(&tick_mutex);
174 int in_filter_net(struct in_addr addr) {
176 ret = ((addr.s_addr & options.netfiltermask.s_addr) == options.netfilternet.s_addr);
180 static int __inline__ ip_addr_match(struct in_addr addr) {
181 return addr.s_addr == if_ip_addr.s_addr;
184 static int __inline__ ip6_addr_match(struct in6_addr *addr) {
185 return IN6_ARE_ADDR_EQUAL(addr, &if_ip6_addr);
189 * Creates an addr_pair from an ip (and tcp/udp) header, swapping src and dst
192 void assign_addr_pair(addr_pair* ap, struct ip* iptr, int flip) {
193 unsigned short int src_port = 0;
194 unsigned short int dst_port = 0;
196 /* Arrange for predictable values. */
197 memset(ap, '\0', sizeof(*ap));
199 if(IP_V(iptr) == 4) {
201 /* Does this protocol use ports? */
202 if(iptr->ip_p == IPPROTO_TCP || iptr->ip_p == IPPROTO_UDP) {
203 /* We take a slight liberty here by treating UDP the same as TCP */
205 /* Find the TCP/UDP header */
206 struct tcphdr* thdr = ((void*)iptr) + IP_HL(iptr) * 4;
207 src_port = ntohs(thdr->th_sport);
208 dst_port = ntohs(thdr->th_dport);
212 ap->src = iptr->ip_src;
213 ap->src_port = src_port;
214 ap->dst = iptr->ip_dst;
215 ap->dst_port = dst_port;
218 ap->src = iptr->ip_dst;
219 ap->src_port = dst_port;
220 ap->dst = iptr->ip_src;
221 ap->dst_port = src_port;
224 else if (IP_V(iptr) == 6) {
225 /* IPv6 packet seen. */
226 struct ip6_hdr *ip6tr = (struct ip6_hdr *) iptr;
230 if( (ip6tr->ip6_nxt == IPPROTO_TCP) || (ip6tr->ip6_nxt == IPPROTO_UDP) ) {
231 struct tcphdr *thdr = ((void *) ip6tr) + 40;
233 src_port = ntohs(thdr->th_sport);
234 dst_port = ntohs(thdr->th_dport);
238 memcpy(&ap->src6, &ip6tr->ip6_src, sizeof(ap->src6));
239 ap->src_port = src_port;
240 memcpy(&ap->dst6, &ip6tr->ip6_dst, sizeof(ap->dst6));
241 ap->dst_port = dst_port;
244 memcpy(&ap->src6, &ip6tr->ip6_dst, sizeof(ap->src6));
245 ap->src_port = dst_port;
246 memcpy(&ap->dst6, &ip6tr->ip6_src, sizeof(ap->dst6));
247 ap->dst_port = src_port;
252 static void handle_ip_packet(struct ip* iptr, int hw_dir)
254 int direction = 0; /* incoming */
257 history_type **ht_pp;
261 unsigned int len = 0;
262 struct in6_addr scribdst; /* Scratch pad. */
263 struct in6_addr scribsrc; /* Scratch pad. */
264 /* Reinterpret packet type. */
265 struct ip6_hdr* ip6tr = (struct ip6_hdr *) iptr;
267 memset(&ap, '\0', sizeof(ap));
271 if( (IP_V(iptr) ==4 && options.netfilter == 0)
272 || (IP_V(iptr) == 6 && options.netfilter6 == 0) ) {
274 * Net filter is off, so assign direction based on MAC address
277 /* Packet leaving this interface. */
278 assign_addr_pair(&ap, iptr, 0);
281 else if(hw_dir == 0) {
282 /* Packet incoming */
283 assign_addr_pair(&ap, iptr, 1);
286 /* Packet direction is not given away by h/ware layer. Try IP
289 else if((IP_V(iptr) == 4) && have_ip_addr && ip_addr_match(iptr->ip_src)) {
291 assign_addr_pair(&ap, iptr, 0);
294 else if((IP_V(iptr) == 4) && have_ip_addr && ip_addr_match(iptr->ip_dst)) {
296 assign_addr_pair(&ap, iptr, 1);
299 else if((IP_V(iptr) == 6) && have_ip6_addr && ip6_addr_match(&ip6tr->ip6_src)) {
301 assign_addr_pair(&ap, iptr, 0);
304 else if((IP_V(iptr) == 6) && have_ip6_addr && ip6_addr_match(&ip6tr->ip6_dst)) {
306 assign_addr_pair(&ap, iptr, 1);
309 else if (IP_V(iptr) == 4 && IN_MULTICAST(iptr->ip_dst.s_addr)) {
310 assign_addr_pair(&ap, iptr, 1);
313 else if (IP_V(iptr) == 6 && IN6_IS_ADDR_MULTICAST(&ip6tr->ip6_dst)) {
314 assign_addr_pair(&ap, iptr, 1);
318 * Cannot determine direction from hardware or IP levels. Therefore
319 * assume that it was a packet between two other machines, assign
320 * source and dest arbitrarily (by numerical value) and account as
323 else if (options.promiscuous_but_choosy) {
324 return; /* junk it */
326 else if((IP_V(iptr) == 4) && (iptr->ip_src.s_addr < iptr->ip_dst.s_addr)) {
327 assign_addr_pair(&ap, iptr, 1);
330 else if(IP_V(iptr) == 4) {
331 assign_addr_pair(&ap, iptr, 0);
334 /* Drop other uncertain packages. */
339 if(IP_V(iptr) == 4 && options.netfilter != 0) {
341 * Net filter on, assign direction according to netmask
343 if(in_filter_net(iptr->ip_src) && !in_filter_net(iptr->ip_dst)) {
345 assign_addr_pair(&ap, iptr, 0);
348 else if(in_filter_net(iptr->ip_dst) && !in_filter_net(iptr->ip_src)) {
350 assign_addr_pair(&ap, iptr, 1);
359 if(IP_V(iptr) == 6 && options.netfilter6 != 0) {
361 * Net filter IPv6 active.
364 //else if((IP_V(iptr) == 6) && have_ip6_addr && ip6_addr_match(&ip6tr->ip6_dst)) {
365 /* First reduce the participating addresses using the netfilter prefix.
366 * We need scratch pads to do this.
368 for (j=0; j < 16; ++j) {
369 scribdst.s6_addr[j] = ip6tr->ip6_dst.s6_addr[j]
370 & options.netfilter6mask.s6_addr[j];
371 scribsrc.s6_addr[j] = ip6tr->ip6_src.s6_addr[j]
372 & options.netfilter6mask.s6_addr[j];
375 /* Now look for any hits. */
376 //if(in_filter_net(iptr->ip_src) && !in_filter_net(iptr->ip_dst)) {
377 if (IN6_ARE_ADDR_EQUAL(&scribsrc, &options.netfilter6net)
378 && ! IN6_ARE_ADDR_EQUAL(&scribdst, &options.netfilter6net)) {
380 assign_addr_pair(&ap, iptr, 0);
383 //else if(in_filter_net(iptr->ip_dst) && !in_filter_net(iptr->ip_src)) {
384 else if (! IN6_ARE_ADDR_EQUAL(&scribsrc, &options.netfilter6net)
385 && IN6_ARE_ADDR_EQUAL(&scribdst, &options.netfilter6net)) {
387 assign_addr_pair(&ap, iptr, 1);
397 /* Test if link-local IPv6 packets should be dropped. */
398 if( IP_V(iptr) == 6 && !options.link_local
399 && (IN6_IS_ADDR_LINKLOCAL(&ip6tr->ip6_dst)
400 || IN6_IS_ADDR_LINKLOCAL(&ip6tr->ip6_src)) )
404 /* Do address resolving. */
405 switch (IP_V(iptr)) {
407 ap.protocol = iptr->ip_p;
408 /* Add the addresses to be resolved */
409 /* The IPv4 address is embedded in a in6_addr structure,
410 * so it need be copied, and delivered to resolve(). */
411 memset(&scribdst, '\0', sizeof(scribdst));
412 memcpy(&scribdst, &iptr->ip_dst, sizeof(struct in_addr));
413 resolve(ap.af, &scribdst, NULL, 0);
414 memset(&scribsrc, '\0', sizeof(scribsrc));
415 memcpy(&scribsrc, &iptr->ip_src, sizeof(struct in_addr));
416 resolve(ap.af, &scribsrc, NULL, 0);
419 ap.protocol = ip6tr->ip6_nxt;
420 /* Add the addresses to be resolved */
421 resolve(ap.af, &ip6tr->ip6_dst, NULL, 0);
422 resolve(ap.af, &ip6tr->ip6_src, NULL, 0);
428 if(hash_find(history, &ap, u_ht.void_pp) == HASH_STATUS_KEY_NOT_FOUND) {
429 ht = history_create();
430 hash_insert(history, &ap, ht);
434 switch (IP_V(iptr)) {
436 len = ntohs(iptr->ip_len);
439 len = ntohs(ip6tr->ip6_plen) + 40;
445 ht->last_write = history_pos;
446 if( ((IP_V(iptr) == 4) && (iptr->ip_src.s_addr == ap.src.s_addr))
447 || ((IP_V(iptr) == 6) && !memcmp(&ip6tr->ip6_src, &ap.src6, sizeof(ap.src6))) )
449 ht->sent[history_pos] += len;
450 ht->total_sent += len;
453 ht->recv[history_pos] += len;
454 ht->total_recv += len;
459 history_totals.recv[history_pos] += len;
460 history_totals.total_recv += len;
463 history_totals.sent[history_pos] += len;
464 history_totals.total_sent += len;
469 static void handle_raw_packet(unsigned char* args, const struct pcap_pkthdr* pkthdr, const unsigned char* packet)
471 handle_ip_packet((struct ip*)packet, -1);
475 static void handle_pflog_packet(unsigned char* args, const struct pcap_pkthdr* pkthdr, const unsigned char* packet)
477 register u_int length = pkthdr->len;
479 const struct pfloghdr *hdr;
481 hdr = (struct pfloghdr *)packet;
482 hdrlen = BPF_WORDALIGN(hdr->length);
485 handle_ip_packet((struct ip*)packet, -1);
489 static void handle_null_packet(unsigned char* args, const struct pcap_pkthdr* pkthdr, const unsigned char* packet)
491 handle_ip_packet((struct ip*)(packet + 4), -1);
494 static void handle_llc_packet(const struct llc* llc, int dir) {
496 struct ip* ip = (struct ip*)((void*)llc + sizeof(struct llc));
498 /* Taken from tcpdump/print-llc.c */
499 if(llc->ssap == LLCSAP_SNAP && llc->dsap == LLCSAP_SNAP
500 && llc->llcui == LLC_UI) {
503 orgcode = EXTRACT_24BITS(&llc->llc_orgcode[0]);
504 et = (llc->llc_ethertype[0] << 8) + llc->llc_ethertype[1];
506 case OUI_ENCAP_ETHER:
508 handle_ip_packet(ip, dir);
511 if(et == ETHERTYPE_ATALK) {
512 handle_ip_packet(ip, dir);
516 /* Not a lot we can do */
521 static void handle_tokenring_packet(unsigned char* args, const struct pcap_pkthdr* pkthdr, const unsigned char* packet)
523 struct token_header *trp;
525 trp = (struct token_header *)packet;
527 if(IS_SOURCE_ROUTED(trp)) {
528 packet += RIF_LENGTH(trp);
530 packet += TOKEN_HDRLEN;
532 if(memcmp(trp->token_shost, if_hw_addr, 6) == 0 ) {
533 /* packet leaving this i/f */
536 else if(memcmp(trp->token_dhost, if_hw_addr, 6) == 0 || memcmp("\xFF\xFF\xFF\xFF\xFF\xFF", trp->token_dhost, 6) == 0) {
537 /* packet entering this i/f */
541 /* Only know how to deal with LLC encapsulated packets */
542 if(FRAME_TYPE(trp) == TOKEN_FC_LLC) {
543 handle_llc_packet((struct llc*)packet, dir);
547 static void handle_ppp_packet(unsigned char* args, const struct pcap_pkthdr* pkthdr, const unsigned char* packet)
549 register u_int length = pkthdr->len;
550 register u_int caplen = pkthdr->caplen;
556 if(packet[0] == PPP_ADDRESS) {
563 proto = EXTRACT_16BITS(packet);
567 if(proto == PPP_IP || proto == ETHERTYPE_IP || proto == ETHERTYPE_IPV6) {
568 handle_ip_packet((struct ip*)packet, -1);
574 static void handle_cooked_packet(unsigned char *args, const struct pcap_pkthdr * thdr, const unsigned char * packet)
576 struct sll_header *sptr;
578 sptr = (struct sll_header *) packet;
580 switch (ntohs(sptr->sll_pkttype))
583 /*entering this interface*/
586 case LINUX_SLL_OUTGOING:
587 /*leaving this interface */
591 handle_ip_packet((struct ip*)(packet+SLL_HDR_LEN), dir);
593 #endif /* DLT_LINUX_SLL */
595 static void handle_eth_packet(unsigned char* args, const struct pcap_pkthdr* pkthdr, const unsigned char* packet)
597 struct ether_header *eptr;
599 const unsigned char *payload;
600 eptr = (struct ether_header*)packet;
601 ether_type = ntohs(eptr->ether_type);
602 payload = packet + sizeof(struct ether_header);
604 if(ether_type == ETHERTYPE_8021Q) {
605 struct vlan_8021q_header* vptr;
606 vptr = (struct vlan_8021q_header*)payload;
607 ether_type = ntohs(vptr->ether_type);
608 payload += sizeof(struct vlan_8021q_header);
611 if(ether_type == ETHERTYPE_IP || ether_type == ETHERTYPE_IPV6) {
616 * Is a direction implied by the MAC addresses?
618 if(have_hw_addr && memcmp(eptr->ether_shost, if_hw_addr, 6) == 0 ) {
619 /* packet leaving this i/f */
622 else if(have_hw_addr && memcmp(eptr->ether_dhost, if_hw_addr, 6) == 0 ) {
623 /* packet entering this i/f */
626 else if (memcmp("\xFF\xFF\xFF\xFF\xFF\xFF", eptr->ether_dhost, 6) == 0) {
627 /* broadcast packet, count as incoming */
631 /* Distinguishing ip_hdr and ip6_hdr will be done later. */
632 iptr = (struct ip*)(payload); /* alignment? */
633 handle_ip_packet(iptr, dir);
637 #ifdef DLT_IEEE802_11_RADIO
639 * Packets with a bonus radiotap header.
640 * See http://www.gsp.com/cgi-bin/man.cgi?section=9&topic=ieee80211_radiotap
642 static void handle_radiotap_packet(unsigned char* args, const struct pcap_pkthdr* pkthdr, const unsigned char* packet)
644 /* 802.11 MAC header is = 34 bytes (not sure if that's universally true) */
645 /* We could try harder to figure out hardware direction from the MAC header */
646 handle_ip_packet((struct ip*)(packet + ((struct radiotap_header *)packet)->it_len + 34),-1);
653 * Install some filter code. Returns NULL on success or an error message on
655 char *set_filter_code(const char *filter) {
658 x = xmalloc(strlen(filter) + sizeof "() and (ip or ip6)");
659 sprintf(x, "(%s) and (ip or ip6)", filter);
661 x = xstrdup("ip or ip6");
662 if (pcap_compile(pd, &pcap_filter, x, 1, 0) == -1) {
664 return pcap_geterr(pd);
667 if (pcap_setfilter(pd, &pcap_filter) == -1)
668 return pcap_geterr(pd);
678 * performs pcap initialisation, called before ui is initialised
681 char errbuf[PCAP_ERRBUF_SIZE];
688 result = get_addrs_dlpi(options.interface, if_hw_addr, &if_ip_addr);
690 result = get_addrs_ioctl(options.interface, if_hw_addr,
691 &if_ip_addr, &if_ip6_addr);
698 have_hw_addr = result & 0x01;
699 have_ip_addr = result & 0x02;
700 have_ip6_addr = result & 0x04;
703 fprintf(stderr, "IP address is: %s\n", inet_ntoa(if_ip_addr));
706 char ip6str[INET6_ADDRSTRLEN];
709 inet_ntop(AF_INET6, &if_ip6_addr, ip6str, sizeof(ip6str));
710 fprintf(stderr, "IPv6 address is: %s\n", ip6str);
714 fprintf(stderr, "MAC address is:");
715 for (i = 0; i < 6; ++i)
716 fprintf(stderr, "%c%02x", i ? ':' : ' ', (unsigned int)if_hw_addr[i]);
717 fprintf(stderr, "\n");
721 resolver_initialise();
723 pd = pcap_open_live(options.interface, CAPTURE_LENGTH, options.promiscuous, 1000, errbuf);
724 // DEBUG: pd = pcap_open_offline("tcpdump.out", errbuf);
726 fprintf(stderr, "pcap_open_live(%s): %s\n", options.interface, errbuf);
729 dlt = pcap_datalink(pd);
730 if(dlt == DLT_EN10MB) {
731 packet_handler = handle_eth_packet;
734 else if (dlt == DLT_PFLOG) {
735 packet_handler = handle_pflog_packet;
738 else if(dlt == DLT_RAW) {
739 packet_handler = handle_raw_packet;
741 else if(dlt == DLT_NULL) {
742 packet_handler = handle_null_packet;
745 else if(dlt == DLT_LOOP) {
746 packet_handler = handle_null_packet;
749 #ifdef DLT_IEEE802_11_RADIO
750 else if(dlt == DLT_IEEE802_11_RADIO) {
751 packet_handler = handle_radiotap_packet;
754 else if(dlt == DLT_IEEE802) {
755 packet_handler = handle_tokenring_packet;
757 else if(dlt == DLT_PPP) {
758 packet_handler = handle_ppp_packet;
761 * SLL support not available in older libpcaps
764 else if(dlt == DLT_LINUX_SLL) {
765 packet_handler = handle_cooked_packet;
769 fprintf(stderr, "Unsupported datalink type: %d\n"
770 "Please email pdw@ex-parrot.com, quoting the datalink type and what you were\n"
771 "trying to do at the time\n.", dlt);
775 if ((m = set_filter_code(options.filtercode))) {
776 fprintf(stderr, "set_filter_code: %s\n", m);
783 * Worker function for packet capture thread. */
784 void packet_loop(void* ptr) {
785 pcap_loop(pd,-1,(pcap_handler)packet_handler,NULL);
790 * Entry point. See usage(). */
791 int main(int argc, char **argv) {
793 struct sigaction sa = {};
795 setlocale(LC_ALL, "");
797 /* TODO: tidy this up */
798 /* read command line options and config file */
800 options_set_defaults();
801 options_read_args(argc, argv);
802 /* If a config was explicitly specified, whinge if it can't be found */
803 read_config(options.config_file, options.config_file_specified);
806 sa.sa_handler = finish;
807 sigaction(SIGINT, &sa, NULL);
809 pthread_mutex_init(&tick_mutex, NULL);
815 if (options.no_curses) {
822 pthread_create(&thread, NULL, (void*)&packet_loop, NULL);
824 /* Keep the starting time (used for timed termination) */
825 first_timestamp = time(NULL);
827 if (options.no_curses) {
828 if (options.timed_output) {
841 pthread_cancel(thread);