forked from thinhhoangpham/tcp_analysis
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathattack-network.js
More file actions
1943 lines (1674 loc) · 76.1 KB
/
attack-network.js
File metadata and controls
1943 lines (1674 loc) · 76.1 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
import { MARGIN, DEFAULT_WIDTH, DEFAULT_HEIGHT, INNER_HEIGHT, MIN_IP_SPACING, MIN_IP_SPACING_WITHIN_COMPONENT, INTER_COMPONENT_GAP, PROTOCOL_COLORS, DEFAULT_COLOR, NEUTRAL_GREY } from './src/config/constants.js';
import { toNumber, sanitizeId, canonicalizeName, showTooltip, hideTooltip, setStatus } from './src/utils/helpers.js';
import { decodeIp, decodeAttack, decodeAttackGroup, lookupAttackColor, lookupAttackGroupColor } from './src/mappings/decoders.js';
import { buildRelationships, computeConnectivityFromRelationships, computeLinks, findConnectedComponents } from './src/data/aggregation.js';
import { componentLoader } from './src/data/component-loader.js';
import { linkArc, gradientIdForLink } from './src/rendering/arcPath.js';
import { buildLegend as createLegend, updateLegendVisualState as updateLegendUI, isolateAttack as isolateLegendAttack } from './src/ui/legend.js';
import { parseCSVStream, parseCSVLine } from './src/data/csvParser.js';
import { detectTimestampUnit, createToDateConverter, createTimeScale, createIpScale, createWidthScale, calculateMaxArcRadius } from './src/scales/scaleFactory.js';
import { createForceSimulation, runUntilConverged, createComponentSeparationForce, createWeakComponentSeparationForce, createComponentCohesionForce, createHubCenteringForce, createComponentYForce, initializeNodePositions, calculateComponentCenters, findComponentHubIps, calculateIpDegrees, calculateConnectionStrength, createMutualHubAttractionForce } from './src/layout/forceSimulation.js';
import { createLensXScale } from './src/scales/distortion.js';
import { updateFocusRegion } from './src/scales/bifocal.js';
import { createBifocalHandles } from './src/ui/bifocal-handles.js';
import { computeIpSpans, createSpanData, renderRowLines, renderIpLabels, createLabelHoverHandler, createLabelMoveHandler, createLabelLeaveHandler, attachLabelHoverHandlers, renderComponentToggles, updateComponentToggles, showComponentToggles } from './src/rendering/rows.js';
import { createArcHoverHandler, createArcMoveHandler, createArcLeaveHandler, attachArcHandlers } from './src/rendering/arcInteractions.js';
import { loadAllMappings } from './src/mappings/loaders.js';
import { setupWindowResizeHandler as setupWindowResizeHandlerFromModule } from './src/interaction/resize.js';
import { ForceNetworkLayout } from './src/layout/force_network.js';
import { TimearcsLayout } from './src/layout/timearcs_layout.js';
// Network TimeArcs visualization
// Input CSV schema: timestamp,length,src_ip,dst_ip,protocol,count
// - timestamp: integer absolute minutes. If very large (>1e6), treated as minutes since Unix epoch.
// Otherwise treated as relative minutes and displayed as t=.. labels.
(function () {
const fileInput = document.getElementById('fileInput');
const statusEl = document.getElementById('status');
const svg = d3.select('#chart');
const container = document.getElementById('chart-container');
const legendEl = document.getElementById('legend');
const tooltip = document.getElementById('tooltip');
const labelModeRadios = document.querySelectorAll('input[name="labelMode"]');
const brushStatusEl = document.getElementById('brushStatus');
const brushStatusText = document.getElementById('brushStatusText');
const clearBrushBtn = document.getElementById('clearBrush');
// Legend panel collapse/expand functionality
const legendPanel = document.getElementById('legendPanel');
const legendPanelHeader = document.getElementById('legendPanelHeader');
let legendPanelDragState = null;
let legendPanelCollapsed = false;
function toggleLegendCollapse() {
if (legendPanel) {
legendPanelCollapsed = !legendPanelCollapsed;
if (legendPanelCollapsed) {
legendPanel.classList.add('collapsed');
} else {
legendPanel.classList.remove('collapsed');
}
}
}
// Make legend panel draggable and collapsible
if (legendPanel && legendPanelHeader) {
let clickStartTime = 0;
let clickStartPos = { x: 0, y: 0 };
legendPanelHeader.addEventListener('mousedown', (e) => {
clickStartTime = Date.now();
clickStartPos = { x: e.clientX, y: e.clientY };
const rect = legendPanel.getBoundingClientRect();
legendPanelDragState = {
offsetX: e.clientX - rect.left,
offsetY: e.clientY - rect.top,
startX: e.clientX,
startY: e.clientY,
hasMoved: false
};
document.addEventListener('mousemove', onLegendPanelDrag);
document.addEventListener('mouseup', onLegendPanelDragEnd);
e.preventDefault();
});
}
function onLegendPanelDrag(e) {
if (!legendPanelDragState || !legendPanel) return;
const dragDistance = Math.sqrt(
Math.pow(e.clientX - legendPanelDragState.startX, 2) +
Math.pow(e.clientY - legendPanelDragState.startY, 2)
);
// Only start dragging if moved more than 5 pixels
if (dragDistance > 5) {
legendPanelDragState.hasMoved = true;
legendPanelHeader.style.cursor = 'grabbing';
const newLeft = e.clientX - legendPanelDragState.offsetX;
const newTop = e.clientY - legendPanelDragState.offsetY;
// Keep within viewport bounds
const maxLeft = window.innerWidth - legendPanel.offsetWidth;
const maxTop = window.innerHeight - legendPanel.offsetHeight;
legendPanel.style.left = Math.max(0, Math.min(newLeft, maxLeft)) + 'px';
legendPanel.style.top = Math.max(0, Math.min(newTop, maxTop)) + 'px';
legendPanel.style.right = 'auto'; // Override right positioning when dragging
}
}
function onLegendPanelDragEnd(e) {
if (legendPanelDragState && !legendPanelDragState.hasMoved) {
// This was a click, not a drag - toggle collapse
toggleLegendCollapse();
}
legendPanelDragState = null;
if (legendPanelHeader) {
legendPanelHeader.style.cursor = 'pointer';
}
document.removeEventListener('mousemove', onLegendPanelDrag);
document.removeEventListener('mouseup', onLegendPanelDragEnd);
}
// Progress bar elements
const loadingProgressEl = document.getElementById('loadingProgress');
const progressBarEl = document.getElementById('progressBar');
const progressTextEl = document.getElementById('progressText');
// Bifocal controls (always enabled, no toggle button)
const compressionSlider = document.getElementById('compressionSlider');
const compressionValue = document.getElementById('compressionValue');
const bifocalRegionIndicator = document.getElementById('bifocalRegionIndicator');
const bifocalRegionText = document.getElementById('bifocalRegionText');
// IP Communications panel elements
const ipCommHeader = document.getElementById('ip-comm-header');
const ipCommContent = document.getElementById('ip-comm-content');
const ipCommToggle = document.getElementById('ip-comm-toggle');
const ipCommList = document.getElementById('ip-comm-list');
const exportIPListBtn = document.getElementById('exportIPList');
// Store IP pairs data for export
let currentPairsByFile = null;
// Setup collapsible panel toggle
if (ipCommHeader) {
ipCommHeader.addEventListener('click', (e) => {
// Don't toggle if clicking on the export button
if (e.target.id === 'exportIPList' || e.target.closest('#exportIPList')) return;
const isVisible = ipCommContent.style.display !== 'none';
ipCommContent.style.display = isVisible ? 'none' : 'block';
ipCommToggle.style.transform = isVisible ? 'rotate(0deg)' : 'rotate(180deg)';
});
}
// Setup IP list export button
if (exportIPListBtn) {
exportIPListBtn.addEventListener('click', (e) => {
e.stopPropagation(); // Prevent panel toggle
exportIPListToFile();
});
}
// Export IP list to file
function exportIPListToFile() {
if (!currentPairsByFile || currentPairsByFile.size === 0) {
alert('No IP communications data to export. Please load data first.');
return;
}
// Build text content grouped by file
let content = '';
const sortedFiles = Array.from(currentPairsByFile.keys()).sort();
sortedFiles.forEach(file => {
const pairs = Array.from(currentPairsByFile.get(file)).sort();
content += `${file}\n`;
pairs.forEach(pair => {
content += `${pair}\n`;
});
content += '\n';
});
// Create and download file
const blob = new Blob([content], { type: 'text/plain' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'ip_communications.txt';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
console.log('Exported IP communications to ip_communications.txt');
}
// User-selected labeling mode: 'timearcs' or 'force_layout'
let labelMode = 'force_layout';
// Force layout mode state
let layoutMode = 'force_layout'; // 'timearcs' | 'force_layout'
let forceLayout = null; // ForceNetworkLayout instance (null when in timearcs mode)
let forceLayoutLayer = null; // <g> for force layout rendering
let timearcsLayout = null; // TimearcsLayout instance
let layoutTransitionInProgress = false; // Guard against rapid switching
// Timestamp information (needed for export)
let currentTimeInfo = null; // Stores {unit, looksAbsolute, unitMs, base, activeLabelKey}
// (Brush selection, persistent selections, component expansion, and drag state
// are all owned by TimearcsLayout — access via timearcsLayout.getPersistentSelections() etc.)
// Dataset configuration: maps time ranges to data files
// This will be populated based on loaded data or can be configured manually
let datasetConfig = {
// Time is in the data's native unit (e.g., minutes since epoch)
// Will be auto-detected from loaded files or can be set manually
sets: [],
baseDataPath: './', // Base path for data files
ipMapPath: './full_ip_map.json', // Default IP map path
autoDetected: false,
// Path to multi-resolution data for tcp-analysis detail view
// This should point to a folder with manifest.json compatible with tcp-analysis
detailViewDataPath: 'packets_data/attack_packets_day1to5'
};
// Store loaded file info for smart detection
let loadedFileInfo = [];
labelModeRadios.forEach(r => r.addEventListener('change', () => {
const sel = Array.from(labelModeRadios).find(r => r.checked);
const newMode = sel ? sel.value : 'timearcs';
if (newMode === layoutMode || layoutTransitionInProgress) return;
const prev = layoutMode;
layoutMode = newMode;
labelMode = newMode; // preserve backward compat for colorForAttack
if (prev === 'timearcs' && newMode === 'force_layout') {
transitionToForceLayout();
} else if (prev === 'force_layout' && newMode === 'timearcs') {
transitionToTimearcs();
}
}));
// Handle bifocal compression slider
if (compressionSlider && compressionValue) {
compressionSlider.addEventListener('input', (e) => {
const ratio = parseFloat(e.target.value);
compressionValue.textContent = `${ratio}x`;
if (timearcsLayout) {
timearcsLayout.updateBifocalCompression(ratio);
}
});
}
// Handle keyboard shortcuts for bifocal navigation
document.addEventListener('keydown', (e) => {
// Arrow keys: navigate bifocal focus
if (e.key.startsWith('Arrow') && timearcsLayout) {
const step = e.shiftKey ? 0.1 : 0.02; // Shift for large steps
const state = timearcsLayout.getBifocalState();
const focusSpan = state.focusEnd - state.focusStart;
let newState = null;
if (e.key === 'ArrowLeft') {
e.preventDefault();
const newStart = Math.max(0, state.focusStart - step);
newState = updateFocusRegion(state, newStart, newStart + focusSpan);
} else if (e.key === 'ArrowRight') {
e.preventDefault();
const newEnd = Math.min(1, state.focusEnd + step);
newState = updateFocusRegion(state, newEnd - focusSpan, newEnd);
} else if (e.key === 'ArrowUp') {
e.preventDefault();
const expandStep = step / 2;
newState = updateFocusRegion(
state,
Math.max(0, state.focusStart - expandStep),
Math.min(1, state.focusEnd + expandStep)
);
} else if (e.key === 'ArrowDown') {
e.preventDefault();
const contractStep = step / 2;
const center = (state.focusStart + state.focusEnd) / 2;
const newSpan = Math.max(0.05, focusSpan - contractStep * 2);
newState = updateFocusRegion(state, center - newSpan / 2, center + newSpan / 2);
}
if (newState) {
timearcsLayout.setBifocalState(newState);
}
}
});
// Update brush status indicator
function updateBrushStatus(text, isActive = false) {
if (!brushStatusEl || !brushStatusText) return;
brushStatusText.textContent = text;
if (isActive) {
brushStatusEl.style.background = '#e7f5ff';
brushStatusEl.style.borderColor = '#74c0fc';
} else {
brushStatusEl.style.background = '#f8f9fa';
brushStatusEl.style.borderColor = '#dee2e6';
}
}
// Progress bar helper functions
function showProgress() {
if (loadingProgressEl) {
loadingProgressEl.style.display = 'block';
statusEl.style.display = 'none';
}
}
function hideProgress() {
if (loadingProgressEl) {
loadingProgressEl.style.display = 'none';
statusEl.style.display = 'block';
}
}
function updateProgress(text, percent) {
if (progressTextEl) {
progressTextEl.textContent = text;
}
if (progressBarEl) {
progressBarEl.style.width = `${Math.min(100, Math.max(0, percent))}%`;
}
}
// Handle clear brush button
if (clearBrushBtn) {
clearBrushBtn.addEventListener('click', () => {
console.log('Clearing brush selection');
if (layoutMode === 'force_layout') {
// In force layout mode, clear time filter (show all data)
if (forceLayout) forceLayout.updateTimeFilter(null);
} else if (timearcsLayout) {
timearcsLayout.clearBrushSelection();
}
});
}
let width = DEFAULT_WIDTH; // updated on render
let height = DEFAULT_HEIGHT; // updated on render
// (Bifocal state, cached layout, and render generation are now owned by TimearcsLayout)
// IP map state (id -> dotted string)
let ipIdToAddr = null; // Map<number, string>
let ipMapLoaded = false;
// Attack/event mapping: id -> name, and color mapping: name -> color
let attackIdToName = null; // Map<number, string>
let colorByAttack = null; // Map<string, string> by canonicalized name
let rawColorByAttack = null; // original keys
// Attack group mapping/color
let attackGroupIdToName = null; // Map<number,string>
let colorByAttackGroup = null; // canonical map
let rawColorByAttackGroup = null;
// Track visible attacks for legend filtering
let visibleAttacks = new Set(); // Set of attack names that are currently visible
let currentLabelMode = 'timearcs'; // Track current label mode for filtering
// Store original unfiltered data for legend filtering and resize re-render
let originalData = null;
// Flag to track if we're rendering filtered data (to prevent overwriting originalData)
let isRenderingFilteredData = false;
// Cleanup function for resize handler
let resizeCleanup = null;
// Render context is now retrieved via timearcsLayout.getContext() instead of _render* vars
// Initialize mappings, then try a default CSV load
(async function init() {
try {
const mappings = await loadAllMappings(canonicalizeName);
ipIdToAddr = mappings.ipIdToAddr;
ipMapLoaded = ipIdToAddr !== null && ipIdToAddr.size > 0;
attackIdToName = mappings.attackIdToName;
colorByAttack = mappings.colorByAttack;
rawColorByAttack = mappings.rawColorByAttack;
attackGroupIdToName = mappings.attackGroupIdToName;
colorByAttackGroup = mappings.colorByAttackGroup;
rawColorByAttackGroup = mappings.rawColorByAttackGroup;
if (ipMapLoaded) {
}
} catch (err) {
console.warn('Mapping load failed:', err);
}
// Setup window resize handler
resizeCleanup = setupWindowResizeHandler();
// After maps are ready (or failed gracefully), try default CSV
tryLoadDefaultCsv();
})();
// Window resize handler for responsive visualization
function setupWindowResizeHandler() {
const handleResizeLogic = () => {
try {
// Only proceed if we have data to re-render
if (!originalData || originalData.length === 0) {
return;
}
console.log('Handling window resize, updating visualization dimensions');
// Store old dimensions for comparison
const oldWidth = width;
const oldHeight = height;
const containerEl = document.getElementById('chart-container');
if (!containerEl) return;
// Calculate new dimensions
const containerRect = containerEl.getBoundingClientRect();
const availableWidth = containerRect.width || 1200;
const viewportWidth = Math.max(availableWidth, 800);
const newWidth = viewportWidth - MARGIN.left - MARGIN.right;
// Skip if dimensions haven't changed significantly
if (Math.abs(newWidth - oldWidth) < 10) {
return;
}
console.log(`Resize: ${oldWidth}x${oldHeight} -> ${newWidth}x${height}`);
// In force layout mode, update dimensions and re-render
if (layoutMode === 'force_layout' && forceLayout) {
width = newWidth; // Update module-level width for brush extent
forceLayout.width = newWidth + MARGIN.left + MARGIN.right;
forceLayout.height = height;
if (forceLayoutLayer) {
forceLayout.render(forceLayoutLayer);
}
// Redraw persistent selections at new node positions
if (timearcsLayout && timearcsLayout.getPersistentSelections().length > 0) {
timearcsLayout.redrawPersistentSelections();
}
return;
}
// Lightweight rescale — stretch timeline, no layout recompute
if (timearcsLayout) {
timearcsLayout.updateWidth();
width = timearcsLayout._width; // sync module-level width
}
console.log('Window resize handling complete');
} catch (e) {
console.warn('Error during window resize:', e);
}
};
// Use module's resize handler with our custom logic
return setupWindowResizeHandlerFromModule({
debounceMs: 200,
onResize: handleResizeLogic
});
}
// Stream-parse a CSV file incrementally to avoid loading entire file into memory
// Pushes transformed rows directly into combinedData, returns {totalRows, validRows}
async function processCsvFile(file, combinedData, options = { hasHeader: true, delimiter: ',', onProgress: null }) {
const fileName = file.name;
const result = await parseCSVStream(file, (obj, idx) => {
const attackName = _decodeAttack(obj.attack);
const attackGroupName = _decodeAttackGroup(obj.attack_group, obj.attack);
const rec = {
idx: combinedData.length,
timestamp: toNumber(obj.timestamp),
length: toNumber(obj.length),
src_ip: _decodeIp(obj.src_ip),
dst_ip: _decodeIp(obj.dst_ip),
protocol: (obj.protocol || '').toUpperCase() || 'OTHER',
count: toNumber(obj.count) || 1,
attack: attackName,
attack_group: attackGroupName,
sourceFile: fileName, // Track which file this record came from
};
const hasValidTimestamp = isFinite(rec.timestamp);
const hasValidSrcIp = rec.src_ip && rec.src_ip !== 'N/A' && !String(rec.src_ip).startsWith('IP_');
const hasValidDstIp = rec.dst_ip && rec.dst_ip !== 'N/A' && !String(rec.dst_ip).startsWith('IP_');
if (hasValidTimestamp && hasValidSrcIp && hasValidDstIp) {
combinedData.push(rec);
return true;
}
return false;
}, options);
return {
fileName: result.fileName,
totalRows: result.totalRows,
validRows: result.validRows
};
}
// Transform raw CSV rows to processed data
function transformRows(rows, startIdx = 0) {
return rows.map((d, i) => {
const attackName = _decodeAttack(d.attack);
const attackGroupName = _decodeAttackGroup(d.attack_group, d.attack);
const srcIp = _decodeIp(d.src_ip);
const dstIp = _decodeIp(d.dst_ip);
return {
idx: startIdx + i,
timestamp: toNumber(d.timestamp),
length: toNumber(d.length),
src_ip: srcIp,
dst_ip: dstIp,
protocol: (d.protocol || '').toUpperCase() || 'OTHER',
count: toNumber(d.count) || 1,
attack: attackName,
attack_group: attackGroupName,
};
}).filter(d => {
// Filter out records with invalid data
const hasValidTimestamp = isFinite(d.timestamp);
const hasValidSrcIp = d.src_ip && d.src_ip !== 'N/A' && !d.src_ip.startsWith('IP_');
const hasValidDstIp = d.dst_ip && d.dst_ip !== 'N/A' && !d.dst_ip.startsWith('IP_');
// Debug logging for filtered records
if (!hasValidSrcIp || !hasValidDstIp) {
console.log('Filtering out record:', {
src_ip: d.src_ip,
dst_ip: d.dst_ip,
hasValidSrcIp,
hasValidDstIp,
ipMapLoaded,
ipMapSize: ipIdToAddr ? ipIdToAddr.size : 0
});
}
return hasValidTimestamp && hasValidSrcIp && hasValidDstIp;
});
}
// Handle CSV upload - supports multiple files
fileInput?.addEventListener('change', async (e) => {
const files = Array.from(e.target.files || []);
if (files.length === 0) return;
// Show progress bar
showProgress();
try {
// === CLEANUP: Free memory from previous data BEFORE loading new data ===
// This prevents having both old and new data in memory simultaneously
if (originalData) {
originalData.length = 0; // Clear array contents
originalData = null;
}
// Clear selection and UI state
visibleAttacks.clear();
currentPairsByFile = null;
// Destroy timearcsLayout (clears selections, arcs, DOM references)
if (timearcsLayout) {
timearcsLayout.destroy();
timearcsLayout = null;
}
// Clear chart SVG to free DOM memory
svg.selectAll('*').remove();
d3.select('#axis-top').selectAll('*').remove();
console.log('Pre-load cleanup completed - old data freed before loading new files');
// === END CLEANUP ===
console.log('Processing CSV files with IP map status:', {
fileCount: files.length,
ipMapLoaded,
ipMapSize: ipIdToAddr ? ipIdToAddr.size : 0
});
// Warn if IP map is not loaded
if (!ipMapLoaded || !ipIdToAddr || ipIdToAddr.size === 0) {
console.warn('IP map not loaded or empty. Some IP IDs may not be mapped correctly.');
}
// Reset loaded file info
loadedFileInfo = [];
// Process files sequentially to bound memory; stream-parse to avoid full-file buffers
const combinedData = [];
const fileStats = [];
const errors = [];
for (let fileIdx = 0; fileIdx < files.length; fileIdx++) {
const file = files[fileIdx];
try {
const startIdx = combinedData.length;
// Update progress: show which file we're processing
const fileNum = fileIdx + 1;
const baseProgress = (fileIdx / files.length) * 100;
const fileProgressRange = 100 / files.length;
updateProgress(
files.length === 1
? `Loading ${file.name}...`
: `Loading file ${fileNum}/${files.length}: ${file.name}`,
baseProgress
);
// Process file with progress callback
const res = await processCsvFile(file, combinedData, {
hasHeader: true,
delimiter: ',',
onProgress: (bytesProcessed, totalBytes) => {
const filePercent = (bytesProcessed / totalBytes) * fileProgressRange;
const totalPercent = baseProgress + filePercent;
updateProgress(
files.length === 1
? `Loading ${file.name}... ${Math.round((bytesProcessed / totalBytes) * 100)}%`
: `Loading file ${fileNum}/${files.length}: ${file.name} (${Math.round((bytesProcessed / totalBytes) * 100)}%)`,
totalPercent
);
}
});
const filteredRows = res.totalRows - res.validRows;
// Track time range for this file (use efficient iteration to avoid stack overflow)
const fileData = combinedData.slice(startIdx);
let fileMinTime = null;
let fileMaxTime = null;
if (fileData.length > 0) {
fileMinTime = Infinity;
fileMaxTime = -Infinity;
for (let i = 0; i < fileData.length; i++) {
const ts = fileData[i].timestamp;
if (isFinite(ts)) {
if (ts < fileMinTime) fileMinTime = ts;
if (ts > fileMaxTime) fileMaxTime = ts;
}
}
if (fileMinTime === Infinity) fileMinTime = null;
if (fileMaxTime === -Infinity) fileMaxTime = null;
}
fileStats.push({ fileName: file.name, totalRows: res.totalRows, validRows: res.validRows, filteredRows });
// Store file info for smart detection
const decodedFileName = mapToDecodedFilename(file.name);
loadedFileInfo.push({
fileName: file.name, // Original timearcs filename
decodedFileName: decodedFileName, // Mapped to Python input filename
filePath: file.name, // Browser doesn't expose full path, user may need to adjust
minTime: fileMinTime,
maxTime: fileMaxTime,
recordCount: fileData.length,
// Try to detect set/day from filename
setNumber: detectSetNumber(file.name),
dayNumber: detectDayNumber(file.name)
});
} catch (err) {
errors.push({ fileName: file.name, error: err });
console.error(`Failed to load ${file.name}:`, err);
}
}
// Update dataset config with loaded file info
updateDatasetConfig();
// Disable rebuild cache for huge datasets to avoid memory spikes
lastRawCsvRows = null;
// Hide progress bar
hideProgress();
if (combinedData.length === 0) {
clearChart();
return;
}
// Build status message with summary
const successfulFiles = fileStats.length;
const totalValidRows = combinedData.length;
const totalFilteredRows = fileStats.reduce((sum, stat) => sum + stat.filteredRows, 0);
let statusMsg = '';
if (files.length === 1) {
// Single file: show simple message
if (totalFilteredRows > 0) {
statusMsg = `Loaded ${totalValidRows} valid rows (${totalFilteredRows} rows filtered due to missing IP mappings)`;
} else {
statusMsg = `Loaded ${totalValidRows} records`;
}
} else {
// Multiple files: show detailed summary
const fileSummary = fileStats.map(stat =>
`${stat.fileName} (${stat.validRows} valid${stat.filteredRows > 0 ? `, ${stat.filteredRows} filtered` : ''})`
).join('; ');
statusMsg = `Loaded ${successfulFiles} file(s): ${fileSummary}. Total: ${totalValidRows} records`;
if (errors.length > 0) {
statusMsg += `. ${errors.length} file(s) failed to load.`;
}
}
// Render new data (cleanup already done at the start of this handler)
render(combinedData);
} catch (err) {
console.error(err);
hideProgress();
clearChart();
}
});
// Keep last raw CSV rows so we can rebuild when mappings change
let lastRawCsvRows = null; // array of raw objects from csvParse
function rebuildDataFromRawRows(rows){
return rows.map((d, i) => {
const attackName = _decodeAttack(d.attack);
const attackGroupName = _decodeAttackGroup(d.attack_group, d.attack);
return {
idx: i,
timestamp: toNumber(d.timestamp),
length: toNumber(d.length),
src_ip: _decodeIp(d.src_ip),
dst_ip: _decodeIp(d.dst_ip),
protocol: (d.protocol || '').toUpperCase() || 'OTHER',
count: toNumber(d.count) || 1,
attack: attackName,
attack_group: attackGroupName,
};
}).filter(d => {
// Filter out records with invalid data
const hasValidTimestamp = isFinite(d.timestamp);
const hasValidSrcIp = d.src_ip && d.src_ip !== 'N/A' && !d.src_ip.startsWith('IP_');
const hasValidDstIp = d.dst_ip && d.dst_ip !== 'N/A' && !d.dst_ip.startsWith('IP_');
return hasValidTimestamp && hasValidSrcIp && hasValidDstIp;
});
}
async function tryLoadDefaultCsv() {
const defaultPath = './set1_first90_minutes.csv';
try {
const res = await fetch(defaultPath, { cache: 'no-store' });
if (!res.ok) return; // quietly exit if not found
const text = await res.text();
const rows = d3.csvParse((text || '').trim());
lastRawCsvRows = rows; // cache raw rows
const data = rows.map((d, i) => {
const attackName = _decodeAttack(d.attack);
const attackGroupName = _decodeAttackGroup(d.attack_group, d.attack);
return {
idx: i,
timestamp: toNumber(d.timestamp),
length: toNumber(d.length),
src_ip: _decodeIp(d.src_ip),
dst_ip: _decodeIp(d.dst_ip),
protocol: (d.protocol || '').toUpperCase() || 'OTHER',
count: toNumber(d.count) || 1,
attack: attackName,
attack_group: attackGroupName,
};
}).filter(d => {
// Filter out records with invalid data
const hasValidTimestamp = isFinite(d.timestamp);
const hasValidSrcIp = d.src_ip && d.src_ip !== 'N/A' && !d.src_ip.startsWith('IP_');
const hasValidDstIp = d.dst_ip && d.dst_ip !== 'N/A' && !d.dst_ip.startsWith('IP_');
return hasValidTimestamp && hasValidSrcIp && hasValidDstIp;
});
if (!data.length) {
return;
}
// Store file info for smart detection (use efficient iteration to avoid stack overflow)
let minTime = Infinity;
let maxTime = -Infinity;
for (let i = 0; i < data.length; i++) {
const ts = data[i].timestamp;
if (isFinite(ts)) {
if (ts < minTime) minTime = ts;
if (ts > maxTime) maxTime = ts;
}
}
if (minTime === Infinity) minTime = null;
if (maxTime === -Infinity) maxTime = null;
const defaultFileName = 'set1_first90_minutes.csv';
const decodedFileName = mapToDecodedFilename(defaultFileName);
loadedFileInfo = [{
fileName: defaultFileName, // Original timearcs filename
decodedFileName: decodedFileName, // Mapped to Python input filename
filePath: defaultPath,
minTime,
maxTime,
recordCount: data.length,
setNumber: detectSetNumber(defaultFileName),
dayNumber: detectDayNumber(defaultFileName)
}];
updateDatasetConfig();
// Report how many rows were filtered out
const totalRows = rows.length;
const filteredRows = totalRows - data.length;
render(data);
} catch (err) {
// ignore if file isn't present; keep waiting for upload
}
}
function clearChart() {
// Clear main chart SVG
svg.selectAll('*').remove();
// Clear axis SVG
const axisSvg = d3.select('#axis-top');
axisSvg.selectAll('*').remove();
// Clear legend
legendEl.innerHTML = '';
// Clear data array to free memory
if (originalData) {
originalData.length = 0;
originalData = null;
}
// Destroy timearcsLayout (clears selections, arcs, DOM references)
if (timearcsLayout) {
timearcsLayout.destroy();
timearcsLayout = null;
}
// Clear resize handler
if (resizeCleanup && typeof resizeCleanup === 'function') {
resizeCleanup();
resizeCleanup = null;
}
console.log('Chart cleared - all SVG elements and data structures released');
}
// Use d3 formatters consistently; we prefer UTC to match axis
// Update label mode without recomputing layout
function updateLabelMode() {
if (!timearcsLayout?._attacks || !timearcsLayout?._arcPaths) {
console.warn('Cannot update label mode - missing data or arcs');
return;
}
const activeLabelKey = labelMode === 'force_layout' ? 'attack_group' : 'attack';
console.log(`Switching to ${activeLabelKey} label mode (lightweight update)`);
// Helper to get color for current label mode
const colorForAttack = (name) => {
return _lookupAttackColor(name) || _lookupAttackGroupColor(name) || DEFAULT_COLOR;
};
// 1. Update arc data attributes (for filtering)
timearcsLayout._arcPaths.attr('data-attack', d => d[activeLabelKey] || 'normal');
// 2. Update gradient colors
svg.selectAll('linearGradient').each(function(d) {
const grad = d3.select(this);
grad.select('stop:first-child')
.attr('stop-color', colorForAttack(d[activeLabelKey] || 'normal'));
});
// 3. Rebuild legend with new attack list
const attacks = Array.from(new Set(timearcsLayout._attacks.map(l => l[activeLabelKey] || 'normal'))).sort();
// Reset visible attacks to show all attacks in new mode
visibleAttacks.clear();
attacks.forEach(a => visibleAttacks.add(a));
currentLabelMode = labelMode;
buildLegend(attacks, colorForAttack);
console.log(`Label mode updated: ${attacks.length} ${activeLabelKey} types`);
}
// Function to filter data based on visible attacks and re-render
// Also used by resize handler to re-render current view (filtered or unfiltered)
async function applyAttackFilter() {
// In force layout mode, delegate to the force layout instance
if (layoutMode === 'force_layout' && forceLayout) {
forceLayout.updateVisibleAttacks(visibleAttacks);
return;
}
if (!originalData || originalData.length === 0) return;
const activeLabelKey = labelMode === 'force_layout' ? 'attack_group' : 'attack';
// Get all possible attacks from original data
const allAttacks = new Set(originalData.map(d => d[activeLabelKey] || 'normal'));
// If all attacks are visible, render original data without filtering
if (visibleAttacks.size >= allAttacks.size) {
render(originalData);
return;
}
// Filter data to only include visible attacks
const filteredData = originalData.filter(d => {
const attackName = (d[activeLabelKey] || 'normal');
return visibleAttacks.has(attackName);
});
console.log(`Filtered data: ${filteredData.length} of ${originalData.length} records (${visibleAttacks.size} visible attacks)`);
// Set flag to prevent overwriting originalData during filtered render
isRenderingFilteredData = true;
// Re-render with filtered data (reuses cached layout, skips simulation)
await render(filteredData);
// Reset flag after render completes
isRenderingFilteredData = false;
}
// ═══════════════════════════════════════════════════════════
// Force-directed network layout transitions
// ═══════════════════════════════════════════════════════════
async function transitionToForceLayout() {
const ctx = timearcsLayout ? timearcsLayout.getContext() : {};
if (!ctx.linksWithNodes || ctx.linksWithNodes.length === 0) {
console.warn('No data available for force layout');
layoutMode = 'timearcs';
labelMode = 'timearcs';
document.getElementById('labelModeTimearcs').checked = true;
return;
}
layoutTransitionInProgress = true;
const activeLabelKey = 'attack_group';
// Use same color priority as timearcs for consistency
const colorForAttack = (name) => {
return _lookupAttackColor(name) || _lookupAttackGroupColor(name) || DEFAULT_COLOR;
};
// Build initial positions (center X, timearcs Y) for force simulation seed
const drawWidth = width - MARGIN.left - MARGIN.right;
const centerX = MARGIN.left + drawWidth / 2;
const initialPositions = new Map();
for (const ip of ctx.allIps) {
const yPos = ctx.yScaleLens ? ctx.yScaleLens(ip) : MARGIN.top + 50;
initialPositions.set(ip, { x: centerX, y: yPos });
}
// Create force layout and pre-calculate final positions (run simulation to completion)
forceLayout = new ForceNetworkLayout({
d3, svg, width, height, margin: MARGIN,
colorForAttack, tooltip, showTooltip, hideTooltip
});
forceLayout.setData(
ctx.linksWithNodes, ctx.allIps,
ctx.ipToComponent, ctx.components, activeLabelKey
);
forceLayout.aggregateForTimeRange(null);
// rawPositions: pass to render() so autoFit reproduces the same visual layout
// visualPositions: where nodes will appear on screen (arc merge targets)
const { rawPositions, visualPositions } = forceLayout.precalculate(initialPositions);
// --- Phase 1: Animate arcs to precalculated force node positions ---
svg.selectAll('path.arc').style('pointer-events', 'none');
function mergeArcTween(d, targetSrcPos, targetTgtPos) {
const sx0 = d.source.x, sy0 = d.source.y;
const tx0 = d.target.x, ty0 = d.target.y;
return function(t) {
const sx = sx0 + (targetSrcPos.x - sx0) * t;
const sy = sy0 + (targetSrcPos.y - sy0) * t;
const tx = tx0 + (targetTgtPos.x - tx0) * t;
const ty = ty0 + (targetTgtPos.y - ty0) * t;
const dx = tx - sx, dy = ty - sy;
const dr = Math.sqrt(dx * dx + dy * dy) / 2 * (1 - t);
if (dr < 1) return `M${sx},${sy} L${tx},${ty}`;
return sy < ty
? `M${sx},${sy} A${dr},${dr} 0 0,1 ${tx},${ty}`
: `M${tx},${ty} A${dr},${dr} 0 0,1 ${sx},${sy}`;
};
}
const arcMergeTransition = svg.selectAll('path.arc')
.transition().duration(800)
.attrTween('d', function(d) {
const srcIp = d.sourceNode.name;
const tgtIp = d.targetNode.name;
const srcPos = visualPositions.get(srcIp) || { x: centerX, y: MARGIN.top + 50 };
const tgtPos = visualPositions.get(tgtIp) || { x: centerX, y: MARGIN.top + 100 };
return mergeArcTween(d, srcPos, tgtPos);
})
.style('opacity', 0.3);