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