-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
2216 lines (1980 loc) · 78.5 KB
/
main.cpp
File metadata and controls
2216 lines (1980 loc) · 78.5 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
#define NOMINMAX
#include <imgui.h>
#include <imgui_impl_glfw.h>
#include <imgui_impl_opengl3.h>
#include <GLFW/glfw3.h>
#ifndef IMPLOT_H
#define IMPLOT_H
#include <implot.h>
#endif
#include <iostream>
#include <vector>
#include <string>
#include <thread>
#include <mutex>
#include <queue>
#include <Python.h>
#include <cstdlib>
#include <WinSock2.h>
#include <WS2tcpip.h>
#include <limits>
#ifndef IMPLOT_INTERNAL_H
#define IMPLOT_INTERNAL_H
#include <implot_internal.h>
#endif
#include <nlohmann/json.hpp>
#include <unordered_map>
#include <algorithm>
#include <unordered_set>
#include <thread>
#include <sqlite3.h>
#include <filesystem>
#include <Windows.h>
#include <commdlg.h>
#include <ctime>
#include <iomanip>
#include <sstream>
#pragma comment(lib, "Ws2_32.lib")
using json = nlohmann::json;
#include <random>
std::vector<std::thread> pythonScriptThreads;
std::atomic<bool> applicationClosing(false);
static float globalScrollX = 0.0f;
static bool isScrolling = false;
static bool scrollFromPlot = false; // To track which plot triggered the scroll
enum class DataSource
{
SIMULATION,
WIRESHARK
};
DataSource currentDataSource = DataSource::SIMULATION;
bool wiresharkRunning = false;
std::thread wiresharkThread;
enum class AttackType
{
NONE,
DDOS,
SYN_FLOOD,
MITM_SCADA
};
struct AttackInfo
{
bool none;
bool ddos;
bool synflood;
bool mitm;
};
enum class TrafficType
{
NORMAL,
DDOS,
SYN_FLOOD,
MITM_SCADA
};
TrafficType currentTrafficType = TrafficType::NORMAL;
const char *attackLabels[] = {"None", "DDoS", "SYN Flood", "MITM"};
struct PlotData
{
// std::map<std::pair<int, int>, std::vector<float>> time;
std::map<std::pair<int, int>, std::vector<float>> values;
};
struct ModelInfo
{
std::string name;
std::string path;
bool selected;
SOCKET socket;
int port;
ImVec4 color;
std::vector<PlotData> plotData;
std::map<AttackType, float> attackAccuracy;
ModelInfo() : plotData(1) {} // Initialize with one PlotData for predictions
};
std::vector<std::string> metricLabels = {
"Packets Dropped",
"Average Queue Size",
"System Occupancy",
"Service Rate",
"Transmission Delay",
"Round Trip Time (RTT)",
"Arrival Rate",
"Attack Type",
"Packet Size",
"IAT",
"Acknowledgement Size",
"Packet Count (PC)"};
// Update the plotDataArray size initialization
std::vector<PlotData> plotDataArray(metricLabels.size());
std::vector<std::mutex> plotDataMutexes(metricLabels.size());
std::vector<bool> plotVisibility(metricLabels.size(), true);
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> portDist(12348, 65535);
std::vector<ModelInfo> availableModels;
std::mutex modelsMutex;
struct pair_hash
{
template <class T1, class T2>
std::size_t operator()(const std::pair<T1, T2> &p) const
{
auto h1 = std::hash<T1>{}(p.first);
auto h2 = std::hash<T2>{}(p.second);
return h1 ^ h2;
}
};
std::unordered_map<std::pair<int, int>, int, pair_hash> fbTbCombinations;
const int MAX_COMBINATIONS = 10;
const int MAX_LINES = 10;
std::queue<std::vector<float>> dataQueue;
std::vector<json> modelStats;
std::mutex queueMutex;
bool simulationRunning = false;
bool simulationEnded = false;
bool includeDOS = true; // Global variable to control DOS inclusion
int totalSimulationTime = 20; // Default total simulation time in seconds
int dosAttackTime = 10; // Default DOS attack time in seconds
std::atomic<bool> stopSimulationRequested(false);
std::atomic<bool> receiverRunning(true);
SOCKET predictionSocket = INVALID_SOCKET;
std::atomic<bool> shouldExit(false);
SOCKET listenSocket = INVALID_SOCKET;
ImVec4 colors[] = {
ImVec4(1.0f, 0.0f, 0.0f, 1.0f), // Red
ImVec4(0.0f, 1.0f, 0.0f, 1.0f), // Green
ImVec4(0.0f, 0.0f, 1.0f, 1.0f), // Blue
ImVec4(1.0f, 1.0f, 0.0f, 1.0f), // Yellow
ImVec4(1.0f, 0.0f, 1.0f, 1.0f), // Magenta
ImVec4(0.0f, 1.0f, 1.0f, 1.0f), // Cyan
ImVec4(1.0f, 0.5f, 0.0f, 1.0f), // Orange
ImVec4(0.5f, 0.0f, 0.5f, 1.0f), // Purple
ImVec4(0.0f, 0.5f, 0.5f, 1.0f), // Teal
ImVec4(0.5f, 0.5f, 0.5f, 1.0f) // Gray
};
const ImVec4 ATTACK_COLORS[] = {
ImVec4(0.5f, 0.5f, 0.5f, 1.0f), // Normal traffic (Grey)
ImVec4(1.0f, 0.0f, 0.0f, 1.0f), // DDoS (Red)
ImVec4(0.0f, 0.0f, 1.0f, 1.0f), // SYN Flood (Blue)
ImVec4(1.0f, 0.6f, 0.0f, 1.0f) // MITM (Orange)
};
// Function to initialize Python
void updateSimulationParameters()
{
ImGui::InputInt("Total Simulation Time (s)", &totalSimulationTime);
static int selectedAttackType = 0;
const char *attackTypes[] = {"None", "DDoS", "SYN Flood", "MITM SCADA"};
ImGui::Combo("Attack Type", &selectedAttackType, attackTypes, IM_ARRAYSIZE(attackTypes));
if (selectedAttackType > 0)
{
ImGui::InputInt("Attack Duration (s)", &dosAttackTime);
if (dosAttackTime > totalSimulationTime)
{
dosAttackTime = totalSimulationTime;
}
}
}
void processPredictionResponse(ModelInfo &model, const json &response, const std::pair<int, int> &connection)
{
float prediction = response["prediction"].get<float>();
std::string attackType = response["attack_type"].get<std::string>();
// std::cout << prediction << std::endl;
// std::cout << attackType << std::endl;
// Update plot data
model.plotData[0].values[connection].push_back(prediction);
// Limit the size of the plot data
if (model.plotData[0].values[connection].size() > 1000)
{
model.plotData[0].values[connection].erase(
model.plotData[0].values[connection].begin());
}
}
std::string openFileDialog(const char *filter = "Python Files\0*.py\0All Files\0*.*\0")
{
OPENFILENAMEA ofn;
char szFile[260] = {0};
ZeroMemory(&ofn, sizeof(ofn));
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = NULL;
ofn.lpstrFile = szFile;
ofn.nMaxFile = sizeof(szFile);
ofn.lpstrFilter = filter;
ofn.nFilterIndex = 1;
ofn.lpstrFileTitle = NULL;
ofn.nMaxFileTitle = 0;
ofn.lpstrInitialDir = NULL;
ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
if (GetOpenFileNameA(&ofn) == TRUE)
{
return ofn.lpstrFile;
}
return "";
}
bool fileExists(const std::string &path)
{
return std::filesystem::exists(path);
}
void initAvailableModels()
{
std::vector<std::string> modelNames = {
"isolation_forest_model.pkl",
"decision_tree_model.pkl",
"kmeans_model.pkl",
"random_forest_model.pkl"};
for (size_t i = 0; i < modelNames.size(); ++i)
{
ModelInfo model;
model.name = modelNames[i];
model.selected = false;
model.socket = INVALID_SOCKET;
model.port = portDist(gen);
model.color = colors[i % MAX_LINES];
availableModels.push_back(model);
}
}
void loadModel()
{
std::string customModelPath = openFileDialog("Pickle Files\0*.pkl\0All Files\0*.*\0");
if (!customModelPath.empty())
{
ModelInfo customModel;
customModel.name = "Custom: " + std::filesystem::path(customModelPath).filename().string();
customModel.selected = false;
customModel.socket = INVALID_SOCKET;
customModel.port = portDist(gen);
customModel.color = colors[availableModels.size() % MAX_LINES];
customModel.path = std::filesystem::absolute(customModelPath).string(); // Store the full absolute path
std::lock_guard<std::mutex> lock(modelsMutex);
availableModels.push_back(customModel);
}
}
std::string getCurrentTimestamp()
{
auto now = std::chrono::system_clock::now();
auto in_time_t = std::chrono::system_clock::to_time_t(now);
std::stringstream ss;
ss << std::put_time(std::localtime(&in_time_t), "%Y%m%d_%H%M%S");
return ss.str();
}
void trainModel(const std::string &csvPath)
{
std::string scriptPath = openFileDialog("Python Files\0*.py\0All Files\0*.*\0");
if (scriptPath.empty())
{
std::cout << "No script selected." << std::endl;
return;
}
std::string timestamp = getCurrentTimestamp();
std::string command = "python \"" + scriptPath + "\" \"" + csvPath + "\" \"" + timestamp + "\"";
std::cout << "Executing command: " << command << std::endl;
int result = std::system(command.c_str());
if (result == 0)
{
std::cout << "Successfully trained model using " << scriptPath << std::endl;
}
else
{
std::cerr << "Error training model using " << scriptPath << std::endl;
}
}
void initPython()
{
std::cout << "Initializing Python..." << std::endl;
// Append to PYTHONPATH instead of overwriting
const char *current_pythonpath = std::getenv("PYTHONPATH");
std::string new_pythonpath = current_pythonpath ? std::string(current_pythonpath) + ";" : "";
new_pythonpath += "C:/Users/papis/AppData/Local/Packages/PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0/LocalCache/local-packages/Python311/site-packages;.";
#ifdef _WIN32
_putenv_s("PYTHONPATH", new_pythonpath.c_str());
#else
setenv("PYTHONPATH", new_pythonpath.c_str(), 1);
#endif
Py_Initialize();
if (!Py_IsInitialized())
{
std::cerr << "Failed to initialize Python" << std::endl;
return;
}
// Print Python information
PyRun_SimpleString(
"import sys\n"
"import os\n"
"print('Python version:', sys.version)\n"
"print('Python executable:', sys.executable)\n"
"print('Python prefix:', sys.prefix)\n"
"print('Python path:', sys.path)\n"
"print('Current working directory:', os.getcwd())\n"
"print('Files in current directory:', os.listdir('.'))\n");
}
bool initModelSockets()
{
const int MAX_RETRIES = 5;
const int RETRY_DELAY_MS = 1000;
for (auto &model : availableModels)
{
if (model.selected)
{
for (int retry = 0; retry < MAX_RETRIES; ++retry)
{
model.socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (model.socket == INVALID_SOCKET)
{
std::cerr << "Error creating socket for " << model.name << ": " << WSAGetLastError() << std::endl;
return false;
}
sockaddr_in serverAddr;
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(model.port);
inet_pton(AF_INET, "127.0.0.1", &serverAddr.sin_addr);
if (connect(model.socket, (SOCKADDR *)&serverAddr, sizeof(serverAddr)) == SOCKET_ERROR)
{
int error = WSAGetLastError();
if (error == WSAEADDRINUSE)
{
std::cerr << "Address already in use for " << model.name << ". Retrying..." << std::endl;
closesocket(model.socket);
model.socket = INVALID_SOCKET;
std::this_thread::sleep_for(std::chrono::milliseconds(RETRY_DELAY_MS));
continue;
}
else
{
std::cerr << "Connect failed for " << model.name << " with error: " << error << std::endl;
closesocket(model.socket);
model.socket = INVALID_SOCKET;
return false;
}
}
else
{
std::cout << "Successfully connected to " << model.name << " on port " << model.port << std::endl;
break;
}
}
if (model.socket == INVALID_SOCKET)
{
std::cerr << "Failed to connect to " << model.name << " after " << MAX_RETRIES << " attempts" << std::endl;
return false;
}
}
}
return true;
}
void closeModelSockets()
{
for (auto &model : availableModels)
{
if (model.socket != INVALID_SOCKET)
{
closesocket(model.socket);
model.socket = INVALID_SOCKET;
}
}
}
void terminatePythonProcesses()
{
// Send termination command to all model sockets
for (auto &model : availableModels)
{
if (model.socket != INVALID_SOCKET)
{
try
{
json terminateCmd;
terminateCmd["command"] = "terminate";
std::string jsonStr = terminateCmd.dump() + "\n"; // Add newline for message completion
send(model.socket, jsonStr.c_str(), jsonStr.length(), 0);
// Wait briefly for the command to be sent
std::this_thread::sleep_for(std::chrono::milliseconds(100));
// Shutdown and close socket
shutdown(model.socket, SD_BOTH);
closesocket(model.socket);
model.socket = INVALID_SOCKET;
}
catch (...)
{
// Ignore cleanup errors
}
}
}
// On Windows, forcefully terminate Python processes if they're still running
#ifdef _WIN32
std::system("taskkill /F /IM python.exe /T > nul 2>&1");
#endif
}
void stopSimulation()
{
simulationEnded = true;
simulationRunning = false;
modelStats.clear();
for (const auto &model : availableModels)
{
if (model.selected && model.socket != INVALID_SOCKET)
{
json request;
request["command"] = "get_stats";
std::string jsonStr = request.dump() + "\n";
send(model.socket, jsonStr.c_str(), jsonStr.length(), 0);
char recvbuf[1024];
int iResult = recv(model.socket, recvbuf, 1024, 0);
if (iResult > 0)
{
std::string response(recvbuf, iResult);
json stats = json::parse(response);
stats["model_name"] = model.name;
modelStats.push_back(stats);
}
}
}
terminatePythonProcesses();
}
void runSimulation()
{
std::cout << "Running simulation..." << std::endl;
PyObject *pName, *pModule, *pFunc, *pArgs, *pQueue, *pValue;
// Print current working directory and Python path
PyRun_SimpleString(
"import os\n"
"import sys\n"
"import queue\n"
"print('Current working directory:', os.getcwd())\n"
"print('Files in current directory:', os.listdir('.'))\n"
"print('Python path:', sys.path)\n");
pName = PyUnicode_FromString("simulation_script");
std::cout << "A... (Created module name object)" << std::endl;
pModule = PyImport_ImportModule("simulation_script");
if (pModule == NULL)
{
PyErr_Print();
std::cerr << "Failed to load the Python module." << std::endl;
// Additional debugging information
PyRun_SimpleString(
"import sys\n"
"import importlib.util\n"
"import traceback\n"
"script_path = 'simulation_script.py'\n"
"print('Attempting to load:', script_path)\n"
"if os.path.exists(script_path):\n"
" print('File exists')\n"
" with open(script_path, 'r') as f:\n"
" print('File contents:')\n"
" print(f.read())\n"
" try:\n"
" spec = importlib.util.spec_from_file_location('simulation_script', script_path)\n"
" module = importlib.util.module_from_spec(spec)\n"
" spec.loader.exec_module(module)\n"
" print('Module loaded successfully')\n"
" except Exception as e:\n"
" print('Error loading module:', str(e))\n"
" print('Traceback:')\n"
" traceback.print_exc()\n"
"else:\n"
" print('File does not exist')\n"
"print('Updated Python path:', sys.path)\n");
return;
}
std::cout << "B... (Imported module)" << std::endl;
pFunc = PyObject_GetAttrString(pModule, "run_simulation");
if (pFunc && PyCallable_Check(pFunc))
{
std::cout << "C... (Found run_simulation function)" << std::endl;
// Create a Python queue
PyObject *queueModule = PyImport_ImportModule("queue");
PyObject *queueClass = PyObject_GetAttrString(queueModule, "Queue");
pQueue = PyObject_CallObject(queueClass, NULL);
std::cout << "Created Python queue" << std::endl;
// Create arguments tuple for the function call
pArgs = PyTuple_New(3);
PyTuple_SetItem(pArgs, 0, pQueue);
PyTuple_SetItem(pArgs, 1, PyBool_FromLong(includeDOS));
PyTuple_SetItem(pArgs, 2, PyLong_FromLong(12345)); // Pass the port number as the third argument
// Call the Python function
std::cout << "Calling run_simulation function..." << std::endl;
pValue = PyObject_CallObject(pFunc, pArgs);
Py_DECREF(pArgs);
if (pValue == NULL)
{
PyErr_Print();
std::cerr << "Call to run_simulation failed" << std::endl;
}
else
{
std::cout << "D... (Called run_simulation function successfully)" << std::endl;
Py_DECREF(pValue);
}
}
else
{
if (PyErr_Occurred())
PyErr_Print();
std::cerr << "Cannot find function 'run_simulation'" << std::endl;
}
if (PyErr_Occurred())
{
PyErr_Print();
std::cerr << "Python error occurred during simulation" << std::endl;
}
Py_XDECREF(pFunc);
Py_DECREF(pModule);
std::cout << "Z... (Finished runSimulation)" << std::endl;
}
std::queue<std::vector<float>> predictionQueue;
std::mutex predictionQueueMutex;
std::atomic<bool> predictionReceiverRunning(true);
void sendDataToPredictionScript(const std::vector<float> &data)
{
try
{
json j;
j["FB"] = data[0];
j["TB"] = data[1];
j["IAT"] = data[2];
j["TD"] = data[3];
j["Arrival Time"] = data[4];
j["PC"] = data[5];
j["Packet Size"] = data[6];
j["Acknowledgement Packet Size"] = data[7];
j["RTT"] = data[8];
j["Average Queue Size"] = data[9];
j["System Occupancy"] = data[10];
j["Arrival Rate"] = data[11];
j["Service Rate"] = data[12];
j["Packet Dropped"] = data[13];
j["Is Attack"] = data[16];
std::string jsonStr = j.dump();
SOCKET sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sock == INVALID_SOCKET)
{
std::cerr << "Error creating socket for sending to prediction script: " << WSAGetLastError() << std::endl;
return;
}
sockaddr_in serverAddr;
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(12347); // different port for sending to prediction script
inet_pton(AF_INET, "127.0.0.1", &serverAddr.sin_addr);
if (connect(sock, (SOCKADDR *)&serverAddr, sizeof(serverAddr)) == SOCKET_ERROR)
{
std::cerr << "Connect failed with error: " << WSAGetLastError() << std::endl;
closesocket(sock);
return;
}
if (send(sock, jsonStr.c_str(), jsonStr.length(), 0) == SOCKET_ERROR)
{
std::cerr << "Send failed with error: " << WSAGetLastError() << std::endl;
}
closesocket(sock);
}
catch (const std::exception &e)
{
std::cerr << "Error sending data to prediction script: " << e.what() << std::endl;
}
}
bool initPredictionSocket()
{
const int MAX_RETRIES = 10;
const int RETRY_DELAY_MS = 500;
for (auto &model : availableModels)
{
if (model.selected)
{
bool connected = false;
for (int retry = 0; retry < MAX_RETRIES && !connected; ++retry)
{
if (retry > 0)
{
std::cout << "Retry " << retry << " for " << model.name << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(RETRY_DELAY_MS));
}
model.socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (model.socket == INVALID_SOCKET)
{
std::cerr << "Error creating prediction socket for " << model.name
<< ": " << WSAGetLastError() << std::endl;
continue;
}
sockaddr_in serverAddr;
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(model.port);
inet_pton(AF_INET, "127.0.0.1", &serverAddr.sin_addr);
if (connect(model.socket, (SOCKADDR *)&serverAddr, sizeof(serverAddr)) == SOCKET_ERROR)
{
std::cerr << "Connect attempt " << retry + 1 << " failed for " << model.name
<< " with error: " << WSAGetLastError() << std::endl;
closesocket(model.socket);
model.socket = INVALID_SOCKET;
continue;
}
std::cout << "Successfully connected to " << model.name
<< " on port " << model.port << std::endl;
connected = true;
}
if (!connected)
{
std::cerr << "Failed to connect to " << model.name
<< " after " << MAX_RETRIES << " attempts" << std::endl;
return false;
}
}
}
return true;
}
float getPredictionFromPython(const std::vector<float> &data, const std::string &modelName)
{
auto it = std::find_if(availableModels.begin(), availableModels.end(),
[&modelName](const ModelInfo &model)
{ return model.name == modelName; });
if (it == availableModels.end() || it->socket == INVALID_SOCKET)
{
std::cerr << "Invalid socket for " << modelName << std::endl;
return 0.0f;
}
json j;
j["model"] = modelName;
j["IAT"] = data[2];
j["TD"] = data[3];
j["Arrival Time"] = data[4];
j["PC"] = data[5];
j["Packet Size"] = data[6];
j["Acknowledgement Packet Size"] = data[7];
j["RTT"] = data[8];
j["Average Queue Size"] = data[9];
j["System Occupancy"] = data[10];
j["Arrival Rate"] = data[11];
j["Service Rate"] = data[12];
j["Packet Dropped"] = data[13];
j["Is Attack"] = data[16];
std::string jsonStr = j.dump();
if (send(it->socket, jsonStr.c_str(), jsonStr.length(), 0) == SOCKET_ERROR)
{
std::cerr << "Send failed for " << modelName << " with error: " << WSAGetLastError() << std::endl;
return 0.0f;
}
char recvbuf[1024];
int iResult = recv(it->socket, recvbuf, 1024, 0);
if (iResult > 0)
{
std::string response(recvbuf, iResult);
json responseJson = json::parse(response);
return responseJson["prediction"].get<float>();
}
else if (iResult == 0)
{
std::cout << "Connection closed for " << modelName << std::endl;
}
else
{
std::cerr << "Recv failed for " << modelName << " with error: " << WSAGetLastError() << std::endl;
}
return 0.0f;
}
void processData()
{
std::lock_guard<std::mutex> lock(queueMutex);
while (!dataQueue.empty())
{
std::vector<float> data = dataQueue.front();
dataQueue.pop();
if (data.size() >= 20)
{
int fb = static_cast<int>(data[0]);
int tb = static_cast<int>(data[1]);
std::pair<int, int> connection(fb, tb);
if (fbTbCombinations.find(connection) == fbTbCombinations.end())
{
fbTbCombinations[connection] = fbTbCombinations.size();
}
// Create AttackInfo structure
AttackInfo attackInfo;
attackInfo.none = data[16] > 0.5f;
attackInfo.ddos = data[17] > 0.5f;
attackInfo.synflood = data[18] > 0.5f;
attackInfo.mitm = data[19] > 0.5f;
std::cout << "Received data point with " << data.size() << " elements" << std::endl;
std::cout << "CPP DATA ENQUEUE [ ";
for (const auto &value : data)
{
std::cout << value << " ";
}
std::cout << "]" << std::endl;
// Process all metrics
for (int i = 0; i < metricLabels.size(); ++i)
{
std::lock_guard<std::mutex> lock(plotDataMutexes[i]);
float value = 0.0f;
switch (i)
{
case 0: // Packets Dropped
value = data[13];
break;
case 1: // Average Queue Size
value = data[9];
break;
case 2: // System Occupancy
value = data[10];
break;
case 3: // Service Rate
value = data[12];
break;
case 4: // Transmission Delay
value = data[3];
break;
case 5: // Round Trip Time (RTT)
value = data[8];
break;
case 6: // Arrival Rate
value = data[11];
break;
case 7: // Attack Type Distribution
if (attackInfo.ddos)
value = 1.0f;
else if (attackInfo.synflood)
value = 2.0f;
else if (attackInfo.mitm)
value = 3.0f;
else
value = 0.0f;
break;
case 8: // Packet Size
value = data[6];
break;
case 9: // IAT
value = data[2];
break;
case 10: // Acknowledgement Size
value = data[7];
break;
case 11: // Packet Count (PC)
value = data[5];
break;
default:
value = 0.0f;
}
plotDataArray[i].values[connection].push_back(value);
// Limit data points for each metric
if (plotDataArray[i].values[connection].size() > 1000)
{
plotDataArray[i].values[connection].erase(
plotDataArray[i].values[connection].begin());
}
}
// Process model predictions
for (auto &model : availableModels)
{
if (model.selected)
{
// Create prediction request
json predictionRequest;
predictionRequest["IAT"] = data[2];
predictionRequest["TD"] = data[3];
predictionRequest["Arrival Time"] = data[4];
predictionRequest["PC"] = data[5];
predictionRequest["Packet Size"] = data[6];
predictionRequest["Acknowledgement Packet Size"] = data[7];
predictionRequest["RTT"] = data[8];
predictionRequest["Average Queue Size"] = data[9];
predictionRequest["System Occupancy"] = data[10];
predictionRequest["Arrival Rate"] = data[11];
predictionRequest["Service Rate"] = data[12];
predictionRequest["Packet Dropped"] = data[13];
predictionRequest["attack_none"] = attackInfo.none;
predictionRequest["attack_ddos"] = attackInfo.ddos;
predictionRequest["attack_synflood"] = attackInfo.synflood;
predictionRequest["attack_mitm"] = attackInfo.mitm;
std::string jsonStr = predictionRequest.dump();
if (send(model.socket, jsonStr.c_str(), jsonStr.length(), 0) != SOCKET_ERROR)
{
char recvbuf[1024];
int iResult = recv(model.socket, recvbuf, 1024, 0);
if (iResult > 0)
{
std::string response(recvbuf, iResult);
json responseJson = json::parse(response);
float prediction = responseJson["prediction"].get<float>();
model.plotData[0].values[connection].push_back(prediction);
}
}
}
}
}
}
}
void simulationThread()
{
try
{
PyObject *pName, *pModule, *pFunc, *pArgs, *pValue;
pName = PyUnicode_FromString("simulation_script");
pModule = PyImport_ImportModule("simulation_script");
if (pModule == NULL)
{
PyErr_Print();
std::cerr << "Failed to load the Python module." << std::endl;
simulationEnded = true;
return;
}
pFunc = PyObject_GetAttrString(pModule, "run_simulation");
if (pFunc && PyCallable_Check(pFunc))
{
pArgs = PyTuple_New(5);
// Convert traffic type to corresponding AttackType value
PyObject *attackType;
switch (currentTrafficType)
{
case TrafficType::NORMAL:
attackType = PyLong_FromLong(0);
break;
case TrafficType::DDOS:
attackType = PyLong_FromLong(1);
break;
case TrafficType::SYN_FLOOD:
attackType = PyLong_FromLong(2); // AttackType.SYN_FLOOD
break;
case TrafficType::MITM_SCADA:
attackType = PyLong_FromLong(3);
break;
default:
attackType = PyLong_FromLong(0);
}
PyTuple_SetItem(pArgs, 0, PyLong_FromLong(12345)); // port
PyTuple_SetItem(pArgs, 1, attackType);
PyTuple_SetItem(pArgs, 2, PyLong_FromLong(totalSimulationTime));
PyTuple_SetItem(pArgs, 3, PyLong_FromLong(dosAttackTime));
PyTuple_SetItem(pArgs, 4, PyBool_FromLong(true)); // start_simulation flag
pValue = PyObject_CallObject(pFunc, pArgs);
Py_DECREF(pArgs);
if (pValue == NULL)
{
PyErr_Print();
std::cerr << "Call to run_simulation failed" << std::endl;
}
else
{
Py_DECREF(pValue);
}
}
Py_XDECREF(pFunc);
Py_DECREF(pModule);
while (!dataQueue.empty())
{
processData();
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
catch (const std::exception &e)
{
std::cerr << "Exception in simulation thread: " << e.what() << std::endl;
}
simulationRunning = false;
simulationEnded = true;
stopSimulation();
}
void handleGlobalScroll(float newScrollX, bool fromPlot)
{
if (!isScrolling)
{
isScrolling = true;
globalScrollX = newScrollX;
scrollFromPlot = fromPlot;
// Update all metric plots
for (size_t i = 0; i < metricLabels.size(); ++i)
{
if (plotVisibility[i])
{
ImGuiWindow *window = ImGui::FindWindowByName(("ScrollingRegion##" + std::to_string(i)).c_str());
if (window)
{
window->Scroll.x = globalScrollX;
}
}
}
// Update all model plots
for (const auto &model : availableModels)
{
if (model.selected)
{
ImGuiWindow *window = ImGui::FindWindowByName(("ScrollingRegion##" + model.name).c_str());
if (window)
{
window->Scroll.x = globalScrollX;
}
}
}
isScrolling = false;
scrollFromPlot = false;
}
}
void renderPlots()
{
ImPlotFlags flags = ImPlotFlags_NoMouseText;
ImPlotAxisFlags axes_flags = ImPlotAxisFlags_NoTickLabels;
const int VISIBLE_POINTS = 100;
static std::vector<bool> showLegends(metricLabels.size(), false);
for (size_t i = 0; i < metricLabels.size(); ++i)
{
if (plotVisibility[i])
{
ImGui::BeginChild(metricLabels[i].c_str(), ImVec2(0, 250), true);
ImGui::Text("%s", metricLabels[i].c_str());
ImGui::SameLine(ImGui::GetWindowWidth() - 70);
std::string buttonLabel = (showLegends[i] ? "Hide" : "Show");
buttonLabel += " Legend##";
buttonLabel += std::to_string(i);
if (ImGui::Button(buttonLabel.c_str()))
{
showLegends[i] = !showLegends[i];