/src/network/access/qnetworkcookiejar.cpp

https://bitbucket.org/ultra_iter/qt-vtl · C++ · 320 lines · 124 code · 26 blank · 170 comment · 39 complexity · 80837a569ac48964b5111605396f6402 MD5 · raw file

  1. /****************************************************************************
  2. **
  3. ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
  4. ** All rights reserved.
  5. ** Contact: Nokia Corporation (qt-info@nokia.com)
  6. **
  7. ** This file is part of the QtNetwork module of the Qt Toolkit.
  8. **
  9. ** $QT_BEGIN_LICENSE:LGPL$
  10. ** GNU Lesser General Public License Usage
  11. ** This file may be used under the terms of the GNU Lesser General Public
  12. ** License version 2.1 as published by the Free Software Foundation and
  13. ** appearing in the file LICENSE.LGPL included in the packaging of this
  14. ** file. Please review the following information to ensure the GNU Lesser
  15. ** General Public License version 2.1 requirements will be met:
  16. ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
  17. **
  18. ** In addition, as a special exception, Nokia gives you certain additional
  19. ** rights. These rights are described in the Nokia Qt LGPL Exception
  20. ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
  21. **
  22. ** GNU General Public License Usage
  23. ** Alternatively, this file may be used under the terms of the GNU General
  24. ** Public License version 3.0 as published by the Free Software Foundation
  25. ** and appearing in the file LICENSE.GPL included in the packaging of this
  26. ** file. Please review the following information to ensure the GNU General
  27. ** Public License version 3.0 requirements will be met:
  28. ** http://www.gnu.org/copyleft/gpl.html.
  29. **
  30. ** Other Usage
  31. ** Alternatively, this file may be used in accordance with the terms and
  32. ** conditions contained in a signed written agreement between you and Nokia.
  33. **
  34. **
  35. **
  36. **
  37. **
  38. ** $QT_END_LICENSE$
  39. **
  40. ****************************************************************************/
  41. #include "qnetworkcookiejar.h"
  42. #include "qnetworkcookiejar_p.h"
  43. #include "QtNetwork/qnetworkcookie.h"
  44. #include "QtCore/qurl.h"
  45. #include "QtCore/qdatetime.h"
  46. #include "private/qtldurl_p.h"
  47. QT_BEGIN_NAMESPACE
  48. /*!
  49. \class QNetworkCookieJar
  50. \brief The QNetworkCookieJar class implements a simple jar of QNetworkCookie objects
  51. \since 4.4
  52. Cookies are small bits of information that stateless protocols
  53. like HTTP use to maintain some persistent information across
  54. requests.
  55. A cookie is set by a remote server when it replies to a request
  56. and it expects the same cookie to be sent back when further
  57. requests are sent.
  58. The cookie jar is the object that holds all cookies set in
  59. previous requests. Web browsers save their cookie jars to disk in
  60. order to conserve permanent cookies across invocations of the
  61. application.
  62. QNetworkCookieJar does not implement permanent storage: it only
  63. keeps the cookies in memory. Once the QNetworkCookieJar object is
  64. deleted, all cookies it held will be discarded as well. If you
  65. want to save the cookies, you should derive from this class and
  66. implement the saving to disk to your own storage format.
  67. This class implements only the basic security recommended by the
  68. cookie specifications and does not implement any cookie acceptance
  69. policy (it accepts all cookies set by any requests). In order to
  70. override those rules, you should reimplement the
  71. cookiesForUrl() and setCookiesFromUrl() virtual
  72. functions. They are called by QNetworkReply and
  73. QNetworkAccessManager when they detect new cookies and when they
  74. require cookies.
  75. \sa QNetworkCookie, QNetworkAccessManager, QNetworkReply,
  76. QNetworkRequest, QNetworkAccessManager::setCookieJar()
  77. */
  78. /*!
  79. Creates a QNetworkCookieJar object and sets the parent object to
  80. be \a parent.
  81. The cookie jar is initialized to empty.
  82. */
  83. QNetworkCookieJar::QNetworkCookieJar(QObject *parent)
  84. : QObject(*new QNetworkCookieJarPrivate, parent)
  85. {
  86. }
  87. /*!
  88. Destroys this cookie jar object and discards all cookies stored in
  89. it. Cookies are not saved to disk in the QNetworkCookieJar default
  90. implementation.
  91. If you need to save the cookies to disk, you have to derive from
  92. QNetworkCookieJar and save the cookies to disk yourself.
  93. */
  94. QNetworkCookieJar::~QNetworkCookieJar()
  95. {
  96. }
  97. /*!
  98. Returns all cookies stored in this cookie jar. This function is
  99. suitable for derived classes to save cookies to disk, as well as
  100. to implement cookie expiration and other policies.
  101. \sa setAllCookies(), cookiesForUrl()
  102. */
  103. QList<QNetworkCookie> QNetworkCookieJar::allCookies() const
  104. {
  105. return d_func()->allCookies;
  106. }
  107. /*!
  108. Sets the internal list of cookies held by this cookie jar to be \a
  109. cookieList. This function is suitable for derived classes to
  110. implement loading cookies from permanent storage, or their own
  111. cookie acceptance policies by reimplementing
  112. setCookiesFromUrl().
  113. \sa allCookies(), setCookiesFromUrl()
  114. */
  115. void QNetworkCookieJar::setAllCookies(const QList<QNetworkCookie> &cookieList)
  116. {
  117. Q_D(QNetworkCookieJar);
  118. d->allCookies = cookieList;
  119. }
  120. static inline bool isParentPath(QString path, QString reference)
  121. {
  122. if (!path.endsWith(QLatin1Char('/')))
  123. path += QLatin1Char('/');
  124. if (!reference.endsWith(QLatin1Char('/')))
  125. reference += QLatin1Char('/');
  126. return path.startsWith(reference);
  127. }
  128. static inline bool isParentDomain(QString domain, QString reference)
  129. {
  130. if (!reference.startsWith(QLatin1Char('.')))
  131. return domain == reference;
  132. return domain.endsWith(reference) || domain == reference.mid(1);
  133. }
  134. /*!
  135. Adds the cookies in the list \a cookieList to this cookie
  136. jar. Default values for path and domain are taken from the \a
  137. url object.
  138. Returns true if one or more cookies are set for \a url,
  139. otherwise false.
  140. If a cookie already exists in the cookie jar, it will be
  141. overridden by those in \a cookieList.
  142. The default QNetworkCookieJar class implements only a very basic
  143. security policy (it makes sure that the cookies' domain and path
  144. match the reply's). To enhance the security policy with your own
  145. algorithms, override setCookiesFromUrl().
  146. Also, QNetworkCookieJar does not have a maximum cookie jar
  147. size. Reimplement this function to discard older cookies to create
  148. room for new ones.
  149. \sa cookiesForUrl(), QNetworkAccessManager::setCookieJar()
  150. */
  151. bool QNetworkCookieJar::setCookiesFromUrl(const QList<QNetworkCookie> &cookieList,
  152. const QUrl &url)
  153. {
  154. Q_D(QNetworkCookieJar);
  155. QString defaultDomain = url.host();
  156. QString pathAndFileName = url.path();
  157. QString defaultPath = pathAndFileName.left(pathAndFileName.lastIndexOf(QLatin1Char('/'))+1);
  158. if (defaultPath.isEmpty())
  159. defaultPath = QLatin1Char('/');
  160. int added = 0;
  161. QDateTime now = QDateTime::currentDateTime();
  162. foreach (QNetworkCookie cookie, cookieList) {
  163. bool isDeletion = !cookie.isSessionCookie() &&
  164. cookie.expirationDate() < now;
  165. // validate the cookie & set the defaults if unset
  166. if (cookie.path().isEmpty())
  167. cookie.setPath(defaultPath);
  168. // don't do path checking. See http://bugreports.qt.nokia.com/browse/QTBUG-5815
  169. // else if (!isParentPath(pathAndFileName, cookie.path())) {
  170. // continue; // not accepted
  171. // }
  172. if (cookie.domain().isEmpty()) {
  173. cookie.setDomain(defaultDomain);
  174. } else {
  175. // Ensure the domain starts with a dot if its field was not empty
  176. // in the HTTP header. There are some servers that forget the
  177. // leading dot and this is actually forbidden according to RFC 2109,
  178. // but all browsers accept it anyway so we do that as well.
  179. if (!cookie.domain().startsWith(QLatin1Char('.')))
  180. cookie.setDomain(QLatin1Char('.') + cookie.domain());
  181. QString domain = cookie.domain();
  182. if (!(isParentDomain(domain, defaultDomain)
  183. || isParentDomain(defaultDomain, domain)))
  184. continue; // not accepted
  185. // the check for effective TLDs makes the "embedded dot" rule from RFC 2109 section 4.3.2
  186. // redundant; the "leading dot" rule has been relaxed anyway, see above
  187. // we remove the leading dot for this check
  188. if (qIsEffectiveTLD(domain.remove(0, 1)))
  189. continue; // not accepted
  190. }
  191. for (int i = 0; i < d->allCookies.size(); ++i) {
  192. // does this cookie already exist?
  193. const QNetworkCookie &current = d->allCookies.at(i);
  194. if (cookie.name() == current.name() &&
  195. cookie.domain() == current.domain() &&
  196. cookie.path() == current.path()) {
  197. // found a match
  198. d->allCookies.removeAt(i);
  199. break;
  200. }
  201. }
  202. // did not find a match
  203. if (!isDeletion) {
  204. int countForDomain = 0;
  205. for (int i = d->allCookies.size() - 1; i >= 0; --i) {
  206. // Start from the end and delete the oldest cookies to keep a maximum count of 50.
  207. const QNetworkCookie &current = d->allCookies.at(i);
  208. if (isParentDomain(cookie.domain(), current.domain())
  209. || isParentDomain(current.domain(), cookie.domain())) {
  210. if (countForDomain >= 49)
  211. d->allCookies.removeAt(i);
  212. else
  213. ++countForDomain;
  214. }
  215. }
  216. d->allCookies += cookie;
  217. ++added;
  218. }
  219. }
  220. return (added > 0);
  221. }
  222. /*!
  223. Returns the cookies to be added to when a request is sent to
  224. \a url. This function is called by the default
  225. QNetworkAccessManager::createRequest(), which adds the
  226. cookies returned by this function to the request being sent.
  227. If more than one cookie with the same name is found, but with
  228. differing paths, the one with longer path is returned before the
  229. one with shorter path. In other words, this function returns
  230. cookies sorted decreasingly by path length.
  231. The default QNetworkCookieJar class implements only a very basic
  232. security policy (it makes sure that the cookies' domain and path
  233. match the reply's). To enhance the security policy with your own
  234. algorithms, override cookiesForUrl().
  235. \sa setCookiesFromUrl(), QNetworkAccessManager::setCookieJar()
  236. */
  237. QList<QNetworkCookie> QNetworkCookieJar::cookiesForUrl(const QUrl &url) const
  238. {
  239. // \b Warning! This is only a dumb implementation!
  240. // It does NOT follow all of the recommendations from
  241. // http://wp.netscape.com/newsref/std/cookie_spec.html
  242. // It does not implement a very good cross-domain verification yet.
  243. Q_D(const QNetworkCookieJar);
  244. QDateTime now = QDateTime::currentDateTime();
  245. QList<QNetworkCookie> result;
  246. bool isEncrypted = url.scheme().toLower() == QLatin1String("https");
  247. // scan our cookies for something that matches
  248. QList<QNetworkCookie>::ConstIterator it = d->allCookies.constBegin(),
  249. end = d->allCookies.constEnd();
  250. for ( ; it != end; ++it) {
  251. if (!isParentDomain(url.host(), it->domain()))
  252. continue;
  253. if (!isParentPath(url.path(), it->path()))
  254. continue;
  255. if (!(*it).isSessionCookie() && (*it).expirationDate() < now)
  256. continue;
  257. if ((*it).isSecure() && !isEncrypted)
  258. continue;
  259. // insert this cookie into result, sorted by path
  260. QList<QNetworkCookie>::Iterator insertIt = result.begin();
  261. while (insertIt != result.end()) {
  262. if (insertIt->path().length() < it->path().length()) {
  263. // insert here
  264. insertIt = result.insert(insertIt, *it);
  265. break;
  266. } else {
  267. ++insertIt;
  268. }
  269. }
  270. // this is the shortest path yet, just append
  271. if (insertIt == result.end())
  272. result += *it;
  273. }
  274. return result;
  275. }
  276. QT_END_NAMESPACE