| 1 | use ddccontrol_caps::{Caps, MonitorType, VcpEntry}; |
| 2 | use libc::{c_char, c_int, c_ushort, c_void, free, malloc}; |
| 3 | use std::ffi::CStr; |
| 4 | use std::panic::{catch_unwind, AssertUnwindSafe}; |
| 5 | use std::ptr; |
| 6 | use std::slice; |
| 7 | |
| 8 | #[repr(C)] |
| 9 | pub struct CVcpEntry { |
| 10 | values_len: c_int, |
| 11 | values: *mut c_ushort, |
| 12 | } |
| 13 | |
| 14 | #[repr(C)] |
| 15 | pub struct CCaps { |
| 16 | vcp: [*mut CVcpEntry; 256], |
| 17 | monitor_type: c_int, |
| 18 | raw_caps: *mut c_char, |
| 19 | } |
| 20 | |
| 21 | #[cfg(test)] |
| 22 | macro_rules! field_offset { |
| 23 | ($ty:ty, $field:tt) => {{ |
| 24 | let value = std::mem::MaybeUninit::<$ty>::uninit(); |
| 25 | let base = value.as_ptr(); |
| 26 | unsafe { std::ptr::addr_of!((*base).$field) as usize - base as usize } |
| 27 | }}; |
| 28 | } |
| 29 | |
| 30 | #[no_mangle] |
| 31 | pub unsafe extern "C" fn ddccontrol_caps_parse( |
| 32 | caps_str: *const c_char, |
| 33 | caps: *mut CCaps, |
| 34 | add: c_int, |
| 35 | ) -> c_int { |
| 36 | match catch_unwind(AssertUnwindSafe(|| { |
| 37 | ddccontrol_caps_parse_inner(caps_str, caps, add) |
| 38 | })) { |
| 39 | Ok(result) => result, |
| 40 | Err(_) => -1, |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | unsafe fn ddccontrol_caps_parse_inner( |
| 45 | caps_str: *const c_char, |
| 46 | caps: *mut CCaps, |
| 47 | add: c_int, |
| 48 | ) -> c_int { |
| 49 | if caps_str.is_null() || caps.is_null() { |
| 50 | return -1; |
| 51 | } |
| 52 | |
| 53 | let input = CStr::from_ptr(caps_str).to_string_lossy(); |
| 54 | let mut rust_caps = caps_from_c(caps); |
| 55 | let result = if add != 0 { |
| 56 | rust_caps.apply_add(&input) |
| 57 | } else { |
| 58 | rust_caps.apply_remove(&input) |
| 59 | }; |
| 60 | |
| 61 | match result { |
| 62 | Ok(count) => { |
| 63 | if replace_c_caps(caps, &rust_caps) { |
| 64 | count as c_int |
| 65 | } else { |
| 66 | free_c_vcp_entries(caps); |
| 67 | -1 |
| 68 | } |
| 69 | } |
| 70 | Err(_) => { |
| 71 | free_c_vcp_entries(caps); |
| 72 | -1 |
| 73 | } |
| 74 | } |
| 75 | } |
| 76 | |
| 77 | unsafe fn caps_from_c(caps: *mut CCaps) -> Caps { |
| 78 | let mut rust_caps = Caps::default(); |
| 79 | rust_caps.set_monitor_type(match (*caps).monitor_type { |
| 80 | 1 => MonitorType::Lcd, |
| 81 | 2 => MonitorType::Crt, |
| 82 | _ => MonitorType::Unknown, |
| 83 | }); |
| 84 | |
| 85 | for code in 0..256 { |
| 86 | let entry = (*caps).vcp[code]; |
| 87 | if entry.is_null() { |
| 88 | continue; |
| 89 | } |
| 90 | |
| 91 | let values_len = (*entry).values_len; |
| 92 | let values = if values_len < 0 { |
| 93 | None |
| 94 | } else if values_len == 0 || (*entry).values.is_null() { |
| 95 | Some(Vec::new()) |
| 96 | } else { |
| 97 | Some(slice::from_raw_parts((*entry).values, values_len as usize).to_vec()) |
| 98 | }; |
| 99 | |
| 100 | rust_caps.insert_vcp( |
| 101 | code as u8, |
| 102 | match values { |
| 103 | Some(values) => VcpEntry::with_values(values), |
| 104 | None => VcpEntry::all_values(), |
| 105 | }, |
| 106 | ); |
| 107 | } |
| 108 | |
| 109 | rust_caps |
| 110 | } |
| 111 | |
| 112 | unsafe fn replace_c_caps(caps: *mut CCaps, rust_caps: &Caps) -> bool { |
| 113 | free_c_vcp_entries(caps); |
| 114 | (*caps).monitor_type = match rust_caps.monitor_type() { |
| 115 | MonitorType::Unknown => 0, |
| 116 | MonitorType::Lcd => 1, |
| 117 | MonitorType::Crt => 2, |
| 118 | }; |
| 119 | |
| 120 | for (code, entry) in rust_caps.vcp_entries() { |
| 121 | let c_entry = malloc(std::mem::size_of::<CVcpEntry>()) as *mut CVcpEntry; |
| 122 | if c_entry.is_null() { |
| 123 | return false; |
| 124 | } |
| 125 | |
| 126 | match entry.values() { |
| 127 | Some(values) => { |
| 128 | (*c_entry).values_len = values.len() as c_int; |
| 129 | if values.is_empty() { |
| 130 | (*c_entry).values = ptr::null_mut(); |
| 131 | } else { |
| 132 | let values_size = values.len() * std::mem::size_of::<c_ushort>(); |
| 133 | let c_values = malloc(values_size) as *mut c_ushort; |
| 134 | if c_values.is_null() { |
| 135 | free(c_entry as *mut c_void); |
| 136 | return false; |
| 137 | } |
| 138 | ptr::copy_nonoverlapping(values.as_ptr(), c_values, values.len()); |
| 139 | (*c_entry).values = c_values; |
| 140 | } |
| 141 | } |
| 142 | None => { |
| 143 | (*c_entry).values_len = -1; |
| 144 | (*c_entry).values = ptr::null_mut(); |
| 145 | } |
| 146 | } |
| 147 | |
| 148 | (*caps).vcp[code as usize] = c_entry; |
| 149 | } |
| 150 | |
| 151 | true |
| 152 | } |
| 153 | |
| 154 | unsafe fn free_c_vcp_entries(caps: *mut CCaps) { |
| 155 | for entry in &mut (*caps).vcp { |
| 156 | if !entry.is_null() { |
| 157 | free((**entry).values as *mut c_void); |
| 158 | free(*entry as *mut c_void); |
| 159 | *entry = ptr::null_mut(); |
| 160 | } |
| 161 | } |
| 162 | } |
| 163 | |
| 164 | #[cfg(test)] |
| 165 | mod abi_tests { |
| 166 | use super::*; |
| 167 | use std::mem::{align_of, size_of}; |
| 168 | |
| 169 | fn align_up(value: usize, align: usize) -> usize { |
| 170 | (value + align - 1) & !(align - 1) |
| 171 | } |
| 172 | |
| 173 | #[test] |
| 174 | fn caps_ffi_layout_matches_c_abi_contract() { |
| 175 | assert_eq!(size_of::<c_int>(), 4); |
| 176 | assert_eq!(size_of::<c_ushort>(), 2); |
| 177 | |
| 178 | assert_eq!(field_offset!(CVcpEntry, values_len), 0); |
| 179 | assert_eq!( |
| 180 | field_offset!(CVcpEntry, values), |
| 181 | align_up(size_of::<c_int>(), align_of::<*mut c_ushort>()) |
| 182 | ); |
| 183 | |
| 184 | let expected_vcp_bytes = size_of::<[*mut CVcpEntry; 256]>(); |
| 185 | assert_eq!(field_offset!(CCaps, vcp), 0); |
| 186 | assert_eq!(field_offset!(CCaps, monitor_type), expected_vcp_bytes); |
| 187 | assert_eq!( |
| 188 | field_offset!(CCaps, raw_caps), |
| 189 | align_up( |
| 190 | expected_vcp_bytes + size_of::<c_int>(), |
| 191 | align_of::<*mut c_char>() |
| 192 | ) |
| 193 | ); |
| 194 | } |
| 195 | } |
| 196 | |
| 197 | mod monitor_db { |
| 198 | use super::{ddccontrol_caps_parse, free, malloc, CCaps}; |
| 199 | use encoding_rs::{Encoding, UTF_8}; |
| 200 | use libc::{c_char, c_int, c_uchar, c_ushort, c_void}; |
| 201 | use roxmltree::{Document, Node}; |
| 202 | use std::borrow::Cow; |
| 203 | use std::ffi::{CStr, CString}; |
| 204 | use std::fs; |
| 205 | use std::path::{Path, PathBuf}; |
| 206 | use std::ptr; |
| 207 | use std::sync::Mutex; |
| 208 | |
| 209 | const DBVERSION: i64 = 3; |
| 210 | #[cfg(all(not(test), feature = "gettext"))] |
| 211 | const DBPACKAGE: &[u8] = b"ddccontrol-db\0"; |
| 212 | const DEFAULT_DATADIR: &str = match option_env!("DDCONTROL_DATADIR") { |
| 213 | Some(value) => value, |
| 214 | None => "/usr/local/share/ddccontrol-db", |
| 215 | }; |
| 216 | |
| 217 | const CONTROL_TYPE_VALUE: c_int = 0; |
| 218 | const CONTROL_TYPE_COMMAND: c_int = 1; |
| 219 | const CONTROL_TYPE_LIST: c_int = 2; |
| 220 | const REFRESH_TYPE_NONE: c_int = 0; |
| 221 | const REFRESH_TYPE_ALL: c_int = 1; |
| 222 | const INIT_TYPE_UNKNOWN: c_int = 0; |
| 223 | const INIT_TYPE_STANDARD: c_int = 1; |
| 224 | const INIT_TYPE_SAMSUNG: c_int = 2; |
| 225 | |
| 226 | #[repr(C)] |
| 227 | pub struct CValueDb { |
| 228 | id: *mut c_uchar, |
| 229 | name: *mut c_uchar, |
| 230 | value: c_uchar, |
| 231 | next: *mut CValueDb, |
| 232 | } |
| 233 | |
| 234 | #[repr(C)] |
| 235 | struct CValueDbPrivate { |
| 236 | public_value: CValueDb, |
| 237 | value16: c_ushort, |
| 238 | } |
| 239 | |
| 240 | #[repr(C)] |
| 241 | pub struct CControlDb { |
| 242 | id: *mut c_uchar, |
| 243 | name: *mut c_uchar, |
| 244 | address: c_uchar, |
| 245 | delay: c_int, |
| 246 | control_type: c_int, |
| 247 | refresh: c_int, |
| 248 | next: *mut CControlDb, |
| 249 | value_list: *mut CValueDb, |
| 250 | } |
| 251 | |
| 252 | #[repr(C)] |
| 253 | pub struct CSubgroupDb { |
| 254 | name: *mut c_uchar, |
| 255 | pattern: *mut c_uchar, |
| 256 | next: *mut CSubgroupDb, |
| 257 | control_list: *mut CControlDb, |
| 258 | } |
| 259 | |
| 260 | #[repr(C)] |
| 261 | pub struct CGroupDb { |
| 262 | name: *mut c_uchar, |
| 263 | next: *mut CGroupDb, |
| 264 | subgroup_list: *mut CSubgroupDb, |
| 265 | } |
| 266 | |
| 267 | #[repr(C)] |
| 268 | pub struct CMonitorDb { |
| 269 | name: *mut c_uchar, |
| 270 | init: c_int, |
| 271 | group_list: *mut CGroupDb, |
| 272 | } |
| 273 | |
| 274 | #[cfg(all(not(test), feature = "gettext"))] |
| 275 | extern "C" { |
| 276 | fn dgettext(domainname: *const c_char, msgid: *const c_char) -> *mut c_char; |
| 277 | } |
| 278 | |
| 279 | static DB_CONTEXT: Mutex<Option<DbContext>> = Mutex::new(None); |
| 280 | |
| 281 | #[derive(Clone)] |
| 282 | struct DbContext { |
| 283 | datadir: PathBuf, |
| 284 | options: OptionsDb, |
| 285 | } |
| 286 | |
| 287 | #[derive(Clone, Default)] |
| 288 | struct OptionsDb { |
| 289 | groups: Vec<OptionGroup>, |
| 290 | } |
| 291 | |
| 292 | #[derive(Clone)] |
| 293 | struct OptionGroup { |
| 294 | name: String, |
| 295 | subgroups: Vec<OptionSubgroup>, |
| 296 | } |
| 297 | |
| 298 | #[derive(Clone)] |
| 299 | struct OptionSubgroup { |
| 300 | name: String, |
| 301 | pattern: Option<String>, |
| 302 | controls: Vec<OptionControl>, |
| 303 | } |
| 304 | |
| 305 | #[derive(Clone)] |
| 306 | struct OptionControl { |
| 307 | id: String, |
| 308 | name: String, |
| 309 | control_type: c_int, |
| 310 | refresh: c_int, |
| 311 | values: Vec<OptionValue>, |
| 312 | } |
| 313 | |
| 314 | #[derive(Clone)] |
| 315 | struct OptionValue { |
| 316 | id: String, |
| 317 | name: Option<String>, |
| 318 | } |
| 319 | |
| 320 | #[derive(Default)] |
| 321 | struct MonitorBuild { |
| 322 | name: Option<Vec<u8>>, |
| 323 | init: c_int, |
| 324 | groups: Vec<DbGroup>, |
| 325 | } |
| 326 | |
| 327 | struct DbGroup { |
| 328 | name: Vec<u8>, |
| 329 | subgroups: Vec<DbSubgroup>, |
| 330 | } |
| 331 | |
| 332 | struct DbSubgroup { |
| 333 | name: Vec<u8>, |
| 334 | pattern: Option<String>, |
| 335 | controls: Vec<DbControl>, |
| 336 | } |
| 337 | |
| 338 | struct DbControl { |
| 339 | id: String, |
| 340 | name: Vec<u8>, |
| 341 | address: u8, |
| 342 | delay: c_int, |
| 343 | control_type: c_int, |
| 344 | refresh: c_int, |
| 345 | values: Vec<DbValue>, |
| 346 | } |
| 347 | |
| 348 | struct DbValue { |
| 349 | id: String, |
| 350 | name: Vec<u8>, |
| 351 | value16: u16, |
| 352 | } |
| 353 | |
| 354 | struct ParsedMonitorControls { |
| 355 | controls: Vec<MonitorControl>, |
| 356 | elements: Vec<MonitorElement>, |
| 357 | } |
| 358 | |
| 359 | struct MonitorElement { |
| 360 | name: String, |
| 361 | id: Option<String>, |
| 362 | line: u32, |
| 363 | } |
| 364 | |
| 365 | struct MonitorControl { |
| 366 | id: String, |
| 367 | raw_address: Option<String>, |
| 368 | raw_delay: Option<String>, |
| 369 | values: Vec<MonitorValue>, |
| 370 | child_index: usize, |
| 371 | } |
| 372 | |
| 373 | struct MonitorValue { |
| 374 | element_name: String, |
| 375 | id: Option<String>, |
| 376 | raw_value: Option<String>, |
| 377 | line: u32, |
| 378 | } |
| 379 | |
| 380 | #[no_mangle] |
| 381 | pub unsafe extern "C" fn ddcci_init_db(usedatadir: *mut c_char) -> c_int { |
| 382 | let datadir = if usedatadir.is_null() { |
| 383 | PathBuf::from(DEFAULT_DATADIR) |
| 384 | } else { |
| 385 | pathbuf_from_c_path(usedatadir) |
| 386 | }; |
| 387 | |
| 388 | *DB_CONTEXT.lock().unwrap() = None; |
| 389 | match load_options(&datadir) { |
| 390 | Ok(options) => { |
| 391 | *DB_CONTEXT.lock().unwrap() = Some(DbContext { datadir, options }); |
| 392 | 1 |
| 393 | } |
| 394 | Err(err) => { |
| 395 | eprintln!("{err}"); |
| 396 | 0 |
| 397 | } |
| 398 | } |
| 399 | } |
| 400 | |
| 401 | unsafe fn pathbuf_from_c_path(path: *const c_char) -> PathBuf { |
| 402 | #[cfg(unix)] |
| 403 | { |
| 404 | use std::ffi::OsStr; |
| 405 | use std::os::unix::ffi::OsStrExt; |
| 406 | |
| 407 | PathBuf::from(OsStr::from_bytes(CStr::from_ptr(path).to_bytes())) |
| 408 | } |
| 409 | #[cfg(not(unix))] |
| 410 | { |
| 411 | PathBuf::from(CStr::from_ptr(path).to_string_lossy().into_owned()) |
| 412 | } |
| 413 | } |
| 414 | |
| 415 | #[no_mangle] |
| 416 | pub unsafe extern "C" fn ddcci_release_db() { |
| 417 | *DB_CONTEXT.lock().unwrap() = None; |
| 418 | } |
| 419 | |
| 420 | #[no_mangle] |
| 421 | pub unsafe extern "C" fn ddcci_create_db( |
| 422 | pnpname: *const c_char, |
| 423 | caps: *mut CCaps, |
| 424 | faulttolerance: c_int, |
| 425 | ) -> *mut CMonitorDb { |
| 426 | if pnpname.is_null() || caps.is_null() { |
| 427 | return ptr::null_mut(); |
| 428 | } |
| 429 | |
| 430 | let pnpname = CStr::from_ptr(pnpname).to_string_lossy().into_owned(); |
| 431 | let context = match DB_CONTEXT.lock().unwrap().clone() { |
| 432 | Some(context) => context, |
| 433 | None => { |
| 434 | eprintln!("Database must be inited before reading a monitor file."); |
| 435 | return ptr::null_mut(); |
| 436 | } |
| 437 | }; |
| 438 | |
| 439 | let mut build = MonitorBuild { |
| 440 | init: INIT_TYPE_UNKNOWN, |
| 441 | groups: groups_from_options(&context.options), |
| 442 | ..MonitorBuild::default() |
| 443 | }; |
| 444 | let mut defined = [false; 256]; |
| 445 | |
| 446 | let result = create_db_protected( |
| 447 | &context, |
| 448 | &mut build, |
| 449 | &pnpname, |
| 450 | caps, |
| 451 | 0, |
| 452 | &mut defined, |
| 453 | faulttolerance != 0, |
| 454 | ); |
| 455 | |
| 456 | if let Err(err) = result { |
| 457 | if !err.missing_profile || faulttolerance == 0 { |
| 458 | eprintln!("{}", err.message); |
| 459 | } |
| 460 | return ptr::null_mut(); |
| 461 | } |
| 462 | |
| 463 | if build.init == INIT_TYPE_UNKNOWN { |
| 464 | if faulttolerance != 0 { |
| 465 | eprintln!("Warning: init mode not set, using standard."); |
| 466 | build.init = INIT_TYPE_STANDARD; |
| 467 | } else { |
| 468 | eprintln!("Error: init mode not set."); |
| 469 | return ptr::null_mut(); |
| 470 | } |
| 471 | } |
| 472 | |
| 473 | prune_empty_groups(&mut build.groups); |
| 474 | match alloc_monitor(&build) { |
| 475 | Some(monitor) => monitor, |
| 476 | None => ptr::null_mut(), |
| 477 | } |
| 478 | } |
| 479 | |
| 480 | #[no_mangle] |
| 481 | pub unsafe extern "C" fn ddcci_free_db(monitor: *mut CMonitorDb) { |
| 482 | free_monitor(monitor); |
| 483 | } |
| 484 | |
| 485 | fn load_options(datadir: &Path) -> Result<OptionsDb, String> { |
| 486 | let path = datadir.join("options.xml"); |
| 487 | let xml = read_xml_file(&path) |
| 488 | .map_err(|err| format!("I/O error while reading options.xml: {err}."))?; |
| 489 | let doc = |
| 490 | Document::parse(&xml).map_err(|_| "Document not parsed successfully.".to_string())?; |
| 491 | let root = doc.root_element(); |
| 492 | if root.tag_name().name() != "options" { |
| 493 | return Err(format!( |
| 494 | "options.xml of the wrong type, root node {} != options", |
| 495 | root.tag_name().name() |
| 496 | )); |
| 497 | } |
| 498 | |
| 499 | let version = root.attribute("dbversion").ok_or_else(|| { |
| 500 | "options.xml dbversion attribute missing, please update your database.".to_string() |
| 501 | })?; |
| 502 | let _date = root.attribute("date").ok_or_else(|| { |
| 503 | "options.xml date attribute missing, please update your database.".to_string() |
| 504 | })?; |
| 505 | let version = |
| 506 | parse_int(version).map_err(|_| "Can't convert version to int.".to_string())?; |
| 507 | if version > DBVERSION { |
| 508 | return Err(format!( |
| 509 | "options.xml dbversion ({version}) is greater than the supported version ({DBVERSION}).\nPlease update ddccontrol program." |
| 510 | )); |
| 511 | } |
| 512 | if version < DBVERSION { |
| 513 | return Err(format!( |
| 514 | "options.xml dbversion ({version}) is less than the supported version ({DBVERSION}).\nPlease update ddccontrol database." |
| 515 | )); |
| 516 | } |
| 517 | |
| 518 | let mut options = OptionsDb::default(); |
| 519 | for group in element_children(root).filter(|node| node.tag_name().name() == "group") { |
| 520 | let name = required_attr(group, "name")?.to_string(); |
| 521 | let mut option_group = OptionGroup { |
| 522 | name, |
| 523 | subgroups: Vec::new(), |
| 524 | }; |
| 525 | for subgroup in |
| 526 | element_children(group).filter(|node| node.tag_name().name() == "subgroup") |
| 527 | { |
| 528 | let name = required_attr(subgroup, "name")?.to_string(); |
| 529 | let pattern = subgroup.attribute("pattern").map(ToString::to_string); |
| 530 | let mut option_subgroup = OptionSubgroup { |
| 531 | name, |
| 532 | pattern, |
| 533 | controls: Vec::new(), |
| 534 | }; |
| 535 | for control in |
| 536 | element_children(subgroup).filter(|node| node.tag_name().name() == "control") |
| 537 | { |
| 538 | let refresh = match control.attribute("refresh") { |
| 539 | Some("none") | None => REFRESH_TYPE_NONE, |
| 540 | Some("all") => REFRESH_TYPE_ALL, |
| 541 | Some(_) => { |
| 542 | return Err(node_error( |
| 543 | control, |
| 544 | "Invalid refresh type (!= none, != all).", |
| 545 | )) |
| 546 | } |
| 547 | }; |
| 548 | let control_type = match required_attr(control, "type")? { |
| 549 | "value" => CONTROL_TYPE_VALUE, |
| 550 | "command" => CONTROL_TYPE_COMMAND, |
| 551 | "list" => CONTROL_TYPE_LIST, |
| 552 | _ => return Err(node_error(control, "Invalid type.")), |
| 553 | }; |
| 554 | let mut option_control = OptionControl { |
| 555 | id: required_attr(control, "id")?.to_string(), |
| 556 | name: required_attr(control, "name")?.to_string(), |
| 557 | control_type, |
| 558 | refresh, |
| 559 | values: Vec::new(), |
| 560 | }; |
| 561 | for value in |
| 562 | element_children(control).filter(|node| node.tag_name().name() == "value") |
| 563 | { |
| 564 | option_control.values.push(OptionValue { |
| 565 | id: required_attr(value, "id")?.to_string(), |
| 566 | name: value.attribute("name").map(ToString::to_string), |
| 567 | }); |
| 568 | } |
| 569 | option_subgroup.controls.push(option_control); |
| 570 | } |
| 571 | option_group.subgroups.push(option_subgroup); |
| 572 | } |
| 573 | options.groups.push(option_group); |
| 574 | } |
| 575 | |
| 576 | Ok(options) |
| 577 | } |
| 578 | |
| 579 | fn create_db_protected( |
| 580 | context: &DbContext, |
| 581 | build: &mut MonitorBuild, |
| 582 | pnpname: &str, |
| 583 | caps: *mut CCaps, |
| 584 | recursionlevel: usize, |
| 585 | defined: &mut [bool; 256], |
| 586 | faulttolerance: bool, |
| 587 | ) -> Result<(), DbError> { |
| 588 | if !is_valid_monitor_profile_name(pnpname) { |
| 589 | return Err(DbError::new(format!( |
| 590 | "Invalid monitor profile name ({pnpname})." |
| 591 | ))); |
| 592 | } |
| 593 | if recursionlevel > 15 { |
| 594 | return Err(DbError::new(format!( |
| 595 | "Error, include recursion level > 15 (file: {pnpname})." |
| 596 | ))); |
| 597 | } |
| 598 | |
| 599 | let path = context |
| 600 | .datadir |
| 601 | .join("monitor") |
| 602 | .join(format!("{pnpname}.xml")); |
| 603 | let xml = match read_xml_file(&path) { |
| 604 | Ok(xml) => xml, |
| 605 | Err(err) if err.kind() == std::io::ErrorKind::NotFound => { |
| 606 | return Err(DbError::missing(format!( |
| 607 | "Cannot access {}: {err}", |
| 608 | path.display() |
| 609 | ))); |
| 610 | } |
| 611 | Err(err) => { |
| 612 | return Err(DbError::new(format!( |
| 613 | "Cannot access {}: {err}", |
| 614 | path.display() |
| 615 | ))); |
| 616 | } |
| 617 | }; |
| 618 | let doc = Document::parse(&xml) |
| 619 | .map_err(|_| DbError::new("Document not parsed successfully.".to_string()))?; |
| 620 | let root = doc.root_element(); |
| 621 | if root.tag_name().name() != "monitor" { |
| 622 | return Err(DbError::new(format!( |
| 623 | "monitor/{pnpname}.xml of the wrong type, root node {} != monitor", |
| 624 | root.tag_name().name() |
| 625 | ))); |
| 626 | } |
| 627 | |
| 628 | if build.name.is_none() { |
| 629 | build.name = Some( |
| 630 | root.attribute("name") |
| 631 | .ok_or_else(|| DbError::new(node_error(root, "Can't find name property.")))? |
| 632 | .as_bytes() |
| 633 | .to_vec(), |
| 634 | ); |
| 635 | } |
| 636 | |
| 637 | if build.init == INIT_TYPE_UNKNOWN { |
| 638 | if let Some(init) = root.attribute("init") { |
| 639 | build.init = match init { |
| 640 | "standard" => INIT_TYPE_STANDARD, |
| 641 | "samsung" => INIT_TYPE_SAMSUNG, |
| 642 | _ => return Err(DbError::new(node_error(root, "Invalid type."))), |
| 643 | }; |
| 644 | } |
| 645 | } |
| 646 | |
| 647 | if root.attribute("caps").is_some() { |
| 648 | if faulttolerance { |
| 649 | eprintln!("Warning: caps property is deprecated."); |
| 650 | } else { |
| 651 | return Err(DbError::new( |
| 652 | "Error: caps property is deprecated.".to_string(), |
| 653 | )); |
| 654 | } |
| 655 | } |
| 656 | if root.attribute("include").is_some() { |
| 657 | if faulttolerance { |
| 658 | eprintln!("Warning: include property is deprecated."); |
| 659 | } else { |
| 660 | return Err(DbError::new( |
| 661 | "Error: include property is deprecated.".to_string(), |
| 662 | )); |
| 663 | } |
| 664 | } |
| 665 | |
| 666 | let mut controls_or_include = false; |
| 667 | let mut seen_controls = false; |
| 668 | for child in element_children(root) { |
| 669 | match child.tag_name().name() { |
| 670 | "caps" => { |
| 671 | let remove = child.attribute("remove"); |
| 672 | let add = child.attribute("add"); |
| 673 | if remove.is_none() && add.is_none() { |
| 674 | return Err(DbError::new(node_error( |
| 675 | child, |
| 676 | "Can't find add or remove property in caps.", |
| 677 | ))); |
| 678 | } |
| 679 | if let Some(remove) = remove { |
| 680 | apply_caps(remove, caps, 0) |
| 681 | .map_err(|_| DbError::new(node_error(child, "Invalid remove caps.")))?; |
| 682 | } |
| 683 | if let Some(add) = add { |
| 684 | apply_caps(add, caps, 1) |
| 685 | .map_err(|_| DbError::new(node_error(child, "Invalid add caps.")))?; |
| 686 | } |
| 687 | } |
| 688 | "include" => { |
| 689 | controls_or_include = true; |
| 690 | let file = required_attr(child, "file").map_err(DbError::new)?; |
| 691 | create_db_protected( |
| 692 | context, |
| 693 | build, |
| 694 | file, |
| 695 | caps, |
| 696 | recursionlevel + 1, |
| 697 | defined, |
| 698 | faulttolerance, |
| 699 | )?; |
| 700 | } |
| 701 | "controls" => { |
| 702 | if seen_controls { |
| 703 | return Err(DbError::new(node_error( |
| 704 | child, |
| 705 | "Two controls part in XML file.", |
| 706 | ))); |
| 707 | } |
| 708 | seen_controls = true; |
| 709 | controls_or_include = true; |
| 710 | let monitor_controls = parse_monitor_controls(child).map_err(DbError::new)?; |
| 711 | add_controls_from_options( |
| 712 | build, |
| 713 | &context.options, |
| 714 | &monitor_controls, |
| 715 | caps, |
| 716 | defined, |
| 717 | faulttolerance, |
| 718 | )?; |
| 719 | } |
| 720 | _ => {} |
| 721 | } |
| 722 | } |
| 723 | |
| 724 | if !controls_or_include { |
| 725 | return Err(DbError::new( |
| 726 | "document of the wrong type, can't find controls or include.".to_string(), |
| 727 | )); |
| 728 | } |
| 729 | |
| 730 | Ok(()) |
| 731 | } |
| 732 | |
| 733 | fn add_controls_from_options( |
| 734 | build: &mut MonitorBuild, |
| 735 | options: &OptionsDb, |
| 736 | monitor_controls: &ParsedMonitorControls, |
| 737 | caps: *mut CCaps, |
| 738 | defined: &mut [bool; 256], |
| 739 | faulttolerance: bool, |
| 740 | ) -> Result<(), DbError> { |
| 741 | let mut matched = vec![false; monitor_controls.elements.len()]; |
| 742 | |
| 743 | for (group_index, option_group) in options.groups.iter().enumerate() { |
| 744 | for (subgroup_index, option_subgroup) in option_group.subgroups.iter().enumerate() { |
| 745 | for option_control in &option_subgroup.controls { |
| 746 | let Some(monitor_control) = monitor_controls |
| 747 | .controls |
| 748 | .iter() |
| 749 | .find(|control| control.id == option_control.id) |
| 750 | else { |
| 751 | continue; |
| 752 | }; |
| 753 | |
| 754 | matched[monitor_control.child_index] = true; |
| 755 | let address = monitor_control_address(monitor_control)? as usize; |
| 756 | unsafe { |
| 757 | if (*caps).vcp[address].is_null() { |
| 758 | continue; |
| 759 | } |
| 760 | } |
| 761 | if defined[address] { |
| 762 | continue; |
| 763 | } |
| 764 | |
| 765 | let mut values = |
| 766 | get_value_list(option_control, monitor_control, faulttolerance)?; |
| 767 | if option_control.control_type == CONTROL_TYPE_COMMAND && values.is_empty() { |
| 768 | values.push(DbValue { |
| 769 | id: "default".to_string(), |
| 770 | name: translate(&option_control.name), |
| 771 | value16: 0x01, |
| 772 | }); |
| 773 | } |
| 774 | |
| 775 | let control = DbControl { |
| 776 | id: option_control.id.clone(), |
| 777 | name: translate(&option_control.name), |
| 778 | address: address as u8, |
| 779 | delay: monitor_control_delay(monitor_control)?, |
| 780 | control_type: option_control.control_type, |
| 781 | refresh: option_control.refresh, |
| 782 | values, |
| 783 | }; |
| 784 | build.groups[group_index].subgroups[subgroup_index] |
| 785 | .controls |
| 786 | .push(control); |
| 787 | defined[address] = true; |
| 788 | } |
| 789 | } |
| 790 | } |
| 791 | |
| 792 | for (index, control) in monitor_controls.elements.iter().enumerate() { |
| 793 | if !matched[index] { |
| 794 | eprintln!( |
| 795 | "Element {} (id={}) has not been found (line {}).", |
| 796 | control.name, |
| 797 | control.id.as_deref().unwrap_or("(null)"), |
| 798 | control.line |
| 799 | ); |
| 800 | if !faulttolerance { |
| 801 | return Err(DbError::new( |
| 802 | "Unmatched control in monitor XML.".to_string(), |
| 803 | )); |
| 804 | } |
| 805 | } |
| 806 | } |
| 807 | |
| 808 | Ok(()) |
| 809 | } |
| 810 | |
| 811 | fn read_xml_file(path: &Path) -> std::io::Result<String> { |
| 812 | let bytes = fs::read(path)?; |
| 813 | Ok(decode_xml_bytes(&bytes).into_owned()) |
| 814 | } |
| 815 | |
| 816 | fn decode_xml_bytes(bytes: &[u8]) -> Cow<'_, str> { |
| 817 | let encoding = xml_declared_encoding(bytes).unwrap_or(UTF_8); |
| 818 | let (decoded, _, _) = encoding.decode(bytes); |
| 819 | decoded |
| 820 | } |
| 821 | |
| 822 | fn xml_declared_encoding(bytes: &[u8]) -> Option<&'static Encoding> { |
| 823 | let prefix_len = bytes.len().min(256); |
| 824 | let prefix = &bytes[..prefix_len]; |
| 825 | let declaration_start = prefix.iter().position(|byte| !byte.is_ascii_whitespace())?; |
| 826 | let prefix = &prefix[declaration_start..]; |
| 827 | if !prefix.starts_with(b"<?xml") { |
| 828 | return None; |
| 829 | } |
| 830 | let declaration_end = prefix |
| 831 | .windows(2) |
| 832 | .position(|window| window == b"?>") |
| 833 | .unwrap_or(prefix.len()); |
| 834 | let declaration = &prefix[..declaration_end]; |
| 835 | let encoding_index = declaration |
| 836 | .windows("encoding".len()) |
| 837 | .position(|window| window == b"encoding")?; |
| 838 | let after_encoding = &declaration[encoding_index + "encoding".len()..]; |
| 839 | let after_encoding = trim_ascii_bytes_start(after_encoding); |
| 840 | let after_equals = trim_ascii_bytes_start(after_encoding.strip_prefix(b"=")?); |
| 841 | let quote = after_equals.first().copied()?; |
| 842 | if quote != b'\'' && quote != b'"' { |
| 843 | return None; |
| 844 | } |
| 845 | let label_end = after_equals[1..] |
| 846 | .iter() |
| 847 | .position(|byte| *byte == quote) |
| 848 | .map(|index| index + 1)?; |
| 849 | Encoding::for_label(&after_equals[1..label_end]) |
| 850 | } |
| 851 | |
| 852 | fn trim_ascii_bytes_start(input: &[u8]) -> &[u8] { |
| 853 | let start = input |
| 854 | .iter() |
| 855 | .position(|byte| !byte.is_ascii_whitespace()) |
| 856 | .unwrap_or(input.len()); |
| 857 | &input[start..] |
| 858 | } |
| 859 | |
| 860 | fn monitor_control_address(monitor_control: &MonitorControl) -> Result<u8, DbError> { |
| 861 | let raw_address = monitor_control |
| 862 | .raw_address |
| 863 | .as_deref() |
| 864 | .ok_or_else(|| DbError::new("Can't find address property.".to_string()))?; |
| 865 | let address = parse_int(raw_address) |
| 866 | .map_err(|_| DbError::new("Can't convert address to int.".to_string()))?; |
| 867 | if !(0..=255).contains(&address) { |
| 868 | return Err(DbError::new( |
| 869 | "Address is outside the supported 0-255 range.".to_string(), |
| 870 | )); |
| 871 | } |
| 872 | Ok(address as u8) |
| 873 | } |
| 874 | |
| 875 | fn monitor_control_delay(monitor_control: &MonitorControl) -> Result<c_int, DbError> { |
| 876 | match monitor_control.raw_delay.as_deref() { |
| 877 | Some(delay) => parse_int_decimal(delay) |
| 878 | .map(|delay| delay as c_int) |
| 879 | .map_err(|_| DbError::new("Can't convert delay to int.".to_string())), |
| 880 | None => Ok(-1), |
| 881 | } |
| 882 | } |
| 883 | |
| 884 | fn get_value_list( |
| 885 | option_control: &OptionControl, |
| 886 | monitor_control: &MonitorControl, |
| 887 | faulttolerance: bool, |
| 888 | ) -> Result<Vec<DbValue>, DbError> { |
| 889 | let mut values = Vec::new(); |
| 890 | let mut matched = vec![false; monitor_control.values.len()]; |
| 891 | |
| 892 | for option_value in &option_control.values { |
| 893 | if let Some((monitor_index, monitor_value)) = monitor_control |
| 894 | .values |
| 895 | .iter() |
| 896 | .enumerate() |
| 897 | .find(|(_, value)| { |
| 898 | value.element_name == "value" |
| 899 | && value.id.as_deref() == Some(option_value.id.as_str()) |
| 900 | }) |
| 901 | { |
| 902 | matched[monitor_index] = true; |
| 903 | let raw_value = monitor_value |
| 904 | .raw_value |
| 905 | .as_deref() |
| 906 | .ok_or_else(|| DbError::new("Can't find value property.".to_string()))?; |
| 907 | let parsed_value = parse_int(raw_value) |
| 908 | .map_err(|_| DbError::new("Can't convert value to int.".to_string()))?; |
| 909 | if !(0..=u16::MAX as i64).contains(&parsed_value) { |
| 910 | return Err(DbError::new( |
| 911 | "Value is outside the supported 0-65535 range.".to_string(), |
| 912 | )); |
| 913 | } |
| 914 | let name = if option_control.control_type == CONTROL_TYPE_COMMAND { |
| 915 | option_value |
| 916 | .name |
| 917 | .as_ref() |
| 918 | .unwrap_or(&option_control.name) |
| 919 | .to_string() |
| 920 | } else { |
| 921 | option_value |
| 922 | .name |
| 923 | .clone() |
| 924 | .ok_or_else(|| DbError::new("Can't find name property.".to_string()))? |
| 925 | }; |
| 926 | values.push(DbValue { |
| 927 | id: option_value.id.clone(), |
| 928 | name: translate(&name), |
| 929 | value16: parsed_value as u16, |
| 930 | }); |
| 931 | } |
| 932 | } |
| 933 | |
| 934 | for (index, value) in monitor_control.values.iter().enumerate() { |
| 935 | if !matched[index] { |
| 936 | eprintln!( |
| 937 | "Element {} (id={}) has not been found (line {}).", |
| 938 | value.element_name, |
| 939 | value.id.as_deref().unwrap_or("(null)"), |
| 940 | value.line |
| 941 | ); |
| 942 | if !faulttolerance { |
| 943 | return Err(DbError::new("Unmatched value in monitor XML.".to_string())); |
| 944 | } |
| 945 | } |
| 946 | } |
| 947 | |
| 948 | Ok(values) |
| 949 | } |
| 950 | |
| 951 | fn parse_monitor_controls(node: Node<'_, '_>) -> Result<ParsedMonitorControls, String> { |
| 952 | let mut controls = Vec::new(); |
| 953 | let mut elements = Vec::new(); |
| 954 | for (child_index, control) in element_children(node).enumerate() { |
| 955 | elements.push(MonitorElement { |
| 956 | name: control.tag_name().name().to_string(), |
| 957 | id: control.attribute("id").map(ToString::to_string), |
| 958 | line: line(control), |
| 959 | }); |
| 960 | if control.tag_name().name() != "control" { |
| 961 | continue; |
| 962 | } |
| 963 | let Some(id) = control.attribute("id") else { |
| 964 | continue; |
| 965 | }; |
| 966 | let mut monitor_control = MonitorControl { |
| 967 | id: id.to_string(), |
| 968 | raw_address: control.attribute("address").map(ToString::to_string), |
| 969 | raw_delay: control.attribute("delay").map(ToString::to_string), |
| 970 | values: Vec::new(), |
| 971 | child_index, |
| 972 | }; |
| 973 | for value in element_children(control) { |
| 974 | monitor_control.values.push(MonitorValue { |
| 975 | element_name: value.tag_name().name().to_string(), |
| 976 | id: value.attribute("id").map(ToString::to_string), |
| 977 | raw_value: value.attribute("value").map(ToString::to_string), |
| 978 | line: line(value), |
| 979 | }); |
| 980 | } |
| 981 | controls.push(monitor_control); |
| 982 | } |
| 983 | Ok(ParsedMonitorControls { controls, elements }) |
| 984 | } |
| 985 | |
| 986 | fn groups_from_options(options: &OptionsDb) -> Vec<DbGroup> { |
| 987 | options |
| 988 | .groups |
| 989 | .iter() |
| 990 | .map(|group| DbGroup { |
| 991 | name: translate(&group.name), |
| 992 | subgroups: group |
| 993 | .subgroups |
| 994 | .iter() |
| 995 | .map(|subgroup| DbSubgroup { |
| 996 | name: translate(&subgroup.name), |
| 997 | pattern: subgroup.pattern.clone(), |
| 998 | controls: Vec::new(), |
| 999 | }) |
| 1000 | .collect(), |
| 1001 | }) |
| 1002 | .collect() |
| 1003 | } |
| 1004 | |
| 1005 | fn prune_empty_groups(groups: &mut Vec<DbGroup>) { |
| 1006 | for group in groups.iter_mut() { |
| 1007 | group |
| 1008 | .subgroups |
| 1009 | .retain(|subgroup| !subgroup.controls.is_empty()); |
| 1010 | } |
| 1011 | groups.retain(|group| !group.subgroups.is_empty()); |
| 1012 | } |
| 1013 | |
| 1014 | fn apply_caps(input: &str, caps: *mut CCaps, add: c_int) -> Result<(), ()> { |
| 1015 | let input = CString::new(input).map_err(|_| ())?; |
| 1016 | let parsed = unsafe { ddccontrol_caps_parse(input.as_ptr(), caps, add) }; |
| 1017 | if parsed <= 0 { |
| 1018 | Err(()) |
| 1019 | } else { |
| 1020 | Ok(()) |
| 1021 | } |
| 1022 | } |
| 1023 | |
| 1024 | fn alloc_monitor(build: &MonitorBuild) -> Option<*mut CMonitorDb> { |
| 1025 | unsafe { |
| 1026 | let name = c_bytes(build.name.as_deref().unwrap_or_default())?; |
| 1027 | let group_list = match alloc_groups(&build.groups) { |
| 1028 | Some(group_list) => group_list, |
| 1029 | None => { |
| 1030 | free(name as *mut c_void); |
| 1031 | return None; |
| 1032 | } |
| 1033 | }; |
| 1034 | |
| 1035 | let monitor = malloc(std::mem::size_of::<CMonitorDb>()) as *mut CMonitorDb; |
| 1036 | if monitor.is_null() { |
| 1037 | free(name as *mut c_void); |
| 1038 | free_groups(group_list); |
| 1039 | return None; |
| 1040 | } |
| 1041 | ptr::write( |
| 1042 | monitor, |
| 1043 | CMonitorDb { |
| 1044 | name, |
| 1045 | init: build.init, |
| 1046 | group_list, |
| 1047 | }, |
| 1048 | ); |
| 1049 | Some(monitor) |
| 1050 | } |
| 1051 | } |
| 1052 | |
| 1053 | unsafe fn alloc_groups(groups: &[DbGroup]) -> Option<*mut CGroupDb> { |
| 1054 | let mut head = ptr::null_mut(); |
| 1055 | let mut tail = &mut head as *mut *mut CGroupDb; |
| 1056 | for group in groups { |
| 1057 | let name = match c_bytes(&group.name) { |
| 1058 | Some(name) => name, |
| 1059 | None => { |
| 1060 | free_groups(head); |
| 1061 | return None; |
| 1062 | } |
| 1063 | }; |
| 1064 | let subgroup_list = match alloc_subgroups(&group.subgroups) { |
| 1065 | Some(subgroup_list) => subgroup_list, |
| 1066 | None => { |
| 1067 | free(name as *mut c_void); |
| 1068 | free_groups(head); |
| 1069 | return None; |
| 1070 | } |
| 1071 | }; |
| 1072 | let node = malloc(std::mem::size_of::<CGroupDb>()) as *mut CGroupDb; |
| 1073 | if node.is_null() { |
| 1074 | free(name as *mut c_void); |
| 1075 | free_subgroups(subgroup_list); |
| 1076 | free_groups(head); |
| 1077 | return None; |
| 1078 | } |
| 1079 | ptr::write( |
| 1080 | node, |
| 1081 | CGroupDb { |
| 1082 | name, |
| 1083 | next: ptr::null_mut(), |
| 1084 | subgroup_list, |
| 1085 | }, |
| 1086 | ); |
| 1087 | *tail = node; |
| 1088 | tail = &mut (*node).next; |
| 1089 | } |
| 1090 | Some(head) |
| 1091 | } |
| 1092 | |
| 1093 | unsafe fn alloc_subgroups(subgroups: &[DbSubgroup]) -> Option<*mut CSubgroupDb> { |
| 1094 | let mut head = ptr::null_mut(); |
| 1095 | let mut tail = &mut head as *mut *mut CSubgroupDb; |
| 1096 | for subgroup in subgroups { |
| 1097 | let name = match c_bytes(&subgroup.name) { |
| 1098 | Some(name) => name, |
| 1099 | None => { |
| 1100 | free_subgroups(head); |
| 1101 | return None; |
| 1102 | } |
| 1103 | }; |
| 1104 | let pattern = match &subgroup.pattern { |
| 1105 | Some(pattern) => match c_string(pattern) { |
| 1106 | Some(pattern) => pattern, |
| 1107 | None => { |
| 1108 | free(name as *mut c_void); |
| 1109 | free_subgroups(head); |
| 1110 | return None; |
| 1111 | } |
| 1112 | }, |
| 1113 | None => ptr::null_mut(), |
| 1114 | }; |
| 1115 | let control_list = match alloc_controls(&subgroup.controls) { |
| 1116 | Some(control_list) => control_list, |
| 1117 | None => { |
| 1118 | free(name as *mut c_void); |
| 1119 | free(pattern as *mut c_void); |
| 1120 | free_subgroups(head); |
| 1121 | return None; |
| 1122 | } |
| 1123 | }; |
| 1124 | let node = malloc(std::mem::size_of::<CSubgroupDb>()) as *mut CSubgroupDb; |
| 1125 | if node.is_null() { |
| 1126 | free(name as *mut c_void); |
| 1127 | free(pattern as *mut c_void); |
| 1128 | free_controls(control_list); |
| 1129 | free_subgroups(head); |
| 1130 | return None; |
| 1131 | } |
| 1132 | ptr::write( |
| 1133 | node, |
| 1134 | CSubgroupDb { |
| 1135 | name, |
| 1136 | pattern, |
| 1137 | next: ptr::null_mut(), |
| 1138 | control_list, |
| 1139 | }, |
| 1140 | ); |
| 1141 | *tail = node; |
| 1142 | tail = &mut (*node).next; |
| 1143 | } |
| 1144 | Some(head) |
| 1145 | } |
| 1146 | |
| 1147 | unsafe fn alloc_controls(controls: &[DbControl]) -> Option<*mut CControlDb> { |
| 1148 | let mut head = ptr::null_mut(); |
| 1149 | let mut tail = &mut head as *mut *mut CControlDb; |
| 1150 | for control in controls { |
| 1151 | let id = match c_string(&control.id) { |
| 1152 | Some(id) => id, |
| 1153 | None => { |
| 1154 | free_controls(head); |
| 1155 | return None; |
| 1156 | } |
| 1157 | }; |
| 1158 | let name = match c_bytes(&control.name) { |
| 1159 | Some(name) => name, |
| 1160 | None => { |
| 1161 | free(id as *mut c_void); |
| 1162 | free_controls(head); |
| 1163 | return None; |
| 1164 | } |
| 1165 | }; |
| 1166 | let value_list = match alloc_values(&control.values) { |
| 1167 | Some(value_list) => value_list, |
| 1168 | None => { |
| 1169 | free(id as *mut c_void); |
| 1170 | free(name as *mut c_void); |
| 1171 | free_controls(head); |
| 1172 | return None; |
| 1173 | } |
| 1174 | }; |
| 1175 | let node = malloc(std::mem::size_of::<CControlDb>()) as *mut CControlDb; |
| 1176 | if node.is_null() { |
| 1177 | free(id as *mut c_void); |
| 1178 | free(name as *mut c_void); |
| 1179 | free_values(value_list); |
| 1180 | free_controls(head); |
| 1181 | return None; |
| 1182 | } |
| 1183 | ptr::write( |
| 1184 | node, |
| 1185 | CControlDb { |
| 1186 | id, |
| 1187 | name, |
| 1188 | address: control.address, |
| 1189 | delay: control.delay, |
| 1190 | control_type: control.control_type, |
| 1191 | refresh: control.refresh, |
| 1192 | next: ptr::null_mut(), |
| 1193 | value_list, |
| 1194 | }, |
| 1195 | ); |
| 1196 | *tail = node; |
| 1197 | tail = &mut (*node).next; |
| 1198 | } |
| 1199 | Some(head) |
| 1200 | } |
| 1201 | |
| 1202 | unsafe fn alloc_values(values: &[DbValue]) -> Option<*mut CValueDb> { |
| 1203 | let mut head = ptr::null_mut(); |
| 1204 | let mut tail = &mut head as *mut *mut CValueDb; |
| 1205 | for value in values { |
| 1206 | let id = match c_string(&value.id) { |
| 1207 | Some(id) => id, |
| 1208 | None => { |
| 1209 | free_values(head); |
| 1210 | return None; |
| 1211 | } |
| 1212 | }; |
| 1213 | let name = match c_bytes(&value.name) { |
| 1214 | Some(name) => name, |
| 1215 | None => { |
| 1216 | free(id as *mut c_void); |
| 1217 | free_values(head); |
| 1218 | return None; |
| 1219 | } |
| 1220 | }; |
| 1221 | let node = malloc(std::mem::size_of::<CValueDbPrivate>()) as *mut CValueDbPrivate; |
| 1222 | if node.is_null() { |
| 1223 | free(id as *mut c_void); |
| 1224 | free(name as *mut c_void); |
| 1225 | free_values(head); |
| 1226 | return None; |
| 1227 | } |
| 1228 | ptr::write( |
| 1229 | node, |
| 1230 | CValueDbPrivate { |
| 1231 | public_value: CValueDb { |
| 1232 | id, |
| 1233 | name, |
| 1234 | value: (value.value16 & 0xff) as c_uchar, |
| 1235 | next: ptr::null_mut(), |
| 1236 | }, |
| 1237 | value16: value.value16, |
| 1238 | }, |
| 1239 | ); |
| 1240 | *tail = &mut (*node).public_value; |
| 1241 | tail = &mut (*node).public_value.next; |
| 1242 | } |
| 1243 | Some(head) |
| 1244 | } |
| 1245 | |
| 1246 | unsafe fn free_monitor(monitor: *mut CMonitorDb) { |
| 1247 | if monitor.is_null() { |
| 1248 | return; |
| 1249 | } |
| 1250 | free((*monitor).name as *mut c_void); |
| 1251 | free_groups((*monitor).group_list); |
| 1252 | free(monitor as *mut c_void); |
| 1253 | } |
| 1254 | |
| 1255 | unsafe fn free_groups(mut group: *mut CGroupDb) { |
| 1256 | while !group.is_null() { |
| 1257 | let next = (*group).next; |
| 1258 | free((*group).name as *mut c_void); |
| 1259 | free_subgroups((*group).subgroup_list); |
| 1260 | free(group as *mut c_void); |
| 1261 | group = next; |
| 1262 | } |
| 1263 | } |
| 1264 | |
| 1265 | unsafe fn free_subgroups(mut subgroup: *mut CSubgroupDb) { |
| 1266 | while !subgroup.is_null() { |
| 1267 | let next = (*subgroup).next; |
| 1268 | free((*subgroup).name as *mut c_void); |
| 1269 | free((*subgroup).pattern as *mut c_void); |
| 1270 | free_controls((*subgroup).control_list); |
| 1271 | free(subgroup as *mut c_void); |
| 1272 | subgroup = next; |
| 1273 | } |
| 1274 | } |
| 1275 | |
| 1276 | unsafe fn free_controls(mut control: *mut CControlDb) { |
| 1277 | while !control.is_null() { |
| 1278 | let next = (*control).next; |
| 1279 | free((*control).id as *mut c_void); |
| 1280 | free((*control).name as *mut c_void); |
| 1281 | free_values((*control).value_list); |
| 1282 | free(control as *mut c_void); |
| 1283 | control = next; |
| 1284 | } |
| 1285 | } |
| 1286 | |
| 1287 | unsafe fn free_values(mut value: *mut CValueDb) { |
| 1288 | while !value.is_null() { |
| 1289 | let next = (*value).next; |
| 1290 | free((*value).id as *mut c_void); |
| 1291 | free((*value).name as *mut c_void); |
| 1292 | free(value as *mut c_void); |
| 1293 | value = next; |
| 1294 | } |
| 1295 | } |
| 1296 | |
| 1297 | unsafe fn c_string(input: &str) -> Option<*mut c_uchar> { |
| 1298 | c_bytes(input.as_bytes()) |
| 1299 | } |
| 1300 | |
| 1301 | unsafe fn c_bytes(bytes: &[u8]) -> Option<*mut c_uchar> { |
| 1302 | if bytes.contains(&0) { |
| 1303 | return None; |
| 1304 | } |
| 1305 | let ptr = malloc(bytes.len() + 1) as *mut c_uchar; |
| 1306 | if ptr.is_null() { |
| 1307 | return None; |
| 1308 | } |
| 1309 | ptr::copy_nonoverlapping(bytes.as_ptr(), ptr, bytes.len()); |
| 1310 | *ptr.add(bytes.len()) = 0; |
| 1311 | Some(ptr) |
| 1312 | } |
| 1313 | |
| 1314 | fn translate(input: &str) -> Vec<u8> { |
| 1315 | #[cfg(test)] |
| 1316 | { |
| 1317 | return input.as_bytes().to_vec(); |
| 1318 | } |
| 1319 | |
| 1320 | #[cfg(all(not(test), not(feature = "gettext")))] |
| 1321 | { |
| 1322 | input.as_bytes().to_vec() |
| 1323 | } |
| 1324 | |
| 1325 | #[cfg(all(not(test), feature = "gettext"))] |
| 1326 | { |
| 1327 | let Ok(c_input) = CString::new(input) else { |
| 1328 | return input.as_bytes().to_vec(); |
| 1329 | }; |
| 1330 | unsafe { |
| 1331 | let translated = dgettext(DBPACKAGE.as_ptr() as *const c_char, c_input.as_ptr()); |
| 1332 | if translated.is_null() { |
| 1333 | input.as_bytes().to_vec() |
| 1334 | } else { |
| 1335 | CStr::from_ptr(translated).to_bytes().to_vec() |
| 1336 | } |
| 1337 | } |
| 1338 | } |
| 1339 | } |
| 1340 | |
| 1341 | fn required_attr<'a, 'd>(node: Node<'a, 'd>, name: &str) -> Result<&'a str, String> { |
| 1342 | node.attribute(name) |
| 1343 | .ok_or_else(|| node_error(node, &format!("Can't find {name} property."))) |
| 1344 | } |
| 1345 | |
| 1346 | fn element_children<'a, 'd>(node: Node<'a, 'd>) -> impl Iterator<Item = Node<'a, 'd>> { |
| 1347 | node.children().filter(|child| child.is_element()) |
| 1348 | } |
| 1349 | |
| 1350 | fn node_error(node: Node<'_, '_>, message: &str) -> String { |
| 1351 | format!("Error: {message} @line {}", line(node)) |
| 1352 | } |
| 1353 | |
| 1354 | fn line(node: Node<'_, '_>) -> u32 { |
| 1355 | node.document().text_pos_at(node.range().start).row |
| 1356 | } |
| 1357 | |
| 1358 | fn parse_int(input: &str) -> Result<i64, std::num::ParseIntError> { |
| 1359 | let input = trim_ascii_start(input); |
| 1360 | let (negative, rest) = if let Some(rest) = input.strip_prefix('-') { |
| 1361 | (true, rest) |
| 1362 | } else if let Some(rest) = input.strip_prefix('+') { |
| 1363 | (false, rest) |
| 1364 | } else { |
| 1365 | (false, input) |
| 1366 | }; |
| 1367 | let (radix, digits) = |
| 1368 | if let Some(rest) = rest.strip_prefix("0x").or_else(|| rest.strip_prefix("0X")) { |
| 1369 | (16, rest) |
| 1370 | } else if rest.len() > 1 && rest.starts_with('0') { |
| 1371 | (8, &rest[1..]) |
| 1372 | } else { |
| 1373 | (10, rest) |
| 1374 | }; |
| 1375 | let value = i64::from_str_radix(digits, radix)?; |
| 1376 | Ok(if negative { -value } else { value }) |
| 1377 | } |
| 1378 | |
| 1379 | fn parse_int_decimal(input: &str) -> Result<i64, std::num::ParseIntError> { |
| 1380 | trim_ascii_start(input).parse::<i64>() |
| 1381 | } |
| 1382 | |
| 1383 | fn trim_ascii_start(input: &str) -> &str { |
| 1384 | input.trim_start_matches(|byte: char| byte.is_ascii_whitespace()) |
| 1385 | } |
| 1386 | |
| 1387 | fn is_valid_monitor_profile_name(name: &str) -> bool { |
| 1388 | !name.is_empty() |
| 1389 | && name |
| 1390 | .bytes() |
| 1391 | .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'-') |
| 1392 | } |
| 1393 | |
| 1394 | #[cfg(test)] |
| 1395 | mod compatibility_tests; |
| 1396 | |
| 1397 | #[cfg(test)] |
| 1398 | mod tests { |
| 1399 | use super::*; |
| 1400 | use std::mem::{align_of, size_of}; |
| 1401 | |
| 1402 | fn align_up(value: usize, align: usize) -> usize { |
| 1403 | (value + align - 1) & !(align - 1) |
| 1404 | } |
| 1405 | |
| 1406 | #[test] |
| 1407 | fn monitor_database_ffi_layout_matches_c_abi_contract() { |
| 1408 | assert_eq!(size_of::<c_int>(), 4); |
| 1409 | assert_eq!(size_of::<c_uchar>(), 1); |
| 1410 | assert_eq!(size_of::<c_ushort>(), 2); |
| 1411 | |
| 1412 | assert_eq!(field_offset!(CValueDb, id), 0); |
| 1413 | assert_eq!( |
| 1414 | field_offset!(CValueDb, name), |
| 1415 | align_up(size_of::<*mut c_uchar>(), align_of::<*mut c_uchar>()) |
| 1416 | ); |
| 1417 | assert_eq!( |
| 1418 | field_offset!(CValueDb, value), |
| 1419 | size_of::<*mut c_uchar>() * 2 |
| 1420 | ); |
| 1421 | assert_eq!(field_offset!(CValueDbPrivate, public_value), 0); |
| 1422 | assert!(field_offset!(CValueDbPrivate, value16) >= size_of::<CValueDb>()); |
| 1423 | |
| 1424 | assert_eq!(field_offset!(CControlDb, id), 0); |
| 1425 | assert_eq!(field_offset!(CControlDb, name), size_of::<*mut c_uchar>()); |
| 1426 | assert!(field_offset!(CControlDb, address) > field_offset!(CControlDb, name)); |
| 1427 | assert!(field_offset!(CControlDb, value_list) > field_offset!(CControlDb, next)); |
| 1428 | |
| 1429 | assert_eq!(field_offset!(CSubgroupDb, name), 0); |
| 1430 | assert_eq!( |
| 1431 | field_offset!(CSubgroupDb, pattern), |
| 1432 | size_of::<*mut c_uchar>() |
| 1433 | ); |
| 1434 | assert_eq!(field_offset!(CGroupDb, name), 0); |
| 1435 | assert_eq!(field_offset!(CMonitorDb, name), 0); |
| 1436 | assert_eq!( |
| 1437 | field_offset!(CMonitorDb, init), |
| 1438 | align_up(size_of::<*mut c_uchar>(), align_of::<c_int>()) |
| 1439 | ); |
| 1440 | } |
| 1441 | |
| 1442 | #[cfg(unix)] |
| 1443 | #[test] |
| 1444 | fn c_datadir_paths_preserve_non_utf8_bytes() { |
| 1445 | use std::ffi::CString; |
| 1446 | use std::os::unix::ffi::OsStrExt; |
| 1447 | |
| 1448 | let raw_path = b"/tmp/ddccontrol-\xff-db".to_vec(); |
| 1449 | let c_path = CString::new(raw_path.clone()).unwrap(); |
| 1450 | |
| 1451 | let path = unsafe { pathbuf_from_c_path(c_path.as_ptr()) }; |
| 1452 | |
| 1453 | assert_eq!(path.as_os_str().as_bytes(), raw_path); |
| 1454 | } |
| 1455 | |
| 1456 | #[test] |
| 1457 | fn c_bytes_preserves_non_utf8_labels() { |
| 1458 | let label = b"Contr\xf4le".to_vec(); |
| 1459 | |
| 1460 | let ptr = unsafe { c_bytes(&label).unwrap() }; |
| 1461 | let copied = unsafe { CStr::from_ptr(ptr as *const c_char).to_bytes().to_vec() }; |
| 1462 | unsafe { |
| 1463 | free(ptr as *mut c_void); |
| 1464 | } |
| 1465 | |
| 1466 | assert_eq!(copied, label); |
| 1467 | } |
| 1468 | |
| 1469 | #[test] |
| 1470 | fn decode_xml_bytes_uses_declared_non_utf8_encoding() { |
| 1471 | let xml = |
| 1472 | b"<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><options name=\"Contr\xf4le\"/>"; |
| 1473 | |
| 1474 | let decoded = decode_xml_bytes(xml); |
| 1475 | |
| 1476 | assert!(decoded.contains("Contr\u{00f4}le")); |
| 1477 | } |
| 1478 | |
| 1479 | #[test] |
| 1480 | fn parse_int_matches_strtol_style_database_values() { |
| 1481 | assert_eq!(parse_int(" 1").unwrap(), 1); |
| 1482 | assert_eq!(parse_int("+1").unwrap(), 1); |
| 1483 | assert_eq!(parse_int("-1").unwrap(), -1); |
| 1484 | assert_eq!(parse_int("0x10").unwrap(), 16); |
| 1485 | assert_eq!(parse_int("010").unwrap(), 8); |
| 1486 | assert!(parse_int("09").is_err()); |
| 1487 | assert!(parse_int("1 ").is_err()); |
| 1488 | } |
| 1489 | |
| 1490 | #[test] |
| 1491 | fn unmatched_monitor_values_are_not_parsed() { |
| 1492 | let option_control = OptionControl { |
| 1493 | id: "input".to_string(), |
| 1494 | name: "Input".to_string(), |
| 1495 | control_type: CONTROL_TYPE_LIST, |
| 1496 | refresh: REFRESH_TYPE_NONE, |
| 1497 | values: vec![OptionValue { |
| 1498 | id: "hdmi".to_string(), |
| 1499 | name: Some("HDMI".to_string()), |
| 1500 | }], |
| 1501 | }; |
| 1502 | let monitor_control = MonitorControl { |
| 1503 | id: "input".to_string(), |
| 1504 | raw_address: Some("0x60".to_string()), |
| 1505 | raw_delay: None, |
| 1506 | values: vec![ |
| 1507 | MonitorValue { |
| 1508 | element_name: "value".to_string(), |
| 1509 | id: Some("hdmi".to_string()), |
| 1510 | raw_value: Some(" 1".to_string()), |
| 1511 | line: 1, |
| 1512 | }, |
| 1513 | MonitorValue { |
| 1514 | element_name: "value".to_string(), |
| 1515 | id: Some("unused".to_string()), |
| 1516 | raw_value: Some("not-an-int".to_string()), |
| 1517 | line: 2, |
| 1518 | }, |
| 1519 | ], |
| 1520 | child_index: 0, |
| 1521 | }; |
| 1522 | |
| 1523 | let values = get_value_list(&option_control, &monitor_control, true).unwrap(); |
| 1524 | |
| 1525 | assert_eq!(values.len(), 1); |
| 1526 | assert_eq!(values[0].id, "hdmi"); |
| 1527 | assert_eq!(values[0].value16, 1); |
| 1528 | } |
| 1529 | |
| 1530 | #[test] |
| 1531 | fn parse_monitor_controls_keeps_unknown_control_children_for_validation() { |
| 1532 | let doc = Document::parse( |
| 1533 | r#"<controls> |
| 1534 | <unknown id="bad"/> |
| 1535 | <control id="input" address="0x60"/> |
| 1536 | </controls>"#, |
| 1537 | ) |
| 1538 | .unwrap(); |
| 1539 | |
| 1540 | let parsed = parse_monitor_controls(doc.root_element()).unwrap(); |
| 1541 | |
| 1542 | assert_eq!(parsed.elements.len(), 2); |
| 1543 | assert_eq!(parsed.elements[0].name, "unknown"); |
| 1544 | assert_eq!(parsed.controls.len(), 1); |
| 1545 | assert_eq!(parsed.controls[0].child_index, 1); |
| 1546 | } |
| 1547 | |
| 1548 | #[test] |
| 1549 | fn missing_value_id_is_deferred_until_control_is_matched() { |
| 1550 | let doc = Document::parse( |
| 1551 | r#"<controls> |
| 1552 | <control id="input" address="0x60"> |
| 1553 | <value value="1"/> |
| 1554 | </control> |
| 1555 | </controls>"#, |
| 1556 | ) |
| 1557 | .unwrap(); |
| 1558 | |
| 1559 | let parsed = parse_monitor_controls(doc.root_element()).unwrap(); |
| 1560 | |
| 1561 | assert_eq!(parsed.controls.len(), 1); |
| 1562 | assert!(parsed.controls[0].values[0].id.is_none()); |
| 1563 | } |
| 1564 | |
| 1565 | #[test] |
| 1566 | fn monitor_values_without_id_use_unmatched_validation() { |
| 1567 | let option_control = OptionControl { |
| 1568 | id: "input".to_string(), |
| 1569 | name: "Input".to_string(), |
| 1570 | control_type: CONTROL_TYPE_LIST, |
| 1571 | refresh: REFRESH_TYPE_NONE, |
| 1572 | values: vec![OptionValue { |
| 1573 | id: "hdmi".to_string(), |
| 1574 | name: Some("HDMI".to_string()), |
| 1575 | }], |
| 1576 | }; |
| 1577 | let monitor_control = MonitorControl { |
| 1578 | id: "input".to_string(), |
| 1579 | raw_address: Some("0x60".to_string()), |
| 1580 | raw_delay: None, |
| 1581 | values: vec![MonitorValue { |
| 1582 | element_name: "value".to_string(), |
| 1583 | id: None, |
| 1584 | raw_value: Some("1".to_string()), |
| 1585 | line: 1, |
| 1586 | }], |
| 1587 | child_index: 0, |
| 1588 | }; |
| 1589 | |
| 1590 | assert!(get_value_list(&option_control, &monitor_control, false).is_err()); |
| 1591 | assert!(get_value_list(&option_control, &monitor_control, true).is_ok()); |
| 1592 | } |
| 1593 | |
| 1594 | #[test] |
| 1595 | fn parse_monitor_controls_keeps_control_without_id_unmatched() { |
| 1596 | let doc = Document::parse( |
| 1597 | r#"<controls> |
| 1598 | <control address="0x60"/> |
| 1599 | </controls>"#, |
| 1600 | ) |
| 1601 | .unwrap(); |
| 1602 | |
| 1603 | let parsed = parse_monitor_controls(doc.root_element()).unwrap(); |
| 1604 | |
| 1605 | assert_eq!(parsed.elements.len(), 1); |
| 1606 | assert_eq!(parsed.elements[0].name, "control"); |
| 1607 | assert!(parsed.elements[0].id.is_none()); |
| 1608 | assert!(parsed.controls.is_empty()); |
| 1609 | } |
| 1610 | |
| 1611 | #[test] |
| 1612 | fn parse_monitor_controls_defers_address_and_delay_validation() { |
| 1613 | let doc = Document::parse( |
| 1614 | r#"<controls> |
| 1615 | <control id="unknown" address="not-hex" delay="bad"/> |
| 1616 | </controls>"#, |
| 1617 | ) |
| 1618 | .unwrap(); |
| 1619 | |
| 1620 | let parsed = parse_monitor_controls(doc.root_element()).unwrap(); |
| 1621 | |
| 1622 | assert_eq!(parsed.controls.len(), 1); |
| 1623 | assert!(monitor_control_address(&parsed.controls[0]).is_err()); |
| 1624 | assert!(monitor_control_delay(&parsed.controls[0]).is_err()); |
| 1625 | } |
| 1626 | |
| 1627 | #[test] |
| 1628 | fn unknown_monitor_value_children_use_unmatched_validation() { |
| 1629 | let option_control = OptionControl { |
| 1630 | id: "input".to_string(), |
| 1631 | name: "Input".to_string(), |
| 1632 | control_type: CONTROL_TYPE_LIST, |
| 1633 | refresh: REFRESH_TYPE_NONE, |
| 1634 | values: vec![OptionValue { |
| 1635 | id: "hdmi".to_string(), |
| 1636 | name: Some("HDMI".to_string()), |
| 1637 | }], |
| 1638 | }; |
| 1639 | let monitor_control = MonitorControl { |
| 1640 | id: "input".to_string(), |
| 1641 | raw_address: Some("0x60".to_string()), |
| 1642 | raw_delay: None, |
| 1643 | values: vec![ |
| 1644 | MonitorValue { |
| 1645 | element_name: "value".to_string(), |
| 1646 | id: Some("hdmi".to_string()), |
| 1647 | raw_value: Some("1".to_string()), |
| 1648 | line: 1, |
| 1649 | }, |
| 1650 | MonitorValue { |
| 1651 | element_name: "unknown".to_string(), |
| 1652 | id: Some("extra".to_string()), |
| 1653 | raw_value: None, |
| 1654 | line: 2, |
| 1655 | }, |
| 1656 | ], |
| 1657 | child_index: 0, |
| 1658 | }; |
| 1659 | |
| 1660 | assert!(get_value_list(&option_control, &monitor_control, false).is_err()); |
| 1661 | assert!(get_value_list(&option_control, &monitor_control, true).is_ok()); |
| 1662 | } |
| 1663 | } |
| 1664 | |
| 1665 | #[derive(Debug)] |
| 1666 | struct DbError { |
| 1667 | message: String, |
| 1668 | missing_profile: bool, |
| 1669 | } |
| 1670 | |
| 1671 | impl DbError { |
| 1672 | fn new(message: String) -> Self { |
| 1673 | Self { |
| 1674 | message, |
| 1675 | missing_profile: false, |
| 1676 | } |
| 1677 | } |
| 1678 | |
| 1679 | fn missing(message: String) -> Self { |
| 1680 | Self { |
| 1681 | message, |
| 1682 | missing_profile: true, |
| 1683 | } |
| 1684 | } |
| 1685 | } |
| 1686 | } |