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