1 /* 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 17 #include <ctype.h> 18 #include <errno.h> 19 #include <fcntl.h> 20 #include <ftw.h> 21 #include <pwd.h> 22 #include <stdarg.h> 23 #include <stdlib.h> 24 #include <stdio.h> 25 #include <string.h> 26 #include <time.h> 27 #include <unistd.h> 28 29 #include <selinux/android.h> 30 #include <selinux/label.h> 31 32 #include <sys/socket.h> 33 #include <sys/stat.h> 34 #include <sys/types.h> 35 #include <sys/un.h> 36 37 #include <thread> 38 39 #include <android-base/file.h> 40 #include <android-base/logging.h> 41 #include <android-base/properties.h> 42 #include <android-base/stringprintf.h> 43 #include <android-base/strings.h> 44 #include <android-base/unique_fd.h> 45 46 #include <cutils/android_reboot.h> 47 /* for ANDROID_SOCKET_* */ 48 #include <cutils/sockets.h> 49 50 #include "init.h" 51 #include "log.h" 52 #include "reboot.h" 53 #include "util.h" 54 55 static unsigned int do_decode_uid(const char *s) 56 { 57 unsigned int v; 58 59 if (!s || *s == '\0') 60 return UINT_MAX; 61 62 if (isalpha(s[0])) { 63 struct passwd* pwd = getpwnam(s); 64 if (!pwd) 65 return UINT_MAX; 66 return pwd->pw_uid; 67 } 68 69 errno = 0; 70 v = (unsigned int) strtoul(s, 0, 0); 71 if (errno) 72 return UINT_MAX; 73 return v; 74 } 75 76 /* 77 * decode_uid - decodes and returns the given string, which can be either the 78 * numeric or name representation, into the integer uid or gid. Returns 79 * UINT_MAX on error. 80 */ 81 unsigned int decode_uid(const char *s) { 82 unsigned int v = do_decode_uid(s); 83 if (v == UINT_MAX) { 84 LOG(ERROR) << "decode_uid: Unable to find UID for '" << s << "'; returning UINT_MAX"; 85 } 86 return v; 87 } 88 89 /* 90 * create_socket - creates a Unix domain socket in ANDROID_SOCKET_DIR 91 * ("/dev/socket") as dictated in init.rc. This socket is inherited by the 92 * daemon. We communicate the file descriptor's value via the environment 93 * variable ANDROID_SOCKET_ENV_PREFIX<name> ("ANDROID_SOCKET_foo"). 94 */ 95 int create_socket(const char *name, int type, mode_t perm, uid_t uid, 96 gid_t gid, const char *socketcon) 97 { 98 if (socketcon) { 99 if (setsockcreatecon(socketcon) == -1) { 100 PLOG(ERROR) << "setsockcreatecon(\"" << socketcon << "\") failed"; 101 return -1; 102 } 103 } 104 105 android::base::unique_fd fd(socket(PF_UNIX, type, 0)); 106 if (fd < 0) { 107 PLOG(ERROR) << "Failed to open socket '" << name << "'"; 108 return -1; 109 } 110 111 if (socketcon) setsockcreatecon(NULL); 112 113 struct sockaddr_un addr; 114 memset(&addr, 0 , sizeof(addr)); 115 addr.sun_family = AF_UNIX; 116 snprintf(addr.sun_path, sizeof(addr.sun_path), ANDROID_SOCKET_DIR"/%s", 117 name); 118 119 if ((unlink(addr.sun_path) != 0) && (errno != ENOENT)) { 120 PLOG(ERROR) << "Failed to unlink old socket '" << name << "'"; 121 return -1; 122 } 123 124 char *filecon = NULL; 125 if (sehandle) { 126 if (selabel_lookup(sehandle, &filecon, addr.sun_path, S_IFSOCK) == 0) { 127 setfscreatecon(filecon); 128 } 129 } 130 131 int ret = bind(fd, (struct sockaddr *) &addr, sizeof (addr)); 132 int savederrno = errno; 133 134 setfscreatecon(NULL); 135 freecon(filecon); 136 137 if (ret) { 138 errno = savederrno; 139 PLOG(ERROR) << "Failed to bind socket '" << name << "'"; 140 goto out_unlink; 141 } 142 143 if (lchown(addr.sun_path, uid, gid)) { 144 PLOG(ERROR) << "Failed to lchown socket '" << addr.sun_path << "'"; 145 goto out_unlink; 146 } 147 if (fchmodat(AT_FDCWD, addr.sun_path, perm, AT_SYMLINK_NOFOLLOW)) { 148 PLOG(ERROR) << "Failed to fchmodat socket '" << addr.sun_path << "'"; 149 goto out_unlink; 150 } 151 152 LOG(INFO) << "Created socket '" << addr.sun_path << "'" 153 << ", mode " << std::oct << perm << std::dec 154 << ", user " << uid 155 << ", group " << gid; 156 157 return fd.release(); 158 159 out_unlink: 160 unlink(addr.sun_path); 161 return -1; 162 } 163 164 bool read_file(const std::string& path, std::string* content) { 165 content->clear(); 166 167 android::base::unique_fd fd( 168 TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC))); 169 if (fd == -1) { 170 return false; 171 } 172 173 // For security reasons, disallow world-writable 174 // or group-writable files. 175 struct stat sb; 176 if (fstat(fd, &sb) == -1) { 177 PLOG(ERROR) << "fstat failed for '" << path << "'"; 178 return false; 179 } 180 if ((sb.st_mode & (S_IWGRP | S_IWOTH)) != 0) { 181 LOG(ERROR) << "skipping insecure file '" << path << "'"; 182 return false; 183 } 184 185 return android::base::ReadFdToString(fd, content); 186 } 187 188 bool write_file(const std::string& path, const std::string& content) { 189 android::base::unique_fd fd(TEMP_FAILURE_RETRY( 190 open(path.c_str(), O_WRONLY | O_CREAT | O_NOFOLLOW | O_TRUNC | O_CLOEXEC, 0600))); 191 if (fd == -1) { 192 PLOG(ERROR) << "write_file: Unable to open '" << path << "'"; 193 return false; 194 } 195 bool success = android::base::WriteStringToFd(content, fd); 196 if (!success) { 197 PLOG(ERROR) << "write_file: Unable to write to '" << path << "'"; 198 } 199 return success; 200 } 201 202 boot_clock::time_point boot_clock::now() { 203 timespec ts; 204 clock_gettime(CLOCK_BOOTTIME, &ts); 205 return boot_clock::time_point(std::chrono::seconds(ts.tv_sec) + 206 std::chrono::nanoseconds(ts.tv_nsec)); 207 } 208 209 int mkdir_recursive(const char *pathname, mode_t mode) 210 { 211 char buf[128]; 212 const char *slash; 213 const char *p = pathname; 214 int width; 215 int ret; 216 struct stat info; 217 218 while ((slash = strchr(p, '/')) != NULL) { 219 width = slash - pathname; 220 p = slash + 1; 221 if (width < 0) 222 break; 223 if (width == 0) 224 continue; 225 if ((unsigned int)width > sizeof(buf) - 1) { 226 LOG(ERROR) << "path too long for mkdir_recursive"; 227 return -1; 228 } 229 memcpy(buf, pathname, width); 230 buf[width] = 0; 231 if (stat(buf, &info) != 0) { 232 ret = make_dir(buf, mode); 233 if (ret && errno != EEXIST) 234 return ret; 235 } 236 } 237 ret = make_dir(pathname, mode); 238 if (ret && errno != EEXIST) 239 return ret; 240 return 0; 241 } 242 243 /* 244 * replaces any unacceptable characters with '_', the 245 * length of the resulting string is equal to the input string 246 */ 247 void sanitize(char *s) 248 { 249 const char* accept = 250 "abcdefghijklmnopqrstuvwxyz" 251 "ABCDEFGHIJKLMNOPQRSTUVWXYZ" 252 "0123456789" 253 "_-."; 254 255 if (!s) 256 return; 257 258 while (*s) { 259 s += strspn(s, accept); 260 if (*s) *s++ = '_'; 261 } 262 } 263 264 int wait_for_file(const char* filename, std::chrono::nanoseconds timeout) { 265 boot_clock::time_point timeout_time = boot_clock::now() + timeout; 266 while (boot_clock::now() < timeout_time) { 267 struct stat sb; 268 if (stat(filename, &sb) != -1) return 0; 269 270 std::this_thread::sleep_for(10ms); 271 } 272 return -1; 273 } 274 275 void import_kernel_cmdline(bool in_qemu, 276 const std::function<void(const std::string&, const std::string&, bool)>& fn) { 277 std::string cmdline; 278 android::base::ReadFileToString("/proc/cmdline", &cmdline); 279 280 for (const auto& entry : android::base::Split(android::base::Trim(cmdline), " ")) { 281 std::vector<std::string> pieces = android::base::Split(entry, "="); 282 if (pieces.size() == 2) { 283 fn(pieces[0], pieces[1], in_qemu); 284 } 285 } 286 } 287 288 int make_dir(const char *path, mode_t mode) 289 { 290 int rc; 291 292 char *secontext = NULL; 293 294 if (sehandle) { 295 selabel_lookup(sehandle, &secontext, path, mode); 296 setfscreatecon(secontext); 297 } 298 299 rc = mkdir(path, mode); 300 301 if (secontext) { 302 int save_errno = errno; 303 freecon(secontext); 304 setfscreatecon(NULL); 305 errno = save_errno; 306 } 307 308 return rc; 309 } 310 311 int restorecon(const char* pathname, int flags) 312 { 313 return selinux_android_restorecon(pathname, flags); 314 } 315 316 /* 317 * Writes hex_len hex characters (1/2 byte) to hex from bytes. 318 */ 319 std::string bytes_to_hex(const uint8_t* bytes, size_t bytes_len) { 320 std::string hex("0x"); 321 for (size_t i = 0; i < bytes_len; i++) 322 android::base::StringAppendF(&hex, "%02x", bytes[i]); 323 return hex; 324 } 325 326 /* 327 * Returns true is pathname is a directory 328 */ 329 bool is_dir(const char* pathname) { 330 struct stat info; 331 if (stat(pathname, &info) == -1) { 332 return false; 333 } 334 return S_ISDIR(info.st_mode); 335 } 336 337 bool expand_props(const std::string& src, std::string* dst) { 338 const char* src_ptr = src.c_str(); 339 340 if (!dst) { 341 return false; 342 } 343 344 /* - variables can either be $x.y or ${x.y}, in case they are only part 345 * of the string. 346 * - will accept $$ as a literal $. 347 * - no nested property expansion, i.e. ${foo.${bar}} is not supported, 348 * bad things will happen 349 * - ${x.y:-default} will return default value if property empty. 350 */ 351 while (*src_ptr) { 352 const char* c; 353 354 c = strchr(src_ptr, '$'); 355 if (!c) { 356 dst->append(src_ptr); 357 return true; 358 } 359 360 dst->append(src_ptr, c); 361 c++; 362 363 if (*c == '$') { 364 dst->push_back(*(c++)); 365 src_ptr = c; 366 continue; 367 } else if (*c == '\0') { 368 return true; 369 } 370 371 std::string prop_name; 372 std::string def_val; 373 if (*c == '{') { 374 c++; 375 const char* end = strchr(c, '}'); 376 if (!end) { 377 // failed to find closing brace, abort. 378 LOG(ERROR) << "unexpected end of string in '" << src << "', looking for }"; 379 return false; 380 } 381 prop_name = std::string(c, end); 382 c = end + 1; 383 size_t def = prop_name.find(":-"); 384 if (def < prop_name.size()) { 385 def_val = prop_name.substr(def + 2); 386 prop_name = prop_name.substr(0, def); 387 } 388 } else { 389 prop_name = c; 390 LOG(ERROR) << "using deprecated syntax for specifying property '" << c << "', use ${name} instead"; 391 c += prop_name.size(); 392 } 393 394 if (prop_name.empty()) { 395 LOG(ERROR) << "invalid zero-length property name in '" << src << "'"; 396 return false; 397 } 398 399 std::string prop_val = android::base::GetProperty(prop_name, ""); 400 if (prop_val.empty()) { 401 if (def_val.empty()) { 402 LOG(ERROR) << "property '" << prop_name << "' doesn't exist while expanding '" << src << "'"; 403 return false; 404 } 405 prop_val = def_val; 406 } 407 408 dst->append(prop_val); 409 src_ptr = c; 410 } 411 412 return true; 413 } 414 415 void panic() { 416 LOG(ERROR) << "panic: rebooting to bootloader"; 417 DoReboot(ANDROID_RB_RESTART2, "reboot", "bootloader", false); 418 } 419 420 std::ostream& operator<<(std::ostream& os, const Timer& t) { 421 os << t.duration_s() << " seconds"; 422 return os; 423 } 424 425 // Reads the content of device tree file under kAndroidDtDir directory. 426 // Returns true if the read is success, false otherwise. 427 bool read_android_dt_file(const std::string& sub_path, std::string* dt_content) { 428 const std::string file_name = kAndroidDtDir + sub_path; 429 if (android::base::ReadFileToString(file_name, dt_content)) { 430 if (!dt_content->empty()) { 431 dt_content->pop_back(); // Trims the trailing '\0' out. 432 return true; 433 } 434 } 435 return false; 436 } 437 438 bool is_android_dt_value_expected(const std::string& sub_path, const std::string& expected_content) { 439 std::string dt_content; 440 if (read_android_dt_file(sub_path, &dt_content)) { 441 if (dt_content == expected_content) { 442 return true; 443 } 444 } 445 return false; 446 } 447