]> gitweb.fperrin.net Git - iftop.git/blob - iftop-dump.c
Import iftop-1.0pre4
[iftop.git] / iftop-dump.c
1 /*
2  * iftop.c:
3  *
4  */
5
6 #include "integers.h"
7
8 #if defined(HAVE_PCAP_H)
9 #   include <pcap.h>
10 #elif defined(HAVE_PCAP_PCAP_H)
11 #   include <pcap/pcap.h>
12 #else
13 #   error No pcap.h
14 #endif
15 #include <stdio.h>
16 #include <stdlib.h>
17 #include <time.h>
18 #include <sys/types.h>
19 #include <sys/ioctl.h>
20 #include <sys/socket.h>
21 #include <net/if.h>
22 #include <netinet/in.h>
23
24 #include <pthread.h>
25 #include <curses.h>
26 #include <signal.h>
27 #include <string.h>
28 #include <unistd.h>
29 #include <errno.h>
30
31 #include "iftop.h"
32 #include "counter_hash.h"
33 #include "resolver.h"
34 #include "options.h"
35 #ifdef DLT_LINUX_SLL
36 #include "sll.h"
37 #endif /* DLT_LINUX_SLL */
38 #include "threadprof.h"
39 #include "ether.h"
40 #include "ip.h"
41 #include "tcp.h"
42 #include "token.h"
43 #include "llc.h"
44 #include "extract.h"
45 #include "ethertype.h"
46 #include "cfgfile.h"
47 #include "ppp.h"
48 #include "time.h"
49
50
51 /* ethernet address of interface. */
52 int have_hw_addr = 0;
53 unsigned char if_hw_addr[6];    
54
55 /* IP address of interface */
56 int have_ip_addr = 0;
57 struct in_addr if_ip_addr;
58
59 extern options_t options;
60
61 hash_type* counters;
62 time_t last_timestamp;
63 long last_day = 0;
64 pthread_mutex_t tick_mutex;
65
66 pcap_t* pd; /* pcap descriptor */
67 struct bpf_program pcap_filter;
68 pcap_handler packet_handler;
69
70 FILE*fout = NULL;
71
72
73
74 sig_atomic_t foad;
75
76 static void finish(int sig) {
77     foad = sig;
78 }
79
80
81
82
83
84 /* Only need ethernet (plus optional 4 byte VLAN) and IP headers (48) + first 2 bytes of tcp/udp header */
85 #define CAPTURE_LENGTH 72
86
87 void init_counters() {
88     counters = counter_hash_create();
89     last_timestamp = time(NULL);
90 }
91
92 counter_type* counter_create() {
93     counter_type* c;
94     c = xcalloc(1, sizeof *c);
95     return c;
96 }
97
98 void close_log_file(void) {
99     if(fout) {
100         fclose(fout);
101     }
102     fout = NULL;
103 }
104
105 void open_log_file(void) {
106     char  filename[255];
107     time_t t;
108     t = time(NULL);
109     strftime(filename, 255, "/var/bandwidth/bw-%Y%m%d",localtime(&t)); 
110     fout = fopen(filename, "w+");
111     if(fout == NULL) {
112         fprintf(stderr, "Could not open log file: %s", strerror(errno));
113     }
114
115 }
116
117 void print_counter(struct in_addr * ip, counter_type * n) {
118     if(!fout) {
119         open_log_file();
120     }
121     fprintf(fout,"%d %s %lld %lld\n",time(NULL),inet_ntoa((struct in_addr)*ip),n->sent,n->recv);
122 }
123
124
125 void tick(int print) {
126     time_t t;
127     hash_node_type * hn = NULL;
128     counter_type* n;
129     struct tm* tt;
130     long day;
131    
132     t = time(NULL);
133
134     if(t - last_timestamp >= DUMP_RESOLUTION) {
135         tt = localtime(&t);
136         day = tt->tm_yday + tt->tm_year * 366;
137         if(day != last_day) {
138             close_log_file();
139             open_log_file();
140         }
141     last_day = day;
142
143         last_timestamp = t;
144         while(hash_next_item(counters, &hn) == HASH_STATUS_OK) {
145           n = (counter_type*)hn->rec;
146           print_counter((struct in_addr*)hn->key, n);
147         }
148     }
149
150 }
151
152 int in_filter_net(struct in_addr addr) {
153     int ret;
154     ret = ((addr.s_addr & options.netfiltermask.s_addr) == options.netfilternet.s_addr);
155     return ret;
156 }
157
158 int ip_addr_match(struct in_addr addr) {
159     return addr.s_addr == if_ip_addr.s_addr;
160 }
161
162
163 static void handle_ip_packet(struct ip* iptr, int hw_dir)
164 {
165     int direction = 0; /* incoming */
166     counter_type * counter;
167     int len;
168     struct in_addr local_addr;
169
170     if(options.netfilter == 0) { 
171         fprintf(stderr, "netfilter option must be specified for iftop-dump\n");
172     }
173     else {
174         /* 
175          * Net filter on, assign direction according to netmask 
176          */ 
177         if(in_filter_net(iptr->ip_src) && !in_filter_net(iptr->ip_dst)) {
178             /* out of network */
179             local_addr = iptr->ip_src;
180             direction = 1;
181         }
182         else if(in_filter_net(iptr->ip_dst) && !in_filter_net(iptr->ip_src)) {
183             /* into network */
184             local_addr = iptr->ip_dst;
185             direction = 0;
186         }
187         else {
188             /* drop packet */
189             return ;
190         }
191     }
192
193     if(hash_find(counters, &local_addr, (void**)&counter) == HASH_STATUS_KEY_NOT_FOUND) {
194         counter = counter_create();
195         hash_insert(counters, &local_addr, counter);
196         print_counter(&local_addr, counter);
197         fflush(fout);
198     }
199
200     len = ntohs(iptr->ip_len);
201
202     if(direction == 0) {
203         /* incoming */
204         counter->recv += len;
205     }
206     else {
207         counter->sent += len; 
208     }
209     if(counter->recv > 2147483648ULL || counter->sent > 2147483648ULL) {
210         print_counter(&local_addr, counter);
211         counter->recv = counter->sent = 0;
212         print_counter(&local_addr, counter);
213         fflush(stdout);
214     }
215
216 }
217
218 static void handle_raw_packet(unsigned char* args, const struct pcap_pkthdr* pkthdr, const unsigned char* packet)
219 {
220     handle_ip_packet((struct ip*)packet, -1);
221 }
222
223 static void handle_llc_packet(const struct llc* llc, int dir) {
224
225     struct ip* ip = (struct ip*)((void*)llc + sizeof(struct llc));
226
227     /* Taken from tcpdump/print-llc.c */
228     if(llc->ssap == LLCSAP_SNAP && llc->dsap == LLCSAP_SNAP
229        && llc->llcui == LLC_UI) {
230         u_int32_t orgcode;
231         register u_short et;
232         orgcode = EXTRACT_24BITS(&llc->llc_orgcode[0]);
233         et = EXTRACT_16BITS(&llc->llc_ethertype[0]);
234         switch(orgcode) {
235           case OUI_ENCAP_ETHER:
236           case OUI_CISCO_90:
237             handle_ip_packet(ip, dir);
238             break;
239           case OUI_APPLETALK:
240             if(et == ETHERTYPE_ATALK) {
241               handle_ip_packet(ip, dir);
242             }
243             break;
244           default:;
245             /* Not a lot we can do */
246         }
247     }
248 }
249
250 static void handle_tokenring_packet(unsigned char* args, const struct pcap_pkthdr* pkthdr, const unsigned char* packet)
251 {
252     struct token_header *trp;
253     int dir = -1;
254     trp = (struct token_header *)packet;
255
256     if(IS_SOURCE_ROUTED(trp)) {
257       packet += RIF_LENGTH(trp);
258     }
259     packet += TOKEN_HDRLEN;
260
261     if(memcmp(trp->token_shost, if_hw_addr, 6) == 0 ) {
262       /* packet leaving this i/f */
263       dir = 1;
264     } 
265         else if(memcmp(trp->token_dhost, if_hw_addr, 6) == 0 || memcmp("\xFF\xFF\xFF\xFF\xFF\xFF", trp->token_dhost, 6) == 0) {
266       /* packet entering this i/f */
267       dir = 0;
268     }
269
270     /* Only know how to deal with LLC encapsulated packets */
271     if(FRAME_TYPE(trp) == TOKEN_FC_LLC) {
272       handle_llc_packet((struct llc*)packet, dir);
273     }
274 }
275
276 static void handle_ppp_packet(unsigned char* args, const struct pcap_pkthdr* pkthdr, const unsigned char* packet)
277 {
278         register u_int length = pkthdr->len;
279         register u_int caplen = pkthdr->caplen;
280         u_int proto;
281
282         if (caplen < 2) 
283         return;
284
285         if(packet[0] == PPP_ADDRESS) {
286                 if (caplen < 4) 
287             return;
288
289                 packet += 2;
290                 length -= 2;
291
292                 proto = EXTRACT_16BITS(packet);
293                 packet += 2;
294                 length -= 2;
295
296         if(proto == PPP_IP || proto == ETHERTYPE_IP) {
297             handle_ip_packet((struct ip*)packet, -1);
298         }
299     }
300 }
301
302 #ifdef DLT_LINUX_SLL
303 static void handle_cooked_packet(unsigned char *args, const struct pcap_pkthdr * thdr, const unsigned char * packet)
304 {
305     struct sll_header *sptr;
306     int dir = -1;
307     sptr = (struct sll_header *) packet;
308
309     switch (ntohs(sptr->sll_pkttype))
310     {
311     case LINUX_SLL_HOST:
312         /*entering this interface*/
313         dir = 0;
314         break;
315     case LINUX_SLL_OUTGOING:
316         /*leaving this interface */
317         dir=1;
318         break;
319     }
320     handle_ip_packet((struct ip*)(packet+SLL_HDR_LEN), dir);
321 }
322 #endif /* DLT_LINUX_SLL */
323
324 static void handle_eth_packet(unsigned char* args, const struct pcap_pkthdr* pkthdr, const unsigned char* packet)
325 {
326     struct ether_header *eptr;
327     int ether_type;
328     const unsigned char *payload;
329     eptr = (struct ether_header*)packet;
330     ether_type = ntohs(eptr->ether_type);
331     payload = packet + sizeof(struct ether_header);
332
333     tick(0);
334
335     if(ether_type == ETHERTYPE_8021Q) {
336         struct vlan_8021q_header* vptr;
337         vptr = (struct vlan_8021q_header*)payload;
338         ether_type = ntohs(vptr->ether_type);
339         payload += sizeof(struct vlan_8021q_header);
340     }
341
342     if(ether_type == ETHERTYPE_IP) {
343         struct ip* iptr;
344         int dir = -1;
345         
346         /*
347          * Is a direction implied by the MAC addresses?
348          */
349         if(have_hw_addr && memcmp(eptr->ether_shost, if_hw_addr, 6) == 0 ) {
350             /* packet leaving this i/f */
351             dir = 1;
352         }
353         else if(have_hw_addr && memcmp(eptr->ether_dhost, if_hw_addr, 6) == 0 ) {
354             /* packet entering this i/f */
355             dir = 0;
356         }
357         else if (memcmp("\xFF\xFF\xFF\xFF\xFF\xFF", eptr->ether_dhost, 6) == 0) {
358           /* broadcast packet, count as incoming */
359             dir = 0;
360         }
361
362         iptr = (struct ip*)(payload); /* alignment? */
363         handle_ip_packet(iptr, dir);
364     }
365 }
366
367
368 /* set_filter_code:
369  * Install some filter code. Returns NULL on success or an error message on
370  * failure. */
371 char *set_filter_code(const char *filter) {
372     char *x;
373     if (filter) {
374         x = xmalloc(strlen(filter) + sizeof "() and ip");
375         sprintf(x, "(%s) and ip", filter);
376     } else
377         x = xstrdup("ip");
378     if (pcap_compile(pd, &pcap_filter, x, 1, 0) == -1) {
379         xfree(x);
380         return pcap_geterr(pd);
381     }
382     xfree(x);
383     if (pcap_setfilter(pd, &pcap_filter) == -1)
384         return pcap_geterr(pd);
385     else
386         return NULL;
387 }
388
389
390
391 /*
392  * packet_init:
393  *
394  * performs pcap initialisation, called before ui is initialised
395  */
396 void packet_init() {
397     char errbuf[PCAP_ERRBUF_SIZE];
398     char *m;
399     int s;
400     int i;
401     int dlt;
402     int result;
403
404 #ifdef HAVE_DLPI
405     result = get_addrs_dlpi(options.interface, if_hw_addr, &if_ip_addr);
406 #else
407     result = get_addrs_ioctl(options.interface, if_hw_addr, &if_ip_addr);
408 #endif
409
410     if (result < 0) {
411       exit(1);
412     }
413
414     have_hw_addr = result & 1;
415     have_ip_addr = result & 2;
416     
417     if(have_ip_addr) {
418       fprintf(stderr, "IP address is: %s\n", inet_ntoa(if_ip_addr));
419     }
420
421     if(have_hw_addr) {
422       fprintf(stderr, "MAC address is:");
423       for (i = 0; i < 6; ++i)
424         fprintf(stderr, "%c%02x", i ? ':' : ' ', (unsigned int)if_hw_addr[i]);
425       fprintf(stderr, "\n");
426     }
427     
428     //    exit(0);
429     /* resolver_initialise(); */
430
431     pd = pcap_open_live(options.interface, CAPTURE_LENGTH, options.promiscuous, 1000, errbuf);
432     // DEBUG: pd = pcap_open_offline("tcpdump.out", errbuf);
433     if(pd == NULL) { 
434         fprintf(stderr, "pcap_open_live(%s): %s\n", options.interface, errbuf); 
435         exit(1);
436     }
437     dlt = pcap_datalink(pd);
438     if(dlt == DLT_EN10MB) {
439         packet_handler = handle_eth_packet;
440     }
441     else if(dlt == DLT_RAW || dlt == DLT_NULL) {
442         packet_handler = handle_raw_packet;
443     } 
444     else if(dlt == DLT_IEEE802) {
445         packet_handler = handle_tokenring_packet;
446     }
447     else if(dlt == DLT_PPP) {
448         packet_handler = handle_ppp_packet;
449     }
450 /* 
451  * SLL support not available in older libpcaps
452  */
453 #ifdef DLT_LINUX_SLL
454     else if(dlt == DLT_LINUX_SLL) {
455       packet_handler = handle_cooked_packet;
456     }
457 #endif
458     else {
459         fprintf(stderr, "Unsupported datalink type: %d\n"
460                 "Please email pdw@ex-parrot.com, quoting the datalink type and what you were\n"
461                 "trying to do at the time\n.", dlt);
462         exit(1);
463     }
464
465     if ((m = set_filter_code(options.filtercode))) {
466         fprintf(stderr, "set_filter_code: %s\n", m);
467         exit(1);
468         return;
469     }
470 }
471
472 /* packet_loop: */
473 void packet_loop() {
474     pcap_loop(pd,-1,(pcap_handler)packet_handler,NULL);
475 }
476
477
478 /* main:
479  * Entry point. See usage(). */
480 int main(int argc, char **argv) {
481     pthread_t thread;
482     struct sigaction sa = {};
483
484     /* TODO: tidy this up */
485     /* read command line options and config file */   
486     config_init();
487     options_set_defaults();
488     options_read_args(argc, argv);
489     /* If a config was explicitly specified, whinge if it can't be found */
490     read_config(options.config_file, options.config_file_specified);
491     options_make();
492     
493     /*
494     sa.sa_handler = finish;
495     sigaction(SIGINT, &sa, NULL);
496     */
497
498     pthread_mutex_init(&tick_mutex, NULL);
499
500     packet_init();
501
502     init_counters();
503
504     packet_loop();
505     
506     return 0;
507 }