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
//! Keychain support.

use core_foundation::base::{Boolean, TCFType};
use security_framework_sys::base::SecKeychainRef;
use security_framework_sys::keychain::*;
use std::path::Path;
use std::ptr;
use std::ffi::CString;
use libc::c_void;
use std::os::unix::ffi::OsStrExt;

use cvt;
use base::Result;
use os::macos::access::SecAccess;

make_wrapper! {
    /// A type representing a keychain.
    struct SecKeychain, SecKeychainRef, SecKeychainGetTypeID
}

unsafe impl Sync for SecKeychain {}
unsafe impl Send for SecKeychain {}

/// Deprecated.
pub trait SecKeychainExt {
    /// Deprecated.
    fn default() -> Result<SecKeychain>;

    /// Deprecated.
    fn open<P: AsRef<Path>>(path: P) -> Result<SecKeychain>;

    /// Deprecated.
    fn unlock(&mut self, password: Option<&str>) -> Result<()>;
}

impl SecKeychainExt for SecKeychain {
    fn default() -> Result<SecKeychain> {
        SecKeychain::default()
    }

    fn open<P: AsRef<Path>>(path: P) -> Result<SecKeychain> {
        SecKeychain::open(path)
    }

    fn unlock(&mut self, password: Option<&str>) -> Result<()> {
        SecKeychain::unlock(self, password)
    }
}

impl SecKeychain {
    /// Creates a `SecKeychain` object corresponding to the user's default
    /// keychain.
    fn default() -> Result<SecKeychain> {
        unsafe {
            let mut keychain = ptr::null_mut();
            try!(cvt(SecKeychainCopyDefault(&mut keychain)));
            Ok(SecKeychain::wrap_under_create_rule(keychain))
        }
    }

    /// Opens a keychain from a file.
    fn open<P: AsRef<Path>>(path: P) -> Result<SecKeychain> {
        let path_name = path.as_ref().as_os_str().as_bytes();
        // FIXME
        let path_name = CString::new(path_name).unwrap();

        unsafe {
            let mut keychain = ptr::null_mut();
            try!(cvt(SecKeychainOpen(path_name.as_ptr(), &mut keychain)));
            Ok(SecKeychain::wrap_under_create_rule(keychain))
        }
    }

    /// Unlocks the keychain.
    ///
    /// If a password is not specified, the user will be prompted to enter it.
    fn unlock(&mut self, password: Option<&str>) -> Result<()> {
        let (len, ptr, use_password) = match password {
            Some(password) => (password.len(), password.as_ptr() as *const _, true),
            None => (0, ptr::null(), false),
        };

        unsafe {
            cvt(SecKeychainUnlock(self.as_concrete_TypeRef(),
                                  len as u32,
                                  ptr,
                                  use_password as Boolean))
        }
    }
}

/// A builder type to create new keychains.
#[derive(Default)]
pub struct CreateOptions {
    password: Option<String>,
    prompt_user: bool,
    access: Option<SecAccess>,
}

impl CreateOptions {
    /// Creates a new builder with default options.
    pub fn new() -> CreateOptions {
        CreateOptions::default()
    }

    /// Sets the password to be used to protect the keychain.
    pub fn password(&mut self, password: &str) -> &mut CreateOptions {
        self.password = Some(password.into());
        self
    }

    /// If set, the user will be prompted to provide a password used to
    /// protect the keychain.
    pub fn prompt_user(&mut self, prompt_user: bool) -> &mut CreateOptions {
        self.prompt_user = prompt_user;
        self
    }

    /// Sets the access control applied to the keychain.
    pub fn access(&mut self, access: SecAccess) -> &mut CreateOptions {
        self.access = Some(access);
        self
    }

    /// Creates a new keychain at the specified location on the filesystem.
    pub fn create<P: AsRef<Path>>(&self, path: P) -> Result<SecKeychain> {
        unsafe {
            let path_name = path.as_ref().as_os_str().as_bytes();
            // FIXME
            let path_name = CString::new(path_name).unwrap();

            let (password, password_len) = match self.password {
                Some(ref password) => (password.as_ptr() as *const c_void, password.len() as u32),
                None => (ptr::null(), 0),
            };

            let access = match self.access {
                Some(ref access) => access.as_concrete_TypeRef(),
                None => ptr::null_mut(),
            };

            let mut keychain = ptr::null_mut();
            try!(cvt(SecKeychainCreate(path_name.as_ptr(),
                                       password_len,
                                       password,
                                       self.prompt_user as Boolean,
                                       access,
                                       &mut keychain)));

            Ok(SecKeychain::wrap_under_create_rule(keychain))
        }
    }
}

#[cfg(test)]
mod test {
    use tempdir::TempDir;

    use super::*;

    #[test]
    fn create_options() {
        let dir = TempDir::new("keychain").unwrap();

        CreateOptions::new()
            .password("foobar")
            .create(dir.path().join("test.keychain"))
            .unwrap();
    }
}