1 /*
2 * Copyright (C) 2014 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 #include "fuse_sdcard_provider.h"
18
19 #include <errno.h>
20 #include <fcntl.h>
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <sys/mount.h>
25 #include <sys/stat.h>
26 #include <unistd.h>
27
28 #include <functional>
29
30 #include <android-base/file.h>
31
32 #include "fuse_sideload.h"
33
34 struct file_data {
35 int fd; // the underlying sdcard file
36
37 uint64_t file_size;
38 uint32_t block_size;
39 };
40
read_block_file(const file_data & fd,uint32_t block,uint8_t * buffer,uint32_t fetch_size)41 static int read_block_file(const file_data& fd, uint32_t block, uint8_t* buffer,
42 uint32_t fetch_size) {
43 off64_t offset = static_cast<off64_t>(block) * fd.block_size;
44 if (TEMP_FAILURE_RETRY(lseek64(fd.fd, offset, SEEK_SET)) == -1) {
45 fprintf(stderr, "seek on sdcard failed: %s\n", strerror(errno));
46 return -EIO;
47 }
48
49 if (!android::base::ReadFully(fd.fd, buffer, fetch_size)) {
50 fprintf(stderr, "read on sdcard failed: %s\n", strerror(errno));
51 return -EIO;
52 }
53
54 return 0;
55 }
56
start_sdcard_fuse(const char * path)57 bool start_sdcard_fuse(const char* path) {
58 struct stat sb;
59 if (stat(path, &sb) == -1) {
60 fprintf(stderr, "failed to stat %s: %s\n", path, strerror(errno));
61 return false;
62 }
63
64 file_data fd;
65 fd.fd = open(path, O_RDONLY);
66 if (fd.fd == -1) {
67 fprintf(stderr, "failed to open %s: %s\n", path, strerror(errno));
68 return false;
69 }
70 fd.file_size = sb.st_size;
71 fd.block_size = 65536;
72
73 provider_vtab vtab;
74 vtab.read_block = std::bind(&read_block_file, fd, std::placeholders::_1, std::placeholders::_2,
75 std::placeholders::_3);
76 vtab.close = [&fd]() { close(fd.fd); };
77
78 // The installation process expects to find the sdcard unmounted. Unmount it with MNT_DETACH so
79 // that our open file continues to work but new references see it as unmounted.
80 umount2("/sdcard", MNT_DETACH);
81
82 return run_fuse_sideload(vtab, fd.file_size, fd.block_size) == 0;
83 }
84