get-cve 1.5.8

Tools for CVE managing, exploring and collect some data about their weaknesses and classifications
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
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
#![deny(clippy::mem_forget)]

use ascii_table_rs::{AsciiTable, CellValue};
use fenir::cpe::Cpe;
use fenir::cve::{create_cve_from, cve_from_cwe, Cve, Score};
use fenir::cwe::show_weaknesses;
use fenir::database::{
    execute_query, find_capec_by_id, find_cwe_by_id, parse_id_to_u32, MitreDefinition,
};
use fenir::facilities::{
    build_dates_range, print_values, Reduce, FIELD_SEPARATOR_STRING, FIELD_SEPARATOR_STRING_LONG,
};
use fenir::facilities::{Cleaning, Uppercase, Wording};
use fenir::network::{check_mitre_data, check_nvd_api_key, check_nvd_api_key_warning};
use fenir::package::concepts::{filtering_cve, print_cve, simplify_list_content};
use fenir::package::errors::{write_error_message, write_error_message_and_exit};
use fenir::query::QueryType::{
    ByCpeVulnerable, ByCve, ByCveCpeName, ByCveExploited, ByCveNew, ByCveUpdated, ByCwe,
};
use fenir::query::{build_query, create_query_dates, QueryType};
use fenir::{header, section, section_level, show_version};
use serde_json::Value;
use serde_json::Value::Null;
use std::io::stdout;
use std::process::exit;
use termint::enums::Color;
use termint::widgets::ToSpan;
use treelog::builder::TreeBuilder;

#[cfg(target_os = "linux")]
use crate::package::{get_changelog_for, get_package};

#[cfg(target_os = "linux")]
use fenir::os::{OSFamily, SupportedOs};

#[cfg(target_os = "linux")]
use fenir::package::concepts::show_cve_list;

#[cfg(target_os = "linux")]
use fenir::package::concepts::Changelog;

#[cfg(target_os = "linux")]
use fenir::package::errors::stop_if_invalid_package;

/// Packages management according ot supported os.
#[cfg(target_os = "linux")]
mod package {
    use crate::package::os::{Debian, RedHat};
    use core::str;
    use fenir::facilities::{restore_current_dir_and_remove_temp_dir, show_command_result};
    use fenir::os::{OSFamily, SupportedOs};
    use fenir::package::concepts::{
        changelog_result, default_package, Package, PackageStatus, Repository, Request,
    };
    use fenir::package::errors::{write_error_message, write_error_message_and_exit};
    use std::env;
    use std::fs::File;
    use std::io::{BufReader, Read};
    use std::path::Path;
    use std::process::{Child, Output, Stdio};
    use std::string::FromUtf8Error;

    /// Module for OS detection and representation.
    pub mod os {
        /// Represents a Debian-based system
        pub struct Debian;

        /// Represents a RedHat-based system.
        pub struct RedHat;
    }

    impl Request for Debian {
        fn ask_package(&self, package: &str, version: &str) -> Package {
            let command_output: Result<String, FromUtf8Error> = if version.is_empty() {
                let command_result = std::process::Command::new("/usr/bin/dpkg-query")
                    .arg("-W")
                    .arg(package)
                    .stderr(Stdio::null())
                    .output()
                    .expect("Fail to run dpkg-query command");

                show_command_result(command_result)
            } else if version.eq("next") {
                let command_result = std::process::Command::new("/usr/bin/apt")
                    .arg("list")
                    .arg("--upgradable")
                    .arg(package)
                    .arg("-qq")
                    .stderr(Stdio::null())
                    .output()
                    .expect("Fail to run apt-get list");

                show_command_result(command_result)
            } else {
                let cmd_package = std::process::Command::new("/usr/bin/dpkg-query")
                    .arg("-W")
                    .arg(package)
                    .stderr(Stdio::null())
                    .stdout(Stdio::piped())
                    .spawn()
                    .unwrap();

                let cmd_version = grep_version(version, cmd_package);

                show_command_result(cmd_version)
            };

            extract_package_result(command_output)
        }

        fn ask_changelog_package(&self, package: Package) -> String {
            let changelog_command = std::process::Command::new("/usr/bin/apt")
                .args([
                    "changelog",
                    format!("{}={}", package.name, package.version).as_str(),
                ])
                .stderr(Stdio::null())
                .output()
                .expect("Fail to run apt command");

            changelog_result(
                package.clone(),
                changelog_command,
                self.read_changelog_files(package.clone()),
            )
        }

        fn read_changelog_files(&self, package: Package) -> String {
            let changelog_file = match get_debian_changelog_for("/usr/share/doc", &package) {
                Ok(file) => file,
                Err(err) => {
                    write_error_message(package.name.as_str(), Some(err));
                    return String::new();
                }
            };

            let result = decode_changelog(changelog_file);
            result.unwrap_or_else(|_| String::new())
        }
    }

    /// Decodes a gzipped Debian changelog file and returns its content as a string.
    ///
    /// # Arguments
    ///
    /// * `file` - A `File` handle to the gzipped changelog file.
    ///
    /// # Returns
    ///
    /// This function returns a `Result` which is:
    /// * `Ok(String)` containing the changelog content if the file was successfully
    ///   decoded and read.
    /// * `Err(&'static str)` with an error message if the file could not be read.
    ///
    /// # Errors
    ///
    /// This function will return an error if:
    /// * The gzipped changelog file cannot be decompressed.
    /// * The changelog file cannot be read or parsed.
    ///
    /// # Side Effects
    ///
    /// * Attempts to remove the directory at `/var/tmp/get-cve`.
    ///
    fn decode_changelog(file: File) -> Result<String, &'static str> {
        let gz_decoder = flate2::read::GzDecoder::new(BufReader::new(file));
        match debian_changelog::ChangeLog::read(BufReader::new(gz_decoder)) {
            Ok(changelog) => {
                let _ = std::fs::remove_dir_all("/var/tmp/get-cve");
                Ok(changelog.to_string())
            }
            _ => Err("Failed for changelog reading"),
        }
    }

    impl Request for RedHat {
        fn ask_package(&self, package: &str, version: &str) -> Package {
            let command_output: Result<String, FromUtf8Error> = if version.is_empty() {
                let command_result = std::process::Command::new("/usr/bin/rpm")
                    .arg("-qa")
                    .arg("--qf")
                    .arg("%{NAME}.%{ARCH}\t%{VERSION}-%{RELEASE}")
                    .arg(package)
                    .stderr(Stdio::null())
                    .output()
                    .expect("Error on rpm command running");

                show_command_result(command_result)
            } else {
                let command_result = std::process::Command::new("/usr/bin/rpm")
                    .arg("-qa")
                    .arg("--qf")
                    .arg("%{NAME}.%{ARCH}\t%{VERSION}-%{RELEASE}")
                    .arg(package)
                    .stderr(Stdio::null())
                    .stdout(Stdio::piped())
                    .spawn()
                    .expect("Error on rpm command running");

                let grep_result = grep_version(version, command_result);
                show_command_result(grep_result)
            };

            extract_package_result(command_output)
        }

        fn ask_changelog_package(&self, package: Package) -> String {
            let changelog_command = std::process::Command::new("/usr/bin/rpm")
                .arg("-q")
                .arg("--changelog")
                .arg(package.name.as_str())
                .stderr(Stdio::null())
                .output()
                .expect("Impossible to run rpm command for changelog");

            changelog_result(
                package.clone(),
                changelog_command,
                self.read_changelog_files(package.clone()),
            )
        }

        fn read_changelog_files(&self, package: Package) -> String {
            let package_name = extract_package_name(&package.name);
            let changelog_path = format!("/usr/share/doc/{}", package_name);

            match get_changelog_files(changelog_path) {
                Some(changelog_files) => merge_files_content(changelog_files),
                _ => String::new(),
            }
        }
    }

    /// Extracts the base package name from a given package name string.
    ///
    /// This function takes a package name string and returns the base package name.
    /// If the input package name contains a '.', the function will split the string
    /// at the first '.' and return the portion before the '.'; otherwise, it returns
    /// the entire input package name.
    ///
    /// # Arguments
    ///
    /// * `pkg_name` - A string slice that holds the package name.
    ///
    /// # Returns
    ///
    /// A `String` containing the base package name.
    ///
    fn extract_package_name(pkg_name: &str) -> String {
        if pkg_name.contains('.') {
            pkg_name.split('.').next().unwrap().to_string()
        } else {
            pkg_name.to_string()
        }
    }

    /// Retrieves a list of changelog files from the specified directory.
    ///
    /// # Arguments
    ///
    /// * `directory` - A string slice that holds the path to the directory containing changelog files.
    ///
    /// # Returns
    ///
    /// * `Result<Vec<String>, std::io::Error>` - A Result containing either:
    ///   - A Vec of strings, where each string is the path to a changelog file
    ///   - Or an `std::io::Error` if an error occurred during file reading
    ///
    fn get_changelog_files<P: AsRef<Path>>(path: P) -> Option<Vec<std::fs::DirEntry>> {
        let dir = std::fs::read_dir(path).ok()?;
        Some(dir.flatten().collect())
    }

    /// Merges the content of multiple files into a single string.
    ///
    /// This function takes a vector of `std::fs::DirEntry` objects representing file entries, reads
    /// their content, and concatenates it into a single string. Files that cannot be read are
    /// skipped.
    ///
    /// # Arguments
    ///
    /// * `files` - A vector of `std::fs::DirEntry` objects representing the files to be read.
    ///
    /// # Returns
    ///
    /// A `String` containing the concatenated content of all the files that were successfully read.
    ///
    ///
    /// Note: The function assumes that the files contain UTF-8 encoded text.
    fn merge_files_content(files: Vec<std::fs::DirEntry>) -> String {
        files
            .iter()
            .filter_map(|file| {
                let path = file.path();
                if path.is_file() {
                    let file = File::open(&path).ok()?;
                    let mut buffer = BufReader::new(file);
                    let mut content = String::new();
                    buffer.read_to_string(&mut content).ok()?;
                    Some(content)
                } else {
                    None
                }
            })
            .collect::<String>()
    }

    /// Retrieves a software package with an optional version.
    ///
    /// # Arguments
    ///
    /// * `argument` - A string representing the package name.
    /// * `version` - An optional string representing the version of the package.
    ///
    /// # Returns
    ///
    /// * `Package` - A struct representing the retrieved package, including its name, version, and status.
    pub fn get_package(argument: String, version: Option<String>) -> Package {
        if SupportedOs::supported_os() == OSFamily::Debian {
            let repository = Repository { repos: Debian };
            Request::ask_package(
                &repository.repos,
                argument.as_str(),
                version.unwrap_or_default().as_str(),
            )
        } else if SupportedOs::supported_os() == OSFamily::RedHat {
            let repository = Repository { repos: RedHat };
            Request::ask_package(
                &repository.repos,
                argument.as_str(),
                version.unwrap_or_default().as_str(),
            )
        } else {
            default_package()
        }
    }

    /// Retrieves the changelog content for the specified package.
    ///
    /// # Arguments
    ///
    /// * `package` - A reference to a `Package` struct representing the package for which the changelog is being requested.
    ///
    /// # Returns
    ///
    /// Returns a `String` containing the changelog content for the specified package.
    pub fn get_changelog_for(package: &Package) -> String {
        if SupportedOs::supported_os() == OSFamily::Debian {
            let repository = Repository { repos: Debian };
            Request::ask_changelog_package(&repository.repos, package.clone())
        } else {
            let repository = Repository { repos: RedHat };
            Request::ask_changelog_package(&repository.repos, package.clone())
        }
    }

    /// Retrieves the Debian changelog for a given package.
    ///
    /// This function fetches the changelog of a Debian package, parses it, and
    /// returns it in a readable format.
    ///
    /// # Arguments
    ///
    /// * `path` - A `str` that corresponding to the changelog file to explore.
    /// * `package` - A `Package` that holds the name of the Debian package.
    ///
    /// # Returns
    ///
    /// This function returns a `Result`:
    /// * `Ok(String)` - The contents of the Debian changelog.
    /// * `Err(String)` - An error message if the changelog could not be retrieved.
    ///
    /// # Errors
    ///
    /// This function returns an error if the package name is not valid,
    /// the changelog is not available, or if there is a network failure.
    fn get_debian_changelog_for(path: &str, package: &Package) -> Result<File, &'static str> {
        match package.status {
            PackageStatus::Uninstalled => get_next_changelog_file(&mut package.clone()),
            _ => {
                let changelogs = [
                    format!("{}/{}/changelog.Debian.gz", path, package.name),
                    format!("{}/{}/changelog.gz", path, package.name),
                ];

                let mut idx = 0usize;
                let mut result = Err("No alternative changelog");
                while idx < changelogs.len() && result.is_err() {
                    let changelog = changelogs[idx].clone();
                    idx += 1;
                    result = match File::open(changelog) {
                        Ok(file) => Ok(file),
                        _ => Err("No alternative changelog"),
                    };
                }

                result
            }
        }
    }

    /// Retrieves the next changelog file for the given package.
    ///
    /// This function attempts to locate the next changelog file associated with
    /// the specified package. It queries the system for the appropriate file paths
    /// depending on the package's properties and its installation status. The
    /// resulting changelog file, if found, is returned as a `std::fs::File` object.
    ///
    /// With this function, the package will be downloaded and explore into an internal temp directory.
    /// So, according to package weight, the result can take a while during download.
    ///
    /// # Arguments
    ///
    /// * `package` - A reference to the `Package` struct, which contains information
    ///   about the software package, such as its name, version, and current status.
    ///
    /// # Returns
    ///
    /// This function returns a `Result<File, &'static str>` where:
    ///
    /// * `Ok(File)` - Contains the `File` object representing the changelog if found.
    /// * `Err(&'static str)` - Contains an error message if the changelog file could not be located.
    ///
    /// # Errors
    ///
    /// This function will return an error if the changelog file cannot be found for the given package.
    ///
    fn get_next_changelog_file(package: &mut Package) -> Result<File, &'static str> {
        let current_dir = env::current_dir();
        let current_dir_clone = env::current_dir();
        let _ = std::fs::create_dir("/var/tmp/get-cve");
        env::set_current_dir("/var/tmp/get-cve").expect("Error setting tmp directory");

        println!("Download {package}");

        let command_download = std::process::Command::new("/usr/bin/apt-get")
            .arg("download")
            .arg(package.name.as_str())
            .stderr(Stdio::null())
            .current_dir("/var/tmp/get-cve")
            .output()
            .expect("Error on apt-get command running");

        if command_download.status.success() {
            println!("Decompress {package}");
            let package_deb = glob::glob(format!("{}*.deb", package.name).as_str());
            if let Err(_item) = package_deb {
                restore_current_dir_and_remove_temp_dir(current_dir, "get-cve");
                write_error_message_and_exit(
                    "Error, problem on packages into temp \
                    directory",
                    None,
                );
            } else {
                let package_name = package_deb.unwrap().next().unwrap();
                let command_decompress = std::process::Command::new("/usr/bin/dpkg")
                    .current_dir("/var/tmp/get-cve/")
                    .arg("-x")
                    .arg(package_name.unwrap())
                    .arg(".")
                    .output()
                    .expect("Error on decompress command running");

                if !command_decompress.status.success() {
                    restore_current_dir_and_remove_temp_dir(current_dir_clone, "get-cve");
                    write_error_message_and_exit(
                        "Decompression error",
                        Option::from(
                            String::from_utf8(command_decompress.stderr)
                                .unwrap()
                                .as_str(),
                        ),
                    );
                } else {
                    println!("Search changelog for {package}");
                    package.status = PackageStatus::Installed;
                    return get_debian_changelog_for("/var/tmp/get-cve/usr/share/doc", package);
                }
            }
        }
        Err("Error on package download")
    }

    /// Extracts a `Package` instance from the output of a command.
    ///
    /// # Arguments
    ///
    /// * `command_output` - A `Result` containing the command output as a `String` or
    ///   a `FromUtf8Error` if the conversion from bytes to a string failed.
    ///
    /// # Returns
    ///
    /// * A `Package` instance that encapsulates information about a software package,
    ///   such as the package's name, version, and status.
    ///
    /// # Errors
    ///
    /// If the `command_output` is an `Err` variant, this function may handle it
    /// internally, possibly creating a `Package` with a default or error state.
    fn extract_package_result(command_output: Result<String, FromUtf8Error>) -> Package {
        let output_string = command_output.unwrap();
        if output_string.contains("upgradable") {
            let elements = output_string.split("/").collect::<Vec<&str>>();
            let version_elements = elements[1].split(' ').collect::<Vec<&str>>();

            Package {
                name: String::from(elements[0]),
                version: String::from(version_elements[1].trim()),
                status: PackageStatus::Uninstalled,
            }
        } else {
            let elements: Vec<&str> = output_string.as_str().split('\t').collect();
            if elements.len() < 2 {
                write_error_message_and_exit("Package not found", None);
                default_package()
            } else {
                Package {
                    name: String::from(elements[0]),
                    version: String::from(elements[1].trim()),
                    status: PackageStatus::Installed,
                }
            }
        }
    }

    /// Executes the `grep` command to search for an exact match of the given version string
    /// from the standard output of a previously executed command (pipe_package).
    ///
    /// # Arguments
    ///
    /// * `version` - A string slice that holds the version to search for.
    /// * `pipe_package` - A `Child` process whose standard output is used as the input for `grep`.
    ///
    /// # Returns
    ///
    /// * `Output` - The result of executing the `grep` command, containing the standard output,
    ///   standard error and the exit status of the process.
    ///
    /// # Panics
    ///
    /// This function will panic if the `grep` command fails to execute or if there is an error
    /// converting the `pipe_package`'s standard output into the standard input of the `grep` command.
    ///
    /// # Notes
    ///
    /// The `-w` flag in the `grep` command specifies that the search term must appear as a
    /// whole word. The `stderr` is silenced by redirecting to `/dev/null`.
    fn grep_version(version: &str, pipe_package: Child) -> Output {
        std::process::Command::new("/usr/bin/grep")
            .arg("-w")
            .arg(version)
            .stdin(Stdio::from(pipe_package.stdout.unwrap()))
            .stderr(Stdio::null())
            .output()
            .expect("Error on grep on version")
    }
}

trait CvssColor {
    fn cvss_color(&self) -> (Color, Color);
}

impl CvssColor for f64 {
    fn cvss_color(&self) -> (Color, Color) {
        match *self {
            0.0 => (Color::Default, Color::Default),
            value if value > 0.0 && value < 4.0 => {
                (Color::Rgb(255, 255, 255), Color::Rgb(95, 177, 88))
            }
            value if (4.0..7.0).contains(&value) => (Color::Black, Color::Rgb(249, 238, 86)),
            value if (7.0..9.0).contains(&value) => {
                (Color::Rgb(255, 255, 255), Color::Rgb(232, 152, 63))
            }
            _ => (Color::Rgb(255, 255, 255), Color::Rgb(176, 54, 52)),
        }
    }
}

#[cfg(target_os = "linux")]
pub fn special_options(args: &[String]) {
    let mut filter: Option<&String> = None;
    if let Some(idx_filter) = args.iter().position(|a| a == "--filter") {
        filter = args.get(idx_filter + 1);
    }

    let (package_name, mut package_version) = extract_argument(args[0].clone());

    if SupportedOs::supported_os() == OSFamily::Debian && args.iter().any(|a| a == "--next") {
        package_version = Option::from(String::from("next"));
    }

    let package = get_package(package_name, package_version);
    stop_if_invalid_package(&package);

    let changelog_content = get_changelog_for(&package);
    let changelog_cve_list = filtering_cve(package.cve_list(&changelog_content), filter);
    if args.iter().any(|a| a == "--long" || a == "-L") {
        if check_nvd_api_key().is_none() {
            check_nvd_api_key_warning();
        }

        let mut cve_list = Vec::new();
        for cve_value in changelog_cve_list {
            eprint!(
                "Search CVE list for package: {package}. It will take a while... {}\r",
                cve_value.reference
            );
            let result = execute_query(build_query(ByCve, cve_value.reference.as_str()));
            if result != Null {
                let cve = create_cve_from(&result["vulnerabilities"][0]);
                cve_list.push(cve);
            }
        }
        show_cves(args, &mut cve_list);
    } else {
        show_cve_list(changelog_cve_list, package);
    }
}

pub fn common_options(args: &mut [String]) {
    if args.iter().any(|a| a == "version" || a == "v") {
        show_version(env!("CARGO_PKG_VERSION"));
        exit(0);
    }

    #[cfg(not(target_os = "linux"))]
    if check_nvd_api_key().is_none() {
        check_nvd_api_key_warning();
    }

    if args.iter().any(|a| a == "check" || a == "c") {
        check_mitre_data(Cve::define());
        exit(0);
    }

    if args.iter().any(|a| a == "e" || a == "exploited") {
        let mut cve_list = standard_or_filtered_list(args, extract_cve_list("", ByCveExploited));
        show_cves(args, &mut cve_list);
        exit(0);
    }

    if let Some(cpe_string) = args
        .iter()
        .position(|a| a == "for-cpe" || a == "f")
        .and_then(|i| args.get(i + 1))
    {
        let cpe = Cpe::from(cpe_string);
        let mut result = run_search_cpe(cpe, args);
        show_cves(args, &mut result);

        exit(0);
    }

    if let Some(new_option) = args.iter().position(|a| a == "new" || a == "n") {
        let dates_range = build_dates_range(Some(new_option), args);
        let mut cve_list =
            standard_or_filtered_list(args, extract_cve_list(dates_range.as_str(), ByCveNew));
        show_cves(args, &mut cve_list);
        exit(0);
    }

    if let Some(updated_option) = args.iter().position(|a| a == "updated" || a == "u") {
        let dates_range = build_dates_range(Some(updated_option), args);
        let mut cve_list =
            standard_or_filtered_list(args, extract_cve_list(dates_range.as_str(), ByCveUpdated));
        show_cves(args, &mut cve_list);
        exit(0);
    }

    if let Some(cwe_option) = args.iter().position(|a| a == "cwe" || a == "w") {
        run_search_cwe(args, Some(cwe_option));
        exit(0);
    }

    if let Some(search_option) = args.iter().position(|a| a == "search" || a == "s") {
        let result = run_search_cve_string(args, Some(search_option));
        let mut values = standard_or_filtered_list(args, result);
        show_cves(args, &mut values);
        exit(0);
    }

    let key_cve = args
        .iter()
        .position(|a| a.to_ascii_lowercase().contains("cve"));
    if let Some(pos) = key_cve
        && pos == 0
    {
        run_search_cve(args, key_cve);
        exit(0);
    }
}

fn standard_or_filtered_list(args: &mut [String], cve_list: Vec<Cve>) -> Vec<Cve> {
    match args.iter().position(|a| a == "--filter") {
        Some(pos) => filtering_cve(cve_list, args.get(pos + 1)),
        _ => cve_list,
    }
}

fn show_cves(args: &[String], cve_list: &mut [Cve]) {
    println!();
    if !args.iter().any(|a| a == "--long" || a == "-L") {
        show_cve_values(cve_list);
    } else {
        if let Some(pos) = args.iter().position(|a| a == "--sort_by")
            && let Some(criteria) = args.get(pos + 1)
        {
            let mut sort_score_by = String::new();
            if let Some(sorting_criteria) = args.get(pos + 2) {
                sort_score_by = sorting_criteria.clone();
            }

            match criteria.as_str() {
                "score" => match sort_score_by.as_str() {
                    "v4" => cve_list.sort_by(|a, b| {
                        b.score_v4
                            .clone()
                            .unwrap()
                            .value()
                            .total_cmp(&a.score_v4.clone().unwrap().value())
                    }),

                    _ => cve_list.sort_by(|a, b| {
                        b.score_v3
                            .clone()
                            .unwrap()
                            .value()
                            .total_cmp(&a.score_v3.clone().unwrap().value())
                    }),
                },

                "description" => cve_list.sort_by(|a, b| {
                    a.description
                        .clone()
                        .unwrap()
                        .cmp(&b.description.clone().unwrap())
                }),

                "cpe" => cve_list
                    .sort_by(|a, b| a.cpe_id.clone().unwrap().cmp(&b.cpe_id.clone().unwrap())),
                "weaknesses" => cve_list.sort_by(|a, b| {
                    b.weaknesses
                        .clone()
                        .unwrap()
                        .cmp(&a.weaknesses.clone().unwrap())
                }),

                _ => (),
            };
        }

        if args.iter().any(|a| a == "--to_csv") {
            show_as_csv(cve_list, args.iter().any(|a| a == "with_headers"));
        } else {
            show_as_table(cve_list);
        }
    }
}

fn show_as_csv(cve_list: &mut [Cve], with_headers: bool) {
    if !cve_list.is_empty() {
        let mut writer = csv::Writer::from_writer(stdout());
        if with_headers {
            writer
                .write_record([
                    "cve",
                    "description",
                    "score v3",
                    "level v3",
                    "score v4",
                    "level v4",
                    "cpe",
                    "weaknesses",
                ])
                .expect("Failed to write CSV headers");
        }

        cve_list.iter_mut().for_each(|cve| {
            writer
                .write_record([
                    cve.reference.clone(),
                    cve.description.clone().unwrap(),
                    cve.score_v3.clone().unwrap().value().to_string(),
                    cve.score_v3.clone().unwrap().label().to_string(),
                    cve.score_v4.clone().unwrap().value().to_string(),
                    cve.score_v4.clone().unwrap().label().to_string(),
                    cve.cpe_id.clone().unwrap(),
                    cve.weaknesses.clone().unwrap(),
                ])
                .expect("Failed to write CSV content");
        });

        writer.flush().expect("Failed to flush CSV writer");
    }
}

fn show_cve_values(cve_list: &[Cve]) {
    cve_list.iter().for_each(|c| println!("{c}"));
}

fn run_search_cve_string(args: &mut [String], position: Option<usize>) -> Vec<Cve> {
    let result = match args.iter().position(|a| a == "--strict" || a == "-S") {
        Some(pos) => {
            let values = args.get(pos + 1);
            if let Some(item) = values {
                execute_query(build_query(QueryType::ByCveSearchStrict, item.as_str()))
            } else {
                write_error_message_and_exit("Missing criteria", None);
                Null
            }
        }

        _ => match args.get(position.unwrap() + 1) {
            Some(values) => {
                execute_query(build_query(QueryType::ByCveSearchString, values.as_str()))
            }
            _ => {
                write_error_message_and_exit("Missing criteria", None);
                Null
            }
        },
    };
    let mut cves = cve_from_new_query(&result);
    simplify_list_content(&mut cves);
    cves
}

/// Extracts the package name and optional version from a given argument string.
///
/// This function takes a string argument which may or may not contain a version
/// separated by an '=' character. If the argument contains '=', it splits the
/// argument into two parts: the package name and the package version. Otherwise,
/// it considers the entire argument as the package name.
///
/// # Arguments
///
/// * `argument` - A `String` containing the package name and optionally, the version.
///
/// # Returns
///
/// A tuple containing:
/// * `String` - The package name.
/// * `Option<String>` - The optional package version, `None` if the version is not provided.
///
#[cfg(target_os = "linux")]
fn extract_argument(argument: String) -> (String, Option<String>) {
    let package_name: String;
    let mut package_version: Option<String> = None;

    if argument.contains("=") {
        let component: Vec<&str> = argument.split("=").collect();
        package_name = String::from(component[0]);
        package_version = Some(String::from(component[1]));
    } else {
        package_name = argument.clone();
    }

    (package_name, package_version)
}

/// Extracts a list of CVEs (Common Vulnerabilities and Exposures) based on a given criteria and query type.
///
/// This function performs iterative queries to gather all relevant CVEs from an API.
/// It starts by fetching an initial batch of CVEs, and continues fetching subsequent batches until
/// all CVEs are retrieved. Finally, it simplifies and prints out the retrieved CVEs.
///
/// # Arguments
///
/// * `criteria` - A string slice containing the criteria used for the CVE query.
/// * `cve_type` - A variant of the `QueryType` enum specifying the type of CVE query.
///
/// # Returns
///
///  The list of found CVE.
///
/// # Panics
///
/// This function will panic if the initial result is null.
fn extract_cve_list(criteria: &str, cve_type: QueryType) -> Vec<Cve> {
    let result = execute_query(build_query(cve_type.clone(), criteria));
    if !result.is_null() && result["resultsPerPage"] != 0 {
        let mut start_index = result["startIndex"].clone().as_u64().unwrap();
        let total_results = result["totalResults"].clone().as_u64().unwrap();

        let mut cve_list = cve_from_new_query(&result);
        start_index += cve_list.len() as u64;
        while cve_list.len() < (total_results as usize) {
            let query = format!(
                "{}&startIndex={}",
                build_query(cve_type.clone(), criteria).unwrap(),
                start_index
            );
            let result = execute_query(Ok(query));
            let mut cves = cve_from_new_query(&result);
            start_index += cves.len() as u64;
            cve_list.append(&mut cves);
        }

        simplify_list_content(&mut cve_list);
        return cve_list;
    } else {
        write_error_message_and_exit("No result found", None)
    }

    Vec::new()
}

fn show_as_table(cve_list: &[Cve]) {
    let mut table = AsciiTable::new("CVE list");

    table.set_headers(vec![
        "CVE",
        "Description",
        "Score v3",
        "Score v4",
        "CPE",
        "Weaknesses",
    ]);

    cve_list.iter().for_each(|cve| {
        let description = cve.description.clone().unwrap_or(String::from("None"));
        let cpe_id = cve.cpe_id.clone().unwrap_or(String::from("None"));
        let weaknesses = cve.weaknesses.clone().unwrap_or(String::from("None"));

        let score_v3 = format_score(cve.score_v3.clone().unwrap());
        let score_v4 = format_score(cve.score_v4.clone().unwrap());

        table.add_row(vec![
            CellValue::Str(cve.reference.clone()),
            CellValue::Str(description.replace("\n", " ").reduce(70)),
            CellValue::Str(score_v3.to_string()),
            CellValue::Str(score_v4.to_string()),
            CellValue::Str(cpe_id.reduce(40)),
            CellValue::Str(weaknesses.reduce(15)),
        ])
    });

    table.render()
}

fn format_score(cve_score: Score) -> String {
    let (color_fg, color_bg) = cve_score.value().cvss_color();
    format!(
        "{:^18}",
        format!(
            " {} - {} ",
            format!("{0:.1}", cve_score.value()),
            cve_score.label()
        )
    )
    .fg(color_fg)
    .bg(color_bg)
    .to_string()
}

/// Handles updates for Common Vulnerabilities and Exposures (CVE) based on the given
/// Common Platform Enumeration (CPE) identifier and command-line arguments.
///
/// This function determines the type of update based on the provided arguments and constructs
/// the necessary queries to retrieve updated CVE information.
///
/// # Arguments
///
/// * `cpe` - A `Cpe` struct representing the CPE identifier.
/// * `args` - A slice of strings representing command-line arguments.
///
/// # Return
///
/// The CVE list corresponding to the CPE definition.
///
fn run_search_cpe(cpe: Cpe, args: &mut [String]) -> Vec<Cve> {
    if let Some(new_date_option) = args.iter().position(|a| a == "--new") {
        let dates = build_dates_range(Some(new_date_option), args);
        let query_dates = create_query_dates(ByCveNew, dates.as_str());
        let cpe_query = build_query(ByCveCpeName, cpe.name().as_str());
        standard_or_filtered_list(
            args,
            extract_cve_list(
                format!("{}&{}", cpe_query.unwrap(), query_dates).as_str(),
                ByCveCpeName,
            ),
        )
    } else if let Some(updated_date_option) = args.iter().position(|a| a == "--updated") {
        let dates = build_dates_range(Some(updated_date_option), args);
        let query_dates = create_query_dates(ByCveUpdated, dates.as_str());
        let cpe_query = build_query(ByCveCpeName, cpe.name().as_str());
        standard_or_filtered_list(
            args,
            extract_cve_list(
                format!("{}&{}", cpe_query.unwrap(), query_dates).as_str(),
                ByCveCpeName,
            ),
        )
    } else if args.iter().any(|a| a == "--vul" || a == "-v") {
        standard_or_filtered_list(args, extract_cve_list(cpe.name().as_str(), ByCpeVulnerable))
    } else {
        standard_or_filtered_list(args, extract_cve_list(cpe.name().as_str(), ByCveCpeName))
    }
}

/// Executes a search for a specific CVE (Common Vulnerability and Exposure) and processes the results
/// based on the provided command-line arguments.
///
/// This function extracts the value for the CVE identifier from the provided command-line arguments and
/// builds a query to fetch the associated CVE data. It supports additional arguments to display specific
/// details such as scores, CWE (Common Weakness Enumeration) values, known affected languages, and descriptions.
///
/// # Arguments
///
/// * `args` - A mutable reference to a slice containing the command-line argument strings.
/// * `key_cve` - An optional index indicating the position of the CVE key within the `args` slice.
///
/// # Behaviour
///
/// - If the CVE value is found in the `args`, the query is executed to retrieve the CVE data.
/// - If no results are found for the given CVE, an error message is written, and the process exits.
/// - The function looks for additional command-line arguments to determine which specific details to display:
///   - `--score` to display CVSS scores.
///   - `--cwe` to display CWE values.
///   - `--lang` to display known affected languages.
///   - `--desc` to display a description of the CVE.
/// - If no specific detail arguments are provided, the function prints the full CVE data in a pretty JSON format.
///
fn run_search_cve(args: &mut [String], key_cve: Option<usize>) {
    if let Some(cve_value) = args.get(key_cve.unwrap()) {
        let result = if cve_value == &String::from("--cpe") {
            println!("Searching...");
            execute_query(build_query(ByCveCpeName, args[2].as_str()))
        } else {
            execute_query(build_query(ByCve, cve_value.as_str()))
        };

        if args.iter().any(|a| a == "--long" || a == "-L") {
            let mut cve = vec![create_cve_from(&result["vulnerabilities"][0])];
            if args.iter().any(|a| a == "--to_csv") {
                show_as_csv(&mut cve, args.iter().any(|a| a == "with_headers"));
            } else {
                show_as_table(&cve);
            }
            return;
        }

        if result["resultsPerPage"] == 0 || result == Null {
            write_error_message_and_exit("CVE not found", None);
        }

        if args.iter().any(|a| a == "--schema" || a == "-S") {
            show_schema(&result);
            return;
        }

        println!("{}", header!(cve_value));
        if cve_value == &String::from("--cpe") {
            cve_from_new_query(&result).iter().for_each(print_cve);
            return;
        }

        let mut cumulative_args = 0;

        if args.iter().any(|a| a == "--score" || a == "-s") {
            let include_data = args.iter().any(|a| a == "--data" || a == "-D");
            if include_data {
                cumulative_args += 1;
            }
            if args.iter().any(|a| a == "v3") {
                CveDisplayType::ByScores.show(&result, Some("v3"), Some(include_data));
                cumulative_args += 1;
            } else if args.iter().any(|a| a == "v4") {
                CveDisplayType::ByScores.show(&result, Some("v4"), Some(include_data));
                cumulative_args += 1;
            } else {
                CveDisplayType::ByScores.show(&result, Some("all"), Some(include_data));
                cumulative_args += 1;
            }
        }

        if args.iter().any(|a| a == "--cwe" || a == "-w") {
            CveDisplayType::ByCwe.show(&result, None, None);
            cumulative_args += 1;
        }

        if args.iter().any(|a| a == "--lang" || a == "-l") {
            CveDisplayType::ByLanguages.show(&result, None, None);
            cumulative_args += 1;
        }

        if let Some(key_description) = args.iter().position(|a| a == "--desc" || a == "-d") {
            let key_lang = args.get(key_description + 1).map(|lang| lang.as_str());

            CveDisplayType::ByDescription.show(&result, key_lang, None);
            cumulative_args += 1;
        }

        if args.iter().any(|a| a == "--doc" || a == "-K") {
            CveDisplayType::ByDocumentations.show(&result, None, None);
            cumulative_args += 1;
        }

        if args.iter().any(|a| a == "--cpe" || a == "-f") {
            CveDisplayType::ByCpe.show(&result, None, None);
            cumulative_args += 1;
        }

        if cumulative_args == 0 {
            CveDisplayType::All.show(&result, Some("all"), Some(true));
        }
    }
}

fn show_schema(result: &Value) {
    let cve = create_cve_from(&result["vulnerabilities"][0]);

    let mut builder = TreeBuilder::new();
    let cve_node = builder.node(section!(cve.reference, Color::Green).to_string());

    if let Some(cwe_list) = cve.weaknesses {
        let cwe_id = parse_id_to_u32(
            cwe_list
                .replace("CWE-", "")
                .replace(", ", FIELD_SEPARATOR_STRING),
        );
        cwe_id.iter().for_each(|id| {
            if let Some(cwe) = find_cwe_by_id(*id) {
                let cwe_node = cve_node.node(
                    format!("CWE-{} - {}", cwe.id, cwe.name)
                        .fg(Color::Red)
                        .to_string(),
                );

                let capec_id = parse_id_to_u32(
                    cwe.clone()
                        .attacks
                        .replace("CAPEC-", "")
                        .replace(", ", FIELD_SEPARATOR_STRING),
                );
                if !capec_id.is_empty() {
                    capec_id.iter().for_each(|ca_id| {
                        if let Some(capec) = find_capec_by_id(*ca_id) {
                            cwe_node.leaf(
                                format!("CAPEC-{} - {}", capec.id, capec.name)
                                    .fg(Color::DarkCyan)
                                    .to_string(),
                            );
                        }
                    });
                }
                cwe_node.end();
            }
        });
    } else {
        write_error_message_and_exit("No schemas found", None);
    }

    let tree = builder.build();
    println!("{}", tree.render_to_string());
}

fn show_data(result: &Value, level: &str) {
    let cvss_data = match level {
        "v3" => get_cvss3_data(result),
        "v4" => get_cvss4_data(result),
        _ => Null,
    };

    if !cvss_data.is_null() {
        let map = cvss_data.as_object().unwrap();
        let filtered = map
            .iter()
            .filter(|(k, _)| **k != "baseScore" && **k != "baseSeverity" && **k != "version");
        filtered.for_each(|(k, v)| {
            let str_value = match k.to_string().contains("vectorString") {
                false => v.to_string().wording().replace("_", " "),
                true => v.to_string(),
            };
            println!(
                "{:>7} {}: {}",
                "-",
                k.wording(),
                String::cleaning(str_value)
            );
        });
    } else {
        write_error_message("CVSS data not found", Some(level));
    }
}

/// Displays the languages from the JSON result.
///
/// This function extracts the descriptions section from the JSON result and
/// prints out the cleaned language codes. Each language code is cleaned to
/// remove any surrounding quotes.
///
/// # Arguments
///
/// * `result` - A reference to a `serde_json::Value` that contains the JSON data.
///
/// # Example
///
/// ```rust
/// use get_cve::show_languages;
///
/// let json_data = serde_json::json!({
///     "vulnerabilities": [
///         {
///             "cve": {
///                 "descriptions": [
///                     {"lang": "\"en\""},
///                     {"lang": "\"fr\""}
///                 ]
///             }
///         }
///     ]
/// });
///
/// show_languages(&json_data);
/// // Will show:
/// // en
/// // fr
/// ```
pub fn show_languages(result: &Value) {
    if let Some(descriptions) = get_descriptions_section(result) {
        section_level!(2, "Languages");
        for l in descriptions {
            print_values(&[l["lang"].clone()]);
        }
    }
}

/// Displays the description of a result based on the provided optional language key.
///
/// This function attempts to extract a description from a JSON `Value`
/// based on an optional language key. If a language key is provided, it is used
/// to try to fetch the description in that specific language. If no language key
/// is provided or if the description for the given language key is not found, it
/// defaults to extracting the description without any language specification.
///
/// The extracted description is then cleaned by removing surrounding quotation marks
/// and printed to the console.
///
/// # Parameters
/// - `result`: A reference to a `serde_json::Value` which holds the JSON data.
/// - `key_lang`: An optional reference to a `String` which specifies the language key
///   for fetching the description.
///
/// # Examples
///
/// ```
/// use serde_json::json;
/// use get_cve::show_description;
///
/// let data = json!({
///     "vulnerabilities": [
///         {
///             "cve": {
///                 "descriptions": [
///                     { "lang": "en", "value": "\"This is an English description.\"" },
///                     { "lang": "fr", "value": "\"Ceci est une description en français.\"" }
///                 ]
///             }
///         }
///     ]
/// });
///
/// show_description(&data, Some(&String::from("en"))); // prints: This is an English description.
/// show_description(&data, None); // If no default, it prints the first available description
/// ```
pub fn show_description(result: &Value, key_lang: Option<&String>) {
    section_level!(2, "Description");

    let description = if let Some(lang) = key_lang {
        extract_description(result, Some(lang.as_str()))
    } else {
        extract_description(result, None)
    };
    print_values(&[description]);
    println!();
}

fn show_documentations(result: &Value) {
    if let Some(documentations) = get_documentation_section(result) {
        section_level!(2, "Documentations");
        documentations.iter().for_each(|doc| {
            print_values(std::slice::from_ref(doc));
            if doc != documentations.last().unwrap() {
                println!();
            }
        });
    } else {
        write_error_message_and_exit("Documentation not found", None);
    }
}

/// Extracts the description from the given `value`, depending on the provided `lang` option.
///
/// If a language is specified, the function attempts to find a description matching the given language.
/// If no description matches the specified language, or if no language is specified,
/// the function falls back to extracting the default description.
///
/// # Arguments
///
/// * `value` - A reference to a `Value` type holding the JSON data.
/// * `lang` - An `Option` holding a reference to a string slice representing the desired language.
///
/// # Returns
///
/// A `Value` containing the extracted description.
fn extract_description(value: &Value, lang: Option<&str>) -> Value {
    if let Some(lang) = lang
        && let Some(languages) = get_descriptions_section(value)
    {
        for l in languages {
            if l["lang"].as_str() == Some(lang) {
                return l["value"].clone();
            }
        }
    }
    extract_default_description(value)
}

/// Extracts the default description from the given `value`.
///
/// It navigates the JSON structure to find and return the default description.
///
/// # Arguments
///
/// * `value` - A reference to a `Value` type holding the JSON data.
///
/// # Returns
///
/// A `Value` containing the default description.
fn extract_default_description(value: &Value) -> Value {
    value["vulnerabilities"][0]["cve"]["descriptions"][0]["value"].clone()
}

/// Retrieves the list of descriptions from the given `value`.
///
/// It navigates the JSON structure to return a reference to an array of descriptions if it exists.
///
/// # Arguments
///
/// * `value` - A reference to a `Value` type holding the JSON data.
///
/// # Returns
///
/// An `Option` containing a reference to a `&Vec<Value>` with descriptions or `None` if it does not exist.
fn get_descriptions_section(value: &Value) -> Option<&Vec<Value>> {
    value["vulnerabilities"][0]["cve"]["descriptions"].as_array()
}

/// Retrieves the list of documentations from the given `value`.
///
/// # Arguments
/// * `value`- A reference to a `Value` type holding the JSON data.
///
/// # Returns
///
/// An `Option` containing a reference to a `&Vec<Value>` with list of documentations or `None` if it does not exist.
fn get_documentation_section(value: &Value) -> Option<&Vec<Value>> {
    value["vulnerabilities"][0]["cve"]["references"].as_array()
}

/// Executes a search for CVEs associated with a specified CWE and prints the results.
///
/// This function extracts a CWE identifier from the `args` array based on the index provided
/// by `cwe_option`, builds a query URL using the CWE identifier, executes the query to fetch
/// the CVE data, processes the CVE data to remove duplicates and sort it, and then prints
/// each CVE entry.
///
/// # Arguments
///
/// * `args` - A mutable slice of `String` containing command line arguments. The CWE identifier
///   is expected to be at the position indicated by `cwe_option` + 1.
/// * `cwe_option` - An `Option` containing the index of the CWE identifier in the `args` array.
///   If `None`, the function immediately returns without performing any action.
///
/// # Example
///
/// ```rust
/// use get_cve::run_search_cwe;
///
/// let mut args = vec![String::from("program_name"), String::from("CWE-79")];
/// run_search_cwe(&mut args, Some(1));
/// ```
///
/// # Panics
///
/// This function will panic if `cwe_option` does not contain a valid index that points to a
/// CWE identifier inside the `args` array.
///
/// # Details
///
/// - The function first checks whether `cwe_option` contains a value. If it does, the function
///   attempts to retrieve the CWE identifier from the `args` array using
///   `args.get(cwe_option.unwrap() + 1)`.
/// - A query URL is then built using the retrieved CWE identifier by calling `build_query` with
///   `QueryType::Cwe` and the CWE identifier.
/// - The query is executed by calling `execute_query`, which returns a `Value` (expected to be a JSON
///   response).
/// - The `Value` is passed to the `cve_from_cwe` function, which extracts a list of CVE objects.
/// - The list is then simplified using `simplify_cve_list_content`, which sorts and removes
///   duplicates.
/// - Finally, the function prints each CVE entry using an iterator.
pub fn run_search_cwe(args: &mut [String], cwe_option: Option<usize>) {
    if let Some(cwe_value) = args.get(cwe_option.unwrap() + 1) {
        let result = execute_query(build_query(ByCwe, cwe_value.as_str()));
        let mut cve_list = standard_or_filtered_list(args, cve_from_cwe(&result));
        simplify_list_content(&mut cve_list);
        if cve_list.is_empty() {
            write_error_message_and_exit("CVE not found", None);
        }
        show_cves(args, &mut cve_list);
    }
}

enum CveDisplayType {
    All,
    ByCpe,
    ByCwe,
    ByData,
    ByDescription,
    ByDocumentations,
    ByLanguages,
    ByScores,
}

impl CveDisplayType {
    fn show(&self, value: &Value, argument: Option<&str>, flag: Option<bool>) {
        match self {
            CveDisplayType::All => {
                show_description(value, None);
                show_scores(value, argument.unwrap().trim(), flag.unwrap_or(false));
                show_documentations(value);
                println!();
                show_cwe_values(value);
                println!();
                show_cpe_values(value);
            }

            CveDisplayType::ByCpe => {
                show_cpe_values(value);
            }

            CveDisplayType::ByCwe => {
                show_cwe_values(value);
            }

            CveDisplayType::ByData => {
                show_data(value, argument.unwrap().trim());
            }

            CveDisplayType::ByDescription => {
                show_description(value, None);
            }

            CveDisplayType::ByDocumentations => {
                show_documentations(value);
            }

            CveDisplayType::ByLanguages => {
                show_languages(value);
            }

            CveDisplayType::ByScores => {
                show_scores(value, argument.unwrap().trim(), flag.unwrap_or(false));
            }
        }
    }
}

fn show_cpe_values(value: &Value) {
    section_level!(2, "CPE");
    let values = extract_cpe_id_list(value);
    if let Some(values) = values {
        values.iter().for_each(|v| {
            let mut result = v.as_object().unwrap().clone();
            result.remove("matchCriteriaId");
            print_values(&[Value::Object(result)]);
            println!();
        })
    } else {
        println!("None");
    }
}

fn extract_cpe_id_list(value: &Value) -> Option<&Vec<Value>> {
    value["vulnerabilities"][0]["cve"]["configurations"][0]["nodes"][0]["cpeMatch"].as_array()
}

/// Displays the Common Weakness Enumeration (CWE) values extracted from a JSON result.
///
/// This function extracts CWE values from the given JSON result using the `extract_cwe` function.
/// If the extracted values are not empty, it prints the values using the `print_values` function.
/// Otherwise, it prints "None".
///
/// # Arguments
///
/// * `result` - A reference to a JSON Value from which CWE values should be extracted.
///
/// # Example
///
/// ```
/// use serde_json::json;
/// use get_cve::show_cwe_values;
///
/// let json_result = json!({
///     "vulnerabilities": [
///         {
///             "cve": {
///                 "weaknesses": [
///                     {
///                         "description": [
///                             {
///                                 "value": "CWE-89"
///                             }
///                         ]
///                     }
///                 ]
///             }
///         }
///     ]
/// });
///
/// show_cwe_values(&json_result);  // Should print "CWE-89"
/// ```
pub fn show_cwe_values(result: &Value) {
    let values = extract_cwe(result);
    if !values.is_empty() {
        let slice_values: Vec<_> = values
            .iter()
            .map(|v| String::cleaning(v.to_string()))
            .collect();
        let mut str_values = slice_values.join(FIELD_SEPARATOR_STRING_LONG);
        str_values = str_values.replace("CWE-", FIELD_SEPARATOR_STRING_LONG);
        show_weaknesses("weaknesses", str_values);
    } else {
        println!("None");
    }
}

/// Extracts Common Weakness Enumeration (CWE) values from a given JSON object.
///
/// This function takes a JSON Value and attempts to parse and extract CWE descriptions
/// from it. The CWE descriptions are expected to be nested within the following structure:
/// `vulnerabilities -> cve -> weaknesses`.
///
/// # Arguments
///
/// * `value` - A reference to a JSON Value from which CWE descriptions should be extracted.
///
/// # Returns
///
/// A `Vec<Value>` containing unique CWE description values. If the expected structure is not
/// present or if there are no CWE descriptions, an empty vector is returned.
fn extract_cwe(value: &Value) -> Vec<Value> {
    let mut result: Vec<Value> = vec![];
    let binding = value["vulnerabilities"][0]["cve"]["weaknesses"].clone();
    let elements_option = binding.as_array();
    if let Some(elements) = elements_option {
        elements.iter().for_each(|value| {
            let vals = value["description"].as_array().unwrap();
            vals.iter()
                .for_each(|val| result.push(val["value"].clone()))
        });
    }

    result.dedup();

    result
}

/// Displays CVSS (Common Vulnerability Scoring System) scores from the given JSON result.
///
/// This function prints out the CVSS v3 and, if available, the CVSS v4 base scores and severities.
///
/// # Arguments
///
/// * `result` - A reference to a `serde_json::Value` which contains the CVSS data.
/// * `level`- "v3" for showing CVSS v3 scoring, "v4" for showing CVSS v4 socring, "all" for all scoring levels
///
/// # Example
///
/// ```
/// use serde_json::Value;
/// use get_cve::show_scores;
///
/// let json_data = r#"
/// {
///     "vulnerabilities": [
///         {
///             "cve": {
///                 "metrics": {
///                     "cvssMetricV31": [
///                         {
///                             "cvssData": {
///                                 "baseScore": 7.5,
///                                 "baseSeverity": "HIGH"
///                             }
///                         }
///                     ],
///                     "cvssMetricV40": [
///                         {
///                             "cvssData": {
///                                 "baseScore": 9.8,
///                                 "baseSeverity": "CRITICAL"
///                             }
///                         }
///                     ]
///                 }
///             }
///         }
///     ]
/// }
/// "#;
///
/// let result: Value = serde_json::from_str(json_data).unwrap();
/// show_scores(&result, "v3", true);
/// ```
///
/// The expected output for the above example output would be:
/// ```plaintext
/// Score v3: 7.5 - HIGH
/// Score v4: 9.8 - CRITICAL
/// ```
pub fn show_scores(result: &Value, level: &str, include_data: bool) {
    if level != "all" {
        let cvss_data = match level {
            "v3" => get_cvss3_data(result),
            "v4" => get_cvss4_data(result),
            _ => Null,
        };

        section_level!(2, "Scores");
        if !cvss_data.is_null() {
            let score = cvss_data["baseScore"].as_f64().unwrap();
            let (color_fg, color_bg) = score.cvss_color();
            println!(
                "{:>6} Score {}: {:.1} - {}",
                "-",
                level,
                score,
                format!(
                    " {} ",
                    String::cleaning(cvss_data["baseSeverity"].to_string())
                )
                .fg(color_fg)
                .bg(color_bg),
            );
            println!();

            if include_data {
                section_level!(3, "Data");
                CveDisplayType::ByData.show(result, Some(level), None);
                println!();
            }
        } else {
            write_error_message("Score not found", Some(level));
            println!();
        }
    } else if level == "all" {
        show_scores(result, "v3", include_data);
        show_scores(result, "v4", include_data);
    } else {
        write_error_message("Score type not found", Some(level));
    }
}

/// Retrieves the CVSSv4 data from a given JSON value.
///
/// This function attempts to extract the Common Vulnerability Scoring System (CVSS) version 4 data
/// from the nested structure of the provided JSON value. It specifically looks for the CVSS data
/// within the `result` JSON structure at the following path:
/// `result["vulnerabilities"][0]["cve"]["metrics"]["cvssMetricV40"][0]["cvssData"]`.
///
/// # Arguments
///
/// * `result` - A reference to a JSON `Value` from which the CVSSv4 data is to be extracted.
///
/// # Returns
///
/// * `Value` - `Value` that's containing the CVSSv4 data if it exists,
///   otherwise `Null`.
///
/// # Dependencies
///
/// Make sure to include `serde` and `serde_json` in your dependencies.
fn get_cvss4_data(result: &Value) -> Value {
    get_cvss_scoring(result, "V40")
}

/// Extracts CVSS v3.1 data from a JSON value.
///
/// # Arguments
///
/// * `result` - A reference to a `serde_json::Value` which is expected to have a specific JSON structure.
///
/// # Returns
///
/// * A `serde_json::Value` containing the `cvssData` from the first CVSS v3.1 metric.
///
/// # Panics
///
/// This function will panic if the expected structure is not present in the `result`.
///
/// The expected structure within `result`:
/// ```json
/// {
///   "vulnerabilities": [
///     {
///       "cve": {
///         "metrics": {
///           "cvssMetricV31": [
///             {
///               "cvssData": {
///                 // The CVSS v3.1 data goes here
///               }
///             }
///           ]
///         }
///       }
///     }
///   ]
/// }
/// ```
///
///
/// # Dependencies
///
/// Make sure to include `serde` and `serde_json` in your dependencies.
/// ```
fn get_cvss3_data(result: &Value) -> Value {
    get_cvss_scoring(result, "V31")
}

/// Get cvss data according to the level score type
///
/// # Arguments
/// - `result`- Result cve searching
/// - `level` - Scoring level. Await: "V31" for the v 3.1 score, "V40" for the v4.0 score.
///
/// # Returns
///
/// The Scoring data
fn get_cvss_scoring(result: &Value, level: &str) -> Value {
    result["vulnerabilities"][0]["cve"]["metrics"][format!("cvssMetric{}", level)][0]["cvssData"]
        .clone()
}

/// Extracts a list of `Cve` structs from a given JSON `Value`.
///
/// This function processes a JSON `Value` to extract an array of vulnerabilities,
/// then it iterates over this array to create a `Vec<Cve>`. Each `Cve` contains
/// a reference string extracted from the respective vulnerability.
///
/// # Arguments
///
/// * `values` - A reference to a `Value` representing the JSON structure that
///   contains the vulnerabilities.
///
/// # Returns
///
/// * `Vec<Cve>` - A vector containing the extracted `Cve` structs. If the
///   vulnerabilities array is not present in the JSON `Value`,
///   it returns an empty vector.
///
/// # Example
///
/// ```rust
/// use serde_json::json;
/// use get_cve::cve_from_new_query;
/// use fenir::package::concepts::Cve;
///
/// let data = json!({
///     "vulnerabilities": [
///         {"cve": {"id": "CVE-2023-1234"}},
///         {"cve": {"id": "CVE-2023-5678"}}
///     ]
/// });
///
/// let cves = cve_from_new_query(&data);
/// assert_eq!(cves.len(), 2);
/// assert_eq!(cves[0].reference, "CVE-2023-1234");
/// assert_eq!(cves[1].reference, "CVE-2023-5678");
/// ```
pub fn cve_from_new_query(values: &Value) -> Vec<Cve> {
    if let Some(vulnerabilities) = values["vulnerabilities"].as_array() {
        let mut results: Vec<Cve> = vec![];
        vulnerabilities
            .iter()
            .for_each(|v| results.push(create_cve_from(v)));

        results
    } else {
        vec![]
    }
}

#[cfg(test)]
mod tests {
    use crate::{extract_cwe, extract_description};
    use fenir::cve::{create_cve_from, cve_from_cwe};
    use fenir::database::execute_query;
    use fenir::query::build_query;
    use fenir::query::QueryType::{ByCve, ByCwe};
    use serde_json::Value;
    use std::thread::sleep;
    use std::time::Duration;
    use utmt::assert_all;

    fn setup() {
        let waiting = Duration::from_millis(30);
        sleep(waiting);
    }

    #[test]
    fn extract_description_default_lang_valid() {
        setup();

        let result = execute_query(build_query(ByCve, "CVE-2024-6387"));

        assert_default_description(&result, None);
    }

    fn assert_default_description(result: &Value, option: Option<&str>) {
        assert!(
            extract_description(&result, option)
                .to_string()
                .contains("A security regression (CVE-2006-5051) was discovered ")
        );
    }

    #[test]
    fn extract_description_invalid_default() {
        setup();

        let result = execute_query(build_query(ByCve, "CVE-2024-6387"));

        assert_default_description(&result, Option::from("ff"));
    }

    #[test]
    fn extract_description_es_lang_valid() {
        setup();

        let result = execute_query(build_query(ByCve, "CVE-2024-6387"));

        assert!(extract_description(&result, Option::from("es")).to_string().contains("Se encontró una condición de ejecución del controlador de señales en el servidor de OpenSSH"));
    }

    #[test]
    fn extract_cwe_valid_cve_non_empty() {
        setup();

        let result = execute_query(build_query(ByCve, "CVE-2024-6387"));

        assert!(!extract_cwe(&result).is_empty());
    }

    #[test]
    fn create_cve_from_value() {
        setup();

        let cve = create_cve_from(&execute_query(build_query(ByCve, "CVE-2024-6387")));

        assert_all!(
            cve.cpe_id.is_some(),
            cve.description.is_some(),
            cve.score_v3.is_some(),
            !cve.reference.is_empty(),
            cve.weaknesses.is_some()
        );
    }

    #[test]
    fn extract_cwe_invalid_cve_empty() {
        setup();

        let result = execute_query(build_query(ByCve, "CVE-1970-0000"));

        assert!(extract_cwe(&result).is_empty());
    }

    #[test]
    fn cve_from_cwe_result_valid_cwe_not_empty() {
        setup();

        let result = execute_query(build_query(ByCwe, "CWE-287"));

        assert!(!cve_from_cwe(&result).is_empty());
    }
}