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