1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "chrome/browser/download/download_path_reservation_tracker.h"
10 #include "base/callback.h"
11 #include "base/files/file_util.h"
12 #include "base/logging.h"
13 #include "base/path_service.h"
14 #include "base/stl_util.h"
15 #include "base/strings/string_util.h"
16 #include "base/strings/stringprintf.h"
17 #include "base/third_party/icu/icu_utf.h"
18 #include "chrome/common/chrome_paths.h"
19 #include "content/public/browser/browser_thread.h"
20 #include "content/public/browser/download_item.h"
22 using content::BrowserThread
;
23 using content::DownloadItem
;
27 typedef DownloadItem
* ReservationKey
;
28 typedef std::map
<ReservationKey
, base::FilePath
> ReservationMap
;
30 // The lower bound for file name truncation. If the truncation results in a name
31 // shorter than this limit, we give up automatic truncation and prompt the user.
32 static const size_t kTruncatedNameLengthLowerbound
= 5;
34 // The length of the suffix string we append for an intermediate file name.
35 // In the file name truncation, we keep the margin to append the suffix.
36 // TODO(kinaba): remove the margin. The user should be able to set maximum
38 static const size_t kIntermediateNameSuffixLength
= sizeof(".crdownload") - 1;
40 // Map of download path reservations. Each reserved path is associated with a
41 // ReservationKey=DownloadItem*. This object is destroyed in |Revoke()| when
42 // there are no more reservations.
44 // It is not an error, although undesirable, to have multiple DownloadItem*s
45 // that are mapped to the same path. This can happen if a reservation is created
46 // that is supposed to overwrite an existing reservation.
47 ReservationMap
* g_reservation_map
= NULL
;
49 // Observes a DownloadItem for changes to its target path and state. Updates or
50 // revokes associated download path reservations as necessary. Created, invoked
51 // and destroyed on the UI thread.
52 class DownloadItemObserver
: public DownloadItem::Observer
{
54 explicit DownloadItemObserver(DownloadItem
* download_item
);
57 ~DownloadItemObserver() override
;
59 // DownloadItem::Observer
60 void OnDownloadUpdated(DownloadItem
* download
) override
;
61 void OnDownloadDestroyed(DownloadItem
* download
) override
;
63 DownloadItem
* download_item_
;
65 // Last known target path for the download.
66 base::FilePath last_target_path_
;
68 DISALLOW_COPY_AND_ASSIGN(DownloadItemObserver
);
71 // Returns true if the given path is in use by a path reservation.
72 bool IsPathReserved(const base::FilePath
& path
) {
73 DCHECK_CURRENTLY_ON(BrowserThread::FILE);
74 // No reservation map => no reservations.
75 if (g_reservation_map
== NULL
)
77 // Unfortunately path normalization doesn't work reliably for non-existant
78 // files. So given a FilePath, we can't derive a normalized key that we can
79 // use for lookups. We only expect a small number of concurrent downloads at
80 // any given time, so going through all of them shouldn't be too slow.
81 for (ReservationMap::const_iterator iter
= g_reservation_map
->begin();
82 iter
!= g_reservation_map
->end(); ++iter
) {
83 if (iter
->second
== path
)
89 // Returns true if the given path is in use by any path reservation or the
90 // file system. Called on the FILE thread.
91 bool IsPathInUse(const base::FilePath
& path
) {
92 DCHECK_CURRENTLY_ON(BrowserThread::FILE);
93 // If there is a reservation, then the path is in use.
94 if (IsPathReserved(path
))
97 // If the path exists in the file system, then the path is in use.
98 if (base::PathExists(path
))
104 // Truncates path->BaseName() to make path->BaseName().value().size() <= limit.
105 // - It keeps the extension as is. Only truncates the body part.
106 // - It secures the base filename length to be more than or equals to
107 // kTruncatedNameLengthLowerbound.
108 // If it was unable to shorten the name, returns false.
109 bool TruncateFileName(base::FilePath
* path
, size_t limit
) {
110 base::FilePath
basename(path
->BaseName());
111 // It is already short enough.
112 if (basename
.value().size() <= limit
)
115 base::FilePath
dir(path
->DirName());
116 base::FilePath::StringType
ext(basename
.Extension());
117 base::FilePath::StringType
name(basename
.RemoveExtension().value());
119 // Impossible to satisfy the limit.
120 if (limit
< kTruncatedNameLengthLowerbound
+ ext
.size())
124 // Encoding specific truncation logic.
125 base::FilePath::StringType truncated
;
126 #if defined(OS_CHROMEOS) || defined(OS_MACOSX)
128 base::TruncateUTF8ToByteSize(name
, limit
, &truncated
);
129 #elif defined(OS_WIN)
131 DCHECK(name
.size() > limit
);
132 truncated
= name
.substr(0, CBU16_IS_TRAIL(name
[limit
]) ? limit
- 1 : limit
);
134 // We cannot generally assume that the file name encoding is in UTF-8 (see
135 // the comment for FilePath::AsUTF8Unsafe), hence no safe way to truncate.
138 if (truncated
.size() < kTruncatedNameLengthLowerbound
)
140 *path
= dir
.Append(truncated
+ ext
);
144 // Called on the FILE thread to reserve a download path. This method:
145 // - Creates directory |default_download_path| if it doesn't exist.
146 // - Verifies that the parent directory of |suggested_path| exists and is
148 // - Truncates the suggested name if it exceeds the filesystem's limit.
149 // - Uniquifies |suggested_path| if |should_uniquify_path| is true.
150 // - Returns true if |reserved_path| has been successfully verified.
151 bool CreateReservation(
153 const base::FilePath
& suggested_path
,
154 const base::FilePath
& default_download_path
,
155 bool create_directory
,
156 DownloadPathReservationTracker::FilenameConflictAction conflict_action
,
157 base::FilePath
* reserved_path
) {
158 DCHECK_CURRENTLY_ON(BrowserThread::FILE);
159 DCHECK(suggested_path
.IsAbsolute());
161 // Create a reservation map if one doesn't exist. It will be automatically
162 // deleted when all the reservations are revoked.
163 if (g_reservation_map
== NULL
)
164 g_reservation_map
= new ReservationMap
;
166 ReservationMap
& reservations
= *g_reservation_map
;
167 DCHECK(!ContainsKey(reservations
, key
));
169 base::FilePath
target_path(suggested_path
.NormalizePathSeparators());
170 base::FilePath target_dir
= target_path
.DirName();
171 base::FilePath filename
= target_path
.BaseName();
172 bool is_path_writeable
= true;
173 bool has_conflicts
= false;
174 bool name_too_long
= false;
176 // Create target_dir if necessary and appropriate. target_dir may be the last
177 // directory that the user selected in a FilePicker; if that directory has
178 // since been removed, do NOT automatically re-create it. Only automatically
179 // create the directory if it is the default Downloads directory or if the
180 // caller explicitly requested automatic directory creation.
181 if (!base::DirectoryExists(target_dir
) &&
183 (!default_download_path
.empty() &&
184 (default_download_path
== target_dir
)))) {
185 base::CreateDirectory(target_dir
);
188 // Check writability of the suggested path. If we can't write to it, default
189 // to the user's "My Documents" directory. We'll prompt them in this case.
190 if (!base::PathIsWritable(target_dir
)) {
191 DVLOG(1) << "Unable to write to directory \"" << target_dir
.value() << "\"";
192 is_path_writeable
= false;
193 PathService::Get(chrome::DIR_USER_DOCUMENTS
, &target_dir
);
194 target_path
= target_dir
.Append(filename
);
197 if (is_path_writeable
) {
198 // Check the limit of file name length if it could be obtained. When the
199 // suggested name exceeds the limit, truncate or prompt the user.
200 int max_length
= base::GetMaximumPathComponentLength(target_dir
);
201 if (max_length
!= -1) {
202 int limit
= max_length
- kIntermediateNameSuffixLength
;
203 if (limit
<= 0 || !TruncateFileName(&target_path
, limit
))
204 name_too_long
= true;
207 // Uniquify the name, if it already exists.
208 if (!name_too_long
&& IsPathInUse(target_path
)) {
209 has_conflicts
= true;
210 if (conflict_action
== DownloadPathReservationTracker::OVERWRITE
) {
211 has_conflicts
= false;
213 // If ...PROMPT, then |has_conflicts| will remain true, |verified| will be
214 // false, and CDMD will prompt.
215 if (conflict_action
== DownloadPathReservationTracker::UNIQUIFY
) {
216 for (int uniquifier
= 1;
217 uniquifier
<= DownloadPathReservationTracker::kMaxUniqueFiles
;
219 // Append uniquifier.
220 std::string
suffix(base::StringPrintf(" (%d)", uniquifier
));
221 base::FilePath
path_to_check(target_path
);
222 // If the name length limit is available (max_length != -1), and the
223 // the current name exceeds the limit, truncate.
224 if (max_length
!= -1) {
226 max_length
- kIntermediateNameSuffixLength
- suffix
.size();
227 // If truncation failed, give up uniquification.
228 if (limit
<= 0 || !TruncateFileName(&path_to_check
, limit
))
231 path_to_check
= path_to_check
.InsertBeforeExtensionASCII(suffix
);
233 if (!IsPathInUse(path_to_check
)) {
234 target_path
= path_to_check
;
235 has_conflicts
= false;
243 reservations
[key
] = target_path
;
244 bool verified
= (is_path_writeable
&& !has_conflicts
&& !name_too_long
);
245 *reserved_path
= target_path
;
249 // Called on the FILE thread to update the path of the reservation associated
250 // with |key| to |new_path|.
251 void UpdateReservation(ReservationKey key
, const base::FilePath
& new_path
) {
252 DCHECK_CURRENTLY_ON(BrowserThread::FILE);
253 DCHECK(g_reservation_map
!= NULL
);
254 ReservationMap::iterator iter
= g_reservation_map
->find(key
);
255 if (iter
!= g_reservation_map
->end()) {
256 iter
->second
= new_path
;
258 // This would happen if an UpdateReservation() notification was scheduled on
259 // the FILE thread before ReserveInternal(), or after a Revoke()
260 // call. Neither should happen.
265 // Called on the FILE thread to remove the path reservation associated with
267 void RevokeReservation(ReservationKey key
) {
268 DCHECK_CURRENTLY_ON(BrowserThread::FILE);
269 DCHECK(g_reservation_map
!= NULL
);
270 DCHECK(ContainsKey(*g_reservation_map
, key
));
271 g_reservation_map
->erase(key
);
272 if (g_reservation_map
->size() == 0) {
273 // No more reservations. Delete map.
274 delete g_reservation_map
;
275 g_reservation_map
= NULL
;
279 void RunGetReservedPathCallback(
280 const DownloadPathReservationTracker::ReservedPathCallback
& callback
,
281 const base::FilePath
* reserved_path
,
283 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
284 callback
.Run(*reserved_path
, verified
);
287 DownloadItemObserver::DownloadItemObserver(DownloadItem
* download_item
)
288 : download_item_(download_item
),
289 last_target_path_(download_item
->GetTargetFilePath()) {
290 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
291 download_item_
->AddObserver(this);
294 DownloadItemObserver::~DownloadItemObserver() {
295 download_item_
->RemoveObserver(this);
298 void DownloadItemObserver::OnDownloadUpdated(DownloadItem
* download
) {
299 switch (download
->GetState()) {
300 case DownloadItem::IN_PROGRESS
: {
301 // Update the reservation.
302 base::FilePath new_target_path
= download
->GetTargetFilePath();
303 if (new_target_path
!= last_target_path_
) {
304 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE
, base::Bind(
305 &UpdateReservation
, download
, new_target_path
));
306 last_target_path_
= new_target_path
;
311 case DownloadItem::COMPLETE
:
312 // If the download is complete, then it has already been renamed to the
313 // final name. The existence of the file on disk is sufficient to prevent
314 // conflicts from now on.
316 case DownloadItem::CANCELLED
:
317 // We no longer need the reservation if the download is being removed.
319 case DownloadItem::INTERRUPTED
:
320 // The download filename will need to be re-generated when the download is
321 // restarted. Holding on to the reservation now would prevent the name
322 // from being used for a subsequent retry attempt.
324 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE
, base::Bind(
325 &RevokeReservation
, download
));
329 case DownloadItem::MAX_DOWNLOAD_STATE
:
330 // Compiler appeasement.
335 void DownloadItemObserver::OnDownloadDestroyed(DownloadItem
* download
) {
336 // Items should be COMPLETE/INTERRUPTED/CANCELLED before being destroyed.
338 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE
, base::Bind(
339 &RevokeReservation
, download
));
346 void DownloadPathReservationTracker::GetReservedPath(
347 DownloadItem
* download_item
,
348 const base::FilePath
& target_path
,
349 const base::FilePath
& default_path
,
350 bool create_directory
,
351 FilenameConflictAction conflict_action
,
352 const ReservedPathCallback
& callback
) {
353 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
354 // Attach an observer to the download item so that we know when the target
355 // path changes and/or the download is no longer active.
356 new DownloadItemObserver(download_item
);
357 // DownloadItemObserver deletes itself.
359 base::FilePath
* reserved_path
= new base::FilePath
;
360 BrowserThread::PostTaskAndReplyWithResult(
363 base::Bind(&CreateReservation
,
370 base::Bind(&RunGetReservedPathCallback
,
372 base::Owned(reserved_path
)));
376 bool DownloadPathReservationTracker::IsPathInUseForTesting(
377 const base::FilePath
& path
) {
378 return IsPathInUse(path
);