Download Crawford-S-dissertat.. - Department of Computer Science
Transcript
hash_add_flow(flow);
/**
* Debug method for writing flow information directly to database query
* (thus bypassing the server). May be more efficient in a *very* high
* traffic environment, as there is no overhead in communicating flows to
* the server
*/
void writedb(IPFlow *flow)
{
fprintf(stdout,"INSERT INTO flow (saddr,daddr,sport,dport,len,packets,
protocol,application,started,expires) VALUES (");
fprintf(stdout,"'%s',",inet_ntoa(htonl(flow->saddr)));
fprintf(stdout,"'%s',",inet_ntoa(htonl(flow->daddr)));
fprintf(stdout,"%u,%u,%u,%u,%u,%u,FROM_UNIXTIME(%d),
FROM_UNIXTIME(%d));\n",
flow->sport,flow->dport,flow->len,flow->packets,flow->protocol,
flow->application,flow->started,flow->expires);
fflush(stdout);
}
}
/* If we've reached capacity in our flow table, or haven't phoned home
* in over 60 seconds, then look to see if we need to perform a push
*/
if (mode == MODE_LIVE &&
(total_packets == PACKET_CHUNK_LIMIT || (total_packets %10000 == 0
&& time(NULL) > lastsend+60))) {
total_packets = 0;
lastsend = time(NULL);
netmon_pushdata();
/* Push data to server */
}
}
}
/**
* Connects to netmond server
* TODO: Add failed connections counter
*/
int netmon_server_connect()
{
int sockfd;
struct hostent *he;
struct sockaddr_in remote_addr;
/**
* Push flow data to the server if necessary
*/
void netmon_pushdata()
{
int connected = 0;
int sockfd;
int size=0,n;
char buf[BUFF_LEN];
time_t currtime = time(NULL);
int i;
if (!USE_STDOUT) bzero(buf,BUFF_LEN);
/* Lookup hostname */
if ((he=gethostbyname(netmond_server)) == NULL) {
fprintf(stderr,"Failed to determine hostname\n");
return -1;
}
/* Create a socket */
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
fprintf(stderr,"Could not create socket\n");
return -1;
}
/* Loop over hash table */
for (i=0; i<HASH_SIZE; i++)
{
IPFlow *t = hash_table[i];
/* Loop along linked list from this branch of the hash table */
while(t)
{
IPFlow *toFree = NULL;
/* Has this flow expired? */
/* If so, remove it from our cache and send it! */
if (mode == MODE_FILE || t->expires <= currtime ||
t->len >= FLOW_EXPIRY_BYTES)
{
/* If we're not connected, connect to the server */
if (!USE_STDOUT && !connected) {
sockfd = netmon_server_connect();
if (sockfd != -1) connected = 1;
}
/* If flow has already been sent, don't resend
* should never be hit since v0.2
/* Set socket properties */
remote_addr.sin_family = AF_INET;
remote_addr.sin_port = htons(netmond_port);
remote_addr.sin_addr = *((struct in_addr *)he->h_addr);
memset(&(remote_addr.sin_zero), '\0', 8);
/* Connect to server */
if (connect(sockfd, (struct sockaddr *)&remote_addr,
sizeof(struct sockaddr)) == -1) {
fprintf(stderr,"Could not connect to server!\n");
return -1;
}
return sockfd;
}
150