3 Copyright (C) 2010 celeron55, Perttu Ahola <celeron55@gmail.com>
4 Copyright (C) 2012 Jonathan Neuschäfer <j.neuschaefer@gmx.net>
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2 of the License, or
9 (at your option) any later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License along
17 with this program; if not, write to the Free Software Foundation, Inc.,
18 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21 #include "filecache.h"
22 #include "clientserver.h"
32 bool FileCache::loadByPath(const std::string &path, std::ostream &os)
34 std::ifstream fis(path.c_str(), std::ios_base::binary);
37 verbosestream<<"FileCache: File not found in cache: "
46 std::streamsize len = fis.gcount();
56 errorstream<<"FileCache: Failed to read file from cache: \""
57 <<path<<"\""<<std::endl;
63 bool FileCache::updateByPath(const std::string &path, const std::string &data)
65 std::ofstream file(path.c_str(), std::ios_base::binary |
66 std::ios_base::trunc);
70 errorstream<<"FileCache: Can't write to file at "
75 file.write(data.c_str(), data.length());
81 bool FileCache::update(const std::string &name, const std::string &data)
83 std::string path = m_dir + DIR_DELIM + name;
84 return updateByPath(path, data);
86 bool FileCache::update_sha1(const std::string &data)
89 sha1.addBytes(data.c_str(), data.size());
90 unsigned char *digest = sha1.getDigest();
91 std::string sha1_raw((char*)digest, 20);
93 std::string sha1_hex = hex_encode(sha1_raw);
94 return update(sha1_hex, data);
96 bool FileCache::load(const std::string &name, std::ostream &os)
98 std::string path = m_dir + DIR_DELIM + name;
99 return loadByPath(path, os);
101 bool FileCache::load_sha1(const std::string &sha1_raw, std::ostream &os)
103 std::ostringstream tmp_os(std::ios_base::binary);
104 if(!load(hex_encode(sha1_raw), tmp_os))
107 sha1.addBytes(tmp_os.str().c_str(), tmp_os.str().length());
108 unsigned char *digest = sha1.getDigest();
109 std::string sha1_real_raw((char*)digest, 20);
111 if(sha1_real_raw != sha1_raw){
112 verbosestream<<"FileCache["<<m_dir<<"]: filename "<<sha1_real_raw
113 <<" mismatches actual checksum"<<std::endl;