forked from thinhhoangpham/tcp_analysis
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtcp-analysis.js
More file actions
6240 lines (5471 loc) · 265 KB
/
tcp-analysis.js
File metadata and controls
6240 lines (5471 loc) · 265 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 { initControlPanel, createIPCheckboxes as sbCreateIPCheckboxes, filterIPList as sbFilterIPList, filterFlowList as sbFilterFlowList, updateFlagStats as sbUpdateFlagStats, updateIPStats as sbUpdateIPStats, createFlowListCapped as sbCreateFlowListCapped, updateTcpFlowStats as sbUpdateTcpFlowStats, updateGroundTruthStatsUI as sbUpdateGroundTruthStatsUI, wireControlPanelControls as sbWireControlPanelControls, showFlowProgress as sbShowFlowProgress, updateFlowProgress as sbUpdateFlowProgress, hideFlowProgress as sbHideFlowProgress, wireFlowListModalControls as sbWireFlowListModalControls, showCsvProgress as sbShowCsvProgress, updateCsvProgress as sbUpdateCsvProgress, hideCsvProgress as sbHideCsvProgress, refreshIPCollapseState as sbRefreshIPCollapseState, updateSizeLegend as sbUpdateSizeLegend } from './control-panel.js';
import { renderInvalidLegend as sbRenderInvalidLegend, renderClosingLegend as sbRenderClosingLegend, drawFlagLegend as drawFlagLegendFromModule } from './legends.js';
import { initOverview, createOverviewChart, createOverviewFromAdaptive, createFlowOverviewChart, updateBrushFromZoom, updateOverviewInvalidVisibility, setBrushUpdating, refreshFlowOverview } from './overview_chart.js';
import { FLOW_RECONSTRUCT_BATCH } from './config.js';
import {
DEBUG, RADIUS_MIN, RADIUS_MAX, ROW_GAP, TOP_PAD,
TCP_STATES, HANDSHAKE_TIMEOUT_MS, REORDER_WINDOW_PKTS, REORDER_WINDOW_MS,
DEFAULT_FLAG_COLORS, FLAG_CURVATURE, PROTOCOL_MAP,
DEFAULT_FLOW_COLORS, DEFAULT_EVENT_COLORS
} from './src/config/constants.js';
import {
LOG, formatBytes, formatTimestamp, formatDuration,
utcToEpochMicroseconds, epochMicrosecondsToUTC,
makeConnectionKey, clamp, normalizeProtocolValue,
createSmartTickFormatter, createZoomAdaptiveTickFormatter
} from './src/utils/formatters.js';
import {
classifyFlags, getFlagType, flagPhase, isFlagVisibleByPhase,
has, isSYN, isSYNACK, isACKonly,
getColoredFlagBadges, getTopFlags
} from './src/tcp/flags.js';
import { getVisiblePackets, computeBarWidthPx } from './src/data/binning.js';
import { AdaptiveOverviewLoader } from './src/data/adaptive-overview-loader.js';
import {
computeTimeArcsRange,
createSyntheticFlowsFromChunks,
logSyntheticFlowRange,
initializeAdaptiveLoader,
updateFlowDataUI,
calculateChartDimensions
} from './src/data/flow-data-handler.js';
import {
reconstructFlowsFromCSVAsync,
reconstructFlowsFromCSV,
buildSelectedFlowKeySet as buildSelectedFlowKeySetFromModule,
verifyFlowPacketConnection,
exportFlowToCSV as exportFlowToCSVFromModule
} from './src/data/flowReconstruction.js';
import { renderCircles } from './src/rendering/circles.js';
import { createTooltipHTML } from './src/rendering/tooltip.js';
import { arcPathGenerator } from './src/rendering/arcPath.js';
import { createZoomBehavior, applyZoomDomain as applyZoomDomainFromModule } from './src/interaction/zoom.js';
import { setupZoomButtons, updateZoomButtonStates } from './src/interaction/zoomButtons.js';
import { createDragReorderBehavior } from './src/interaction/dragReorder.js';
import { setupWindowResizeHandler as setupWindowResizeHandlerFromModule } from './src/interaction/resize.js';
import {
loadGroundTruthData,
filterGroundTruthByIPs,
prepareGroundTruthBoxData,
calculateGroundTruthStats
} from './src/groundTruth/groundTruth.js';
import {
createPacketWorkerManager,
applyVisibilityToDots
} from './src/workers/packetWorkerManager.js';
import {
computeIPCounts,
computeIPPositioning,
applyIPPositioningToState,
computeIPPairOrderByRow,
computeIPPairCounts
} from './src/layout/ipPositioning.js';
import {
createSVGStructure,
createBottomOverlay,
renderIPRowLabels,
resizeBottomOverlay
} from './src/rendering/svgSetup.js';
import {
prepareInitialRenderData,
performInitialRender,
createRadiusScale
} from './src/rendering/initialRender.js';
import {
createTimeArcsZoomHandler,
createDurationLabelUpdater,
clearZoomTimeouts,
resetResolutionTransitionState
} from './src/interaction/timearcsZoomHandler.js';
import { createIPFilterController } from './src/interaction/ip-filter-controller.js';
import { tryLoadFlowList, getFlowListLoader } from './src/data/flow-list-loader.js';
// Multi-resolution support (optional - may not be available)
let getMultiResData = null;
let isMultiResAvailable = null;
let getCurrentResolution = null;
let setMultiResSelectedIPs = null;
let loadFlowDetailWithPackets = null;
let extractPacketsFromFlow = null;
let getChunkedFlowState = null;
// Try to dynamically import multi-resolution functions
try {
const folderIntegration = await import('./folder_integration.js');
getMultiResData = folderIntegration.getMultiResData;
isMultiResAvailable = folderIntegration.isMultiResAvailable;
getCurrentResolution = folderIntegration.getCurrentResolution;
setMultiResSelectedIPs = folderIntegration.setMultiResSelectedIPs;
loadFlowDetailWithPackets = folderIntegration.loadFlowDetailWithPackets;
extractPacketsFromFlow = folderIntegration.extractPacketsFromFlow;
getChunkedFlowState = folderIntegration.getChunkedFlowState;
console.log('Multi-resolution support loaded');
} catch (err) {
console.log('Multi-resolution support not available:', err.message);
}
// Multi-resolution state
let useMultiRes = false; // Whether to use multi-resolution data
let currentResolutionLevel = null; // Current resolution: 'seconds', 'milliseconds', 'raw', or null
let isInitialResolutionLoad = true; // Only sync with overview on initial load, then allow free zoom
let manualResolutionOverride = null; // User-selected resolution override (null = auto)
let defaultCollapseApplied = false; // Auto-collapse all multi-pair IP rows on first render
// --- Web Worker for packet filtering ---
let workerManager = null;
function initializeWorkerManager() {
workerManager = createPacketWorkerManager({
onVisibilityApplied: (mask) => {
if (!mainGroup) {
console.warn('Worker visibility applied but mainGroup not available');
return;
}
const dots = mainGroup.selectAll('.direction-dot').nodes();
if (DEBUG && dots.length !== mask.length) {
console.warn(`Worker mask/dots mismatch: mask=${mask.length}, dots=${dots.length}. This may indicate DOM was updated after worker init.`);
}
applyVisibilityToDots(mask, dots, {
onComplete: () => {
try { applyInvalidReasonFilter(); } catch(e) { logCatchError('applyInvalidReasonFilter', e); }
}
});
},
onError: (error) => {
console.error('Worker error, falling back to legacy filtering:', error);
legacyFilterPacketsBySelectedFlows();
}
});
}
// --- Error logging helper for catch blocks ---
// Provides consistent error logging with context for debugging
// Usage: catch(e) { logCatchError('functionName', e); }
function logCatchError(context, error) {
if (DEBUG) {
console.warn(`[${context}] Error caught:`, error?.message || error);
}
}
function reinitializeWorkerIfNeeded(packets) {
if (workerManager && packets) {
try {
workerManager.initPackets(packets);
} catch (err) {
console.error('Failed to reinitialize worker:', err);
legacyFilterPacketsBySelectedFlows();
}
}
}
function syncWorkerWithRenderedData() {
if (!workerManager || !mainGroup) return;
// Get currently rendered dots data
const dots = mainGroup.selectAll('.direction-dot');
const renderedData = [];
dots.each(function(d) {
if (d) {
// Extract the data bound to each DOM element
renderedData.push({
src_ip: d.src_ip,
dst_ip: d.dst_ip,
src_port: d.src_port,
dst_port: d.dst_port,
_packetIndex: renderedData.length // Use array index as packet index
});
}
});
if (renderedData.length > 0) {
try {
workerManager.initPackets(renderedData);
} catch (err) {
console.error('Failed to sync worker with rendered data:', err);
}
}
}
// state.data.full, state.data.filtered, state.data.isPreBinned moved to state.data (Phase 6)
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 = 180;
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
// state.data.timeExtent moved to state.data (Phase 6)
// Global bin count is sourced from shared config.js
// pairs, state.layout.ipPositions, ipOrder moved to state.layout (Phase 4)
// TimeArcs integration variables moved to state.timearcs (Phase 3)
// Force layout variables moved to state.layout (Phase 4)
// Flow variables moved to state.flows (Phase 5)
// 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 (state.data.version moved to state.data)
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)
// - globalMaxBinCount: computed from the initial full-domain binning; reused at all zoom levels
let globalMaxBinCount = 1;
// useBinning and renderMode moved to state.ui (Phase 2)
// Consolidated state object for better organization
const state = {
// Phase 1: Flow Detail Mode (isolated, ~20 refs)
flowDetail: {
mode: false, // Whether we're in single-flow detail view
flow: null, // The flow object being viewed in detail
packets: [], // Extracted packets from the flow
previousState: null // State to restore when exiting flow detail mode
},
// Phase 2: UI Toggles (isolated, ~30 refs)
ui: {
showTcpFlows: true, // Toggle for TCP flow visualization
showEstablishment: true, // Toggle for establishment phase
showDataTransfer: true, // Toggle for data transfer phase
showClosing: true, // Toggle for closing phase
showGroundTruth: false, // Toggle for ground truth visualization
useBinning: true, // User toggle: binning on/off
renderMode: 'circles', // Render mode (circles only)
separateFlags: false, // Spread overlapping flag circles vertically
showSubRowArcs: false, // Show permanent ghost arcs for IP pair sub-rows
showFlowThreading: true // Auto-draw flow threading arcs at raw resolution
},
// Phase 3: TimeArcs Integration (isolated, ~50 refs)
timearcs: {
ipOrder: null, // Array of IPs in vertical order from TimeArcs, or null
timeRange: null, // {minUs, maxUs} or null (microseconds)
overviewTimeExtent: null, // [start, end] in data units, or null (falls back to state.data.timeExtent)
intendedZoomDomain: null // [start, end] in data units, persists zoom state
},
// Phase 4: Layout (medium coupling, ~70 refs)
layout: {
ipPositions: new Map(), // Global IP positions map
ipOrder: [], // Current vertical order of IPs
pairs: new Map(), // Global pairs map for IP pairing system
ipPairCounts: new Map(), // Count of unique destination IPs per source IP
ipRowHeights: new Map(), // Per-IP row heights based on pair count
ipConnectivity: new Map(), // Map<ip, Set<connectedIps>> for row highlighting
collapsedIPs: new Set() // Set of IPs whose sub-rows are collapsed into one
},
// Phase 5: Flows (medium coupling, ~60 refs)
flows: {
tcp: [], // Store detected TCP flows (from CSV)
current: [], // Flows matching current IP selection (subset of tcp)
selectedIds: new Set(), // Store IDs of selected flows as strings
groundTruth: [] // Store ground truth events
},
// Phase 6: Data (high coupling, ~130 refs)
data: {
full: [], // Full dataset
filtered: [], // Filtered dataset (by IP selection)
isPreBinned: false, // Track if data is already pre-binned (from multi-resolution)
version: 0, // Increment when filtered data changes
timeExtent: [0, 0] // Global time extent for the dataset
}
};
// Create canonical IP pair key (alphabetically ordered)
function makeIpPairKey(srcIp, dstIp) {
if (!srcIp || !dstIp) return 'unknown';
return srcIp < dstIp ? `${srcIp}<->${dstIp}` : `${dstIp}<->${srcIp}`;
}
/**
* Merge bins for collapsed IPs: bins at the same (time, yPos, flagType) from
* different IP pairs are combined into a single bin with summed counts.
* Only bins whose src_ip is in the collapsedIPs set are merged.
*/
function collapseSubRowsBins(binned, collapsedIPs) {
if (!collapsedIPs || collapsedIPs.size === 0) return binned;
const pass = []; // bins for non-collapsed IPs (unchanged)
const merge = []; // bins for collapsed IPs (need merging)
for (const d of binned) {
if (d.src_ip && collapsedIPs.has(d.src_ip)) {
merge.push(d);
} else {
pass.push(d);
}
}
if (merge.length === 0) return binned;
// Group by (time | yPos | flagType)
const groups = new Map();
for (const d of merge) {
const t = Number.isFinite(d.binCenter) ? Math.floor(d.binCenter)
: (Number.isFinite(d.binTimestamp) ? Math.floor(d.binTimestamp) : Math.floor(d.timestamp));
const ft = d.flagType || 'OTHER';
const key = `${t}|${d.yPos}|${ft}`;
let g = groups.get(key);
if (!g) {
g = {
...d,
count: 0,
totalBytes: 0,
originalPackets: [],
ipPairs: [],
allIPs: new Set(),
_seenPairs: new Set()
};
groups.set(key, g);
}
g.count += (d.count || 1);
g.totalBytes = (g.totalBytes || 0) + (d.totalBytes || 0);
if (Array.isArray(d.originalPackets)) {
g.originalPackets.push(...d.originalPackets);
}
if (d.src_ip) g.allIPs.add(d.src_ip);
if (d.dst_ip) g.allIPs.add(d.dst_ip);
const pk = makeIpPairKey(d.src_ip, d.dst_ip);
if (!g._seenPairs.has(pk)) {
g._seenPairs.add(pk);
g.ipPairs.push({ src_ip: d.src_ip, dst_ip: d.dst_ip, count: d.count || 1 });
}
}
for (const g of groups.values()) {
g.ipPairKey = '__collapsed__';
delete g._seenPairs;
pass.push(g);
}
return pass;
}
/**
* Compute the maximum merged bin count per collapsed IP.
* Mirrors the grouping logic of collapseSubRowsBins but only tracks max counts.
* Used to update globalMaxBinCount and row heights for collapsed IPs.
* @param {Array} binnedPackets - Binned packet data (pre-collapse)
* @param {Set} collapsedIPs - Set of collapsed IP addresses
* @returns {Object|null} { globalMax, maxPerIP: Map<string, number> } or null if no collapsed IPs
*/
function computeCollapsedMaxCounts(binnedPackets, collapsedIPs) {
if (!collapsedIPs || collapsedIPs.size === 0) return null;
const maxPerIP = new Map();
const groups = new Map(); // key: "ip|time|flag" → count
for (const d of binnedPackets) {
if (!d.src_ip || !collapsedIPs.has(d.src_ip)) continue;
const t = Number.isFinite(d.binCenter) ? Math.floor(d.binCenter)
: (Number.isFinite(d.binTimestamp) ? Math.floor(d.binTimestamp) : Math.floor(d.timestamp));
const ft = d.flagType || 'OTHER';
const key = `${d.src_ip}|${t}|${ft}`;
groups.set(key, (groups.get(key) || 0) + (d.count || 1));
}
let globalMax = 0;
for (const [key, count] of groups) {
const ip = key.split('|')[0];
if (count > (maxPerIP.get(ip) || 0)) maxPerIP.set(ip, count);
if (count > globalMax) globalMax = count;
}
return { globalMax, maxPerIP };
}
/**
* Apply collapse overrides to ipPairOrderByRow for collapsed IPs.
* All pairs for a collapsed IP get index 0, count 1.
*/
function applyCollapseOverrides(ipPairOrderByRow) {
if (!state.layout.collapsedIPs.size) return;
for (const ip of state.layout.collapsedIPs) {
const yPos = state.layout.ipPositions.get(ip);
if (yPos === undefined) continue;
const pairInfo = ipPairOrderByRow.get(yPos);
if (pairInfo) {
const collapsedOrder = new Map();
for (const key of pairInfo.order.keys()) collapsedOrder.set(key, 0);
ipPairOrderByRow.set(yPos, { order: collapsedOrder, count: 1 });
}
}
}
/**
* Calculate the vertical position for the expand-all button based on visible IPs.
* @param {number} marginTop - The chart's top margin (px)
*/
function updateExpandAllBtnPosition(marginTop) {
const container = document.getElementById('chart-container');
const btn = document.getElementById('expand-all-btn');
if (!container || !btn) return;
// Collect y-positions (in container content space) of ALL IPs
let minY = Infinity, maxY = -Infinity;
for (const [, yPos] of state.layout.ipPositions) {
const contentY = yPos + marginTop;
if (contentY < minY) minY = contentY;
if (contentY > maxY) maxY = contentY;
}
if (minY === Infinity) { btn.style.display = 'none'; return; }
// Visible viewport in content-space coordinates
const viewTop = container.scrollTop;
const viewBottom = viewTop + container.clientHeight;
// Clamp the IP span to the visible viewport
const clampedTop = Math.max(minY, viewTop);
const clampedBottom = Math.min(maxY, viewBottom);
let centerY;
if (clampedTop <= clampedBottom) {
// IPs overlap with viewport — center within the overlap
centerY = (clampedTop + clampedBottom) / 2;
} else {
// No IPs visible — center in viewport
centerY = viewTop + container.clientHeight / 2;
}
btn.style.top = (centerY - 12) + 'px'; // 12 = half button height (24px)
}
/** Scroll listener reference so we don't double-bind */
let _expandAllScrollBound = false;
/**
* Create or update the floating "Expand/Collapse All" sub-row button.
* Called after renderIPRowLabels on each render.
* @param {number} marginTop - The chart's top margin (px)
*/
function createOrUpdateExpandAllBtn(marginTop) {
const container = document.getElementById('chart-container');
if (!container) return;
// Only show when multi-pair IPs exist
let hasMultiPairIPs = false;
if (state.layout.ipPairCounts) {
for (const [, count] of state.layout.ipPairCounts) {
if (count > 1) { hasMultiPairIPs = true; break; }
}
}
let btn = document.getElementById('expand-all-btn');
if (!btn) {
btn = document.createElement('div');
btn.id = 'expand-all-btn';
container.appendChild(btn);
btn.addEventListener('click', () => {
if (state.layout.collapsedIPs.size > 0) {
// Expand all
state.layout.collapsedIPs.clear();
} else {
// Collapse all
for (const ip of state.layout.ipOrder) {
if ((state.layout.ipPairCounts.get(ip) || 1) > 1) {
state.layout.collapsedIPs.add(ip);
}
}
}
isHardResetInProgress = true;
visualizeTimeArcs(state.data.filtered);
updateTcpFlowPacketsGlobal();
drawSelectedFlowArcs();
applyInvalidReasonFilter();
});
btn.addEventListener('mouseenter', () => {
const circle = btn.querySelector('circle');
if (!circle) return;
const collapsed = state.layout.collapsedIPs.size > 0;
circle.setAttribute('fill', collapsed ? '#5a6268' : '#218838');
});
btn.addEventListener('mouseleave', () => {
const circle = btn.querySelector('circle');
if (!circle) return;
const collapsed = state.layout.collapsedIPs.size > 0;
circle.setAttribute('fill', collapsed ? '#6c757d' : '#28a745');
});
}
// Bind scroll + resize listeners once
if (!_expandAllScrollBound) {
_expandAllScrollBound = true;
container.addEventListener('scroll', () => updateExpandAllBtnPosition(marginTop), { passive: true });
// ResizeObserver catches layout shifts (overview chart appearing, window resize)
new ResizeObserver(() => updateExpandAllBtnPosition(marginTop)).observe(container);
}
btn.style.display = hasMultiPairIPs ? '' : 'none';
if (!hasMultiPairIPs) return;
// Visual state: collapsed → gray + right chevron; expanded → green + down chevron
const isCollapsedState = state.layout.collapsedIPs.size > 0;
const fill = isCollapsedState ? '#6c757d' : '#28a745';
const chevron = isCollapsedState
? 'M -2 -3 L 2 0 L -2 3' // right chevron (collapsed state)
: 'M -3 -2 L 0 2 L 3 -2'; // down chevron (expanded state)
const title = isCollapsedState ? 'Expand all sub-rows' : 'Collapse all sub-rows';
btn.title = title;
btn.innerHTML = `
<svg width="24" height="24" viewBox="-12 -12 24 24">
<circle r="9" fill="${fill}" stroke="#fff" stroke-width="2" style="transition: fill 0.2s ease;"/>
<path d="${chevron}" fill="none" stroke="#fff" stroke-width="2.5"
stroke-linecap="round" stroke-linejoin="round"/>
</svg>`;
// Position after layout settles (DOM may not be final during render)
requestAnimationFrame(() => updateExpandAllBtnPosition(marginTop));
}
/**
* Compute y position for an IP accounting for sub-row offset within an expanded row.
* Falls back to base ipPositions when sub-row data is unavailable.
*/
function getIPYWithSubRowOffset(ip, srcIp, dstIp) {
const baseY = findIPPosition(ip, srcIp, dstIp, state.layout.pairs, state.layout.ipPositions);
if (!baseY || !state.layout.ipPairOrderByRow) return baseY;
const pairKey = makeIpPairKey(srcIp, dstIp);
const pairInfo = state.layout.ipPairOrderByRow.get(baseY);
if (!pairInfo || pairInfo.count <= 1) return baseY;
const pairIndex = pairInfo.order.get(pairKey) || 0;
const rh = (state.layout.ipRowHeights && state.layout.ipRowHeights.get(ip)) || ROW_GAP;
const availableHeight = Math.max(20, rh - 6);
const totalGaps = Math.max(0, pairInfo.count - 1) * 2;
const subRowHeight = Math.max(4, (availableHeight - totalGaps) / pairInfo.count);
return baseY + pairIndex * (subRowHeight + 2);
}
/**
* Build a position lookup from rendered DOM circles.
* This accounts for both sub-row offsets AND flag separation — the single
* source of truth for where circles actually appear on screen.
* Returns { exact: Map, byRow: Map } where:
* exact: `${time}|${src_ip}|${dst_ip}|${flagType}` → yPosWithOffset
* byRow: `${time}|${src_ip}|${flagType}` → yPosWithOffset (fallback for collapsed rows)
*/
function buildCirclePositionMap() {
const exact = new Map();
const byRow = new Map();
const activeLayer = (dynamicLayer && dynamicLayer.style('display') !== 'none' && !dynamicLayer.selectAll('.direction-dot').empty())
? dynamicLayer
: fullDomainLayer;
if (!activeLayer) return { exact, byRow };
activeLayer.selectAll('.direction-dot').each(function () {
const d = d3.select(this).datum();
if (!d || !d.src_ip) return;
const time = Math.floor(d.binCenter ?? d.timestamp ?? 0);
const flagType = d.flagType || d.flag_type || getFlagType(d);
const yPos = d.yPosWithOffset;
if (yPos == null) return;
// For collapsed circles, register every merged IP pair
const pairs = (d.ipPairKey === '__collapsed__' && Array.isArray(d.ipPairs))
? d.ipPairs
: [{ src_ip: d.src_ip, dst_ip: d.dst_ip }];
for (const p of pairs) {
if (p.dst_ip) {
exact.set(`${time}|${d.src_ip}|${p.dst_ip}|${flagType}`, yPos);
}
}
// Row-level fallback (first circle wins — all collapsed circles share yPos)
const rowKey = `${time}|${d.src_ip}|${flagType}`;
if (!byRow.has(rowKey)) byRow.set(rowKey, yPos);
});
return { exact, byRow };
}
/**
* Look up the actual rendered y-position for a packet using the circle position map.
* Falls back to getIPYWithSubRowOffset() when no matching circle is in the DOM.
*/
function lookupCircleY(circlePosMap, time, srcIp, dstIp, flagType) {
const t = Math.floor(time);
return circlePosMap.exact.get(`${t}|${srcIp}|${dstIp}|${flagType}`)
?? circlePosMap.byRow.get(`${t}|${srcIp}|${flagType}`)
?? getIPYWithSubRowOffset(srcIp, srcIp, dstIp);
}
/**
* Sync sub-row-highlight rect positions with current state.layout.
* Called after any position recalculation (collapse adjustment, drag reorder).
*/
function syncSubRowHighlights(svgEl, st) {
const SUB_ROW_GAP = 2;
svgEl.selectAll('.sub-row-highlight, .sub-row-hover-target').each(function() {
const rect = d3.select(this);
const d = rect.datum();
if (!d || !d.ip) return;
const baseY = st.layout.ipPositions.get(d.ip);
if (baseY === undefined) return;
const rh = (st.layout.ipRowHeights && st.layout.ipRowHeights.get(d.ip)) || ROW_GAP;
const pairInfo = st.layout.ipPairOrderByRow.get(baseY);
if (!pairInfo) return;
const availableHeight = Math.max(20, rh - 6);
const totalGaps = Math.max(0, pairInfo.count - 1) * SUB_ROW_GAP;
const subRowHeight = Math.max(4, (availableHeight - totalGaps) / pairInfo.count);
const centerY = baseY + d.pairIndex * (subRowHeight + SUB_ROW_GAP);
rect.attr('y', centerY - subRowHeight / 2)
.attr('height', subRowHeight);
});
}
// Circle hover: highlight source/destination IP rows and labels
function onCircleHighlight(srcIp, dstIps) {
// Bold source label, mark destination labels, fade others
svg.selectAll('.node-label')
.classed('highlighted', d => d === srcIp)
.classed('connected', d => dstIps.has(d))
.classed('faded', d => d !== srcIp && !dstIps.has(d));
// Grey row backgrounds for source and destination rows
svg.selectAll('.row-highlight')
.classed('self', d => d === srcIp)
.classed('active', d => dstIps.has(d));
// Sub-row highlights for expanded multi-pair IPs
svg.selectAll('.sub-row-highlight')
.classed('self', d => d && d.ip === srcIp)
.classed('active', d => d && dstIps.has(d.ip));
}
function onCircleClearHighlight() {
svg.selectAll('.node-label')
.classed('highlighted', false)
.classed('connected', false)
.classed('faded', false);
svg.selectAll('.row-highlight')
.classed('self', false)
.classed('active', false);
svg.selectAll('.sub-row-highlight')
.classed('self', false)
.classed('active', false);
}
// Wrapper to call imported renderCircles with required options and event handlers
function renderCirclesWithOptions(layer, binned, rScale, transitionOpts) {
const data = collapseSubRowsBins(binned, state.layout.collapsedIPs);
const processed = renderCircles(layer, data, {
xScale,
rScale,
flagColors,
RADIUS_MIN,
ROW_GAP,
ipRowHeights: state.layout.ipRowHeights,
ipPairCounts: state.layout.ipPairCounts,
stableIpPairOrderByRow: state.layout.ipPairOrderByRow,
mainGroup,
arcPathGenerator,
findIPPosition,
pairs: state.layout.pairs,
ipPositions: state.layout.ipPositions,
createTooltipHTML,
FLAG_CURVATURE,
d3,
separateFlags: state.ui.separateFlags,
onCircleHighlight,
onCircleClearHighlight,
transitionOpts
});
}
// Unified render function
function renderMarksForLayerLocal(layer, data, rScale, transitionOpts) {
return renderCirclesWithOptions(layer, data, rScale, transitionOpts);
}
// Size legend moved to control panel; update it there
function drawSizeLegend() {
sbUpdateSizeLegend(globalMaxBinCount, RADIUS_MIN, RADIUS_MAX);
}
// Flag color legend moved to control panel; no-op here to keep call sites intact
function drawFlagLegend() {}
// TCP flag colors, now loaded from flag_colors.json with defaults
let flagColors = { ...DEFAULT_FLAG_COLORS };
// 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
}
};
// 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(e) { logCatchError('drawFlagLegend', e); }
})
.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
});
// 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: () => {
const result = state.timearcs.overviewTimeExtent || flowDataState?.timeExtent || state.data.timeExtent;
console.log('[getTimeExtent] Returning:', result, '| state.timearcs.overviewTimeExtent:', state.timearcs.overviewTimeExtent, '| flowDataState?.timeExtent:', flowDataState?.timeExtent, '| timeExtent:', state.data.timeExtent);
return result;
},
getCurrentDomain: () => {
// Return current xScale domain, with state.timearcs.intendedZoomDomain as fallback
// This handles race conditions where zoom hasn't been applied yet
const current = xScale ? xScale.domain() : null;
if (current && current[0] !== undefined && current[1] !== undefined) {
// Check if at full extent - if so, prefer state.timearcs.intendedZoomDomain
const atFullExtent = state.data.timeExtent &&
Math.abs(current[0] - state.data.timeExtent[0]) < 1 &&
Math.abs(current[1] - state.data.timeExtent[1]) < 1;
if (atFullExtent && state.timearcs.intendedZoomDomain) {
return state.timearcs.intendedZoomDomain;
}
return current;
}
return state.timearcs.intendedZoomDomain || current;
},
getOverviewTimeExtent: () => state.timearcs.overviewTimeExtent, // TimeArcs range or null
getCurrentFlows: () => state.flows.current,
getSelectedFlowIds: () => state.flows.selectedIds,
updateTcpFlowPacketsGlobal: () => updateTcpFlowPacketsGlobal(),
createFlowList: (flows) => createFlowList(flows),
// Load flows for a given time range (async, prefers FlowListLoader CSV files when available)
loadChunksForTimeRange: async (startTime, endTime) => {
const state = getFlowDataState();
// Get currently selected IPs to filter flows
const selectedIPs = Array.from(document.querySelectorAll('#ipCheckboxes input[type="checkbox"]:checked'))
.map(cb => cb.value);
// Try FlowListLoader first (loads from CSV files - works without chunk files)
const flowListLoader = getFlowListLoader();
if (flowListLoader.isLoaded()) {
console.log(`[loadChunksForTimeRange] Using FlowListLoader CSV for ${selectedIPs.length} IPs, time: ${startTime}-${endTime}`);
const flows = await flowListLoader.filterByIPs(selectedIPs, [startTime, endTime]);
console.log(`[loadChunksForTimeRange] FlowListLoader returned ${flows.length} flows`);
return flows;
}
// Fall back to chunked flows loader
if (state && typeof state.loadChunksForTimeRange === 'function') {
return await state.loadChunksForTimeRange(startTime, endTime, selectedIPs);
}
if (state && typeof state.loadFlowsForTimeRange === 'function') {
const result = await state.loadFlowsForTimeRange(startTime, endTime);
// For multires, filter by selected IPs here since the function doesn't support it
if (result && selectedIPs.length > 0) {
const selectedIPSet = new Set(selectedIPs);
return result.filter(f =>
selectedIPSet.has(f.initiator) && selectedIPSet.has(f.responder)
);
}
return result;
}
return [];
},
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,
flagColors,
flowColors
});
initControlPanel({
onResetView: () => {
if (state.data.full.length > 0 && zoomTarget && zoom && state.data.timeExtent && state.data.timeExtent[1] > state.data.timeExtent[0]) {
isHardResetInProgress = true;
applyZoomDomain([state.data.timeExtent[0], state.data.timeExtent[1]], 'reset');
if (state.ui.showTcpFlows && state.flows.selectedIds && state.flows.selectedIds.size > 0) {
try { setTimeout(() => redrawSelectedFlowsView(), 0); } catch(e) { logCatchError('redrawSelectedFlowsView', e); }
}
}
}
});
// Delegate control panel event wiring
sbWireControlPanelControls({
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) => { state.ui.showTcpFlows = checked; updateTcpFlowPacketsGlobal(); drawSelectedFlowArcs(); try { applyInvalidReasonFilter(); } catch(e) { logCatchError('applyInvalidReasonFilter', e); } },
onToggleEstablishment: (checked) => { state.ui.showEstablishment = checked; drawSelectedFlowArcs(); try { applyInvalidReasonFilter(); } catch(e) { logCatchError('applyInvalidReasonFilter', e); } },
onToggleDataTransfer: (checked) => { state.ui.showDataTransfer = checked; drawSelectedFlowArcs(); try { applyInvalidReasonFilter(); } catch(e) { logCatchError('applyInvalidReasonFilter', e); } },
onToggleClosing: (checked) => { state.ui.showClosing = checked; drawSelectedFlowArcs(); try { applyInvalidReasonFilter(); } catch(e) { logCatchError('applyInvalidReasonFilter', e); } },
onToggleGroundTruth: (checked) => { state.ui.showGroundTruth = checked; const selectedIPs = Array.from(document.querySelectorAll('#ipCheckboxes input[type="checkbox"]:checked')).map(cb => cb.value); drawGroundTruthBoxes(selectedIPs); },
onToggleSubRowArcs: (checked) => {
state.ui.showSubRowArcs = checked;
drawSubRowArcs();
},
onToggleSeparateFlags: (checked) => {
state.ui.separateFlags = checked;
isHardResetInProgress = true;
try {
visualizeTimeArcs(state.data.filtered);
updateTcpFlowPacketsGlobal();
drawSelectedFlowArcs();
applyInvalidReasonFilter();
} catch(e) { logCatchError('toggleSeparateFlags', e); }
},
onToggleFlowThreading: (checked) => {
state.ui.showFlowThreading = checked;
if (!checked) {
clearAutoFlowThreading();
} else if (currentResolutionLevel === 'raw' && xScale) {
// Turning on while already at raw resolution — draw immediately
const visible = getVisiblePackets(state.data.filtered, xScale);
drawAutoFlowThreading(visible);
}
},
onToggleBinning: (checked) => {
state.ui.useBinning = checked;
isHardResetInProgress = true;
// Force immediate re-render of the visualization
try {
// Re-render the main visualization with current filtered data
visualizeTimeArcs(state.data.filtered);
// 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(e) { logCatchError('drawSizeLegend', e); }
drawFlagLegend();
const selIPs = Array.from(document.querySelectorAll('#ipCheckboxes input[type="checkbox"]:checked')).map(cb => cb.value);
drawGroundTruthBoxes(selIPs);
} catch(e) { logCatchError('binningToggle.refresh', e); }
}, 50);
} catch (e) {
console.warn('Error updating visualization after binning toggle:', e);
// Fallback to original behavior
applyZoomDomain(xScale.domain(), 'program');
}
}
});
// Window resize handler for responsive visualization
setupWindowResizeHandler();
// Zoom In/Out button handlers (configurable zoom step per click)
setupZoomButtons({
getXScale: () => xScale,
getTimeExtent: () => state.data.timeExtent,
applyZoomDomain,
setIsHardResetInProgress: (val) => { isHardResetInProgress = val; }
});
// Populate resolution dropdown
populateResolutionDropdown();
// 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(e) { logCatchError('sbWireFlowListModalControls', e); }
}
// Window resize handler for responsive visualization
// Uses module for event handling, with custom onResize callback for app-specific logic
function setupWindowResizeHandler() {
const handleResizeLogic = () => {
try {
// Only proceed if we have data and existing visualization
if (!state.data.full || state.data.full.length === 0 || !svg || !xScale || !yScale) {
return;
}
console.log('[Resize] Handling window resize, updating visualization dimensions');
// Store old dimensions for comparison
const oldWidth = width;
const oldHeight = height;
// IMPORTANT: Save the current TIME DOMAIN before resize
// This is what we want to preserve, not the pixel-based transform
const currentDomain = xScale.domain();
console.log('[Resize] Preserving time domain across resize:', currentDomain);
console.log('[Resize] Current timeExtent:', state.data.timeExtent);
const container = d3.select("#chart-container").node();
if (!container) return;
// Calculate new dimensions
const containerRect = container.getBoundingClientRect();