blob: e7f724b8fc20808274c8a9d2d777768a172556db [file] [log] [blame]
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Tom Cherry3f5eaae52017-04-06 16:30:22 -070017#include "util.h"
18
Mark Salyzyn62767fe2016-10-27 07:45:34 -070019#include <ctype.h>
20#include <errno.h>
21#include <fcntl.h>
Mark Salyzyn62767fe2016-10-27 07:45:34 -070022#include <pwd.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080023#include <stdarg.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080024#include <stdio.h>
Tom Cherry3f5eaae52017-04-06 16:30:22 -070025#include <stdlib.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080026#include <string.h>
Tom Cherry3f5eaae52017-04-06 16:30:22 -070027#include <sys/socket.h>
28#include <sys/un.h>
Colin Cross504bc512010-04-13 19:35:09 -070029#include <time.h>
Mark Salyzyn62767fe2016-10-27 07:45:34 -070030#include <unistd.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080031
Elliott Hughes290a2282016-11-14 17:08:47 -080032#include <thread>
33
Elliott Hughes4f713192015-12-04 22:00:26 -080034#include <android-base/file.h>
Elliott Hughesf86b5a62016-06-24 15:12:21 -070035#include <android-base/logging.h>
Tom Cherryccf23532017-03-28 16:40:41 -070036#include <android-base/properties.h>
Mark Salyzyn62767fe2016-10-27 07:45:34 -070037#include <android-base/stringprintf.h>
Elliott Hughes4f713192015-12-04 22:00:26 -080038#include <android-base/strings.h>
Mark Salyzyndb691072016-11-07 10:16:53 -080039#include <android-base/unique_fd.h>
Elliott Hughes331cf2f2016-11-29 19:20:58 +000040#include <cutils/android_reboot.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080041#include <cutils/sockets.h>
Tom Cherry3f5eaae52017-04-06 16:30:22 -070042#include <selinux/android.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080043
Keun-young Park8d01f632017-03-13 11:54:47 -070044#include "reboot.h"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080045
Tom Cherrye7656b72017-05-01 17:10:09 -070046#ifdef _INIT_INIT_H
47#error "Do not include init.h in files used by ueventd or watchdogd; it will expose init's globals"
48#endif
49
James Hawkinse78ea772017-03-24 11:43:02 -070050using android::base::boot_clock;
Tom Cherry517e1f12017-05-04 17:40:33 -070051using namespace std::literals::string_literals;
James Hawkinse78ea772017-03-24 11:43:02 -070052
Tom Cherry517e1f12017-05-04 17:40:33 -070053// DecodeUid() - decodes and returns the given string, which can be either the
54// numeric or name representation, into the integer uid or gid. Returns
55// UINT_MAX on error.
56bool DecodeUid(const std::string& name, uid_t* uid, std::string* err) {
57 *uid = UINT_MAX;
58 *err = "";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080059
Tom Cherry517e1f12017-05-04 17:40:33 -070060 if (isalpha(name[0])) {
61 passwd* pwd = getpwnam(name.c_str());
62 if (!pwd) {
63 *err = "getpwnam failed: "s + strerror(errno);
64 return false;
65 }
66 *uid = pwd->pw_uid;
67 return true;
William Roberts3792e6c2016-04-06 19:18:50 -070068 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080069
70 errno = 0;
Tom Cherry517e1f12017-05-04 17:40:33 -070071 uid_t result = static_cast<uid_t>(strtoul(name.c_str(), 0, 0));
72 if (errno) {
73 *err = "strtoul failed: "s + strerror(errno);
74 return false;
Nick Kralevichd2104df2015-06-18 17:46:54 -070075 }
Tom Cherry517e1f12017-05-04 17:40:33 -070076 *uid = result;
77 return true;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080078}
79
80/*
81 * create_socket - creates a Unix domain socket in ANDROID_SOCKET_DIR
82 * ("/dev/socket") as dictated in init.rc. This socket is inherited by the
83 * daemon. We communicate the file descriptor's value via the environment
84 * variable ANDROID_SOCKET_ENV_PREFIX<name> ("ANDROID_SOCKET_foo").
85 */
Tom Cherrye7656b72017-05-01 17:10:09 -070086int create_socket(const char* name, int type, mode_t perm, uid_t uid, gid_t gid,
87 const char* socketcon, selabel_handle* sehandle) {
Nick Kralevich83ccb1c2015-11-23 16:26:42 -080088 if (socketcon) {
89 if (setsockcreatecon(socketcon) == -1) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -070090 PLOG(ERROR) << "setsockcreatecon(\"" << socketcon << "\") failed";
Nick Kralevich83ccb1c2015-11-23 16:26:42 -080091 return -1;
92 }
93 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080094
Mark Salyzyndb691072016-11-07 10:16:53 -080095 android::base::unique_fd fd(socket(PF_UNIX, type, 0));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080096 if (fd < 0) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -070097 PLOG(ERROR) << "Failed to open socket '" << name << "'";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080098 return -1;
99 }
100
Mark Salyzyndb691072016-11-07 10:16:53 -0800101 if (socketcon) setsockcreatecon(NULL);
Stephen Smalley8348d272013-05-13 12:37:04 -0400102
Mark Salyzyndb691072016-11-07 10:16:53 -0800103 struct sockaddr_un addr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800104 memset(&addr, 0 , sizeof(addr));
105 addr.sun_family = AF_UNIX;
106 snprintf(addr.sun_path, sizeof(addr.sun_path), ANDROID_SOCKET_DIR"/%s",
107 name);
108
Mark Salyzyndb691072016-11-07 10:16:53 -0800109 if ((unlink(addr.sun_path) != 0) && (errno != ENOENT)) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700110 PLOG(ERROR) << "Failed to unlink old socket '" << name << "'";
Mark Salyzyndb691072016-11-07 10:16:53 -0800111 return -1;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800112 }
113
Mark Salyzyndb691072016-11-07 10:16:53 -0800114 char *filecon = NULL;
Stephen Smalleye46f9d52012-01-13 08:48:47 -0500115 if (sehandle) {
Mark Salyzyndb691072016-11-07 10:16:53 -0800116 if (selabel_lookup(sehandle, &filecon, addr.sun_path, S_IFSOCK) == 0) {
Stephen Smalley8348d272013-05-13 12:37:04 -0400117 setfscreatecon(filecon);
Mark Salyzyndb691072016-11-07 10:16:53 -0800118 }
Stephen Smalleye46f9d52012-01-13 08:48:47 -0500119 }
Stephen Smalleye46f9d52012-01-13 08:48:47 -0500120
Mark Salyzyndb691072016-11-07 10:16:53 -0800121 int ret = bind(fd, (struct sockaddr *) &addr, sizeof (addr));
122 int savederrno = errno;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800123
Stephen Smalleye46f9d52012-01-13 08:48:47 -0500124 setfscreatecon(NULL);
Stephen Smalley8348d272013-05-13 12:37:04 -0400125 freecon(filecon);
Stephen Smalleye46f9d52012-01-13 08:48:47 -0500126
Nick Kralevich9bcfd642016-02-24 15:50:52 -0800127 if (ret) {
Mark Salyzyndb691072016-11-07 10:16:53 -0800128 errno = savederrno;
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700129 PLOG(ERROR) << "Failed to bind socket '" << name << "'";
Nick Kralevich9bcfd642016-02-24 15:50:52 -0800130 goto out_unlink;
131 }
132
Mark Salyzyndb691072016-11-07 10:16:53 -0800133 if (lchown(addr.sun_path, uid, gid)) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700134 PLOG(ERROR) << "Failed to lchown socket '" << addr.sun_path << "'";
Nick Kralevich9bcfd642016-02-24 15:50:52 -0800135 goto out_unlink;
136 }
Mark Salyzyndb691072016-11-07 10:16:53 -0800137 if (fchmodat(AT_FDCWD, addr.sun_path, perm, AT_SYMLINK_NOFOLLOW)) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700138 PLOG(ERROR) << "Failed to fchmodat socket '" << addr.sun_path << "'";
Nick Kralevich9bcfd642016-02-24 15:50:52 -0800139 goto out_unlink;
140 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800141
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700142 LOG(INFO) << "Created socket '" << addr.sun_path << "'"
143 << ", mode " << std::oct << perm << std::dec
144 << ", user " << uid
145 << ", group " << gid;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800146
Mark Salyzyndb691072016-11-07 10:16:53 -0800147 return fd.release();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800148
149out_unlink:
150 unlink(addr.sun_path);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800151 return -1;
152}
153
Tom Cherry2cbbe9f2017-05-04 18:17:33 -0700154bool ReadFile(const std::string& path, std::string* content, std::string* err) {
Elliott Hughesf682b472015-02-06 12:19:48 -0800155 content->clear();
Tom Cherry2cbbe9f2017-05-04 18:17:33 -0700156 *err = "";
Elliott Hughesf682b472015-02-06 12:19:48 -0800157
Tom Cherry53089aa2017-03-31 15:47:33 -0700158 android::base::unique_fd fd(
159 TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC)));
Elliott Hughesf682b472015-02-06 12:19:48 -0800160 if (fd == -1) {
Tom Cherry2cbbe9f2017-05-04 18:17:33 -0700161 *err = "Unable to open '" + path + "': " + strerror(errno);
Elliott Hughesf682b472015-02-06 12:19:48 -0800162 return false;
163 }
164
165 // For security reasons, disallow world-writable
166 // or group-writable files.
Nick Kralevich38f368c2012-01-18 10:39:01 -0800167 struct stat sb;
Elliott Hughesf682b472015-02-06 12:19:48 -0800168 if (fstat(fd, &sb) == -1) {
Tom Cherry2cbbe9f2017-05-04 18:17:33 -0700169 *err = "fstat failed for '" + path + "': " + strerror(errno);
Elliott Hughesf682b472015-02-06 12:19:48 -0800170 return false;
Nick Kralevich38f368c2012-01-18 10:39:01 -0800171 }
172 if ((sb.st_mode & (S_IWGRP | S_IWOTH)) != 0) {
Tom Cherry2cbbe9f2017-05-04 18:17:33 -0700173 *err = "Skipping insecure file '" + path + "'";
Elliott Hughesf682b472015-02-06 12:19:48 -0800174 return false;
Nick Kralevich38f368c2012-01-18 10:39:01 -0800175 }
176
Tom Cherry2cbbe9f2017-05-04 18:17:33 -0700177 if (!android::base::ReadFdToString(fd, content)) {
178 *err = "Unable to read '" + path + "': " + strerror(errno);
179 return false;
180 }
181 return true;
Elliott Hughesf682b472015-02-06 12:19:48 -0800182}
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800183
Tom Cherry2cbbe9f2017-05-04 18:17:33 -0700184bool WriteFile(const std::string& path, const std::string& content, std::string* err) {
185 *err = "";
186
Yongqin Liudbe88e72016-12-28 16:06:19 +0800187 android::base::unique_fd fd(TEMP_FAILURE_RETRY(
188 open(path.c_str(), O_WRONLY | O_CREAT | O_NOFOLLOW | O_TRUNC | O_CLOEXEC, 0600)));
Elliott Hughesf682b472015-02-06 12:19:48 -0800189 if (fd == -1) {
Tom Cherry2cbbe9f2017-05-04 18:17:33 -0700190 *err = "Unable to open '" + path + "': " + strerror(errno);
Jorge Lucangeli Obes77f0e9f2016-12-28 14:07:02 -0500191 return false;
Elliott Hughesf682b472015-02-06 12:19:48 -0800192 }
Tom Cherry2cbbe9f2017-05-04 18:17:33 -0700193 if (!android::base::WriteStringToFd(content, fd)) {
194 *err = "Unable to write to '" + path + "': " + strerror(errno);
195 return false;
Nick Kralevicheedbe812015-04-25 14:10:03 -0700196 }
Tom Cherry2cbbe9f2017-05-04 18:17:33 -0700197 return true;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800198}
199
Tom Cherrye7656b72017-05-01 17:10:09 -0700200int mkdir_recursive(const std::string& path, mode_t mode, selabel_handle* sehandle) {
Tom Cherry060b74b2017-04-12 14:27:51 -0700201 std::string::size_type slash = 0;
202 while ((slash = path.find('/', slash + 1)) != std::string::npos) {
203 auto directory = path.substr(0, slash);
204 struct stat info;
205 if (stat(directory.c_str(), &info) != 0) {
Tom Cherrye7656b72017-05-01 17:10:09 -0700206 auto ret = make_dir(directory.c_str(), mode, sehandle);
Tom Cherry060b74b2017-04-12 14:27:51 -0700207 if (ret && errno != EEXIST) return ret;
Colin Crossb0ab94b2010-04-08 16:16:20 -0700208 }
209 }
Tom Cherrye7656b72017-05-01 17:10:09 -0700210 auto ret = make_dir(path.c_str(), mode, sehandle);
Tom Cherry060b74b2017-04-12 14:27:51 -0700211 if (ret && errno != EEXIST) return ret;
Colin Crossb0ab94b2010-04-08 16:16:20 -0700212 return 0;
213}
214
Elliott Hughes9605a942016-11-10 17:43:47 -0800215int wait_for_file(const char* filename, std::chrono::nanoseconds timeout) {
216 boot_clock::time_point timeout_time = boot_clock::now() + timeout;
217 while (boot_clock::now() < timeout_time) {
218 struct stat sb;
219 if (stat(filename, &sb) != -1) return 0;
Colin Crosscd0f1732010-04-19 17:10:24 -0700220
Elliott Hughes290a2282016-11-14 17:08:47 -0800221 std::this_thread::sleep_for(10ms);
Elliott Hughes9605a942016-11-10 17:43:47 -0800222 }
223 return -1;
Colin Crosscd0f1732010-04-19 17:10:24 -0700224}
Colin Crossf83d0b92010-04-21 12:04:20 -0700225
Elliott Hughese5ce30f2015-05-06 19:19:24 -0700226void import_kernel_cmdline(bool in_qemu,
Chih-Hung Hsieh8f7b9e32016-07-27 16:25:51 -0700227 const std::function<void(const std::string&, const std::string&, bool)>& fn) {
Elliott Hughese5ce30f2015-05-06 19:19:24 -0700228 std::string cmdline;
229 android::base::ReadFileToString("/proc/cmdline", &cmdline);
Vladimir Chtchetkine2b995432011-09-28 09:55:31 -0700230
Elliott Hughese5ce30f2015-05-06 19:19:24 -0700231 for (const auto& entry : android::base::Split(android::base::Trim(cmdline), " ")) {
232 std::vector<std::string> pieces = android::base::Split(entry, "=");
233 if (pieces.size() == 2) {
234 fn(pieces[0], pieces[1], in_qemu);
235 }
Vladimir Chtchetkine2b995432011-09-28 09:55:31 -0700236 }
237}
Stephen Smalleye096e362012-06-11 13:37:39 -0400238
Tom Cherrye7656b72017-05-01 17:10:09 -0700239int make_dir(const char* path, mode_t mode, selabel_handle* sehandle) {
Stephen Smalleye096e362012-06-11 13:37:39 -0400240 int rc;
241
Stephen Smalleye096e362012-06-11 13:37:39 -0400242 char *secontext = NULL;
243
244 if (sehandle) {
245 selabel_lookup(sehandle, &secontext, path, mode);
246 setfscreatecon(secontext);
247 }
Stephen Smalleye096e362012-06-11 13:37:39 -0400248
249 rc = mkdir(path, mode);
250
Stephen Smalleye096e362012-06-11 13:37:39 -0400251 if (secontext) {
252 int save_errno = errno;
253 freecon(secontext);
254 setfscreatecon(NULL);
255 errno = save_errno;
256 }
Kenny Rootb5982bf2012-10-16 23:07:05 -0700257
Stephen Smalleye096e362012-06-11 13:37:39 -0400258 return rc;
259}
260
Paul Lawrencea8d84342016-11-14 15:40:18 -0800261int restorecon(const char* pathname, int flags)
Stephen Smalleye096e362012-06-11 13:37:39 -0400262{
Paul Lawrencea8d84342016-11-14 15:40:18 -0800263 return selinux_android_restorecon(pathname, flags);
Jeff Sharkeyd1d3bdd2016-07-15 16:21:34 -0600264}
265
Andres Moralesdb5f5d42015-05-08 08:30:33 -0700266/*
267 * Writes hex_len hex characters (1/2 byte) to hex from bytes.
268 */
269std::string bytes_to_hex(const uint8_t* bytes, size_t bytes_len) {
270 std::string hex("0x");
271 for (size_t i = 0; i < bytes_len; i++)
272 android::base::StringAppendF(&hex, "%02x", bytes[i]);
273 return hex;
274}
Lee Campbellf13b1b32015-07-24 16:57:14 -0700275
276/*
277 * Returns true is pathname is a directory
278 */
279bool is_dir(const char* pathname) {
280 struct stat info;
281 if (stat(pathname, &info) == -1) {
282 return false;
283 }
284 return S_ISDIR(info.st_mode);
285}
Tom Cherryb7349902015-08-26 11:43:36 -0700286
287bool expand_props(const std::string& src, std::string* dst) {
288 const char* src_ptr = src.c_str();
289
290 if (!dst) {
291 return false;
292 }
293
294 /* - variables can either be $x.y or ${x.y}, in case they are only part
295 * of the string.
296 * - will accept $$ as a literal $.
297 * - no nested property expansion, i.e. ${foo.${bar}} is not supported,
298 * bad things will happen
Mark Salyzyn4b561622016-06-07 08:49:01 -0700299 * - ${x.y:-default} will return default value if property empty.
Tom Cherryb7349902015-08-26 11:43:36 -0700300 */
301 while (*src_ptr) {
302 const char* c;
303
304 c = strchr(src_ptr, '$');
305 if (!c) {
306 dst->append(src_ptr);
307 return true;
308 }
309
310 dst->append(src_ptr, c);
311 c++;
312
313 if (*c == '$') {
314 dst->push_back(*(c++));
315 src_ptr = c;
316 continue;
317 } else if (*c == '\0') {
318 return true;
319 }
320
321 std::string prop_name;
Mark Salyzyn4b561622016-06-07 08:49:01 -0700322 std::string def_val;
Tom Cherryb7349902015-08-26 11:43:36 -0700323 if (*c == '{') {
324 c++;
325 const char* end = strchr(c, '}');
326 if (!end) {
327 // failed to find closing brace, abort.
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700328 LOG(ERROR) << "unexpected end of string in '" << src << "', looking for }";
Tom Cherryb7349902015-08-26 11:43:36 -0700329 return false;
330 }
331 prop_name = std::string(c, end);
332 c = end + 1;
Mark Salyzyn4b561622016-06-07 08:49:01 -0700333 size_t def = prop_name.find(":-");
334 if (def < prop_name.size()) {
335 def_val = prop_name.substr(def + 2);
336 prop_name = prop_name.substr(0, def);
337 }
Tom Cherryb7349902015-08-26 11:43:36 -0700338 } else {
339 prop_name = c;
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700340 LOG(ERROR) << "using deprecated syntax for specifying property '" << c << "', use ${name} instead";
Tom Cherryb7349902015-08-26 11:43:36 -0700341 c += prop_name.size();
342 }
343
344 if (prop_name.empty()) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700345 LOG(ERROR) << "invalid zero-length property name in '" << src << "'";
Tom Cherryb7349902015-08-26 11:43:36 -0700346 return false;
347 }
348
Tom Cherryccf23532017-03-28 16:40:41 -0700349 std::string prop_val = android::base::GetProperty(prop_name, "");
Tom Cherryb7349902015-08-26 11:43:36 -0700350 if (prop_val.empty()) {
Mark Salyzyn4b561622016-06-07 08:49:01 -0700351 if (def_val.empty()) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700352 LOG(ERROR) << "property '" << prop_name << "' doesn't exist while expanding '" << src << "'";
Mark Salyzyn4b561622016-06-07 08:49:01 -0700353 return false;
354 }
355 prop_val = def_val;
Tom Cherryb7349902015-08-26 11:43:36 -0700356 }
357
358 dst->append(prop_val);
359 src_ptr = c;
360 }
361
362 return true;
363}
Elliott Hughes331cf2f2016-11-29 19:20:58 +0000364
Elliott Hughes331cf2f2016-11-29 19:20:58 +0000365void panic() {
366 LOG(ERROR) << "panic: rebooting to bootloader";
Keun-young Park8d01f632017-03-13 11:54:47 -0700367 DoReboot(ANDROID_RB_RESTART2, "reboot", "bootloader", false);
Elliott Hughes331cf2f2016-11-29 19:20:58 +0000368}
369
370std::ostream& operator<<(std::ostream& os, const Timer& t) {
371 os << t.duration_s() << " seconds";
372 return os;
373}
Bowgo Tsaid2620172017-04-17 22:17:09 +0800374
375// Reads the content of device tree file under kAndroidDtDir directory.
376// Returns true if the read is success, false otherwise.
377bool read_android_dt_file(const std::string& sub_path, std::string* dt_content) {
378 const std::string file_name = kAndroidDtDir + sub_path;
379 if (android::base::ReadFileToString(file_name, dt_content)) {
380 if (!dt_content->empty()) {
381 dt_content->pop_back(); // Trims the trailing '\0' out.
382 return true;
383 }
384 }
385 return false;
386}
387
388bool is_android_dt_value_expected(const std::string& sub_path, const std::string& expected_content) {
389 std::string dt_content;
390 if (read_android_dt_file(sub_path, &dt_content)) {
391 if (dt_content == expected_content) {
392 return true;
393 }
394 }
395 return false;
396}