Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(204)

Side by Side Diff: chrome/browser/download/download_path_reservation_tracker.cc

Issue 12212010: Truncate the download file name if it exceeds the filesystem limit. (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: Add test. Created 7 years, 10 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 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 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "chrome/browser/download/download_path_reservation_tracker.h" 5 #include "chrome/browser/download/download_path_reservation_tracker.h"
6 6
7 #include <map> 7 #include <map>
8 8
9 #include "base/bind.h" 9 #include "base/bind.h"
10 #include "base/callback.h" 10 #include "base/callback.h"
11 #include "base/file_util.h" 11 #include "base/file_util.h"
12 #include "base/logging.h" 12 #include "base/logging.h"
13 #include "base/path_service.h" 13 #include "base/path_service.h"
14 #include "base/stl_util.h" 14 #include "base/stl_util.h"
15 #include "base/string_util.h"
16 #include "base/stringprintf.h"
17 #include "base/third_party/icu/icu_utf.h"
15 #include "chrome/browser/download/download_util.h" 18 #include "chrome/browser/download/download_util.h"
16 #include "chrome/common/chrome_paths.h" 19 #include "chrome/common/chrome_paths.h"
17 #include "content/public/browser/browser_thread.h" 20 #include "content/public/browser/browser_thread.h"
18 #include "content/public/browser/download_id.h" 21 #include "content/public/browser/download_id.h"
19 #include "content/public/browser/download_item.h" 22 #include "content/public/browser/download_item.h"
20 23
21 using content::BrowserThread; 24 using content::BrowserThread;
22 using content::DownloadId; 25 using content::DownloadId;
23 using content::DownloadItem; 26 using content::DownloadItem;
24 27
25 namespace { 28 namespace {
26 29
27 typedef std::map<content::DownloadId, base::FilePath> ReservationMap; 30 typedef std::map<content::DownloadId, base::FilePath> ReservationMap;
28 31
32 // The lower bound for file name truncation. If the truncation results in a name
33 // shorter than this limit, we give up automatic truncation and prompt the user.
34 static const size_t kTruncatedNameLengthLowerbound = 5;
tfarina 2013/03/14 16:00:48 nit: you are already in unnamed namespace, static
35
36 // The length of the suffix string we append for an intermediate file name.
37 // In the file name truncation, we keep the margin to append the suffix.
38 // TODO(kinaba): remove the margin. The user should be able to set maximum
39 // possible filename.
40 static const size_t kIntermediateNameSuffixLength = sizeof(".crdownload") - 1;
41
29 // Map of download path reservations. Each reserved path is associated with a 42 // Map of download path reservations. Each reserved path is associated with a
30 // DownloadId. This object is destroyed in |Revoke()| when there are no more 43 // DownloadId. This object is destroyed in |Revoke()| when there are no more
31 // reservations. 44 // reservations.
32 // 45 //
33 // It is not an error, although undesirable, to have multiple DownloadIds that 46 // It is not an error, although undesirable, to have multiple DownloadIds that
34 // are mapped to the same path. This can happen if a reservation is created that 47 // are mapped to the same path. This can happen if a reservation is created that
35 // is supposed to overwrite an existing reservation. 48 // is supposed to overwrite an existing reservation.
36 ReservationMap* g_reservation_map = NULL; 49 ReservationMap* g_reservation_map = NULL;
37 50
38 // Observes a DownloadItem for changes to its target path and state. Updates or 51 // Observes a DownloadItem for changes to its target path and state. Updates or
(...skipping 44 matching lines...) Expand 10 before | Expand all | Expand 10 after
83 if (IsPathReserved(path)) 96 if (IsPathReserved(path))
84 return true; 97 return true;
85 98
86 // If the path exists in the file system, then the path is in use. 99 // If the path exists in the file system, then the path is in use.
87 if (file_util::PathExists(path)) 100 if (file_util::PathExists(path))
88 return true; 101 return true;
89 102
90 return false; 103 return false;
91 } 104 }
92 105
106 // Truncates path->BaseName() to make path->BaseName().value().size() <= limit.
107 // - It keeps the extension as is. Only truncates the body part.
108 // - It secures the base filename length to be more than or equals to
109 // kTruncatedNameLengthLowerbound.
110 // If it was unable to shorten the name, returns false.
111 bool TruncateFileName(base::FilePath* path, size_t limit) {
112 base::FilePath basename(path->BaseName());
113 // It is already short enough.
114 if (basename.value().size() <= limit)
115 return true;
116
117 base::FilePath dir(path->DirName());
118 base::FilePath::StringType ext(basename.Extension());
119 base::FilePath::StringType name(basename.RemoveExtension().value());
120
121 // Impossible to satisfy the limit.
122 if (limit < kTruncatedNameLengthLowerbound + ext.size())
123 return false;
124 limit -= ext.size();
125
126 // Encoding specific truncation logic.
127 base::FilePath::StringType truncated;
128 #if defined(OS_CHROMEOS) || defined(OS_MACOSX)
129 // UTF-8.
130 TruncateUTF8ToByteSize(name, limit, &truncated);
131 #elif defined(OS_WIN)
132 // UTF-16.
133 DCHECK(name.size() > limit);
134 truncated = name.substr(0, CBU16_IS_TRAIL(name[limit]) ? limit - 1 : limit);
135 #else
136 // We cannot generally assume that the file name encoding is in UTF-8 (see
137 // the comment for FilePath::AsUTF8Unsafe), hence no safe way to truncate.
138 #endif
139
140 if (truncated.size() < kTruncatedNameLengthLowerbound)
141 return false;
142 *path = dir.Append(truncated + ext);
143 return true;
144 }
145
93 // Called on the FILE thread to reserve a download path. This method: 146 // Called on the FILE thread to reserve a download path. This method:
94 // - Creates directory |default_download_path| if it doesn't exist. 147 // - Creates directory |default_download_path| if it doesn't exist.
95 // - Verifies that the parent directory of |suggested_path| exists and is 148 // - Verifies that the parent directory of |suggested_path| exists and is
96 // writeable. 149 // writeable.
150 // - Truncates the suggested name if it exceeds the filesystem's limit.
97 // - Uniquifies |suggested_path| if |should_uniquify_path| is true. 151 // - Uniquifies |suggested_path| if |should_uniquify_path| is true.
98 // - Schedules |callback| on the UI thread with the reserved path and a flag 152 // - Schedules |callback| on the UI thread with the reserved path and a flag
99 // indicating whether the returned path has been successfully verified. 153 // indicating whether the returned path has been successfully verified.
100 void CreateReservation( 154 void CreateReservation(
101 DownloadId download_id, 155 DownloadId download_id,
102 const base::FilePath& suggested_path, 156 const base::FilePath& suggested_path,
103 const base::FilePath& default_download_path, 157 const base::FilePath& default_download_path,
104 bool should_uniquify, 158 bool should_uniquify,
105 const DownloadPathReservationTracker::ReservedPathCallback& callback) { 159 const DownloadPathReservationTracker::ReservedPathCallback& callback) {
106 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); 160 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
107 DCHECK(download_id.IsValid()); 161 DCHECK(download_id.IsValid());
108 DCHECK(suggested_path.IsAbsolute()); 162 DCHECK(suggested_path.IsAbsolute());
109 163
110 // Create a reservation map if one doesn't exist. It will be automatically 164 // Create a reservation map if one doesn't exist. It will be automatically
111 // deleted when all the reservations are revoked. 165 // deleted when all the reservations are revoked.
112 if (g_reservation_map == NULL) 166 if (g_reservation_map == NULL)
113 g_reservation_map = new ReservationMap; 167 g_reservation_map = new ReservationMap;
114 168
115 ReservationMap& reservations = *g_reservation_map; 169 ReservationMap& reservations = *g_reservation_map;
116 DCHECK(!ContainsKey(reservations, download_id)); 170 DCHECK(!ContainsKey(reservations, download_id));
117 171
118 base::FilePath target_path(suggested_path.NormalizePathSeparators()); 172 base::FilePath target_path(suggested_path.NormalizePathSeparators());
119 bool is_path_writeable = true; 173 bool is_path_writeable = true;
120 bool has_conflicts = false; 174 bool has_conflicts = false;
175 bool name_too_long = false;
121 176
122 // Create the default download path if it doesn't already exist and is where 177 // Create the default download path if it doesn't already exist and is where
123 // we are going to create the downloaded file. |target_path| might point 178 // we are going to create the downloaded file. |target_path| might point
124 // elsewhere if this was a programmatic download. 179 // elsewhere if this was a programmatic download.
125 if (!default_download_path.empty() && 180 if (!default_download_path.empty() &&
126 default_download_path == target_path.DirName() && 181 default_download_path == target_path.DirName() &&
127 !file_util::DirectoryExists(default_download_path)) { 182 !file_util::DirectoryExists(default_download_path)) {
128 file_util::CreateDirectory(default_download_path); 183 file_util::CreateDirectory(default_download_path);
129 } 184 }
130 185
131 // Check writability of the suggested path. If we can't write to it, default 186 // Check writability of the suggested path. If we can't write to it, default
132 // to the user's "My Documents" directory. We'll prompt them in this case. 187 // to the user's "My Documents" directory. We'll prompt them in this case.
133 base::FilePath dir = target_path.DirName(); 188 base::FilePath dir = target_path.DirName();
134 base::FilePath filename = target_path.BaseName(); 189 base::FilePath filename = target_path.BaseName();
135 if (!file_util::PathIsWritable(dir)) { 190 if (!file_util::PathIsWritable(dir)) {
136 DVLOG(1) << "Unable to write to directory \"" << dir.value() << "\""; 191 DVLOG(1) << "Unable to write to directory \"" << dir.value() << "\"";
137 is_path_writeable = false; 192 is_path_writeable = false;
138 PathService::Get(chrome::DIR_USER_DOCUMENTS, &dir); 193 PathService::Get(chrome::DIR_USER_DOCUMENTS, &dir);
139 target_path = dir.Append(filename); 194 target_path = dir.Append(filename);
140 } 195 }
141 196
142 if (is_path_writeable && should_uniquify && IsPathInUse(target_path)) { 197 if (is_path_writeable) {
143 has_conflicts = true; 198 // Check the limit of file name length if it could be obtained. When the
144 for (int uniquifier = 1; 199 // suggested name exceeds the limit, truncate or prompt the user.
145 uniquifier <= DownloadPathReservationTracker::kMaxUniqueFiles; 200 int max_length = file_util::GetMaximumPathComponentLength(dir);
146 ++uniquifier) { 201 if (max_length != -1) {
147 base::FilePath path_to_check(target_path.InsertBeforeExtensionASCII( 202 int limit = max_length - kIntermediateNameSuffixLength;
148 StringPrintf(" (%d)", uniquifier))); 203 if (limit <= 0 || !TruncateFileName(&target_path, limit))
149 if (!IsPathInUse(path_to_check)) { 204 name_too_long = true;
150 target_path = path_to_check; 205 }
151 has_conflicts = false; 206
152 break; 207 // Uniquify the name, if it already exists.
208 if (!name_too_long && should_uniquify && IsPathInUse(target_path)) {
209 has_conflicts = true;
210 for (int uniquifier = 1;
211 uniquifier <= DownloadPathReservationTracker::kMaxUniqueFiles;
212 ++uniquifier) {
213 // Append uniquifier.
214 std::string suffix(base::StringPrintf(" (%d)", uniquifier));
215 base::FilePath path_to_check(target_path);
216 // If the name length limit is available (max_length != -1), and the
217 // the current name exceeds the limit, truncate.
218 if (max_length != -1) {
219 int limit =
220 max_length - kIntermediateNameSuffixLength - suffix.size();
221 // If truncation failed, give up uniquification.
222 if (limit <= 0 || !TruncateFileName(&path_to_check, limit))
223 break;
224 }
225 path_to_check = path_to_check.InsertBeforeExtensionASCII(suffix);
226
227 if (!IsPathInUse(path_to_check)) {
228 target_path = path_to_check;
229 has_conflicts = false;
230 break;
231 }
153 } 232 }
154 } 233 }
155 } 234 }
235
156 reservations[download_id] = target_path; 236 reservations[download_id] = target_path;
157 BrowserThread::PostTask( 237 bool verified = (is_path_writeable && !has_conflicts && !name_too_long);
158 BrowserThread::UI, FROM_HERE, 238 BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
159 base::Bind(callback, target_path, (is_path_writeable && !has_conflicts))); 239 base::Bind(callback, target_path, verified));
160 } 240 }
161 241
162 // Called on the FILE thread to update the path of the reservation associated 242 // Called on the FILE thread to update the path of the reservation associated
163 // with |download_id| to |new_path|. 243 // with |download_id| to |new_path|.
164 void UpdateReservation(DownloadId download_id, const base::FilePath& new_path) { 244 void UpdateReservation(DownloadId download_id, const base::FilePath& new_path) {
165 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); 245 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
166 DCHECK(g_reservation_map != NULL); 246 DCHECK(g_reservation_map != NULL);
167 ReservationMap::iterator iter = g_reservation_map->find(download_id); 247 ReservationMap::iterator iter = g_reservation_map->find(download_id);
168 if (iter != g_reservation_map->end()) { 248 if (iter != g_reservation_map->end()) {
169 iter->second = new_path; 249 iter->second = new_path;
(...skipping 97 matching lines...) Expand 10 before | Expand all | Expand 10 after
267 BrowserThread::FILE, FROM_HERE, 347 BrowserThread::FILE, FROM_HERE,
268 base::Bind(&CreateReservation, download_item.GetGlobalId(), 348 base::Bind(&CreateReservation, download_item.GetGlobalId(),
269 target_path, default_path, uniquify_path, callback)); 349 target_path, default_path, uniquify_path, callback));
270 } 350 }
271 351
272 // static 352 // static
273 bool DownloadPathReservationTracker::IsPathInUseForTesting( 353 bool DownloadPathReservationTracker::IsPathInUseForTesting(
274 const base::FilePath& path) { 354 const base::FilePath& path) {
275 return IsPathInUse(path); 355 return IsPathInUse(path);
276 } 356 }
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698