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