aboutsummaryrefslogtreecommitdiff
path: root/wireshark/ndpi.lua
blob: f9db384119c7bdd227a6093ad4944d7197820737 (plain)
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
--
-- (C) 2017 - ntop.org
--
-- This plugin is part of nDPI (https://github.com/ntop/nDPI)
--
-- 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 3 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.
--

local ndpi_proto = Proto("ndpi", "nDPI", "nDPI Protocol Interpreter")
ndpi_proto.fields = {}

local ndpi_fds    = ndpi_proto.fields
ndpi_fds.network_protocol     = ProtoField.new("nDPI Network Protocol", "ndpi.protocol.network", ftypes.UINT8, nil, base.DEC)
ndpi_fds.application_protocol = ProtoField.new("nDPI Application Protocol", "ndpi.protocol.application", ftypes.UINT8, nil, base.DEC)
ndpi_fds.name                 = ProtoField.new("nDPI Protocol Name", "ndpi.protocol.name", ftypes.STRING)

local ntop_proto = Proto("ntop", "ntop", "ntop Extensions")
ntop_proto.fields = {}

local ntop_fds = ntop_proto.fields
ntop_fds.client_nw_rtt    = ProtoField.new("TCP client network RTT (msec)",  "ntop.latency.client_rtt", ftypes.FLOAT, nil, base.NONE)
ntop_fds.server_nw_rtt    = ProtoField.new("TCP server network RTT (msec)",  "ntop.latency.server_rtt", ftypes.FLOAT, nil, base.NONE)
ntop_fds.appl_latency_rtt = ProtoField.new("Application Latency RTT (msec)", "ntop.latency.appl_rtt",   ftypes.FLOAT, nil, base.NONE)

local f_eth_trailer       = Field.new("eth.trailer")
local f_vlan_id           = Field.new("vlan.id")
local f_arp_opcode        = Field.new("arp.opcode")
local f_arp_sender_mac    = Field.new("arp.src.hw_mac")
local f_arp_target_mac    = Field.new("arp.dst.hw_mac")
local f_dns_query_name    = Field.new("dns.qry.name")
local f_dns_ret_code      = Field.new("dns.flags.rcode")
local f_dns_response      = Field.new("dns.flags.response")
local f_udp_len           = Field.new("udp.length")
local f_tcp_header_len    = Field.new("tcp.hdr_len")
local f_ip_len            = Field.new("ip.len")
local f_ip_hdr_len        = Field.new("ip.hdr_len")
local f_ssl_server_name   = Field.new("ssl.handshake.extensions_server_name")
local f_tcp_flags         = Field.new('tcp.flags')

local ndpi_protos            = {}
local ndpi_flows             = {}
local num_ndpi_flows         = 0

local arp_stats              = {}
local mac_stats              = {}
local vlan_stats             = {}
local vlan_found             = false

local dns_responses_ok       = {}
local dns_responses_error    = {}
local dns_client_queries     = {}
local dns_server_responses   = {}
local dns_queries            = {}

local syn                    = {}
local synack                 = {}
local lower_ndpi_flow_id     = 0
local lower_ndpi_flow_volume = 0

local compute_flows_stats    = true
local max_num_entries        = 10
local max_num_flows          = 50

local num_top_dns_queries    = 0
local max_num_dns_queries    = 50

local ssl_server_names       = {}
local tot_ssl_flows          = 0

local min_nw_client_RRT      = {}
local min_nw_server_RRT      = {}
local max_nw_client_RRT      = {}
local max_nw_server_RRT      = {}
local min_appl_RRT           = {}
local max_appl_RRT           = {}

local first_payload_ts       = {}
local first_payload_id       = {}

local num_pkts               = 0
local last_processed_packet_number = 0
local max_latency_discard    = 5000  -- 5 sec
local max_appl_lat_discard   = 15000 -- 15 sec
local debug                  = false

-- ##############################################

function string.contains(String,Start)
   if type(String) ~= 'string' or type(Start) ~= 'string' then
      return false
   end
   return(string.find(String,Start,1) ~= nil)
end

-- ##############################################

function string.starts(String,Start)
   if type(String) ~= 'string' or type(Start) ~= 'string' then
      return false
   end
   return string.sub(String,1,string.len(Start))==Start
end

-- ##############################################

function string.ends(String,End)
   if type(String) ~= 'string' or type(End) ~= 'string' then
      return false
   end
   return End=='' or string.sub(String,-string.len(End))==End
end

-- ###############################################

function round(num, idp)
   return tonumber(string.format("%." .. (idp or 0) .. "f", num))
end

function formatPctg(p)
   local p = round(p, 1)

   if(p < 1) then return("< 1 %") end

   return p.." %"
end

-- ###############################################

string.split = function(s, p)
   local temp = {}
   local index = 0
   local last_index = string.len(s)

   while true do
      local i, e = string.find(s, p, index)

      if i and e then
	 local next_index = e + 1
	 local word_bound = i - 1
	 table.insert(temp, string.sub(s, index, word_bound))
	 index = next_index
      else
	 if index > 0 and index <= last_index then
	    table.insert(temp, string.sub(s, index, last_index))
	 elseif index == 0 then
	    temp = nil
	 end
	 break
      end
   end

   return temp
end

-- ##############################################

function shortenString(name, max_len)
   max_len = max_len or 24
   if(string.len(name) < max_len) then
      return(name)
   else
      return(string.sub(name, 1, max_len).."...")
   end
end

-- ###############################################

-- Convert bytes to human readable format
function bytesToSize(bytes)
   if(bytes == nil) then
      return("0")
   else
      precision = 2
      kilobyte = 1024;
      megabyte = kilobyte * 1024;
      gigabyte = megabyte * 1024;
      terabyte = gigabyte * 1024;

      bytes = tonumber(bytes)
      if((bytes >= 0) and (bytes < kilobyte)) then
	 return round(bytes, precision) .. " Bytes";
      elseif((bytes >= kilobyte) and (bytes < megabyte)) then
	 return round(bytes / kilobyte, precision) .. ' KB';
      elseif((bytes >= megabyte) and (bytes < gigabyte)) then
	 return round(bytes / megabyte, precision) .. ' MB';
      elseif((bytes >= gigabyte) and (bytes < terabyte)) then
	 return round(bytes / gigabyte, precision) .. ' GB';
      elseif(bytes >= terabyte) then
	 return round(bytes / terabyte, precision) .. ' TB';
      else
	 return round(bytes, precision) .. ' Bytes';
      end
   end
end

-- ###############################################

function pairsByValues(t, f)
   local a = {}
   for n in pairs(t) do table.insert(a, n) end
   table.sort(a, function(x, y) return f(t[x], t[y]) end)
   local i = 0      -- iterator variable
   local iter = function ()   -- iterator function
      i = i + 1
      if a[i] == nil then return nil
      else return a[i], t[a[i]]
      end
   end
   return iter
end

-- ###############################################

function asc(a,b) return (a < b) end
function rev(a,b) return (a > b) end

-- ###############################################

local function BitOR(a,b)--Bitwise or
   local p,c=1,0
   while a+b>0 do
      local ra,rb=a%2,b%2
      if ra+rb>0 then c=c+p end
      a,b,p=(a-ra)/2,(b-rb)/2,p*2
   end
   return c
end

local function BitNOT(n)
   local p,c=1,0
   while n>0 do
      local r=n%2
      if r<1 then c=c+p end
      n,p=(n-r)/2,p*2
   end
   return c
end

local function BitAND(a,b)--Bitwise and (portable edition)
   local p,c=1,0
   while a>0 and b>0 do
      local ra,rb=a%2,b%2
      if ra+rb>1 then c=c+p end
      a,b,p=(a-ra)/2,(b-rb)/2,p*2
   end
   return c
end

-- ###############################################

function ndpi_proto.init()
   ndpi_protos            = { }
   ndpi_flows             = { }

   num_ndpi_flows         = 0
   lower_ndpi_flow_id     = 0
   lower_ndpi_flow_volume = 0
   num_pkts               = 0
   last_processed_packet_number = 0

   -- ARP
   arp_stats              = { }

   -- MAC
   mac_stats              = { }

   -- VLAN
   vlan_stats             = { }
   vlan_found             = false

   -- TCP
   syn                    = {}
   synack                 = {}

   -- SSL
   ssl_server_names       = {}

   -- DNS
   dns_responses_ok       = {}
   dns_responses_error    = {}
   dns_client_queries     = {}
   dns_server_responses   = {}
   top_dns_queries        = {}
   num_top_dns_queries    = 0

   -- Network RRT
   min_nw_client_RRT  = {}
   min_nw_server_RRT  = {}
   max_nw_client_RRT  = {}
   max_nw_server_RRT  = {}

   -- Application Latency
   min_nw_client_RRT     = {}
   min_nw_server_RRT     = {}
   max_nw_client_RRT     = {}
   max_nw_server_RRT     = {}
   min_appl_RRT          = {}
   max_appl_RRT          = {}
   first_payload_ts      = {}
   first_payload_id      = {}
end

function slen(str)
   local i = 1
   local len = 0
   local zero = string.char(0)

   for i = 1, 16 do
      local c = str:sub(i,i)

      if(c ~= zero) then
	 len = len + 1
      else
	 break
      end
   end

   return(str:sub(1, len))
end

-- Print contents of `tbl`, with indentation.
-- You can call it as tprint(mytable)
-- The other two parameters should not be set
function tprint(s, l, i)
   l = (l) or 1000; i = i or "";-- default item limit, indent string
   if (l<1) then io.write("ERROR: Item limit reached.\n"); return l-1 end;
   local ts = type(s);
   if (ts ~= "table") then io.write(i..' '..ts..' '..tostring(s)..'\n'); return l-1 end
   io.write(i..' '..ts..'\n');
   for k,v in pairs(s) do
      local indent = ""

      if(i ~= "") then
	 indent = i .. "."
      end
      indent = indent .. tostring(k)

      l = tprint(v, l, indent);
      if (l < 0) then break end
   end

   return l
end

-- ###############################################

local function getstring(finfo)
   local ok, val = pcall(tostring, finfo)
   if not ok then val = "(unknown)" end
   return val
end

local function getval(finfo)
   local ok, val = pcall(tostring, finfo)
   if not ok then val = nil end
   return val
end

function dump_pinfo(pinfo)
   local fields = { all_field_infos() }
   for ix, finfo in ipairs(fields) do
      --  output = output .. "\t[" .. ix .. "] " .. finfo.name .. " = " .. getstring(finfo) .. "\n"
      --print(finfo.name .. "\n")
      print("\t[" .. ix .. "] " .. finfo.name .. " = " .. getstring(finfo) .. "\n")
   end
end

-- ###############################################


function initARPEntry(mac)
   if(arp_stats[mac] == nil) then
      arp_stats[mac] = { request_sent=0, request_rcvd=0, response_sent=0, response_rcvd=0 }
   end
end

function dissectARP(isRequest, src_mac, dst_mac)
   if(isRequest == 1) then
      -- ARP Request
      initARPEntry(src_mac)
      arp_stats[src_mac].request_sent = arp_stats[src_mac].request_sent + 1

      initARPEntry(dst_mac)
      arp_stats[dst_mac].request_rcvd = arp_stats[dst_mac].request_rcvd + 1
   else
      -- ARP Response
      initARPEntry(src_mac)
      arp_stats[src_mac].response_sent = arp_stats[src_mac].response_sent + 1

      initARPEntry(dst_mac)
      arp_stats[dst_mac].response_rcvd = arp_stats[dst_mac].response_rcvd + 1
   end
end

-- ###############################################

function abstime_diff(a, b)
   return(tonumber(a)-tonumber(b))
end

-- ###############################################

function arp_dissector(tvb, pinfo, tree)
   local arp_opcode = f_arp_opcode()

   if(arp_opcode ~= nil) then
      -- ARP
      local isRequest = getval(arp_opcode)
      local src_mac = getval(f_arp_sender_mac())
      local dst_mac = getval(f_arp_target_mac())
      dissectARP(isRequest, src_mac, dst_mac)
   end
end

-- ###############################################

function vlan_dissector(tvb, pinfo, tree)
   local vlan_id = f_vlan_id()
   if(vlan_id ~= nil) then
      vlan_id = tonumber(getval(vlan_id))

      if(vlan_stats[vlan_id] == nil) then vlan_stats[vlan_id] = 0 end
      vlan_stats[vlan_id] = vlan_stats[vlan_id] + 1
      vlan_found = true
   end
end

-- ###############################################

function mac_dissector(tvb, pinfo, tree)
   local src_mac = tostring(pinfo.dl_src)
   local src_ip  = tostring(pinfo.src)
   if(mac_stats[src_mac] == nil) then mac_stats[src_mac] = {} end
   mac_stats[src_mac][src_ip] = 1
end

-- ###############################################

function ssl_dissector(tvb, pinfo, tree)
   local ssl_server_name = f_ssl_server_name()
   if(ssl_server_name ~= nil) then
      ssl_server_name = getval(ssl_server_name)

      if(ssl_server_names[ssl_server_name] == nil) then
	 ssl_server_names[ssl_server_name] = 0
      end

      ssl_server_names[ssl_server_name] = ssl_server_names[ssl_server_name] + 1
      tot_ssl_flows = tot_ssl_flows + 1
   end
end

-- ###############################################

function dns_dissector(tvb, pinfo, tree)
   local dns_response = f_dns_response()
   if(dns_response ~= nil) then
      local dns_ret_code = f_dns_ret_code()
      local dns_response = tonumber(getval(dns_response))
      local srckey = tostring(pinfo.src)
      local dstkey = tostring(pinfo.dst)
      local dns_query_name = f_dns_query_name()
      dns_query_name = getval(dns_query_name)

      if(dns_response == 0) then
	 -- DNS Query
	 if(dns_client_queries[srckey] == nil) then dns_client_queries[srckey] = 0 end
	 dns_client_queries[srckey] = dns_client_queries[srckey] + 1

	 if(dns_query_name ~= nil) then
	    if(top_dns_queries[dns_query_name] == nil) then
	       top_dns_queries[dns_query_name] = 0
	       num_top_dns_queries = num_top_dns_queries + 1

	       if(num_top_dns_queries > max_num_dns_queries) then
		  -- We need to harvest the flow with least packets beside this new one
		  for k,v in pairsByValues(dns_client_queries, asc) do
		     if(k ~= dns_query_name) then
			table.remove(ndpi_flows, k)
			num_top_dns_queries = num_top_dns_queries - 1

			if(num_top_dns_queries == (2*max_num_entries)) then
			   break
			end
		     end
		  end
	       end
	    end

	    top_dns_queries[dns_query_name] = top_dns_queries[dns_query_name] + 1
	 end
      else
	 -- DNS Response
	 if(dns_server_responses[srckey] == nil) then dns_server_responses[srckey] = 0 end
	 dns_server_responses[srckey] = dns_server_responses[srckey] + 1

	 if(dns_ret_code ~= nil) then
	    dns_ret_code = getval(dns_ret_code)

	    if((dns_query_name ~= nil) and (dns_ret_code ~= nil)) then
	       dns_ret_code = tonumber(dns_ret_code)

	       if(debug) then print("[".. srckey .." -> ".. dstkey .."] "..dns_query_name.."\t"..dns_ret_code) end

	       if(dns_ret_code == 0) then
		  if(dns_responses_ok[srckey] == nil) then dns_responses_ok[srckey] = 0 end
		  dns_responses_ok[srckey] = dns_responses_ok[srckey] + 1
	       else
		  if(dns_responses_error[srckey] == nil) then dns_responses_error[srckey] = 0 end
		  dns_responses_error[srckey] = dns_responses_error[srckey] + 1
	       end
	    end
	 end
      end
   end
end

-- ###############################################

function latency_dissector(tvb, pinfo, tree)
   local _tcp_flags = f_tcp_flags()
   local udp_len    = f_udp_len()

   if((_tcp_flags ~= nil) or (udp_len ~= nil)) then
      local key
      local rtt_debug = false
      local tcp_flags
      local tcp_header_len
      local ip_len
      local ip_hdr_len

      if(udp_len == nil) then
	 tcp_flags      = f_tcp_flags().value
	 tcp_header_len = f_tcp_header_len()
	 ip_len         = f_ip_len()
	 ip_hdr_len     = f_ip_hdr_len()
      end

      if(((ip_len ~= nil) and (tcp_header_len ~= nil) and (ip_hdr_len ~= nil))
	    or (udp_len ~= nil)
      ) then
	 local payloadLen

	 if(udp_len == nil) then
	    ip_len         = tonumber(getval(ip_len))
	    tcp_header_len = tonumber(getval(tcp_header_len))
	    ip_hdr_len     = tonumber(getval(ip_hdr_len))

	    payloadLen = ip_len - tcp_header_len - ip_hdr_len
	 else
	    payloadLen = tonumber(getval(udp_len))
	 end

	 if(payloadLen > 0) then
	    local key = getstring(pinfo.src).."_"..getstring(pinfo.src_port).."_"..getstring(pinfo.dst).."_"..getstring(pinfo.dst_port)
	    local revkey = getstring(pinfo.dst).."_"..getstring(pinfo.dst_port).."_"..getstring(pinfo.src).."_"..getstring(pinfo.src_port)

	    if(first_payload_ts[revkey] ~= nil) then
	       local appl_latency = abstime_diff(pinfo.abs_ts, first_payload_ts[revkey]) * 1000

	       if((appl_latency > 0) and (appl_latency < max_appl_lat_discard)
		  -- The trick below is used to set only the first latency packet
		     and ((first_payload_id[revkey] == nil) or (first_payload_id[revkey] == pinfo.number))
	       ) then
		  local ntop_subtree = tree:add(ntop_proto, tvb(), "ntop")
		  local server = getstring(pinfo.src)
		  if(rtt_debug) then print("==> Appl Latency @ "..pinfo.number..": "..appl_latency) end

		  ntop_subtree:add(ntop_fds.appl_latency_rtt, appl_latency)
		  first_payload_id[revkey] = pinfo.number

		  if(min_appl_RRT[server] == nil) then
		     min_appl_RRT[server] = appl_latency
		  else
		     min_appl_RRT[server] = math.min(min_appl_RRT[server], appl_latency)
		  end

		  if(max_appl_RRT[server] == nil) then
		     max_appl_RRT[server] = appl_latency
		  else
		     max_appl_RRT[server] = math.max(max_appl_RRT[server], appl_latency)
		  end

		  -- first_payload_ts[revkey] = nil
	       end
	    else
	       if(first_payload_ts[key] == nil) then first_payload_ts[key] = pinfo.abs_ts end
	    end
	 end
      end

      tcp_flags = tonumber(tcp_flags)

      if(tcp_flags == 2) then
	 -- SYN
	 key = getstring(pinfo.src).."_"..getstring(pinfo.src_port).."_"..getstring(pinfo.dst).."_"..getstring(pinfo.dst_port)
	 if(rtt_debug) then print("SYN @ ".. pinfo.abs_ts.." "..key) end
	 syn[key] = pinfo.abs_ts
      elseif(tcp_flags == 18) then
	 -- SYN|ACK
	 key = getstring(pinfo.dst).."_"..getstring(pinfo.dst_port).."_"..getstring(pinfo.src).."_"..getstring(pinfo.src_port)
	 if(rtt_debug) then print("SYN|ACK @ ".. pinfo.abs_ts.." "..key) end
	 synack[key] = pinfo.abs_ts
	 if(syn[key] ~= nil) then
	    local diff = abstime_diff(synack[key], syn[key]) * 1000 -- msec

	    if(rtt_debug) then print("Server RTT --> ".. diff .. " msec") end

	    if(diff <= max_latency_discard) then
	       local ntop_subtree = tree:add(ntop_proto, tvb(), "ntop")
	       ntop_subtree:add(ntop_fds.server_nw_rtt, diff)
	       -- Do not delete the key below as it's used when a user clicks on a packet
	       -- syn[key] = nil

	       local server = getstring(pinfo.src)
	       if(min_nw_server_RRT[server] == nil) then
		  min_nw_server_RRT[server] = diff
	       else
		  min_nw_server_RRT[server] = math.min(min_nw_server_RRT[server], diff)
	       end

	       if(max_nw_server_RRT[server] == nil) then
		  max_nw_server_RRT[server] = diff
	       else
		  max_nw_server_RRT[server] = math.max(max_nw_server_RRT[server], diff)
	       end
	    end
	 end
      elseif(tcp_flags == 16) then
	 -- ACK
	 key = getstring(pinfo.src).."_"..getstring(pinfo.src_port).."_"..getstring(pinfo.dst).."_"..getstring(pinfo.dst_port)
	 if(rtt_debug) then print("ACK @ ".. pinfo.abs_ts.." "..key) end

	 if(synack[key] ~= nil) then
	    local diff = abstime_diff(pinfo.abs_ts, synack[key]) * 1000 -- msec
	    if(rtt_debug) then print("Client RTT --> ".. diff .. " msec") end

	    if(diff <= max_latency_discard) then
	       local ntop_subtree = tree:add(ntop_proto, tvb(), "ntop")
	       ntop_subtree:add(ntop_fds.client_nw_rtt, diff)

	       -- Do not delete the key below as it's used when a user clicks on a packet
	       synack[key] = nil

	       local client = getstring(pinfo.src)
	       if(min_nw_client_RRT[client] == nil) then
		  min_nw_client_RRT[client] = diff
	       else
		  min_nw_client_RRT[client] = math.min(min_nw_client_RRT[client], diff)
	       end

	       if(max_nw_client_RRT[client] == nil) then
		  max_nw_client_RRT[client] = diff
	       else
		  max_nw_client_RRT[client] = math.max(max_nw_client_RRT[client], diff)
	       end
	    end
	 end
      end
   end
end

-- the dissector function callback
function ndpi_proto.dissector(tvb, pinfo, tree)
   -- Wireshark dissects the packet twice. We ignore the first
   -- run as on that step the packet is still undecoded
   -- The trick below avoids to process the packet twice

   if(pinfo.visited == true) then
      local eth_trailer = f_eth_trailer()

      if(eth_trailer ~= nil) then
	 local eth_trailer = getval(eth_trailer)
	 local magic = string.sub(eth_trailer, 1, 11)

	 if(magic == "19:68:09:24") then
	    local ndpikey, srckey, dstkey, flowkey
	    local elems                = string.split(string.sub(eth_trailer, 12), ":")
	    local ndpi_subtree         = tree:add(ndpi_proto, tvb(), "nDPI Protocol")
	    local network_protocol     = tonumber(elems[2]..elems[3], 16) -- 16 = HEX
	    local application_protocol = tonumber(elems[4]..elems[5], 16) -- 16 = HEX
	    local name                 = ""

	    for i=6,21 do
	       name = name .. string.char(tonumber(elems[i], 16))
	    end

	    ndpi_subtree:add(ndpi_fds.network_protocol, network_protocol)
	    ndpi_subtree:add(ndpi_fds.application_protocol, application_protocol)
	    ndpi_subtree:add(ndpi_fds.name, name)

	    if(application_protocol ~= 0) then
	       -- Set protocol name in the wireshark protocol column (if not Unknown)
	       --pinfo.cols.protocol = name
	       print(network_protocol .. "/" .. application_protocol .. "/".. name)
	    end

	    if(compute_flows_stats) then
	       ndpikey = tostring(slen(name))

	       if(ndpi_protos[ndpikey] == nil) then ndpi_protos[ndpikey] = 0 end
	       ndpi_protos[ndpikey] = ndpi_protos[ndpikey] + pinfo.len

	       srckey = tostring(pinfo.src)
	       dstkey = tostring(pinfo.dst)

	       flowkey = srckey.." / "..dstkey.."\t["..ndpikey.."]"
	       if(ndpi_flows[flowkey] == nil) then
		  ndpi_flows[flowkey] = 0
		  num_ndpi_flows = num_ndpi_flows + 1

		  if(num_ndpi_flows > max_num_flows) then
		     -- We need to harvest the flow with least packets beside this new one
		     local tot_removed = 0

		     for k,v in pairsByValues(ndpi_flows, asc) do
			if(k ~= flowkey) then
			   table.remove(ndpi_flows, k)
			   num_ndpi_flows = num_ndpi_flows + 1
			   if(num_ndpi_flows == (2*max_num_entries)) then
			      break
			   end
			end
		     end
		  end
	       end

	       ndpi_flows[flowkey] = ndpi_flows[flowkey] + pinfo.len
	    end
	 end
      end -- nDPI

      latency_dissector(tvb, pinfo, tree)
   end
   
   -- ###########################################

   -- As we do not need to add fields to the dissection
   -- there is no need to process the packet multiple times
   if(pinfo.visited == true) then return end

   num_pkts = num_pkts + 1
   if((num_pkts > 1) and (pinfo.number == 1)) then return end

   if(last_processed_packet_number < pinfo.number) then
      last_processed_packet_number = pinfo.number
   end

   -- print(num_pkts .. " / " .. pinfo.number .. " / " .. last_processed_packet_number)

   if(false) then
      local srckey = tostring(pinfo.src)
      local dstkey = tostring(pinfo.dst)
      print("Processing packet "..pinfo.number .. "["..srckey.." / "..dstkey.."]")
   end

   mac_dissector(tvb, pinfo, tree)
   arp_dissector(tvb, pinfo, tree)
   vlan_dissector(tvb, pinfo, tree)
   ssl_dissector(tvb, pinfo, tree)
   dns_dissector(tvb, pinfo, tree)
end

register_postdissector(ndpi_proto)

-- ###############################################

local function ndpi_dialog_menu()
   local win = TextWindow.new("nDPI Protocol Statistics");
   local label = ""
   local i

   if(ndpi_protos ~= {}) then
      local tot = 0
      label =          "nDPI Protocol Breakdown\n"
      label = label .. "-----------------------\n"

      for _,v in pairs(ndpi_protos) do
	 tot = tot + v
      end

      i = 0
      for k,v in pairsByValues(ndpi_protos, rev) do
	 local pctg = formatPctg((v * 100) / tot)
	 label = label .. string.format("%-32s\t\t%s\t", k, bytesToSize(v)).. "\t["..pctg.."]\n"
	 if(i == max_num_entries) then break else i = i + 1 end
      end

      -- #######

      label = label .. "\nTop nDPI Flows\n"
      label = label .. "-----------\n"
      i = 0
      for k,v in pairsByValues(ndpi_flows, rev) do
	 local pctg = formatPctg((v * 100) / tot)
	 label = label .. string.format("%-48s\t%s", k, bytesToSize(v)).. "\t["..pctg.."]\n"
	 if(i == max_num_entries) then break else i = i + 1 end
      end

      win:set(label)
      win:add_button("Clear", function() win:clear() end)
   end
end

-- ###############################################

local function arp_dialog_menu()
   local win = TextWindow.new("ARP Statistics");
   local label = ""
   local _stats
   local found = false
   local tot_arp_pkts = 0

   _stats = {}
   for k,v in pairs(arp_stats) do
      if(k ~= "Broadcast") then
	 _stats[k] = v.request_sent + v.request_rcvd + v.response_sent + v.response_rcvd
	 tot_arp_pkts = tot_arp_pkts + _stats[k]
	 found = true
      end
   end

   if(not found) then
      label = "No ARP Traffic detected"
   else
      label = "Top ARP Senders/Receivers\n\nMAC Address\tTot Pkts\tPctg\tARP Breakdown\n"
      i = 0
      for k,v in pairsByValues(_stats, rev) do
	 local s = arp_stats[k]
	 local pctg = formatPctg((v * 100) / tot_arp_pkts)
	 local str = k .. "\t" .. v .. "\t" .. pctg .. "\t" .. "[sent: ".. (s.request_sent + s.response_sent) .. "][rcvd: ".. (s.request_rcvd + s.response_rcvd) .. "]\n"
	 label = label .. str
	 if(i == max_num_entries) then break else i = i + 1 end
      end
   end

   win:set(label)
   win:add_button("Clear", function() win:clear() end)
end

-- ###############################################

local function vlan_dialog_menu()
   local win = TextWindow.new("VLAN Statistics");
   local label = ""
   local _macs
   local num_hosts = 0

   if(vlan_found) then
      i = 0
      label = "VLAN\tPackets\n"
      for k,v in pairsByValues(vlan_stats, rev) do
	 local pctg = formatPctg((v * 100) / last_processed_packet_number)
	 label = label .. k .. "\t" .. v .. " pkts [".. pctg .."]\n"
	 if(i == max_num_entries) then break else i = i + 1 end
      end
   else
      label = "No VLAN traffic found"
   end

   win:set(label)
   win:add_button("Clear", function() win:clear() end)
end

-- ###############################################

local function ip_mac_dialog_menu()
   local win = TextWindow.new("IP-MAC Statistics");
   local label = ""
   local _macs, _manufacturers
   local num_hosts = 0

   _macs = {}
   _manufacturers = {}
   for mac,v in pairs(mac_stats) do
      local num = 0
      local m =  string.split(mac, "_")
      local manuf

      if(m == nil) then
	 m =  string.split(mac, ":")

	 manuf = m[1]..":"..m[2]..":"..m[3]
      else
	 manuf = m[1]
      end

      for a,b in pairs(v) do
	 num = num +1
      end

      _macs[mac] = num
      if(_manufacturers[manuf] == nil) then _manufacturers[manuf] = 0 end
      _manufacturers[manuf] = _manufacturers[manuf] + 1
      num_hosts = num_hosts + num
   end

   if(num_hosts > 0) then
      i = 0
      label = label .. "MAC\t\t# Hosts\tPercentage\n"
      for k,v in pairsByValues(_macs, rev) do
	 local pctg = formatPctg((v * 100) / num_hosts)
	 label = label .. k .. "\t" .. v .. "\t".. pctg .."\n"
	 if(i == max_num_entries) then break else i = i + 1 end
      end

      i = 0
      label = label .. "\n\nManufacturer\t# Hosts\tPercentage\n"
      for k,v in pairsByValues(_manufacturers, rev) do
	 local pctg = formatPctg((v * 100) / num_hosts)
	 label = label .. k .. "\t\t" .. v .. "\t".. pctg .."\n"
	 if(i == max_num_entries) then break else i = i + 1 end
      end
   else
      label = label .. "\nIP-MAC traffic found"
   end

   win:set(label)
   win:add_button("Clear", function() win:clear() end)
end

-- ###############################################

local function dns_dialog_menu()
   local win = TextWindow.new("DNS Statistics");
   local label = ""
   local tot = 0
   local _dns = {}

   for k,v in pairs(dns_responses_ok) do
      _dns[k] = v
      tot = tot + v
   end

   for k,v in pairs(dns_responses_error) do
      if(_dns[k] == nil) then _dns[k] = 0 end
      _dns[k] = _dns[k] + v
      tot = tot + v
   end

   if(tot > 0) then
      i = 0
      label = label .. "DNS Server\t\t# Responses\n"
      for k,v in pairsByValues(_dns, rev) do
	 local pctg = formatPctg((v * 100) / tot)
	 local ok   = dns_responses_ok[k]
	 local err  = dns_responses_error[k]

	 if(ok == nil)  then ok = 0 end
	 if(err == nil) then err = 0 end
	 label = label .. string.format("%-20s\t%s\n", shortenString(k), v .. "\t[ok: "..ok.."][error: "..err.."][".. pctg .."]")

	 if(i == max_num_entries) then break else i = i + 1 end
      end

      i = 0
      label = label .. "\n\nTop DNS Clients\t# Queries\n"
      for k,v in pairsByValues(dns_client_queries, rev) do
	 local pctg = formatPctg((v * 100) / tot)
	 label = label .. string.format("%-20s\t%s\n", shortenString(k), v .. "\t["..pctg.."]")
	 if(i == max_num_entries) then break else i = i + 1 end
      end

      i = 0
      label = label .. "\n\nTop DNS Resolvers\t# Responses\n"
      for k,v in pairsByValues(dns_server_responses, rev) do
	 local pctg = formatPctg((v * 100) / tot)
	 label = label .. string.format("%-20s\t%s\n", shortenString(k), v .. "\t["..pctg.."]")
	 if(i == max_num_entries) then break else i = i + 1 end
      end

      i = 0
      label = label .. "\n\nTop DNS Queries\t\t\t# Queries\n"
      for k,v in pairsByValues(top_dns_queries, rev) do
	 local pctg = formatPctg((v * 100) / tot)
	 label = label .. string.format("%-32s\t%s\n", shortenString(k,32), v .. "\t["..pctg.."]")
	 if(i == max_num_entries) then break else i = i + 1 end
      end
   else
      label = label .. "\nNo DNS traffic found"
   end

   win:set(label)


   -- add buttons to clear text window and to enable editing
   win:add_button("Clear", function() win:clear() end)
   --win:add_button("Enable edit", function() win:set_editable(true) end)

   -- print "closing" to stdout when the user closes the text windw
   --win:set_atclose(function() print("closing") end)
end

-- ###############################################

local function rtt_dialog_menu()
   local win = TextWindow.new("Network Latency");
   local label = ""
   local tot = 0
   local i

   i = 0
   label = label .. "Client\t\tMin/Max RTT\n"
   for k,v in pairsByValues(min_nw_client_RRT, rev) do
      label = label .. string.format("%-20s\t%.3f / %.3f msec\n", shortenString(k), v, max_nw_client_RRT[k])
      if(i == max_num_entries) then break else i = i + 1 end
   end

   i = 0
   label = label .. "\nServer\t\tMin RTT\n"
   for k,v in pairsByValues(min_nw_server_RRT, rev) do
      label = label .. string.format("%-20s\t%.3f / %.3f msec\n", shortenString(k), v, max_nw_server_RRT[k])
      if(i == max_num_entries) then break else i = i + 1 end
   end

   win:set(label)
   win:add_button("Clear", function() win:clear() end)
end

-- ###############################################

local function appl_rtt_dialog_menu()
   local win = TextWindow.new("Application Latency");
   local label = ""
   local tot = 0
   local i

   i = 0
   label = label .. "Server\t\tMin Application RTT\n"
   for k,v in pairsByValues(min_appl_RRT, rev) do
      label = label .. string.format("%-20s\t%.3f / %.3f msec\n", shortenString(k), v, max_appl_RRT[k])
      if(i == max_num_entries) then break else i = i + 1 end
   end

   win:set(label)
   win:add_button("Clear", function() win:clear() end)
end

-- ###############################################

local function ssl_dialog_menu()
   local win = TextWindow.new("SSL Server Contacts");
   local label = ""
   local tot = 0
   local i

   if(tot_ssl_flows > 0) then
      i = 0
      label = label .. "SSL Server\t\t\t\t# Flows\n"
      for k,v in pairsByValues(ssl_server_names, rev) do
	 local pctg

	 v = tonumber(v)
	 pctg = formatPctg((v * 100) / tot_ssl_flows)
	 label = label .. string.format("%-32s", shortenString(k,32)).."\t"..v.." [".. pctg.." %]\n"
	 if(i == 50) then break else i = i + 1 end
      end
   else
      label = "No SSL server certificates detected"
   end

   win:set(label)
   win:add_button("Clear", function() win:clear() end)
end

-- ###############################################

register_menu("ntop/ARP",          arp_dialog_menu, MENU_TOOLS_UNSORTED)
register_menu("ntop/VLAN",         vlan_dialog_menu, MENU_TOOLS_UNSORTED)
register_menu("ntop/IP-MAC",       ip_mac_dialog_menu, MENU_TOOLS_UNSORTED)
register_menu("ntop/DNS",          dns_dialog_menu, MENU_TOOLS_UNSORTED)
register_menu("ntop/SSL",          ssl_dialog_menu, MENU_TOOLS_UNSORTED)
register_menu("ntop/Latency/Network",      rtt_dialog_menu, MENU_TOOLS_UNSORTED)
register_menu("ntop/Latency/Application",  appl_rtt_dialog_menu, MENU_TOOLS_UNSORTED)

-- ###############################################

if(compute_flows_stats) then
   register_menu("ntop/nDPI", ndpi_dialog_menu, MENU_TOOLS_UNSORTED)
end