summaryrefslogtreecommitdiff
path: root/src/util.rs
blob: ac6c722978823f897e9a03a47d15e7ae1dbbbe7c (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
use std::borrow::Cow;
use std::path::Path;

use {raw, Error, Session};

#[doc(hidden)]
pub trait Binding: Sized {
    type Raw;

    unsafe fn from_raw(raw: Self::Raw) -> Self;
    fn raw(&self) -> Self::Raw;
}

#[doc(hidden)]
pub trait SessionBinding<'sess>: Sized {
    type Raw;

    unsafe fn from_raw(sess: &'sess Session, raw: *mut Self::Raw) -> Self;
    fn raw(&self) -> *mut Self::Raw;

    unsafe fn from_raw_opt(sess: &'sess Session, raw: *mut Self::Raw) -> Result<Self, Error> {
        if raw.is_null() {
            Err(Error::last_error(sess).unwrap_or_else(Error::unknown))
        } else {
            Ok(SessionBinding::from_raw(sess, raw))
        }
    }
}

#[cfg(unix)]
pub fn path2bytes(p: &Path) -> Result<Cow<[u8]>, Error> {
    use std::ffi::OsStr;
    use std::os::unix::prelude::*;
    let s: &OsStr = p.as_ref();
    check(Cow::Borrowed(s.as_bytes()))
}
#[cfg(windows)]
pub fn path2bytes(p: &Path) -> Result<Cow<[u8]>, Error> {
    p.to_str()
        .map(|s| s.as_bytes())
        .ok_or_else(|| {
            Error::new(
                raw::LIBSSH2_ERROR_INVAL,
                "only unicode paths on windows may be used",
            )
        })
        .map(|bytes| {
            if bytes.contains(&b'\\') {
                // Normalize to Unix-style path separators
                let mut bytes = bytes.to_owned();
                for b in &mut bytes {
                    if *b == b'\\' {
                        *b = b'/';
                    }
                }
                Cow::Owned(bytes)
            } else {
                Cow::Borrowed(bytes)
            }
        })
        .and_then(check)
}

fn check(b: Cow<[u8]>) -> Result<Cow<[u8]>, Error> {
    if b.iter().any(|b| *b == 0) {
        Err(Error::new(
            raw::LIBSSH2_ERROR_INVAL,
            "path provided contains a 0 byte",
        ))
    } else {
        Ok(b)
    }
}