1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
use super::interface;
use super::{
    host::{HostDisplayInfo, RemoteHostInfo},
    packet::PacketFrame,
    service::ServiceDisplayInfo,
    traffic::{Direction, TrafficDisplayInfo, TrafficInfo},
};
use crate::db::service::ServiceDatabase;
use crate::db::ip::IpDatabase;
use crate::notification::Notification;
use crate::process::{ProcessDisplayInfo, ProcessInfo};
use crate::net::socket::{AddressFamily, LocalSocket, ProtocolPort, SocketConnection, SocketProcess, TransportProtocol, SocketInfoOption, SocketDisplayInfo};
use crate::thread_log;
use netdev::{mac::MacAddr, Interface};
use serde::{Deserialize, Serialize};
use std::{
    collections::HashMap,
    net::IpAddr,
    sync::{Arc, Mutex},
    thread,
    time::Duration,
};

#[derive(Debug, Clone)]
pub struct NetStatStrage {
    pub interface: Arc<Mutex<Interface>>,
    pub traffic: Arc<Mutex<TrafficInfo>>,
    /// Remote Host Traffic Info Map (IpAddr -> RemoteHostInfo)
    pub remote_hosts: Arc<Mutex<HashMap<IpAddr, RemoteHostInfo>>>,
    /// Socket Connection Traffic Map (SocketConnection -> TrafficInfo)
    pub connection_map: Arc<Mutex<HashMap<SocketConnection, TrafficInfo>>>,
    /// Socket Process Map (LocalSocket -> SocketProcess)
    pub local_socket_map: Arc<Mutex<HashMap<LocalSocket, SocketProcess>>>,
    /// Reverse DNS Map (IpAddr -> Hostname)
    pub reverse_dns_map: Arc<Mutex<HashMap<IpAddr, String>>>,
    /// Local IP Map (IpAddr -> Interface Name)
    pub local_ip_map: Arc<Mutex<HashMap<IpAddr, String>>>,
    /// IP Database for IP, ASN, Country, etc.
    pub ipdb: Arc<Mutex<IpDatabase>>,
}

impl NetStatStrage {
    pub fn new() -> Self {
        let default_interface = match netdev::get_default_interface() {
            Ok(iface) => iface,
            Err(e) => {
                thread_log!(error, "NetStatStrage get_default_interface error: {:?}", e);
                Interface::dummy()
            }
        };
        let local_ip_map = interface::get_local_ip_map();
        NetStatStrage {
            interface: Arc::new(Mutex::new(default_interface)),
            traffic: Arc::new(Mutex::new(TrafficInfo::new())),
            remote_hosts: Arc::new(Mutex::new(HashMap::new())),
            connection_map: Arc::new(Mutex::new(HashMap::new())),
            local_socket_map: Arc::new(Mutex::new(HashMap::new())),
            reverse_dns_map: Arc::new(Mutex::new(HashMap::new())),
            local_ip_map: Arc::new(Mutex::new(local_ip_map)),
            ipdb: Arc::new(Mutex::new(IpDatabase::new())),
        }
    }
    // Set interface
    pub fn set_interface(&self, new_interface: Interface) {
        match self.interface.lock() {
            Ok(mut iface) => {
                *iface = new_interface;
            }
            Err(e) => {
                thread_log!(error, "set_interface error: {:?}", e);
            }
        }
    }
    // Get interface
    pub fn get_interface(&self) -> Interface {
        match self.interface.lock() {
            Ok(iface) => iface.clone(),
            Err(e) => {
                thread_log!(error, "get_interface error: {:?}", e);
                Interface::dummy()
            }
        }
    }
    // Get the interface index
    pub fn get_if_index(&self) -> u32 {
        match self.interface.lock() {
            Ok(iface) => iface.index,
            Err(e) => {
                thread_log!(error, "get_if_index error: {:?}", e);
                0
            }
        }
    }
    // Get the interface name
    pub fn get_if_name(&self) -> String {
        match self.interface.lock() {
            Ok(iface) => iface.name.clone(),
            Err(e) => {
                thread_log!(error, "get_if_name error: {:?}", e);
                String::new()
            }
        }
    }
    /// Get the traffic info. (thread safe clone)
    fn get_trrafic(&self) -> TrafficInfo {
        match self.traffic.lock() {
            Ok(traffic) => traffic.clone(),
            Err(e) => {
                thread_log!(error, "get_trrafic error: {:?}", e);
                TrafficInfo::new()
            }
        }
    }
    /// Get the remote hosts. (thread safe clone)
    pub fn get_remote_hosts(&self) -> HashMap<IpAddr, RemoteHostInfo> {
        match self.remote_hosts.lock() {
            Ok(remote_hosts) => remote_hosts.clone(),
            Err(e) => {
                thread_log!(error, "get_remote_hosts error: {:?}", e);
                HashMap::new()
            }
        }
    }
    /// Get the connection_map (thread safe clone)
    pub fn get_connection_map(&self) -> HashMap<SocketConnection, TrafficInfo> {
        match self.connection_map.lock() {
            Ok(connection_map) => connection_map.clone(),
            Err(e) => {
                thread_log!(error, "get_connection_map error: {:?}", e);
                HashMap::new()
            }
        }
    }
    /// Get the local_socket_map (thread safe clone)
    pub fn get_local_socket_map(&self) -> HashMap<LocalSocket, SocketProcess> {
        match self.local_socket_map.lock() {
            Ok(local_socket_map) => local_socket_map.clone(),
            Err(e) => {
                thread_log!(error, "get_local_socket_map error: {:?}", e);
                HashMap::new()
            }
        }
    }
    pub fn get_local_ip_map(&self) -> HashMap<IpAddr, String> {
        match self.local_ip_map.try_lock() {
            Ok(local_ip_map) => local_ip_map.clone(),
            Err(e) => {
                thread_log!(error, "get_local_ip_map error: {:?}", e);
                HashMap::new()
            }
        }
    }
    fn clear_trraffic(&self) {
        match self.traffic.lock() {
            Ok(mut traffic) => {
                *traffic = TrafficInfo::new();
            }
            Err(e) => {
                thread_log!(error, "clear_trraffic error: {:?}", e);
            }
        }
    }
    fn clear_remote_hosts(&self) {
        match self.remote_hosts.lock() {
            Ok(mut remote_hosts) => {
                remote_hosts.clear();
            }
            Err(e) => {
                thread_log!(error, "clear_remote_hosts error: {:?}", e);
            }
        }
    }
    fn clear_connection_map(&self) {
        match self.connection_map.lock() {
            Ok(mut connection_map) => {
                connection_map.clear();
            }
            Err(e) => {
                thread_log!(error, "clear_connection_map error: {:?}", e);
            }
        }
    }
    fn clear_local_socket_map(&self) {
        match self.local_socket_map.lock() {
            Ok(mut local_socket_map) => {
                local_socket_map.clear();
            }
            Err(e) => {
                thread_log!(error, "clear_local_socket_map error: {:?}", e);
            }
        }
    }
    fn clear_reverse_dns_map(&self) {
        match self.reverse_dns_map.lock() {
            Ok(mut reverse_dns_map) => {
                reverse_dns_map.clear();
            }
            Err(e) => {
                thread_log!(error, "clear_reverse_dns_map error: {:?}", e);
            }
        }
    }
    pub fn reset(&self) {
        self.clear_trraffic();
        self.clear_remote_hosts();
        self.clear_connection_map();
        self.clear_local_socket_map();
        self.clear_reverse_dns_map();
    }
    pub fn reset_data(&self) {
        self.clear_trraffic();
        self.clear_remote_hosts();
        self.clear_connection_map();
        self.clear_local_socket_map();
    }
    pub fn clone_and_reset(&self) -> Self {
        let clone = self.clone();
        self.reset();
        clone
    }
    pub fn clone_data_and_reset(&self) -> NetStatData {
        let mut clone: NetStatData = NetStatData::new();
        clone.default_interface = self.get_interface();
        clone.traffic = self.get_trrafic();
        clone.remote_hosts = self.get_remote_hosts();
        clone.connection_map = self.get_connection_map();
        clone.local_socket_map = self.get_local_socket_map();
        clone.local_ip_map = self.get_local_ip_map();
        self.reset_data();
        clone
    }
    pub fn clone_data(&self) -> NetStatData {
        let mut clone: NetStatData = NetStatData::new();
        clone.default_interface = self.get_interface();
        clone.traffic = self.get_trrafic();
        clone.remote_hosts = self.get_remote_hosts();
        clone.connection_map = self.get_connection_map();
        clone.local_socket_map = self.get_local_socket_map();
        clone
    }
    pub fn change_interface(&self, interface: &Interface) {
        //self.reset();
        self.set_interface(interface.clone());
        //self.set_local_ips(interface::get_interface_local_ips(interface));
    }
    pub fn interface_changed(&self, if_index: u32) -> bool {
        if if_index != self.get_if_index() {
            return true;
        }
        false
    }
    pub fn load_ipdb(&self) {
        match IpDatabase::load() {
            Ok(ipdb) => {
                let mut ipdb_mutex = self.ipdb.lock().unwrap();
                *ipdb_mutex = ipdb;
            }
            Err(e) => {
                thread_log!(error, "load_ipdb error: {:?}", e);
            }
        }
    }
    pub fn update(&self, frame: PacketFrame) {
        let local_ip_map_inner = match self.local_ip_map.lock() {
            Ok(inner) => inner,
            Err(e) => {
                thread_log!(error, "Failed to lock local_ips: {:?}", e);
                return;
            }
        };
        // Lock traffic field
        let mut traffic_inner = match self.traffic.lock() {
            Ok(inner) => inner,
            Err(e) => {
                thread_log!(error, "Failed to lock traffic: {:?}", e);
                return;
            }
        };
        // Lock remote_hosts field
        let mut remote_hosts_inner = match self.remote_hosts.lock() {
            Ok(inner) => inner,
            Err(e) => {
                thread_log!(error, "Failed to lock remote_hosts: {:?}", e);
                return;
            }
        };
        // Lock connection_map field
        let mut connections_inner = match self.connection_map.lock() {
            Ok(inner) => inner,
            Err(e) => {
                thread_log!(error, "Failed to lock connection_map: {:?}", e);
                return;
            }
        };
        // Lock ipdb field
        let ipdb_inner = match self.ipdb.lock() {
            Ok(inner) => inner,
            Err(e) => {
                thread_log!(error, "Failed to lock ipdb: {:?}", e);
                return;
            }
        };
        let datalink_layer = match frame.datalink {
            Some(datalink) => datalink,
            None => return,
        };
        let ip_layer = match frame.ip {
            Some(ip) => ip,
            None => return,
        };
        // Determine if the packet is incoming or outgoing.
        let direction: Direction = if let Some(ipv4) = &ip_layer.ipv4 {
            if local_ip_map_inner.contains_key(&IpAddr::V4(ipv4.source)) {
                Direction::Egress
            } else if local_ip_map_inner.contains_key(&IpAddr::V4(ipv4.destination)) {
                Direction::Ingress
            } else {
                return;
            }
        } else if let Some(ipv6) = &ip_layer.ipv6 {
            if local_ip_map_inner.contains_key(&IpAddr::V6(ipv6.source)) {
                Direction::Egress
            } else if local_ip_map_inner.contains_key(&IpAddr::V6(ipv6.destination)) {
                Direction::Ingress
            } else {
                return;
            }
        } else {
            return;
        };
        // Update TrafficInfo
        match direction {
            Direction::Egress => {
                traffic_inner.packet_sent += 1;
                traffic_inner.bytes_sent += frame.packet_len;
            }
            Direction::Ingress => {
                traffic_inner.packet_received += 1;
                traffic_inner.bytes_received += frame.packet_len;
            }
        }
        let mac_addr: String = match direction {
            Direction::Egress => {
                if let Some(ethernet) = datalink_layer.ethernet {
                    ethernet.destination.address()
                } else {
                    MacAddr::zero().to_string()
                }
            }
            Direction::Ingress => {
                if let Some(ethernet) = datalink_layer.ethernet {
                    ethernet.source.address()
                } else {
                    MacAddr::zero().to_string()
                }
            }
        };
        let local_ip_addr: IpAddr = match direction {
            Direction::Egress => {
                if let Some(ipv4) = &ip_layer.ipv4 {
                    IpAddr::V4(ipv4.source)
                } else if let Some(ipv6) = &ip_layer.ipv6 {
                    IpAddr::V6(ipv6.source)
                } else {
                    return;
                }
            }
            Direction::Ingress => {
                if let Some(ipv4) = &ip_layer.ipv4 {
                    IpAddr::V4(ipv4.destination)
                } else if let Some(ipv6) = &ip_layer.ipv6 {
                    IpAddr::V6(ipv6.destination)
                } else {
                    return;
                }
            }
        };
        let interface_name = match local_ip_map_inner.get(&local_ip_addr) {
            Some(name) => name.clone(),
            None => String::from("unknown"),
        };
        let local_port: u16 = match direction {
            Direction::Egress => {
                if let Some(transport) = &frame.transport {
                    if let Some(tcp) = &transport.tcp {
                        tcp.source
                    } else if let Some(udp) = &transport.udp {
                        udp.source
                    } else {
                        0
                    }
                } else {
                    0
                }
            }
            Direction::Ingress => {
                if let Some(transport) = &frame.transport {
                    if let Some(tcp) = &transport.tcp {
                        tcp.destination
                    } else if let Some(udp) = &transport.udp {
                        udp.destination
                    } else {
                        0
                    }
                } else {
                    0
                }
            }
        };
        let remote_ip_addr: IpAddr = match direction {
            Direction::Egress => {
                if let Some(ipv4) = ip_layer.ipv4 {
                    IpAddr::V4(ipv4.destination)
                } else if let Some(ipv6) = ip_layer.ipv6 {
                    IpAddr::V6(ipv6.destination)
                } else {
                    return;
                }
            }
            Direction::Ingress => {
                if let Some(ipv4) = ip_layer.ipv4 {
                    IpAddr::V4(ipv4.source)
                } else if let Some(ipv6) = ip_layer.ipv6 {
                    IpAddr::V6(ipv6.source)
                } else {
                    return;
                }
            }
        };
        let remote_port: u16 = match direction {
            Direction::Egress => {
                if let Some(transport) = &frame.transport {
                    if let Some(tcp) = &transport.tcp {
                        tcp.destination
                    } else if let Some(udp) = &transport.udp {
                        udp.destination
                    } else {
                        0
                    }
                } else {
                    0
                }
            }
            Direction::Ingress => {
                if let Some(transport) = &frame.transport {
                    if let Some(tcp) = &transport.tcp {
                        tcp.source
                    } else if let Some(udp) = &transport.udp {
                        udp.source
                    } else {
                        0
                    }
                } else {
                    0
                }
            }
        };
        // Update or Insert RemoteHostInfo
        let remote_host: &mut RemoteHostInfo = remote_hosts_inner
            .entry(remote_ip_addr)
            .or_insert(RemoteHostInfo::new(mac_addr, remote_ip_addr));
        match direction {
            Direction::Egress => {
                remote_host.traffic_info.packet_sent += 1;
                remote_host.traffic_info.bytes_sent += frame.packet_len;
            }
            Direction::Ingress => {
                remote_host.traffic_info.packet_received += 1;
                remote_host.traffic_info.bytes_received += frame.packet_len;
            }
        }
        match remote_host.ip_addr {
            IpAddr::V4(ipv4) => {
                if let Some(ipv4_info) = ipdb_inner.get_ipv4_info(ipv4) {
                    remote_host.country_code = ipv4_info.country_code;
                    remote_host.country_name = ipv4_info.country_name;
                    remote_host.asn = ipv4_info.asn;
                    remote_host.as_name = ipv4_info.as_name;
                }
            }
            IpAddr::V6(ipv6) => {
                if let Some(ipv6_info) = ipdb_inner.get_ipv6_info(ipv6) {
                    remote_host.country_code = ipv6_info.country_code;
                    remote_host.country_name = ipv6_info.country_name;
                    remote_host.asn = ipv6_info.asn;
                    remote_host.as_name = ipv6_info.as_name;
                }
            }
        }
        // Update SocketConnection if the packet is TCP or UDP.
        if let Some(transport) = frame.transport {
            if let Some(_tcp) = transport.tcp {
                let socket_connection: SocketConnection = SocketConnection {
                    interface_name: interface_name.clone(),
                    local_ip_addr: local_ip_addr,
                    local_port: local_port,
                    remote_ip_addr: remote_ip_addr,
                    remote_port: remote_port,
                    protocol: TransportProtocol::TCP,
                };
                let socket_traffic: &mut TrafficInfo = connections_inner
                    .entry(socket_connection)
                    .or_insert(TrafficInfo::new());
                match direction {
                    Direction::Egress => {
                        socket_traffic.packet_sent += 1;
                        socket_traffic.bytes_sent += frame.packet_len;
                    }
                    Direction::Ingress => {
                        socket_traffic.packet_received += 1;
                        socket_traffic.bytes_received += frame.packet_len;
                    }
                }
            }
            if let Some(_udp) = transport.udp {
                let socket_connection: SocketConnection = SocketConnection {
                    interface_name: interface_name,
                    local_ip_addr: local_ip_addr,
                    local_port: local_port,
                    remote_ip_addr: remote_ip_addr,
                    remote_port: remote_port,
                    protocol: TransportProtocol::UDP,
                };
                let socket_traffic: &mut TrafficInfo = connections_inner
                    .entry(socket_connection)
                    .or_insert(TrafficInfo::new());
                match direction {
                    Direction::Egress => {
                        socket_traffic.packet_sent += 1;
                        socket_traffic.bytes_sent += frame.packet_len;
                    }
                    Direction::Ingress => {
                        socket_traffic.packet_received += 1;
                        socket_traffic.bytes_received += frame.packet_len;
                    }
                }
            }
        }
        // Drop the locks
        drop(traffic_inner);
        drop(remote_hosts_inner);
        drop(connections_inner);
        drop(ipdb_inner);
    }
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Overview {
    pub traffic: TrafficDisplayInfo,
    pub top_processes: Vec<ProcessDisplayInfo>,
    pub top_remote_hosts: Vec<HostDisplayInfo>,
    pub top_app_protocols: Vec<ServiceDisplayInfo>,
    pub notificatons: Vec<Notification>,
}

impl Overview {
    pub fn new() -> Self {
        Overview {
            traffic: TrafficDisplayInfo::new(),
            top_processes: Vec::new(),
            top_remote_hosts: Vec::new(),
            top_app_protocols: Vec::new(),
            notificatons: Vec::new(),
        }
    }
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct NetStatData {
    pub default_interface: Interface,
    pub traffic: TrafficInfo,
    pub remote_hosts: HashMap<IpAddr, RemoteHostInfo>,
    pub connection_map: HashMap<SocketConnection, TrafficInfo>,
    pub local_socket_map: HashMap<LocalSocket, SocketProcess>,
    pub local_ip_map: HashMap<IpAddr, String>,
}

impl NetStatData {
    pub fn new() -> Self {
        let default_interface = match netdev::get_default_interface() {
            Ok(iface) => iface,
            Err(e) => {
                thread_log!(error, "NetStatData get_default_interface error: {:?}", e);
                Interface::dummy()
            }
        };
        NetStatData {
            default_interface: default_interface,
            traffic: TrafficInfo::new(),
            remote_hosts: HashMap::new(),
            connection_map: HashMap::new(),
            local_socket_map: HashMap::new(),
            local_ip_map: HashMap::new(),
        }
    }
    // merge using entry method to merge traffic info.
    pub fn merge(&mut self, other: NetStatData, duration: Duration) {
        // Update Interface Info
        self.default_interface = other.default_interface;
        // Update Traffic Info
        self.traffic.update_bytes_per_sec(&other.traffic, duration);
        self.traffic.add_traffic(&other.traffic);
        // Update RemoteHostInfo
        other
            .remote_hosts
            .iter()
            .for_each(|(ip, host)| match self.remote_hosts.entry(*ip) {
                std::collections::hash_map::Entry::Occupied(mut entry) => {
                    let host_entry = entry.get_mut();
                    host_entry.merge(host, duration);
                }
                std::collections::hash_map::Entry::Vacant(entry) => {
                    entry.insert(host.clone());
                }
            });
        // Update SocketConnection Traffic Info
        other
            .connection_map
            .iter()
            .for_each(
                |(conn, traffic_info)| match self.connection_map.entry(conn.clone()) {
                    std::collections::hash_map::Entry::Occupied(mut entry) => {
                        let traffic_info_entry = entry.get_mut();
                        traffic_info_entry.update_bytes_per_sec(traffic_info, duration);
                        traffic_info_entry.add_traffic(traffic_info);
                    }
                    std::collections::hash_map::Entry::Vacant(entry) => {
                        entry.insert(traffic_info.clone());
                    }
                },
            );
        // Update local_socket_map
        other
            .local_socket_map
            .iter()
            .for_each(|(local_socket, socket_process)| {
                match self.local_socket_map.entry(local_socket.clone()) {
                    std::collections::hash_map::Entry::Occupied(mut entry) => {
                        let socket_process_entry = entry.get_mut();
                        socket_process_entry.merge(socket_process);
                    }
                    std::collections::hash_map::Entry::Vacant(entry) => {
                        entry.insert(socket_process.clone());
                    }
                }
            });
        // Update local_ip_map
        self.local_ip_map = other.local_ip_map;
    }

    // Remove old entries from remote_hosts, connection_map, local_socket_map
    // TrafficInfo.last_seen is used to determine if the entry is old.
    // If the entry is older than ttl, it will be removed.
    pub fn remove_old_entries(&mut self, ttl: Duration) {
        let now = std::time::SystemTime::now();
        let remote_hosts: HashMap<IpAddr, RemoteHostInfo> = self
            .remote_hosts
            .iter()
            .filter(
                |(_ip, host)| match now.duration_since(host.traffic_info.last_seen) {
                    Ok(duration) => {
                        if duration > ttl {
                            return false;
                        }
                        true
                    }
                    Err(e) => {
                        thread_log!(error, "remove_old_entries error: {:?}", e);
                        false
                    }
                },
            )
            .map(|(ip, host)| (*ip, host.clone()))
            .collect();
        self.remote_hosts = remote_hosts;
        let mut remove_local_socket: Vec<LocalSocket> = Vec::new();
        let connection_map: HashMap<SocketConnection, TrafficInfo> = self
            .connection_map
            .iter()
            .filter(
                |(conn, traffic_info)| match now.duration_since(traffic_info.last_seen) {
                    Ok(duration) => {
                        if duration > ttl {
                            remove_local_socket.push(LocalSocket {
                                interface_name: conn.interface_name.clone(),
                                port: conn.local_port,
                                protocol: conn.protocol,
                            });
                            return false;
                        }
                        true
                    }
                    Err(e) => {
                        thread_log!(error, "remove_old_entries error: {:?}", e);
                        remove_local_socket.push(LocalSocket {
                            interface_name: conn.interface_name.clone(),
                            port: conn.local_port,
                            protocol: conn.protocol,
                        });
                        false
                    }
                },
            )
            .map(|(conn, traffic_info)| (conn.clone(), traffic_info.clone()))
            .collect();
        self.connection_map = connection_map;

        for local_socket in remove_local_socket {
            self.local_socket_map.remove(&local_socket);
        }
    }

    pub fn get_remote_hosts(&self, limit: Option<usize>) -> Vec<HostDisplayInfo> {
        let mut host_traffic_map: HashMap<IpAddr, usize> = HashMap::new();
        self.remote_hosts.iter().for_each(|(_ip, host)| {
            match host_traffic_map.get(&host.ip_addr) {
                Some(traffic) => {
                    let mut traffic = traffic.clone();
                    traffic += host.traffic_info.bytes_sent;
                    traffic += host.traffic_info.bytes_received;
                    host_traffic_map.insert(host.ip_addr, traffic);
                }
                None => {
                    host_traffic_map.insert(
                        host.ip_addr,
                        host.traffic_info.bytes_sent + host.traffic_info.bytes_received,
                    );
                }
            }
        });
        let mut host_traffic_vec: Vec<(&IpAddr, &usize)> = host_traffic_map.iter().collect();
        host_traffic_vec.sort_by(|a, b| b.1.cmp(a.1));
        let mut remote_hosts: Vec<HostDisplayInfo> = Vec::new();
        // limit : if limit is None, return all remote hosts.
        for (ip, _) in host_traffic_vec
            .iter()
            .take(limit.unwrap_or(host_traffic_vec.len()))
        {
            if let Some(host) = self.remote_hosts.get(ip) {
                let host = HostDisplayInfo {
                    ip_addr: host.ip_addr,
                    host_name: host.hostname.clone(),
                    country_code: host.country_code.clone(),
                    country_name: host.country_name.clone(),
                    asn: host.asn.clone(),
                    as_name: host.as_name.clone(),
                    traffic: host.traffic_info.to_display_info(),
                };
                remote_hosts.push(host);
            }
        }
        remote_hosts
    }

    pub fn get_processes(&self, limit: Option<usize>) -> Vec<ProcessDisplayInfo> {
        let mut process_traffic_map: HashMap<u32, TrafficInfo> = HashMap::new();
        let mut process_map: HashMap<u32, ProcessInfo> = HashMap::new();
        self.connection_map.iter().for_each(|(conn, traffic_info)| {
            let local_socket: LocalSocket = LocalSocket {
                interface_name: conn.interface_name.clone(),
                port: conn.local_port,
                protocol: conn.protocol,
            };
            match self.local_socket_map.get(&local_socket) {
                Some(socket_process) => {
                    if let Some(process) = &socket_process.process {
                        match process_traffic_map.get(&process.pid) {
                            Some(traffic) => {
                                let mut traffic = traffic.clone();
                                traffic.add_traffic(traffic_info);
                                process_traffic_map.insert(process.pid, traffic);
                            }
                            None => {
                                process_traffic_map.insert(process.pid, traffic_info.clone());
                            }
                        }
                        process_map.insert(process.pid, process.clone());
                    }
                }
                None => {}
            }
        });
        // Create process total traffic map from process_traffic_map
        let process_total_traffic_map: HashMap<u32, usize> = process_traffic_map
            .iter()
            .map(|(pid, traffic)| (*pid, traffic.total_bytes()))
            .collect();
        // Sort process_total_traffic_map by traffic
        let mut process_total_traffic_vec: Vec<(&u32, &usize)> =
            process_total_traffic_map.iter().collect();
        process_total_traffic_vec.sort_by(|a, b| b.1.cmp(a.1));
        // Create top processes from process_total_traffic_vec
        let mut top_processes: Vec<ProcessDisplayInfo> = Vec::new();
        // limit : if limit is None, return all processes.
        for (pid, _) in process_total_traffic_vec
            .iter()
            .take(limit.unwrap_or(process_total_traffic_vec.len()))
        {
            if let Some(traffic) = process_traffic_map.get(pid) {
                if let Some(process) = process_map.get(pid) {
                    let process = ProcessDisplayInfo {
                        pid: process.pid,
                        name: process.name.clone(),
                        traffic: traffic.to_display_info(),
                    };
                    top_processes.push(process);
                }
            }
        }
        top_processes
    }

    pub fn get_connections(&self, limit: Option<usize>) -> Vec<SocketDisplayInfo> {
        let connection_total_traffic_map: HashMap<SocketConnection, usize> = self
            .connection_map
            .iter()
            .map(|(conn, traffic)| (conn.clone(), traffic.total_bytes()))
            .collect();
        let mut connection_total_traffic_vec: Vec<(&SocketConnection, &usize)> =
            connection_total_traffic_map.iter().collect();
        connection_total_traffic_vec.sort_by(|a, b| b.1.cmp(a.1));
        let mut top_connections: Vec<SocketDisplayInfo> = Vec::new();
        // limit : if limit is None, return all connections.
        for (conn, _) in connection_total_traffic_vec
            .iter()
            .take(limit.unwrap_or(connection_total_traffic_vec.len()))
        {
            // Get process info from local_socket_map
            let process: Option<ProcessInfo> = match self.local_socket_map.get(&LocalSocket {
                interface_name: conn.interface_name.clone(),
                port: conn.local_port,
                protocol: conn.protocol,
            }) {
                Some(socket_process) => socket_process.process.clone(),
                None => None,
            };
            if let Some(traffic) = self.connection_map.get(conn) {
                let socket_traffic_info = SocketDisplayInfo {
                    interface_name: conn.interface_name.clone(),
                    local_ip_addr: conn.local_ip_addr,
                    local_port: conn.local_port,
                    remote_ip_addr: Some(conn.remote_ip_addr),
                    remote_port: Some(conn.remote_port),
                    protocol: conn.protocol,
                    ip_version: match conn.remote_ip_addr {
                        IpAddr::V4(_) => AddressFamily::IPv4,
                        IpAddr::V6(_) => AddressFamily::IPv6,
                    },
                    traffic: traffic.to_display_info(),
                    process: process,
                };
                top_connections.push(socket_traffic_info);
            }
        }
        top_connections
    }
    
    pub fn get_connections_with_opt(
        &self,
        limit: Option<usize>,
        opt: SocketInfoOption,
    ) -> Vec<SocketDisplayInfo> {
        let connection_total_traffic_map: HashMap<SocketConnection, usize> = self
            .connection_map
            .iter()
            .map(|(conn, traffic)| (conn.clone(), traffic.total_bytes()))
            .collect();
        let mut connection_total_traffic_vec: Vec<(&SocketConnection, &usize)> =
            connection_total_traffic_map.iter().collect();
        connection_total_traffic_vec.sort_by(|a, b| b.1.cmp(a.1));
        let mut top_connections: Vec<SocketDisplayInfo> = Vec::new();
        // limit : if limit is None, return all connections.
        for (conn, _) in connection_total_traffic_vec
            .iter()
            .take(limit.unwrap_or(connection_total_traffic_vec.len()))
        {
            // Get process info from local_socket_map
            let process: Option<ProcessInfo> = match self.local_socket_map.get(&LocalSocket {
                interface_name: conn.interface_name.clone(),
                port: conn.local_port,
                protocol: conn.protocol,
            }) {
                Some(socket_process) => socket_process.process.clone(),
                None => None,
            };
            if let Some(traffic) = self.connection_map.get(conn) {
                let socket_traffic_info = SocketDisplayInfo {
                    interface_name: conn.interface_name.clone(),
                    local_ip_addr: conn.local_ip_addr,
                    local_port: conn.local_port,
                    remote_ip_addr: Some(conn.remote_ip_addr),
                    remote_port: Some(conn.remote_port),
                    protocol: conn.protocol,
                    ip_version: match conn.remote_ip_addr {
                        IpAddr::V4(_) => AddressFamily::IPv4,
                        IpAddr::V6(_) => AddressFamily::IPv6,
                    },
                    traffic: traffic.to_display_info(),
                    process: process,
                };
                if opt.address_family.contains(&socket_traffic_info.ip_version)
                    && opt
                        .transport_protocol
                        .contains(&socket_traffic_info.protocol)
                {
                    top_connections.push(socket_traffic_info);
                }
            }
        }
        top_connections
    }

    pub fn get_app_protocols(&self, limit: Option<usize>) -> Vec<ServiceDisplayInfo> {
        let service_db: ServiceDatabase = match crate::db::service::ServiceDatabase::load() {
            Ok(db) => db,
            Err(e) => {
                thread_log!(error, "get_app_protocols load service db error: {:?}", e);
                ServiceDatabase::new()
            }
        };
        let mut protocol_port_map: HashMap<ProtocolPort, TrafficInfo> = HashMap::new();
        self.connection_map.iter().for_each(|(conn, traffic_info)| {
            let protocol_port: ProtocolPort = ProtocolPort {
                protocol: conn.protocol,
                port: conn.remote_port,
            };
            match protocol_port_map.get(&protocol_port) {
                Some(traffic) => {
                    let mut traffic = traffic.clone();
                    traffic.add_traffic(traffic_info);
                    protocol_port_map.insert(protocol_port, traffic);
                }
                None => {
                    protocol_port_map.insert(protocol_port, traffic_info.clone());
                }
            }
        });
        let protocol_total_traffic_map: HashMap<ProtocolPort, usize> = protocol_port_map
            .iter()
            .map(|(protocol_port, traffic)| (*protocol_port, traffic.total_bytes()))
            .collect();
        let mut protocol_total_traffic_vec: Vec<(&ProtocolPort, &usize)> =
            protocol_total_traffic_map.iter().collect();
        protocol_total_traffic_vec.sort_by(|a, b| b.1.cmp(a.1));
        let mut top_app_protocols: Vec<ServiceDisplayInfo> = Vec::new();
        // limit : if limit is None, return all app protocols.
        for (protocol_port, _) in protocol_total_traffic_vec
            .iter()
            .take(limit.unwrap_or(protocol_total_traffic_vec.len()))
        {
            if let Some(traffic) = protocol_port_map.get(protocol_port) {
                let service = ServiceDisplayInfo {
                    port: protocol_port.port,
                    protocol: protocol_port.protocol.as_str().to_string(),
                    name: match protocol_port.protocol {
                        TransportProtocol::TCP => {
                            service_db
                                .tcp_map
                                .get(&protocol_port.port)
                                .unwrap_or(&String::from("unknown"))
                                .clone()
                        }
                        TransportProtocol::UDP => {
                            service_db
                                .udp_map
                                .get(&protocol_port.port)
                                .unwrap_or(&String::from("unknown"))
                                .clone()
                        }
                    },
                    traffic: traffic.to_display_info(),
                };
                top_app_protocols.push(service);
            }
        }
        top_app_protocols
    }

    pub fn get_overview(&self) -> Overview {
        let mut overview = Overview::new();
        overview.traffic = TrafficDisplayInfo::from_traffic(&self.traffic);
        // Get top remote hosts
        overview.top_remote_hosts = self.get_remote_hosts(Some(10));
        // Get top processes
        overview.top_processes = self.get_processes(Some(10));
        // Get top app protocols
        overview.top_app_protocols = self.get_app_protocols(Some(10));
        overview
    }
}

pub fn update_netstat_data(
    netstat_strage: &mut Arc<NetStatStrage>,
    netstat_data: &mut Arc<Mutex<NetStatData>>,
    interval: Duration,
) {
    loop {
        match netstat_data.lock() {
            Ok(mut data) => {
                data.merge(netstat_strage.clone_data_and_reset(), interval);
            }
            Err(e) => {
                thread_log!(error, "Error: {:?}", e);
                continue;
            }
        }
        thread::sleep(interval);
    }
}