CookieStorage.cc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  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 "StringFormat.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
  55. (const std::string& domain):
  56. key_(util::isNumericHost(domain)?domain:cookie::reverseDomainLevel(domain))
  57. {}
  58. bool CookieStorage::DomainEntry::addCookie(const Cookie& cookie, time_t now)
  59. {
  60. setLastAccessTime(now);
  61. std::deque<Cookie>::iterator i =
  62. std::find(cookies_.begin(), cookies_.end(), cookie);
  63. if(i == cookies_.end()) {
  64. if(cookie.isExpired(now)) {
  65. return false;
  66. } else {
  67. if(cookies_.size() >= CookieStorage::MAX_COOKIE_PER_DOMAIN) {
  68. cookies_.erase
  69. (std::remove_if(cookies_.begin(), cookies_.end(),
  70. std::bind2nd
  71. (std::mem_fun_ref(&Cookie::isExpired), now)),
  72. cookies_.end());
  73. if(cookies_.size() >= CookieStorage::MAX_COOKIE_PER_DOMAIN) {
  74. std::deque<Cookie>::iterator m = std::min_element
  75. (cookies_.begin(), cookies_.end(), LeastRecentAccess<Cookie>());
  76. *m = cookie;
  77. } else {
  78. cookies_.push_back(cookie);
  79. }
  80. } else {
  81. cookies_.push_back(cookie);
  82. }
  83. return true;
  84. }
  85. } else if(cookie.isExpired(now)) {
  86. cookies_.erase(i);
  87. return false;
  88. } else {
  89. *i = cookie;
  90. return true;
  91. }
  92. }
  93. bool CookieStorage::DomainEntry::contains(const Cookie& cookie) const
  94. {
  95. return std::find(cookies_.begin(), cookies_.end(), cookie) != cookies_.end();
  96. }
  97. void CookieStorage::DomainEntry::writeCookie(std::ostream& o) const
  98. {
  99. for(std::deque<Cookie>::const_iterator i = cookies_.begin(),
  100. eoi = cookies_.end(); i != eoi; ++i) {
  101. o << (*i).toNsCookieFormat() << "\n";
  102. }
  103. }
  104. CookieStorage::CookieStorage():logger_(LogFactory::getInstance()) {}
  105. CookieStorage::~CookieStorage() {}
  106. // See CookieStorageTest::testDomainIsFull() in CookieStorageTest.cc
  107. static const size_t DOMAIN_EVICTION_TRIGGER = 2000;
  108. static const double DOMAIN_EVICTION_RATE = 0.1;
  109. bool CookieStorage::store(const Cookie& cookie, time_t now)
  110. {
  111. if(domains_.size() >= DOMAIN_EVICTION_TRIGGER) {
  112. std::sort(domains_.begin(), domains_.end(),
  113. LeastRecentAccess<DomainEntry>());
  114. size_t delnum = (size_t)(domains_.size()*DOMAIN_EVICTION_RATE);
  115. domains_.erase(domains_.begin(), domains_.begin()+delnum);
  116. std::sort(domains_.begin(), domains_.end());
  117. }
  118. DomainEntry v(cookie.getDomain());
  119. std::deque<DomainEntry>::iterator i =
  120. std::lower_bound(domains_.begin(), domains_.end(), v);
  121. bool added = false;
  122. if(i != domains_.end() && (*i).getKey() == v.getKey()) {
  123. added = (*i).addCookie(cookie, now);
  124. } else {
  125. added = v.addCookie(cookie, now);
  126. if(added) {
  127. domains_.insert(i, v);
  128. }
  129. }
  130. return added;
  131. }
  132. bool CookieStorage::parseAndStore
  133. (const std::string& setCookieString,
  134. const std::string& requestHost,
  135. const std::string& defaultPath,
  136. time_t now)
  137. {
  138. Cookie cookie;
  139. if(cookie::parse(cookie, setCookieString, requestHost, defaultPath, now)) {
  140. return store(cookie, now);
  141. } else {
  142. return false;
  143. }
  144. }
  145. struct CookiePathDivider {
  146. Cookie cookie_;
  147. int pathDepth_;
  148. CookiePathDivider(const Cookie& cookie):cookie_(cookie)
  149. {
  150. std::vector<std::string> paths;
  151. util::split(cookie_.getPath(), std::back_inserter(paths), A2STR::SLASH_C);
  152. pathDepth_ = paths.size();
  153. }
  154. };
  155. namespace {
  156. class CookiePathDividerConverter {
  157. public:
  158. CookiePathDivider operator()(const Cookie& cookie) const
  159. {
  160. return CookiePathDivider(cookie);
  161. }
  162. Cookie operator()(const CookiePathDivider& cookiePathDivider) const
  163. {
  164. return cookiePathDivider.cookie_;
  165. }
  166. };
  167. } // namespace
  168. namespace {
  169. class OrderByPathDepthDesc:public std::binary_function<Cookie, Cookie, bool> {
  170. public:
  171. bool operator()
  172. (const CookiePathDivider& lhs, const CookiePathDivider& rhs) const
  173. {
  174. // Sort by path-length.
  175. //
  176. // RFC2965 says: Note that the NAME=VALUE pair for the cookie with
  177. // the more specific Path attribute, /acme/ammo, comes before the
  178. // one with the less specific Path attribute, /acme. Further note
  179. // that the same cookie name appears more than once.
  180. //
  181. // Netscape spec says: When sending cookies to a server, all
  182. // cookies with a more specific path mapping should be sent before
  183. // cookies with less specific path mappings. For example, a cookie
  184. // "name1=foo" with a path mapping of "/" should be sent after a
  185. // cookie "name1=foo2" with a path mapping of "/bar" if they are
  186. // both to be sent.
  187. //
  188. // See also http://tools.ietf.org/html/draft-ietf-httpstate-cookie-14
  189. // section5.4
  190. return lhs.pathDepth_ > rhs.pathDepth_ ||
  191. (!(rhs.pathDepth_ > lhs.pathDepth_) &&
  192. lhs.cookie_.getCreationTime() < rhs.cookie_.getCreationTime());
  193. }
  194. };
  195. } // namespace
  196. namespace {
  197. template<typename DomainInputIterator, typename CookieOutputIterator>
  198. void searchCookieByDomainSuffix
  199. (const std::string& domain,
  200. DomainInputIterator first, DomainInputIterator last, CookieOutputIterator out,
  201. const std::string& requestHost,
  202. const std::string& requestPath,
  203. time_t now, bool secure)
  204. {
  205. CookieStorage::DomainEntry v(domain);
  206. std::deque<CookieStorage::DomainEntry>::iterator i =
  207. std::lower_bound(first, last, v);
  208. if(i != last && (*i).getKey() == v.getKey()) {
  209. (*i).setLastAccessTime(now);
  210. (*i).findCookie(out, requestHost, requestPath, now, secure);
  211. }
  212. }
  213. } // namespace
  214. bool CookieStorage::contains(const Cookie& cookie) const
  215. {
  216. CookieStorage::DomainEntry v(cookie.getDomain());
  217. std::deque<CookieStorage::DomainEntry>::const_iterator i =
  218. std::lower_bound(domains_.begin(), domains_.end(), v);
  219. if(i != domains_.end() && (*i).getKey() == v.getKey()) {
  220. return (*i).contains(cookie);
  221. } else {
  222. return false;
  223. }
  224. }
  225. std::vector<Cookie> CookieStorage::criteriaFind
  226. (const std::string& requestHost,
  227. const std::string& requestPath,
  228. time_t now,
  229. bool secure)
  230. {
  231. std::vector<Cookie> res;
  232. if(requestPath.empty()) {
  233. return res;
  234. }
  235. if(util::isNumericHost(requestHost)) {
  236. searchCookieByDomainSuffix
  237. (requestHost, domains_.begin(), domains_.end(), std::back_inserter(res),
  238. requestHost, requestPath, now, secure);
  239. } else {
  240. std::vector<std::string> levels;
  241. util::split(requestHost, std::back_inserter(levels),A2STR::DOT_C);
  242. std::reverse(levels.begin(), levels.end());
  243. std::string domain;
  244. for(std::vector<std::string>::const_iterator i =
  245. levels.begin(), eoi = levels.end();
  246. i != eoi; ++i, domain.insert(domain.begin(), '.')) {
  247. domain.insert(domain.begin(), (*i).begin(), (*i).end());
  248. searchCookieByDomainSuffix
  249. (domain, domains_.begin(), domains_.end(),
  250. std::back_inserter(res), requestHost, requestPath, now, secure);
  251. }
  252. }
  253. std::vector<CookiePathDivider> divs;
  254. std::transform(res.begin(), res.end(), std::back_inserter(divs),
  255. CookiePathDividerConverter());
  256. std::sort(divs.begin(), divs.end(), OrderByPathDepthDesc());
  257. std::transform(divs.begin(), divs.end(), res.begin(),
  258. CookiePathDividerConverter());
  259. return res;
  260. }
  261. size_t CookieStorage::size() const
  262. {
  263. size_t numCookie = 0;
  264. for(std::deque<DomainEntry>::const_iterator i = domains_.begin(),
  265. eoi = domains_.end(); i != eoi; ++i) {
  266. numCookie += (*i).countCookie();
  267. }
  268. return numCookie;
  269. }
  270. bool CookieStorage::load(const std::string& filename, time_t now)
  271. {
  272. char header[16]; // "SQLite format 3" plus \0
  273. std::ifstream s(filename.c_str(), std::ios::binary);
  274. if(!s) {
  275. logger_->error("Failed to open cookie file %s", filename.c_str());
  276. return false;
  277. }
  278. s.get(header, sizeof(header));
  279. if(!s) {
  280. logger_->error("Failed to read header of cookie file %s",
  281. filename.c_str());
  282. return false;
  283. }
  284. try {
  285. if(std::string(header) == "SQLite format 3") {
  286. #ifdef HAVE_SQLITE3
  287. std::vector<Cookie> cookies;
  288. try {
  289. Sqlite3MozCookieParser(filename).parse(cookies);
  290. } catch(RecoverableException& e) {
  291. if(logger_->info()) {
  292. logger_->info(EX_EXCEPTION_CAUGHT, e);
  293. logger_->info("This does not look like Firefox3 cookie file."
  294. " Retrying, assuming it is Chromium cookie file.");
  295. }
  296. // Try chrome cookie format
  297. Sqlite3ChromiumCookieParser(filename).parse(cookies);
  298. }
  299. storeCookies(cookies.begin(), cookies.end(), now);
  300. #else // !HAVE_SQLITE3
  301. throw DL_ABORT_EX
  302. ("Cannot read SQLite3 database because SQLite3 support is disabled by"
  303. " configuration.");
  304. #endif // !HAVE_SQLITE3
  305. } else {
  306. std::vector<Cookie> cookies = NsCookieParser().parse(filename, now);
  307. storeCookies(cookies.begin(), cookies.end(), now);
  308. }
  309. return true;
  310. } catch(RecoverableException& e) {
  311. logger_->error("Failed to load cookies from %s", filename.c_str());
  312. return false;
  313. }
  314. }
  315. bool CookieStorage::saveNsFormat(const std::string& filename)
  316. {
  317. std::string tempfilename = filename+"__temp";
  318. {
  319. std::ofstream o(tempfilename.c_str(), std::ios::binary);
  320. if(!o) {
  321. logger_->error("Cannot create cookie file %s, cause %s",
  322. filename.c_str(), strerror(errno));
  323. return false;
  324. }
  325. for(std::deque<DomainEntry>::const_iterator i = domains_.begin(),
  326. eoi = domains_.end(); i != eoi; ++i) {
  327. (*i).writeCookie(o);
  328. }
  329. o.flush();
  330. if(!o) {
  331. logger_->error("Failed to save cookies to %s, cause %s",
  332. filename.c_str(), strerror(errno));
  333. return false;
  334. }
  335. }
  336. if(File(tempfilename).renameTo(filename)) {
  337. return true;
  338. } else {
  339. logger_->error("Could not rename file %s as %s",
  340. tempfilename.c_str(), filename.c_str());
  341. return false;
  342. }
  343. }
  344. } // namespace aria2