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 syncmsg msg;
233
234 __android_log_security_bswrite(SEC_TAG_ADB_SEND_FILE, path);
235
236 unique_fd fd(adb_open_mode(path, O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, mode));
237
238 if (posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL | POSIX_FADV_NOREUSE | POSIX_FADV_WILLNEED) <
239 0) {
240 D("[ Failed to fadvise: %d ]", errno);
241 }
242
243 if (fd < 0 && errno == ENOENT) {
244 if (!secure_mkdirs(Dirname(path))) {
245 SendSyncFailErrno(s, "secure_mkdirs failed");
246 goto fail;
247 }
248 fd.reset(adb_open_mode(path, O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, mode));
249 }
250 if (fd < 0 && errno == EEXIST) {
251 fd.reset(adb_open_mode(path, O_WRONLY | O_CLOEXEC, mode));
252 }
253 if (fd < 0) {
254 SendSyncFailErrno(s, "couldn't create file");
255 goto fail;
256 } else {
257 if (fchown(fd.get(), uid, gid) == -1) {
258 SendSyncFailErrno(s, "fchown failed");
259 goto fail;
260 }
261
262 #if defined(__ANDROID__)
263 // Not all filesystems support setting SELinux labels. http://b/23530370.
264 selinux_android_restorecon(path, 0);
265 #endif
266
267 // fchown clears the setuid bit - restore it if present.
268 // Ignore the result of calling fchmod. It's not supported
269 // by all filesystems, so we don't check for success. b/12441485
270 fchmod(fd.get(), mode);
271 }
272
273 while (true) {
274 if (!ReadFdExactly(s, &msg.data, sizeof(msg.data))) goto fail;
275
276 if (msg.data.id != ID_DATA) {
277 if (msg.data.id == ID_DONE) {
278 *timestamp = msg.data.size;
279 break;
280 }
281 SendSyncFail(s, "invalid data message");
282 goto abort;
283 }
284
285 if (msg.data.size > buffer.size()) { // TODO: resize buffer?
286 SendSyncFail(s, "oversize data message");
287 goto abort;
288 }
289
290 if (!ReadFdExactly(s, &buffer[0], msg.data.size)) goto abort;
291
292 if (!WriteFdExactly(fd.get(), &buffer[0], msg.data.size)) {
293 SendSyncFailErrno(s, "write failed");
294 goto fail;
295 }
296 }
297
298 if (!update_capabilities(path, capabilities)) {
299 SendSyncFailErrno(s, "update_capabilities failed");
300 goto fail;
301 }
302
303 msg.status.id = ID_OKAY;
304 msg.status.msglen = 0;
305 return WriteFdExactly(s, &msg.status, sizeof(msg.status));
306
307 fail:
308 // If there's a problem on the device, we'll send an ID_FAIL message and
309 // close the socket. Unfortunately the kernel will sometimes throw that
310 // data away if the other end keeps writing without reading (which is
311 // the case with old versions of adb). To maintain compatibility, keep
312 // reading and throwing away ID_DATA packets until the other side notices
313 // that we've reported an error.
314 while (true) {
315 if (!ReadFdExactly(s, &msg.data, sizeof(msg.data))) break;
316
317 if (msg.data.id == ID_DONE) {
318 break;
319 } else if (msg.data.id != ID_DATA) {
320 char id[5];
321 memcpy(id, &msg.data.id, sizeof(msg.data.id));
322 id[4] = '\0';
323 D("handle_send_fail received unexpected id '%s' during failure", id);
324 break;
325 }
326
327 if (msg.data.size > buffer.size()) {
328 D("handle_send_fail received oversized packet of length '%u' during failure",
329 msg.data.size);
330 break;
331 }
332
333 if (!ReadFdExactly(s, &buffer[0], msg.data.size)) break;
334 }
335
336 abort:
337 if (do_unlink) adb_unlink(path);
338 return false;
339 }
340
341 #if defined(_WIN32)
342 extern bool handle_send_link(int s, const std::string& path,
343 uint32_t* timestamp, std::vector<char>& buffer)
344 __attribute__((error("no symlinks on Windows")));
345 #else
handle_send_link(int s,const std::string & path,uint32_t * timestamp,std::vector<char> & buffer)346 static bool handle_send_link(int s, const std::string& path, uint32_t* timestamp,
347 std::vector<char>& buffer) {
348 syncmsg msg;
349
350 if (!ReadFdExactly(s, &msg.data, sizeof(msg.data))) return false;
351
352 if (msg.data.id != ID_DATA) {
353 SendSyncFail(s, "invalid data message: expected ID_DATA");
354 return false;
355 }
356
357 unsigned int len = msg.data.size;
358 if (len > buffer.size()) { // TODO: resize buffer?
359 SendSyncFail(s, "oversize data message");
360 return false;
361 }
362 if (!ReadFdExactly(s, &buffer[0], len)) return false;
363
364 std::string buf_link;
365 if (!android::base::Readlink(path, &buf_link) || (buf_link != &buffer[0])) {
366 adb_unlink(path.c_str());
367 auto ret = symlink(&buffer[0], path.c_str());
368 if (ret && errno == ENOENT) {
369 if (!secure_mkdirs(Dirname(path))) {
370 SendSyncFailErrno(s, "secure_mkdirs failed");
371 return false;
372 }
373 ret = symlink(&buffer[0], path.c_str());
374 }
375 if (ret) {
376 SendSyncFailErrno(s, "symlink failed");
377 return false;
378 }
379 }
380
381 if (!ReadFdExactly(s, &msg.data, sizeof(msg.data))) return false;
382
383 if (msg.data.id == ID_DONE) {
384 *timestamp = msg.data.size;
385 msg.status.id = ID_OKAY;
386 msg.status.msglen = 0;
387 if (!WriteFdExactly(s, &msg.status, sizeof(msg.status))) return false;
388 } else {
389 SendSyncFail(s, "invalid data message: expected ID_DONE");
390 return false;
391 }
392
393 return true;
394 }
395 #endif
396
do_send(int s,const std::string & spec,std::vector<char> & buffer)397 static bool do_send(int s, const std::string& spec, std::vector<char>& buffer) {
398 // 'spec' is of the form "/some/path,0755". Break it up.
399 size_t comma = spec.find_last_of(',');
400 if (comma == std::string::npos) {
401 SendSyncFail(s, "missing , in ID_SEND");
402 return false;
403 }
404
405 std::string path = spec.substr(0, comma);
406
407 errno = 0;
408 mode_t mode = strtoul(spec.substr(comma + 1).c_str(), nullptr, 0);
409 if (errno != 0) {
410 SendSyncFail(s, "bad mode");
411 return false;
412 }
413
414 // Don't delete files before copying if they are not "regular" or symlinks.
415 struct stat st;
416 bool do_unlink = (lstat(path.c_str(), &st) == -1) || S_ISREG(st.st_mode) ||
417 (S_ISLNK(st.st_mode) && !S_ISLNK(mode));
418 if (do_unlink) {
419 adb_unlink(path.c_str());
420 }
421
422 bool result;
423 uint32_t timestamp;
424 if (S_ISLNK(mode)) {
425 result = handle_send_link(s, path, ×tamp, buffer);
426 } else {
427 // Copy user permission bits to "group" and "other" permissions.
428 mode &= 0777;
429 mode |= ((mode >> 3) & 0070);
430 mode |= ((mode >> 3) & 0007);
431
432 uid_t uid = -1;
433 gid_t gid = -1;
434 uint64_t capabilities = 0;
435 if (should_use_fs_config(path)) {
436 unsigned int broken_api_hack = mode;
437 fs_config(path.c_str(), 0, nullptr, &uid, &gid, &broken_api_hack, &capabilities);
438 mode = broken_api_hack;
439 }
440
441 result = handle_send_file(s, path.c_str(), ×tamp, uid, gid, capabilities, mode, buffer,
442 do_unlink);
443 }
444
445 if (!result) {
446 return false;
447 }
448
449 struct timeval tv[2];
450 tv[0].tv_sec = timestamp;
451 tv[0].tv_usec = 0;
452 tv[1].tv_sec = timestamp;
453 tv[1].tv_usec = 0;
454 lutimes(path.c_str(), tv);
455 return true;
456 }
457
do_recv(int s,const char * path,std::vector<char> & buffer)458 static bool do_recv(int s, const char* path, std::vector<char>& buffer) {
459 __android_log_security_bswrite(SEC_TAG_ADB_RECV_FILE, path);
460
461 unique_fd fd(adb_open(path, O_RDONLY | O_CLOEXEC));
462 if (fd < 0) {
463 SendSyncFailErrno(s, "open failed");
464 return false;
465 }
466
467 if (posix_fadvise(fd.get(), 0, 0, POSIX_FADV_SEQUENTIAL | POSIX_FADV_NOREUSE) < 0) {
468 D("[ Failed to fadvise: %d ]", errno);
469 }
470
471 syncmsg msg;
472 msg.data.id = ID_DATA;
473 while (true) {
474 int r = adb_read(fd.get(), &buffer[0], buffer.size() - sizeof(msg.data));
475 if (r <= 0) {
476 if (r == 0) break;
477 SendSyncFailErrno(s, "read failed");
478 return false;
479 }
480 msg.data.size = r;
481 if (!WriteFdExactly(s, &msg.data, sizeof(msg.data)) || !WriteFdExactly(s, &buffer[0], r)) {
482 return false;
483 }
484 }
485
486 msg.data.id = ID_DONE;
487 msg.data.size = 0;
488 return WriteFdExactly(s, &msg.data, sizeof(msg.data));
489 }
490
sync_id_to_name(uint32_t id)491 static const char* sync_id_to_name(uint32_t id) {
492 switch (id) {
493 case ID_LSTAT_V1:
494 return "lstat_v1";
495 case ID_LSTAT_V2:
496 return "lstat_v2";
497 case ID_STAT_V2:
498 return "stat_v2";
499 case ID_LIST:
500 return "list";
501 case ID_SEND:
502 return "send";
503 case ID_RECV:
504 return "recv";
505 case ID_QUIT:
506 return "quit";
507 default:
508 return "???";
509 }
510 }
511
handle_sync_command(int fd,std::vector<char> & buffer)512 static bool handle_sync_command(int fd, std::vector<char>& buffer) {
513 D("sync: waiting for request");
514
515 ATRACE_CALL();
516 SyncRequest request;
517 if (!ReadFdExactly(fd, &request, sizeof(request))) {
518 SendSyncFail(fd, "command read failure");
519 return false;
520 }
521 size_t path_length = request.path_length;
522 if (path_length > 1024) {
523 SendSyncFail(fd, "path too long");
524 return false;
525 }
526 char name[1025];
527 if (!ReadFdExactly(fd, name, path_length)) {
528 SendSyncFail(fd, "filename read failure");
529 return false;
530 }
531 name[path_length] = 0;
532
533 std::string id_name = sync_id_to_name(request.id);
534 std::string trace_name = StringPrintf("%s(%s)", id_name.c_str(), name);
535 ATRACE_NAME(trace_name.c_str());
536
537 D("sync: %s('%s')", id_name.c_str(), name);
538 switch (request.id) {
539 case ID_LSTAT_V1:
540 if (!do_lstat_v1(fd, name)) return false;
541 break;
542 case ID_LSTAT_V2:
543 case ID_STAT_V2:
544 if (!do_stat_v2(fd, request.id, name)) return false;
545 break;
546 case ID_LIST:
547 if (!do_list(fd, name)) return false;
548 break;
549 case ID_SEND:
550 if (!do_send(fd, name, buffer)) return false;
551 break;
552 case ID_RECV:
553 if (!do_recv(fd, name, buffer)) return false;
554 break;
555 case ID_QUIT:
556 return false;
557 default:
558 SendSyncFail(fd, StringPrintf("unknown command %08x", request.id));
559 return false;
560 }
561
562 return true;
563 }
564
file_sync_service(unique_fd fd)565 void file_sync_service(unique_fd fd) {
566 std::vector<char> buffer(SYNC_DATA_MAX);
567
568 while (handle_sync_command(fd.get(), buffer)) {
569 }
570
571 D("sync: done");
572 }
573