forked from thinhhoangpham/tcp_timearcs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathip_bar_diagram.js.backup
More file actions
3908 lines (3465 loc) · 164 KB
/
ip_bar_diagram.js.backup
File metadata and controls
3908 lines (3465 loc) · 164 KB
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
// Extracted from ip_arc_diagram_3.html inline script
// This file contains all logic for the IP Connection Analysis visualization
import { initSidebar, createIPCheckboxes as sbCreateIPCheckboxes, filterIPList as sbFilterIPList, filterFlowList as sbFilterFlowList, updateFlagStats as sbUpdateFlagStats, updateIPStats as sbUpdateIPStats, createFlowListCapped as sbCreateFlowListCapped, updateTcpFlowStats as sbUpdateTcpFlowStats, updateGroundTruthStatsUI as sbUpdateGroundTruthStatsUI, wireSidebarControls as sbWireSidebarControls, showFlowProgress as sbShowFlowProgress, updateFlowProgress as sbUpdateFlowProgress, hideFlowProgress as sbHideFlowProgress, wireFlowListModalControls as sbWireFlowListModalControls, showCsvProgress as sbShowCsvProgress, updateCsvProgress as sbUpdateCsvProgress, hideCsvProgress as sbHideCsvProgress } from './sidebar.js';
import { renderInvalidLegend as sbRenderInvalidLegend, renderClosingLegend as sbRenderClosingLegend, drawFlagLegend as drawFlagLegendFromModule } from './legends.js';
import { initOverview, createOverviewChart, updateBrushFromZoom, updateOverviewInvalidVisibility, setBrushUpdating } from './overview_chart.js';
import { GLOBAL_BIN_COUNT, FLOW_RECONSTRUCT_BATCH } from './config.js';
// Global debug flag to silence heavy logs in production
const DEBUG = false;
// Unified debug logger; usage: LOG('message', optionalData)
function LOG(...args) { if (DEBUG) console.log(...args); }
// --- Web Worker for packet filtering ---
let packetWorker = null;
let packetWorkerReady = false;
let lastWorkerVersion = 0;
let pendingFilterRequest = null;
let workerVisibilityMask = null; // Uint8Array bitmask for packet visibility
function initPacketWorker() {
if (packetWorker) return;
try {
packetWorker = new Worker('packet_worker.js');
packetWorker.onmessage = (e) => {
const msg = e.data;
switch (msg.type) {
case 'ready':
packetWorkerReady = true;
lastWorkerVersion = msg.version || 0;
if (DEBUG) console.log('[Worker] Ready. packets=', msg.packetCount);
if (pendingFilterRequest) {
packetWorker.postMessage(pendingFilterRequest);
pendingFilterRequest = null;
}
break;
case 'filtered':
if ((msg.version || 0) < lastWorkerVersion) return; // stale
lastWorkerVersion = msg.version || lastWorkerVersion;
workerVisibilityMask = msg.visible; // transferred Uint8Array
applyVisibilityToDots(workerVisibilityMask);
break;
case 'error':
console.error('[Worker] error:', msg.message);
break;
}
};
packetWorker.onerror = (err) => console.error('[Worker] onerror', err);
} catch (err) {
console.error('Failed creating worker', err);
}
}
function applyVisibilityToDots(mask) {
if (!mask || !mainGroup) return;
const dots = mainGroup.selectAll('.direction-dot');
const nodes = dots.nodes();
if (nodes.length !== mask.length) {
if (DEBUG) console.warn('Mask length mismatch; fallback', mask.length, nodes.length);
legacyFilterPacketsBySelectedFlows();
return;
}
const BATCH = 4000;
function batch(start) {
const end = Math.min(nodes.length, start + BATCH);
for (let i = start; i < end; i++) {
const n = nodes[i];
n.style.display = mask[i] === 1 ? '' : 'none';
}
if (end < nodes.length) {
requestAnimationFrame(() => batch(end));
} else {
try { applyInvalidReasonFilter(); } catch(_) {}
}
}
requestAnimationFrame(() => batch(0));
}
let fullData = [];
let filteredData = [];
let svg, mainGroup, width, height, xScale, yScale, zoom;
// Bottom overlay (fixed area above overview) for main x-axis and legends
let bottomOverlaySvg = null;
let bottomOverlayRoot = null;
let bottomOverlayAxisGroup = null;
let bottomOverlayDurationLabel = null;
let bottomOverlayWidth = 0;
let bottomOverlayHeight = 140; // generous to fit axis + legends without changing sizes
let chartMarginLeft = 150;
let chartMarginRight = 120;
// Layers for performance tuning: persistent full-domain layer and dynamic zoom layer
let fullDomainLayer = null;
let dynamicLayer = null;
// The element that has the zoom behavior attached (svg container)
let zoomTarget = null;
let dotsSelection; // Cache the dots selection for performance
// Overview timeline variables moved to overview_chart.js
let isHardResetInProgress = false; // Programmatic Reset View fast-path
let timeExtent = [0, 0]; // Global time extent for the dataset
// Global bin count is sourced from shared config.js
let pairs = new Map(); // Global pairs map for IP pairing system
let ipPositions = new Map(); // Global IP positions map
let ipOrder = []; // Current vertical order of IPs
// Row layout constants (used for positioning and drag-reorder)
const ROW_GAP = 50; // vertical gap between IP rows
const TOP_PAD = 30; // top padding before first row
// Force layout for IP positioning
let forceLayout = null;
let forceNodes = [];
let forceLinks = [];
let isForceLayoutRunning = false;
let tcpFlows = []; // Store detected TCP flows (from CSV)
let currentFlows = []; // Flows matching current IP selection (subset of tcpFlows)
let selectedFlowIds = new Set(); // Store IDs of selected flows as strings
let showTcpFlows = true; // Toggle for TCP flow visualization (default ON)
let showEstablishment = true; // Toggle for establishment phase (default ON)
let showDataTransfer = true; // Toggle for data transfer phase (default ON)
let showClosing = true; // Toggle for closing phase (default ON)
let groundTruthData = []; // Store ground truth events
let showGroundTruth = false; // Toggle for ground truth visualization
// Global toggle state for invalid flow categories in legend
const hiddenInvalidReasons = new Set();
// Cache for IP filtered packet subsets (key: sorted IP list)
const filterCache = new Map();
// Cache for full-domain binned result to make Reset View fast
let dataVersion = 0; // increment when filteredData changes
let fullDomainBinsCache = { version: -1, data: [], binSize: null, sorted: false };
// Global radius scaling: anchor sizes across zooms
// - RADIUS_MIN: circle size for an individual packet (count = 1)
// - RADIUS_MAX: circle size for the largest bin observed at full zoom-out
// - globalMaxBinCount: computed from the initial full-domain binning; reused at all zoom levels
const RADIUS_MIN = 3;
const RADIUS_MAX = 30;
let globalMaxBinCount = 1;
// User toggle: binning on/off
let useBinning = true;
// Render mode: 'circles' (default) or 'bars'
let renderMode = 'circles';
// Choose the effective bin count based on render mode and config
function getEffectiveBinCount() {
const cfg = GLOBAL_BIN_COUNT;
if (typeof cfg === 'object' && cfg) {
// ip_bar_diagram uses BAR bin count by design
return cfg.BAR || cfg.BARS || 300;
}
return (typeof cfg === 'number' ? cfg : 300);
}
// Helper to compute bar width in pixels from binned data and current xScale
function computeBarWidthPx(binned) {
try {
if (!Array.isArray(binned) || binned.length === 0 || !xScale) return 4;
const centers = Array.from(new Set(binned.filter(d => d.binned && Number.isFinite(d.binCenter)).map(d => Math.floor(d.binCenter)))).sort((a,b)=>a-b);
let gap = 0;
for (let i = 1; i < centers.length; i++) {
const d = centers[i] - centers[i-1];
if (d > 0) { gap = (gap === 0) ? d : Math.min(gap, d); }
}
if (gap <= 0) {
const domain = xScale.domain();
const microRange = Math.max(1, domain[1] - domain[0]);
gap = Math.floor(microRange / Math.max(1, getEffectiveBinCount()));
}
const half = Math.max(1, Math.floor(gap / 2));
const px = Math.max(2, xScale(centers[0] + half) - xScale(centers[0] - half));
return Math.max(2, Math.min(24, px));
} catch (_) { return 4; }
}
// Render stacked bars for binned items into given layer
function renderBars(layer, binned) {
if (!layer) return;
try { layer.selectAll('.direction-dot').remove(); } catch {}
// Build stacks per (timeBin, yPos)
const stacks = new Map();
const items = (binned || []).filter(d => d && d.binned);
const globalFlagTotals = new Map();
for (const d of items) {
const ft = d.flagType || classifyFlags(d.flags);
const c = Math.max(1, d.count || 1);
globalFlagTotals.set(ft, (globalFlagTotals.get(ft) || 0) + c);
}
for (const d of items) {
const t = Number.isFinite(d.binCenter) ? Math.floor(d.binCenter) : (Number.isFinite(d.binTimestamp) ? Math.floor(d.binTimestamp) : Math.floor(d.timestamp));
const key = `${t}|${d.yPos}`;
let s = stacks.get(key);
if (!s) { s = { center: t, yPos: d.yPos, byFlag: new Map(), total: 0 }; stacks.set(key, s); }
const ft = d.flagType || classifyFlags(d.flags);
const prev = s.byFlag.get(ft) || { count: 0, packets: [] };
prev.count += Math.max(1, d.count || 1);
if (Array.isArray(d.originalPackets)) prev.packets = prev.packets.concat(d.originalPackets);
s.byFlag.set(ft, prev);
s.total += Math.max(1, d.count || 1);
}
const data = Array.from(stacks.values());
const barWidth = computeBarWidthPx(items);
const MAX_BAR_H = Math.max(6, Math.min(ROW_GAP - 28, 16));
const hScale = d3.scaleLinear().domain([0, Math.max(1, globalMaxBinCount)]).range([1, MAX_BAR_H]);
const toSegments = (s) => {
const parts = Array.from(s.byFlag.entries()).map(([flag, info]) => ({ flagType: flag, count: info.count, packets: info.packets }));
parts.sort((a, b) => {
const ga = globalFlagTotals.get(a.flagType) || 0;
const gb = globalFlagTotals.get(b.flagType) || 0;
if (gb !== ga) return gb - ga;
return b.count - a.count;
});
let acc = 0;
return parts.map(p => {
const h = hScale(Math.max(1, p.count));
const yTop = s.yPos - acc - h;
acc += h;
return {
x: xScale(Math.floor(s.center)) - barWidth / 2,
y: yTop,
w: barWidth,
h,
datum: {
binned: true,
count: p.count,
flagType: p.flagType,
yPos: s.yPos,
binCenter: s.center,
originalPackets: p.packets || []
}
};
});
};
// Stack groups
const stackJoin = layer.selectAll('.bin-stack').data(data, d => `${Math.floor(d.center)}_${d.yPos}`);
const stackEnter = stackJoin.enter().append('g').attr('class', 'bin-stack');
const stackMerge = stackEnter.merge(stackJoin)
.attr('data-anchor-x', d => xScale(Math.floor(d.center)))
.attr('data-anchor-y', d => d.yPos)
.attr('transform', null)
.on('mouseenter', function (event, d) {
const g = d3.select(this);
const ax = +g.attr('data-anchor-x') || xScale(Math.floor(d.center));
const ay = +g.attr('data-anchor-y') || d.yPos;
const sx = 1.4, sy = 1.8;
g.raise().attr('transform', `translate(${ax},${ay}) scale(${sx},${sy}) translate(${-ax},${-ay})`);
})
.on('mouseleave', function () {
d3.select(this).attr('transform', null);
d3.select('#tooltip').style('display', 'none');
});
// Segments within each stack
stackMerge.each(function (s) {
const segs = toSegments(s);
const segJoin = d3.select(this).selectAll('.bin-bar-segment')
.data(segs, d => `${Math.floor(d.datum.binCenter || d.datum.timestamp || 0)}_${d.datum.yPos}_${d.datum.flagType}`);
segJoin.enter().append('rect')
.attr('class', 'bin-bar-segment')
.attr('x', d => d.x)
.attr('y', d => d.y)
.attr('width', d => d.w)
.attr('height', d => d.h)
.style('fill', d => flagColors[d.datum.flagType] || flagColors.OTHER)
.style('opacity', 0.8)
.style('stroke', 'none')
.style('cursor', 'pointer')
.on('mousemove', (event, d) => {
const datum = d.datum || {};
const center = Math.floor(datum.binCenter || datum.timestamp || 0);
const start = Math.floor(datum.binTimestamp || (center - Math.abs(center - (datum.binTimestamp || center))));
const end = Math.floor(start + (center - start) * 2);
const { utcTime: cUTC } = formatTimestamp(center);
const { utcTime: sUTC } = formatTimestamp(start);
const { utcTime: eUTC } = formatTimestamp(end);
const count = datum.count || 0;
const ft = datum.flagType || 'OTHER';
const bytes = formatBytes((datum.totalBytes || 0));
let tooltipHTML = `<b>${ft}</b><br>Count: ${count}<br>Center: ${cUTC}`;
if (start && end) tooltipHTML += `<br>Window: ${sUTC} → ${eUTC}`;
tooltipHTML += `<br>Bytes: ${bytes}`;
d3.select('#tooltip').style('display', 'block').html(tooltipHTML)
.style('left', `${event.pageX + 40}px`).style('top', `${event.pageY - 40}px`);
})
.on('mouseleave', () => { d3.select('#tooltip').style('display', 'none'); })
.merge(segJoin)
.attr('x', d => d.x)
.attr('y', d => d.y)
.attr('width', d => d.w)
.attr('height', d => d.h)
.style('fill', d => flagColors[d.datum.flagType] || flagColors.OTHER);
segJoin.exit().remove();
});
stackJoin.exit().remove();
}
// Render circles (existing) for binned items into given layer
function renderCircles(layer, binned, rScale) {
if (!layer) return;
// Clear bar segments in this layer
try { layer.selectAll('.bin-bar-segment').remove(); } catch {}
const tooltip = d3.select('#tooltip');
layer.selectAll('.direction-dot')
.data(binned, d => d.binned ? `bin_${d.timestamp}_${d.yPos}_${d.flagType}` : `${d.src_ip}-${d.dst_ip}-${d.timestamp}`)
.join(
enter => enter.append('circle')
.attr('class', d => `direction-dot ${d.binned && d.count > 1 ? 'binned' : ''}`)
.attr('r', d => d.binned && d.count > 1 ? rScale(d.count) : RADIUS_MIN)
.attr('data-orig-r', d => d.binned && d.count > 1 ? rScale(d.count) : RADIUS_MIN)
.attr('fill', d => flagColors[d.binned ? d.flagType : classifyFlags(d.flags)] || flagColors.OTHER)
.attr('cx', d => xScale(Math.floor(d.binned && Number.isFinite(d.binCenter) ? d.binCenter : d.timestamp)))
.attr('cy', d => d.binned ? d.yPos : findIPPosition(d.src_ip, d.src_ip, d.dst_ip, pairs, ipPositions))
.style('cursor', 'pointer')
.on('mouseover', (event, d) => {
const dot = d3.select(event.currentTarget);
dot.classed('highlighted', true).style('stroke', '#000').style('stroke-width', '2px');
const baseR = +dot.attr('data-orig-r') || +dot.attr('r') || RADIUS_MIN;
dot.attr('r', baseR);
const packet = d.originalPackets ? d.originalPackets[0] : d;
const arcPath = arcPathGenerator(packet);
if (arcPath) {
mainGroup.append('path').attr('class', 'hover-arc').attr('d', arcPath)
.style('stroke', flagColors[d.binned ? d.flagType : classifyFlags(d.flags)] || flagColors.OTHER)
.style('stroke-width', '2px')
.style('stroke-opacity', 0.8).style('fill', 'none').style('pointer-events', 'none');
}
tooltip.style('display', 'block').html(createTooltipHTML(d));
})
.on('mousemove', e => { tooltip.style('left', `${e.pageX + 40}px`).style('top', `${e.pageY - 40}px`); })
.on('mouseout', e => {
const dot = d3.select(e.currentTarget);
dot.classed('highlighted', false).style('stroke', null).style('stroke-width', null);
const baseR = +dot.attr('data-orig-r') || RADIUS_MIN; dot.attr('r', baseR);
mainGroup.selectAll('.hover-arc').remove(); tooltip.style('display', 'none');
}),
update => update
.attr('class', d => `direction-dot ${d.binned && d.count > 1 ? 'binned' : ''}`)
.attr('r', d => d.binned && d.count > 1 ? rScale(d.count) : RADIUS_MIN)
.attr('data-orig-r', d => d.binned && d.count > 1 ? rScale(d.count) : RADIUS_MIN)
.attr('fill', d => flagColors[d.binned ? d.flagType : classifyFlags(d.flags)] || flagColors.OTHER)
.attr('cx', d => xScale(Math.floor(d.binned && Number.isFinite(d.binCenter) ? d.binCenter : d.timestamp)))
.attr('cy', d => d.binned ? d.yPos : findIPPosition(d.src_ip, d.src_ip, d.dst_ip, pairs, ipPositions))
.style('cursor', 'pointer')
);
}
function renderMarksForLayer(layer, data, rScale) {
if (renderMode === 'bars') return renderBars(layer, data);
return renderCircles(layer, data, rScale);
}
// Draw a circle-size legend (bottom-right) for smallest/middle/largest counts
function drawSizeLegend(targetSvgOverride = null, targetWidth = null, targetHeight = null, axisY = null) {
try {
const targetSvg = targetSvgOverride || svg;
const w = (typeof targetWidth === 'number') ? targetWidth : width;
const h = (typeof targetHeight === 'number') ? targetHeight : height;
if (!targetSvg || !w || !h) return;
// Remove previous legend if any
targetSvg.select('.size-legend').remove();
const maxCount = Math.max(1, globalMaxBinCount);
const midCount = Math.max(1, Math.round(maxCount / 2));
const values = [1, midCount, maxCount];
const rScale = d3.scaleSqrt().domain([1, maxCount]).range([RADIUS_MIN, RADIUS_MAX]);
const radii = values.map(v => rScale(v));
const maxR = Math.max(...radii, RADIUS_MIN);
// Layout constants
const padding = 8;
const labelGap = 32; // top headroom for title + labels
const legendWidth = maxR * 2 + padding * 2; // compact width
const legendHeight = 2 * maxR + padding + (padding + labelGap); // space for title + labels
const anchorY = (typeof axisY === 'number') ? axisY : h;
const legendX = Math.max(0, w - legendWidth - 12);
const legendY = Math.max(0, (anchorY - legendHeight - 8));
const g = targetSvg.append('g')
.attr('class', 'size-legend')
.attr('transform', `translate(${legendX},${legendY})`)
.style('pointer-events', 'none');
// Background
g.append('rect')
.attr('x', 0)
.attr('y', 0)
.attr('rx', 6)
.attr('ry', 6)
.attr('width', legendWidth)
.attr('height', legendHeight)
.style('fill', '#fff')
.style('opacity', 0.85)
.style('stroke', '#ccc');
// Title
g.append('text')
.attr('x', legendWidth / 2)
.attr('y', padding + 10)
.attr('text-anchor', 'middle')
.style('font-size', '12px')
.style('font-weight', '600')
.style('fill', '#333')
.text('Circle Size');
// Baseline at the bottom inside the box
const innerTop = padding + labelGap; // extra top room for labels
const baseline = innerTop + 2 * maxR;
const cx = padding + maxR; // center x for all circles
// Draw nested circles (bottom-aligned), no fill. Draw largest first.
const order = [2, 1, 0]; // indices for [max, mid, min]
order.forEach((idx) => {
const v = values[idx];
const r = Math.max(RADIUS_MIN, radii[idx]);
const cy = baseline - r; // bottom-aligned
g.append('circle')
.attr('cx', cx)
.attr('cy', cy)
.attr('r', r)
.style('fill', 'none')
.style('stroke', '#555');
// Label centered above each circle
g.append('text')
.attr('x', cx)
.attr('y', cy - r - 4)
.attr('text-anchor', 'middle')
.style('font-size', '12px')
.style('fill', '#333')
.text(v);
});
} catch (_) { /* ignore legend draw errors */ }
}
// Wrapper function for the extracted flag legend
function drawFlagLegend() {
// Default to bottom overlay if available; fallback to main svg
const targetSvg = bottomOverlayRoot || svg;
const w = bottomOverlayRoot ? width : width;
const h = bottomOverlayRoot ? bottomOverlayHeight : height;
const axisBaseY = bottomOverlayRoot ? Math.max(20, bottomOverlayHeight - 20) : (height - 12);
drawFlagLegendFromModule({
svg: targetSvg,
width: w,
height: h,
flagColors,
globalMaxBinCount,
RADIUS_MIN,
RADIUS_MAX,
d3,
axisY: axisBaseY
});
}
// Global line path generator function updated to draw curved arcs
function arcPathGenerator(d) {
if (!xScale || !ipPositions) return "";
const timestampInt = Math.floor(d.timestamp);
const x = xScale(timestampInt);
const y1 = findIPPosition(d.src_ip, d.src_ip, d.dst_ip, pairs, ipPositions);
const y2 = findIPPosition(d.dst_ip, d.src_ip, d.dst_ip, pairs, ipPositions);
if (y1 === 0 || y2 === 0 || y1 === y2) return "";
// Curvature by TCP flag type (pixels of horizontal offset)
const flagType = classifyFlags(d.flags);
const base = (flagCurvature[flagType] !== undefined) ? flagCurvature[flagType] : flagCurvature.OTHER;
const vert = Math.abs(y2 - y1);
// Scale curvature slightly with vertical distance so long arcs remain visible
const scale = Math.min(1, vert / 200);
const dx = base * (0.5 + 0.5 * scale);
// If no curvature for this flag, draw straight line
if (dx <= 0) {
return `M${x},${y1} L${x},${y2}`;
}
// Curve everything to the right regardless of direction
const cx1 = x + dx;
const cy1 = y1;
const cx2 = x + dx;
const cy2 = y2;
return `M${x},${y1} C${cx1},${cy1} ${cx2},${cy2} ${x},${y2}`;
}
// TCP flag colors, now loaded from flag_colors.json with defaults
const defaultFlagColors = {
'SYN': '#e74c3c', 'SYN+ACK': '#f39c12', 'ACK': '#27ae60',
'FIN': '#8e44ad', 'FIN+ACK': '#9b59b6', 'RST': '#34495e',
'PSH+ACK': '#3498db', 'ACK+RST': '#c0392b', 'OTHER': '#bdc3c7'
};
let flagColors = { ...defaultFlagColors };
// Flow-related colors (closing types and invalid reasons) loaded from flow_colors.json
let flowColors = {
closing: {
graceful: '#8e44ad',
abortive: '#c0392b'
},
ongoing: {
open: '#6c757d',
incomplete: '#adb5bd'
},
invalid: {
// Optional overrides; default invalid reason colors derive from flagColors
}
};
// Horizontal curvature levels (in pixels) by TCP flag type
const flagCurvature = {
// Establishment: increasing curvature across steps
'SYN': 12,
'SYN+ACK': 18,
'ACK': 24, // treat pure ACK as final handshake step curvature
// Data transfer: moderate curvature
'PSH+ACK': 14,
// Closing: higher curvature
'FIN': 18,
'FIN+ACK': 20,
'ACK+RST': 28,
'RST': 30,
// OTHER and unknown types: straight lines
'OTHER': 0
};
// Load color mapping for ground truth events
let eventColors = {};
fetch('color_mapping.json')
.then(response => response.json())
.then(colors => {
eventColors = colors;
LOG('Loaded event colors:', eventColors);
})
.catch(error => {
console.warn('Could not load color_mapping.json:', error);
// Use default colors if file not found
eventColors = {
'normal': '#4B4B4B',
'client compromise': '#D41159',
'malware ddos': '#2A9D4F',
'scan /usr/bin/nmap': '#C9A200',
'ddos': '#264D99'
};
});
// Load colors for flags from external JSON, merging into the existing object
fetch('flag_colors.json')
.then(r => r.ok ? r.json() : Promise.reject(new Error(`HTTP ${r.status}`)))
.then(colors => {
Object.assign(flagColors, colors);
LOG('Loaded flag colors:', flagColors);
try { drawFlagLegend(); } catch (_) {}
})
.catch(err => {
console.warn('Could not load flag_colors.json:', err);
// keep defaults in flagColors
});
// Load colors for flows (closing + invalid) from external JSON, deep-merge
fetch('flow_colors.json')
.then(r => r.ok ? r.json() : Promise.reject(new Error(`HTTP ${r.status}`)))
.then(colors => {
try {
if (colors && typeof colors === 'object') {
if (colors.closing && typeof colors.closing === 'object') {
flowColors.closing = { ...flowColors.closing, ...colors.closing };
}
if (colors.invalid && typeof colors.invalid === 'object') {
flowColors.invalid = { ...flowColors.invalid, ...colors.invalid };
}
if (colors.ongoing && typeof colors.ongoing === 'object') {
flowColors.ongoing = { ...flowColors.ongoing, ...colors.ongoing };
}
}
LOG('Loaded flow colors:', flowColors);
} catch (e) { console.warn('Merging flow_colors.json failed:', e); }
})
.catch(err => {
console.warn('Could not load flow_colors.json:', err);
// keep defaults in flowColors
});
function classifyFlags(flags) {
if (flags === undefined || flags === null) return 'OTHER';
const flagMap = { 0x01: 'FIN', 0x02: 'SYN', 0x04: 'RST', 0x08: 'PSH', 0x10: 'ACK' };
const setFlags = Object.entries(flagMap)
.filter(([val, _]) => (flags & val) > 0).map(([_, name]) => name).sort();
if (setFlags.length === 0) return 'OTHER';
const flagStr = setFlags.join('+');
if (flagStr === 'ACK+SYN') return 'SYN+ACK';
if (flagStr === 'ACK+FIN') return 'FIN+ACK';
if (flagStr === 'ACK+PSH') return 'PSH+ACK';
return flagStr;
}
// Map flag type to a high-level TCP phase
function flagPhase(flagType) {
switch (flagType) {
case 'SYN':
case 'SYN+ACK':
case 'ACK':
return 'establishment';
case 'PSH+ACK':
case 'OTHER':
return 'data';
case 'FIN':
case 'FIN+ACK':
case 'RST':
case 'ACK+RST':
return 'closing';
default:
return 'data';
}
}
function isFlagVisibleByPhase(flagType) {
const phase = flagPhase(flagType);
if (phase === 'establishment') return !!showEstablishment;
if (phase === 'data') return !!showDataTransfer;
if (phase === 'closing') return !!showClosing;
return true;
}
// Initialization function for the bar diagram module
function initializeBarVisualization() {
// Initialize overview module with references
initOverview({
d3,
applyZoomDomain: (domain, source) => applyZoomDomain(domain, source),
getWidth: () => width,
getTimeExtent: () => timeExtent,
getCurrentFlows: () => currentFlows,
getSelectedFlowIds: () => selectedFlowIds,
updateTcpFlowPacketsGlobal: () => updateTcpFlowPacketsGlobal(),
createFlowList: (flows) => createFlowList(flows),
sbRenderInvalidLegend: (panel, html, title) => sbRenderInvalidLegend(panel, html, title),
sbRenderClosingLegend: (panel, html, title) => sbRenderClosingLegend(panel, html, title),
makeConnectionKey: (a,b,c,d) => makeConnectionKey(a,b,c,d),
// Allow overview legend toggles to affect the arc graph immediately
applyInvalidReasonFilter: () => applyInvalidReasonFilter(),
hiddenInvalidReasons,
hiddenCloseTypes,
GLOBAL_BIN_COUNT,
flagColors,
flowColors
});
initSidebar({
onResetView: () => {
if (fullData.length > 0 && zoomTarget && zoom && timeExtent && timeExtent[1] > timeExtent[0]) {
isHardResetInProgress = true;
applyZoomDomain([timeExtent[0], timeExtent[1]], 'reset');
if (showTcpFlows && selectedFlowIds && selectedFlowIds.size > 0) {
try { setTimeout(() => redrawSelectedFlowsView(), 0); } catch(_) {}
}
}
}
});
// Delegate sidebar event wiring
sbWireSidebarControls({
onIpSearch: (term) => sbFilterIPList(term),
onSelectAllIPs: () => { document.querySelectorAll('#ipCheckboxes input[type="checkbox"]').forEach(cb => cb.checked = true); updateIPFilter(); },
onClearAllIPs: () => { document.querySelectorAll('#ipCheckboxes input[type="checkbox"]').forEach(cb => cb.checked = false); updateIPFilter(); },
onToggleShowTcpFlows: (checked) => { showTcpFlows = checked; updateTcpFlowPacketsGlobal(); drawSelectedFlowArcs(); try { applyInvalidReasonFilter(); } catch(_) {} },
onToggleEstablishment: (checked) => { showEstablishment = checked; drawSelectedFlowArcs(); try { applyInvalidReasonFilter(); } catch(_) {} },
onToggleDataTransfer: (checked) => { showDataTransfer = checked; drawSelectedFlowArcs(); try { applyInvalidReasonFilter(); } catch(_) {} },
onToggleClosing: (checked) => { showClosing = checked; drawSelectedFlowArcs(); try { applyInvalidReasonFilter(); } catch(_) {} },
onToggleGroundTruth: (checked) => { showGroundTruth = checked; const selectedIPs = Array.from(document.querySelectorAll('#ipCheckboxes input[type="checkbox"]:checked')).map(cb => cb.value); drawGroundTruthBoxes(selectedIPs); },
onToggleBinning: (checked) => {
useBinning = checked;
isHardResetInProgress = true;
// Force immediate re-render of the visualization
try {
// Re-render the main visualization with current filtered data
visualizeTimeArcs(filteredData);
// Update TCP flow packets and arcs
updateTcpFlowPacketsGlobal();
// Redraw selected flow arcs with new binning
drawSelectedFlowArcs();
// Apply any active filters
applyInvalidReasonFilter();
// Update legends to reflect new scaling
setTimeout(() => {
try {
try {
const axisBaseY = Math.max(20, bottomOverlayHeight - 20);
drawSizeLegend(bottomOverlayRoot, width, bottomOverlayHeight, axisBaseY);
} catch {}
drawFlagLegend();
const selIPs = Array.from(document.querySelectorAll('#ipCheckboxes input[type="checkbox"]:checked')).map(cb => cb.value);
drawGroundTruthBoxes(selIPs);
} catch(_) {}
}, 50);
} catch (e) {
console.warn('Error updating visualization after binning toggle:', e);
// Fallback to original behavior
applyZoomDomain(xScale.domain(), 'program');
}
},
onToggleRenderMode: (mode) => {
try {
renderMode = (mode === 'bars') ? 'bars' : 'circles';
// Re-render marks in current domain using chosen mode
isHardResetInProgress = true;
visualizeTimeArcs(filteredData);
updateTcpFlowPacketsGlobal();
drawSelectedFlowArcs();
applyInvalidReasonFilter();
} catch (e) { console.warn('Render mode toggle failed', e); }
}
});
// Window resize handler for responsive visualization
setupWindowResizeHandler();
// Wire Flow List modal controls
try {
sbWireFlowListModalControls({
onSelectAll: () => {
document.querySelectorAll('#flowListModalList .flow-checkbox').forEach(cb => { if (!cb.checked) cb.click(); });
},
onClearAll: () => {
document.querySelectorAll('#flowListModalList .flow-checkbox').forEach(cb => { if (cb.checked) cb.click(); });
},
onSearch: (term) => {
const items = document.querySelectorAll('#flowListModalList .flow-item');
const t = (term || '').toLowerCase();
items.forEach(it => {
const text = (it.innerText || it.textContent || '').toLowerCase();
it.style.display = text.includes(t) ? '' : 'none';
});
}
});
} catch (_) {}
}
// Window resize handler for responsive visualization
function setupWindowResizeHandler() {
let resizeTimeout;
const handleResize = () => {
// Clear existing timeout to debounce rapid resize events
clearTimeout(resizeTimeout);
resizeTimeout = setTimeout(() => {
try {
// Only proceed if we have data and existing visualization
if (!fullData || fullData.length === 0 || !svg || !xScale || !yScale) {
return;
}
LOG('Handling window resize, updating visualization dimensions');
// Store old dimensions for comparison
const oldWidth = width;
const oldHeight = height;
const container = d3.select("#chart-container").node();
if (!container) return;
// Calculate new dimensions
const containerRect = container.getBoundingClientRect();
const newWidth = Math.max(400, containerRect.width - chartMarginLeft - chartMarginRight);
const newHeight = Math.max(300, containerRect.height - 100); // Leave space for controls
// Update global dimensions
width = newWidth;
height = newHeight;
LOG(`Resize: ${oldWidth}x${oldHeight} -> ${width}x${height}`);
// Resize main SVG
svg.attr('width', width + chartMarginLeft + chartMarginRight)
.attr('height', height + 100); // Extra space for bottom margin
// Update scales with new width
if (xScale && timeExtent) {
xScale.range([0, width]);
}
// Update bottom overlay dimensions
bottomOverlayWidth = Math.max(0, newWidth + chartMarginLeft + chartMarginRight);
d3.select('#chart-bottom-overlay-svg')
.attr('width', bottomOverlayWidth)
.attr('height', bottomOverlayHeight);
if (bottomOverlayRoot) {
bottomOverlayRoot.attr('transform', `translate(${chartMarginLeft},0)`);
}
// Update main chart axis and legends
if (bottomOverlayAxisGroup && xScale) {
const axis = d3.axisBottom(xScale).tickFormat(d => {
const timestampInt = Math.floor(d);
const date = new Date(timestampInt / 1000);
return date.toISOString().split('T')[1].split('.')[0];
});
bottomOverlayAxisGroup.call(axis);
// Redraw legends with new dimensions
const axisBaseY = Math.max(20, bottomOverlayHeight - 20);
if (bottomOverlayDurationLabel) {
bottomOverlayDurationLabel.attr('y', axisBaseY - 12);
}
try {
drawSizeLegend(bottomOverlayRoot, newWidth, bottomOverlayHeight, axisBaseY);
} catch (e) {
LOG('Error redrawing size legend:', e);
}
try {
drawFlagLegend();
} catch (e) {
LOG('Error redrawing flag legend:', e);
}
}
// Update zoom behavior with new dimensions
if (zoom && zoomTarget) {
const currentTransform = d3.zoomTransform(zoomTarget.node());
zoom.extent([[0, 0], [width, height]])
.scaleExtent([1, Math.max(20, width / 50)]);
// Clear the cache to force fresh calculations
fullDomainBinsCache = { version: -1, data: [], binSize: null, sorted: false };
// Also increment data version to invalidate other caches
dataVersion++;
// Clear cached selections to force fresh rendering
dotsSelection = null;
// Trigger the zoom event handler to redraw everything with new scale
// We need to dispatch a zoom event to trigger the redraw
const event = new CustomEvent('zoom');
event.transform = currentTransform;
event.sourceEvent = { type: 'resize' };
// Get the zoom handler function and call it
const zoomHandler = zoom.on('zoom');
if (typeof zoomHandler === 'function') {
try {
LOG('Calling zoom handler to redraw with new dimensions');
zoomHandler.call(zoomTarget.node(), event);
LOG('Zoom handler called successfully');
} catch (e) {
LOG('Error calling zoom handler directly:', e);
// Fallback: manually trigger zoom transform
zoomTarget.call(zoom.transform, currentTransform);
}
} else {
LOG('Zoom handler not found, using fallback');
// Fallback: manually trigger zoom transform
zoomTarget.call(zoom.transform, currentTransform);
}
}
// Recreate overview chart with new dimensions
if (timeExtent && timeExtent.length === 2) {
try {
createOverviewChart(fullData, {
timeExtent: timeExtent,
width: width,
margins: { left: chartMarginLeft, right: chartMarginRight, top: 80, bottom: 50 }
});
// Restore brush selection to current zoom domain if available
if (xScale && updateBrushFromZoom) {
updateBrushFromZoom();
}
} catch (e) {
LOG('Error recreating overview chart on resize:', e);
}
}
// The zoom handler will take care of redrawing dots and arcs
// Just need to update any additional elements that aren't handled by zoom
// Update clip path with new dimensions
if (svg) {
svg.select('#clip rect')
.attr('width', width + 40) // DOT_RADIUS equivalent
.attr('height', height + 80); // 2 * DOT_RADIUS equivalent
}
// Update global domain for overview sync
try {
window.__arc_x_domain__ = xScale.domain();
} catch {}
LOG('Window resize handling complete - zoom handler will redraw visualization');
LOG('Window resize handling complete');
} catch (e) {
console.warn('Error during window resize:', e);
}
}, 150); // 150ms debounce delay
};
// Add resize event listener
window.addEventListener('resize', handleResize);
// Also handle zoom events from browser (Ctrl+/Ctrl-)
window.addEventListener('wheel', (event) => {
if (event.ctrlKey || event.metaKey) {
// Browser zoom detected, trigger resize after a short delay
setTimeout(handleResize, 100);
}
}, { passive: true });
// Handle browser zoom via keyboard shortcuts
document.addEventListener('keydown', (event) => {
if ((event.ctrlKey || event.metaKey) && (event.key === '+' || event.key === '-' || event.key === '0')) {
// Browser zoom shortcut detected
setTimeout(handleResize, 100);
}
});
}
// Function to convert UTC datetime string to epoch microseconds
function utcToEpochMicroseconds(utcString) {
// Parse UTC datetime string like "2009-11-03 13:36:00"
const date = new Date(utcString + ' UTC');
return date.getTime() * 1000; // Convert to microseconds
}
// Function to convert epoch microseconds to UTC datetime string
function epochMicrosecondsToUTC(epochMicroseconds) {
const date = new Date(epochMicroseconds / 1000);
return date.toISOString().replace('T', ' ').replace('Z', ' UTC');
}
// Function to load ground truth data
function loadGroundTruthData() {
fetch('GroundTruth_UTC_naive.csv')
.then(response => response.text())
.then(csvText => {
const lines = csvText.split('\n');
const headers = lines[0].split(',');
groundTruthData = [];
for (let i = 1; i < lines.length; i++) {
if (lines[i].trim()) {
const values = lines[i].split(',');
if (values.length >= 8) {
const event = {
eventType: values[0],
c2sId: values[1],
source: values[2],
sourcePorts: values[3],
destination: values[4],
destinationPorts: values[5],
startTime: values[6],
stopTime: values[7],
startTimeMicroseconds: utcToEpochMicroseconds(values[6]),
stopTimeMicroseconds: utcToEpochMicroseconds(values[7])
};
groundTruthData.push(event);
}
}
}
LOG(`Loaded ${groundTruthData.length} ground truth events`);
// Update ground truth stats display
const container = document.getElementById('groundTruthStats');
container.innerHTML = `Loaded ${groundTruthData.length} ground truth events<br>Select 2+ IPs to view matching events`;
container.style.color = '#27ae60';
})
.catch(error => {
console.warn('Could not load GroundTruth_UTC_naive.csv:', error);
groundTruthData = [];
});
}
// Global update functions that preserve zoom state
let flowUpdateTimeout = null;
// Centralized helper to apply a new time domain to the main chart (keeps brush/wheel/flow zoom in sync)
function applyZoomDomain(newDomain, source = 'program') {
if (!zoom || !zoomTarget || !xScale || !timeExtent || timeExtent.length !== 2) return;
let [a, b] = newDomain;
// Clamp and normalize
const min = timeExtent[0], max = timeExtent[1];
a = Math.max(min, Math.min(max, Math.floor(a)));
b = Math.max(min, Math.min(max, Math.floor(b)));
if (b <= a) { b = Math.min(max, a + 1); }
const fullRange = max - min;
const selectedRange = b - a;
const k = fullRange / selectedRange;
const originalScale = d3.scaleLinear().domain(timeExtent).range([0, width]);
// Correct transform math: x = -k * S0(a)
const tx = -k * originalScale(a);
// If the source is the brush, notify overview to avoid circular updates
if (source === 'brush') { try { setBrushUpdating(true); } catch(_) {} }