forked from lucab/ntop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpbuf.c
1625 lines (1344 loc) · 57.3 KB
/
pbuf.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"
static void updateASTraffic(int actualDeviceId, u_int16_t src_as_id,
u_int16_t dst_as_id, u_int octets);
/* ******************************* */
void allocateSecurityHostPkts(HostTraffic *srcHost) {
if(srcHost->secHostPkts == NULL) {
if((srcHost->secHostPkts = (SecurityHostProbes*)malloc(sizeof(SecurityHostProbes))) == NULL) return;
resetSecurityHostTraffic(srcHost);
}
}
/* ************************************ */
u_int computeEfficiency(u_int pktLen) {
u_int pktEfficiency;
if(myGlobals.cellLength == 0)
pktEfficiency = 0;
else
pktEfficiency = 100 - (((pktLen % myGlobals.cellLength) * 100) / myGlobals.cellLength);
// traceEvent(CONST_TRACE_WARNING, "[len=%d][efficiency=%d]", pktLen, pktEfficiency);
return(pktEfficiency);
}
/* ************************************ */
/* Reset the traffic at every hour */
static void resetHourTraffic(u_short hourId) {
int i;
for(i=0; i<myGlobals.numDevices; i++) {
HostTraffic *el;
for(el=getFirstHost(i); el != NULL; el = getNextHost(i, el)) {
if(el->trafficDistribution != NULL) {
resetTrafficCounter(&el->trafficDistribution->last24HoursBytesSent[hourId]);
resetTrafficCounter(&el->trafficDistribution->last24HoursBytesRcvd[hourId]);
}
}
}
}
/* ************************************ */
static void addContactedPeers(HostTraffic *sender, HostAddr *srcAddr,
HostTraffic *receiver, HostAddr *dstAddr,
int actualDeviceId) {
if((sender == NULL) || (receiver == NULL) || (sender == receiver)) {
if(sender != NULL) {
/* This is normal. Return without warning */
return;
}
traceEvent(CONST_TRACE_ERROR, "Sanity check failed @ addContactedPeers (%p, %p)",
sender, receiver);
return;
}
if((sender != myGlobals.otherHostEntry) && (receiver != myGlobals.otherHostEntry)) {
/* The statements below have no effect if the serial has been already computed */
setHostSerial(sender); setHostSerial(receiver);
sender->totContactedSentPeers +=
incrementUsageCounter(&sender->contactedSentPeers, receiver, actualDeviceId);
receiver->totContactedRcvdPeers +=
incrementUsageCounter(&receiver->contactedRcvdPeers, sender, actualDeviceId);
}
}
/* ************************************ */
void updatePacketCount(HostTraffic *srcHost, HostTraffic *dstHost,
TrafficCounter bytes, Counter numPkts,
int actualDeviceId) {
static u_short lastHourId=0;
u_short hourId;
struct tm t, *thisTime;
if(numPkts == 0) return;
if((srcHost == NULL) || (dstHost == NULL)) {
traceEvent(CONST_TRACE_ERROR, "NULL host detected");
return;
}
CM_Update(srcHost->sent_to_matrix, dstHost->serialHostIndex, (int)numPkts);
CM_Update(dstHost->recv_from_matrix, srcHost->serialHostIndex, (int)numPkts);
updateASTraffic(actualDeviceId, srcHost->hostAS, dstHost->hostAS, (u_int)bytes.value);
if(srcHost == dstHost) {
return;
} else if((srcHost == myGlobals.otherHostEntry)
&& (dstHost == myGlobals.otherHostEntry)) {
return;
}
thisTime = localtime_r(&myGlobals.actTime, &t);
if(thisTime == NULL) {
myGlobals.actTime = time(NULL);
thisTime = localtime_r(&myGlobals.actTime, &t);
}
hourId = thisTime->tm_hour % 24 /* just in case... */;;
if(lastHourId != hourId) {
resetHourTraffic(hourId);
lastHourId = hourId;
}
if(srcHost != myGlobals.otherHostEntry) {
incrementHostTrafficCounter(srcHost, pktsSent, numPkts);
incrementHostTrafficCounter(srcHost, pktsSentSession, numPkts);
allocHostTrafficCounterMemory(srcHost, trafficDistribution, sizeof(TrafficDistribution));
if(srcHost->trafficDistribution == NULL) return;
incrementHostTrafficCounter(srcHost, trafficDistribution->last24HoursBytesSent[hourId], bytes.value);
incrementHostTrafficCounter(srcHost, bytesSent, bytes.value);
incrementHostTrafficCounter(srcHost, bytesSentSession, bytes.value);
}
if(dstHost != myGlobals.otherHostEntry) {
incrementHostTrafficCounter(dstHost, pktsRcvd, numPkts);
incrementHostTrafficCounter(dstHost, pktsRcvdSession, numPkts);
allocHostTrafficCounterMemory(dstHost, trafficDistribution, sizeof(TrafficDistribution));
if(dstHost->trafficDistribution == NULL) return;
incrementHostTrafficCounter(dstHost, trafficDistribution->last24HoursBytesRcvd[hourId], bytes.value);
incrementHostTrafficCounter(dstHost, bytesRcvd, bytes.value);
incrementHostTrafficCounter(dstHost, bytesRcvdSession, bytes.value);
}
if(broadcastHost(dstHost)) {
if(srcHost != myGlobals.otherHostEntry) {
incrementHostTrafficCounter(srcHost, pktsBroadcastSent, numPkts);
incrementHostTrafficCounter(srcHost, bytesBroadcastSent, bytes.value);
}
incrementTrafficCounter(&myGlobals.device[actualDeviceId].broadcastPkts, numPkts);
} else if(isMulticastAddress(&(dstHost->hostIpAddress), NULL, NULL)) {
#ifdef DEBUG
traceEvent(CONST_TRACE_INFO, "%s->%s",
srcHost->hostResolvedName, dstHost->hostResolvedName);
#endif
if(srcHost != myGlobals.otherHostEntry) {
incrementHostTrafficCounter(srcHost, pktsMulticastSent, numPkts);
incrementHostTrafficCounter(srcHost, bytesMulticastSent, bytes.value);
}
if(dstHost != myGlobals.otherHostEntry) {
incrementHostTrafficCounter(dstHost, pktsMulticastRcvd, numPkts);
incrementHostTrafficCounter(dstHost, bytesMulticastRcvd, bytes.value);
}
incrementTrafficCounter(&myGlobals.device[actualDeviceId].multicastPkts, numPkts);
}
if((dstHost != NULL) /*&& (!broadcastHost(dstHost))*/)
addContactedPeers(srcHost, &srcHost->hostIpAddress, dstHost, &dstHost->hostIpAddress, actualDeviceId);
}
/* ************************************ */
void updateHostName(HostTraffic *el) {
if((el->hostNumIpAddress[0] == '\0')
|| (el->hostResolvedName == NULL)
|| (el->hostResolvedNameType == FLAG_HOST_SYM_ADDR_TYPE_NONE)
|| strcmp(el->hostResolvedName, el->hostNumIpAddress) == 0) {
int i;
if(el->nonIPTraffic == NULL) {
el->nonIPTraffic = (NonIPTraffic*)calloc(1, sizeof(NonIPTraffic));
if(el->nonIPTraffic == NULL) return; /* Not enough memory */
}
if(el->nonIPTraffic->nbHostName != NULL) {
/*
Use NetBIOS name (when available) if the
IP address has not been resolved.
*/
memset(el->hostResolvedName, 0, sizeof(el->hostResolvedName));
setResolvedName(el, el->nonIPTraffic->nbHostName, FLAG_HOST_SYM_ADDR_TYPE_NETBIOS);
}
if(el->hostResolvedName[0] != '\0')
for(i=0; el->hostResolvedName[i] != '\0'; i++)
el->hostResolvedName[i] = (char)tolower(el->hostResolvedName[i]);
}
}
/* ************************************ */
void updateInterfacePorts(int actualDeviceId, u_short sport, u_short dport, u_int length) {
if((sport >= MAX_IP_PORT) || (dport >= MAX_IP_PORT) || (length == 0))
return;
accessMutex(&myGlobals.purgePortsMutex, "updateInterfacePorts");
if(myGlobals.device[actualDeviceId].ipPorts == NULL)
allocDeviceMemory(actualDeviceId);
if(myGlobals.device[actualDeviceId].ipPorts[sport] == NULL) {
myGlobals.device[actualDeviceId].ipPorts[sport] = (PortCounter*)malloc(sizeof(PortCounter));
if(myGlobals.device[actualDeviceId].ipPorts[sport] == NULL) {
releaseMutex(&myGlobals.purgePortsMutex);
return;
}
myGlobals.device[actualDeviceId].ipPorts[sport]->port = sport;
myGlobals.device[actualDeviceId].ipPorts[sport]->sent = 0;
myGlobals.device[actualDeviceId].ipPorts[sport]->rcvd = 0;
}
if(myGlobals.device[actualDeviceId].ipPorts[dport] == NULL) {
myGlobals.device[actualDeviceId].ipPorts[dport] = (PortCounter*)malloc(sizeof(PortCounter));
if(myGlobals.device[actualDeviceId].ipPorts[dport] == NULL) {
releaseMutex(&myGlobals.purgePortsMutex);
return;
}
myGlobals.device[actualDeviceId].ipPorts[dport]->port = dport;
myGlobals.device[actualDeviceId].ipPorts[dport]->sent = 0;
myGlobals.device[actualDeviceId].ipPorts[dport]->rcvd = 0;
}
myGlobals.device[actualDeviceId].ipPorts[sport]->sent += length;
myGlobals.device[actualDeviceId].ipPorts[dport]->rcvd += length;
releaseMutex(&myGlobals.purgePortsMutex);
}
/* ************************************ */
void incrementUnknownProto(HostTraffic *host,
int direction,
u_int16_t eth_type,
u_int16_t dsap, u_int16_t ssap,
u_int16_t ipProto) {
int i;
if(host->nonIPTraffic == NULL) {
host->nonIPTraffic = (NonIPTraffic*)calloc(1, sizeof(NonIPTraffic));
if(host->nonIPTraffic == NULL) return;
}
if(direction == 0) {
/* Sent */
if(host->nonIPTraffic->unknownProtoSent == NULL) {
host->nonIPTraffic->unknownProtoSent = (UnknownProto*)malloc(sizeof(UnknownProto)*
MAX_NUM_UNKNOWN_PROTOS);
if(host->nonIPTraffic->unknownProtoSent == NULL) return;
memset(host->nonIPTraffic->unknownProtoSent, 0, sizeof(UnknownProto)*MAX_NUM_UNKNOWN_PROTOS);
}
for(i=0; i<MAX_NUM_UNKNOWN_PROTOS; i++) {
if(host->nonIPTraffic->unknownProtoSent[i].protoType == 0) break;
if((host->nonIPTraffic->unknownProtoSent[i].protoType == 1) && eth_type) {
if(host->nonIPTraffic->unknownProtoSent[i].proto.ethType == eth_type) { return; }
} else if((host->nonIPTraffic->unknownProtoSent[i].protoType == 2) && (dsap || ssap)) {
if((host->nonIPTraffic->unknownProtoSent[i].proto.sapType.dsap == dsap)
&& (host->nonIPTraffic->unknownProtoSent[i].proto.sapType.ssap == ssap)) { return; }
} else if((host->nonIPTraffic->unknownProtoSent[i].protoType == 3) && ipProto) {
if(host->nonIPTraffic->unknownProtoSent[i].proto.ipType == ipProto) { return; }
}
}
if(i<MAX_NUM_UNKNOWN_PROTOS) {
if(eth_type) {
host->nonIPTraffic->unknownProtoSent[i].protoType = 1;
host->nonIPTraffic->unknownProtoSent[i].proto.ethType = eth_type;
} else if(dsap || ssap) {
host->nonIPTraffic->unknownProtoSent[i].protoType = 2;
host->nonIPTraffic->unknownProtoSent[i].proto.sapType.dsap = dsap;
host->nonIPTraffic->unknownProtoSent[i].proto.sapType.ssap = ssap;
} else {
host->nonIPTraffic->unknownProtoSent[i].protoType = 3;
host->nonIPTraffic->unknownProtoSent[i].proto.ipType = ipProto;
}
}
} else {
/* Rcvd */
if(host->nonIPTraffic->unknownProtoRcvd == NULL) {
host->nonIPTraffic->unknownProtoRcvd = (UnknownProto*)malloc(sizeof(UnknownProto)*
MAX_NUM_UNKNOWN_PROTOS);
if(host->nonIPTraffic->unknownProtoRcvd == NULL) return;
memset(host->nonIPTraffic->unknownProtoRcvd, 0, sizeof(UnknownProto)*MAX_NUM_UNKNOWN_PROTOS);
}
for(i=0; i<MAX_NUM_UNKNOWN_PROTOS; i++) {
if(host->nonIPTraffic->unknownProtoRcvd[i].protoType == 0) break;
if((host->nonIPTraffic->unknownProtoRcvd[i].protoType == 1) && eth_type) {
if(host->nonIPTraffic->unknownProtoRcvd[i].proto.ethType == eth_type) { return; }
} else if((host->nonIPTraffic->unknownProtoRcvd[i].protoType == 2) && (dsap || ssap)) {
if((host->nonIPTraffic->unknownProtoRcvd[i].proto.sapType.dsap == dsap)
&& (host->nonIPTraffic->unknownProtoRcvd[i].proto.sapType.ssap == ssap)) { return; }
} else if((host->nonIPTraffic->unknownProtoRcvd[i].protoType == 3) && ipProto) {
if(host->nonIPTraffic->unknownProtoRcvd[i].proto.ipType == ipProto) { return; }
}
}
if(i<MAX_NUM_UNKNOWN_PROTOS) {
if(eth_type) {
host->nonIPTraffic->unknownProtoRcvd[i].protoType = 1;
host->nonIPTraffic->unknownProtoRcvd[i].proto.ethType = eth_type;
} else if(dsap || ssap) {
host->nonIPTraffic->unknownProtoRcvd[i].protoType = 2;
host->nonIPTraffic->unknownProtoRcvd[i].proto.sapType.dsap = dsap;
host->nonIPTraffic->unknownProtoRcvd[i].proto.sapType.ssap = ssap;
} else {
host->nonIPTraffic->unknownProtoRcvd[i].protoType = 3;
host->nonIPTraffic->unknownProtoRcvd[i].proto.ipType = ipProto;
}
}
}
}
/* ************************************ */
static AsStats* allocASStats(u_int16_t as_id) {
AsStats *asStats = (AsStats*)malloc(sizeof(AsStats));
if(0) traceEvent(CONST_TRACE_WARNING, "Allocating stats for AS %d", as_id);
if(asStats != NULL) {
memset(asStats, 0, sizeof(AsStats));
asStats->as_id = as_id;
resetTrafficCounter(&asStats->outBytes);
resetTrafficCounter(&asStats->outPkts);
resetTrafficCounter(&asStats->inBytes);
resetTrafficCounter(&asStats->inPkts);
resetTrafficCounter(&asStats->selfBytes);
resetTrafficCounter(&asStats->selfPkts);
}
return(asStats);
}
/* ************************************ */
static void updateASTraffic(int actualDeviceId, u_int16_t src_as_id,
u_int16_t dst_as_id, u_int octets) {
AsStats *stats, *prev_stats = NULL;
u_char found_src = 0, found_dst = 0;
if(0)
traceEvent(CONST_TRACE_INFO, "updateASTraffic(actualDeviceId=%d, src_as_id=%d, dst_as_id=%d, octets=%d)",
actualDeviceId, src_as_id, dst_as_id, octets);
if((src_as_id == 0) && (dst_as_id == 0))
return;
accessMutex(&myGlobals.device[actualDeviceId].asMutex, "updateASTraffic");
stats = myGlobals.device[actualDeviceId].asStats;
while(stats) {
if(stats->as_id == src_as_id) {
stats->lastUpdate = myGlobals.actTime;
incrementTrafficCounter(&stats->outBytes, octets), incrementTrafficCounter(&stats->outPkts, 1), stats->totPktsSinceLastRRDDump++;
if(src_as_id == dst_as_id) {
incrementTrafficCounter(&stats->selfBytes, octets), incrementTrafficCounter(&stats->selfPkts, 1);
releaseMutex(&myGlobals.device[actualDeviceId].asMutex);
return;
}
if(dst_as_id == 0) {
releaseMutex(&myGlobals.device[actualDeviceId].asMutex);
return;
} else
found_src = 1;
} else if(stats->as_id == dst_as_id) {
stats->lastUpdate = myGlobals.actTime;
incrementTrafficCounter(&stats->inBytes, octets), incrementTrafficCounter(&stats->inPkts, 1), stats->totPktsSinceLastRRDDump++;
if(src_as_id == dst_as_id) {
incrementTrafficCounter(&stats->selfBytes, octets), incrementTrafficCounter(&stats->selfPkts, 1);
releaseMutex(&myGlobals.device[actualDeviceId].asMutex);
return;
}
if(src_as_id == 0) {
releaseMutex(&myGlobals.device[actualDeviceId].asMutex);
return;
} else
found_dst = 1;
}
if(found_src && found_dst) {
releaseMutex(&myGlobals.device[actualDeviceId].asMutex);
return;
}
if((myGlobals.actTime-stats->lastUpdate) > PARM_AS_MAXIMUM_IDLE) {
AsStats *next = stats->next;
if(0) traceEvent(CONST_TRACE_INFO, "Purging stats about AS %d", stats->as_id);
if(prev_stats == NULL)
myGlobals.device[actualDeviceId].asStats = next;
else
prev_stats->next = next;
free(stats);
stats = next;
} else {
prev_stats = stats;
stats = stats->next;
}
} /* while */
/* One (or both) ASs are missing */
if((src_as_id != 0) && (!found_src)) {
stats = allocASStats(src_as_id);
stats->next = myGlobals.device[actualDeviceId].asStats;
stats->lastUpdate = myGlobals.actTime;
myGlobals.device[actualDeviceId].asStats = stats;
}
if((dst_as_id != 0) && (dst_as_id != src_as_id) && (!found_dst)) {
stats = allocASStats(dst_as_id);
stats->next = myGlobals.device[actualDeviceId].asStats;
stats->lastUpdate = myGlobals.actTime;
myGlobals.device[actualDeviceId].asStats = stats;
}
releaseMutex(&myGlobals.device[actualDeviceId].asMutex);
/* We created the AS entry so we now need to update the AS information */
updateASTraffic(actualDeviceId, src_as_id, dst_as_id, octets);
}
/* ************************************ */
#undef DEBUG
void queuePacket(u_char *_deviceId,
const struct pcap_pkthdr *h,
const u_char *p) {
int len, deviceId, actDeviceId;
/* ***************************
- If the queue is full then wait until a slot is freed
- If the queue is getting full then periodically wait
until a slot is freed
**************************** */
#ifdef MAX_PROCESS_BUFFER
if(myGlobals.queueBufferInit == 0) {
myGlobals.queueBufferCount = 0;
myGlobals.queueBufferInit = 1;
memset(&myGlobals.queueBuffer, 0, sizeof(myGlobals.queueBuffer));
}
#endif
myGlobals.receivedPackets++;
if((p == NULL) || (h == NULL)) {
traceEvent(CONST_TRACE_WARNING, "Invalid packet received. Skipped.");
}
#ifdef WIN32_DEMO
if(myGlobals.receivedPackets >= MAX_NUM_PACKETS)
return;
#endif
if(myGlobals.ntopRunState > FLAG_NTOPSTATE_RUN) return;
deviceId = (int)((long)_deviceId);
actDeviceId = getActualInterface(deviceId);
incrementTrafficCounter(&myGlobals.device[actDeviceId].receivedPkts, 1);
/* We assume that if there's a packet to queue for the sFlow interface
then this has been queued by the sFlow plugins, while it was
probably handling a queued packet */
#ifdef DEBUG
traceEvent(CONST_TRACE_INFO, "queuePacket: got packet from %s (%d)",
myGlobals.device[deviceId].name, deviceId);
#endif
/* We don't sample on sFlow sampled interfaces */
if(myGlobals.device[deviceId].sflowGlobals == NULL) {
if(myGlobals.device[actDeviceId].samplingRate > 1) {
if(myGlobals.device[actDeviceId].droppedSamples < myGlobals.device[actDeviceId].samplingRate) {
myGlobals.device[actDeviceId].droppedSamples++;
return; /* Not enough samples received */
} else
myGlobals.device[actDeviceId].droppedSamples = 0;
}
}
if(h->len < 60) {
/* Filter out noise */
updateDevicePacketStats(h->len, actDeviceId);
return;
}
if(tryLockMutex(&myGlobals.device[deviceId].packetProcessMutex, "queuePacket") == 0) {
/* Locked so we can process the packet now */
u_char p1[MAX_PACKET_LEN];
myGlobals.receivedPacketsProcessed++;
len = h->caplen;
if(h->caplen >= MAX_PACKET_LEN) {
if(h->caplen > myGlobals.device[deviceId].mtuSize) {
#ifndef WIN32
static u_int8_t msg_shown = 0;
if(!msg_shown) {
traceEvent(CONST_TRACE_WARNING, "Packet truncated (%d->%d): using LRO perhaps ?", h->len, MAX_PACKET_LEN);
msg_shown = 1;
}
#endif
}
((struct pcap_pkthdr*)h)->caplen = len = MAX_PACKET_LEN-1;
}
memcpy(p1, p, len);
processPacket(_deviceId, h, p1);
releaseMutex(&myGlobals.device[deviceId].packetProcessMutex);
return;
}
/*
If we reach this point it means that somebody was already
processing a packet so we need to queue it.
*/
if(myGlobals.device[deviceId].packetQueueLen >= CONST_PACKET_QUEUE_LENGTH) {
#ifdef DEBUG
traceEvent(CONST_TRACE_INFO, "Dropping packet [packet queue=%d/max=%d][id=%d]",
myGlobals.device[deviceId].packetQueueLen, myGlobals.maxPacketQueueLen, deviceId);
#endif
myGlobals.receivedPacketsLostQ++;
incrementTrafficCounter(&myGlobals.device[getActualInterface(deviceId)].droppedPkts, 1);
ntop_conditional_sched_yield(); /* Allow other threads (dequeue) to run */
sleep(1);
} else {
#ifdef DEBUG
traceEvent(CONST_TRACE_INFO, "About to queue packet... ");
#endif
accessMutex(&myGlobals.device[deviceId].packetQueueMutex, "queuePacket");
myGlobals.receivedPacketsQueued++;
memcpy(&myGlobals.device[deviceId].packetQueue[myGlobals.device[deviceId].packetQueueHead].h,
h, sizeof(struct pcap_pkthdr));
memset(myGlobals.device[deviceId].packetQueue[myGlobals.device[deviceId].packetQueueHead].p, 0,
sizeof(myGlobals.device[deviceId].packetQueue[myGlobals.device[deviceId].packetQueueHead].p));
/* Just to be safe */
len = h->caplen;
memcpy(myGlobals.device[deviceId].packetQueue[myGlobals.device[deviceId].packetQueueHead].p, p, len);
myGlobals.device[deviceId].packetQueue[myGlobals.device[deviceId].packetQueueHead].h.caplen = len;
myGlobals.device[deviceId].packetQueue[myGlobals.device[deviceId].packetQueueHead].deviceId =
(int)((long)((void*)_deviceId));
myGlobals.device[deviceId].packetQueueHead = (myGlobals.device[deviceId].packetQueueHead+1)
% CONST_PACKET_QUEUE_LENGTH;
myGlobals.device[deviceId].packetQueueLen++;
if(myGlobals.device[deviceId].packetQueueLen > myGlobals.device[deviceId].maxPacketQueueLen)
myGlobals.device[deviceId].maxPacketQueueLen = myGlobals.device[deviceId].packetQueueLen;
releaseMutex(&myGlobals.device[deviceId].packetQueueMutex);
#ifdef DEBUG
traceEvent(CONST_TRACE_INFO, "Queued packet... [packet queue=%d/max=%d]",
myGlobals.device[deviceId].packetQueueLen, myGlobals.maxPacketQueueLen);
#endif
#ifdef DEBUG_THREADS
traceEvent(CONST_TRACE_INFO, "+ [packet queue=%d/max=%d]",
myGlobals.device[deviceId].packetQueueLen, myGlobals.maxPacketQueueLen);
#endif
}
signalCondvar(&myGlobals.device[deviceId].queueCondvar, 0);
ntop_conditional_sched_yield(); /* Allow other threads (dequeue) to run */
}
/* ************************************ */
void cleanupPacketQueue(void) {
; /* Nothing to do */
}
/* ************************************ */
void* dequeuePacket(void* _deviceId) {
u_int deviceId = (u_int)((long)_deviceId);
struct pcap_pkthdr h;
u_char p[MAX_PACKET_LEN];
traceEvent(CONST_TRACE_INFO,
"THREADMGMT[t%lu]: NPA: network packet analyzer (packet processor) thread running [p%d]",
(long unsigned int)pthread_self(), getpid());
/* Don't bother stalling until RUN, start grabbing packets NOW ... */
while(myGlobals.ntopRunState <= FLAG_NTOPSTATE_RUN) {
#ifdef DEBUG
traceEvent(CONST_TRACE_INFO, "Waiting for packet...");
#endif
while((myGlobals.device[deviceId].packetQueueLen == 0) &&
(myGlobals.ntopRunState <= FLAG_NTOPSTATE_RUN) /* Courtesy of Wies-Software <[email protected]> */) {
waitCondvar(&myGlobals.device[deviceId].queueCondvar);
}
if(myGlobals.ntopRunState > FLAG_NTOPSTATE_RUN) break;
#ifdef DEBUG
traceEvent(CONST_TRACE_INFO, "Got packet...");
#endif
accessMutex(&myGlobals.device[deviceId].packetQueueMutex, "dequeuePacket");
memcpy(&h, &myGlobals.device[deviceId].packetQueue[myGlobals.device[deviceId].packetQueueTail].h,
sizeof(struct pcap_pkthdr));
deviceId = myGlobals.device[deviceId].packetQueue[myGlobals.device[deviceId].packetQueueTail].deviceId;
/* This code should be changed ASAP. It is a bad trick that avoids ntop to
go beyond packet boundaries (L.Deri 17/03/2003)
1. h->len is truncated
2. MAX_PACKET_LEN should probably be removed
3. all the functions must check that they are not going beyond packet boundaries
*/
if((h.caplen != h.len)
&& (myGlobals.device[deviceId].sflowGlobals == NULL) /* This warning is normal for sFlow */
&& (myGlobals.runningPref.enablePacketDecoding /* Courtesy of Ken Beaty <[email protected]> */))
traceEvent (CONST_TRACE_WARNING, "dequeuePacket: caplen %d != len %d\n", h.caplen, h.len);
memcpy(p, myGlobals.device[deviceId].packetQueue[myGlobals.device[deviceId].packetQueueTail].p, MAX_PACKET_LEN);
if(h.len > MAX_PACKET_LEN) {
static u_int8_t msg_shown = 0;
if(!msg_shown) {
traceEvent(CONST_TRACE_WARNING, "Packet truncated (%d->%d): using LRO perhaps ?", h.len, MAX_PACKET_LEN);
msg_shown = 1;
}
h.len = MAX_PACKET_LEN;
}
myGlobals.device[deviceId].packetQueueTail = (myGlobals.device[deviceId].packetQueueTail+1) % CONST_PACKET_QUEUE_LENGTH;
myGlobals.device[deviceId].packetQueueLen--;
releaseMutex(&myGlobals.device[deviceId].packetQueueMutex);
#ifdef DEBUG_THREADS
traceEvent(CONST_TRACE_INFO, "- [packet queue=%d/max=%d]", myGlobals.device[deviceId].packetQueueLen, myGlobals.maxPacketQueueLen);
#endif
#ifdef DEBUG
traceEvent(CONST_TRACE_INFO, "Processing packet... [packet queue=%d/max=%d][id=%d]",
myGlobals.device[deviceId].packetQueueLen, myGlobals.maxPacketQueueLen, deviceId);
#endif
myGlobals.actTime = time(NULL);
accessMutex(&myGlobals.device[deviceId].packetProcessMutex, "dequeuePacket");
processPacket((u_char*)((long)deviceId), &h, p);
releaseMutex(&myGlobals.device[deviceId].packetProcessMutex);
}
myGlobals.device[deviceId].dequeuePacketThreadId = 0;
traceEvent(CONST_TRACE_INFO,
"THREADMGMT[t%lu]: NPA: network packet analyzer (%s) thread terminated [p%d]",
(long unsigned int)pthread_self(),
myGlobals.device[deviceId].humanFriendlyName, getpid());
return(NULL);
}
/* ************************************ */
static void flowsProcess(const struct pcap_pkthdr *h, const u_char *p, int deviceId) {
FlowFilterList *list = myGlobals.flowsList;
while(list != NULL) {
#ifdef DEBUG
if(!list->pluginStatus.activePlugin)
traceEvent(CONST_TRACE_NOISY, "%s inactive", list->flowName);
else if(list->fcode[deviceId].bf_insns == NULL)
traceEvent(CONST_TRACE_NOISY, "%s no filter", list->flowName);
#endif
if((list->pluginStatus.activePlugin) &&
(list->fcode[deviceId].bf_insns != NULL)) {
#ifdef DEBUG
{
struct ether_header *ep;
u_int16_t et=0, et8021q=0;
ep = (struct ether_header *)p;
et = ntohs(ep->ether_type);
if(et == ETHERTYPE_802_1Q) {
et8021q = et;
ep = (struct ether_header *)(p+4);
et = ntohs(ep->ether_type);
}
traceEvent(CONST_TRACE_NOISY, "%smatch on %s for '%s' %s0x%04x-%s-%d/%d",
bpf_filter(list->fcode[deviceId].bf_insns, (u_char*)p, h->len, h->caplen) ?
"" : "No ",
myGlobals.device[deviceId].name,
list->flowName,
et8021q == ETHERTYPE_802_1Q ? "(802.1q) " : "",
et,
et == ETHERTYPE_IP ? "IPv4" :
et == ETHERTYPE_IPv6 ? "IPv6" :
et == ETHERTYPE_ARP ? "ARP" :
et == ETHERTYPE_REVARP ? "RARP" :
"other",
h->len, h->caplen);
}
#endif
if(bpf_filter(list->fcode[deviceId].bf_insns, (u_char*)p, h->len, h->caplen)) {
incrementTrafficCounter(&list->bytes, h->len);
incrementTrafficCounter(&list->packets, 1);
if(list->pluginStatus.pluginPtr != NULL) {
void(*pluginFunct)(u_char*, const struct pcap_pkthdr*, const u_char*);
pluginFunct = (void(*)(u_char *_deviceId, const struct pcap_pkthdr*,
const u_char*))list->pluginStatus.pluginPtr->pluginFunct;
pluginFunct((u_char*)&deviceId, h, p);
}
}
}
list = list->next;
}
}
/* ************************************ */
static void addNonIpTrafficInfo(HostTraffic *el, u_int16_t proto,
u_short len, u_int direction) {
NonIpProtoTrafficInfo *nonIp;
int numIterations;
if(el->nonIpProtoTrafficInfos == NULL)
goto notFoundProto;
else
nonIp = el->nonIpProtoTrafficInfos;
numIterations = 0;
while(nonIp != NULL) {
if(nonIp->protocolId == proto)
break;
numIterations++;
if(numIterations == MAX_NUM_NON_IP_PROTO_TRAFFIC_INFO)
return; /* Too many protocols */
nonIp = nonIp->next;
}
if(nonIp == NULL) {
notFoundProto:
/* Protocol not found */
nonIp = (NonIpProtoTrafficInfo*)calloc(1, sizeof(NonIpProtoTrafficInfo));
if(nonIp == NULL) return;
nonIp->next = el->nonIpProtoTrafficInfos;
el->nonIpProtoTrafficInfos = nonIp;
nonIp->protocolId = proto;
}
if(direction == 0)
incrementTrafficCounter(&nonIp->sentPkts, 1), incrementTrafficCounter(&nonIp->sentBytes, len);
else
incrementTrafficCounter(&nonIp->rcvdPkts, 1), incrementTrafficCounter(&nonIp->rcvdBytes, len);
}
/* ************************************ */
void updateDevicePacketStats(u_int length, int actualDeviceId) {
if(length <= 64) incrementTrafficCounter(&myGlobals.device[actualDeviceId].rcvdPktStats.upTo64, 1);
else if(length <= 128) incrementTrafficCounter(&myGlobals.device[actualDeviceId].rcvdPktStats.upTo128, 1);
else if(length <= 256) incrementTrafficCounter(&myGlobals.device[actualDeviceId].rcvdPktStats.upTo256, 1);
else if(length <= 512) incrementTrafficCounter(&myGlobals.device[actualDeviceId].rcvdPktStats.upTo512, 1);
else if(length <= 1024) incrementTrafficCounter(&myGlobals.device[actualDeviceId].rcvdPktStats.upTo1024, 1);
else if(length <= 1518) incrementTrafficCounter(&myGlobals.device[actualDeviceId].rcvdPktStats.upTo1518, 1);
#ifdef MAKE_WITH_JUMBO_FRAMES
else if(length <= 2500) incrementTrafficCounter(&myGlobals.device[actualDeviceId].rcvdPktStats.upTo2500, 1);
else if(length <= 6500) incrementTrafficCounter(&myGlobals.device[actualDeviceId].rcvdPktStats.upTo6500, 1);
else if(length <= 9000) incrementTrafficCounter(&myGlobals.device[actualDeviceId].rcvdPktStats.upTo9000, 1);
else incrementTrafficCounter(&myGlobals.device[actualDeviceId].rcvdPktStats.above9000, 1);
#else
else incrementTrafficCounter(&myGlobals.device[actualDeviceId].rcvdPktStats.above1518, 1);
#endif
if((myGlobals.device[actualDeviceId].rcvdPktStats.shortest.value == 0)
|| (myGlobals.device[actualDeviceId].rcvdPktStats.shortest.value > length))
myGlobals.device[actualDeviceId].rcvdPktStats.shortest.value = length;
if(myGlobals.device[actualDeviceId].rcvdPktStats.longest.value < length)
myGlobals.device[actualDeviceId].rcvdPktStats.longest.value = length;
}
/* ***************************************************** */
void dumpSuspiciousPacket(int actualDeviceId, const struct pcap_pkthdr *h, const u_char *p) {
if((p == NULL) || (h == NULL)) return;
if(myGlobals.device[actualDeviceId].pcapErrDumper != NULL) {
pcap_dump((u_char*)myGlobals.device[actualDeviceId].pcapErrDumper, h, p);
traceEvent(CONST_TRACE_INFO, "Dumped %d bytes suspicious packet", h->caplen);
}
}
/* ***************************************************** */
void dumpOtherPacket(int actualDeviceId, const struct pcap_pkthdr *h, const u_char *p) {
if((p == NULL) || (h == NULL)) return;
if(myGlobals.device[actualDeviceId].pcapOtherDumper != NULL)
pcap_dump((u_char*)myGlobals.device[actualDeviceId].pcapOtherDumper, h, p);
}
/* ***************************************************** */
/*
* This is the top level routine of the printer. 'p' is the points
* to the ether header of the packet, 'tvp' is the timestamp,
* 'length' is the length of the packet off the wire, and 'caplen'
* is the number of bytes actually captured.
*/
void processPacket(u_char *_deviceId,
const struct pcap_pkthdr *h,
const u_char *p) {
struct ether_header ehdr;
struct tokenRing_header *trp;
u_int hlen, caplen = h->caplen;
u_int headerDisplacement = 0, length = h->len;
const u_char *orig_p = p, *p1;
u_char *ether_src=NULL, *ether_dst=NULL;
u_short eth_type=0;
/* Token-Ring Strings */
struct tokenRing_llc *trllc;
int deviceId, actualDeviceId;
u_int16_t vlanId=NO_VLAN;
static time_t lastUpdateThptTime = 0;
#ifdef LINUX
AnyHeader *anyHeader;
#endif
#ifdef MAX_PROCESS_BUFFER
struct timeval pktStartOfProcessing,
pktEndOfProcessing;
#endif
#ifdef MEMORY_DEBUG
#ifdef MEMORY_DEBUG_UNLIMITED
#warning MEMORY_DEBUG defined for UNLIMITED usage!
#else
#ifdef MEMORY_DEBUG_PACKETS
{
static long numPkt=0;
if(++numPkt >= MEMORY_DEBUG_PACKETS) {
traceEvent(CONST_TRACE_ALWAYSDISPLAY,
"NOTE: ntop shutting down - memory debug packet limit (%d) reached",
MEMORY_DEBUG_PACKETS);
cleanup(1);
}
}
#endif /* MEMORY_DEBUG_PACKETS */
#ifdef MEMORY_DEBUG_SECONDS
{
static time_t memoryDebugAbortTime=0;
if(memoryDebugAbortTime == 0) {
memoryDebugAbortTime = time(NULL) + MEMORY_DEBUG_SECONDS;
} else if(time(NULL) > memoryDebugAbortTime) {
traceEvent(CONST_TRACE_ALWAYSDISPLAY,
"NOTE: ntop shutting down - memory debug abort time reached");
cleanup(1);
}
}
#endif /* MEMORY_DEBUG_SECONDS */
#endif /* MEMORY_DEBUG_UNLIMITED */
#endif /* MEMORY_DEBUG */
if(myGlobals.ntopRunState > FLAG_NTOPSTATE_RUN)
return;
/*
This allows me to fetch the time from
the captured packet instead of calling
time(NULL).
*/
myGlobals.actTime = h->ts.tv_sec;
deviceId = (int)((long)_deviceId);
actualDeviceId = getActualInterface(deviceId);
#ifdef DEBUG
traceEvent(CONST_TRACE_INFO, "deviceId=%d - actualDeviceId=%ld", deviceId, actualDeviceId);
#endif
#ifdef MAX_PROCESS_BUFFER
{
float elapsed;
gettimeofday(&pktStartOfProcessing, NULL);
elapsed = timeval_subtract(pktStartOfProcessing, h->ts);
if(elapsed < 0) elapsed = 0;
myGlobals.queueBuffer[++myGlobals.queueBufferCount & (MAX_PROCESS_BUFFER - 1)] = elapsed;
if((myGlobals.device[actualDeviceId].ethernetPkts.value > 100) && (elapsed > myGlobals.qmaxDelay))
myGlobals.qmaxDelay = elapsed;
}
#endif
#ifdef DEBUG
if(myGlobals.pcap_file_list != NULL) {
traceEvent(CONST_TRACE_INFO, ".");
fflush(stdout);
}
#endif
updateDevicePacketStats(length, actualDeviceId);
incrementTrafficCounter(&myGlobals.device[actualDeviceId].ethernetPkts, 1);
incrementTrafficCounter(&myGlobals.device[actualDeviceId].ethernetBytes, h->len);
if(myGlobals.runningPref.mergeInterfaces && actualDeviceId != deviceId)
incrementTrafficCounter(&myGlobals.device[deviceId].ethernetPkts, 1);
if(myGlobals.device[actualDeviceId].pcapDumper != NULL)
pcap_dump((u_char*)myGlobals.device[actualDeviceId].pcapDumper, h, p);
if((myGlobals.device[deviceId].mtuSize != CONST_UNKNOWN_MTU) &&
(length > myGlobals.device[deviceId].mtuSize) ) {
/* Sanity check */
if(myGlobals.runningPref.enableSuspiciousPacketDump) {
traceEvent(CONST_TRACE_WARNING, "Packet # %u too long (len = %u)!",
(unsigned int)myGlobals.device[deviceId].ethernetPkts.value,
(unsigned int)length);
dumpSuspiciousPacket(actualDeviceId, h, p);
}
/* Fix below courtesy of Andreas Pfaller <[email protected]> */
length = myGlobals.device[deviceId].mtuSize;
incrementTrafficCounter(&myGlobals.device[actualDeviceId].rcvdPktStats.tooLong, 1);
}
#ifdef DEBUG
traceEvent(CONST_TRACE_INFO, "actualDeviceId = %d", actualDeviceId);
#endif
/* Note: The code below starts by assuming that if we haven't captured at
* least an Ethernet frame header's worth of bytes we drop the packet.
* This might be a bad assumption - why aren't we using the DLT_ derived fields?
* e.g.: hlen = myGlobals.device[deviceId].headerSize;
* Also, we probably should account for these runt packets - both count the
* # of packets and the associated # of bytes.
*/
hlen = (u_int)((myGlobals.device[deviceId].datalink == DLT_NULL) ? CONST_NULL_HDRLEN : sizeof(struct ether_header));
if(!myGlobals.initialSniffTime && (myGlobals.pcap_file_list != NULL)) {
myGlobals.initialSniffTime = h->ts.tv_sec;
myGlobals.device[deviceId].lastThptUpdate = myGlobals.device[deviceId].lastMinThptUpdate =
myGlobals.device[deviceId].lastHourThptUpdate = myGlobals.device[deviceId].lastFiveMinsThptUpdate = myGlobals.initialSniffTime;
}
memcpy(&myGlobals.lastPktTime, &h->ts, sizeof(myGlobals.lastPktTime));
if(caplen >= hlen) {
HostTraffic *srcHost = NULL, *dstHost = NULL;
memcpy(&ehdr, p, sizeof(struct ether_header));
switch(myGlobals.device[deviceId].datalink) {