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 <android-base/file.h>
36 #include <android-base/strings.h>
37 
38 /* for ANDROID_SOCKET_* */
39 #include <cutils/sockets.h>
40 #include <android-base/stringprintf.h>
41 
42 #include <private/android_filesystem_config.h>
43 
44 #include "init.h"
45 #include "log.h"
46 #include "property_service.h"
47 #include "util.h"
48 
49 /*
50  * android_name_to_id - returns the integer uid/gid associated with the given
51  * name, or UINT_MAX on error.
52  */
android_name_to_id(const char * name)53 static unsigned int android_name_to_id(const char *name)
54 {
55     const struct android_id_info *info = android_ids;
56     unsigned int n;
57 
58     for (n = 0; n < android_id_count; n++) {
59         if (!strcmp(info[n].name, name))
60             return info[n].aid;
61     }
62 
63     return UINT_MAX;
64 }
65 
do_decode_uid(const char * s)66 static unsigned int do_decode_uid(const char *s)
67 {
68     unsigned int v;
69 
70     if (!s || *s == '\0')
71         return UINT_MAX;
72     if (isalpha(s[0]))
73         return android_name_to_id(s);
74 
75     errno = 0;
76     v = (unsigned int) strtoul(s, 0, 0);
77     if (errno)
78         return UINT_MAX;
79     return v;
80 }
81 
82 /*
83  * decode_uid - decodes and returns the given string, which can be either the
84  * numeric or name representation, into the integer uid or gid. Returns
85  * UINT_MAX on error.
86  */
decode_uid(const char * s)87 unsigned int decode_uid(const char *s) {
88     unsigned int v = do_decode_uid(s);
89     if (v == UINT_MAX) {
90         ERROR("decode_uid: Unable to find UID for '%s'. Returning UINT_MAX\n", s);
91     }
92     return v;
93 }
94 
95 /*
96  * create_socket - creates a Unix domain socket in ANDROID_SOCKET_DIR
97  * ("/dev/socket") as dictated in init.rc. This socket is inherited by the
98  * daemon. We communicate the file descriptor's value via the environment
99  * variable ANDROID_SOCKET_ENV_PREFIX<name> ("ANDROID_SOCKET_foo").
100  */
create_socket(const char * name,int type,mode_t perm,uid_t uid,gid_t gid,const char * socketcon)101 int create_socket(const char *name, int type, mode_t perm, uid_t uid,
102                   gid_t gid, const char *socketcon)
103 {
104     struct sockaddr_un addr;
105     int fd, ret, savederrno;
106     char *filecon;
107 
108     if (socketcon) {
109         if (setsockcreatecon(socketcon) == -1) {
110             ERROR("setsockcreatecon(\"%s\") failed: %s\n", socketcon, strerror(errno));
111             return -1;
112         }
113     }
114 
115     fd = socket(PF_UNIX, type, 0);
116     if (fd < 0) {
117         ERROR("Failed to open socket '%s': %s\n", name, strerror(errno));
118         return -1;
119     }
120 
121     if (socketcon)
122         setsockcreatecon(NULL);
123 
124     memset(&addr, 0 , sizeof(addr));
125     addr.sun_family = AF_UNIX;
126     snprintf(addr.sun_path, sizeof(addr.sun_path), ANDROID_SOCKET_DIR"/%s",
127              name);
128 
129     ret = unlink(addr.sun_path);
130     if (ret != 0 && errno != ENOENT) {
131         ERROR("Failed to unlink old socket '%s': %s\n", name, strerror(errno));
132         goto out_close;
133     }
134 
135     filecon = NULL;
136     if (sehandle) {
137         ret = selabel_lookup(sehandle, &filecon, addr.sun_path, S_IFSOCK);
138         if (ret == 0)
139             setfscreatecon(filecon);
140     }
141 
142     ret = bind(fd, (struct sockaddr *) &addr, sizeof (addr));
143     savederrno = errno;
144 
145     setfscreatecon(NULL);
146     freecon(filecon);
147 
148     if (ret) {
149         ERROR("Failed to bind socket '%s': %s\n", name, strerror(savederrno));
150         goto out_unlink;
151     }
152 
153     ret = lchown(addr.sun_path, uid, gid);
154     if (ret) {
155         ERROR("Failed to lchown socket '%s': %s\n", addr.sun_path, strerror(errno));
156         goto out_unlink;
157     }
158     ret = fchmodat(AT_FDCWD, addr.sun_path, perm, AT_SYMLINK_NOFOLLOW);
159     if (ret) {
160         ERROR("Failed to fchmodat socket '%s': %s\n", addr.sun_path, strerror(errno));
161         goto out_unlink;
162     }
163 
164     INFO("Created socket '%s' with mode '%o', user '%d', group '%d'\n",
165          addr.sun_path, perm, uid, gid);
166 
167     return fd;
168 
169 out_unlink:
170     unlink(addr.sun_path);
171 out_close:
172     close(fd);
173     return -1;
174 }
175 
read_file(const char * path,std::string * content)176 bool read_file(const char* path, std::string* content) {
177     content->clear();
178 
179     int fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY|O_NOFOLLOW|O_CLOEXEC));
180     if (fd == -1) {
181         return false;
182     }
183 
184     // For security reasons, disallow world-writable
185     // or group-writable files.
186     struct stat sb;
187     if (fstat(fd, &sb) == -1) {
188         ERROR("fstat failed for '%s': %s\n", path, strerror(errno));
189         return false;
190     }
191     if ((sb.st_mode & (S_IWGRP | S_IWOTH)) != 0) {
192         ERROR("skipping insecure file '%s'\n", path);
193         return false;
194     }
195 
196     bool okay = android::base::ReadFdToString(fd, content);
197     close(fd);
198     return okay;
199 }
200 
write_file(const char * path,const char * content)201 int write_file(const char* path, const char* content) {
202     int fd = TEMP_FAILURE_RETRY(open(path, O_WRONLY|O_CREAT|O_NOFOLLOW|O_CLOEXEC, 0600));
203     if (fd == -1) {
204         NOTICE("write_file: Unable to open '%s': %s\n", path, strerror(errno));
205         return -1;
206     }
207     int result = android::base::WriteStringToFd(content, fd) ? 0 : -1;
208     if (result == -1) {
209         NOTICE("write_file: Unable to write to '%s': %s\n", path, strerror(errno));
210     }
211     close(fd);
212     return result;
213 }
214 
215 #define MAX_MTD_PARTITIONS 16
216 
217 static struct {
218     char name[16];
219     int number;
220 } mtd_part_map[MAX_MTD_PARTITIONS];
221 
222 static int mtd_part_count = -1;
223 
find_mtd_partitions(void)224 static void find_mtd_partitions(void)
225 {
226     int fd;
227     char buf[1024];
228     char *pmtdbufp;
229     ssize_t pmtdsize;
230     int r;
231 
232     fd = open("/proc/mtd", O_RDONLY|O_CLOEXEC);
233     if (fd < 0)
234         return;
235 
236     buf[sizeof(buf) - 1] = '\0';
237     pmtdsize = read(fd, buf, sizeof(buf) - 1);
238     pmtdbufp = buf;
239     while (pmtdsize > 0) {
240         int mtdnum, mtdsize, mtderasesize;
241         char mtdname[16];
242         mtdname[0] = '\0';
243         mtdnum = -1;
244         r = sscanf(pmtdbufp, "mtd%d: %x %x %15s",
245                    &mtdnum, &mtdsize, &mtderasesize, mtdname);
246         if ((r == 4) && (mtdname[0] == '"')) {
247             char *x = strchr(mtdname + 1, '"');
248             if (x) {
249                 *x = 0;
250             }
251             INFO("mtd partition %d, %s\n", mtdnum, mtdname + 1);
252             if (mtd_part_count < MAX_MTD_PARTITIONS) {
253                 strcpy(mtd_part_map[mtd_part_count].name, mtdname + 1);
254                 mtd_part_map[mtd_part_count].number = mtdnum;
255                 mtd_part_count++;
256             } else {
257                 ERROR("too many mtd partitions\n");
258             }
259         }
260         while (pmtdsize > 0 && *pmtdbufp != '\n') {
261             pmtdbufp++;
262             pmtdsize--;
263         }
264         if (pmtdsize > 0) {
265             pmtdbufp++;
266             pmtdsize--;
267         }
268     }
269     close(fd);
270 }
271 
mtd_name_to_number(const char * name)272 int mtd_name_to_number(const char *name)
273 {
274     int n;
275     if (mtd_part_count < 0) {
276         mtd_part_count = 0;
277         find_mtd_partitions();
278     }
279     for (n = 0; n < mtd_part_count; n++) {
280         if (!strcmp(name, mtd_part_map[n].name)) {
281             return mtd_part_map[n].number;
282         }
283     }
284     return -1;
285 }
286 
gettime()287 time_t gettime() {
288     timespec now;
289     clock_gettime(CLOCK_MONOTONIC, &now);
290     return now.tv_sec;
291 }
292 
gettime_ns()293 uint64_t gettime_ns() {
294     timespec now;
295     clock_gettime(CLOCK_MONOTONIC, &now);
296     return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000000000) + now.tv_nsec;
297 }
298 
mkdir_recursive(const char * pathname,mode_t mode)299 int mkdir_recursive(const char *pathname, mode_t mode)
300 {
301     char buf[128];
302     const char *slash;
303     const char *p = pathname;
304     int width;
305     int ret;
306     struct stat info;
307 
308     while ((slash = strchr(p, '/')) != NULL) {
309         width = slash - pathname;
310         p = slash + 1;
311         if (width < 0)
312             break;
313         if (width == 0)
314             continue;
315         if ((unsigned int)width > sizeof(buf) - 1) {
316             ERROR("path too long for mkdir_recursive\n");
317             return -1;
318         }
319         memcpy(buf, pathname, width);
320         buf[width] = 0;
321         if (stat(buf, &info) != 0) {
322             ret = make_dir(buf, mode);
323             if (ret && errno != EEXIST)
324                 return ret;
325         }
326     }
327     ret = make_dir(pathname, mode);
328     if (ret && errno != EEXIST)
329         return ret;
330     return 0;
331 }
332 
333 /*
334  * replaces any unacceptable characters with '_', the
335  * length of the resulting string is equal to the input string
336  */
sanitize(char * s)337 void sanitize(char *s)
338 {
339     const char* accept =
340             "abcdefghijklmnopqrstuvwxyz"
341             "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
342             "0123456789"
343             "_-.";
344 
345     if (!s)
346         return;
347 
348     while (*s) {
349         s += strspn(s, accept);
350         if (*s) *s++ = '_';
351     }
352 }
353 
make_link_init(const char * oldpath,const char * newpath)354 void make_link_init(const char *oldpath, const char *newpath)
355 {
356     int ret;
357     char buf[256];
358     char *slash;
359     int width;
360 
361     slash = strrchr(newpath, '/');
362     if (!slash)
363         return;
364     width = slash - newpath;
365     if (width <= 0 || width > (int)sizeof(buf) - 1)
366         return;
367     memcpy(buf, newpath, width);
368     buf[width] = 0;
369     ret = mkdir_recursive(buf, 0755);
370     if (ret)
371         ERROR("Failed to create directory %s: %s (%d)\n", buf, strerror(errno), errno);
372 
373     ret = symlink(oldpath, newpath);
374     if (ret && errno != EEXIST)
375         ERROR("Failed to symlink %s to %s: %s (%d)\n", oldpath, newpath, strerror(errno), errno);
376 }
377 
remove_link(const char * oldpath,const char * newpath)378 void remove_link(const char *oldpath, const char *newpath)
379 {
380     char path[256];
381     ssize_t ret;
382     ret = readlink(newpath, path, sizeof(path) - 1);
383     if (ret <= 0)
384         return;
385     path[ret] = 0;
386     if (!strcmp(path, oldpath))
387         unlink(newpath);
388 }
389 
wait_for_file(const char * filename,int timeout)390 int wait_for_file(const char *filename, int timeout)
391 {
392     struct stat info;
393     uint64_t timeout_time_ns = gettime_ns() + timeout * UINT64_C(1000000000);
394     int ret = -1;
395 
396     while (gettime_ns() < timeout_time_ns && ((ret = stat(filename, &info)) < 0))
397         usleep(10000);
398 
399     return ret;
400 }
401 
open_devnull_stdio(void)402 void open_devnull_stdio(void)
403 {
404     // Try to avoid the mknod() call if we can. Since SELinux makes
405     // a /dev/null replacement available for free, let's use it.
406     int fd = open("/sys/fs/selinux/null", O_RDWR);
407     if (fd == -1) {
408         // OOPS, /sys/fs/selinux/null isn't available, likely because
409         // /sys/fs/selinux isn't mounted. Fall back to mknod.
410         static const char *name = "/dev/__null__";
411         if (mknod(name, S_IFCHR | 0600, (1 << 8) | 3) == 0) {
412             fd = open(name, O_RDWR);
413             unlink(name);
414         }
415         if (fd == -1) {
416             exit(1);
417         }
418     }
419 
420     dup2(fd, 0);
421     dup2(fd, 1);
422     dup2(fd, 2);
423     if (fd > 2) {
424         close(fd);
425     }
426 }
427 
import_kernel_cmdline(bool in_qemu,std::function<void (const std::string &,const std::string &,bool)> fn)428 void import_kernel_cmdline(bool in_qemu,
429                            std::function<void(const std::string&, const std::string&, bool)> fn) {
430     std::string cmdline;
431     android::base::ReadFileToString("/proc/cmdline", &cmdline);
432 
433     for (const auto& entry : android::base::Split(android::base::Trim(cmdline), " ")) {
434         std::vector<std::string> pieces = android::base::Split(entry, "=");
435         if (pieces.size() == 2) {
436             fn(pieces[0], pieces[1], in_qemu);
437         }
438     }
439 }
440 
make_dir(const char * path,mode_t mode)441 int make_dir(const char *path, mode_t mode)
442 {
443     int rc;
444 
445     char *secontext = NULL;
446 
447     if (sehandle) {
448         selabel_lookup(sehandle, &secontext, path, mode);
449         setfscreatecon(secontext);
450     }
451 
452     rc = mkdir(path, mode);
453 
454     if (secontext) {
455         int save_errno = errno;
456         freecon(secontext);
457         setfscreatecon(NULL);
458         errno = save_errno;
459     }
460 
461     return rc;
462 }
463 
restorecon(const char * pathname)464 int restorecon(const char* pathname)
465 {
466     return selinux_android_restorecon(pathname, 0);
467 }
468 
restorecon_recursive(const char * pathname)469 int restorecon_recursive(const char* pathname)
470 {
471     return selinux_android_restorecon(pathname, SELINUX_ANDROID_RESTORECON_RECURSE);
472 }
473 
474 /*
475  * Writes hex_len hex characters (1/2 byte) to hex from bytes.
476  */
bytes_to_hex(const uint8_t * bytes,size_t bytes_len)477 std::string bytes_to_hex(const uint8_t* bytes, size_t bytes_len) {
478     std::string hex("0x");
479     for (size_t i = 0; i < bytes_len; i++)
480         android::base::StringAppendF(&hex, "%02x", bytes[i]);
481     return hex;
482 }
483 
484 /*
485  * Returns true is pathname is a directory
486  */
is_dir(const char * pathname)487 bool is_dir(const char* pathname) {
488     struct stat info;
489     if (stat(pathname, &info) == -1) {
490         return false;
491     }
492     return S_ISDIR(info.st_mode);
493 }
494 
expand_props(const std::string & src,std::string * dst)495 bool expand_props(const std::string& src, std::string* dst) {
496     const char* src_ptr = src.c_str();
497 
498     if (!dst) {
499         return false;
500     }
501 
502     /* - variables can either be $x.y or ${x.y}, in case they are only part
503      *   of the string.
504      * - will accept $$ as a literal $.
505      * - no nested property expansion, i.e. ${foo.${bar}} is not supported,
506      *   bad things will happen
507      */
508     while (*src_ptr) {
509         const char* c;
510 
511         c = strchr(src_ptr, '$');
512         if (!c) {
513             dst->append(src_ptr);
514             return true;
515         }
516 
517         dst->append(src_ptr, c);
518         c++;
519 
520         if (*c == '$') {
521             dst->push_back(*(c++));
522             src_ptr = c;
523             continue;
524         } else if (*c == '\0') {
525             return true;
526         }
527 
528         std::string prop_name;
529         if (*c == '{') {
530             c++;
531             const char* end = strchr(c, '}');
532             if (!end) {
533                 // failed to find closing brace, abort.
534                 ERROR("unexpected end of string in '%s', looking for }\n", src.c_str());
535                 return false;
536             }
537             prop_name = std::string(c, end);
538             c = end + 1;
539         } else {
540             prop_name = c;
541             ERROR("using deprecated syntax for specifying property '%s', use ${name} instead\n",
542                   c);
543             c += prop_name.size();
544         }
545 
546         if (prop_name.empty()) {
547             ERROR("invalid zero-length prop name in '%s'\n", src.c_str());
548             return false;
549         }
550 
551         std::string prop_val = property_get(prop_name.c_str());
552         if (prop_val.empty()) {
553             ERROR("property '%s' doesn't exist while expanding '%s'\n",
554                   prop_name.c_str(), src.c_str());
555             return false;
556         }
557 
558         dst->append(prop_val);
559         src_ptr = c;
560     }
561 
562     return true;
563 }
564