1 /*
2  * Copyright (C) 2007 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 #define TRACE_TAG SYNC
18 
19 #include "sysdeps.h"
20 #include "file_sync_service.h"
21 
22 #include <dirent.h>
23 #include <errno.h>
24 #include <linux/xattr.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <sys/stat.h>
29 #include <sys/types.h>
30 #include <sys/xattr.h>
31 #include <unistd.h>
32 #include <utime.h>
33 
34 #include <android-base/file.h>
35 #include <android-base/stringprintf.h>
36 #include <android-base/strings.h>
37 #include <private/android_filesystem_config.h>
38 #include <private/android_logger.h>
39 #include <selinux/android.h>
40 
41 #include "adb.h"
42 #include "adb_io.h"
43 #include "adb_trace.h"
44 #include "adb_utils.h"
45 #include "security_log_tags.h"
46 #include "sysdeps/errno.h"
47 
48 using android::base::StringPrintf;
49 
should_use_fs_config(const std::string & path)50 static bool should_use_fs_config(const std::string& path) {
51     // TODO: use fs_config to configure permissions on /data.
52     return android::base::StartsWith(path, "/system/") ||
53            android::base::StartsWith(path, "/vendor/") ||
54            android::base::StartsWith(path, "/oem/");
55 }
56 
update_capabilities(const char * path,uint64_t capabilities)57 static bool update_capabilities(const char* path, uint64_t capabilities) {
58     if (capabilities == 0) {
59         // Ensure we clean up in case the capabilities weren't 0 in the past.
60         removexattr(path, XATTR_NAME_CAPS);
61         return true;
62     }
63 
64     vfs_cap_data cap_data = {};
65     cap_data.magic_etc = VFS_CAP_REVISION | VFS_CAP_FLAGS_EFFECTIVE;
66     cap_data.data[0].permitted = (capabilities & 0xffffffff);
67     cap_data.data[0].inheritable = 0;
68     cap_data.data[1].permitted = (capabilities >> 32);
69     cap_data.data[1].inheritable = 0;
70     return setxattr(path, XATTR_NAME_CAPS, &cap_data, sizeof(cap_data), 0) != -1;
71 }
72 
secure_mkdirs(const std::string & path)73 static bool secure_mkdirs(const std::string& path) {
74     uid_t uid = -1;
75     gid_t gid = -1;
76     unsigned int mode = 0775;
77     uint64_t capabilities = 0;
78 
79     if (path[0] != '/') return false;
80 
81     std::vector<std::string> path_components = android::base::Split(path, "/");
82     std::string partial_path;
83     for (const auto& path_component : path_components) {
84         if (partial_path.back() != OS_PATH_SEPARATOR) partial_path += OS_PATH_SEPARATOR;
85         partial_path += path_component;
86 
87         if (should_use_fs_config(partial_path)) {
88             fs_config(partial_path.c_str(), 1, nullptr, &uid, &gid, &mode, &capabilities);
89         }
90         if (adb_mkdir(partial_path.c_str(), mode) == -1) {
91             if (errno != EEXIST) {
92                 return false;
93             }
94         } else {
95             if (chown(partial_path.c_str(), uid, gid) == -1) return false;
96 
97             // Not all filesystems support setting SELinux labels. http://b/23530370.
98             selinux_android_restorecon(partial_path.c_str(), 0);
99 
100             if (!update_capabilities(partial_path.c_str(), capabilities)) return false;
101         }
102     }
103     return true;
104 }
105 
do_lstat_v1(int s,const char * path)106 static bool do_lstat_v1(int s, const char* path) {
107     syncmsg msg = {};
108     msg.stat_v1.id = ID_LSTAT_V1;
109 
110     struct stat st = {};
111     lstat(path, &st);
112     msg.stat_v1.mode = st.st_mode;
113     msg.stat_v1.size = st.st_size;
114     msg.stat_v1.time = st.st_mtime;
115     return WriteFdExactly(s, &msg.stat_v1, sizeof(msg.stat_v1));
116 }
117 
do_stat_v2(int s,uint32_t id,const char * path)118 static bool do_stat_v2(int s, uint32_t id, const char* path) {
119     syncmsg msg = {};
120     msg.stat_v2.id = id;
121 
122     decltype(&stat) stat_fn;
123     if (id == ID_STAT_V2) {
124         stat_fn = stat;
125     } else {
126         stat_fn = lstat;
127     }
128 
129     struct stat st = {};
130     int rc = stat_fn(path, &st);
131     if (rc == -1) {
132         msg.stat_v2.error = errno_to_wire(errno);
133     } else {
134         msg.stat_v2.dev = st.st_dev;
135         msg.stat_v2.ino = st.st_ino;
136         msg.stat_v2.mode = st.st_mode;
137         msg.stat_v2.nlink = st.st_nlink;
138         msg.stat_v2.uid = st.st_uid;
139         msg.stat_v2.gid = st.st_gid;
140         msg.stat_v2.size = st.st_size;
141         msg.stat_v2.atime = st.st_atime;
142         msg.stat_v2.mtime = st.st_mtime;
143         msg.stat_v2.ctime = st.st_ctime;
144     }
145 
146     return WriteFdExactly(s, &msg.stat_v2, sizeof(msg.stat_v2));
147 }
148 
do_list(int s,const char * path)149 static bool do_list(int s, const char* path) {
150     dirent* de;
151 
152     syncmsg msg;
153     msg.dent.id = ID_DENT;
154 
155     std::unique_ptr<DIR, int(*)(DIR*)> d(opendir(path), closedir);
156     if (!d) goto done;
157 
158     while ((de = readdir(d.get()))) {
159         std::string filename(StringPrintf("%s/%s", path, de->d_name));
160 
161         struct stat st;
162         if (lstat(filename.c_str(), &st) == 0) {
163             size_t d_name_length = strlen(de->d_name);
164             msg.dent.mode = st.st_mode;
165             msg.dent.size = st.st_size;
166             msg.dent.time = st.st_mtime;
167             msg.dent.namelen = d_name_length;
168 
169             if (!WriteFdExactly(s, &msg.dent, sizeof(msg.dent)) ||
170                     !WriteFdExactly(s, de->d_name, d_name_length)) {
171                 return false;
172             }
173         }
174     }
175 
176 done:
177     msg.dent.id = ID_DONE;
178     msg.dent.mode = 0;
179     msg.dent.size = 0;
180     msg.dent.time = 0;
181     msg.dent.namelen = 0;
182     return WriteFdExactly(s, &msg.dent, sizeof(msg.dent));
183 }
184 
185 // Make sure that SendFail from adb_io.cpp isn't accidentally used in this file.
186 #pragma GCC poison SendFail
187 
SendSyncFail(int fd,const std::string & reason)188 static bool SendSyncFail(int fd, const std::string& reason) {
189     D("sync: failure: %s", reason.c_str());
190 
191     syncmsg msg;
192     msg.data.id = ID_FAIL;
193     msg.data.size = reason.size();
194     return WriteFdExactly(fd, &msg.data, sizeof(msg.data)) && WriteFdExactly(fd, reason);
195 }
196 
SendSyncFailErrno(int fd,const std::string & reason)197 static bool SendSyncFailErrno(int fd, const std::string& reason) {
198     return SendSyncFail(fd, StringPrintf("%s: %s", reason.c_str(), strerror(errno)));
199 }
200 
handle_send_file(int s,const char * path,uid_t uid,gid_t gid,uint64_t capabilities,mode_t mode,std::vector<char> & buffer,bool do_unlink)201 static bool handle_send_file(int s, const char* path, uid_t uid, gid_t gid, uint64_t capabilities,
202                              mode_t mode, std::vector<char>& buffer, bool do_unlink) {
203     syncmsg msg;
204     unsigned int timestamp = 0;
205 
206     __android_log_security_bswrite(SEC_TAG_ADB_SEND_FILE, path);
207 
208     int fd = adb_open_mode(path, O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, mode);
209     if (fd < 0 && errno == ENOENT) {
210         if (!secure_mkdirs(android::base::Dirname(path))) {
211             SendSyncFailErrno(s, "secure_mkdirs failed");
212             goto fail;
213         }
214         fd = adb_open_mode(path, O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, mode);
215     }
216     if (fd < 0 && errno == EEXIST) {
217         fd = adb_open_mode(path, O_WRONLY | O_CLOEXEC, mode);
218     }
219     if (fd < 0) {
220         SendSyncFailErrno(s, "couldn't create file");
221         goto fail;
222     } else {
223         if (fchown(fd, uid, gid) == -1) {
224             SendSyncFailErrno(s, "fchown failed");
225             goto fail;
226         }
227 
228         // Not all filesystems support setting SELinux labels. http://b/23530370.
229         selinux_android_restorecon(path, 0);
230 
231         // fchown clears the setuid bit - restore it if present.
232         // Ignore the result of calling fchmod. It's not supported
233         // by all filesystems, so we don't check for success. b/12441485
234         fchmod(fd, mode);
235     }
236 
237     while (true) {
238         if (!ReadFdExactly(s, &msg.data, sizeof(msg.data))) goto fail;
239 
240         if (msg.data.id != ID_DATA) {
241             if (msg.data.id == ID_DONE) {
242                 timestamp = msg.data.size;
243                 break;
244             }
245             SendSyncFail(s, "invalid data message");
246             goto abort;
247         }
248 
249         if (msg.data.size > buffer.size()) {  // TODO: resize buffer?
250             SendSyncFail(s, "oversize data message");
251             goto abort;
252         }
253 
254         if (!ReadFdExactly(s, &buffer[0], msg.data.size)) goto abort;
255 
256         if (!WriteFdExactly(fd, &buffer[0], msg.data.size)) {
257             SendSyncFailErrno(s, "write failed");
258             goto fail;
259         }
260     }
261 
262     adb_close(fd);
263 
264     if (!update_capabilities(path, capabilities)) {
265         SendSyncFailErrno(s, "update_capabilities failed");
266         goto fail;
267     }
268 
269     utimbuf u;
270     u.actime = timestamp;
271     u.modtime = timestamp;
272     utime(path, &u);
273 
274     msg.status.id = ID_OKAY;
275     msg.status.msglen = 0;
276     return WriteFdExactly(s, &msg.status, sizeof(msg.status));
277 
278 fail:
279     // If there's a problem on the device, we'll send an ID_FAIL message and
280     // close the socket. Unfortunately the kernel will sometimes throw that
281     // data away if the other end keeps writing without reading (which is
282     // the case with old versions of adb). To maintain compatibility, keep
283     // reading and throwing away ID_DATA packets until the other side notices
284     // that we've reported an error.
285     while (true) {
286         if (!ReadFdExactly(s, &msg.data, sizeof(msg.data))) goto fail;
287 
288         if (msg.data.id == ID_DONE) {
289             goto abort;
290         } else if (msg.data.id != ID_DATA) {
291             char id[5];
292             memcpy(id, &msg.data.id, sizeof(msg.data.id));
293             id[4] = '\0';
294             D("handle_send_fail received unexpected id '%s' during failure", id);
295             goto abort;
296         }
297 
298         if (msg.data.size > buffer.size()) {
299             D("handle_send_fail received oversized packet of length '%u' during failure",
300               msg.data.size);
301             goto abort;
302         }
303 
304         if (!ReadFdExactly(s, &buffer[0], msg.data.size)) goto abort;
305     }
306 
307 abort:
308     if (fd >= 0) adb_close(fd);
309     if (do_unlink) adb_unlink(path);
310     return false;
311 }
312 
313 #if defined(_WIN32)
314 extern bool handle_send_link(int s, const std::string& path, std::vector<char>& buffer) __attribute__((error("no symlinks on Windows")));
315 #else
handle_send_link(int s,const std::string & path,std::vector<char> & buffer)316 static bool handle_send_link(int s, const std::string& path, std::vector<char>& buffer) {
317     syncmsg msg;
318     unsigned int len;
319     int ret;
320 
321     if (!ReadFdExactly(s, &msg.data, sizeof(msg.data))) return false;
322 
323     if (msg.data.id != ID_DATA) {
324         SendSyncFail(s, "invalid data message: expected ID_DATA");
325         return false;
326     }
327 
328     len = msg.data.size;
329     if (len > buffer.size()) { // TODO: resize buffer?
330         SendSyncFail(s, "oversize data message");
331         return false;
332     }
333     if (!ReadFdExactly(s, &buffer[0], len)) return false;
334 
335     ret = symlink(&buffer[0], path.c_str());
336     if (ret && errno == ENOENT) {
337         if (!secure_mkdirs(android::base::Dirname(path))) {
338             SendSyncFailErrno(s, "secure_mkdirs failed");
339             return false;
340         }
341         ret = symlink(&buffer[0], path.c_str());
342     }
343     if (ret) {
344         SendSyncFailErrno(s, "symlink failed");
345         return false;
346     }
347 
348     if (!ReadFdExactly(s, &msg.data, sizeof(msg.data))) return false;
349 
350     if (msg.data.id == ID_DONE) {
351         msg.status.id = ID_OKAY;
352         msg.status.msglen = 0;
353         if (!WriteFdExactly(s, &msg.status, sizeof(msg.status))) return false;
354     } else {
355         SendSyncFail(s, "invalid data message: expected ID_DONE");
356         return false;
357     }
358 
359     return true;
360 }
361 #endif
362 
do_send(int s,const std::string & spec,std::vector<char> & buffer)363 static bool do_send(int s, const std::string& spec, std::vector<char>& buffer) {
364     // 'spec' is of the form "/some/path,0755". Break it up.
365     size_t comma = spec.find_last_of(',');
366     if (comma == std::string::npos) {
367         SendSyncFail(s, "missing , in ID_SEND");
368         return false;
369     }
370 
371     std::string path = spec.substr(0, comma);
372 
373     errno = 0;
374     mode_t mode = strtoul(spec.substr(comma + 1).c_str(), nullptr, 0);
375     if (errno != 0) {
376         SendSyncFail(s, "bad mode");
377         return false;
378     }
379 
380     // Don't delete files before copying if they are not "regular" or symlinks.
381     struct stat st;
382     bool do_unlink = (lstat(path.c_str(), &st) == -1) || S_ISREG(st.st_mode) || S_ISLNK(st.st_mode);
383     if (do_unlink) {
384         adb_unlink(path.c_str());
385     }
386 
387     if (S_ISLNK(mode)) {
388         return handle_send_link(s, path.c_str(), buffer);
389     }
390 
391     // Copy user permission bits to "group" and "other" permissions.
392     mode &= 0777;
393     mode |= ((mode >> 3) & 0070);
394     mode |= ((mode >> 3) & 0007);
395 
396     uid_t uid = -1;
397     gid_t gid = -1;
398     uint64_t capabilities = 0;
399     if (should_use_fs_config(path)) {
400         unsigned int broken_api_hack = mode;
401         fs_config(path.c_str(), 0, nullptr, &uid, &gid, &broken_api_hack, &capabilities);
402         mode = broken_api_hack;
403     }
404     return handle_send_file(s, path.c_str(), uid, gid, capabilities, mode, buffer, do_unlink);
405 }
406 
do_recv(int s,const char * path,std::vector<char> & buffer)407 static bool do_recv(int s, const char* path, std::vector<char>& buffer) {
408     __android_log_security_bswrite(SEC_TAG_ADB_RECV_FILE, path);
409 
410     int fd = adb_open(path, O_RDONLY | O_CLOEXEC);
411     if (fd < 0) {
412         SendSyncFailErrno(s, "open failed");
413         return false;
414     }
415 
416     syncmsg msg;
417     msg.data.id = ID_DATA;
418     while (true) {
419         int r = adb_read(fd, &buffer[0], buffer.size());
420         if (r <= 0) {
421             if (r == 0) break;
422             SendSyncFailErrno(s, "read failed");
423             adb_close(fd);
424             return false;
425         }
426         msg.data.size = r;
427         if (!WriteFdExactly(s, &msg.data, sizeof(msg.data)) || !WriteFdExactly(s, &buffer[0], r)) {
428             adb_close(fd);
429             return false;
430         }
431     }
432 
433     adb_close(fd);
434 
435     msg.data.id = ID_DONE;
436     msg.data.size = 0;
437     return WriteFdExactly(s, &msg.data, sizeof(msg.data));
438 }
439 
sync_id_to_name(uint32_t id)440 static const char* sync_id_to_name(uint32_t id) {
441   switch (id) {
442     case ID_LSTAT_V1:
443       return "lstat_v1";
444     case ID_LSTAT_V2:
445       return "lstat_v2";
446     case ID_STAT_V2:
447       return "stat_v2";
448     case ID_LIST:
449       return "list";
450     case ID_SEND:
451       return "send";
452     case ID_RECV:
453       return "recv";
454     case ID_QUIT:
455         return "quit";
456     default:
457         return "???";
458   }
459 }
460 
handle_sync_command(int fd,std::vector<char> & buffer)461 static bool handle_sync_command(int fd, std::vector<char>& buffer) {
462     D("sync: waiting for request");
463 
464     ATRACE_CALL();
465     SyncRequest request;
466     if (!ReadFdExactly(fd, &request, sizeof(request))) {
467         SendSyncFail(fd, "command read failure");
468         return false;
469     }
470     size_t path_length = request.path_length;
471     if (path_length > 1024) {
472         SendSyncFail(fd, "path too long");
473         return false;
474     }
475     char name[1025];
476     if (!ReadFdExactly(fd, name, path_length)) {
477         SendSyncFail(fd, "filename read failure");
478         return false;
479     }
480     name[path_length] = 0;
481 
482     std::string id_name = sync_id_to_name(request.id);
483     std::string trace_name = StringPrintf("%s(%s)", id_name.c_str(), name);
484     ATRACE_NAME(trace_name.c_str());
485 
486     D("sync: %s('%s')", id_name.c_str(), name);
487     switch (request.id) {
488         case ID_LSTAT_V1:
489             if (!do_lstat_v1(fd, name)) return false;
490             break;
491         case ID_LSTAT_V2:
492         case ID_STAT_V2:
493             if (!do_stat_v2(fd, request.id, name)) return false;
494             break;
495         case ID_LIST:
496             if (!do_list(fd, name)) return false;
497             break;
498         case ID_SEND:
499             if (!do_send(fd, name, buffer)) return false;
500             break;
501         case ID_RECV:
502             if (!do_recv(fd, name, buffer)) return false;
503             break;
504         case ID_QUIT:
505             return false;
506         default:
507             SendSyncFail(fd, StringPrintf("unknown command %08x", request.id));
508             return false;
509     }
510 
511     return true;
512 }
513 
file_sync_service(int fd,void *)514 void file_sync_service(int fd, void*) {
515     std::vector<char> buffer(SYNC_DATA_MAX);
516 
517     while (handle_sync_command(fd, buffer)) {
518     }
519 
520     D("sync: done");
521     adb_close(fd);
522 }
523