use super::super::{CertRule, RuleViolation};
use crate::manifest::{RuleCategory, Severity};
use crate::utility::cert_c::ast_utils::get_node_text;
use tree_sitter::Node;
pub struct Fio11C;
const VALID_MODES: &[&str] = &[
"r", "w", "a", "rb", "wb", "ab", "r+", "w+", "a+", "r+b", "rb+", "w+b", "wb+", "a+b", "ab+",
"wx", "wbx", "w+x", "w+bx", "wb+x",
];
impl CertRule for Fio11C {
fn rule_id(&self) -> &'static str {
"FIO11-C"
}
fn description(&self) -> &'static str {
"Take care when specifying the mode parameter of fopen()"
}
fn severity(&self) -> Severity {
Severity::Medium
}
fn category(&self) -> RuleCategory {
RuleCategory::Recommendation
}
fn cert_id(&self) -> &'static str {
"FIO11-C"
}
fn check(&self, node: &Node, source: &str) -> Vec<RuleViolation> {
let mut violations = Vec::new();
self.check_node(node, source, &mut violations);
violations
}
}
impl Fio11C {
fn check_node(&self, node: &Node, source: &str, violations: &mut Vec<RuleViolation>) {
if node.kind() == "call_expression" {
if let Some(function) = node.child_by_field_name("function") {
let func_name = get_node_text(&function, source);
if func_name == "fopen" || func_name == "fopen_s" {
self.check_fopen_call(node, source, violations);
}
}
}
for i in 0..node.child_count() {
if let Some(child) = node.child(i) {
self.check_node(&child, source, violations);
}
}
}
fn check_fopen_call(&self, node: &Node, source: &str, violations: &mut Vec<RuleViolation>) {
if let Some(arguments) = node.child_by_field_name("arguments") {
let mode_arg_index = {
if let Some(function) = node.child_by_field_name("function") {
let func_name = get_node_text(&function, source);
if func_name == "fopen_s" {
2 } else {
1 }
} else {
1
}
};
let args = self.extract_arguments(&arguments);
if args.len() > mode_arg_index {
let mode_node = &args[mode_arg_index];
let mode_text = get_node_text(mode_node, source);
if mode_node.kind() == "string_literal" {
let mode = mode_text.trim_matches('"');
if !self.is_valid_mode(mode) {
let start_point = mode_node.start_position();
violations.push(RuleViolation {
rule_id: self.rule_id().to_string(),
severity: Severity::Medium,
message: format!(
"Non-standard fopen() mode string '{}'; use only C standard mode strings for portability",
mode
),
file_path: String::new(),
line: start_point.row + 1,
column: start_point.column + 1,
suggestion: Some(
"Use one of: r, w, a, rb, wb, ab, r+, w+, a+, r+b, rb+, w+b, wb+, a+b, ab+, wx, wbx, w+x, w+bx, wb+x".to_string(),
),
..Default::default()
});
}
}
}
}
}
fn extract_arguments<'a>(&self, arguments_node: &Node<'a>) -> Vec<Node<'a>> {
let mut args = Vec::new();
for i in 0..arguments_node.child_count() {
if let Some(child) = arguments_node.child(i) {
if child.kind() != "," && child.kind() != "(" && child.kind() != ")" {
args.push(child);
}
}
}
args
}
fn is_valid_mode(&self, mode: &str) -> bool {
VALID_MODES.contains(&mode)
}
}