cookie_helper.cc 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. /* <!-- copyright */
  2. /*
  3. * aria2 - The high speed download utility
  4. *
  5. * Copyright (C) 2010 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 "cookie_helper.h"
  36. #include <cstring>
  37. #include <vector>
  38. #include <limits>
  39. #include "util.h"
  40. #include "array_fun.h"
  41. #include "Cookie.h"
  42. #include "a2functional.h"
  43. namespace aria2 {
  44. namespace cookie {
  45. namespace {
  46. bool isDelimiter(unsigned char c)
  47. {
  48. return c == 0x09u || in(c, 0x20u, 0x2fu) || in(c, 0x3bu, 0x40u) ||
  49. in(c, 0x5bu, 0x60u) || in(c, 0x7bu, 0x7eu);
  50. }
  51. } // namespace
  52. namespace {
  53. std::string::const_iterator getNextDigit(std::string::const_iterator first,
  54. std::string::const_iterator last)
  55. {
  56. for (; first != last && in(static_cast<unsigned char>(*first), 0x30u, 0x39u);
  57. ++first)
  58. ;
  59. return first;
  60. }
  61. } // namespace
  62. namespace {
  63. template <typename InputIterator>
  64. int getInteger(InputIterator first, InputIterator last)
  65. {
  66. int res = 0;
  67. // We assume *dest won't overflow.
  68. for (; first != last; ++first) {
  69. res *= 10;
  70. res += (*first) - '0';
  71. }
  72. return res;
  73. }
  74. } // namespace
  75. bool parseDate(time_t& time, std::string::const_iterator first,
  76. std::string::const_iterator last)
  77. {
  78. // Following algorithm is described in
  79. // http://tools.ietf.org/html/rfc6265#section-5.1.1
  80. std::vector<std::string> dateTokens;
  81. for (std::string::const_iterator i = first, eoi = last; i != eoi;) {
  82. unsigned char c = *i;
  83. if (isDelimiter(c)) {
  84. ++i;
  85. continue;
  86. }
  87. std::string::const_iterator s = i;
  88. for (; s != eoi && !isDelimiter(static_cast<unsigned char>(*s)); ++s)
  89. ;
  90. dateTokens.push_back(std::string(i, s));
  91. i = s;
  92. }
  93. int dayOfMonth = 0;
  94. bool foundDayOfMonth = false;
  95. int month = 0;
  96. bool foundMonth = false;
  97. int year = 0;
  98. bool foundYear = false;
  99. int hour = 0;
  100. int minute = 0;
  101. int second = 0;
  102. bool foundTime = false;
  103. for (std::vector<std::string>::const_iterator i = dateTokens.begin(),
  104. eoi = dateTokens.end();
  105. i != eoi; ++i) {
  106. if (!foundTime) {
  107. std::string::const_iterator hEnd;
  108. std::string::const_iterator mEnd;
  109. std::string::const_iterator sEnd;
  110. hEnd = getNextDigit((*i).begin(), (*i).end());
  111. size_t len = std::distance((*i).begin(), hEnd);
  112. if (len == 0 || 2 < len || hEnd == (*i).end() || *hEnd != ':') {
  113. goto NOT_TIME;
  114. }
  115. mEnd = getNextDigit(hEnd + 1, (*i).end());
  116. len = std::distance(hEnd + 1, mEnd);
  117. if (len == 0 || 2 < len || mEnd == (*i).end() || *mEnd != ':') {
  118. goto NOT_TIME;
  119. }
  120. sEnd = getNextDigit(mEnd + 1, (*i).end());
  121. len = std::distance(mEnd + 1, sEnd);
  122. if (len == 0 || 2 < len) {
  123. goto NOT_TIME;
  124. }
  125. foundTime = true;
  126. hour = getInteger((*i).begin(), hEnd);
  127. minute = getInteger(hEnd + 1, mEnd);
  128. second = getInteger(mEnd + 1, sEnd);
  129. continue;
  130. NOT_TIME:;
  131. }
  132. if (!foundDayOfMonth) {
  133. std::string::const_iterator j = getNextDigit((*i).begin(), (*i).end());
  134. size_t len = std::distance((*i).begin(), j);
  135. if (1 <= len && len <= 2) {
  136. foundDayOfMonth = true;
  137. dayOfMonth = getInteger((*i).begin(), j);
  138. continue;
  139. }
  140. }
  141. if (!foundMonth) {
  142. static const char MONTH[][12] = {"jan", "feb", "mar", "apr",
  143. "may", "jun", "jul", "aug",
  144. "sep", "oct", "nov", "dec"};
  145. if ((*i).size() >= 3) {
  146. bool found = false;
  147. size_t j;
  148. for (j = 0; j < 12; ++j) {
  149. if (util::strieq((*i).begin(), (*i).begin() + 3, &MONTH[j][0],
  150. &MONTH[j][3])) {
  151. found = true;
  152. break;
  153. }
  154. }
  155. if (found) {
  156. foundMonth = true;
  157. month = j + 1;
  158. continue;
  159. }
  160. }
  161. }
  162. if (!foundYear) {
  163. std::string::const_iterator j = getNextDigit((*i).begin(), (*i).end());
  164. size_t len = std::distance((*i).begin(), j);
  165. if (1 <= len && len <= 4) {
  166. foundYear = true;
  167. year = getInteger((*i).begin(), j);
  168. continue;
  169. }
  170. }
  171. }
  172. if (in(year, 70, 99)) {
  173. year += 1900;
  174. }
  175. else if (in(year, 0, 69)) {
  176. year += 2000;
  177. }
  178. if (!foundDayOfMonth || !foundMonth || !foundYear || !foundTime ||
  179. !in(dayOfMonth, 1, 31) || year < 1601 || hour > 23 || minute > 59 ||
  180. second > 59) {
  181. return false;
  182. }
  183. if ((month == 4 || month == 6 || month == 9 || month == 11) &&
  184. dayOfMonth > 30) {
  185. return false;
  186. }
  187. if (month == 2) {
  188. if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
  189. if (dayOfMonth > 29) {
  190. return false;
  191. }
  192. }
  193. else if (dayOfMonth > 28) {
  194. return false;
  195. }
  196. }
  197. tm timespec;
  198. memset(&timespec, 0, sizeof(timespec));
  199. timespec.tm_sec = second;
  200. timespec.tm_min = minute;
  201. timespec.tm_hour = hour;
  202. timespec.tm_mday = dayOfMonth;
  203. timespec.tm_mon = month - 1;
  204. timespec.tm_year = year - 1900;
  205. time = timegm(&timespec);
  206. return time != -1;
  207. }
  208. std::unique_ptr<Cookie> parse(const std::string& cookieStr,
  209. const std::string& requestHost,
  210. const std::string& defaultPath,
  211. time_t creationTime)
  212. {
  213. // This implementation is based on the algorithm listed in
  214. // http://tools.ietf.org/html/rfc6265
  215. std::string::const_iterator nvEnd = cookieStr.begin();
  216. std::string::const_iterator end = cookieStr.end();
  217. for (; nvEnd != end && *nvEnd != ';'; ++nvEnd)
  218. ;
  219. std::string::const_iterator eq = cookieStr.begin();
  220. for (; eq != nvEnd && *eq != '='; ++eq)
  221. ;
  222. if (eq == nvEnd) {
  223. return nullptr;
  224. }
  225. std::pair<std::string::const_iterator, std::string::const_iterator> p =
  226. util::stripIter(cookieStr.begin(), eq);
  227. if (p.first == p.second) {
  228. return nullptr;
  229. }
  230. Scip cookieName(p.first, p.second);
  231. p = util::stripIter(eq + 1, nvEnd);
  232. p = util::stripIter(p.first, p.second, "\"");
  233. Scip cookieValue(p.first, p.second);
  234. time_t expiryTime = 0;
  235. bool foundExpires = false;
  236. bool persistent = false;
  237. time_t maxAge = 0;
  238. bool foundMaxAge = false;
  239. std::string cookieDomain;
  240. bool hostOnly = false;
  241. std::string cookiePath;
  242. bool secure = false;
  243. bool httpOnly = false;
  244. if (nvEnd != end) {
  245. ++nvEnd;
  246. }
  247. for (std::string::const_iterator i = nvEnd; i != end;) {
  248. std::string::const_iterator j = std::find(i, end, ';');
  249. std::string::const_iterator eq = std::find(i, j, '=');
  250. p = util::stripIter(i, eq);
  251. std::pair<std::string::const_iterator, std::string::const_iterator> attrp;
  252. if (eq == j) {
  253. attrp.first = attrp.second = j;
  254. }
  255. else {
  256. attrp = util::stripIter(eq + 1, j);
  257. }
  258. i = j;
  259. if (j != end) {
  260. ++i;
  261. }
  262. if (util::strieq(p.first, p.second, "expires")) {
  263. if (parseDate(expiryTime, attrp.first, attrp.second)) {
  264. foundExpires = true;
  265. }
  266. else {
  267. return nullptr;
  268. }
  269. }
  270. else if (util::strieq(p.first, p.second, "max-age")) {
  271. if (attrp.first == attrp.second ||
  272. (!in(static_cast<unsigned char>(*attrp.first), 0x30u, 0x39u) &&
  273. *attrp.first != '-')) {
  274. return nullptr;
  275. }
  276. for (std::string::const_iterator s = attrp.first + 1, eos = attrp.second;
  277. s != eos; ++s) {
  278. if (!in(static_cast<unsigned char>(*s), 0x30u, 0x39u)) {
  279. return nullptr;
  280. }
  281. }
  282. int64_t delta;
  283. if (util::parseLLIntNoThrow(delta,
  284. std::string(attrp.first, attrp.second))) {
  285. foundMaxAge = true;
  286. if (delta <= 0) {
  287. maxAge = 0;
  288. }
  289. else {
  290. int64_t n = creationTime;
  291. n += delta;
  292. if (n < 0 || std::numeric_limits<time_t>::max() < n) {
  293. maxAge = std::numeric_limits<time_t>::max();
  294. }
  295. else {
  296. maxAge = n;
  297. }
  298. }
  299. }
  300. else {
  301. return nullptr;
  302. }
  303. }
  304. else if (util::strieq(p.first, p.second, "domain")) {
  305. if (attrp.first == attrp.second) {
  306. return nullptr;
  307. }
  308. std::string::const_iterator noDot = attrp.first;
  309. std::string::const_iterator end = attrp.second;
  310. for (; noDot != end && *noDot == '.'; ++noDot)
  311. ;
  312. if (noDot == end) {
  313. return nullptr;
  314. }
  315. cookieDomain.assign(noDot, end);
  316. }
  317. else if (util::strieq(p.first, p.second, "path")) {
  318. if (goodPath(attrp.first, attrp.second)) {
  319. cookiePath.assign(attrp.first, attrp.second);
  320. }
  321. else {
  322. cookiePath = defaultPath;
  323. }
  324. }
  325. else if (util::strieq(p.first, p.second, "secure")) {
  326. secure = true;
  327. }
  328. else if (util::strieq(p.first, p.second, "httponly")) {
  329. httpOnly = true;
  330. }
  331. }
  332. if (foundMaxAge) {
  333. expiryTime = maxAge;
  334. persistent = true;
  335. }
  336. else if (foundExpires) {
  337. persistent = true;
  338. }
  339. else {
  340. expiryTime = std::numeric_limits<time_t>::max();
  341. persistent = false;
  342. }
  343. std::string canonicalizedHost = canonicalizeHost(requestHost);
  344. if (cookieDomain.empty()) {
  345. hostOnly = true;
  346. cookieDomain = canonicalizedHost;
  347. }
  348. else if (domainMatch(canonicalizedHost, cookieDomain)) {
  349. hostOnly = util::isNumericHost(canonicalizedHost);
  350. }
  351. else {
  352. return nullptr;
  353. }
  354. if (cookiePath.empty()) {
  355. cookiePath = defaultPath;
  356. }
  357. auto cookie = make_unique<Cookie>();
  358. cookie->setName(cookieName.first, cookieName.second);
  359. cookie->setValue(cookieValue.first, cookieValue.second);
  360. cookie->setExpiryTime(expiryTime);
  361. cookie->setPersistent(persistent);
  362. cookie->setDomain(std::move(cookieDomain));
  363. cookie->setHostOnly(hostOnly);
  364. cookie->setPath(std::move(cookiePath));
  365. cookie->setSecure(secure);
  366. cookie->setHttpOnly(httpOnly);
  367. cookie->setCreationTime(creationTime);
  368. cookie->setLastAccessTime(creationTime);
  369. return cookie;
  370. }
  371. bool goodPath(std::string::const_iterator first,
  372. std::string::const_iterator last)
  373. {
  374. return first != last && *first == '/';
  375. }
  376. std::string canonicalizeHost(const std::string& host)
  377. {
  378. return util::toLower(host);
  379. }
  380. bool domainMatch(const std::string& requestHost, const std::string& domain)
  381. {
  382. return requestHost == domain ||
  383. (util::endsWith(requestHost, domain) &&
  384. requestHost[requestHost.size() - domain.size() - 1] == '.' &&
  385. !util::isNumericHost(requestHost));
  386. }
  387. bool pathMatch(const std::string& requestPath, const std::string& path)
  388. {
  389. return requestPath == path ||
  390. (util::startsWith(requestPath, path) &&
  391. (path[path.size() - 1] == '/' || requestPath[path.size()] == '/'));
  392. }
  393. std::string reverseDomainLevel(const std::string& domain)
  394. {
  395. std::string r;
  396. if (domain.empty()) {
  397. return r;
  398. }
  399. r.reserve(domain.size());
  400. // Cut trailing dots
  401. std::string::const_iterator s = domain.end() - 1;
  402. for (; *s == '.'; --s) {
  403. if (s == domain.begin()) {
  404. return r;
  405. }
  406. }
  407. std::string::const_iterator t = s + 1;
  408. for (;; --s) {
  409. if (*s == '.') {
  410. r.append(s + 1, t);
  411. r += '.';
  412. t = s;
  413. }
  414. if (s == domain.begin()) {
  415. r.append(s, t);
  416. break;
  417. }
  418. }
  419. return r;
  420. }
  421. } // namespace cookie
  422. } // namespace aria2