CookieStorage.cc 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. /* <!-- copyright */
  2. /*
  3. * aria2 - The high speed download utility
  4. *
  5. * Copyright (C) 2006 Tatsuhiro Tsujikawa
  6. *
  7. * This program is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. *
  21. * In addition, as a special exception, the copyright holders give
  22. * permission to link the code of portions of this program with the
  23. * OpenSSL library under certain conditions as described in each
  24. * individual source file, and distribute linked combinations
  25. * including the two.
  26. * You must obey the GNU General Public License in all respects
  27. * for all of the code used other than OpenSSL. If you modify
  28. * file(s) with this exception, you may extend this exception to your
  29. * version of the file(s), but you are not obligated to do so. If you
  30. * do not wish to do so, delete this exception statement from your
  31. * version. If you delete this exception statement from all source
  32. * files in the program, then also delete it here.
  33. */
  34. /* copyright --> */
  35. #include "CookieStorage.h"
  36. #include <cstring>
  37. #include <algorithm>
  38. #include <fstream>
  39. #include "util.h"
  40. #include "LogFactory.h"
  41. #include "Logger.h"
  42. #include "DlAbortEx.h"
  43. #include "fmt.h"
  44. #include "NsCookieParser.h"
  45. #include "File.h"
  46. #include "a2functional.h"
  47. #include "A2STR.h"
  48. #include "message.h"
  49. #include "cookie_helper.h"
  50. #ifdef HAVE_SQLITE3
  51. # include "Sqlite3CookieParserImpl.h"
  52. #endif // HAVE_SQLITE3
  53. namespace aria2 {
  54. CookieStorage::DomainEntry::DomainEntry(const std::string& domain)
  55. : key_(util::isNumericHost(domain)?domain:cookie::reverseDomainLevel(domain))
  56. {}
  57. CookieStorage::DomainEntry::DomainEntry
  58. (const DomainEntry& c)
  59. : key_(c.key_),
  60. lastAccessTime_(c.lastAccessTime_),
  61. cookies_(c.cookies_)
  62. {}
  63. CookieStorage::DomainEntry::~DomainEntry() {}
  64. CookieStorage::DomainEntry& CookieStorage::DomainEntry::operator=
  65. (const DomainEntry& c)
  66. {
  67. if(this != &c) {
  68. key_ = c.key_;
  69. lastAccessTime_ = c.lastAccessTime_;
  70. cookies_ = c.cookies_;
  71. }
  72. return *this;
  73. }
  74. void CookieStorage::DomainEntry::swap(CookieStorage::DomainEntry& c)
  75. {
  76. using std::swap;
  77. swap(key_, c.key_);
  78. swap(lastAccessTime_, c.lastAccessTime_);
  79. swap(cookies_, c.cookies_);
  80. }
  81. void swap(CookieStorage::DomainEntry& a, CookieStorage::DomainEntry& b)
  82. {
  83. a.swap(b);
  84. }
  85. bool CookieStorage::DomainEntry::addCookie(const Cookie& cookie, time_t now)
  86. {
  87. setLastAccessTime(now);
  88. std::deque<Cookie>::iterator i =
  89. std::find(cookies_.begin(), cookies_.end(), cookie);
  90. if(i == cookies_.end()) {
  91. if(cookie.isExpired(now)) {
  92. return false;
  93. } else {
  94. if(cookies_.size() >= CookieStorage::MAX_COOKIE_PER_DOMAIN) {
  95. cookies_.erase
  96. (std::remove_if(cookies_.begin(), cookies_.end(),
  97. std::bind2nd
  98. (std::mem_fun_ref(&Cookie::isExpired), now)),
  99. cookies_.end());
  100. if(cookies_.size() >= CookieStorage::MAX_COOKIE_PER_DOMAIN) {
  101. std::deque<Cookie>::iterator m = std::min_element
  102. (cookies_.begin(), cookies_.end(), LeastRecentAccess<Cookie>());
  103. *m = cookie;
  104. } else {
  105. cookies_.push_back(cookie);
  106. }
  107. } else {
  108. cookies_.push_back(cookie);
  109. }
  110. return true;
  111. }
  112. } else if(cookie.isExpired(now)) {
  113. cookies_.erase(i);
  114. return false;
  115. } else {
  116. *i = cookie;
  117. return true;
  118. }
  119. }
  120. bool CookieStorage::DomainEntry::contains(const Cookie& cookie) const
  121. {
  122. return std::find(cookies_.begin(), cookies_.end(), cookie) != cookies_.end();
  123. }
  124. void CookieStorage::DomainEntry::writeCookie(std::ostream& o) const
  125. {
  126. for(std::deque<Cookie>::const_iterator i = cookies_.begin(),
  127. eoi = cookies_.end(); i != eoi; ++i) {
  128. o << (*i).toNsCookieFormat() << "\n";
  129. }
  130. }
  131. size_t CookieStorage::DomainEntry::countCookie() const
  132. {
  133. return cookies_.size();
  134. }
  135. bool CookieStorage::DomainEntry::operator<(const DomainEntry& de) const
  136. {
  137. return key_ < de.key_;
  138. }
  139. CookieStorage::CookieStorage() {}
  140. CookieStorage::~CookieStorage() {}
  141. namespace {
  142. // See CookieStorageTest::testDomainIsFull() in CookieStorageTest.cc
  143. const size_t DOMAIN_EVICTION_TRIGGER = 2000;
  144. const double DOMAIN_EVICTION_RATE = 0.1;
  145. } // namespace
  146. bool CookieStorage::store(const Cookie& cookie, time_t now)
  147. {
  148. if(domains_.size() >= DOMAIN_EVICTION_TRIGGER) {
  149. std::sort(domains_.begin(), domains_.end(),
  150. LeastRecentAccess<DomainEntry>());
  151. size_t delnum = (size_t)(domains_.size()*DOMAIN_EVICTION_RATE);
  152. domains_.erase(domains_.begin(), domains_.begin()+delnum);
  153. std::sort(domains_.begin(), domains_.end());
  154. }
  155. DomainEntry v(cookie.getDomain());
  156. std::deque<DomainEntry>::iterator i =
  157. std::lower_bound(domains_.begin(), domains_.end(), v);
  158. bool added = false;
  159. if(i != domains_.end() && (*i).getKey() == v.getKey()) {
  160. added = (*i).addCookie(cookie, now);
  161. } else {
  162. added = v.addCookie(cookie, now);
  163. if(added) {
  164. domains_.insert(i, v);
  165. }
  166. }
  167. return added;
  168. }
  169. bool CookieStorage::parseAndStore
  170. (const std::string& setCookieString,
  171. const std::string& requestHost,
  172. const std::string& defaultPath,
  173. time_t now)
  174. {
  175. Cookie cookie;
  176. if(cookie::parse(cookie, setCookieString, requestHost, defaultPath, now)) {
  177. return store(cookie, now);
  178. } else {
  179. return false;
  180. }
  181. }
  182. struct CookiePathDivider {
  183. Cookie cookie_;
  184. int pathDepth_;
  185. CookiePathDivider(const Cookie& cookie):cookie_(cookie)
  186. {
  187. std::vector<std::string> paths;
  188. util::split(cookie_.getPath(), std::back_inserter(paths), A2STR::SLASH_C);
  189. pathDepth_ = paths.size();
  190. }
  191. };
  192. namespace {
  193. class CookiePathDividerConverter {
  194. public:
  195. CookiePathDivider operator()(const Cookie& cookie) const
  196. {
  197. return CookiePathDivider(cookie);
  198. }
  199. Cookie operator()(const CookiePathDivider& cookiePathDivider) const
  200. {
  201. return cookiePathDivider.cookie_;
  202. }
  203. };
  204. } // namespace
  205. namespace {
  206. class OrderByPathDepthDesc:public std::binary_function<Cookie, Cookie, bool> {
  207. public:
  208. bool operator()
  209. (const CookiePathDivider& lhs, const CookiePathDivider& rhs) const
  210. {
  211. // From http://tools.ietf.org/html/rfc6265#section-5.4:
  212. // 2. The user agent SHOULD sort the cookie-list in the following
  213. // order:
  214. //
  215. // * Cookies with longer paths are listed before cookies with
  216. // shorter paths.
  217. //
  218. // * Among cookies that have equal-length path fields, cookies with
  219. // earlier creation-times are listed before cookies with later
  220. // creation-times.
  221. return lhs.pathDepth_ > rhs.pathDepth_ ||
  222. (!(rhs.pathDepth_ > lhs.pathDepth_) &&
  223. lhs.cookie_.getCreationTime() < rhs.cookie_.getCreationTime());
  224. }
  225. };
  226. } // namespace
  227. namespace {
  228. template<typename DomainInputIterator, typename CookieOutputIterator>
  229. void searchCookieByDomainSuffix
  230. (const std::string& domain,
  231. DomainInputIterator first, DomainInputIterator last, CookieOutputIterator out,
  232. const std::string& requestHost,
  233. const std::string& requestPath,
  234. time_t now, bool secure)
  235. {
  236. CookieStorage::DomainEntry v(domain);
  237. std::deque<CookieStorage::DomainEntry>::iterator i =
  238. std::lower_bound(first, last, v);
  239. if(i != last && (*i).getKey() == v.getKey()) {
  240. (*i).setLastAccessTime(now);
  241. (*i).findCookie(out, requestHost, requestPath, now, secure);
  242. }
  243. }
  244. } // namespace
  245. bool CookieStorage::contains(const Cookie& cookie) const
  246. {
  247. CookieStorage::DomainEntry v(cookie.getDomain());
  248. std::deque<CookieStorage::DomainEntry>::const_iterator i =
  249. std::lower_bound(domains_.begin(), domains_.end(), v);
  250. if(i != domains_.end() && (*i).getKey() == v.getKey()) {
  251. return (*i).contains(cookie);
  252. } else {
  253. return false;
  254. }
  255. }
  256. std::vector<Cookie> CookieStorage::criteriaFind
  257. (const std::string& requestHost,
  258. const std::string& requestPath,
  259. time_t now,
  260. bool secure)
  261. {
  262. std::vector<Cookie> res;
  263. if(requestPath.empty()) {
  264. return res;
  265. }
  266. if(util::isNumericHost(requestHost)) {
  267. searchCookieByDomainSuffix
  268. (requestHost, domains_.begin(), domains_.end(), std::back_inserter(res),
  269. requestHost, requestPath, now, secure);
  270. } else {
  271. std::vector<std::string> levels;
  272. util::split(requestHost, std::back_inserter(levels),A2STR::DOT_C);
  273. std::reverse(levels.begin(), levels.end());
  274. std::string domain;
  275. for(std::vector<std::string>::const_iterator i =
  276. levels.begin(), eoi = levels.end();
  277. i != eoi; ++i, domain.insert(domain.begin(), '.')) {
  278. domain.insert(domain.begin(), (*i).begin(), (*i).end());
  279. searchCookieByDomainSuffix
  280. (domain, domains_.begin(), domains_.end(),
  281. std::back_inserter(res), requestHost, requestPath, now, secure);
  282. }
  283. }
  284. std::vector<CookiePathDivider> divs;
  285. std::transform(res.begin(), res.end(), std::back_inserter(divs),
  286. CookiePathDividerConverter());
  287. std::sort(divs.begin(), divs.end(), OrderByPathDepthDesc());
  288. std::transform(divs.begin(), divs.end(), res.begin(),
  289. CookiePathDividerConverter());
  290. return res;
  291. }
  292. size_t CookieStorage::size() const
  293. {
  294. size_t numCookie = 0;
  295. for(std::deque<DomainEntry>::const_iterator i = domains_.begin(),
  296. eoi = domains_.end(); i != eoi; ++i) {
  297. numCookie += (*i).countCookie();
  298. }
  299. return numCookie;
  300. }
  301. bool CookieStorage::load(const std::string& filename, time_t now)
  302. {
  303. char header[16]; // "SQLite format 3" plus \0
  304. std::ifstream s(filename.c_str(), std::ios::binary);
  305. if(!s) {
  306. A2_LOG_ERROR(fmt("Failed to open cookie file %s", filename.c_str()));
  307. return false;
  308. }
  309. s.get(header, sizeof(header));
  310. if(!s) {
  311. A2_LOG_ERROR(fmt("Failed to read header of cookie file %s",
  312. filename.c_str()));
  313. return false;
  314. }
  315. try {
  316. if(std::string(header) == "SQLite format 3") {
  317. #ifdef HAVE_SQLITE3
  318. std::vector<Cookie> cookies;
  319. try {
  320. Sqlite3MozCookieParser(filename).parse(cookies);
  321. } catch(RecoverableException& e) {
  322. A2_LOG_INFO_EX(EX_EXCEPTION_CAUGHT, e);
  323. A2_LOG_INFO("This does not look like Firefox3 cookie file."
  324. " Retrying, assuming it is Chromium cookie file.");
  325. // Try chrome cookie format
  326. Sqlite3ChromiumCookieParser(filename).parse(cookies);
  327. }
  328. storeCookies(cookies.begin(), cookies.end(), now);
  329. #else // !HAVE_SQLITE3
  330. throw DL_ABORT_EX
  331. ("Cannot read SQLite3 database because SQLite3 support is disabled by"
  332. " configuration.");
  333. #endif // !HAVE_SQLITE3
  334. } else {
  335. std::vector<Cookie> cookies = NsCookieParser().parse(filename, now);
  336. storeCookies(cookies.begin(), cookies.end(), now);
  337. }
  338. return true;
  339. } catch(RecoverableException& e) {
  340. A2_LOG_ERROR(fmt("Failed to load cookies from %s", filename.c_str()));
  341. return false;
  342. }
  343. }
  344. bool CookieStorage::saveNsFormat(const std::string& filename)
  345. {
  346. std::string tempfilename = filename+"__temp";
  347. {
  348. std::ofstream o(tempfilename.c_str(), std::ios::binary);
  349. if(!o) {
  350. A2_LOG_ERROR(fmt("Cannot create cookie file %s", filename.c_str()));
  351. return false;
  352. }
  353. for(std::deque<DomainEntry>::const_iterator i = domains_.begin(),
  354. eoi = domains_.end(); i != eoi; ++i) {
  355. (*i).writeCookie(o);
  356. }
  357. o.flush();
  358. if(!o) {
  359. A2_LOG_ERROR(fmt("Failed to save cookies to %s", filename.c_str()));
  360. return false;
  361. }
  362. }
  363. if(File(tempfilename).renameTo(filename)) {
  364. return true;
  365. } else {
  366. A2_LOG_ERROR(fmt("Could not rename file %s as %s",
  367. tempfilename.c_str(),
  368. filename.c_str()));
  369. return false;
  370. }
  371. }
  372. } // namespace aria2
  373. namespace std {
  374. template<>
  375. void swap<aria2::CookieStorage::DomainEntry>
  376. (aria2::CookieStorage::DomainEntry& a,
  377. aria2::CookieStorage::DomainEntry& b)
  378. {
  379. a.swap(b);
  380. }
  381. } // namespace std