Debian Codegraph @

src/unix/funcs.rs

raw symbols SCIP
1 // unix/funcs.rs
2
3 use byteorder::{ByteOrder, WriteBytesExt};
4 use consts::*;
5 use ctl_error::*;
6 use ctl_info::*;
7 use ctl_type::*;
8 use ctl_value::*;
9 #[cfg(any(target_os = "macos", target_os = "ios"))]
10 use std::ffi::CString;
11
12 #[cfg(target_os = "freebsd")]
13 use temperature::*;
14
15 pub fn name2oid(name: &str) -> Result<Vec<libc::c_int>, SysctlError> {
16 // We get results in this vector
17 let mut len: usize = CTL_MAXNAME as usize;
18 let mut res = Vec::<libc::c_int>::with_capacity(len);
19 let rcname = std::ffi::CString::new(name);
20 if rcname.is_err() {
21 return Err(SysctlError::NotFound(name.to_owned()));
22 }
23 let cname = rcname.unwrap();
24
25 let ret = unsafe {
26 libc::sysctlnametomib(
27 cname.as_ptr() as *const libc::c_char,
28 res.as_mut_ptr(),
29 &mut len
30 )
31 };
32 if ret < 0 {
33 let e = std::io::Error::last_os_error();
34 return Err(match e.kind() {
35 std::io::ErrorKind::NotFound => SysctlError::NotFound(name.into()),
36 _ => SysctlError::IoError(e),
37 });
38 } else {
39 unsafe { res.set_len(len); }
40 }
41
42 Ok(res)
43 }
44
45 #[cfg(not(any(target_os = "macos", target_os = "ios")))]
46 pub fn oidfmt(oid: &[libc::c_int]) -> Result<CtlInfo, SysctlError> {
47 // Request command for type info
48 let mut qoid: Vec<libc::c_int> = vec![0, 4];
49 qoid.extend(oid);
50
51 // Store results here
52 let mut buf: [libc::c_uchar; libc::BUFSIZ as usize] = [0; libc::BUFSIZ as usize];
53 let mut buf_len = std::mem::size_of_val(&buf);
54 let ret = unsafe {
55 libc::sysctl(
56 qoid.as_ptr(),
57 qoid.len() as u32,
58 buf.as_mut_ptr() as *mut libc::c_void,
59 &mut buf_len,
60 std::ptr::null(),
61 0,
62 )
63 };
64 if ret != 0 {
65 return Err(SysctlError::IoError(std::io::Error::last_os_error()));
66 }
67
68 // 'Kind' is the first 32 bits of result buffer
69 let kind = byteorder::LittleEndian::read_u32(&buf);
70
71 // 'Type' is the first 4 bits of 'Kind'
72 let ctltype_val = kind & CTLTYPE as u32;
73
74 // 'fmt' is after 'Kind' in result buffer
75 let fmt: String =
76 match std::ffi::CStr::from_bytes_with_nul(&buf[std::mem::size_of::<u32>()..buf_len]) {
77 Ok(x) => x.to_string_lossy().into(),
78 Err(e) => return Err(SysctlError::InvalidCStr(e)),
79 };
80
81 #[cfg_attr(feature = "cargo-clippy", allow(clippy::redundant_field_names))]
82 let s = CtlInfo {
83 ctl_type: CtlType::from(ctltype_val),
84 fmt: fmt,
85 flags: kind,
86 };
87 Ok(s)
88 }
89
90 #[cfg(any(target_os = "macos", target_os = "ios"))]
91 pub fn oidfmt(oid: &[libc::c_int]) -> Result<CtlInfo, SysctlError> {
92 // Request command for type info
93 let mut qoid: Vec<libc::c_int> = vec![0, 4];
94 qoid.extend(oid);
95
96 // Store results here
97 let mut buf: [libc::c_uchar; libc::BUFSIZ as usize] = [0; libc::BUFSIZ as usize];
98 let mut buf_len = std::mem::size_of_val(&buf);
99 let ret = unsafe {
100 libc::sysctl(
101 qoid.as_mut_ptr(),
102 qoid.len() as u32,
103 buf.as_mut_ptr() as *mut libc::c_void,
104 &mut buf_len,
105 std::ptr::null_mut(),
106 0,
107 )
108 };
109 if ret != 0 {
110 return Err(SysctlError::IoError(std::io::Error::last_os_error()));
111 }
112
113 // 'Kind' is the first 32 bits of result buffer
114 let kind = byteorder::LittleEndian::read_u32(&buf);
115
116 // 'Type' is the first 4 bits of 'Kind'
117 let ctltype_val = kind & CTLTYPE as u32;
118
119 // 'fmt' is after 'Kind' in result buffer
120 let bytes = &buf[std::mem::size_of::<u32>()..buf_len];
121
122 // Ensure we drop the '\0' byte if there are any.
123 let len = match bytes.iter().position(|c| *c == 0) {
124 Some(index) => index,
125 _ => bytes.len(),
126 };
127
128 let fmt: String = match std::str::from_utf8(&bytes[..len]) {
129 Ok(x) => x.to_owned(),
130 Err(e) => return Err(SysctlError::Utf8Error(e)),
131 };
132
133 let s = CtlInfo {
134 ctl_type: CtlType::from(ctltype_val),
135 fmt: fmt,
136 flags: kind,
137 };
138 Ok(s)
139 }
140
141 #[cfg(not(any(target_os = "macos", target_os = "ios")))]
142 pub fn value_oid(oid: &[i32]) -> Result<CtlValue, SysctlError> {
143 let info: CtlInfo = oidfmt(&oid)?;
144
145 // Check if the value is readable
146 if info.flags & CTLFLAG_RD != CTLFLAG_RD {
147 return Err(SysctlError::NoReadAccess);
148 }
149
150 // First get size of value in bytes
151 let mut val_len = 0;
152 let ret = unsafe {
153 libc::sysctl(
154 oid.as_ptr(),
155 oid.len() as u32,
156 std::ptr::null_mut(),
157 &mut val_len,
158 std::ptr::null(),
159 0,
160 )
161 };
162 if ret < 0 {
163 return Err(SysctlError::IoError(std::io::Error::last_os_error()));
164 }
165
166 // If the length reported is shorter than the type we will convert it into,
167 // byteorder::LittleEndian::read_* will panic. Therefore, expand the value length to at
168 // Least the size of the value.
169 let val_minsize = std::cmp::max(val_len, info.ctl_type.min_type_size());
170
171 // Then get value
172 let mut val: Vec<libc::c_uchar> = vec![0; val_minsize];
173 let mut new_val_len = val_len;
174 let ret = unsafe {
175 libc::sysctl(
176 oid.as_ptr(),
177 oid.len() as u32,
178 val.as_mut_ptr() as *mut libc::c_void,
179 &mut new_val_len,
180 std::ptr::null(),
181 0,
182 )
183 };
184 if ret < 0 {
185 return Err(SysctlError::IoError(std::io::Error::last_os_error()));
186 }
187
188 // Confirm that we did not read out of bounds
189 assert!(new_val_len <= val_len);
190 // Confirm that we got the bytes we requested
191 if new_val_len < val_len {
192 return Err(SysctlError::ShortRead {
193 read: new_val_len,
194 reported: val_len,
195 });
196 }
197
198 // Special treatment for temperature ctls.
199 if info.is_temperature() {
200 return temperature(&info, &val);
201 }
202
203 // Wrap in Enum and return
204 match info.ctl_type {
205 CtlType::None => Ok(CtlValue::None),
206 CtlType::Node => Ok(CtlValue::Node(val)),
207 CtlType::Int => Ok(CtlValue::Int(byteorder::LittleEndian::read_i32(&val))),
208 CtlType::String => match val.len() {
209 0 => Ok(CtlValue::String("".to_string())),
210 l => std::str::from_utf8(&val[..l - 1])
211 .map_err(SysctlError::Utf8Error)
212 .map(|s| CtlValue::String(s.into())),
213 },
214 CtlType::S64 => Ok(CtlValue::S64(byteorder::LittleEndian::read_i64(&val))),
215 CtlType::Struct => Ok(CtlValue::Struct(val)),
216 CtlType::Uint => Ok(CtlValue::Uint(byteorder::LittleEndian::read_u32(&val))),
217 CtlType::Long => Ok(CtlValue::Long(byteorder::LittleEndian::read_i64(&val))),
218 CtlType::Ulong => Ok(CtlValue::Ulong(byteorder::LittleEndian::read_u64(&val))),
219 CtlType::U64 => Ok(CtlValue::U64(byteorder::LittleEndian::read_u64(&val))),
220 CtlType::U8 => Ok(CtlValue::U8(val[0])),
221 CtlType::U16 => Ok(CtlValue::U16(byteorder::LittleEndian::read_u16(&val))),
222 CtlType::S8 => Ok(CtlValue::S8(val[0] as i8)),
223 CtlType::S16 => Ok(CtlValue::S16(byteorder::LittleEndian::read_i16(&val))),
224 CtlType::S32 => Ok(CtlValue::S32(byteorder::LittleEndian::read_i32(&val))),
225 CtlType::U32 => Ok(CtlValue::U32(byteorder::LittleEndian::read_u32(&val))),
226 _ => Err(SysctlError::UnknownType),
227 }
228 }
229
230 #[cfg(any(target_os = "macos", target_os = "ios"))]
231 pub fn value_oid(oid: &mut Vec<i32>) -> Result<CtlValue, SysctlError> {
232 let info: CtlInfo = oidfmt(&oid)?;
233
234 // Check if the value is readable
235 if !(info.flags & CTLFLAG_RD == CTLFLAG_RD) {
236 return Err(SysctlError::NoReadAccess);
237 }
238
239 // First get size of value in bytes
240 let mut val_len = 0;
241 let ret = unsafe {
242 libc::sysctl(
243 oid.as_mut_ptr(),
244 oid.len() as u32,
245 std::ptr::null_mut(),
246 &mut val_len,
247 std::ptr::null_mut(),
248 0,
249 )
250 };
251 if ret < 0 {
252 return Err(SysctlError::IoError(std::io::Error::last_os_error()));
253 }
254
255 // If the length reported is shorter than the type we will convert it into,
256 // byteorder::LittleEndian::read_* will panic. Therefore, expand the value length to at
257 // Least the size of the value.
258 let val_minsize = std::cmp::max(val_len, info.ctl_type.min_type_size());
259
260 // Then get value
261 let mut val: Vec<libc::c_uchar> = vec![0; val_minsize];
262 let mut new_val_len = val_len;
263 let ret = unsafe {
264 libc::sysctl(
265 oid.as_mut_ptr(),
266 oid.len() as u32,
267 val.as_mut_ptr() as *mut libc::c_void,
268 &mut new_val_len,
269 std::ptr::null_mut(),
270 0,
271 )
272 };
273 if ret < 0 {
274 return Err(SysctlError::IoError(std::io::Error::last_os_error()));
275 }
276
277 // Confirm that we did not read out of bounds
278 assert!(new_val_len <= val_len);
279 // The call can sometimes return bytes that are smaller than initially indicated, so it should
280 // be safe to truncate it. See a similar approach in golang module:
281 // https://github.com/golang/sys/blob/43e60d72a8e2bd92ee98319ba9a384a0e9837c08/unix/syscall_bsd.go#L545-L548
282 if new_val_len < val_len {
283 val.truncate(new_val_len);
284 }
285
286 // Wrap in Enum and return
287 match info.ctl_type {
288 CtlType::None => Ok(CtlValue::None),
289 CtlType::Node => Ok(CtlValue::Node(val)),
290 CtlType::Int => match info.fmt.as_str() {
291 "I" => Ok(CtlValue::Int(byteorder::LittleEndian::read_i32(&val))),
292 "IU" => Ok(CtlValue::Uint(byteorder::LittleEndian::read_u32(&val))),
293 "L" => Ok(CtlValue::Long(byteorder::LittleEndian::read_i64(&val))),
294 "LU" => Ok(CtlValue::Ulong(byteorder::LittleEndian::read_u64(&val))),
295 _ => Ok(CtlValue::None),
296 }
297 CtlType::String => match val.len() {
298 0 => Ok(CtlValue::String("".to_string())),
299 l => std::str::from_utf8(&val[..l - 1])
300 .map_err(SysctlError::Utf8Error)
301 .map(|s| CtlValue::String(s.into())),
302 },
303 CtlType::S64 => Ok(CtlValue::S64(byteorder::LittleEndian::read_i64(&val))),
304 CtlType::Struct => Ok(CtlValue::Struct(val)),
305 CtlType::Uint => Ok(CtlValue::Uint(byteorder::LittleEndian::read_u32(&val))),
306 CtlType::Long => Ok(CtlValue::Long(byteorder::LittleEndian::read_i64(&val))),
307 CtlType::Ulong => Ok(CtlValue::Ulong(byteorder::LittleEndian::read_u64(&val))),
308 CtlType::U64 => Ok(CtlValue::U64(byteorder::LittleEndian::read_u64(&val))),
309 CtlType::U8 => Ok(CtlValue::U8(val[0])),
310 CtlType::U16 => Ok(CtlValue::U16(byteorder::LittleEndian::read_u16(&val))),
311 CtlType::S8 => Ok(CtlValue::S8(val[0] as i8)),
312 CtlType::S16 => Ok(CtlValue::S16(byteorder::LittleEndian::read_i16(&val))),
313 CtlType::S32 => Ok(CtlValue::S32(byteorder::LittleEndian::read_i32(&val))),
314 CtlType::U32 => Ok(CtlValue::U32(byteorder::LittleEndian::read_u32(&val))),
315 }
316 }
317
318 #[cfg(not(any(target_os = "macos", target_os = "ios")))]
319 pub fn value_oid_as<T>(oid: &[i32]) -> Result<Box<T>, SysctlError> {
320 let val_enum = value_oid(oid)?;
321
322 // Some structs are apparently reported as Node so this check is invalid..
323 // let ctl_type = CtlType::from(&val_enum);
324 // assert_eq!(CtlType::Struct, ctl_type, "Error type is not struct/opaque");
325
326 // TODO: refactor this when we have better clue to what's going on
327 if let CtlValue::Struct(val) = val_enum {
328 // Make sure we got correct data size
329 assert_eq!(
330 std::mem::size_of::<T>(),
331 val.len(),
332 "Error memory size mismatch. Size of struct {}, size of data retrieved {}.",
333 std::mem::size_of::<T>(),
334 val.len()
335 );
336
337 // val is Vec<u8>
338 let val_array: Box<[u8]> = val.into_boxed_slice();
339 let val_raw: *mut T = Box::into_raw(val_array) as *mut T;
340 let val_box: Box<T> = unsafe { Box::from_raw(val_raw) };
341 Ok(val_box)
342 } else if let CtlValue::Node(val) = val_enum {
343 // Make sure we got correct data size
344 assert_eq!(
345 std::mem::size_of::<T>(),
346 val.len(),
347 "Error memory size mismatch. Size of struct {}, size of data retrieved {}.",
348 std::mem::size_of::<T>(),
349 val.len()
350 );
351
352 // val is Vec<u8>
353 let val_array: Box<[u8]> = val.into_boxed_slice();
354 let val_raw: *mut T = Box::into_raw(val_array) as *mut T;
355 let val_box: Box<T> = unsafe { Box::from_raw(val_raw) };
356 Ok(val_box)
357 } else {
358 Err(SysctlError::ExtractionError)
359 }
360 }
361
362 #[cfg(any(target_os = "macos", target_os = "ios"))]
363 pub fn value_oid_as<T>(oid: &mut Vec<i32>) -> Result<Box<T>, SysctlError> {
364 let val_enum = value_oid(oid)?;
365
366 // Some structs are apparently reported as Node so this check is invalid..
367 // let ctl_type = CtlType::from(&val_enum);
368 // assert_eq!(CtlType::Struct, ctl_type, "Error type is not struct/opaque");
369
370 // TODO: refactor this when we have better clue to what's going on
371 if let CtlValue::Struct(val) = val_enum {
372 // Make sure we got correct data size
373 assert_eq!(
374 std::mem::size_of::<T>(),
375 val.len(),
376 "Error memory size mismatch. Size of struct {}, size of data retrieved {}.",
377 std::mem::size_of::<T>(),
378 val.len()
379 );
380
381 // val is Vec<u8>
382 let val_array: Box<[u8]> = val.into_boxed_slice();
383 let val_raw: *mut T = Box::into_raw(val_array) as *mut T;
384 let val_box: Box<T> = unsafe { Box::from_raw(val_raw) };
385 Ok(val_box)
386 } else if let CtlValue::Node(val) = val_enum {
387 // Make sure we got correct data size
388 assert_eq!(
389 std::mem::size_of::<T>(),
390 val.len(),
391 "Error memory size mismatch. Size of struct {}, size of data retrieved {}.",
392 std::mem::size_of::<T>(),
393 val.len()
394 );
395
396 // val is Vec<u8>
397 let val_array: Box<[u8]> = val.into_boxed_slice();
398 let val_raw: *mut T = Box::into_raw(val_array) as *mut T;
399 let val_box: Box<T> = unsafe { Box::from_raw(val_raw) };
400 Ok(val_box)
401 } else {
402 Err(SysctlError::ExtractionError)
403 }
404 }
405
406 #[cfg(any(target_os = "macos", target_os = "ios"))]
407 pub fn value_name(name: &str, ctl_type: CtlType, fmt: &str) -> Result<CtlValue, SysctlError> {
408 let name = CString::new(name)?;
409
410 // First get size of value in bytes
411 let mut val_len = 0;
412 let ret = unsafe {
413 libc::sysctlbyname(
414 name.as_ptr(),
415 std::ptr::null_mut(),
416 &mut val_len,
417 std::ptr::null_mut(),
418 0,
419 )
420 };
421 if ret < 0 {
422 return Err(SysctlError::IoError(std::io::Error::last_os_error()));
423 }
424
425 // If the length reported is shorter than the type we will convert it into,
426 // byteorder::LittleEndian::read_* will panic. Therefore, expand the value length to at
427 // Least the size of the value.
428 let val_minsize = std::cmp::max(val_len, ctl_type.min_type_size());
429
430 // Then get value
431 let mut val: Vec<libc::c_uchar> = vec![0; val_minsize];
432 let mut new_val_len = val_len;
433 let ret = unsafe {
434 libc::sysctlbyname(
435 name.as_ptr(),
436 val.as_mut_ptr() as *mut libc::c_void,
437 &mut new_val_len,
438 std::ptr::null_mut(),
439 0,
440 )
441 };
442 if ret < 0 {
443 return Err(SysctlError::IoError(std::io::Error::last_os_error()));
444 }
445
446 // Confirm that we did not read out of bounds
447 assert!(new_val_len <= val_len);
448 // The call can sometimes return bytes that are smaller than initially indicated, so it should
449 // be safe to truncate it. See a similar approach in golang module:
450 // https://github.com/golang/sys/blob/43e60d72a8e2bd92ee98319ba9a384a0e9837c08/unix/syscall_bsd.go#L545-L548
451 if new_val_len < val_len {
452 val.truncate(new_val_len);
453 }
454
455 // Wrap in Enum and return
456 match ctl_type {
457 CtlType::None => Ok(CtlValue::None),
458 CtlType::Node => Ok(CtlValue::Node(val)),
459 CtlType::Int => match fmt {
460 "I" => Ok(CtlValue::Int(byteorder::LittleEndian::read_i32(&val))),
461 "IU" => Ok(CtlValue::Uint(byteorder::LittleEndian::read_u32(&val))),
462 "L" => Ok(CtlValue::Long(byteorder::LittleEndian::read_i64(&val))),
463 "LU" => Ok(CtlValue::Ulong(byteorder::LittleEndian::read_u64(&val))),
464 _ => Ok(CtlValue::None),
465 }
466 CtlType::String => match val.len() {
467 0 => Ok(CtlValue::String("".to_string())),
468 l => std::str::from_utf8(&val[..l - 1])
469 .map_err(SysctlError::Utf8Error)
470 .map(|s| CtlValue::String(s.into())),
471 },
472 CtlType::S64 => Ok(CtlValue::S64(byteorder::LittleEndian::read_i64(&val))),
473 CtlType::Struct => Ok(CtlValue::Struct(val)),
474 CtlType::Uint => Ok(CtlValue::Uint(byteorder::LittleEndian::read_u32(&val))),
475 CtlType::Long => Ok(CtlValue::Long(byteorder::LittleEndian::read_i64(&val))),
476 CtlType::Ulong => Ok(CtlValue::Ulong(byteorder::LittleEndian::read_u64(&val))),
477 CtlType::U64 => Ok(CtlValue::U64(byteorder::LittleEndian::read_u64(&val))),
478 CtlType::U8 => Ok(CtlValue::U8(val[0])),
479 CtlType::U16 => Ok(CtlValue::U16(byteorder::LittleEndian::read_u16(&val))),
480 CtlType::S8 => Ok(CtlValue::S8(val[0] as i8)),
481 CtlType::S16 => Ok(CtlValue::S16(byteorder::LittleEndian::read_i16(&val))),
482 CtlType::S32 => Ok(CtlValue::S32(byteorder::LittleEndian::read_i32(&val))),
483 CtlType::U32 => Ok(CtlValue::U32(byteorder::LittleEndian::read_u32(&val))),
484 }
485 }
486
487 #[cfg(any(target_os = "macos", target_os = "ios"))]
488 pub fn value_name_as<T>(name: &str, ctl_type: CtlType, fmt: &str) -> Result<Box<T>, SysctlError> {
489 let val_enum = value_name(name, ctl_type, fmt)?;
490
491 // Some structs are apparently reported as Node so this check is invalid..
492 // let ctl_type = CtlType::from(&val_enum);
493 // assert_eq!(CtlType::Struct, ctl_type, "Error type is not struct/opaque");
494
495 // TODO: refactor this when we have better clue to what's going on
496 if let CtlValue::Struct(val) = val_enum {
497 // Make sure we got correct data size
498 assert_eq!(
499 std::mem::size_of::<T>(),
500 val.len(),
501 "Error memory size mismatch. Size of struct {}, size of data retrieved {}.",
502 std::mem::size_of::<T>(),
503 val.len()
504 );
505
506 // val is Vec<u8>
507 let val_array: Box<[u8]> = val.into_boxed_slice();
508 let val_raw: *mut T = Box::into_raw(val_array) as *mut T;
509 let val_box: Box<T> = unsafe { Box::from_raw(val_raw) };
510 Ok(val_box)
511 } else if let CtlValue::Node(val) = val_enum {
512 // Make sure we got correct data size
513 assert_eq!(
514 std::mem::size_of::<T>(),
515 val.len(),
516 "Error memory size mismatch. Size of struct {}, size of data retrieved {}.",
517 std::mem::size_of::<T>(),
518 val.len()
519 );
520
521 // val is Vec<u8>
522 let val_array: Box<[u8]> = val.into_boxed_slice();
523 let val_raw: *mut T = Box::into_raw(val_array) as *mut T;
524 let val_box: Box<T> = unsafe { Box::from_raw(val_raw) };
525 Ok(val_box)
526 } else {
527 Err(SysctlError::ExtractionError)
528 }
529 }
530
531 fn value_to_bytes(value: CtlValue) -> Result<Vec<u8>, SysctlError> {
532 // TODO rest of the types
533 match value {
534 CtlValue::String(v) => Ok(v.as_bytes().to_owned()),
535 CtlValue::Ulong(v) => {
536 let mut bytes = vec![];
537 bytes.write_u64::<byteorder::LittleEndian>(v)?;
538 Ok(bytes)
539 }
540 CtlValue::Uint(v) => {
541 let mut bytes = vec![];
542 bytes.write_u32::<byteorder::LittleEndian>(v)?;
543 Ok(bytes)
544 }
545 CtlValue::Int(v) => {
546 let mut bytes = vec![];
547 bytes.write_i32::<byteorder::LittleEndian>(v)?;
548 Ok(bytes)
549 }
550 CtlValue::U8(v) => {
551 let mut bytes = vec![];
552 bytes.write_u8(v)?;
553 Ok(bytes)
554 }
555 _ => Err(SysctlError::MissingImplementation),
556 }
557 }
558
559 #[cfg(not(any(target_os = "macos", target_os = "ios")))]
560 pub fn set_oid_value(oid: &[libc::c_int], value: CtlValue) -> Result<CtlValue, SysctlError> {
561 let info: CtlInfo = oidfmt(&oid)?;
562
563 // Check if the value is writeable
564 if info.flags & CTLFLAG_WR != CTLFLAG_WR {
565 return Err(SysctlError::NoWriteAccess);
566 }
567
568 let ctl_type = CtlType::from(&value);
569 assert_eq!(
570 info.ctl_type, ctl_type,
571 "Error type mismatch. Type given {:?}, sysctl type: {:?}",
572 ctl_type, info.ctl_type
573 );
574
575 let bytes = value_to_bytes(value)?;
576
577 let ret = unsafe {
578 libc::sysctl(
579 oid.as_ptr(),
580 oid.len() as u32,
581 std::ptr::null_mut(),
582 std::ptr::null_mut(),
583 bytes.as_ptr() as *const libc::c_void,
584 bytes.len(),
585 )
586 };
587 if ret < 0 {
588 return Err(SysctlError::IoError(std::io::Error::last_os_error()));
589 }
590
591 // Get the new value and return for confirmation
592 self::value_oid(oid)
593 }
594
595 #[cfg(any(target_os = "macos", target_os = "ios"))]
596 pub fn set_oid_value(oid: &mut Vec<libc::c_int>, value: CtlValue) -> Result<CtlValue, SysctlError> {
597 let info: CtlInfo = oidfmt(&oid)?;
598
599 // Check if the value is writeable
600 if !(info.flags & CTLFLAG_WR == CTLFLAG_WR) {
601 return Err(SysctlError::NoWriteAccess);
602 }
603
604 let ctl_type = CtlType::from(&value);
605
606 // Get the correct ctl type based on the format string
607 let info_ctl_type = match info.ctl_type {
608 CtlType::Int => match info.fmt.as_str() {
609 "I" => CtlType::Int,
610 "IU" => CtlType::Uint,
611 "L" => CtlType::Long,
612 "LU" => CtlType::Ulong,
613 _ => return Err(SysctlError::MissingImplementation),
614 }
615 ctl_type => ctl_type,
616 };
617
618 assert_eq!(
619 info_ctl_type, ctl_type,
620 "Error type mismatch. Type given {:?}, sysctl type: {:?}",
621 ctl_type, info_ctl_type
622 );
623
624 let bytes = value_to_bytes(value)?;
625
626 // Set value
627 let ret = unsafe {
628 libc::sysctl(
629 oid.as_mut_ptr(),
630 oid.len() as u32,
631 std::ptr::null_mut(),
632 std::ptr::null_mut(),
633 bytes.as_ptr() as *mut libc::c_void,
634 bytes.len(),
635 )
636 };
637 if ret < 0 {
638 return Err(SysctlError::IoError(std::io::Error::last_os_error()));
639 }
640
641 // Get the new value and return for confirmation
642 self::value_oid(oid)
643 }
644
645 #[cfg(any(target_os = "macos", target_os = "ios"))]
646 pub fn set_name_value(
647 name: &str,
648 info_ctl_type: CtlType,
649 fmt: &str,
650 value: CtlValue,
651 ) -> Result<CtlValue, SysctlError> {
652 let c_name = CString::new(name)?;
653 let ctl_type = CtlType::from(&value);
654
655 // Get the correct ctl type based on the format string
656 let info_ctl_type = match info_ctl_type {
657 CtlType::Int => match fmt {
658 "I" => CtlType::Int,
659 "IU" => CtlType::Uint,
660 "L" => CtlType::Long,
661 "LU" => CtlType::Ulong,
662 _ => return Err(SysctlError::MissingImplementation),
663 }
664 ctl_type => ctl_type,
665 };
666
667 assert_eq!(
668 info_ctl_type, ctl_type,
669 "Error type mismatch. Type given {:?}, sysctl type: {:?}",
670 ctl_type, info_ctl_type
671 );
672
673 let bytes = value_to_bytes(value)?;
674
675 // Set value
676 let ret = unsafe {
677 libc::sysctlbyname(
678 c_name.as_ptr(),
679 std::ptr::null_mut(),
680 std::ptr::null_mut(),
681 bytes.as_ptr() as *mut libc::c_void,
682 bytes.len(),
683 )
684 };
685 if ret < 0 {
686 return Err(SysctlError::IoError(std::io::Error::last_os_error()));
687 }
688
689 // Get the new value and return for confirmation
690 self::value_name(name, ctl_type, fmt)
691 }
692
693 #[cfg(not(any(target_os = "macos", target_os = "ios")))]
694 pub fn oid2description(oid: &[libc::c_int]) -> Result<String, SysctlError> {
695 // Request command for description
696 let mut qoid: Vec<libc::c_int> = vec![0, 5];
697 qoid.extend(oid);
698
699 // Store results in u8 array
700 let mut buf: [libc::c_uchar; libc::BUFSIZ as usize] = [0; libc::BUFSIZ as usize];
701 let mut buf_len = std::mem::size_of_val(&buf);
702 let ret = unsafe {
703 libc::sysctl(
704 qoid.as_ptr(),
705 qoid.len() as u32,
706 buf.as_mut_ptr() as *mut libc::c_void,
707 &mut buf_len,
708 std::ptr::null(),
709 0,
710 )
711 };
712 if ret != 0 {
713 return Err(SysctlError::IoError(std::io::Error::last_os_error()));
714 }
715
716 // Use buf_len - 1 so that we remove the trailing NULL
717 match std::str::from_utf8(&buf[..buf_len - 1]) {
718 Ok(s) => Ok(s.to_owned()),
719 Err(e) => Err(SysctlError::Utf8Error(e)),
720 }
721 }
722
723 #[cfg(not(any(target_os = "macos", target_os = "ios")))]
724 pub fn oid2name(oid: &[libc::c_int]) -> Result<String, SysctlError> {
725 // Request command for name
726 let mut qoid: Vec<libc::c_int> = vec![0, 1];
727 qoid.extend(oid);
728
729 // Store results in u8 array
730 let mut buf: [libc::c_uchar; libc::BUFSIZ as usize] = [0; libc::BUFSIZ as usize];
731 let mut buf_len = std::mem::size_of_val(&buf);
732 let ret = unsafe {
733 libc::sysctl(
734 qoid.as_ptr(),
735 qoid.len() as u32,
736 buf.as_mut_ptr() as *mut libc::c_void,
737 &mut buf_len,
738 std::ptr::null(),
739 0,
740 )
741 };
742 if ret != 0 {
743 return Err(SysctlError::IoError(std::io::Error::last_os_error()));
744 }
745
746 // Use buf_len - 1 so that we remove the trailing NULL
747 match std::str::from_utf8(&buf[..buf_len - 1]) {
748 Ok(s) => Ok(s.to_owned()),
749 Err(e) => Err(SysctlError::Utf8Error(e)),
750 }
751 }
752
753 #[cfg(any(target_os = "macos", target_os = "ios"))]
754 pub fn oid2name(oid: &Vec<libc::c_int>) -> Result<String, SysctlError> {
755 // Request command for name
756 let mut qoid: Vec<libc::c_int> = vec![0, 1];
757 qoid.extend(oid);
758
759 // Store results in u8 array
760 let mut buf: [libc::c_uchar; libc::BUFSIZ as usize] = [0; libc::BUFSIZ as usize];
761 let mut buf_len = std::mem::size_of_val(&buf);
762 let ret = unsafe {
763 libc::sysctl(
764 qoid.as_mut_ptr(),
765 qoid.len() as u32,
766 buf.as_mut_ptr() as *mut libc::c_void,
767 &mut buf_len,
768 std::ptr::null_mut(),
769 0,
770 )
771 };
772 if ret != 0 {
773 return Err(SysctlError::IoError(std::io::Error::last_os_error()));
774 }
775
776 // Use buf_len - 1 so that we remove the trailing NULL
777 match std::str::from_utf8(&buf[..buf_len - 1]) {
778 Ok(s) => Ok(s.to_owned()),
779 Err(e) => Err(SysctlError::Utf8Error(e)),
780 }
781 }
782
783 #[cfg(not(any(target_os = "macos", target_os = "ios")))]
784 pub fn next_oid(oid: &[libc::c_int]) -> Result<Option<Vec<libc::c_int>>, SysctlError> {
785 // Request command for next oid
786 let mut qoid: Vec<libc::c_int> = vec![0, 2];
787 qoid.extend(oid);
788
789 let mut len: usize = CTL_MAXNAME as usize * std::mem::size_of::<libc::c_int>();
790
791 // We get results in this vector
792 let mut res: Vec<libc::c_int> = vec![0; CTL_MAXNAME as usize];
793
794 let ret = unsafe {
795 libc::sysctl(
796 qoid.as_ptr(),
797 qoid.len() as u32,
798 res.as_mut_ptr() as *mut libc::c_void,
799 &mut len,
800 std::ptr::null(),
801 0,
802 )
803 };
804 if ret != 0 {
805 let e = std::io::Error::last_os_error();
806
807 if e.raw_os_error() == Some(libc::ENOENT) {
808 return Ok(None);
809 }
810 return Err(SysctlError::IoError(e));
811 }
812
813 // len is in bytes, convert to number of libc::c_ints
814 len /= std::mem::size_of::<libc::c_int>();
815
816 // Trim result vector
817 res.truncate(len);
818
819 Ok(Some(res))
820 }
821
822 #[cfg(any(target_os = "macos", target_os = "ios"))]
823 pub fn next_oid(oid: &Vec<libc::c_int>) -> Result<Option<Vec<libc::c_int>>, SysctlError> {
824 // Request command for next oid
825 let mut qoid: Vec<libc::c_int> = vec![0, 2];
826 qoid.extend(oid);
827
828 let mut len: usize = CTL_MAXNAME as usize * std::mem::size_of::<libc::c_int>();
829
830 // We get results in this vector
831 let mut res: Vec<libc::c_int> = vec![0; CTL_MAXNAME as usize];
832
833 let ret = unsafe {
834 libc::sysctl(
835 qoid.as_mut_ptr(),
836 qoid.len() as u32,
837 res.as_mut_ptr() as *mut libc::c_void,
838 &mut len,
839 std::ptr::null_mut(),
840 0,
841 )
842 };
843 if ret != 0 {
844 let e = std::io::Error::last_os_error();
845
846 if e.raw_os_error() == Some(libc::ENOENT) {
847 return Ok(None);
848 }
849 return Err(SysctlError::IoError(e));
850 }
851
852 // len is in bytes, convert to number of libc::c_ints
853 len /= std::mem::size_of::<libc::c_int>();
854
855 // Trim result vector
856 res.truncate(len);
857
858 Ok(Some(res))
859 }
860
861 #[cfg(test)]
862 mod tests {
863 use crate::Sysctl;
864
865 #[test]
866 fn ctl_name() {
867 let oid = vec![libc::CTL_KERN, libc::KERN_OSREV];
868 let name = super::oid2name(&oid).expect("Could not get name of kern.osrevision sysctl.");
869
870 assert_eq!(name, "kern.osrevision");
871
872 let ctl = crate::Ctl::Oid(oid);
873 let name = ctl
874 .name()
875 .expect("Could not get name of kern.osrevision sysctl.");
876 assert_eq!(name, "kern.osrevision");
877 }
878
879 #[test]
880 fn ctl_type() {
881 let oid = super::name2oid("kern").unwrap();
882 let fmt = super::oidfmt(&oid).unwrap();
883 assert_eq!(fmt.ctl_type, crate::CtlType::Node);
884 let kern = crate::Ctl::new("kern").expect("Could not get kern node");
885 let value_type = kern.value_type().expect("Could not get kern value type");
886 assert_eq!(value_type, crate::CtlType::Node);
887
888 let oid = super::name2oid("kern.osrelease").unwrap();
889 let fmt = super::oidfmt(&oid).unwrap();
890 assert_eq!(fmt.ctl_type, crate::CtlType::String);
891 let osrelease =
892 crate::Ctl::new("kern.osrelease").expect("Could not get kern.osrelease sysctl");
893 let value_type = osrelease
894 .value_type()
895 .expect("Could not get kern.osrelease value type");
896 assert_eq!(value_type, crate::CtlType::String);
897
898 let oid = super::name2oid("kern.osrevision").unwrap();
899 let fmt = super::oidfmt(&oid).unwrap();
900 assert_eq!(fmt.ctl_type, crate::CtlType::Int);
901 let osrevision =
902 crate::Ctl::new("kern.osrevision").expect("Could not get kern.osrevision sysctl");
903 let value_type = osrevision
904 .value_type()
905 .expect("Could notget kern.osrevision value type");
906 assert_eq!(value_type, crate::CtlType::Int);
907 }
908
909 /// The name must be respresentable as a C String
910 #[test]
911 fn name2oid_invalid_name() {
912 let r = super::name2oid("kern.\0.invalid.utf-8");
913 assert!(matches!(r, Err(super::SysctlError::NotFound(_))));
914 }
915 }
916
917 #[cfg(all(test, target_os = "freebsd"))]
918 mod tests_freebsd {
919 #[test]
920 fn ctl_mib() {
921 let oid = super::name2oid("kern.proc.pid").unwrap();
922 assert_eq!(oid.len(), 3);
923 assert_eq!(oid[0], libc::CTL_KERN);
924 assert_eq!(oid[1], libc::KERN_PROC);
925 assert_eq!(oid[2], libc::KERN_PROC_PID);
926 }
927 }
928
929 #[cfg(all(test, any(target_os = "macos", target_os = "ios")))]
930 mod tests_macos {
931 #[test]
932 fn ctl_mib() {
933 let oid = super::name2oid("kern.proc.pid").unwrap();
934 assert_eq!(oid.len(), 3);
935 assert_eq!(oid[0], libc::CTL_KERN);
936 assert_eq!(oid[1], libc::KERN_PROC);
937 assert_eq!(oid[2], libc::KERN_PROC_PID);
938 }
939 }