forked from lucab/ntop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinitialize.c
1419 lines (1175 loc) · 49.1 KB
/
initialize.c
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
/*
* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
*
* http://www.ntop.org
*
* Copyright (C) 1998-2012 Luca Deri <[email protected]>
*
* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
*
* 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"
/*
* 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 <[email protected]>
*/
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;
gethostname(szLclHost, 64);
lpstHostent = gethostbyname(szLclHost);
if(lpstHostent) {
struct hostent *hp;
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 = (int)(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 = (int)(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[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 */
char name[64], proto[16];
int numPort;
/* Fix below courtesy of Andreas Pfaller <[email protected]> */
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");
}
/* ******************************* */
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 <[email protected]>
*/
void resetDevice(int devIdx, short fullReset) {
int len;
void *ptr;
if(myGlobals.device[devIdx].dummyDevice) return;
myGlobals.device[devIdx].hosts.actualHashSize = CONST_HASH_INITIAL_SIZE;
len = CONST_HASH_INITIAL_SIZE * sizeof(HostTraffic*);
if(myGlobals.device[devIdx].hosts.hash_hostTraffic == NULL) {
ptr = calloc(CONST_HASH_INITIAL_SIZE, sizeof(HostTraffic*));
myGlobals.device[devIdx].hosts.hash_hostTraffic = ptr;
}
memset(myGlobals.device[devIdx].hosts.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].ipv4Bytes);
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].stpBytes);
resetTrafficCounter(&myGlobals.device[devIdx].ipsecBytes);
resetTrafficCounter(&myGlobals.device[devIdx].netbiosBytes);
resetTrafficCounter(&myGlobals.device[devIdx].arpRarpBytes);
resetTrafficCounter(&myGlobals.device[devIdx].greBytes);
resetTrafficCounter(&myGlobals.device[devIdx].ipv6Bytes);
resetTrafficCounter(&myGlobals.device[devIdx].otherBytes);
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);
memset(&myGlobals.device[devIdx].rcvdPktStats, 0, sizeof(PacketStats));
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;
if(myGlobals.pcap_file_list == 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].last60MinTopTalkers, 0, sizeof(myGlobals.device[devIdx].last60MinTopTalkers));
memset(myGlobals.device[devIdx].last24HoursTopTalkers, 0, sizeof(myGlobals.device[devIdx].last24HoursTopTalkers));
myGlobals.device[devIdx].hosts.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 = (int)(myGlobals.numIpProtosToMonitor*sizeof(SimpleProtoTrafficInfo));
if(myGlobals.device[devIdx].ipProtosList != NULL) {
free(myGlobals.device[devIdx].ipProtosList);
myGlobals.device[devIdx].ipProtosList = NULL;
}
createDeviceIpProtosList(devIdx);
}
/* ******************************************* */
void initCounters(void) {
int len, i;
setDomainName();
_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;
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) {
myGlobals.device[i].sessions = (IPSession**)calloc(sizeof(IPSession*), MAX_TOT_NUM_SESSIONS);
} else
myGlobals.device[i].sessions = NULL;
myGlobals.device[i].fragmentList = NULL;
}
myGlobals.hashCollisionsLookup = 0;
if(myGlobals.pcap_file_list == 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;
}
/* ******************************* */
void resetStats(int deviceId) {
u_int j;
traceEvent(CONST_TRACE_INFO, "Resetting traffic statistics for device %s",
myGlobals.device[deviceId].humanFriendlyName);
if(myGlobals.purgeMutex.isInitialized)
accessMutex(&myGlobals.purgeMutex, "resetStats");
for(j=FIRST_HOSTS_ENTRY; j<myGlobals.device[deviceId].hosts.actualHashSize; j++) {
HostTraffic *el = myGlobals.device[deviceId].hosts.hash_hostTraffic[j], *elNext;
if(el) lockExclusiveHostsHashMutex(el, "resetStats");
while(el != NULL) {
elNext = el->next;
if((el != myGlobals.broadcastEntry) && (el != myGlobals.otherHostEntry)) {
unlockExclusiveHostsHashMutex(el);
freeHostInfo(el, deviceId);
if(elNext) lockExclusiveHostsHashMutex(elNext, "resetStats");
} else {
if(!elNext)
unlockExclusiveHostsHashMutex(el);
}
el = elNext;
}
myGlobals.device[deviceId].hosts.hash_hostTraffic[j] = NULL;
}
resetDevice(deviceId, 0);
if(myGlobals.device[deviceId].sessions != NULL) {
for(j=0; j<MAX_TOT_NUM_SESSIONS; j++)
if(myGlobals.device[deviceId].sessions[j] != NULL) {
free(myGlobals.device[deviceId].sessions[j]);
myGlobals.device[deviceId].sessions[j] = NULL;
}
}
myGlobals.device[deviceId].hosts.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;
setHostFlag(FLAG_BROADCAST_HOST, myGlobals.broadcastEntry);
if(myGlobals.otherHostEntry != myGlobals.broadcastEntry) {
myGlobals.device[deviceId].hosts.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;
}
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;
double d;
/* Courtesy of Andreas Pfaller <[email protected]>. */
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, %.1f second(s) ago",
theDate,
d = difftime(now, st_time));
if(d > (15 * 60)) {
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.portsMutex); /* Avoid race conditions while handling ports */
for(i=0; i<NUM_SESSION_MUTEXES; i++)
createMutex(&myGlobals.sessionsMutex[i]); /* data to synchronize TCP sessions access */
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);
}
#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;
/*
* 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 != noDnsResolution) {
createMutex(&myGlobals.addressResolutionMutex);
#if defined(HAVE_GETHOSTBYADDR_R)
myGlobals.numDequeueAddressThreads = MAX_NUM_DEQUEUE_ADDRESS_THREADS;
#else
myGlobals.numDequeueAddressThreads = 1;
#endif
initAddressResolution();
/*
* Create the thread (5) - 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);
}
}
}
/*
* 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].counterMutex);
createMutex(&myGlobals.device[deviceId].asMutex);
createMutex(&myGlobals.device[deviceId].packetProcessMutex);
createMutex(&myGlobals.device[deviceId].packetQueueMutex);
if(myGlobals.device[deviceId].packetQueue)
memset(myGlobals.device[deviceId].packetQueue, 0,
sizeof(PacketInformation) * (CONST_PACKET_QUEUE_LENGTH+1));
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));
initL7DeviceDiscovery(deviceId);
myGlobals.device[deviceId].l7.protoTraffic = (Counter*)calloc(myGlobals.l7.numSupportedProtocols, sizeof(Counter));
}
/* ******************************* */
/*
* 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;
char *workDevices = NULL;
char myName[255], *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 {
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 <[email protected]>
*/
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
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 */
}
#ifdef HAVE_PF_RING
pcap_set_appl_name_linux(myGlobals.device[deviceId].pcapPtr, "ntop");
#endif
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 <[email protected]> */
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.pcap_file_list == NULL)
safe_snprintf(__FILE__, __LINE__, myName, sizeof(myName), "%s%cntop-suspicious-pkts.dev%s.pcap",
myGlobals.runningPref.pcapLogBasePath, /* Added by Ola Lundqvist <[email protected]> */
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.pcap_file_list,
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);
}
} 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 <[email protected]>
*/
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 */
}
addDeviceNetworkToKnownSubnetList(&myGlobals.device[deviceId]);
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
* 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 +=
(int)(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);
}
}
/* ********************************************* */
#ifdef INET6
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);
myGlobals.device[deviceId].v6Addrs = getLocalHostAddressv6(myGlobals.device[deviceId].v6Addrs, myGlobals.device[deviceId].name);
if(myGlobals.device[deviceId].network.s_addr == 0) {
myGlobals.device[deviceId].netmask.s_addr = 0xFFFFFF00;/* /24 */
myGlobals.device[deviceId].network.s_addr = myGlobals.device[deviceId].ifAddr.s_addr
& myGlobals.device[deviceId].netmask.s_addr;
}
}
#endif
mallocLen = 2;
for(i=0; i<myGlobals.numDevices; i++) {
if(myGlobals.device[i].name != NULL)
mallocLen += (int)(strlen(myGlobals.device[i].name) + 2);
}
workDevices = calloc(mallocLen+1, 1);
if(workDevices == NULL)
return;
else
for(i=0; i<myGlobals.numDevices; i++) {
if(myGlobals.device[i].name != NULL) {
int len = (int)strlen(workDevices);
safe_snprintf(__FILE__, __LINE__,
&workDevices[len], mallocLen-len,
"%s%s", (i > 0) ? ", " : "",
myGlobals.device[i].name);
}
}
if(myGlobals.runningPref.devices != NULL)
free(myGlobals.runningPref.devices);
myGlobals.runningPref.devices = 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-1))
&& 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 */
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 */