CookieStorage.cc 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  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. // Sort by path-length.
  212. //
  213. // RFC2965 says: Note that the NAME=VALUE pair for the cookie with
  214. // the more specific Path attribute, /acme/ammo, comes before the
  215. // one with the less specific Path attribute, /acme. Further note
  216. // that the same cookie name appears more than once.
  217. //
  218. // Netscape spec says: When sending cookies to a server, all
  219. // cookies with a more specific path mapping should be sent before
  220. // cookies with less specific path mappings. For example, a cookie
  221. // "name1=foo" with a path mapping of "/" should be sent after a
  222. // cookie "name1=foo2" with a path mapping of "/bar" if they are
  223. // both to be sent.
  224. //
  225. // See also http://tools.ietf.org/html/draft-ietf-httpstate-cookie-14
  226. // section5.4
  227. return lhs.pathDepth_ > rhs.pathDepth_ ||
  228. (!(rhs.pathDepth_ > lhs.pathDepth_) &&
  229. lhs.cookie_.getCreationTime() < rhs.cookie_.getCreationTime());
  230. }
  231. };
  232. } // namespace
  233. namespace {
  234. template<typename DomainInputIterator, typename CookieOutputIterator>
  235. void searchCookieByDomainSuffix
  236. (const std::string& domain,
  237. DomainInputIterator first, DomainInputIterator last, CookieOutputIterator out,
  238. const std::string& requestHost,
  239. const std::string& requestPath,
  240. time_t now, bool secure)
  241. {
  242. CookieStorage::DomainEntry v(domain);
  243. std::deque<CookieStorage::DomainEntry>::iterator i =
  244. std::lower_bound(first, last, v);
  245. if(i != last && (*i).getKey() == v.getKey()) {
  246. (*i).setLastAccessTime(now);
  247. (*i).findCookie(out, requestHost, requestPath, now, secure);
  248. }
  249. }
  250. } // namespace
  251. bool CookieStorage::contains(const Cookie& cookie) const
  252. {
  253. CookieStorage::DomainEntry v(cookie.getDomain());
  254. std::deque<CookieStorage::DomainEntry>::const_iterator i =
  255. std::lower_bound(domains_.begin(), domains_.end(), v);
  256. if(i != domains_.end() && (*i).getKey() == v.getKey()) {
  257. return (*i).contains(cookie);
  258. } else {
  259. return false;
  260. }
  261. }
  262. std::vector<Cookie> CookieStorage::criteriaFind
  263. (const std::string& requestHost,
  264. const std::string& requestPath,
  265. time_t now,
  266. bool secure)
  267. {
  268. std::vector<Cookie> res;
  269. if(requestPath.empty()) {
  270. return res;
  271. }
  272. if(util::isNumericHost(requestHost)) {
  273. searchCookieByDomainSuffix
  274. (requestHost, domains_.begin(), domains_.end(), std::back_inserter(res),
  275. requestHost, requestPath, now, secure);
  276. } else {
  277. std::vector<std::string> levels;
  278. util::split(requestHost, std::back_inserter(levels),A2STR::DOT_C);
  279. std::reverse(levels.begin(), levels.end());
  280. std::string domain;
  281. for(std::vector<std::string>::const_iterator i =
  282. levels.begin(), eoi = levels.end();
  283. i != eoi; ++i, domain.insert(domain.begin(), '.')) {
  284. domain.insert(domain.begin(), (*i).begin(), (*i).end());
  285. searchCookieByDomainSuffix
  286. (domain, domains_.begin(), domains_.end(),
  287. std::back_inserter(res), requestHost, requestPath, now, secure);
  288. }
  289. }
  290. std::vector<CookiePathDivider> divs;
  291. std::transform(res.begin(), res.end(), std::back_inserter(divs),
  292. CookiePathDividerConverter());
  293. std::sort(divs.begin(), divs.end(), OrderByPathDepthDesc());
  294. std::transform(divs.begin(), divs.end(), res.begin(),
  295. CookiePathDividerConverter());
  296. return res;
  297. }
  298. size_t CookieStorage::size() const
  299. {
  300. size_t numCookie = 0;
  301. for(std::deque<DomainEntry>::const_iterator i = domains_.begin(),
  302. eoi = domains_.end(); i != eoi; ++i) {
  303. numCookie += (*i).countCookie();
  304. }
  305. return numCookie;
  306. }
  307. bool CookieStorage::load(const std::string& filename, time_t now)
  308. {
  309. char header[16]; // "SQLite format 3" plus \0
  310. std::ifstream s(filename.c_str(), std::ios::binary);
  311. if(!s) {
  312. A2_LOG_ERROR(fmt("Failed to open cookie file %s", filename.c_str()));
  313. return false;
  314. }
  315. s.get(header, sizeof(header));
  316. if(!s) {
  317. A2_LOG_ERROR(fmt("Failed to read header of cookie file %s",
  318. filename.c_str()));
  319. return false;
  320. }
  321. try {
  322. if(std::string(header) == "SQLite format 3") {
  323. #ifdef HAVE_SQLITE3
  324. std::vector<Cookie> cookies;
  325. try {
  326. Sqlite3MozCookieParser(filename).parse(cookies);
  327. } catch(RecoverableException& e) {
  328. A2_LOG_INFO_EX(EX_EXCEPTION_CAUGHT, e);
  329. A2_LOG_INFO("This does not look like Firefox3 cookie file."
  330. " Retrying, assuming it is Chromium cookie file.");
  331. // Try chrome cookie format
  332. Sqlite3ChromiumCookieParser(filename).parse(cookies);
  333. }
  334. storeCookies(cookies.begin(), cookies.end(), now);
  335. #else // !HAVE_SQLITE3
  336. throw DL_ABORT_EX
  337. ("Cannot read SQLite3 database because SQLite3 support is disabled by"
  338. " configuration.");
  339. #endif // !HAVE_SQLITE3
  340. } else {
  341. std::vector<Cookie> cookies = NsCookieParser().parse(filename, now);
  342. storeCookies(cookies.begin(), cookies.end(), now);
  343. }
  344. return true;
  345. } catch(RecoverableException& e) {
  346. A2_LOG_ERROR(fmt("Failed to load cookies from %s", filename.c_str()));
  347. return false;
  348. }
  349. }
  350. bool CookieStorage::saveNsFormat(const std::string& filename)
  351. {
  352. std::string tempfilename = filename+"__temp";
  353. {
  354. std::ofstream o(tempfilename.c_str(), std::ios::binary);
  355. if(!o) {
  356. A2_LOG_ERROR(fmt("Cannot create cookie file %s", filename.c_str()));
  357. return false;
  358. }
  359. for(std::deque<DomainEntry>::const_iterator i = domains_.begin(),
  360. eoi = domains_.end(); i != eoi; ++i) {
  361. (*i).writeCookie(o);
  362. }
  363. o.flush();
  364. if(!o) {
  365. A2_LOG_ERROR(fmt("Failed to save cookies to %s", filename.c_str()));
  366. return false;
  367. }
  368. }
  369. if(File(tempfilename).renameTo(filename)) {
  370. return true;
  371. } else {
  372. A2_LOG_ERROR(fmt("Could not rename file %s as %s",
  373. tempfilename.c_str(),
  374. filename.c_str()));
  375. return false;
  376. }
  377. }
  378. } // namespace aria2
  379. namespace std {
  380. template<>
  381. void swap<aria2::CookieStorage::DomainEntry>
  382. (aria2::CookieStorage::DomainEntry& a,
  383. aria2::CookieStorage::DomainEntry& b)
  384. {
  385. a.swap(b);
  386. }
  387. } // namespace std