Home | History | Annotate | Download | only in download
      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.
      4 
      5 #include "chrome/browser/download/download_path_reservation_tracker.h"
      6 
      7 #include <map>
      8 
      9 #include "base/bind.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"
     21 
     22 using content::BrowserThread;
     23 using content::DownloadItem;
     24 
     25 namespace {
     26 
     27 typedef DownloadItem* ReservationKey;
     28 typedef std::map<ReservationKey, base::FilePath> ReservationMap;
     29 
     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;
     33 
     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
     37 // possible filename.
     38 static const size_t kIntermediateNameSuffixLength = sizeof(".crdownload") - 1;
     39 
     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.
     43 //
     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;
     48 
     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 {
     53  public:
     54   explicit DownloadItemObserver(DownloadItem* download_item);
     55 
     56  private:
     57   virtual ~DownloadItemObserver();
     58 
     59   // DownloadItem::Observer
     60   virtual void OnDownloadUpdated(DownloadItem* download) OVERRIDE;
     61   virtual void OnDownloadDestroyed(DownloadItem* download) OVERRIDE;
     62 
     63   DownloadItem* download_item_;
     64 
     65   // Last known target path for the download.
     66   base::FilePath last_target_path_;
     67 
     68   DISALLOW_COPY_AND_ASSIGN(DownloadItemObserver);
     69 };
     70 
     71 // Returns true if the given path is in use by a path reservation.
     72 bool IsPathReserved(const base::FilePath& path) {
     73   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
     74   // No reservation map => no reservations.
     75   if (g_reservation_map == NULL)
     76     return false;
     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)
     84       return true;
     85   }
     86   return false;
     87 }
     88 
     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(BrowserThread::CurrentlyOn(BrowserThread::FILE));
     93   // If there is a reservation, then the path is in use.
     94   if (IsPathReserved(path))
     95     return true;
     96 
     97   // If the path exists in the file system, then the path is in use.
     98   if (base::PathExists(path))
     99     return true;
    100 
    101   return false;
    102 }
    103 
    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)
    113     return true;
    114 
    115   base::FilePath dir(path->DirName());
    116   base::FilePath::StringType ext(basename.Extension());
    117   base::FilePath::StringType name(basename.RemoveExtension().value());
    118 
    119   // Impossible to satisfy the limit.
    120   if (limit < kTruncatedNameLengthLowerbound + ext.size())
    121     return false;
    122   limit -= ext.size();
    123 
    124   // Encoding specific truncation logic.
    125   base::FilePath::StringType truncated;
    126 #if defined(OS_CHROMEOS) || defined(OS_MACOSX)
    127   // UTF-8.
    128   base::TruncateUTF8ToByteSize(name, limit, &truncated);
    129 #elif defined(OS_WIN)
    130   // UTF-16.
    131   DCHECK(name.size() > limit);
    132   truncated = name.substr(0, CBU16_IS_TRAIL(name[limit]) ? limit - 1 : limit);
    133 #else
    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.
    136 #endif
    137 
    138   if (truncated.size() < kTruncatedNameLengthLowerbound)
    139     return false;
    140   *path = dir.Append(truncated + ext);
    141   return true;
    142 }
    143 
    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
    147 //   writeable.
    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(
    152     ReservationKey key,
    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(BrowserThread::CurrentlyOn(BrowserThread::FILE));
    159   DCHECK(suggested_path.IsAbsolute());
    160 
    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;
    165 
    166   ReservationMap& reservations = *g_reservation_map;
    167   DCHECK(!ContainsKey(reservations, key));
    168 
    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;
    175 
    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) &&
    182       (create_directory ||
    183        (!default_download_path.empty() &&
    184         (default_download_path == target_dir)))) {
    185     base::CreateDirectory(target_dir);
    186   }
    187 
    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);
    195   }
    196 
    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;
    205     }
    206 
    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;
    212       }
    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;
    218             ++uniquifier) {
    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) {
    225             int limit =
    226                 max_length - kIntermediateNameSuffixLength - suffix.size();
    227             // If truncation failed, give up uniquification.
    228             if (limit <= 0 || !TruncateFileName(&path_to_check, limit))
    229               break;
    230           }
    231           path_to_check = path_to_check.InsertBeforeExtensionASCII(suffix);
    232 
    233           if (!IsPathInUse(path_to_check)) {
    234             target_path = path_to_check;
    235             has_conflicts = false;
    236             break;
    237           }
    238         }
    239       }
    240     }
    241   }
    242 
    243   reservations[key] = target_path;
    244   bool verified = (is_path_writeable && !has_conflicts && !name_too_long);
    245   *reserved_path = target_path;
    246   return verified;
    247 }
    248 
    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(BrowserThread::CurrentlyOn(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;
    257   } else {
    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.
    261     NOTREACHED();
    262   }
    263 }
    264 
    265 // Called on the FILE thread to remove the path reservation associated with
    266 // |key|.
    267 void RevokeReservation(ReservationKey key) {
    268   DCHECK(BrowserThread::CurrentlyOn(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;
    276   }
    277 }
    278 
    279 void RunGetReservedPathCallback(
    280     const DownloadPathReservationTracker::ReservedPathCallback& callback,
    281     const base::FilePath* reserved_path,
    282     bool verified) {
    283   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
    284   callback.Run(*reserved_path, verified);
    285 }
    286 
    287 DownloadItemObserver::DownloadItemObserver(DownloadItem* download_item)
    288     : download_item_(download_item),
    289       last_target_path_(download_item->GetTargetFilePath()) {
    290   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
    291   download_item_->AddObserver(this);
    292 }
    293 
    294 DownloadItemObserver::~DownloadItemObserver() {
    295   download_item_->RemoveObserver(this);
    296 }
    297 
    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;
    307       }
    308       break;
    309     }
    310 
    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.
    315 
    316     case DownloadItem::CANCELLED:
    317       // We no longer need the reservation if the download is being removed.
    318 
    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.
    323 
    324       BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE, base::Bind(
    325           &RevokeReservation, download));
    326       delete this;
    327       break;
    328 
    329     case DownloadItem::MAX_DOWNLOAD_STATE:
    330       // Compiler appeasement.
    331       NOTREACHED();
    332   }
    333 }
    334 
    335 void DownloadItemObserver::OnDownloadDestroyed(DownloadItem* download) {
    336   // Items should be COMPLETE/INTERRUPTED/CANCELLED before being destroyed.
    337   NOTREACHED();
    338   BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE, base::Bind(
    339       &RevokeReservation, download));
    340   delete this;
    341 }
    342 
    343 }  // namespace
    344 
    345 // static
    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(BrowserThread::CurrentlyOn(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.
    358 
    359   base::FilePath* reserved_path = new base::FilePath;
    360   BrowserThread::PostTaskAndReplyWithResult(
    361       BrowserThread::FILE,
    362       FROM_HERE,
    363       base::Bind(&CreateReservation,
    364                  download_item,
    365                  target_path,
    366                  default_path,
    367                  create_directory,
    368                  conflict_action,
    369                  reserved_path),
    370       base::Bind(&RunGetReservedPathCallback,
    371                  callback,
    372                  base::Owned(reserved_path)));
    373 }
    374 
    375 // static
    376 bool DownloadPathReservationTracker::IsPathInUseForTesting(
    377     const base::FilePath& path) {
    378   return IsPathInUse(path);
    379 }
    380