File: initialize.c

package info (click to toggle)
ntop 3:3.3-11
  • links: PTS
  • area: main
  • in suites: lenny
  • size: 12,772 kB
  • ctags: 7,534
  • sloc: ansic: 71,427; sh: 16,772; awk: 1,504; perl: 792; makefile: 782; php: 123; python: 23; sql: 13; sed: 11
file content (1953 lines) | stat: -rw-r--r-- 70,372 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
/*
 * -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
 *                          http://www.ntop.org
 *
 * Copyright (C) 1998-2007 Luca Deri <deri@ntop.org>
 *
 * -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */


#include "ntop.h"
#include "globals-report.h"

static void initIPCountryTable(void); /* Forward */

/*
 * calculate the domain name for this host
 */
static void setDomainName(void) {
  int len;

#ifndef WIN32
  char *p;

  /*
   * The name of the local domain is now calculated properly
   * Kimmo Suominen <kim@tac.nyc.ny.us>
   */
  if(myGlobals.runningPref.domainName[0] == '\0') {
    if((getdomainname(myGlobals.runningPref.domainName, MAXHOSTNAMELEN) != 0)
       || (myGlobals.runningPref.domainName[0] == '\0')
       || (strcmp(myGlobals.runningPref.domainName, "(none)") == 0)) {
      if((gethostname(myGlobals.runningPref.domainName, MAXHOSTNAMELEN) == 0)
	 && ((p = memchr(myGlobals.runningPref.domainName, '.', MAXHOSTNAMELEN)) != NULL)) {
	myGlobals.runningPref.domainName[MAXHOSTNAMELEN - 1] = '\0';
	++p;
	memmove(myGlobals.runningPref.domainName, p, (MAXHOSTNAMELEN+myGlobals.runningPref.domainName-p));
      } else
	myGlobals.runningPref.domainName[0] = '\0';
    }

    /*
     * Still unresolved! Try again
     */
    if(myGlobals.runningPref.domainName[0] == '\0') {
      char szLclHost[64];
      struct hostent *lpstHostent;
      struct in_addr stLclAddr;

      gethostname(szLclHost, 64);
      lpstHostent = gethostbyname(szLclHost);
      if(lpstHostent) {
	struct hostent *hp;

	stLclAddr.s_addr = ntohl(*(lpstHostent->h_addr));

	hp = (struct hostent*)gethostbyaddr((char*)lpstHostent->h_addr, 4, AF_INET);

	if(hp && (hp->h_name)) {
	  char *dotp = (char*) hp->h_name;
	  int i;

	  for(i=0; (dotp[i] != '\0') && (dotp[i] != '.'); i++)
	    ;

	  if(dotp[i] == '.')
	    strncpy(myGlobals.runningPref.domainName, &dotp[i+1], MAXHOSTNAMELEN);
	}
      }
    }

    if(myGlobals.runningPref.domainName[0] == '\0') {
      /* Last chance.... */
      /* strncpy(myGlobals.runningPref.domainName, "please_set_your_local_domain.org", MAXHOSTNAMELEN); */
      ;
    }
  }
#endif

  len = strlen(myGlobals.runningPref.domainName)-1;

  while((len > 0) && (myGlobals.runningPref.domainName[len] != '.'))
    len--;

  if((len > 0) 
     && ((len+1) <  strlen(myGlobals.runningPref.domainName)))
    myGlobals.shortDomainName = strdup(&myGlobals.runningPref.domainName[len+1]);
  else
    myGlobals.shortDomainName = strdup(myGlobals.runningPref.domainName);
}

/* ------------------------------------------------------------ */

/*
 * Initialize memory/data for the protocols being monitored
 * looking at local or system wide "services" files
 */
void initIPServices(void) {
  FILE* fd;
  int idx, numSlots, len;

  traceEvent(CONST_TRACE_NOISY, "Initializing IP services");


  /* Let's count the entries first */
  numSlots = 0;
  for(idx=0; myGlobals.configFileDirs[idx] != NULL; idx++) {
    char tmpStr[256];

    safe_snprintf(__FILE__, __LINE__, tmpStr, sizeof(tmpStr), "%s/services", myGlobals.configFileDirs[idx]);
    fd = fopen(tmpStr, "r");

    if(fd != NULL) {
      char tmpLine[512];

      while(fgets(tmpLine, 512, fd))
	if((tmpLine[0] != '#') && (strlen(tmpLine) > 10)) {
	  /* discard  9/tcp sink null */
	  numSlots++;
	}
      fclose(fd);
    }
  }

  if(numSlots == 0) numSlots = CONST_HASH_INITIAL_SIZE;

  myGlobals.numActServices = 2*numSlots; /* Double the hash */

  /* ************************************* */

  len = sizeof(ServiceEntry*)*myGlobals.numActServices;
  myGlobals.udpSvc = (ServiceEntry**)malloc(len);
  memset(myGlobals.udpSvc, 0, len);
  myGlobals.tcpSvc = (ServiceEntry**)malloc(len);
  memset(myGlobals.tcpSvc, 0, len);

  for(idx=0; myGlobals.configFileDirs[idx] != NULL; idx++) {
    char tmpStr[64];

    safe_snprintf(__FILE__, __LINE__, tmpStr, sizeof(tmpStr), "%s/services", myGlobals.configFileDirs[idx]);
    fd = fopen(tmpStr, "r");

    if(fd != NULL) {
      char tmpLine[512];

      while(fgets(tmpLine, 512, fd))
	if((tmpLine[0] != '#') && (strlen(tmpLine) > 10)) {
	  /* discard  9/tcp sink null */
	  char name[64], proto[16];
	  int numPort;

	  /* Fix below courtesy of Andreas Pfaller <apfaller@yahoo.com.au> */
	  if(3 == sscanf(tmpLine, "%63[^ \t] %d/%15s", name, &numPort, proto)) {
	    /* traceEvent(CONST_TRACE_INFO, "'%s' - '%s' - '%d'", name, proto, numPort); */

	    if(strcmp(proto, "tcp") == 0)
	      addPortHashEntry(myGlobals.tcpSvc, numPort, name);
	    else
	      addPortHashEntry(myGlobals.udpSvc, numPort, name);
	  }
	}
      fclose(fd);
      break;
    }
  }

  /* Add some basic services, just in case they
     are not included in /etc/services */
  addPortHashEntry(myGlobals.tcpSvc, 21,  "ftp");
  addPortHashEntry(myGlobals.tcpSvc, 20,  "ftp-data");
  addPortHashEntry(myGlobals.tcpSvc, 23,  "telnet");
  addPortHashEntry(myGlobals.tcpSvc, 42,  "name");
  addPortHashEntry(myGlobals.tcpSvc, 80,  "http");
  addPortHashEntry(myGlobals.tcpSvc, 443, "https");

  addPortHashEntry(myGlobals.udpSvc, 137, "netbios-ns");
  addPortHashEntry(myGlobals.tcpSvc, 137, "netbios-ns");
  addPortHashEntry(myGlobals.udpSvc, 138, "netbios-dgm");
  addPortHashEntry(myGlobals.tcpSvc, 138, "netbios-dgm");
  addPortHashEntry(myGlobals.udpSvc, 139, "netbios-ssn");
  addPortHashEntry(myGlobals.tcpSvc, 139, "netbios-ssn");

  addPortHashEntry(myGlobals.tcpSvc, 109, "pop-2");
  addPortHashEntry(myGlobals.tcpSvc, 110, "pop-3");
  addPortHashEntry(myGlobals.tcpSvc, 1109,"kpop");

  addPortHashEntry(myGlobals.udpSvc, 161, "snmp");
  addPortHashEntry(myGlobals.udpSvc, 162, "snmp-trap");
  addPortHashEntry(myGlobals.udpSvc, 635, "mount");
  addPortHashEntry(myGlobals.udpSvc, 640, "pcnfs");
  addPortHashEntry(myGlobals.udpSvc, 650, "bwnfs");
  addPortHashEntry(myGlobals.udpSvc, 2049,"nfsd");
  addPortHashEntry(myGlobals.udpSvc, 1110,"nfsd-status");
}

/* ******************************* */

static void initIPCountryTable(void) {
  u_char compressedFormat;
  char buf[LEN_GENERAL_WORK_BUFFER];
  FILE* fd;

  myGlobals.ipCountryCount = 0;
  if((myGlobals.countryFlagHead = malloc(sizeof(IPNode))) == NULL) {
    traceEvent(CONST_TRACE_FATALERROR, "IP2CC: Unable to allocate table memory. Quitting...");
    exit(4); /* Just in case */
  }
  myGlobals.ipCountryMem += sizeof(IPNode);

  strcpy(myGlobals.countryFlagHead->node.cc, "***");

  myGlobals.countryFlagHead->b[0]=NULL;
  myGlobals.countryFlagHead->b[1]=NULL;

  if (!myGlobals.runningPref.printFcOnly) {
    fd=checkForInputFile("IP2CC",
			 "IP address <-> Country Code mapping",
			 CONST_P2C_FILE,
			 NULL,
			 &compressedFormat);
      if(fd != NULL) {
          char *strtokState, *cc, *ip, *prefix;
          int numRead=0;

          while(readInputFile(fd,
                              "IP2CC",
                              FALSE,
                              compressedFormat,
			      10000,
                              buf, sizeof(buf),
                              &numRead) == 0) {
              if((cc=strtok_r(buf, ":", &strtokState))       == NULL) continue;
              if((ip=strtok_r(NULL, "/", &strtokState))      == NULL) continue;
              if((prefix=strtok_r(NULL, "\n", &strtokState)) == NULL) continue;

              strtolower(cc);

              if(addNodeInternal(xaton(ip), atoi(prefix), cc, 0) == NULL) {
                traceEvent(CONST_TRACE_FATALERROR,
                           "IP2CC: Insufficient memory to load table");
                /* This isn't fatal of an itself, but we'll fail every malloc() from here on ... */
                exit(5); /* Just in case */
              }
          }

          myGlobals.ipCountryCount += numRead;
      } else {
          traceEvent(CONST_TRACE_WARNING,
                     "IP2CC: Unable to read IP address <-> Country code mapping file (non-existant or no data)");
          traceEvent(CONST_TRACE_INFO,
                     "IP2CC: ntop will perform correctly but without this minor feature");
      }
  }
}

/* ******************************* */

void createDeviceIpProtosList(int devIdx) {
  size_t len = (size_t)myGlobals.numIpProtosList*sizeof(TrafficCounter);

  if(len > 0) {
    if(myGlobals.device[devIdx].ipProtosList != NULL)
      free(myGlobals.device[devIdx].ipProtosList);
    if((myGlobals.device[devIdx].ipProtosList = (TrafficCounter*)malloc(len)) == NULL)
      return;
    memset(myGlobals.device[devIdx].ipProtosList, 0, len);
  }
}

/* ******************************* */

/*
  Function below courtesy of
  Eric Dumazet <dada1@cosmosbay.com>
*/
void resetDevice(int devIdx, short fullReset) {
  int len;
  void *ptr;

  if(myGlobals.device[devIdx].dummyDevice) return;

  myGlobals.device[devIdx].actualHashSize = CONST_HASH_INITIAL_SIZE;

  len = CONST_HASH_INITIAL_SIZE * sizeof(HostTraffic*);
  if(myGlobals.device[devIdx].hash_hostTraffic == NULL) {
    ptr = calloc(CONST_HASH_INITIAL_SIZE, sizeof(HostTraffic*));
    myGlobals.device[devIdx].hash_hostTraffic = ptr;
  }

  memset(myGlobals.device[devIdx].hash_hostTraffic, 0, len);

  resetTrafficCounter(&myGlobals.device[devIdx].receivedPkts);
  resetTrafficCounter(&myGlobals.device[devIdx].droppedPkts);
  resetTrafficCounter(&myGlobals.device[devIdx].ethernetPkts);
  resetTrafficCounter(&myGlobals.device[devIdx].broadcastPkts);
  resetTrafficCounter(&myGlobals.device[devIdx].multicastPkts);
  resetTrafficCounter(&myGlobals.device[devIdx].ipPkts);
  resetTrafficCounter(&myGlobals.device[devIdx].ethernetBytes);
  resetTrafficCounter(&myGlobals.device[devIdx].ipBytes);
  resetTrafficCounter(&myGlobals.device[devIdx].fragmentedIpBytes);
  resetTrafficCounter(&myGlobals.device[devIdx].tcpBytes);
  resetTrafficCounter(&myGlobals.device[devIdx].udpBytes);
  resetTrafficCounter(&myGlobals.device[devIdx].otherIpBytes);
  resetTrafficCounter(&myGlobals.device[devIdx].icmpBytes);
  resetTrafficCounter(&myGlobals.device[devIdx].dlcBytes);
  resetTrafficCounter(&myGlobals.device[devIdx].ipxBytes);
  resetTrafficCounter(&myGlobals.device[devIdx].stpBytes);
  resetTrafficCounter(&myGlobals.device[devIdx].decnetBytes);
  resetTrafficCounter(&myGlobals.device[devIdx].netbiosBytes);
  resetTrafficCounter(&myGlobals.device[devIdx].arpRarpBytes);
  resetTrafficCounter(&myGlobals.device[devIdx].atalkBytes);
  resetTrafficCounter(&myGlobals.device[devIdx].egpBytes);
  resetTrafficCounter(&myGlobals.device[devIdx].osiBytes);
  resetTrafficCounter(&myGlobals.device[devIdx].ipv6Bytes);
  resetTrafficCounter(&myGlobals.device[devIdx].otherBytes);
  resetTrafficCounter(&myGlobals.device[devIdx].fcBytes);
  resetTrafficCounter(&myGlobals.device[devIdx].fragmentedFcBytes);
  resetTrafficCounter(&myGlobals.device[devIdx].fcFcpBytes);
  resetTrafficCounter(&myGlobals.device[devIdx].fcFiconBytes);
  resetTrafficCounter(&myGlobals.device[devIdx].fcIpfcBytes);
  resetTrafficCounter(&myGlobals.device[devIdx].fcSwilsBytes);
  resetTrafficCounter(&myGlobals.device[devIdx].fcDnsBytes);
  resetTrafficCounter(&myGlobals.device[devIdx].fcElsBytes);
  resetTrafficCounter(&myGlobals.device[devIdx].otherFcBytes);
  resetTrafficCounter(&myGlobals.device[devIdx].class2Bytes);
  resetTrafficCounter(&myGlobals.device[devIdx].class3Bytes);
  resetTrafficCounter(&myGlobals.device[devIdx].classFBytes);
  resetTrafficCounter(&myGlobals.device[devIdx].lastMinEthernetBytes);
  resetTrafficCounter(&myGlobals.device[devIdx].lastFiveMinsEthernetBytes);
  resetTrafficCounter(&myGlobals.device[devIdx].lastMinEthernetPkts);
  resetTrafficCounter(&myGlobals.device[devIdx].lastFiveMinsEthernetPkts);
  resetTrafficCounter(&myGlobals.device[devIdx].lastNumEthernetPkts);
  resetTrafficCounter(&myGlobals.device[devIdx].lastEthernetPkts);
  resetTrafficCounter(&myGlobals.device[devIdx].lastTotalPkts);
  resetTrafficCounter(&myGlobals.device[devIdx].lastBroadcastPkts);
  resetTrafficCounter(&myGlobals.device[devIdx].lastMulticastPkts);
  resetTrafficCounter(&myGlobals.device[devIdx].lastEthernetBytes);
  resetTrafficCounter(&myGlobals.device[devIdx].lastIpBytes);
  resetTrafficCounter(&myGlobals.device[devIdx].lastNonIpBytes);
  resetTrafficCounter(&myGlobals.device[devIdx].fcPkts);
  resetTrafficCounter(&myGlobals.device[devIdx].fcEofaPkts);
  resetTrafficCounter(&myGlobals.device[devIdx].fcEofAbnormalPkts);
  resetTrafficCounter(&myGlobals.device[devIdx].fcAbnormalPkts);
  resetTrafficCounter(&myGlobals.device[devIdx].fcBroadcastPkts);
  memset(&myGlobals.device[devIdx].rcvdPktStats, 0, sizeof(PacketStats));
  memset(&myGlobals.device[devIdx].rcvdFcPktStats, 0, sizeof(FcPacketStats));
  memset(&myGlobals.device[devIdx].rcvdPktTTLStats, 0, sizeof(TTLstats));
  myGlobals.device[devIdx].peakThroughput = 0;
  myGlobals.device[devIdx].actualThpt = 0;
  myGlobals.device[devIdx].lastMinThpt = 0;
  myGlobals.device[devIdx].lastFiveMinsThpt = 0;
  myGlobals.device[devIdx].peakPacketThroughput = 0;
  myGlobals.device[devIdx].actualPktsThpt = 0;
  myGlobals.device[devIdx].lastMinPktsThpt = 0;
  myGlobals.device[devIdx].lastFiveMinsPktsThpt = 0;
  myGlobals.device[devIdx].lastThptUpdate = 0;
  myGlobals.device[devIdx].lastMinThptUpdate = 0;
  myGlobals.device[devIdx].lastHourThptUpdate = 0;
  myGlobals.device[devIdx].lastFiveMinsThptUpdate = 0;
  myGlobals.device[devIdx].throughput = 0;
  myGlobals.device[devIdx].packetThroughput = 0;
  myGlobals.device[devIdx].numThptSamples = 0;
  myGlobals.device[devIdx].last60MinutesThptIdx = 0;
  myGlobals.device[devIdx].last24HoursThptIdx = 0;
  myGlobals.device[devIdx].last30daysThptIdx = 0;
  myGlobals.device[devIdx].hostsno = 0;

  if(myGlobals.runningPref.rFileName == NULL) {
    myGlobals.device[devIdx].lastThptUpdate = myGlobals.device[devIdx].lastMinThptUpdate =
      myGlobals.device[devIdx].lastHourThptUpdate = myGlobals.device[devIdx].lastFiveMinsThptUpdate = time(NULL);
  }
  resetTrafficCounter(&myGlobals.device[devIdx].lastMinEthernetBytes);
  resetTrafficCounter(&myGlobals.device[devIdx].lastFiveMinsEthernetBytes);
  memset(&myGlobals.device[devIdx].tcpGlobalTrafficStats, 0, sizeof(SimpleProtoTrafficInfo));
  memset(&myGlobals.device[devIdx].udpGlobalTrafficStats, 0, sizeof(SimpleProtoTrafficInfo));
  memset(&myGlobals.device[devIdx].icmpGlobalTrafficStats, 0, sizeof(SimpleProtoTrafficInfo));
  memset(myGlobals.device[devIdx].last60MinutesThpt, 0, sizeof(myGlobals.device[devIdx].last60MinutesThpt));
  memset(myGlobals.device[devIdx].last24HoursThpt, 0, sizeof(myGlobals.device[devIdx].last24HoursThpt));
  memset(myGlobals.device[devIdx].last30daysThpt, 0, sizeof(myGlobals.device[devIdx].last30daysThpt));
  myGlobals.device[devIdx].last60MinutesThptIdx=0, myGlobals.device[devIdx].last24HoursThptIdx=0,
    myGlobals.device[devIdx].last30daysThptIdx=0;
  myGlobals.device[devIdx].hostsno = 1; /* Broadcast entry */

  if(fullReset) {
    if(myGlobals.device[devIdx].netflowGlobals != NULL)
      free(myGlobals.device[devIdx].netflowGlobals);
    myGlobals.device[devIdx].netflowGlobals = NULL;
    
    if(myGlobals.device[devIdx].sflowGlobals != NULL)
      free(myGlobals.device[devIdx].sflowGlobals);
    myGlobals.device[devIdx].sflowGlobals = NULL;
  }
  
  len = (size_t)myGlobals.numIpProtosToMonitor*sizeof(SimpleProtoTrafficInfo);

  if(myGlobals.device[devIdx].ipProtoStats == NULL)
    myGlobals.device[devIdx].ipProtoStats = (SimpleProtoTrafficInfo*)malloc(len);

  memset(myGlobals.device[devIdx].ipProtoStats, 0, len);

  if(myGlobals.device[devIdx].ipProtosList != NULL) {
    free(myGlobals.device[devIdx].ipProtosList);
    myGlobals.device[devIdx].ipProtosList = NULL;
  }

  createDeviceIpProtosList(devIdx);
}

/* ******************************************* */

void initCounters(void) {
  int len, i;
  FILE* fd;
  int numRead = 0;
  u_char compressedFormat;
  char buf[LEN_GENERAL_WORK_BUFFER];
#ifdef MAKE_WITH_I18N
  char *workLanguage;
#ifdef HAVE_DIRENT_H
  struct dirent **dirList;
  int j, iLang, nLang, found;
  DIR *testDirEnt;
  char *tmpStr;
  char* realLocale;
#endif
#endif

  setDomainName();

#ifdef INET6
  _in6addr_linklocal_allnodes.s6_addr[0] = 0xff;
  _in6addr_linklocal_allnodes.s6_addr[1] = 0x02;
  _in6addr_linklocal_allnodes.s6_addr[2] = 0x00;
  _in6addr_linklocal_allnodes.s6_addr[3] = 0x00;
  _in6addr_linklocal_allnodes.s6_addr[4] = 0x00;
  _in6addr_linklocal_allnodes.s6_addr[5] = 0x00;
  _in6addr_linklocal_allnodes.s6_addr[6] = 0x00;
  _in6addr_linklocal_allnodes.s6_addr[7] = 0x00;
  _in6addr_linklocal_allnodes.s6_addr[8] = 0x00;
  _in6addr_linklocal_allnodes.s6_addr[9] = 0x00;
  _in6addr_linklocal_allnodes.s6_addr[10] = 0x00;
  _in6addr_linklocal_allnodes.s6_addr[11] = 0x00;
  _in6addr_linklocal_allnodes.s6_addr[12] = 0x00;
  _in6addr_linklocal_allnodes.s6_addr[13] = 0x00;
  _in6addr_linklocal_allnodes.s6_addr[14] = 0x00;
  _in6addr_linklocal_allnodes.s6_addr[15] = 0x01;
#endif

  memset(myGlobals.transTimeHash, 0, sizeof(myGlobals.transTimeHash));
  memset(myGlobals.dummyEthAddress, 0, LEN_ETHERNET_ADDRESS);

  for(len=0; len<LEN_ETHERNET_ADDRESS; len++)
    myGlobals.dummyEthAddress[len] = len;

  for(i=0; i<myGlobals.numDevices; i++) {
    if(myGlobals.runningPref.enableSessionHandling) {
      len = sizeof(IPSession*)*MAX_TOT_NUM_SESSIONS;
      myGlobals.device[i].tcpSession = (IPSession**)malloc(len);
      memset(myGlobals.device[i].tcpSession, 0, len);

      len = sizeof(FCSession *)*MAX_TOT_NUM_SESSIONS;
      myGlobals.device[i].fcSession = (FCSession **)malloc(len);
      memset(myGlobals.device[i].fcSession, 0, len);
    } else {
      myGlobals.device[i].tcpSession     = NULL;
      myGlobals.device[i].fcSession      = NULL;
    }

    myGlobals.device[i].fragmentList = NULL;
  }

  myGlobals.ipxsapHashLoadCollisions = 0;
  myGlobals.hashCollisionsLookup     = 0;

  myGlobals.numVendorLookupRead = 0;
  myGlobals.numVendorLookupAdded = 0;
  myGlobals.numVendorLookupAddedSpecial = 0;
  myGlobals.numVendorLookupCalls = 0;
  myGlobals.numVendorLookupSpecialCalls = 0;
  myGlobals.numVendorLookupFound48bit = 0;
  myGlobals.numVendorLookupFound24bit = 0;
  myGlobals.numVendorLookupFoundMulticast = 0;
  myGlobals.numVendorLookupFoundLAA = 0;

  if (myGlobals.runningPref.rFileName == NULL) {
      myGlobals.initialSniffTime = myGlobals.lastRefreshTime = time(NULL);
  }
  else {
      myGlobals.initialSniffTime = 0; /* We set the start when first pkt is
                                       * read */
  }

/* TODO why here AND in globals-core.c? */
  myGlobals.numHandledSIGPIPEerrors = 0;
  for (i=0; i<=1; i++) {
    myGlobals.numHandledRequests[i] = 0;
    myGlobals.numHandledBadrequests[i] = 0;
    myGlobals.numSuccessfulRequests[i] = 0;
    myGlobals.numUnsuccessfulInvalidrequests[i] = 0;
    myGlobals.numUnsuccessfulInvalidmethod[i] = 0;
    myGlobals.numUnsuccessfulInvalidversion[i] = 0;
    myGlobals.numUnsuccessfulTimeout[i] = 0;
    myGlobals.numUnsuccessfulNotfound[i] = 0;
    myGlobals.numUnsuccessfulDenied[i] = 0;
    myGlobals.numUnsuccessfulForbidden[i] = 0;
  }
  myGlobals.numSSIRequests = 0;
  myGlobals.numBadSSIRequests = 0;
  myGlobals.numHandledSSIRequests = 0;

  myGlobals.webServerRequestQueueLength = DEFAULT_WEBSERVER_REQUEST_QUEUE_LEN;

  myGlobals.hostsCacheLen = 0;
  myGlobals.hostsCacheLenMax = 0;
  myGlobals.hostsCacheReused = 0;
#ifdef PARM_USE_SESSIONS_CACHE
  myGlobals.sessionsCacheLen = 0;
  myGlobals.sessionsCacheLenMax = 0;
  myGlobals.sessionsCacheReused = 0;
#endif

  /*
   * Process ASN file
   */
  numRead=0;
  myGlobals.haveASN = FALSE;
  if (!myGlobals.runningPref.printFcOnly) {
      fd=checkForInputFile("ASN",
                           "Autonomous System Number table",
                           CONST_ASLIST_FILE,
                           NULL,
                           &compressedFormat);
      if(fd != NULL) {
          char *strtokState, *as, *ip, *prefix;

          memset(&buf, 0, sizeof(buf));

          myGlobals.asHead = malloc(sizeof(IPNode));
          memset(myGlobals.asHead, 0, sizeof(IPNode));
          myGlobals.asHead->node.as = 0;
          myGlobals.asMem += sizeof(IPNode);

          while(readInputFile(fd,
                              "ASN",
                              FALSE,
                              compressedFormat,
                              25000,
                              buf, sizeof(buf),
                              &numRead) == 0) {

              if((as = strtok_r(buf, ":", &strtokState)) == NULL)  continue;
              if((ip = strtok_r(NULL, "/", &strtokState)) == NULL)  continue;
              if((prefix = strtok_r(NULL, "\n", &strtokState)) == NULL)  continue;

              if(addNodeInternal(xaton(ip), atoi(prefix), NULL, atoi(as)) == NULL) {
                traceEvent(CONST_TRACE_FATALERROR,
                           "ASN: Insufficient memory to load table");
                /* This isn't fatal of an itself, but we'll fail every malloc() from here on ... */
                exit(6); /* Just in case */
              }

              myGlobals.asCount++;
          }
          traceEvent(CONST_TRACE_INFO, "ASN: ....Used %d KB of memory (%d per entry)",
                     ((myGlobals.asMem+512)/1024), (int)sizeof(IPNode));
          myGlobals.haveASN = TRUE;
      } else
          traceEvent(CONST_TRACE_NOISY, "ASN: ntop continues ok, but without ASN information.");
  }
  /* i18n */
#ifdef MAKE_WITH_I18N
  /*
   *  Obtain - from the os - the default locale.
   */
  workLanguage = setlocale(LC_ALL, "");
  if(workLanguage != NULL ) {
#ifdef I18N_DEBUG
    traceEvent(CONST_TRACE_NOISY,
	       "I18N: Default language (from ntop host) is '%s' (raw)\n",
	       workLanguage);
#endif
    myGlobals.defaultLanguage = i18n_xvert_locale2common(workLanguage);
    traceEvent(CONST_TRACE_INFO,
	       "I18N: Default language (from ntop host) is '%s'\n",
	       myGlobals.defaultLanguage);
  } else {
    traceEvent(CONST_TRACE_INFO,
	       "I18N: Default language (from ntop host) is unspecified\n");
    myGlobals.defaultLanguage = NULL;
  }

  /*
   *  We initialize the array, myGlobals.supportedLanguages[] as follows...
   *    We scan the directory entries in LOCALDIR, fix 'em up and then
   *    see if the ntop html directory /html_cc[_XX]) exists?
   *
   *  Those that do, up to the limit, are loaded in the list...
   *
   *  We do not load an empty or artificial en - the logic in http.c will
   *  present the default page (in .../html) if no language specific one is found.
   *
   *  We strip because we're not ready to support multiple char sets.  We're pretty
   *  much just UTF-8
   *
   */

#ifdef HAVE_DIRENT_H
  nLang = scandir(locale_dir, &dirList, NULL, alphasort);
  if(nLang < 0) {
    traceEvent(CONST_TRACE_WARNING,
	       "I18N: Error obtaining locale list, scandir(%s,...) errno is %d\n",
	       locale_dir,
	       errno);
    traceEvent(CONST_TRACE_NOISY, "continues without multiple language support");
  } else {
    traceEvent(CONST_TRACE_NOISY, "I18N: scandir(%s,...) returned %d", locale_dir, nLang);
    for (iLang=0; (iLang<nLang) && (myGlobals.maxSupportedLanguages < MAX_LANGUAGES_SUPPORTED); iLang++) {
#ifdef I18N_DEBUG
      traceEvent(CONST_TRACE_NOISY, "I18N_DEBUG: %2d. '%s'", iLang, dirList[iLang]->d_name);
#endif
      if(dirList[iLang]->d_name[0] == '.') {
	/* skip parent/self directory entries */
	continue;
      }

      if( (dirList[iLang]->d_type == DT_DIR) ||
	  (dirList[iLang]->d_type == DT_LNK) ) {
	tmpStr = i18n_xvert_locale2common(dirList[iLang]->d_name);

	if(!strcmp(myGlobals.defaultLanguage, tmpStr)) {
	  /* skip default language */
	  traceEvent(CONST_TRACE_NOISY,
		     "I18N_DEBUG: Skipping default language '%s' ('%s' raw)\n",
		     tmpStr,
		     dirList[iLang]->d_name);
#ifdef I18N_DEBUG
#endif
	  free(tmpStr);
	  continue;
	}

	found=0;
	for (i=0; (!found) && i<myGlobals.maxSupportedLanguages; i++) {
	  if(!strcmp(tmpStr, myGlobals.supportedLanguages[i])) {
	    traceEvent(CONST_TRACE_NOISY,
		       "I18N_DEBUG: Skipping already supported language, '%s'\n",
		       dirList[iLang]->d_name);
#ifdef I18N_DEBUG
#endif
	    found=1;
	    break;
	  }
	}
	if(!found) {
	  traceEvent(CONST_TRACE_NOISY,
		     "I18N: Testing locale '%s' (from '%s')\n",
		     tmpStr,
		     dirList[iLang]->d_name);
	  for(i=0; (!found) && (myGlobals.dataFileDirs[i] != NULL); i++) {

	    safe_snprintf(__FILE__, __LINE__, buf, sizeof(buf), "%s/html_%s",
			myGlobals.dataFileDirs[i],
			tmpStr);
#ifdef WIN32
	    j=0;
	    while (buf[j] != '\0') {
	      if(buf[j] == '/') buf[j] = CONST_PATH_SEP;
	      j++;
	    }
#endif

#ifdef I18N_DEBUG
	    traceEvent(CONST_TRACE_NOISY,
		       "I18N_DEBUG: Looking for directory '%s'\n",
		       buf);
#endif
	    testDirEnt = opendir(buf);
	    if(testDirEnt != NULL) {
	      closedir(testDirEnt);

	      realLocale = strdup(setlocale(LC_ALL, NULL));
	      setlocale(LC_ALL, tmpStr);
	      myGlobals.strftimeFormat[myGlobals.maxSupportedLanguages] = nl_langinfo(D_T_FMT);
	      setlocale(LC_ALL, realLocale);
	      free(realLocale);

	      myGlobals.supportedLanguages[myGlobals.maxSupportedLanguages++] = strdup(tmpStr);
	      found=1;
	      traceEvent(CONST_TRACE_INFO,
			 "I18N: '%s' ntop language files found, is supported.\n",
			 tmpStr);
	    }
	  }

	  if(!found) {
	    traceEvent(CONST_TRACE_NOISY,
		       "I18N: '%s' ntop language files not found, may not be supported.\n",
		       tmpStr);
	  }

	  free(tmpStr);

#ifdef I18N_DEBUG
	} else {
	  traceEvent(CONST_TRACE_NOISY,
		     "I18N_DEBUG: Skipping duplicate locale '%s'\n",
		     dirList[iLang]->d_name);
#endif
	}

#ifdef I18N_DEBUG
      } else {
	traceEvent(CONST_TRACE_NOISY, "I18N_DEBUG: Skipping file '%s' (type %d)",
		   dirList[iLang]->d_name,
		   dirList[iLang]->d_type);
#endif
      }
    }
    for (iLang=0; iLang<nLang; iLang++) {
      free(dirList[iLang]);
    }
    free(dirList);
  }

#else
  traceEvent(CONST_TRACE_WARNING,
             "I18N: Unable to scan locales (missing dirent.h at compile time) - ntop continues\n");
#endif /* HAVE_DIRENT_H */

  traceEvent(CONST_TRACE_ALWAYSDISPLAY,
             "I18N: This instance of ntop supports %d additional language(s)\n",
             myGlobals.maxSupportedLanguages);
#else
  traceEvent(CONST_TRACE_ALWAYSDISPLAY,
             "I18N: This instance of ntop does not support multiple languages\n");
#endif /* MAKE_WITH_I18N */

  initIPCountryTable();
}


/* ******************************* */

void resetStats(int deviceId) {
  u_int j, i;
  FCSession *session;

  traceEvent(CONST_TRACE_INFO, "Resetting traffic statistics for device %s",
	     myGlobals.device[deviceId].humanFriendlyName);

  if(myGlobals.purgeMutex.isInitialized != 0)
    accessMutex(&myGlobals.purgeMutex, "resetStats");

  for(j=FIRST_HOSTS_ENTRY; j<myGlobals.device[deviceId].actualHashSize; j++) {
    HostTraffic *el = myGlobals.device[deviceId].hash_hostTraffic[j], *elNext;

    if(el) lockHostsHashMutex(el, "resetStats");

    while(el != NULL) {
      elNext = el->next;

      if((el != myGlobals.broadcastEntry) && (el != myGlobals.otherHostEntry)) {
	unlockHostsHashMutex(el);
	freeHostInfo(el, deviceId);
	if(elNext) lockHostsHashMutex(elNext, "resetStats");
      } else {
	if(!elNext) 
	  unlockHostsHashMutex(el);
      }

      el = elNext;
    }

    myGlobals.device[deviceId].hash_hostTraffic[j] = NULL;
  }

  resetDevice(deviceId, 0);

  if(myGlobals.device[deviceId].tcpSession != NULL) {
    for(j=0; j<MAX_TOT_NUM_SESSIONS; j++)
      if(myGlobals.device[deviceId].tcpSession[j] != NULL) {
	free(myGlobals.device[deviceId].tcpSession[j]);
	myGlobals.device[deviceId].tcpSession[j] = NULL;
      }
  }

  if(myGlobals.device[deviceId].fcSession != NULL) {
    for(j=0; j<MAX_TOT_NUM_SESSIONS; j++)
      if((session = myGlobals.device[deviceId].fcSession[j]) != NULL) {
          for (i = 0; i < MAX_LUNS_SUPPORTED; i++) {
              if (session->activeLuns[i] != NULL) {
                  free (session->activeLuns[i]);
              }
          }
          free(session);
          myGlobals.device[deviceId].fcSession[j] = NULL;
      }
  }

  /* Free VSAN Hash */
  if (myGlobals.device[deviceId].vsanHash != NULL) {
      free (myGlobals.device[deviceId].vsanHash);
      myGlobals.device[deviceId].vsanHash = NULL;
  }

  myGlobals.device[deviceId].hash_hostTraffic[BROADCAST_HOSTS_ENTRY] = myGlobals.broadcastEntry;
  myGlobals.broadcastEntry->hostSerial.serialType = SERIAL_IPV4;
  myGlobals.broadcastEntry->hostSerial.value.ipSerial.ipAddress.Ip4Address.s_addr = -1;
  myGlobals.broadcastEntry->next = NULL;
  FD_SET(FLAG_BROADCAST_HOST, &(myGlobals.broadcastEntry->flags));

  if(myGlobals.otherHostEntry != myGlobals.broadcastEntry) {
    myGlobals.device[deviceId].hash_hostTraffic[OTHER_HOSTS_ENTRY] = myGlobals.otherHostEntry;
    /* Dirty trick */
    myGlobals.otherHostEntry->hostSerial.serialType = SERIAL_IPV4;
    myGlobals.otherHostEntry->hostSerial.value.ipSerial.ipAddress.Ip4Address.s_addr = -1;
    myGlobals.otherHostEntry->next = NULL;
    FD_SET(FLAG_BROADCAST_HOST, &(myGlobals.broadcastEntry->flags));
    myGlobals.otherHostEntry->next = NULL;
  }

  if(myGlobals.purgeMutex.isInitialized)
    releaseMutex(&myGlobals.purgeMutex);
}

/* ******************************* */

void initSingleGdbm(GDBM_FILE *database,
		    char *dbName, char *directory,
		    int doUnlink, struct stat *statbuf) {
  char tmpBuf[200], theDate[48];
  time_t        st_time, now;
  struct tm t;
  int d;

  /* Courtesy of Andreas Pfaller <apfaller@yahoo.com.au>. */
  memset(&tmpBuf, 0, sizeof(tmpBuf));
 
#ifdef WIN32
  {
    unsigned long driveSerial;
  
    get_serial(&driveSerial);

    safe_snprintf(__FILE__, __LINE__, tmpBuf, sizeof(tmpBuf), "%s/%u",
		  directory != NULL ? directory : myGlobals.dbPath, driveSerial);

    mkdir_p("DB", tmpBuf, 0x777);

    safe_snprintf(__FILE__, __LINE__, tmpBuf, sizeof(tmpBuf), "%s/%u/%s",
		  directory != NULL ? directory : myGlobals.dbPath, driveSerial,
		  dbName);
  }
#else
  safe_snprintf(__FILE__, __LINE__, tmpBuf, sizeof(tmpBuf), "%s/%s",
	      directory != NULL ? directory : myGlobals.dbPath,
	      dbName);
#endif

  if(statbuf) {
    if(stat(tmpBuf, statbuf) == 0) {
      /* File already exists */
      if((doUnlink != TRUE) && (doUnlink != FALSE)) {

	traceEvent(CONST_TRACE_INFO, "Checking age of database %s", tmpBuf);

	/* Some systems or mounts don't maintain atime so fox 'em */
	if (statbuf->st_atime > 0)
	  st_time = statbuf->st_atime;
	else
	  st_time = 0;
	if((statbuf->st_mtime) && (statbuf->st_mtime > st_time))
	  st_time = statbuf->st_mtime;
	if((statbuf->st_ctime) && (statbuf->st_ctime > st_time))
	  st_time = statbuf->st_ctime;

	strftime(theDate, sizeof(theDate)-1, CONST_LOCALE_TIMESPEC, localtime_r(&st_time, &t));
	theDate[sizeof(theDate)-1] = '\0';
	now  = time(NULL);
	traceEvent(CONST_TRACE_NOISY,
		   "...last create/modify/access was %s, %d second(s) ago",
		   theDate,
		   d = difftime(now, st_time));

	if(d > CONST_DNSCACHE_PERMITTED_AGE) {
	  traceEvent(CONST_TRACE_INFO, "...older, will recreate it");
	  doUnlink = TRUE;
	} else {
	  traceEvent(CONST_TRACE_INFO, "...new enough, will not recreate it");
	  doUnlink = FALSE; /* New enough */
	}
      }
    } else {
      memset(statbuf, 0, sizeof(struct stat));
    }
  }

  if(doUnlink == TRUE)
    unlink(tmpBuf); /* Delete the old one (if present) */

  traceEvent(CONST_TRACE_NOISY, "%s database '%s'",
	     doUnlink == TRUE ? "Creating" : "Opening",
	     tmpBuf);
  *database = gdbm_open (tmpBuf, 0, GDBM_WRCREAT, 00640, NULL);

  if(*database == NULL) {
    traceEvent(CONST_TRACE_ERROR, "....open of %s failed: %s",
	       tmpBuf,
#if defined(WIN32) && defined(__GNUC__)
	       "unknown gdbm errno"
#else
	       gdbm_strerror(gdbm_errno)
#endif
	       );

    if(directory == NULL)
      traceEvent(CONST_TRACE_INFO, "Possible solution: please use '-P <directory>'");
    else {
      traceEvent(CONST_TRACE_INFO, "1. Is another instance of ntop running?");
      traceEvent(CONST_TRACE_INFO, "2. Make sure that the user you specified can write in the target directory");
    }
    traceEvent(CONST_TRACE_FATALERROR, "GDBM open failed, ntop shutting down...");
    exit(7); /* Just in case */
  }
}

/* ************************************************************ */

#ifdef HAVE_PTHREAD_ATFORK
void reinitMutexes (void) {
  int i;

/*
 * Although the fork()ed child gets a copy of the storage for the mutexes,
 * in fact, these are invalid copies and the mutex must be cleared and
 * reinitialized.  Read man pthread_atfork for lots more...
 *
 * Note that once this reinit happens, THEY ARE NOT THE SAME MUTEX.
 * They have the same 'name', but are different blocks of (unshared) storage.
 *
 * Although the ntop 2.2 code has the ILLUSION that the resources are protected
 * they are not!  The code is wrong, but a real fix will have to be in 2.3...
 * (BMS 06-2003, ntop 2.2c)
 *
 * NOTE: For the logViewMutex, we must use the native calls, not the enhanced ones
 *       in util.c - otherwise the calls to traceEvent() cause deadlocks!
 */
  createMutex(&myGlobals.logViewMutex);
  createMutex(&myGlobals.gdbmMutex);        /* data to synchronize thread access to db files */
  createMutex(&myGlobals.tcpSessionsMutex); /* data to synchronize TCP sessions
                                             * access */
  createMutex(&myGlobals.fcSessionsMutex);
  createMutex(&myGlobals.purgePortsMutex);  /* data to synchronize port purge access */
  createMutex(&myGlobals.purgePortsMutex);  /* data to synchronize port purge access */

  for(i=0; i<CONST_HASH_INITIAL_SIZE; i++) {
    createMutex(&myGlobals.hostsHashMutex[i]);
    myGlobals.hostsHashMutexNumLocks[i] = 0;
  }

  createMutex(&myGlobals.securityItemsMutex);
  createMutex(&myGlobals.hostsHashLockMutex);

  if(myGlobals.runningPref.numericFlag == 0) {
    createMutex(&myGlobals.addressResolutionMutex);
  }
}
#endif /* HAVE_PTHREAD_ATFORK */

/*
 * Initialize all the threads used by ntop to:
 * a) sniff packets from NICs and push them in internal data structures
 * b) pop and decode packets
 * c) collect data
 * d) display/emit information
 */
void initThreads(void) {
  int i;

  for(i=0; i<myGlobals.numDevices; i++) {
    createThread(&myGlobals.device[i].dequeuePacketThreadId, dequeuePacket, (void*)((long)i));
    traceEvent(CONST_TRACE_INFO, "THREADMGMT[t%lu]: NPA: Started thread for network packet analyzer (%s)",
	       (long)myGlobals.device[i].dequeuePacketThreadId,
	       myGlobals.device[i].humanFriendlyName);
  }

  /*
   * Create the thread (3) - SFP - Scan Fingerprints
   */
  createThread(&myGlobals.scanFingerprintsThreadId, scanFingerprintLoop, NULL);
  traceEvent(CONST_TRACE_INFO, "THREADMGMT[t%lu]: SFP: Started thread for fingerprinting",
             (long)myGlobals.scanFingerprintsThreadId);

  /*
   * Create the thread (4) - SIH - Scan Idle Hosts - optional
   */
  createThread(&myGlobals.scanIdleThreadId, scanIdleLoop, NULL);
  traceEvent(CONST_TRACE_INFO, "THREADMGMT[t%lu]: SIH: Started thread for idle hosts detection",
             (long)myGlobals.scanIdleThreadId);

  if(myGlobals.runningPref.numericFlag == 0) {
    createMutex(&myGlobals.addressResolutionMutex);

    myGlobals. numDequeueAddressThreads = MAX_NUM_DEQUEUE_ADDRESS_THREADS;

    /*
     * Create the thread (6) - DNSAR - DNS Address Resolution - optional
     */
    for(i=0; i<myGlobals.numDequeueAddressThreads; i++) {
      createThread(&myGlobals.dequeueAddressThreadId[i], dequeueAddress, (char*)((long)i));
      traceEvent(CONST_TRACE_INFO, "THREADMGMT[t%lu]: DNSAR(%d): Started thread for DNS address resolution",
		 (long)myGlobals.dequeueAddressThreadId[i], i+1);
    }
  }

#ifdef MAKE_WITH_SSLWATCHDOG
#ifdef MAKE_WITH_SSLWATCHDOG_RUNTIME
  if(myGlobals.runningPref.useSSLwatchdog == 1)
#endif
    {
      traceEvent(CONST_TRACE_NOISY, "Initializing Condvar for ssl watchdog");
      createCondvar(&myGlobals.sslwatchdogCondvar);
      myGlobals.sslwatchdogCondvar.predicate = FLAG_SSLWATCHDOG_UNINIT;
    }
#endif
}

/*
 * Initialize helper applications
 */
void initApps(void) {
  traceEvent(CONST_TRACE_INFO, "Initializing external applications");
  /* Nothing to do at the moment */
}

/* ******************************* */

void initDeviceSemaphores(int deviceId) {
  traceEvent(CONST_TRACE_INFO, "Initializing device %s (%d)",
	     myGlobals.device[deviceId].name, deviceId);
    
  createMutex(&myGlobals.device[deviceId].asMutex);
  createMutex(&myGlobals.device[deviceId].packetProcessMutex);
  createMutex(&myGlobals.device[deviceId].packetQueueMutex);
  memset(&myGlobals.device[deviceId].packetQueue, 0, sizeof(PacketInformation));
  myGlobals.device[deviceId].packetQueueLen           = 0;
  myGlobals.device[deviceId].maxPacketQueueLen        = 0;
  myGlobals.device[deviceId].packetQueueHead          = 0;
  myGlobals.device[deviceId].packetQueueTail          = 0;

  createCondvar(&myGlobals.device[deviceId].queueCondvar);
}

/* ******************************* */

void allocDeviceMemory(int deviceId) {
  if(!myGlobals.device[deviceId].ipPorts)
    myGlobals.device[deviceId].ipPorts = 
      (PortCounter**)calloc(sizeof(PortCounter*), MAX_IP_PORT);
  
  if(!myGlobals.device[deviceId].packetQueue)
    myGlobals.device[deviceId].packetQueue = 
      (PacketInformation*)calloc(sizeof(PacketInformation), (CONST_PACKET_QUEUE_LENGTH+1));
}

/* ******************************* */

/*
 * Initialize the table of NICs enabled for packet sniffing
 *
 * Unless we are reading data from a file:
 *
 * 1. find a suitable interface, if none ws not specified one
 *    using pcap_lookupdev()
 * 2. get the interface network number and its mask
 *    using pcap_lookupnet()
 * 3. get the type of the underlying network and the data-link encapsulation method
 *    using pcap_datalink()
 *
 * if device is "none" it adds a dummy interface
 */
void addDevice(char* deviceName, char* deviceDescr) {
  int i, deviceId, mallocLen, memlen;
  NtopInterface *tmpDevice, *oldDevice;
  char *workDevices = NULL;
  char myName[80], *column = NULL, ebuf[CONST_SIZE_PCAP_ERR_BUF], tmpStr[64];

  ebuf[0] = '\0', myName[0] = '\0';

  if(deviceName == NULL) {
    traceEvent(CONST_TRACE_WARNING, "Attempt to add a NULL device");
    return;
  }

  /* Remove unwanted characters */
 sanitizeIfName(deviceName);

  traceEvent(CONST_TRACE_NOISY, "Adding network device %s", deviceName);

  if((deviceName != NULL) && (strcmp(deviceName, "none") == 0)) {
    deviceId = createDummyInterface("none");
    traceEvent(CONST_TRACE_INFO, "-i none, so initialized only a dummy device");
  } else {
    mallocLen = sizeof(NtopInterface)*(myGlobals.numDevices+1);
    tmpDevice = (NtopInterface*)malloc(mallocLen);
    memset(tmpDevice, 0, mallocLen);
    memcpy(tmpDevice, myGlobals.device, sizeof(NtopInterface)*(myGlobals.numDevices));
    oldDevice = myGlobals.device;
    myGlobals.device = tmpDevice;
    if (oldDevice != NULL) free(oldDevice);
    deviceId = myGlobals.numDevices;

    safe_snprintf(__FILE__, __LINE__, tmpStr, sizeof(tmpStr), "device.name.%s", deviceName);
    if(fetchPrefsValue(tmpStr, ebuf, sizeof(ebuf)) != -1)
      myGlobals.device[deviceId].humanFriendlyName = strdup(ebuf);
    else
      myGlobals.device[deviceId].humanFriendlyName = strdup(deviceDescr);

    allocDeviceMemory(deviceId);

    myGlobals.device[deviceId].name         = strdup(deviceName);
    myGlobals.device[deviceId].samplingRate =  myGlobals.runningPref.samplingRate;
    calculateUniqueInterfaceName(deviceId);
    myGlobals.numDevices++;

    if(myGlobals.numDevices >= MAX_NUM_DEVICES) {
      static u_char msgSent = 0;

      if(!msgSent) {
	traceEvent(CONST_TRACE_WARNING, "ntop can handle up to %d interfaces",
		   myGlobals.numDevices);
	traceEvent(CONST_TRACE_NOISY, "Additional interfaces will be ignored");
	msgSent = 1;
      }
    }

    /* ********************************************* */

#ifndef WIN32
    column = strchr(myGlobals.device[deviceId].name, ':');
#endif

    /*
      The timeout below for packet capture
      has been set to 100ms.

      Courtesy of: Nicolai Petri <Nicolai@atomic.dk>
    */
    if((!myGlobals.device[deviceId].dummyDevice)
       && (!myGlobals.device[deviceId].virtualDevice)
       && (column == NULL)) {
#ifdef WIN32
      if(strncmp(myGlobals.device[deviceId].name, "rpcap:", 6) != 0) {

	/*
	   The code below has been disabled because it seems
	   that with some network adapters, although there are no
	   errors at all, the stack memory is corrupted and this
	   will cause troubles later on
	*/
#if 0
	NetType adapter;

	LPADAPTER a = PacketOpenAdapter((LPTSTR)myGlobals.device[deviceId].name);

	if(a == NULL) {
	  traceEvent(CONST_TRACE_FATALERROR, "Unable to open device '%s' (invalid name?)",
		     myGlobals.device[deviceId].name);
	  exit(8); /* Just in case */
	}
	if(PacketGetNetType (a,&adapter)) {
	  myGlobals.device[deviceId].deviceSpeed = adapter.LinkSpeed;
	} else
	  PacketCloseAdapter((LPTSTR)myGlobals.device[deviceId].name);
#endif
      }
#else /* not WIN32 */
    if(setuid(0) == -1) {
      traceEvent(CONST_TRACE_FATALERROR, "Unable to become root");
      exit(9); /* Just in case */
    }
#endif

    if (myGlobals.runningPref.printIpOnly) {
      myGlobals.device[deviceId].pcapPtr =
	pcap_open_live(myGlobals.device[deviceId].name,
		       myGlobals.runningPref.enablePacketDecoding == 0 ? 68 : DEFAULT_SNAPLEN,
		       myGlobals.runningPref.disablePromiscuousMode == 1 ? 0 : 1,
		       1000 /* ms */, ebuf);
    }
    else {
        myGlobals.device[deviceId].pcapPtr =
	pcap_open_live(myGlobals.device[deviceId].name,
		       MAX_PACKET_LEN,
		       myGlobals.runningPref.disablePromiscuousMode == 1 ? 0 : 1,
		       1000 /* ms */, ebuf);
    }

      if(myGlobals.device[deviceId].pcapPtr == NULL) {
	traceEvent(CONST_TRACE_ERROR, "pcap_open_live(): '%s'", ebuf);
	if(myGlobals.runningPref.disablePromiscuousMode == 1)
	  traceEvent(CONST_TRACE_INFO,
		     "Sorry, but on this system, even with -s, it appears "
		     "that ntop must be started as root");
	traceEvent(CONST_TRACE_INFO, "Please correct the problem or select "
		   "a different interface using the -i flag");
	traceEvent(CONST_TRACE_FATALERROR, "Not root, ntop shutting down...");
        exit(10); /* Just in case */
      }

      if(myGlobals.runningPref.pcapLog != NULL) {
	if(strlen(myGlobals.runningPref.pcapLog) > 64)
	  myGlobals.runningPref.pcapLog[64] = '\0';
        safe_snprintf(__FILE__, __LINE__, myName, sizeof(myName), "%s%c%s.%s.pcap",
		      myGlobals.runningPref.pcapLogBasePath, /* Added by Ola Lundqvist <opal@debian.org> */
		      CONST_PATH_SEP, myGlobals.runningPref.pcapLog,
		      myGlobals.device[deviceId].uniqueIfName != NULL ?
		      myGlobals.device[deviceId].uniqueIfName :
		      myGlobals.device[deviceId].name);

	myGlobals.device[deviceId].pcapDumper = pcap_dump_open(myGlobals.device[deviceId].pcapPtr, myName);

	if(myGlobals.device[deviceId].pcapDumper == NULL) {
          traceEvent(CONST_TRACE_FATALERROR, "pcap_dump_open(..., '%s') failed", myName);
	  exit(11); /* Just in case */
	}

	traceEvent(CONST_TRACE_NOISY, "Saving packets into file %s", myName);
      }

    if(myGlobals.runningPref.enableSuspiciousPacketDump) {
        if(myGlobals.runningPref.rFileName == NULL)
	  safe_snprintf(__FILE__, __LINE__, myName, sizeof(myName), "%s%cntop-suspicious-pkts.dev%s.pcap",
			myGlobals.runningPref.pcapLogBasePath, /* Added by Ola Lundqvist <opal@debian.org> */
			CONST_PATH_SEP,
			myGlobals.device[deviceId].uniqueIfName != NULL ?
			myGlobals.device[deviceId].uniqueIfName :
			myGlobals.device[deviceId].name);
	else
	  safe_snprintf(__FILE__, __LINE__, myName, sizeof(myName), "%s%cntop-suspicious-pkts.pcap",
			myGlobals.runningPref.rFileName,
			CONST_PATH_SEP);

	myGlobals.device[deviceId].pcapErrDumper = pcap_dump_open(myGlobals.device[deviceId].pcapPtr, myName);

	if(myGlobals.device[deviceId].pcapErrDumper == NULL) {
          myGlobals.runningPref.enableSuspiciousPacketDump = 0;
	  traceEvent(CONST_TRACE_ERROR, "pcap_dump_open(..., '%s') failed (suspicious packets)", myName);
	  traceEvent(CONST_TRACE_INFO, "Continuing without suspicious packet dump");
        } else
	  traceEvent(CONST_TRACE_NOISY, "Saving packets into file %s", myName);
      }

      if(myGlobals.runningPref.enableOtherPacketDump) {
        safe_snprintf(__FILE__, __LINE__, myName, sizeof(myName), "%s%cntop-other-pkts.%s.pcap",
		      myGlobals.runningPref.pcapLogBasePath,
		      CONST_PATH_SEP,
		      myGlobals.device[deviceId].uniqueIfName != NULL ?
		      myGlobals.device[deviceId].uniqueIfName :
		      myGlobals.device[deviceId].name);

	myGlobals.device[deviceId].pcapOtherDumper = pcap_dump_open(myGlobals.device[deviceId].pcapPtr, myName);

	if(myGlobals.device[deviceId].pcapOtherDumper == NULL) {
          myGlobals.runningPref.enableOtherPacketDump = 0;
	  traceEvent(CONST_TRACE_ERROR, "pcap_dump_open(..., '%s') failed (other (unknown) packets)", myName);
	  traceEvent(CONST_TRACE_INFO, "Continuing without other (unknown) packet dump");
        } else
	  traceEvent(CONST_TRACE_NOISY, "Saving packets into file %s", myName);
      }
    } else {
      myGlobals.device[deviceId].virtualDevice = 1;
      if(column != NULL) column[0] = ':';
    }

    if((!myGlobals.device[deviceId].virtualDevice)
       && (pcap_lookupnet(myGlobals.device[deviceId].name,
			  (bpf_u_int32*)&myGlobals.device[deviceId].network.s_addr,
			  (bpf_u_int32*)&myGlobals.device[deviceId].netmask.s_addr, ebuf) < 0)) {
      /* Fix for IP-less interfaces (e.g. bridge)
	 Courtesy of Diana Eichert <deicher@sandia.gov>
      */
      myGlobals.device[deviceId].network.s_addr = htonl(0);
      myGlobals.device[deviceId].netmask.s_addr = htonl(0xFFFFFFFF);
    } else {
      myGlobals.device[deviceId].network.s_addr = htonl(myGlobals.device[deviceId].network.s_addr);
      myGlobals.device[deviceId].netmask.s_addr = htonl(myGlobals.device[deviceId].netmask.s_addr);
    }

    /* ******************************************* */

    if(myGlobals.device[deviceId].netmask.s_addr == 0) {
      /* In this case we are using a dump file */
      myGlobals.device[deviceId].netmask.s_addr = 0xFFFFFF00; /* dummy */
    }

    if((myGlobals.device[deviceId].network.s_addr == 0) &&
       (myGlobals.device[deviceId].netmask.s_addr == 0xFFFFFFFF) ) {
      /* Unnumbered interface... */
      myGlobals.device[deviceId].numHosts = MAX_SUBNET_HOSTS;
    } else {
      myGlobals.device[deviceId].numHosts = 0xFFFFFFFF - myGlobals.device[deviceId].netmask.s_addr + 1;

      /* Add some room for multicast hosts in the ipTrafficMatrix
       * This is an arbitrary guess.
       * We use the log function to limit growth for large networks, while the factor of 50
       * is designed to ensure a certain minimal # even for smaller networks
       */
      myGlobals.device[deviceId].numHosts +=
	ceil(log((double)(0xFFFFFFFF - myGlobals.device[deviceId].netmask.s_addr + 1))+1.0)*50;
    }

    if(myGlobals.device[deviceId].numHosts > MAX_SUBNET_HOSTS) {
      myGlobals.device[deviceId].numHosts = MAX_SUBNET_HOSTS;
      traceEvent(CONST_TRACE_WARNING, "Truncated network size (device %s) to %d hosts (real netmask %s)",
		 myGlobals.device[deviceId].name, myGlobals.device[deviceId].numHosts,
		 intoa(myGlobals.device[deviceId].netmask));
    } else {
      traceEvent(CONST_TRACE_NOISY, "Interface '%s' (netmask %s) computed network size is %d hosts",
		 myGlobals.device[deviceId].name,
		 intoa(myGlobals.device[deviceId].netmask),
		 myGlobals.device[deviceId].numHosts);
    }

    memlen = sizeof(TrafficEntry*)*myGlobals.device[deviceId].numHosts*myGlobals.device[deviceId].numHosts;
    myGlobals.device[deviceId].ipTrafficMatrix = (TrafficEntry**)calloc(myGlobals.device[deviceId].numHosts
									*myGlobals.device[deviceId].numHosts,
									sizeof(TrafficEntry*));
    if(myGlobals.device[deviceId].ipTrafficMatrix == NULL) {
      traceEvent(CONST_TRACE_FATALERROR, "Memory allocation (%d bytes) for ipTraffixMatrix failed", memlen);
      exit(12); /* Just in case */
    }

    traceEvent(CONST_TRACE_NOISY, "MEMORY: ipTrafficMatrix base (no TrafficEntry) for interface '%s' is %5.2fMB",
	       myGlobals.device[deviceId].name,
	       ((float)(memlen)/(float)(1024.0*1024.0))+0.05);
    myGlobals.ipTrafficMatrixMemoryUsage += memlen;

    memlen = sizeof(struct hostTraffic*)*myGlobals.device[deviceId].numHosts;
    myGlobals.device[deviceId].ipTrafficMatrixHosts = (struct hostTraffic**)calloc(sizeof(struct hostTraffic*),
										   myGlobals.device[deviceId].numHosts);

    if(myGlobals.device[deviceId].ipTrafficMatrixHosts == NULL) {
      traceEvent(CONST_TRACE_FATALERROR, "Memory allocation (%d bytes) for ipTraffixMatrixHosts failed", memlen);
      exit(13); /* Just in case */
    }

    /* Allocate FC Traffic Matrices */
#ifdef NOT_YET
    if (!myGlobals.runningPref.printIpOnly) {
        memlen = sizeof(TrafficEntry*)*myGlobals.device[deviceId].numHosts*myGlobals.device[deviceId].numHosts;
        myGlobals.device[deviceId].fcTrafficMatrix = (TrafficEntry**)calloc(myGlobals.device[deviceId].numHosts
                                                                            *myGlobals.device[deviceId].numHosts,
                                                                            sizeof(TrafficEntry*));
        if(myGlobals.device[deviceId].fcTrafficMatrix == NULL) {
          traceEvent(CONST_TRACE_FATALERROR, "Memory allocation (%d bytes) for fcTraffixMatrix failed", memlen);
          exit(14); /* Just in case */
        }
        myGlobals.fcTrafficMatrixMemoryUsage += memlen;

        memlen = sizeof(struct hostTraffic*)*myGlobals.device[deviceId].numHosts;
        myGlobals.device[deviceId].fcTrafficMatrixHosts = (struct hostTraffic**)calloc(sizeof(struct hostTraffic*),
                                                                                       myGlobals.device[deviceId].numHosts);
    }
#endif
  }

  /* ********************************************* */

  if(!(myGlobals.device[deviceId].dummyDevice || myGlobals.device[deviceId].virtualDevice)){
    u_int8_t netmask_v6;
    
    getLocalHostAddress(&myGlobals.device[deviceId].ifAddr, &netmask_v6, myGlobals.device[deviceId].name);
#ifdef INET6
    myGlobals.device[deviceId].v6Addrs = getLocalHostAddressv6(myGlobals.device[deviceId].v6Addrs, myGlobals.device[deviceId].name);
#endif
  }

  mallocLen = 2;
  for(i=0; i<myGlobals.numDevices; i++) {
    if(myGlobals.device[i].name != NULL)
      mallocLen += strlen(myGlobals.device[i].name) + 2;
  }
  workDevices = malloc(mallocLen);
  if(workDevices == NULL)
    return;
  else
    memset(workDevices, 0, mallocLen);

  for(i=0; i<myGlobals.numDevices; i++) {
    if(myGlobals.device[i].name != NULL) {
      int hasSpace;

      if(i>0)
        strncat(workDevices, ", ", (sizeof(workDevices) - strlen(workDevices) - 1));

      if(myGlobals.device[i].name[strlen(myGlobals.device[i].name)-1] == ' ')
	hasSpace = 1;
      else
	hasSpace = 0;

      strncat(workDevices,
              myGlobals.device[i].name,
              (sizeof(workDevices) - strlen(workDevices) - hasSpace));
    }
  }

  if(myGlobals.runningPref.devices != NULL)
    free(myGlobals.runningPref.devices);

  myGlobals.runningPref.devices = strdup(workDevices);
  free(workDevices);

  /* ********************************************** */

#ifndef WIN32
  if(strncmp(myGlobals.device[deviceId].name, "lo", 2)) {
    /* Do not care of virtual loopback interfaces */
    int k;
    char tmpDeviceName[64];
    struct in_addr myLocalHostAddress;


    if((myGlobals.numDevices < MAX_NUM_DEVICES)
       && strcmp(myGlobals.device[deviceId].name, "none")) {
      traceEvent(CONST_TRACE_INFO, "Checking %s for additional devices", myGlobals.device[deviceId].name);
      for(k=0; k<=MAX_NUM_DEVICES_VIRTUAL; k++) {
	u_int8_t netmask_v6;
	
	safe_snprintf(__FILE__, __LINE__, tmpDeviceName, sizeof(tmpDeviceName), "%s:%d", myGlobals.device[deviceId].name, k);

	traceEvent(CONST_TRACE_NOISY, "Checking %s", tmpDeviceName);
	if(getLocalHostAddress(&myLocalHostAddress, &netmask_v6, tmpDeviceName) == 0) {
	  /* The virtual interface exists */

	  mallocLen = sizeof(NtopInterface)*(myGlobals.numDevices+1);
	  tmpDevice = (NtopInterface*)malloc(mallocLen);
	  memset(tmpDevice, 0, mallocLen);
	  memcpy(tmpDevice, myGlobals.device, sizeof(NtopInterface)*myGlobals.numDevices);
	  free(myGlobals.device);
	  myGlobals.device = tmpDevice;

	  myGlobals.device[myGlobals.numDevices].ifAddr.s_addr = myLocalHostAddress.s_addr;
	  if(myLocalHostAddress.s_addr == myGlobals.device[deviceId].ifAddr.s_addr)
	    continue; /* No virtual Interfaces */
	 myGlobals.device[myGlobals.numDevices].virtualDevice = 1;
	 myGlobals.device[myGlobals.numDevices].activeDevice = 1;
	 myGlobals.device[myGlobals.numDevices].humanFriendlyName = strdup(tmpDeviceName);
	 myGlobals.device[myGlobals.numDevices].name = strdup(tmpDeviceName);
	 calculateUniqueInterfaceName(myGlobals.numDevices);
	 myGlobals.numDevices++;
	 traceEvent(CONST_TRACE_INFO, "Added virtual interface: '%s'", tmpDeviceName);
	 if(myGlobals.numDevices >= MAX_NUM_DEVICES) {
	   traceEvent(CONST_TRACE_WARNING, "Stopping scan - no room for additional (virtual) interfaces");
	   break;
	 }
	}
      }
    }
  }
#endif /* WIN32 */

  resetStats(deviceId);
  initDeviceDatalink(deviceId);

  if((myGlobals.actualReportDeviceId == 0) && myGlobals.device[0].dummyDevice)
    myGlobals.actualReportDeviceId = deviceId;
  
}

/* ******************************* */

int validInterface(char *name) {
  if(name && 
     (strstr(name, "PPP") /* Avoid to use the PPP interface */
      || strstr(name, "dialup")  /* Avoid to use the dialup interface */
      || strstr(name, "ICSHARE")  /* Avoid to use the internet sharing interface */
      || strstr(name, "NdisWan"))) { /* Avoid to use the internet sharing interface */
    return(0);
  }
  
  return(1);
}

#define MAX_IF_NAME    256

/*
 * If device is NULL, this function adds the default interface
 * if device is "none" it adds a dummy interface
 */
void initDevices(char* devices) {
  char *tmpDev=NULL, *tmpDescr=NULL;
  pcap_if_t *devpointer, *devpointer_original;
  char intNames[32][MAX_IF_NAME], intDescr[32][MAX_IF_NAME];
  int ifIdx = 0;
  int defaultIdx = -1;
  int found = 0, intfc;
  char ebuf[CONST_SIZE_PCAP_ERR_BUF];
  char myName[80];

  ebuf[0] = '\0', myName[0] = '\0';

  traceEvent(CONST_TRACE_NOISY, "Initializing network devices");

  if(myGlobals.runningPref.rFileName != NULL) {
    createDummyInterface("none");
    myGlobals.device[0].dummyDevice = 0;
    myGlobals.device[0].pcapPtr  = pcap_open_offline(myGlobals.runningPref.rFileName, ebuf);

    if(myGlobals.device[0].pcapPtr == NULL) {
      traceEvent(CONST_TRACE_ERROR, "pcap_open_offline(%s): '%s'",
		 myGlobals.runningPref.rFileName, ebuf);
      exit(-1);
    } else {
      if(myGlobals.device[0].humanFriendlyName != NULL) free(myGlobals.device[0].humanFriendlyName);
      myGlobals.device[0].humanFriendlyName = strdup(myGlobals.runningPref.rFileName);
      calculateUniqueInterfaceName(0);
    }

    resetStats(0);
    initDeviceDatalink(0);

    if(myGlobals.runningPref.enableSuspiciousPacketDump) {
      if(myGlobals.runningPref.rFileName == NULL)
	safe_snprintf(__FILE__, __LINE__, myName, sizeof(myName), "%s%cntop-suspicious-pkts.%s.pcap",
		      myGlobals.runningPref.pcapLogBasePath, /* Added by Ola Lundqvist <opal@debian.org> */
		      CONST_PATH_SEP,
		      myGlobals.device[0].uniqueIfName != NULL ?
		      myGlobals.device[0].uniqueIfName :
		      myGlobals.device[0].name);
      else
	safe_snprintf(__FILE__, __LINE__, myName, sizeof(myName), "%s.ntop-suspicious-pkts.pcap",
		      myGlobals.runningPref.rFileName);

        myGlobals.device[0].pcapErrDumper = pcap_dump_open(myGlobals.device[0].pcapPtr, myName);

        if(myGlobals.device[0].pcapErrDumper == NULL)
	  traceEvent(CONST_TRACE_ALWAYSDISPLAY, "pcap_dump_open() for suspicious packets: '%s'", ebuf);
	else
	  traceEvent(CONST_TRACE_NOISY, "Saving packets into file %s", myName);
    }

    free(myGlobals.device[0].name);
    myGlobals.device[0].name = strdup("pcap-file");
    myGlobals.numDevices = 1;
    return;
  }

  if(pcap_findalldevs(&devpointer, ebuf) < 0) {
    traceEvent(CONST_TRACE_ERROR, "pcap_findalldevs() call failed [%s]", ebuf);
    traceEvent(CONST_TRACE_ERROR, "Have you instaled libpcap/winpcap properly?");
    return;
  } else {
    int i;

    devpointer_original = devpointer;
    for(i = 0; devpointer != 0; i++) {
      traceEvent(CONST_TRACE_NOISY, "Found interface [index=%d] '%s'", ifIdx, devpointer->name);

      if(tmpDev == NULL) {
	tmpDev = devpointer->name;
	tmpDescr = devpointer->description;
      }

      if(ifIdx < 32) {
	char *descr;

	if(validInterface(devpointer->description)) {
	descr = devpointer->description;

	if(descr != NULL) {
	  /* Sanitize the interface name */
	  for(i=0; i<strlen(descr); i++)
	    if(descr[i] == '(') {
	      descr[i] = '\0';
	      break;
	    }

	  while(descr[strlen(descr)-1] == ' ')
	    descr[strlen(descr)-1] = '\0';

	  safe_snprintf(__FILE__, __LINE__, intDescr[ifIdx], MAX_IF_NAME, "%s_%d", descr, ifIdx);
	} else
	  safe_snprintf(__FILE__, __LINE__, intDescr[ifIdx], MAX_IF_NAME, "%s", devpointer->name);

	strncpy(intNames[ifIdx], devpointer->name, MAX_IF_NAME);

	if(defaultIdx == -1) {
		defaultIdx = ifIdx;
		tmpDev = devpointer->name;
		tmpDescr = devpointer->description;
	}

	ifIdx++;
      }
	  }

      devpointer = devpointer->next;
    }
  }

  pcap_freealldevs(devpointer_original);

  if(devices != NULL) {
    /* User has specified devices in the parameter list */
    char *workDevices = strdup(devices), *strtokState;
    int warnedVirtual = 0;

    tmpDev = strtok_r(workDevices, ",", &strtokState);

    while(tmpDev != NULL) {
#ifndef WIN32
      char *nwInterface;
      deviceSanityCheck(tmpDev); /* These checks do not apply to Win32 */

      traceEvent(CONST_TRACE_NOISY, "Checking requested device '%s'", tmpDev);

      if(((nwInterface = strchr(tmpDev, ':')) != NULL) 
	 && (!strstr(tmpDev, "dag")) /* Endace DAG cards are valid (e.g. dag0:0) */
	 )
	{
 	/* This is a virtual nwInterface */
        char *requestedDev;

        /* Copy (unaltered) for traceEvent() messages */
        requestedDev = strdup(tmpDev);

        if(!warnedVirtual) {
          warnedVirtual = 1;
          traceEvent(CONST_TRACE_WARNING, "Virtual device(s), e.g. %s, specified on "
		     "-i | --interface parameter are ignored", tmpDev);
        }

 	nwInterface[0] = 0;
        /* tmpDev is now just the base name */

 	for(intfc=0; intfc<myGlobals.numDevices; intfc++) {
 	  if(myGlobals.device[intfc].name && (strcmp(myGlobals.device[intfc].name, tmpDev) == 0)) {
 	    found = 1;
            traceEvent(CONST_TRACE_INFO,
                       "NOTE: Virual device '%s' is already implied from a prior base device",
                       requestedDev);
 	    break;
 	  }
 	}

 	if(found) {
 	  tmpDev = strtok_r(NULL, ",", &strtokState);
          free(requestedDev);
 	  continue;
 	}

        traceEvent(CONST_TRACE_INFO, "Using base device %s in place of requested %s",
                   tmpDev, requestedDev);

        free(requestedDev);
      }
#else /* WIN32 */
      if(isdigit(tmpDev[0])) {
	if(atoi(tmpDev) < ifIdx) {
	  tmpDescr = intDescr[atoi(tmpDev)];
	  tmpDev   = intNames[atoi(tmpDev)];
	} else {
	  traceEvent(CONST_TRACE_ERROR, "Interface index '%d' is out of range [0..%d]", 
		  atoi(tmpDev), ifIdx > 0 ? (ifIdx -1) : 0);
	  return;
	}
      } else {
	/* Nothing to do: the user has specified an interface name */
	int i;

	tmpDescr = NULL;
	for(i=0; i<ifIdx; i++) {
	  if(!strcmp(intNames[i], devices)) {
	    tmpDescr = intDescr[i];
	    break;
	  }
	}
      }
#endif

      for(intfc=0; intfc<myGlobals.numDevices; intfc++) {
        if(myGlobals.device[intfc].name && (strcmp(myGlobals.device[intfc].name, tmpDev) == 0)) {
          found = 1;
          break;
        }
      }

      if(found)
        traceEvent(CONST_TRACE_WARNING,
                   "Device '%s' is already specified/implied - ignoring it", tmpDev);
      else
        addDevice(tmpDev, tmpDescr == NULL ? tmpDev : tmpDescr);

      tmpDev = strtok_r(NULL, ",", &strtokState);
    } /* while */

    free(workDevices);
  } else if(defaultIdx != -1) {
    /* Default interface found */
    traceEvent(CONST_TRACE_INFO, "No default device configured. Using %s", intNames[defaultIdx]);
    processStrPref(NTOP_PREF_DEVICES, intNames[defaultIdx], &myGlobals.runningPref.devices, TRUE);
    processStrPref(NTOP_PREF_DEVICES, intNames[defaultIdx], &myGlobals.savedPref.devices, TRUE);
    addDevice(intNames[defaultIdx], intDescr[defaultIdx]);
  }
}

/* ******************************* */

void initDeviceDatalink(int deviceId) {
  if(myGlobals.device[deviceId].dummyDevice) return;
  myGlobals.device[deviceId].activeDevice = 1;
  initDeviceSemaphores(deviceId);
  if(myGlobals.device[deviceId].virtualDevice) return;

  /* get datalink type */
#if defined(__FreeBSD__)
  if(strncmp(myGlobals.device[deviceId].name, "tun", 3) == 0) {
    myGlobals.device[deviceId].datalink = DLT_PPP;
    traceEvent(CONST_TRACE_NOISY, "DLT: Device %d [%s] is \"tun\", treating as DLT_PPP",
	       deviceId,
	       myGlobals.device[deviceId].name);
  } else
#else /* Not FreeBSD */
  if((myGlobals.device[deviceId].name[0] == 'l') /* loopback check */
     && (myGlobals.device[deviceId].name[1] == 'o')) {
    myGlobals.device[deviceId].datalink = DLT_NULL;
    traceEvent(CONST_TRACE_NOISY, "DLT: Device %d [%s] is loopback, treating as DLT_NULL",
	       deviceId,
	       myGlobals.device[deviceId].name);
  } else
#endif
  /* Other OSes have SOME issues, but if we don't recognize the special device,
   * use libpcap */
    myGlobals.device[deviceId].datalink = pcap_datalink(myGlobals.device[deviceId].pcapPtr);

  if(myGlobals.device[deviceId].datalink > MAX_DLT_ARRAY) {
    traceEvent(CONST_TRACE_WARNING,
               "DLT: Device %d [%s] DLT_ value, %d, exceeds highest known value(%d)",
               deviceId,
               myGlobals.device[deviceId].name,
               myGlobals.device[deviceId].datalink,
               MAX_DLT_ARRAY);
    traceEvent(CONST_TRACE_WARNING, "DLT: Please report above message to the ntop-dev list.");
    traceEvent(CONST_TRACE_WARNING, "DLT: Processing continues OK");
    myGlobals.device[deviceId].mtuSize    = CONST_UNKNOWN_MTU;
    myGlobals.device[deviceId].headerSize = 0;
  } else {
    myGlobals.device[deviceId].mtuSize    = myGlobals.mtuSize[myGlobals.device[deviceId].datalink];
    myGlobals.device[deviceId].headerSize = myGlobals.headerSize[myGlobals.device[deviceId].datalink];

    if((myGlobals.device[deviceId].mtuSize == 0) ||
       (myGlobals.device[deviceId].mtuSize == CONST_UNKNOWN_MTU) ) {
      traceEvent(CONST_TRACE_WARNING, "DLT: Device %d [%s] MTU value unknown",
                 deviceId,
                 myGlobals.device[deviceId].name);
      if(myGlobals.device[deviceId].datalink != DLT_RAW)
        traceEvent(CONST_TRACE_NOISY, "DLT: Please report your DLT and MTU values (e.g. ifconfig) to the ntop-dev list");
      traceEvent(CONST_TRACE_WARNING, "DLT: Processing continues OK");
    }
  }

  traceEvent(CONST_TRACE_INFO, "DLT: Device %d [%s] is %d, mtu %d, header %d",
	       deviceId,
	       myGlobals.device[deviceId].name,
	       myGlobals.device[deviceId].datalink,
	       myGlobals.device[deviceId].mtuSize,
	       myGlobals.device[deviceId].headerSize);
}

/* ******************************* */

void parseTrafficFilter(void) {
  /* Construct, compile and set filter */
  if(myGlobals.runningPref.currentFilterExpression != NULL) {
    int i;
    struct bpf_program fcode;

    for(i=0; i<myGlobals.numDevices; i++) {
      if(myGlobals.device[i].pcapPtr && (!myGlobals.device[i].virtualDevice)) {
	if((pcap_compile(myGlobals.device[i].pcapPtr, &fcode, myGlobals.runningPref.currentFilterExpression, 1,
			 myGlobals.device[i].netmask.s_addr) < 0)
	   || (pcap_setfilter(myGlobals.device[i].pcapPtr, &fcode) < 0)) {
	  traceEvent(CONST_TRACE_FATALERROR,
		     "Wrong filter '%s' (%s) on interface %s",
		     myGlobals.runningPref.currentFilterExpression,
		     pcap_geterr(myGlobals.device[i].pcapPtr),
		     myGlobals.device[i].name[0] == '0' ? "<pcap file>" : myGlobals.device[i].name);
	  exit(15); /* Just in case */
	}

        traceEvent(CONST_TRACE_NOISY, "Setting filter to \"%s\" on device %s.",
		     myGlobals.runningPref.currentFilterExpression, myGlobals.device[i].name);
        pcap_freecode(&fcode);
      }
    }
  } else
    myGlobals.runningPref.currentFilterExpression = strdup("");	/* so that it isn't NULL! */
}

/* *************************** */

#ifndef WIN32
static void ignoreThisSignal(int signalId) {
  signal(signalId, ignoreThisSignal);
}
#endif

/* ******************************* */

void initSignals(void) {
  /*
    The handler below has been restored due
    to compatibility problems:
    Courtesy of Martin Lucina <mato@kotelna.sk>
  */
#ifndef WIN32
  signal(SIGCHLD, handleDiedChild);
#endif

#ifndef WIN32
  /* Setup signal handlers */
  signal(SIGTERM, cleanup);
  signal(SIGINT,  cleanup);
  signal(SIGHUP,  handleSigHup);
  signal(SIGPIPE, ignoreThisSignal);
  signal(SIGABRT, ignoreThisSignal);
#if 0
  if(myGlobals.runningPref.debugMode) {
    /* Activate backtrace trap on -K flag */
    signal(SIGSEGV, cleanup);
  }
#endif
#endif
}

/* ***************************** */

void startSniffer(void) {
  int i;

  if((myGlobals.ntopRunState != FLAG_NTOPSTATE_INIT) &&
     (myGlobals.ntopRunState != FLAG_NTOPSTATE_INITNONROOT)) {
    traceEvent(CONST_TRACE_ERROR, "Unable to start sniffer - not in INIT state");
//TODO Should above be FATALERROR???
    return;
  }

  setRunState(FLAG_NTOPSTATE_RUN);

  for(i=0; i<myGlobals.numDevices; i++)
    if((!myGlobals.device[i].virtualDevice)
       && (!myGlobals.device[i].dummyDevice)
       && (myGlobals.device[i].pcapPtr != NULL)) {
      /*
       * (8) - NPS - Network Packet Sniffer (main thread)
       */
      createThread(&myGlobals.device[i].pcapDispatchThreadId, pcapDispatch, (char*)((long)i));
      traceEvent(CONST_TRACE_INFO, "THREADMGMT[t%lu]: NPS(%d): Started thread for network packet sniffing [%s]",
		 (long)myGlobals.device[i].pcapDispatchThreadId, i+1, myGlobals.device[i].name);
    }
}

/* ***************************** */

u_int createDummyInterface(char *ifName) {
  u_int mallocLen, deviceId = myGlobals.numDevices;
  NtopInterface *tmpDevice;

  traceEvent(CONST_TRACE_INFO, "Creating dummy interface, '%s'", ifName);

  mallocLen = sizeof(NtopInterface)*(myGlobals.numDevices+1);
  tmpDevice = (NtopInterface*)malloc(mallocLen);

  if(tmpDevice == NULL)
    return(-1);

  memset(tmpDevice, 0, mallocLen);

  if(myGlobals.numDevices > 0) {
    NtopInterface *old_ptr = myGlobals.device;
    memcpy(tmpDevice, myGlobals.device,
	   sizeof(NtopInterface)*myGlobals.numDevices);
    myGlobals.device = tmpDevice;
    free(old_ptr);
  } else
    myGlobals.device = tmpDevice;

  myGlobals.numDevices++;
  memset(&myGlobals.device[deviceId], 0, sizeof(NtopInterface));

  resetDevice(deviceId, 1);
  myGlobals.device[deviceId].network.s_addr = 0xFFFFFFFF;
  myGlobals.device[deviceId].netmask.s_addr = 0xFFFFFFFF;
  myGlobals.device[deviceId].numHosts = myGlobals.device[0].numHosts;
  myGlobals.device[deviceId].name = strdup(ifName);
  myGlobals.device[deviceId].humanFriendlyName = strdup(ifName);
  myGlobals.device[deviceId].datalink = DLT_EN10MB;
  myGlobals.device[deviceId].hash_hostTraffic[BROADCAST_HOSTS_ENTRY] = myGlobals.broadcastEntry;
  myGlobals.broadcastEntry->next = NULL;
  myGlobals.device[deviceId].dummyDevice   = 1; /* This is basically a fake device */
  myGlobals.device[deviceId].virtualDevice = 0;
  myGlobals.device[deviceId].activeDevice  = 0;
  myGlobals.device[deviceId].samplingRate =  myGlobals.runningPref.samplingRate;
  calculateUniqueInterfaceName(deviceId);

  if(myGlobals.otherHostEntry != NULL) {
    myGlobals.device[deviceId].hash_hostTraffic[OTHER_HOSTS_ENTRY] = myGlobals.otherHostEntry;
    myGlobals.otherHostEntry->next = NULL;
  }

#ifdef NOT_YET
  mallocLen = sizeof(TrafficEntry*)*myGlobals.device[deviceId].numHosts*myGlobals.device[deviceId].numHosts;
  myGlobals.device[deviceId].fcTrafficMatrix = (TrafficEntry**)calloc(myGlobals.device[deviceId].numHosts
                                                                      *myGlobals.device[deviceId].numHosts,
                                                                      sizeof(TrafficEntry*));
  if(myGlobals.device[deviceId].fcTrafficMatrix == NULL) {
      traceEvent(CONST_TRACE_FATALERROR, "Memory allocation (%d bytes) for fcTraffixMatrix failed", mallocLen);
      exit(16); /* Just in case */
  }

  mallocLen = sizeof(struct hostTraffic*)*myGlobals.device[deviceId].numHosts;
  myGlobals.device[deviceId].fcTrafficMatrixHosts = (struct hostTraffic**)calloc(sizeof(struct hostTraffic*),
                                                                                 myGlobals.device[deviceId].numHosts);

  if(myGlobals.device[deviceId].fcTrafficMatrixHosts == NULL) {
      traceEvent(CONST_TRACE_FATALERROR, "Memory allocation (%d bytes) for fcTrafficMatrixHosts failed", mallocLen);
      exit(17); /* Just in case */
  }
#endif

  if(myGlobals.runningPref.enableSessionHandling) {
    int len = sizeof(IPSession*)*MAX_TOT_NUM_SESSIONS;
    myGlobals.device[deviceId].tcpSession = (IPSession**)malloc(len);
    memset(myGlobals.device[deviceId].tcpSession, 0, len);
  }

  return(deviceId);
}