cookie_helper.cc 11 KB

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