pistol 4.0.18

A Rust Library about Cybersecurity
Documentation
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
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
use crc32fast;
use gcdx::gcdx;
use pnet::packet::Packet;
use pnet::packet::icmp::IcmpCode;
use pnet::packet::icmp::IcmpPacket;
use pnet::packet::ipv4;
use pnet::packet::ipv4::Ipv4Packet;
use pnet::packet::tcp::TcpOptionNumbers;
use pnet::packet::tcp::TcpPacket;
use pnet::packet::udp::UdpPacket;
use tracing::warn;

use crate::error::PistolError;
use crate::os::rr::IERR;
use crate::os::rr::SEQRR;
use crate::os::rr::TXRR;
use crate::os::rr::U1RR;
use crate::utils::PistolHex;

const CWR_MASK: u8 = 0b10000000;
const ECE_MASK: u8 = 0b01000000;
const URG_MASK: u8 = 0b00100000;
const ACK_MASK: u8 = 0b00010000;
const PSH_MASK: u8 = 0b00001000;
const RST_MASK: u8 = 0b00000100;
const SYN_MASK: u8 = 0b00000010;
const FIN_MASK: u8 = 0b00000001;

// Because different programs wait, process, and send probebao for different times,
// so there is a certain error in the two indicators calculated based on time.
// Program estimation error, ISR, SP use.
// const PROGRAM_ESTIMATION_ERROR_ISR: f64 = 0.35;
// const PROGRAM_ESTIMATION_ERROR_SP: f64 = 0.35;
const PROGRAM_ESTIMATION_ERROR_ISR: f64 = 0.0;
const PROGRAM_ESTIMATION_ERROR_SP: f64 = 0.0;

fn build_ipv4_packet<'a>(
    ipv4_buff: &'a [u8],
    probe_name: &str,
) -> Result<Ipv4Packet<'a>, PistolError> {
    if ipv4_buff.len() > 0 {
        match Ipv4Packet::new(ipv4_buff) {
            Some(p) => return Ok(p),
            None => (),
        }
    }
    Err(PistolError::BuildIpv4PacketFailed {
        probe_name: probe_name.to_string(),
    })
}

fn build_tcp_packet<'a>(
    tcp_buff: &'a [u8],
    probe_name: &str,
) -> Result<TcpPacket<'a>, PistolError> {
    if tcp_buff.len() > 0 {
        match TcpPacket::new(tcp_buff) {
            Some(p) => return Ok(p),
            None => (),
        }
    }
    Err(PistolError::BuildTcpPacketFailed {
        probe_name: probe_name.to_string(),
    })
}

fn build_icmp_packet<'a>(
    icmp_buff: &'a [u8],
    probe_name: &str,
) -> Result<IcmpPacket<'a>, PistolError> {
    if icmp_buff.len() > 0 {
        match IcmpPacket::new(icmp_buff) {
            Some(p) => return Ok(p),
            None => (),
        }
    }
    Err(PistolError::BuildIcmpPacketFailed {
        probe_name: probe_name.to_string(),
    })
}

fn build_udp_packet<'a>(
    udp_buff: &'a [u8],
    probe_name: &str,
) -> Result<UdpPacket<'a>, PistolError> {
    if udp_buff.len() > 0 {
        match UdpPacket::new(udp_buff) {
            Some(p) => return Ok(p),
            None => (),
        }
    }
    Err(PistolError::BuildUdpPacketFailed {
        probe_name: probe_name.to_string(),
    })
}

fn get_tcp_seq(ipv4_buff: &[u8], probe_name: &str) -> Result<u32, PistolError> {
    let ipv4_packet = build_ipv4_packet(ipv4_buff, probe_name)?;
    let tcp_packet = build_tcp_packet(ipv4_packet.payload(), probe_name)?;
    Ok(tcp_packet.get_sequence())
}

fn get_diff_u32(input: &[u32]) -> Vec<u32> {
    if input.len() >= 2 {
        let input_slice = input[0..(input.len() - 1)].to_vec();
        let mut diff = Vec::new();
        for (i, x) in input_slice.iter().enumerate() {
            let y = input[i + 1];
            let x = *x;
            let k = if x <= y { y - x } else { !(x - y) };
            diff.push(k);
        }
        diff
    } else {
        Vec::new()
    }
}

fn get_diff_u16(input: &[u16]) -> Vec<u16> {
    if input.len() >= 2 {
        let input_slice = input[0..(input.len() - 1)].to_vec();
        let mut diff = Vec::new();
        for (i, x) in input_slice.iter().enumerate() {
            let y = input[i + 1];
            let x = *x;
            let k = if x <= y { y - x } else { !(x - y) };
            diff.push(k);
        }
        diff
    } else {
        Vec::new()
    }
}

/// TCP ISN greatest common divisor (GCD)
pub fn tcp_gcd(seqrr: &SEQRR) -> Result<(u32, Vec<u32>), PistolError> {
    let s1 = get_tcp_seq(&seqrr.seq1.response, "seq1");
    let s2 = get_tcp_seq(&seqrr.seq2.response, "seq2");
    let s3 = get_tcp_seq(&seqrr.seq3.response, "seq3");
    let s4 = get_tcp_seq(&seqrr.seq4.response, "seq4");
    let s5 = get_tcp_seq(&seqrr.seq5.response, "seq5");
    let s6 = get_tcp_seq(&seqrr.seq6.response, "seq6");
    let mut tmp_vec = Vec::new();
    tmp_vec.push(s1);
    tmp_vec.push(s2);
    tmp_vec.push(s3);
    tmp_vec.push(s4);
    tmp_vec.push(s5);
    tmp_vec.push(s6);

    let mut seq_vec: Vec<u32> = Vec::new();
    for s in tmp_vec {
        match s {
            Ok(s) => seq_vec.push(s),
            Err(e) => warn!("{}", e),
        }
    }

    let diff = get_diff_u32(&seq_vec);
    if diff.len() > 1 {
        let gcd = match gcdx(&diff) {
            Some(g) => g,
            None => return Err(PistolError::CalcDiffFailed),
        };
        Ok((gcd, diff))
    } else if diff.len() == 1 {
        let gcd = diff[0];
        Ok((gcd, diff))
    } else {
        Err(PistolError::CalcDiffFailed)
    }
}

/// TCP ISN counter rate (ISR)
pub fn tcp_isr(diff: Vec<u32>, elapsed: f64) -> Result<(u32, Vec<f64>), PistolError> {
    if diff.len() > 0 {
        let mut seq_rates: Vec<f64> = Vec::new();
        let mut sum = 0.0;
        for d in &diff {
            let f = (*d as f64) / elapsed;
            seq_rates.push(f);
            sum += f;
        }
        let avg = sum / diff.len() as f64;
        let isr = if avg < 1.0 {
            0
        } else {
            ((8.0 - PROGRAM_ESTIMATION_ERROR_ISR) * avg.log2()).round() as u32
        };
        Ok((isr, seq_rates))
    } else {
        Err(PistolError::CalcISRFailed)
    }
}

/// Calculate standard deviation
fn vec_std(values: &[f64]) -> f64 {
    let mut sum = 0.0;
    for v in values {
        sum += *v;
    }
    let mean = sum / values.len() as f64;
    let mut ret = 0.0;
    for v in values {
        ret += (v - mean).powi(2);
    }
    ret.sqrt()
}

/// TCP ISN sequence predictability index (SP)
pub fn tcp_sp(seq_rates: Vec<f64>, gcd: u32) -> Result<u32, PistolError> {
    // This test is only performed if at least four responses were seen.
    if seq_rates.len() >= 4 {
        let mut seq_rates_clone = seq_rates.clone();
        // If the previously computed GCD value is greater than nine.
        if gcd > 9 {
            for i in 0..seq_rates.len() {
                seq_rates_clone[i] /= gcd as f64;
            }
        }
        let sd = vec_std(&seq_rates);
        let sp = if sd <= 1.0 {
            0
        } else {
            ((8.0 - PROGRAM_ESTIMATION_ERROR_SP) * sd.log2()).round() as u32
        };
        Ok(sp)
    } else {
        Ok(0) // mean omitting
    }
}

fn get_ip_id(ipv4_buff: &[u8], probe_name: &str) -> Result<u16, PistolError> {
    let ipv4_packet = build_ipv4_packet(ipv4_buff, probe_name)?;
    Ok(ipv4_packet.get_identification())
}

/// IP ID sequence generation algorithm (TI, CI, II)
pub fn tcp_ti_ci_ii(
    seqrr: &SEQRR,
    t2t7rr: &TXRR,
    ierr: &IERR,
) -> Result<(String, String, String), PistolError> {
    let z_judgement = |x: &[u16]| -> bool {
        let mut conditon = true; // all of the ID numbers are zero
        for v in x {
            if *v != 0 {
                conditon = false;
            }
        }
        conditon
    };
    let rd_judgement = |diff: &[u16]| -> bool {
        let mut condition = true; // IP ID sequence ever increases by at least 20,000
        for d in diff {
            if *d < 20000 {
                condition = false;
            }
        }
        condition
    };
    let hex_judgement = |ip_id_vec: &[u16]| -> Result<bool, PistolError> {
        let v3 = get_diff_u16(ip_id_vec);
        let mut sum = 0;
        for v in v3 {
            sum += v;
        }

        if sum == 0 { Ok(true) } else { Ok(false) }
    };
    let ri_judgement = |diff: &[u16]| -> bool {
        let mut condition_1 = true; // any of the differences exceeds 1000
        let mut condition_2 = true; // any of the differences not evenly divisiable by 256
        for d in diff {
            if *d < 1000 {
                condition_1 = false;
            }
            if *d % 256 == 0 {
                condition_2 = false;
            }
        }

        if condition_1 && condition_2 {
            true
        } else {
            false
        }
    };
    let bi_judgement = |diff: &[u16]| -> bool {
        let mut condition_1 = true; // all of the differences are divisible by 256
        let mut condition_2 = true; // all of the differences are no greater than 5,120
        for d in diff {
            if *d % 256 != 0 {
                condition_1 = false;
            }
            if *d > 5120 {
                condition_2 = false;
            }
        }

        if condition_1 && condition_2 {
            true
        } else {
            false
        }
    };
    let i_judgement = |diff: &[u16]| -> bool {
        let mut condition = true; // all of the differences are less than ten
        for d in diff {
            if *d >= 10 {
                condition = false;
            }
        }
        condition
    };

    let seq1_ip_id = get_ip_id(&seqrr.seq1.response, "seq1");
    let seq2_ip_id = get_ip_id(&seqrr.seq2.response, "seq2");
    let seq3_ip_id = get_ip_id(&seqrr.seq3.response, "seq3");
    let seq4_ip_id = get_ip_id(&seqrr.seq4.response, "seq4");
    let seq5_ip_id = get_ip_id(&seqrr.seq5.response, "seq5");
    let seq6_ip_id = get_ip_id(&seqrr.seq6.response, "seq6");
    let mut tmp_vec = Vec::new();
    tmp_vec.push(seq1_ip_id);
    tmp_vec.push(seq2_ip_id);
    tmp_vec.push(seq3_ip_id);
    tmp_vec.push(seq4_ip_id);
    tmp_vec.push(seq5_ip_id);
    tmp_vec.push(seq6_ip_id);

    let mut seq_ip_id_vec = Vec::new();
    for s in tmp_vec {
        match s {
            Ok(s) => seq_ip_id_vec.push(s),
            Err(e) => warn!("{}", e),
        }
    }

    let seq_diff = get_diff_u16(&seq_ip_id_vec);

    // TI is based on responses to the TCP SEQ probes.
    let ti = if seq_ip_id_vec.len() >= 3 {
        if z_judgement(&seq_ip_id_vec) {
            // If all of the ID numbers are zero, the value of the test is Z.
            String::from("Z")
        } else if ri_judgement(&seq_diff) {
            // If the IP ID sequence ever increases by at least 20,000, the value is RD (random).
            // This result isn't possible for II because there are not enough samples to support it.
            String::from("RD")
        } else if hex_judgement(&seq_ip_id_vec)? {
            // If all of the IP IDs are identical, the test is set to that value in hex.
            format!("{:X}", seq_ip_id_vec[0])
        } else if ri_judgement(&seq_diff) {
            // If any of the differences between two consecutive IDs exceeds 1,000, and is not evenly divisible by 256,
            // the test's value is RI (random positive increments).
            // If the difference is evenly divisible by 256, it must be at least 256,000 to cause this RI result.
            String::from("RI")
        } else if bi_judgement(&seq_diff) {
            // If all of the differences are divisible by 256 and no greater than 5,120, the test is set to BI (broken increment).
            // This happens on systems like Microsoft Windows where the IP ID is sent in host byte order rather than network byte order.
            // It works fine and isn't any sort of RFC violation, though it does give away host architecture details which can be useful to attackers.
            String::from("BI")
        } else if i_judgement(&seq_diff) {
            // If all of the differences are less than ten, the value is I (incremental).
            // We allow difference up to ten here (rather than requiring sequential ordering) because traffic from other hosts can cause sequence gaps.
            String::from("I")
        } else {
            // If none of the previous steps identify the generation algorithm, the test is omitted from the fingerprint.
            String::new()
        }
    } else {
        // For TI, at least three responses must be received for the test to be included.
        String::new()
    };

    // CI is from the responses to the three TCP probes sent to a closed port: T5, T6, and T7.
    let t5_ip_id = get_ip_id(&t2t7rr.t5.response, "t5");
    let t6_ip_id = get_ip_id(&t2t7rr.t6.response, "t6");
    let t7_ip_id = get_ip_id(&t2t7rr.t7.response, "t7");
    let mut tmp_vec = Vec::new();
    tmp_vec.push(t5_ip_id);
    tmp_vec.push(t6_ip_id);
    tmp_vec.push(t7_ip_id);

    let mut t_ip_id_vec = Vec::new();
    for t in tmp_vec {
        match t {
            Ok(t) => t_ip_id_vec.push(t),
            Err(e) => warn!("{}", e),
        }
    }
    let t_diff = get_diff_u16(&t_ip_id_vec);

    let ci = if t_ip_id_vec.len() >= 2 {
        if z_judgement(&t_ip_id_vec) {
            // If all of the ID numbers are zero, the value of the test is Z.
            String::from("Z")
        } else if rd_judgement(&t_diff) {
            // If the IP ID sequence ever increases by at least 20,000, the value is RD (random).
            // This result isn't possible for II because there are not enough samples to support it.
            String::from("RD")
        } else if hex_judgement(&t_ip_id_vec)? {
            // If all of the IP IDs are identical, the test is set to that value in hex.
            format!("{:X}", t_ip_id_vec[0])
        } else if ri_judgement(&t_diff) {
            // If any of the differences between two consecutive IDs exceeds 1,000, and is not evenly divisible by 256,
            // the test's value is RI (random positive increments).
            // If the difference is evenly divisible by 256, it must be at least 256,000 to cause this RI result.
            String::from("RI")
        } else if bi_judgement(&t_diff) {
            // If all of the differences are divisible by 256 and no greater than 5,120, the test is set to BI (broken increment).
            // This happens on systems like Microsoft Windows where the IP ID is sent in host byte order rather than network byte order.
            // It works fine and isn't any sort of RFC violation, though it does give away host architecture details which can be useful to attackers.
            String::from("BI")
        } else if i_judgement(&t_diff) {
            // If all of the differences are less than ten, the value is I (incremental).
            // We allow difference up to ten here (rather than requiring sequential ordering) because traffic from other hosts can cause sequence gaps.
            String::from("I")
        } else {
            // If none of the previous steps identify the generation algorithm, the test is omitted from the fingerprint.
            String::new()
        }
    } else {
        // for CI, at least two responses are required.
        String::new()
    };

    // II comes from the ICMP responses to the two IE ping probes.
    let ie1_ip_id = get_ip_id(&ierr.ie1.response, "ie1");
    let ie2_ip_id = get_ip_id(&ierr.ie2.response, "ie2");
    let mut tmp_vec = Vec::new();
    tmp_vec.push(ie1_ip_id);
    tmp_vec.push(ie2_ip_id);

    let mut ie_ip_id_vec = Vec::new();
    for i in tmp_vec {
        match i {
            Ok(i) => ie_ip_id_vec.push(i),
            Err(e) => warn!("{}", e),
        }
    }
    let ie_diff = get_diff_u16(&ie_ip_id_vec);
    // println!("{:?}", ie_ip_id_vec);
    // println!("{:?}", ie_diff);

    // RD result isn't possible for II because there are not enough samples to support it.
    let ii = if ie_ip_id_vec.len() >= 2 {
        if z_judgement(&ie_ip_id_vec) {
            // If all of the ID numbers are zero, the value of the test is Z.
            String::from("Z")
        } else if hex_judgement(&ie_ip_id_vec)? {
            // If all of the IP IDs are identical, the test is set to that value in hex.
            format!("{:X}", ie_ip_id_vec[0])
        } else if ri_judgement(&ie_diff) {
            // If any of the differences between two consecutive IDs exceeds 1,000, and is not evenly divisible by 256,
            // the test's value is RI (random positive increments).
            // If the difference is evenly divisible by 256, it must be at least 256,000 to cause this RI result.
            String::from("RI")
        } else if bi_judgement(&ie_diff) {
            // If all of the differences are divisible by 256 and no greater than 5,120, the test is set to BI (broken increment).
            // This happens on systems like Microsoft Windows where the IP ID is sent in host byte order rather than network byte order.
            // It works fine and isn't any sort of RFC violation, though it does give away host architecture details which can be useful to attackers.
            String::from("BI")
        } else if i_judgement(&ie_diff) {
            // If all of the differences are less than ten, the value is I (incremental).
            // We allow difference up to ten here (rather than requiring sequential ordering) because traffic from other hosts can cause sequence gaps.
            String::from("I")
        } else {
            // If none of the previous steps identify the generation algorithm, the test is omitted from the fingerprint.
            String::new()
        }
    } else {
        // and for II, both ICMP responses must be received.
        String::new()
    };
    Ok((ti, ci, ii))
}

/// Shared IP ID sequence Boolean (SS)
pub fn tcp_ss(seqrr: &SEQRR, ierr: &IERR, ti: &str, ii: &str) -> Result<String, PistolError> {
    let judge_value = |x: &str| -> bool {
        if x == "RI" || x == "BI" || x == "I" {
            true
        } else {
            false
        }
    };
    // This test is only included if II is RI, BI, or I and TI is the same.
    let c1 = judge_value(ii);
    let c2 = judge_value(ti);

    if c1 && c2 {
        let seq1_ip_id = get_ip_id(&seqrr.seq1.response, "seq1");
        let seq2_ip_id = get_ip_id(&seqrr.seq2.response, "seq2");
        let seq3_ip_id = get_ip_id(&seqrr.seq3.response, "seq3");
        let seq4_ip_id = get_ip_id(&seqrr.seq4.response, "seq4");
        let seq5_ip_id = get_ip_id(&seqrr.seq5.response, "seq5");
        let seq6_ip_id = get_ip_id(&seqrr.seq6.response, "seq6");
        let mut tmp_vec = Vec::new();
        tmp_vec.push(seq1_ip_id);
        tmp_vec.push(seq2_ip_id);
        tmp_vec.push(seq3_ip_id);
        tmp_vec.push(seq4_ip_id);
        tmp_vec.push(seq5_ip_id);
        tmp_vec.push(seq6_ip_id);

        let mut ip_id_vec = Vec::new();
        for i in tmp_vec {
            match i {
                Ok(i) => ip_id_vec.push(Some(i)),
                Err(e) => {
                    warn!("{}", e);
                    ip_id_vec.push(None) // need None value here to identified the localtion of specific value
                }
            }
        }

        let first_ip_id = |ip_id_vec: &[Option<u16>]| -> Option<(u16, usize)> {
            for (i, ip_id) in ip_id_vec.iter().enumerate() {
                match ip_id {
                    Some(ip_id) => return Some((*ip_id, i)),
                    None => (),
                }
            }
            None
        };
        let last_ip_id = |ip_id_vec: &[Option<u16>]| -> Option<(u16, usize)> {
            for (i, ip_id) in ip_id_vec.iter().rev().enumerate() {
                match ip_id {
                    Some(ip_id) => return Some((*ip_id, ip_id_vec.len() - i)),
                    None => (),
                }
            }
            None
        };

        let (seq_first_ip_id, first) = match first_ip_id(&ip_id_vec) {
            Some((s, f)) => (s, f),
            None => return Err(PistolError::CalcSSFailed),
        };

        let (seq_last_ip_id, last) = match last_ip_id(&ip_id_vec) {
            Some((s, f)) => (s, f),
            None => return Err(PistolError::CalcSSFailed),
        };

        if last <= first {
            return Ok(String::new());
        }

        let difference = if seq_last_ip_id > seq_first_ip_id {
            seq_last_ip_id - seq_first_ip_id
        } else {
            !(seq_first_ip_id - seq_last_ip_id)
        };

        let avg = difference as f64 / (last - first) as f64;
        let ie1_ip_id = get_ip_id(&ierr.ie1.response, "ie1");
        let ss = match ie1_ip_id {
            Ok(ie1_ip_id) => {
                // If the first ICMP echo response IP ID is less than the final TCP sequence response IP ID plus three times avg,
                // the SS result is S. Otherwise it is O.
                let temp_value = seq_last_ip_id as f64 + (3.0 * avg);
                let ss = if (ie1_ip_id as f64) < temp_value {
                    String::from("S")
                } else {
                    String::from("O")
                };
                ss
            }
            Err(e) => {
                warn!("{}", e);
                String::new()
            }
        };
        Ok(ss)
    } else {
        Ok(String::new())
    }
}

fn get_tsval(ipv4_response: &[u8], probe_name: &str) -> Result<u32, PistolError> {
    let ipv4_packet = build_ipv4_packet(ipv4_response, probe_name)?;
    let tcp_packet = build_tcp_packet(ipv4_packet.payload(), probe_name)?;
    let options_vec = tcp_packet.get_options();
    for option in options_vec {
        match option.number {
            TcpOptionNumbers::TIMESTAMPS => {
                // get first 4 u8 values
                if option.data.len() >= 4 {
                    let tsval_vec = option.data[0..4].to_vec();
                    let tsval = PistolHex::be_vec_to_u32(&tsval_vec)?;
                    return Ok(tsval);
                }
            }
            _ => (),
        }
    }
    Err(PistolError::TsValIsNull)
}

/// TCP timestamp option algorithm (TS)
pub fn tcp_ts(seqrr: &SEQRR) -> Result<String, PistolError> {
    let tsval_1 = get_tsval(&seqrr.seq1.response, "seq1");
    let tsval_2 = get_tsval(&seqrr.seq2.response, "seq2");
    let tsval_3 = get_tsval(&seqrr.seq3.response, "seq3");
    let tsval_4 = get_tsval(&seqrr.seq4.response, "seq4");
    let tsval_5 = get_tsval(&seqrr.seq5.response, "seq5");
    let tsval_6 = get_tsval(&seqrr.seq6.response, "seq6");
    let mut tmp_vec = Vec::new();
    tmp_vec.push(tsval_1);
    tmp_vec.push(tsval_2);
    tmp_vec.push(tsval_3);
    tmp_vec.push(tsval_4);
    tmp_vec.push(tsval_5);
    tmp_vec.push(tsval_6);

    let mut tsval_vec = Vec::new();
    for t in tmp_vec {
        match t {
            Ok(t) => tsval_vec.push(t),
            Err(e) => warn!("{}", e),
        }
    }

    let mut one_tsval_zero = false;
    for tsval in &tsval_vec {
        if *tsval == 0 {
            one_tsval_zero = true;
        }
    }

    let ts = if tsval_vec.len() == 0 {
        // If any of the responses have no timestamp option, TS is set to U (unsupported).
        String::from("U")
    } else if one_tsval_zero {
        // If any of the timestamp values are zero, TS is set to 0.
        String::from("0")
    } else {
        let diff = get_diff_u32(&tsval_vec);
        let ts = if diff.len() > 0 {
            let mut sum = 0.0;
            for d in &diff {
                // It takes the difference between each consecutive TSval
                // and divides that by the amount of time elapsed between Nmap sending the two probes which generated those responses.
                sum += *d as f64 / 0.1;
            }
            let avg = sum / diff.len() as f64;

            // If the average increments per second falls within the ranges 0-5.66, 70-150, or 150-350, TS is set to 1, 7, or 8, respectively.
            // These three ranges get special treatment because they correspond to the 2 Hz, 100 Hz, and 200 Hz frequencies used by many hosts.
            let ts = if avg > 0.0 && avg <= 5.66 {
                String::from("1")
            } else if avg > 70.0 && avg <= 150.0 {
                String::from("7")
            } else if avg > 150.0 && avg <= 350.0 {
                String::from("8")
            } else {
                // In all other cases, Nmap records the binary logarithm of the average increments per second, rounded to the nearest integer.
                // Since most hosts use 1,000 Hz frequencies, A is a common result.
                // A(hex)=10(dec), log_2(1024)=10
                let a = avg.log2().round() as u64;
                let hex_str = format!("{:X}", a);
                hex_str
            };
            ts
        } else {
            String::new()
        };
        ts
    };
    Ok(ts)
}

/// TCP options (O, O1–O6)
pub fn tcp_o(ipv4_response: &[u8], probe_name: &str) -> Result<String, PistolError> {
    let ipv4_packet = build_ipv4_packet(ipv4_response, probe_name)?;
    let tcp_packet = build_tcp_packet(ipv4_packet.payload(), probe_name)?;
    let options_vec = tcp_packet.get_options();
    let mut o_ret = String::new();
    for option in options_vec {
        match option.number {
            TcpOptionNumbers::MSS => {
                let data = if option.data.len() > 4 {
                    &option.data[0..4]
                } else {
                    &option.data
                };
                let mss = PistolHex::be_vec_to_u32(data)?;
                let o_str = format!("M{:X}", mss);
                o_ret += &o_str;
            }
            TcpOptionNumbers::SACK_PERMITTED => {
                o_ret += "S";
            }
            TcpOptionNumbers::EOL => {
                o_ret += "L";
            }
            TcpOptionNumbers::NOP => {
                o_ret += "N";
            }
            TcpOptionNumbers::WSCALE => {
                let data = if option.data.len() > 4 {
                    &option.data[0..4]
                } else {
                    &option.data
                };
                let wscale = PistolHex::be_vec_to_u32(data)?;
                let o_str = format!("W{:X}", wscale);
                o_ret += &o_str;
            }
            TcpOptionNumbers::TIMESTAMPS => {
                o_ret += "T";
                let t0 = if option.data.len() > 0 {
                    if option.data.len() >= 4 {
                        option.data[0..4].to_vec()
                    } else {
                        option.data[0..option.data.len() - 1].to_vec()
                    }
                } else {
                    vec![0; 4]
                };

                let t1 = if option.data.len() > 4 {
                    if option.data.len() >= 8 {
                        option.data[4..8].to_vec()
                    } else {
                        option.data[4..option.data.len() - 1].to_vec()
                    }
                } else {
                    vec![0; 4]
                };

                let t0_u32 = PistolHex::be_vec_to_u32(&t0)?;
                let t1_u32 = PistolHex::be_vec_to_u32(&t1)?;
                if t0_u32 == 0 {
                    o_ret += "0";
                } else {
                    o_ret += "1";
                }
                if t1_u32 == 0 {
                    o_ret += "0";
                } else {
                    o_ret += "1";
                }
            }
            _ => (),
        }
    }
    return Ok(o_ret);
}

/// TCP options (O, O1–O6)
pub fn tcp_ox(
    seqrr: &SEQRR,
) -> Result<(String, String, String, String, String, String), PistolError> {
    let o1 = tcp_o(&seqrr.seq1.response, "seq1")?;
    let o2 = tcp_o(&seqrr.seq2.response, "seq2")?;
    let o3 = tcp_o(&seqrr.seq3.response, "seq3")?;
    let o4 = tcp_o(&seqrr.seq4.response, "seq4")?;
    let o5 = tcp_o(&seqrr.seq5.response, "seq5")?;
    let o6 = tcp_o(&seqrr.seq6.response, "seq6")?;
    Ok((o1, o2, o3, o4, o5, o6))
}

/// TCP initial window size (W, W1–W6)
pub fn tcp_w(ipv4_response: &[u8], probe_name: &str) -> Result<u16, PistolError> {
    let ipv4_packet = build_ipv4_packet(ipv4_response, probe_name)?;
    let tcp_packet = build_tcp_packet(ipv4_packet.payload(), probe_name)?;
    let window = tcp_packet.get_window();
    Ok(window)
}

/// TCP initial window size (W, W1–W6)
pub fn tcp_wx(seqrr: &SEQRR) -> Result<(u16, u16, u16, u16, u16, u16), PistolError> {
    let w1 = tcp_w(&seqrr.seq1.response, "seq1")?;
    let w2 = tcp_w(&seqrr.seq2.response, "seq2")?;
    let w3 = tcp_w(&seqrr.seq3.response, "seq3")?;
    let w4 = tcp_w(&seqrr.seq4.response, "seq4")?;
    let w5 = tcp_w(&seqrr.seq5.response, "seq5")?;
    let w6 = tcp_w(&seqrr.seq6.response, "seq6")?;
    Ok((w1, w2, w3, w4, w5, w6))
}

/// Responsiveness (R)
pub fn tcp_udp_icmp_r(ipv4_response: &[u8]) -> Result<String, PistolError> {
    match ipv4_response.len() {
        0 => Ok(String::from("N")),
        _ => Ok(String::from("Y")),
    }
}

/// IP don't fragment bit (DF)
pub fn tcp_udp_df(ipv4_response: &[u8], probe_name: &str) -> Result<String, PistolError> {
    let ipv4_packet = build_ipv4_packet(ipv4_response, probe_name)?;
    let ipv4_flags = ipv4_packet.get_flags();
    let df_mask: u8 = 0b0010;
    let ret = if (ipv4_flags & df_mask) != 0 {
        String::from("Y")
    } else {
        String::from("N")
    };
    Ok(ret)
}

fn udp_hops(u1rr: &U1RR, probe_name: &str) -> Result<Option<u8>, PistolError> {
    let request = build_ipv4_packet(&u1rr.u1.request, probe_name)?; // must have request
    match build_ipv4_packet(&u1rr.u1.response, probe_name) {
        Ok(ipv4_packet) => {
            let icmp_packet = build_icmp_packet(ipv4_packet.payload(), probe_name)?;
            let r_ipv4_buff = icmp_packet.payload()[4..].to_vec();
            let r_ipv4_packet = build_ipv4_packet(&r_ipv4_buff, probe_name)?;
            let ttl_1 = request.get_ttl();
            let ttl_2 = r_ipv4_packet.get_ttl();
            let hops = ttl_1 - ttl_2;
            // It is not uncommon for Nmap to receive no response to the U1 probe.
            Ok(Some(hops))
        }
        Err(e) => {
            // It is common for Nmap to receive no response when target is Windows.
            warn!("udp hops calc failed: {}", e);
            Ok(None)
        }
    }
}

/// IP initial time-to-live (T)
pub fn tcp_udp_icmp_t(
    ipv4_response: &[u8],
    u1rr: &U1RR,
    probe_name: &str,
) -> Result<Option<u16>, PistolError> {
    let hops = udp_hops(u1rr, probe_name)?;
    match hops {
        Some(hops) => {
            let ipv4_packet = build_ipv4_packet(ipv4_response, probe_name)?;
            let ipv4_ttl = ipv4_packet.get_ttl();
            // avoid overflow in integer addition
            Ok(Some(hops as u16 + ipv4_ttl as u16))
        }
        None => Ok(None), // no udp return, ignore t and use tg instead
    }
}

/// IP initial time-to-live guess (TG)
pub fn tcp_udp_icmp_tg(ipv4_response: &[u8], probe_name: &str) -> Result<u16, PistolError> {
    let ipv4_packet = build_ipv4_packet(ipv4_response, probe_name)?;
    let ipv4_ttl = ipv4_packet.get_ttl() as u16;

    let er_lim = 5;
    let regual_ttl_vec = vec![32, 64, 128, 255];
    let mut guess_value = 0;

    for r in regual_ttl_vec {
        if ipv4_ttl > r {
            if ipv4_ttl - r <= er_lim {
                guess_value = r;
            }
        } else {
            if r - ipv4_ttl <= er_lim {
                guess_value = r;
            }
        }
    }

    if guess_value != 0 {
        Ok(guess_value)
    } else {
        // take the observed value
        Ok(ipv4_ttl)
    }
}

/// Explicit congestion notification (CC)
pub fn tcp_cc(ipv4_response: &[u8], probe_name: &str) -> Result<String, PistolError> {
    let ipv4_packet = build_ipv4_packet(ipv4_response, probe_name)?;
    let tcp_packet = build_tcp_packet(ipv4_packet.payload(), probe_name)?;
    let tcp_flag = tcp_packet.get_flags();
    let ret = if (tcp_flag & ECE_MASK != 0) && (tcp_flag & CWR_MASK == 0) {
        // Only the ECE bit is set (not CWR). This host supports ECN.
        String::from("Y")
    } else if (tcp_flag & CWR_MASK == 0) && (tcp_flag & ECE_MASK == 0) {
        // Neither of these two bits is set. The target does not support ECN.
        String::from("N")
    } else if (tcp_flag & CWR_MASK != 0) && (tcp_flag & ECE_MASK != 0) {
        // Both bits are set. The target does not support ECN, but it echoes back what it thinks is a reserved bit.
        String::from("S")
    } else {
        // The one remaining combination of these two bits (other).
        String::from("O")
    };
    Ok(ret)
}

/// TCP miscellaneous quirks (Q)
pub fn tcp_q(ipv4_response: &[u8], probe_name: &str) -> Result<String, PistolError> {
    let ipv4_packet = build_ipv4_packet(ipv4_response, probe_name)?;
    let tcp_packet = build_tcp_packet(ipv4_packet.payload(), probe_name)?;
    let mut ret = String::new();
    let tcp_reserved = tcp_packet.get_reserved();
    if tcp_reserved != 0 {
        // The first is that the reserved field in the TCP header (right after the header length) is nonzero.
        // This is particularly likely to happen in response to the ECN test as that one sets a reserved bit in the probe.
        // If this is seen in a packet, an "R" is recorded in the Q string.
        ret += "R"
    }
    if tcp_packet.get_urgent_ptr() != 0 {
        // The other quirk Nmap tests for is a nonzero urgent pointer field value when the URG flag is not set.
        // This is also particularly likely to be seen in response to the ECN probe, which sets a non-zero urgent field.
        // A "U" is appended to the Q string when this is seen.
        ret += "U"
    }
    Ok(ret)
}

/// TCP sequence number (S)
pub fn tcp_s(
    ipv4_request: &[u8],
    ipv4_response: &[u8],
    probe_name: &str,
) -> Result<String, PistolError> {
    let ipv4_packet_request = build_ipv4_packet(ipv4_request, probe_name)?; // must have
    let tcp_packet_request = build_tcp_packet(ipv4_packet_request.payload(), probe_name)?; // must have

    let ipv4_packet_response = build_ipv4_packet(ipv4_response, probe_name)?;
    let tcp_packet_response = build_tcp_packet(ipv4_packet_response.payload(), probe_name)?;
    let ack_request = tcp_packet_request.get_acknowledgement();
    let seq_response = tcp_packet_response.get_sequence();
    let ret = if seq_response == 0 {
        // Sequence number is zero.
        String::from("Z")
    } else if seq_response == ack_request {
        // Sequence number is the same as the acknowledgment number in the probe.
        String::from("A")
    } else if seq_response == (ack_request + 1) {
        // Sequence number is the same as the acknowledgment number in the probe plus one.
        String::from("A+")
    } else {
        // Sequence number is something else (other).
        String::from("O")
    };
    Ok(ret)
}

/// TCP acknowledgment number (A)
pub fn tcp_a(
    ipv4_request: &[u8],
    ipv4_response: &[u8],
    probe_name: &str,
) -> Result<String, PistolError> {
    let ipv4_packet_request = build_ipv4_packet(ipv4_request, probe_name)?; // must have
    let tcp_packet_request = build_tcp_packet(ipv4_packet_request.payload(), probe_name)?; // must have

    let ipv4_packet_response = build_ipv4_packet(ipv4_response, probe_name)?;
    let tcp_packet_response = build_tcp_packet(ipv4_packet_response.payload(), probe_name)?;
    let seq_request = tcp_packet_request.get_sequence();
    let ack_response = tcp_packet_response.get_acknowledgement();
    let ret = if ack_response == 0 {
        // Acknowledgment number is zero.
        String::from("Z")
    } else if ack_response == seq_request {
        // Acknowledgment number is the same as the sequence number in the probe.
        String::from("S")
    } else if ack_response == (seq_request + 1) {
        // Acknowledgment number is the same as the sequence number in the probe plus one.
        String::from("S+")
    } else {
        // Acknowledgment number is something else (other).
        String::from("O")
    };
    Ok(ret)
}

/// TCP flags (F)
pub fn tcp_f(ipv4_response: &[u8], probe_name: &str) -> Result<String, PistolError> {
    let ipv4_packet = build_ipv4_packet(ipv4_response, probe_name)?;
    let tcp_packet = build_tcp_packet(ipv4_packet.payload(), probe_name)?;
    let tcp_flag = tcp_packet.get_flags();
    let mut ret = String::new();
    if tcp_flag & ECE_MASK != 0 {
        // ECN Echo (ECE)
        ret += "E";
    }
    if tcp_flag & URG_MASK != 0 {
        // Urgent Data (URG)
        ret += "U";
    }
    if tcp_flag & ACK_MASK != 0 {
        // Acknowledgment (ACK)
        ret += "A";
    }
    if tcp_flag & PSH_MASK != 0 {
        // Push (PSH)
        ret += "P";
    }
    if tcp_flag & RST_MASK != 0 {
        // Reset (RST)
        ret += "R";
    }
    if tcp_flag & SYN_MASK != 0 {
        // Synchronize (SYN)
        ret += "S";
    }
    if tcp_flag & FIN_MASK != 0 {
        // Final (FIN)
        ret += "F";
    }
    Ok(ret)
}

/// TCP RST data checksum (RD)
pub fn tcp_rd(ipv4_response: &[u8], probe_name: &str) -> Result<u32, PistolError> {
    let ipv4_packet = build_ipv4_packet(ipv4_response, probe_name)?;
    let tcp_packet = build_tcp_packet(ipv4_packet.payload(), probe_name)?;
    let tcp_payload = tcp_packet.payload();
    Ok(crc32fast::hash(tcp_payload))
}

/// IP total length (IPL)
pub fn udp_ipl(u1: &U1RR) -> Result<usize, PistolError> {
    let response = &u1.u1.response;
    Ok(response.len())
}

/// Unused port unreachable field nonzero (UN)
pub fn udp_un(u1: &U1RR, probe_name: &str) -> Result<u32, PistolError> {
    let response = &u1.u1.response;
    let ipv4_packet = build_ipv4_packet(response, probe_name)?;
    let icmp_packet = ipv4_packet.payload().to_vec();
    if icmp_packet.len() > 4 {
        let rest_of_header = if icmp_packet.len() >= 8 {
            icmp_packet[4..8].to_vec()
        } else {
            icmp_packet[4..icmp_packet.len() - 1].to_vec()
        };
        let un = PistolHex::be_vec_to_u32(&rest_of_header)?;
        Ok(un)
    } else {
        Err(PistolError::CalcUNFailed)
    }
}

/// Returned probe IP total length value (RIPL)
pub fn udp_ripl(u1: &U1RR, probe_name: &str) -> Result<String, PistolError> {
    let response = &u1.u1.response;
    let ipv4_packet = build_ipv4_packet(response, probe_name)?;
    let icmp_packet = build_icmp_packet(ipv4_packet.payload(), probe_name)?;
    let ripl = icmp_packet.payload().len() - 4;
    let ret = if ripl == 328 {
        // If the correct value of 0x148 (328) is returned, the value G (for good) is stored instead of the actual value.
        String::from("G")
    } else {
        format!("{:X}", ripl)
    };
    Ok(ret)
}

/// Returned probe IP ID value (RID)
pub fn udp_rid(u1: &U1RR, probe_name: &str) -> Result<String, PistolError> {
    let response = &u1.u1.response;
    let ipv4_packet = build_ipv4_packet(response, probe_name)?;
    let icmp_packet = build_icmp_packet(ipv4_packet.payload(), probe_name)?;
    let r_ipv4_packet = build_ipv4_packet(&icmp_packet.payload()[4..], probe_name)?;
    let rid = r_ipv4_packet.get_identification();
    let ret = if rid == 0x1042 {
        // The U1 probe has a static IP ID value of 0x1042.
        // If that value is returned in the port unreachable message, the value G is stored for this test.
        String::from("G")
    } else {
        format!("{:X}", rid)
    };
    Ok(ret)
}

/// Integrity of returned probe IP checksum value (RIPCK)
pub fn udp_ripck(u1: &U1RR, probe_name: &str) -> Result<String, PistolError> {
    let response = &u1.u1.response;
    let ipv4_packet = build_ipv4_packet(response, probe_name)?;
    let o_checksum = ipv4_packet.get_checksum();
    let t_checksum = ipv4::checksum(&ipv4_packet.to_immutable());
    let ret = if o_checksum == t_checksum {
        // However, the checksum we receive should match the enclosing IP packet.
        // If it does, the value G (good) is stored for this test.
        String::from("G")
    } else if o_checksum == 0 {
        // If the returned value is zero, then Z is stored.
        String::from("Z")
    } else {
        // Otherwise the result is I (invalid).
        String::from("I")
    };
    Ok(ret)
}

/// Integrity of returned probe UDP checksum (RUCK)
pub fn udp_ruck(u1: &U1RR, probe_name: &str) -> Result<String, PistolError> {
    let request = &u1.u1.request;
    let response = &u1.u1.response;

    let ipv4_packet_request = build_ipv4_packet(request, probe_name)?; // must have
    let udp_packet_request = build_udp_packet(ipv4_packet_request.payload(), probe_name)?; // must have
    let checksum_request = udp_packet_request.get_checksum();

    let ipv4_packet_response = build_ipv4_packet(response, probe_name)?;
    let icmp_packet_response = build_icmp_packet(ipv4_packet_response.payload(), probe_name)?;
    let r_ipv4_packet_response =
        build_ipv4_packet(&icmp_packet_response.payload()[4..], probe_name)?;
    let udp_packet_response = build_udp_packet(r_ipv4_packet_response.payload(), probe_name)?;
    let checksum_response = udp_packet_response.get_checksum();
    let ret = if checksum_response == checksum_request {
        // The UDP header checksum value should be returned exactly as it was sent.
        // If it is, G is recorded for this test. Otherwise the value actually returned is recorded.
        String::from("G")
    } else {
        format!("{:X}", checksum_response)
    };
    Ok(ret)
}

/// Integrity of returned UDP data (RUD)
pub fn udp_rud(u1: &U1RR, probe_name: &str) -> Result<String, PistolError> {
    let response = &u1.u1.response;
    let ipv4_packet_response = build_ipv4_packet(response, probe_name)?;
    let icmp_packet_response = build_icmp_packet(ipv4_packet_response.payload(), probe_name)?;
    let r_ipv4_packet_response =
        build_ipv4_packet(&icmp_packet_response.payload()[4..], probe_name)?;
    let r_udp_packet_response = build_udp_packet(&r_ipv4_packet_response.payload(), probe_name)?;
    let payload_c_judge = |payload: &[u8]| -> bool {
        for p in payload {
            if *p != 0x43 {
                return false;
            }
        }
        true
    };
    let c = payload_c_judge(r_udp_packet_response.payload());
    let ret = if c || r_udp_packet_response.payload().len() == 0 {
        // This test checks the integrity of the (possibly truncated) returned UDP payload.
        // If all the payload bytes are the expected 'C' (0x43), or if the payload was truncated to zero length, G is recorded;
        String::from("G")
    } else {
        // Otherwise, I (invalid) is recorded.
        String::from("I")
    };
    Ok(ret)
}

/// Don't fragment (ICMP) (DFI)
pub fn icmp_dfi(ie: &IERR, probe_name: &str) -> Result<String, PistolError> {
    let df_mask: u8 = 0b0010;

    let request_1 = &ie.ie1.request;
    let request_2 = &ie.ie2.request;
    let response_1 = &ie.ie1.response;
    let response_2 = &ie.ie2.response;

    let ipv4_packet_1 = build_ipv4_packet(request_1, probe_name)?;
    let flag_1 = ipv4_packet_1.get_flags();
    let df_1_set = if flag_1 & df_mask != 0 { true } else { false };

    let ipv4_packet_2 = build_ipv4_packet(request_2, probe_name)?;
    let flag_2 = ipv4_packet_2.get_flags();
    let df_2_set = if flag_2 & df_mask != 0 { true } else { false };

    let ipv4_packet_3 = build_ipv4_packet(response_1, probe_name)?;
    let flag_3 = ipv4_packet_3.get_flags();
    let df_3_set = if flag_3 & df_mask != 0 { true } else { false };

    let ipv4_packet_4 = build_ipv4_packet(response_2, probe_name)?;
    let flag_4 = ipv4_packet_4.get_flags();
    let df_4_set = if flag_4 & df_mask != 0 { true } else { false };

    let ret = if !df_3_set && !df_4_set {
        // Neither of the ping responses have the DF bit set.
        String::from("N")
    } else if (df_1_set == df_3_set) && (df_2_set == df_4_set) {
        // Both responses echo the DF value of the probe.
        String::from("S")
    } else if df_3_set && df_4_set {
        // 	Both of the response DF bits are set.
        String::from("Y")
    } else {
        String::from("O")
    };
    Ok(ret)
}

/// ICMP response code (CD)
pub fn icmp_cd(ie: &IERR, probe_name: &str) -> Result<String, PistolError> {
    let request_1 = &ie.ie1.request;
    let request_2 = &ie.ie2.request;
    let response_1 = &ie.ie1.response;
    let response_2 = &ie.ie2.response;

    if response_1.len() > 0 && response_2.len() > 0 {
        let ipv4_packet_1 = build_ipv4_packet(&request_1, probe_name)?;
        let icmp_packet_1 = build_icmp_packet(ipv4_packet_1.payload(), probe_name)?;
        let ipv4_packet_2 = build_ipv4_packet(&request_2, probe_name)?;
        let icmp_packet_2 = build_icmp_packet(ipv4_packet_2.payload(), probe_name)?;
        let code_1 = icmp_packet_1.get_icmp_code();
        let code_2 = icmp_packet_2.get_icmp_code();

        let ipv4_packet_3 = build_ipv4_packet(&response_1, probe_name)?;
        let icmp_packet_3 = build_icmp_packet(ipv4_packet_3.payload(), probe_name)?;
        let ipv4_packet_4 = build_ipv4_packet(&response_2, probe_name)?;
        let icmp_packet_4 = build_icmp_packet(ipv4_packet_4.payload(), probe_name)?;
        let code_3 = icmp_packet_3.get_icmp_code();
        let code_4 = icmp_packet_4.get_icmp_code();

        let ret = if (code_3 == IcmpCode(0)) && (code_4 == IcmpCode(0)) {
            // Both code values are zero.
            String::from("Z")
        } else if (code_1 == code_3) && (code_2 == code_4) {
            // Both code values are the same as in the corresponding probe.
            String::from("S")
        } else if code_3 == code_4 {
            // When they both use the same non-zero number, it is shown here.
            format!("{:X}", code_3.0)
        } else {
            String::from("O")
        };
        Ok(ret)
    } else {
        Ok(String::new())
    }
}