Debian Codegraph @

third_party/rust/winreg/src/lib.rs

raw
1 // Copyright 2015, Igor Shaula
2 // Licensed under the MIT License <LICENSE or
3 // http://opensource.org/licenses/MIT>. This file
4 // may not be copied, modified, or distributed
5 // except according to those terms.
6
7 //! Crate for accessing MS Windows registry
8 //!
9 //!## Usage
10 //!
11 //!### Basic usage
12 //!
13 //!```toml,ignore
14 //!# Cargo.toml
15 //![dependencies]
16 //!winreg = "0.10"
17 //!```
18 //!
19 //!```no_run
20 //!extern crate winreg;
21 //!use std::io;
22 //!use std::path::Path;
23 //!use winreg::enums::*;
24 //!use winreg::RegKey;
25 //!
26 //!fn main() -> io::Result<()> {
27 //! println!("Reading some system info...");
28 //! let hklm = RegKey::predef(HKEY_LOCAL_MACHINE);
29 //! let cur_ver = hklm.open_subkey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion")?;
30 //! let pf: String = cur_ver.get_value("ProgramFilesDir")?;
31 //! let dp: String = cur_ver.get_value("DevicePath")?;
32 //! println!("ProgramFiles = {}\nDevicePath = {}", pf, dp);
33 //! let info = cur_ver.query_info()?;
34 //! println!("info = {:?}", info);
35 //! let mt = info.get_last_write_time_system();
36 //! println!(
37 //! "last_write_time as winapi::um::minwinbase::SYSTEMTIME = {}-{:02}-{:02} {:02}:{:02}:{:02}",
38 //! mt.wYear, mt.wMonth, mt.wDay, mt.wHour, mt.wMinute, mt.wSecond
39 //! );
40 //!
41 //! // enable `chrono` feature on `winreg` to make this work
42 //! // println!(
43 //! // "last_write_time as chrono::NaiveDateTime = {}",
44 //! // info.get_last_write_time_chrono()
45 //! // );
46 //!
47 //! println!("And now lets write something...");
48 //! let hkcu = RegKey::predef(HKEY_CURRENT_USER);
49 //! let path = Path::new("Software").join("WinregRsExample1");
50 //! let (key, disp) = hkcu.create_subkey(&path)?;
51 //!
52 //! match disp {
53 //! REG_CREATED_NEW_KEY => println!("A new key has been created"),
54 //! REG_OPENED_EXISTING_KEY => println!("An existing key has been opened"),
55 //! }
56 //!
57 //! key.set_value("TestSZ", &"written by Rust")?;
58 //! let sz_val: String = key.get_value("TestSZ")?;
59 //! key.delete_value("TestSZ")?;
60 //! println!("TestSZ = {}", sz_val);
61 //!
62 //! key.set_value("TestMultiSZ", &vec!["written", "by", "Rust"])?;
63 //! let multi_sz_val: Vec<String> = key.get_value("TestMultiSZ")?;
64 //! key.delete_value("TestMultiSZ")?;
65 //! println!("TestMultiSZ = {:?}", multi_sz_val);
66 //!
67 //! key.set_value("TestDWORD", &1234567890u32)?;
68 //! let dword_val: u32 = key.get_value("TestDWORD")?;
69 //! println!("TestDWORD = {}", dword_val);
70 //!
71 //! key.set_value("TestQWORD", &1234567891011121314u64)?;
72 //! let qword_val: u64 = key.get_value("TestQWORD")?;
73 //! println!("TestQWORD = {}", qword_val);
74 //!
75 //! key.create_subkey("sub\\key")?;
76 //! hkcu.delete_subkey_all(&path)?;
77 //!
78 //! println!("Trying to open nonexistent key...");
79 //! hkcu.open_subkey(&path).unwrap_or_else(|e| match e.kind() {
80 //! io::ErrorKind::NotFound => panic!("Key doesn't exist"),
81 //! io::ErrorKind::PermissionDenied => panic!("Access denied"),
82 //! _ => panic!("{:?}", e),
83 //! });
84 //! Ok(())
85 //!}
86 //!```
87 //!
88 //!### Iterators
89 //!
90 //!```no_run
91 //!extern crate winreg;
92 //!use std::io;
93 //!use winreg::RegKey;
94 //!use winreg::enums::*;
95 //!
96 //!fn main() -> io::Result<()> {
97 //! println!("File extensions, registered in system:");
98 //! for i in RegKey::predef(HKEY_CLASSES_ROOT)
99 //! .enum_keys().map(|x| x.unwrap())
100 //! .filter(|x| x.starts_with("."))
101 //! {
102 //! println!("{}", i);
103 //! }
104 //!
105 //! let system = RegKey::predef(HKEY_LOCAL_MACHINE)
106 //! .open_subkey("HARDWARE\\DESCRIPTION\\System")?;
107 //! for (name, value) in system.enum_values().map(|x| x.unwrap()) {
108 //! println!("{} = {:?}", name, value);
109 //! }
110 //!
111 //! Ok(())
112 //!}
113 //!```
114 //!
115 #[cfg(feature = "chrono")]
116 extern crate chrono;
117 #[cfg(feature = "serialization-serde")]
118 extern crate serde;
119 extern crate winapi;
120 use enums::*;
121 use std::default::Default;
122 use std::ffi::OsStr;
123 use std::fmt;
124 use std::io;
125 use std::mem::transmute;
126 use std::os::windows::ffi::OsStrExt;
127 use std::ptr;
128 use std::slice;
129 #[cfg(feature = "transactions")]
130 use transaction::Transaction;
131 use types::{FromRegValue, ToRegValue};
132 pub use winapi::shared::minwindef::HKEY;
133 use winapi::shared::minwindef::{BYTE, DWORD, FILETIME, LPBYTE};
134 use winapi::shared::winerror;
135 use winapi::um::minwinbase::SYSTEMTIME;
136 use winapi::um::timezoneapi::FileTimeToSystemTime;
137 use winapi::um::winnt::{self, WCHAR};
138 use winapi::um::winreg as winapi_reg;
139
140 macro_rules! werr {
141 ($e:expr) => {
142 Err(io::Error::from_raw_os_error($e as i32))
143 };
144 }
145
146 #[cfg(feature = "serialization-serde")]
147 mod decoder;
148 #[cfg(feature = "serialization-serde")]
149 mod encoder;
150 pub mod enums;
151 #[cfg(feature = "transactions")]
152 pub mod transaction;
153 pub mod types;
154
155 /// Metadata returned by `RegKey::query_info`
156 #[derive(Debug, Default)]
157 pub struct RegKeyMetadata {
158 // pub Class: winapi::LPWSTR,
159 // pub ClassLen: DWORD,
160 pub sub_keys: DWORD,
161 pub max_sub_key_len: DWORD,
162 pub max_class_len: DWORD,
163 pub values: DWORD,
164 pub max_value_name_len: DWORD,
165 pub max_value_len: DWORD,
166 // pub SecurityDescriptor: DWORD,
167 pub last_write_time: FILETIME,
168 }
169
170 impl RegKeyMetadata {
171 /// Returns `last_write_time` field as `winapi::um::minwinbase::SYSTEMTIME`
172 pub fn get_last_write_time_system(&self) -> SYSTEMTIME {
173 let mut st: SYSTEMTIME = unsafe { ::std::mem::zeroed() };
174 unsafe {
175 FileTimeToSystemTime(&self.last_write_time, &mut st);
176 }
177 st
178 }
179
180 /// Returns `last_write_time` field as `chrono::NaiveDateTime`.
181 /// Part of `chrono` feature.
182 #[cfg(feature = "chrono")]
183 pub fn get_last_write_time_chrono(&self) -> chrono::NaiveDateTime {
184 let st = self.get_last_write_time_system();
185
186 chrono::NaiveDate::from_ymd(st.wYear.into(), st.wMonth.into(), st.wDay.into()).and_hms(
187 st.wHour.into(),
188 st.wMinute.into(),
189 st.wSecond.into(),
190 )
191 }
192 }
193
194 /// Raw registry value
195 #[derive(PartialEq)]
196 pub struct RegValue {
197 pub bytes: Vec<u8>,
198 pub vtype: RegType,
199 }
200
201 macro_rules! format_reg_value {
202 ($e:expr => $t:ident) => {
203 match $t::from_reg_value($e) {
204 Ok(val) => format!("{:?}", val),
205 Err(_) => return Err(fmt::Error),
206 }
207 };
208 }
209
210 impl fmt::Display for RegValue {
211 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
212 let f_val = match self.vtype {
213 REG_SZ | REG_EXPAND_SZ | REG_MULTI_SZ => format_reg_value!(self => String),
214 REG_DWORD => format_reg_value!(self => u32),
215 REG_QWORD => format_reg_value!(self => u64),
216 _ => format!("{:?}", self.bytes), //TODO: implement more types
217 };
218 write!(f, "{}", f_val)
219 }
220 }
221
222 impl fmt::Debug for RegValue {
223 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
224 write!(f, "RegValue({:?}: {})", self.vtype, self)
225 }
226 }
227
228 /// Handle of opened registry key
229 #[derive(Debug)]
230 pub struct RegKey {
231 hkey: HKEY,
232 }
233
234 unsafe impl Send for RegKey {}
235
236 impl RegKey {
237 /// Open one of predefined keys:
238 ///
239 /// * `HKEY_CLASSES_ROOT`
240 /// * `HKEY_CURRENT_USER`
241 /// * `HKEY_LOCAL_MACHINE`
242 /// * `HKEY_USERS`
243 /// * `HKEY_PERFORMANCE_DATA`
244 /// * `HKEY_PERFORMANCE_TEXT`
245 /// * `HKEY_PERFORMANCE_NLSTEXT`
246 /// * `HKEY_CURRENT_CONFIG`
247 /// * `HKEY_DYN_DATA`
248 /// * `HKEY_CURRENT_USER_LOCAL_SETTINGS`
249 ///
250 /// # Examples
251 ///
252 /// ```no_run
253 /// # use winreg::RegKey;
254 /// # use winreg::enums::*;
255 /// let hklm = RegKey::predef(HKEY_LOCAL_MACHINE);
256 /// ```
257 pub const fn predef(hkey: HKEY) -> RegKey {
258 RegKey { hkey }
259 }
260
261 /// Load a registry hive from a file as an application hive.
262 /// If `lock` is set to `true`, then the hive cannot be loaded again until
263 /// it's unloaded (i.e. all keys from it go out of scope).
264 ///
265 /// # Examples
266 ///
267 /// ```no_run
268 /// # use std::error::Error;
269 /// # use winreg::RegKey;
270 /// # use winreg::enums::*;
271 /// # fn main() -> Result<(), Box<dyn Error>> {
272 /// let handle = RegKey::load_app_key("C:\\myhive.dat", false)?;
273 /// # Ok(())
274 /// # }
275 /// ```
276 pub fn load_app_key<N: AsRef<OsStr>>(filename: N, lock: bool) -> io::Result<RegKey> {
277 let options = if lock {
278 winapi_reg::REG_PROCESS_APPKEY
279 } else {
280 0
281 };
282 RegKey::load_app_key_with_flags(filename, enums::KEY_ALL_ACCESS, options)
283 }
284
285 /// Load a registry hive from a file as an application hive with desired
286 /// permissions and options. If `options` is set to `REG_PROCESS_APPKEY`,
287 /// then the hive cannot be loaded again until it's unloaded (i.e. all keys
288 /// from it go out of scope).
289 /// # Examples
290 ///
291 /// ```no_run
292 /// # use std::error::Error;
293 /// # use winreg::RegKey;
294 /// # use winreg::enums::*;
295 /// # fn main() -> Result<(), Box<dyn Error>> {
296 /// let handle = RegKey::load_app_key_with_flags("C:\\myhive.dat", KEY_READ, 0)?;
297 /// # Ok(())
298 /// # }
299 /// ```
300 pub fn load_app_key_with_flags<N: AsRef<OsStr>>(
301 filename: N,
302 perms: winapi_reg::REGSAM,
303 options: DWORD,
304 ) -> io::Result<RegKey> {
305 let c_filename = to_utf16(filename);
306 let mut new_hkey: HKEY = ptr::null_mut();
307 match unsafe {
308 winapi_reg::RegLoadAppKeyW(c_filename.as_ptr(), &mut new_hkey, perms, options, 0)
309 as DWORD
310 } {
311 0 => Ok(RegKey { hkey: new_hkey }),
312 err => werr!(err),
313 }
314 }
315
316 /// Return inner winapi HKEY of a key:
317 ///
318 /// # Examples
319 ///
320 /// ```no_run
321 /// # use std::error::Error;
322 /// # use winreg::RegKey;
323 /// # use winreg::enums::*;
324 /// # fn main() -> Result<(), Box<dyn Error>> {
325 /// let hklm = RegKey::predef(HKEY_LOCAL_MACHINE);
326 /// let soft = hklm.open_subkey("SOFTWARE")?;
327 /// let handle = soft.raw_handle();
328 /// # Ok(())
329 /// # }
330 /// ```
331 pub const fn raw_handle(&self) -> HKEY {
332 self.hkey
333 }
334
335 /// Open subkey with `KEY_READ` permissions.
336 /// Will open another handle to itself if `path` is an empty string.
337 /// To open with different permissions use `open_subkey_with_flags`.
338 /// You can also use `create_subkey` to open with `KEY_ALL_ACCESS` permissions.
339 ///
340 /// # Examples
341 ///
342 /// ```no_run
343 /// # use std::error::Error;
344 /// # use winreg::RegKey;
345 /// # use winreg::enums::*;
346 /// # fn main() -> Result<(), Box<dyn Error>> {
347 /// let soft = RegKey::predef(HKEY_CURRENT_USER)
348 /// .open_subkey("Software")?;
349 /// # Ok(())
350 /// # }
351 /// ```
352 pub fn open_subkey<P: AsRef<OsStr>>(&self, path: P) -> io::Result<RegKey> {
353 self.open_subkey_with_flags(path, enums::KEY_READ)
354 }
355
356 /// Open subkey with desired permissions.
357 /// Will open another handle to itself if `path` is an empty string.
358 ///
359 /// # Examples
360 ///
361 /// ```no_run
362 /// # use std::error::Error;
363 /// # use winreg::RegKey;
364 /// # use winreg::enums::*;
365 /// # fn main() -> Result<(), Box<dyn Error>> {
366 /// let hklm = RegKey::predef(HKEY_LOCAL_MACHINE);
367 /// hklm.open_subkey_with_flags("SOFTWARE\\Microsoft", KEY_READ)?;
368 /// # Ok(())
369 /// # }
370 /// ```
371 pub fn open_subkey_with_flags<P: AsRef<OsStr>>(
372 &self,
373 path: P,
374 perms: winapi_reg::REGSAM,
375 ) -> io::Result<RegKey> {
376 let c_path = to_utf16(path);
377 let mut new_hkey: HKEY = ptr::null_mut();
378 match unsafe {
379 winapi_reg::RegOpenKeyExW(self.hkey, c_path.as_ptr(), 0, perms, &mut new_hkey) as DWORD
380 } {
381 0 => Ok(RegKey { hkey: new_hkey }),
382 err => werr!(err),
383 }
384 }
385
386 /// Part of `transactions` feature.
387 #[cfg(feature = "transactions")]
388 pub fn open_subkey_transacted<P: AsRef<OsStr>>(
389 &self,
390 path: P,
391 t: &Transaction,
392 ) -> io::Result<RegKey> {
393 self.open_subkey_transacted_with_flags(path, t, winnt::KEY_READ)
394 }
395
396 /// Part of `transactions` feature.
397 #[cfg(feature = "transactions")]
398 pub fn open_subkey_transacted_with_flags<P: AsRef<OsStr>>(
399 &self,
400 path: P,
401 t: &Transaction,
402 perms: winapi_reg::REGSAM,
403 ) -> io::Result<RegKey> {
404 let c_path = to_utf16(path);
405 let mut new_hkey: HKEY = ptr::null_mut();
406 match unsafe {
407 winapi_reg::RegOpenKeyTransactedW(
408 self.hkey,
409 c_path.as_ptr(),
410 0,
411 perms,
412 &mut new_hkey,
413 t.handle,
414 ptr::null_mut(),
415 ) as DWORD
416 } {
417 0 => Ok(RegKey { hkey: new_hkey }),
418 err => werr!(err),
419 }
420 }
421
422 /// Create subkey (and all missing parent keys)
423 /// and open it with `KEY_ALL_ACCESS` permissions.
424 /// Will just open key if it already exists.
425 /// If succeeds returns a tuple with the created subkey and its disposition,
426 /// which can be `REG_CREATED_NEW_KEY` or `REG_OPENED_EXISTING_KEY`.
427 /// Will open another handle to itself if `path` is an empty string.
428 /// To create with different permissions use `create_subkey_with_flags`.
429 ///
430 /// # Examples
431 ///
432 /// ```no_run
433 /// # use std::error::Error;
434 /// # use winreg::RegKey;
435 /// use winreg::enums::*;
436 /// # fn main() -> Result<(), Box<dyn Error>> {
437 /// let hkcu = RegKey::predef(HKEY_CURRENT_USER);
438 /// let (settings, disp) = hkcu.create_subkey("Software\\MyProduct\\Settings")?;
439 ///
440 /// match disp {
441 /// REG_CREATED_NEW_KEY => println!("A new key has been created"),
442 /// REG_OPENED_EXISTING_KEY => println!("An existing key has been opened")
443 /// }
444 /// # Ok(())
445 /// # }
446 /// ```
447 pub fn create_subkey<P: AsRef<OsStr>>(&self, path: P) -> io::Result<(RegKey, RegDisposition)> {
448 self.create_subkey_with_flags(path, enums::KEY_ALL_ACCESS)
449 }
450
451 pub fn create_subkey_with_flags<P: AsRef<OsStr>>(
452 &self,
453 path: P,
454 perms: winapi_reg::REGSAM,
455 ) -> io::Result<(RegKey, RegDisposition)> {
456 let c_path = to_utf16(path);
457 let mut new_hkey: HKEY = ptr::null_mut();
458 let mut disp_buf: DWORD = 0;
459 match unsafe {
460 winapi_reg::RegCreateKeyExW(
461 self.hkey,
462 c_path.as_ptr(),
463 0,
464 ptr::null_mut(),
465 winnt::REG_OPTION_NON_VOLATILE,
466 perms,
467 ptr::null_mut(),
468 &mut new_hkey,
469 &mut disp_buf,
470 )
471 } {
472 0 => {
473 let disp: RegDisposition = unsafe { transmute(disp_buf as u8) };
474 Ok((RegKey { hkey: new_hkey }, disp))
475 }
476 err => werr!(err),
477 }
478 }
479
480 /// Part of `transactions` feature.
481 #[cfg(feature = "transactions")]
482 pub fn create_subkey_transacted<P: AsRef<OsStr>>(
483 &self,
484 path: P,
485 t: &Transaction,
486 ) -> io::Result<(RegKey, RegDisposition)> {
487 self.create_subkey_transacted_with_flags(path, t, winnt::KEY_ALL_ACCESS)
488 }
489
490 /// Part of `transactions` feature.
491 #[cfg(feature = "transactions")]
492 pub fn create_subkey_transacted_with_flags<P: AsRef<OsStr>>(
493 &self,
494 path: P,
495 t: &Transaction,
496 perms: winapi_reg::REGSAM,
497 ) -> io::Result<(RegKey, RegDisposition)> {
498 let c_path = to_utf16(path);
499 let mut new_hkey: HKEY = ptr::null_mut();
500 let mut disp_buf: DWORD = 0;
501 match unsafe {
502 winapi_reg::RegCreateKeyTransactedW(
503 self.hkey,
504 c_path.as_ptr(),
505 0,
506 ptr::null_mut(),
507 winnt::REG_OPTION_NON_VOLATILE,
508 perms,
509 ptr::null_mut(),
510 &mut new_hkey,
511 &mut disp_buf,
512 t.handle,
513 ptr::null_mut(),
514 ) as DWORD
515 } {
516 0 => {
517 let disp: RegDisposition = unsafe { transmute(disp_buf as u8) };
518 Ok((RegKey { hkey: new_hkey }, disp))
519 }
520 err => werr!(err),
521 }
522 }
523
524 /// Copy all the values and subkeys from `path` to `dest` key.
525 /// WIll copy the content of `self` if `path` is an empty string.
526 ///
527 /// # Examples
528 ///
529 /// ```no_run
530 /// # use std::error::Error;
531 /// # use winreg::RegKey;
532 /// # use winreg::enums::*;
533 /// # fn main() -> Result<(), Box<dyn Error>> {
534 /// let hkcu = RegKey::predef(HKEY_CURRENT_USER);
535 /// let src = hkcu.open_subkey_with_flags("Software\\MyProduct", KEY_READ)?;
536 /// let (dst, dst_disp) = hkcu.create_subkey("Software\\MyProduct\\Section2")?;
537 /// src.copy_tree("Section1", &dst)?;
538 /// # Ok(())
539 /// # }
540 /// ```
541 pub fn copy_tree<P: AsRef<OsStr>>(&self, path: P, dest: &RegKey) -> io::Result<()> {
542 let c_path = to_utf16(path);
543 match unsafe { winapi_reg::RegCopyTreeW(self.hkey, c_path.as_ptr(), dest.hkey) } {
544 0 => Ok(()),
545 err => werr!(err),
546 }
547 }
548
549 pub fn query_info(&self) -> io::Result<RegKeyMetadata> {
550 let mut info: RegKeyMetadata = Default::default();
551 match unsafe {
552 winapi_reg::RegQueryInfoKeyW(
553 self.hkey,
554 ptr::null_mut(), // Class: winapi::LPWSTR,
555 ptr::null_mut(), // ClassLen: DWORD,
556 ptr::null_mut(), // Reserved
557 &mut info.sub_keys,
558 &mut info.max_sub_key_len,
559 &mut info.max_class_len,
560 &mut info.values,
561 &mut info.max_value_name_len,
562 &mut info.max_value_len,
563 ptr::null_mut(), // lpcbSecurityDescriptor: winapi::LPDWORD,
564 &mut info.last_write_time,
565 ) as DWORD
566 } {
567 0 => Ok(info),
568 err => werr!(err),
569 }
570 }
571
572 /// Return an iterator over subkeys names.
573 ///
574 /// # Examples
575 ///
576 /// ```no_run
577 /// # use winreg::RegKey;
578 /// # use winreg::enums::*;
579 /// println!("File extensions, registered in this system:");
580 /// for i in RegKey::predef(HKEY_CLASSES_ROOT)
581 /// .enum_keys().map(|x| x.unwrap())
582 /// .filter(|x| x.starts_with("."))
583 /// {
584 /// println!("{}", i);
585 /// }
586 /// ```
587 pub const fn enum_keys(&self) -> EnumKeys {
588 EnumKeys {
589 key: self,
590 index: 0,
591 }
592 }
593
594 /// Return an iterator over values.
595 ///
596 /// # Examples
597 ///
598 /// ```no_run
599 /// # use std::error::Error;
600 /// # use winreg::RegKey;
601 /// # use winreg::enums::*;
602 /// # fn main() -> Result<(), Box<dyn Error>> {
603 /// let system = RegKey::predef(HKEY_LOCAL_MACHINE)
604 /// .open_subkey_with_flags("HARDWARE\\DESCRIPTION\\System", KEY_READ)?;
605 /// for (name, value) in system.enum_values().map(|x| x.unwrap()) {
606 /// println!("{} = {:?}", name, value);
607 /// }
608 /// # Ok(())
609 /// # }
610 /// ```
611 pub const fn enum_values(&self) -> EnumValues {
612 EnumValues {
613 key: self,
614 index: 0,
615 }
616 }
617
618 /// Delete key. Key names are not case sensitive.
619 /// Cannot delete if it has subkeys.
620 /// Use `delete_subkey_all` for that.
621 ///
622 /// # Examples
623 ///
624 /// ```no_run
625 /// # use std::error::Error;
626 /// # use winreg::RegKey;
627 /// # use winreg::enums::*;
628 /// # fn main() -> Result<(), Box<dyn Error>> {
629 /// RegKey::predef(HKEY_CURRENT_USER)
630 /// .delete_subkey(r"Software\MyProduct\History")?;
631 /// # Ok(())
632 /// # }
633 /// ```
634 pub fn delete_subkey<P: AsRef<OsStr>>(&self, path: P) -> io::Result<()> {
635 self.delete_subkey_with_flags(path, 0)
636 }
637
638 /// Delete key from the desired platform-specific view of the registry.
639 /// Key names are not case sensitive.
640 ///
641 /// # Examples
642 /// ```no_run
643 /// # use std::error::Error;
644 /// # use winreg::RegKey;
645 /// # use winreg::enums::*;
646 /// # fn main() -> Result<(), Box<dyn Error>> {
647 /// // delete the key from the 32-bit registry view
648 /// RegKey::predef(HKEY_LOCAL_MACHINE)
649 /// .delete_subkey_with_flags(r"Software\MyProduct\History", KEY_WOW64_32KEY)?;
650 /// # Ok(())
651 /// # }
652 /// ```
653 pub fn delete_subkey_with_flags<P: AsRef<OsStr>>(
654 &self,
655 path: P,
656 perms: winapi_reg::REGSAM,
657 ) -> io::Result<()> {
658 let c_path = to_utf16(path);
659 match unsafe {
660 winapi_reg::RegDeleteKeyExW(
661 self.hkey,
662 c_path.as_ptr(), // This parameter cannot be NULL.
663 perms,
664 0,
665 )
666 } {
667 0 => Ok(()),
668 err => werr!(err),
669 }
670 }
671
672 /// Part of `transactions` feature.
673 #[cfg(feature = "transactions")]
674 pub fn delete_subkey_transacted<P: AsRef<OsStr>>(
675 &self,
676 path: P,
677 t: &Transaction,
678 ) -> io::Result<()> {
679 self.delete_subkey_transacted_with_flags(path, t, 0)
680 }
681
682 /// Part of `transactions` feature.
683 #[cfg(feature = "transactions")]
684 pub fn delete_subkey_transacted_with_flags<P: AsRef<OsStr>>(
685 &self,
686 path: P,
687 t: &Transaction,
688 perms: winapi_reg::REGSAM,
689 ) -> io::Result<()> {
690 let c_path = to_utf16(path);
691 match unsafe {
692 winapi_reg::RegDeleteKeyTransactedW(
693 self.hkey,
694 c_path.as_ptr(), // This parameter cannot be NULL.
695 perms,
696 0,
697 t.handle,
698 ptr::null_mut(),
699 )
700 } {
701 0 => Ok(()),
702 err => werr!(err),
703 }
704 }
705
706 /// Recursively delete subkey with all its subkeys and values.
707 /// If `path` is an empty string, the subkeys and values of this key are deleted.
708 ///
709 /// # Examples
710 ///
711 /// ```no_run
712 /// # use std::error::Error;
713 /// # use winreg::RegKey;
714 /// # use winreg::enums::*;
715 /// # fn main() -> Result<(), Box<dyn Error>> {
716 /// RegKey::predef(HKEY_CURRENT_USER)
717 /// .delete_subkey_all("Software\\MyProduct")?;
718 /// # Ok(())
719 /// # }
720 /// ```
721 pub fn delete_subkey_all<P: AsRef<OsStr>>(&self, path: P) -> io::Result<()> {
722 let c_path;
723 let path_ptr = if path.as_ref().is_empty() {
724 ptr::null()
725 } else {
726 c_path = to_utf16(path);
727 c_path.as_ptr()
728 };
729 match unsafe {
730 winapi_reg::RegDeleteTreeW(
731 self.hkey,
732 path_ptr, //If this parameter is NULL, the subkeys and values of this key are deleted.
733 ) as DWORD
734 } {
735 0 => Ok(()),
736 err => werr!(err),
737 }
738 }
739
740 /// Get a value from registry and seamlessly convert it to the specified rust type
741 /// with `FromRegValue` implemented (currently `String`, `u32` and `u64`).
742 /// Will get the `Default` value if `name` is an empty string.
743 ///
744 /// # Examples
745 ///
746 /// ```no_run
747 /// # use std::error::Error;
748 /// # use winreg::RegKey;
749 /// # use winreg::enums::*;
750 /// # fn main() -> Result<(), Box<dyn Error>> {
751 /// let hkcu = RegKey::predef(HKEY_CURRENT_USER);
752 /// let settings = hkcu.open_subkey("Software\\MyProduct\\Settings")?;
753 /// let server: String = settings.get_value("server")?;
754 /// let port: u32 = settings.get_value("port")?;
755 /// # Ok(())
756 /// # }
757 /// ```
758 pub fn get_value<T: FromRegValue, N: AsRef<OsStr>>(&self, name: N) -> io::Result<T> {
759 match self.get_raw_value(name) {
760 Ok(ref val) => FromRegValue::from_reg_value(val),
761 Err(err) => Err(err),
762 }
763 }
764
765 /// Get raw bytes from registry value.
766 /// Will get the `Default` value if `name` is an empty string.
767 ///
768 /// # Examples
769 ///
770 /// ```no_run
771 /// # use std::error::Error;
772 /// # use winreg::RegKey;
773 /// # use winreg::enums::*;
774 /// # fn main() -> Result<(), Box<dyn Error>> {
775 /// let hkcu = RegKey::predef(HKEY_CURRENT_USER);
776 /// let settings = hkcu.open_subkey("Software\\MyProduct\\Settings")?;
777 /// let data = settings.get_raw_value("data")?;
778 /// println!("Bytes: {:?}", data.bytes);
779 /// # Ok(())
780 /// # }
781 /// ```
782 pub fn get_raw_value<N: AsRef<OsStr>>(&self, name: N) -> io::Result<RegValue> {
783 let c_name = to_utf16(name);
784 let mut buf_len: DWORD = 2048;
785 let mut buf_type: DWORD = 0;
786 let mut buf: Vec<u8> = Vec::with_capacity(buf_len as usize);
787 loop {
788 match unsafe {
789 winapi_reg::RegQueryValueExW(
790 self.hkey,
791 c_name.as_ptr() as *const u16,
792 ptr::null_mut(),
793 &mut buf_type,
794 buf.as_mut_ptr() as LPBYTE,
795 &mut buf_len,
796 ) as DWORD
797 } {
798 0 => {
799 unsafe {
800 buf.set_len(buf_len as usize);
801 }
802 // minimal check before transmute to RegType
803 if buf_type > winnt::REG_QWORD {
804 return werr!(winerror::ERROR_BAD_FILE_TYPE);
805 }
806 let t: RegType = unsafe { transmute(buf_type as u8) };
807 return Ok(RegValue {
808 bytes: buf,
809 vtype: t,
810 });
811 }
812 winerror::ERROR_MORE_DATA => {
813 buf.reserve(buf_len as usize);
814 }
815 err => return werr!(err),
816 }
817 }
818 }
819
820 /// Seamlessly convert a value from a rust type and write it to the registry value
821 /// with `ToRegValue` trait implemented (currently `String`, `&str`, `u32` and `u64`).
822 /// Will set the `Default` value if `name` is an empty string.
823 ///
824 /// # Examples
825 ///
826 /// ```no_run
827 /// # use std::error::Error;
828 /// # use winreg::RegKey;
829 /// # use winreg::enums::*;
830 /// # fn main() -> Result<(), Box<dyn Error>> {
831 /// let hkcu = RegKey::predef(HKEY_CURRENT_USER);
832 /// let (settings, disp) = hkcu.create_subkey("Software\\MyProduct\\Settings")?;
833 /// settings.set_value("server", &"www.example.com")?;
834 /// settings.set_value("port", &8080u32)?;
835 /// # Ok(())
836 /// # }
837 /// ```
838 pub fn set_value<T: ToRegValue, N: AsRef<OsStr>>(&self, name: N, value: &T) -> io::Result<()> {
839 self.set_raw_value(name, &value.to_reg_value())
840 }
841
842 /// Write raw bytes from `RegValue` struct to a registry value.
843 /// Will set the `Default` value if `name` is an empty string.
844 ///
845 /// # Examples
846 ///
847 /// ```no_run
848 /// # use std::error::Error;
849 /// use winreg::{RegKey, RegValue};
850 /// use winreg::enums::*;
851 /// # fn main() -> Result<(), Box<dyn Error>> {
852 /// let hkcu = RegKey::predef(HKEY_CURRENT_USER);
853 /// let settings = hkcu.open_subkey("Software\\MyProduct\\Settings")?;
854 /// let bytes: Vec<u8> = vec![1, 2, 3, 5, 8, 13, 21, 34, 55, 89];
855 /// let data = RegValue{ vtype: REG_BINARY, bytes: bytes};
856 /// settings.set_raw_value("data", &data)?;
857 /// println!("Bytes: {:?}", data.bytes);
858 /// # Ok(())
859 /// # }
860 /// ```
861 pub fn set_raw_value<N: AsRef<OsStr>>(&self, name: N, value: &RegValue) -> io::Result<()> {
862 let c_name = to_utf16(name);
863 let t = value.vtype.clone() as DWORD;
864 match unsafe {
865 winapi_reg::RegSetValueExW(
866 self.hkey,
867 c_name.as_ptr(),
868 0,
869 t,
870 value.bytes.as_ptr() as *const BYTE,
871 value.bytes.len() as u32,
872 ) as DWORD
873 } {
874 0 => Ok(()),
875 err => werr!(err),
876 }
877 }
878
879 /// Delete specified value from registry.
880 /// Will delete the `Default` value if `name` is an empty string.
881 ///
882 /// # Examples
883 ///
884 /// ```no_run
885 /// # use std::error::Error;
886 /// # use winreg::RegKey;
887 /// # use winreg::enums::*;
888 /// # fn main() -> Result<(), Box<dyn Error>> {
889 /// let hkcu = RegKey::predef(HKEY_CURRENT_USER);
890 /// let settings = hkcu.open_subkey("Software\\MyProduct\\Settings")?;
891 /// settings.delete_value("data")?;
892 /// # Ok(())
893 /// # }
894 /// ```
895 pub fn delete_value<N: AsRef<OsStr>>(&self, name: N) -> io::Result<()> {
896 let c_name = to_utf16(name);
897 match unsafe { winapi_reg::RegDeleteValueW(self.hkey, c_name.as_ptr()) as DWORD } {
898 0 => Ok(()),
899 err => werr!(err),
900 }
901 }
902
903 /// Save `Encodable` type to a registry key.
904 /// Part of `serialization-serde` feature.
905 ///
906 /// # Examples
907 ///
908 /// ```no_run
909 /// # use std::error::Error;
910 /// #[macro_use]
911 /// extern crate serde_derive;
912 /// extern crate winreg;
913 /// use winreg::RegKey;
914 /// use winreg::enums::*;
915 ///
916 /// #[derive(Serialize)]
917 /// struct Rectangle{
918 /// x: u32,
919 /// y: u32,
920 /// w: u32,
921 /// h: u32,
922 /// }
923 ///
924 /// #[derive(Serialize)]
925 /// struct Settings{
926 /// current_dir: String,
927 /// window_pos: Rectangle,
928 /// show_in_tray: bool,
929 /// }
930 ///
931 /// # fn main() -> Result<(), Box<dyn Error>> {
932 /// let s: Settings = Settings{
933 /// current_dir: "C:\\".to_owned(),
934 /// window_pos: Rectangle{ x:200, y: 100, w: 800, h: 500 },
935 /// show_in_tray: false,
936 /// };
937 /// let s_key = RegKey::predef(HKEY_CURRENT_USER)
938 /// .open_subkey("Software\\MyProduct\\Settings")?;
939 /// s_key.encode(&s)?;
940 /// # Ok(())
941 /// # }
942 /// ```
943 #[cfg(feature = "serialization-serde")]
944 pub fn encode<T: serde::Serialize>(&self, value: &T) -> encoder::EncodeResult<()> {
945 let mut encoder = encoder::Encoder::from_key(self)?;
946 value.serialize(&mut encoder)?;
947 encoder.commit()
948 }
949
950 /// Load `Decodable` type from a registry key.
951 /// Part of `serialization-serde` feature.
952 ///
953 /// # Examples
954 ///
955 /// ```no_run
956 /// # use std::error::Error;
957 /// #[macro_use]
958 /// extern crate serde_derive;
959 /// extern crate winreg;
960 /// use winreg::RegKey;
961 /// use winreg::enums::*;
962 ///
963 /// #[derive(Deserialize)]
964 /// struct Rectangle{
965 /// x: u32,
966 /// y: u32,
967 /// w: u32,
968 /// h: u32,
969 /// }
970 ///
971 /// #[derive(Deserialize)]
972 /// struct Settings{
973 /// current_dir: String,
974 /// window_pos: Rectangle,
975 /// show_in_tray: bool,
976 /// }
977 ///
978 /// # fn main() -> Result<(), Box<dyn Error>> {
979 /// let s_key = RegKey::predef(HKEY_CURRENT_USER)
980 /// .open_subkey("Software\\MyProduct\\Settings")?;
981 /// let s: Settings = s_key.decode()?;
982 /// # Ok(())
983 /// # }
984 /// ```
985 #[cfg(feature = "serialization-serde")]
986 pub fn decode<'de, T: serde::Deserialize<'de>>(&self) -> decoder::DecodeResult<T> {
987 let mut decoder = decoder::Decoder::from_key(self)?;
988 T::deserialize(&mut decoder)
989 }
990
991 fn close_(&mut self) -> io::Result<()> {
992 // don't try to close predefined keys
993 if self.hkey >= enums::HKEY_CLASSES_ROOT {
994 return Ok(());
995 };
996 match unsafe { winapi_reg::RegCloseKey(self.hkey) as DWORD } {
997 0 => Ok(()),
998 err => werr!(err),
999 }
1000 }
1001
1002 fn enum_key(&self, index: DWORD) -> Option<io::Result<String>> {
1003 let mut name_len = 2048;
1004 #[allow(clippy::unnecessary_cast)]
1005 let mut name = [0 as WCHAR; 2048];
1006 match unsafe {
1007 winapi_reg::RegEnumKeyExW(
1008 self.hkey,
1009 index,
1010 name.as_mut_ptr(),
1011 &mut name_len,
1012 ptr::null_mut(), // reserved
1013 ptr::null_mut(), // lpClass: LPWSTR,
1014 ptr::null_mut(), // lpcClass: LPDWORD,
1015 ptr::null_mut(), // lpftLastWriteTime: PFILETIME,
1016 ) as DWORD
1017 } {
1018 0 => match String::from_utf16(&name[..name_len as usize]) {
1019 Ok(s) => Some(Ok(s)),
1020 Err(_) => Some(werr!(winerror::ERROR_INVALID_BLOCK)),
1021 },
1022 winerror::ERROR_NO_MORE_ITEMS => None,
1023 err => Some(werr!(err)),
1024 }
1025 }
1026
1027 fn enum_value(&self, index: DWORD) -> Option<io::Result<(String, RegValue)>> {
1028 let mut name_len = 2048;
1029 #[allow(clippy::unnecessary_cast)]
1030 let mut name = [0 as WCHAR; 2048];
1031
1032 let mut buf_len: DWORD = 2048;
1033 let mut buf_type: DWORD = 0;
1034 let mut buf: Vec<u8> = Vec::with_capacity(buf_len as usize);
1035 loop {
1036 match unsafe {
1037 winapi_reg::RegEnumValueW(
1038 self.hkey,
1039 index,
1040 name.as_mut_ptr(),
1041 &mut name_len,
1042 ptr::null_mut(), // reserved
1043 &mut buf_type,
1044 buf.as_mut_ptr() as LPBYTE,
1045 &mut buf_len,
1046 ) as DWORD
1047 } {
1048 0 => {
1049 let name = match String::from_utf16(&name[..name_len as usize]) {
1050 Ok(s) => s,
1051 Err(_) => return Some(werr!(winerror::ERROR_INVALID_DATA)),
1052 };
1053 unsafe {
1054 buf.set_len(buf_len as usize);
1055 }
1056 // minimal check before transmute to RegType
1057 if buf_type > winnt::REG_QWORD {
1058 return Some(werr!(winerror::ERROR_BAD_FILE_TYPE));
1059 }
1060 let t: RegType = unsafe { transmute(buf_type as u8) };
1061 let value = RegValue {
1062 bytes: buf,
1063 vtype: t,
1064 };
1065 return Some(Ok((name, value)));
1066 }
1067 winerror::ERROR_MORE_DATA => {
1068 name_len += 1; //for NULL char
1069 buf.reserve(buf_len as usize);
1070 }
1071 winerror::ERROR_NO_MORE_ITEMS => return None,
1072 err => return Some(werr!(err)),
1073 }
1074 }
1075 }
1076 }
1077
1078 impl Drop for RegKey {
1079 fn drop(&mut self) {
1080 self.close_().unwrap_or(());
1081 }
1082 }
1083
1084 /// Iterator over subkeys names
1085 pub struct EnumKeys<'key> {
1086 key: &'key RegKey,
1087 index: DWORD,
1088 }
1089
1090 impl<'key> Iterator for EnumKeys<'key> {
1091 type Item = io::Result<String>;
1092
1093 fn next(&mut self) -> Option<io::Result<String>> {
1094 match self.key.enum_key(self.index) {
1095 v @ Some(_) => {
1096 self.index += 1;
1097 v
1098 }
1099 e @ None => e,
1100 }
1101 }
1102
1103 fn nth(&mut self, n: usize) -> Option<Self::Item> {
1104 self.index += n as DWORD;
1105 self.next()
1106 }
1107 }
1108
1109 /// Iterator over values
1110 pub struct EnumValues<'key> {
1111 key: &'key RegKey,
1112 index: DWORD,
1113 }
1114
1115 impl<'key> Iterator for EnumValues<'key> {
1116 type Item = io::Result<(String, RegValue)>;
1117
1118 fn next(&mut self) -> Option<io::Result<(String, RegValue)>> {
1119 match self.key.enum_value(self.index) {
1120 v @ Some(_) => {
1121 self.index += 1;
1122 v
1123 }
1124 e @ None => e,
1125 }
1126 }
1127
1128 fn nth(&mut self, n: usize) -> Option<Self::Item> {
1129 self.index += n as DWORD;
1130 self.next()
1131 }
1132 }
1133
1134 fn to_utf16<P: AsRef<OsStr>>(s: P) -> Vec<u16> {
1135 s.as_ref()
1136 .encode_wide()
1137 .chain(Some(0).into_iter())
1138 .collect()
1139 }
1140
1141 fn v16_to_v8(v: &[u16]) -> Vec<u8> {
1142 unsafe { slice::from_raw_parts(v.as_ptr() as *const u8, v.len() * 2).to_vec() }
1143 }