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 <stdarg.h> 18 #include <stdlib.h> 19 #include <stdio.h> 20 #include <string.h> 21 #include <fcntl.h> 22 #include <ctype.h> 23 #include <errno.h> 24 #include <time.h> 25 #include <ftw.h> 26 27 #include <selinux/label.h> 28 #include <selinux/android.h> 29 30 #include <sys/stat.h> 31 #include <sys/types.h> 32 #include <sys/socket.h> 33 #include <sys/un.h> 34 35 #include <base/file.h> 36 37 /* for ANDROID_SOCKET_* */ 38 #include <cutils/sockets.h> 39 #include <base/stringprintf.h> 40 41 #include <private/android_filesystem_config.h> 42 43 #include "init.h" 44 #include "log.h" 45 #include "util.h" 46 47 /* 48 * android_name_to_id - returns the integer uid/gid associated with the given 49 * name, or -1U on error. 50 */ 51 static unsigned int android_name_to_id(const char *name) 52 { 53 const struct android_id_info *info = android_ids; 54 unsigned int n; 55 56 for (n = 0; n < android_id_count; n++) { 57 if (!strcmp(info[n].name, name)) 58 return info[n].aid; 59 } 60 61 return -1U; 62 } 63 64 /* 65 * decode_uid - decodes and returns the given string, which can be either the 66 * numeric or name representation, into the integer uid or gid. Returns -1U on 67 * error. 68 */ 69 unsigned int decode_uid(const char *s) 70 { 71 unsigned int v; 72 73 if (!s || *s == '\0') 74 return -1U; 75 if (isalpha(s[0])) 76 return android_name_to_id(s); 77 78 errno = 0; 79 v = (unsigned int) strtoul(s, 0, 0); 80 if (errno) 81 return -1U; 82 return v; 83 } 84 85 /* 86 * create_socket - creates a Unix domain socket in ANDROID_SOCKET_DIR 87 * ("/dev/socket") as dictated in init.rc. This socket is inherited by the 88 * daemon. We communicate the file descriptor's value via the environment 89 * variable ANDROID_SOCKET_ENV_PREFIX<name> ("ANDROID_SOCKET_foo"). 90 */ 91 int create_socket(const char *name, int type, mode_t perm, uid_t uid, 92 gid_t gid, const char *socketcon) 93 { 94 struct sockaddr_un addr; 95 int fd, ret; 96 char *filecon; 97 98 if (socketcon) 99 setsockcreatecon(socketcon); 100 101 fd = socket(PF_UNIX, type, 0); 102 if (fd < 0) { 103 ERROR("Failed to open socket '%s': %s\n", name, strerror(errno)); 104 return -1; 105 } 106 107 if (socketcon) 108 setsockcreatecon(NULL); 109 110 memset(&addr, 0 , sizeof(addr)); 111 addr.sun_family = AF_UNIX; 112 snprintf(addr.sun_path, sizeof(addr.sun_path), ANDROID_SOCKET_DIR"/%s", 113 name); 114 115 ret = unlink(addr.sun_path); 116 if (ret != 0 && errno != ENOENT) { 117 ERROR("Failed to unlink old socket '%s': %s\n", name, strerror(errno)); 118 goto out_close; 119 } 120 121 filecon = NULL; 122 if (sehandle) { 123 ret = selabel_lookup(sehandle, &filecon, addr.sun_path, S_IFSOCK); 124 if (ret == 0) 125 setfscreatecon(filecon); 126 } 127 128 ret = bind(fd, (struct sockaddr *) &addr, sizeof (addr)); 129 if (ret) { 130 ERROR("Failed to bind socket '%s': %s\n", name, strerror(errno)); 131 goto out_unlink; 132 } 133 134 setfscreatecon(NULL); 135 freecon(filecon); 136 137 chown(addr.sun_path, uid, gid); 138 chmod(addr.sun_path, perm); 139 140 INFO("Created socket '%s' with mode '%o', user '%d', group '%d'\n", 141 addr.sun_path, perm, uid, gid); 142 143 return fd; 144 145 out_unlink: 146 unlink(addr.sun_path); 147 out_close: 148 close(fd); 149 return -1; 150 } 151 152 bool read_file(const char* path, std::string* content) { 153 content->clear(); 154 155 int fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY|O_NOFOLLOW|O_CLOEXEC)); 156 if (fd == -1) { 157 return false; 158 } 159 160 // For security reasons, disallow world-writable 161 // or group-writable files. 162 struct stat sb; 163 if (fstat(fd, &sb) == -1) { 164 ERROR("fstat failed for '%s': %s\n", path, strerror(errno)); 165 return false; 166 } 167 if ((sb.st_mode & (S_IWGRP | S_IWOTH)) != 0) { 168 ERROR("skipping insecure file '%s'\n", path); 169 return false; 170 } 171 172 bool okay = android::base::ReadFdToString(fd, content); 173 close(fd); 174 return okay; 175 } 176 177 int write_file(const char* path, const char* content) { 178 int fd = TEMP_FAILURE_RETRY(open(path, O_WRONLY|O_CREAT|O_NOFOLLOW|O_CLOEXEC, 0600)); 179 if (fd == -1) { 180 NOTICE("write_file: Unable to open '%s': %s\n", path, strerror(errno)); 181 return -1; 182 } 183 int result = android::base::WriteStringToFd(content, fd) ? 0 : -1; 184 if (result == -1) { 185 NOTICE("write_file: Unable to write to '%s': %s\n", path, strerror(errno)); 186 } 187 close(fd); 188 return result; 189 } 190 191 #define MAX_MTD_PARTITIONS 16 192 193 static struct { 194 char name[16]; 195 int number; 196 } mtd_part_map[MAX_MTD_PARTITIONS]; 197 198 static int mtd_part_count = -1; 199 200 static void find_mtd_partitions(void) 201 { 202 int fd; 203 char buf[1024]; 204 char *pmtdbufp; 205 ssize_t pmtdsize; 206 int r; 207 208 fd = open("/proc/mtd", O_RDONLY|O_CLOEXEC); 209 if (fd < 0) 210 return; 211 212 buf[sizeof(buf) - 1] = '\0'; 213 pmtdsize = read(fd, buf, sizeof(buf) - 1); 214 pmtdbufp = buf; 215 while (pmtdsize > 0) { 216 int mtdnum, mtdsize, mtderasesize; 217 char mtdname[16]; 218 mtdname[0] = '\0'; 219 mtdnum = -1; 220 r = sscanf(pmtdbufp, "mtd%d: %x %x %15s", 221 &mtdnum, &mtdsize, &mtderasesize, mtdname); 222 if ((r == 4) && (mtdname[0] == '"')) { 223 char *x = strchr(mtdname + 1, '"'); 224 if (x) { 225 *x = 0; 226 } 227 INFO("mtd partition %d, %s\n", mtdnum, mtdname + 1); 228 if (mtd_part_count < MAX_MTD_PARTITIONS) { 229 strcpy(mtd_part_map[mtd_part_count].name, mtdname + 1); 230 mtd_part_map[mtd_part_count].number = mtdnum; 231 mtd_part_count++; 232 } else { 233 ERROR("too many mtd partitions\n"); 234 } 235 } 236 while (pmtdsize > 0 && *pmtdbufp != '\n') { 237 pmtdbufp++; 238 pmtdsize--; 239 } 240 if (pmtdsize > 0) { 241 pmtdbufp++; 242 pmtdsize--; 243 } 244 } 245 close(fd); 246 } 247 248 int mtd_name_to_number(const char *name) 249 { 250 int n; 251 if (mtd_part_count < 0) { 252 mtd_part_count = 0; 253 find_mtd_partitions(); 254 } 255 for (n = 0; n < mtd_part_count; n++) { 256 if (!strcmp(name, mtd_part_map[n].name)) { 257 return mtd_part_map[n].number; 258 } 259 } 260 return -1; 261 } 262 263 time_t gettime() { 264 timespec now; 265 clock_gettime(CLOCK_MONOTONIC, &now); 266 return now.tv_sec; 267 } 268 269 uint64_t gettime_ns() { 270 timespec now; 271 clock_gettime(CLOCK_MONOTONIC, &now); 272 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000000000) + now.tv_nsec; 273 } 274 275 int mkdir_recursive(const char *pathname, mode_t mode) 276 { 277 char buf[128]; 278 const char *slash; 279 const char *p = pathname; 280 int width; 281 int ret; 282 struct stat info; 283 284 while ((slash = strchr(p, '/')) != NULL) { 285 width = slash - pathname; 286 p = slash + 1; 287 if (width < 0) 288 break; 289 if (width == 0) 290 continue; 291 if ((unsigned int)width > sizeof(buf) - 1) { 292 ERROR("path too long for mkdir_recursive\n"); 293 return -1; 294 } 295 memcpy(buf, pathname, width); 296 buf[width] = 0; 297 if (stat(buf, &info) != 0) { 298 ret = make_dir(buf, mode); 299 if (ret && errno != EEXIST) 300 return ret; 301 } 302 } 303 ret = make_dir(pathname, mode); 304 if (ret && errno != EEXIST) 305 return ret; 306 return 0; 307 } 308 309 /* 310 * replaces any unacceptable characters with '_', the 311 * length of the resulting string is equal to the input string 312 */ 313 void sanitize(char *s) 314 { 315 const char* accept = 316 "abcdefghijklmnopqrstuvwxyz" 317 "ABCDEFGHIJKLMNOPQRSTUVWXYZ" 318 "0123456789" 319 "_-."; 320 321 if (!s) 322 return; 323 324 while (*s) { 325 s += strspn(s, accept); 326 if (*s) *s++ = '_'; 327 } 328 } 329 330 void make_link_init(const char *oldpath, const char *newpath) 331 { 332 int ret; 333 char buf[256]; 334 char *slash; 335 int width; 336 337 slash = strrchr(newpath, '/'); 338 if (!slash) 339 return; 340 width = slash - newpath; 341 if (width <= 0 || width > (int)sizeof(buf) - 1) 342 return; 343 memcpy(buf, newpath, width); 344 buf[width] = 0; 345 ret = mkdir_recursive(buf, 0755); 346 if (ret) 347 ERROR("Failed to create directory %s: %s (%d)\n", buf, strerror(errno), errno); 348 349 ret = symlink(oldpath, newpath); 350 if (ret && errno != EEXIST) 351 ERROR("Failed to symlink %s to %s: %s (%d)\n", oldpath, newpath, strerror(errno), errno); 352 } 353 354 void remove_link(const char *oldpath, const char *newpath) 355 { 356 char path[256]; 357 ssize_t ret; 358 ret = readlink(newpath, path, sizeof(path) - 1); 359 if (ret <= 0) 360 return; 361 path[ret] = 0; 362 if (!strcmp(path, oldpath)) 363 unlink(newpath); 364 } 365 366 int wait_for_file(const char *filename, int timeout) 367 { 368 struct stat info; 369 uint64_t timeout_time_ns = gettime_ns() + timeout * UINT64_C(1000000000); 370 int ret = -1; 371 372 while (gettime_ns() < timeout_time_ns && ((ret = stat(filename, &info)) < 0)) 373 usleep(10000); 374 375 return ret; 376 } 377 378 void open_devnull_stdio(void) 379 { 380 // Try to avoid the mknod() call if we can. Since SELinux makes 381 // a /dev/null replacement available for free, let's use it. 382 int fd = open("/sys/fs/selinux/null", O_RDWR); 383 if (fd == -1) { 384 // OOPS, /sys/fs/selinux/null isn't available, likely because 385 // /sys/fs/selinux isn't mounted. Fall back to mknod. 386 static const char *name = "/dev/__null__"; 387 if (mknod(name, S_IFCHR | 0600, (1 << 8) | 3) == 0) { 388 fd = open(name, O_RDWR); 389 unlink(name); 390 } 391 if (fd == -1) { 392 exit(1); 393 } 394 } 395 396 dup2(fd, 0); 397 dup2(fd, 1); 398 dup2(fd, 2); 399 if (fd > 2) { 400 close(fd); 401 } 402 } 403 404 void import_kernel_cmdline(bool in_qemu, std::function<void(char*,bool)> import_kernel_nv) 405 { 406 char cmdline[2048]; 407 char *ptr; 408 int fd; 409 410 fd = open("/proc/cmdline", O_RDONLY | O_CLOEXEC); 411 if (fd >= 0) { 412 int n = read(fd, cmdline, sizeof(cmdline) - 1); 413 if (n < 0) n = 0; 414 415 /* get rid of trailing newline, it happens */ 416 if (n > 0 && cmdline[n-1] == '\n') n--; 417 418 cmdline[n] = 0; 419 close(fd); 420 } else { 421 cmdline[0] = 0; 422 } 423 424 ptr = cmdline; 425 while (ptr && *ptr) { 426 char *x = strchr(ptr, ' '); 427 if (x != 0) *x++ = 0; 428 import_kernel_nv(ptr, in_qemu); 429 ptr = x; 430 } 431 } 432 433 int make_dir(const char *path, mode_t mode) 434 { 435 int rc; 436 437 char *secontext = NULL; 438 439 if (sehandle) { 440 selabel_lookup(sehandle, &secontext, path, mode); 441 setfscreatecon(secontext); 442 } 443 444 rc = mkdir(path, mode); 445 446 if (secontext) { 447 int save_errno = errno; 448 freecon(secontext); 449 setfscreatecon(NULL); 450 errno = save_errno; 451 } 452 453 return rc; 454 } 455 456 int restorecon(const char* pathname) 457 { 458 return selinux_android_restorecon(pathname, 0); 459 } 460 461 int restorecon_recursive(const char* pathname) 462 { 463 return selinux_android_restorecon(pathname, SELINUX_ANDROID_RESTORECON_RECURSE); 464 } 465 466 /* 467 * Writes hex_len hex characters (1/2 byte) to hex from bytes. 468 */ 469 std::string bytes_to_hex(const uint8_t* bytes, size_t bytes_len) { 470 std::string hex("0x"); 471 for (size_t i = 0; i < bytes_len; i++) 472 android::base::StringAppendF(&hex, "%02x", bytes[i]); 473 return hex; 474 } 475