blob: b87d7e89c746b3c551e28302c15761bd94324026 [file] [log] [blame]
Narayan Kamathc9ae21a2014-02-19 17:59:05 +00001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in
12 * the documentation and/or other materials provided with the
13 * distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
18 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
19 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
21 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
22 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
23 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
24 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
25 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 * SUCH DAMAGE.
27 */
Elliott Hughesf8562c52017-01-26 16:48:57 -080028
Tom Cherry49a309f2015-09-23 16:09:47 -070029#include <ctype.h>
Narayan Kamathc9ae21a2014-02-19 17:59:05 +000030#include <errno.h>
Narayan Kamathc9ae21a2014-02-19 17:59:05 +000031#include <fcntl.h>
Tom Cherry49a309f2015-09-23 16:09:47 -070032#include <poll.h>
33#include <stdatomic.h>
Tom Cherry49a309f2015-09-23 16:09:47 -070034#include <stddef.h>
35#include <stdint.h>
Tom Cherry49a309f2015-09-23 16:09:47 -070036#include <stdlib.h>
Narayan Kamathc9ae21a2014-02-19 17:59:05 +000037#include <string.h>
Tom Cherry49a309f2015-09-23 16:09:47 -070038#include <unistd.h>
39#include <new>
Narayan Kamathc9ae21a2014-02-19 17:59:05 +000040
Tom Cherry49a309f2015-09-23 16:09:47 -070041#include <linux/xattr.h>
42#include <netinet/in.h>
Narayan Kamathc9ae21a2014-02-19 17:59:05 +000043#include <sys/mman.h>
Narayan Kamathc9ae21a2014-02-19 17:59:05 +000044#include <sys/select.h>
Tom Cherry49a309f2015-09-23 16:09:47 -070045#include <sys/socket.h>
Narayan Kamathc9ae21a2014-02-19 17:59:05 +000046#include <sys/stat.h>
47#include <sys/types.h>
Dimitry Ivanov6391e1a2017-02-23 17:57:14 -080048#include <sys/uio.h>
Tom Cherry49a309f2015-09-23 16:09:47 -070049#include <sys/un.h>
50#include <sys/xattr.h>
Narayan Kamathc9ae21a2014-02-19 17:59:05 +000051
52#define _REALLY_INCLUDE_SYS__SYSTEM_PROPERTIES_H_
53#include <sys/_system_properties.h>
54#include <sys/system_properties.h>
55
Christopher Ferris7a3681e2017-04-24 17:48:32 -070056#include <async_safe/log.h>
57
Elliott Hughes7ade61c2017-04-11 13:38:36 -070058#include "private/ErrnoRestorer.h"
Elliott Hughesd5ed63a2014-05-21 18:27:40 -070059#include "private/bionic_futex.h"
Tom Cherry49a309f2015-09-23 16:09:47 -070060#include "private/bionic_lock.h"
Elliott Hughes8eac9af2014-05-09 19:12:08 -070061#include "private/bionic_macros.h"
Dimitry Ivanov581b9f62017-01-09 11:05:52 -080062#include "private/bionic_sdk_version.h"
Narayan Kamathc9ae21a2014-02-19 17:59:05 +000063
Elliott Hughesf8562c52017-01-26 16:48:57 -080064static constexpr int PROP_FILENAME_MAX = 1024;
65
66static constexpr uint32_t PROP_AREA_MAGIC = 0x504f5250;
67static constexpr uint32_t PROP_AREA_VERSION = 0xfc6ed0ab;
68
69static constexpr size_t PA_SIZE = 128 * 1024;
70
Elliott Hughes9160ed92017-01-30 17:54:57 -080071#define SERIAL_DIRTY(serial) ((serial)&1)
Dimitry Ivanov16b2a4d2017-01-24 20:43:29 +000072#define SERIAL_VALUE_LEN(serial) ((serial) >> 24)
Dimitry Ivanov489f58b2017-01-24 18:39:04 +000073
Tom Cherry8a311632017-10-09 13:49:17 -070074constexpr static const char kLongLegacyError[] = "Must use __system_property_read_callback() to read";
75
76// The error message fits in part of a union with the previous 92 char property value so there must
77// be room left over after the error message for the offset to the new longer property value and
78// future expansion fields if needed.
79// Note that this value cannot ever increase. The offset to the new longer property value appears
80// immediately after it, so an increase of this size will break compatibility.
81constexpr size_t kLongLegacyErrorBufferSize = 56;
82static_assert(sizeof(kLongLegacyError) < kLongLegacyErrorBufferSize,
83 "Error message for long properties read by legacy libc must fit within 56 chars");
84
Dimitry Ivanov16b2a4d2017-01-24 20:43:29 +000085static const char property_service_socket[] = "/dev/socket/" PROP_SERVICE_NAME;
86static const char* kServiceVersionPropertyName = "ro.property_service.version";
Narayan Kamathc9ae21a2014-02-19 17:59:05 +000087
Tom Cherry8a311632017-10-09 13:49:17 -070088// The C11 standard doesn't allow atomic loads from const fields,
89// though C++11 does. Fudge it until standards get straightened out.
90static inline uint_least32_t load_const_atomic(const atomic_uint_least32_t* s, memory_order mo) {
91 atomic_uint_least32_t* non_const_s = const_cast<atomic_uint_least32_t*>(s);
92 return atomic_load_explicit(non_const_s, mo);
93}
94
Narayan Kamathc9ae21a2014-02-19 17:59:05 +000095/*
96 * Properties are stored in a hybrid trie/binary tree structure.
97 * Each property's name is delimited at '.' characters, and the tokens are put
98 * into a trie structure. Siblings at each level of the trie are stored in a
99 * binary tree. For instance, "ro.secure"="1" could be stored as follows:
100 *
101 * +-----+ children +----+ children +--------+
102 * | |-------------->| ro |-------------->| secure |
103 * +-----+ +----+ +--------+
104 * / \ / |
105 * left / \ right left / | prop +===========+
106 * v v v +-------->| ro.secure |
107 * +-----+ +-----+ +-----+ +-----------+
108 * | net | | sys | | com | | 1 |
109 * +-----+ +-----+ +-----+ +===========+
110 */
111
112// Represents a node in the trie.
113struct prop_bt {
Elliott Hughes9160ed92017-01-30 17:54:57 -0800114 uint32_t namelen;
Narayan Kamathc9ae21a2014-02-19 17:59:05 +0000115
Elliott Hughes9160ed92017-01-30 17:54:57 -0800116 // The property trie is updated only by the init process (single threaded) which provides
117 // property service. And it can be read by multiple threads at the same time.
118 // As the property trie is not protected by locks, we use atomic_uint_least32_t types for the
119 // left, right, children "pointers" in the trie node. To make sure readers who see the
120 // change of "pointers" can also notice the change of prop_bt structure contents pointed by
121 // the "pointers", we always use release-consume ordering pair when accessing these "pointers".
Yabin Cuib8ce4742015-02-10 21:35:56 -0800122
Elliott Hughes9160ed92017-01-30 17:54:57 -0800123 // prop "points" to prop_info structure if there is a propery associated with the trie node.
124 // Its situation is similar to the left, right, children "pointers". So we use
125 // atomic_uint_least32_t and release-consume ordering to protect it as well.
Yabin Cuib8ce4742015-02-10 21:35:56 -0800126
Elliott Hughes9160ed92017-01-30 17:54:57 -0800127 // We should also avoid rereading these fields redundantly, since not
128 // all processor implementations ensure that multiple loads from the
129 // same field are carried out in the right order.
130 atomic_uint_least32_t prop;
Narayan Kamathc9ae21a2014-02-19 17:59:05 +0000131
Elliott Hughes9160ed92017-01-30 17:54:57 -0800132 atomic_uint_least32_t left;
133 atomic_uint_least32_t right;
Narayan Kamathc9ae21a2014-02-19 17:59:05 +0000134
Elliott Hughes9160ed92017-01-30 17:54:57 -0800135 atomic_uint_least32_t children;
Narayan Kamathc9ae21a2014-02-19 17:59:05 +0000136
Elliott Hughes9160ed92017-01-30 17:54:57 -0800137 char name[0];
Narayan Kamathc9ae21a2014-02-19 17:59:05 +0000138
Elliott Hughes9160ed92017-01-30 17:54:57 -0800139 prop_bt(const char* name, const uint32_t name_length) {
140 this->namelen = name_length;
141 memcpy(this->name, name, name_length);
142 this->name[name_length] = '\0';
143 }
Narayan Kamathc9ae21a2014-02-19 17:59:05 +0000144
Elliott Hughes9160ed92017-01-30 17:54:57 -0800145 private:
146 DISALLOW_COPY_AND_ASSIGN(prop_bt);
Narayan Kamathc9ae21a2014-02-19 17:59:05 +0000147};
148
Tom Cherry926ebe12015-09-23 15:34:40 -0700149class prop_area {
Elliott Hughes9160ed92017-01-30 17:54:57 -0800150 public:
151 prop_area(const uint32_t magic, const uint32_t version) : magic_(magic), version_(version) {
152 atomic_init(&serial_, 0);
153 memset(reserved_, 0, sizeof(reserved_));
154 // Allocate enough space for the root node.
155 bytes_used_ = sizeof(prop_bt);
156 }
Narayan Kamathc9ae21a2014-02-19 17:59:05 +0000157
Elliott Hughes9160ed92017-01-30 17:54:57 -0800158 const prop_info* find(const char* name);
159 bool add(const char* name, unsigned int namelen, const char* value, unsigned int valuelen);
Narayan Kamathc9ae21a2014-02-19 17:59:05 +0000160
Elliott Hughes9160ed92017-01-30 17:54:57 -0800161 bool foreach (void (*propfn)(const prop_info* pi, void* cookie), void* cookie);
Tom Cherry926ebe12015-09-23 15:34:40 -0700162
Elliott Hughes9160ed92017-01-30 17:54:57 -0800163 atomic_uint_least32_t* serial() {
164 return &serial_;
165 }
166 uint32_t magic() const {
167 return magic_;
168 }
169 uint32_t version() const {
170 return version_;
171 }
Tom Cherry926ebe12015-09-23 15:34:40 -0700172
Elliott Hughes9160ed92017-01-30 17:54:57 -0800173 private:
174 void* allocate_obj(const size_t size, uint_least32_t* const off);
175 prop_bt* new_prop_bt(const char* name, uint32_t namelen, uint_least32_t* const off);
176 prop_info* new_prop_info(const char* name, uint32_t namelen, const char* value, uint32_t valuelen,
177 uint_least32_t* const off);
178 void* to_prop_obj(uint_least32_t off);
179 prop_bt* to_prop_bt(atomic_uint_least32_t* off_p);
180 prop_info* to_prop_info(atomic_uint_least32_t* off_p);
Tom Cherry926ebe12015-09-23 15:34:40 -0700181
Elliott Hughes9160ed92017-01-30 17:54:57 -0800182 prop_bt* root_node();
Tom Cherry926ebe12015-09-23 15:34:40 -0700183
Elliott Hughes9160ed92017-01-30 17:54:57 -0800184 prop_bt* find_prop_bt(prop_bt* const bt, const char* name, uint32_t namelen, bool alloc_if_needed);
Tom Cherry926ebe12015-09-23 15:34:40 -0700185
Elliott Hughes9160ed92017-01-30 17:54:57 -0800186 const prop_info* find_property(prop_bt* const trie, const char* name, uint32_t namelen,
187 const char* value, uint32_t valuelen, bool alloc_if_needed);
Tom Cherry926ebe12015-09-23 15:34:40 -0700188
Elliott Hughes9160ed92017-01-30 17:54:57 -0800189 bool foreach_property(prop_bt* const trie, void (*propfn)(const prop_info* pi, void* cookie),
190 void* cookie);
Tom Cherry926ebe12015-09-23 15:34:40 -0700191
Elliott Hughes9160ed92017-01-30 17:54:57 -0800192 uint32_t bytes_used_;
193 atomic_uint_least32_t serial_;
194 uint32_t magic_;
195 uint32_t version_;
196 uint32_t reserved_[28];
197 char data_[0];
Tom Cherry926ebe12015-09-23 15:34:40 -0700198
Elliott Hughes9160ed92017-01-30 17:54:57 -0800199 DISALLOW_COPY_AND_ASSIGN(prop_area);
Narayan Kamathc9ae21a2014-02-19 17:59:05 +0000200};
201
202struct prop_info {
Tom Cherry8a311632017-10-09 13:49:17 -0700203 // Read only properties will not set anything but the bottom most bit of serial and the top byte.
204 // We borrow the 2nd from the top byte for extra flags, and use the bottom most bit of that for
205 // our first user, kLongFlag.
206 constexpr static uint32_t kLongFlag = 1 << 16;
Elliott Hughes9160ed92017-01-30 17:54:57 -0800207 atomic_uint_least32_t serial;
208 // we need to keep this buffer around because the property
209 // value can be modified whereas name is constant.
Tom Cherry8a311632017-10-09 13:49:17 -0700210 union {
211 char value[PROP_VALUE_MAX];
212 struct {
213 char error_message[kLongLegacyErrorBufferSize];
214 uint32_t offset;
215 } long_property;
216 };
Elliott Hughes9160ed92017-01-30 17:54:57 -0800217 char name[0];
Narayan Kamathc9ae21a2014-02-19 17:59:05 +0000218
Tom Cherry8a311632017-10-09 13:49:17 -0700219 bool is_long() const {
220 return (load_const_atomic(&serial, memory_order_relaxed) & kLongFlag) != 0;
221 }
222
223 const char* long_value() const {
224 // We can't store pointers here since this is shared memory that will have different absolute
225 // pointers in different processes. We don't have data_ from prop_area, but since we know
226 // `this` is data_ + some offset and long_value is data_ + some other offset, we calculate the
227 // offset from `this` to long_value and store it as long_property.offset.
228 return reinterpret_cast<const char*>(this) + long_property.offset;
229 }
230
Elliott Hughes9160ed92017-01-30 17:54:57 -0800231 prop_info(const char* name, uint32_t namelen, const char* value, uint32_t valuelen) {
232 memcpy(this->name, name, namelen);
233 this->name[namelen] = '\0';
234 atomic_init(&this->serial, valuelen << 24);
235 memcpy(this->value, value, valuelen);
236 this->value[valuelen] = '\0';
237 }
238
Tom Cherry8a311632017-10-09 13:49:17 -0700239 prop_info(const char* name, uint32_t namelen, uint32_t long_offset) {
240 memcpy(this->name, name, namelen);
241 this->name[namelen] = '\0';
242
243 auto error_value_len = sizeof(kLongLegacyError) - 1;
244 atomic_init(&this->serial, error_value_len << 24 | kLongFlag);
245 memcpy(this->long_property.error_message, kLongLegacyError, sizeof(kLongLegacyError));
246
247 this->long_property.offset = long_offset;
248 }
249
Elliott Hughes9160ed92017-01-30 17:54:57 -0800250 private:
251 DISALLOW_IMPLICIT_CONSTRUCTORS(prop_info);
Narayan Kamathc9ae21a2014-02-19 17:59:05 +0000252};
253
Tom Cherry8a311632017-10-09 13:49:17 -0700254static_assert(sizeof(prop_info) == 96, "size of struct prop_info must be 96 bytes");
255
Elliott Hughesf8562c52017-01-26 16:48:57 -0800256// This is public because it was exposed in the NDK. As of 2017-01, ~60 apps reference this symbol.
Elliott Hughesf8562c52017-01-26 16:48:57 -0800257prop_area* __system_property_area__ = nullptr;
258
Tom Cherry49a309f2015-09-23 16:09:47 -0700259static char property_filename[PROP_FILENAME_MAX] = PROP_FILENAME;
Narayan Kamathc9ae21a2014-02-19 17:59:05 +0000260static size_t pa_data_size;
261static size_t pa_size;
Tom Cherryb4171692015-12-09 15:48:15 -0800262static bool initialized = false;
Narayan Kamathc9ae21a2014-02-19 17:59:05 +0000263
Tom Cherry49a309f2015-09-23 16:09:47 -0700264static prop_area* map_prop_area_rw(const char* filename, const char* context,
265 bool* fsetxattr_failed) {
Elliott Hughes9160ed92017-01-30 17:54:57 -0800266 /* dev is a tmpfs that we can use to carve a shared workspace
267 * out of, so let's do that...
268 */
269 const int fd = open(filename, O_RDWR | O_CREAT | O_NOFOLLOW | O_CLOEXEC | O_EXCL, 0444);
Narayan Kamathc9ae21a2014-02-19 17:59:05 +0000270
Elliott Hughes9160ed92017-01-30 17:54:57 -0800271 if (fd < 0) {
272 if (errno == EACCES) {
273 /* for consistency with the case where the process has already
274 * mapped the page in and segfaults when trying to write to it
275 */
276 abort();
Tom Cherry49a309f2015-09-23 16:09:47 -0700277 }
Elliott Hughes9160ed92017-01-30 17:54:57 -0800278 return nullptr;
279 }
Tom Cherry49a309f2015-09-23 16:09:47 -0700280
Elliott Hughes9160ed92017-01-30 17:54:57 -0800281 if (context) {
282 if (fsetxattr(fd, XATTR_NAME_SELINUX, context, strlen(context) + 1, 0) != 0) {
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700283 async_safe_format_log(ANDROID_LOG_ERROR, "libc",
284 "fsetxattr failed to set context (%s) for \"%s\"", context, filename);
Elliott Hughes9160ed92017-01-30 17:54:57 -0800285 /*
286 * fsetxattr() will fail during system properties tests due to selinux policy.
287 * We do not want to create a custom policy for the tester, so we will continue in
288 * this function but set a flag that an error has occurred.
289 * Init, which is the only daemon that should ever call this function will abort
290 * when this error occurs.
291 * Otherwise, the tester will ignore it and continue, albeit without any selinux
292 * property separation.
293 */
294 if (fsetxattr_failed) {
295 *fsetxattr_failed = true;
296 }
Narayan Kamathc9ae21a2014-02-19 17:59:05 +0000297 }
Elliott Hughes9160ed92017-01-30 17:54:57 -0800298 }
Narayan Kamathc9ae21a2014-02-19 17:59:05 +0000299
Elliott Hughes9160ed92017-01-30 17:54:57 -0800300 if (ftruncate(fd, PA_SIZE) < 0) {
Narayan Kamathc9ae21a2014-02-19 17:59:05 +0000301 close(fd);
Elliott Hughes9160ed92017-01-30 17:54:57 -0800302 return nullptr;
303 }
304
305 pa_size = PA_SIZE;
306 pa_data_size = pa_size - sizeof(prop_area);
307
Elliott Hughes8e7396c2017-01-31 08:24:43 -0800308 void* const memory_area = mmap(nullptr, pa_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
Elliott Hughes9160ed92017-01-30 17:54:57 -0800309 if (memory_area == MAP_FAILED) {
310 close(fd);
311 return nullptr;
312 }
313
314 prop_area* pa = new (memory_area) prop_area(PROP_AREA_MAGIC, PROP_AREA_VERSION);
315
316 close(fd);
317 return pa;
Narayan Kamathc9ae21a2014-02-19 17:59:05 +0000318}
319
Tom Cherry49a309f2015-09-23 16:09:47 -0700320static prop_area* map_fd_ro(const int fd) {
Elliott Hughes9160ed92017-01-30 17:54:57 -0800321 struct stat fd_stat;
322 if (fstat(fd, &fd_stat) < 0) {
323 return nullptr;
324 }
Narayan Kamathc9ae21a2014-02-19 17:59:05 +0000325
Elliott Hughes9160ed92017-01-30 17:54:57 -0800326 if ((fd_stat.st_uid != 0) || (fd_stat.st_gid != 0) ||
327 ((fd_stat.st_mode & (S_IWGRP | S_IWOTH)) != 0) ||
328 (fd_stat.st_size < static_cast<off_t>(sizeof(prop_area)))) {
329 return nullptr;
330 }
Narayan Kamathc9ae21a2014-02-19 17:59:05 +0000331
Elliott Hughes9160ed92017-01-30 17:54:57 -0800332 pa_size = fd_stat.st_size;
333 pa_data_size = pa_size - sizeof(prop_area);
Narayan Kamathc9ae21a2014-02-19 17:59:05 +0000334
Elliott Hughes8e7396c2017-01-31 08:24:43 -0800335 void* const map_result = mmap(nullptr, pa_size, PROT_READ, MAP_SHARED, fd, 0);
Elliott Hughes9160ed92017-01-30 17:54:57 -0800336 if (map_result == MAP_FAILED) {
337 return nullptr;
338 }
Narayan Kamathc9ae21a2014-02-19 17:59:05 +0000339
Elliott Hughes9160ed92017-01-30 17:54:57 -0800340 prop_area* pa = reinterpret_cast<prop_area*>(map_result);
341 if ((pa->magic() != PROP_AREA_MAGIC) || (pa->version() != PROP_AREA_VERSION)) {
342 munmap(pa, pa_size);
343 return nullptr;
344 }
Narayan Kamathc9ae21a2014-02-19 17:59:05 +0000345
Elliott Hughes9160ed92017-01-30 17:54:57 -0800346 return pa;
Narayan Kamathc9ae21a2014-02-19 17:59:05 +0000347}
348
Elliott Hughesf8562c52017-01-26 16:48:57 -0800349static prop_area* map_prop_area(const char* filename) {
Elliott Hughes9160ed92017-01-30 17:54:57 -0800350 int fd = open(filename, O_CLOEXEC | O_NOFOLLOW | O_RDONLY);
351 if (fd == -1) return nullptr;
Narayan Kamathc9ae21a2014-02-19 17:59:05 +0000352
Elliott Hughes9160ed92017-01-30 17:54:57 -0800353 prop_area* map_result = map_fd_ro(fd);
354 close(fd);
Narayan Kamathc9ae21a2014-02-19 17:59:05 +0000355
Elliott Hughes9160ed92017-01-30 17:54:57 -0800356 return map_result;
Narayan Kamathc9ae21a2014-02-19 17:59:05 +0000357}
358
Elliott Hughes9160ed92017-01-30 17:54:57 -0800359void* prop_area::allocate_obj(const size_t size, uint_least32_t* const off) {
Dan Alberta613d0d2017-10-05 16:39:33 -0700360 const size_t aligned = __BIONIC_ALIGN(size, sizeof(uint_least32_t));
Elliott Hughes9160ed92017-01-30 17:54:57 -0800361 if (bytes_used_ + aligned > pa_data_size) {
Elliott Hughes8e7396c2017-01-31 08:24:43 -0800362 return nullptr;
Elliott Hughes9160ed92017-01-30 17:54:57 -0800363 }
364
365 *off = bytes_used_;
366 bytes_used_ += aligned;
367 return data_ + *off;
Narayan Kamathc9ae21a2014-02-19 17:59:05 +0000368}
369
Elliott Hughes9160ed92017-01-30 17:54:57 -0800370prop_bt* prop_area::new_prop_bt(const char* name, uint32_t namelen, uint_least32_t* const off) {
371 uint_least32_t new_offset;
372 void* const p = allocate_obj(sizeof(prop_bt) + namelen + 1, &new_offset);
Elliott Hughes8e7396c2017-01-31 08:24:43 -0800373 if (p != nullptr) {
Elliott Hughes9160ed92017-01-30 17:54:57 -0800374 prop_bt* bt = new (p) prop_bt(name, namelen);
375 *off = new_offset;
376 return bt;
377 }
Narayan Kamathc9ae21a2014-02-19 17:59:05 +0000378
Elliott Hughes8e7396c2017-01-31 08:24:43 -0800379 return nullptr;
Narayan Kamathc9ae21a2014-02-19 17:59:05 +0000380}
381
Elliott Hughes9160ed92017-01-30 17:54:57 -0800382prop_info* prop_area::new_prop_info(const char* name, uint32_t namelen, const char* value,
383 uint32_t valuelen, uint_least32_t* const off) {
384 uint_least32_t new_offset;
385 void* const p = allocate_obj(sizeof(prop_info) + namelen + 1, &new_offset);
Tom Cherry8a311632017-10-09 13:49:17 -0700386 if (p == nullptr) return nullptr;
Narayan Kamathc9ae21a2014-02-19 17:59:05 +0000387
Tom Cherry8a311632017-10-09 13:49:17 -0700388 prop_info* info;
389 if (valuelen >= PROP_VALUE_MAX) {
390 uint32_t long_value_offset = 0;
391 char* long_location = reinterpret_cast<char*>(allocate_obj(valuelen + 1, &long_value_offset));
392 if (!long_location) return nullptr;
393
394 memcpy(long_location, value, valuelen);
395 long_location[valuelen] = '\0';
396
397 // Both new_offset and long_value_offset are offsets based off of data_, however prop_info
398 // does not know what data_ is, so we change this offset to be an offset from the prop_info
399 // pointer that contains it.
400 long_value_offset -= new_offset;
401
402 info = new (p) prop_info(name, namelen, long_value_offset);
403 } else {
404 info = new (p) prop_info(name, namelen, value, valuelen);
405 }
406 *off = new_offset;
407 return info;
Narayan Kamathc9ae21a2014-02-19 17:59:05 +0000408}
409
Elliott Hughes9160ed92017-01-30 17:54:57 -0800410void* prop_area::to_prop_obj(uint_least32_t off) {
Elliott Hughes8e7396c2017-01-31 08:24:43 -0800411 if (off > pa_data_size) return nullptr;
Elliott Hughes9160ed92017-01-30 17:54:57 -0800412
413 return (data_ + off);
414}
415
416inline prop_bt* prop_area::to_prop_bt(atomic_uint_least32_t* off_p) {
Yabin Cuib8ce4742015-02-10 21:35:56 -0800417 uint_least32_t off = atomic_load_explicit(off_p, memory_order_consume);
418 return reinterpret_cast<prop_bt*>(to_prop_obj(off));
419}
420
Elliott Hughes9160ed92017-01-30 17:54:57 -0800421inline prop_info* prop_area::to_prop_info(atomic_uint_least32_t* off_p) {
Yabin Cuib8ce4742015-02-10 21:35:56 -0800422 uint_least32_t off = atomic_load_explicit(off_p, memory_order_consume);
423 return reinterpret_cast<prop_info*>(to_prop_obj(off));
424}
425
Elliott Hughes9160ed92017-01-30 17:54:57 -0800426inline prop_bt* prop_area::root_node() {
427 return reinterpret_cast<prop_bt*>(to_prop_obj(0));
Narayan Kamathc9ae21a2014-02-19 17:59:05 +0000428}
429
Elliott Hughes9160ed92017-01-30 17:54:57 -0800430static int cmp_prop_name(const char* one, uint32_t one_len, const char* two, uint32_t two_len) {
431 if (one_len < two_len)
432 return -1;
433 else if (one_len > two_len)
434 return 1;
435 else
436 return strncmp(one, two, one_len);
Narayan Kamathc9ae21a2014-02-19 17:59:05 +0000437}
438
Elliott Hughes9160ed92017-01-30 17:54:57 -0800439prop_bt* prop_area::find_prop_bt(prop_bt* const bt, const char* name, uint32_t namelen,
440 bool alloc_if_needed) {
441 prop_bt* current = bt;
442 while (true) {
443 if (!current) {
Elliott Hughes8e7396c2017-01-31 08:24:43 -0800444 return nullptr;
Narayan Kamathc9ae21a2014-02-19 17:59:05 +0000445 }
446
Elliott Hughes9160ed92017-01-30 17:54:57 -0800447 const int ret = cmp_prop_name(name, namelen, current->name, current->namelen);
448 if (ret == 0) {
449 return current;
450 }
451
452 if (ret < 0) {
453 uint_least32_t left_offset = atomic_load_explicit(&current->left, memory_order_relaxed);
454 if (left_offset != 0) {
455 current = to_prop_bt(&current->left);
456 } else {
457 if (!alloc_if_needed) {
Elliott Hughes8e7396c2017-01-31 08:24:43 -0800458 return nullptr;
Elliott Hughes9160ed92017-01-30 17:54:57 -0800459 }
460
Yabin Cuib8ce4742015-02-10 21:35:56 -0800461 uint_least32_t new_offset;
Elliott Hughes9160ed92017-01-30 17:54:57 -0800462 prop_bt* new_bt = new_prop_bt(name, namelen, &new_offset);
463 if (new_bt) {
464 atomic_store_explicit(&current->left, new_offset, memory_order_release);
465 }
466 return new_bt;
467 }
468 } else {
469 uint_least32_t right_offset = atomic_load_explicit(&current->right, memory_order_relaxed);
470 if (right_offset != 0) {
471 current = to_prop_bt(&current->right);
472 } else {
473 if (!alloc_if_needed) {
Elliott Hughes8e7396c2017-01-31 08:24:43 -0800474 return nullptr;
Narayan Kamathc9ae21a2014-02-19 17:59:05 +0000475 }
476
Elliott Hughes9160ed92017-01-30 17:54:57 -0800477 uint_least32_t new_offset;
478 prop_bt* new_bt = new_prop_bt(name, namelen, &new_offset);
479 if (new_bt) {
480 atomic_store_explicit(&current->right, new_offset, memory_order_release);
481 }
482 return new_bt;
483 }
Narayan Kamathc9ae21a2014-02-19 17:59:05 +0000484 }
Elliott Hughes9160ed92017-01-30 17:54:57 -0800485 }
486}
487
488const prop_info* prop_area::find_property(prop_bt* const trie, const char* name, uint32_t namelen,
489 const char* value, uint32_t valuelen,
490 bool alloc_if_needed) {
Elliott Hughes8e7396c2017-01-31 08:24:43 -0800491 if (!trie) return nullptr;
Elliott Hughes9160ed92017-01-30 17:54:57 -0800492
493 const char* remaining_name = name;
494 prop_bt* current = trie;
495 while (true) {
496 const char* sep = strchr(remaining_name, '.');
Elliott Hughes8e7396c2017-01-31 08:24:43 -0800497 const bool want_subtree = (sep != nullptr);
Elliott Hughes9160ed92017-01-30 17:54:57 -0800498 const uint32_t substr_size = (want_subtree) ? sep - remaining_name : strlen(remaining_name);
499
500 if (!substr_size) {
Elliott Hughes8e7396c2017-01-31 08:24:43 -0800501 return nullptr;
Elliott Hughes9160ed92017-01-30 17:54:57 -0800502 }
503
Elliott Hughes8e7396c2017-01-31 08:24:43 -0800504 prop_bt* root = nullptr;
Elliott Hughes9160ed92017-01-30 17:54:57 -0800505 uint_least32_t children_offset = atomic_load_explicit(&current->children, memory_order_relaxed);
506 if (children_offset != 0) {
507 root = to_prop_bt(&current->children);
508 } else if (alloc_if_needed) {
509 uint_least32_t new_offset;
510 root = new_prop_bt(remaining_name, substr_size, &new_offset);
511 if (root) {
512 atomic_store_explicit(&current->children, new_offset, memory_order_release);
513 }
514 }
515
516 if (!root) {
Elliott Hughes8e7396c2017-01-31 08:24:43 -0800517 return nullptr;
Elliott Hughes9160ed92017-01-30 17:54:57 -0800518 }
519
520 current = find_prop_bt(root, remaining_name, substr_size, alloc_if_needed);
521 if (!current) {
Elliott Hughes8e7396c2017-01-31 08:24:43 -0800522 return nullptr;
Elliott Hughes9160ed92017-01-30 17:54:57 -0800523 }
524
525 if (!want_subtree) break;
526
527 remaining_name = sep + 1;
528 }
529
530 uint_least32_t prop_offset = atomic_load_explicit(&current->prop, memory_order_relaxed);
531 if (prop_offset != 0) {
532 return to_prop_info(&current->prop);
533 } else if (alloc_if_needed) {
534 uint_least32_t new_offset;
535 prop_info* new_info = new_prop_info(name, namelen, value, valuelen, &new_offset);
536 if (new_info) {
537 atomic_store_explicit(&current->prop, new_offset, memory_order_release);
538 }
539
540 return new_info;
541 } else {
Elliott Hughes8e7396c2017-01-31 08:24:43 -0800542 return nullptr;
Elliott Hughes9160ed92017-01-30 17:54:57 -0800543 }
Narayan Kamathc9ae21a2014-02-19 17:59:05 +0000544}
545
Dimitry Ivanov16b2a4d2017-01-24 20:43:29 +0000546class PropertyServiceConnection {
547 public:
548 PropertyServiceConnection() : last_error_(0) {
Dimitry Ivanov6391e1a2017-02-23 17:57:14 -0800549 socket_ = ::socket(AF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0);
550 if (socket_ == -1) {
Dimitry Ivanov16b2a4d2017-01-24 20:43:29 +0000551 last_error_ = errno;
552 return;
Narayan Kamathc9ae21a2014-02-19 17:59:05 +0000553 }
554
555 const size_t namelen = strlen(property_service_socket);
Narayan Kamathc9ae21a2014-02-19 17:59:05 +0000556 sockaddr_un addr;
557 memset(&addr, 0, sizeof(addr));
558 strlcpy(addr.sun_path, property_service_socket, sizeof(addr.sun_path));
559 addr.sun_family = AF_LOCAL;
560 socklen_t alen = namelen + offsetof(sockaddr_un, sun_path) + 1;
Dimitry Ivanov16b2a4d2017-01-24 20:43:29 +0000561
Dimitry Ivanov6391e1a2017-02-23 17:57:14 -0800562 if (TEMP_FAILURE_RETRY(connect(socket_, reinterpret_cast<sockaddr*>(&addr), alen)) == -1) {
Tom Cherrybe4232b2017-04-14 13:45:20 -0700563 last_error_ = errno;
Dimitry Ivanov6391e1a2017-02-23 17:57:14 -0800564 close(socket_);
565 socket_ = -1;
Dimitry Ivanov16b2a4d2017-01-24 20:43:29 +0000566 }
567 }
568
569 bool IsValid() {
Dimitry Ivanov6391e1a2017-02-23 17:57:14 -0800570 return socket_ != -1;
Dimitry Ivanov16b2a4d2017-01-24 20:43:29 +0000571 }
572
573 int GetLastError() {
574 return last_error_;
575 }
576
Dimitry Ivanov16b2a4d2017-01-24 20:43:29 +0000577 bool RecvInt32(int32_t* value) {
Dimitry Ivanov6391e1a2017-02-23 17:57:14 -0800578 int result = TEMP_FAILURE_RETRY(recv(socket_, value, sizeof(*value), MSG_WAITALL));
Dimitry Ivanov16b2a4d2017-01-24 20:43:29 +0000579 return CheckSendRecvResult(result, sizeof(*value));
580 }
581
Dimitry Ivanov6391e1a2017-02-23 17:57:14 -0800582 int socket() {
583 return socket_;
Dimitry Ivanov16b2a4d2017-01-24 20:43:29 +0000584 }
585
586 ~PropertyServiceConnection() {
Dimitry Ivanov6391e1a2017-02-23 17:57:14 -0800587 if (socket_ != -1) {
588 close(socket_);
Dimitry Ivanov16b2a4d2017-01-24 20:43:29 +0000589 }
590 }
Elliott Hughes9160ed92017-01-30 17:54:57 -0800591
Dimitry Ivanov16b2a4d2017-01-24 20:43:29 +0000592 private:
593 bool CheckSendRecvResult(int result, int expected_len) {
594 if (result == -1) {
595 last_error_ = errno;
596 } else if (result != expected_len) {
597 last_error_ = -1;
598 } else {
599 last_error_ = 0;
600 }
601
602 return last_error_ == 0;
603 }
604
Dimitry Ivanov6391e1a2017-02-23 17:57:14 -0800605 int socket_;
Dimitry Ivanov16b2a4d2017-01-24 20:43:29 +0000606 int last_error_;
Dimitry Ivanov6391e1a2017-02-23 17:57:14 -0800607
608 friend class SocketWriter;
609};
610
611class SocketWriter {
612 public:
613 explicit SocketWriter(PropertyServiceConnection* connection)
614 : connection_(connection), iov_index_(0), uint_buf_index_(0)
615 {}
616
617 SocketWriter& WriteUint32(uint32_t value) {
618 CHECK(uint_buf_index_ < kUintBufSize);
619 CHECK(iov_index_ < kIovSize);
620 uint32_t* ptr = uint_buf_ + uint_buf_index_;
621 uint_buf_[uint_buf_index_++] = value;
622 iov_[iov_index_].iov_base = ptr;
623 iov_[iov_index_].iov_len = sizeof(*ptr);
624 ++iov_index_;
625 return *this;
626 }
627
628 SocketWriter& WriteString(const char* value) {
629 uint32_t valuelen = strlen(value);
630 WriteUint32(valuelen);
631 if (valuelen == 0) {
632 return *this;
633 }
634
635 CHECK(iov_index_ < kIovSize);
636 iov_[iov_index_].iov_base = const_cast<char*>(value);
637 iov_[iov_index_].iov_len = valuelen;
638 ++iov_index_;
639
640 return *this;
641 }
642
643 bool Send() {
644 if (!connection_->IsValid()) {
645 return false;
646 }
647
648 if (writev(connection_->socket(), iov_, iov_index_) == -1) {
649 connection_->last_error_ = errno;
650 return false;
651 }
652
653 iov_index_ = uint_buf_index_ = 0;
654 return true;
655 }
656
657 private:
658 static constexpr size_t kUintBufSize = 8;
659 static constexpr size_t kIovSize = 8;
660
661 PropertyServiceConnection* connection_;
662 iovec iov_[kIovSize];
663 size_t iov_index_;
664 uint32_t uint_buf_[kUintBufSize];
665 size_t uint_buf_index_;
666
667 DISALLOW_IMPLICIT_CONSTRUCTORS(SocketWriter);
Dimitry Ivanov16b2a4d2017-01-24 20:43:29 +0000668};
669
Elliott Hughesf8562c52017-01-26 16:48:57 -0800670struct prop_msg {
Elliott Hughes9160ed92017-01-30 17:54:57 -0800671 unsigned cmd;
672 char name[PROP_NAME_MAX];
673 char value[PROP_VALUE_MAX];
Elliott Hughesf8562c52017-01-26 16:48:57 -0800674};
675
Dimitry Ivanov16b2a4d2017-01-24 20:43:29 +0000676static int send_prop_msg(const prop_msg* msg) {
Elliott Hughes9160ed92017-01-30 17:54:57 -0800677 PropertyServiceConnection connection;
678 if (!connection.IsValid()) {
679 return connection.GetLastError();
680 }
681
682 int result = -1;
Dimitry Ivanov6391e1a2017-02-23 17:57:14 -0800683 int s = connection.socket();
Elliott Hughes9160ed92017-01-30 17:54:57 -0800684
Dimitry Ivanov6391e1a2017-02-23 17:57:14 -0800685 const int num_bytes = TEMP_FAILURE_RETRY(send(s, msg, sizeof(prop_msg), 0));
Elliott Hughes9160ed92017-01-30 17:54:57 -0800686 if (num_bytes == sizeof(prop_msg)) {
687 // We successfully wrote to the property server but now we
688 // wait for the property server to finish its work. It
689 // acknowledges its completion by closing the socket so we
690 // poll here (on nothing), waiting for the socket to close.
691 // If you 'adb shell setprop foo bar' you'll see the POLLHUP
692 // once the socket closes. Out of paranoia we cap our poll
693 // at 250 ms.
694 pollfd pollfds[1];
Dimitry Ivanov6391e1a2017-02-23 17:57:14 -0800695 pollfds[0].fd = s;
Elliott Hughes9160ed92017-01-30 17:54:57 -0800696 pollfds[0].events = 0;
697 const int poll_result = TEMP_FAILURE_RETRY(poll(pollfds, 1, 250 /* ms */));
698 if (poll_result == 1 && (pollfds[0].revents & POLLHUP) != 0) {
699 result = 0;
700 } else {
701 // Ignore the timeout and treat it like a success anyway.
702 // The init process is single-threaded and its property
703 // service is sometimes slow to respond (perhaps it's off
704 // starting a child process or something) and thus this
705 // times out and the caller thinks it failed, even though
706 // it's still getting around to it. So we fake it here,
707 // mostly for ctl.* properties, but we do try and wait 250
708 // ms so callers who do read-after-write can reliably see
709 // what they've written. Most of the time.
710 // TODO: fix the system properties design.
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700711 async_safe_format_log(ANDROID_LOG_WARN, "libc",
712 "Property service has timed out while trying to set \"%s\" to \"%s\"",
713 msg->name, msg->value);
Elliott Hughes9160ed92017-01-30 17:54:57 -0800714 result = 0;
Dimitry Ivanov16b2a4d2017-01-24 20:43:29 +0000715 }
Elliott Hughes9160ed92017-01-30 17:54:57 -0800716 }
Dimitry Ivanov489f58b2017-01-24 18:39:04 +0000717
Elliott Hughes9160ed92017-01-30 17:54:57 -0800718 return result;
Narayan Kamathc9ae21a2014-02-19 17:59:05 +0000719}
720
Elliott Hughes9160ed92017-01-30 17:54:57 -0800721bool prop_area::foreach_property(prop_bt* const trie,
722 void (*propfn)(const prop_info* pi, void* cookie), void* cookie) {
723 if (!trie) return false;
Narayan Kamathc9ae21a2014-02-19 17:59:05 +0000724
Elliott Hughes9160ed92017-01-30 17:54:57 -0800725 uint_least32_t left_offset = atomic_load_explicit(&trie->left, memory_order_relaxed);
726 if (left_offset != 0) {
727 const int err = foreach_property(to_prop_bt(&trie->left), propfn, cookie);
728 if (err < 0) return false;
729 }
730 uint_least32_t prop_offset = atomic_load_explicit(&trie->prop, memory_order_relaxed);
731 if (prop_offset != 0) {
732 prop_info* info = to_prop_info(&trie->prop);
733 if (!info) return false;
734 propfn(info, cookie);
735 }
736 uint_least32_t children_offset = atomic_load_explicit(&trie->children, memory_order_relaxed);
737 if (children_offset != 0) {
738 const int err = foreach_property(to_prop_bt(&trie->children), propfn, cookie);
739 if (err < 0) return false;
740 }
741 uint_least32_t right_offset = atomic_load_explicit(&trie->right, memory_order_relaxed);
742 if (right_offset != 0) {
743 const int err = foreach_property(to_prop_bt(&trie->right), propfn, cookie);
744 if (err < 0) return false;
745 }
Narayan Kamathc9ae21a2014-02-19 17:59:05 +0000746
Elliott Hughes9160ed92017-01-30 17:54:57 -0800747 return true;
Tom Cherry926ebe12015-09-23 15:34:40 -0700748}
749
Elliott Hughes9160ed92017-01-30 17:54:57 -0800750const prop_info* prop_area::find(const char* name) {
751 return find_property(root_node(), name, strlen(name), nullptr, 0, false);
Tom Cherry926ebe12015-09-23 15:34:40 -0700752}
753
Elliott Hughes9160ed92017-01-30 17:54:57 -0800754bool prop_area::add(const char* name, unsigned int namelen, const char* value,
755 unsigned int valuelen) {
756 return find_property(root_node(), name, namelen, value, valuelen, true);
Tom Cherry926ebe12015-09-23 15:34:40 -0700757}
758
Elliott Hughes9160ed92017-01-30 17:54:57 -0800759bool prop_area::foreach (void (*propfn)(const prop_info* pi, void* cookie), void* cookie) {
760 return foreach_property(root_node(), propfn, cookie);
Narayan Kamathc9ae21a2014-02-19 17:59:05 +0000761}
762
Tom Cherryb4171692015-12-09 15:48:15 -0800763class context_node {
Elliott Hughes9160ed92017-01-30 17:54:57 -0800764 public:
765 context_node(context_node* next, const char* context, prop_area* pa)
766 : next(next), context_(strdup(context)), pa_(pa), no_access_(false) {
767 lock_.init(false);
768 }
769 ~context_node() {
770 unmap();
771 free(context_);
772 }
773 bool open(bool access_rw, bool* fsetxattr_failed);
774 bool check_access_and_open();
775 void reset_access();
Tom Cherryb4171692015-12-09 15:48:15 -0800776
Elliott Hughes9160ed92017-01-30 17:54:57 -0800777 const char* context() const {
778 return context_;
779 }
780 prop_area* pa() {
781 return pa_;
782 }
Tom Cherryb4171692015-12-09 15:48:15 -0800783
Elliott Hughes9160ed92017-01-30 17:54:57 -0800784 context_node* next;
Tom Cherryb4171692015-12-09 15:48:15 -0800785
Elliott Hughes9160ed92017-01-30 17:54:57 -0800786 private:
787 bool check_access();
788 void unmap();
Tom Cherryb4171692015-12-09 15:48:15 -0800789
Elliott Hughes9160ed92017-01-30 17:54:57 -0800790 Lock lock_;
791 char* context_;
792 prop_area* pa_;
793 bool no_access_;
Tom Cherry49a309f2015-09-23 16:09:47 -0700794};
795
796struct prefix_node {
Elliott Hughes9160ed92017-01-30 17:54:57 -0800797 prefix_node(struct prefix_node* next, const char* prefix, context_node* context)
798 : prefix(strdup(prefix)), prefix_len(strlen(prefix)), context(context), next(next) {
799 }
800 ~prefix_node() {
801 free(prefix);
802 }
803 char* prefix;
804 const size_t prefix_len;
805 context_node* context;
806 struct prefix_node* next;
Tom Cherry49a309f2015-09-23 16:09:47 -0700807};
808
809template <typename List, typename... Args>
810static inline void list_add(List** list, Args... args) {
Elliott Hughes9160ed92017-01-30 17:54:57 -0800811 *list = new List(*list, args...);
Tom Cherry49a309f2015-09-23 16:09:47 -0700812}
813
814static void list_add_after_len(prefix_node** list, const char* prefix, context_node* context) {
Elliott Hughes9160ed92017-01-30 17:54:57 -0800815 size_t prefix_len = strlen(prefix);
Tom Cherry49a309f2015-09-23 16:09:47 -0700816
Elliott Hughes9160ed92017-01-30 17:54:57 -0800817 auto next_list = list;
Tom Cherry49a309f2015-09-23 16:09:47 -0700818
Elliott Hughes9160ed92017-01-30 17:54:57 -0800819 while (*next_list) {
820 if ((*next_list)->prefix_len < prefix_len || (*next_list)->prefix[0] == '*') {
821 list_add(next_list, prefix, context);
822 return;
Tom Cherry49a309f2015-09-23 16:09:47 -0700823 }
Elliott Hughes9160ed92017-01-30 17:54:57 -0800824 next_list = &(*next_list)->next;
825 }
826 list_add(next_list, prefix, context);
Tom Cherry49a309f2015-09-23 16:09:47 -0700827}
828
829template <typename List, typename Func>
830static void list_foreach(List* list, Func func) {
Elliott Hughes9160ed92017-01-30 17:54:57 -0800831 while (list) {
832 func(list);
833 list = list->next;
834 }
Tom Cherry49a309f2015-09-23 16:09:47 -0700835}
836
837template <typename List, typename Func>
838static List* list_find(List* list, Func func) {
Elliott Hughes9160ed92017-01-30 17:54:57 -0800839 while (list) {
840 if (func(list)) {
841 return list;
Tom Cherry49a309f2015-09-23 16:09:47 -0700842 }
Elliott Hughes9160ed92017-01-30 17:54:57 -0800843 list = list->next;
844 }
845 return nullptr;
Tom Cherry49a309f2015-09-23 16:09:47 -0700846}
847
848template <typename List>
849static void list_free(List** list) {
Elliott Hughes9160ed92017-01-30 17:54:57 -0800850 while (*list) {
851 auto old_list = *list;
852 *list = old_list->next;
853 delete old_list;
854 }
Tom Cherry49a309f2015-09-23 16:09:47 -0700855}
856
857static prefix_node* prefixes = nullptr;
858static context_node* contexts = nullptr;
859
860/*
861 * pthread_mutex_lock() calls into system_properties in the case of contention.
862 * This creates a risk of dead lock if any system_properties functions
863 * use pthread locks after system_property initialization.
864 *
865 * For this reason, the below three functions use a bionic Lock and static
866 * allocation of memory for each filename.
867 */
868
Tom Cherryb4171692015-12-09 15:48:15 -0800869bool context_node::open(bool access_rw, bool* fsetxattr_failed) {
Elliott Hughes9160ed92017-01-30 17:54:57 -0800870 lock_.lock();
871 if (pa_) {
Tom Cherryb4171692015-12-09 15:48:15 -0800872 lock_.unlock();
Elliott Hughes9160ed92017-01-30 17:54:57 -0800873 return true;
874 }
875
876 char filename[PROP_FILENAME_MAX];
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700877 int len = async_safe_format_buffer(filename, sizeof(filename), "%s/%s", property_filename,
878 context_);
Elliott Hughes9160ed92017-01-30 17:54:57 -0800879 if (len < 0 || len > PROP_FILENAME_MAX) {
880 lock_.unlock();
881 return false;
882 }
883
884 if (access_rw) {
885 pa_ = map_prop_area_rw(filename, context_, fsetxattr_failed);
886 } else {
887 pa_ = map_prop_area(filename);
888 }
889 lock_.unlock();
890 return pa_;
Tom Cherry49a309f2015-09-23 16:09:47 -0700891}
892
Tom Cherryb4171692015-12-09 15:48:15 -0800893bool context_node::check_access_and_open() {
Elliott Hughes9160ed92017-01-30 17:54:57 -0800894 if (!pa_ && !no_access_) {
895 if (!check_access() || !open(false, nullptr)) {
896 no_access_ = true;
Tom Cherryb4171692015-12-09 15:48:15 -0800897 }
Elliott Hughes9160ed92017-01-30 17:54:57 -0800898 }
899 return pa_;
Tom Cherryb4171692015-12-09 15:48:15 -0800900}
901
902void context_node::reset_access() {
Elliott Hughes9160ed92017-01-30 17:54:57 -0800903 if (!check_access()) {
904 unmap();
905 no_access_ = true;
906 } else {
907 no_access_ = false;
908 }
Tom Cherryb4171692015-12-09 15:48:15 -0800909}
910
911bool context_node::check_access() {
Elliott Hughes9160ed92017-01-30 17:54:57 -0800912 char filename[PROP_FILENAME_MAX];
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700913 int len = async_safe_format_buffer(filename, sizeof(filename), "%s/%s", property_filename,
914 context_);
Elliott Hughes9160ed92017-01-30 17:54:57 -0800915 if (len < 0 || len > PROP_FILENAME_MAX) {
916 return false;
917 }
Tom Cherry49a309f2015-09-23 16:09:47 -0700918
Elliott Hughes9160ed92017-01-30 17:54:57 -0800919 return access(filename, R_OK) == 0;
Tom Cherry49a309f2015-09-23 16:09:47 -0700920}
921
Tom Cherryb4171692015-12-09 15:48:15 -0800922void context_node::unmap() {
Elliott Hughes9160ed92017-01-30 17:54:57 -0800923 if (!pa_) {
924 return;
925 }
Tom Cherryb4171692015-12-09 15:48:15 -0800926
Elliott Hughes9160ed92017-01-30 17:54:57 -0800927 munmap(pa_, pa_size);
928 if (pa_ == __system_property_area__) {
929 __system_property_area__ = nullptr;
930 }
931 pa_ = nullptr;
Tom Cherryb4171692015-12-09 15:48:15 -0800932}
933
Tom Cherry49a309f2015-09-23 16:09:47 -0700934static bool map_system_property_area(bool access_rw, bool* fsetxattr_failed) {
Elliott Hughes9160ed92017-01-30 17:54:57 -0800935 char filename[PROP_FILENAME_MAX];
936 int len =
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700937 async_safe_format_buffer(filename, sizeof(filename), "%s/properties_serial",
938 property_filename);
Elliott Hughes9160ed92017-01-30 17:54:57 -0800939 if (len < 0 || len > PROP_FILENAME_MAX) {
940 __system_property_area__ = nullptr;
941 return false;
942 }
Tom Cherry49a309f2015-09-23 16:09:47 -0700943
Elliott Hughes9160ed92017-01-30 17:54:57 -0800944 if (access_rw) {
945 __system_property_area__ =
946 map_prop_area_rw(filename, "u:object_r:properties_serial:s0", fsetxattr_failed);
947 } else {
948 __system_property_area__ = map_prop_area(filename);
949 }
950 return __system_property_area__;
Tom Cherry49a309f2015-09-23 16:09:47 -0700951}
952
953static prop_area* get_prop_area_for_name(const char* name) {
Elliott Hughes9160ed92017-01-30 17:54:57 -0800954 auto entry = list_find(prefixes, [name](prefix_node* l) {
955 return l->prefix[0] == '*' || !strncmp(l->prefix, name, l->prefix_len);
956 });
957 if (!entry) {
958 return nullptr;
959 }
Tom Cherry49a309f2015-09-23 16:09:47 -0700960
Elliott Hughes9160ed92017-01-30 17:54:57 -0800961 auto cnode = entry->context;
962 if (!cnode->pa()) {
963 /*
964 * We explicitly do not check no_access_ in this case because unlike the
965 * case of foreach(), we want to generate an selinux audit for each
966 * non-permitted property access in this function.
967 */
968 cnode->open(false, nullptr);
969 }
970 return cnode->pa();
Tom Cherry49a309f2015-09-23 16:09:47 -0700971}
972
973/*
974 * The below two functions are duplicated from label_support.c in libselinux.
975 * TODO: Find a location suitable for these functions such that both libc and
976 * libselinux can share a common source file.
977 */
978
979/*
980 * The read_spec_entries and read_spec_entry functions may be used to
981 * replace sscanf to read entries from spec files. The file and
982 * property services now use these.
983 */
984
985/* Read an entry from a spec file (e.g. file_contexts) */
Elliott Hughes9160ed92017-01-30 17:54:57 -0800986static inline int read_spec_entry(char** entry, char** ptr, int* len) {
Elliott Hughes8e7396c2017-01-31 08:24:43 -0800987 *entry = nullptr;
988 char* tmp_buf = nullptr;
Tom Cherry49a309f2015-09-23 16:09:47 -0700989
Elliott Hughes9160ed92017-01-30 17:54:57 -0800990 while (isspace(**ptr) && **ptr != '\0') (*ptr)++;
Tom Cherry49a309f2015-09-23 16:09:47 -0700991
Elliott Hughes9160ed92017-01-30 17:54:57 -0800992 tmp_buf = *ptr;
993 *len = 0;
Tom Cherry49a309f2015-09-23 16:09:47 -0700994
Elliott Hughes9160ed92017-01-30 17:54:57 -0800995 while (!isspace(**ptr) && **ptr != '\0') {
996 (*ptr)++;
997 (*len)++;
998 }
Tom Cherry49a309f2015-09-23 16:09:47 -0700999
Elliott Hughes9160ed92017-01-30 17:54:57 -08001000 if (*len) {
1001 *entry = strndup(tmp_buf, *len);
1002 if (!*entry) return -1;
1003 }
Tom Cherry49a309f2015-09-23 16:09:47 -07001004
Elliott Hughes9160ed92017-01-30 17:54:57 -08001005 return 0;
Tom Cherry49a309f2015-09-23 16:09:47 -07001006}
1007
1008/*
1009 * line_buf - Buffer containing the spec entries .
1010 * num_args - The number of spec parameter entries to process.
1011 * ... - A 'char **spec_entry' for each parameter.
1012 * returns - The number of items processed.
1013 *
1014 * This function calls read_spec_entry() to do the actual string processing.
1015 */
Elliott Hughes9160ed92017-01-30 17:54:57 -08001016static int read_spec_entries(char* line_buf, int num_args, ...) {
1017 char **spec_entry, *buf_p;
1018 int len, rc, items, entry_len = 0;
1019 va_list ap;
Tom Cherry49a309f2015-09-23 16:09:47 -07001020
Elliott Hughes9160ed92017-01-30 17:54:57 -08001021 len = strlen(line_buf);
1022 if (line_buf[len - 1] == '\n')
1023 line_buf[len - 1] = '\0';
1024 else
1025 /* Handle case if line not \n terminated by bumping
1026 * the len for the check below (as the line is NUL
1027 * terminated by getline(3)) */
1028 len++;
Tom Cherry49a309f2015-09-23 16:09:47 -07001029
Elliott Hughes9160ed92017-01-30 17:54:57 -08001030 buf_p = line_buf;
1031 while (isspace(*buf_p)) buf_p++;
Tom Cherry49a309f2015-09-23 16:09:47 -07001032
Elliott Hughes9160ed92017-01-30 17:54:57 -08001033 /* Skip comment lines and empty lines. */
1034 if (*buf_p == '#' || *buf_p == '\0') return 0;
Tom Cherry49a309f2015-09-23 16:09:47 -07001035
Elliott Hughes9160ed92017-01-30 17:54:57 -08001036 /* Process the spec file entries */
1037 va_start(ap, num_args);
Tom Cherry49a309f2015-09-23 16:09:47 -07001038
Elliott Hughes9160ed92017-01-30 17:54:57 -08001039 items = 0;
1040 while (items < num_args) {
1041 spec_entry = va_arg(ap, char**);
Tom Cherry49a309f2015-09-23 16:09:47 -07001042
Elliott Hughes9160ed92017-01-30 17:54:57 -08001043 if (len - 1 == buf_p - line_buf) {
1044 va_end(ap);
1045 return items;
Tom Cherry49a309f2015-09-23 16:09:47 -07001046 }
Elliott Hughes9160ed92017-01-30 17:54:57 -08001047
1048 rc = read_spec_entry(spec_entry, &buf_p, &entry_len);
1049 if (rc < 0) {
1050 va_end(ap);
1051 return rc;
1052 }
1053 if (entry_len) items++;
1054 }
1055 va_end(ap);
1056 return items;
Tom Cherry49a309f2015-09-23 16:09:47 -07001057}
1058
Elliott Hughes9160ed92017-01-30 17:54:57 -08001059static bool initialize_properties_from_file(const char* filename) {
1060 FILE* file = fopen(filename, "re");
1061 if (!file) {
1062 return false;
1063 }
1064
1065 char* buffer = nullptr;
1066 size_t line_len;
1067 char* prop_prefix = nullptr;
1068 char* context = nullptr;
1069
1070 while (getline(&buffer, &line_len, file) > 0) {
1071 int items = read_spec_entries(buffer, 2, &prop_prefix, &context);
1072 if (items <= 0) {
1073 continue;
1074 }
1075 if (items == 1) {
1076 free(prop_prefix);
1077 continue;
1078 }
1079 /*
1080 * init uses ctl.* properties as an IPC mechanism and does not write them
1081 * to a property file, therefore we do not need to create property files
1082 * to store them.
1083 */
1084 if (!strncmp(prop_prefix, "ctl.", 4)) {
1085 free(prop_prefix);
1086 free(context);
1087 continue;
Tom Cherry49a309f2015-09-23 16:09:47 -07001088 }
1089
Elliott Hughes9160ed92017-01-30 17:54:57 -08001090 auto old_context =
1091 list_find(contexts, [context](context_node* l) { return !strcmp(l->context(), context); });
1092 if (old_context) {
1093 list_add_after_len(&prefixes, prop_prefix, old_context);
1094 } else {
1095 list_add(&contexts, context, nullptr);
1096 list_add_after_len(&prefixes, prop_prefix, contexts);
Tom Cherry49a309f2015-09-23 16:09:47 -07001097 }
Elliott Hughes9160ed92017-01-30 17:54:57 -08001098 free(prop_prefix);
1099 free(context);
1100 }
Tom Cherry49a309f2015-09-23 16:09:47 -07001101
Elliott Hughes9160ed92017-01-30 17:54:57 -08001102 free(buffer);
1103 fclose(file);
Sandeep Patil34f0cfa2016-12-27 17:37:44 -08001104
Elliott Hughes9160ed92017-01-30 17:54:57 -08001105 return true;
Sandeep Patil34f0cfa2016-12-27 17:37:44 -08001106}
1107
1108static bool initialize_properties() {
Elliott Hughes9160ed92017-01-30 17:54:57 -08001109 // If we do find /property_contexts, then this is being
1110 // run as part of the OTA updater on older release that had
1111 // /property_contexts - b/34370523
1112 if (initialize_properties_from_file("/property_contexts")) {
Tom Cherry49a309f2015-09-23 16:09:47 -07001113 return true;
Elliott Hughes9160ed92017-01-30 17:54:57 -08001114 }
1115
Alex Klyubin176cf1f2017-03-08 13:16:03 -08001116 // Use property_contexts from /system & /vendor, fall back to those from /
1117 if (access("/system/etc/selinux/plat_property_contexts", R_OK) != -1) {
1118 if (!initialize_properties_from_file("/system/etc/selinux/plat_property_contexts")) {
1119 return false;
1120 }
Sandeep Patil03ed4af2017-05-17 11:33:37 -07001121 // Don't check for failure here, so we always have a sane list of properties.
1122 // E.g. In case of recovery, the vendor partition will not have mounted and we
1123 // still need the system / platform properties to function.
1124 initialize_properties_from_file("/vendor/etc/selinux/nonplat_property_contexts");
Alex Klyubin176cf1f2017-03-08 13:16:03 -08001125 } else {
1126 if (!initialize_properties_from_file("/plat_property_contexts")) {
1127 return false;
1128 }
Sandeep Patil03ed4af2017-05-17 11:33:37 -07001129 initialize_properties_from_file("/nonplat_property_contexts");
Elliott Hughes9160ed92017-01-30 17:54:57 -08001130 }
1131
Elliott Hughes9160ed92017-01-30 17:54:57 -08001132 return true;
Tom Cherry49a309f2015-09-23 16:09:47 -07001133}
1134
1135static bool is_dir(const char* pathname) {
Elliott Hughes9160ed92017-01-30 17:54:57 -08001136 struct stat info;
1137 if (stat(pathname, &info) == -1) {
1138 return false;
1139 }
1140 return S_ISDIR(info.st_mode);
Tom Cherry49a309f2015-09-23 16:09:47 -07001141}
1142
Tom Cherryb4171692015-12-09 15:48:15 -08001143static void free_and_unmap_contexts() {
Elliott Hughes9160ed92017-01-30 17:54:57 -08001144 list_free(&prefixes);
1145 list_free(&contexts);
1146 if (__system_property_area__) {
1147 munmap(__system_property_area__, pa_size);
1148 __system_property_area__ = nullptr;
1149 }
Tom Cherryb4171692015-12-09 15:48:15 -08001150}
1151
Elliott Hughes9160ed92017-01-30 17:54:57 -08001152int __system_properties_init() {
Elliott Hughes7ade61c2017-04-11 13:38:36 -07001153 // This is called from __libc_init_common, and should leave errno at 0 (http://b/37248982).
1154 ErrnoRestorer errno_restorer;
1155
Elliott Hughes9160ed92017-01-30 17:54:57 -08001156 if (initialized) {
1157 list_foreach(contexts, [](context_node* l) { l->reset_access(); });
Tom Cherry49a309f2015-09-23 16:09:47 -07001158 return 0;
Elliott Hughes9160ed92017-01-30 17:54:57 -08001159 }
1160 if (is_dir(property_filename)) {
Tom Cherry49a309f2015-09-23 16:09:47 -07001161 if (!initialize_properties()) {
Elliott Hughes9160ed92017-01-30 17:54:57 -08001162 return -1;
Tom Cherry49a309f2015-09-23 16:09:47 -07001163 }
Elliott Hughes9160ed92017-01-30 17:54:57 -08001164 if (!map_system_property_area(false, nullptr)) {
1165 free_and_unmap_contexts();
1166 return -1;
Tom Cherry49a309f2015-09-23 16:09:47 -07001167 }
Elliott Hughes9160ed92017-01-30 17:54:57 -08001168 } else {
1169 __system_property_area__ = map_prop_area(property_filename);
Tom Cherry6ed51c02015-12-04 11:34:42 -08001170 if (!__system_property_area__) {
Elliott Hughes9160ed92017-01-30 17:54:57 -08001171 return -1;
Tom Cherry6ed51c02015-12-04 11:34:42 -08001172 }
Elliott Hughes9160ed92017-01-30 17:54:57 -08001173 list_add(&contexts, "legacy_system_prop_area", __system_property_area__);
1174 list_add_after_len(&prefixes, "*", contexts);
1175 }
1176 initialized = true;
1177 return 0;
1178}
Tom Cherry6ed51c02015-12-04 11:34:42 -08001179
Elliott Hughes9160ed92017-01-30 17:54:57 -08001180int __system_property_set_filename(const char* filename) {
1181 size_t len = strlen(filename);
1182 if (len >= sizeof(property_filename)) return -1;
1183
1184 strcpy(property_filename, filename);
1185 return 0;
1186}
1187
1188int __system_property_area_init() {
1189 free_and_unmap_contexts();
1190 mkdir(property_filename, S_IRWXU | S_IXGRP | S_IXOTH);
1191 if (!initialize_properties()) {
1192 return -1;
1193 }
1194 bool open_failed = false;
1195 bool fsetxattr_failed = false;
1196 list_foreach(contexts, [&fsetxattr_failed, &open_failed](context_node* l) {
1197 if (!l->open(true, &fsetxattr_failed)) {
1198 open_failed = true;
Tom Cherry926ebe12015-09-23 15:34:40 -07001199 }
Elliott Hughes9160ed92017-01-30 17:54:57 -08001200 });
1201 if (open_failed || !map_system_property_area(true, &fsetxattr_failed)) {
1202 free_and_unmap_contexts();
1203 return -1;
1204 }
1205 initialized = true;
1206 return fsetxattr_failed ? -2 : 0;
1207}
Tom Cherry926ebe12015-09-23 15:34:40 -07001208
Elliott Hughesa0d374d2017-02-10 18:13:46 -08001209uint32_t __system_property_area_serial() {
Elliott Hughes9160ed92017-01-30 17:54:57 -08001210 prop_area* pa = __system_property_area__;
1211 if (!pa) {
1212 return -1;
1213 }
1214 // Make sure this read fulfilled before __system_property_serial
1215 return atomic_load_explicit(pa->serial(), memory_order_acquire);
1216}
1217
1218const prop_info* __system_property_find(const char* name) {
1219 if (!__system_property_area__) {
1220 return nullptr;
1221 }
1222
1223 prop_area* pa = get_prop_area_for_name(name);
1224 if (!pa) {
Christopher Ferris7a3681e2017-04-24 17:48:32 -07001225 async_safe_format_log(ANDROID_LOG_ERROR, "libc", "Access denied finding property \"%s\"", name);
Elliott Hughes9160ed92017-01-30 17:54:57 -08001226 return nullptr;
1227 }
1228
1229 return pa->find(name);
Narayan Kamathc9ae21a2014-02-19 17:59:05 +00001230}
1231
Tom Cherry8a311632017-10-09 13:49:17 -07001232static bool is_read_only(const char* name) {
1233 return strncmp(name, "ro.", 3) == 0;
Hans Boehm1e8587a2014-08-19 14:07:55 -07001234}
1235
Elliott Hughes9160ed92017-01-30 17:54:57 -08001236int __system_property_read(const prop_info* pi, char* name, char* value) {
1237 while (true) {
1238 uint32_t serial = __system_property_serial(pi); // acquire semantics
1239 size_t len = SERIAL_VALUE_LEN(serial);
1240 memcpy(value, pi->value, len + 1);
1241 // TODO: Fix the synchronization scheme here.
1242 // There is no fully supported way to implement this kind
1243 // of synchronization in C++11, since the memcpy races with
1244 // updates to pi, and the data being accessed is not atomic.
1245 // The following fence is unintuitive, but would be the
1246 // correct one if memcpy used memory_order_relaxed atomic accesses.
1247 // In practice it seems unlikely that the generated code would
1248 // would be any different, so this should be OK.
1249 atomic_thread_fence(memory_order_acquire);
1250 if (serial == load_const_atomic(&(pi->serial), memory_order_relaxed)) {
1251 if (name != nullptr) {
1252 size_t namelen = strlcpy(name, pi->name, PROP_NAME_MAX);
1253 if (namelen >= PROP_NAME_MAX) {
Christopher Ferris7a3681e2017-04-24 17:48:32 -07001254 async_safe_format_log(ANDROID_LOG_ERROR, "libc",
1255 "The property name length for \"%s\" is >= %d;"
1256 " please use __system_property_read_callback"
1257 " to read this property. (the name is truncated to \"%s\")",
1258 pi->name, PROP_NAME_MAX - 1, name);
Narayan Kamathc9ae21a2014-02-19 17:59:05 +00001259 }
Elliott Hughes9160ed92017-01-30 17:54:57 -08001260 }
Tom Cherry8a311632017-10-09 13:49:17 -07001261 if (is_read_only(pi->name) && pi->is_long()) {
1262 async_safe_format_log(ANDROID_LOG_ERROR, "libc",
1263 "The property \"%s\" has a value with length %zu that is too large for"
1264 " __system_property_get()/__system_property_read(); use"
1265 " __system_property_read_callback() instead.",
1266 pi->name, strlen(pi->long_value()));
1267 }
Elliott Hughes9160ed92017-01-30 17:54:57 -08001268 return len;
Narayan Kamathc9ae21a2014-02-19 17:59:05 +00001269 }
Elliott Hughes9160ed92017-01-30 17:54:57 -08001270 }
Narayan Kamathc9ae21a2014-02-19 17:59:05 +00001271}
1272
Dimitry Ivanov16b2a4d2017-01-24 20:43:29 +00001273void __system_property_read_callback(const prop_info* pi,
Elliott Hughesa0d374d2017-02-10 18:13:46 -08001274 void (*callback)(void* cookie,
1275 const char* name,
1276 const char* value,
1277 uint32_t serial),
Dimitry Ivanov16b2a4d2017-01-24 20:43:29 +00001278 void* cookie) {
Tom Cherry8a311632017-10-09 13:49:17 -07001279 // Read only properties don't need to copy the value to a temporary buffer, since it can never
1280 // change.
1281 if (is_read_only(pi->name)) {
1282 uint32_t serial = __system_property_serial(pi);
1283 if (pi->is_long()) {
1284 callback(cookie, pi->name, pi->long_value(), serial);
1285 } else {
1286 callback(cookie, pi->name, pi->value, serial);
1287 }
1288 return;
1289 }
1290
Dimitry Ivanov16b2a4d2017-01-24 20:43:29 +00001291 while (true) {
Elliott Hughes9160ed92017-01-30 17:54:57 -08001292 uint32_t serial = __system_property_serial(pi); // acquire semantics
Dimitry Ivanov16b2a4d2017-01-24 20:43:29 +00001293 size_t len = SERIAL_VALUE_LEN(serial);
Elliott Hughes9160ed92017-01-30 17:54:57 -08001294 char value_buf[len + 1];
Dimitry Ivanov16b2a4d2017-01-24 20:43:29 +00001295
1296 memcpy(value_buf, pi->value, len);
1297 value_buf[len] = '\0';
1298
1299 // TODO: see todo in __system_property_read function
1300 atomic_thread_fence(memory_order_acquire);
1301 if (serial == load_const_atomic(&(pi->serial), memory_order_relaxed)) {
Elliott Hughesa0d374d2017-02-10 18:13:46 -08001302 callback(cookie, pi->name, value_buf, serial);
Dimitry Ivanov16b2a4d2017-01-24 20:43:29 +00001303 return;
1304 }
1305 }
1306}
1307
Elliott Hughes9160ed92017-01-30 17:54:57 -08001308int __system_property_get(const char* name, char* value) {
1309 const prop_info* pi = __system_property_find(name);
Narayan Kamathc9ae21a2014-02-19 17:59:05 +00001310
Elliott Hughes9160ed92017-01-30 17:54:57 -08001311 if (pi != 0) {
1312 return __system_property_read(pi, nullptr, value);
1313 } else {
1314 value[0] = 0;
1315 return 0;
1316 }
Narayan Kamathc9ae21a2014-02-19 17:59:05 +00001317}
1318
Dimitry Ivanov16b2a4d2017-01-24 20:43:29 +00001319static constexpr uint32_t kProtocolVersion1 = 1;
Elliott Hughes9160ed92017-01-30 17:54:57 -08001320static constexpr uint32_t kProtocolVersion2 = 2; // current
Dimitry Ivanov16b2a4d2017-01-24 20:43:29 +00001321
1322static atomic_uint_least32_t g_propservice_protocol_version = 0;
1323
1324static void detect_protocol_version() {
Elliott Hughes9160ed92017-01-30 17:54:57 -08001325 char value[PROP_VALUE_MAX];
1326 if (__system_property_get(kServiceVersionPropertyName, value) == 0) {
1327 g_propservice_protocol_version = kProtocolVersion1;
Christopher Ferris7a3681e2017-04-24 17:48:32 -07001328 async_safe_format_log(ANDROID_LOG_WARN, "libc",
1329 "Using old property service protocol (\"%s\" is not set)",
1330 kServiceVersionPropertyName);
Elliott Hughes9160ed92017-01-30 17:54:57 -08001331 } else {
1332 uint32_t version = static_cast<uint32_t>(atoll(value));
1333 if (version >= kProtocolVersion2) {
1334 g_propservice_protocol_version = kProtocolVersion2;
Dimitry Ivanov16b2a4d2017-01-24 20:43:29 +00001335 } else {
Christopher Ferris7a3681e2017-04-24 17:48:32 -07001336 async_safe_format_log(ANDROID_LOG_WARN, "libc",
1337 "Using old property service protocol (\"%s\"=\"%s\")",
1338 kServiceVersionPropertyName, value);
Elliott Hughes9160ed92017-01-30 17:54:57 -08001339 g_propservice_protocol_version = kProtocolVersion1;
Dimitry Ivanov16b2a4d2017-01-24 20:43:29 +00001340 }
Elliott Hughes9160ed92017-01-30 17:54:57 -08001341 }
Dimitry Ivanov16b2a4d2017-01-24 20:43:29 +00001342}
1343
1344int __system_property_set(const char* key, const char* value) {
Elliott Hughes9160ed92017-01-30 17:54:57 -08001345 if (key == nullptr) return -1;
1346 if (value == nullptr) value = "";
Narayan Kamathc9ae21a2014-02-19 17:59:05 +00001347
Elliott Hughes9160ed92017-01-30 17:54:57 -08001348 if (g_propservice_protocol_version == 0) {
1349 detect_protocol_version();
1350 }
Narayan Kamathc9ae21a2014-02-19 17:59:05 +00001351
Elliott Hughes9160ed92017-01-30 17:54:57 -08001352 if (g_propservice_protocol_version == kProtocolVersion1) {
Tom Cherry8a311632017-10-09 13:49:17 -07001353 // Old protocol does not support long names or values
Elliott Hughes9160ed92017-01-30 17:54:57 -08001354 if (strlen(key) >= PROP_NAME_MAX) return -1;
Tom Cherry8a311632017-10-09 13:49:17 -07001355 if (strlen(value) >= PROP_VALUE_MAX) return -1;
Dimitry Ivanov16b2a4d2017-01-24 20:43:29 +00001356
Elliott Hughes9160ed92017-01-30 17:54:57 -08001357 prop_msg msg;
1358 memset(&msg, 0, sizeof msg);
1359 msg.cmd = PROP_MSG_SETPROP;
1360 strlcpy(msg.name, key, sizeof msg.name);
1361 strlcpy(msg.value, value, sizeof msg.value);
Dimitry Ivanov16b2a4d2017-01-24 20:43:29 +00001362
Dimitry Ivanov6391e1a2017-02-23 17:57:14 -08001363 return send_prop_msg(&msg);
Elliott Hughes9160ed92017-01-30 17:54:57 -08001364 } else {
Tom Cherry8a311632017-10-09 13:49:17 -07001365 // New protocol only allows long values for ro. properties only.
1366 if (strlen(value) >= PROP_VALUE_MAX && !is_read_only(key)) return -1;
Elliott Hughes9160ed92017-01-30 17:54:57 -08001367 // Use proper protocol
1368 PropertyServiceConnection connection;
Dimitry Ivanov6391e1a2017-02-23 17:57:14 -08001369 if (!connection.IsValid()) {
1370 errno = connection.GetLastError();
Christopher Ferris7a3681e2017-04-24 17:48:32 -07001371 async_safe_format_log(ANDROID_LOG_WARN,
1372 "libc",
1373 "Unable to set property \"%s\" to \"%s\": connection failed; errno=%d (%s)",
1374 key,
1375 value,
1376 errno,
1377 strerror(errno));
Dimitry Ivanov6391e1a2017-02-23 17:57:14 -08001378 return -1;
Dimitry Ivanov16b2a4d2017-01-24 20:43:29 +00001379 }
1380
Dimitry Ivanov6391e1a2017-02-23 17:57:14 -08001381 SocketWriter writer(&connection);
1382 if (!writer.WriteUint32(PROP_MSG_SETPROP2).WriteString(key).WriteString(value).Send()) {
1383 errno = connection.GetLastError();
Christopher Ferris7a3681e2017-04-24 17:48:32 -07001384 async_safe_format_log(ANDROID_LOG_WARN,
1385 "libc",
1386 "Unable to set property \"%s\" to \"%s\": write failed; errno=%d (%s)",
1387 key,
1388 value,
1389 errno,
1390 strerror(errno));
Dimitry Ivanov6391e1a2017-02-23 17:57:14 -08001391 return -1;
1392 }
1393
1394 int result = -1;
1395 if (!connection.RecvInt32(&result)) {
1396 errno = connection.GetLastError();
Christopher Ferris7a3681e2017-04-24 17:48:32 -07001397 async_safe_format_log(ANDROID_LOG_WARN,
1398 "libc",
1399 "Unable to set property \"%s\" to \"%s\": recv failed; errno=%d (%s)",
1400 key,
1401 value,
1402 errno,
1403 strerror(errno));
Dimitry Ivanov6391e1a2017-02-23 17:57:14 -08001404 return -1;
1405 }
1406
1407 if (result != PROP_SUCCESS) {
Christopher Ferris7a3681e2017-04-24 17:48:32 -07001408 async_safe_format_log(ANDROID_LOG_WARN,
1409 "libc",
1410 "Unable to set property \"%s\" to \"%s\": error code: 0x%x",
1411 key,
1412 value,
1413 result);
Dimitry Ivanov6391e1a2017-02-23 17:57:14 -08001414 return -1;
1415 }
1416
1417 return 0;
1418 }
Narayan Kamathc9ae21a2014-02-19 17:59:05 +00001419}
1420
Elliott Hughes9160ed92017-01-30 17:54:57 -08001421int __system_property_update(prop_info* pi, const char* value, unsigned int len) {
1422 if (len >= PROP_VALUE_MAX) {
1423 return -1;
1424 }
Narayan Kamathc9ae21a2014-02-19 17:59:05 +00001425
Elliott Hughes9160ed92017-01-30 17:54:57 -08001426 prop_area* pa = __system_property_area__;
Tom Cherry6ed51c02015-12-04 11:34:42 -08001427
Elliott Hughes9160ed92017-01-30 17:54:57 -08001428 if (!pa) {
1429 return -1;
1430 }
Tom Cherry6ed51c02015-12-04 11:34:42 -08001431
Elliott Hughes9160ed92017-01-30 17:54:57 -08001432 uint32_t serial = atomic_load_explicit(&pi->serial, memory_order_relaxed);
1433 serial |= 1;
1434 atomic_store_explicit(&pi->serial, serial, memory_order_relaxed);
1435 // The memcpy call here also races. Again pretend it
1436 // used memory_order_relaxed atomics, and use the analogous
1437 // counterintuitive fence.
1438 atomic_thread_fence(memory_order_release);
1439 strlcpy(pi->value, value, len + 1);
Dimitry Ivanov16b2a4d2017-01-24 20:43:29 +00001440
Elliott Hughes9160ed92017-01-30 17:54:57 -08001441 atomic_store_explicit(&pi->serial, (len << 24) | ((serial + 1) & 0xffffff), memory_order_release);
1442 __futex_wake(&pi->serial, INT32_MAX);
Narayan Kamathc9ae21a2014-02-19 17:59:05 +00001443
Elliott Hughes9160ed92017-01-30 17:54:57 -08001444 atomic_store_explicit(pa->serial(), atomic_load_explicit(pa->serial(), memory_order_relaxed) + 1,
1445 memory_order_release);
1446 __futex_wake(pa->serial(), INT32_MAX);
Narayan Kamathc9ae21a2014-02-19 17:59:05 +00001447
Elliott Hughes9160ed92017-01-30 17:54:57 -08001448 return 0;
Narayan Kamathc9ae21a2014-02-19 17:59:05 +00001449}
jiaguo879d3302014-03-13 17:39:58 +08001450
Elliott Hughes9160ed92017-01-30 17:54:57 -08001451int __system_property_add(const char* name, unsigned int namelen, const char* value,
1452 unsigned int valuelen) {
Tom Cherry8a311632017-10-09 13:49:17 -07001453 if (valuelen >= PROP_VALUE_MAX && !is_read_only(name)) {
Elliott Hughes9160ed92017-01-30 17:54:57 -08001454 return -1;
1455 }
Dimitry Ivanov16b2a4d2017-01-24 20:43:29 +00001456
Elliott Hughes9160ed92017-01-30 17:54:57 -08001457 if (namelen < 1) {
1458 return -1;
1459 }
Narayan Kamathc9ae21a2014-02-19 17:59:05 +00001460
Elliott Hughes9160ed92017-01-30 17:54:57 -08001461 if (!__system_property_area__) {
1462 return -1;
1463 }
Tom Cherry6ed51c02015-12-04 11:34:42 -08001464
Elliott Hughes9160ed92017-01-30 17:54:57 -08001465 prop_area* pa = get_prop_area_for_name(name);
Tom Cherry49a309f2015-09-23 16:09:47 -07001466
Elliott Hughes9160ed92017-01-30 17:54:57 -08001467 if (!pa) {
Christopher Ferris7a3681e2017-04-24 17:48:32 -07001468 async_safe_format_log(ANDROID_LOG_ERROR, "libc", "Access denied adding property \"%s\"", name);
Elliott Hughes9160ed92017-01-30 17:54:57 -08001469 return -1;
1470 }
Tom Cherry926ebe12015-09-23 15:34:40 -07001471
Elliott Hughes9160ed92017-01-30 17:54:57 -08001472 bool ret = pa->add(name, namelen, value, valuelen);
1473 if (!ret) {
1474 return -1;
1475 }
Narayan Kamathc9ae21a2014-02-19 17:59:05 +00001476
Elliott Hughes9160ed92017-01-30 17:54:57 -08001477 // There is only a single mutator, but we want to make sure that
1478 // updates are visible to a reader waiting for the update.
1479 atomic_store_explicit(
1480 __system_property_area__->serial(),
1481 atomic_load_explicit(__system_property_area__->serial(), memory_order_relaxed) + 1,
1482 memory_order_release);
1483 __futex_wake(__system_property_area__->serial(), INT32_MAX);
1484 return 0;
Narayan Kamathc9ae21a2014-02-19 17:59:05 +00001485}
1486
Hans Boehm30214b92014-07-31 15:53:22 -07001487// Wait for non-locked serial, and retrieve it with acquire semantics.
Elliott Hughesa0d374d2017-02-10 18:13:46 -08001488uint32_t __system_property_serial(const prop_info* pi) {
Elliott Hughes9160ed92017-01-30 17:54:57 -08001489 uint32_t serial = load_const_atomic(&pi->serial, memory_order_acquire);
1490 while (SERIAL_DIRTY(serial)) {
Elliott Hughesa0d374d2017-02-10 18:13:46 -08001491 __futex_wait(const_cast<_Atomic(uint_least32_t)*>(&pi->serial), serial, nullptr);
Elliott Hughes9160ed92017-01-30 17:54:57 -08001492 serial = load_const_atomic(&pi->serial, memory_order_acquire);
1493 }
1494 return serial;
Narayan Kamathc9ae21a2014-02-19 17:59:05 +00001495}
1496
Elliott Hughesa0d374d2017-02-10 18:13:46 -08001497uint32_t __system_property_wait_any(uint32_t old_serial) {
Elliott Hughesa0d374d2017-02-10 18:13:46 -08001498 uint32_t new_serial;
Elliott Hughes40c885a2017-02-16 17:13:04 -08001499 __system_property_wait(nullptr, old_serial, &new_serial, nullptr);
Elliott Hughesa0d374d2017-02-10 18:13:46 -08001500 return new_serial;
1501}
Elliott Hughes9160ed92017-01-30 17:54:57 -08001502
Elliott Hughes40c885a2017-02-16 17:13:04 -08001503bool __system_property_wait(const prop_info* pi,
1504 uint32_t old_serial,
1505 uint32_t* new_serial_ptr,
1506 const timespec* relative_timeout) {
1507 // Are we waiting on the global serial or a specific serial?
1508 atomic_uint_least32_t* serial_ptr;
1509 if (pi == nullptr) {
1510 if (__system_property_area__ == nullptr) return -1;
1511 serial_ptr = __system_property_area__->serial();
1512 } else {
1513 serial_ptr = const_cast<atomic_uint_least32_t*>(&pi->serial);
1514 }
1515
Elliott Hughesa0d374d2017-02-10 18:13:46 -08001516 uint32_t new_serial;
1517 do {
Elliott Hughes40c885a2017-02-16 17:13:04 -08001518 int rc;
1519 if ((rc = __futex_wait(serial_ptr, old_serial, relative_timeout)) != 0 && rc == -ETIMEDOUT) {
1520 return false;
1521 }
1522 new_serial = load_const_atomic(serial_ptr, memory_order_acquire);
Elliott Hughesa0d374d2017-02-10 18:13:46 -08001523 } while (new_serial == old_serial);
Elliott Hughes40c885a2017-02-16 17:13:04 -08001524
1525 *new_serial_ptr = new_serial;
1526 return true;
Elliott Hughes9160ed92017-01-30 17:54:57 -08001527}
1528
1529const prop_info* __system_property_find_nth(unsigned n) {
Elliott Hughes438e0192017-04-17 14:53:07 -07001530 struct find_nth {
1531 const uint32_t sought;
1532 uint32_t current;
1533 const prop_info* result;
Elliott Hughes9160ed92017-01-30 17:54:57 -08001534
Elliott Hughes438e0192017-04-17 14:53:07 -07001535 explicit find_nth(uint32_t n) : sought(n), current(0), result(nullptr) {}
1536 static void fn(const prop_info* pi, void* ptr) {
1537 find_nth* self = reinterpret_cast<find_nth*>(ptr);
1538 if (self->current++ == self->sought) self->result = pi;
1539 }
1540 } state(n);
1541 __system_property_foreach(find_nth::fn, &state);
1542 return state.result;
Elliott Hughes9160ed92017-01-30 17:54:57 -08001543}
1544
1545int __system_property_foreach(void (*propfn)(const prop_info* pi, void* cookie), void* cookie) {
1546 if (!__system_property_area__) {
1547 return -1;
1548 }
1549
1550 list_foreach(contexts, [propfn, cookie](context_node* l) {
1551 if (l->check_access_and_open()) {
Elliott Hughes438e0192017-04-17 14:53:07 -07001552 l->pa()->foreach(propfn, cookie);
Elliott Hughes9160ed92017-01-30 17:54:57 -08001553 }
1554 });
1555 return 0;
Narayan Kamathc9ae21a2014-02-19 17:59:05 +00001556}