blob: 80c01bf16a16fb7bd4395cbcc06cf3937ced4e88 [file] [log] [blame]
bigbiff bigbiffaf32bb92018-12-18 18:39:53 -05001/*
2 * Copyright (C) 2010 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 LOG_TAG "MtpUtils"
18
19#include <android-base/logging.h>
20#include <android-base/unique_fd.h>
21#include <dirent.h>
22#include <fcntl.h>
23#include <string>
24#include <sys/sendfile.h>
25#include <sys/stat.h>
26#include <sys/types.h>
27#include <stdio.h>
28#include <time.h>
29#include <unistd.h>
30
31#include "MtpUtils.h"
32
33using namespace std;
34
35constexpr unsigned long FILE_COPY_SIZE = 262144;
36
37static void access_ok(const char *path) {
38 if (access(path, F_OK) == -1) {
39 // Ignore. Failure could be common in cases of delete where
40 // the metadata was updated through other paths.
41 }
42}
43
44/*
45DateTime strings follow a compatible subset of the definition found in ISO 8601, and
46take the form of a Unicode string formatted as: "YYYYMMDDThhmmss.s". In this
47representation, YYYY shall be replaced by the year, MM replaced by the month (01-12),
48DD replaced by the day (01-31), T is a constant character 'T' delimiting time from date,
49hh is replaced by the hour (00-23), mm is replaced by the minute (00-59), and ss by the
50second (00-59). The ".s" is optional, and represents tenths of a second.
51This is followed by a UTC offset given as "[+-]zzzz" or the literal "Z", meaning UTC.
52*/
53
54bool parseDateTime(const char* dateTime, time_t& outSeconds) {
55 int year, month, day, hour, minute, second;
56 if (sscanf(dateTime, "%04d%02d%02dT%02d%02d%02d",
57 &year, &month, &day, &hour, &minute, &second) != 6)
58 return false;
59
60 // skip optional tenth of second
61 const char* tail = dateTime + 15;
62 if (tail[0] == '.' && tail[1]) tail += 2;
63
64 // FIXME: "Z" means UTC, but non-"Z" doesn't mean local time.
65 // It might be that you're in Asia/Seoul on vacation and your Android
66 // device has noticed this via the network, but your camera was set to
67 // America/Los_Angeles once when you bought it and doesn't know where
68 // it is right now, so the camera says "20160106T081700-0800" but we
69 // just ignore the "-0800" and assume local time which is actually "+0900".
70 // I think to support this (without switching to Java or using icu4c)
71 // you'd want to always use timegm(3) and then manually add/subtract
72 // the UTC offset parsed from the string (taking care of wrapping).
73 // mktime(3) ignores the tm_gmtoff field, so you can't let it do the work.
74 bool useUTC = (tail[0] == 'Z');
75
76 struct tm tm = {};
77 tm.tm_sec = second;
78 tm.tm_min = minute;
79 tm.tm_hour = hour;
80 tm.tm_mday = day;
81 tm.tm_mon = month - 1; // mktime uses months in 0 - 11 range
82 tm.tm_year = year - 1900;
83 tm.tm_isdst = -1;
84 outSeconds = useUTC ? timegm(&tm) : mktime(&tm);
85
86 return true;
87}
88
89void formatDateTime(time_t seconds, char* buffer, int bufferLength) {
90 struct tm tm;
91
92 localtime_r(&seconds, &tm);
93 snprintf(buffer, bufferLength, "%04d%02d%02dT%02d%02d%02d",
94 tm.tm_year + 1900,
95 tm.tm_mon + 1, // localtime_r uses months in 0 - 11 range
96 tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
97}
98
99int makeFolder(const char *path) {
100 mode_t mask = umask(0);
101 int ret = mkdir((const char *)path, DIR_PERM);
102 umask(mask);
103 if (ret && ret != -EEXIST) {
104 PLOG(ERROR) << "Failed to create folder " << path;
105 ret = -1;
106 } else {
107 chown((const char *)path, getuid(), FILE_GROUP);
108 }
109 access_ok(path);
110 return ret;
111}
112
113/**
114 * Copies target path and all children to destination path.
115 *
116 * Returns 0 on success or a negative value indicating number of failures
117 */
118int copyRecursive(const char *fromPath, const char *toPath) {
119 int ret = 0;
120 string fromPathStr(fromPath);
121 string toPathStr(toPath);
122
123 DIR* dir = opendir(fromPath);
124 if (!dir) {
125 PLOG(ERROR) << "opendir " << fromPath << " failed";
126 return -1;
127 }
128 if (fromPathStr[fromPathStr.size()-1] != '/')
129 fromPathStr += '/';
130 if (toPathStr[toPathStr.size()-1] != '/')
131 toPathStr += '/';
132
133 struct dirent* entry;
134 while ((entry = readdir(dir))) {
135 const char* name = entry->d_name;
136
137 // ignore "." and ".."
138 if (name[0] == '.' && (name[1] == 0 || (name[1] == '.' && name[2] == 0))) {
139 continue;
140 }
141 string oldFile = fromPathStr + name;
142 string newFile = toPathStr + name;
143
144 if (entry->d_type == DT_DIR) {
145 ret += makeFolder(newFile.c_str());
146 ret += copyRecursive(oldFile.c_str(), newFile.c_str());
147 } else {
148 ret += copyFile(oldFile.c_str(), newFile.c_str());
149 }
150 }
151 return ret;
152}
153
154int copyFile(const char *fromPath, const char *toPath) {
155 auto start = std::chrono::steady_clock::now();
156
157 android::base::unique_fd fromFd(open(fromPath, O_RDONLY));
158 if (fromFd == -1) {
159 PLOG(ERROR) << "Failed to open copy from " << fromPath;
160 return -1;
161 }
162 android::base::unique_fd toFd(open(toPath, O_CREAT | O_WRONLY, FILE_PERM));
163 if (toFd == -1) {
164 PLOG(ERROR) << "Failed to open copy to " << toPath;
165 return -1;
166 }
167 off_t offset = 0;
168
169 struct stat sstat = {};
170 if (stat(fromPath, &sstat) == -1)
171 return -1;
172
173 off_t length = sstat.st_size;
174 int ret = 0;
175
176 while (offset < length) {
177 ssize_t transfer_length = std::min(length - offset, (off_t) FILE_COPY_SIZE);
178 ret = sendfile(toFd, fromFd, &offset, transfer_length);
179 if (ret != transfer_length) {
180 ret = -1;
181 PLOG(ERROR) << "Copying failed!";
182 break;
183 }
184 }
185 auto end = std::chrono::steady_clock::now();
186 std::chrono::duration<double> diff = end - start;
187 LOG(DEBUG) << "Copied a file with MTP. Time: " << diff.count() << " s, Size: " << length <<
188 ", Rate: " << ((double) length) / diff.count() << " bytes/s";
189 chown(toPath, getuid(), FILE_GROUP);
190 access_ok(toPath);
191 return ret == -1 ? -1 : 0;
192}
193
194void deleteRecursive(const char* path) {
195 string pathStr(path);
196 if (pathStr[pathStr.size()-1] != '/') {
197 pathStr += '/';
198 }
199
200 DIR* dir = opendir(path);
201 if (!dir) {
202 PLOG(ERROR) << "opendir " << path << " failed";
203 return;
204 }
205
206 struct dirent* entry;
207 while ((entry = readdir(dir))) {
208 const char* name = entry->d_name;
209
210 // ignore "." and ".."
211 if (name[0] == '.' && (name[1] == 0 || (name[1] == '.' && name[2] == 0))) {
212 continue;
213 }
214 string childPath = pathStr + name;
215 int success;
216 if (entry->d_type == DT_DIR) {
217 deleteRecursive(childPath.c_str());
218 success = rmdir(childPath.c_str());
219 } else {
220 success = unlink(childPath.c_str());
221 }
222 access_ok(childPath.c_str());
223 if (success == -1)
224 PLOG(ERROR) << "Deleting path " << childPath << " failed";
225 }
226 closedir(dir);
227}
228
229bool deletePath(const char* path) {
230 struct stat statbuf;
231 int success;
232 if (stat(path, &statbuf) == 0) {
233 if (S_ISDIR(statbuf.st_mode)) {
234 // rmdir will fail if the directory is non empty, so
235 // there is no need to keep errors from deleteRecursive
236 deleteRecursive(path);
237 success = rmdir(path);
238 } else {
239 success = unlink(path);
240 }
241 } else {
242 PLOG(ERROR) << "deletePath stat failed for " << path;
243 return false;
244 }
245 if (success == -1)
246 PLOG(ERROR) << "Deleting path " << path << " failed";
247 access_ok(path);
248 return success == 0;
249}
250
251int renameTo(const char *oldPath, const char *newPath) {
252 int ret = rename(oldPath, newPath);
253 access_ok(oldPath);
254 access_ok(newPath);
255 return ret;
256}
257
258// Calls access(2) on the path to update underlying filesystems,
259// then closes the fd.
260void closeObjFd(int fd, const char *path) {
261 close(fd);
262 access_ok(path);
263}