blob: 5d13404ecf9f2bd766d4546434de48806d126629 [file] [log] [blame]
Tom Cherryfd44b9f2017-11-08 14:01:00 -08001/*
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 */
28
29#include <errno.h>
30#include <fcntl.h>
31#include <netinet/in.h>
32#include <poll.h>
33#include <stdatomic.h>
34#include <stdint.h>
35#include <stdlib.h>
36#include <string.h>
37#include <sys/select.h>
38#include <sys/socket.h>
39#include <sys/stat.h>
40#include <sys/types.h>
41#include <sys/uio.h>
42#include <sys/un.h>
43#include <unistd.h>
44
45#define _REALLY_INCLUDE_SYS__SYSTEM_PROPERTIES_H_
46#include <sys/_system_properties.h>
47#include <sys/system_properties.h>
48
49#include <async_safe/log.h>
50
51#include "private/ErrnoRestorer.h"
52#include "private/bionic_defs.h"
53#include "private/bionic_futex.h"
54#include "private/bionic_macros.h"
55#include "private/bionic_sdk_version.h"
56
57#include "context_node.h"
58#include "contexts.h"
59#include "contexts_pre_split.h"
60#include "contexts_split.h"
61#include "prop_area.h"
62#include "prop_info.h"
63#include "system_property_globals.h"
64
65// We don't want to use new or malloc in properties (b/31659220), and since these classes are
66// small enough and don't have non-trivial constructors, it's easier to just statically declare
67// them than anything else.
68static ContextsSplit contexts_split;
69static ContextsPreSplit contexts_pre_split;
70static Contexts* contexts = nullptr;
71
72#define SERIAL_DIRTY(serial) ((serial)&1)
73#define SERIAL_VALUE_LEN(serial) ((serial) >> 24)
74
75static const char property_service_socket[] = "/dev/socket/" PROP_SERVICE_NAME;
76static const char* kServiceVersionPropertyName = "ro.property_service.version";
77
78// This is public because it was exposed in the NDK. As of 2017-01, ~60 apps reference this symbol.
79__BIONIC_WEAK_VARIABLE_FOR_NATIVE_BRIDGE
80prop_area* __system_property_area__ = nullptr;
81
82char property_filename[PROP_FILENAME_MAX] = PROP_FILENAME;
83size_t pa_size;
84
85class PropertyServiceConnection {
86 public:
87 PropertyServiceConnection() : last_error_(0) {
88 socket_ = ::socket(AF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0);
89 if (socket_ == -1) {
90 last_error_ = errno;
91 return;
92 }
93
94 const size_t namelen = strlen(property_service_socket);
95 sockaddr_un addr;
96 memset(&addr, 0, sizeof(addr));
97 strlcpy(addr.sun_path, property_service_socket, sizeof(addr.sun_path));
98 addr.sun_family = AF_LOCAL;
99 socklen_t alen = namelen + offsetof(sockaddr_un, sun_path) + 1;
100
101 if (TEMP_FAILURE_RETRY(connect(socket_, reinterpret_cast<sockaddr*>(&addr), alen)) == -1) {
102 last_error_ = errno;
103 close(socket_);
104 socket_ = -1;
105 }
106 }
107
108 bool IsValid() {
109 return socket_ != -1;
110 }
111
112 int GetLastError() {
113 return last_error_;
114 }
115
116 bool RecvInt32(int32_t* value) {
117 int result = TEMP_FAILURE_RETRY(recv(socket_, value, sizeof(*value), MSG_WAITALL));
118 return CheckSendRecvResult(result, sizeof(*value));
119 }
120
121 int socket() {
122 return socket_;
123 }
124
125 ~PropertyServiceConnection() {
126 if (socket_ != -1) {
127 close(socket_);
128 }
129 }
130
131 private:
132 bool CheckSendRecvResult(int result, int expected_len) {
133 if (result == -1) {
134 last_error_ = errno;
135 } else if (result != expected_len) {
136 last_error_ = -1;
137 } else {
138 last_error_ = 0;
139 }
140
141 return last_error_ == 0;
142 }
143
144 int socket_;
145 int last_error_;
146
147 friend class SocketWriter;
148};
149
150class SocketWriter {
151 public:
152 explicit SocketWriter(PropertyServiceConnection* connection)
153 : connection_(connection), iov_index_(0), uint_buf_index_(0) {
154 }
155
156 SocketWriter& WriteUint32(uint32_t value) {
157 CHECK(uint_buf_index_ < kUintBufSize);
158 CHECK(iov_index_ < kIovSize);
159 uint32_t* ptr = uint_buf_ + uint_buf_index_;
160 uint_buf_[uint_buf_index_++] = value;
161 iov_[iov_index_].iov_base = ptr;
162 iov_[iov_index_].iov_len = sizeof(*ptr);
163 ++iov_index_;
164 return *this;
165 }
166
167 SocketWriter& WriteString(const char* value) {
168 uint32_t valuelen = strlen(value);
169 WriteUint32(valuelen);
170 if (valuelen == 0) {
171 return *this;
172 }
173
174 CHECK(iov_index_ < kIovSize);
175 iov_[iov_index_].iov_base = const_cast<char*>(value);
176 iov_[iov_index_].iov_len = valuelen;
177 ++iov_index_;
178
179 return *this;
180 }
181
182 bool Send() {
183 if (!connection_->IsValid()) {
184 return false;
185 }
186
187 if (writev(connection_->socket(), iov_, iov_index_) == -1) {
188 connection_->last_error_ = errno;
189 return false;
190 }
191
192 iov_index_ = uint_buf_index_ = 0;
193 return true;
194 }
195
196 private:
197 static constexpr size_t kUintBufSize = 8;
198 static constexpr size_t kIovSize = 8;
199
200 PropertyServiceConnection* connection_;
201 iovec iov_[kIovSize];
202 size_t iov_index_;
203 uint32_t uint_buf_[kUintBufSize];
204 size_t uint_buf_index_;
205
206 DISALLOW_IMPLICIT_CONSTRUCTORS(SocketWriter);
207};
208
209struct prop_msg {
210 unsigned cmd;
211 char name[PROP_NAME_MAX];
212 char value[PROP_VALUE_MAX];
213};
214
215static int send_prop_msg(const prop_msg* msg) {
216 PropertyServiceConnection connection;
217 if (!connection.IsValid()) {
218 return connection.GetLastError();
219 }
220
221 int result = -1;
222 int s = connection.socket();
223
224 const int num_bytes = TEMP_FAILURE_RETRY(send(s, msg, sizeof(prop_msg), 0));
225 if (num_bytes == sizeof(prop_msg)) {
226 // We successfully wrote to the property server but now we
227 // wait for the property server to finish its work. It
228 // acknowledges its completion by closing the socket so we
229 // poll here (on nothing), waiting for the socket to close.
230 // If you 'adb shell setprop foo bar' you'll see the POLLHUP
231 // once the socket closes. Out of paranoia we cap our poll
232 // at 250 ms.
233 pollfd pollfds[1];
234 pollfds[0].fd = s;
235 pollfds[0].events = 0;
236 const int poll_result = TEMP_FAILURE_RETRY(poll(pollfds, 1, 250 /* ms */));
237 if (poll_result == 1 && (pollfds[0].revents & POLLHUP) != 0) {
238 result = 0;
239 } else {
240 // Ignore the timeout and treat it like a success anyway.
241 // The init process is single-threaded and its property
242 // service is sometimes slow to respond (perhaps it's off
243 // starting a child process or something) and thus this
244 // times out and the caller thinks it failed, even though
245 // it's still getting around to it. So we fake it here,
246 // mostly for ctl.* properties, but we do try and wait 250
247 // ms so callers who do read-after-write can reliably see
248 // what they've written. Most of the time.
249 // TODO: fix the system properties design.
250 async_safe_format_log(ANDROID_LOG_WARN, "libc",
251 "Property service has timed out while trying to set \"%s\" to \"%s\"",
252 msg->name, msg->value);
253 result = 0;
254 }
255 }
256
257 return result;
258}
259
260static bool is_dir(const char* pathname) {
261 struct stat info;
262 if (stat(pathname, &info) == -1) {
263 return false;
264 }
265 return S_ISDIR(info.st_mode);
266}
267
268__BIONIC_WEAK_FOR_NATIVE_BRIDGE
269int __system_properties_init() {
270 // This is called from __libc_init_common, and should leave errno at 0 (http://b/37248982).
271 ErrnoRestorer errno_restorer;
272
273 if (contexts != nullptr) {
274 contexts->ResetAccess();
275 return 0;
276 }
277 contexts = nullptr;
278 if (is_dir(property_filename)) {
279 if (!contexts_split.Initialize(false)) {
280 return -1;
281 }
282 contexts = &contexts_split;
283 } else {
284 if (!contexts_pre_split.Initialize(false)) {
285 return -1;
286 }
287 contexts = &contexts_pre_split;
288 }
289 return 0;
290}
291
292__BIONIC_WEAK_FOR_NATIVE_BRIDGE
293int __system_property_set_filename(const char* filename) {
294 size_t len = strlen(filename);
295 if (len >= sizeof(property_filename)) return -1;
296
297 strcpy(property_filename, filename);
298 return 0;
299}
300
301__BIONIC_WEAK_FOR_NATIVE_BRIDGE
302int __system_property_area_init() {
303 if (contexts != nullptr) {
304 contexts->FreeAndUnmap();
305 }
306 // We set this unconditionally as we want tests to continue on regardless of if this failed
307 // and property_service will abort on an error condition, so no harm done.
308 contexts = &contexts_split;
309 if (!contexts_split.Initialize(true)) {
310 return -1;
311 }
312 return 0;
313}
314
315__BIONIC_WEAK_FOR_NATIVE_BRIDGE
316uint32_t __system_property_area_serial() {
317 prop_area* pa = __system_property_area__;
318 if (!pa) {
319 return -1;
320 }
321 // Make sure this read fulfilled before __system_property_serial
322 return atomic_load_explicit(pa->serial(), memory_order_acquire);
323}
324
325__BIONIC_WEAK_FOR_NATIVE_BRIDGE
326const prop_info* __system_property_find(const char* name) {
327 if (contexts == nullptr) {
328 return nullptr;
329 }
330
331 prop_area* pa = contexts->GetPropAreaForName(name);
332 if (!pa) {
333 async_safe_format_log(ANDROID_LOG_ERROR, "libc", "Access denied finding property \"%s\"", name);
334 return nullptr;
335 }
336
337 return pa->find(name);
338}
339
340static bool is_read_only(const char* name) {
341 return strncmp(name, "ro.", 3) == 0;
342}
343
344__BIONIC_WEAK_FOR_NATIVE_BRIDGE
345int __system_property_read(const prop_info* pi, char* name, char* value) {
346 while (true) {
347 uint32_t serial = __system_property_serial(pi); // acquire semantics
348 size_t len = SERIAL_VALUE_LEN(serial);
349 memcpy(value, pi->value, len + 1);
350 // TODO: Fix the synchronization scheme here.
351 // There is no fully supported way to implement this kind
352 // of synchronization in C++11, since the memcpy races with
353 // updates to pi, and the data being accessed is not atomic.
354 // The following fence is unintuitive, but would be the
355 // correct one if memcpy used memory_order_relaxed atomic accesses.
356 // In practice it seems unlikely that the generated code would
357 // would be any different, so this should be OK.
358 atomic_thread_fence(memory_order_acquire);
359 if (serial == load_const_atomic(&(pi->serial), memory_order_relaxed)) {
360 if (name != nullptr) {
361 size_t namelen = strlcpy(name, pi->name, PROP_NAME_MAX);
362 if (namelen >= PROP_NAME_MAX) {
363 async_safe_format_log(ANDROID_LOG_ERROR, "libc",
364 "The property name length for \"%s\" is >= %d;"
365 " please use __system_property_read_callback"
366 " to read this property. (the name is truncated to \"%s\")",
367 pi->name, PROP_NAME_MAX - 1, name);
368 }
369 }
370 if (is_read_only(pi->name) && pi->is_long()) {
371 async_safe_format_log(
372 ANDROID_LOG_ERROR, "libc",
373 "The property \"%s\" has a value with length %zu that is too large for"
374 " __system_property_get()/__system_property_read(); use"
375 " __system_property_read_callback() instead.",
376 pi->name, strlen(pi->long_value()));
377 }
378 return len;
379 }
380 }
381}
382
383__BIONIC_WEAK_FOR_NATIVE_BRIDGE
384void __system_property_read_callback(const prop_info* pi,
385 void (*callback)(void* cookie, const char* name,
386 const char* value, uint32_t serial),
387 void* cookie) {
388 // Read only properties don't need to copy the value to a temporary buffer, since it can never
389 // change.
390 if (is_read_only(pi->name)) {
391 uint32_t serial = __system_property_serial(pi);
392 if (pi->is_long()) {
393 callback(cookie, pi->name, pi->long_value(), serial);
394 } else {
395 callback(cookie, pi->name, pi->value, serial);
396 }
397 return;
398 }
399
400 while (true) {
401 uint32_t serial = __system_property_serial(pi); // acquire semantics
402 size_t len = SERIAL_VALUE_LEN(serial);
403 char value_buf[len + 1];
404
405 memcpy(value_buf, pi->value, len);
406 value_buf[len] = '\0';
407
408 // TODO: see todo in __system_property_read function
409 atomic_thread_fence(memory_order_acquire);
410 if (serial == load_const_atomic(&(pi->serial), memory_order_relaxed)) {
411 callback(cookie, pi->name, value_buf, serial);
412 return;
413 }
414 }
415}
416
417__BIONIC_WEAK_FOR_NATIVE_BRIDGE
418int __system_property_get(const char* name, char* value) {
419 const prop_info* pi = __system_property_find(name);
420
421 if (pi != 0) {
422 return __system_property_read(pi, nullptr, value);
423 } else {
424 value[0] = 0;
425 return 0;
426 }
427}
428
429static constexpr uint32_t kProtocolVersion1 = 1;
430static constexpr uint32_t kProtocolVersion2 = 2; // current
431
432static atomic_uint_least32_t g_propservice_protocol_version = 0;
433
434static void detect_protocol_version() {
435 char value[PROP_VALUE_MAX];
436 if (__system_property_get(kServiceVersionPropertyName, value) == 0) {
437 g_propservice_protocol_version = kProtocolVersion1;
438 async_safe_format_log(ANDROID_LOG_WARN, "libc",
439 "Using old property service protocol (\"%s\" is not set)",
440 kServiceVersionPropertyName);
441 } else {
442 uint32_t version = static_cast<uint32_t>(atoll(value));
443 if (version >= kProtocolVersion2) {
444 g_propservice_protocol_version = kProtocolVersion2;
445 } else {
446 async_safe_format_log(ANDROID_LOG_WARN, "libc",
447 "Using old property service protocol (\"%s\"=\"%s\")",
448 kServiceVersionPropertyName, value);
449 g_propservice_protocol_version = kProtocolVersion1;
450 }
451 }
452}
453
454__BIONIC_WEAK_FOR_NATIVE_BRIDGE
455int __system_property_set(const char* key, const char* value) {
456 if (key == nullptr) return -1;
457 if (value == nullptr) value = "";
458
459 if (g_propservice_protocol_version == 0) {
460 detect_protocol_version();
461 }
462
463 if (g_propservice_protocol_version == kProtocolVersion1) {
464 // Old protocol does not support long names or values
465 if (strlen(key) >= PROP_NAME_MAX) return -1;
466 if (strlen(value) >= PROP_VALUE_MAX) return -1;
467
468 prop_msg msg;
469 memset(&msg, 0, sizeof msg);
470 msg.cmd = PROP_MSG_SETPROP;
471 strlcpy(msg.name, key, sizeof msg.name);
472 strlcpy(msg.value, value, sizeof msg.value);
473
474 return send_prop_msg(&msg);
475 } else {
476 // New protocol only allows long values for ro. properties only.
477 if (strlen(value) >= PROP_VALUE_MAX && !is_read_only(key)) return -1;
478 // Use proper protocol
479 PropertyServiceConnection connection;
480 if (!connection.IsValid()) {
481 errno = connection.GetLastError();
482 async_safe_format_log(
483 ANDROID_LOG_WARN, "libc",
484 "Unable to set property \"%s\" to \"%s\": connection failed; errno=%d (%s)", key, value,
485 errno, strerror(errno));
486 return -1;
487 }
488
489 SocketWriter writer(&connection);
490 if (!writer.WriteUint32(PROP_MSG_SETPROP2).WriteString(key).WriteString(value).Send()) {
491 errno = connection.GetLastError();
492 async_safe_format_log(ANDROID_LOG_WARN, "libc",
493 "Unable to set property \"%s\" to \"%s\": write failed; errno=%d (%s)",
494 key, value, errno, strerror(errno));
495 return -1;
496 }
497
498 int result = -1;
499 if (!connection.RecvInt32(&result)) {
500 errno = connection.GetLastError();
501 async_safe_format_log(ANDROID_LOG_WARN, "libc",
502 "Unable to set property \"%s\" to \"%s\": recv failed; errno=%d (%s)",
503 key, value, errno, strerror(errno));
504 return -1;
505 }
506
507 if (result != PROP_SUCCESS) {
508 async_safe_format_log(ANDROID_LOG_WARN, "libc",
509 "Unable to set property \"%s\" to \"%s\": error code: 0x%x", key, value,
510 result);
511 return -1;
512 }
513
514 return 0;
515 }
516}
517
518__BIONIC_WEAK_FOR_NATIVE_BRIDGE
519int __system_property_update(prop_info* pi, const char* value, unsigned int len) {
520 if (len >= PROP_VALUE_MAX) {
521 return -1;
522 }
523
524 prop_area* pa = __system_property_area__;
525
526 if (!pa) {
527 return -1;
528 }
529
530 uint32_t serial = atomic_load_explicit(&pi->serial, memory_order_relaxed);
531 serial |= 1;
532 atomic_store_explicit(&pi->serial, serial, memory_order_relaxed);
533 // The memcpy call here also races. Again pretend it
534 // used memory_order_relaxed atomics, and use the analogous
535 // counterintuitive fence.
536 atomic_thread_fence(memory_order_release);
537 strlcpy(pi->value, value, len + 1);
538
539 atomic_store_explicit(&pi->serial, (len << 24) | ((serial + 1) & 0xffffff), memory_order_release);
540 __futex_wake(&pi->serial, INT32_MAX);
541
542 atomic_store_explicit(pa->serial(), atomic_load_explicit(pa->serial(), memory_order_relaxed) + 1,
543 memory_order_release);
544 __futex_wake(pa->serial(), INT32_MAX);
545
546 return 0;
547}
548
549__BIONIC_WEAK_FOR_NATIVE_BRIDGE
550int __system_property_add(const char* name, unsigned int namelen, const char* value,
551 unsigned int valuelen) {
552 if (valuelen >= PROP_VALUE_MAX && !is_read_only(name)) {
553 return -1;
554 }
555
556 if (namelen < 1) {
557 return -1;
558 }
559
560 if (__system_property_area__ == nullptr || contexts == nullptr) {
561 return -1;
562 }
563
564 prop_area* pa = contexts->GetPropAreaForName(name);
565
566 if (!pa) {
567 async_safe_format_log(ANDROID_LOG_ERROR, "libc", "Access denied adding property \"%s\"", name);
568 return -1;
569 }
570
571 bool ret = pa->add(name, namelen, value, valuelen);
572 if (!ret) {
573 return -1;
574 }
575
576 // There is only a single mutator, but we want to make sure that
577 // updates are visible to a reader waiting for the update.
578 atomic_store_explicit(
579 __system_property_area__->serial(),
580 atomic_load_explicit(__system_property_area__->serial(), memory_order_relaxed) + 1,
581 memory_order_release);
582 __futex_wake(__system_property_area__->serial(), INT32_MAX);
583 return 0;
584}
585
586// Wait for non-locked serial, and retrieve it with acquire semantics.
587__BIONIC_WEAK_FOR_NATIVE_BRIDGE
588uint32_t __system_property_serial(const prop_info* pi) {
589 uint32_t serial = load_const_atomic(&pi->serial, memory_order_acquire);
590 while (SERIAL_DIRTY(serial)) {
591 __futex_wait(const_cast<_Atomic(uint_least32_t)*>(&pi->serial), serial, nullptr);
592 serial = load_const_atomic(&pi->serial, memory_order_acquire);
593 }
594 return serial;
595}
596
597__BIONIC_WEAK_FOR_NATIVE_BRIDGE
598uint32_t __system_property_wait_any(uint32_t old_serial) {
599 uint32_t new_serial;
600 __system_property_wait(nullptr, old_serial, &new_serial, nullptr);
601 return new_serial;
602}
603
604__BIONIC_WEAK_FOR_NATIVE_BRIDGE
605bool __system_property_wait(const prop_info* pi, uint32_t old_serial, uint32_t* new_serial_ptr,
606 const timespec* relative_timeout) {
607 // Are we waiting on the global serial or a specific serial?
608 atomic_uint_least32_t* serial_ptr;
609 if (pi == nullptr) {
610 if (__system_property_area__ == nullptr) return -1;
611 serial_ptr = __system_property_area__->serial();
612 } else {
613 serial_ptr = const_cast<atomic_uint_least32_t*>(&pi->serial);
614 }
615
616 uint32_t new_serial;
617 do {
618 int rc;
619 if ((rc = __futex_wait(serial_ptr, old_serial, relative_timeout)) != 0 && rc == -ETIMEDOUT) {
620 return false;
621 }
622 new_serial = load_const_atomic(serial_ptr, memory_order_acquire);
623 } while (new_serial == old_serial);
624
625 *new_serial_ptr = new_serial;
626 return true;
627}
628
629__BIONIC_WEAK_FOR_NATIVE_BRIDGE
630const prop_info* __system_property_find_nth(unsigned n) {
631 struct find_nth {
632 const uint32_t sought;
633 uint32_t current;
634 const prop_info* result;
635
636 explicit find_nth(uint32_t n) : sought(n), current(0), result(nullptr) {
637 }
638 static void fn(const prop_info* pi, void* ptr) {
639 find_nth* self = reinterpret_cast<find_nth*>(ptr);
640 if (self->current++ == self->sought) self->result = pi;
641 }
642 } state(n);
643 __system_property_foreach(find_nth::fn, &state);
644 return state.result;
645}
646
647__BIONIC_WEAK_FOR_NATIVE_BRIDGE
648int __system_property_foreach(void (*propfn)(const prop_info* pi, void* cookie), void* cookie) {
649 if (contexts == nullptr) {
650 return -1;
651 }
652
653 contexts->ForEach(propfn, cookie);
654
655 return 0;
656}