• Skip to content
  • Skip to link menu
Trinity API Reference
  • Trinity API Reference
  • tdeioslave/http
 

tdeioslave/http

  • tdeioslave
  • http
http.cc
1 /*
2  Copyright (C) 2000-2003 Waldo Bastian <bastian@kde.org>
3  Copyright (C) 2000-2002 George Staikos <staikos@kde.org>
4  Copyright (C) 2000-2002 Dawit Alemayehu <adawit@kde.org>
5  Copyright (C) 2001,2002 Hamish Rodda <rodda@kde.org>
6 
7  This library is free software; you can redistribute it and/or
8  modify it under the terms of the GNU Library General Public
9  License (LGPL) as published by the Free Software Foundation;
10  either version 2 of the License, or (at your option) any later
11  version.
12 
13  This library is distributed in the hope that it will be useful,
14  but WITHOUT ANY WARRANTY; without even the implied warranty of
15  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16  Library General Public License for more details.
17 
18  You should have received a copy of the GNU Library General Public License
19  along with this library; see the file COPYING.LIB. If not, write to
20  the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
21  Boston, MA 02110-1301, USA.
22 */
23 
24 #include <config.h>
25 
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <utime.h>
29 #include <stdlib.h>
30 #include <signal.h>
31 #include <sys/stat.h>
32 #include <sys/socket.h>
33 #include <netinet/in.h> // Required for AIX
34 #include <netinet/tcp.h>
35 #include <unistd.h> // must be explicitly included for MacOSX
36 
37 /*
38 #include <netdb.h>
39 #include <sys/time.h>
40 #include <sys/wait.h>
41 */
42 
43 #include <tqdom.h>
44 #include <tqfile.h>
45 #include <tqregexp.h>
46 #include <tqdatetime.h>
47 #include <tqstringlist.h>
48 #include <tqurl.h>
49 
50 #include <kurl.h>
51 #include <kidna.h>
52 #include <ksocks.h>
53 #include <kdebug.h>
54 #include <tdelocale.h>
55 #include <tdeconfig.h>
56 #include <kextsock.h>
57 #include <kservice.h>
58 #include <krfcdate.h>
59 #include <kmdcodec.h>
60 #include <kinstance.h>
61 #include <kresolver.h>
62 #include <kmimemagic.h>
63 #include <dcopclient.h>
64 #include <kdatastream.h>
65 #include <tdeapplication.h>
66 #include <kstandarddirs.h>
67 #include <kstringhandler.h>
68 #include <kremoteencoding.h>
69 
70 #include "tdeio/ioslave_defaults.h"
71 #include "tdeio/http_slave_defaults.h"
72 
73 #include "httpfilter.h"
74 #include "http.h"
75 
76 #ifdef HAVE_LIBGSSAPI
77 #ifdef GSSAPI_MIT
78 #include <gssapi/gssapi.h>
79 #else
80 #include <gssapi.h>
81 #endif /* GSSAPI_MIT */
82 
83 // Catch uncompatible crap (BR86019)
84 #if defined(GSS_RFC_COMPLIANT_OIDS) && (GSS_RFC_COMPLIANT_OIDS == 0)
85 #include <gssapi/gssapi_generic.h>
86 #define GSS_C_NT_HOSTBASED_SERVICE gss_nt_service_name
87 #endif
88 
89 #endif /* HAVE_LIBGSSAPI */
90 
91 #include <misc/tdentlm/tdentlm.h>
92 
93 using namespace TDEIO;
94 
95 extern "C" {
96  KDE_EXPORT int kdemain(int argc, char **argv);
97 }
98 
99 int kdemain( int argc, char **argv )
100 {
101  TDELocale::setMainCatalogue("tdelibs");
102  TDEInstance instance( "tdeio_http" );
103  ( void ) TDEGlobal::locale();
104 
105  if (argc != 4)
106  {
107  fprintf(stderr, "Usage: tdeio_http protocol domain-socket1 domain-socket2\n");
108  exit(-1);
109  }
110 
111  HTTPProtocol slave(argv[1], argv[2], argv[3]);
112  slave.dispatchLoop();
113  return 0;
114 }
115 
116 /*********************************** Generic utility functions ********************/
117 
118 static char * trimLead (char *orig_string)
119 {
120  while (*orig_string == ' ')
121  orig_string++;
122  return orig_string;
123 }
124 
125 static bool isCrossDomainRequest( const TQString& fqdn, const TQString& originURL )
126 {
127  if (originURL == "true") // Backwards compatibility
128  return true;
129 
130  KURL url ( originURL );
131 
132  // Document Origin domain
133  TQString a = url.host();
134 
135  // Current request domain
136  TQString b = fqdn;
137 
138  if (a == b)
139  return false;
140 
141  TQStringList l1 = TQStringList::split('.', a);
142  TQStringList l2 = TQStringList::split('.', b);
143 
144  while(l1.count() > l2.count())
145  l1.pop_front();
146 
147  while(l2.count() > l1.count())
148  l2.pop_front();
149 
150  while(l2.count() >= 2)
151  {
152  if (l1 == l2)
153  return false;
154 
155  l1.pop_front();
156  l2.pop_front();
157  }
158 
159  return true;
160 }
161 
162 /*
163  Eliminates any custom header that could potentically alter the request
164 */
165 static TQString sanitizeCustomHTTPHeader(const TQString& _header)
166 {
167  TQString sanitizedHeaders;
168  TQStringList headers = TQStringList::split(TQRegExp("[\r\n]"), _header);
169 
170  for(TQStringList::Iterator it = headers.begin(); it != headers.end(); ++it)
171  {
172  TQString header = (*it).lower();
173  // Do not allow Request line to be specified and ignore
174  // the other HTTP headers.
175  if (header.find(':') == -1 ||
176  header.startsWith("host") ||
177  header.startsWith("via"))
178  continue;
179 
180  sanitizedHeaders += (*it);
181  sanitizedHeaders += "\r\n";
182  }
183 
184  return sanitizedHeaders.stripWhiteSpace();
185 }
186 
187 
188 #define NO_SIZE ((TDEIO::filesize_t) -1)
189 
190 #ifdef HAVE_STRTOLL
191 #define STRTOLL strtoll
192 #else
193 #define STRTOLL strtol
194 #endif
195 
196 
197 /************************************** HTTPProtocol **********************************************/
198 
199 HTTPProtocol::HTTPProtocol( const TQCString &protocol, const TQCString &pool,
200  const TQCString &app )
201  :TCPSlaveBase( 0, protocol , pool, app,
202  (protocol == "https" || protocol == "webdavs") )
203 {
204  m_requestQueue.setAutoDelete(true);
205 
206  m_bBusy = false;
207  m_bFirstRequest = false;
208  m_bProxyAuthValid = false;
209 
210  m_iSize = NO_SIZE;
211  m_lineBufUnget = 0;
212 
213  m_protocol = protocol;
214 
215  m_maxCacheAge = DEFAULT_MAX_CACHE_AGE;
216  m_maxCacheSize = DEFAULT_MAX_CACHE_SIZE / 2;
217  m_remoteConnTimeout = DEFAULT_CONNECT_TIMEOUT;
218  m_remoteRespTimeout = DEFAULT_RESPONSE_TIMEOUT;
219  m_proxyConnTimeout = DEFAULT_PROXY_CONNECT_TIMEOUT;
220 
221  m_pid = getpid();
222 
223  setMultipleAuthCaching( true );
224  reparseConfiguration();
225 }
226 
227 HTTPProtocol::~HTTPProtocol()
228 {
229  httpClose(false);
230 }
231 
232 void HTTPProtocol::reparseConfiguration()
233 {
234  kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::reparseConfiguration" << endl;
235 
236  m_strProxyRealm = TQString::null;
237  m_strProxyAuthorization = TQString::null;
238  ProxyAuthentication = AUTH_None;
239  m_bUseProxy = false;
240 
241  if (m_protocol == "https" || m_protocol == "webdavs")
242  m_iDefaultPort = DEFAULT_HTTPS_PORT;
243  else if (m_protocol == "ftp")
244  m_iDefaultPort = DEFAULT_FTP_PORT;
245  else
246  m_iDefaultPort = DEFAULT_HTTP_PORT;
247 }
248 
249 void HTTPProtocol::resetConnectionSettings()
250 {
251  m_bEOF = false;
252  m_bError = false;
253  m_lineCount = 0;
254  m_iWWWAuthCount = 0;
255  m_lineCountUnget = 0;
256  m_iProxyAuthCount = 0;
257 
258 }
259 
260 void HTTPProtocol::resetResponseSettings()
261 {
262  m_bRedirect = false;
263  m_redirectLocation = KURL();
264  m_bChunked = false;
265  m_iSize = NO_SIZE;
266 
267  m_responseHeader.clear();
268  m_qContentEncodings.clear();
269  m_qTransferEncodings.clear();
270  m_sContentMD5 = TQString::null;
271  m_strMimeType = TQString::null;
272 
273  setMetaData("request-id", m_request.id);
274 }
275 
276 void HTTPProtocol::resetSessionSettings()
277 {
278  // Do not reset the URL on redirection if the proxy
279  // URL, username or password has not changed!
280  KURL proxy ( config()->readEntry("UseProxy") );
281 
282  if ( m_strProxyRealm.isEmpty() || !proxy.isValid() ||
283  m_proxyURL.host() != proxy.host() ||
284  (!proxy.user().isNull() && proxy.user() != m_proxyURL.user()) ||
285  (!proxy.pass().isNull() && proxy.pass() != m_proxyURL.pass()) )
286  {
287  m_bProxyAuthValid = false;
288  m_proxyURL = proxy;
289  m_bUseProxy = m_proxyURL.isValid();
290 
291  kdDebug(7113) << "(" << m_pid << ") Using proxy: " << m_bUseProxy <<
292  " URL: " << m_proxyURL.url() <<
293  " Realm: " << m_strProxyRealm << endl;
294  }
295 
296  m_bPersistentProxyConnection = config()->readBoolEntry("PersistentProxyConnection", false);
297  kdDebug(7113) << "(" << m_pid << ") Enable Persistent Proxy Connection: "
298  << m_bPersistentProxyConnection << endl;
299 
300  m_request.bUseCookiejar = config()->readBoolEntry("Cookies");
301  m_request.bUseCache = config()->readBoolEntry("UseCache", true);
302  m_request.bErrorPage = config()->readBoolEntry("errorPage", true);
303  m_request.bNoAuth = config()->readBoolEntry("no-auth");
304  m_strCacheDir = config()->readPathEntry("CacheDir");
305  m_maxCacheAge = config()->readNumEntry("MaxCacheAge", DEFAULT_MAX_CACHE_AGE);
306  m_request.window = config()->readEntry("window-id");
307 
308  kdDebug(7113) << "(" << m_pid << ") Window Id = " << m_request.window << endl;
309  kdDebug(7113) << "(" << m_pid << ") ssl_was_in_use = "
310  << metaData ("ssl_was_in_use") << endl;
311 
312  m_request.referrer = TQString::null;
313  if ( config()->readBoolEntry("SendReferrer", true) &&
314  (m_protocol == "https" || m_protocol == "webdavs" ||
315  metaData ("ssl_was_in_use") != "TRUE" ) )
316  {
317  KURL referrerURL ( metaData("referrer") );
318  if (referrerURL.isValid())
319  {
320  // Sanitize
321  TQString protocol = referrerURL.protocol();
322  if (protocol.startsWith("webdav"))
323  {
324  protocol.replace(0, 6, "http");
325  referrerURL.setProtocol(protocol);
326  }
327 
328  if (protocol.startsWith("http"))
329  {
330  referrerURL.setRef(TQString::null);
331  referrerURL.setUser(TQString::null);
332  referrerURL.setPass(TQString::null);
333  m_request.referrer = referrerURL.url();
334  }
335  }
336  }
337 
338  if ( config()->readBoolEntry("SendLanguageSettings", true) )
339  {
340  m_request.charsets = config()->readEntry( "Charsets", "iso-8859-1" );
341 
342  if ( !m_request.charsets.isEmpty() )
343  m_request.charsets += DEFAULT_PARTIAL_CHARSET_HEADER;
344 
345  m_request.languages = config()->readEntry( "Languages", DEFAULT_LANGUAGE_HEADER );
346  }
347  else
348  {
349  m_request.charsets = TQString::null;
350  m_request.languages = TQString::null;
351  }
352 
353  // Adjust the offset value based on the "resume" meta-data.
354  TQString resumeOffset = metaData("resume");
355  if ( !resumeOffset.isEmpty() )
356  m_request.offset = resumeOffset.toInt(); // TODO: Convert to 64 bit
357  else
358  m_request.offset = 0;
359 
360  m_request.disablePassDlg = config()->readBoolEntry("DisablePassDlg", false);
361  m_request.allowCompressedPage = config()->readBoolEntry("AllowCompressedPage", true);
362  m_request.id = metaData("request-id");
363 
364  // Store user agent for this host.
365  if ( config()->readBoolEntry("SendUserAgent", true) )
366  m_request.userAgent = metaData("UserAgent");
367  else
368  m_request.userAgent = TQString::null;
369 
370  // Deal with cache cleaning.
371  // TODO: Find a smarter way to deal with cleaning the
372  // cache ?
373  if ( m_request.bUseCache )
374  cleanCache();
375 
376  // Deal with HTTP tunneling
377  if ( m_bIsSSL && m_bUseProxy && m_proxyURL.protocol() != "https" &&
378  m_proxyURL.protocol() != "webdavs")
379  {
380  m_bNeedTunnel = true;
381  setRealHost( m_request.hostname );
382  kdDebug(7113) << "(" << m_pid << ") SSL tunnel: Setting real hostname to: "
383  << m_request.hostname << endl;
384  }
385  else
386  {
387  m_bNeedTunnel = false;
388  setRealHost( TQString::null);
389  }
390 
391  m_responseCode = 0;
392  m_prevResponseCode = 0;
393 
394  m_strRealm = TQString::null;
395  m_strAuthorization = TQString::null;
396  Authentication = AUTH_None;
397 
398  // Obtain the proxy and remote server timeout values
399  m_proxyConnTimeout = proxyConnectTimeout();
400  m_remoteConnTimeout = connectTimeout();
401  m_remoteRespTimeout = responseTimeout();
402 
403  // Set the SSL meta-data here...
404  setSSLMetaData();
405 
406  // Bounce back the actual referrer sent
407  setMetaData("referrer", m_request.referrer);
408 
409  // Follow HTTP/1.1 spec and enable keep-alive by default
410  // unless the remote side tells us otherwise or we determine
411  // the persistent link has been terminated by the remote end.
412  m_bKeepAlive = true;
413  m_keepAliveTimeout = 0;
414  m_bUnauthorized = false;
415 
416  // A single request can require multiple exchanges with the remote
417  // server due to authentication challenges or SSL tunneling.
418  // m_bFirstRequest is a flag that indicates whether we are
419  // still processing the first request. This is important because we
420  // should not force a close of a keep-alive connection in the middle
421  // of the first request.
422  // m_bFirstRequest is set to "true" whenever a new connection is
423  // made in httpOpenConnection()
424  m_bFirstRequest = false;
425 }
426 
427 void HTTPProtocol::setHost( const TQString& host, int port,
428  const TQString& user, const TQString& pass )
429 {
430  // Reset the webdav-capable flags for this host
431  if ( m_request.hostname != host )
432  m_davHostOk = m_davHostUnsupported = false;
433 
434  // is it an IPv6 address?
435  if (host.find(':') == -1)
436  {
437  m_request.hostname = host;
438  m_request.encoded_hostname = KIDNA::toAscii(host);
439  }
440  else
441  {
442  m_request.hostname = host;
443  int pos = host.find('%');
444  if (pos == -1)
445  m_request.encoded_hostname = '[' + host + ']';
446  else
447  // don't send the scope-id in IPv6 addresses to the server
448  m_request.encoded_hostname = '[' + host.left(pos) + ']';
449  }
450  m_request.port = (port == 0) ? m_iDefaultPort : port;
451  m_request.user = user;
452  m_request.passwd = pass;
453 
454  m_bIsTunneled = false;
455 
456  kdDebug(7113) << "(" << m_pid << ") Hostname is now: " << m_request.hostname <<
457  " (" << m_request.encoded_hostname << ")" <<endl;
458 }
459 
460 bool HTTPProtocol::checkRequestURL( const KURL& u )
461 {
462  kdDebug (7113) << "(" << m_pid << ") HTTPProtocol::checkRequestURL: " << u.url() << endl;
463 
464  m_request.url = u;
465 
466  if (m_request.hostname.isEmpty())
467  {
468  error( TDEIO::ERR_UNKNOWN_HOST, i18n("No host specified."));
469  return false;
470  }
471 
472  if (u.path().isEmpty())
473  {
474  KURL newUrl(u);
475  newUrl.setPath("/");
476  redirection(newUrl);
477  finished();
478  return false;
479  }
480 
481  if ( m_protocol != u.protocol().latin1() )
482  {
483  short unsigned int oldDefaultPort = m_iDefaultPort;
484  m_protocol = u.protocol().latin1();
485  reparseConfiguration();
486  if ( m_iDefaultPort != oldDefaultPort &&
487  m_request.port == oldDefaultPort )
488  m_request.port = m_iDefaultPort;
489  }
490 
491  resetSessionSettings();
492  return true;
493 }
494 
495 void HTTPProtocol::retrieveContent( bool dataInternal /* = false */ )
496 {
497  kdDebug (7113) << "(" << m_pid << ") HTTPProtocol::retrieveContent " << endl;
498  if ( !retrieveHeader( false ) )
499  {
500  if ( m_bError )
501  return;
502  }
503  else
504  {
505  if ( !readBody( dataInternal ) && m_bError )
506  return;
507  }
508 
509  httpClose(m_bKeepAlive);
510 
511  // if data is required internally, don't finish,
512  // it is processed before we finish()
513  if ( !dataInternal )
514  {
515  if ((m_responseCode == 204) &&
516  ((m_request.method == HTTP_GET) || (m_request.method == HTTP_POST)))
517  error(ERR_NO_CONTENT, "");
518  else
519  finished();
520  }
521 }
522 
523 bool HTTPProtocol::retrieveHeader( bool close_connection )
524 {
525  kdDebug (7113) << "(" << m_pid << ") HTTPProtocol::retrieveHeader " << endl;
526  while ( 1 )
527  {
528  if (!httpOpen())
529  return false;
530 
531  resetResponseSettings();
532  if (!readHeader())
533  {
534  if ( m_bError )
535  return false;
536 
537  if (m_bIsTunneled)
538  {
539  kdDebug(7113) << "(" << m_pid << ") Re-establishing SSL tunnel..." << endl;
540  httpCloseConnection();
541  }
542  }
543  else
544  {
545  // Do not save authorization if the current response code is
546  // 4xx (client error) or 5xx (server error).
547  kdDebug(7113) << "(" << m_pid << ") Previous Response: "
548  << m_prevResponseCode << endl;
549  kdDebug(7113) << "(" << m_pid << ") Current Response: "
550  << m_responseCode << endl;
551 
552  if (isSSLTunnelEnabled() && m_bIsSSL && !m_bUnauthorized && !m_bError)
553  {
554  // If there is no error, disable tunneling
555  if ( m_responseCode < 400 )
556  {
557  kdDebug(7113) << "(" << m_pid << ") Unset tunneling flag!" << endl;
558  setEnableSSLTunnel( false );
559  m_bIsTunneled = true;
560  // Reset the CONNECT response code...
561  m_responseCode = m_prevResponseCode;
562  continue;
563  }
564  else
565  {
566  if ( !m_request.bErrorPage )
567  {
568  kdDebug(7113) << "(" << m_pid << ") Sending an error message!" << endl;
569  error( ERR_UNKNOWN_PROXY_HOST, m_proxyURL.host() );
570  return false;
571  }
572 
573  kdDebug(7113) << "(" << m_pid << ") Sending an error page!" << endl;
574  }
575  }
576 
577  if (m_responseCode < 400 && (m_prevResponseCode == 401 ||
578  m_prevResponseCode == 407))
579  saveAuthorization();
580  break;
581  }
582  }
583 
584  // Clear of the temporary POST buffer if it is not empty...
585  if (!m_bufPOST.isEmpty())
586  {
587  m_bufPOST.resize(0);
588  kdDebug(7113) << "(" << m_pid << ") HTTP::retreiveHeader: Cleared POST "
589  "buffer..." << endl;
590  }
591 
592  if ( close_connection )
593  {
594  httpClose(m_bKeepAlive);
595  finished();
596  }
597 
598  return true;
599 }
600 
601 void HTTPProtocol::stat(const KURL& url)
602 {
603  kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::stat " << url.prettyURL()
604  << endl;
605 
606  if ( !checkRequestURL( url ) )
607  return;
608 
609  if ( m_protocol != "webdav" && m_protocol != "webdavs" )
610  {
611  TQString statSide = metaData(TQString::fromLatin1("statSide"));
612  if ( statSide != "source" )
613  {
614  // When uploading we assume the file doesn't exit
615  error( ERR_DOES_NOT_EXIST, url.prettyURL() );
616  return;
617  }
618 
619  // When downloading we assume it exists
620  UDSEntry entry;
621  UDSAtom atom;
622  atom.m_uds = TDEIO::UDS_NAME;
623  atom.m_str = url.fileName();
624  entry.append( atom );
625 
626  atom.m_uds = TDEIO::UDS_FILE_TYPE;
627  atom.m_long = S_IFREG; // a file
628  entry.append( atom );
629 
630  atom.m_uds = TDEIO::UDS_ACCESS;
631  atom.m_long = S_IRUSR | S_IRGRP | S_IROTH; // readable by everybody
632  entry.append( atom );
633 
634  statEntry( entry );
635  finished();
636  return;
637  }
638 
639  davStatList( url );
640 }
641 
642 void HTTPProtocol::listDir( const KURL& url )
643 {
644  kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::listDir " << url.url()
645  << endl;
646 
647  if ( !checkRequestURL( url ) )
648  return;
649 
650  if (!url.protocol().startsWith("webdav")) {
651  error(ERR_UNSUPPORTED_ACTION, url.prettyURL());
652  return;
653  }
654 
655  davStatList( url, false );
656 }
657 
658 void HTTPProtocol::davSetRequest( const TQCString& requestXML )
659 {
660  // insert the document into the POST buffer, kill trailing zero byte
661  m_bufPOST = requestXML;
662 
663  if (m_bufPOST.size())
664  m_bufPOST.truncate( m_bufPOST.size() - 1 );
665 }
666 
667 void HTTPProtocol::davStatList( const KURL& url, bool stat )
668 {
669  UDSEntry entry;
670  UDSAtom atom;
671 
672  // check to make sure this host supports WebDAV
673  if ( !davHostOk() )
674  return;
675 
676  // Maybe it's a disguised SEARCH...
677  TQString query = metaData("davSearchQuery");
678  if ( !query.isEmpty() )
679  {
680  TQCString request = "<?xml version=\"1.0\"?>\r\n";
681  request.append( "<D:searchrequest xmlns:D=\"DAV:\">\r\n" );
682  request.append( query.utf8() );
683  request.append( "</D:searchrequest>\r\n" );
684 
685  davSetRequest( request );
686  } else {
687  // We are only after certain features...
688  TQCString request;
689  request = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>"
690  "<D:propfind xmlns:D=\"DAV:\">";
691 
692  // insert additional XML request from the davRequestResponse metadata
693  if ( hasMetaData( "davRequestResponse" ) )
694  request += metaData( "davRequestResponse" ).utf8();
695  else {
696  // No special request, ask for default properties
697  request += "<D:prop>"
698  "<D:creationdate/>"
699  "<D:getcontentlength/>"
700  "<D:displayname/>"
701  "<D:source/>"
702  "<D:getcontentlanguage/>"
703  "<D:getcontenttype/>"
704  "<D:executable/>"
705  "<D:getlastmodified/>"
706  "<D:getetag/>"
707  "<D:supportedlock/>"
708  "<D:lockdiscovery/>"
709  "<D:resourcetype/>"
710  "</D:prop>";
711  }
712  request += "</D:propfind>";
713 
714  davSetRequest( request );
715  }
716 
717  // WebDAV Stat or List...
718  m_request.method = query.isEmpty() ? DAV_PROPFIND : DAV_SEARCH;
719  m_request.query = TQString::null;
720  m_request.cache = CC_Reload;
721  m_request.doProxy = m_bUseProxy;
722  m_request.davData.depth = stat ? 0 : 1;
723  if (!stat)
724  m_request.url.adjustPath(+1);
725 
726  retrieveContent( true );
727 
728  // Has a redirection already been called? If so, we're done.
729  if (m_bRedirect) {
730  finished();
731  return;
732  }
733 
734  TQDomDocument multiResponse;
735  multiResponse.setContent( m_bufWebDavData, true );
736 
737  bool hasResponse = false;
738 
739  for ( TQDomNode n = multiResponse.documentElement().firstChild();
740  !n.isNull(); n = n.nextSibling())
741  {
742  TQDomElement thisResponse = n.toElement();
743  if (thisResponse.isNull())
744  continue;
745 
746  hasResponse = true;
747 
748  TQDomElement href = thisResponse.namedItem( "href" ).toElement();
749  if ( !href.isNull() )
750  {
751  entry.clear();
752 
753  TQString urlStr = href.text();
754 #if 0
755  int encoding = remoteEncoding()->encodingMib();
756  if ((encoding == 106) && (!KStringHandler::isUtf8(KURL::decode_string(urlStr, 4).latin1())))
757  encoding = 4; // Use latin1 if the file is not actually utf-8
758 #else
759  TQUrl::decode(urlStr);
760  int encoding = 106;
761 #endif
762 
763  KURL thisURL ( urlStr, encoding );
764 
765  atom.m_uds = TDEIO::UDS_NAME;
766 
767  if ( thisURL.isValid() ) {
768  // don't list the base dir of a listDir()
769  if ( !stat && thisURL.path(+1).length() == url.path(+1).length() )
770  continue;
771 
772  atom.m_str = thisURL.fileName();
773  } else {
774  // This is a relative URL.
775  atom.m_str = href.text();
776  }
777 
778  entry.append( atom );
779 
780  TQDomNodeList propstats = thisResponse.elementsByTagName( "propstat" );
781 
782  davParsePropstats( propstats, entry );
783 
784  if ( stat )
785  {
786  // return an item
787  statEntry( entry );
788  finished();
789  return;
790  }
791  else
792  {
793  listEntry( entry, false );
794  }
795  }
796  else
797  {
798  kdDebug(7113) << "Error: no URL contained in response to PROPFIND on "
799  << url.prettyURL() << endl;
800  }
801  }
802 
803  if ( stat || !hasResponse )
804  {
805  error( ERR_DOES_NOT_EXIST, url.prettyURL() );
806  }
807  else
808  {
809  listEntry( entry, true );
810  finished();
811  }
812 }
813 
814 void HTTPProtocol::davGeneric( const KURL& url, TDEIO::HTTP_METHOD method )
815 {
816  kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::davGeneric " << url.url()
817  << endl;
818 
819  if ( !checkRequestURL( url ) )
820  return;
821 
822  // check to make sure this host supports WebDAV
823  if ( !davHostOk() )
824  return;
825 
826  // WebDAV method
827  m_request.method = method;
828  m_request.query = TQString::null;
829  m_request.cache = CC_Reload;
830  m_request.doProxy = m_bUseProxy;
831 
832  retrieveContent( false );
833 }
834 
835 int HTTPProtocol::codeFromResponse( const TQString& response )
836 {
837  int firstSpace = response.find( ' ' );
838  int secondSpace = response.find( ' ', firstSpace + 1 );
839  return response.mid( firstSpace + 1, secondSpace - firstSpace - 1 ).toInt();
840 }
841 
842 void HTTPProtocol::davParsePropstats( const TQDomNodeList& propstats, UDSEntry& entry )
843 {
844  TQString mimeType;
845  UDSAtom atom;
846  bool foundExecutable = false;
847  bool isDirectory = false;
848  uint lockCount = 0;
849  uint supportedLockCount = 0;
850 
851  for ( uint i = 0; i < propstats.count(); i++)
852  {
853  TQDomElement propstat = propstats.item(i).toElement();
854 
855  TQDomElement status = propstat.namedItem( "status" ).toElement();
856  if ( status.isNull() )
857  {
858  // error, no status code in this propstat
859  kdDebug(7113) << "Error, no status code in this propstat" << endl;
860  return;
861  }
862 
863  int code = codeFromResponse( status.text() );
864 
865  if ( code != 200 )
866  {
867  kdDebug(7113) << "Warning: status code " << code << " (this may mean that some properties are unavailable" << endl;
868  continue;
869  }
870 
871  TQDomElement prop = propstat.namedItem( "prop" ).toElement();
872  if ( prop.isNull() )
873  {
874  kdDebug(7113) << "Error: no prop segment in this propstat." << endl;
875  return;
876  }
877 
878  if ( hasMetaData( "davRequestResponse" ) )
879  {
880  atom.m_uds = TDEIO::UDS_XML_PROPERTIES;
881  TQDomDocument doc;
882  doc.appendChild(prop);
883  atom.m_str = doc.toString();
884  entry.append( atom );
885  }
886 
887  for ( TQDomNode n = prop.firstChild(); !n.isNull(); n = n.nextSibling() )
888  {
889  TQDomElement property = n.toElement();
890  if (property.isNull())
891  continue;
892 
893  if ( property.namespaceURI() != "DAV:" )
894  {
895  // break out - we're only interested in properties from the DAV namespace
896  continue;
897  }
898 
899  if ( property.tagName() == "creationdate" )
900  {
901  // Resource creation date. Should be is ISO 8601 format.
902  atom.m_uds = TDEIO::UDS_CREATION_TIME;
903  atom.m_long = parseDateTime( property.text(), property.attribute("dt") );
904  entry.append( atom );
905  }
906  else if ( property.tagName() == "getcontentlength" )
907  {
908  // Content length (file size)
909  atom.m_uds = TDEIO::UDS_SIZE;
910  atom.m_long = property.text().toULong();
911  entry.append( atom );
912  }
913  else if ( property.tagName() == "displayname" )
914  {
915  // Name suitable for presentation to the user
916  setMetaData( "davDisplayName", property.text() );
917  }
918  else if ( property.tagName() == "source" )
919  {
920  // Source template location
921  TQDomElement source = property.namedItem( "link" ).toElement()
922  .namedItem( "dst" ).toElement();
923  if ( !source.isNull() )
924  setMetaData( "davSource", source.text() );
925  }
926  else if ( property.tagName() == "getcontentlanguage" )
927  {
928  // equiv. to Content-Language header on a GET
929  setMetaData( "davContentLanguage", property.text() );
930  }
931  else if ( property.tagName() == "getcontenttype" )
932  {
933  // Content type (mime type)
934  // This may require adjustments for other server-side webdav implementations
935  // (tested with Apache + mod_dav 1.0.3)
936  if ( property.text() == "httpd/unix-directory" )
937  {
938  isDirectory = true;
939  }
940  else
941  {
942  mimeType = property.text();
943  }
944  }
945  else if ( property.tagName() == "executable" )
946  {
947  // File executable status
948  if ( property.text() == "T" )
949  foundExecutable = true;
950 
951  }
952  else if ( property.tagName() == "getlastmodified" )
953  {
954  // Last modification date
955  atom.m_uds = TDEIO::UDS_MODIFICATION_TIME;
956  atom.m_long = parseDateTime( property.text(), property.attribute("dt") );
957  entry.append( atom );
958 
959  }
960  else if ( property.tagName() == "getetag" )
961  {
962  // Entity tag
963  setMetaData( "davEntityTag", property.text() );
964  }
965  else if ( property.tagName() == "supportedlock" )
966  {
967  // Supported locking specifications
968  for ( TQDomNode n2 = property.firstChild(); !n2.isNull(); n2 = n2.nextSibling() )
969  {
970  TQDomElement lockEntry = n2.toElement();
971  if ( lockEntry.tagName() == "lockentry" )
972  {
973  TQDomElement lockScope = lockEntry.namedItem( "lockscope" ).toElement();
974  TQDomElement lockType = lockEntry.namedItem( "locktype" ).toElement();
975  if ( !lockScope.isNull() && !lockType.isNull() )
976  {
977  // Lock type was properly specified
978  supportedLockCount++;
979  TQString scope = lockScope.firstChild().toElement().tagName();
980  TQString type = lockType.firstChild().toElement().tagName();
981 
982  setMetaData( TQString("davSupportedLockScope%1").arg(supportedLockCount), scope );
983  setMetaData( TQString("davSupportedLockType%1").arg(supportedLockCount), type );
984  }
985  }
986  }
987  }
988  else if ( property.tagName() == "lockdiscovery" )
989  {
990  // Lists the available locks
991  davParseActiveLocks( property.elementsByTagName( "activelock" ), lockCount );
992  }
993  else if ( property.tagName() == "resourcetype" )
994  {
995  // Resource type. "Specifies the nature of the resource."
996  if ( !property.namedItem( "collection" ).toElement().isNull() )
997  {
998  // This is a collection (directory)
999  isDirectory = true;
1000  }
1001  }
1002  else
1003  {
1004  kdDebug(7113) << "Found unknown webdav property: " << property.tagName() << endl;
1005  }
1006  }
1007  }
1008 
1009  setMetaData( "davLockCount", TQString("%1").arg(lockCount) );
1010  setMetaData( "davSupportedLockCount", TQString("%1").arg(supportedLockCount) );
1011 
1012  atom.m_uds = TDEIO::UDS_FILE_TYPE;
1013  atom.m_long = isDirectory ? S_IFDIR : S_IFREG;
1014  entry.append( atom );
1015 
1016  if ( foundExecutable || isDirectory )
1017  {
1018  // File was executable, or is a directory.
1019  atom.m_uds = TDEIO::UDS_ACCESS;
1020  atom.m_long = 0700;
1021  entry.append(atom);
1022  }
1023  else
1024  {
1025  atom.m_uds = TDEIO::UDS_ACCESS;
1026  atom.m_long = 0600;
1027  entry.append(atom);
1028  }
1029 
1030  if ( !isDirectory && !mimeType.isEmpty() )
1031  {
1032  atom.m_uds = TDEIO::UDS_MIME_TYPE;
1033  atom.m_str = mimeType;
1034  entry.append( atom );
1035  }
1036 }
1037 
1038 void HTTPProtocol::davParseActiveLocks( const TQDomNodeList& activeLocks,
1039  uint& lockCount )
1040 {
1041  for ( uint i = 0; i < activeLocks.count(); i++ )
1042  {
1043  TQDomElement activeLock = activeLocks.item(i).toElement();
1044 
1045  lockCount++;
1046  // required
1047  TQDomElement lockScope = activeLock.namedItem( "lockscope" ).toElement();
1048  TQDomElement lockType = activeLock.namedItem( "locktype" ).toElement();
1049  TQDomElement lockDepth = activeLock.namedItem( "depth" ).toElement();
1050  // optional
1051  TQDomElement lockOwner = activeLock.namedItem( "owner" ).toElement();
1052  TQDomElement lockTimeout = activeLock.namedItem( "timeout" ).toElement();
1053  TQDomElement lockToken = activeLock.namedItem( "locktoken" ).toElement();
1054 
1055  if ( !lockScope.isNull() && !lockType.isNull() && !lockDepth.isNull() )
1056  {
1057  // lock was properly specified
1058  lockCount++;
1059  TQString scope = lockScope.firstChild().toElement().tagName();
1060  TQString type = lockType.firstChild().toElement().tagName();
1061  TQString depth = lockDepth.text();
1062 
1063  setMetaData( TQString("davLockScope%1").arg( lockCount ), scope );
1064  setMetaData( TQString("davLockType%1").arg( lockCount ), type );
1065  setMetaData( TQString("davLockDepth%1").arg( lockCount ), depth );
1066 
1067  if ( !lockOwner.isNull() )
1068  setMetaData( TQString("davLockOwner%1").arg( lockCount ), lockOwner.text() );
1069 
1070  if ( !lockTimeout.isNull() )
1071  setMetaData( TQString("davLockTimeout%1").arg( lockCount ), lockTimeout.text() );
1072 
1073  if ( !lockToken.isNull() )
1074  {
1075  TQDomElement tokenVal = lockScope.namedItem( "href" ).toElement();
1076  if ( !tokenVal.isNull() )
1077  setMetaData( TQString("davLockToken%1").arg( lockCount ), tokenVal.text() );
1078  }
1079  }
1080  }
1081 }
1082 
1083 long HTTPProtocol::parseDateTime( const TQString& input, const TQString& type )
1084 {
1085  if ( type == "dateTime.tz" )
1086  {
1087  return KRFCDate::parseDateISO8601( input );
1088  }
1089  else if ( type == "dateTime.rfc1123" )
1090  {
1091  return KRFCDate::parseDate( input );
1092  }
1093 
1094  // format not advertised... try to parse anyway
1095  time_t time = KRFCDate::parseDate( input );
1096  if ( time != 0 )
1097  return time;
1098 
1099  return KRFCDate::parseDateISO8601( input );
1100 }
1101 
1102 TQString HTTPProtocol::davProcessLocks()
1103 {
1104  if ( hasMetaData( "davLockCount" ) )
1105  {
1106  TQString response("If:");
1107  int numLocks;
1108  numLocks = metaData( "davLockCount" ).toInt();
1109  bool bracketsOpen = false;
1110  for ( int i = 0; i < numLocks; i++ )
1111  {
1112  if ( hasMetaData( TQString("davLockToken%1").arg(i) ) )
1113  {
1114  if ( hasMetaData( TQString("davLockURL%1").arg(i) ) )
1115  {
1116  if ( bracketsOpen )
1117  {
1118  response += ")";
1119  bracketsOpen = false;
1120  }
1121  response += " <" + metaData( TQString("davLockURL%1").arg(i) ) + ">";
1122  }
1123 
1124  if ( !bracketsOpen )
1125  {
1126  response += " (";
1127  bracketsOpen = true;
1128  }
1129  else
1130  {
1131  response += " ";
1132  }
1133 
1134  if ( hasMetaData( TQString("davLockNot%1").arg(i) ) )
1135  response += "Not ";
1136 
1137  response += "<" + metaData( TQString("davLockToken%1").arg(i) ) + ">";
1138  }
1139  }
1140 
1141  if ( bracketsOpen )
1142  response += ")";
1143 
1144  response += "\r\n";
1145  return response;
1146  }
1147 
1148  return TQString::null;
1149 }
1150 
1151 bool HTTPProtocol::davHostOk()
1152 {
1153  // FIXME needs to be reworked. Switched off for now.
1154  return true;
1155 
1156  // cached?
1157  if ( m_davHostOk )
1158  {
1159  kdDebug(7113) << "(" << m_pid << ") " << k_funcinfo << " true" << endl;
1160  return true;
1161  }
1162  else if ( m_davHostUnsupported )
1163  {
1164  kdDebug(7113) << "(" << m_pid << ") " << k_funcinfo << " false" << endl;
1165  davError( -2 );
1166  return false;
1167  }
1168 
1169  m_request.method = HTTP_OPTIONS;
1170 
1171  // query the server's capabilities generally, not for a specific URL
1172  m_request.path = "*";
1173  m_request.query = TQString::null;
1174  m_request.cache = CC_Reload;
1175  m_request.doProxy = m_bUseProxy;
1176 
1177  // clear davVersions variable, which holds the response to the DAV: header
1178  m_davCapabilities.clear();
1179 
1180  retrieveHeader(false);
1181 
1182  if (m_davCapabilities.count())
1183  {
1184  for (uint i = 0; i < m_davCapabilities.count(); i++)
1185  {
1186  bool ok;
1187  uint verNo = m_davCapabilities[i].toUInt(&ok);
1188  if (ok && verNo > 0 && verNo < 3)
1189  {
1190  m_davHostOk = true;
1191  kdDebug(7113) << "Server supports DAV version " << verNo << "." << endl;
1192  }
1193  }
1194 
1195  if ( m_davHostOk )
1196  return true;
1197  }
1198 
1199  m_davHostUnsupported = true;
1200  davError( -2 );
1201  return false;
1202 }
1203 
1204 // This function is for closing retrieveHeader( false ); requests
1205 // Required because there may or may not be further info expected
1206 void HTTPProtocol::davFinished()
1207 {
1208  // TODO: Check with the DAV extension developers
1209  httpClose(m_bKeepAlive);
1210  finished();
1211 }
1212 
1213 void HTTPProtocol::mkdir( const KURL& url, int )
1214 {
1215  kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::mkdir " << url.url()
1216  << endl;
1217 
1218  if ( !checkRequestURL( url ) )
1219  return;
1220 
1221  m_request.method = DAV_MKCOL;
1222  m_request.path = url.path();
1223  m_request.query = TQString::null;
1224  m_request.cache = CC_Reload;
1225  m_request.doProxy = m_bUseProxy;
1226 
1227  retrieveHeader( false );
1228 
1229  if ( m_responseCode == 201 )
1230  davFinished();
1231  else
1232  davError();
1233 }
1234 
1235 void HTTPProtocol::get( const KURL& url )
1236 {
1237  kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::get " << url.url()
1238  << endl;
1239 
1240  if ( !checkRequestURL( url ) )
1241  return;
1242 
1243  m_request.method = HTTP_GET;
1244  m_request.path = url.path();
1245  m_request.query = url.query();
1246 
1247  TQString tmp = metaData("cache");
1248  if (!tmp.isEmpty())
1249  m_request.cache = parseCacheControl(tmp);
1250  else
1251  m_request.cache = DEFAULT_CACHE_CONTROL;
1252 
1253  m_request.passwd = url.pass();
1254  m_request.user = url.user();
1255  m_request.doProxy = m_bUseProxy;
1256 
1257  retrieveContent();
1258 }
1259 
1260 void HTTPProtocol::put( const KURL &url, int, bool overwrite, bool)
1261 {
1262  kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::put " << url.prettyURL()
1263  << endl;
1264 
1265  if ( !checkRequestURL( url ) )
1266  return;
1267 
1268  // Webdav hosts are capable of observing overwrite == false
1269  if (!overwrite && m_protocol.left(6) == "webdav") {
1270  // check to make sure this host supports WebDAV
1271  if ( !davHostOk() )
1272  return;
1273 
1274  TQCString request;
1275  request = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>"
1276  "<D:propfind xmlns:D=\"DAV:\"><D:prop>"
1277  "<D:creationdate/>"
1278  "<D:getcontentlength/>"
1279  "<D:displayname/>"
1280  "<D:resourcetype/>"
1281  "</D:prop></D:propfind>";
1282 
1283  davSetRequest( request );
1284 
1285  // WebDAV Stat or List...
1286  m_request.method = DAV_PROPFIND;
1287  m_request.query = TQString::null;
1288  m_request.cache = CC_Reload;
1289  m_request.doProxy = m_bUseProxy;
1290  m_request.davData.depth = 0;
1291 
1292  retrieveContent(true);
1293 
1294  if (m_responseCode == 207) {
1295  error(ERR_FILE_ALREADY_EXIST, TQString::null);
1296  return;
1297  }
1298 
1299  m_bError = false;
1300  }
1301 
1302  m_request.method = HTTP_PUT;
1303  m_request.path = url.path();
1304  m_request.query = TQString::null;
1305  m_request.cache = CC_Reload;
1306  m_request.doProxy = m_bUseProxy;
1307 
1308  retrieveHeader( false );
1309 
1310  kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::put error = " << m_bError << endl;
1311  if (m_bError)
1312  return;
1313 
1314  kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::put responseCode = " << m_responseCode << endl;
1315 
1316  httpClose(false); // Always close connection.
1317 
1318  if ( (m_responseCode >= 200) && (m_responseCode < 300) )
1319  finished();
1320  else
1321  httpError();
1322 }
1323 
1324 void HTTPProtocol::copy( const KURL& src, const KURL& dest, int, bool overwrite )
1325 {
1326  kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::copy " << src.prettyURL()
1327  << " -> " << dest.prettyURL() << endl;
1328 
1329  if ( !checkRequestURL( dest ) || !checkRequestURL( src ) )
1330  return;
1331 
1332  // destination has to be "http(s)://..."
1333  KURL newDest = dest;
1334  if (newDest.protocol() == "webdavs")
1335  newDest.setProtocol("https");
1336  else
1337  newDest.setProtocol("http");
1338 
1339  m_request.method = DAV_COPY;
1340  m_request.path = src.path();
1341  m_request.davData.desturl = newDest.url();
1342  m_request.davData.overwrite = overwrite;
1343  m_request.query = TQString::null;
1344  m_request.cache = CC_Reload;
1345  m_request.doProxy = m_bUseProxy;
1346 
1347  retrieveHeader( false );
1348 
1349  // The server returns a HTTP/1.1 201 Created or 204 No Content on successful completion
1350  if ( m_responseCode == 201 || m_responseCode == 204 )
1351  davFinished();
1352  else
1353  davError();
1354 }
1355 
1356 void HTTPProtocol::rename( const KURL& src, const KURL& dest, bool overwrite )
1357 {
1358  kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::rename " << src.prettyURL()
1359  << " -> " << dest.prettyURL() << endl;
1360 
1361  if ( !checkRequestURL( dest ) || !checkRequestURL( src ) )
1362  return;
1363 
1364  // destination has to be "http://..."
1365  KURL newDest = dest;
1366  if (newDest.protocol() == "webdavs")
1367  newDest.setProtocol("https");
1368  else
1369  newDest.setProtocol("http");
1370 
1371  m_request.method = DAV_MOVE;
1372  m_request.path = src.path();
1373  m_request.davData.desturl = newDest.url();
1374  m_request.davData.overwrite = overwrite;
1375  m_request.query = TQString::null;
1376  m_request.cache = CC_Reload;
1377  m_request.doProxy = m_bUseProxy;
1378 
1379  retrieveHeader( false );
1380 
1381  if ( m_responseCode == 301 )
1382  {
1383  // Work around strict Apache-2 WebDAV implementation which refuses to cooperate
1384  // with webdav://host/directory, instead requiring webdav://host/directory/
1385  // (strangely enough it accepts Destination: without a trailing slash)
1386 
1387  if (m_redirectLocation.protocol() == "https")
1388  m_redirectLocation.setProtocol("webdavs");
1389  else
1390  m_redirectLocation.setProtocol("webdav");
1391 
1392  if ( !checkRequestURL( m_redirectLocation ) )
1393  return;
1394 
1395  m_request.method = DAV_MOVE;
1396  m_request.path = m_redirectLocation.path();
1397  m_request.davData.desturl = newDest.url();
1398  m_request.davData.overwrite = overwrite;
1399  m_request.query = TQString::null;
1400  m_request.cache = CC_Reload;
1401  m_request.doProxy = m_bUseProxy;
1402 
1403  retrieveHeader( false );
1404  }
1405 
1406  if ( m_responseCode == 201 )
1407  davFinished();
1408  else
1409  davError();
1410 }
1411 
1412 void HTTPProtocol::del( const KURL& url, bool )
1413 {
1414  kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::del " << url.prettyURL()
1415  << endl;
1416 
1417  if ( !checkRequestURL( url ) )
1418  return;
1419 
1420  m_request.method = HTTP_DELETE;
1421  m_request.path = url.path();
1422  m_request.query = TQString::null;
1423  m_request.cache = CC_Reload;
1424  m_request.doProxy = m_bUseProxy;
1425 
1426  retrieveHeader( false );
1427 
1428  // The server returns a HTTP/1.1 200 Ok or HTTP/1.1 204 No Content
1429  // on successful completion
1430  if ( m_responseCode == 200 || m_responseCode == 204 )
1431  davFinished();
1432  else
1433  davError();
1434 }
1435 
1436 void HTTPProtocol::post( const KURL& url )
1437 {
1438  kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::post "
1439  << url.prettyURL() << endl;
1440 
1441  if ( !checkRequestURL( url ) )
1442  return;
1443 
1444  m_request.method = HTTP_POST;
1445  m_request.path = url.path();
1446  m_request.query = url.query();
1447  m_request.cache = CC_Reload;
1448  m_request.doProxy = m_bUseProxy;
1449 
1450  retrieveContent();
1451 }
1452 
1453 void HTTPProtocol::davLock( const KURL& url, const TQString& scope,
1454  const TQString& type, const TQString& owner )
1455 {
1456  kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::davLock "
1457  << url.prettyURL() << endl;
1458 
1459  if ( !checkRequestURL( url ) )
1460  return;
1461 
1462  m_request.method = DAV_LOCK;
1463  m_request.path = url.path();
1464  m_request.query = TQString::null;
1465  m_request.cache = CC_Reload;
1466  m_request.doProxy = m_bUseProxy;
1467 
1468  /* Create appropriate lock XML request. */
1469  TQDomDocument lockReq;
1470 
1471  TQDomElement lockInfo = lockReq.createElementNS( "DAV:", "lockinfo" );
1472  lockReq.appendChild( lockInfo );
1473 
1474  TQDomElement lockScope = lockReq.createElement( "lockscope" );
1475  lockInfo.appendChild( lockScope );
1476 
1477  lockScope.appendChild( lockReq.createElement( scope ) );
1478 
1479  TQDomElement lockType = lockReq.createElement( "locktype" );
1480  lockInfo.appendChild( lockType );
1481 
1482  lockType.appendChild( lockReq.createElement( type ) );
1483 
1484  if ( !owner.isNull() ) {
1485  TQDomElement ownerElement = lockReq.createElement( "owner" );
1486  lockReq.appendChild( ownerElement );
1487 
1488  TQDomElement ownerHref = lockReq.createElement( "href" );
1489  ownerElement.appendChild( ownerHref );
1490 
1491  ownerHref.appendChild( lockReq.createTextNode( owner ) );
1492  }
1493 
1494  // insert the document into the POST buffer
1495  m_bufPOST = lockReq.toCString();
1496 
1497  retrieveContent( true );
1498 
1499  if ( m_responseCode == 200 ) {
1500  // success
1501  TQDomDocument multiResponse;
1502  multiResponse.setContent( m_bufWebDavData, true );
1503 
1504  TQDomElement prop = multiResponse.documentElement().namedItem( "prop" ).toElement();
1505 
1506  TQDomElement lockdiscovery = prop.namedItem( "lockdiscovery" ).toElement();
1507 
1508  uint lockCount = 0;
1509  davParseActiveLocks( lockdiscovery.elementsByTagName( "activelock" ), lockCount );
1510 
1511  setMetaData( "davLockCount", TQString("%1").arg( lockCount ) );
1512 
1513  finished();
1514 
1515  } else
1516  davError();
1517 }
1518 
1519 void HTTPProtocol::davUnlock( const KURL& url )
1520 {
1521  kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::davUnlock "
1522  << url.prettyURL() << endl;
1523 
1524  if ( !checkRequestURL( url ) )
1525  return;
1526 
1527  m_request.method = DAV_UNLOCK;
1528  m_request.path = url.path();
1529  m_request.query = TQString::null;
1530  m_request.cache = CC_Reload;
1531  m_request.doProxy = m_bUseProxy;
1532 
1533  retrieveContent( true );
1534 
1535  if ( m_responseCode == 200 )
1536  finished();
1537  else
1538  davError();
1539 }
1540 
1541 TQString HTTPProtocol::davError( int code /* = -1 */, TQString url )
1542 {
1543  bool callError = false;
1544  if ( code == -1 ) {
1545  code = m_responseCode;
1546  callError = true;
1547  }
1548  if ( code == -2 ) {
1549  callError = true;
1550  }
1551 
1552  if ( !url.isNull() )
1553  url = m_request.url.url();
1554 
1555  TQString action, errorString;
1556  TDEIO::Error kError;
1557 
1558  // for 412 Precondition Failed
1559  TQString ow = i18n( "Otherwise, the request would have succeeded." );
1560 
1561  switch ( m_request.method ) {
1562  case DAV_PROPFIND:
1563  action = i18n( "retrieve property values" );
1564  break;
1565  case DAV_PROPPATCH:
1566  action = i18n( "set property values" );
1567  break;
1568  case DAV_MKCOL:
1569  action = i18n( "create the requested folder" );
1570  break;
1571  case DAV_COPY:
1572  action = i18n( "copy the specified file or folder" );
1573  break;
1574  case DAV_MOVE:
1575  action = i18n( "move the specified file or folder" );
1576  break;
1577  case DAV_SEARCH:
1578  action = i18n( "search in the specified folder" );
1579  break;
1580  case DAV_LOCK:
1581  action = i18n( "lock the specified file or folder" );
1582  break;
1583  case DAV_UNLOCK:
1584  action = i18n( "unlock the specified file or folder" );
1585  break;
1586  case HTTP_DELETE:
1587  action = i18n( "delete the specified file or folder" );
1588  break;
1589  case HTTP_OPTIONS:
1590  action = i18n( "query the server's capabilities" );
1591  break;
1592  case HTTP_GET:
1593  action = i18n( "retrieve the contents of the specified file or folder" );
1594  break;
1595  case HTTP_PUT:
1596  case HTTP_POST:
1597  case HTTP_HEAD:
1598  default:
1599  // this should not happen, this function is for webdav errors only
1600  Q_ASSERT(0);
1601  }
1602 
1603  // default error message if the following code fails
1604  kError = ERR_INTERNAL;
1605  errorString = i18n("An unexpected error (%1) occurred while attempting to %2.")
1606  .arg( code ).arg( action );
1607 
1608  switch ( code )
1609  {
1610  case -2:
1611  // internal error: OPTIONS request did not specify DAV compliance
1612  kError = ERR_UNSUPPORTED_PROTOCOL;
1613  errorString = i18n("The server does not support the WebDAV protocol.");
1614  break;
1615  case 207:
1616  // 207 Multi-status
1617  {
1618  // our error info is in the returned XML document.
1619  // retrieve the XML document
1620 
1621  // there was an error retrieving the XML document.
1622  // ironic, eh?
1623  if ( !readBody( true ) && m_bError )
1624  return TQString::null;
1625 
1626  TQStringList errors;
1627  TQDomDocument multiResponse;
1628 
1629  multiResponse.setContent( m_bufWebDavData, true );
1630 
1631  TQDomElement multistatus = multiResponse.documentElement().namedItem( "multistatus" ).toElement();
1632 
1633  TQDomNodeList responses = multistatus.elementsByTagName( "response" );
1634 
1635  for (uint i = 0; i < responses.count(); i++)
1636  {
1637  int errCode;
1638  TQString errUrl;
1639 
1640  TQDomElement response = responses.item(i).toElement();
1641  TQDomElement code = response.namedItem( "status" ).toElement();
1642 
1643  if ( !code.isNull() )
1644  {
1645  errCode = codeFromResponse( code.text() );
1646  TQDomElement href = response.namedItem( "href" ).toElement();
1647  if ( !href.isNull() )
1648  errUrl = href.text();
1649  errors << davError( errCode, errUrl );
1650  }
1651  }
1652 
1653  //kError = ERR_SLAVE_DEFINED;
1654  errorString = i18n("An error occurred while attempting to %1, %2. A "
1655  "summary of the reasons is below.<ul>").arg( action ).arg( url );
1656 
1657  for ( TQStringList::Iterator it = errors.begin(); it != errors.end(); ++it )
1658  errorString += "<li>" + *it + "</li>";
1659 
1660  errorString += "</ul>";
1661  }
1662  case 403:
1663  case 500: // hack: Apache mod_dav returns this instead of 403 (!)
1664  // 403 Forbidden
1665  kError = ERR_ACCESS_DENIED;
1666  errorString = i18n("Access was denied while attempting to %1.").arg( action );
1667  break;
1668  case 405:
1669  // 405 Method Not Allowed
1670  if ( m_request.method == DAV_MKCOL )
1671  {
1672  kError = ERR_DIR_ALREADY_EXIST;
1673  errorString = i18n("The specified folder already exists.");
1674  }
1675  break;
1676  case 409:
1677  // 409 Conflict
1678  kError = ERR_ACCESS_DENIED;
1679  errorString = i18n("A resource cannot be created at the destination "
1680  "until one or more intermediate collections (folders) "
1681  "have been created.");
1682  break;
1683  case 412:
1684  // 412 Precondition failed
1685  if ( m_request.method == DAV_COPY || m_request.method == DAV_MOVE )
1686  {
1687  kError = ERR_ACCESS_DENIED;
1688  errorString = i18n("The server was unable to maintain the liveness of "
1689  "the properties listed in the propertybehavior XML "
1690  "element or you attempted to overwrite a file while "
1691  "requesting that files are not overwritten. %1")
1692  .arg( ow );
1693 
1694  }
1695  else if ( m_request.method == DAV_LOCK )
1696  {
1697  kError = ERR_ACCESS_DENIED;
1698  errorString = i18n("The requested lock could not be granted. %1").arg( ow );
1699  }
1700  break;
1701  case 415:
1702  // 415 Unsupported Media Type
1703  kError = ERR_ACCESS_DENIED;
1704  errorString = i18n("The server does not support the request type of the body.");
1705  break;
1706  case 423:
1707  // 423 Locked
1708  kError = ERR_ACCESS_DENIED;
1709  errorString = i18n("Unable to %1 because the resource is locked.").arg( action );
1710  break;
1711  case 425:
1712  // 424 Failed Dependency
1713  errorString = i18n("This action was prevented by another error.");
1714  break;
1715  case 502:
1716  // 502 Bad Gateway
1717  if ( m_request.method == DAV_COPY || m_request.method == DAV_MOVE )
1718  {
1719  kError = ERR_WRITE_ACCESS_DENIED;
1720  errorString = i18n("Unable to %1 because the destination server refuses "
1721  "to accept the file or folder.").arg( action );
1722  }
1723  break;
1724  case 507:
1725  // 507 Insufficient Storage
1726  kError = ERR_DISK_FULL;
1727  errorString = i18n("The destination resource does not have sufficient space "
1728  "to record the state of the resource after the execution "
1729  "of this method.");
1730  break;
1731  }
1732 
1733  // if ( kError != ERR_SLAVE_DEFINED )
1734  //errorString += " (" + url + ")";
1735 
1736  if ( callError )
1737  error( ERR_SLAVE_DEFINED, errorString );
1738 
1739  return errorString;
1740 }
1741 
1742 void HTTPProtocol::httpError()
1743 {
1744  TQString action, errorString;
1745  TDEIO::Error kError;
1746 
1747  switch ( m_request.method ) {
1748  case HTTP_PUT:
1749  action = i18n( "upload %1" ).arg(m_request.url.prettyURL());
1750  break;
1751  default:
1752  // this should not happen, this function is for http errors only
1753  Q_ASSERT(0);
1754  }
1755 
1756  // default error message if the following code fails
1757  kError = ERR_INTERNAL;
1758  errorString = i18n("An unexpected error (%1) occurred while attempting to %2.")
1759  .arg( m_responseCode ).arg( action );
1760 
1761  switch ( m_responseCode )
1762  {
1763  case 403:
1764  case 405:
1765  case 500: // hack: Apache mod_dav returns this instead of 403 (!)
1766  // 403 Forbidden
1767  // 405 Method Not Allowed
1768  kError = ERR_ACCESS_DENIED;
1769  errorString = i18n("Access was denied while attempting to %1.").arg( action );
1770  break;
1771  case 409:
1772  // 409 Conflict
1773  kError = ERR_ACCESS_DENIED;
1774  errorString = i18n("A resource cannot be created at the destination "
1775  "until one or more intermediate collections (folders) "
1776  "have been created.");
1777  break;
1778  case 423:
1779  // 423 Locked
1780  kError = ERR_ACCESS_DENIED;
1781  errorString = i18n("Unable to %1 because the resource is locked.").arg( action );
1782  break;
1783  case 502:
1784  // 502 Bad Gateway
1785  kError = ERR_WRITE_ACCESS_DENIED;
1786  errorString = i18n("Unable to %1 because the destination server refuses "
1787  "to accept the file or folder.").arg( action );
1788  break;
1789  case 507:
1790  // 507 Insufficient Storage
1791  kError = ERR_DISK_FULL;
1792  errorString = i18n("The destination resource does not have sufficient space "
1793  "to record the state of the resource after the execution "
1794  "of this method.");
1795  break;
1796  }
1797 
1798  // if ( kError != ERR_SLAVE_DEFINED )
1799  //errorString += " (" + url + ")";
1800 
1801  error( ERR_SLAVE_DEFINED, errorString );
1802 }
1803 
1804 bool HTTPProtocol::isOffline(const KURL &url)
1805 {
1806  const int NetWorkStatusUnknown = 1;
1807  const int NetWorkStatusOnline = 8;
1808  TQCString replyType;
1809  TQByteArray params;
1810  TQByteArray reply;
1811 
1812  TQDataStream stream(params, IO_WriteOnly);
1813 
1814  if ( url.host() == TQString::fromLatin1("localhost") || url.host() == TQString::fromLatin1("127.0.0.1") || url.host() == TQString::fromLatin1("::") ) {
1815  return false;
1816  }
1817  if ( dcopClient()->call( "kded", "networkstatus", "status()",
1818  params, replyType, reply ) && (replyType == "int") )
1819  {
1820  int result;
1821  TQDataStream stream2( reply, IO_ReadOnly );
1822  stream2 >> result;
1823  kdDebug(7113) << "(" << m_pid << ") networkstatus status = " << result << endl;
1824  return (result != NetWorkStatusUnknown) && (result != NetWorkStatusOnline);
1825  }
1826  kdDebug(7113) << "(" << m_pid << ") networkstatus <unreachable>" << endl;
1827  return false; // On error, assume we are online
1828 }
1829 
1830 void HTTPProtocol::multiGet(const TQByteArray &data)
1831 {
1832  TQDataStream stream(data, IO_ReadOnly);
1833  TQ_UINT32 n;
1834  stream >> n;
1835 
1836  kdDebug(7113) << "(" << m_pid << ") HTTPProtcool::multiGet n = " << n << endl;
1837 
1838  HTTPRequest saveRequest;
1839  if (m_bBusy)
1840  saveRequest = m_request;
1841 
1842 // m_requestQueue.clear();
1843  for(unsigned i = 0; i < n; i++)
1844  {
1845  KURL url;
1846  stream >> url >> mIncomingMetaData;
1847 
1848  if ( !checkRequestURL( url ) )
1849  continue;
1850 
1851  kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::multi_get " << url.url() << endl;
1852 
1853  m_request.method = HTTP_GET;
1854  m_request.path = url.path();
1855  m_request.query = url.query();
1856  TQString tmp = metaData("cache");
1857  if (!tmp.isEmpty())
1858  m_request.cache = parseCacheControl(tmp);
1859  else
1860  m_request.cache = DEFAULT_CACHE_CONTROL;
1861 
1862  m_request.passwd = url.pass();
1863  m_request.user = url.user();
1864  m_request.doProxy = m_bUseProxy;
1865 
1866  HTTPRequest *newRequest = new HTTPRequest(m_request);
1867  m_requestQueue.append(newRequest);
1868  }
1869 
1870  if (m_bBusy)
1871  m_request = saveRequest;
1872 
1873  if (!m_bBusy)
1874  {
1875  m_bBusy = true;
1876  while(!m_requestQueue.isEmpty())
1877  {
1878  HTTPRequest *request = m_requestQueue.take(0);
1879  m_request = *request;
1880  delete request;
1881  retrieveContent();
1882  }
1883  m_bBusy = false;
1884  }
1885 }
1886 
1887 ssize_t HTTPProtocol::write (const void *_buf, size_t nbytes)
1888 {
1889  int bytes_sent = 0;
1890  const char* buf = static_cast<const char*>(_buf);
1891  while ( nbytes > 0 )
1892  {
1893  int n = TCPSlaveBase::write(buf, nbytes);
1894 
1895  if ( n <= 0 )
1896  {
1897  // remote side closed connection ?
1898  if ( n == 0 )
1899  break;
1900  // a valid exception(s) occurred, let's retry...
1901  if (n < 0 && ((errno == EINTR) || (errno == EAGAIN)))
1902  continue;
1903  // some other error occurred ?
1904  return -1;
1905  }
1906 
1907  nbytes -= n;
1908  buf += n;
1909  bytes_sent += n;
1910  }
1911 
1912  return bytes_sent;
1913 }
1914 
1915 void HTTPProtocol::setRewindMarker()
1916 {
1917  m_rewindCount = 0;
1918 }
1919 
1920 void HTTPProtocol::rewind()
1921 {
1922  m_linePtrUnget = m_rewindBuf,
1923  m_lineCountUnget = m_rewindCount;
1924  m_rewindCount = 0;
1925 }
1926 
1927 
1928 char *HTTPProtocol::gets (char *s, int size)
1929 {
1930  int len=0;
1931  char *buf=s;
1932  char mybuf[2]={0,0};
1933 
1934  while (len < size)
1935  {
1936  read(mybuf, 1);
1937  if (m_bEOF)
1938  break;
1939 
1940  if (m_rewindCount < sizeof(m_rewindBuf))
1941  m_rewindBuf[m_rewindCount++] = *mybuf;
1942 
1943  if (*mybuf == '\r') // Ignore!
1944  continue;
1945 
1946  if ((*mybuf == '\n') || !*mybuf)
1947  break;
1948 
1949  *buf++ = *mybuf;
1950  len++;
1951  }
1952 
1953  *buf=0;
1954  return s;
1955 }
1956 
1957 ssize_t HTTPProtocol::read (void *b, size_t nbytes)
1958 {
1959  ssize_t ret = 0;
1960 
1961  if (m_lineCountUnget > 0)
1962  {
1963  ret = ( nbytes < m_lineCountUnget ? nbytes : m_lineCountUnget );
1964  m_lineCountUnget -= ret;
1965  memcpy(b, m_linePtrUnget, ret);
1966  m_linePtrUnget += ret;
1967 
1968  return ret;
1969  }
1970 
1971  if (m_lineCount > 0)
1972  {
1973  ret = ( nbytes < m_lineCount ? nbytes : m_lineCount );
1974  m_lineCount -= ret;
1975  memcpy(b, m_linePtr, ret);
1976  m_linePtr += ret;
1977  return ret;
1978  }
1979 
1980  if (nbytes == 1)
1981  {
1982  ret = read(m_lineBuf, 1024); // Read into buffer
1983  m_linePtr = m_lineBuf;
1984  if (ret <= 0)
1985  {
1986  m_lineCount = 0;
1987  return ret;
1988  }
1989  m_lineCount = ret;
1990  return read(b, 1); // Read from buffer
1991  }
1992 
1993  do
1994  {
1995  ret = TCPSlaveBase::read( b, nbytes);
1996  if (ret == 0)
1997  m_bEOF = true;
1998 
1999  } while ((ret == -1) && (errno == EAGAIN || errno == EINTR));
2000 
2001  return ret;
2002 }
2003 
2004 void HTTPProtocol::httpCheckConnection()
2005 {
2006  kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::httpCheckConnection: " <<
2007  " Socket status: " << m_iSock <<
2008  " Keep Alive: " << m_bKeepAlive <<
2009  " First: " << m_bFirstRequest << endl;
2010 
2011  if ( !m_bFirstRequest && (m_iSock != -1) )
2012  {
2013  bool closeDown = false;
2014  if ( !isConnectionValid())
2015  {
2016  kdDebug(7113) << "(" << m_pid << ") Connection lost!" << endl;
2017  closeDown = true;
2018  }
2019  else if ( m_request.method != HTTP_GET )
2020  {
2021  closeDown = true;
2022  }
2023  else if ( !m_state.doProxy && !m_request.doProxy )
2024  {
2025  if (m_state.hostname != m_request.hostname ||
2026  m_state.port != m_request.port ||
2027  m_state.user != m_request.user ||
2028  m_state.passwd != m_request.passwd)
2029  closeDown = true;
2030  }
2031  else
2032  {
2033  // Keep the connection to the proxy.
2034  if ( !(m_request.doProxy && m_state.doProxy) )
2035  closeDown = true;
2036  }
2037 
2038  if (closeDown)
2039  httpCloseConnection();
2040  }
2041 
2042  // Let's update our current state
2043  m_state.hostname = m_request.hostname;
2044  m_state.encoded_hostname = m_request.encoded_hostname;
2045  m_state.port = m_request.port;
2046  m_state.user = m_request.user;
2047  m_state.passwd = m_request.passwd;
2048  m_state.doProxy = m_request.doProxy;
2049 }
2050 
2051 bool HTTPProtocol::httpOpenConnection()
2052 {
2053  int errCode;
2054  TQString errMsg;
2055 
2056  kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::httpOpenConnection" << endl;
2057 
2058  setBlockConnection( true );
2059  // tdeio_http uses its own proxying:
2060  KSocks::self()->disableSocks();
2061 
2062  if ( m_state.doProxy )
2063  {
2064  TQString proxy_host = m_proxyURL.host();
2065  int proxy_port = m_proxyURL.port();
2066 
2067  kdDebug(7113) << "(" << m_pid << ") Connecting to proxy server: "
2068  << proxy_host << ", port: " << proxy_port << endl;
2069 
2070  infoMessage( i18n("Connecting to %1...").arg(m_state.hostname) );
2071 
2072  setConnectTimeout( m_proxyConnTimeout );
2073 
2074  if ( !connectToHost(proxy_host, proxy_port, false) )
2075  {
2076  if (userAborted()) {
2077  error(ERR_NO_CONTENT, "");
2078  return false;
2079  }
2080 
2081  switch ( connectResult() )
2082  {
2083  case IO_LookupError:
2084  errMsg = proxy_host;
2085  errCode = ERR_UNKNOWN_PROXY_HOST;
2086  break;
2087  case IO_TimeOutError:
2088  errMsg = i18n("Proxy %1 at port %2").arg(proxy_host).arg(proxy_port);
2089  errCode = ERR_SERVER_TIMEOUT;
2090  break;
2091  default:
2092  errMsg = i18n("Proxy %1 at port %2").arg(proxy_host).arg(proxy_port);
2093  errCode = ERR_COULD_NOT_CONNECT;
2094  }
2095  error( errCode, errMsg );
2096  return false;
2097  }
2098  }
2099  else
2100  {
2101  // Apparently we don't want a proxy. let's just connect directly
2102  setConnectTimeout(m_remoteConnTimeout);
2103 
2104  if ( !connectToHost(m_state.hostname, m_state.port, false ) )
2105  {
2106  if (userAborted()) {
2107  error(ERR_NO_CONTENT, "");
2108  return false;
2109  }
2110 
2111  switch ( connectResult() )
2112  {
2113  case IO_LookupError:
2114  errMsg = m_state.hostname;
2115  errCode = ERR_UNKNOWN_HOST;
2116  break;
2117  case IO_TimeOutError:
2118  errMsg = i18n("Connection was to %1 at port %2").arg(m_state.hostname).arg(m_state.port);
2119  errCode = ERR_SERVER_TIMEOUT;
2120  break;
2121  default:
2122  errCode = ERR_COULD_NOT_CONNECT;
2123  if (m_state.port != m_iDefaultPort)
2124  errMsg = i18n("%1 (port %2)").arg(m_state.hostname).arg(m_state.port);
2125  else
2126  errMsg = m_state.hostname;
2127  }
2128  error( errCode, errMsg );
2129  return false;
2130  }
2131  }
2132 
2133  // Set our special socket option!!
2134  int on = 1;
2135  (void) setsockopt( m_iSock, IPPROTO_TCP, TCP_NODELAY, (char*)&on, sizeof(on) );
2136 
2137  m_bFirstRequest = true;
2138 
2139  connected();
2140  return true;
2141 }
2142 
2143 
2166 bool HTTPProtocol::httpOpen()
2167 {
2168  kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::httpOpen" << endl;
2169 
2170  // Cannot have an https request without the m_bIsSSL being set! This can
2171  // only happen if TCPSlaveBase::InitializeSSL() function failed in which it
2172  // means the current installation does not support SSL...
2173  if ( (m_protocol == "https" || m_protocol == "webdavs") && !m_bIsSSL )
2174  {
2175  error( ERR_UNSUPPORTED_PROTOCOL, m_protocol );
2176  return false;
2177  }
2178 
2179  m_request.fcache = 0;
2180  m_request.bCachedRead = false;
2181  m_request.bCachedWrite = false;
2182  m_request.bMustRevalidate = false;
2183  m_request.expireDate = 0;
2184  m_request.creationDate = 0;
2185 
2186  if (m_request.bUseCache)
2187  {
2188  m_request.fcache = checkCacheEntry( );
2189 
2190  bool bCacheOnly = (m_request.cache == TDEIO::CC_CacheOnly);
2191  bool bOffline = isOffline(m_request.doProxy ? m_proxyURL : m_request.url);
2192  if (bOffline && (m_request.cache != TDEIO::CC_Reload))
2193  m_request.cache = TDEIO::CC_CacheOnly;
2194 
2195  if (m_request.cache == CC_Reload && m_request.fcache)
2196  {
2197  if (m_request.fcache)
2198  fclose(m_request.fcache);
2199  m_request.fcache = 0;
2200  }
2201  if ((m_request.cache == TDEIO::CC_CacheOnly) || (m_request.cache == TDEIO::CC_Cache))
2202  m_request.bMustRevalidate = false;
2203 
2204  m_request.bCachedWrite = true;
2205 
2206  if (m_request.fcache && !m_request.bMustRevalidate)
2207  {
2208  // Cache entry is OK.
2209  m_request.bCachedRead = true; // Cache hit.
2210  return true;
2211  }
2212  else if (!m_request.fcache)
2213  {
2214  m_request.bMustRevalidate = false; // Cache miss
2215  }
2216  else
2217  {
2218  // Conditional cache hit. (Validate)
2219  }
2220 
2221  if (bCacheOnly && bOffline)
2222  {
2223  error( ERR_OFFLINE_MODE, m_request.url.url() );
2224  return false;
2225  }
2226  if (bCacheOnly)
2227  {
2228  error( ERR_DOES_NOT_EXIST, m_request.url.url() );
2229  return false;
2230  }
2231  if (bOffline)
2232  {
2233  error( ERR_OFFLINE_MODE, m_request.url.url() );
2234  return false;
2235  }
2236  }
2237 
2238  TQString header;
2239  TQString davHeader;
2240 
2241  bool moreData = false;
2242  bool davData = false;
2243 
2244  // Clear out per-connection settings...
2245  resetConnectionSettings ();
2246 
2247  // Check the validity of the current connection, if one exists.
2248  httpCheckConnection();
2249 
2250  if ( !m_bIsTunneled && m_bNeedTunnel )
2251  {
2252  setEnableSSLTunnel( true );
2253  // We send a HTTP 1.0 header since some proxies refuse HTTP 1.1 and we don't
2254  // need any HTTP 1.1 capabilities for CONNECT - Waba
2255  header = TQString("CONNECT %1:%2 HTTP/1.0"
2256  "\r\n").arg( m_request.encoded_hostname).arg(m_request.port);
2257 
2258  // Identify who you are to the proxy server!
2259  if (!m_request.userAgent.isEmpty())
2260  header += "User-Agent: " + m_request.userAgent + "\r\n";
2261 
2262  /* Add hostname information */
2263  header += "Host: " + m_state.encoded_hostname;
2264 
2265  if (m_state.port != m_iDefaultPort)
2266  header += TQString(":%1").arg(m_state.port);
2267  header += "\r\n";
2268 
2269  header += proxyAuthenticationHeader();
2270  }
2271  else
2272  {
2273  // Determine if this is a POST or GET method
2274  switch (m_request.method)
2275  {
2276  case HTTP_GET:
2277  header = "GET ";
2278  break;
2279  case HTTP_PUT:
2280  header = "PUT ";
2281  moreData = true;
2282  m_request.bCachedWrite = false; // Do not put any result in the cache
2283  break;
2284  case HTTP_POST:
2285  header = "POST ";
2286  moreData = true;
2287  m_request.bCachedWrite = false; // Do not put any result in the cache
2288  break;
2289  case HTTP_HEAD:
2290  header = "HEAD ";
2291  break;
2292  case HTTP_DELETE:
2293  header = "DELETE ";
2294  m_request.bCachedWrite = false; // Do not put any result in the cache
2295  break;
2296  case HTTP_OPTIONS:
2297  header = "OPTIONS ";
2298  m_request.bCachedWrite = false; // Do not put any result in the cache
2299  break;
2300  case DAV_PROPFIND:
2301  header = "PROPFIND ";
2302  davData = true;
2303  davHeader = "Depth: ";
2304  if ( hasMetaData( "davDepth" ) )
2305  {
2306  kdDebug(7113) << "Reading DAV depth from metadata: " << metaData( "davDepth" ) << endl;
2307  davHeader += metaData( "davDepth" );
2308  }
2309  else
2310  {
2311  if ( m_request.davData.depth == 2 )
2312  davHeader += "infinity";
2313  else
2314  davHeader += TQString("%1").arg( m_request.davData.depth );
2315  }
2316  davHeader += "\r\n";
2317  m_request.bCachedWrite = false; // Do not put any result in the cache
2318  break;
2319  case DAV_PROPPATCH:
2320  header = "PROPPATCH ";
2321  davData = true;
2322  m_request.bCachedWrite = false; // Do not put any result in the cache
2323  break;
2324  case DAV_MKCOL:
2325  header = "MKCOL ";
2326  m_request.bCachedWrite = false; // Do not put any result in the cache
2327  break;
2328  case DAV_COPY:
2329  case DAV_MOVE:
2330  header = ( m_request.method == DAV_COPY ) ? "COPY " : "MOVE ";
2331  davHeader = "Destination: " + m_request.davData.desturl;
2332  // infinity depth means copy recursively
2333  // (optional for copy -> but is the desired action)
2334  davHeader += "\r\nDepth: infinity\r\nOverwrite: ";
2335  davHeader += m_request.davData.overwrite ? "T" : "F";
2336  davHeader += "\r\n";
2337  m_request.bCachedWrite = false; // Do not put any result in the cache
2338  break;
2339  case DAV_LOCK:
2340  header = "LOCK ";
2341  davHeader = "Timeout: ";
2342  {
2343  uint timeout = 0;
2344  if ( hasMetaData( "davTimeout" ) )
2345  timeout = metaData( "davTimeout" ).toUInt();
2346  if ( timeout == 0 )
2347  davHeader += "Infinite";
2348  else
2349  davHeader += TQString("Seconds-%1").arg(timeout);
2350  }
2351  davHeader += "\r\n";
2352  m_request.bCachedWrite = false; // Do not put any result in the cache
2353  davData = true;
2354  break;
2355  case DAV_UNLOCK:
2356  header = "UNLOCK ";
2357  davHeader = "Lock-token: " + metaData("davLockToken") + "\r\n";
2358  m_request.bCachedWrite = false; // Do not put any result in the cache
2359  break;
2360  case DAV_SEARCH:
2361  header = "SEARCH ";
2362  davData = true;
2363  m_request.bCachedWrite = false;
2364  break;
2365  case DAV_SUBSCRIBE:
2366  header = "SUBSCRIBE ";
2367  m_request.bCachedWrite = false;
2368  break;
2369  case DAV_UNSUBSCRIBE:
2370  header = "UNSUBSCRIBE ";
2371  m_request.bCachedWrite = false;
2372  break;
2373  case DAV_POLL:
2374  header = "POLL ";
2375  m_request.bCachedWrite = false;
2376  break;
2377  default:
2378  error (ERR_UNSUPPORTED_ACTION, TQString::null);
2379  return false;
2380  }
2381  // DAV_POLL; DAV_NOTIFY
2382 
2383  // format the URI
2384  if (m_state.doProxy && !m_bIsTunneled)
2385  {
2386  KURL u;
2387 
2388  if (m_protocol == "webdav")
2389  u.setProtocol( "http" );
2390  else if (m_protocol == "webdavs" )
2391  u.setProtocol( "https" );
2392  else
2393  u.setProtocol( m_protocol );
2394 
2395  // For all protocols other than the once handled by this io-slave
2396  // append the username. This fixes a long standing bug of ftp io-slave
2397  // logging in anonymously in proxied connections even when the username
2398  // is explicitly specified.
2399  if (m_protocol != "http" && m_protocol != "https" &&
2400  !m_state.user.isEmpty())
2401  u.setUser (m_state.user);
2402 
2403  u.setHost( m_state.hostname );
2404  if (m_state.port != m_iDefaultPort)
2405  u.setPort( m_state.port );
2406  u.setEncodedPathAndQuery( m_request.url.encodedPathAndQuery(0,true) );
2407  header += u.url();
2408  }
2409  else
2410  {
2411  header += m_request.url.encodedPathAndQuery(0, true);
2412  }
2413 
2414  header += " HTTP/1.1\r\n"; /* start header */
2415 
2416  if (!m_request.userAgent.isEmpty())
2417  {
2418  header += "User-Agent: ";
2419  header += m_request.userAgent;
2420  header += "\r\n";
2421  }
2422 
2423  if (!m_request.referrer.isEmpty())
2424  {
2425  header += "Referer: "; //Don't try to correct spelling!
2426  header += m_request.referrer;
2427  header += "\r\n";
2428  }
2429 
2430  if ( m_request.offset > 0 )
2431  {
2432  header += TQString("Range: bytes=%1-\r\n").arg(TDEIO::number(m_request.offset));
2433  kdDebug(7103) << "tdeio_http : Range = " << TDEIO::number(m_request.offset) << endl;
2434  }
2435 
2436  if ( m_request.cache == CC_Reload )
2437  {
2438  /* No caching for reload */
2439  header += "Pragma: no-cache\r\n"; /* for HTTP/1.0 caches */
2440  header += "Cache-control: no-cache\r\n"; /* for HTTP >=1.1 caches */
2441  }
2442 
2443  if (m_request.bMustRevalidate)
2444  {
2445  /* conditional get */
2446  if (!m_request.etag.isEmpty())
2447  header += "If-None-Match: "+m_request.etag+"\r\n";
2448  if (!m_request.lastModified.isEmpty())
2449  header += "If-Modified-Since: "+m_request.lastModified+"\r\n";
2450  }
2451 
2452  header += "Accept: ";
2453  TQString acceptHeader = metaData("accept");
2454  if (!acceptHeader.isEmpty())
2455  header += acceptHeader;
2456  else
2457  header += DEFAULT_ACCEPT_HEADER;
2458  header += "\r\n";
2459 
2460 #ifdef DO_GZIP
2461  if (m_request.allowCompressedPage)
2462  header += "Accept-Encoding: x-gzip, x-deflate, gzip, deflate\r\n";
2463 #endif
2464 
2465  if (!m_request.charsets.isEmpty())
2466  header += "Accept-Charset: " + m_request.charsets + "\r\n";
2467 
2468  if (!m_request.languages.isEmpty())
2469  header += "Accept-Language: " + m_request.languages + "\r\n";
2470 
2471 
2472  /* support for virtual hosts and required by HTTP 1.1 */
2473  header += "Host: " + m_state.encoded_hostname;
2474 
2475  if (m_state.port != m_iDefaultPort)
2476  header += TQString(":%1").arg(m_state.port);
2477  header += "\r\n";
2478 
2479  TQString cookieStr;
2480  TQString cookieMode = metaData("cookies").lower();
2481  if (cookieMode == "none")
2482  {
2483  m_request.cookieMode = HTTPRequest::CookiesNone;
2484  }
2485  else if (cookieMode == "manual")
2486  {
2487  m_request.cookieMode = HTTPRequest::CookiesManual;
2488  cookieStr = metaData("setcookies");
2489  }
2490  else
2491  {
2492  m_request.cookieMode = HTTPRequest::CookiesAuto;
2493  if (m_request.bUseCookiejar)
2494  cookieStr = findCookies( m_request.url.url());
2495  }
2496 
2497  if (!cookieStr.isEmpty())
2498  header += cookieStr + "\r\n";
2499 
2500  TQString customHeader = metaData( "customHTTPHeader" );
2501  if (!customHeader.isEmpty())
2502  {
2503  header += sanitizeCustomHTTPHeader(customHeader);
2504  header += "\r\n";
2505  }
2506 
2507  if (m_request.method == HTTP_POST)
2508  {
2509  header += metaData("content-type");
2510  header += "\r\n";
2511  }
2512 
2513  // Only check for a cached copy if the previous
2514  // response was NOT a 401 or 407.
2515  // no caching for Negotiate auth.
2516  if ( !m_request.bNoAuth && m_responseCode != 401 && m_responseCode != 407 && Authentication != AUTH_Negotiate )
2517  {
2518  kdDebug(7113) << "(" << m_pid << ") Calling checkCachedAuthentication " << endl;
2519  AuthInfo info;
2520  info.url = m_request.url;
2521  info.verifyPath = true;
2522  if ( !m_request.user.isEmpty() )
2523  info.username = m_request.user;
2524  if ( checkCachedAuthentication( info ) && !info.digestInfo.isEmpty() )
2525  {
2526  Authentication = info.digestInfo.startsWith("Basic") ? AUTH_Basic : info.digestInfo.startsWith("NTLM") ? AUTH_NTLM : info.digestInfo.startsWith("Negotiate") ? AUTH_Negotiate : AUTH_Digest ;
2527  m_state.user = info.username;
2528  m_state.passwd = info.password;
2529  m_strRealm = info.realmValue;
2530  if ( Authentication != AUTH_NTLM && Authentication != AUTH_Negotiate ) // don't use the cached challenge
2531  m_strAuthorization = info.digestInfo;
2532  }
2533  }
2534  else
2535  {
2536  kdDebug(7113) << "(" << m_pid << ") Not calling checkCachedAuthentication " << endl;
2537  }
2538 
2539  switch ( Authentication )
2540  {
2541  case AUTH_Basic:
2542  header += createBasicAuth();
2543  break;
2544  case AUTH_Digest:
2545  header += createDigestAuth();
2546  break;
2547 #ifdef HAVE_LIBGSSAPI
2548  case AUTH_Negotiate:
2549  header += createNegotiateAuth();
2550  break;
2551 #endif
2552  case AUTH_NTLM:
2553  header += createNTLMAuth();
2554  break;
2555  case AUTH_None:
2556  default:
2557  break;
2558  }
2559 
2560  /********* Only for debugging purpose *********/
2561  if ( Authentication != AUTH_None )
2562  {
2563  kdDebug(7113) << "(" << m_pid << ") Using Authentication: " << endl;
2564  kdDebug(7113) << "(" << m_pid << ") HOST= " << m_state.hostname << endl;
2565  kdDebug(7113) << "(" << m_pid << ") PORT= " << m_state.port << endl;
2566  kdDebug(7113) << "(" << m_pid << ") USER= " << m_state.user << endl;
2567  kdDebug(7113) << "(" << m_pid << ") PASSWORD= [protected]" << endl;
2568  kdDebug(7113) << "(" << m_pid << ") REALM= " << m_strRealm << endl;
2569  kdDebug(7113) << "(" << m_pid << ") EXTRA= " << m_strAuthorization << endl;
2570  }
2571 
2572  // Do we need to authorize to the proxy server ?
2573  if ( m_state.doProxy && !m_bIsTunneled )
2574  header += proxyAuthenticationHeader();
2575 
2576  // Support old HTTP/1.0 style keep-alive header for compatability
2577  // purposes as well as performance improvements while giving end
2578  // users the ability to disable this feature proxy servers that
2579  // don't not support such feature, e.g. junkbuster proxy server.
2580  if (!m_bUseProxy || m_bPersistentProxyConnection || m_bIsTunneled)
2581  header += "Connection: Keep-Alive\r\n";
2582  else
2583  header += "Connection: close\r\n";
2584 
2585  if ( m_protocol == "webdav" || m_protocol == "webdavs" )
2586  {
2587  header += davProcessLocks();
2588 
2589  // add extra webdav headers, if supplied
2590  TQString davExtraHeader = metaData("davHeader");
2591  if ( !davExtraHeader.isEmpty() )
2592  davHeader += davExtraHeader;
2593 
2594  // Set content type of webdav data
2595  if (davData)
2596  davHeader += "Content-Type: text/xml; charset=utf-8\r\n";
2597 
2598  // add extra header elements for WebDAV
2599  if ( !davHeader.isNull() )
2600  header += davHeader;
2601  }
2602  }
2603 
2604  kdDebug(7103) << "(" << m_pid << ") ============ Sending Header:" << endl;
2605 
2606  TQStringList headerOutput = TQStringList::split("\r\n", header);
2607  TQStringList::Iterator it = headerOutput.begin();
2608 
2609  for (; it != headerOutput.end(); it++)
2610  kdDebug(7103) << "(" << m_pid << ") " << (*it) << endl;
2611 
2612  if ( !moreData && !davData)
2613  header += "\r\n"; /* end header */
2614 
2615  // Now that we have our formatted header, let's send it!
2616  // Create a new connection to the remote machine if we do
2617  // not already have one...
2618  if ( m_iSock == -1)
2619  {
2620  if (!httpOpenConnection())
2621  return false;
2622  }
2623 
2624  // Send the data to the remote machine...
2625  bool sendOk = (write(header.latin1(), header.length()) == (ssize_t) header.length());
2626  if (!sendOk)
2627  {
2628  kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::httpOpen: "
2629  "Connection broken! (" << m_state.hostname << ")" << endl;
2630 
2631  // With a Keep-Alive connection this can happen.
2632  // Just reestablish the connection.
2633  if (m_bKeepAlive)
2634  {
2635  httpCloseConnection();
2636  return true; // Try again
2637  }
2638 
2639  if (!sendOk)
2640  {
2641  kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::httpOpen: sendOk==false."
2642  " Connnection broken !" << endl;
2643  error( ERR_CONNECTION_BROKEN, m_state.hostname );
2644  return false;
2645  }
2646  }
2647 
2648  bool res = true;
2649 
2650  if ( moreData || davData )
2651  res = sendBody();
2652 
2653  infoMessage(i18n("%1 contacted. Waiting for reply...").arg(m_request.hostname));
2654 
2655  return res;
2656 }
2657 
2658 void HTTPProtocol::forwardHttpResponseHeader()
2659 {
2660  // Send the response header if it was requested
2661  if ( config()->readBoolEntry("PropagateHttpHeader", false) )
2662  {
2663  setMetaData("HTTP-Headers", m_responseHeader.join("\n"));
2664  sendMetaData();
2665  }
2666  m_responseHeader.clear();
2667 }
2668 
2675 bool HTTPProtocol::readHeader()
2676 {
2677 try_again:
2678  kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::readHeader" << endl;
2679 
2680  // Check
2681  if (m_request.bCachedRead)
2682  {
2683  m_responseHeader << "HTTP-CACHE";
2684  // Read header from cache...
2685  char buffer[4097];
2686  if (!fgets(buffer, 4096, m_request.fcache) )
2687  {
2688  // Error, delete cache entry
2689  kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::readHeader: "
2690  << "Could not access cache to obtain mimetype!" << endl;
2691  error( ERR_CONNECTION_BROKEN, m_state.hostname );
2692  return false;
2693  }
2694 
2695  m_strMimeType = TQString(TQString::fromUtf8( buffer)).stripWhiteSpace();
2696 
2697  kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::readHeader: cached "
2698  << "data mimetype: " << m_strMimeType << endl;
2699 
2700  if (!fgets(buffer, 4096, m_request.fcache) )
2701  {
2702  // Error, delete cache entry
2703  kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::readHeader: "
2704  << "Could not access cached data! " << endl;
2705  error( ERR_CONNECTION_BROKEN, m_state.hostname );
2706  return false;
2707  }
2708 
2709  m_request.strCharset = TQString(TQString::fromUtf8( buffer)).stripWhiteSpace().lower();
2710  setMetaData("charset", m_request.strCharset);
2711  if (!m_request.lastModified.isEmpty())
2712  setMetaData("modified", m_request.lastModified);
2713  TQString tmp;
2714  tmp.setNum(m_request.expireDate);
2715  setMetaData("expire-date", tmp);
2716  tmp.setNum(m_request.creationDate);
2717  setMetaData("cache-creation-date", tmp);
2718  mimeType(m_strMimeType);
2719  forwardHttpResponseHeader();
2720  return true;
2721  }
2722 
2723  TQCString locationStr; // In case we get a redirect.
2724  TQCString cookieStr; // In case we get a cookie.
2725 
2726  TQString dispositionType; // In case we get a Content-Disposition type
2727  TQString dispositionFilename; // In case we get a Content-Disposition filename
2728 
2729  TQString mediaValue;
2730  TQString mediaAttribute;
2731 
2732  TQStringList upgradeOffers;
2733 
2734  bool upgradeRequired = false; // Server demands that we upgrade to something
2735  // This is also true if we ask to upgrade and
2736  // the server accepts, since we are now
2737  // committed to doing so
2738  bool canUpgrade = false; // The server offered an upgrade
2739 
2740 
2741  m_request.etag = TQString::null;
2742  m_request.lastModified = TQString::null;
2743  m_request.strCharset = TQString::null;
2744 
2745  time_t dateHeader = 0;
2746  time_t expireDate = 0; // 0 = no info, 1 = already expired, > 1 = actual date
2747  int currentAge = 0;
2748  int maxAge = -1; // -1 = no max age, 0 already expired, > 0 = actual time
2749  int maxHeaderSize = 64*1024; // 64Kb to catch DOS-attacks
2750 
2751  // read in 8192 bytes at a time (HTTP cookies can be quite large.)
2752  int len = 0;
2753  char buffer[8193];
2754  bool cont = false;
2755  bool cacheValidated = false; // Revalidation was successful
2756  bool mayCache = true;
2757  bool hasCacheDirective = false;
2758  bool bCanResume = false;
2759 
2760  if (m_iSock == -1)
2761  {
2762  kdDebug(7113) << "HTTPProtocol::readHeader: No connection." << endl;
2763  return false; // Restablish connection and try again
2764  }
2765 
2766  if (!waitForResponse(m_remoteRespTimeout))
2767  {
2768  // No response error
2769  error( ERR_SERVER_TIMEOUT , m_state.hostname );
2770  return false;
2771  }
2772 
2773  setRewindMarker();
2774 
2775  gets(buffer, sizeof(buffer)-1);
2776 
2777  if (m_bEOF || *buffer == '\0')
2778  {
2779  kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::readHeader: "
2780  << "EOF while waiting for header start." << endl;
2781  if (m_bKeepAlive) // Try to reestablish connection.
2782  {
2783  httpCloseConnection();
2784  return false; // Reestablish connection and try again.
2785  }
2786 
2787  if (m_request.method == HTTP_HEAD)
2788  {
2789  // HACK
2790  // Some web-servers fail to respond properly to a HEAD request.
2791  // We compensate for their failure to properly implement the HTTP standard
2792  // by assuming that they will be sending html.
2793  kdDebug(7113) << "(" << m_pid << ") HTTPPreadHeader: HEAD -> returned "
2794  << "mimetype: " << DEFAULT_MIME_TYPE << endl;
2795  mimeType(TQString::fromLatin1(DEFAULT_MIME_TYPE));
2796  return true;
2797  }
2798 
2799  kdDebug(7113) << "HTTPProtocol::readHeader: Connection broken !" << endl;
2800  error( ERR_CONNECTION_BROKEN, m_state.hostname );
2801  return false;
2802  }
2803 
2804  kdDebug(7103) << "(" << m_pid << ") ============ Received Response:"<< endl;
2805 
2806  bool noHeader = true;
2807  HTTP_REV httpRev = HTTP_None;
2808  int headerSize = 0;
2809 
2810  do
2811  {
2812  // strip off \r and \n if we have them
2813  len = strlen(buffer);
2814 
2815  while(len && (buffer[len-1] == '\n' || buffer[len-1] == '\r'))
2816  buffer[--len] = 0;
2817 
2818  // if there was only a newline then continue
2819  if (!len)
2820  {
2821  kdDebug(7103) << "(" << m_pid << ") --empty--" << endl;
2822  continue;
2823  }
2824 
2825  headerSize += len;
2826 
2827  // We have a response header. This flag is a work around for
2828  // servers that append a "\r\n" before the beginning of the HEADER
2829  // response!!! It only catches x number of \r\n being placed at the
2830  // top of the reponse...
2831  noHeader = false;
2832 
2833  kdDebug(7103) << "(" << m_pid << ") \"" << buffer << "\"" << endl;
2834 
2835  // Save broken servers from damnation!!
2836  char* buf = buffer;
2837  while( *buf == ' ' )
2838  buf++;
2839 
2840 
2841  if (buf[0] == '<')
2842  {
2843  // We get XML / HTTP without a proper header
2844  // put string back
2845  kdDebug(7103) << "tdeio_http: No valid HTTP header found! Document starts with XML/HTML tag" << endl;
2846 
2847  // Document starts with a tag, assume html instead of text/plain
2848  m_strMimeType = "text/html";
2849 
2850  rewind();
2851  break;
2852  }
2853 
2854  // Store the the headers so they can be passed to the
2855  // calling application later
2856  m_responseHeader << TQString::fromLatin1(buf);
2857 
2858  if ((strncasecmp(buf, "HTTP/", 5) == 0) ||
2859  (strncasecmp(buf, "ICY ", 4) == 0)) // Shoutcast support
2860  {
2861  if (strncasecmp(buf, "ICY ", 4) == 0)
2862  {
2863  // Shoutcast support
2864  httpRev = SHOUTCAST;
2865  m_bKeepAlive = false;
2866  }
2867  else if (strncmp((buf + 5), "1.0",3) == 0)
2868  {
2869  httpRev = HTTP_10;
2870  // For 1.0 servers, the server itself has to explicitly
2871  // tell us whether it supports persistent connection or
2872  // not. By default, we assume it does not, but we do
2873  // send the old style header "Connection: Keep-Alive" to
2874  // inform it that we support persistence.
2875  m_bKeepAlive = false;
2876  }
2877  else if (strncmp((buf + 5), "1.1",3) == 0)
2878  {
2879  httpRev = HTTP_11;
2880  }
2881  else
2882  {
2883  httpRev = HTTP_Unknown;
2884  }
2885 
2886  if (m_responseCode)
2887  m_prevResponseCode = m_responseCode;
2888 
2889  const char* rptr = buf;
2890  while ( *rptr && *rptr > ' ' )
2891  ++rptr;
2892  m_responseCode = atoi(rptr);
2893 
2894  // server side errors
2895  if (m_responseCode >= 500 && m_responseCode <= 599)
2896  {
2897  if (m_request.method == HTTP_HEAD)
2898  {
2899  ; // Ignore error
2900  }
2901  else
2902  {
2903  if (m_request.bErrorPage)
2904  errorPage();
2905  else
2906  {
2907  error(ERR_INTERNAL_SERVER, m_request.url.url());
2908  return false;
2909  }
2910  }
2911  m_request.bCachedWrite = false; // Don't put in cache
2912  mayCache = false;
2913  }
2914  // Unauthorized access
2915  else if (m_responseCode == 401 || m_responseCode == 407)
2916  {
2917  // Double authorization requests, i.e. a proxy auth
2918  // request followed immediately by a regular auth request.
2919  if ( m_prevResponseCode != m_responseCode &&
2920  (m_prevResponseCode == 401 || m_prevResponseCode == 407) )
2921  saveAuthorization();
2922 
2923  m_bUnauthorized = true;
2924  m_request.bCachedWrite = false; // Don't put in cache
2925  mayCache = false;
2926  }
2927  //
2928  else if (m_responseCode == 416) // Range not supported
2929  {
2930  m_request.offset = 0;
2931  httpCloseConnection();
2932  return false; // Try again.
2933  }
2934  // Upgrade Required
2935  else if (m_responseCode == 426)
2936  {
2937  upgradeRequired = true;
2938  }
2939  // Any other client errors
2940  else if (m_responseCode >= 400 && m_responseCode <= 499)
2941  {
2942  // Tell that we will only get an error page here.
2943  if (m_request.bErrorPage)
2944  errorPage();
2945  else
2946  {
2947  error(ERR_DOES_NOT_EXIST, m_request.url.url());
2948  return false;
2949  }
2950  m_request.bCachedWrite = false; // Don't put in cache
2951  mayCache = false;
2952  }
2953  else if (m_responseCode == 307)
2954  {
2955  // 307 Temporary Redirect
2956  m_request.bCachedWrite = false; // Don't put in cache
2957  mayCache = false;
2958  }
2959  else if (m_responseCode == 304)
2960  {
2961  // 304 Not Modified
2962  // The value in our cache is still valid.
2963  cacheValidated = true;
2964  }
2965  else if (m_responseCode >= 301 && m_responseCode<= 303)
2966  {
2967  // 301 Moved permanently
2968  if (m_responseCode == 301)
2969  setMetaData("permanent-redirect", "true");
2970 
2971  // 302 Found (temporary location)
2972  // 303 See Other
2973  if (m_request.method != HTTP_HEAD && m_request.method != HTTP_GET)
2974  {
2975 #if 0
2976  // Reset the POST buffer to avoid a double submit
2977  // on redirection
2978  if (m_request.method == HTTP_POST)
2979  m_bufPOST.resize(0);
2980 #endif
2981 
2982  // NOTE: This is wrong according to RFC 2616. However,
2983  // because most other existing user agent implementations
2984  // treat a 301/302 response as a 303 response and preform
2985  // a GET action regardless of what the previous method was,
2986  // many servers have simply adapted to this way of doing
2987  // things!! Thus, we are forced to do the same thing or we
2988  // won't be able to retrieve these pages correctly!! See RFC
2989  // 2616 sections 10.3.[2/3/4/8]
2990  m_request.method = HTTP_GET; // Force a GET
2991  }
2992  m_request.bCachedWrite = false; // Don't put in cache
2993  mayCache = false;
2994  }
2995  else if ( m_responseCode == 207 ) // Multi-status (for WebDav)
2996  {
2997 
2998  }
2999  else if ( m_responseCode == 204 ) // No content
3000  {
3001  // error(ERR_NO_CONTENT, i18n("Data have been successfully sent."));
3002  // Short circuit and do nothing!
3003 
3004  // The original handling here was wrong, this is not an error: eg. in the
3005  // example of a 204 No Content response to a PUT completing.
3006  // m_bError = true;
3007  // return false;
3008  }
3009  else if ( m_responseCode == 206 )
3010  {
3011  if ( m_request.offset )
3012  bCanResume = true;
3013  }
3014  else if (m_responseCode == 102) // Processing (for WebDAV)
3015  {
3016  /***
3017  * This status code is given when the server expects the
3018  * command to take significant time to complete. So, inform
3019  * the user.
3020  */
3021  infoMessage( i18n( "Server processing request, please wait..." ) );
3022  cont = true;
3023  }
3024  else if (m_responseCode == 100)
3025  {
3026  // We got 'Continue' - ignore it
3027  cont = true;
3028  }
3029  }
3030 
3031  // are we allowd to resume? this will tell us
3032  else if (strncasecmp(buf, "Accept-Ranges:", 14) == 0) {
3033  if (strncasecmp(trimLead(buf + 14), "none", 4) == 0)
3034  bCanResume = false;
3035  }
3036  // Keep Alive
3037  else if (strncasecmp(buf, "Keep-Alive:", 11) == 0) {
3038  TQStringList options = TQStringList::split(',',
3039  TQString::fromLatin1(trimLead(buf+11)));
3040  for(TQStringList::ConstIterator it = options.begin();
3041  it != options.end();
3042  it++)
3043  {
3044  TQString option = (*it).stripWhiteSpace().lower();
3045  if (option.startsWith("timeout="))
3046  {
3047  m_keepAliveTimeout = option.mid(8).toInt();
3048  }
3049  }
3050  }
3051 
3052  // Cache control
3053  else if (strncasecmp(buf, "Cache-Control:", 14) == 0) {
3054  TQStringList cacheControls = TQStringList::split(',',
3055  TQString::fromLatin1(trimLead(buf+14)));
3056  for(TQStringList::ConstIterator it = cacheControls.begin();
3057  it != cacheControls.end();
3058  it++)
3059  {
3060  TQString cacheControl = (*it).stripWhiteSpace();
3061  if (strncasecmp(cacheControl.latin1(), "no-cache", 8) == 0)
3062  {
3063  m_request.bCachedWrite = false; // Don't put in cache
3064  mayCache = false;
3065  }
3066  else if (strncasecmp(cacheControl.latin1(), "no-store", 8) == 0)
3067  {
3068  m_request.bCachedWrite = false; // Don't put in cache
3069  mayCache = false;
3070  }
3071  else if (strncasecmp(cacheControl.latin1(), "max-age=", 8) == 0)
3072  {
3073  TQString age = cacheControl.mid(8).stripWhiteSpace();
3074  if (!age.isNull())
3075  maxAge = STRTOLL(age.latin1(), 0, 10);
3076  }
3077  }
3078  hasCacheDirective = true;
3079  }
3080 
3081  // get the size of our data
3082  else if (strncasecmp(buf, "Content-length:", 15) == 0) {
3083  char* len = trimLead(buf + 15);
3084  if (len)
3085  m_iSize = STRTOLL(len, 0, 10);
3086  }
3087 
3088  else if (strncasecmp(buf, "Content-location:", 17) == 0) {
3089  setMetaData ("content-location",
3090  TQString::fromLatin1(trimLead(buf+17)).stripWhiteSpace());
3091  }
3092 
3093  // what type of data do we have?
3094  else if (strncasecmp(buf, "Content-type:", 13) == 0) {
3095  char *start = trimLead(buf + 13);
3096  char *pos = start;
3097 
3098  // Increment until we encounter ";" or the end of the buffer
3099  while ( *pos && *pos != ';' ) pos++;
3100 
3101  // Assign the mime-type.
3102  m_strMimeType = TQString::fromLatin1(start, pos-start).stripWhiteSpace().lower();
3103  kdDebug(7113) << "(" << m_pid << ") Content-type: " << m_strMimeType << endl;
3104 
3105  // If we still have text, then it means we have a mime-type with a
3106  // parameter (eg: charset=iso-8851) ; so let's get that...
3107  while (*pos)
3108  {
3109  start = ++pos;
3110  while ( *pos && *pos != '=' ) pos++;
3111 
3112  char *end = pos;
3113  while ( *end && *end != ';' ) end++;
3114 
3115  if (*pos)
3116  {
3117  mediaAttribute = TQString::fromLatin1(start, pos-start).stripWhiteSpace().lower();
3118  mediaValue = TQString::fromLatin1(pos+1, end-pos-1).stripWhiteSpace();
3119  pos = end;
3120  if (mediaValue.length() &&
3121  (mediaValue[0] == '"') &&
3122  (mediaValue[mediaValue.length()-1] == '"'))
3123  mediaValue = mediaValue.mid(1, mediaValue.length()-2);
3124 
3125  kdDebug (7113) << "(" << m_pid << ") Media-Parameter Attribute: "
3126  << mediaAttribute << endl;
3127  kdDebug (7113) << "(" << m_pid << ") Media-Parameter Value: "
3128  << mediaValue << endl;
3129 
3130  if ( mediaAttribute == "charset")
3131  {
3132  mediaValue = mediaValue.lower();
3133  m_request.strCharset = mediaValue;
3134  }
3135  else
3136  {
3137  setMetaData("media-"+mediaAttribute, mediaValue);
3138  }
3139  }
3140  }
3141  }
3142 
3143  // Date
3144  else if (strncasecmp(buf, "Date:", 5) == 0) {
3145  dateHeader = KRFCDate::parseDate(trimLead(buf+5));
3146  }
3147 
3148  // Cache management
3149  else if (strncasecmp(buf, "ETag:", 5) == 0) {
3150  m_request.etag = trimLead(buf+5);
3151  }
3152 
3153  // Cache management
3154  else if (strncasecmp(buf, "Expires:", 8) == 0) {
3155  expireDate = KRFCDate::parseDate(trimLead(buf+8));
3156  if (!expireDate)
3157  expireDate = 1; // Already expired
3158  }
3159 
3160  // Cache management
3161  else if (strncasecmp(buf, "Last-Modified:", 14) == 0) {
3162  m_request.lastModified = (TQString::fromLatin1(trimLead(buf+14))).stripWhiteSpace();
3163  }
3164 
3165  // whoops.. we received a warning
3166  else if (strncasecmp(buf, "Warning:", 8) == 0) {
3167  //Don't use warning() here, no need to bother the user.
3168  //Those warnings are mostly about caches.
3169  infoMessage(trimLead(buf + 8));
3170  }
3171 
3172  // Cache management (HTTP 1.0)
3173  else if (strncasecmp(buf, "Pragma:", 7) == 0) {
3174  TQCString pragma = TQCString(trimLead(buf+7)).stripWhiteSpace().lower();
3175  if (pragma == "no-cache")
3176  {
3177  m_request.bCachedWrite = false; // Don't put in cache
3178  mayCache = false;
3179  hasCacheDirective = true;
3180  }
3181  }
3182 
3183  // The deprecated Refresh Response
3184  else if (strncasecmp(buf,"Refresh:", 8) == 0) {
3185  mayCache = false; // Do not cache page as it defeats purpose of Refresh tag!
3186  setMetaData( "http-refresh", TQString::fromLatin1(trimLead(buf+8)).stripWhiteSpace() );
3187  }
3188 
3189  // In fact we should do redirection only if we got redirection code
3190  else if (strncasecmp(buf, "Location:", 9) == 0) {
3191  // Redirect only for 3xx status code, will ya! Thanks, pal!
3192  if ( m_responseCode > 299 && m_responseCode < 400 )
3193  locationStr = TQCString(trimLead(buf+9)).stripWhiteSpace();
3194  }
3195 
3196  // Check for cookies
3197  else if (strncasecmp(buf, "Set-Cookie", 10) == 0) {
3198  cookieStr += buf;
3199  cookieStr += '\n';
3200  }
3201 
3202  // check for direct authentication
3203  else if (strncasecmp(buf, "WWW-Authenticate:", 17) == 0) {
3204  configAuth(trimLead(buf + 17), false);
3205  }
3206 
3207  // check for proxy-based authentication
3208  else if (strncasecmp(buf, "Proxy-Authenticate:", 19) == 0) {
3209  configAuth(trimLead(buf + 19), true);
3210  }
3211 
3212  else if (strncasecmp(buf, "Upgrade:", 8) == 0) {
3213  // Now we have to check to see what is offered for the upgrade
3214  TQString offered = &(buf[8]);
3215  upgradeOffers = TQStringList::split(TQRegExp("[ \n,\r\t]"), offered);
3216  }
3217 
3218  // content?
3219  else if (strncasecmp(buf, "Content-Encoding:", 17) == 0) {
3220  // This is so wrong !! No wonder tdeio_http is stripping the
3221  // gzip encoding from downloaded files. This solves multiple
3222  // bug reports and caitoo's problem with downloads when such a
3223  // header is encountered...
3224 
3225  // A quote from RFC 2616:
3226  // " When present, its (Content-Encoding) value indicates what additional
3227  // content have been applied to the entity body, and thus what decoding
3228  // mechanism must be applied to obtain the media-type referenced by the
3229  // Content-Type header field. Content-Encoding is primarily used to allow
3230  // a document to be compressed without loosing the identity of its underlying
3231  // media type. Simply put if it is specified, this is the actual mime-type
3232  // we should use when we pull the resource !!!
3233  addEncoding(trimLead(buf + 17), m_qContentEncodings);
3234  }
3235  // Refer to RFC 2616 sec 15.5/19.5.1 and RFC 2183
3236  else if(strncasecmp(buf, "Content-Disposition:", 20) == 0) {
3237  char* dispositionBuf = trimLead(buf + 20);
3238  while ( *dispositionBuf )
3239  {
3240  if ( strncasecmp( dispositionBuf, "filename", 8 ) == 0 )
3241  {
3242  dispositionBuf += 8;
3243 
3244  while ( *dispositionBuf == ' ' || *dispositionBuf == '=' )
3245  dispositionBuf++;
3246 
3247  char* bufStart = dispositionBuf;
3248 
3249  while ( *dispositionBuf && *dispositionBuf != ';' )
3250  dispositionBuf++;
3251 
3252  if ( dispositionBuf > bufStart )
3253  {
3254  // Skip any leading quotes...
3255  while ( *bufStart == '"' )
3256  bufStart++;
3257 
3258  // Skip any trailing quotes as well as white spaces...
3259  while ( *(dispositionBuf-1) == ' ' || *(dispositionBuf-1) == '"')
3260  dispositionBuf--;
3261 
3262  if ( dispositionBuf > bufStart )
3263  dispositionFilename = TQString::fromLatin1( bufStart, dispositionBuf-bufStart );
3264 
3265  break;
3266  }
3267  }
3268  else
3269  {
3270  char *bufStart = dispositionBuf;
3271 
3272  while ( *dispositionBuf && *dispositionBuf != ';' )
3273  dispositionBuf++;
3274 
3275  if ( dispositionBuf > bufStart )
3276  dispositionType = TQString::fromLatin1( bufStart, dispositionBuf-bufStart ).stripWhiteSpace();
3277 
3278  while ( *dispositionBuf == ';' || *dispositionBuf == ' ' )
3279  dispositionBuf++;
3280  }
3281  }
3282 
3283  // Content-Dispostion is not allowed to dictate directory
3284  // path, thus we extract the filename only.
3285  if ( !dispositionFilename.isEmpty() )
3286  {
3287  int pos = dispositionFilename.findRev( '/' );
3288 
3289  if( pos > -1 )
3290  dispositionFilename = dispositionFilename.mid(pos+1);
3291 
3292  kdDebug(7113) << "(" << m_pid << ") Content-Disposition: filename="
3293  << dispositionFilename<< endl;
3294  }
3295  }
3296  else if(strncasecmp(buf, "Content-Language:", 17) == 0) {
3297  TQString language = TQString::fromLatin1(trimLead(buf+17)).stripWhiteSpace();
3298  if (!language.isEmpty())
3299  setMetaData("content-language", language);
3300  }
3301  else if (strncasecmp(buf, "Proxy-Connection:", 17) == 0)
3302  {
3303  if (strncasecmp(trimLead(buf + 17), "Close", 5) == 0)
3304  m_bKeepAlive = false;
3305  else if (strncasecmp(trimLead(buf + 17), "Keep-Alive", 10)==0)
3306  m_bKeepAlive = true;
3307  }
3308  else if (strncasecmp(buf, "Link:", 5) == 0) {
3309  // We only support Link: <url>; rel="type" so far
3310  TQStringList link = TQStringList::split(";", TQString(buf)
3311  .replace(TQRegExp("^Link:[ ]*"),
3312  ""));
3313  if (link.count() == 2) {
3314  TQString rel = link[1].stripWhiteSpace();
3315  if (rel.startsWith("rel=\"")) {
3316  rel = rel.mid(5, rel.length() - 6);
3317  if (rel.lower() == "pageservices") {
3318  TQString url = TQString(link[0].replace(TQRegExp("[<>]"),"")).stripWhiteSpace();
3319  setMetaData("PageServices", url);
3320  }
3321  }
3322  }
3323  }
3324  else if (strncasecmp(buf, "P3P:", 4) == 0) {
3325  TQString p3pstr = buf;
3326  p3pstr = p3pstr.mid(4).simplifyWhiteSpace();
3327  TQStringList policyrefs, compact;
3328  TQStringList policyfields = TQStringList::split(TQRegExp(",[ ]*"), p3pstr);
3329  for (TQStringList::Iterator it = policyfields.begin();
3330  it != policyfields.end();
3331  ++it) {
3332  TQStringList policy = TQStringList::split("=", *it);
3333 
3334  if (policy.count() == 2) {
3335  if (policy[0].lower() == "policyref") {
3336  policyrefs << TQString(policy[1].replace(TQRegExp("[\"\']"), ""))
3337  .stripWhiteSpace();
3338  } else if (policy[0].lower() == "cp") {
3339  // We convert to cp\ncp\ncp\n[...]\ncp to be consistent with
3340  // other metadata sent in strings. This could be a bit more
3341  // efficient but I'm going for correctness right now.
3342  TQStringList cps = TQStringList::split(" ",
3343  TQString(policy[1].replace(TQRegExp("[\"\']"), ""))
3344  .simplifyWhiteSpace());
3345 
3346  for (TQStringList::Iterator j = cps.begin(); j != cps.end(); ++j)
3347  compact << *j;
3348  }
3349  }
3350  }
3351 
3352  if (!policyrefs.isEmpty())
3353  setMetaData("PrivacyPolicy", policyrefs.join("\n"));
3354 
3355  if (!compact.isEmpty())
3356  setMetaData("PrivacyCompactPolicy", compact.join("\n"));
3357  }
3358  // let them tell us if we should stay alive or not
3359  else if (strncasecmp(buf, "Connection:", 11) == 0)
3360  {
3361  if (strncasecmp(trimLead(buf + 11), "Close", 5) == 0)
3362  m_bKeepAlive = false;
3363  else if (strncasecmp(trimLead(buf + 11), "Keep-Alive", 10)==0)
3364  m_bKeepAlive = true;
3365  else if (strncasecmp(trimLead(buf + 11), "Upgrade", 7)==0)
3366  {
3367  if (m_responseCode == 101) {
3368  // Ok, an upgrade was accepted, now we must do it
3369  upgradeRequired = true;
3370  } else if (upgradeRequired) { // 426
3371  // Nothing to do since we did it above already
3372  } else {
3373  // Just an offer to upgrade - no need to take it
3374  canUpgrade = true;
3375  }
3376  }
3377  }
3378  // continue only if we know that we're HTTP/1.1
3379  else if ( httpRev == HTTP_11) {
3380  // what kind of encoding do we have? transfer?
3381  if (strncasecmp(buf, "Transfer-Encoding:", 18) == 0) {
3382  // If multiple encodings have been applied to an entity, the
3383  // transfer-codings MUST be listed in the order in which they
3384  // were applied.
3385  addEncoding(trimLead(buf + 18), m_qTransferEncodings);
3386  }
3387 
3388  // md5 signature
3389  else if (strncasecmp(buf, "Content-MD5:", 12) == 0) {
3390  m_sContentMD5 = TQString::fromLatin1(trimLead(buf + 12));
3391  }
3392 
3393  // *** Responses to the HTTP OPTIONS method follow
3394  // WebDAV capabilities
3395  else if (strncasecmp(buf, "DAV:", 4) == 0) {
3396  if (m_davCapabilities.isEmpty()) {
3397  m_davCapabilities << TQString::fromLatin1(trimLead(buf + 4));
3398  }
3399  else {
3400  m_davCapabilities << TQString::fromLatin1(trimLead(buf + 4));
3401  }
3402  }
3403  // *** Responses to the HTTP OPTIONS method finished
3404  }
3405  else if ((httpRev == HTTP_None) && (strlen(buf) != 0))
3406  {
3407  // Remote server does not seem to speak HTTP at all
3408  // Put the crap back into the buffer and hope for the best
3409  rewind();
3410  if (m_responseCode)
3411  m_prevResponseCode = m_responseCode;
3412 
3413  m_responseCode = 200; // Fake it
3414  httpRev = HTTP_Unknown;
3415  m_bKeepAlive = false;
3416  break;
3417  }
3418  setRewindMarker();
3419 
3420  // Clear out our buffer for further use.
3421  memset(buffer, 0, sizeof(buffer));
3422 
3423  } while (!m_bEOF && (len || noHeader) && (headerSize < maxHeaderSize) && (gets(buffer, sizeof(buffer)-1)));
3424 
3425  // Now process the HTTP/1.1 upgrade
3426  TQStringList::Iterator opt = upgradeOffers.begin();
3427  for( ; opt != upgradeOffers.end(); ++opt) {
3428  if (*opt == "TLS/1.0") {
3429  if(upgradeRequired) {
3430  if (!startTLS() && !usingTLS()) {
3431  error(ERR_UPGRADE_REQUIRED, *opt);
3432  return false;
3433  }
3434  }
3435  } else if (*opt == "HTTP/1.1") {
3436  httpRev = HTTP_11;
3437  } else {
3438  // unknown
3439  if (upgradeRequired) {
3440  error(ERR_UPGRADE_REQUIRED, *opt);
3441  return false;
3442  }
3443  }
3444  }
3445 
3446  setMetaData("charset", m_request.strCharset);
3447 
3448  // If we do not support the requested authentication method...
3449  if ( (m_responseCode == 401 && Authentication == AUTH_None) ||
3450  (m_responseCode == 407 && ProxyAuthentication == AUTH_None) )
3451  {
3452  m_bUnauthorized = false;
3453  if (m_request.bErrorPage)
3454  errorPage();
3455  else
3456  {
3457  error( ERR_UNSUPPORTED_ACTION, "Unknown Authorization method!" );
3458  return false;
3459  }
3460  }
3461 
3462  // Fixup expire date for clock drift.
3463  if (expireDate && (expireDate <= dateHeader))
3464  expireDate = 1; // Already expired.
3465 
3466  // Convert max-age into expireDate (overriding previous set expireDate)
3467  if (maxAge == 0)
3468  expireDate = 1; // Already expired.
3469  else if (maxAge > 0)
3470  {
3471  if (currentAge)
3472  maxAge -= currentAge;
3473  if (maxAge <=0)
3474  maxAge = 0;
3475  expireDate = time(0) + maxAge;
3476  }
3477 
3478  if (!expireDate)
3479  {
3480  time_t lastModifiedDate = 0;
3481  if (!m_request.lastModified.isEmpty())
3482  lastModifiedDate = KRFCDate::parseDate(m_request.lastModified);
3483 
3484  if (lastModifiedDate)
3485  {
3486  long diff = static_cast<long>(difftime(dateHeader, lastModifiedDate));
3487  if (diff < 0)
3488  expireDate = time(0) + 1;
3489  else
3490  expireDate = time(0) + (diff / 10);
3491  }
3492  else
3493  {
3494  expireDate = time(0) + DEFAULT_CACHE_EXPIRE;
3495  }
3496  }
3497 
3498  // DONE receiving the header!
3499  if (!cookieStr.isEmpty())
3500  {
3501  if ((m_request.cookieMode == HTTPRequest::CookiesAuto) && m_request.bUseCookiejar)
3502  {
3503  // Give cookies to the cookiejar.
3504  TQString domain = config()->readEntry("cross-domain");
3505  if (!domain.isEmpty() && isCrossDomainRequest(m_request.url.host(), domain))
3506  cookieStr = "Cross-Domain\n" + cookieStr;
3507  addCookies( m_request.url.url(), cookieStr );
3508  }
3509  else if (m_request.cookieMode == HTTPRequest::CookiesManual)
3510  {
3511  // Pass cookie to application
3512  setMetaData("setcookies", cookieStr);
3513  }
3514  }
3515 
3516  if (m_request.bMustRevalidate)
3517  {
3518  m_request.bMustRevalidate = false; // Reset just in case.
3519  if (cacheValidated)
3520  {
3521  // Yippie, we can use the cached version.
3522  // Update the cache with new "Expire" headers.
3523  fclose(m_request.fcache);
3524  m_request.fcache = 0;
3525  updateExpireDate( expireDate, true );
3526  m_request.fcache = checkCacheEntry( ); // Re-read cache entry
3527 
3528  if (m_request.fcache)
3529  {
3530  m_request.bCachedRead = true;
3531  goto try_again; // Read header again, but now from cache.
3532  }
3533  else
3534  {
3535  // Where did our cache entry go???
3536  }
3537  }
3538  else
3539  {
3540  // Validation failed. Close cache.
3541  fclose(m_request.fcache);
3542  m_request.fcache = 0;
3543  }
3544  }
3545 
3546  // We need to reread the header if we got a '100 Continue' or '102 Processing'
3547  if ( cont )
3548  {
3549  goto try_again;
3550  }
3551 
3552  // Do not do a keep-alive connection if the size of the
3553  // response is not known and the response is not Chunked.
3554  if (!m_bChunked && (m_iSize == NO_SIZE))
3555  m_bKeepAlive = false;
3556 
3557  if ( m_responseCode == 204 )
3558  {
3559  return true;
3560  }
3561 
3562  // We need to try to login again if we failed earlier
3563  if ( m_bUnauthorized )
3564  {
3565  if ( (m_responseCode == 401) ||
3566  (m_bUseProxy && (m_responseCode == 407))
3567  )
3568  {
3569  if ( getAuthorization() )
3570  {
3571  // for NTLM Authentication we have to keep the connection open!
3572  if ( Authentication == AUTH_NTLM && m_strAuthorization.length() > 4 )
3573  {
3574  m_bKeepAlive = true;
3575  readBody( true );
3576  }
3577  else if (ProxyAuthentication == AUTH_NTLM && m_strProxyAuthorization.length() > 4)
3578  {
3579  readBody( true );
3580  }
3581  else
3582  httpCloseConnection();
3583  return false; // Try again.
3584  }
3585 
3586  if (m_bError)
3587  return false; // Error out
3588 
3589  // Show error page...
3590  }
3591  m_bUnauthorized = false;
3592  }
3593 
3594  // We need to do a redirect
3595  if (!locationStr.isEmpty())
3596  {
3597  KURL u(m_request.url, locationStr);
3598  if(!u.isValid())
3599  {
3600  error(ERR_MALFORMED_URL, u.url());
3601  return false;
3602  }
3603  if ((u.protocol() != "http") && (u.protocol() != "https") &&
3604  (u.protocol() != "ftp") && (u.protocol() != "webdav") &&
3605  (u.protocol() != "webdavs"))
3606  {
3607  redirection(u);
3608  error(ERR_ACCESS_DENIED, u.url());
3609  return false;
3610  }
3611 
3612  // preserve #ref: (bug 124654)
3613  // if we were at http://host/resource1#ref, we sent a GET for "/resource1"
3614  // if we got redirected to http://host/resource2, then we have to re-add
3615  // the fragment:
3616  if (m_request.url.hasRef() && !u.hasRef() &&
3617  (m_request.url.host() == u.host()) &&
3618  (m_request.url.protocol() == u.protocol()))
3619  u.setRef(m_request.url.ref());
3620 
3621  m_bRedirect = true;
3622  m_redirectLocation = u;
3623 
3624  if (!m_request.id.isEmpty())
3625  {
3626  sendMetaData();
3627  }
3628 
3629  kdDebug(7113) << "(" << m_pid << ") request.url: " << m_request.url.url()
3630  << endl << "LocationStr: " << locationStr.data() << endl;
3631 
3632  kdDebug(7113) << "(" << m_pid << ") Requesting redirection to: " << u.url()
3633  << endl;
3634 
3635  // If we're redirected to a http:// url, remember that we're doing webdav...
3636  if (m_protocol == "webdav" || m_protocol == "webdavs")
3637  u.setProtocol(m_protocol);
3638 
3639  redirection(u);
3640  m_request.bCachedWrite = false; // Turn off caching on re-direction (DA)
3641  mayCache = false;
3642  }
3643 
3644  // Inform the job that we can indeed resume...
3645  if ( bCanResume && m_request.offset )
3646  canResume();
3647  else
3648  m_request.offset = 0;
3649 
3650  // We don't cache certain text objects
3651  if (m_strMimeType.startsWith("text/") &&
3652  (m_strMimeType != "text/css") &&
3653  (m_strMimeType != "text/x-javascript") &&
3654  !hasCacheDirective)
3655  {
3656  // Do not cache secure pages or pages
3657  // originating from password protected sites
3658  // unless the webserver explicitly allows it.
3659  if ( m_bIsSSL || (Authentication != AUTH_None) )
3660  {
3661  m_request.bCachedWrite = false;
3662  mayCache = false;
3663  }
3664  }
3665 
3666  // WABA: Correct for tgz files with a gzip-encoding.
3667  // They really shouldn't put gzip in the Content-Encoding field!
3668  // Web-servers really shouldn't do this: They let Content-Size refer
3669  // to the size of the tgz file, not to the size of the tar file,
3670  // while the Content-Type refers to "tar" instead of "tgz".
3671  if (m_qContentEncodings.last() == "gzip")
3672  {
3673  if (m_strMimeType == "application/x-tar")
3674  {
3675  m_qContentEncodings.remove(m_qContentEncodings.fromLast());
3676  m_strMimeType = TQString::fromLatin1("application/x-tgz");
3677  }
3678  else if (m_strMimeType == "application/postscript")
3679  {
3680  // LEONB: Adding another exception for psgz files.
3681  // Could we use the mimelnk files instead of hardcoding all this?
3682  m_qContentEncodings.remove(m_qContentEncodings.fromLast());
3683  m_strMimeType = TQString::fromLatin1("application/x-gzpostscript");
3684  }
3685  else if ( m_request.allowCompressedPage &&
3686  m_strMimeType != "application/x-tgz" &&
3687  m_strMimeType != "application/x-targz" &&
3688  m_strMimeType != "application/x-gzip" &&
3689  m_request.url.path().right(6) == ".ps.gz" )
3690  {
3691  m_qContentEncodings.remove(m_qContentEncodings.fromLast());
3692  m_strMimeType = TQString::fromLatin1("application/x-gzpostscript");
3693  }
3694  else if ( (m_request.allowCompressedPage &&
3695  m_strMimeType == "text/html")
3696  ||
3697  (m_request.allowCompressedPage &&
3698  m_strMimeType != "application/x-tgz" &&
3699  m_strMimeType != "application/x-targz" &&
3700  m_strMimeType != "application/x-gzip" &&
3701  m_request.url.path().right(3) != ".gz")
3702  )
3703  {
3704  // Unzip!
3705  }
3706  else
3707  {
3708  m_qContentEncodings.remove(m_qContentEncodings.fromLast());
3709  m_strMimeType = TQString::fromLatin1("application/x-gzip");
3710  }
3711  }
3712 
3713  // We can't handle "bzip2" encoding (yet). So if we get something with
3714  // bzip2 encoding, we change the mimetype to "application/x-bzip2".
3715  // Note for future changes: some web-servers send both "bzip2" as
3716  // encoding and "application/x-bzip2" as mimetype. That is wrong.
3717  // currently that doesn't bother us, because we remove the encoding
3718  // and set the mimetype to x-bzip2 anyway.
3719  if (m_qContentEncodings.last() == "bzip2")
3720  {
3721  m_qContentEncodings.remove(m_qContentEncodings.fromLast());
3722  m_strMimeType = TQString::fromLatin1("application/x-bzip2");
3723  }
3724 
3725  // Convert some common mimetypes to standard KDE mimetypes
3726  if (m_strMimeType == "application/x-targz")
3727  m_strMimeType = TQString::fromLatin1("application/x-tgz");
3728  else if (m_strMimeType == "application/zip")
3729  m_strMimeType = TQString::fromLatin1("application/x-zip");
3730  else if (m_strMimeType == "image/x-png")
3731  m_strMimeType = TQString::fromLatin1("image/png");
3732  else if (m_strMimeType == "image/bmp")
3733  m_strMimeType = TQString::fromLatin1("image/x-bmp");
3734  else if (m_strMimeType == "audio/mpeg" || m_strMimeType == "audio/x-mpeg" || m_strMimeType == "audio/mp3")
3735  m_strMimeType = TQString::fromLatin1("audio/x-mp3");
3736  else if (m_strMimeType == "audio/microsoft-wave")
3737  m_strMimeType = TQString::fromLatin1("audio/x-wav");
3738  else if (m_strMimeType == "audio/midi")
3739  m_strMimeType = TQString::fromLatin1("audio/x-midi");
3740  else if (m_strMimeType == "image/x-xpixmap")
3741  m_strMimeType = TQString::fromLatin1("image/x-xpm");
3742  else if (m_strMimeType == "application/rtf")
3743  m_strMimeType = TQString::fromLatin1("text/rtf");
3744 
3745  // Crypto ones....
3746  else if (m_strMimeType == "application/pkix-cert" ||
3747  m_strMimeType == "application/binary-certificate")
3748  {
3749  m_strMimeType = TQString::fromLatin1("application/x-x509-ca-cert");
3750  }
3751 
3752  // Prefer application/x-tgz or x-gzpostscript over application/x-gzip.
3753  else if (m_strMimeType == "application/x-gzip")
3754  {
3755  if ((m_request.url.path().right(7) == ".tar.gz") ||
3756  (m_request.url.path().right(4) == ".tar"))
3757  m_strMimeType = TQString::fromLatin1("application/x-tgz");
3758  if ((m_request.url.path().right(6) == ".ps.gz"))
3759  m_strMimeType = TQString::fromLatin1("application/x-gzpostscript");
3760  }
3761 
3762  // Some webservers say "text/plain" when they mean "application/x-bzip2"
3763  else if ((m_strMimeType == "text/plain") || (m_strMimeType == "application/octet-stream"))
3764  {
3765  TQString ext = m_request.url.path().right(4).upper();
3766  if (ext == ".BZ2")
3767  m_strMimeType = TQString::fromLatin1("application/x-bzip2");
3768  else if (ext == ".PEM")
3769  m_strMimeType = TQString::fromLatin1("application/x-x509-ca-cert");
3770  else if (ext == ".SWF")
3771  m_strMimeType = TQString::fromLatin1("application/x-shockwave-flash");
3772  else if (ext == ".PLS")
3773  m_strMimeType = TQString::fromLatin1("audio/x-scpls");
3774  else if (ext == ".WMV")
3775  m_strMimeType = TQString::fromLatin1("video/x-ms-wmv");
3776  }
3777 
3778 #if 0
3779  // Even if we can't rely on content-length, it seems that we should
3780  // never get more data than content-length. Maybe less, if the
3781  // content-length refers to the unzipped data.
3782  if (!m_qContentEncodings.isEmpty())
3783  {
3784  // If we still have content encoding we can't rely on the Content-Length.
3785  m_iSize = NO_SIZE;
3786  }
3787 #endif
3788 
3789  if( !dispositionType.isEmpty() )
3790  {
3791  kdDebug(7113) << "(" << m_pid << ") Setting Content-Disposition type to: "
3792  << dispositionType << endl;
3793  setMetaData("content-disposition-type", dispositionType);
3794  }
3795  if( !dispositionFilename.isEmpty() )
3796  {
3797  kdDebug(7113) << "(" << m_pid << ") Setting Content-Disposition filename to: "
3798  << dispositionFilename << endl;
3799  // ### KDE4: setting content-disposition to filename for pre 3.5.2 compatability
3800  setMetaData("content-disposition", dispositionFilename);
3801  setMetaData("content-disposition-filename", dispositionFilename);
3802  }
3803 
3804  if (!m_request.lastModified.isEmpty())
3805  setMetaData("modified", m_request.lastModified);
3806 
3807  if (!mayCache)
3808  {
3809  setMetaData("no-cache", "true");
3810  setMetaData("expire-date", "1"); // Expired
3811  }
3812  else
3813  {
3814  TQString tmp;
3815  tmp.setNum(expireDate);
3816  setMetaData("expire-date", tmp);
3817  tmp.setNum(time(0)); // Cache entry will be created shortly.
3818  setMetaData("cache-creation-date", tmp);
3819  }
3820 
3821  // Let the app know about the mime-type iff this is not
3822  // a redirection and the mime-type string is not empty.
3823  if (locationStr.isEmpty() && (!m_strMimeType.isEmpty() ||
3824  m_request.method == HTTP_HEAD))
3825  {
3826  kdDebug(7113) << "(" << m_pid << ") Emitting mimetype " << m_strMimeType << endl;
3827  mimeType( m_strMimeType );
3828  }
3829 
3830  // Do not move send response header before any redirection as it seems
3831  // to screw up some sites. See BR# 150904.
3832  forwardHttpResponseHeader();
3833 
3834  if (m_request.method == HTTP_HEAD)
3835  return true;
3836 
3837  // Do we want to cache this request?
3838  if (m_request.bUseCache)
3839  {
3840  ::unlink( TQFile::encodeName(m_request.cef));
3841  if ( m_request.bCachedWrite && !m_strMimeType.isEmpty() )
3842  {
3843  // Check...
3844  createCacheEntry(m_strMimeType, expireDate); // Create a cache entry
3845  if (!m_request.fcache)
3846  {
3847  m_request.bCachedWrite = false; // Error creating cache entry.
3848  kdDebug(7113) << "(" << m_pid << ") Error creating cache entry for " << m_request.url.url()<<"!\n";
3849  }
3850  m_request.expireDate = expireDate;
3851  m_maxCacheSize = config()->readNumEntry("MaxCacheSize", DEFAULT_MAX_CACHE_SIZE) / 2;
3852  }
3853  }
3854 
3855  if (m_request.bCachedWrite && !m_strMimeType.isEmpty())
3856  kdDebug(7113) << "(" << m_pid << ") Cache, adding \"" << m_request.url.url() << "\"" << endl;
3857  else if (m_request.bCachedWrite && m_strMimeType.isEmpty())
3858  kdDebug(7113) << "(" << m_pid << ") Cache, pending \"" << m_request.url.url() << "\"" << endl;
3859  else
3860  kdDebug(7113) << "(" << m_pid << ") Cache, not adding \"" << m_request.url.url() << "\"" << endl;
3861  return true;
3862 }
3863 
3864 
3865 void HTTPProtocol::addEncoding(TQString encoding, TQStringList &encs)
3866 {
3867  encoding = encoding.stripWhiteSpace().lower();
3868  // Identity is the same as no encoding
3869  if (encoding == "identity") {
3870  return;
3871  } else if (encoding == "8bit") {
3872  // Strange encoding returned by http://linac.ikp.physik.tu-darmstadt.de
3873  return;
3874  } else if (encoding == "chunked") {
3875  m_bChunked = true;
3876  // Anyone know of a better way to handle unknown sizes possibly/ideally with unsigned ints?
3877  //if ( m_cmd != CMD_COPY )
3878  m_iSize = NO_SIZE;
3879  } else if ((encoding == "x-gzip") || (encoding == "gzip")) {
3880  encs.append(TQString::fromLatin1("gzip"));
3881  } else if ((encoding == "x-bzip2") || (encoding == "bzip2")) {
3882  encs.append(TQString::fromLatin1("bzip2")); // Not yet supported!
3883  } else if ((encoding == "x-deflate") || (encoding == "deflate")) {
3884  encs.append(TQString::fromLatin1("deflate"));
3885  } else {
3886  kdDebug(7113) << "(" << m_pid << ") Unknown encoding encountered. "
3887  << "Please write code. Encoding = \"" << encoding
3888  << "\"" << endl;
3889  }
3890 }
3891 
3892 bool HTTPProtocol::sendBody()
3893 {
3894  int result=-1;
3895  int length=0;
3896 
3897  infoMessage( i18n( "Requesting data to send" ) );
3898 
3899  // m_bufPOST will NOT be empty iff authentication was required before posting
3900  // the data OR a re-connect is requested from ::readHeader because the
3901  // connection was lost for some reason.
3902  if ( !m_bufPOST.isNull() )
3903  {
3904  kdDebug(7113) << "(" << m_pid << ") POST'ing saved data..." << endl;
3905 
3906  result = 0;
3907  length = m_bufPOST.size();
3908  }
3909  else
3910  {
3911  kdDebug(7113) << "(" << m_pid << ") POST'ing live data..." << endl;
3912 
3913  TQByteArray buffer;
3914  int old_size;
3915 
3916  m_bufPOST.resize(0);
3917  do
3918  {
3919  dataReq(); // Request for data
3920  result = readData( buffer );
3921  if ( result > 0 )
3922  {
3923  length += result;
3924  old_size = m_bufPOST.size();
3925  m_bufPOST.resize( old_size+result );
3926  memcpy( m_bufPOST.data()+ old_size, buffer.data(), buffer.size() );
3927  buffer.resize(0);
3928  }
3929  } while ( result > 0 );
3930  }
3931 
3932  if ( result < 0 )
3933  {
3934  error( ERR_ABORTED, m_request.hostname );
3935  return false;
3936  }
3937 
3938  infoMessage( i18n( "Sending data to %1" ).arg( m_request.hostname ) );
3939 
3940  TQString size = TQString ("Content-Length: %1\r\n\r\n").arg(length);
3941  kdDebug( 7113 ) << "(" << m_pid << ")" << size << endl;
3942 
3943  // Send the content length...
3944  bool sendOk = (write(size.latin1(), size.length()) == (ssize_t) size.length());
3945  if (!sendOk)
3946  {
3947  kdDebug( 7113 ) << "(" << m_pid << ") Connection broken when sending "
3948  << "content length: (" << m_state.hostname << ")" << endl;
3949  error( ERR_CONNECTION_BROKEN, m_state.hostname );
3950  return false;
3951  }
3952 
3953  // Send the data...
3954  // kdDebug( 7113 ) << "(" << m_pid << ") POST DATA: " << TQCString(m_bufPOST) << endl;
3955  sendOk = (write(m_bufPOST.data(), m_bufPOST.size()) == (ssize_t) m_bufPOST.size());
3956  if (!sendOk)
3957  {
3958  kdDebug(7113) << "(" << m_pid << ") Connection broken when sending message body: ("
3959  << m_state.hostname << ")" << endl;
3960  error( ERR_CONNECTION_BROKEN, m_state.hostname );
3961  return false;
3962  }
3963 
3964  return true;
3965 }
3966 
3967 void HTTPProtocol::httpClose( bool keepAlive )
3968 {
3969  kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::httpClose" << endl;
3970 
3971  if (m_request.fcache)
3972  {
3973  fclose(m_request.fcache);
3974  m_request.fcache = 0;
3975  if (m_request.bCachedWrite)
3976  {
3977  TQString filename = m_request.cef + ".new";
3978  ::unlink( TQFile::encodeName(filename) );
3979  }
3980  }
3981 
3982  // Only allow persistent connections for GET requests.
3983  // NOTE: we might even want to narrow this down to non-form
3984  // based submit requests which will require a meta-data from
3985  // tdehtml.
3986  if (keepAlive && (!m_bUseProxy ||
3987  m_bPersistentProxyConnection || m_bIsTunneled))
3988  {
3989  if (!m_keepAliveTimeout)
3990  m_keepAliveTimeout = DEFAULT_KEEP_ALIVE_TIMEOUT;
3991  else if (m_keepAliveTimeout > 2*DEFAULT_KEEP_ALIVE_TIMEOUT)
3992  m_keepAliveTimeout = 2*DEFAULT_KEEP_ALIVE_TIMEOUT;
3993 
3994  kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::httpClose: keep alive (" << m_keepAliveTimeout << ")" << endl;
3995  TQByteArray data;
3996  TQDataStream stream( data, IO_WriteOnly );
3997  stream << int(99); // special: Close connection
3998  setTimeoutSpecialCommand(m_keepAliveTimeout, data);
3999  return;
4000  }
4001 
4002  httpCloseConnection();
4003 }
4004 
4005 void HTTPProtocol::closeConnection()
4006 {
4007  kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::closeConnection" << endl;
4008  httpCloseConnection ();
4009 }
4010 
4011 void HTTPProtocol::httpCloseConnection ()
4012 {
4013  kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::httpCloseConnection" << endl;
4014  m_bIsTunneled = false;
4015  m_bKeepAlive = false;
4016  closeDescriptor();
4017  setTimeoutSpecialCommand(-1); // Cancel any connection timeout
4018 }
4019 
4020 void HTTPProtocol::slave_status()
4021 {
4022  kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::slave_status" << endl;
4023 
4024  if ( m_iSock != -1 && !isConnectionValid() )
4025  httpCloseConnection();
4026 
4027  slaveStatus( m_state.hostname, (m_iSock != -1) );
4028 }
4029 
4030 void HTTPProtocol::mimetype( const KURL& url )
4031 {
4032  kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::mimetype: "
4033  << url.prettyURL() << endl;
4034 
4035  if ( !checkRequestURL( url ) )
4036  return;
4037 
4038  m_request.method = HTTP_HEAD;
4039  m_request.path = url.path();
4040  m_request.query = url.query();
4041  m_request.cache = CC_Cache;
4042  m_request.doProxy = m_bUseProxy;
4043 
4044  retrieveHeader();
4045 
4046  kdDebug(7113) << "(" << m_pid << ") http: mimetype = " << m_strMimeType
4047  << endl;
4048 }
4049 
4050 void HTTPProtocol::special( const TQByteArray &data )
4051 {
4052  kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::special" << endl;
4053 
4054  int tmp;
4055  TQDataStream stream(data, IO_ReadOnly);
4056 
4057  stream >> tmp;
4058  switch (tmp) {
4059  case 1: // HTTP POST
4060  {
4061  KURL url;
4062  stream >> url;
4063  post( url );
4064  break;
4065  }
4066  case 2: // cache_update
4067  {
4068  KURL url;
4069  bool no_cache;
4070  time_t expireDate;
4071  stream >> url >> no_cache >> expireDate;
4072  cacheUpdate( url, no_cache, expireDate );
4073  break;
4074  }
4075  case 5: // WebDAV lock
4076  {
4077  KURL url;
4078  TQString scope, type, owner;
4079  stream >> url >> scope >> type >> owner;
4080  davLock( url, scope, type, owner );
4081  break;
4082  }
4083  case 6: // WebDAV unlock
4084  {
4085  KURL url;
4086  stream >> url;
4087  davUnlock( url );
4088  break;
4089  }
4090  case 7: // Generic WebDAV
4091  {
4092  KURL url;
4093  int method;
4094  stream >> url >> method;
4095  davGeneric( url, (TDEIO::HTTP_METHOD) method );
4096  break;
4097  }
4098  case 99: // Close Connection
4099  {
4100  httpCloseConnection();
4101  break;
4102  }
4103  default:
4104  // Some command we don't understand.
4105  // Just ignore it, it may come from some future version of KDE.
4106  break;
4107  }
4108 }
4109 
4113 int HTTPProtocol::readChunked()
4114 {
4115  if ((m_iBytesLeft == 0) || (m_iBytesLeft == NO_SIZE))
4116  {
4117  setRewindMarker();
4118 
4119  m_bufReceive.resize(4096);
4120 
4121  if (!gets(m_bufReceive.data(), m_bufReceive.size()-1))
4122  {
4123  kdDebug(7113) << "(" << m_pid << ") gets() failure on Chunk header" << endl;
4124  return -1;
4125  }
4126  // We could have got the CRLF of the previous chunk.
4127  // If so, try again.
4128  if (m_bufReceive[0] == '\0')
4129  {
4130  if (!gets(m_bufReceive.data(), m_bufReceive.size()-1))
4131  {
4132  kdDebug(7113) << "(" << m_pid << ") gets() failure on Chunk header" << endl;
4133  return -1;
4134  }
4135  }
4136 
4137  // m_bEOF is set to true when read called from gets returns 0. For chunked reading 0
4138  // means end of chunked transfer and not error. See RFC 2615 section 3.6.1
4139  #if 0
4140  if (m_bEOF)
4141  {
4142  kdDebug(7113) << "(" << m_pid << ") EOF on Chunk header" << endl;
4143  return -1;
4144  }
4145  #endif
4146 
4147  long long trunkSize = STRTOLL(m_bufReceive.data(), 0, 16);
4148  if (trunkSize < 0)
4149  {
4150  kdDebug(7113) << "(" << m_pid << ") Negative chunk size" << endl;
4151  return -1;
4152  }
4153  m_iBytesLeft = trunkSize;
4154 
4155  // kdDebug(7113) << "(" << m_pid << ") Chunk size = " << m_iBytesLeft << " bytes" << endl;
4156 
4157  if (m_iBytesLeft == 0)
4158  {
4159  // Last chunk.
4160  // Skip trailers.
4161  do {
4162  // Skip trailer of last chunk.
4163  if (!gets(m_bufReceive.data(), m_bufReceive.size()-1))
4164  {
4165  kdDebug(7113) << "(" << m_pid << ") gets() failure on Chunk trailer" << endl;
4166  return -1;
4167  }
4168  // kdDebug(7113) << "(" << m_pid << ") Chunk trailer = \"" << m_bufReceive.data() << "\"" << endl;
4169  }
4170  while (strlen(m_bufReceive.data()) != 0);
4171 
4172  return 0;
4173  }
4174  }
4175 
4176  int bytesReceived = readLimited();
4177  if (!m_iBytesLeft)
4178  m_iBytesLeft = NO_SIZE; // Don't stop, continue with next chunk
4179 
4180  // kdDebug(7113) << "(" << m_pid << ") readChunked: BytesReceived=" << bytesReceived << endl;
4181  return bytesReceived;
4182 }
4183 
4184 int HTTPProtocol::readLimited()
4185 {
4186  if (!m_iBytesLeft)
4187  return 0;
4188 
4189  m_bufReceive.resize(4096);
4190 
4191  int bytesReceived;
4192  int bytesToReceive;
4193 
4194  if (m_iBytesLeft > m_bufReceive.size())
4195  bytesToReceive = m_bufReceive.size();
4196  else
4197  bytesToReceive = m_iBytesLeft;
4198 
4199  bytesReceived = read(m_bufReceive.data(), bytesToReceive);
4200 
4201  if (bytesReceived <= 0)
4202  return -1; // Error: connection lost
4203 
4204  m_iBytesLeft -= bytesReceived;
4205  return bytesReceived;
4206 }
4207 
4208 int HTTPProtocol::readUnlimited()
4209 {
4210  if (m_bKeepAlive)
4211  {
4212  kdDebug(7113) << "(" << m_pid << ") Unbounded datastream on a Keep "
4213  << "alive connection!" << endl;
4214  m_bKeepAlive = false;
4215  }
4216 
4217  m_bufReceive.resize(4096);
4218 
4219  int result = read(m_bufReceive.data(), m_bufReceive.size());
4220  if (result > 0)
4221  return result;
4222 
4223  m_bEOF = true;
4224  m_iBytesLeft = 0;
4225  return 0;
4226 }
4227 
4228 void HTTPProtocol::slotData(const TQByteArray &_d)
4229 {
4230  if (!_d.size())
4231  {
4232  m_bEOD = true;
4233  return;
4234  }
4235 
4236  if (m_iContentLeft != NO_SIZE)
4237  {
4238  if (m_iContentLeft >= _d.size())
4239  m_iContentLeft -= _d.size();
4240  else
4241  m_iContentLeft = NO_SIZE;
4242  }
4243 
4244  TQByteArray d = _d;
4245  if ( !m_dataInternal )
4246  {
4247  // If a broken server does not send the mime-type,
4248  // we try to id it from the content before dealing
4249  // with the content itself.
4250  if ( m_strMimeType.isEmpty() && !m_bRedirect &&
4251  !( m_responseCode >= 300 && m_responseCode <=399) )
4252  {
4253  kdDebug(7113) << "(" << m_pid << ") Determining mime-type from content..." << endl;
4254  int old_size = m_mimeTypeBuffer.size();
4255  m_mimeTypeBuffer.resize( old_size + d.size() );
4256  memcpy( m_mimeTypeBuffer.data() + old_size, d.data(), d.size() );
4257  if ( (m_iBytesLeft != NO_SIZE) && (m_iBytesLeft > 0)
4258  && (m_mimeTypeBuffer.size() < 1024) )
4259  {
4260  m_cpMimeBuffer = true;
4261  return; // Do not send up the data since we do not yet know its mimetype!
4262  }
4263 
4264  kdDebug(7113) << "(" << m_pid << ") Mimetype buffer size: " << m_mimeTypeBuffer.size()
4265  << endl;
4266 
4267  KMimeMagicResult *result;
4268  result = KMimeMagic::self()->findBufferFileType( m_mimeTypeBuffer,
4269  m_request.url.fileName() );
4270  if( result )
4271  {
4272  m_strMimeType = result->mimeType();
4273  kdDebug(7113) << "(" << m_pid << ") Mimetype from content: "
4274  << m_strMimeType << endl;
4275  }
4276 
4277  if ( m_strMimeType.isEmpty() )
4278  {
4279  m_strMimeType = TQString::fromLatin1( DEFAULT_MIME_TYPE );
4280  kdDebug(7113) << "(" << m_pid << ") Using default mimetype: "
4281  << m_strMimeType << endl;
4282  }
4283 
4284  if ( m_request.bCachedWrite )
4285  {
4286  createCacheEntry( m_strMimeType, m_request.expireDate );
4287  if (!m_request.fcache)
4288  m_request.bCachedWrite = false;
4289  }
4290 
4291  if ( m_cpMimeBuffer )
4292  {
4293  // Do not make any assumption about the state of the TQByteArray we received.
4294  // Fix the crash described by BR# 130104.
4295  d.detach();
4296  d.resize(0);
4297  d.resize(m_mimeTypeBuffer.size());
4298  memcpy( d.data(), m_mimeTypeBuffer.data(),
4299  d.size() );
4300  }
4301  mimeType(m_strMimeType);
4302  m_mimeTypeBuffer.resize(0);
4303  }
4304 
4305  data( d );
4306  if (m_request.bCachedWrite && m_request.fcache)
4307  writeCacheEntry(d.data(), d.size());
4308  }
4309  else
4310  {
4311  uint old_size = m_bufWebDavData.size();
4312  m_bufWebDavData.resize (old_size + d.size());
4313  memcpy (m_bufWebDavData.data() + old_size, d.data(), d.size());
4314  }
4315 }
4316 
4326 bool HTTPProtocol::readBody( bool dataInternal /* = false */ )
4327 {
4328  if (m_responseCode == 204)
4329  return true;
4330 
4331  m_bEOD = false;
4332  // Note that when dataInternal is true, we are going to:
4333  // 1) save the body data to a member variable, m_bufWebDavData
4334  // 2) _not_ advertise the data, speed, size, etc., through the
4335  // corresponding functions.
4336  // This is used for returning data to WebDAV.
4337  m_dataInternal = dataInternal;
4338  if ( dataInternal )
4339  m_bufWebDavData.resize (0);
4340 
4341  // Check if we need to decode the data.
4342  // If we are in copy mode, then use only transfer decoding.
4343  bool useMD5 = !m_sContentMD5.isEmpty();
4344 
4345  // Deal with the size of the file.
4346  TDEIO::filesize_t sz = m_request.offset;
4347  if ( sz )
4348  m_iSize += sz;
4349 
4350  // Update the application with total size except when
4351  // it is compressed, or when the data is to be handled
4352  // internally (webDAV). If compressed we have to wait
4353  // until we uncompress to find out the actual data size
4354  if ( !dataInternal ) {
4355  if ( (m_iSize > 0) && (m_iSize != NO_SIZE)) {
4356  totalSize(m_iSize);
4357  infoMessage( i18n( "Retrieving %1 from %2...").arg(TDEIO::convertSize(m_iSize))
4358  .arg( m_request.hostname ) );
4359  }
4360  else
4361  {
4362  totalSize ( 0 );
4363  }
4364  }
4365  else
4366  infoMessage( i18n( "Retrieving from %1..." ).arg( m_request.hostname ) );
4367 
4368  if (m_request.bCachedRead)
4369  {
4370  kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::readBody: read data from cache!" << endl;
4371  m_request.bCachedWrite = false;
4372 
4373  char buffer[ MAX_IPC_SIZE ];
4374 
4375  m_iContentLeft = NO_SIZE;
4376 
4377  // Jippie! It's already in the cache :-)
4378  while (!feof(m_request.fcache) && !ferror(m_request.fcache))
4379  {
4380  int nbytes = fread( buffer, 1, MAX_IPC_SIZE, m_request.fcache);
4381 
4382  if (nbytes > 0)
4383  {
4384  m_bufReceive.setRawData( buffer, nbytes);
4385  slotData( m_bufReceive );
4386  m_bufReceive.resetRawData( buffer, nbytes );
4387  sz += nbytes;
4388  }
4389  }
4390 
4391  m_bufReceive.resize( 0 );
4392 
4393  if ( !dataInternal )
4394  {
4395  processedSize( sz );
4396  data( TQByteArray() );
4397  }
4398 
4399  return true;
4400  }
4401 
4402 
4403  if (m_iSize != NO_SIZE)
4404  m_iBytesLeft = m_iSize - sz;
4405  else
4406  m_iBytesLeft = NO_SIZE;
4407 
4408  m_iContentLeft = m_iBytesLeft;
4409 
4410  if (m_bChunked)
4411  m_iBytesLeft = NO_SIZE;
4412 
4413  kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::readBody: retrieve data. "
4414  << TDEIO::number(m_iBytesLeft) << " left." << endl;
4415 
4416  // Main incoming loop... Gather everything while we can...
4417  m_cpMimeBuffer = false;
4418  m_mimeTypeBuffer.resize(0);
4419  struct timeval last_tv;
4420  gettimeofday( &last_tv, 0L );
4421 
4422  HTTPFilterChain chain;
4423 
4424  TQObject::connect(&chain, TQT_SIGNAL(output(const TQByteArray &)),
4425  this, TQT_SLOT(slotData(const TQByteArray &)));
4426  TQObject::connect(&chain, TQT_SIGNAL(error(int, const TQString &)),
4427  this, TQT_SLOT(error(int, const TQString &)));
4428 
4429  // decode all of the transfer encodings
4430  while (!m_qTransferEncodings.isEmpty())
4431  {
4432  TQString enc = m_qTransferEncodings.last();
4433  m_qTransferEncodings.remove(m_qTransferEncodings.fromLast());
4434  if ( enc == "gzip" )
4435  chain.addFilter(new HTTPFilterGZip);
4436  else if ( enc == "deflate" )
4437  chain.addFilter(new HTTPFilterDeflate);
4438  }
4439 
4440  // From HTTP 1.1 Draft 6:
4441  // The MD5 digest is computed based on the content of the entity-body,
4442  // including any content-coding that has been applied, but not including
4443  // any transfer-encoding applied to the message-body. If the message is
4444  // received with a transfer-encoding, that encoding MUST be removed
4445  // prior to checking the Content-MD5 value against the received entity.
4446  HTTPFilterMD5 *md5Filter = 0;
4447  if ( useMD5 )
4448  {
4449  md5Filter = new HTTPFilterMD5;
4450  chain.addFilter(md5Filter);
4451  }
4452 
4453  // now decode all of the content encodings
4454  // -- Why ?? We are not
4455  // -- a proxy server, be a client side implementation!! The applications
4456  // -- are capable of determinig how to extract the encoded implementation.
4457  // WB: That's a misunderstanding. We are free to remove the encoding.
4458  // WB: Some braindead www-servers however, give .tgz files an encoding
4459  // WB: of "gzip" (or even "x-gzip") and a content-type of "applications/tar"
4460  // WB: They shouldn't do that. We can work around that though...
4461  while (!m_qContentEncodings.isEmpty())
4462  {
4463  TQString enc = m_qContentEncodings.last();
4464  m_qContentEncodings.remove(m_qContentEncodings.fromLast());
4465  if ( enc == "gzip" )
4466  chain.addFilter(new HTTPFilterGZip);
4467  else if ( enc == "deflate" )
4468  chain.addFilter(new HTTPFilterDeflate);
4469  }
4470 
4471  while (!m_bEOF)
4472  {
4473  int bytesReceived;
4474 
4475  if (m_bChunked)
4476  bytesReceived = readChunked();
4477  else if (m_iSize != NO_SIZE)
4478  bytesReceived = readLimited();
4479  else
4480  bytesReceived = readUnlimited();
4481 
4482  // make sure that this wasn't an error, first
4483  // kdDebug(7113) << "(" << (int) m_pid << ") readBody: bytesReceived: "
4484  // << (int) bytesReceived << " m_iSize: " << (int) m_iSize << " Chunked: "
4485  // << (int) m_bChunked << " BytesLeft: "<< (int) m_iBytesLeft << endl;
4486  if (bytesReceived == -1)
4487  {
4488  if (m_iContentLeft == 0)
4489  {
4490  // gzip'ed data sometimes reports a too long content-length.
4491  // (The length of the unzipped data)
4492  m_iBytesLeft = 0;
4493  break;
4494  }
4495  // Oh well... log an error and bug out
4496  kdDebug(7113) << "(" << m_pid << ") readBody: bytesReceived==-1 sz=" << (int)sz
4497  << " Connnection broken !" << endl;
4498  error(ERR_CONNECTION_BROKEN, m_state.hostname);
4499  return false;
4500  }
4501 
4502  // I guess that nbytes == 0 isn't an error.. but we certainly
4503  // won't work with it!
4504  if (bytesReceived > 0)
4505  {
4506  // Important: truncate the buffer to the actual size received!
4507  // Otherwise garbage will be passed to the app
4508  m_bufReceive.truncate( bytesReceived );
4509 
4510  chain.slotInput(m_bufReceive);
4511 
4512  if (m_bError)
4513  return false;
4514 
4515  sz += bytesReceived;
4516  if (!dataInternal)
4517  processedSize( sz );
4518  }
4519  m_bufReceive.resize(0); // res
4520 
4521  if (m_iBytesLeft && m_bEOD && !m_bChunked)
4522  {
4523  // gzip'ed data sometimes reports a too long content-length.
4524  // (The length of the unzipped data)
4525  m_iBytesLeft = 0;
4526  }
4527 
4528  if (m_iBytesLeft == 0)
4529  {
4530  kdDebug(7113) << "("<<m_pid<<") EOD received! Left = "<< TDEIO::number(m_iBytesLeft) << endl;
4531  break;
4532  }
4533  }
4534  chain.slotInput(TQByteArray()); // Flush chain.
4535 
4536  if ( useMD5 )
4537  {
4538  TQString calculatedMD5 = md5Filter->md5();
4539 
4540  if ( m_sContentMD5 == calculatedMD5 )
4541  kdDebug(7113) << "(" << m_pid << ") MD5 checksum MATCHED!!" << endl;
4542  else
4543  kdDebug(7113) << "(" << m_pid << ") MD5 checksum MISMATCH! Expected: "
4544  << calculatedMD5 << ", Got: " << m_sContentMD5 << endl;
4545  }
4546 
4547  // Close cache entry
4548  if (m_iBytesLeft == 0)
4549  {
4550  if (m_request.bCachedWrite && m_request.fcache)
4551  closeCacheEntry();
4552  else if (m_request.bCachedWrite)
4553  kdDebug(7113) << "(" << m_pid << ") no cache file!\n";
4554  }
4555  else
4556  {
4557  kdDebug(7113) << "(" << m_pid << ") still "<< TDEIO::number(m_iBytesLeft)
4558  << " bytes left! can't close cache entry!\n";
4559  }
4560 
4561  if (sz <= 1)
4562  {
4563  /* kdDebug(7113) << "(" << m_pid << ") readBody: sz = " << TDEIO::number(sz)
4564  << ", responseCode =" << m_responseCode << endl; */
4565  if (m_responseCode >= 500 && m_responseCode <= 599)
4566  error(ERR_INTERNAL_SERVER, m_state.hostname);
4567  else if (m_responseCode >= 400 && m_responseCode <= 499)
4568  error(ERR_DOES_NOT_EXIST, m_state.hostname);
4569  }
4570 
4571  if (!dataInternal)
4572  data( TQByteArray() );
4573 
4574  return true;
4575 }
4576 
4577 
4578 void HTTPProtocol::error( int _err, const TQString &_text )
4579 {
4580  httpClose(false);
4581 
4582  if (!m_request.id.isEmpty())
4583  {
4584  forwardHttpResponseHeader();
4585  sendMetaData();
4586  }
4587 
4588  // Clear of the temporary POST buffer if it is not empty...
4589  if (!m_bufPOST.isEmpty())
4590  {
4591  m_bufPOST.resize(0);
4592  kdDebug(7113) << "(" << m_pid << ") HTTP::retreiveHeader: Cleared POST "
4593  "buffer..." << endl;
4594  }
4595 
4596  SlaveBase::error( _err, _text );
4597  m_bError = true;
4598 }
4599 
4600 
4601 void HTTPProtocol::addCookies( const TQString &url, const TQCString &cookieHeader )
4602 {
4603  long windowId = m_request.window.toLong();
4604  TQByteArray params;
4605  TQDataStream stream(params, IO_WriteOnly);
4606  stream << url << cookieHeader << windowId;
4607 
4608  kdDebug(7113) << "(" << m_pid << ") " << cookieHeader << endl;
4609  kdDebug(7113) << "(" << m_pid << ") " << "Window ID: "
4610  << windowId << ", for host = " << url << endl;
4611 
4612  if ( !dcopClient()->send( "kded", "kcookiejar", "addCookies(TQString,TQCString,long int)", params ) )
4613  {
4614  kdWarning(7113) << "(" << m_pid << ") Can't communicate with kded_kcookiejar!" << endl;
4615  }
4616 }
4617 
4618 TQString HTTPProtocol::findCookies( const TQString &url)
4619 {
4620  TQCString replyType;
4621  TQByteArray params;
4622  TQByteArray reply;
4623  TQString result;
4624 
4625  long windowId = m_request.window.toLong();
4626  result = TQString::null;
4627  TQDataStream stream(params, IO_WriteOnly);
4628  stream << url << windowId;
4629 
4630  if ( !dcopClient()->call( "kded", "kcookiejar", "findCookies(TQString,long int)",
4631  params, replyType, reply ) )
4632  {
4633  kdWarning(7113) << "(" << m_pid << ") Can't communicate with kded_kcookiejar!" << endl;
4634  return result;
4635  }
4636  if ( replyType == "TQString" )
4637  {
4638  TQDataStream stream2( reply, IO_ReadOnly );
4639  stream2 >> result;
4640  }
4641  else
4642  {
4643  kdError(7113) << "(" << m_pid << ") DCOP function findCookies(...) returns "
4644  << replyType << ", expected TQString" << endl;
4645  }
4646  return result;
4647 }
4648 
4649 /******************************* CACHING CODE ****************************/
4650 
4651 
4652 void HTTPProtocol::cacheUpdate( const KURL& url, bool no_cache, time_t expireDate)
4653 {
4654  if ( !checkRequestURL( url ) )
4655  return;
4656 
4657  m_request.path = url.path();
4658  m_request.query = url.query();
4659  m_request.cache = CC_Reload;
4660  m_request.doProxy = m_bUseProxy;
4661 
4662  if (no_cache)
4663  {
4664  m_request.fcache = checkCacheEntry( );
4665  if (m_request.fcache)
4666  {
4667  fclose(m_request.fcache);
4668  m_request.fcache = 0;
4669  ::unlink( TQFile::encodeName(m_request.cef) );
4670  }
4671  }
4672  else
4673  {
4674  updateExpireDate( expireDate );
4675  }
4676  finished();
4677 }
4678 
4679 // !START SYNC!
4680 // The following code should be kept in sync
4681 // with the code in http_cache_cleaner.cpp
4682 
4683 FILE* HTTPProtocol::checkCacheEntry( bool readWrite)
4684 {
4685  const TQChar separator = '_';
4686 
4687  TQString CEF = m_request.path;
4688 
4689  int p = CEF.find('/');
4690 
4691  while(p != -1)
4692  {
4693  CEF[p] = separator;
4694  p = CEF.find('/', p);
4695  }
4696 
4697  TQString host = m_request.hostname.lower();
4698  CEF = host + CEF + '_';
4699 
4700  TQString dir = m_strCacheDir;
4701  if (dir[dir.length()-1] != '/')
4702  dir += "/";
4703 
4704  int l = host.length();
4705  for(int i = 0; i < l; i++)
4706  {
4707  if (host[i].isLetter() && (host[i] != 'w'))
4708  {
4709  dir += host[i];
4710  break;
4711  }
4712  }
4713  if (dir[dir.length()-1] == '/')
4714  dir += "0";
4715 
4716  unsigned long hash = 0x00000000;
4717  TQCString u = m_request.url.url().latin1();
4718  for(int i = u.length(); i--;)
4719  {
4720  hash = (hash * 12211 + static_cast<const char>(u.at(i))) % 2147483563;
4721  }
4722 
4723  TQString hashString;
4724  hashString.sprintf("%08lx", hash);
4725 
4726  CEF = CEF + hashString;
4727 
4728  CEF = dir + "/" + CEF;
4729 
4730  m_request.cef = CEF;
4731 
4732  const char *mode = (readWrite ? "r+" : "r");
4733 
4734  FILE *fs = fopen( TQFile::encodeName(CEF), mode); // Open for reading and writing
4735  if (!fs)
4736  return 0;
4737 
4738  char buffer[401];
4739  bool ok = true;
4740 
4741  // CacheRevision
4742  if (ok && (!fgets(buffer, 400, fs)))
4743  ok = false;
4744  if (ok && (strcmp(buffer, CACHE_REVISION) != 0))
4745  ok = false;
4746 
4747  time_t date;
4748  time_t currentDate = time(0);
4749 
4750  // URL
4751  if (ok && (!fgets(buffer, 400, fs)))
4752  ok = false;
4753  if (ok)
4754  {
4755  int l = strlen(buffer);
4756  if (l>0)
4757  buffer[l-1] = 0; // Strip newline
4758  if (m_request.url.url() != buffer)
4759  {
4760  ok = false; // Hash collision
4761  }
4762  }
4763 
4764  // Creation Date
4765  if (ok && (!fgets(buffer, 400, fs)))
4766  ok = false;
4767  if (ok)
4768  {
4769  date = (time_t) strtoul(buffer, 0, 10);
4770  m_request.creationDate = date;
4771  if (m_maxCacheAge && (difftime(currentDate, date) > m_maxCacheAge))
4772  {
4773  m_request.bMustRevalidate = true;
4774  m_request.expireDate = currentDate;
4775  }
4776  }
4777 
4778  // Expiration Date
4779  m_request.cacheExpireDateOffset = ftell(fs);
4780  if (ok && (!fgets(buffer, 400, fs)))
4781  ok = false;
4782  if (ok)
4783  {
4784  if (m_request.cache == CC_Verify)
4785  {
4786  date = (time_t) strtoul(buffer, 0, 10);
4787  // After the expire date we need to revalidate.
4788  if (!date || difftime(currentDate, date) >= 0)
4789  m_request.bMustRevalidate = true;
4790  m_request.expireDate = date;
4791  }
4792  else if (m_request.cache == CC_Refresh)
4793  {
4794  m_request.bMustRevalidate = true;
4795  m_request.expireDate = currentDate;
4796  }
4797  }
4798 
4799  // ETag
4800  if (ok && (!fgets(buffer, 400, fs)))
4801  ok = false;
4802  if (ok)
4803  {
4804  m_request.etag = TQString(buffer).stripWhiteSpace();
4805  }
4806 
4807  // Last-Modified
4808  if (ok && (!fgets(buffer, 400, fs)))
4809  ok = false;
4810  if (ok)
4811  {
4812  m_request.lastModified = TQString(buffer).stripWhiteSpace();
4813  }
4814 
4815  if (ok)
4816  return fs;
4817 
4818  fclose(fs);
4819  unlink( TQFile::encodeName(CEF));
4820  return 0;
4821 }
4822 
4823 void HTTPProtocol::updateExpireDate(time_t expireDate, bool updateCreationDate)
4824 {
4825  bool ok = true;
4826 
4827  FILE *fs = checkCacheEntry(true);
4828  if (fs)
4829  {
4830  TQString date;
4831  char buffer[401];
4832  time_t creationDate;
4833 
4834  fseek(fs, 0, SEEK_SET);
4835  if (ok && !fgets(buffer, 400, fs))
4836  ok = false;
4837  if (ok && !fgets(buffer, 400, fs))
4838  ok = false;
4839  long cacheCreationDateOffset = ftell(fs);
4840  if (ok && !fgets(buffer, 400, fs))
4841  ok = false;
4842  creationDate = strtoul(buffer, 0, 10);
4843  if (!creationDate)
4844  ok = false;
4845 
4846  if (updateCreationDate)
4847  {
4848  if (!ok || fseek(fs, cacheCreationDateOffset, SEEK_SET))
4849  return;
4850  TQString date;
4851  date.setNum( time(0) );
4852  date = date.leftJustify(16);
4853  fputs(date.latin1(), fs); // Creation date
4854  fputc('\n', fs);
4855  }
4856 
4857  if (expireDate>(30*365*24*60*60))
4858  {
4859  // expire date is a really a big number, it can't be
4860  // a relative date.
4861  date.setNum( expireDate );
4862  }
4863  else
4864  {
4865  // expireDate before 2000. those values must be
4866  // interpreted as relative expiration dates from
4867  // <META http-equiv="Expires"> tags.
4868  // so we have to scan the creation time and add
4869  // it to the expiryDate
4870  date.setNum( creationDate + expireDate );
4871  }
4872  date = date.leftJustify(16);
4873  if (!ok || fseek(fs, m_request.cacheExpireDateOffset, SEEK_SET))
4874  return;
4875  fputs(date.latin1(), fs); // Expire date
4876  fseek(fs, 0, SEEK_END);
4877  fclose(fs);
4878  }
4879 }
4880 
4881 void HTTPProtocol::createCacheEntry( const TQString &mimetype, time_t expireDate)
4882 {
4883  TQString dir = m_request.cef;
4884  int p = dir.findRev('/');
4885  if (p == -1) return; // Error.
4886  dir.truncate(p);
4887 
4888  // Create file
4889  (void) ::mkdir( TQFile::encodeName(dir), 0700 );
4890 
4891  TQString filename = m_request.cef + ".new"; // Create a new cache entryexpireDate
4892 
4893 // kdDebug( 7103 ) << "creating new cache entry: " << filename << endl;
4894 
4895  m_request.fcache = fopen( TQFile::encodeName(filename), "w");
4896  if (!m_request.fcache)
4897  {
4898  kdWarning(7113) << "(" << m_pid << ")createCacheEntry: opening " << filename << " failed." << endl;
4899  return; // Error.
4900  }
4901 
4902  fputs(CACHE_REVISION, m_request.fcache); // Revision
4903 
4904  fputs(m_request.url.url().latin1(), m_request.fcache); // Url
4905  fputc('\n', m_request.fcache);
4906 
4907  TQString date;
4908  m_request.creationDate = time(0);
4909  date.setNum( m_request.creationDate );
4910  date = date.leftJustify(16);
4911  fputs(date.latin1(), m_request.fcache); // Creation date
4912  fputc('\n', m_request.fcache);
4913 
4914  date.setNum( expireDate );
4915  date = date.leftJustify(16);
4916  fputs(date.latin1(), m_request.fcache); // Expire date
4917  fputc('\n', m_request.fcache);
4918 
4919  if (!m_request.etag.isEmpty())
4920  fputs(m_request.etag.latin1(), m_request.fcache); //ETag
4921  fputc('\n', m_request.fcache);
4922 
4923  if (!m_request.lastModified.isEmpty())
4924  fputs(m_request.lastModified.latin1(), m_request.fcache); // Last modified
4925  fputc('\n', m_request.fcache);
4926 
4927  fputs(mimetype.latin1(), m_request.fcache); // Mimetype
4928  fputc('\n', m_request.fcache);
4929 
4930  if (!m_request.strCharset.isEmpty())
4931  fputs(m_request.strCharset.latin1(), m_request.fcache); // Charset
4932  fputc('\n', m_request.fcache);
4933 
4934  return;
4935 }
4936 // The above code should be kept in sync
4937 // with the code in http_cache_cleaner.cpp
4938 // !END SYNC!
4939 
4940 void HTTPProtocol::writeCacheEntry( const char *buffer, int nbytes)
4941 {
4942  if (fwrite( buffer, nbytes, 1, m_request.fcache) != 1)
4943  {
4944  kdWarning(7113) << "(" << m_pid << ") writeCacheEntry: writing " << nbytes << " bytes failed." << endl;
4945  fclose(m_request.fcache);
4946  m_request.fcache = 0;
4947  TQString filename = m_request.cef + ".new";
4948  ::unlink( TQFile::encodeName(filename) );
4949  return;
4950  }
4951  long file_pos = ftell( m_request.fcache ) / 1024;
4952  if ( file_pos > m_maxCacheSize )
4953  {
4954  kdDebug(7113) << "writeCacheEntry: File size reaches " << file_pos
4955  << "Kb, exceeds cache limits. (" << m_maxCacheSize << "Kb)" << endl;
4956  fclose(m_request.fcache);
4957  m_request.fcache = 0;
4958  TQString filename = m_request.cef + ".new";
4959  ::unlink( TQFile::encodeName(filename) );
4960  return;
4961  }
4962 }
4963 
4964 void HTTPProtocol::closeCacheEntry()
4965 {
4966  TQString filename = m_request.cef + ".new";
4967  int result = fclose( m_request.fcache);
4968  m_request.fcache = 0;
4969  if (result == 0)
4970  {
4971  if (::rename( TQFile::encodeName(filename), TQFile::encodeName(m_request.cef)) == 0)
4972  return; // Success
4973 
4974  kdWarning(7113) << "(" << m_pid << ") closeCacheEntry: error renaming "
4975  << "cache entry. (" << filename << " -> " << m_request.cef
4976  << ")" << endl;
4977  }
4978 
4979  kdWarning(7113) << "(" << m_pid << ") closeCacheEntry: error closing cache "
4980  << "entry. (" << filename<< ")" << endl;
4981 }
4982 
4983 void HTTPProtocol::cleanCache()
4984 {
4985  const time_t maxAge = DEFAULT_CLEAN_CACHE_INTERVAL; // 30 Minutes.
4986  bool doClean = false;
4987  TQString cleanFile = m_strCacheDir;
4988  if (cleanFile[cleanFile.length()-1] != '/')
4989  cleanFile += "/";
4990  cleanFile += "cleaned";
4991 
4992  struct stat stat_buf;
4993 
4994  int result = ::stat(TQFile::encodeName(cleanFile), &stat_buf);
4995  if (result == -1)
4996  {
4997  int fd = creat( TQFile::encodeName(cleanFile), 0600);
4998  if (fd != -1)
4999  {
5000  doClean = true;
5001  ::close(fd);
5002  }
5003  }
5004  else
5005  {
5006  time_t age = (time_t) difftime( time(0), stat_buf.st_mtime );
5007  if (age > maxAge) //
5008  doClean = true;
5009  }
5010  if (doClean)
5011  {
5012  // Touch file.
5013  utime(TQFile::encodeName(cleanFile), 0);
5014  TDEApplication::startServiceByDesktopPath("http_cache_cleaner.desktop");
5015  }
5016 }
5017 
5018 
5019 
5020 //************************** AUTHENTICATION CODE ********************/
5021 
5022 
5023 void HTTPProtocol::configAuth( char *p, bool isForProxy )
5024 {
5025  HTTP_AUTH f = AUTH_None;
5026  const char *strAuth = p;
5027 
5028  if ( strncasecmp( p, "Basic", 5 ) == 0 )
5029  {
5030  f = AUTH_Basic;
5031  p += 5;
5032  strAuth = "Basic"; // Correct for upper-case variations.
5033  }
5034  else if ( strncasecmp (p, "Digest", 6) == 0 )
5035  {
5036  f = AUTH_Digest;
5037  memcpy((void *)p, "Digest", 6); // Correct for upper-case variations.
5038  p += 6;
5039  }
5040  else if (strncasecmp( p, "MBS_PWD_COOKIE", 14 ) == 0)
5041  {
5042  // Found on http://www.webscription.net/baen/default.asp
5043  f = AUTH_Basic;
5044  p += 14;
5045  strAuth = "Basic";
5046  }
5047 #ifdef HAVE_LIBGSSAPI
5048  else if ( strncasecmp( p, "Negotiate", 9 ) == 0 )
5049  {
5050  // if we get two 401 in a row let's assume for now that
5051  // Negotiate isn't working and ignore it
5052  if ( !isForProxy && !(m_responseCode == 401 && m_prevResponseCode == 401) )
5053  {
5054  f = AUTH_Negotiate;
5055  memcpy((void *)p, "Negotiate", 9); // Correct for upper-case variations.
5056  p += 9;
5057  };
5058  }
5059 #endif
5060  else if ( strncasecmp( p, "NTLM", 4 ) == 0 )
5061  {
5062  f = AUTH_NTLM;
5063  memcpy((void *)p, "NTLM", 4); // Correct for upper-case variations.
5064  p += 4;
5065  m_strRealm = "NTLM"; // set a dummy realm
5066  }
5067  else
5068  {
5069  kdWarning(7113) << "(" << m_pid << ") Unsupported or invalid authorization "
5070  << "type requested" << endl;
5071  if (isForProxy)
5072  kdWarning(7113) << "(" << m_pid << ") Proxy URL: " << m_proxyURL << endl;
5073  else
5074  kdWarning(7113) << "(" << m_pid << ") URL: " << m_request.url << endl;
5075  kdWarning(7113) << "(" << m_pid << ") Request Authorization: " << p << endl;
5076  }
5077 
5078  /*
5079  This check ensures the following:
5080  1.) Rejection of any unknown/unsupported authentication schemes
5081  2.) Usage of the strongest possible authentication schemes if
5082  and when multiple Proxy-Authenticate or WWW-Authenticate
5083  header field is sent.
5084  */
5085  if (isForProxy)
5086  {
5087  if ((f == AUTH_None) ||
5088  ((m_iProxyAuthCount > 0) && (f < ProxyAuthentication)))
5089  {
5090  // Since I purposefully made the Proxy-Authentication settings
5091  // persistent to reduce the number of round-trips to tdesud we
5092  // have to take special care when an unknown/unsupported auth-
5093  // scheme is received. This check accomplishes just that...
5094  if ( m_iProxyAuthCount == 0)
5095  ProxyAuthentication = f;
5096  kdDebug(7113) << "(" << m_pid << ") Rejected proxy auth method: " << f << endl;
5097  return;
5098  }
5099  m_iProxyAuthCount++;
5100  kdDebug(7113) << "(" << m_pid << ") Accepted proxy auth method: " << f << endl;
5101  }
5102  else
5103  {
5104  if ((f == AUTH_None) ||
5105  ((m_iWWWAuthCount > 0) && (f < Authentication)))
5106  {
5107  kdDebug(7113) << "(" << m_pid << ") Rejected auth method: " << f << endl;
5108  return;
5109  }
5110  m_iWWWAuthCount++;
5111  kdDebug(7113) << "(" << m_pid << ") Accepted auth method: " << f << endl;
5112  }
5113 
5114 
5115  while (*p)
5116  {
5117  int i = 0;
5118  while( (*p == ' ') || (*p == ',') || (*p == '\t') ) { p++; }
5119  if ( strncasecmp( p, "realm=", 6 ) == 0 )
5120  {
5121  //for sites like lib.homelinux.org
5122  TQTextCodec* oldCodec=TQTextCodec::codecForCStrings();
5123  if (TDEGlobal::locale()->language().contains("ru"))
5124  TQTextCodec::setCodecForCStrings(TQTextCodec::codecForName("CP1251"));
5125 
5126  p += 6;
5127  if (*p == '"') p++;
5128  while( p[i] && p[i] != '"' ) i++;
5129  if( isForProxy )
5130  m_strProxyRealm = TQString::fromAscii( p, i );
5131  else
5132  m_strRealm = TQString::fromAscii( p, i );
5133 
5134  TQTextCodec::setCodecForCStrings(oldCodec);
5135 
5136  if (!p[i]) break;
5137  }
5138  p+=(i+1);
5139  }
5140 
5141  if( isForProxy )
5142  {
5143  ProxyAuthentication = f;
5144  m_strProxyAuthorization = TQString::fromLatin1( strAuth );
5145  }
5146  else
5147  {
5148  Authentication = f;
5149  m_strAuthorization = TQString::fromLatin1( strAuth );
5150  }
5151 }
5152 
5153 
5154 bool HTTPProtocol::retryPrompt()
5155 {
5156  TQString prompt;
5157  switch ( m_responseCode )
5158  {
5159  case 401:
5160  prompt = i18n("Authentication Failed.");
5161  break;
5162  case 407:
5163  prompt = i18n("Proxy Authentication Failed.");
5164  break;
5165  default:
5166  break;
5167  }
5168  prompt += i18n(" Do you want to retry?");
5169  return (messageBox(QuestionYesNo, prompt, i18n("Authentication")) == 3);
5170 }
5171 
5172 void HTTPProtocol::promptInfo( AuthInfo& info )
5173 {
5174  if ( m_responseCode == 401 )
5175  {
5176  info.url = m_request.url;
5177  if ( !m_state.user.isEmpty() )
5178  info.username = m_state.user;
5179  info.readOnly = !m_request.url.user().isEmpty();
5180  info.prompt = i18n( "You need to supply a username and a "
5181  "password to access this site." );
5182  info.keepPassword = true; // Prompt the user for persistence as well.
5183  if ( !m_strRealm.isEmpty() )
5184  {
5185  info.realmValue = m_strRealm;
5186  info.verifyPath = false;
5187  info.digestInfo = m_strAuthorization;
5188  info.commentLabel = i18n( "Site:" );
5189  info.comment = i18n("<b>%1</b> at <b>%2</b>").arg( m_strRealm ).arg( m_request.hostname );
5190  }
5191  }
5192  else if ( m_responseCode == 407 )
5193  {
5194  info.url = m_proxyURL;
5195  info.username = m_proxyURL.user();
5196  info.prompt = i18n( "You need to supply a username and a password for "
5197  "the proxy server listed below before you are allowed "
5198  "to access any sites." );
5199  info.keepPassword = true;
5200  if ( !m_strProxyRealm.isEmpty() )
5201  {
5202  info.realmValue = m_strProxyRealm;
5203  info.verifyPath = false;
5204  info.digestInfo = m_strProxyAuthorization;
5205  info.commentLabel = i18n( "Proxy:" );
5206  info.comment = i18n("<b>%1</b> at <b>%2</b>").arg( m_strProxyRealm ).arg( m_proxyURL.host() );
5207  }
5208  }
5209 }
5210 
5211 bool HTTPProtocol::getAuthorization()
5212 {
5213  AuthInfo info;
5214  bool result = false;
5215 
5216  kdDebug (7113) << "(" << m_pid << ") HTTPProtocol::getAuthorization: "
5217  << "Current Response: " << m_responseCode << ", "
5218  << "Previous Response: " << m_prevResponseCode << ", "
5219  << "Authentication: " << Authentication << ", "
5220  << "ProxyAuthentication: " << ProxyAuthentication << endl;
5221 
5222  if (m_request.bNoAuth)
5223  {
5224  if (m_request.bErrorPage)
5225  errorPage();
5226  else
5227  error( ERR_COULD_NOT_LOGIN, i18n("Authentication needed for %1 but authentication is disabled.").arg(m_request.hostname));
5228  return false;
5229  }
5230 
5231  bool repeatFailure = (m_prevResponseCode == m_responseCode);
5232 
5233  TQString errorMsg;
5234 
5235  if (repeatFailure)
5236  {
5237  bool prompt = true;
5238  if ( Authentication == AUTH_Digest || ProxyAuthentication == AUTH_Digest )
5239  {
5240  bool isStaleNonce = false;
5241  TQString auth = ( m_responseCode == 401 ) ? m_strAuthorization : m_strProxyAuthorization;
5242  int pos = auth.find("stale", 0, false);
5243  if ( pos != -1 )
5244  {
5245  pos += 5;
5246  int len = auth.length();
5247  while( pos < len && (auth[pos] == ' ' || auth[pos] == '=') ) pos++;
5248  if ( pos < len && auth.find("true", pos, false) != -1 )
5249  {
5250  isStaleNonce = true;
5251  kdDebug(7113) << "(" << m_pid << ") Stale nonce value. "
5252  << "Will retry using same info..." << endl;
5253  }
5254  }
5255  if ( isStaleNonce )
5256  {
5257  prompt = false;
5258  result = true;
5259  if ( m_responseCode == 401 )
5260  {
5261  info.username = m_request.user;
5262  info.password = m_request.passwd;
5263  info.realmValue = m_strRealm;
5264  info.digestInfo = m_strAuthorization;
5265  }
5266  else if ( m_responseCode == 407 )
5267  {
5268  info.username = m_proxyURL.user();
5269  info.password = m_proxyURL.pass();
5270  info.realmValue = m_strProxyRealm;
5271  info.digestInfo = m_strProxyAuthorization;
5272  }
5273  }
5274  }
5275 
5276  if ( Authentication == AUTH_NTLM || ProxyAuthentication == AUTH_NTLM )
5277  {
5278  TQString auth = ( m_responseCode == 401 ) ? m_strAuthorization : m_strProxyAuthorization;
5279  kdDebug(7113) << "auth: " << auth << endl;
5280  if ( auth.length() > 4 )
5281  {
5282  prompt = false;
5283  result = true;
5284  kdDebug(7113) << "(" << m_pid << ") NTLM auth second phase, "
5285  << "sending response..." << endl;
5286  if ( m_responseCode == 401 )
5287  {
5288  info.username = m_request.user;
5289  info.password = m_request.passwd;
5290  info.realmValue = m_strRealm;
5291  info.digestInfo = m_strAuthorization;
5292  }
5293  else if ( m_responseCode == 407 )
5294  {
5295  info.username = m_proxyURL.user();
5296  info.password = m_proxyURL.pass();
5297  info.realmValue = m_strProxyRealm;
5298  info.digestInfo = m_strProxyAuthorization;
5299  }
5300  }
5301  }
5302 
5303  if ( prompt )
5304  {
5305  switch ( m_responseCode )
5306  {
5307  case 401:
5308  errorMsg = i18n("Authentication Failed.");
5309  break;
5310  case 407:
5311  errorMsg = i18n("Proxy Authentication Failed.");
5312  break;
5313  default:
5314  break;
5315  }
5316  }
5317  }
5318  else
5319  {
5320  // At this point we know more details, so use it to find
5321  // out if we have a cached version and avoid a re-prompt!
5322  // We also do not use verify path unlike the pre-emptive
5323  // requests because we already know the realm value...
5324 
5325  if (m_bProxyAuthValid)
5326  {
5327  // Reset cached proxy auth
5328  m_bProxyAuthValid = false;
5329  KURL proxy ( config()->readEntry("UseProxy") );
5330  m_proxyURL.setUser(proxy.user());
5331  m_proxyURL.setPass(proxy.pass());
5332  }
5333 
5334  info.verifyPath = false;
5335  if ( m_responseCode == 407 )
5336  {
5337  info.url = m_proxyURL;
5338  info.username = m_proxyURL.user();
5339  info.password = m_proxyURL.pass();
5340  info.realmValue = m_strProxyRealm;
5341  info.digestInfo = m_strProxyAuthorization;
5342  }
5343  else
5344  {
5345  info.url = m_request.url;
5346  info.username = m_request.user;
5347  info.password = m_request.passwd;
5348  info.realmValue = m_strRealm;
5349  info.digestInfo = m_strAuthorization;
5350  }
5351 
5352  // If either username or password is not supplied
5353  // with the request, check the password cache.
5354  if ( info.username.isNull() ||
5355  info.password.isNull() )
5356  result = checkCachedAuthentication( info );
5357 
5358  if ( Authentication == AUTH_Digest )
5359  {
5360  TQString auth;
5361 
5362  if (m_responseCode == 401)
5363  auth = m_strAuthorization;
5364  else
5365  auth = m_strProxyAuthorization;
5366 
5367  int pos = auth.find("stale", 0, false);
5368  if ( pos != -1 )
5369  {
5370  pos += 5;
5371  int len = auth.length();
5372  while( pos < len && (auth[pos] == ' ' || auth[pos] == '=') ) pos++;
5373  if ( pos < len && auth.find("true", pos, false) != -1 )
5374  {
5375  info.digestInfo = (m_responseCode == 401) ? m_strAuthorization : m_strProxyAuthorization;
5376  kdDebug(7113) << "(" << m_pid << ") Just a stale nonce value! "
5377  << "Retrying using the new nonce sent..." << endl;
5378  }
5379  }
5380  }
5381  }
5382 
5383  if (!result )
5384  {
5385  // Do not prompt if the username & password
5386  // is already supplied and the login attempt
5387  // did not fail before.
5388  if ( !repeatFailure &&
5389  !info.username.isNull() &&
5390  !info.password.isNull() )
5391  result = true;
5392  else
5393  {
5394  if (Authentication == AUTH_Negotiate)
5395  {
5396  if (!repeatFailure)
5397  result = true;
5398  }
5399  else if ( m_request.disablePassDlg == false )
5400  {
5401  kdDebug( 7113 ) << "(" << m_pid << ") Prompting the user for authorization..." << endl;
5402  promptInfo( info );
5403  result = openPassDlg( info, errorMsg );
5404  }
5405  }
5406  }
5407 
5408  if ( result )
5409  {
5410  switch (m_responseCode)
5411  {
5412  case 401: // Request-Authentication
5413  m_request.user = info.username;
5414  m_request.passwd = info.password;
5415  m_strRealm = info.realmValue;
5416  m_strAuthorization = info.digestInfo;
5417  break;
5418  case 407: // Proxy-Authentication
5419  m_proxyURL.setUser( info.username );
5420  m_proxyURL.setPass( info.password );
5421  m_strProxyRealm = info.realmValue;
5422  m_strProxyAuthorization = info.digestInfo;
5423  break;
5424  default:
5425  break;
5426  }
5427  return true;
5428  }
5429 
5430  if (m_request.bErrorPage)
5431  errorPage();
5432  else
5433  error( ERR_USER_CANCELED, TQString::null );
5434  return false;
5435 }
5436 
5437 void HTTPProtocol::saveAuthorization()
5438 {
5439  AuthInfo info;
5440  if ( m_prevResponseCode == 407 )
5441  {
5442  if (!m_bUseProxy)
5443  return;
5444  m_bProxyAuthValid = true;
5445  info.url = m_proxyURL;
5446  info.username = m_proxyURL.user();
5447  info.password = m_proxyURL.pass();
5448  info.realmValue = m_strProxyRealm;
5449  info.digestInfo = m_strProxyAuthorization;
5450  cacheAuthentication( info );
5451  }
5452  else
5453  {
5454  info.url = m_request.url;
5455  info.username = m_request.user;
5456  info.password = m_request.passwd;
5457  info.realmValue = m_strRealm;
5458  info.digestInfo = m_strAuthorization;
5459  cacheAuthentication( info );
5460  }
5461 }
5462 
5463 #ifdef HAVE_LIBGSSAPI
5464 TQCString HTTPProtocol::gssError( int major_status, int minor_status )
5465 {
5466  OM_uint32 new_status;
5467  OM_uint32 msg_ctx = 0;
5468  gss_buffer_desc major_string;
5469  gss_buffer_desc minor_string;
5470  OM_uint32 ret;
5471  TQCString errorstr;
5472 
5473  errorstr = "";
5474 
5475  do {
5476  ret = gss_display_status(&new_status, major_status, GSS_C_GSS_CODE, GSS_C_NULL_OID, &msg_ctx, &major_string);
5477  errorstr += (const char *)major_string.value;
5478  errorstr += " ";
5479  ret = gss_display_status(&new_status, minor_status, GSS_C_MECH_CODE, GSS_C_NULL_OID, &msg_ctx, &minor_string);
5480  errorstr += (const char *)minor_string.value;
5481  errorstr += " ";
5482  } while (!GSS_ERROR(ret) && msg_ctx != 0);
5483 
5484  return errorstr;
5485 }
5486 
5487 TQString HTTPProtocol::createNegotiateAuth()
5488 {
5489  TQString auth;
5490  TQCString servicename;
5491  TQByteArray input;
5492  OM_uint32 major_status, minor_status;
5493  OM_uint32 req_flags = 0;
5494  gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER;
5495  gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER;
5496  gss_name_t server;
5497  gss_ctx_id_t ctx;
5498  gss_OID mech_oid;
5499  static gss_OID_desc krb5_oid_desc = {9, (void *) "\x2a\x86\x48\x86\xf7\x12\x01\x02\x02"};
5500  static gss_OID_desc spnego_oid_desc = {6, (void *) "\x2b\x06\x01\x05\x05\x02"};
5501  int found = 0;
5502  unsigned int i;
5503  gss_OID_set mech_set;
5504  gss_OID tmp_oid;
5505 
5506  ctx = GSS_C_NO_CONTEXT;
5507  mech_oid = &krb5_oid_desc;
5508 
5509  // see whether we can use the SPNEGO mechanism
5510  major_status = gss_indicate_mechs(&minor_status, &mech_set);
5511  if (GSS_ERROR(major_status)) {
5512  kdDebug(7113) << "(" << m_pid << ") gss_indicate_mechs failed: " << gssError(major_status, minor_status) << endl;
5513  } else {
5514  for (i=0; i<mech_set->count && !found; i++) {
5515  tmp_oid = &mech_set->elements[i];
5516  if (tmp_oid->length == spnego_oid_desc.length &&
5517  !memcmp(tmp_oid->elements, spnego_oid_desc.elements, tmp_oid->length)) {
5518  kdDebug(7113) << "(" << m_pid << ") createNegotiateAuth: found SPNEGO mech" << endl;
5519  found = 1;
5520  mech_oid = &spnego_oid_desc;
5521  break;
5522  }
5523  }
5524  gss_release_oid_set(&minor_status, &mech_set);
5525  }
5526 
5527  // the service name is "HTTP/f.q.d.n"
5528  servicename = "HTTP@";
5529  servicename += m_state.hostname.ascii();
5530 
5531  input_token.value = (void *)servicename.data();
5532  input_token.length = servicename.length() + 1;
5533 
5534  major_status = gss_import_name(&minor_status, &input_token,
5535  GSS_C_NT_HOSTBASED_SERVICE, &server);
5536 
5537  input_token.value = NULL;
5538  input_token.length = 0;
5539 
5540  if (GSS_ERROR(major_status)) {
5541  kdDebug(7113) << "(" << m_pid << ") gss_import_name failed: " << gssError(major_status, minor_status) << endl;
5542  // reset the auth string so that subsequent methods aren't confused
5543  m_strAuthorization = TQString::null;
5544  return TQString::null;
5545  }
5546 
5547  major_status = gss_init_sec_context(&minor_status, GSS_C_NO_CREDENTIAL,
5548  &ctx, server, mech_oid,
5549  req_flags, GSS_C_INDEFINITE,
5550  GSS_C_NO_CHANNEL_BINDINGS,
5551  GSS_C_NO_BUFFER, NULL, &output_token,
5552  NULL, NULL);
5553 
5554 
5555  if (GSS_ERROR(major_status) || (output_token.length == 0)) {
5556  kdDebug(7113) << "(" << m_pid << ") gss_init_sec_context failed: " << gssError(major_status, minor_status) << endl;
5557  gss_release_name(&minor_status, &server);
5558  if (ctx != GSS_C_NO_CONTEXT) {
5559  gss_delete_sec_context(&minor_status, &ctx, GSS_C_NO_BUFFER);
5560  ctx = GSS_C_NO_CONTEXT;
5561  }
5562  // reset the auth string so that subsequent methods aren't confused
5563  m_strAuthorization = TQString::null;
5564  return TQString::null;
5565  }
5566 
5567  input.duplicate((const char *)output_token.value, output_token.length);
5568  auth = "Authorization: Negotiate ";
5569  auth += KCodecs::base64Encode( input );
5570  auth += "\r\n";
5571 
5572  // free everything
5573  gss_release_name(&minor_status, &server);
5574  if (ctx != GSS_C_NO_CONTEXT) {
5575  gss_delete_sec_context(&minor_status, &ctx, GSS_C_NO_BUFFER);
5576  ctx = GSS_C_NO_CONTEXT;
5577  }
5578  gss_release_buffer(&minor_status, &output_token);
5579 
5580  return auth;
5581 }
5582 #else
5583 
5584 // Dummy
5585 TQCString HTTPProtocol::gssError( int, int )
5586 {
5587  return "";
5588 }
5589 
5590 // Dummy
5591 TQString HTTPProtocol::createNegotiateAuth()
5592 {
5593  return TQString::null;
5594 }
5595 #endif
5596 
5597 TQString HTTPProtocol::createNTLMAuth( bool isForProxy )
5598 {
5599  uint len;
5600  TQString auth, user, domain, passwd;
5601  TQCString strauth;
5602  TQByteArray buf;
5603 
5604  if ( isForProxy )
5605  {
5606  auth = "Proxy-Connection: Keep-Alive\r\n";
5607  auth += "Proxy-Authorization: NTLM ";
5608  user = m_proxyURL.user();
5609  passwd = m_proxyURL.pass();
5610  strauth = m_strProxyAuthorization.latin1();
5611  len = m_strProxyAuthorization.length();
5612  }
5613  else
5614  {
5615  auth = "Authorization: NTLM ";
5616  user = m_state.user;
5617  passwd = m_state.passwd;
5618  strauth = m_strAuthorization.latin1();
5619  len = m_strAuthorization.length();
5620  }
5621  if ( user.contains('\\') ) {
5622  domain = user.section( '\\', 0, 0);
5623  user = user.section( '\\', 1 );
5624  }
5625 
5626  kdDebug(7113) << "(" << m_pid << ") NTLM length: " << len << endl;
5627  if ( user.isEmpty() || passwd.isEmpty() || len < 4 )
5628  return TQString::null;
5629 
5630  if ( len > 4 )
5631  {
5632  // create a response
5633  TQByteArray challenge;
5634  KCodecs::base64Decode( strauth.right( len - 5 ), challenge );
5635  KNTLM::getAuth( buf, challenge, user, passwd, domain,
5636  KNetwork::KResolver::localHostName(), false, false );
5637  }
5638  else
5639  {
5640  KNTLM::getNegotiate( buf );
5641  }
5642 
5643  // remove the challenge to prevent reuse
5644  if ( isForProxy )
5645  m_strProxyAuthorization = "NTLM";
5646  else
5647  m_strAuthorization = "NTLM";
5648 
5649  auth += KCodecs::base64Encode( buf );
5650  auth += "\r\n";
5651 
5652  return auth;
5653 }
5654 
5655 TQString HTTPProtocol::createBasicAuth( bool isForProxy )
5656 {
5657  TQString auth;
5658  TQCString user, passwd;
5659  if ( isForProxy )
5660  {
5661  auth = "Proxy-Authorization: Basic ";
5662  user = m_proxyURL.user().latin1();
5663  passwd = m_proxyURL.pass().latin1();
5664  }
5665  else
5666  {
5667  auth = "Authorization: Basic ";
5668  user = m_state.user.latin1();
5669  passwd = m_state.passwd.latin1();
5670  }
5671 
5672  if ( user.isEmpty() )
5673  user = "";
5674  if ( passwd.isEmpty() )
5675  passwd = "";
5676 
5677  user += ':';
5678  user += passwd;
5679  auth += KCodecs::base64Encode( user );
5680  auth += "\r\n";
5681 
5682  return auth;
5683 }
5684 
5685 void HTTPProtocol::calculateResponse( DigestAuthInfo& info, TQCString& Response )
5686 {
5687  KMD5 md;
5688  TQCString HA1;
5689  TQCString HA2;
5690 
5691  // Calculate H(A1)
5692  TQCString authStr = info.username;
5693  authStr += ':';
5694  authStr += info.realm;
5695  authStr += ':';
5696  authStr += info.password;
5697  md.update( authStr );
5698 
5699  if ( info.algorithm.lower() == "md5-sess" )
5700  {
5701  authStr = md.hexDigest();
5702  authStr += ':';
5703  authStr += info.nonce;
5704  authStr += ':';
5705  authStr += info.cnonce;
5706  md.reset();
5707  md.update( authStr );
5708  }
5709  HA1 = md.hexDigest();
5710 
5711  kdDebug(7113) << "(" << m_pid << ") calculateResponse(): A1 => " << HA1 << endl;
5712 
5713  // Calcualte H(A2)
5714  authStr = info.method;
5715  authStr += ':';
5716  authStr += m_request.url.encodedPathAndQuery(0, true).latin1();
5717  if ( info.qop == "auth-int" )
5718  {
5719  authStr += ':';
5720  authStr += info.entityBody;
5721  }
5722  md.reset();
5723  md.update( authStr );
5724  HA2 = md.hexDigest();
5725 
5726  kdDebug(7113) << "(" << m_pid << ") calculateResponse(): A2 => "
5727  << HA2 << endl;
5728 
5729  // Calcualte the response.
5730  authStr = HA1;
5731  authStr += ':';
5732  authStr += info.nonce;
5733  authStr += ':';
5734  if ( !info.qop.isEmpty() )
5735  {
5736  authStr += info.nc;
5737  authStr += ':';
5738  authStr += info.cnonce;
5739  authStr += ':';
5740  authStr += info.qop;
5741  authStr += ':';
5742  }
5743  authStr += HA2;
5744  md.reset();
5745  md.update( authStr );
5746  Response = md.hexDigest();
5747 
5748  kdDebug(7113) << "(" << m_pid << ") calculateResponse(): Response => "
5749  << Response << endl;
5750 }
5751 
5752 TQString HTTPProtocol::createDigestAuth ( bool isForProxy )
5753 {
5754  const char *p;
5755 
5756  TQString auth;
5757  TQCString opaque;
5758  TQCString Response;
5759 
5760  DigestAuthInfo info;
5761 
5762  opaque = "";
5763  if ( isForProxy )
5764  {
5765  auth = "Proxy-Authorization: Digest ";
5766  info.username = m_proxyURL.user().latin1();
5767  info.password = m_proxyURL.pass().latin1();
5768  p = m_strProxyAuthorization.latin1();
5769  }
5770  else
5771  {
5772  auth = "Authorization: Digest ";
5773  info.username = m_state.user.latin1();
5774  info.password = m_state.passwd.latin1();
5775  p = m_strAuthorization.latin1();
5776  }
5777  if (!p || !*p)
5778  return TQString::null;
5779 
5780  p += 6; // Skip "Digest"
5781 
5782  if ( info.username.isEmpty() || info.password.isEmpty() || !p )
5783  return TQString::null;
5784 
5785  // info.entityBody = p; // FIXME: send digest of data for POST action ??
5786  info.realm = "";
5787  info.algorithm = "MD5";
5788  info.nonce = "";
5789  info.qop = "";
5790 
5791  // cnonce is recommended to contain about 64 bits of entropy
5792  info.cnonce = TDEApplication::randomString(16).latin1();
5793 
5794  // HACK: Should be fixed according to RFC 2617 section 3.2.2
5795  info.nc = "00000001";
5796 
5797  // Set the method used...
5798  switch ( m_request.method )
5799  {
5800  case HTTP_GET:
5801  info.method = "GET";
5802  break;
5803  case HTTP_PUT:
5804  info.method = "PUT";
5805  break;
5806  case HTTP_POST:
5807  info.method = "POST";
5808  break;
5809  case HTTP_HEAD:
5810  info.method = "HEAD";
5811  break;
5812  case HTTP_DELETE:
5813  info.method = "DELETE";
5814  break;
5815  case DAV_PROPFIND:
5816  info.method = "PROPFIND";
5817  break;
5818  case DAV_PROPPATCH:
5819  info.method = "PROPPATCH";
5820  break;
5821  case DAV_MKCOL:
5822  info.method = "MKCOL";
5823  break;
5824  case DAV_COPY:
5825  info.method = "COPY";
5826  break;
5827  case DAV_MOVE:
5828  info.method = "MOVE";
5829  break;
5830  case DAV_LOCK:
5831  info.method = "LOCK";
5832  break;
5833  case DAV_UNLOCK:
5834  info.method = "UNLOCK";
5835  break;
5836  case DAV_SEARCH:
5837  info.method = "SEARCH";
5838  break;
5839  case DAV_SUBSCRIBE:
5840  info.method = "SUBSCRIBE";
5841  break;
5842  case DAV_UNSUBSCRIBE:
5843  info.method = "UNSUBSCRIBE";
5844  break;
5845  case DAV_POLL:
5846  info.method = "POLL";
5847  break;
5848  default:
5849  error( ERR_UNSUPPORTED_ACTION, i18n("Unsupported method: authentication will fail. Please submit a bug report."));
5850  break;
5851  }
5852 
5853  // Parse the Digest response....
5854  while (*p)
5855  {
5856  int i = 0;
5857  while ( (*p == ' ') || (*p == ',') || (*p == '\t')) { p++; }
5858  if (strncasecmp(p, "realm=", 6 )==0)
5859  {
5860  p+=6;
5861  while ( *p == '"' ) p++; // Go past any number of " mark(s) first
5862  while ( p[i] != '"' ) i++; // Read everything until the last " mark
5863  info.realm = TQCString( p, i+1 );
5864  }
5865  else if (strncasecmp(p, "algorith=", 9)==0)
5866  {
5867  p+=9;
5868  while ( *p == '"' ) p++; // Go past any number of " mark(s) first
5869  while ( ( p[i] != '"' ) && ( p[i] != ',' ) && ( p[i] != '\0' ) ) i++;
5870  info.algorithm = TQCString(p, i+1);
5871  }
5872  else if (strncasecmp(p, "algorithm=", 10)==0)
5873  {
5874  p+=10;
5875  while ( *p == '"' ) p++; // Go past any " mark(s) first
5876  while ( ( p[i] != '"' ) && ( p[i] != ',' ) && ( p[i] != '\0' ) ) i++;
5877  info.algorithm = TQCString(p,i+1);
5878  }
5879  else if (strncasecmp(p, "domain=", 7)==0)
5880  {
5881  p+=7;
5882  while ( *p == '"' ) p++; // Go past any " mark(s) first
5883  while ( p[i] != '"' ) i++; // Read everything until the last " mark
5884  int pos;
5885  int idx = 0;
5886  TQCString uri = TQCString(p,i+1);
5887  do
5888  {
5889  pos = uri.find( ' ', idx );
5890  if ( pos != -1 )
5891  {
5892  KURL u (m_request.url, uri.mid(idx, pos-idx));
5893  if (u.isValid ())
5894  info.digestURI.append( u.url().latin1() );
5895  }
5896  else
5897  {
5898  KURL u (m_request.url, uri.mid(idx, uri.length()-idx));
5899  if (u.isValid ())
5900  info.digestURI.append( u.url().latin1() );
5901  }
5902  idx = pos+1;
5903  } while ( pos != -1 );
5904  }
5905  else if (strncasecmp(p, "nonce=", 6)==0)
5906  {
5907  p+=6;
5908  while ( *p == '"' ) p++; // Go past any " mark(s) first
5909  while ( p[i] != '"' ) i++; // Read everything until the last " mark
5910  info.nonce = TQCString(p,i+1);
5911  }
5912  else if (strncasecmp(p, "opaque=", 7)==0)
5913  {
5914  p+=7;
5915  while ( *p == '"' ) p++; // Go past any " mark(s) first
5916  while ( p[i] != '"' ) i++; // Read everything until the last " mark
5917  opaque = TQCString(p,i+1);
5918  }
5919  else if (strncasecmp(p, "qop=", 4)==0)
5920  {
5921  p+=4;
5922  while ( *p == '"' ) p++; // Go past any " mark(s) first
5923  while ( p[i] != '"' ) i++; // Read everything until the last " mark
5924  info.qop = TQCString(p,i+1);
5925  }
5926  p+=(i+1);
5927  }
5928 
5929  if (info.realm.isEmpty() || info.nonce.isEmpty())
5930  return TQString::null;
5931 
5932  // If the "domain" attribute was not specified and the current response code
5933  // is authentication needed, add the current request url to the list over which
5934  // this credential can be automatically applied.
5935  if (info.digestURI.isEmpty() && (m_responseCode == 401 || m_responseCode == 407))
5936  info.digestURI.append (m_request.url.url().latin1());
5937  else
5938  {
5939  // Verify whether or not we should send a cached credential to the
5940  // server based on the stored "domain" attribute...
5941  bool send = true;
5942 
5943  // Determine the path of the request url...
5944  TQString requestPath = m_request.url.directory(false, false);
5945  if (requestPath.isEmpty())
5946  requestPath = "/";
5947 
5948  int count = info.digestURI.count();
5949 
5950  for (int i = 0; i < count; i++ )
5951  {
5952  KURL u ( info.digestURI.at(i) );
5953 
5954  send &= (m_request.url.protocol().lower() == u.protocol().lower());
5955  send &= (m_request.hostname.lower() == u.host().lower());
5956 
5957  if (m_request.port > 0 && u.port() > 0)
5958  send &= (m_request.port == u.port());
5959 
5960  TQString digestPath = u.directory (false, false);
5961  if (digestPath.isEmpty())
5962  digestPath = "/";
5963 
5964  send &= (requestPath.startsWith(digestPath));
5965 
5966  if (send)
5967  break;
5968  }
5969 
5970  kdDebug(7113) << "(" << m_pid << ") createDigestAuth(): passed digest "
5971  "authentication credential test: " << send << endl;
5972 
5973  if (!send)
5974  return TQString::null;
5975  }
5976 
5977  kdDebug(7113) << "(" << m_pid << ") RESULT OF PARSING:" << endl;
5978  kdDebug(7113) << "(" << m_pid << ") algorithm: " << info.algorithm << endl;
5979  kdDebug(7113) << "(" << m_pid << ") realm: " << info.realm << endl;
5980  kdDebug(7113) << "(" << m_pid << ") nonce: " << info.nonce << endl;
5981  kdDebug(7113) << "(" << m_pid << ") opaque: " << opaque << endl;
5982  kdDebug(7113) << "(" << m_pid << ") qop: " << info.qop << endl;
5983 
5984  // Calculate the response...
5985  calculateResponse( info, Response );
5986 
5987  auth += "username=\"";
5988  auth += info.username;
5989 
5990  auth += "\", realm=\"";
5991  auth += info.realm;
5992  auth += "\"";
5993 
5994  auth += ", nonce=\"";
5995  auth += info.nonce;
5996 
5997  auth += "\", uri=\"";
5998  auth += m_request.url.encodedPathAndQuery(0, true);
5999 
6000  auth += "\", algorithm=\"";
6001  auth += info.algorithm;
6002  auth +="\"";
6003 
6004  if ( !info.qop.isEmpty() )
6005  {
6006  auth += ", qop=\"";
6007  auth += info.qop;
6008  auth += "\", cnonce=\"";
6009  auth += info.cnonce;
6010  auth += "\", nc=";
6011  auth += info.nc;
6012  }
6013 
6014  auth += ", response=\"";
6015  auth += Response;
6016  if ( !opaque.isEmpty() )
6017  {
6018  auth += "\", opaque=\"";
6019  auth += opaque;
6020  }
6021  auth += "\"\r\n";
6022 
6023  return auth;
6024 }
6025 
6026 TQString HTTPProtocol::proxyAuthenticationHeader()
6027 {
6028  TQString header;
6029 
6030  // We keep proxy authentication locally until they are changed.
6031  // Thus, no need to check with the password manager for every
6032  // connection.
6033  if ( m_strProxyRealm.isEmpty() )
6034  {
6035  AuthInfo info;
6036  info.url = m_proxyURL;
6037  info.username = m_proxyURL.user();
6038  info.password = m_proxyURL.pass();
6039  info.verifyPath = true;
6040 
6041  // If the proxy URL already contains username
6042  // and password simply attempt to retrieve it
6043  // without prompting the user...
6044  if ( !info.username.isNull() && !info.password.isNull() )
6045  {
6046  if( m_strProxyAuthorization.isEmpty() )
6047  ProxyAuthentication = AUTH_None;
6048  else if( m_strProxyAuthorization.startsWith("Basic") )
6049  ProxyAuthentication = AUTH_Basic;
6050  else if( m_strProxyAuthorization.startsWith("NTLM") )
6051  ProxyAuthentication = AUTH_NTLM;
6052  else
6053  ProxyAuthentication = AUTH_Digest;
6054  }
6055  else
6056  {
6057  if ( checkCachedAuthentication(info) && !info.digestInfo.isEmpty() )
6058  {
6059  m_proxyURL.setUser( info.username );
6060  m_proxyURL.setPass( info.password );
6061  m_strProxyRealm = info.realmValue;
6062  m_strProxyAuthorization = info.digestInfo;
6063  if( m_strProxyAuthorization.startsWith("Basic") )
6064  ProxyAuthentication = AUTH_Basic;
6065  else if( m_strProxyAuthorization.startsWith("NTLM") )
6066  ProxyAuthentication = AUTH_NTLM;
6067  else
6068  ProxyAuthentication = AUTH_Digest;
6069  }
6070  else
6071  {
6072  ProxyAuthentication = AUTH_None;
6073  }
6074  }
6075  }
6076 
6077  /********* Only for debugging purpose... *********/
6078  if ( ProxyAuthentication != AUTH_None )
6079  {
6080  kdDebug(7113) << "(" << m_pid << ") Using Proxy Authentication: " << endl;
6081  kdDebug(7113) << "(" << m_pid << ") HOST= " << m_proxyURL.host() << endl;
6082  kdDebug(7113) << "(" << m_pid << ") PORT= " << m_proxyURL.port() << endl;
6083  kdDebug(7113) << "(" << m_pid << ") USER= " << m_proxyURL.user() << endl;
6084  kdDebug(7113) << "(" << m_pid << ") PASSWORD= [protected]" << endl;
6085  kdDebug(7113) << "(" << m_pid << ") REALM= " << m_strProxyRealm << endl;
6086  kdDebug(7113) << "(" << m_pid << ") EXTRA= " << m_strProxyAuthorization << endl;
6087  }
6088 
6089  switch ( ProxyAuthentication )
6090  {
6091  case AUTH_Basic:
6092  header += createBasicAuth( true );
6093  break;
6094  case AUTH_Digest:
6095  header += createDigestAuth( true );
6096  break;
6097  case AUTH_NTLM:
6098  if ( m_bFirstRequest ) header += createNTLMAuth( true );
6099  break;
6100  case AUTH_None:
6101  default:
6102  break;
6103  }
6104 
6105  return header;
6106 }
6107 
6108 #include "http.moc"

tdeioslave/http

Skip menu "tdeioslave/http"
  • Main Page
  • Alphabetical List
  • Class List
  • File List

tdeioslave/http

Skip menu "tdeioslave/http"
  • arts
  • dcop
  • dnssd
  • interfaces
  •   kspeech
  •     interface
  •     library
  •   tdetexteditor
  • kate
  • kded
  • kdoctools
  • kimgio
  • kjs
  • knewstuff
  • libtdemid
  • libtdescreensaver
  • tdeabc
  • tdecmshell
  • tdecore
  • tdefx
  • tdehtml
  • tdeinit
  • tdeio
  •   bookmarks
  •   httpfilter
  •   kpasswdserver
  •   kssl
  •   tdefile
  •   tdeio
  •   tdeioexec
  • tdeioslave
  •   http
  • tdemdi
  •   tdemdi
  • tdeparts
  • tdeprint
  • tderandr
  • tderesources
  • tdespell2
  • tdesu
  • tdeui
  • tdeunittest
  • tdeutils
  • tdewallet
Generated for tdeioslave/http by doxygen 1.8.3.1
This website is maintained by Timothy Pearson.