1 /*
2  * Copyright (C) 2024 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 //! flag table query module defines the flag table file read from mapped bytes
18 
19 use crate::{AconfigStorageError, FILE_VERSION};
20 use aconfig_storage_file::{
21     flag_table::FlagTableHeader, flag_table::FlagTableNode, read_u32_from_bytes, StoredFlagType,
22 };
23 use anyhow::anyhow;
24 
25 /// Flag table query return
26 #[derive(PartialEq, Debug)]
27 pub struct FlagReadContext {
28     pub flag_type: StoredFlagType,
29     pub flag_index: u16,
30 }
31 
32 /// Query flag read context: flag type and within package flag index
find_flag_read_context( buf: &[u8], package_id: u32, flag: &str, ) -> Result<Option<FlagReadContext>, AconfigStorageError>33 pub fn find_flag_read_context(
34     buf: &[u8],
35     package_id: u32,
36     flag: &str,
37 ) -> Result<Option<FlagReadContext>, AconfigStorageError> {
38     let interpreted_header = FlagTableHeader::from_bytes(buf)?;
39     if interpreted_header.version > crate::FILE_VERSION {
40         return Err(AconfigStorageError::HigherStorageFileVersion(anyhow!(
41             "Cannot read storage file with a higher version of {} with lib version {}",
42             interpreted_header.version,
43             FILE_VERSION
44         )));
45     }
46 
47     let num_buckets = (interpreted_header.node_offset - interpreted_header.bucket_offset) / 4;
48     let bucket_index = FlagTableNode::find_bucket_index(package_id, flag, num_buckets);
49 
50     let mut pos = (interpreted_header.bucket_offset + 4 * bucket_index) as usize;
51     let mut flag_node_offset = read_u32_from_bytes(buf, &mut pos)? as usize;
52     if flag_node_offset < interpreted_header.node_offset as usize
53         || flag_node_offset >= interpreted_header.file_size as usize
54     {
55         return Ok(None);
56     }
57 
58     loop {
59         let interpreted_node = FlagTableNode::from_bytes(&buf[flag_node_offset..])?;
60         if interpreted_node.package_id == package_id && interpreted_node.flag_name == flag {
61             return Ok(Some(FlagReadContext {
62                 flag_type: interpreted_node.flag_type,
63                 flag_index: interpreted_node.flag_index,
64             }));
65         }
66         match interpreted_node.next_offset {
67             Some(offset) => flag_node_offset = offset as usize,
68             None => return Ok(None),
69         }
70     }
71 }
72 
73 #[cfg(test)]
74 mod tests {
75     use super::*;
76     use aconfig_storage_file::test_utils::create_test_flag_table;
77 
78     #[test]
79     // this test point locks down table query
test_flag_query()80     fn test_flag_query() {
81         let flag_table = create_test_flag_table().into_bytes();
82         let baseline = vec![
83             (0, "enabled_ro", StoredFlagType::ReadOnlyBoolean, 1u16),
84             (0, "enabled_rw", StoredFlagType::ReadWriteBoolean, 2u16),
85             (2, "enabled_rw", StoredFlagType::ReadWriteBoolean, 1u16),
86             (1, "disabled_rw", StoredFlagType::ReadWriteBoolean, 0u16),
87             (1, "enabled_fixed_ro", StoredFlagType::FixedReadOnlyBoolean, 1u16),
88             (1, "enabled_ro", StoredFlagType::ReadOnlyBoolean, 2u16),
89             (2, "enabled_fixed_ro", StoredFlagType::FixedReadOnlyBoolean, 0u16),
90             (0, "disabled_rw", StoredFlagType::ReadWriteBoolean, 0u16),
91         ];
92         for (package_id, flag_name, flag_type, flag_index) in baseline.into_iter() {
93             let flag_context =
94                 find_flag_read_context(&flag_table[..], package_id, flag_name).unwrap().unwrap();
95             assert_eq!(flag_context.flag_type, flag_type);
96             assert_eq!(flag_context.flag_index, flag_index);
97         }
98     }
99 
100     #[test]
101     // this test point locks down table query of a non exist flag
test_not_existed_flag_query()102     fn test_not_existed_flag_query() {
103         let flag_table = create_test_flag_table().into_bytes();
104         let flag_context = find_flag_read_context(&flag_table[..], 1, "disabled_fixed_ro").unwrap();
105         assert_eq!(flag_context, None);
106         let flag_context = find_flag_read_context(&flag_table[..], 2, "disabled_rw").unwrap();
107         assert_eq!(flag_context, None);
108     }
109 
110     #[test]
111     // this test point locks down query error when file has a higher version
test_higher_version_storage_file()112     fn test_higher_version_storage_file() {
113         let mut table = create_test_flag_table();
114         table.header.version = crate::FILE_VERSION + 1;
115         let flag_table = table.into_bytes();
116         let error = find_flag_read_context(&flag_table[..], 0, "enabled_ro").unwrap_err();
117         assert_eq!(
118             format!("{:?}", error),
119             format!(
120                 "HigherStorageFileVersion(Cannot read storage file with a higher version of {} with lib version {})",
121                 crate::FILE_VERSION + 1,
122                 crate::FILE_VERSION
123             )
124         );
125     }
126 }
127