• Skip to content
  • Skip to link menu
  • KDE API Reference
  • kdelibs-4.9.1 API Reference
  • KDE Home
  • Contact Us
 

KIOSlave

  • kioslave
  • http
  • kcookiejar
kcookiejar.cpp
Go to the documentation of this file.
1 /* This file is part of the KDE File Manager
2 
3  Copyright (C) 1998-2000 Waldo Bastian (bastian@kde.org)
4  Copyright (C) 2000,2001 Dawit Alemayehu (adawit@kde.org)
5 
6  Permission is hereby granted, free of charge, to any person obtaining a copy
7  of this software and associated documentation files (the "Software"), to deal
8  in the Software without restriction, including without limitation the rights
9  to use, copy, modify, merge, publish, distribute, and/or sell copies of the
10  Software, and to permit persons to whom the Software is furnished to do so,
11  subject to the following conditions:
12 
13  The above copyright notice and this permission notice shall be included in
14  all copies or substantial portions of the Software.
15 
16  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19  AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
20  ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 */
23 //----------------------------------------------------------------------------
24 //
25 // KDE File Manager -- HTTP Cookies
26 
27 //
28 // The cookie protocol is a mess. RFC2109 is a joke since nobody seems to
29 // use it. Apart from that it is badly written.
30 // We try to implement Netscape Cookies and try to behave us according to
31 // RFC2109 as much as we can.
32 //
33 // We assume cookies do not contain any spaces (Netscape spec.)
34 // According to RFC2109 this is allowed though.
35 //
36 
37 #include "kcookiejar.h"
38 
39 #include <kurl.h>
40 #include <kdatetime.h>
41 #include <ksystemtimezone.h>
42 #include <kconfig.h>
43 #include <kconfiggroup.h>
44 #include <ksavefile.h>
45 #include <kdebug.h>
46 
47 #include <QtCore/QString>
48 #include <QtCore/QFile>
49 #include <QtCore/QDir>
50 #include <QtCore/QRegExp>
51 #include <QtCore/QTextStream>
52 
53 // BR87227
54 // Waba: Should the number of cookies be limited?
55 // I am not convinced of the need of such limit
56 // Mozilla seems to limit to 20 cookies / domain
57 // but it is unclear which policy it uses to expire
58 // cookies when it exceeds that amount
59 #undef MAX_COOKIE_LIMIT
60 
61 #define MAX_COOKIES_PER_HOST 25
62 #define READ_BUFFER_SIZE 8192
63 #define IP_ADDRESS_EXPRESSION "(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)"
64 
65 // Note with respect to QLatin1String( )....
66 // Cookies are stored as 8 bit data and passed to kio_http as Latin1
67 // regardless of their actual encoding.
68 #define QL1S(x) QLatin1String(x)
69 #define QL1C(x) QLatin1Char(x)
70 
71 
72 static QString removeWeekday(const QString& value)
73 {
74  const int index = value.indexOf(QL1C(' '));
75  if (index > -1) {
76  int pos = 0;
77  const QString weekday = value.left(index);
78  for (int i = 1; i < 8; ++i) {
79  if (weekday.startsWith(QDate::shortDayName(i), Qt::CaseInsensitive) ||
80  weekday.startsWith(QDate::longDayName(i), Qt::CaseInsensitive)) {
81  pos = index + 1;
82  break;
83  }
84  }
85  if (pos > 0) {
86  return value.mid(pos);
87  }
88  }
89  return value;
90 }
91 
92 static QDateTime parseDate(const QString& _value)
93 {
94  // Handle sites sending invalid weekday as part of the date. #298660
95  const QString value (removeWeekday(_value));
96 
97  // Check if expiration date matches RFC dates as specified under
98  // RFC 2616 sec 3.3.1 & RFC 6265 sec 4.1.1
99  KDateTime dt = KDateTime::fromString(value, KDateTime::RFCDate);
100 
101  // In addition to the RFC date formats we support the ANSI C asctime format
102  // per RFC 2616 sec 3.3.1 and a variation of that detected @ amazon.com
103  if (!dt.isValid()) {
104  static const char* date_formats[] = {
105  "%:B%t%d%t%H:%M:%S%t%Y%t%Z", /* ANSI C's asctime() format (#145244): Jan 01 00:00:00 1970 GMT */
106  "%:B%t%d%t%Y%t%H:%M:%S%t%Z", /* A variation on the above format seen @ amazon.com: Jan 01 1970 00:00:00 GMT */
107  0
108  };
109 
110  for (int i = 0; date_formats[i]; ++i) {
111  qDebug() << "Checking" << value << "vs" << date_formats[i];
112  dt = KDateTime::fromString(value, QL1S(date_formats[i]));
113  if (dt.isValid()) {
114  qDebug() << "Matched" << date_formats[i];
115  break;
116  }
117  }
118  }
119 
120  return dt.toUtc().dateTime(); // Per RFC 2616 sec 3.3.1 always convert to UTC.
121 }
122 
123 static qint64 toEpochSecs(const QDateTime& dt)
124 {
125  return (dt.toMSecsSinceEpoch()/1000); // convert to seconds...
126 }
127 
128 static qint64 epoch()
129 {
130  return toEpochSecs(QDateTime::currentDateTimeUtc());
131 }
132 
133 QString KCookieJar::adviceToStr(KCookieAdvice _advice)
134 {
135  switch( _advice )
136  {
137  case KCookieAccept: return QL1S("Accept");
138  case KCookieReject: return QL1S("Reject");
139  case KCookieAsk: return QL1S("Ask");
140  default: return QL1S("Dunno");
141  }
142 }
143 
144 KCookieAdvice KCookieJar::strToAdvice(const QString &_str)
145 {
146  if (_str.isEmpty())
147  return KCookieDunno;
148 
149  QString advice = _str.toLower();
150 
151  if (advice == QL1S("accept"))
152  return KCookieAccept;
153  else if (advice == QL1S("reject"))
154  return KCookieReject;
155  else if (advice == QL1S("ask"))
156  return KCookieAsk;
157 
158  return KCookieDunno;
159 }
160 
161 // KHttpCookie
163 
164 //
165 // Cookie constructor
166 //
167 KHttpCookie::KHttpCookie(const QString &_host,
168  const QString &_domain,
169  const QString &_path,
170  const QString &_name,
171  const QString &_value,
172  qint64 _expireDate,
173  int _protocolVersion,
174  bool _secure,
175  bool _httpOnly,
176  bool _explicitPath) :
177  mHost(_host),
178  mDomain(_domain),
179  mPath(_path.isEmpty() ? QString() : _path),
180  mName(_name),
181  mValue(_value),
182  mExpireDate(_expireDate),
183  mProtocolVersion(_protocolVersion),
184  mSecure(_secure),
185  mHttpOnly(_httpOnly),
186  mExplicitPath(_explicitPath)
187 {
188 }
189 
190 //
191 // Checks if a cookie has been expired
192 //
193 bool KHttpCookie::isExpired(qint64 currentDate) const
194 {
195  if (currentDate == -1)
196  currentDate = epoch();
197 
198  return (mExpireDate != 0) && (mExpireDate < currentDate);
199 }
200 
201 //
202 // Returns a string for a HTTP-header
203 //
204 QString KHttpCookie::cookieStr(bool useDOMFormat) const
205 {
206  QString result;
207 
208  if (useDOMFormat || (mProtocolVersion == 0)) {
209  if ( mName.isEmpty() )
210  result = mValue;
211  else
212  result = mName + QL1C('=') + mValue;
213  } else {
214  result = mName + QL1C('=') + mValue;
215  if (mExplicitPath)
216  result += QL1S("; $Path=\"") + mPath + QL1C('"');
217  if (!mDomain.isEmpty())
218  result += QL1S("; $Domain=\"") + mDomain + QL1C('"');
219  if (!mPorts.isEmpty()) {
220  if (mPorts.length() == 2 && mPorts.at(0) == -1)
221  result += QL1S("; $Port");
222  else {
223  QString portNums;
224  Q_FOREACH(int port, mPorts)
225  portNums += QString::number(port) + QL1C(' ');
226  result += QL1S("; $Port=\"") + portNums.trimmed() + QL1C('"');
227  }
228  }
229  }
230  return result;
231 }
232 
233 //
234 // Returns whether this cookie should be send to this location.
235 bool KHttpCookie::match(const QString &fqdn, const QStringList &domains,
236  const QString &path, int port) const
237 {
238  // Cookie domain match check
239  if (mDomain.isEmpty())
240  {
241  if (fqdn != mHost)
242  return false;
243  }
244  else if (!domains.contains(mDomain))
245  {
246  if (mDomain[0] == '.')
247  return false;
248 
249  // Maybe the domain needs an extra dot.
250  const QString domain = QL1C('.') + mDomain;
251  if ( !domains.contains( domain ) )
252  if ( fqdn != mDomain )
253  return false;
254  }
255  else if (mProtocolVersion != 0 && port != -1 &&
256  !mPorts.isEmpty() && !mPorts.contains(port))
257  {
258  return false;
259  }
260 
261  // Cookie path match check
262  if (mPath.isEmpty())
263  return true;
264 
265  // According to the netscape spec http://www.acme.com/foobar,
266  // http://www.acme.com/foo.bar and http://www.acme.com/foo/bar
267  // should all match http://www.acme.com/foo...
268  // We only match http://www.acme.com/foo/bar
269  if( path.startsWith(mPath) &&
270  (
271  (path.length() == mPath.length() ) || // Paths are exact match
272  mPath.endsWith(QL1C('/')) || // mPath ended with a slash
273  (path[mPath.length()] == QL1C('/')) // A slash follows
274  ))
275  return true; // Path of URL starts with cookie-path
276 
277  return false;
278 }
279 
280 // KCookieJar
282 
283 //
284 // Constructs a new cookie jar
285 //
286 // One jar should be enough for all cookies.
287 //
288 KCookieJar::KCookieJar()
289 {
290  m_globalAdvice = KCookieDunno;
291  m_configChanged = false;
292  m_cookiesChanged = false;
293 
294  KConfig cfg( "khtml/domain_info", KConfig::NoGlobals, "data" );
295  KConfigGroup group( &cfg, QString() );
296  m_gTLDs = QSet<QString>::fromList(group.readEntry("gTLDs", QStringList()));
297  m_twoLevelTLD = QSet<QString>::fromList(group.readEntry("twoLevelTLD", QStringList()));
298 }
299 
300 //
301 // Destructs the cookie jar
302 //
303 // Poor little cookies, they will all be eaten by the cookie monster!
304 //
305 KCookieJar::~KCookieJar()
306 {
307  qDeleteAll(m_cookieDomains);
308  // Not much to do here
309 }
310 
311 // cookiePtr is modified: the window ids of the existing cookie in the list are added to it
312 static void removeDuplicateFromList(KHttpCookieList *list, KHttpCookie& cookiePtr, bool nameMatchOnly=false, bool updateWindowId=false)
313 {
314  QString domain1 = cookiePtr.domain();
315  if (domain1.isEmpty())
316  domain1 = cookiePtr.host();
317 
318  QMutableListIterator<KHttpCookie> cookieIterator(*list);
319  while (cookieIterator.hasNext()) {
320  const KHttpCookie& cookie = cookieIterator.next();
321  QString domain2 = cookie.domain();
322  if (domain2.isEmpty())
323  domain2 = cookie.host();
324 
325  if (cookiePtr.name() == cookie.name() &&
326  (nameMatchOnly || (domain1 == domain2 && cookiePtr.path() == cookie.path())))
327  {
328  if (updateWindowId) {
329  Q_FOREACH(long windowId, cookie.windowIds()) {
330  if (windowId && (!cookiePtr.windowIds().contains(windowId))) {
331  cookiePtr.windowIds().append(windowId);
332  }
333  }
334  }
335  cookieIterator.remove();
336  break;
337  }
338  }
339 }
340 
341 
342 //
343 // Looks for cookies in the cookie jar which are appropriate for _url.
344 // Returned is a string containing all appropriate cookies in a format
345 // which can be added to a HTTP-header without any additional processing.
346 //
347 QString KCookieJar::findCookies(const QString &_url, bool useDOMFormat, long windowId, KHttpCookieList *pendingCookies)
348 {
349  QString cookieStr, fqdn, path;
350  QStringList domains;
351  int port = -1;
352  KCookieAdvice advice = m_globalAdvice;
353 
354  if (!parseUrl(_url, fqdn, path, &port))
355  return cookieStr;
356 
357  const bool secureRequest = (_url.startsWith(QL1S("https://"), Qt::CaseInsensitive) ||
358  _url.startsWith(QL1S("webdavs://"), Qt::CaseInsensitive));
359  if (port == -1)
360  port = (secureRequest ? 443 : 80);
361 
362  extractDomains(fqdn, domains);
363 
364  KHttpCookieList allCookies;
365  for (QStringList::ConstIterator it = domains.constBegin(), itEnd = domains.constEnd();;++it)
366  {
367  KHttpCookieList *cookieList = 0;
368  if (it == itEnd)
369  {
370  cookieList = pendingCookies; // Add pending cookies
371  pendingCookies = 0;
372  if (!cookieList)
373  break;
374  }
375  else
376  {
377  if ((*it).isNull())
378  cookieList = m_cookieDomains.value(QL1S(""));
379  else
380  cookieList = m_cookieDomains.value(*it);
381 
382  if (!cookieList)
383  continue; // No cookies for this domain
384  }
385 
386  if (cookieList->getAdvice() != KCookieDunno)
387  advice = cookieList->getAdvice();
388 
389  QMutableListIterator<KHttpCookie> cookieIt (*cookieList);
390  while (cookieIt.hasNext())
391  {
392  KHttpCookie& cookie = cookieIt.next();
393  // If the we are setup to automatically accept all session cookies and to
394  // treat all cookies as session cookies or the current cookie is a session
395  // cookie, then send the cookie back regardless of domain policy.
396  if (advice == KCookieReject &&
397  !(m_autoAcceptSessionCookies &&
398  (m_ignoreCookieExpirationDate || cookie.expireDate() == 0)))
399  continue;
400 
401  if (!cookie.match(fqdn, domains, path, port))
402  continue;
403 
404  if( cookie.isSecure() && !secureRequest )
405  continue;
406 
407  if( cookie.isHttpOnly() && useDOMFormat )
408  continue;
409 
410  // Do not send expired cookies.
411  if ( cookie.isExpired())
412  {
413  // NOTE: there is no need to delete the cookie here because the
414  // cookieserver will invoke its saveCookieJar function as a result
415  // of the state change below. This will then result in the cookie
416  // being deleting at that point.
417  m_cookiesChanged = true;
418  continue;
419  }
420 
421  if (windowId && (cookie.windowIds().indexOf(windowId) == -1))
422  cookie.windowIds().append(windowId);
423 
424  if (it == itEnd) // Only needed when processing pending cookies
425  removeDuplicateFromList(&allCookies, cookie);
426 
427  allCookies.append(cookie);
428  }
429 
430  if (it == itEnd)
431  break; // Finished.
432  }
433 
434  int protVersion = 0;
435  Q_FOREACH(const KHttpCookie& cookie, allCookies) {
436  if (cookie.protocolVersion() > protVersion)
437  protVersion = cookie.protocolVersion();
438  }
439 
440  if (!allCookies.isEmpty())
441  {
442  if (!useDOMFormat)
443  cookieStr = QL1S("Cookie: ");
444 
445  if (protVersion > 0)
446  cookieStr = cookieStr + QL1S("$Version=") + QString::number(protVersion) + QL1S("; ");
447 
448  Q_FOREACH(const KHttpCookie& cookie, allCookies)
449  cookieStr = cookieStr + cookie.cookieStr(useDOMFormat) + QL1S("; ");
450 
451  cookieStr.truncate(cookieStr.length() - 2); // Remove the trailing ';'
452  }
453 
454  return cookieStr;
455 }
456 
457 //
458 // This function parses a string like 'my_name="my_value";' and returns
459 // 'my_name' in Name and 'my_value' in Value.
460 //
461 // A pointer to the end of the parsed part is returned.
462 // This pointer points either to:
463 // '\0' - The end of the string has reached.
464 // ';' - Another my_name="my_value" pair follows
465 // ',' - Another cookie follows
466 // '\n' - Another header follows
467 static const char * parseNameValue(const char *header,
468  QString &Name,
469  QString &Value,
470  bool keepQuotes=false,
471  bool rfcQuotes=false)
472 {
473  const char *s = header;
474  // Parse 'my_name' part
475  for(; (*s != '='); s++)
476  {
477  if ((*s=='\0') || (*s==';') || (*s=='\n'))
478  {
479  // No '=' sign -> use string as the value, name is empty
480  // (behavior found in Mozilla and IE)
481  Name = QL1S("");
482  Value = QL1S(header);
483  Value.truncate( s - header );
484  Value = Value.trimmed();
485  return s;
486  }
487  }
488 
489  Name = QL1S(header);
490  Name.truncate( s - header );
491  Name = Name.trimmed();
492 
493  // *s == '='
494  s++;
495 
496  // Skip any whitespace
497  for(; (*s == ' ') || (*s == '\t'); s++)
498  {
499  if ((*s=='\0') || (*s==';') || (*s=='\n'))
500  {
501  // End of Name
502  Value = "";
503  return s;
504  }
505  }
506 
507  if ((rfcQuotes || !keepQuotes) && (*s == '\"'))
508  {
509  // Parse '"my_value"' part (quoted value)
510  if (keepQuotes)
511  header = s++;
512  else
513  header = ++s; // skip "
514  for(;(*s != '\"');s++)
515  {
516  if ((*s=='\0') || (*s=='\n'))
517  {
518  // End of Name
519  Value = QL1S(header);
520  Value.truncate(s - header);
521  return s;
522  }
523  }
524  Value = QL1S(header);
525  // *s == '\"';
526  if (keepQuotes)
527  Value.truncate( ++s - header );
528  else
529  Value.truncate( s++ - header );
530 
531  // Skip any remaining garbage
532  for(;; s++)
533  {
534  if ((*s=='\0') || (*s==';') || (*s=='\n'))
535  break;
536  }
537  }
538  else
539  {
540  // Parse 'my_value' part (unquoted value)
541  header = s;
542  while ((*s != '\0') && (*s != ';') && (*s != '\n'))
543  s++;
544  // End of Name
545  Value = QL1S(header);
546  Value.truncate( s - header );
547  Value = Value.trimmed();
548  }
549  return s;
550 
551 }
552 
553 void KCookieJar::stripDomain(const QString &_fqdn, QString &_domain)
554 {
555  QStringList domains;
556  extractDomains(_fqdn, domains);
557  if (domains.count() > 3)
558  _domain = domains[3];
559  else if ( domains.count() > 0 )
560  _domain = domains[0];
561  else
562  _domain = QL1S("");
563 }
564 
565 QString KCookieJar::stripDomain(const KHttpCookie& cookie)
566 {
567  QString domain; // We file the cookie under this domain.
568  if (cookie.domain().isEmpty())
569  stripDomain( cookie.host(), domain);
570  else
571  domain = cookie.domain();
572  return domain;
573 }
574 
575 bool KCookieJar::parseUrl(const QString &_url,
576  QString &_fqdn,
577  QString &_path,
578  int *port)
579 {
580  KUrl kurl(_url);
581  if (!kurl.isValid() || kurl.protocol().isEmpty())
582  return false;
583 
584  _fqdn = kurl.host().toLower();
585  // Cookie spoofing protection. Since there is no way a path separator,
586  // a space or the escape encoding character is allowed in the hostname
587  // according to RFC 2396, reject attempts to include such things there!
588  if (_fqdn.contains(QL1C('/')) || _fqdn.contains(QL1C('%')))
589  return false; // deny everything!!
590 
591  // Set the port number from the protocol when one is found...
592  if (port)
593  *port = kurl.port();
594 
595  _path = kurl.path();
596  if (_path.isEmpty())
597  _path = QL1S("/");
598 
599  return true;
600 }
601 
602 // not static because it uses m_twoLevelTLD
603 void KCookieJar::extractDomains(const QString &_fqdn,
604  QStringList &_domains) const
605 {
606  if (_fqdn.isEmpty()) {
607  _domains.append( QL1S("localhost") );
608  return;
609  }
610 
611  // Return numeric IPv6 addresses as is...
612  if (_fqdn[0] == '[')
613  {
614  _domains.append( _fqdn );
615  return;
616  }
617  // Return numeric IPv4 addresses as is...
618  if (_fqdn[0] >= '0' && _fqdn[0] <= '9' && _fqdn.indexOf(QRegExp(IP_ADDRESS_EXPRESSION)) > -1)
619  {
620  _domains.append( _fqdn );
621  return;
622  }
623 
624  // Always add the FQDN at the start of the list for
625  // hostname == cookie-domainname checks!
626  _domains.append(_fqdn);
627  _domains.append(QL1C('.') + _fqdn);
628 
629  QStringList partList = _fqdn.split(QL1C('.'), QString::SkipEmptyParts);
630 
631  if (partList.count())
632  partList.erase(partList.begin()); // Remove hostname
633 
634  while(partList.count())
635  {
636 
637  if (partList.count() == 1)
638  break; // We only have a TLD left.
639 
640  if ((partList.count() == 2) && m_twoLevelTLD.contains(partList[1].toLower()))
641  {
642  // This domain uses two-level TLDs in the form xxxx.yy
643  break;
644  }
645 
646  if ((partList.count() == 2) && (partList[1].length() == 2))
647  {
648  // If this is a TLD, we should stop. (e.g. co.uk)
649  // We assume this is a TLD if it ends with .xx.yy or .x.yy
650  if (partList[0].length() <= 2)
651  break; // This is a TLD.
652 
653  // Catch some TLDs that we miss with the previous check
654  // e.g. com.au, org.uk, mil.co
655  if (m_gTLDs.contains(partList[0].toLower()))
656  break;
657  }
658 
659  QString domain = partList.join(QL1S("."));
660  _domains.append(domain);
661  _domains.append(QL1C('.') + domain);
662  partList.erase(partList.begin()); // Remove part
663  }
664 }
665 
666 //
667 // This function parses cookie_headers and returns a linked list of
668 // KHttpCookie objects for all cookies found in cookie_headers.
669 // If no cookies could be found 0 is returned.
670 //
671 // cookie_headers should be a concatenation of all lines of a HTTP-header
672 // which start with "Set-Cookie". The lines should be separated by '\n's.
673 //
674 KHttpCookieList KCookieJar::makeCookies(const QString &_url,
675  const QByteArray &cookie_headers,
676  long windowId)
677 {
678  QString fqdn, path;
679 
680  if (!parseUrl(_url, fqdn, path))
681  return KHttpCookieList(); // Error parsing _url
682 
683  QString Name, Value;
684  KHttpCookieList cookieList, cookieList2;
685 
686  bool isRFC2965 = false;
687  bool crossDomain = false;
688  const char *cookieStr = cookie_headers.constData();
689 
690  QString defaultPath;
691  const int index = path.lastIndexOf(QL1C('/'));
692  if (index > 0)
693  defaultPath = path.left(index);
694 
695  // Check for cross-domain flag from kio_http
696  if (qstrncmp(cookieStr, "Cross-Domain\n", 13) == 0)
697  {
698  cookieStr += 13;
699  crossDomain = true;
700  }
701 
702  // The hard stuff :)
703  for(;;)
704  {
705  // check for "Set-Cookie"
706  if (qstrnicmp(cookieStr, "Set-Cookie:", 11) == 0)
707  {
708  cookieStr = parseNameValue(cookieStr+11, Name, Value, true);
709 
710  // Host = FQDN
711  // Default domain = ""
712  // Default path according to rfc2109
713 
714 
715  KHttpCookie cookie(fqdn, QL1S(""), defaultPath, Name, Value);
716  if (windowId)
717  cookie.mWindowIds.append(windowId);
718  cookie.mCrossDomain = crossDomain;
719 
720  // Insert cookie in chain
721  cookieList.append(cookie);
722  }
723  else if (qstrnicmp(cookieStr, "Set-Cookie2:", 12) == 0)
724  {
725  // Attempt to follow rfc2965
726  isRFC2965 = true;
727  cookieStr = parseNameValue(cookieStr+12, Name, Value, true, true);
728 
729  // Host = FQDN
730  // Default domain = ""
731  // Default path according to rfc2965
732 
733  KHttpCookie cookie(fqdn, QL1S(""), defaultPath, Name, Value);
734  if (windowId)
735  cookie.mWindowIds.append(windowId);
736  cookie.mCrossDomain = crossDomain;
737 
738  // Insert cookie in chain
739  cookieList2.append(cookie);
740  }
741  else
742  {
743  // This is not the start of a cookie header, skip till next line.
744  while (*cookieStr && *cookieStr != '\n')
745  cookieStr++;
746 
747  if (*cookieStr == '\n')
748  cookieStr++;
749 
750  if (!*cookieStr)
751  break; // End of cookie_headers
752  else
753  continue; // end of this header, continue with next.
754  }
755 
756  while ((*cookieStr == ';') || (*cookieStr == ' '))
757  {
758  cookieStr++;
759 
760  // Name-Value pair follows
761  cookieStr = parseNameValue(cookieStr, Name, Value);
762  KHttpCookie& lastCookie = (isRFC2965 ? cookieList2.last() : cookieList.last());
763 
764  if (Name.compare(QL1S("domain"), Qt::CaseInsensitive) == 0)
765  {
766  QString dom = Value.toLower();
767  // RFC2965 3.2.2: If an explicitly specified value does not
768  // start with a dot, the user agent supplies a leading dot
769  if(dom.length() && dom[0] != '.')
770  dom.prepend(".");
771  // remove a trailing dot
772  if(dom.length() > 2 && dom[dom.length()-1] == '.')
773  dom = dom.left(dom.length()-1);
774 
775  if(dom.count(QL1C('.')) > 1 || dom == ".local")
776  lastCookie.mDomain = dom;
777  }
778  else if (Name.compare(QL1S("max-age"), Qt::CaseInsensitive) == 0)
779  {
780  int max_age = Value.toInt();
781  if (max_age == 0)
782  lastCookie.mExpireDate = 1;
783  else
784  lastCookie.mExpireDate = toEpochSecs(QDateTime::currentDateTimeUtc().addSecs(max_age));
785  }
786  else if (Name.compare(QL1S("expires"), Qt::CaseInsensitive) == 0)
787  {
788  const QDateTime dt = parseDate(Value);
789 
790  if (dt.isValid()) {
791  lastCookie.mExpireDate = toEpochSecs(dt);
792  if (lastCookie.mExpireDate == 0)
793  lastCookie.mExpireDate = 1;
794  }
795  }
796  else if (Name.compare(QL1S("path"), Qt::CaseInsensitive) == 0)
797  {
798  if (Value.isEmpty())
799  lastCookie.mPath.clear(); // Catch "" <> QString()
800  else
801  lastCookie.mPath = QUrl::fromPercentEncoding(Value.toLatin1());
802  lastCookie.mExplicitPath = true;
803  }
804  else if (Name.compare(QL1S("version"), Qt::CaseInsensitive) == 0)
805  {
806  lastCookie.mProtocolVersion = Value.toInt();
807  }
808  else if (Name.compare(QL1S("secure"), Qt::CaseInsensitive) == 0 ||
809  (Name.isEmpty() && Value.compare(QL1S("secure"), Qt::CaseInsensitive) == 0))
810  {
811  lastCookie.mSecure = true;
812  }
813  else if (Name.compare(QL1S("httponly"), Qt::CaseInsensitive) == 0 ||
814  (Name.isEmpty() && Value.compare(QL1S("httponly"), Qt::CaseInsensitive) == 0))
815  {
816  lastCookie.mHttpOnly = true;
817  }
818  else if (isRFC2965 && (Name.compare(QL1S("port"), Qt::CaseInsensitive) == 0 ||
819  (Name.isEmpty() && Value.compare(QL1S("port"), Qt::CaseInsensitive) == 0)))
820  {
821  // Based on the port selection rule of RFC 2965 section 3.3.4...
822  if (Name.isEmpty())
823  {
824  // We intentionally append a -1 first in order to distinguish
825  // between only a 'Port' vs a 'Port="80 443"' in the sent cookie.
826  lastCookie.mPorts.append(-1);
827  const bool secureRequest = (_url.startsWith(QL1S("https://"), Qt::CaseInsensitive) ||
828  _url.startsWith(QL1S("webdavs://"), Qt::CaseInsensitive));
829  if (secureRequest)
830  lastCookie.mPorts.append(443);
831  else
832  lastCookie.mPorts.append(80);
833  }
834  else
835  {
836  bool ok;
837  const QStringList portNums = Value.split(QL1C(' '), QString::SkipEmptyParts);
838  Q_FOREACH(const QString& portNum, portNums)
839  {
840  const int port = portNum.toInt(&ok);
841  if (ok)
842  lastCookie.mPorts.append(port);
843  }
844  }
845  }
846  }
847 
848  if (*cookieStr == '\0')
849  break; // End of header
850 
851  // Skip ';' or '\n'
852  cookieStr++;
853  }
854 
855  // RFC2965 cookies come last so that they override netscape cookies.
856  while(!cookieList2.isEmpty()) {
857  KHttpCookie& lastCookie = cookieList2.first();
858  removeDuplicateFromList(&cookieList, lastCookie, true);
859  cookieList.append(lastCookie);
860  cookieList2.removeFirst();
861  }
862 
863  return cookieList;
864 }
865 
872 KHttpCookieList KCookieJar::makeDOMCookies(const QString &_url,
873  const QByteArray &cookie_domstring,
874  long windowId)
875 {
876  // A lot copied from above
877  KHttpCookieList cookieList;
878 
879  const char *cookieStr = cookie_domstring.data();
880  QString fqdn;
881  QString path;
882 
883  if (!parseUrl(_url, fqdn, path))
884  {
885  // Error parsing _url
886  return KHttpCookieList();
887  }
888 
889  QString Name;
890  QString Value;
891  // This time it's easy
892  while(*cookieStr)
893  {
894  cookieStr = parseNameValue(cookieStr, Name, Value);
895 
896  // Host = FQDN
897  // Default domain = ""
898  // Default path = ""
899  KHttpCookie cookie(fqdn, QString(), QString(),
900  Name, Value );
901  if (windowId)
902  cookie.mWindowIds.append(windowId);
903 
904  cookieList.append(cookie);
905 
906  if (*cookieStr != '\0')
907  cookieStr++; // Skip ';' or '\n'
908  }
909 
910  return cookieList;
911 }
912 
913 // KHttpCookieList sorting
915 
916 // We want the longest path first
917 static bool compareCookies(const KHttpCookie& item1, const KHttpCookie& item2)
918 {
919  return item1.path().length() > item2.path().length();
920 }
921 
922 
923 #ifdef MAX_COOKIE_LIMIT
924 static void makeRoom(KHttpCookieList *cookieList, KHttpCookiePtr &cookiePtr)
925 {
926  // Too many cookies: throw one away, try to be somewhat clever
927  KHttpCookiePtr lastCookie = 0;
928  for(KHttpCookiePtr cookie = cookieList->first(); cookie; cookie = cookieList->next())
929  {
930  if (compareCookies(cookie, cookiePtr))
931  break;
932  lastCookie = cookie;
933  }
934  if (!lastCookie)
935  lastCookie = cookieList->first();
936  cookieList->removeRef(lastCookie);
937 }
938 #endif
939 
940 //
941 // This function hands a KHttpCookie object over to the cookie jar.
942 //
943 void KCookieJar::addCookie(KHttpCookie &cookie)
944 {
945  QStringList domains;
946  // We always need to do this to make sure that the
947  // that cookies of type hostname == cookie-domainname
948  // are properly removed and/or updated as necessary!
949  extractDomains( cookie.host(), domains );
950 
951  QStringListIterator it (domains);
952  while (it.hasNext())
953  {
954  const QString& key = it.next();
955  KHttpCookieList* list;
956 
957  if (key.isNull())
958  list = m_cookieDomains.value(QL1S(""));
959  else
960  list = m_cookieDomains.value(key);
961 
962  if (list)
963  removeDuplicateFromList(list, cookie, false, true);
964  }
965 
966  const QString domain = stripDomain( cookie );
967  KHttpCookieList* cookieList;
968  if (domain.isNull())
969  cookieList = m_cookieDomains.value(QL1S(""));
970  else
971  cookieList = m_cookieDomains.value(domain);
972 
973  if (!cookieList)
974  {
975  // Make a new cookie list
976  cookieList = new KHttpCookieList();
977 
978  // All cookies whose domain is not already
979  // known to us should be added with KCookieDunno.
980  // KCookieDunno means that we use the global policy.
981  cookieList->setAdvice( KCookieDunno );
982 
983  m_cookieDomains.insert( domain, cookieList);
984 
985  // Update the list of domains
986  m_domainList.append(domain);
987  }
988 
989  // Add the cookie to the cookie list
990  // The cookie list is sorted 'longest path first'
991  if (!cookie.isExpired())
992  {
993 #ifdef MAX_COOKIE_LIMIT
994  if (cookieList->count() >= MAX_COOKIES_PER_HOST)
995  makeRoom(cookieList, cookie); // Delete a cookie
996 #endif
997  cookieList->push_back(cookie);
998  // Use a stable sort so that unit tests are reliable.
999  // In practice it doesn't matter though.
1000  qStableSort(cookieList->begin(), cookieList->end(), compareCookies);
1001 
1002  m_cookiesChanged = true;
1003  }
1004 }
1005 
1006 //
1007 // This function advices whether a single KHttpCookie object should
1008 // be added to the cookie jar.
1009 //
1010 KCookieAdvice KCookieJar::cookieAdvice(KHttpCookie& cookie)
1011 {
1012  if (m_rejectCrossDomainCookies && cookie.isCrossDomain())
1013  return KCookieReject;
1014 
1015  QStringList domains;
1016  extractDomains(cookie.host(), domains);
1017 
1018  // If the cookie specifies a domain, check whether it is valid. Otherwise,
1019  // accept the cookie anyways but removes the domain="" value to prevent
1020  // cross-site cookie injection.
1021  if (!cookie.domain().isEmpty()) {
1022  if (!domains.contains(cookie.domain()) &&
1023  !cookie.domain().endsWith(QL1C('.') + cookie.host()))
1024  cookie.fixDomain(QString());
1025  }
1026 
1027  if (m_autoAcceptSessionCookies && (cookie.expireDate() == 0 ||
1028  m_ignoreCookieExpirationDate))
1029  return KCookieAccept;
1030 
1031  KCookieAdvice advice = KCookieDunno;
1032  QStringListIterator it (domains);
1033  while(advice == KCookieDunno && it.hasNext()) {
1034  const QString& domain = it.next();
1035  if (domain.startsWith(QL1C('.')) || cookie.host() == domain) {
1036  KHttpCookieList *cookieList = m_cookieDomains.value(domain);
1037  if (cookieList)
1038  advice = cookieList->getAdvice();
1039  }
1040  }
1041 
1042  if (advice == KCookieDunno)
1043  advice = m_globalAdvice;
1044 
1045  return advice;
1046 }
1047 
1048 //
1049 // This function gets the advice for all cookies originating from
1050 // _domain.
1051 //
1052 KCookieAdvice KCookieJar::getDomainAdvice(const QString &_domain)
1053 {
1054  KHttpCookieList *cookieList = m_cookieDomains.value(_domain);
1055  KCookieAdvice advice;
1056 
1057  if (cookieList)
1058  advice = cookieList->getAdvice();
1059  else
1060  advice = KCookieDunno;
1061 
1062  return advice;
1063 }
1064 
1065 //
1066 // This function sets the advice for all cookies originating from
1067 // _domain.
1068 //
1069 void KCookieJar::setDomainAdvice(const QString &_domain, KCookieAdvice _advice)
1070 {
1071  QString domain(_domain);
1072  KHttpCookieList *cookieList = m_cookieDomains.value(domain);
1073 
1074  if (cookieList) {
1075  if (cookieList->getAdvice() != _advice) {
1076  m_configChanged = true;
1077  // domain is already known
1078  cookieList->setAdvice( _advice);
1079  }
1080 
1081  if ((cookieList->isEmpty()) && (_advice == KCookieDunno)) {
1082  // This deletes cookieList!
1083  delete m_cookieDomains.take(domain);
1084  m_domainList.removeAll(domain);
1085  }
1086  } else {
1087  // domain is not yet known
1088  if (_advice != KCookieDunno) {
1089  // We should create a domain entry
1090  m_configChanged = true;
1091  // Make a new cookie list
1092  cookieList = new KHttpCookieList();
1093  cookieList->setAdvice(_advice);
1094  m_cookieDomains.insert(domain, cookieList);
1095  // Update the list of domains
1096  m_domainList.append( domain);
1097  }
1098  }
1099 }
1100 
1101 //
1102 // This function sets the advice for all cookies originating from
1103 // the same domain as _cookie
1104 //
1105 void KCookieJar::setDomainAdvice(const KHttpCookie& cookie, KCookieAdvice _advice)
1106 {
1107  QString domain;
1108  stripDomain(cookie.host(), domain); // We file the cookie under this domain.
1109  setDomainAdvice(domain, _advice);
1110 }
1111 
1112 //
1113 // This function sets the global advice for cookies
1114 //
1115 void KCookieJar::setGlobalAdvice(KCookieAdvice _advice)
1116 {
1117  if (m_globalAdvice != _advice)
1118  m_configChanged = true;
1119  m_globalAdvice = _advice;
1120 }
1121 
1122 //
1123 // Get a list of all domains known to the cookie jar.
1124 //
1125 const QStringList& KCookieJar::getDomainList()
1126 {
1127  return m_domainList;
1128 }
1129 
1130 //
1131 // Get a list of all cookies in the cookie jar originating from _domain.
1132 //
1133 KHttpCookieList *KCookieJar::getCookieList(const QString & _domain,
1134  const QString & _fqdn )
1135 {
1136  QString domain;
1137 
1138  if (_domain.isEmpty())
1139  stripDomain(_fqdn, domain);
1140  else
1141  domain = _domain;
1142 
1143  return m_cookieDomains.value(domain);
1144 }
1145 
1146 //
1147 // Eat a cookie out of the jar.
1148 // cookieIterator should be one of the cookies returned by getCookieList()
1149 //
1150 void KCookieJar::eatCookie(KHttpCookieList::iterator cookieIterator)
1151 {
1152  const KHttpCookie& cookie = *cookieIterator;
1153  const QString domain = stripDomain(cookie); // We file the cookie under this domain.
1154  KHttpCookieList *cookieList = m_cookieDomains.value(domain);
1155 
1156  if (cookieList) {
1157  // This deletes cookie!
1158  cookieList->erase(cookieIterator);
1159 
1160  if ((cookieList->isEmpty()) &&
1161  (cookieList->getAdvice() == KCookieDunno))
1162  {
1163  // This deletes cookieList!
1164  delete m_cookieDomains.take(domain);
1165  m_domainList.removeAll(domain);
1166  }
1167  }
1168 }
1169 
1170 void KCookieJar::eatCookiesForDomain(const QString &domain)
1171 {
1172  KHttpCookieList *cookieList = m_cookieDomains.value(domain);
1173  if (!cookieList || cookieList->isEmpty()) return;
1174 
1175  cookieList->clear();
1176  if (cookieList->getAdvice() == KCookieDunno)
1177  {
1178  // This deletes cookieList!
1179  delete m_cookieDomains.take(domain);
1180  m_domainList.removeAll(domain);
1181  }
1182  m_cookiesChanged = true;
1183 }
1184 
1185 void KCookieJar::eatSessionCookies( long windowId )
1186 {
1187  if (!windowId)
1188  return;
1189 
1190  Q_FOREACH(const QString& domain, m_domainList)
1191  eatSessionCookies( domain, windowId, false );
1192 }
1193 
1194 void KCookieJar::eatAllCookies()
1195 {
1196  Q_FOREACH(const QString& domain, m_domainList)
1197  eatCookiesForDomain(domain); // This might remove domain from m_domainList!
1198 }
1199 
1200 void KCookieJar::eatSessionCookies( const QString& fqdn, long windowId,
1201  bool isFQDN )
1202 {
1203  KHttpCookieList* cookieList;
1204  if ( !isFQDN )
1205  cookieList = m_cookieDomains.value(fqdn);
1206  else {
1207  QString domain;
1208  stripDomain( fqdn, domain );
1209  cookieList = m_cookieDomains.value(domain);
1210  }
1211 
1212  if (cookieList) {
1213  QMutableListIterator<KHttpCookie> cookieIterator(*cookieList);
1214  while (cookieIterator.hasNext()) {
1215  KHttpCookie& cookie = cookieIterator.next();
1216  if ((cookie.expireDate() != 0) && !m_ignoreCookieExpirationDate) {
1217  continue;
1218  }
1219 
1220  QList<long> &ids = cookie.windowIds();
1221 
1222 #ifndef NDEBUG
1223  if (ids.contains(windowId)) {
1224  if (ids.count() > 1)
1225  kDebug(7104) << "removing window id" << windowId << "from session cookie";
1226  else
1227  kDebug(7104) << "deleting session cookie";
1228  }
1229 #endif
1230  if (!ids.removeAll(windowId) || !ids.isEmpty()) {
1231  continue;
1232  }
1233  cookieIterator.remove();
1234  }
1235  }
1236 }
1237 
1238 static QString hostWithPort(const KHttpCookie* cookie)
1239 {
1240  const QList<int>& ports = cookie->ports();
1241 
1242  if (ports.isEmpty())
1243  return cookie->host();
1244 
1245  QStringList portList;
1246  Q_FOREACH(int port, ports)
1247  portList << QString::number(port);
1248 
1249  return (cookie->host() + QL1C(':') + portList.join(QL1S(",")));
1250 }
1251 
1252 //
1253 // Saves all cookies to the file '_filename'.
1254 // On succes 'true' is returned.
1255 // On failure 'false' is returned.
1256 bool KCookieJar::saveCookies(const QString &_filename)
1257 {
1258  KSaveFile cookieFile(_filename);
1259 
1260  if (!cookieFile.open())
1261  return false;
1262  cookieFile.setPermissions(QFile::ReadUser|QFile::WriteUser);
1263 
1264  QTextStream ts(&cookieFile);
1265 
1266  ts << "# KDE Cookie File v2\n#\n";
1267 
1268  QString s;
1269  s.sprintf("%-20s %-20s %-12s %-10s %-4s %-20s %-4s %s\n",
1270  "# Host", "Domain", "Path", "Exp.date", "Prot",
1271  "Name", "Sec", "Value");
1272  ts << s.toLatin1().constData();
1273 
1274  QStringListIterator it(m_domainList);
1275  while (it.hasNext())
1276  {
1277  const QString& domain = it.next();
1278  bool domainPrinted = false;
1279 
1280  KHttpCookieList *cookieList = m_cookieDomains.value(domain);
1281  if (!cookieList)
1282  continue;
1283 
1284  QMutableListIterator<KHttpCookie> cookieIterator(*cookieList);
1285  while (cookieIterator.hasNext()) {
1286  const KHttpCookie& cookie = cookieIterator.next();
1287  if (cookie.isExpired()) {
1288  // Delete expired cookies
1289  cookieIterator.remove();
1290  continue;
1291  }
1292  if (cookie.expireDate() != 0 && !m_ignoreCookieExpirationDate) {
1293  // Only save cookies that are not "session-only cookies"
1294  if (!domainPrinted) {
1295  domainPrinted = true;
1296  ts << '[' << domain.toLocal8Bit().data() << "]\n";
1297  }
1298  // Store persistent cookies
1299  const QString path = QL1S("\"") + cookie.path() + QL1C('"');
1300  const QString domain = QL1S("\"") + cookie.domain() + QL1C('"');
1301  const QString host = hostWithPort(&cookie);
1302 
1303  // TODO: replace with direct QTextStream output ?
1304  s.sprintf("%-20s %-20s %-12s %10lld %3d %-20s %-4i %s\n",
1305  host.toLatin1().constData(), domain.toLatin1().constData(),
1306  path.toLatin1().constData(), cookie.expireDate(),
1307  cookie.protocolVersion(),
1308  cookie.name().isEmpty() ? cookie.value().toLatin1().constData() : cookie.name().toLatin1().constData(),
1309  (cookie.isSecure() ? 1 : 0) + (cookie.isHttpOnly() ? 2 : 0) +
1310  (cookie.hasExplicitPath() ? 4 : 0) + (cookie.name().isEmpty() ? 8 : 0),
1311  cookie.value().toLatin1().constData());
1312  ts << s.toLatin1().constData();
1313  }
1314  }
1315  }
1316 
1317  return cookieFile.finalize();
1318 }
1319 
1320 static const char *parseField(char* &buffer, bool keepQuotes=false)
1321 {
1322  char *result;
1323  if (!keepQuotes && (*buffer == '\"'))
1324  {
1325  // Find terminating "
1326  buffer++;
1327  result = buffer;
1328  while((*buffer != '\"') && (*buffer))
1329  buffer++;
1330  }
1331  else
1332  {
1333  // Find first white space
1334  result = buffer;
1335  while((*buffer != ' ') && (*buffer != '\t') && (*buffer != '\n') && (*buffer))
1336  buffer++;
1337  }
1338 
1339  if (!*buffer)
1340  return result; //
1341  *buffer++ = '\0';
1342 
1343  // Skip white-space
1344  while((*buffer == ' ') || (*buffer == '\t') || (*buffer == '\n'))
1345  buffer++;
1346 
1347  return result;
1348 }
1349 
1350 
1351 static QString extractHostAndPorts(const QString& str, QList<int>* ports = 0)
1352 {
1353  if (str.isEmpty())
1354  return str;
1355 
1356  const int index = str.indexOf(QL1C(':'));
1357  if (index == -1)
1358  return str;
1359 
1360  const QString host = str.left(index);
1361  if (ports) {
1362  bool ok;
1363  QStringList portList = str.mid(index+1).split(QL1C(','));
1364  Q_FOREACH(const QString& portStr, portList) {
1365  const int portNum = portStr.toInt(&ok);
1366  if (ok)
1367  ports->append(portNum);
1368  }
1369  }
1370 
1371  return host;
1372 }
1373 
1374 //
1375 // Reloads all cookies from the file '_filename'.
1376 // On succes 'true' is returned.
1377 // On failure 'false' is returned.
1378 bool KCookieJar::loadCookies(const QString &_filename)
1379 {
1380  QFile cookieFile (_filename);
1381 
1382  if (!cookieFile.open(QIODevice::ReadOnly))
1383  return false;
1384 
1385  int version = 1;
1386  bool success = false;
1387  char *buffer = new char[READ_BUFFER_SIZE];
1388  qint64 len = cookieFile.readLine(buffer, READ_BUFFER_SIZE-1);
1389 
1390  if (len != -1)
1391  {
1392  if (qstrcmp(buffer, "# KDE Cookie File\n") == 0)
1393  {
1394  success = true;
1395  }
1396  else if(qstrcmp(buffer, "# KDE Cookie File v") > 0)
1397  {
1398  bool ok = false;
1399  const int verNum = QByteArray(buffer+19, len-19).trimmed().toInt(&ok);
1400  if (ok)
1401  {
1402  version = verNum;
1403  success = true;
1404  }
1405  }
1406  }
1407 
1408  if (success)
1409  {
1410  const qint64 currentTime = epoch();
1411  QList<int> ports;
1412 
1413  while(cookieFile.readLine(buffer, READ_BUFFER_SIZE-1) != -1)
1414  {
1415  char *line = buffer;
1416  // Skip lines which begin with '#' or '['
1417  if ((line[0] == '#') || (line[0] == '['))
1418  continue;
1419 
1420  const QString host = extractHostAndPorts(QL1S(parseField(line)), &ports);
1421  const QString domain = QL1S( parseField(line) );
1422  if (host.isEmpty() && domain.isEmpty())
1423  continue;
1424  const QString path = QL1S( parseField(line) );
1425  const QString expStr = QL1S( parseField(line) );
1426  if (expStr.isEmpty()) continue;
1427  const qint64 expDate = expStr.toLongLong();
1428  const QString verStr = QL1S( parseField(line) );
1429  if (verStr.isEmpty()) continue;
1430  int protVer = verStr.toInt();
1431  QString name = QL1S( parseField(line) );
1432  bool keepQuotes = false;
1433  bool secure = false;
1434  bool httpOnly = false;
1435  bool explicitPath = false;
1436  const char *value = 0;
1437  if ((version == 2) || (protVer >= 200))
1438  {
1439  if (protVer >= 200)
1440  protVer -= 200;
1441  int i = atoi( parseField(line) );
1442  secure = i & 1;
1443  httpOnly = i & 2;
1444  explicitPath = i & 4;
1445  if (i & 8)
1446  name = "";
1447  line[strlen(line)-1] = '\0'; // Strip LF.
1448  value = line;
1449  }
1450  else
1451  {
1452  if (protVer >= 100)
1453  {
1454  protVer -= 100;
1455  keepQuotes = true;
1456  }
1457  value = parseField(line, keepQuotes);
1458  secure = QByteArray(parseField(line)).toShort();
1459  }
1460 
1461  // Expired or parse error
1462  if (!value || expDate == 0 || expDate < currentTime)
1463  continue;
1464 
1465  KHttpCookie cookie(host, domain, path, name, value, expDate,
1466  protVer, secure, httpOnly, explicitPath);
1467  if (ports.count())
1468  cookie.mPorts = ports;
1469  addCookie(cookie);
1470  }
1471  }
1472 
1473  delete [] buffer;
1474  m_cookiesChanged = false;
1475  return success;
1476 }
1477 
1478 //
1479 // Save the cookie configuration
1480 //
1481 
1482 void KCookieJar::saveConfig(KConfig *_config)
1483 {
1484  if (!m_configChanged)
1485  return;
1486 
1487  KConfigGroup dlgGroup(_config, "Cookie Dialog");
1488  dlgGroup.writeEntry("PreferredPolicy", static_cast<int>(m_preferredPolicy));
1489  dlgGroup.writeEntry("ShowCookieDetails", m_showCookieDetails );
1490  KConfigGroup policyGroup(_config,"Cookie Policy");
1491  policyGroup.writeEntry("CookieGlobalAdvice", adviceToStr( m_globalAdvice));
1492 
1493  QStringList domainSettings;
1494  QStringListIterator it (m_domainList);
1495  while (it.hasNext())
1496  {
1497  const QString& domain = it.next();
1498  KCookieAdvice advice = getDomainAdvice( domain);
1499  if (advice != KCookieDunno)
1500  {
1501  const QString value = domain + QL1C(':') + adviceToStr(advice);
1502  domainSettings.append(value);
1503  }
1504  }
1505  policyGroup.writeEntry("CookieDomainAdvice", domainSettings);
1506  _config->sync();
1507  m_configChanged = false;
1508 }
1509 
1510 
1511 //
1512 // Load the cookie configuration
1513 //
1514 
1515 void KCookieJar::loadConfig(KConfig *_config, bool reparse )
1516 {
1517  if ( reparse )
1518  _config->reparseConfiguration();
1519 
1520  KConfigGroup dlgGroup(_config, "Cookie Dialog");
1521  m_showCookieDetails = dlgGroup.readEntry( "ShowCookieDetails" , false );
1522  m_preferredPolicy = static_cast<KCookieDefaultPolicy>(dlgGroup.readEntry("PreferredPolicy", 0));
1523 
1524  KConfigGroup policyGroup(_config,"Cookie Policy");
1525  const QStringList domainSettings = policyGroup.readEntry("CookieDomainAdvice", QStringList());
1526  // Warning: those default values are duplicated in the kcm (kio/kcookiespolicies.cpp)
1527  m_rejectCrossDomainCookies = policyGroup.readEntry("RejectCrossDomainCookies", true);
1528  m_autoAcceptSessionCookies = policyGroup.readEntry("AcceptSessionCookies", true);
1529  m_ignoreCookieExpirationDate = policyGroup.readEntry("IgnoreExpirationDate", false);
1530  m_globalAdvice = strToAdvice(policyGroup.readEntry("CookieGlobalAdvice", QString(QL1S("Accept"))));
1531 
1532  // Reset current domain settings first.
1533  Q_FOREACH( const QString &domain, m_domainList )
1534  setDomainAdvice(domain, KCookieDunno);
1535 
1536  // Now apply the domain settings read from config file...
1537  for (QStringList::ConstIterator it = domainSettings.constBegin(), itEnd = domainSettings.constEnd();
1538  it != itEnd; ++it)
1539  {
1540  const QString& value = *it;
1541  const int sepPos = value.lastIndexOf(QL1C(':'));
1542  if (sepPos <= 0)
1543  continue;
1544 
1545  const QString domain(value.left(sepPos));
1546  KCookieAdvice advice = strToAdvice( value.mid(sepPos + 1) );
1547  setDomainAdvice(domain, advice);
1548  }
1549 }
1550 
1551 QDebug operator<<(QDebug dbg, const KHttpCookie& cookie)
1552 {
1553  dbg.nospace() << cookie.cookieStr(false);
1554  return dbg.space();
1555 }
1556 
1557 QDebug operator<<(QDebug dbg, const KHttpCookieList& list)
1558 {
1559  Q_FOREACH(const KHttpCookie& cookie, list)
1560  dbg << cookie;
1561  return dbg;
1562 }
This file is part of the KDE documentation.
Documentation copyright © 1996-2012 The KDE developers.
Generated on Mon Sep 24 2012 11:27:27 by doxygen 1.8.1.1 written by Dimitri van Heesch, © 1997-2006

KDE's Doxygen guidelines are available online.

KIOSlave

Skip menu "KIOSlave"
  • Main Page
  • Alphabetical List
  • Class List
  • Class Hierarchy
  • Class Members
  • File List
  • File Members
  • Related Pages

kdelibs-4.9.1 API Reference

Skip menu "kdelibs-4.9.1 API Reference"
  • DNSSD
  • Interfaces
  •   KHexEdit
  •   KMediaPlayer
  •   KSpeech
  •   KTextEditor
  • kconf_update
  • KDE3Support
  •   KUnitTest
  • KDECore
  • KDED
  • KDEsu
  • KDEUI
  • KDEWebKit
  • KDocTools
  • KFile
  • KHTML
  • KImgIO
  • KInit
  • kio
  • KIOSlave
  • KJS
  •   KJS-API
  •   WTF
  • kjsembed
  • KNewStuff
  • KParts
  • KPty
  • Kross
  • KUnitConversion
  • KUtils
  • Nepomuk
  • Plasma
  • Solid
  • Sonnet
  • ThreadWeaver
Report problems with this website to our bug tracking system.
Contact the specific authors with questions and comments about the page contents.

KDE® and the K Desktop Environment® logo are registered trademarks of KDE e.V. | Legal