//
// $Id: ipfw-data.c,v 1.6 2001/11/22 13:29:04 mavetju Exp $
//

//
// The data processing functions of ipfw-graph.
//

#include <gtk/gtk.h>
#include <stdio.h>
#include <string.h>
#include "ipfw-graph.h"


//
// Add 'value' to the 'table' in 'data'
// If updatemax==TRUE, then update the global variable maxyvalue also
//
void update_data(long value,DATA_TYPE *data,bool updatemax) {
    if (maxyvalue==-1)
	data->new=value;

    data->old=data->new;
    data->new=value;

    memmove(data->table,data->table+1,sizeof(long)*(MAXSTORED-1));

    data->table[MAXSTORED-1]=data->new-data->old;

    if (updatemax) {
	int i;

	memmove(maxyvalues,maxyvalues+1,(MAXSTORED-1)*sizeof(long));
	maxyvalues[MAXSTORED-1]=
		data->table[MAXSTORED-1]==0 ? 1 : data->table[MAXSTORED-1];

	maxyvalue=1;
	for (i=MAXSTORED-xsize;i<MAXSTORED;i++)
	    if (maxyvalue<maxyvalues[i])
		maxyvalue=maxyvalues[i];
    }
}

//
// Find a certain rule
//
DATA_TYPE *find_data(char *number,char *rule) {
    int i;

    for (i=0;i<data_size;i++)
	if (strcmp(data[i].number,number)==0 &&
	    strcmp(data[i].rule,rule)==0)
	    return &data[i];
    return NULL;
}

//
// Get the data from the input source and store in into the data-variable
//
#define STRINGSIZE	1000
void getdata(void) {
    FILE *	fin;
    int		packets,bytes;
    int		totalpackets,totalbytes;
    int		chars;
    char	s[STRINGSIZE];
    char	number[STRINGSIZE];
    char *	rule;
    DATA_TYPE *	thisdata;
    char *	ipfwal=BINDIR"/ipfw-al";

    totalpackets=0;
    totalbytes=0;

    if ((fin=popen(ipfwal,"r"))!=NULL) {
	while (!feof(fin)) {
	    if (fgets(s,STRINGSIZE,fin)==NULL) break;
	    if (sscanf(s,"%s %d %d %n",number,&packets,&bytes,&chars)==3) {

		s[chars-1]=0;
		rule=s+chars;
		rule[strlen(rule)-1]=0;

		if ((thisdata=find_data(number,rule))!=NULL)
		    update_data(bytes,thisdata,FALSE);
		else
		    printf("Didn't find: '%s' '%s'\n",number,rule);
		totalbytes+=bytes;
		totalpackets+=packets;
	    } else
		// dynamic rules come after the ## Dynamic rules
		if (s[0]=='#')
		    break;

	}
	pclose(fin);
    }

    update_data(totalbytes,&data_bytes,TRUE);
}




syntax highlighted by Code2HTML, v. 0.9.1