about summary refs log tree commit diff
path: root/src/facility/envsys.rs
blob: 0f5582bde639da419114cbba7dfe5b5fd25d0a86 (plain)
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
use crate::error::{ Error, Result };
use crate::facility::{ CreatableFacility, Facility, FacilityType };
use crate::property_list::{ parse_dictionary, Array, Dictionary, Value };

use std::any::Any;
use std::ffi::c_void;
use std::slice::from_raw_parts;

use async_fs::File;
use futures_lite::future;
use rustix::ioctl::{ ioctl, Opcode, Getter };
use rustix::ioctl::opcode::read_write;
use rustix::mm::munmap;


pub struct EnvSys {
  sysmon: File,
  dictionary: Dictionary,
}


#[repr(C)]
#[derive(Debug)]
struct PropertyListReference {
  data: *mut u8,
  size: usize,
}


impl Facility for EnvSys {
  fn as_any_mut(&mut self) -> &mut dyn Any {
    self
  }

  fn update(&mut self) -> Result<()> {
    future::block_on(self.refresh_dictionary())?;

    Ok(())
  }
}

impl CreatableFacility for EnvSys {
  const FACILITY_TYPE: FacilityType = FacilityType::ENVSYS;

  async fn new() -> Result<Self> {
    let sysmon = File::open("/dev/sysmon").await?;
    let dictionary = get_dictionary(&sysmon).await?;

    Ok(EnvSys { sysmon, dictionary })
  }
}

impl EnvSys {
  const ENVSYS_GETDICTIONARY: Opcode =
            read_write::<PropertyListReference>(b'E', 0);
  #[allow(dead_code)]
  const ENVSYS_SETDICTIONARY: Opcode =
            read_write::<PropertyListReference>(b'E', 1);
  #[allow(dead_code)]
  const ENVSYS_REMOVEPROPS: Opcode =
            read_write::<PropertyListReference>(b'E', 2);

  pub async fn refresh_dictionary(&mut self) -> Result<()> {
    self.dictionary = get_dictionary(&self.sysmon).await?;

    Ok(())
  }

  pub fn device_iter(&self) -> impl Iterator<Item=&str> {
    let hash_iterator = self.dictionary.iter();

    DeviceNames { hash_iterator }
  }

  pub fn get_device(&self, device_name: &str) -> Result<&Array> {
    if let Some(Value::Array(device)) = self.dictionary.get(device_name) {
      Ok(device)
    } else {
      Err(Error::custom(&format!("No such device {}", device_name)))
    }
  }

  pub fn get_sensor(&self, device_name: &str, sensor_name: &str)
    -> Result<&Dictionary>
  {
    let device = self.get_device(device_name)?;

    for sensor in device {
      if let Value::Dictionary(sensor) = sensor {
        if let Some(Value::String(description)) = sensor.get("description")
           && description == sensor_name
        {
          return Ok(sensor);
        }
      }
    }

    Err(Error::custom(&format!("No sensor {} on device {}",
                               sensor_name, device_name)))
  }

  pub fn get_current_value(&self, device_name: &str, sensor_name: &str)
    -> Result<i64>
  {
    let sensor = self.get_sensor(device_name, sensor_name)?;

    if let Some(Value::Integer(value)) = sensor.get("cur-value") {
      Ok(*value)
    } else {
      Err(Error::custom(&format!("No current value for {} on device {}",
                                 sensor_name, device_name)))
    }
  }

  pub fn get_maximum_value(&self, device_name: &str, sensor_name: &str)
    -> Result<i64>
  {
    let sensor = self.get_sensor(device_name, sensor_name)?;

    if let Some(Value::Integer(value)) = sensor.get("max-value") {
      Ok(*value)
    } else {
      Err(Error::custom(&format!("No maximum value for {} on device {}",
                                 sensor_name, device_name)))
    }
  }
}


struct DeviceNames<'a> {
  hash_iterator: std::collections::hash_map::Iter<'a, String, Value>,
}

impl<'a> Iterator for DeviceNames<'a> {
  type Item = &'a str;

  fn next(&mut self) -> Option<Self::Item> {
    if let Some((key, _)) = self.hash_iterator.next() {
      Some(key)
    } else { None }
  }
}


async fn get_dictionary(sysmon: &File) -> Result<Dictionary> {
  let call = unsafe {
    Getter::<{ EnvSys::ENVSYS_GETDICTIONARY }, PropertyListReference>::new()
  };

  /*   If the call fails, we can safely return because there's no resulting
   * memory allocation.
   */
  let result = unsafe { ioctl(&sysmon, call) }?;

  /*   We're expecting the final byte to be a null, acting as a C string
   * terminator. We ignore it.
   */
  let xml: &[u8] = unsafe { from_raw_parts(result.data, result.size - 1) };

  /*   This returns a Result, but we want to clean up before we peek inside.
   */
  let dictionary = parse_dictionary(xml);

  /*   So. Fun story. Inspecting NetBSD src/common/lib/libprop/prop_kern.c,
   * we find that the kernel creates a new memory mapping for the dictionary
   * it returns. When we're done, we're expected to munmap() it. Wild.
   *
   *   Anyway, if munmap() fails we have no way to clean up regardless, so we
   * just return.
   */
  unsafe { munmap(result.data as *mut c_void, result.size) }?;

  dictionary
}