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;
114 history_pos = (history_pos + 1) % HISTORY_LENGTH;
115 hash_next_item(history, &n);
117 hash_node_type* next = n;
118 history_type* d = (history_type*)n->rec;
119 hash_next_item(history, &next);
121 if(d->last_write == history_pos) {
122 addr_pair key = *(addr_pair*)(n->key);
123 hash_delete(history, &key);
127 d->recv[history_pos] = 0;
128 d->sent[history_pos] = 0;
133 history_totals.sent[history_pos] = 0;
134 history_totals.recv[history_pos] = 0;
136 if(history_len < HISTORY_LENGTH) {
141 history_totals.lost_packets = ps.ps_drop + ps.ps_ifdrop;
145 void tick(int print) {
148 pthread_mutex_lock(&tick_mutex);
151 if(t - last_timestamp >= RESOLUTION) {
153 if (options.no_curses) {
154 if (!options.timed_output || (options.timed_output && t - first_timestamp >= options.timed_output)) {
156 if (options.timed_output) {
168 if (options.no_curses) {
176 pthread_mutex_unlock(&tick_mutex);
179 int in_filter_net(struct in_addr addr) {
181 ret = ((addr.s_addr & options.netfiltermask.s_addr) == options.netfilternet.s_addr);
185 static int __inline__ ip_addr_match(struct in_addr addr) {
186 return addr.s_addr == if_ip_addr.s_addr;
189 static int __inline__ ip6_addr_match(struct in6_addr *addr) {
190 return IN6_ARE_ADDR_EQUAL(addr, &if_ip6_addr);
194 * Creates an addr_pair from an ip (and tcp/udp) header, swapping src and dst
197 void assign_addr_pair(addr_pair* ap, struct ip* iptr, int flip) {
198 unsigned short int src_port = 0;
199 unsigned short int dst_port = 0;
201 /* Arrange for predictable values. */
202 memset(ap, '\0', sizeof(*ap));
204 if(IP_V(iptr) == 4) {
206 /* Does this protocol use ports? */
207 if(iptr->ip_p == IPPROTO_TCP || iptr->ip_p == IPPROTO_UDP) {
208 /* We take a slight liberty here by treating UDP the same as TCP */
210 /* Find the TCP/UDP header */
211 struct tcphdr* thdr = ((void*)iptr) + IP_HL(iptr) * 4;
212 src_port = ntohs(thdr->th_sport);
213 dst_port = ntohs(thdr->th_dport);
217 ap->src = iptr->ip_src;
218 ap->src_port = src_port;
219 ap->dst = iptr->ip_dst;
220 ap->dst_port = dst_port;
223 ap->src = iptr->ip_dst;
224 ap->src_port = dst_port;
225 ap->dst = iptr->ip_src;
226 ap->dst_port = src_port;
229 else if (IP_V(iptr) == 6) {
230 /* IPv6 packet seen. */
231 struct ip6_hdr *ip6tr = (struct ip6_hdr *) iptr;
235 if( (ip6tr->ip6_nxt == IPPROTO_TCP) || (ip6tr->ip6_nxt == IPPROTO_UDP) ) {
236 struct tcphdr *thdr = ((void *) ip6tr) + 40;
238 src_port = ntohs(thdr->th_sport);
239 dst_port = ntohs(thdr->th_dport);
243 memcpy(&ap->src6, &ip6tr->ip6_src, sizeof(ap->src6));
244 ap->src_port = src_port;
245 memcpy(&ap->dst6, &ip6tr->ip6_dst, sizeof(ap->dst6));
246 ap->dst_port = dst_port;
249 memcpy(&ap->src6, &ip6tr->ip6_dst, sizeof(ap->src6));
250 ap->src_port = dst_port;
251 memcpy(&ap->dst6, &ip6tr->ip6_src, sizeof(ap->dst6));
252 ap->dst_port = src_port;
257 static void handle_ip_packet(struct ip* iptr, int hw_dir, int pld_len)
259 int direction = 0; /* incoming */
263 history_type **ht_pp;
267 struct in6_addr scribdst; /* Scratch pad. */
268 struct in6_addr scribsrc; /* Scratch pad. */
269 /* Reinterpret packet type. */
270 struct ip6_hdr* ip6tr = (struct ip6_hdr *) iptr;
272 memset(&ap, '\0', sizeof(ap));
277 * Sanity check: drop obviously short packets.
278 * pld_len comes from pcaphdr->len - sizeof(struct l2_header).
280 * It is assumed that the snaplen (currently hard-coded to 1000) is
281 * big enough to always capture the IP header past the L2 encap, and
282 * that pcap never truncates the packet to less than snaplen; in
283 * other words, that pcaphdr->caplen = MIN(pcaphdr->len, snaplen).
285 if (pld_len < sizeof (struct ip))
287 if (IP_V(iptr) == 6 && pld_len < sizeof (struct ip6_hdr))
290 if( (IP_V(iptr) == 4 && options.netfilter == 0)
291 || (IP_V(iptr) == 6 && options.netfilter6 == 0) ) {
293 * Net filter is off, so assign direction based on MAC address
296 /* Packet leaving this interface. */
297 assign_addr_pair(&ap, iptr, 0);
300 else if(hw_dir == 0) {
301 /* Packet incoming */
302 assign_addr_pair(&ap, iptr, 1);
305 /* Packet direction is not given away by h/ware layer. Try IP
308 else if((IP_V(iptr) == 4) && have_ip_addr && ip_addr_match(iptr->ip_src)) {
310 assign_addr_pair(&ap, iptr, 0);
313 else if((IP_V(iptr) == 4) && have_ip_addr && ip_addr_match(iptr->ip_dst)) {
315 assign_addr_pair(&ap, iptr, 1);
318 else if((IP_V(iptr) == 6) && have_ip6_addr && ip6_addr_match(&ip6tr->ip6_src)) {
320 assign_addr_pair(&ap, iptr, 0);
323 else if((IP_V(iptr) == 6) && have_ip6_addr && ip6_addr_match(&ip6tr->ip6_dst)) {
325 assign_addr_pair(&ap, iptr, 1);
328 else if (IP_V(iptr) == 4 && IN_MULTICAST(iptr->ip_dst.s_addr)) {
329 assign_addr_pair(&ap, iptr, 1);
332 else if (IP_V(iptr) == 6 && IN6_IS_ADDR_MULTICAST(&ip6tr->ip6_dst)) {
333 assign_addr_pair(&ap, iptr, 1);
337 * Cannot determine direction from hardware or IP levels. Therefore
338 * assume that it was a packet between two other machines, assign
339 * source and dest arbitrarily (by numerical value) and account as
342 else if (options.promiscuous_but_choosy) {
343 return; /* junk it */
345 else if((IP_V(iptr) == 4) && (iptr->ip_src.s_addr < iptr->ip_dst.s_addr)) {
346 assign_addr_pair(&ap, iptr, 1);
349 else if(IP_V(iptr) == 4) {
350 assign_addr_pair(&ap, iptr, 0);
353 /* Drop other uncertain packages. */
358 if(IP_V(iptr) == 4 && options.netfilter != 0) {
360 * Net filter on, assign direction according to netmask
362 if(in_filter_net(iptr->ip_src) && !in_filter_net(iptr->ip_dst)) {
364 assign_addr_pair(&ap, iptr, 0);
367 else if(in_filter_net(iptr->ip_dst) && !in_filter_net(iptr->ip_src)) {
369 assign_addr_pair(&ap, iptr, 1);
378 if(IP_V(iptr) == 6 && options.netfilter6 != 0) {
380 * Net filter IPv6 active.
383 //else if((IP_V(iptr) == 6) && have_ip6_addr && ip6_addr_match(&ip6tr->ip6_dst)) {
384 /* First reduce the participating addresses using the netfilter prefix.
385 * We need scratch pads to do this.
387 for (j=0; j < 16; ++j) {
388 scribdst.s6_addr[j] = ip6tr->ip6_dst.s6_addr[j]
389 & options.netfilter6mask.s6_addr[j];
390 scribsrc.s6_addr[j] = ip6tr->ip6_src.s6_addr[j]
391 & options.netfilter6mask.s6_addr[j];
394 /* Now look for any hits. */
395 //if(in_filter_net(iptr->ip_src) && !in_filter_net(iptr->ip_dst)) {
396 if (IN6_ARE_ADDR_EQUAL(&scribsrc, &options.netfilter6net)
397 && ! IN6_ARE_ADDR_EQUAL(&scribdst, &options.netfilter6net)) {
399 assign_addr_pair(&ap, iptr, 0);
402 //else if(in_filter_net(iptr->ip_dst) && !in_filter_net(iptr->ip_src)) {
403 else if (! IN6_ARE_ADDR_EQUAL(&scribsrc, &options.netfilter6net)
404 && IN6_ARE_ADDR_EQUAL(&scribdst, &options.netfilter6net)) {
406 assign_addr_pair(&ap, iptr, 1);
416 /* Test if link-local IPv6 packets should be dropped. */
417 if( IP_V(iptr) == 6 && !options.link_local
418 && (IN6_IS_ADDR_LINKLOCAL(&ip6tr->ip6_dst)
419 || IN6_IS_ADDR_LINKLOCAL(&ip6tr->ip6_src)) )
423 /* Do address resolving. */
424 switch (IP_V(iptr)) {
426 ap.protocol = iptr->ip_p;
427 /* Add the addresses to be resolved */
428 /* The IPv4 address is embedded in a in6_addr structure,
429 * so it need be copied, and delivered to resolve(). */
430 memset(&scribdst, '\0', sizeof(scribdst));
431 memcpy(&scribdst, &iptr->ip_dst, sizeof(struct in_addr));
432 resolve(ap.af, &scribdst, NULL, 0);
433 memset(&scribsrc, '\0', sizeof(scribsrc));
434 memcpy(&scribsrc, &iptr->ip_src, sizeof(struct in_addr));
435 resolve(ap.af, &scribsrc, NULL, 0);
438 ap.protocol = ip6tr->ip6_nxt;
439 /* Add the addresses to be resolved */
440 resolve(ap.af, &ip6tr->ip6_dst, NULL, 0);
441 resolve(ap.af, &ip6tr->ip6_src, NULL, 0);
446 if(hash_find(history, &ap, u_ht.void_pp) == HASH_STATUS_KEY_NOT_FOUND) {
447 ht = history_create();
448 hash_insert(history, &ap, ht);
452 switch (options.bandwidth_unit) {
454 case OPTION_BW_BYTES:
465 ht->last_write = history_pos;
466 if( ((IP_V(iptr) == 4) && (iptr->ip_src.s_addr == ap.src.s_addr))
467 || ((IP_V(iptr) == 6) && !memcmp(&ip6tr->ip6_src, &ap.src6, sizeof(ap.src6))) )
469 ht->sent[history_pos] += len;
470 ht->total_sent += len;
473 ht->recv[history_pos] += len;
474 ht->total_recv += len;
479 history_totals.recv[history_pos] += len;
480 history_totals.total_recv += len;
483 history_totals.sent[history_pos] += len;
484 history_totals.total_sent += len;
489 static void handle_raw_packet(unsigned char* args, const struct pcap_pkthdr* pkthdr, const unsigned char* packet)
491 handle_ip_packet((struct ip*)packet, -1, pkthdr->len);
495 static void handle_pflog_packet(unsigned char* args, const struct pcap_pkthdr* pkthdr, const unsigned char* packet)
497 register u_int length = pkthdr->len;
499 const struct pfloghdr *hdr;
501 hdr = (struct pfloghdr *)packet;
502 hdrlen = BPF_WORDALIGN(hdr->length);
505 handle_ip_packet((struct ip*)packet, -1, length);
509 static void handle_null_packet(unsigned char* args, const struct pcap_pkthdr* pkthdr, const unsigned char* packet)
511 handle_ip_packet((struct ip*)(packet + 4), -1, pkthdr->len);
514 static void handle_llc_packet(const struct llc* llc, int dir, int llclen) {
515 int hdrlen = sizeof(struct llc);
516 int pldlen = llclen - hdrlen;
517 struct ip* ip = (struct ip*)((void*)llc + hdrlen);
519 /* Taken from tcpdump/print-llc.c */
520 if(llc->ssap == LLCSAP_SNAP && llc->dsap == LLCSAP_SNAP
521 && llc->llcui == LLC_UI) {
524 orgcode = EXTRACT_24BITS(&llc->llc_orgcode[0]);
525 et = (llc->llc_ethertype[0] << 8) + llc->llc_ethertype[1];
527 case OUI_ENCAP_ETHER:
529 handle_ip_packet(ip, dir, pldlen);
532 if(et == ETHERTYPE_ATALK) {
533 handle_ip_packet(ip, dir, pldlen);
537 /* Not a lot we can do */
542 static void handle_tokenring_packet(unsigned char* args, const struct pcap_pkthdr* pkthdr, const unsigned char* packet)
544 struct token_header *trp;
547 trp = (struct token_header *)packet;
549 if(IS_SOURCE_ROUTED(trp)) {
550 hdrlen += RIF_LENGTH(trp);
552 hdrlen += TOKEN_HDRLEN;
555 if(memcmp(trp->token_shost, if_hw_addr, 6) == 0 ) {
556 /* packet leaving this i/f */
559 else if(memcmp(trp->token_dhost, if_hw_addr, 6) == 0 || memcmp("\xFF\xFF\xFF\xFF\xFF\xFF", trp->token_dhost, 6) == 0) {
560 /* packet entering this i/f */
564 /* Only know how to deal with LLC encapsulated packets */
565 if(FRAME_TYPE(trp) == TOKEN_FC_LLC) {
566 handle_llc_packet((struct llc*)packet, dir, pkthdr->len - hdrlen);
570 static void handle_ppp_packet(unsigned char* args, const struct pcap_pkthdr* pkthdr, const unsigned char* packet)
572 register u_int length = pkthdr->len;
573 register u_int caplen = pkthdr->caplen;
579 if(packet[0] == PPP_ADDRESS) {
586 proto = EXTRACT_16BITS(packet);
590 if(proto == PPP_IP || proto == ETHERTYPE_IP
591 || proto == ETHERTYPE_IPV6) {
592 handle_ip_packet((struct ip*)packet, -1, length);
598 static void handle_cooked_packet(unsigned char *args, const struct pcap_pkthdr * thdr, const unsigned char * packet)
600 struct sll_header *sptr;
602 sptr = (struct sll_header *) packet;
604 switch (ntohs(sptr->sll_pkttype))
607 /*entering this interface*/
610 case LINUX_SLL_OUTGOING:
611 /*leaving this interface */
615 handle_ip_packet((struct ip*)(packet+SLL_HDR_LEN), dir,
616 thdr->len - SLL_HDR_LEN);
618 #endif /* DLT_LINUX_SLL */
620 static void handle_eth_packet(unsigned char* args, const struct pcap_pkthdr* pkthdr, const unsigned char* packet)
622 struct ether_header *eptr;
623 int ether_type, hdrlen;
625 eptr = (struct ether_header*)packet;
626 ether_type = ntohs(eptr->ether_type);
627 hdrlen = sizeof(struct ether_header);
629 if(ether_type == ETHERTYPE_8021Q) {
630 struct vlan_8021q_header* vptr;
631 vptr = (struct vlan_8021q_header*) (packet + hdrlen);
632 ether_type = ntohs(vptr->ether_type);
633 hdrlen += sizeof(struct vlan_8021q_header);
636 if(ether_type == ETHERTYPE_IP || ether_type == ETHERTYPE_IPV6) {
641 * Is a direction implied by the MAC addresses?
643 if(have_hw_addr && memcmp(eptr->ether_shost, if_hw_addr, 6) == 0 ) {
644 /* packet leaving this i/f */
647 else if(have_hw_addr && memcmp(eptr->ether_dhost, if_hw_addr, 6) == 0 ) {
648 /* packet entering this i/f */
651 else if (memcmp("\xFF\xFF\xFF\xFF\xFF\xFF", eptr->ether_dhost, 6) == 0) {
652 /* broadcast packet, count as incoming */
656 /* Distinguishing ip_hdr and ip6_hdr will be done later. */
657 iptr = (struct ip*) (packet + hdrlen); /* alignment? */
658 handle_ip_packet(iptr, dir, pkthdr->len - hdrlen);
662 #ifdef DLT_IEEE802_11_RADIO
664 * Packets with a bonus radiotap header.
665 * See http://www.gsp.com/cgi-bin/man.cgi?section=9&topic=ieee80211_radiotap
667 static void handle_radiotap_packet(unsigned char* args, const struct pcap_pkthdr* pkthdr, const unsigned char* packet)
669 /* 802.11 MAC header is = 34 bytes (not sure if that's universally true) */
670 /* We could try harder to figure out hardware direction from the MAC header */
671 int hdrlen = ((struct radiotap_header *)packet)->it_len + 34;
672 handle_ip_packet((struct ip*)(packet + hdrlen), -1, pkthdr->len - hdrlen);
679 * Install some filter code. Returns NULL on success or an error message on
681 char *set_filter_code(const char *filter) {
684 x = xmalloc(strlen(filter) + sizeof "() and (ip or ip6)");
685 sprintf(x, "(%s) and (ip or ip6)", filter);
687 x = xstrdup("ip or ip6");
688 if (pcap_compile(pd, &pcap_filter, x, 1, 0) == -1) {
690 return pcap_geterr(pd);
693 if (pcap_setfilter(pd, &pcap_filter) == -1)
694 return pcap_geterr(pd);
704 * performs pcap initialisation, called before ui is initialised
707 char errbuf[PCAP_ERRBUF_SIZE];
713 result = get_addrs_dlpi(options.interface, if_hw_addr, &if_ip_addr);
715 result = get_addrs_ioctl(options.interface, if_hw_addr,
716 &if_ip_addr, &if_ip6_addr);
723 have_hw_addr = result & 0x01;
724 have_ip_addr = result & 0x02;
725 have_ip6_addr = result & 0x04;
728 fprintf(stderr, "IP address is: %s\n", inet_ntoa(if_ip_addr));
731 char ip6str[INET6_ADDRSTRLEN];
734 inet_ntop(AF_INET6, &if_ip6_addr, ip6str, sizeof(ip6str));
735 fprintf(stderr, "IPv6 address is: %s\n", ip6str);
739 fprintf(stderr, "MAC address is: %s\n", ether_ntoa(if_hw_addr));
743 resolver_initialise();
745 pd = pcap_open_live(options.interface, CAPTURE_LENGTH, options.promiscuous, 1000, errbuf);
746 // DEBUG: pd = pcap_open_offline("tcpdump.out", errbuf);
748 fprintf(stderr, "pcap_open_live(%s): %s\n", options.interface, errbuf);
751 dlt = pcap_datalink(pd);
752 if(dlt == DLT_EN10MB) {
753 packet_handler = handle_eth_packet;
756 else if (dlt == DLT_PFLOG) {
757 packet_handler = handle_pflog_packet;
760 else if(dlt == DLT_RAW) {
761 packet_handler = handle_raw_packet;
763 else if(dlt == DLT_NULL) {
764 packet_handler = handle_null_packet;
767 else if(dlt == DLT_LOOP) {
768 packet_handler = handle_null_packet;
771 #ifdef DLT_IEEE802_11_RADIO
772 else if(dlt == DLT_IEEE802_11_RADIO) {
773 packet_handler = handle_radiotap_packet;
776 else if(dlt == DLT_IEEE802) {
777 packet_handler = handle_tokenring_packet;
779 else if(dlt == DLT_PPP) {
780 packet_handler = handle_ppp_packet;
783 * SLL support not available in older libpcaps
786 else if(dlt == DLT_LINUX_SLL) {
787 packet_handler = handle_cooked_packet;
791 fprintf(stderr, "Unsupported datalink type: %d\n"
792 "Please email pdw@ex-parrot.com, quoting the datalink type and what you were\n"
793 "trying to do at the time\n.", dlt);
797 if ((m = set_filter_code(options.filtercode))) {
798 fprintf(stderr, "set_filter_code: %s\n", m);
805 * Worker function for packet capture thread. */
806 void packet_loop(void* ptr) {
807 pcap_loop(pd,-1,(pcap_handler)packet_handler,NULL);
812 * Entry point. See usage(). */
813 int main(int argc, char **argv) {
815 struct sigaction sa = {};
817 setlocale(LC_ALL, "");
819 /* TODO: tidy this up */
820 /* read command line options and config file */
822 options_set_defaults();
823 options_read_args(argc, argv);
824 /* If a config was explicitly specified, whinge if it can't be found */
825 read_config(options.config_file, options.config_file_specified);
828 sa.sa_handler = finish;
829 sigaction(SIGINT, &sa, NULL);
831 pthread_mutex_init(&tick_mutex, NULL);
837 if (options.no_curses) {
844 pthread_create(&thread, NULL, (void*)&packet_loop, NULL);
846 /* Keep the starting time (used for timed termination) */
847 first_timestamp = time(NULL);
849 if (options.no_curses) {
850 if (options.timed_output) {
863 pthread_cancel(thread);