You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

364 lines
11 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /*
  2. * libjingle
  3. * Copyright 2004--2005, Google Inc.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice,
  9. * this list of conditions and the following disclaimer.
  10. * 2. Redistributions in binary form must reproduce the above copyright notice,
  11. * this list of conditions and the following disclaimer in the documentation
  12. * and/or other materials provided with the distribution.
  13. * 3. The name of the author may not be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
  17. * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  18. * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
  19. * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  20. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  21. * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
  22. * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  23. * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
  24. * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  25. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. #include <time.h>
  28. #ifdef WIN32
  29. #include "talk/base/win32.h"
  30. #endif
  31. #include "talk/base/common.h"
  32. #include "talk/base/diskcache.h"
  33. #include "talk/base/fileutils.h"
  34. #include "talk/base/pathutils.h"
  35. #include "talk/base/stream.h"
  36. #include "talk/base/stringencode.h"
  37. #include "talk/base/stringutils.h"
  38. #ifdef _DEBUG
  39. #define TRANSPARENT_CACHE_NAMES 1
  40. #else // !_DEBUG
  41. #define TRANSPARENT_CACHE_NAMES 0
  42. #endif // !_DEBUG
  43. namespace talk_base {
  44. class DiskCache;
  45. ///////////////////////////////////////////////////////////////////////////////
  46. // DiskCacheAdapter
  47. ///////////////////////////////////////////////////////////////////////////////
  48. class DiskCacheAdapter : public StreamAdapterInterface {
  49. public:
  50. DiskCacheAdapter(const DiskCache* cache, const std::string& id, size_t index,
  51. StreamInterface* stream)
  52. : StreamAdapterInterface(stream), cache_(cache), id_(id), index_(index)
  53. { }
  54. virtual ~DiskCacheAdapter() {
  55. Close();
  56. cache_->ReleaseResource(id_, index_);
  57. }
  58. private:
  59. const DiskCache* cache_;
  60. std::string id_;
  61. size_t index_;
  62. };
  63. ///////////////////////////////////////////////////////////////////////////////
  64. // DiskCache
  65. ///////////////////////////////////////////////////////////////////////////////
  66. DiskCache::DiskCache() : max_cache_(0), total_size_(0), total_accessors_(0) {
  67. }
  68. DiskCache::~DiskCache() {
  69. ASSERT(0 == total_accessors_);
  70. }
  71. bool DiskCache::Initialize(const std::string& folder, size_t size) {
  72. if (!folder_.empty() || !Filesystem::CreateFolder(folder))
  73. return false;
  74. folder_ = folder;
  75. max_cache_ = size;
  76. ASSERT(0 == total_size_);
  77. if (!InitializeEntries())
  78. return false;
  79. return CheckLimit();
  80. }
  81. bool DiskCache::Purge() {
  82. if (folder_.empty())
  83. return false;
  84. if (total_accessors_ > 0) {
  85. LOG_F(LS_WARNING) << "Cache files open";
  86. return false;
  87. }
  88. if (!PurgeFiles())
  89. return false;
  90. map_.clear();
  91. return true;
  92. }
  93. bool DiskCache::LockResource(const std::string& id) {
  94. Entry* entry = GetOrCreateEntry(id, true);
  95. if (LS_LOCKED == entry->lock_state)
  96. return false;
  97. if ((LS_UNLOCKED == entry->lock_state) && (entry->accessors > 0))
  98. return false;
  99. if ((total_size_ > max_cache_) && !CheckLimit()) {
  100. LOG_F(LS_WARNING) << "Cache overfull";
  101. return false;
  102. }
  103. entry->lock_state = LS_LOCKED;
  104. return true;
  105. }
  106. StreamInterface* DiskCache::WriteResource(const std::string& id, size_t index) {
  107. Entry* entry = GetOrCreateEntry(id, false);
  108. if (LS_LOCKED != entry->lock_state)
  109. return NULL;
  110. size_t previous_size = 0;
  111. std::string filename(IdToFilename(id, index));
  112. FileStream::GetSize(filename, &previous_size);
  113. ASSERT(previous_size <= entry->size);
  114. if (previous_size > entry->size) {
  115. previous_size = entry->size;
  116. }
  117. scoped_ptr<FileStream> file(new FileStream);
  118. if (!file->Open(filename, "wb", NULL)) {
  119. LOG_F(LS_ERROR) << "Couldn't create cache file";
  120. return NULL;
  121. }
  122. entry->streams = stdmax(entry->streams, index + 1);
  123. entry->size -= previous_size;
  124. total_size_ -= previous_size;
  125. entry->accessors += 1;
  126. total_accessors_ += 1;
  127. return new DiskCacheAdapter(this, id, index, file.release());
  128. }
  129. bool DiskCache::UnlockResource(const std::string& id) {
  130. Entry* entry = GetOrCreateEntry(id, false);
  131. if (LS_LOCKED != entry->lock_state)
  132. return false;
  133. if (entry->accessors > 0) {
  134. entry->lock_state = LS_UNLOCKING;
  135. } else {
  136. entry->lock_state = LS_UNLOCKED;
  137. entry->last_modified = time(0);
  138. CheckLimit();
  139. }
  140. return true;
  141. }
  142. StreamInterface* DiskCache::ReadResource(const std::string& id,
  143. size_t index) const {
  144. const Entry* entry = GetEntry(id);
  145. if (LS_UNLOCKED != entry->lock_state)
  146. return NULL;
  147. if (index >= entry->streams)
  148. return NULL;
  149. scoped_ptr<FileStream> file(new FileStream);
  150. if (!file->Open(IdToFilename(id, index), "rb", NULL))
  151. return NULL;
  152. entry->accessors += 1;
  153. total_accessors_ += 1;
  154. return new DiskCacheAdapter(this, id, index, file.release());
  155. }
  156. bool DiskCache::HasResource(const std::string& id) const {
  157. const Entry* entry = GetEntry(id);
  158. return (NULL != entry) && (entry->streams > 0);
  159. }
  160. bool DiskCache::HasResourceStream(const std::string& id, size_t index) const {
  161. const Entry* entry = GetEntry(id);
  162. if ((NULL == entry) || (index >= entry->streams))
  163. return false;
  164. std::string filename = IdToFilename(id, index);
  165. return FileExists(filename);
  166. }
  167. bool DiskCache::DeleteResource(const std::string& id) {
  168. Entry* entry = GetOrCreateEntry(id, false);
  169. if (!entry)
  170. return true;
  171. if ((LS_UNLOCKED != entry->lock_state) || (entry->accessors > 0))
  172. return false;
  173. bool success = true;
  174. for (size_t index = 0; index < entry->streams; ++index) {
  175. std::string filename = IdToFilename(id, index);
  176. if (!FileExists(filename))
  177. continue;
  178. if (!DeleteFile(filename)) {
  179. LOG_F(LS_ERROR) << "Couldn't remove cache file: " << filename;
  180. success = false;
  181. }
  182. }
  183. total_size_ -= entry->size;
  184. map_.erase(id);
  185. return success;
  186. }
  187. bool DiskCache::CheckLimit() {
  188. #ifdef _DEBUG
  189. // Temporary check to make sure everything is working correctly.
  190. size_t cache_size = 0;
  191. for (EntryMap::iterator it = map_.begin(); it != map_.end(); ++it) {
  192. cache_size += it->second.size;
  193. }
  194. ASSERT(cache_size == total_size_);
  195. #endif // _DEBUG
  196. // TODO: Replace this with a non-brain-dead algorithm for clearing out the
  197. // oldest resources... something that isn't O(n^2)
  198. while (total_size_ > max_cache_) {
  199. EntryMap::iterator oldest = map_.end();
  200. for (EntryMap::iterator it = map_.begin(); it != map_.end(); ++it) {
  201. if ((LS_UNLOCKED != it->second.lock_state) || (it->second.accessors > 0))
  202. continue;
  203. oldest = it;
  204. break;
  205. }
  206. if (oldest == map_.end()) {
  207. LOG_F(LS_WARNING) << "All resources are locked!";
  208. return false;
  209. }
  210. for (EntryMap::iterator it = oldest++; it != map_.end(); ++it) {
  211. if (it->second.last_modified < oldest->second.last_modified) {
  212. oldest = it;
  213. }
  214. }
  215. if (!DeleteResource(oldest->first)) {
  216. LOG_F(LS_ERROR) << "Couldn't delete from cache!";
  217. return false;
  218. }
  219. }
  220. return true;
  221. }
  222. std::string DiskCache::IdToFilename(const std::string& id, size_t index) const {
  223. #ifdef TRANSPARENT_CACHE_NAMES
  224. // This escapes colons and other filesystem characters, so the user can't open
  225. // special devices (like "COM1:"), or access other directories.
  226. size_t buffer_size = id.length()*3 + 1;
  227. char* buffer = new char[buffer_size];
  228. encode(buffer, buffer_size, id.data(), id.length(),
  229. unsafe_filename_characters(), '%');
  230. // TODO: ASSERT(strlen(buffer) < FileSystem::MaxBasenameLength());
  231. #else // !TRANSPARENT_CACHE_NAMES
  232. // We might want to just use a hash of the filename at some point, both for
  233. // obfuscation, and to avoid both filename length and escaping issues.
  234. ASSERT(false);
  235. #endif // !TRANSPARENT_CACHE_NAMES
  236. char extension[32];
  237. sprintfn(extension, ARRAY_SIZE(extension), ".%u", index);
  238. Pathname pathname;
  239. pathname.SetFolder(folder_);
  240. pathname.SetBasename(buffer);
  241. pathname.SetExtension(extension);
  242. #ifdef TRANSPARENT_CACHE_NAMES
  243. delete [] buffer;
  244. #endif // TRANSPARENT_CACHE_NAMES
  245. return pathname.pathname();
  246. }
  247. bool DiskCache::FilenameToId(const std::string& filename, std::string* id,
  248. size_t* index) const {
  249. Pathname pathname(filename);
  250. unsigned tempdex;
  251. if (1 != sscanf(pathname.extension().c_str(), ".%u", &tempdex))
  252. return false;
  253. *index = static_cast<size_t>(tempdex);
  254. size_t buffer_size = pathname.basename().length() + 1;
  255. char* buffer = new char[buffer_size];
  256. decode(buffer, buffer_size, pathname.basename().data(),
  257. pathname.basename().length(), '%');
  258. id->assign(buffer);
  259. delete [] buffer;
  260. return true;
  261. }
  262. DiskCache::Entry* DiskCache::GetOrCreateEntry(const std::string& id,
  263. bool create) {
  264. EntryMap::iterator it = map_.find(id);
  265. if (it != map_.end())
  266. return &it->second;
  267. if (!create)
  268. return NULL;
  269. Entry e;
  270. e.lock_state = LS_UNLOCKED;
  271. e.accessors = 0;
  272. e.size = 0;
  273. e.streams = 0;
  274. e.last_modified = time(0);
  275. it = map_.insert(EntryMap::value_type(id, e)).first;
  276. return &it->second;
  277. }
  278. void DiskCache::ReleaseResource(const std::string& id, size_t index) const {
  279. const Entry* entry = GetEntry(id);
  280. if (!entry) {
  281. LOG_F(LS_WARNING) << "Missing cache entry";
  282. ASSERT(false);
  283. return;
  284. }
  285. entry->accessors -= 1;
  286. total_accessors_ -= 1;
  287. if (LS_UNLOCKED != entry->lock_state) {
  288. // This is safe, because locked resources only issue WriteResource, which
  289. // is non-const. Think about a better way to handle it.
  290. DiskCache* this2 = const_cast<DiskCache*>(this);
  291. Entry* entry2 = this2->GetOrCreateEntry(id, false);
  292. size_t new_size = 0;
  293. std::string filename(IdToFilename(id, index));
  294. FileStream::GetSize(filename, &new_size);
  295. entry2->size += new_size;
  296. this2->total_size_ += new_size;
  297. if ((LS_UNLOCKING == entry->lock_state) && (0 == entry->accessors)) {
  298. entry2->last_modified = time(0);
  299. entry2->lock_state = LS_UNLOCKED;
  300. this2->CheckLimit();
  301. }
  302. }
  303. }
  304. ///////////////////////////////////////////////////////////////////////////////
  305. } // namespace talk_base