android_system_properties/lib.rs
1//! A thin rust wrapper for Android system properties.
2//!
3//! This crate is similar to the `android-properties` crate with the exception that
4//! the necessary Android libc symbols are loaded dynamically instead of linked
5//! statically. In practice this means that the same binary will work with old and
6//! new versions of Android, even though the API for reading system properties changed
7//! around Android L.
8//!
9//! ## Example
10//!
11//! ```rust
12//! use android_system_properties::AndroidSystemProperties;
13//!
14//! let properties = AndroidSystemProperties::new();
15//!
16//! if let Some(value) = properties.get("persist.sys.timezone") {
17//! println!("{}", value);
18//! }
19//! ```
20//!
21//! ## Listing and setting properties
22//!
23//! For the sake of simplicity this crate currently only contains what's needed by wgpu.
24//! The implementations for listing and setting properties can be added back if anyone needs
25//! them (let me know by filing an issue).
26//!
27//! ## License
28//!
29//! Licensed under either of
30//!
31//! * Apache License, Version 2.0 ([LICENSE-APACHE] or <http://www.apache.org/licenses/LICENSE-2.0>)
32//! * MIT license ([LICENSE-MIT] or <http://opensource.org/licenses/MIT>)
33//!
34//! at your option.
35//!
36//! [LICENSE-APACHE]: https://github.com/nical/android_system_properties/blob/804681c5c1c93d4fab29c1a2f47b7d808dc70fd3/LICENSE-APACHE
37//! [LICENSE-MIT]: https://github.com/nical/android_system_properties/blob/804681c5c1c93d4fab29c1a2f47b7d808dc70fd3/LICENSE-MIT
38
39use std::{
40 ffi::{CStr, CString},
41 os::raw::{c_char, c_int, c_void},
42};
43
44#[cfg(target_os = "android")]
45use std::mem;
46
47unsafe fn property_callback(payload: *mut String, _name: *const c_char, value: *const c_char, _serial: u32) {
48 let cvalue = CStr::from_ptr(value);
49 (*payload) = cvalue.to_str().unwrap().to_string();
50}
51
52type Callback = unsafe fn(*mut String, *const c_char, *const c_char, u32);
53
54type SystemPropertyGetFn = unsafe extern "C" fn(*const c_char, *mut c_char) -> c_int;
55type SystemPropertyFindFn = unsafe extern "C" fn(*const c_char) -> *const c_void;
56type SystemPropertyReadCallbackFn = unsafe extern "C" fn(*const c_void, Callback, *mut String) -> *const c_void;
57
58#[derive(Debug)]
59/// An object that can retrieve android system properties.
60///
61/// ## Example
62///
63/// ```
64/// use android_system_properties::AndroidSystemProperties;
65///
66/// let properties = AndroidSystemProperties::new();
67///
68/// if let Some(value) = properties.get("persist.sys.timezone") {
69/// println!("{}", value);
70/// }
71/// ```
72pub struct AndroidSystemProperties {
73 libc_so: *mut c_void,
74 get_fn: Option<SystemPropertyGetFn>,
75 find_fn: Option<SystemPropertyFindFn>,
76 read_callback_fn: Option<SystemPropertyReadCallbackFn>,
77}
78
79unsafe impl Send for AndroidSystemProperties {}
80unsafe impl Sync for AndroidSystemProperties {}
81
82impl AndroidSystemProperties {
83 #[cfg(not(target_os = "android"))]
84 /// Create an entry point for accessing Android properties.
85 pub fn new() -> Self {
86 AndroidSystemProperties {
87 libc_so: std::ptr::null_mut(),
88 find_fn: None,
89 read_callback_fn: None,
90 get_fn: None,
91 }
92 }
93
94 #[cfg(target_os = "android")]
95 /// Create an entry point for accessing Android properties.
96 pub fn new() -> Self {
97 let libc_so = unsafe { libc::dlopen(b"libc.so\0".as_ptr().cast(), libc::RTLD_NOLOAD) };
98
99 let mut properties = AndroidSystemProperties {
100 libc_so,
101 find_fn: None,
102 read_callback_fn: None,
103 get_fn: None,
104 };
105
106 if libc_so.is_null() {
107 return properties;
108 }
109
110
111 unsafe fn load_fn(libc_so: *mut c_void, name: &[u8]) -> Option<*const c_void> {
112 let fn_ptr = libc::dlsym(libc_so, name.as_ptr().cast());
113
114 if fn_ptr.is_null() {
115 return None;
116 }
117
118 Some(fn_ptr)
119 }
120
121 unsafe {
122 properties.read_callback_fn = load_fn(libc_so, b"__system_property_read_callback\0")
123 .map(|raw| mem::transmute::<*const c_void, SystemPropertyReadCallbackFn>(raw));
124
125 properties.find_fn = load_fn(libc_so, b"__system_property_find\0")
126 .map(|raw| mem::transmute::<*const c_void, SystemPropertyFindFn>(raw));
127
128 // Fallback for old versions of Android.
129 if properties.read_callback_fn.is_none() || properties.find_fn.is_none() {
130 properties.get_fn = load_fn(libc_so, b"__system_property_get\0")
131 .map(|raw| mem::transmute::<*const c_void, SystemPropertyGetFn>(raw));
132 }
133 }
134
135 properties
136 }
137
138 /// Retrieve a system property.
139 ///
140 /// Returns None if the operation fails.
141 ///
142 /// # Example
143 ///
144 /// ```
145 /// # use android_system_properties::AndroidSystemProperties;
146 /// let properties = AndroidSystemProperties::new();
147 ///
148 /// if let Some(value) = properties.get("persist.sys.timezone") {
149 /// println!("{}", value);
150 /// }
151 /// ```
152 pub fn get(&self, name: &str) -> Option<String> {
153 let cname = CString::new(name).ok()?;
154 self.get_from_cstr(&cname)
155 }
156
157 /// Retrieve a system property using a [`CStr`] key.
158 ///
159 /// Returns None if the operation fails.
160 ///
161 /// # Example
162 ///
163 /// ```
164 /// # use android_system_properties::AndroidSystemProperties;
165 /// # use std::ffi::CStr;
166 /// let properties = AndroidSystemProperties::new();
167 ///
168 /// let key = unsafe { CStr::from_bytes_with_nul_unchecked(b"persist.sys.timezone\0") };
169 /// if let Some(value) = properties.get_from_cstr(key) {
170 /// println!("{}", value);
171 /// }
172 /// ```
173 pub fn get_from_cstr(&self, cname: &std::ffi::CStr) -> Option<String> {
174 // If available, use the recommended approach to accessing properties (Android L and onward).
175 if let (Some(find_fn), Some(read_callback_fn)) = (self.find_fn, self.read_callback_fn) {
176 let info = unsafe { (find_fn)(cname.as_ptr()) };
177
178 if info.is_null() {
179 return None;
180 }
181
182 let mut result = String::new();
183
184 unsafe {
185 (read_callback_fn)(info, property_callback, &mut result);
186 }
187
188 return Some(result);
189 }
190
191 // Fall back to the older approach.
192 if let Some(get_fn) = self.get_fn {
193 // The constant is PROP_VALUE_MAX in Android's libc/include/sys/system_properties.h
194 const PROPERTY_VALUE_MAX: usize = 92;
195 let mut buffer: Vec<u8> = Vec::with_capacity(PROPERTY_VALUE_MAX);
196 let raw = buffer.as_mut_ptr() as *mut c_char;
197
198 let len = unsafe { (get_fn)(cname.as_ptr(), raw) };
199
200 if len > 0 {
201 assert!(len as usize <= buffer.capacity());
202 unsafe { buffer.set_len(len as usize); }
203 String::from_utf8(buffer).ok()
204 } else {
205 None
206 }
207 } else {
208 None
209 }
210 }
211}
212
213impl Drop for AndroidSystemProperties {
214 fn drop(&mut self) {
215 if !self.libc_so.is_null() {
216 unsafe {
217 libc::dlclose(self.libc_so);
218 }
219 }
220 }
221}