~ubuntu-branches/ubuntu/natty/ntop/natty

« back to all changes in this revision

Viewing changes to ntop/ntop.c

  • Committer: Bazaar Package Importer
  • Author(s): Ola Lundqvist
  • Date: 2005-01-30 21:59:13 UTC
  • mfrom: (2.1.1 warty)
  • Revision ID: james.westby@ubuntu.com-20050130215913-xc3ke963bw49b3k4
Tags: 2:3.0-5
* Updated README.Debian file so users will understand what to do at
  install, closes: #291794, #287802.
* Updated ntop init script to give better output.
* Also changed log directory from /var/lib/ntop to /var/log/ntop,
  closes: #252352.
* Quoted the interface list to allow whitespace, closes: #267248.
* Added a couple of logcheck ignores, closes: #269321, #269319.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
/*
2
 
 *  Copyright (C) 1998-2001 Luca Deri <deri@ntop.org>
3
 
 *                          Portions by Stefano Suin <stefano@ntop.org>
4
 
 *
5
 
 *                          http://www.ntop.org/
6
 
 *
7
 
 *  This program is free software; you can redistribute it and/or modify
8
 
 *  it under the terms of the GNU General Public License as published by
9
 
 *  the Free Software Foundation; either version 2 of the License, or
10
 
 *  (at your option) any later version.
11
 
 *
12
 
 *  This program is distributed in the hope that it will be useful,
13
 
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15
 
 *  GNU General Public License for more details.
16
 
 *
17
 
 *  You should have received a copy of the GNU General Public License
18
 
 *  along with this program; if not, write to the Free Software
19
 
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
20
 
 */
21
 
 
22
 
/*
23
 
 * Copyright (c) 1994, 1996
24
 
 *      The Regents of the University of California.  All rights reserved.
25
 
 *
26
 
 * Redistribution and use in source and binary forms, with or without
27
 
 * modification, are permitted provided that: (1) source code distributions
28
 
 * retain the above copyright notice and this paragraph in its entirety, (2)
29
 
 * distributions including binary code include the above copyright notice and
30
 
 * this paragraph in its entirety in the documentation or other materials
31
 
 * provided with the distribution, and (3) all advertising materials mentioning
32
 
 * features or use of this software display the following acknowledgement:
33
 
 * ``This product includes software developed by the University of California,
34
 
 * Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
35
 
 * the University nor the names of its contributors may be used to endorse
36
 
 * or promote products derived from this software without specific prior
37
 
 * written permission.
38
 
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
39
 
 * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
40
 
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
41
 
 */
42
 
 
43
 
#include "ntop.h"
44
 
 
45
 
 
46
 
int numChildren = 0;
47
 
 
48
 
static int enableDBsupport=0;
49
 
static int *servicesMapper = NULL; /* temporary value */
50
 
 
51
 
/* *************************** */
52
 
 
53
 
#ifdef MULTITHREADED
54
 
static void printMutexInfo(PthreadMutex *mutexId, char *mutexName) {  
55
 
 
56
 
  traceEvent(TRACE_INFO, "%s is %s (last lock %s:%d) [max lock time %s:%d (%d sec)]", 
57
 
             mutexName,
58
 
             mutexId->isLocked ? "*locked*" : "unlocked",
59
 
             mutexId->lockFile, mutexId->lockLine,
60
 
             mutexId->maxLockedDurationUnlockFile,
61
 
             mutexId->maxLockedDurationUnlockLine,
62
 
             mutexId->maxLockedDuration);  
63
 
}
64
 
#endif
65
 
 
66
 
#ifndef WIN32
67
 
void handleSigHup(int signalId _UNUSED_) {
68
 
#ifdef MULTITHREADED
69
 
  traceEvent(TRACE_INFO, "========================================");
70
 
   printMutexInfo(&gdbmMutex, "gdbmMutex");
71
 
   printMutexInfo(&packetQueueMutex, "packetQueueMutex");
72
 
   printMutexInfo(&addressResolutionMutex, "addressResolutionMutex");
73
 
   printMutexInfo(&hashResizeMutex, "hashResizeMutex");
74
 
 
75
 
  if(isLsofPresent)
76
 
     printMutexInfo(&lsofMutex, "lsofMutex");
77
 
   printMutexInfo(&hostsHashMutex, "hostsHashMutex");
78
 
   printMutexInfo(&graphMutex, "graphMutex");
79
 
#ifdef ASYNC_ADDRESS_RESOLUTION
80
 
  if(numericFlag == 0)
81
 
     printMutexInfo(&addressQueueMutex, "addressQueueMutex");
82
 
#endif
83
 
  traceEvent(TRACE_INFO, "========================================");
84
 
#endif /* MULTITHREADED */
85
 
 
86
 
  (void)setsignal(SIGHUP,  handleSigHup);
87
 
}
88
 
 
89
 
#endif /* WIN32 */
90
 
 
91
 
/* *************************** */
92
 
 
93
 
#ifdef MULTITHREADED
94
 
#ifndef WIN32
95
 
void* pcapDispatch(void *_i) {
96
 
  int rc;
97
 
  int i = (int)_i;
98
 
  int pcap_fd;
99
 
  fd_set readMask;
100
 
  struct timeval timeout;
101
 
  
102
 
  pcap_fd = pcap_fileno(device[i].pcapPtr);
103
 
 
104
 
  if((pcap_fd == -1) && (rFileName != NULL)) {
105
 
    /*
106
 
      This is a patch to overcome a bug of libpcap
107
 
      while reading from a traffic file instead
108
 
      of sniffying live from a NIC.
109
 
    */
110
 
    struct mypcap {
111
 
      int fd, snapshot, linktype, tzoff, offset;
112
 
      FILE *rfile;
113
 
 
114
 
      /* Other fields have been skipped. Please refer
115
 
         to pcap-int.h for the full datatype.
116
 
      */
117
 
    };
118
 
 
119
 
    pcap_fd = fileno(((struct mypcap *)(device[i].pcapPtr))->rfile);
120
 
  }
121
 
 
122
 
  for(;capturePackets == 1;) {
123
 
    FD_ZERO(&readMask);
124
 
    FD_SET(pcap_fd, &readMask);
125
 
 
126
 
    timeout.tv_sec  = 5 /* seconds */;
127
 
    timeout.tv_usec = 0;
128
 
 
129
 
    if(select(pcap_fd+1, &readMask, NULL, NULL, &timeout) > 0) {
130
 
      /* printf("dispatch device %s\n", device[i].name);*/
131
 
      if(!capturePackets) return(NULL);
132
 
      rc = pcap_dispatch(device[i].pcapPtr, 1, processPacket, (u_char*)_i);
133
 
 
134
 
      if(rc == -1) {
135
 
        traceEvent(TRACE_ERROR, "Error while reading packets: %s.\n",
136
 
                   pcap_geterr(device[i].pcapPtr));
137
 
        break;
138
 
      } else if((rc == 0) && (rFileName != NULL)) {
139
 
        traceEvent(TRACE_INFO, "pcap_dispatch returned %d "
140
 
                   "[No more packets to read]", rc);
141
 
        break; /* No more packets to read */
142
 
      }
143
 
      /* else 
144
 
         traceEvent(TRACE_INFO, "1) %d\n", numPkts++); 
145
 
      */
146
 
    }
147
 
  }
148
 
 
149
 
  return(NULL);
150
 
}
151
 
#else /* WIN32 */
152
 
void* pcapDispatch(void *_i) {
153
 
  int rc;
154
 
  int i = (int)_i;
155
 
 
156
 
  for(;capturePackets == 1;) {
157
 
    rc = pcap_dispatch(device[i].pcapPtr, 1, queuePacket, (u_char*)_i);
158
 
    if(rc == -1) {
159
 
      traceEvent(TRACE_ERROR, "Error while reading packets: %s.\n",
160
 
                 pcap_geterr(device[i].pcapPtr));
161
 
      break;
162
 
    } /* elsetraceEvent(TRACE_INFO, "1) %d\n", numPkts++); */
163
 
  }
164
 
 
165
 
  return(NULL);
166
 
}
167
 
#endif
168
 
#endif
169
 
 
170
 
/* **************************************** */
171
 
 
172
 
#ifndef WIN32
173
 
RETSIGTYPE handleDiedChild(int signal _UNUSED_) {
174
 
  int status;
175
 
  pid_t pidId;
176
 
 
177
 
  while((pidId = waitpid(-1, &status, WNOHANG)) > 0) {
178
 
#ifdef DEBUG
179
 
    if(status == 0) {
180
 
      numChildren--;
181
 
      traceEvent(TRACE_INFO,
182
 
                 "A child has terminated [pid=%d status=%d children=%d]\n",
183
 
                 pidId, status, numChildren);
184
 
    }
185
 
#endif
186
 
  }
187
 
 
188
 
  /* setsignal(SIGCHLD, handleDiedChild); */
189
 
}
190
 
#endif
191
 
 
192
 
 
193
 
/* **************************************** */
194
 
 
195
 
#ifndef WIN32
196
 
 
197
 
void daemonize(void) { 
198
 
  int childpid;
199
 
 
200
 
  signal(SIGHUP, SIG_IGN);
201
 
#ifndef WIN32
202
 
  /* setsignal(SIGCHLD, handleDiedChild); */
203
 
     setsignal(SIGCHLD, SIG_IGN); 
204
 
#endif
205
 
  signal(SIGQUIT, SIG_IGN);
206
 
 
207
 
  if((childpid=fork()) < 0)
208
 
    traceEvent(TRACE_ERROR, "An error occurred while daemonizing ntop (errno=%d)...\n", errno);
209
 
  else {
210
 
    if(!childpid) { /* child */
211
 
      traceEvent(TRACE_INFO, "Bye bye: I'm becoming a daemon...\n");
212
 
      detachFromTerminal();
213
 
    } else { /* father */
214
 
      exit(0);
215
 
    }
216
 
  }
217
 
}
218
 
 
219
 
/* **************************************** */
220
 
 
221
 
void detachFromTerminal(void) {
222
 
#ifndef MULTITHREADED
223
 
  alarm(120); /* Don't freeze */
224
 
#endif
225
 
 
226
 
#ifndef WIN32
227
 
  useSyslog = 1; /* Log in the syslog */
228
 
#endif
229
 
  
230
 
  chdir("/");
231
 
  setsid();  /* detach from the terminal */
232
 
 
233
 
#ifdef ORIGINAL_DETACH
234
 
  if (freopen("/dev/null", "r", stdin) == NULL) {
235
 
    traceEvent(TRACE_ERROR,
236
 
               "ntop: unable to replace stdin with /dev/null: %s\n",
237
 
               strerror(errno));
238
 
  }
239
 
 
240
 
  if (freopen("/dev/null", "w", stdout) == NULL) {
241
 
    traceEvent(TRACE_ERROR,
242
 
               "ntop: unable to replace stdout with /dev/null: %s\n",
243
 
               strerror(errno));
244
 
  }
245
 
 
246
 
  /*
247
 
    if (freopen("/dev/null", "w", stderr) == NULL) {
248
 
    traceEvent(TRACE_ERROR,
249
 
    "ntop: unable to replace stderr with /dev/null: %s\n",
250
 
    strerror(errno));
251
 
    }
252
 
  */
253
 
#else /* !ORIGINAL_DETACH */
254
 
  fclose(stdin);
255
 
  fclose(stdout);
256
 
  /* fclose(stderr); */
257
 
 
258
 
  /*
259
 
   * clear any inherited file mode creation mask
260
 
   */
261
 
  umask (0);
262
 
 
263
 
  /*
264
 
   * Use linebuffered stdout
265
 
   */
266
 
  /* setlinebuf (stdout); */
267
 
  setvbuf(stdout, (char *)NULL, _IOLBF, 0);
268
 
 
269
 
#endif /* ORIGINAL_DETACH */
270
 
}
271
 
#endif /* WIN32 */
272
 
 
273
 
/* **************************************** */
274
 
 
275
 
static short handleProtocol(char* protoName, char *protocol) {
276
 
  int i, idx, lowProtoPort, highProtoPort;
277
 
  short printWarnings = 0;
278
 
 
279
 
  if(protocol[0] == '\0')
280
 
    return(-1);
281
 
  else if(isdigit(protocol[0])) {
282
 
    /* numeric protocol port handling */
283
 
    lowProtoPort = highProtoPort = 0;
284
 
    sscanf(protocol, "%d-%d", &lowProtoPort, &highProtoPort);
285
 
    if(highProtoPort < lowProtoPort)
286
 
      highProtoPort = lowProtoPort;
287
 
 
288
 
    if(lowProtoPort < 0) lowProtoPort = 0;
289
 
    if(highProtoPort >= TOP_IP_PORT) highProtoPort = TOP_IP_PORT-1;
290
 
 
291
 
    for(idx=lowProtoPort; idx<= highProtoPort; idx++) {
292
 
      if(servicesMapper[idx] == -1) {
293
 
        numIpPortsToHandle++;
294
 
 
295
 
#ifdef DEBUG
296
 
        printf("[%d] '%s' [port=%d]\n", numIpProtosToMonitor, protoName, idx);
297
 
#endif
298
 
        servicesMapper[idx] = numIpProtosToMonitor;
299
 
      } else if(printWarnings)
300
 
        printf("WARNING: IP port %d (%s) has been discarded (multiple instances).\n",
301
 
               idx, protoName);
302
 
    }
303
 
 
304
 
    return(1);
305
 
  }
306
 
 
307
 
  for(i=1; i<numActServices; i++) {
308
 
    idx = -1;
309
 
 
310
 
    if((udpSvc[i] != NULL) && (strcmp(udpSvc[i]->name, protocol) == 0))
311
 
      idx = udpSvc[i]->port;
312
 
    else if((tcpSvc[i] != NULL) && (strcmp(tcpSvc[i]->name, protocol) == 0))
313
 
      idx = tcpSvc[i]->port;
314
 
 
315
 
    if(idx != -1) {
316
 
      if(servicesMapper[idx] == -1) {
317
 
        numIpPortsToHandle++;
318
 
 
319
 
#ifdef DEBUG
320
 
        printf("[%d] '%s' [%s:%d]\n", numIpProtosToMonitor, protoName, protocol, idx);
321
 
#endif
322
 
        servicesMapper[idx] = numIpProtosToMonitor;
323
 
      } else if(printWarnings)
324
 
        printf("WARNING: protocol '%s' has been discarded (multiple instances).\n",
325
 
               protocol);
326
 
      return(1);
327
 
    }
328
 
  }
329
 
 
330
 
  if(printWarnings)
331
 
    traceEvent(TRACE_WARNING, "WARNING: unknown protocol '%s'. It has been ignored.\n",
332
 
               protocol);
333
 
 
334
 
  return(-1);
335
 
}
336
 
 
337
 
/* **************************************** */
338
 
 
339
 
static void handleProtocolList(char* protoName,
340
 
                               char *protocolList) {
341
 
  char tmpStr[255];
342
 
  char* lastEntry, *protoEntry;
343
 
  int increment=0, rc;
344
 
 
345
 
  if(servicesMapper == NULL) {
346
 
    servicesMapper = (int*)malloc(sizeof(int)*TOP_IP_PORT);
347
 
    memset(servicesMapper, -1, sizeof(int)*TOP_IP_PORT);
348
 
  }
349
 
 
350
 
#ifdef DEBUG
351
 
  traceEvent(TRACE_INFO, "%s - %s\n", protoName, protocolList);
352
 
#endif
353
 
 
354
 
  /* The trick below is used to avoid to modify static
355
 
     memory like in the case where this function is
356
 
     called by addDefaultProtocols()
357
 
  */
358
 
  lastEntry = strncpy(tmpStr, protocolList, sizeof(tmpStr));
359
 
 
360
 
  while((protoEntry  = strchr(lastEntry, '|')) != NULL) {
361
 
    protoEntry[0] = '\0';
362
 
    rc = handleProtocol(protoName, lastEntry);
363
 
 
364
 
    if(rc != -1)
365
 
      increment=1;
366
 
 
367
 
    lastEntry = &protoEntry[1];
368
 
  }
369
 
 
370
 
  if(increment == 1) {
371
 
    if(numIpProtosToMonitor == 0)
372
 
      protoIPTrafficInfos = (char**)malloc(sizeof(char*));
373
 
    else
374
 
      protoIPTrafficInfos = (char**)realloc(protoIPTrafficInfos, sizeof(char*)*(numIpProtosToMonitor+1));
375
 
 
376
 
    protoIPTrafficInfos[numIpProtosToMonitor] = strdup(protoName);
377
 
    numIpProtosToMonitor++;
378
 
#ifdef DEBUG
379
 
    traceEvent(TRACE_INFO, "%d) %s - %s\n",
380
 
               numIpProtosToMonitor, protoName, protocolList);
381
 
#endif
382
 
  }
383
 
}
384
 
 
385
 
/* **************************************** */
386
 
 
387
 
void createPortHash() {
388
 
  int theSize, i;
389
 
 
390
 
  /* 
391
 
     At this point in time servicesMapper contains all
392
 
     the port data hence we can transform it from
393
 
     an array to a hash table.     
394
 
  */
395
 
  numIpPortMapperSlots = 2*numIpPortsToHandle;
396
 
  theSize = sizeof(PortMapper)*2*numIpPortMapperSlots;
397
 
  ipPortMapper = (PortMapper*)malloc(theSize);
398
 
  for(i=0; i<numIpPortMapperSlots; i++) ipPortMapper[i].port = -1;
399
 
 
400
 
#ifdef DEBUG  
401
 
  traceEvent(TRACE_INFO, "Allocating %d slots", numIpPortMapperSlots);
402
 
#endif
403
 
 
404
 
  for(i=0; i<TOP_IP_PORT; i++) {
405
 
    if(servicesMapper[i] != -1) {
406
 
      int slotId = (3*i) % numIpPortMapperSlots;
407
 
 
408
 
      while(ipPortMapper[slotId].port != -1)    
409
 
        slotId = (slotId+1) % numIpPortMapperSlots;
410
 
 
411
 
#ifdef DEBUG
412
 
      traceEvent(TRACE_INFO, "Mapping port %d to slotId %d", i, slotId);
413
 
#endif
414
 
      ipPortMapper[slotId].port = i, ipPortMapper[slotId].mappedPort = servicesMapper[i];
415
 
    }
416
 
  }
417
 
 
418
 
  free(servicesMapper);
419
 
}
420
 
 
421
 
/* **************************************** */
422
 
 
423
 
void handleProtocols(char *protos) {
424
 
  char *proto, *buffer=NULL, *strtokState;
425
 
  FILE *fd = fopen(protos, "rb");
426
 
 
427
 
  if(fd == NULL)
428
 
    proto = strtok_r(protos, ",", &strtokState);
429
 
  else {
430
 
    struct stat buf;
431
 
    int len, i;
432
 
 
433
 
    if(stat(protos, &buf) != 0) {
434
 
      traceEvent(TRACE_ERROR, "Error while stat() of %s\n", protos);
435
 
      return;
436
 
    }
437
 
 
438
 
    buffer = (char*)malloc(buf.st_size+8) /* just to be safe */;
439
 
 
440
 
    for(i=0;i<buf.st_size;) {
441
 
      len = fread(&buffer[i], sizeof(char), buf.st_size-i, fd);
442
 
      if(len <= 0) break;
443
 
      i += len;
444
 
    }
445
 
 
446
 
    fclose(fd);
447
 
 
448
 
    /* remove trailing carriage return */
449
 
    if(buffer[strlen(buffer)-1] == '\n')
450
 
      buffer[strlen(buffer)-1] = 0;
451
 
 
452
 
    proto = strtok_r(buffer, ",", &strtokState);
453
 
  }
454
 
 
455
 
  while(proto != NULL) {
456
 
    char* protoName = strchr(proto, '=');
457
 
 
458
 
    if(protoName == NULL)
459
 
      traceEvent(TRACE_INFO,
460
 
                 "Unknown protocol '%s'. It has been ignored.\n",
461
 
                 proto);
462
 
    else {
463
 
      char tmpStr[255];
464
 
      int len;
465
 
 
466
 
      protoName[0] = '\0';
467
 
      memset(tmpStr, 0, sizeof(tmpStr));
468
 
      strncpy(tmpStr, &protoName[1], sizeof(tmpStr));
469
 
      len = strlen(tmpStr);
470
 
 
471
 
      if(tmpStr[len-1] != '|') {
472
 
        /* Make sure that the string ends with '|' */
473
 
        tmpStr[len] = '|';
474
 
        tmpStr[len+1] = '\0';
475
 
      }
476
 
 
477
 
      handleProtocolList(proto, tmpStr);
478
 
 
479
 
    }
480
 
    proto = strtok_r(NULL, ",", &strtokState);
481
 
  }
482
 
 
483
 
  if(buffer !=NULL)
484
 
    free(buffer);
485
 
 
486
 
  createPortHash();
487
 
}
488
 
 
489
 
/* **************************************** */
490
 
 
491
 
void addDefaultProtocols(void) {
492
 
  handleProtocolList("FTP", "ftp|ftp-data|");
493
 
  handleProtocolList("HTTP", "http|www|https|");
494
 
  handleProtocolList("DNS", "name|domain|");
495
 
  handleProtocolList("Telnet", "telnet|login|");
496
 
  handleProtocolList("NBios-IP", "netbios-ns|netbios-dgm|netbios-ssn|");
497
 
  handleProtocolList("Mail", "pop-2|pop-3|pop3|kpop|smtp|imap|imap2|");
498
 
  handleProtocolList("DHCP/BOOTP", "67-68|");
499
 
  handleProtocolList("SNMP", "snmp|snmp-trap|");
500
 
  handleProtocolList("NEWS", "nntp|");
501
 
  handleProtocolList("NFS", "mount|pcnfs|bwnfs|nfsd|nfsd-status|");
502
 
  handleProtocolList("X11", "6000-6010|");
503
 
  /* 22 == ssh (just to make sure the port is defined) */
504
 
  handleProtocolList("SSH", "22|");
505
 
 
506
 
  createPortHash();
507
 
}
508
 
 
509
 
/* **************************************** */
510
 
 
511
 
int mapGlobalToLocalIdx(int port) {
512
 
  if((port < 0) || (port >= TOP_IP_PORT))
513
 
   return(-1);
514
 
  else {
515
 
    int j, found, slotId = (3*port) % numIpPortMapperSlots;
516
 
    
517
 
    for(j=0, found=0; j<numIpPortMapperSlots; j++) {
518
 
      if(ipPortMapper[slotId].port == -1)
519
 
        break;
520
 
      else if(ipPortMapper[slotId].port == port) {
521
 
        found = 1;
522
 
        break;
523
 
      }
524
 
      
525
 
      slotId = (slotId+1) % numIpPortMapperSlots;
526
 
    }
527
 
    
528
 
    if(found)
529
 
      return(ipPortMapper[slotId].mappedPort);
530
 
    else
531
 
      return(-1);
532
 
  }
533
 
}
534
 
 
535
 
/* **************************************** */
536
 
 
537
 
#ifdef MULTITHREADED
538
 
void* updateThptLoop(void* notUsed _UNUSED_) {
539
 
  for(;;) {
540
 
#ifdef DEBUG
541
 
    traceEvent(TRACE_INFO, "Sleeping for %d seconds\n",
542
 
               THROUGHPUT_REFRESH_TIME);
543
 
#endif
544
 
 
545
 
    sleep(THROUGHPUT_REFRESH_TIME);
546
 
 
547
 
    if(!capturePackets) break;
548
 
 
549
 
#ifdef DEBUG
550
 
    traceEvent(TRACE_INFO, "Trying to update throughput\n");
551
 
#endif
552
 
 
553
 
    /* Don't update Thpt if the traffic is high */
554
 
    /* if(packetQueueLen < (PACKET_QUEUE_LENGTH/3)) */ {
555
 
      actTime = time(NULL);
556
 
      accessMutex(&hostsHashMutex, "updateThptLoop");
557
 
#ifdef DEBUG
558
 
      traceEvent(TRACE_INFO, "Updating throughput\n");
559
 
#endif
560
 
      updateThpt(); /* Update Throughput */
561
 
      releaseMutex(&hostsHashMutex);
562
 
    }
563
 
  }
564
 
 
565
 
  return(NULL);
566
 
}
567
 
#endif
568
 
 
569
 
/* **************************************** */
570
 
 
571
 
#ifdef MULTITHREADED
572
 
void* updateHostTrafficStatsThptLoop(void* notUsed _UNUSED_) {
573
 
  time_t nextUpdate = actTime+3600;
574
 
  int hourId, minuteId, lastUpdatedHour=-1;
575
 
  char theDate[8];
576
 
  struct tm t;
577
 
 
578
 
  for(;;) {
579
 
#ifdef DEBUG
580
 
    traceEvent(TRACE_INFO, "Sleeping for 60 seconds\n");
581
 
#endif
582
 
 
583
 
    if(!capturePackets) break; /* Before */
584
 
 
585
 
    sleep(60);
586
 
 
587
 
    if(!capturePackets) break; /* After */
588
 
 
589
 
#ifdef DEBUG
590
 
    traceEvent(TRACE_INFO, "Trying to update host traffic stats");
591
 
#endif
592
 
 
593
 
    actTime = time(NULL);
594
 
    strftime(theDate, 8, "%M", localtime_r(&actTime, &t));
595
 
    minuteId = atoi(theDate);
596
 
    strftime(theDate, 8, "%H", localtime_r(&actTime, &t));
597
 
    hourId = atoi(theDate);
598
 
    if((minuteId <= 1) && (hourId != lastUpdatedHour)) {
599
 
      lastUpdatedHour = hourId;
600
 
      accessMutex(&hostsHashMutex, "updateHostTrafficStatsThptLoop");
601
 
#ifdef DEBUG
602
 
      traceEvent(TRACE_INFO, "Updating host traffic stats\n");
603
 
#endif
604
 
      updateHostTrafficStatsThpt(hourId); /* Update Throughput */
605
 
      releaseMutex(&hostsHashMutex);
606
 
      nextUpdate = actTime+3600;
607
 
    }
608
 
  }
609
 
 
610
 
  return(NULL);
611
 
}
612
 
#endif
613
 
 
614
 
/* **************************************** */
615
 
 
616
 
#ifdef MULTITHREADED
617
 
void* updateDBHostsTrafficLoop(void* notUsed _UNUSED_) {
618
 
  u_short updateTime = DEFAULT_DB_UPDATE_TIME; /* This should be user configurable */
619
 
 
620
 
  for(;;) {
621
 
    int i;
622
 
 
623
 
#ifdef DEBUG
624
 
    traceEvent(TRACE_INFO, "Sleeping for %d seconds\n", updateTime);
625
 
#endif
626
 
 
627
 
    sleep(updateTime);
628
 
 
629
 
    if(!capturePackets) break;
630
 
 
631
 
    for(i=0; i<numDevices; i++)
632
 
      if(!device[i].virtualDevice) {
633
 
#ifdef MULTITHREADED
634
 
        accessMutex(&hostsHashMutex, "updateDbHostsTraffic");
635
 
#endif /* MULTITHREADED */
636
 
        updateDbHostsTraffic(i);
637
 
#ifdef MULTITHREADED
638
 
        releaseMutex(&hostsHashMutex);
639
 
#endif /* MULTITHREADED */
640
 
      }
641
 
  }
642
 
  return(NULL);
643
 
 
644
 
}
645
 
#endif
646
 
 
647
 
/* **************************************** */
648
 
 
649
 
void* scanIdleLoop(void* notUsed _UNUSED_) {
650
 
  for(;;) {
651
 
    int i;
652
 
 
653
 
    sleep(SESSION_SCAN_DELAY);
654
 
 
655
 
    if(!capturePackets) break;
656
 
    actTime = time(NULL);
657
 
    
658
 
    for(i=0; i<numDevices; i++)
659
 
      if(!device[i].virtualDevice) {
660
 
        purgeIdleHosts(0 /* Delete only idle hosts */, i);
661
 
#ifdef HAVE_SCHED_H
662
 
        sched_yield(); /* Allow other threads to run */
663
 
#else
664
 
        sleep(1); /* leave some time to others */
665
 
#endif
666
 
      }
667
 
 
668
 
    
669
 
    /* Remove !!!!!!!*/
670
 
    cleanupHostEntries();
671
 
  }
672
 
  
673
 
  return(NULL);
674
 
}
675
 
 
676
 
/* **************************************** */
677
 
 
678
 
void* cleanupExpiredHostEntriesLoop(void* notUsed _UNUSED_) {
679
 
  for(;;) {
680
 
    sleep(PURGE_ADDRESS_TIMEOUT);
681
 
    if(!capturePackets) break;
682
 
    actTime = time(NULL);    
683
 
    cleanupHostEntries();
684
 
  }
685
 
  
686
 
  return(NULL);
687
 
}
688
 
 
689
 
/* **************************************** */
690
 
 
691
 
void* scanIdleSessionsLoop(void* notUsed _UNUSED_) {
692
 
 
693
 
  for(;;) {
694
 
    sleep(SESSION_SCAN_DELAY);
695
 
 
696
 
    if(!capturePackets) break;
697
 
    actTime = time(NULL);
698
 
 
699
 
#ifdef MULTITHREADED
700
 
    accessMutex(&hostsHashMutex, "scanIdleSessionsLoop-1");
701
 
#endif
702
 
    scanTimedoutTCPSessions();
703
 
#ifdef MULTITHREADED
704
 
    releaseMutex(&hostsHashMutex);
705
 
#endif
706
 
 
707
 
#ifdef HAVE_SCHED_H
708
 
    sched_yield(); /* Allow other threads to run */
709
 
#else
710
 
    sleep(1); /* leave some time to others */
711
 
#endif
712
 
 
713
 
#ifdef MULTITHREADED
714
 
    accessMutex(&hostsHashMutex, "scanIdleSessionsLoop-2");
715
 
#endif
716
 
    purgeOldFragmentEntries();
717
 
#ifdef MULTITHREADED
718
 
    releaseMutex(&hostsHashMutex);
719
 
#endif
720
 
 
721
 
    if(handleRules)
722
 
      scanAllTcpExpiredRules();
723
 
  }
724
 
 
725
 
  return(NULL);
726
 
}
727
 
 
728
 
/* **************************************** */
729
 
 
730
 
#ifdef MULTITHREADED
731
 
void* periodicLsofLoop(void* notUsed _UNUSED_) {
732
 
  for(;;) {
733
 
    /*
734
 
      refresh process list each minute
735
 
      if needed
736
 
    */
737
 
 
738
 
    if(!capturePackets) break;
739
 
 
740
 
    if(updateLsof) {
741
 
#ifdef DEBUG
742
 
      traceEvent(TRACE_INFO, "Wait please: reading lsof information...\n");
743
 
#endif
744
 
      if(isLsofPresent) readLsofInfo();
745
 
#ifdef DEBUG
746
 
      traceEvent(TRACE_INFO, "Done with lsof.\n");
747
 
#endif
748
 
    }
749
 
    sleep(60);
750
 
  }
751
 
  return(NULL);
752
 
 
753
 
}
754
 
#endif
755
 
 
756
 
/* **************************************** */
757
 
 
758
 
#ifndef MULTITHREADED
759
 
void packetCaptureLoop(time_t *lastTime, int refreshRate) {
760
 
  int numPkts=0, pcap_fd = pcap_fileno(device[0].pcapPtr);
761
 
  fd_set readMask;
762
 
  struct timeval timeout;
763
 
 
764
 
  if((pcap_fd == -1) && (rFileName != NULL)) {
765
 
    /*
766
 
      This is a patch to overcome a bug of libpcap
767
 
      while reading from a traffic file instead
768
 
      of sniffying live from a NIC.
769
 
    */
770
 
    struct mypcap {
771
 
      int fd, snapshot, linktype, tzoff, offset;
772
 
      FILE *rfile;
773
 
 
774
 
      /* Other fields have been skipped. Please refer
775
 
         to pcap-int.h for the full datatype.
776
 
      */
777
 
    };
778
 
 
779
 
    pcap_fd = fileno(((struct mypcap *)(device[0].pcapPtr))->rfile);
780
 
  }
781
 
 
782
 
  for(;;) {
783
 
    short justRefreshed;
784
 
    int rc;
785
 
 
786
 
    if(!capturePackets) break;
787
 
 
788
 
    FD_ZERO(&readMask);
789
 
    if(pcap_fd != -1) FD_SET(pcap_fd, &readMask);
790
 
 
791
 
    timeout.tv_sec  = 5 /* seconds */;
792
 
    timeout.tv_usec = 0;
793
 
 
794
 
    if(select(pcap_fd+1, &readMask, NULL, NULL, &timeout) > 0) {
795
 
      rc = pcap_dispatch(device[0].pcapPtr, 1, processPacket, NULL);
796
 
 
797
 
      if(rc == -1) {
798
 
        traceEvent(TRACE_ERROR, "Error while reading packets: %s.\n",
799
 
                   pcap_geterr(device[0].pcapPtr));
800
 
        continue;
801
 
      } else if((rc == 0) && (rFileName != NULL)) {
802
 
        traceEvent(TRACE_INFO, "pcap_dispatch returned %d "
803
 
                   "[No more packets to read]", rc);
804
 
        pcap_fd = -1;
805
 
      }
806
 
    }
807
 
 
808
 
    actTime = time(NULL);
809
 
 
810
 
    if(actTime > (*lastTime)) {
811
 
      if(nextSessionTimeoutScan < actTime) {
812
 
        /* It's time to check for timeout sessions */
813
 
        scanTimedoutTCPSessions();
814
 
        nextSessionTimeoutScan = actTime+SESSION_SCAN_DELAY;
815
 
      }
816
 
 
817
 
      if(handleRules)
818
 
        scanAllTcpExpiredRules();
819
 
      updateThpt(); /* Update Throughput */
820
 
      (*lastTime) = actTime + THROUGHPUT_REFRESH_TIME;
821
 
      justRefreshed=1;
822
 
    } else
823
 
      justRefreshed=0;
824
 
 
825
 
    handleWebConnections(NULL);
826
 
  } /* for(;;) */
827
 
}
828
 
#endif
829
 
 
830
 
/* **************************************** */
831
 
 
832
 
/* Report statistics and write out the raw packet file */
833
 
RETSIGTYPE cleanup(int signo) {
834
 
  static int unloaded = 0;
835
 
  struct pcap_stat stat;
836
 
  int i;
837
 
 
838
 
  if(unloaded)
839
 
    return;
840
 
  else
841
 
    unloaded = 1;
842
 
 
843
 
  traceEvent(TRACE_INFO, "Cleaning up...");
844
 
  
845
 
  capturePackets = 0;
846
 
 
847
 
#ifndef WIN32
848
 
#ifdef MULTITHREADED
849
 
  killThread(&dequeueThreadId);
850
 
  killThread(&thptUpdateThreadId);
851
 
  killThread(&hostTrafficStatsThreadId);
852
 
 
853
 
  if(rFileName == NULL) {
854
 
    killThread(&scanIdleThreadId);
855
 
    killThread(&scanIdleSessionsThreadId);
856
 
  }
857
 
 
858
 
  if(enableDBsupport)
859
 
    killThread(&dbUpdateThreadId);
860
 
  
861
 
  if(isLsofPresent)
862
 
    killThread(&lsofThreadId);
863
 
  
864
 
#ifdef ASYNC_ADDRESS_RESOLUTION
865
 
  if(numericFlag == 0) {
866
 
    killThread(&dequeueAddressThreadId);
867
 
    killThread(&purgeAddressThreadId);
868
 
  }
869
 
#endif
870
 
  
871
 
  killThread(&handleWebConnectionsThreadId);
872
 
  
873
 
#ifdef FULL_MEMORY_FREE
874
 
  cleanupAddressQueue();
875
 
  cleanupPacketQueue();
876
 
#endif
877
 
#endif
878
 
 
879
 
#else /* #ifndef WIN32 */
880
 
 
881
 
  /*
882
 
    TW 06.11.2001 
883
 
    Wies-Software <wies@wiessoft.de>
884
 
    
885
 
    #else clause added to force dequeue threads to terminate
886
 
    USE_SEMAPHORES is *NOT* tested!!!
887
 
  */
888
 
#ifdef MULTITHREADED
889
 
#ifdef USE_SEMAPHORES
890
 
  incrementSem(&queueSem);
891
 
#ifdef ASYNC_ADDRESS_RESOLUTION
892
 
  incrementSem(&queueAddressSem);
893
 
#endif
894
 
#else
895
 
  signalCondvar(&queueCondvar);
896
 
#ifdef ASYNC_ADDRESS_RESOLUTION
897
 
  signalCondvar(&queueAddressCondvar);
898
 
#endif
899
 
#endif
900
 
#endif /* MULTITREADED */
901
 
#endif /* #ifndef WIN32 */
902
 
  
903
 
#ifdef MULTITHREADED
904
 
  traceEvent(TRACE_INFO, "Waiting until threads terminate...\n");
905
 
  sleep(3); /* Just to wait until threads complete */
906
 
#endif
907
 
 
908
 
/* #ifdef FULL_MEMORY_FREE */
909
 
  freeHostInstances();
910
 
/* #endif */
911
 
 
912
 
#ifndef MICRO_NTOP
913
 
  unloadPlugins();
914
 
#endif
915
 
  termLogger();
916
 
  (void)fflush(stdout);
917
 
 
918
 
  termIPServices();
919
 
  termIPSessions();
920
 
  termNetFlowExporter();
921
 
  termPassiveSessions();
922
 
  
923
 
#ifndef WIN32
924
 
  endservent();
925
 
#endif
926
 
 
927
 
#ifdef MULTITHREADED
928
 
  deleteMutex(&packetQueueMutex);
929
 
  deleteMutex(&addressResolutionMutex);
930
 
  deleteMutex(&hashResizeMutex);
931
 
  deleteMutex(&hostsHashMutex);
932
 
  deleteMutex(&graphMutex);
933
 
  if(isLsofPresent)
934
 
    deleteMutex(&lsofMutex);
935
 
#ifdef USE_SEMAPHORES
936
 
  deleteSem(&queueSem);
937
 
#ifdef ASYNC_ADDRESS_RESOLUTION
938
 
  deleteSem(&queueAddressSem);
939
 
#endif
940
 
#else
941
 
  deleteCondvar(&queueCondvar);
942
 
#ifdef ASYNC_ADDRESS_RESOLUTION
943
 
  deleteCondvar(&queueAddressCondvar);
944
 
#endif
945
 
#endif
946
 
#endif
947
 
 
948
 
#ifdef HAVE_GDBM_H
949
 
#ifdef MULTITHREADED
950
 
  accessMutex(&gdbmMutex, "cleanup");
951
 
#endif 
952
 
  gdbm_close(gdbm_file);     gdbm_file = NULL;
953
 
  gdbm_close(pwFile);        pwFile = NULL;
954
 
  /* Courtesy of Wies-Software <wies@wiessoft.de> */
955
 
  gdbm_close(hostsInfoFile); hostsInfoFile = NULL; 
956
 
  if(eventFile != NULL) {
957
 
    gdbm_close(eventFile);
958
 
    eventFile = NULL;
959
 
  }
960
 
#ifdef MULTITHREADED
961
 
  releaseMutex(&gdbmMutex);
962
 
#endif
963
 
 
964
 
#ifdef MULTITHREADED
965
 
  deleteMutex(&gdbmMutex);
966
 
#endif
967
 
#endif
968
 
  
969
 
  for(i=0; i<numDevices; i++) {
970
 
    int j;
971
 
      
972
 
    traceEvent(TRACE_INFO, "Freeing device %s (idx=%d)...", device[i].name, i);
973
 
 
974
 
    if(!device[i].virtualDevice) {
975
 
      if (pcap_stats(device[i].pcapPtr, &stat) >= 0) {
976
 
        traceEvent(TRACE_INFO, "%s packets received by filter on %s\n",
977
 
                   formatPkts((TrafficCounter)stat.ps_recv), device[i].name);
978
 
        traceEvent(TRACE_INFO, "%s packets dropped by kernel\n",
979
 
                   formatPkts((TrafficCounter)(stat.ps_drop)));
980
 
#ifdef MULTITHREADED
981
 
        traceEvent(TRACE_INFO, "%s packets dropped by ntop\n",
982
 
                   formatPkts(device[i].droppedPkts));
983
 
#endif
984
 
      }
985
 
    }
986
 
 
987
 
    if(device[i].ipTrafficMatrix != NULL) {
988
 
 
989
 
      /* Courtesy of Wies-Software <wies@wiessoft.de> */
990
 
      for(j=0; j<(device[i].numHosts*device[i].numHosts); j++)
991
 
        if(device[i].ipTrafficMatrix[j] != NULL) 
992
 
          free(device[i].ipTrafficMatrix[j]);
993
 
      
994
 
      free(device[i].ipTrafficMatrix);
995
 
    }
996
 
      
997
 
    if(device[i].ipTrafficMatrix != NULL) 
998
 
      free(device[i].ipTrafficMatrix);
999
 
 
1000
 
    if(device[i].ipTrafficMatrixHosts != NULL) 
1001
 
      free(device[i].ipTrafficMatrixHosts);
1002
 
 
1003
 
    if(device[i].ipProtoStats != NULL)
1004
 
      free(device[i].ipProtoStats);
1005
 
      
1006
 
    if(device[i].hash_hostTraffic != NULL)
1007
 
      free(device[i].hash_hostTraffic);
1008
 
      
1009
 
    if(device[i].tcpSession != NULL)
1010
 
      free(device[i].tcpSession);
1011
 
 
1012
 
    free(device[i].name);
1013
 
 
1014
 
    if(device[i].pcapDumper != NULL)
1015
 
      pcap_dump_close(device[i].pcapDumper);
1016
 
      
1017
 
    if(device[i].pcapErrDumper != NULL)
1018
 
      pcap_dump_close(device[i].pcapErrDumper);
1019
 
      
1020
 
    /* 
1021
 
       Wies-Software <wies@wiessoft.de> on 06/11/2001 says:
1022
 
       device[i].pcapPtr seems to be already freed. further tests needed! 
1023
 
    */
1024
 
    if(device[i].pcapPtr != NULL)
1025
 
      free(device[i].pcapPtr);
1026
 
  }
1027
 
 
1028
 
  free(device);
1029
 
 
1030
 
  if(numProcesses > 0)
1031
 
    free(processes);
1032
 
  
1033
 
  if(enableDBsupport) {
1034
 
    closeSQLsocket(); /* *** SQL Engine *** */
1035
 
#ifdef HAVE_MYSQL
1036
 
    closemySQLsocket();
1037
 
#endif
1038
 
  }
1039
 
 
1040
 
#ifdef WIN32
1041
 
  termWinsock32();
1042
 
#endif
1043
 
 
1044
 
  endNtop = 1;
1045
 
 
1046
 
#ifdef MEMORY_DEBUG
1047
 
  traceEvent(TRACE_INFO, "===================================\n");
1048
 
  termLeaks();
1049
 
  traceEvent(TRACE_INFO, "===================================\n");
1050
 
#endif
1051
 
  exit(0);
1052
 
}