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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
// unix/funcs.rs

use byteorder::{ByteOrder, WriteBytesExt};
use consts::*;
use ctl_error::*;
use ctl_info::*;
use ctl_type::*;
use ctl_value::*;

#[cfg(target_os = "freebsd")]
use temperature::*;

#[cfg(not(target_os = "macos"))]
pub fn name2oid(name: &str) -> Result<Vec<libc::c_int>, SysctlError> {
    // Request command for OID
    let oid: [libc::c_int; 2] = [0, 3];

    let mut len: usize = CTL_MAXNAME as usize * std::mem::size_of::<libc::c_int>();

    // We get results in this vector
    let mut res: Vec<libc::c_int> = vec![0; CTL_MAXNAME as usize];

    let ret = unsafe {
        libc::sysctl(
            oid.as_ptr(),
            2,
            res.as_mut_ptr() as *mut libc::c_void,
            &mut len,
            name.as_ptr() as *const libc::c_void,
            name.len(),
        )
    };
    if ret < 0 {
        let e = std::io::Error::last_os_error();
        return Err(match e.kind() {
            std::io::ErrorKind::NotFound => SysctlError::NotFound(name.into()),
            _ => SysctlError::IoError(e),
        });
    }

    // len is in bytes, convert to number of libc::c_ints
    len /= std::mem::size_of::<libc::c_int>();

    // Trim result vector
    res.truncate(len);

    Ok(res)
}

#[cfg(target_os = "macos")]
pub fn name2oid(name: &str) -> Result<Vec<libc::c_int>, SysctlError> {
    // Request command for OID
    let mut oid: [libc::c_int; 2] = [0, 3];

    let mut len: usize = CTL_MAXNAME as usize * std::mem::size_of::<libc::c_int>();

    // We get results in this vector
    let mut res: Vec<libc::c_int> = vec![0; CTL_MAXNAME as usize];

    let ret = unsafe {
        libc::sysctl(
            oid.as_mut_ptr(),
            2,
            res.as_mut_ptr() as *mut libc::c_void,
            &mut len,
            name.as_ptr() as *mut libc::c_void,
            name.len(),
        )
    };
    if ret < 0 {
        let e = std::io::Error::last_os_error();
        return Err(match e.kind() {
            std::io::ErrorKind::NotFound => SysctlError::NotFound(name.into()),
            _ => SysctlError::IoError(e),
        });
    }

    // len is in bytes, convert to number of libc::c_ints
    len /= std::mem::size_of::<libc::c_int>();

    // Trim result vector
    res.truncate(len);

    Ok(res)
}

#[cfg(not(target_os = "macos"))]
pub fn oidfmt(oid: &[libc::c_int]) -> Result<CtlInfo, SysctlError> {
    // Request command for type info
    let mut qoid: Vec<libc::c_int> = vec![0, 4];
    qoid.extend(oid);

    // Store results here
    let mut buf: [libc::c_uchar; libc::BUFSIZ as usize] = [0; libc::BUFSIZ as usize];
    let mut buf_len = std::mem::size_of_val(&buf);
    let ret = unsafe {
        libc::sysctl(
            qoid.as_ptr(),
            qoid.len() as u32,
            buf.as_mut_ptr() as *mut libc::c_void,
            &mut buf_len,
            std::ptr::null(),
            0,
        )
    };
    if ret != 0 {
        return Err(SysctlError::IoError(std::io::Error::last_os_error()));
    }

    // 'Kind' is the first 32 bits of result buffer
    let kind = byteorder::LittleEndian::read_u32(&buf);

    // 'Type' is the first 4 bits of 'Kind'
    let ctltype_val = kind & CTLTYPE as u32;

    // 'fmt' is after 'Kind' in result buffer
    let fmt: String =
        match std::ffi::CStr::from_bytes_with_nul(&buf[std::mem::size_of::<u32>()..buf_len]) {
            Ok(x) => x.to_string_lossy().into(),
            Err(e) => return Err(SysctlError::InvalidCStr(e)),
        };

    let s = CtlInfo {
        ctl_type: CtlType::from(ctltype_val),
        fmt: fmt,
        flags: kind,
    };
    Ok(s)
}

#[cfg(target_os = "macos")]
pub fn oidfmt(oid: &[libc::c_int]) -> Result<CtlInfo, SysctlError> {
    // Request command for type info
    let mut qoid: Vec<libc::c_int> = vec![0, 4];
    qoid.extend(oid);

    // Store results here
    let mut buf: [libc::c_uchar; libc::BUFSIZ as usize] = [0; libc::BUFSIZ as usize];
    let mut buf_len = std::mem::size_of_val(&buf);
    let ret = unsafe {
        libc::sysctl(
            qoid.as_mut_ptr(),
            qoid.len() as u32,
            buf.as_mut_ptr() as *mut libc::c_void,
            &mut buf_len,
            std::ptr::null_mut(),
            0,
        )
    };
    if ret != 0 {
        return Err(SysctlError::IoError(std::io::Error::last_os_error()));
    }

    // 'Kind' is the first 32 bits of result buffer
    let kind = byteorder::LittleEndian::read_u32(&buf);

    // 'Type' is the first 4 bits of 'Kind'
    let ctltype_val = kind & CTLTYPE as u32;

    // 'fmt' is after 'Kind' in result buffer
    let fmt: String = match std::str::from_utf8(&buf[std::mem::size_of::<u32>()..buf_len]) {
        Ok(x) => x.to_owned(),
        Err(e) => return Err(SysctlError::Utf8Error(e)),
    };

    let s = CtlInfo {
        ctl_type: CtlType::from(ctltype_val),
        fmt: fmt,
        flags: kind,
    };
    Ok(s)
}

#[cfg(not(target_os = "macos"))]
pub fn value_oid(oid: &Vec<i32>) -> Result<CtlValue, SysctlError> {
    let info: CtlInfo = try!(oidfmt(&oid));

    // Check if the value is readable
    if !(info.flags & CTLFLAG_RD == CTLFLAG_RD) {
        return Err(SysctlError::NoReadAccess);
    }

    // First get size of value in bytes
    let mut val_len = 0;
    let ret = unsafe {
        libc::sysctl(
            oid.as_ptr(),
            oid.len() as u32,
            std::ptr::null_mut(),
            &mut val_len,
            std::ptr::null(),
            0,
        )
    };
    if ret < 0 {
        return Err(SysctlError::IoError(std::io::Error::last_os_error()));
    }

    // If the length reported is shorter than the type we will convert it into,
    // byteorder::LittleEndian::read_* will panic. Therefore, expand the value length to at
    // Least the size of the value.
    let val_minsize = std::cmp::max(val_len, info.ctl_type.min_type_size());

    // Then get value
    let mut val: Vec<libc::c_uchar> = vec![0; val_minsize];
    let mut new_val_len = val_len;
    let ret = unsafe {
        libc::sysctl(
            oid.as_ptr(),
            oid.len() as u32,
            val.as_mut_ptr() as *mut libc::c_void,
            &mut new_val_len,
            std::ptr::null(),
            0,
        )
    };
    if ret < 0 {
        return Err(SysctlError::IoError(std::io::Error::last_os_error()));
    }

    // Confirm that we did not read out of bounds
    assert!(new_val_len <= val_len);
    // Confirm that we got the bytes we requested
    if new_val_len < val_len {
        return Err(SysctlError::ShortRead {
            read: new_val_len,
            reported: val_len,
        });
    }

    // Special treatment for temperature ctls.
    if info.is_temperature() {
        return temperature(&info, &val);
    }

    // Wrap in Enum and return
    match info.ctl_type {
        CtlType::None => Ok(CtlValue::None),
        CtlType::Node => Ok(CtlValue::Node(val)),
        CtlType::Int => Ok(CtlValue::Int(byteorder::LittleEndian::read_i32(&val))),
        CtlType::String => match val.len() {
            0 => Ok(CtlValue::String("".to_string())),
            l => std::str::from_utf8(&val[..l - 1])
                .map_err(|e| SysctlError::Utf8Error(e))
                .map(|s| CtlValue::String(s.into())),
        },
        CtlType::S64 => Ok(CtlValue::S64(byteorder::LittleEndian::read_u64(&val))),
        CtlType::Struct => Ok(CtlValue::Struct(val)),
        CtlType::Uint => Ok(CtlValue::Uint(byteorder::LittleEndian::read_u32(&val))),
        CtlType::Long => Ok(CtlValue::Long(byteorder::LittleEndian::read_i64(&val))),
        CtlType::Ulong => Ok(CtlValue::Ulong(byteorder::LittleEndian::read_u64(&val))),
        CtlType::U64 => Ok(CtlValue::U64(byteorder::LittleEndian::read_u64(&val))),
        CtlType::U8 => Ok(CtlValue::U8(val[0])),
        CtlType::U16 => Ok(CtlValue::U16(byteorder::LittleEndian::read_u16(&val))),
        CtlType::S8 => Ok(CtlValue::S8(val[0] as i8)),
        CtlType::S16 => Ok(CtlValue::S16(byteorder::LittleEndian::read_i16(&val))),
        CtlType::S32 => Ok(CtlValue::S32(byteorder::LittleEndian::read_i32(&val))),
        CtlType::U32 => Ok(CtlValue::U32(byteorder::LittleEndian::read_u32(&val))),
        _ => Err(SysctlError::UnknownType),
    }
}

#[cfg(target_os = "macos")]
pub fn value_oid(oid: &mut Vec<i32>) -> Result<CtlValue, SysctlError> {
    let info: CtlInfo = try!(oidfmt(&oid));

    // Check if the value is readable
    if !(info.flags & CTLFLAG_RD == CTLFLAG_RD) {
        return Err(SysctlError::NoReadAccess);
    }

    // First get size of value in bytes
    let mut val_len = 0;
    let ret = unsafe {
        libc::sysctl(
            oid.as_mut_ptr(),
            oid.len() as u32,
            std::ptr::null_mut(),
            &mut val_len,
            std::ptr::null_mut(),
            0,
        )
    };
    if ret < 0 {
        return Err(SysctlError::IoError(std::io::Error::last_os_error()));
    }

    // If the length reported is shorter than the type we will convert it into,
    // byteorder::LittleEndian::read_* will panic. Therefore, expand the value length to at
    // Least the size of the value.
    let val_minsize = std::cmp::max(val_len, info.ctl_type.min_type_size());

    // Then get value
    let mut val: Vec<libc::c_uchar> = vec![0; val_minsize];
    let mut new_val_len = val_len;
    let ret = unsafe {
        libc::sysctl(
            oid.as_mut_ptr(),
            oid.len() as u32,
            val.as_mut_ptr() as *mut libc::c_void,
            &mut new_val_len,
            std::ptr::null_mut(),
            0,
        )
    };
    if ret < 0 {
        return Err(SysctlError::IoError(std::io::Error::last_os_error()));
    }

    // Confirm that we did not read out of bounds
    assert!(new_val_len <= val_len);
    // Confirm that we got the bytes we requested
    if new_val_len < val_len {
        return Err(SysctlError::ShortRead {
            read: new_val_len,
            reported: val_len,
        });
    }

    // Wrap in Enum and return
    match info.ctl_type {
        CtlType::None => Ok(CtlValue::None),
        CtlType::Node => Ok(CtlValue::Node(val)),
        CtlType::Int => Ok(CtlValue::Int(byteorder::LittleEndian::read_i32(&val))),
        CtlType::String => match std::str::from_utf8(&val[..val.len() - 1]) {
            Ok(s) => Ok(CtlValue::String(s.into())),
            Err(e) => Err(SysctlError::Utf8Error(e)),
        },
        CtlType::S64 => Ok(CtlValue::S64(byteorder::LittleEndian::read_u64(&val))),
        CtlType::Struct => Ok(CtlValue::Struct(val)),
        CtlType::Uint => Ok(CtlValue::Uint(byteorder::LittleEndian::read_u32(&val))),
        CtlType::Long => Ok(CtlValue::Long(byteorder::LittleEndian::read_i64(&val))),
        CtlType::Ulong => Ok(CtlValue::Ulong(byteorder::LittleEndian::read_u64(&val))),
        CtlType::U64 => Ok(CtlValue::U64(byteorder::LittleEndian::read_u64(&val))),
        CtlType::U8 => Ok(CtlValue::U8(val[0])),
        CtlType::U16 => Ok(CtlValue::U16(byteorder::LittleEndian::read_u16(&val))),
        CtlType::S8 => Ok(CtlValue::S8(val[0] as i8)),
        CtlType::S16 => Ok(CtlValue::S16(byteorder::LittleEndian::read_i16(&val))),
        CtlType::S32 => Ok(CtlValue::S32(byteorder::LittleEndian::read_i32(&val))),
        CtlType::U32 => Ok(CtlValue::U32(byteorder::LittleEndian::read_u32(&val))),
        #[cfg(not(target_os = "macos"))]
        _ => Err(SysctlError::UnknownType),
    }
}

#[cfg(not(target_os = "macos"))]
pub fn value_oid_as<T>(oid: &Vec<i32>) -> Result<Box<T>, SysctlError> {
    let val_enum = try!(value_oid(oid));

    // Some structs are apparently reported as Node so this check is invalid..
    // let ctl_type = CtlType::from(&val_enum);
    // assert_eq!(CtlType::Struct, ctl_type, "Error type is not struct/opaque");

    // TODO: refactor this when we have better clue to what's going on
    if let CtlValue::Struct(val) = val_enum {
        // Make sure we got correct data size
        assert_eq!(
            std::mem::size_of::<T>(),
            val.len(),
            "Error memory size mismatch. Size of struct {}, size of data retrieved {}.",
            std::mem::size_of::<T>(),
            val.len()
        );

        // val is Vec<u8>
        let val_array: Box<[u8]> = val.into_boxed_slice();
        let val_raw: *mut T = Box::into_raw(val_array) as *mut T;
        let val_box: Box<T> = unsafe { Box::from_raw(val_raw) };
        Ok(val_box)
    } else if let CtlValue::Node(val) = val_enum {
        // Make sure we got correct data size
        assert_eq!(
            std::mem::size_of::<T>(),
            val.len(),
            "Error memory size mismatch. Size of struct {}, size of data retrieved {}.",
            std::mem::size_of::<T>(),
            val.len()
        );

        // val is Vec<u8>
        let val_array: Box<[u8]> = val.into_boxed_slice();
        let val_raw: *mut T = Box::into_raw(val_array) as *mut T;
        let val_box: Box<T> = unsafe { Box::from_raw(val_raw) };
        Ok(val_box)
    } else {
        Err(SysctlError::ExtractionError)
    }
}

#[cfg(target_os = "macos")]
pub fn value_oid_as<T>(oid: &mut Vec<i32>) -> Result<Box<T>, SysctlError> {
    let val_enum = try!(value_oid(oid));

    // Some structs are apparently reported as Node so this check is invalid..
    // let ctl_type = CtlType::from(&val_enum);
    // assert_eq!(CtlType::Struct, ctl_type, "Error type is not struct/opaque");

    // TODO: refactor this when we have better clue to what's going on
    if let CtlValue::Struct(val) = val_enum {
        // Make sure we got correct data size
        assert_eq!(
            std::mem::size_of::<T>(),
            val.len(),
            "Error memory size mismatch. Size of struct {}, size of data retrieved {}.",
            std::mem::size_of::<T>(),
            val.len()
        );

        // val is Vec<u8>
        let val_array: Box<[u8]> = val.into_boxed_slice();
        let val_raw: *mut T = Box::into_raw(val_array) as *mut T;
        let val_box: Box<T> = unsafe { Box::from_raw(val_raw) };
        Ok(val_box)
    } else if let CtlValue::Node(val) = val_enum {
        // Make sure we got correct data size
        assert_eq!(
            std::mem::size_of::<T>(),
            val.len(),
            "Error memory size mismatch. Size of struct {}, size of data retrieved {}.",
            std::mem::size_of::<T>(),
            val.len()
        );

        // val is Vec<u8>
        let val_array: Box<[u8]> = val.into_boxed_slice();
        let val_raw: *mut T = Box::into_raw(val_array) as *mut T;
        let val_box: Box<T> = unsafe { Box::from_raw(val_raw) };
        Ok(val_box)
    } else {
        Err(SysctlError::ExtractionError)
    }
}

fn value_to_bytes(value: CtlValue) -> Result<Vec<u8>, SysctlError> {
    // TODO rest of the types
    match value {
        CtlValue::String(v) => Ok(v.as_bytes().to_owned()),
        CtlValue::Ulong(v) => {
            let mut bytes = vec![];
            bytes.write_u64::<byteorder::LittleEndian>(v)?;
            Ok(bytes)
        }
        CtlValue::Uint(v) => {
            let mut bytes = vec![];
            bytes.write_u32::<byteorder::LittleEndian>(v)?;
            Ok(bytes)
        }
        CtlValue::Int(v) => {
            let mut bytes = vec![];
            bytes.write_i32::<byteorder::LittleEndian>(v)?;
            Ok(bytes)
        }
        CtlValue::U8(v) => {
            let mut bytes = vec![];
            bytes.write_u8(v)?;
            Ok(bytes)
        }
        _ => Err(SysctlError::MissingImplementation),
    }
}

#[cfg(not(target_os = "macos"))]
pub fn set_oid_value(oid: &Vec<libc::c_int>, value: CtlValue) -> Result<CtlValue, SysctlError> {
    let info: CtlInfo = try!(oidfmt(&oid));

    // Check if the value is writeable
    if !(info.flags & CTLFLAG_WR == CTLFLAG_WR) {
        return Err(SysctlError::NoWriteAccess);
    }

    let ctl_type = CtlType::from(&value);
    assert_eq!(
        info.ctl_type, ctl_type,
        "Error type mismatch. Type given {:?}, sysctl type: {:?}",
        ctl_type, info.ctl_type
    );

    let bytes = value_to_bytes(value)?;

    let ret = unsafe {
        libc::sysctl(
            oid.as_ptr(),
            oid.len() as u32,
            std::ptr::null_mut(),
            std::ptr::null_mut(),
            bytes.as_ptr() as *const libc::c_void,
            bytes.len(),
        )
    };
    if ret < 0 {
        return Err(SysctlError::IoError(std::io::Error::last_os_error()));
    }

    // Get the new value and return for confirmation
    self::value_oid(oid)
}

#[cfg(target_os = "macos")]
pub fn set_oid_value(oid: &mut Vec<libc::c_int>, value: CtlValue) -> Result<CtlValue, SysctlError> {
    let info: CtlInfo = try!(oidfmt(&oid));

    // Check if the value is writeable
    if !(info.flags & CTLFLAG_WR == CTLFLAG_WR) {
        return Err(SysctlError::NoWriteAccess);
    }

    let ctl_type = CtlType::from(&value);
    assert_eq!(
        info.ctl_type, ctl_type,
        "Error type mismatch. Type given {:?}, sysctl type: {:?}",
        ctl_type, info.ctl_type
    );

    let bytes = value_to_bytes(value)?;

    // Set value
    let ret = unsafe {
        libc::sysctl(
            oid.as_mut_ptr(),
            oid.len() as u32,
            std::ptr::null_mut(),
            std::ptr::null_mut(),
            bytes.as_ptr() as *mut libc::c_void,
            bytes.len(),
        )
    };
    if ret < 0 {
        return Err(SysctlError::IoError(std::io::Error::last_os_error()));
    }

    // Get the new value and return for confirmation
    self::value_oid(oid)
}

#[cfg(not(target_os = "macos"))]
pub fn oid2description(oid: &Vec<libc::c_int>) -> Result<String, SysctlError> {
    // Request command for description
    let mut qoid: Vec<libc::c_int> = vec![0, 5];
    qoid.extend(oid);

    // Store results in u8 array
    let mut buf: [libc::c_uchar; libc::BUFSIZ as usize] = [0; libc::BUFSIZ as usize];
    let mut buf_len = std::mem::size_of_val(&buf);
    let ret = unsafe {
        libc::sysctl(
            qoid.as_ptr(),
            qoid.len() as u32,
            buf.as_mut_ptr() as *mut libc::c_void,
            &mut buf_len,
            std::ptr::null(),
            0,
        )
    };
    if ret != 0 {
        return Err(SysctlError::IoError(std::io::Error::last_os_error()));
    }

    // Use buf_len - 1 so that we remove the trailing NULL
    match std::str::from_utf8(&buf[..buf_len - 1]) {
        Ok(s) => Ok(s.to_owned()),
        Err(e) => Err(SysctlError::Utf8Error(e)),
    }
}

#[cfg(not(target_os = "macos"))]
pub fn oid2name(oid: &Vec<libc::c_int>) -> Result<String, SysctlError> {
    // Request command for name
    let mut qoid: Vec<libc::c_int> = vec![0, 1];
    qoid.extend(oid);

    // Store results in u8 array
    let mut buf: [libc::c_uchar; libc::BUFSIZ as usize] = [0; libc::BUFSIZ as usize];
    let mut buf_len = std::mem::size_of_val(&buf);
    let ret = unsafe {
        libc::sysctl(
            qoid.as_ptr(),
            qoid.len() as u32,
            buf.as_mut_ptr() as *mut libc::c_void,
            &mut buf_len,
            std::ptr::null(),
            0,
        )
    };
    if ret != 0 {
        return Err(SysctlError::IoError(std::io::Error::last_os_error()));
    }

    // Use buf_len - 1 so that we remove the trailing NULL
    match std::str::from_utf8(&buf[..buf_len - 1]) {
        Ok(s) => Ok(s.to_owned()),
        Err(e) => Err(SysctlError::Utf8Error(e)),
    }
}

#[cfg(target_os = "macos")]
pub fn oid2name(oid: &Vec<libc::c_int>) -> Result<String, SysctlError> {
    // Request command for name
    let mut qoid: Vec<libc::c_int> = vec![0, 1];
    qoid.extend(oid);

    // Store results in u8 array
    let mut buf: [libc::c_uchar; libc::BUFSIZ as usize] = [0; libc::BUFSIZ as usize];
    let mut buf_len = std::mem::size_of_val(&buf);
    let ret = unsafe {
        libc::sysctl(
            qoid.as_mut_ptr(),
            qoid.len() as u32,
            buf.as_mut_ptr() as *mut libc::c_void,
            &mut buf_len,
            std::ptr::null_mut(),
            0,
        )
    };
    if ret != 0 {
        return Err(SysctlError::IoError(std::io::Error::last_os_error()));
    }

    // Use buf_len - 1 so that we remove the trailing NULL
    match std::str::from_utf8(&buf[..buf_len - 1]) {
        Ok(s) => Ok(s.to_owned()),
        Err(e) => Err(SysctlError::Utf8Error(e)),
    }
}

#[cfg(not(target_os = "macos"))]
pub fn next_oid(oid: &Vec<libc::c_int>) -> Result<Option<Vec<libc::c_int>>, SysctlError> {
    // Request command for next oid
    let mut qoid: Vec<libc::c_int> = vec![0, 2];
    qoid.extend(oid);

    let mut len: usize = CTL_MAXNAME as usize * std::mem::size_of::<libc::c_int>();

    // We get results in this vector
    let mut res: Vec<libc::c_int> = vec![0; CTL_MAXNAME as usize];

    let ret = unsafe {
        libc::sysctl(
            qoid.as_ptr(),
            qoid.len() as u32,
            res.as_mut_ptr() as *mut libc::c_void,
            &mut len,
            std::ptr::null(),
            0,
        )
    };
    if ret != 0 {
        let e = std::io::Error::last_os_error();

        if e.raw_os_error() == Some(libc::ENOENT) {
            return Ok(None);
        }
        return Err(SysctlError::IoError(e));
    }

    // len is in bytes, convert to number of libc::c_ints
    len /= std::mem::size_of::<libc::c_int>();

    // Trim result vector
    res.truncate(len);

    Ok(Some(res))
}

#[cfg(target_os = "macos")]
pub fn next_oid(oid: &Vec<libc::c_int>) -> Result<Option<Vec<libc::c_int>>, SysctlError> {
    // Request command for next oid
    let mut qoid: Vec<libc::c_int> = vec![0, 2];
    qoid.extend(oid);

    let mut len: usize = CTL_MAXNAME as usize * std::mem::size_of::<libc::c_int>();

    // We get results in this vector
    let mut res: Vec<libc::c_int> = vec![0; CTL_MAXNAME as usize];

    let ret = unsafe {
        libc::sysctl(
            qoid.as_mut_ptr(),
            qoid.len() as u32,
            res.as_mut_ptr() as *mut libc::c_void,
            &mut len,
            std::ptr::null_mut(),
            0,
        )
    };
    if ret != 0 {
        let e = std::io::Error::last_os_error();

        if e.raw_os_error() == Some(libc::ENOENT) {
            return Ok(None);
        }
        return Err(SysctlError::IoError(e));
    }

    // len is in bytes, convert to number of libc::c_ints
    len /= std::mem::size_of::<libc::c_int>();

    // Trim result vector
    res.truncate(len);

    Ok(Some(res))
}

#[cfg(test)]
mod tests {
    use crate::Sysctl;

    #[test]
    fn ctl_name() {
        let oid = vec![libc::CTL_KERN, libc::KERN_OSREV];
        let name = super::oid2name(&oid).expect("Could not get name of kern.osrevision sysctl.");

        assert_eq!(name, "kern.osrevision");

        let ctl = crate::Ctl { oid };
        let name = ctl
            .name()
            .expect("Could not get name of kern.osrevision sysctl.");
        assert_eq!(name, "kern.osrevision");
    }

    #[test]
    fn ctl_type() {
        let oid = super::name2oid("kern").unwrap();
        let fmt = super::oidfmt(&oid).unwrap();
        assert_eq!(fmt.ctl_type, crate::CtlType::Node);
        let kern = crate::Ctl::new("kern").expect("Could not get kern node");
        let value_type = kern.value_type().expect("Could not get kern value type");
        assert_eq!(value_type, crate::CtlType::Node);

        let oid = super::name2oid("kern.osrelease").unwrap();
        let fmt = super::oidfmt(&oid).unwrap();
        assert_eq!(fmt.ctl_type, crate::CtlType::String);
        let osrelease =
            crate::Ctl::new("kern.osrelease").expect("Could not get kern.osrelease sysctl");
        let value_type = osrelease
            .value_type()
            .expect("Could not get kern.osrelease value type");
        assert_eq!(value_type, crate::CtlType::String);

        let oid = super::name2oid("kern.osrevision").unwrap();
        let fmt = super::oidfmt(&oid).unwrap();
        assert_eq!(fmt.ctl_type, crate::CtlType::Int);
        let osrevision =
            crate::Ctl::new("kern.osrevision").expect("Could not get kern.osrevision sysctl");
        let value_type = osrevision
            .value_type()
            .expect("Could notget kern.osrevision value type");
        assert_eq!(value_type, crate::CtlType::Int);
    }

}

#[cfg(all(test, target_os = "freebsd"))]
mod tests_freebsd {
    #[test]
    fn ctl_mib() {
        let oid = super::name2oid("kern.proc.pid").unwrap();
        assert_eq!(oid.len(), 3);
        assert_eq!(oid[0], libc::CTL_KERN);
        assert_eq!(oid[1], libc::KERN_PROC);
        assert_eq!(oid[2], libc::KERN_PROC_PID);
    }
}

#[cfg(all(test, target_os = "macos"))]
mod tests_macos {
    #[test]
    fn ctl_mib() {
        let oid = super::name2oid("kern.proc.pid").unwrap();
        assert_eq!(oid.len(), 3);
        assert_eq!(oid[0], libc::CTL_KERN);
        assert_eq!(oid[1], libc::KERN_PROC);
        assert_eq!(oid[2], libc::KERN_PROC_PID);
    }
}