cookie_helper.cc 12 KB

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