32 #include <sys/socket.h>
33 #include <netinet/in.h>
34 #include <netinet/tcp.h>
46 #include <tqdatetime.h>
47 #include <tqstringlist.h>
54 #include <tdelocale.h>
55 #include <tdeconfig.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>
70 #include "tdeio/ioslave_defaults.h"
71 #include "tdeio/http_slave_defaults.h"
73 #include "httpfilter.h"
78 #include <gssapi/gssapi.h>
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
91 #include <misc/tdentlm/tdentlm.h>
93 using namespace TDEIO;
96 KDE_EXPORT
int kdemain(
int argc,
char **argv);
99 int kdemain(
int argc,
char **argv )
101 TDELocale::setMainCatalogue(
"tdelibs");
102 TDEInstance instance(
"tdeio_http" );
103 ( void ) TDEGlobal::locale();
107 fprintf(stderr,
"Usage: tdeio_http protocol domain-socket1 domain-socket2\n");
111 HTTPProtocol slave(argv[1], argv[2], argv[3]);
112 slave.dispatchLoop();
118 static char * trimLead (
char *orig_string)
120 while (*orig_string ==
' ')
125 static bool isCrossDomainRequest(
const TQString& fqdn,
const TQString& originURL )
127 if (originURL ==
"true")
130 KURL url ( originURL );
133 TQString a = url.host();
141 TQStringList l1 = TQStringList::split(
'.', a);
142 TQStringList l2 = TQStringList::split(
'.', b);
144 while(l1.count() > l2.count())
147 while(l2.count() > l1.count())
150 while(l2.count() >= 2)
165 static TQString sanitizeCustomHTTPHeader(
const TQString& _header)
167 TQString sanitizedHeaders;
168 TQStringList headers = TQStringList::split(TQRegExp(
"[\r\n]"), _header);
170 for(TQStringList::Iterator it = headers.begin(); it != headers.end(); ++it)
172 TQString header = (*it).lower();
175 if (header.find(
':') == -1 ||
176 header.startsWith(
"host") ||
177 header.startsWith(
"via"))
180 sanitizedHeaders += (*it);
181 sanitizedHeaders +=
"\r\n";
184 return sanitizedHeaders.stripWhiteSpace();
188 #define NO_SIZE ((TDEIO::filesize_t) -1)
191 #define STRTOLL strtoll
193 #define STRTOLL strtol
199 HTTPProtocol::HTTPProtocol(
const TQCString &protocol,
const TQCString &pool,
200 const TQCString &app )
201 :TCPSlaveBase( 0, protocol , pool, app,
202 (protocol ==
"https" || protocol ==
"webdavs") )
204 m_requestQueue.setAutoDelete(
true);
207 m_bFirstRequest =
false;
208 m_bProxyAuthValid =
false;
213 m_protocol = protocol;
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;
223 setMultipleAuthCaching(
true );
224 reparseConfiguration();
227 HTTPProtocol::~HTTPProtocol()
232 void HTTPProtocol::reparseConfiguration()
234 kdDebug(7113) <<
"(" << m_pid <<
") HTTPProtocol::reparseConfiguration" << endl;
236 m_strProxyRealm = TQString::null;
237 m_strProxyAuthorization = TQString::null;
238 ProxyAuthentication = AUTH_None;
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;
246 m_iDefaultPort = DEFAULT_HTTP_PORT;
249 void HTTPProtocol::resetConnectionSettings()
255 m_lineCountUnget = 0;
256 m_iProxyAuthCount = 0;
260 void HTTPProtocol::resetResponseSettings()
263 m_redirectLocation = KURL();
267 m_responseHeader.clear();
268 m_qContentEncodings.clear();
269 m_qTransferEncodings.clear();
270 m_sContentMD5 = TQString::null;
271 m_strMimeType = TQString::null;
273 setMetaData(
"request-id", m_request.id);
276 void HTTPProtocol::resetSessionSettings()
280 KURL proxy ( config()->readEntry(
"UseProxy") );
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()) )
287 m_bProxyAuthValid =
false;
289 m_bUseProxy = m_proxyURL.isValid();
291 kdDebug(7113) <<
"(" << m_pid <<
") Using proxy: " << m_bUseProxy <<
292 " URL: " << m_proxyURL.url() <<
293 " Realm: " << m_strProxyRealm << endl;
296 m_bPersistentProxyConnection = config()->readBoolEntry(
"PersistentProxyConnection",
false);
297 kdDebug(7113) <<
"(" << m_pid <<
") Enable Persistent Proxy Connection: "
298 << m_bPersistentProxyConnection << endl;
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");
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;
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" ) )
317 KURL referrerURL ( metaData(
"referrer") );
318 if (referrerURL.isValid())
321 TQString protocol = referrerURL.protocol();
322 if (protocol.startsWith(
"webdav"))
324 protocol.replace(0, 6,
"http");
325 referrerURL.setProtocol(protocol);
328 if (protocol.startsWith(
"http"))
330 referrerURL.setRef(TQString::null);
331 referrerURL.setUser(TQString::null);
332 referrerURL.setPass(TQString::null);
333 m_request.referrer = referrerURL.url();
338 if ( config()->readBoolEntry(
"SendLanguageSettings",
true) )
340 m_request.charsets = config()->readEntry(
"Charsets",
"iso-8859-1" );
342 if ( !m_request.charsets.isEmpty() )
343 m_request.charsets += DEFAULT_PARTIAL_CHARSET_HEADER;
345 m_request.languages = config()->readEntry(
"Languages", DEFAULT_LANGUAGE_HEADER );
349 m_request.charsets = TQString::null;
350 m_request.languages = TQString::null;
354 TQString resumeOffset = metaData(
"resume");
355 if ( !resumeOffset.isEmpty() )
356 m_request.offset = resumeOffset.toInt();
358 m_request.offset = 0;
360 m_request.disablePassDlg = config()->readBoolEntry(
"DisablePassDlg",
false);
361 m_request.allowCompressedPage = config()->readBoolEntry(
"AllowCompressedPage",
true);
362 m_request.id = metaData(
"request-id");
365 if ( config()->readBoolEntry(
"SendUserAgent",
true) )
366 m_request.userAgent = metaData(
"UserAgent");
368 m_request.userAgent = TQString::null;
373 if ( m_request.bUseCache )
377 if ( m_bIsSSL && m_bUseProxy && m_proxyURL.protocol() !=
"https" &&
378 m_proxyURL.protocol() !=
"webdavs")
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;
387 m_bNeedTunnel =
false;
388 setRealHost( TQString::null);
392 m_prevResponseCode = 0;
394 m_strRealm = TQString::null;
395 m_strAuthorization = TQString::null;
396 Authentication = AUTH_None;
399 m_proxyConnTimeout = proxyConnectTimeout();
400 m_remoteConnTimeout = connectTimeout();
401 m_remoteRespTimeout = responseTimeout();
407 setMetaData(
"referrer", m_request.referrer);
413 m_keepAliveTimeout = 0;
414 m_bUnauthorized =
false;
424 m_bFirstRequest =
false;
427 void HTTPProtocol::setHost(
const TQString& host,
int port,
428 const TQString& user,
const TQString& pass )
431 if ( m_request.hostname != host )
432 m_davHostOk = m_davHostUnsupported =
false;
435 if (host.find(
':') == -1)
437 m_request.hostname = host;
438 m_request.encoded_hostname = KIDNA::toAscii(host);
442 m_request.hostname = host;
443 int pos = host.find(
'%');
445 m_request.encoded_hostname =
'[' + host +
']';
448 m_request.encoded_hostname =
'[' + host.left(pos) +
']';
450 m_request.port = (port == 0) ? m_iDefaultPort : port;
451 m_request.user = user;
452 m_request.passwd = pass;
454 m_bIsTunneled =
false;
456 kdDebug(7113) <<
"(" << m_pid <<
") Hostname is now: " << m_request.hostname <<
457 " (" << m_request.encoded_hostname <<
")" <<endl;
460 bool HTTPProtocol::checkRequestURL(
const KURL& u )
462 kdDebug (7113) <<
"(" << m_pid <<
") HTTPProtocol::checkRequestURL: " << u.url() << endl;
466 if (m_request.hostname.isEmpty())
468 error( TDEIO::ERR_UNKNOWN_HOST, i18n(
"No host specified."));
472 if (u.path().isEmpty())
481 if ( m_protocol != u.protocol().latin1() )
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;
491 resetSessionSettings();
495 void HTTPProtocol::retrieveContent(
bool dataInternal )
497 kdDebug (7113) <<
"(" << m_pid <<
") HTTPProtocol::retrieveContent " << endl;
498 if ( !retrieveHeader(
false ) )
505 if ( !readBody( dataInternal ) && m_bError )
509 httpClose(m_bKeepAlive);
515 if ((m_responseCode == 204) &&
516 ((m_request.method == HTTP_GET) || (m_request.method == HTTP_POST)))
517 error(ERR_NO_CONTENT,
"");
523 bool HTTPProtocol::retrieveHeader(
bool close_connection )
525 kdDebug (7113) <<
"(" << m_pid <<
") HTTPProtocol::retrieveHeader " << endl;
531 resetResponseSettings();
539 kdDebug(7113) <<
"(" << m_pid <<
") Re-establishing SSL tunnel..." << endl;
540 httpCloseConnection();
547 kdDebug(7113) <<
"(" << m_pid <<
") Previous Response: "
548 << m_prevResponseCode << endl;
549 kdDebug(7113) <<
"(" << m_pid <<
") Current Response: "
550 << m_responseCode << endl;
552 if (isSSLTunnelEnabled() && m_bIsSSL && !m_bUnauthorized && !m_bError)
555 if ( m_responseCode < 400 )
557 kdDebug(7113) <<
"(" << m_pid <<
") Unset tunneling flag!" << endl;
558 setEnableSSLTunnel(
false );
559 m_bIsTunneled =
true;
561 m_responseCode = m_prevResponseCode;
566 if ( !m_request.bErrorPage )
568 kdDebug(7113) <<
"(" << m_pid <<
") Sending an error message!" << endl;
569 error( ERR_UNKNOWN_PROXY_HOST, m_proxyURL.host() );
573 kdDebug(7113) <<
"(" << m_pid <<
") Sending an error page!" << endl;
577 if (m_responseCode < 400 && (m_prevResponseCode == 401 ||
578 m_prevResponseCode == 407))
585 if (!m_bufPOST.isEmpty())
588 kdDebug(7113) <<
"(" << m_pid <<
") HTTP::retreiveHeader: Cleared POST "
592 if ( close_connection )
594 httpClose(m_bKeepAlive);
601 void HTTPProtocol::stat(
const KURL& url)
603 kdDebug(7113) <<
"(" << m_pid <<
") HTTPProtocol::stat " << url.prettyURL()
606 if ( !checkRequestURL( url ) )
609 if ( m_protocol !=
"webdav" && m_protocol !=
"webdavs" )
611 TQString statSide = metaData(TQString::fromLatin1(
"statSide"));
612 if ( statSide !=
"source" )
615 error( ERR_DOES_NOT_EXIST, url.prettyURL() );
622 atom.m_uds = TDEIO::UDS_NAME;
623 atom.m_str = url.fileName();
624 entry.append( atom );
626 atom.m_uds = TDEIO::UDS_FILE_TYPE;
627 atom.m_long = S_IFREG;
628 entry.append( atom );
630 atom.m_uds = TDEIO::UDS_ACCESS;
631 atom.m_long = S_IRUSR | S_IRGRP | S_IROTH;
632 entry.append( atom );
642 void HTTPProtocol::listDir(
const KURL& url )
644 kdDebug(7113) <<
"(" << m_pid <<
") HTTPProtocol::listDir " << url.url()
647 if ( !checkRequestURL( url ) )
650 if (!url.protocol().startsWith(
"webdav")) {
651 error(ERR_UNSUPPORTED_ACTION, url.prettyURL());
655 davStatList( url,
false );
658 void HTTPProtocol::davSetRequest(
const TQCString& requestXML )
661 m_bufPOST = requestXML;
663 if (m_bufPOST.size())
664 m_bufPOST.truncate( m_bufPOST.size() - 1 );
667 void HTTPProtocol::davStatList(
const KURL& url,
bool stat )
677 TQString query = metaData(
"davSearchQuery");
678 if ( !query.isEmpty() )
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" );
685 davSetRequest( request );
689 request =
"<?xml version=\"1.0\" encoding=\"utf-8\" ?>"
690 "<D:propfind xmlns:D=\"DAV:\">";
693 if ( hasMetaData(
"davRequestResponse" ) )
694 request += metaData(
"davRequestResponse" ).utf8();
697 request +=
"<D:prop>"
699 "<D:getcontentlength/>"
702 "<D:getcontentlanguage/>"
703 "<D:getcontenttype/>"
705 "<D:getlastmodified/>"
712 request +=
"</D:propfind>";
714 davSetRequest( request );
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;
724 m_request.url.adjustPath(+1);
726 retrieveContent(
true );
734 TQDomDocument multiResponse;
735 multiResponse.setContent( m_bufWebDavData,
true );
737 bool hasResponse =
false;
739 for ( TQDomNode n = multiResponse.documentElement().firstChild();
740 !n.isNull(); n = n.nextSibling())
742 TQDomElement thisResponse = n.toElement();
743 if (thisResponse.isNull())
748 TQDomElement href = thisResponse.namedItem(
"href" ).toElement();
749 if ( !href.isNull() )
753 TQString urlStr = href.text();
755 int encoding = remoteEncoding()->encodingMib();
756 if ((encoding == 106) && (!KStringHandler::isUtf8(KURL::decode_string(urlStr, 4).latin1())))
759 TQUrl::decode(urlStr);
763 KURL thisURL ( urlStr, encoding );
765 atom.m_uds = TDEIO::UDS_NAME;
767 if ( thisURL.isValid() ) {
769 if ( !stat && thisURL.path(+1).length() == url.path(+1).length() )
772 atom.m_str = thisURL.fileName();
775 atom.m_str = href.text();
778 entry.append( atom );
780 TQDomNodeList propstats = thisResponse.elementsByTagName(
"propstat" );
782 davParsePropstats( propstats, entry );
793 listEntry( entry,
false );
798 kdDebug(7113) <<
"Error: no URL contained in response to PROPFIND on "
799 << url.prettyURL() << endl;
803 if ( stat || !hasResponse )
805 error( ERR_DOES_NOT_EXIST, url.prettyURL() );
809 listEntry( entry,
true );
814 void HTTPProtocol::davGeneric(
const KURL& url, TDEIO::HTTP_METHOD method )
816 kdDebug(7113) <<
"(" << m_pid <<
") HTTPProtocol::davGeneric " << url.url()
819 if ( !checkRequestURL( url ) )
827 m_request.method = method;
828 m_request.query = TQString::null;
829 m_request.cache = CC_Reload;
830 m_request.doProxy = m_bUseProxy;
832 retrieveContent(
false );
835 int HTTPProtocol::codeFromResponse(
const TQString& response )
837 int firstSpace = response.find(
' ' );
838 int secondSpace = response.find(
' ', firstSpace + 1 );
839 return response.mid( firstSpace + 1, secondSpace - firstSpace - 1 ).toInt();
842 void HTTPProtocol::davParsePropstats(
const TQDomNodeList& propstats, UDSEntry& entry )
846 bool foundExecutable =
false;
847 bool isDirectory =
false;
849 uint supportedLockCount = 0;
851 for ( uint i = 0; i < propstats.count(); i++)
853 TQDomElement propstat = propstats.item(i).toElement();
855 TQDomElement status = propstat.namedItem(
"status" ).toElement();
856 if ( status.isNull() )
859 kdDebug(7113) <<
"Error, no status code in this propstat" << endl;
863 int code = codeFromResponse( status.text() );
867 kdDebug(7113) <<
"Warning: status code " << code <<
" (this may mean that some properties are unavailable" << endl;
871 TQDomElement prop = propstat.namedItem(
"prop" ).toElement();
874 kdDebug(7113) <<
"Error: no prop segment in this propstat." << endl;
878 if ( hasMetaData(
"davRequestResponse" ) )
880 atom.m_uds = TDEIO::UDS_XML_PROPERTIES;
882 doc.appendChild(prop);
883 atom.m_str = doc.toString();
884 entry.append( atom );
887 for ( TQDomNode n = prop.firstChild(); !n.isNull(); n = n.nextSibling() )
889 TQDomElement
property = n.toElement();
890 if (property.isNull())
893 if ( property.namespaceURI() !=
"DAV:" )
899 if ( property.tagName() ==
"creationdate" )
902 atom.m_uds = TDEIO::UDS_CREATION_TIME;
903 atom.m_long = parseDateTime( property.text(),
property.attribute(
"dt") );
904 entry.append( atom );
906 else if ( property.tagName() ==
"getcontentlength" )
909 atom.m_uds = TDEIO::UDS_SIZE;
910 atom.m_long =
property.text().toULong();
911 entry.append( atom );
913 else if ( property.tagName() ==
"displayname" )
916 setMetaData(
"davDisplayName", property.text() );
918 else if ( property.tagName() ==
"source" )
921 TQDomElement source =
property.namedItem(
"link" ).toElement()
922 .namedItem(
"dst" ).toElement();
923 if ( !source.isNull() )
924 setMetaData(
"davSource", source.text() );
926 else if ( property.tagName() ==
"getcontentlanguage" )
929 setMetaData(
"davContentLanguage", property.text() );
931 else if ( property.tagName() ==
"getcontenttype" )
936 if ( property.text() ==
"httpd/unix-directory" )
942 mimeType =
property.text();
945 else if ( property.tagName() ==
"executable" )
948 if ( property.text() ==
"T" )
949 foundExecutable =
true;
952 else if ( property.tagName() ==
"getlastmodified" )
955 atom.m_uds = TDEIO::UDS_MODIFICATION_TIME;
956 atom.m_long = parseDateTime( property.text(),
property.attribute(
"dt") );
957 entry.append( atom );
960 else if ( property.tagName() ==
"getetag" )
963 setMetaData(
"davEntityTag", property.text() );
965 else if ( property.tagName() ==
"supportedlock" )
968 for ( TQDomNode n2 = property.firstChild(); !n2.isNull(); n2 = n2.nextSibling() )
970 TQDomElement lockEntry = n2.toElement();
971 if ( lockEntry.tagName() ==
"lockentry" )
973 TQDomElement lockScope = lockEntry.namedItem(
"lockscope" ).toElement();
974 TQDomElement lockType = lockEntry.namedItem(
"locktype" ).toElement();
975 if ( !lockScope.isNull() && !lockType.isNull() )
978 supportedLockCount++;
979 TQString scope = lockScope.firstChild().toElement().tagName();
980 TQString type = lockType.firstChild().toElement().tagName();
982 setMetaData( TQString(
"davSupportedLockScope%1").arg(supportedLockCount), scope );
983 setMetaData( TQString(
"davSupportedLockType%1").arg(supportedLockCount), type );
988 else if ( property.tagName() ==
"lockdiscovery" )
991 davParseActiveLocks( property.elementsByTagName(
"activelock" ), lockCount );
993 else if ( property.tagName() ==
"resourcetype" )
996 if ( !property.namedItem(
"collection" ).toElement().isNull() )
1004 kdDebug(7113) <<
"Found unknown webdav property: " <<
property.tagName() << endl;
1009 setMetaData(
"davLockCount", TQString(
"%1").arg(lockCount) );
1010 setMetaData(
"davSupportedLockCount", TQString(
"%1").arg(supportedLockCount) );
1012 atom.m_uds = TDEIO::UDS_FILE_TYPE;
1013 atom.m_long = isDirectory ? S_IFDIR : S_IFREG;
1014 entry.append( atom );
1016 if ( foundExecutable || isDirectory )
1019 atom.m_uds = TDEIO::UDS_ACCESS;
1025 atom.m_uds = TDEIO::UDS_ACCESS;
1030 if ( !isDirectory && !mimeType.isEmpty() )
1032 atom.m_uds = TDEIO::UDS_MIME_TYPE;
1033 atom.m_str = mimeType;
1034 entry.append( atom );
1038 void HTTPProtocol::davParseActiveLocks(
const TQDomNodeList& activeLocks,
1041 for ( uint i = 0; i < activeLocks.count(); i++ )
1043 TQDomElement activeLock = activeLocks.item(i).toElement();
1047 TQDomElement lockScope = activeLock.namedItem(
"lockscope" ).toElement();
1048 TQDomElement lockType = activeLock.namedItem(
"locktype" ).toElement();
1049 TQDomElement lockDepth = activeLock.namedItem(
"depth" ).toElement();
1051 TQDomElement lockOwner = activeLock.namedItem(
"owner" ).toElement();
1052 TQDomElement lockTimeout = activeLock.namedItem(
"timeout" ).toElement();
1053 TQDomElement lockToken = activeLock.namedItem(
"locktoken" ).toElement();
1055 if ( !lockScope.isNull() && !lockType.isNull() && !lockDepth.isNull() )
1059 TQString scope = lockScope.firstChild().toElement().tagName();
1060 TQString type = lockType.firstChild().toElement().tagName();
1061 TQString depth = lockDepth.text();
1063 setMetaData( TQString(
"davLockScope%1").arg( lockCount ), scope );
1064 setMetaData( TQString(
"davLockType%1").arg( lockCount ), type );
1065 setMetaData( TQString(
"davLockDepth%1").arg( lockCount ), depth );
1067 if ( !lockOwner.isNull() )
1068 setMetaData( TQString(
"davLockOwner%1").arg( lockCount ), lockOwner.text() );
1070 if ( !lockTimeout.isNull() )
1071 setMetaData( TQString(
"davLockTimeout%1").arg( lockCount ), lockTimeout.text() );
1073 if ( !lockToken.isNull() )
1075 TQDomElement tokenVal = lockScope.namedItem(
"href" ).toElement();
1076 if ( !tokenVal.isNull() )
1077 setMetaData( TQString(
"davLockToken%1").arg( lockCount ), tokenVal.text() );
1083 long HTTPProtocol::parseDateTime(
const TQString& input,
const TQString& type )
1085 if ( type ==
"dateTime.tz" )
1087 return KRFCDate::parseDateISO8601( input );
1089 else if ( type ==
"dateTime.rfc1123" )
1091 return KRFCDate::parseDate( input );
1095 time_t time = KRFCDate::parseDate( input );
1099 return KRFCDate::parseDateISO8601( input );
1102 TQString HTTPProtocol::davProcessLocks()
1104 if ( hasMetaData(
"davLockCount" ) )
1106 TQString response(
"If:");
1108 numLocks = metaData(
"davLockCount" ).toInt();
1109 bool bracketsOpen =
false;
1110 for (
int i = 0; i < numLocks; i++ )
1112 if ( hasMetaData( TQString(
"davLockToken%1").arg(i) ) )
1114 if ( hasMetaData( TQString(
"davLockURL%1").arg(i) ) )
1119 bracketsOpen =
false;
1121 response +=
" <" + metaData( TQString(
"davLockURL%1").arg(i) ) +
">";
1124 if ( !bracketsOpen )
1127 bracketsOpen =
true;
1134 if ( hasMetaData( TQString(
"davLockNot%1").arg(i) ) )
1137 response +=
"<" + metaData( TQString(
"davLockToken%1").arg(i) ) +
">";
1148 return TQString::null;
1151 bool HTTPProtocol::davHostOk()
1159 kdDebug(7113) <<
"(" << m_pid <<
") " << k_funcinfo <<
" true" << endl;
1162 else if ( m_davHostUnsupported )
1164 kdDebug(7113) <<
"(" << m_pid <<
") " << k_funcinfo <<
" false" << endl;
1169 m_request.method = HTTP_OPTIONS;
1172 m_request.path =
"*";
1173 m_request.query = TQString::null;
1174 m_request.cache = CC_Reload;
1175 m_request.doProxy = m_bUseProxy;
1178 m_davCapabilities.clear();
1180 retrieveHeader(
false);
1182 if (m_davCapabilities.count())
1184 for (uint i = 0; i < m_davCapabilities.count(); i++)
1187 uint verNo = m_davCapabilities[i].toUInt(&ok);
1188 if (ok && verNo > 0 && verNo < 3)
1191 kdDebug(7113) <<
"Server supports DAV version " << verNo <<
"." << endl;
1199 m_davHostUnsupported =
true;
1206 void HTTPProtocol::davFinished()
1209 httpClose(m_bKeepAlive);
1213 void HTTPProtocol::mkdir(
const KURL& url,
int )
1215 kdDebug(7113) <<
"(" << m_pid <<
") HTTPProtocol::mkdir " << url.url()
1218 if ( !checkRequestURL( url ) )
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;
1227 retrieveHeader(
false );
1229 if ( m_responseCode == 201 )
1235 void HTTPProtocol::get(
const KURL& url )
1237 kdDebug(7113) <<
"(" << m_pid <<
") HTTPProtocol::get " << url.url()
1240 if ( !checkRequestURL( url ) )
1243 m_request.method = HTTP_GET;
1244 m_request.path = url.path();
1245 m_request.query = url.query();
1247 TQString tmp = metaData(
"cache");
1249 m_request.cache = parseCacheControl(tmp);
1251 m_request.cache = DEFAULT_CACHE_CONTROL;
1253 m_request.passwd = url.pass();
1254 m_request.user = url.user();
1255 m_request.doProxy = m_bUseProxy;
1260 void HTTPProtocol::put(
const KURL &url,
int,
bool overwrite,
bool)
1262 kdDebug(7113) <<
"(" << m_pid <<
") HTTPProtocol::put " << url.prettyURL()
1265 if ( !checkRequestURL( url ) )
1269 if (!overwrite && m_protocol.left(6) ==
"webdav") {
1275 request =
"<?xml version=\"1.0\" encoding=\"utf-8\" ?>"
1276 "<D:propfind xmlns:D=\"DAV:\"><D:prop>"
1278 "<D:getcontentlength/>"
1281 "</D:prop></D:propfind>";
1283 davSetRequest( request );
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;
1292 retrieveContent(
true);
1294 if (m_responseCode == 207) {
1295 error(ERR_FILE_ALREADY_EXIST, TQString::null);
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;
1308 retrieveHeader(
false );
1310 kdDebug(7113) <<
"(" << m_pid <<
") HTTPProtocol::put error = " << m_bError << endl;
1314 kdDebug(7113) <<
"(" << m_pid <<
") HTTPProtocol::put responseCode = " << m_responseCode << endl;
1318 if ( (m_responseCode >= 200) && (m_responseCode < 300) )
1324 void HTTPProtocol::copy(
const KURL& src,
const KURL& dest,
int,
bool overwrite )
1326 kdDebug(7113) <<
"(" << m_pid <<
") HTTPProtocol::copy " << src.prettyURL()
1327 <<
" -> " << dest.prettyURL() << endl;
1329 if ( !checkRequestURL( dest ) || !checkRequestURL( src ) )
1333 KURL newDest = dest;
1334 if (newDest.protocol() ==
"webdavs")
1335 newDest.setProtocol(
"https");
1337 newDest.setProtocol(
"http");
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;
1347 retrieveHeader(
false );
1350 if ( m_responseCode == 201 || m_responseCode == 204 )
1356 void HTTPProtocol::rename(
const KURL& src,
const KURL& dest,
bool overwrite )
1358 kdDebug(7113) <<
"(" << m_pid <<
") HTTPProtocol::rename " << src.prettyURL()
1359 <<
" -> " << dest.prettyURL() << endl;
1361 if ( !checkRequestURL( dest ) || !checkRequestURL( src ) )
1365 KURL newDest = dest;
1366 if (newDest.protocol() ==
"webdavs")
1367 newDest.setProtocol(
"https");
1369 newDest.setProtocol(
"http");
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;
1379 retrieveHeader(
false );
1381 if ( m_responseCode == 301 )
1387 if (m_redirectLocation.protocol() ==
"https")
1388 m_redirectLocation.setProtocol(
"webdavs");
1390 m_redirectLocation.setProtocol(
"webdav");
1392 if ( !checkRequestURL( m_redirectLocation ) )
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;
1403 retrieveHeader(
false );
1406 if ( m_responseCode == 201 )
1412 void HTTPProtocol::del(
const KURL& url,
bool )
1414 kdDebug(7113) <<
"(" << m_pid <<
") HTTPProtocol::del " << url.prettyURL()
1417 if ( !checkRequestURL( url ) )
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;
1426 retrieveHeader(
false );
1430 if ( m_responseCode == 200 || m_responseCode == 204 )
1436 void HTTPProtocol::post(
const KURL& url )
1438 kdDebug(7113) <<
"(" << m_pid <<
") HTTPProtocol::post "
1439 << url.prettyURL() << endl;
1441 if ( !checkRequestURL( url ) )
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;
1453 void HTTPProtocol::davLock(
const KURL& url,
const TQString& scope,
1454 const TQString& type,
const TQString& owner )
1456 kdDebug(7113) <<
"(" << m_pid <<
") HTTPProtocol::davLock "
1457 << url.prettyURL() << endl;
1459 if ( !checkRequestURL( url ) )
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;
1469 TQDomDocument lockReq;
1471 TQDomElement lockInfo = lockReq.createElementNS(
"DAV:",
"lockinfo" );
1472 lockReq.appendChild( lockInfo );
1474 TQDomElement lockScope = lockReq.createElement(
"lockscope" );
1475 lockInfo.appendChild( lockScope );
1477 lockScope.appendChild( lockReq.createElement( scope ) );
1479 TQDomElement lockType = lockReq.createElement(
"locktype" );
1480 lockInfo.appendChild( lockType );
1482 lockType.appendChild( lockReq.createElement( type ) );
1484 if ( !owner.isNull() ) {
1485 TQDomElement ownerElement = lockReq.createElement(
"owner" );
1486 lockReq.appendChild( ownerElement );
1488 TQDomElement ownerHref = lockReq.createElement(
"href" );
1489 ownerElement.appendChild( ownerHref );
1491 ownerHref.appendChild( lockReq.createTextNode( owner ) );
1495 m_bufPOST = lockReq.toCString();
1497 retrieveContent(
true );
1499 if ( m_responseCode == 200 ) {
1501 TQDomDocument multiResponse;
1502 multiResponse.setContent( m_bufWebDavData,
true );
1504 TQDomElement prop = multiResponse.documentElement().namedItem(
"prop" ).toElement();
1506 TQDomElement lockdiscovery = prop.namedItem(
"lockdiscovery" ).toElement();
1509 davParseActiveLocks( lockdiscovery.elementsByTagName(
"activelock" ), lockCount );
1511 setMetaData(
"davLockCount", TQString(
"%1").arg( lockCount ) );
1519 void HTTPProtocol::davUnlock(
const KURL& url )
1521 kdDebug(7113) <<
"(" << m_pid <<
") HTTPProtocol::davUnlock "
1522 << url.prettyURL() << endl;
1524 if ( !checkRequestURL( url ) )
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;
1533 retrieveContent(
true );
1535 if ( m_responseCode == 200 )
1541 TQString HTTPProtocol::davError(
int code , TQString url )
1543 bool callError =
false;
1545 code = m_responseCode;
1552 if ( !url.isNull() )
1553 url = m_request.url.url();
1555 TQString action, errorString;
1556 TDEIO::Error kError;
1559 TQString ow = i18n(
"Otherwise, the request would have succeeded." );
1561 switch ( m_request.method ) {
1563 action = i18n(
"retrieve property values" );
1566 action = i18n(
"set property values" );
1569 action = i18n(
"create the requested folder" );
1572 action = i18n(
"copy the specified file or folder" );
1575 action = i18n(
"move the specified file or folder" );
1578 action = i18n(
"search in the specified folder" );
1581 action = i18n(
"lock the specified file or folder" );
1584 action = i18n(
"unlock the specified file or folder" );
1587 action = i18n(
"delete the specified file or folder" );
1590 action = i18n(
"query the server's capabilities" );
1593 action = i18n(
"retrieve the contents of the specified file or folder" );
1604 kError = ERR_INTERNAL;
1605 errorString = i18n(
"An unexpected error (%1) occurred while attempting to %2.")
1606 .arg( code ).arg( action );
1612 kError = ERR_UNSUPPORTED_PROTOCOL;
1613 errorString = i18n(
"The server does not support the WebDAV protocol.");
1623 if ( !readBody(
true ) && m_bError )
1624 return TQString::null;
1626 TQStringList errors;
1627 TQDomDocument multiResponse;
1629 multiResponse.setContent( m_bufWebDavData,
true );
1631 TQDomElement multistatus = multiResponse.documentElement().namedItem(
"multistatus" ).toElement();
1633 TQDomNodeList responses = multistatus.elementsByTagName(
"response" );
1635 for (uint i = 0; i < responses.count(); i++)
1640 TQDomElement response = responses.item(i).toElement();
1641 TQDomElement code = response.namedItem(
"status" ).toElement();
1643 if ( !code.isNull() )
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 );
1654 errorString = i18n(
"An error occurred while attempting to %1, %2. A "
1655 "summary of the reasons is below.<ul>").arg( action ).arg( url );
1657 for ( TQStringList::Iterator it = errors.begin(); it != errors.end(); ++it )
1658 errorString +=
"<li>" + *it +
"</li>";
1660 errorString +=
"</ul>";
1665 kError = ERR_ACCESS_DENIED;
1666 errorString = i18n(
"Access was denied while attempting to %1.").arg( action );
1670 if ( m_request.method == DAV_MKCOL )
1672 kError = ERR_DIR_ALREADY_EXIST;
1673 errorString = i18n(
"The specified folder already exists.");
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.");
1685 if ( m_request.method == DAV_COPY || m_request.method == DAV_MOVE )
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")
1695 else if ( m_request.method == DAV_LOCK )
1697 kError = ERR_ACCESS_DENIED;
1698 errorString = i18n(
"The requested lock could not be granted. %1").arg( ow );
1703 kError = ERR_ACCESS_DENIED;
1704 errorString = i18n(
"The server does not support the request type of the body.");
1708 kError = ERR_ACCESS_DENIED;
1709 errorString = i18n(
"Unable to %1 because the resource is locked.").arg( action );
1713 errorString = i18n(
"This action was prevented by another error.");
1717 if ( m_request.method == DAV_COPY || m_request.method == DAV_MOVE )
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 );
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 "
1737 error( ERR_SLAVE_DEFINED, errorString );
1742 void HTTPProtocol::httpError()
1744 TQString action, errorString;
1745 TDEIO::Error kError;
1747 switch ( m_request.method ) {
1749 action = i18n(
"upload %1" ).arg(m_request.url.prettyURL());
1757 kError = ERR_INTERNAL;
1758 errorString = i18n(
"An unexpected error (%1) occurred while attempting to %2.")
1759 .arg( m_responseCode ).arg( action );
1761 switch ( m_responseCode )
1768 kError = ERR_ACCESS_DENIED;
1769 errorString = i18n(
"Access was denied while attempting to %1.").arg( action );
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.");
1780 kError = ERR_ACCESS_DENIED;
1781 errorString = i18n(
"Unable to %1 because the resource is locked.").arg( action );
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 );
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 "
1801 error( ERR_SLAVE_DEFINED, errorString );
1804 bool HTTPProtocol::isOffline(
const KURL &url)
1806 const int NetWorkStatusUnknown = 1;
1807 const int NetWorkStatusOnline = 8;
1808 TQCString replyType;
1812 TQDataStream stream(params, IO_WriteOnly);
1814 if ( url.host() == TQString::fromLatin1(
"localhost") || url.host() == TQString::fromLatin1(
"127.0.0.1") || url.host() == TQString::fromLatin1(
"::") ) {
1817 if ( dcopClient()->call(
"kded",
"networkstatus",
"status()",
1818 params, replyType, reply ) && (replyType ==
"int") )
1821 TQDataStream stream2( reply, IO_ReadOnly );
1823 kdDebug(7113) <<
"(" << m_pid <<
") networkstatus status = " << result << endl;
1824 return (result != NetWorkStatusUnknown) && (result != NetWorkStatusOnline);
1826 kdDebug(7113) <<
"(" << m_pid <<
") networkstatus <unreachable>" << endl;
1830 void HTTPProtocol::multiGet(
const TQByteArray &data)
1832 TQDataStream stream(data, IO_ReadOnly);
1836 kdDebug(7113) <<
"(" << m_pid <<
") HTTPProtcool::multiGet n = " << n << endl;
1838 HTTPRequest saveRequest;
1840 saveRequest = m_request;
1843 for(
unsigned i = 0; i < n; i++)
1846 stream >> url >> mIncomingMetaData;
1848 if ( !checkRequestURL( url ) )
1851 kdDebug(7113) <<
"(" << m_pid <<
") HTTPProtocol::multi_get " << url.url() << endl;
1853 m_request.method = HTTP_GET;
1854 m_request.path = url.path();
1855 m_request.query = url.query();
1856 TQString tmp = metaData(
"cache");
1858 m_request.cache = parseCacheControl(tmp);
1860 m_request.cache = DEFAULT_CACHE_CONTROL;
1862 m_request.passwd = url.pass();
1863 m_request.user = url.user();
1864 m_request.doProxy = m_bUseProxy;
1866 HTTPRequest *newRequest =
new HTTPRequest(m_request);
1867 m_requestQueue.append(newRequest);
1871 m_request = saveRequest;
1876 while(!m_requestQueue.isEmpty())
1878 HTTPRequest *request = m_requestQueue.take(0);
1879 m_request = *request;
1887 ssize_t HTTPProtocol::write (
const void *_buf,
size_t nbytes)
1890 const char* buf =
static_cast<const char*
>(_buf);
1891 while ( nbytes > 0 )
1893 int n = TCPSlaveBase::write(buf, nbytes);
1901 if (n < 0 && ((errno == EINTR) || (errno == EAGAIN)))
1915 void HTTPProtocol::setRewindMarker()
1920 void HTTPProtocol::rewind()
1922 m_linePtrUnget = m_rewindBuf,
1923 m_lineCountUnget = m_rewindCount;
1928 char *HTTPProtocol::gets (
char *s,
int size)
1932 char mybuf[2]={0,0};
1940 if (m_rewindCount <
sizeof(m_rewindBuf))
1941 m_rewindBuf[m_rewindCount++] = *mybuf;
1946 if ((*mybuf ==
'\n') || !*mybuf)
1957 ssize_t HTTPProtocol::read (
void *b,
size_t nbytes)
1961 if (m_lineCountUnget > 0)
1963 ret = ( nbytes < m_lineCountUnget ? nbytes : m_lineCountUnget );
1964 m_lineCountUnget -= ret;
1965 memcpy(b, m_linePtrUnget, ret);
1966 m_linePtrUnget += ret;
1971 if (m_lineCount > 0)
1973 ret = ( nbytes < m_lineCount ? nbytes : m_lineCount );
1975 memcpy(b, m_linePtr, ret);
1982 ret = read(m_lineBuf, 1024);
1983 m_linePtr = m_lineBuf;
1995 ret = TCPSlaveBase::read( b, nbytes);
1999 }
while ((ret == -1) && (errno == EAGAIN || errno == EINTR));
2004 void HTTPProtocol::httpCheckConnection()
2006 kdDebug(7113) <<
"(" << m_pid <<
") HTTPProtocol::httpCheckConnection: " <<
2007 " Socket status: " << m_iSock <<
2008 " Keep Alive: " << m_bKeepAlive <<
2009 " First: " << m_bFirstRequest << endl;
2011 if ( !m_bFirstRequest && (m_iSock != -1) )
2013 bool closeDown =
false;
2014 if ( !isConnectionValid())
2016 kdDebug(7113) <<
"(" << m_pid <<
") Connection lost!" << endl;
2019 else if ( m_request.method != HTTP_GET )
2023 else if ( !m_state.doProxy && !m_request.doProxy )
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)
2034 if ( !(m_request.doProxy && m_state.doProxy) )
2039 httpCloseConnection();
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;
2051 bool HTTPProtocol::httpOpenConnection()
2056 kdDebug(7113) <<
"(" << m_pid <<
") HTTPProtocol::httpOpenConnection" << endl;
2058 setBlockConnection(
true );
2060 KSocks::self()->disableSocks();
2062 if ( m_state.doProxy )
2064 TQString proxy_host = m_proxyURL.host();
2065 int proxy_port = m_proxyURL.port();
2067 kdDebug(7113) <<
"(" << m_pid <<
") Connecting to proxy server: "
2068 << proxy_host <<
", port: " << proxy_port << endl;
2070 infoMessage( i18n(
"Connecting to %1...").arg(m_state.hostname) );
2072 setConnectTimeout( m_proxyConnTimeout );
2074 if ( !connectToHost(proxy_host, proxy_port,
false) )
2076 if (userAborted()) {
2077 error(ERR_NO_CONTENT,
"");
2081 switch ( connectResult() )
2083 case IO_LookupError:
2084 errMsg = proxy_host;
2085 errCode = ERR_UNKNOWN_PROXY_HOST;
2087 case IO_TimeOutError:
2088 errMsg = i18n(
"Proxy %1 at port %2").arg(proxy_host).arg(proxy_port);
2089 errCode = ERR_SERVER_TIMEOUT;
2092 errMsg = i18n(
"Proxy %1 at port %2").arg(proxy_host).arg(proxy_port);
2093 errCode = ERR_COULD_NOT_CONNECT;
2095 error( errCode, errMsg );
2102 setConnectTimeout(m_remoteConnTimeout);
2104 if ( !connectToHost(m_state.hostname, m_state.port,
false ) )
2106 if (userAborted()) {
2107 error(ERR_NO_CONTENT,
"");
2111 switch ( connectResult() )
2113 case IO_LookupError:
2114 errMsg = m_state.hostname;
2115 errCode = ERR_UNKNOWN_HOST;
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;
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);
2126 errMsg = m_state.hostname;
2128 error( errCode, errMsg );
2135 (void) setsockopt( m_iSock, IPPROTO_TCP, TCP_NODELAY, (
char*)&on,
sizeof(on) );
2137 m_bFirstRequest =
true;
2166 bool HTTPProtocol::httpOpen()
2168 kdDebug(7113) <<
"(" << m_pid <<
") HTTPProtocol::httpOpen" << endl;
2173 if ( (m_protocol ==
"https" || m_protocol ==
"webdavs") && !m_bIsSSL )
2175 error( ERR_UNSUPPORTED_PROTOCOL, m_protocol );
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;
2186 if (m_request.bUseCache)
2188 m_request.fcache = checkCacheEntry( );
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;
2195 if (m_request.cache == CC_Reload && m_request.fcache)
2197 if (m_request.fcache)
2198 fclose(m_request.fcache);
2199 m_request.fcache = 0;
2201 if ((m_request.cache == TDEIO::CC_CacheOnly) || (m_request.cache == TDEIO::CC_Cache))
2202 m_request.bMustRevalidate =
false;
2204 m_request.bCachedWrite =
true;
2206 if (m_request.fcache && !m_request.bMustRevalidate)
2209 m_request.bCachedRead =
true;
2212 else if (!m_request.fcache)
2214 m_request.bMustRevalidate =
false;
2221 if (bCacheOnly && bOffline)
2223 error( ERR_OFFLINE_MODE, m_request.url.url() );
2228 error( ERR_DOES_NOT_EXIST, m_request.url.url() );
2233 error( ERR_OFFLINE_MODE, m_request.url.url() );
2241 bool moreData =
false;
2242 bool davData =
false;
2245 resetConnectionSettings ();
2248 httpCheckConnection();
2250 if ( !m_bIsTunneled && m_bNeedTunnel )
2252 setEnableSSLTunnel(
true );
2255 header = TQString(
"CONNECT %1:%2 HTTP/1.0"
2256 "\r\n").arg( m_request.encoded_hostname).arg(m_request.port);
2259 if (!m_request.userAgent.isEmpty())
2260 header +=
"User-Agent: " + m_request.userAgent +
"\r\n";
2263 header +=
"Host: " + m_state.encoded_hostname;
2265 if (m_state.port != m_iDefaultPort)
2266 header += TQString(
":%1").arg(m_state.port);
2269 header += proxyAuthenticationHeader();
2274 switch (m_request.method)
2282 m_request.bCachedWrite =
false;
2287 m_request.bCachedWrite =
false;
2294 m_request.bCachedWrite =
false;
2297 header =
"OPTIONS ";
2298 m_request.bCachedWrite =
false;
2301 header =
"PROPFIND ";
2303 davHeader =
"Depth: ";
2304 if ( hasMetaData(
"davDepth" ) )
2306 kdDebug(7113) <<
"Reading DAV depth from metadata: " << metaData(
"davDepth" ) << endl;
2307 davHeader += metaData(
"davDepth" );
2311 if ( m_request.davData.depth == 2 )
2312 davHeader +=
"infinity";
2314 davHeader += TQString(
"%1").arg( m_request.davData.depth );
2316 davHeader +=
"\r\n";
2317 m_request.bCachedWrite =
false;
2320 header =
"PROPPATCH ";
2322 m_request.bCachedWrite =
false;
2326 m_request.bCachedWrite =
false;
2330 header = ( m_request.method == DAV_COPY ) ?
"COPY " :
"MOVE ";
2331 davHeader =
"Destination: " + m_request.davData.desturl;
2334 davHeader +=
"\r\nDepth: infinity\r\nOverwrite: ";
2335 davHeader += m_request.davData.overwrite ?
"T" :
"F";
2336 davHeader +=
"\r\n";
2337 m_request.bCachedWrite =
false;
2341 davHeader =
"Timeout: ";
2344 if ( hasMetaData(
"davTimeout" ) )
2345 timeout = metaData(
"davTimeout" ).toUInt();
2347 davHeader +=
"Infinite";
2349 davHeader += TQString(
"Seconds-%1").arg(timeout);
2351 davHeader +=
"\r\n";
2352 m_request.bCachedWrite =
false;
2357 davHeader =
"Lock-token: " + metaData(
"davLockToken") +
"\r\n";
2358 m_request.bCachedWrite =
false;
2363 m_request.bCachedWrite =
false;
2366 header =
"SUBSCRIBE ";
2367 m_request.bCachedWrite =
false;
2369 case DAV_UNSUBSCRIBE:
2370 header =
"UNSUBSCRIBE ";
2371 m_request.bCachedWrite =
false;
2375 m_request.bCachedWrite =
false;
2378 error (ERR_UNSUPPORTED_ACTION, TQString::null);
2384 if (m_state.doProxy && !m_bIsTunneled)
2388 if (m_protocol ==
"webdav")
2389 u.setProtocol(
"http" );
2390 else if (m_protocol ==
"webdavs" )
2391 u.setProtocol(
"https" );
2393 u.setProtocol( m_protocol );
2399 if (m_protocol !=
"http" && m_protocol !=
"https" &&
2400 !m_state.user.isEmpty())
2401 u.setUser (m_state.user);
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) );
2411 header += m_request.url.encodedPathAndQuery(0,
true);
2414 header +=
" HTTP/1.1\r\n";
2416 if (!m_request.userAgent.isEmpty())
2418 header +=
"User-Agent: ";
2419 header += m_request.userAgent;
2423 if (!m_request.referrer.isEmpty())
2425 header +=
"Referer: ";
2426 header += m_request.referrer;
2430 if ( m_request.offset > 0 )
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;
2436 if ( m_request.cache == CC_Reload )
2439 header +=
"Pragma: no-cache\r\n";
2440 header +=
"Cache-control: no-cache\r\n";
2443 if (m_request.bMustRevalidate)
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";
2452 header +=
"Accept: ";
2453 TQString acceptHeader = metaData(
"accept");
2454 if (!acceptHeader.isEmpty())
2455 header += acceptHeader;
2457 header += DEFAULT_ACCEPT_HEADER;
2461 if (m_request.allowCompressedPage)
2462 header +=
"Accept-Encoding: x-gzip, x-deflate, gzip, deflate\r\n";
2465 if (!m_request.charsets.isEmpty())
2466 header +=
"Accept-Charset: " + m_request.charsets +
"\r\n";
2468 if (!m_request.languages.isEmpty())
2469 header +=
"Accept-Language: " + m_request.languages +
"\r\n";
2473 header +=
"Host: " + m_state.encoded_hostname;
2475 if (m_state.port != m_iDefaultPort)
2476 header += TQString(
":%1").arg(m_state.port);
2480 TQString cookieMode = metaData(
"cookies").lower();
2481 if (cookieMode ==
"none")
2483 m_request.cookieMode = HTTPRequest::CookiesNone;
2485 else if (cookieMode ==
"manual")
2487 m_request.cookieMode = HTTPRequest::CookiesManual;
2488 cookieStr = metaData(
"setcookies");
2492 m_request.cookieMode = HTTPRequest::CookiesAuto;
2493 if (m_request.bUseCookiejar)
2494 cookieStr = findCookies( m_request.url.url());
2497 if (!cookieStr.isEmpty())
2498 header += cookieStr +
"\r\n";
2500 TQString customHeader = metaData(
"customHTTPHeader" );
2501 if (!customHeader.isEmpty())
2503 header += sanitizeCustomHTTPHeader(customHeader);
2507 if (m_request.method == HTTP_POST)
2509 header += metaData(
"content-type");
2516 if ( !m_request.bNoAuth && m_responseCode != 401 && m_responseCode != 407 && Authentication != AUTH_Negotiate )
2518 kdDebug(7113) <<
"(" << m_pid <<
") Calling checkCachedAuthentication " << endl;
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() )
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 )
2531 m_strAuthorization = info.digestInfo;
2536 kdDebug(7113) <<
"(" << m_pid <<
") Not calling checkCachedAuthentication " << endl;
2539 switch ( Authentication )
2542 header += createBasicAuth();
2545 header += createDigestAuth();
2547 #ifdef HAVE_LIBGSSAPI
2548 case AUTH_Negotiate:
2549 header += createNegotiateAuth();
2553 header += createNTLMAuth();
2561 if ( Authentication != AUTH_None )
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;
2573 if ( m_state.doProxy && !m_bIsTunneled )
2574 header += proxyAuthenticationHeader();
2580 if (!m_bUseProxy || m_bPersistentProxyConnection || m_bIsTunneled)
2581 header +=
"Connection: Keep-Alive\r\n";
2583 header +=
"Connection: close\r\n";
2585 if ( m_protocol ==
"webdav" || m_protocol ==
"webdavs" )
2587 header += davProcessLocks();
2590 TQString davExtraHeader = metaData(
"davHeader");
2591 if ( !davExtraHeader.isEmpty() )
2592 davHeader += davExtraHeader;
2596 davHeader +=
"Content-Type: text/xml; charset=utf-8\r\n";
2599 if ( !davHeader.isNull() )
2600 header += davHeader;
2604 kdDebug(7103) <<
"(" << m_pid <<
") ============ Sending Header:" << endl;
2606 TQStringList headerOutput = TQStringList::split(
"\r\n", header);
2607 TQStringList::Iterator it = headerOutput.begin();
2609 for (; it != headerOutput.end(); it++)
2610 kdDebug(7103) <<
"(" << m_pid <<
") " << (*it) << endl;
2612 if ( !moreData && !davData)
2620 if (!httpOpenConnection())
2625 bool sendOk = (write(header.latin1(), header.length()) == (ssize_t) header.length());
2628 kdDebug(7113) <<
"(" << m_pid <<
") HTTPProtocol::httpOpen: "
2629 "Connection broken! (" << m_state.hostname <<
")" << endl;
2635 httpCloseConnection();
2641 kdDebug(7113) <<
"(" << m_pid <<
") HTTPProtocol::httpOpen: sendOk==false."
2642 " Connnection broken !" << endl;
2643 error( ERR_CONNECTION_BROKEN, m_state.hostname );
2650 if ( moreData || davData )
2653 infoMessage(i18n(
"%1 contacted. Waiting for reply...").arg(m_request.hostname));
2658 void HTTPProtocol::forwardHttpResponseHeader()
2661 if ( config()->readBoolEntry(
"PropagateHttpHeader",
false) )
2663 setMetaData(
"HTTP-Headers", m_responseHeader.join(
"\n"));
2666 m_responseHeader.clear();
2675 bool HTTPProtocol::readHeader()
2678 kdDebug(7113) <<
"(" << m_pid <<
") HTTPProtocol::readHeader" << endl;
2681 if (m_request.bCachedRead)
2683 m_responseHeader <<
"HTTP-CACHE";
2686 if (!fgets(buffer, 4096, m_request.fcache) )
2689 kdDebug(7113) <<
"(" << m_pid <<
") HTTPProtocol::readHeader: "
2690 <<
"Could not access cache to obtain mimetype!" << endl;
2691 error( ERR_CONNECTION_BROKEN, m_state.hostname );
2695 m_strMimeType = TQString(TQString::fromUtf8( buffer)).stripWhiteSpace();
2697 kdDebug(7113) <<
"(" << m_pid <<
") HTTPProtocol::readHeader: cached "
2698 <<
"data mimetype: " << m_strMimeType << endl;
2700 if (!fgets(buffer, 4096, m_request.fcache) )
2703 kdDebug(7113) <<
"(" << m_pid <<
") HTTPProtocol::readHeader: "
2704 <<
"Could not access cached data! " << endl;
2705 error( ERR_CONNECTION_BROKEN, m_state.hostname );
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);
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();
2723 TQCString locationStr;
2724 TQCString cookieStr;
2726 TQString dispositionType;
2727 TQString dispositionFilename;
2729 TQString mediaValue;
2730 TQString mediaAttribute;
2732 TQStringList upgradeOffers;
2734 bool upgradeRequired =
false;
2738 bool canUpgrade =
false;
2741 m_request.etag = TQString::null;
2742 m_request.lastModified = TQString::null;
2743 m_request.strCharset = TQString::null;
2745 time_t dateHeader = 0;
2746 time_t expireDate = 0;
2749 int maxHeaderSize = 64*1024;
2755 bool cacheValidated =
false;
2756 bool mayCache =
true;
2757 bool hasCacheDirective =
false;
2758 bool bCanResume =
false;
2762 kdDebug(7113) <<
"HTTPProtocol::readHeader: No connection." << endl;
2766 if (!waitForResponse(m_remoteRespTimeout))
2769 error( ERR_SERVER_TIMEOUT , m_state.hostname );
2775 gets(buffer,
sizeof(buffer)-1);
2777 if (m_bEOF || *buffer ==
'\0')
2779 kdDebug(7113) <<
"(" << m_pid <<
") HTTPProtocol::readHeader: "
2780 <<
"EOF while waiting for header start." << endl;
2783 httpCloseConnection();
2787 if (m_request.method == HTTP_HEAD)
2793 kdDebug(7113) <<
"(" << m_pid <<
") HTTPPreadHeader: HEAD -> returned "
2794 <<
"mimetype: " << DEFAULT_MIME_TYPE << endl;
2795 mimeType(TQString::fromLatin1(DEFAULT_MIME_TYPE));
2799 kdDebug(7113) <<
"HTTPProtocol::readHeader: Connection broken !" << endl;
2800 error( ERR_CONNECTION_BROKEN, m_state.hostname );
2804 kdDebug(7103) <<
"(" << m_pid <<
") ============ Received Response:"<< endl;
2806 bool noHeader =
true;
2807 HTTP_REV httpRev = HTTP_None;
2813 len = strlen(buffer);
2815 while(len && (buffer[len-1] ==
'\n' || buffer[len-1] ==
'\r'))
2821 kdDebug(7103) <<
"(" << m_pid <<
") --empty--" << endl;
2833 kdDebug(7103) <<
"(" << m_pid <<
") \"" << buffer <<
"\"" << endl;
2837 while( *buf ==
' ' )
2845 kdDebug(7103) <<
"tdeio_http: No valid HTTP header found! Document starts with XML/HTML tag" << endl;
2848 m_strMimeType =
"text/html";
2856 m_responseHeader << TQString::fromLatin1(buf);
2858 if ((strncasecmp(buf,
"HTTP/", 5) == 0) ||
2859 (strncasecmp(buf,
"ICY ", 4) == 0))
2861 if (strncasecmp(buf,
"ICY ", 4) == 0)
2864 httpRev = SHOUTCAST;
2865 m_bKeepAlive =
false;
2867 else if (strncmp((buf + 5),
"1.0",3) == 0)
2875 m_bKeepAlive =
false;
2877 else if (strncmp((buf + 5),
"1.1",3) == 0)
2883 httpRev = HTTP_Unknown;
2887 m_prevResponseCode = m_responseCode;
2889 const char* rptr = buf;
2890 while ( *rptr && *rptr >
' ' )
2892 m_responseCode = atoi(rptr);
2895 if (m_responseCode >= 500 && m_responseCode <= 599)
2897 if (m_request.method == HTTP_HEAD)
2903 if (m_request.bErrorPage)
2907 error(ERR_INTERNAL_SERVER, m_request.url.url());
2911 m_request.bCachedWrite =
false;
2915 else if (m_responseCode == 401 || m_responseCode == 407)
2919 if ( m_prevResponseCode != m_responseCode &&
2920 (m_prevResponseCode == 401 || m_prevResponseCode == 407) )
2921 saveAuthorization();
2923 m_bUnauthorized =
true;
2924 m_request.bCachedWrite =
false;
2928 else if (m_responseCode == 416)
2930 m_request.offset = 0;
2931 httpCloseConnection();
2935 else if (m_responseCode == 426)
2937 upgradeRequired =
true;
2940 else if (m_responseCode >= 400 && m_responseCode <= 499)
2943 if (m_request.bErrorPage)
2947 error(ERR_DOES_NOT_EXIST, m_request.url.url());
2950 m_request.bCachedWrite =
false;
2953 else if (m_responseCode == 307)
2956 m_request.bCachedWrite =
false;
2959 else if (m_responseCode == 304)
2963 cacheValidated =
true;
2965 else if (m_responseCode >= 301 && m_responseCode<= 303)
2968 if (m_responseCode == 301)
2969 setMetaData(
"permanent-redirect",
"true");
2973 if (m_request.method != HTTP_HEAD && m_request.method != HTTP_GET)
2978 if (m_request.method == HTTP_POST)
2979 m_bufPOST.resize(0);
2990 m_request.method = HTTP_GET;
2992 m_request.bCachedWrite =
false;
2995 else if ( m_responseCode == 207 )
2999 else if ( m_responseCode == 204 )
3009 else if ( m_responseCode == 206 )
3011 if ( m_request.offset )
3014 else if (m_responseCode == 102)
3021 infoMessage( i18n(
"Server processing request, please wait..." ) );
3024 else if (m_responseCode == 100)
3032 else if (strncasecmp(buf,
"Accept-Ranges:", 14) == 0) {
3033 if (strncasecmp(trimLead(buf + 14),
"none", 4) == 0)
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();
3044 TQString option = (*it).stripWhiteSpace().lower();
3045 if (option.startsWith(
"timeout="))
3047 m_keepAliveTimeout = option.mid(8).toInt();
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();
3060 TQString cacheControl = (*it).stripWhiteSpace();
3061 if (strncasecmp(cacheControl.latin1(),
"no-cache", 8) == 0)
3063 m_request.bCachedWrite =
false;
3066 else if (strncasecmp(cacheControl.latin1(),
"no-store", 8) == 0)
3068 m_request.bCachedWrite =
false;
3071 else if (strncasecmp(cacheControl.latin1(),
"max-age=", 8) == 0)
3073 TQString age = cacheControl.mid(8).stripWhiteSpace();
3075 maxAge = STRTOLL(age.latin1(), 0, 10);
3078 hasCacheDirective =
true;
3082 else if (strncasecmp(buf,
"Content-length:", 15) == 0) {
3083 char* len = trimLead(buf + 15);
3085 m_iSize = STRTOLL(len, 0, 10);
3088 else if (strncasecmp(buf,
"Content-location:", 17) == 0) {
3089 setMetaData (
"content-location",
3090 TQString::fromLatin1(trimLead(buf+17)).stripWhiteSpace());
3094 else if (strncasecmp(buf,
"Content-type:", 13) == 0) {
3095 char *start = trimLead(buf + 13);
3099 while ( *pos && *pos !=
';' ) pos++;
3102 m_strMimeType = TQString::fromLatin1(start, pos-start).stripWhiteSpace().lower();
3103 kdDebug(7113) <<
"(" << m_pid <<
") Content-type: " << m_strMimeType << endl;
3110 while ( *pos && *pos !=
'=' ) pos++;
3113 while ( *end && *end !=
';' ) end++;
3117 mediaAttribute = TQString::fromLatin1(start, pos-start).stripWhiteSpace().lower();
3118 mediaValue = TQString::fromLatin1(pos+1, end-pos-1).stripWhiteSpace();
3120 if (mediaValue.length() &&
3121 (mediaValue[0] ==
'"') &&
3122 (mediaValue[mediaValue.length()-1] ==
'"'))
3123 mediaValue = mediaValue.mid(1, mediaValue.length()-2);
3125 kdDebug (7113) <<
"(" << m_pid <<
") Media-Parameter Attribute: "
3126 << mediaAttribute << endl;
3127 kdDebug (7113) <<
"(" << m_pid <<
") Media-Parameter Value: "
3128 << mediaValue << endl;
3130 if ( mediaAttribute ==
"charset")
3132 mediaValue = mediaValue.lower();
3133 m_request.strCharset = mediaValue;
3137 setMetaData(
"media-"+mediaAttribute, mediaValue);
3144 else if (strncasecmp(buf,
"Date:", 5) == 0) {
3145 dateHeader = KRFCDate::parseDate(trimLead(buf+5));
3149 else if (strncasecmp(buf,
"ETag:", 5) == 0) {
3150 m_request.etag = trimLead(buf+5);
3154 else if (strncasecmp(buf,
"Expires:", 8) == 0) {
3155 expireDate = KRFCDate::parseDate(trimLead(buf+8));
3161 else if (strncasecmp(buf,
"Last-Modified:", 14) == 0) {
3162 m_request.lastModified = (TQString::fromLatin1(trimLead(buf+14))).stripWhiteSpace();
3166 else if (strncasecmp(buf,
"Warning:", 8) == 0) {
3169 infoMessage(trimLead(buf + 8));
3173 else if (strncasecmp(buf,
"Pragma:", 7) == 0) {
3174 TQCString pragma = TQCString(trimLead(buf+7)).stripWhiteSpace().lower();
3175 if (pragma ==
"no-cache")
3177 m_request.bCachedWrite =
false;
3179 hasCacheDirective =
true;
3184 else if (strncasecmp(buf,
"Refresh:", 8) == 0) {
3186 setMetaData(
"http-refresh", TQString::fromLatin1(trimLead(buf+8)).stripWhiteSpace() );
3190 else if (strncasecmp(buf,
"Location:", 9) == 0) {
3192 if ( m_responseCode > 299 && m_responseCode < 400 )
3193 locationStr = TQCString(trimLead(buf+9)).stripWhiteSpace();
3197 else if (strncasecmp(buf,
"Set-Cookie", 10) == 0) {
3203 else if (strncasecmp(buf,
"WWW-Authenticate:", 17) == 0) {
3204 configAuth(trimLead(buf + 17),
false);
3208 else if (strncasecmp(buf,
"Proxy-Authenticate:", 19) == 0) {
3209 configAuth(trimLead(buf + 19),
true);
3212 else if (strncasecmp(buf,
"Upgrade:", 8) == 0) {
3214 TQString offered = &(buf[8]);
3215 upgradeOffers = TQStringList::split(TQRegExp(
"[ \n,\r\t]"), offered);
3219 else if (strncasecmp(buf,
"Content-Encoding:", 17) == 0) {
3233 addEncoding(trimLead(buf + 17), m_qContentEncodings);
3236 else if(strncasecmp(buf,
"Content-Disposition:", 20) == 0) {
3237 char* dispositionBuf = trimLead(buf + 20);
3238 while ( *dispositionBuf )
3240 if ( strncasecmp( dispositionBuf,
"filename", 8 ) == 0 )
3242 dispositionBuf += 8;
3244 while ( *dispositionBuf ==
' ' || *dispositionBuf ==
'=' )
3247 char* bufStart = dispositionBuf;
3249 while ( *dispositionBuf && *dispositionBuf !=
';' )
3252 if ( dispositionBuf > bufStart )
3255 while ( *bufStart ==
'"' )
3259 while ( *(dispositionBuf-1) ==
' ' || *(dispositionBuf-1) ==
'"')
3262 if ( dispositionBuf > bufStart )
3263 dispositionFilename = TQString::fromLatin1( bufStart, dispositionBuf-bufStart );
3270 char *bufStart = dispositionBuf;
3272 while ( *dispositionBuf && *dispositionBuf !=
';' )
3275 if ( dispositionBuf > bufStart )
3276 dispositionType = TQString::fromLatin1( bufStart, dispositionBuf-bufStart ).stripWhiteSpace();
3278 while ( *dispositionBuf ==
';' || *dispositionBuf ==
' ' )
3285 if ( !dispositionFilename.isEmpty() )
3287 int pos = dispositionFilename.findRev(
'/' );
3290 dispositionFilename = dispositionFilename.mid(pos+1);
3292 kdDebug(7113) <<
"(" << m_pid <<
") Content-Disposition: filename="
3293 << dispositionFilename<< endl;
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);
3301 else if (strncasecmp(buf,
"Proxy-Connection:", 17) == 0)
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;
3308 else if (strncasecmp(buf,
"Link:", 5) == 0) {
3310 TQStringList link = TQStringList::split(
";", TQString(buf)
3311 .replace(TQRegExp(
"^Link:[ ]*"),
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);
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();
3332 TQStringList policy = TQStringList::split(
"=", *it);
3334 if (policy.count() == 2) {
3335 if (policy[0].lower() ==
"policyref") {
3336 policyrefs << TQString(policy[1].replace(TQRegExp(
"[\"\']"),
""))
3338 }
else if (policy[0].lower() ==
"cp") {
3342 TQStringList cps = TQStringList::split(
" ",
3343 TQString(policy[1].replace(TQRegExp(
"[\"\']"),
""))
3344 .simplifyWhiteSpace());
3346 for (TQStringList::Iterator j = cps.begin(); j != cps.end(); ++j)
3352 if (!policyrefs.isEmpty())
3353 setMetaData(
"PrivacyPolicy", policyrefs.join(
"\n"));
3355 if (!compact.isEmpty())
3356 setMetaData(
"PrivacyCompactPolicy", compact.join(
"\n"));
3359 else if (strncasecmp(buf,
"Connection:", 11) == 0)
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)
3367 if (m_responseCode == 101) {
3369 upgradeRequired =
true;
3370 }
else if (upgradeRequired) {
3379 else if ( httpRev == HTTP_11) {
3381 if (strncasecmp(buf,
"Transfer-Encoding:", 18) == 0) {
3385 addEncoding(trimLead(buf + 18), m_qTransferEncodings);
3389 else if (strncasecmp(buf,
"Content-MD5:", 12) == 0) {
3390 m_sContentMD5 = TQString::fromLatin1(trimLead(buf + 12));
3395 else if (strncasecmp(buf,
"DAV:", 4) == 0) {
3396 if (m_davCapabilities.isEmpty()) {
3397 m_davCapabilities << TQString::fromLatin1(trimLead(buf + 4));
3400 m_davCapabilities << TQString::fromLatin1(trimLead(buf + 4));
3405 else if ((httpRev == HTTP_None) && (strlen(buf) != 0))
3411 m_prevResponseCode = m_responseCode;
3413 m_responseCode = 200;
3414 httpRev = HTTP_Unknown;
3415 m_bKeepAlive =
false;
3421 memset(buffer, 0,
sizeof(buffer));
3423 }
while (!m_bEOF && (len || noHeader) && (headerSize < maxHeaderSize) && (gets(buffer,
sizeof(buffer)-1)));
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);
3435 }
else if (*opt ==
"HTTP/1.1") {
3439 if (upgradeRequired) {
3440 error(ERR_UPGRADE_REQUIRED, *opt);
3446 setMetaData(
"charset", m_request.strCharset);
3449 if ( (m_responseCode == 401 && Authentication == AUTH_None) ||
3450 (m_responseCode == 407 && ProxyAuthentication == AUTH_None) )
3452 m_bUnauthorized =
false;
3453 if (m_request.bErrorPage)
3457 error( ERR_UNSUPPORTED_ACTION,
"Unknown Authorization method!" );
3463 if (expireDate && (expireDate <= dateHeader))
3469 else if (maxAge > 0)
3472 maxAge -= currentAge;
3475 expireDate = time(0) + maxAge;
3480 time_t lastModifiedDate = 0;
3481 if (!m_request.lastModified.isEmpty())
3482 lastModifiedDate = KRFCDate::parseDate(m_request.lastModified);
3484 if (lastModifiedDate)
3486 long diff =
static_cast<long>(difftime(dateHeader, lastModifiedDate));
3488 expireDate = time(0) + 1;
3490 expireDate = time(0) + (diff / 10);
3494 expireDate = time(0) + DEFAULT_CACHE_EXPIRE;
3499 if (!cookieStr.isEmpty())
3501 if ((m_request.cookieMode == HTTPRequest::CookiesAuto) && m_request.bUseCookiejar)
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 );
3509 else if (m_request.cookieMode == HTTPRequest::CookiesManual)
3512 setMetaData(
"setcookies", cookieStr);
3516 if (m_request.bMustRevalidate)
3518 m_request.bMustRevalidate =
false;
3523 fclose(m_request.fcache);
3524 m_request.fcache = 0;
3525 updateExpireDate( expireDate,
true );
3526 m_request.fcache = checkCacheEntry( );
3528 if (m_request.fcache)
3530 m_request.bCachedRead =
true;
3541 fclose(m_request.fcache);
3542 m_request.fcache = 0;
3554 if (!m_bChunked && (m_iSize == NO_SIZE))
3555 m_bKeepAlive =
false;
3557 if ( m_responseCode == 204 )
3563 if ( m_bUnauthorized )
3565 if ( (m_responseCode == 401) ||
3566 (m_bUseProxy && (m_responseCode == 407))
3569 if ( getAuthorization() )
3572 if ( Authentication == AUTH_NTLM && m_strAuthorization.length() > 4 )
3574 m_bKeepAlive =
true;
3577 else if (ProxyAuthentication == AUTH_NTLM && m_strProxyAuthorization.length() > 4)
3582 httpCloseConnection();
3591 m_bUnauthorized =
false;
3595 if (!locationStr.isEmpty())
3597 KURL u(m_request.url, locationStr);
3600 error(ERR_MALFORMED_URL, u.url());
3603 if ((u.protocol() !=
"http") && (u.protocol() !=
"https") &&
3604 (u.protocol() !=
"ftp") && (u.protocol() !=
"webdav") &&
3605 (u.protocol() !=
"webdavs"))
3608 error(ERR_ACCESS_DENIED, u.url());
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());
3622 m_redirectLocation = u;
3624 if (!m_request.id.isEmpty())
3629 kdDebug(7113) <<
"(" << m_pid <<
") request.url: " << m_request.url.url()
3630 << endl <<
"LocationStr: " << locationStr.data() << endl;
3632 kdDebug(7113) <<
"(" << m_pid <<
") Requesting redirection to: " << u.url()
3636 if (m_protocol ==
"webdav" || m_protocol ==
"webdavs")
3637 u.setProtocol(m_protocol);
3640 m_request.bCachedWrite =
false;
3645 if ( bCanResume && m_request.offset )
3648 m_request.offset = 0;
3651 if (m_strMimeType.startsWith(
"text/") &&
3652 (m_strMimeType !=
"text/css") &&
3653 (m_strMimeType !=
"text/x-javascript") &&
3659 if ( m_bIsSSL || (Authentication != AUTH_None) )
3661 m_request.bCachedWrite =
false;
3671 if (m_qContentEncodings.last() ==
"gzip")
3673 if (m_strMimeType ==
"application/x-tar")
3675 m_qContentEncodings.remove(m_qContentEncodings.fromLast());
3676 m_strMimeType = TQString::fromLatin1(
"application/x-tgz");
3678 else if (m_strMimeType ==
"application/postscript")
3682 m_qContentEncodings.remove(m_qContentEncodings.fromLast());
3683 m_strMimeType = TQString::fromLatin1(
"application/x-gzpostscript");
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" )
3691 m_qContentEncodings.remove(m_qContentEncodings.fromLast());
3692 m_strMimeType = TQString::fromLatin1(
"application/x-gzpostscript");
3694 else if ( (m_request.allowCompressedPage &&
3695 m_strMimeType ==
"text/html")
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")
3708 m_qContentEncodings.remove(m_qContentEncodings.fromLast());
3709 m_strMimeType = TQString::fromLatin1(
"application/x-gzip");
3719 if (m_qContentEncodings.last() ==
"bzip2")
3721 m_qContentEncodings.remove(m_qContentEncodings.fromLast());
3722 m_strMimeType = TQString::fromLatin1(
"application/x-bzip2");
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");
3746 else if (m_strMimeType ==
"application/pkix-cert" ||
3747 m_strMimeType ==
"application/binary-certificate")
3749 m_strMimeType = TQString::fromLatin1(
"application/x-x509-ca-cert");
3753 else if (m_strMimeType ==
"application/x-gzip")
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");
3763 else if ((m_strMimeType ==
"text/plain") || (m_strMimeType ==
"application/octet-stream"))
3765 TQString ext = m_request.url.path().right(4).upper();
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");
3782 if (!m_qContentEncodings.isEmpty())
3789 if( !dispositionType.isEmpty() )
3791 kdDebug(7113) <<
"(" << m_pid <<
") Setting Content-Disposition type to: "
3792 << dispositionType << endl;
3793 setMetaData(
"content-disposition-type", dispositionType);
3795 if( !dispositionFilename.isEmpty() )
3797 kdDebug(7113) <<
"(" << m_pid <<
") Setting Content-Disposition filename to: "
3798 << dispositionFilename << endl;
3800 setMetaData(
"content-disposition", dispositionFilename);
3801 setMetaData(
"content-disposition-filename", dispositionFilename);
3804 if (!m_request.lastModified.isEmpty())
3805 setMetaData(
"modified", m_request.lastModified);
3809 setMetaData(
"no-cache",
"true");
3810 setMetaData(
"expire-date",
"1");
3815 tmp.setNum(expireDate);
3816 setMetaData(
"expire-date", tmp);
3817 tmp.setNum(time(0));
3818 setMetaData(
"cache-creation-date", tmp);
3823 if (locationStr.isEmpty() && (!m_strMimeType.isEmpty() ||
3824 m_request.method == HTTP_HEAD))
3826 kdDebug(7113) <<
"(" << m_pid <<
") Emitting mimetype " << m_strMimeType << endl;
3827 mimeType( m_strMimeType );
3832 forwardHttpResponseHeader();
3834 if (m_request.method == HTTP_HEAD)
3838 if (m_request.bUseCache)
3840 ::unlink( TQFile::encodeName(m_request.cef));
3841 if ( m_request.bCachedWrite && !m_strMimeType.isEmpty() )
3844 createCacheEntry(m_strMimeType, expireDate);
3845 if (!m_request.fcache)
3847 m_request.bCachedWrite =
false;
3848 kdDebug(7113) <<
"(" << m_pid <<
") Error creating cache entry for " << m_request.url.url()<<
"!\n";
3850 m_request.expireDate = expireDate;
3851 m_maxCacheSize = config()->readNumEntry(
"MaxCacheSize", DEFAULT_MAX_CACHE_SIZE) / 2;
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;
3860 kdDebug(7113) <<
"(" << m_pid <<
") Cache, not adding \"" << m_request.url.url() <<
"\"" << endl;
3865 void HTTPProtocol::addEncoding(TQString encoding, TQStringList &encs)
3867 encoding = encoding.stripWhiteSpace().lower();
3869 if (encoding ==
"identity") {
3871 }
else if (encoding ==
"8bit") {
3874 }
else if (encoding ==
"chunked") {
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"));
3883 }
else if ((encoding ==
"x-deflate") || (encoding ==
"deflate")) {
3884 encs.append(TQString::fromLatin1(
"deflate"));
3886 kdDebug(7113) <<
"(" << m_pid <<
") Unknown encoding encountered. "
3887 <<
"Please write code. Encoding = \"" << encoding
3892 bool HTTPProtocol::sendBody()
3897 infoMessage( i18n(
"Requesting data to send" ) );
3902 if ( !m_bufPOST.isNull() )
3904 kdDebug(7113) <<
"(" << m_pid <<
") POST'ing saved data..." << endl;
3907 length = m_bufPOST.size();
3911 kdDebug(7113) <<
"(" << m_pid <<
") POST'ing live data..." << endl;
3916 m_bufPOST.resize(0);
3920 result = readData( buffer );
3924 old_size = m_bufPOST.size();
3925 m_bufPOST.resize( old_size+result );
3926 memcpy( m_bufPOST.data()+ old_size, buffer.data(), buffer.size() );
3929 }
while ( result > 0 );
3934 error( ERR_ABORTED, m_request.hostname );
3938 infoMessage( i18n(
"Sending data to %1" ).arg( m_request.hostname ) );
3940 TQString size = TQString (
"Content-Length: %1\r\n\r\n").arg(length);
3941 kdDebug( 7113 ) <<
"(" << m_pid <<
")" << size << endl;
3944 bool sendOk = (write(size.latin1(), size.length()) == (ssize_t) size.length());
3947 kdDebug( 7113 ) <<
"(" << m_pid <<
") Connection broken when sending "
3948 <<
"content length: (" << m_state.hostname <<
")" << endl;
3949 error( ERR_CONNECTION_BROKEN, m_state.hostname );
3955 sendOk = (write(m_bufPOST.data(), m_bufPOST.size()) == (ssize_t) m_bufPOST.size());
3958 kdDebug(7113) <<
"(" << m_pid <<
") Connection broken when sending message body: ("
3959 << m_state.hostname <<
")" << endl;
3960 error( ERR_CONNECTION_BROKEN, m_state.hostname );
3967 void HTTPProtocol::httpClose(
bool keepAlive )
3969 kdDebug(7113) <<
"(" << m_pid <<
") HTTPProtocol::httpClose" << endl;
3971 if (m_request.fcache)
3973 fclose(m_request.fcache);
3974 m_request.fcache = 0;
3975 if (m_request.bCachedWrite)
3977 TQString filename = m_request.cef +
".new";
3978 ::unlink( TQFile::encodeName(filename) );
3986 if (keepAlive && (!m_bUseProxy ||
3987 m_bPersistentProxyConnection || m_bIsTunneled))
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;
3994 kdDebug(7113) <<
"(" << m_pid <<
") HTTPProtocol::httpClose: keep alive (" << m_keepAliveTimeout <<
")" << endl;
3996 TQDataStream stream( data, IO_WriteOnly );
3998 setTimeoutSpecialCommand(m_keepAliveTimeout, data);
4002 httpCloseConnection();
4005 void HTTPProtocol::closeConnection()
4007 kdDebug(7113) <<
"(" << m_pid <<
") HTTPProtocol::closeConnection" << endl;
4008 httpCloseConnection ();
4011 void HTTPProtocol::httpCloseConnection ()
4013 kdDebug(7113) <<
"(" << m_pid <<
") HTTPProtocol::httpCloseConnection" << endl;
4014 m_bIsTunneled =
false;
4015 m_bKeepAlive =
false;
4017 setTimeoutSpecialCommand(-1);
4020 void HTTPProtocol::slave_status()
4022 kdDebug(7113) <<
"(" << m_pid <<
") HTTPProtocol::slave_status" << endl;
4024 if ( m_iSock != -1 && !isConnectionValid() )
4025 httpCloseConnection();
4027 slaveStatus( m_state.hostname, (m_iSock != -1) );
4030 void HTTPProtocol::mimetype(
const KURL& url )
4032 kdDebug(7113) <<
"(" << m_pid <<
") HTTPProtocol::mimetype: "
4033 << url.prettyURL() << endl;
4035 if ( !checkRequestURL( url ) )
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;
4046 kdDebug(7113) <<
"(" << m_pid <<
") http: mimetype = " << m_strMimeType
4050 void HTTPProtocol::special(
const TQByteArray &data )
4052 kdDebug(7113) <<
"(" << m_pid <<
") HTTPProtocol::special" << endl;
4055 TQDataStream stream(data, IO_ReadOnly);
4071 stream >> url >> no_cache >> expireDate;
4072 cacheUpdate( url, no_cache, expireDate );
4078 TQString scope, type, owner;
4079 stream >> url >> scope >> type >> owner;
4080 davLock( url, scope, type, owner );
4094 stream >> url >> method;
4095 davGeneric( url, (TDEIO::HTTP_METHOD) method );
4100 httpCloseConnection();
4113 int HTTPProtocol::readChunked()
4115 if ((m_iBytesLeft == 0) || (m_iBytesLeft == NO_SIZE))
4119 m_bufReceive.resize(4096);
4121 if (!gets(m_bufReceive.data(), m_bufReceive.size()-1))
4123 kdDebug(7113) <<
"(" << m_pid <<
") gets() failure on Chunk header" << endl;
4128 if (m_bufReceive[0] ==
'\0')
4130 if (!gets(m_bufReceive.data(), m_bufReceive.size()-1))
4132 kdDebug(7113) <<
"(" << m_pid <<
") gets() failure on Chunk header" << endl;
4142 kdDebug(7113) <<
"(" << m_pid <<
") EOF on Chunk header" << endl;
4147 long long trunkSize = STRTOLL(m_bufReceive.data(), 0, 16);
4150 kdDebug(7113) <<
"(" << m_pid <<
") Negative chunk size" << endl;
4153 m_iBytesLeft = trunkSize;
4157 if (m_iBytesLeft == 0)
4163 if (!gets(m_bufReceive.data(), m_bufReceive.size()-1))
4165 kdDebug(7113) <<
"(" << m_pid <<
") gets() failure on Chunk trailer" << endl;
4170 while (strlen(m_bufReceive.data()) != 0);
4176 int bytesReceived = readLimited();
4178 m_iBytesLeft = NO_SIZE;
4181 return bytesReceived;
4184 int HTTPProtocol::readLimited()
4189 m_bufReceive.resize(4096);
4194 if (m_iBytesLeft > m_bufReceive.size())
4195 bytesToReceive = m_bufReceive.size();
4197 bytesToReceive = m_iBytesLeft;
4199 bytesReceived = read(m_bufReceive.data(), bytesToReceive);
4201 if (bytesReceived <= 0)
4204 m_iBytesLeft -= bytesReceived;
4205 return bytesReceived;
4208 int HTTPProtocol::readUnlimited()
4212 kdDebug(7113) <<
"(" << m_pid <<
") Unbounded datastream on a Keep "
4213 <<
"alive connection!" << endl;
4214 m_bKeepAlive =
false;
4217 m_bufReceive.resize(4096);
4219 int result = read(m_bufReceive.data(), m_bufReceive.size());
4228 void HTTPProtocol::slotData(
const TQByteArray &_d)
4236 if (m_iContentLeft != NO_SIZE)
4238 if (m_iContentLeft >= _d.size())
4239 m_iContentLeft -= _d.size();
4241 m_iContentLeft = NO_SIZE;
4245 if ( !m_dataInternal )
4250 if ( m_strMimeType.isEmpty() && !m_bRedirect &&
4251 !( m_responseCode >= 300 && m_responseCode <=399) )
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) )
4260 m_cpMimeBuffer =
true;
4264 kdDebug(7113) <<
"(" << m_pid <<
") Mimetype buffer size: " << m_mimeTypeBuffer.size()
4267 KMimeMagicResult *result;
4268 result = KMimeMagic::self()->findBufferFileType( m_mimeTypeBuffer,
4269 m_request.url.fileName() );
4272 m_strMimeType = result->mimeType();
4273 kdDebug(7113) <<
"(" << m_pid <<
") Mimetype from content: "
4274 << m_strMimeType << endl;
4277 if ( m_strMimeType.isEmpty() )
4279 m_strMimeType = TQString::fromLatin1( DEFAULT_MIME_TYPE );
4280 kdDebug(7113) <<
"(" << m_pid <<
") Using default mimetype: "
4281 << m_strMimeType << endl;
4284 if ( m_request.bCachedWrite )
4286 createCacheEntry( m_strMimeType, m_request.expireDate );
4287 if (!m_request.fcache)
4288 m_request.bCachedWrite =
false;
4291 if ( m_cpMimeBuffer )
4297 d.resize(m_mimeTypeBuffer.size());
4298 memcpy( d.data(), m_mimeTypeBuffer.data(),
4301 mimeType(m_strMimeType);
4302 m_mimeTypeBuffer.resize(0);
4306 if (m_request.bCachedWrite && m_request.fcache)
4307 writeCacheEntry(d.data(), d.size());
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());
4326 bool HTTPProtocol::readBody(
bool dataInternal )
4328 if (m_responseCode == 204)
4337 m_dataInternal = dataInternal;
4339 m_bufWebDavData.resize (0);
4343 bool useMD5 = !m_sContentMD5.isEmpty();
4346 TDEIO::filesize_t sz = m_request.offset;
4354 if ( !dataInternal ) {
4355 if ( (m_iSize > 0) && (m_iSize != NO_SIZE)) {
4357 infoMessage( i18n(
"Retrieving %1 from %2...").arg(TDEIO::convertSize(m_iSize))
4358 .arg( m_request.hostname ) );
4366 infoMessage( i18n(
"Retrieving from %1..." ).arg( m_request.hostname ) );
4368 if (m_request.bCachedRead)
4370 kdDebug(7113) <<
"(" << m_pid <<
") HTTPProtocol::readBody: read data from cache!" << endl;
4371 m_request.bCachedWrite =
false;
4373 char buffer[ MAX_IPC_SIZE ];
4375 m_iContentLeft = NO_SIZE;
4378 while (!feof(m_request.fcache) && !ferror(m_request.fcache))
4380 int nbytes = fread( buffer, 1, MAX_IPC_SIZE, m_request.fcache);
4384 m_bufReceive.setRawData( buffer, nbytes);
4385 slotData( m_bufReceive );
4386 m_bufReceive.resetRawData( buffer, nbytes );
4391 m_bufReceive.resize( 0 );
4393 if ( !dataInternal )
4395 processedSize( sz );
4396 data( TQByteArray() );
4403 if (m_iSize != NO_SIZE)
4404 m_iBytesLeft = m_iSize - sz;
4406 m_iBytesLeft = NO_SIZE;
4408 m_iContentLeft = m_iBytesLeft;
4411 m_iBytesLeft = NO_SIZE;
4413 kdDebug(7113) <<
"(" << m_pid <<
") HTTPProtocol::readBody: retrieve data. "
4414 << TDEIO::number(m_iBytesLeft) <<
" left." << endl;
4417 m_cpMimeBuffer =
false;
4418 m_mimeTypeBuffer.resize(0);
4419 struct timeval last_tv;
4420 gettimeofday( &last_tv, 0L );
4422 HTTPFilterChain chain;
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 &)));
4430 while (!m_qTransferEncodings.isEmpty())
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);
4446 HTTPFilterMD5 *md5Filter = 0;
4449 md5Filter =
new HTTPFilterMD5;
4450 chain.addFilter(md5Filter);
4461 while (!m_qContentEncodings.isEmpty())
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);
4476 bytesReceived = readChunked();
4477 else if (m_iSize != NO_SIZE)
4478 bytesReceived = readLimited();
4480 bytesReceived = readUnlimited();
4486 if (bytesReceived == -1)
4488 if (m_iContentLeft == 0)
4496 kdDebug(7113) <<
"(" << m_pid <<
") readBody: bytesReceived==-1 sz=" << (int)sz
4497 <<
" Connnection broken !" << endl;
4498 error(ERR_CONNECTION_BROKEN, m_state.hostname);
4504 if (bytesReceived > 0)
4508 m_bufReceive.truncate( bytesReceived );
4510 chain.slotInput(m_bufReceive);
4515 sz += bytesReceived;
4517 processedSize( sz );
4519 m_bufReceive.resize(0);
4521 if (m_iBytesLeft && m_bEOD && !m_bChunked)
4528 if (m_iBytesLeft == 0)
4530 kdDebug(7113) <<
"("<<m_pid<<
") EOD received! Left = "<< TDEIO::number(m_iBytesLeft) << endl;
4534 chain.slotInput(TQByteArray());
4538 TQString calculatedMD5 = md5Filter->md5();
4540 if ( m_sContentMD5 == calculatedMD5 )
4541 kdDebug(7113) <<
"(" << m_pid <<
") MD5 checksum MATCHED!!" << endl;
4543 kdDebug(7113) <<
"(" << m_pid <<
") MD5 checksum MISMATCH! Expected: "
4544 << calculatedMD5 <<
", Got: " << m_sContentMD5 << endl;
4548 if (m_iBytesLeft == 0)
4550 if (m_request.bCachedWrite && m_request.fcache)
4552 else if (m_request.bCachedWrite)
4553 kdDebug(7113) <<
"(" << m_pid <<
") no cache file!\n";
4557 kdDebug(7113) <<
"(" << m_pid <<
") still "<< TDEIO::number(m_iBytesLeft)
4558 <<
" bytes left! can't close cache entry!\n";
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);
4572 data( TQByteArray() );
4578 void HTTPProtocol::error(
int _err,
const TQString &_text )
4582 if (!m_request.id.isEmpty())
4584 forwardHttpResponseHeader();
4589 if (!m_bufPOST.isEmpty())
4591 m_bufPOST.resize(0);
4592 kdDebug(7113) <<
"(" << m_pid <<
") HTTP::retreiveHeader: Cleared POST "
4593 "buffer..." << endl;
4596 SlaveBase::error( _err, _text );
4601 void HTTPProtocol::addCookies(
const TQString &url,
const TQCString &cookieHeader )
4603 long windowId = m_request.window.toLong();
4605 TQDataStream stream(params, IO_WriteOnly);
4606 stream << url << cookieHeader << windowId;
4608 kdDebug(7113) <<
"(" << m_pid <<
") " << cookieHeader << endl;
4609 kdDebug(7113) <<
"(" << m_pid <<
") " <<
"Window ID: "
4610 << windowId <<
", for host = " << url << endl;
4612 if ( !dcopClient()->send(
"kded",
"kcookiejar",
"addCookies(TQString,TQCString,long int)", params ) )
4614 kdWarning(7113) <<
"(" << m_pid <<
") Can't communicate with kded_kcookiejar!" << endl;
4618 TQString HTTPProtocol::findCookies(
const TQString &url)
4620 TQCString replyType;
4625 long windowId = m_request.window.toLong();
4626 result = TQString::null;
4627 TQDataStream stream(params, IO_WriteOnly);
4628 stream << url << windowId;
4630 if ( !dcopClient()->call(
"kded",
"kcookiejar",
"findCookies(TQString,long int)",
4631 params, replyType, reply ) )
4633 kdWarning(7113) <<
"(" << m_pid <<
") Can't communicate with kded_kcookiejar!" << endl;
4636 if ( replyType ==
"TQString" )
4638 TQDataStream stream2( reply, IO_ReadOnly );
4643 kdError(7113) <<
"(" << m_pid <<
") DCOP function findCookies(...) returns "
4644 << replyType <<
", expected TQString" << endl;
4652 void HTTPProtocol::cacheUpdate(
const KURL& url,
bool no_cache, time_t expireDate)
4654 if ( !checkRequestURL( url ) )
4657 m_request.path = url.path();
4658 m_request.query = url.query();
4659 m_request.cache = CC_Reload;
4660 m_request.doProxy = m_bUseProxy;
4664 m_request.fcache = checkCacheEntry( );
4665 if (m_request.fcache)
4667 fclose(m_request.fcache);
4668 m_request.fcache = 0;
4669 ::unlink( TQFile::encodeName(m_request.cef) );
4674 updateExpireDate( expireDate );
4683 FILE* HTTPProtocol::checkCacheEntry(
bool readWrite)
4685 const TQChar separator =
'_';
4687 TQString CEF = m_request.path;
4689 int p = CEF.find(
'/');
4694 p = CEF.find(
'/', p);
4697 TQString host = m_request.hostname.lower();
4698 CEF = host + CEF +
'_';
4700 TQString dir = m_strCacheDir;
4701 if (dir[dir.length()-1] !=
'/')
4704 int l = host.length();
4705 for(
int i = 0; i < l; i++)
4707 if (host[i].isLetter() && (host[i] !=
'w'))
4713 if (dir[dir.length()-1] ==
'/')
4716 unsigned long hash = 0x00000000;
4717 TQCString u = m_request.url.url().latin1();
4718 for(
int i = u.length(); i--;)
4720 hash = (hash * 12211 +
static_cast<const char>(u.at(i))) % 2147483563;
4723 TQString hashString;
4724 hashString.sprintf(
"%08lx", hash);
4726 CEF = CEF + hashString;
4728 CEF = dir +
"/" + CEF;
4730 m_request.cef = CEF;
4732 const char *mode = (readWrite ?
"r+" :
"r");
4734 FILE *fs = fopen( TQFile::encodeName(CEF), mode);
4742 if (ok && (!fgets(buffer, 400, fs)))
4744 if (ok && (strcmp(buffer, CACHE_REVISION) != 0))
4748 time_t currentDate = time(0);
4751 if (ok && (!fgets(buffer, 400, fs)))
4755 int l = strlen(buffer);
4758 if (m_request.url.url() != buffer)
4765 if (ok && (!fgets(buffer, 400, fs)))
4769 date = (time_t) strtoul(buffer, 0, 10);
4770 m_request.creationDate = date;
4771 if (m_maxCacheAge && (difftime(currentDate, date) > m_maxCacheAge))
4773 m_request.bMustRevalidate =
true;
4774 m_request.expireDate = currentDate;
4779 m_request.cacheExpireDateOffset = ftell(fs);
4780 if (ok && (!fgets(buffer, 400, fs)))
4784 if (m_request.cache == CC_Verify)
4786 date = (time_t) strtoul(buffer, 0, 10);
4788 if (!date || difftime(currentDate, date) >= 0)
4789 m_request.bMustRevalidate =
true;
4790 m_request.expireDate = date;
4792 else if (m_request.cache == CC_Refresh)
4794 m_request.bMustRevalidate =
true;
4795 m_request.expireDate = currentDate;
4800 if (ok && (!fgets(buffer, 400, fs)))
4804 m_request.etag = TQString(buffer).stripWhiteSpace();
4808 if (ok && (!fgets(buffer, 400, fs)))
4812 m_request.lastModified = TQString(buffer).stripWhiteSpace();
4819 unlink( TQFile::encodeName(CEF));
4823 void HTTPProtocol::updateExpireDate(time_t expireDate,
bool updateCreationDate)
4827 FILE *fs = checkCacheEntry(
true);
4832 time_t creationDate;
4834 fseek(fs, 0, SEEK_SET);
4835 if (ok && !fgets(buffer, 400, fs))
4837 if (ok && !fgets(buffer, 400, fs))
4839 long cacheCreationDateOffset = ftell(fs);
4840 if (ok && !fgets(buffer, 400, fs))
4842 creationDate = strtoul(buffer, 0, 10);
4846 if (updateCreationDate)
4848 if (!ok || fseek(fs, cacheCreationDateOffset, SEEK_SET))
4851 date.setNum( time(0) );
4852 date = date.leftJustify(16);
4853 fputs(date.latin1(), fs);
4857 if (expireDate>(30*365*24*60*60))
4861 date.setNum( expireDate );
4870 date.setNum( creationDate + expireDate );
4872 date = date.leftJustify(16);
4873 if (!ok || fseek(fs, m_request.cacheExpireDateOffset, SEEK_SET))
4875 fputs(date.latin1(), fs);
4876 fseek(fs, 0, SEEK_END);
4881 void HTTPProtocol::createCacheEntry(
const TQString &mimetype, time_t expireDate)
4883 TQString dir = m_request.cef;
4884 int p = dir.findRev(
'/');
4885 if (p == -1)
return;
4889 (void) ::mkdir( TQFile::encodeName(dir), 0700 );
4891 TQString filename = m_request.cef +
".new";
4895 m_request.fcache = fopen( TQFile::encodeName(filename),
"w");
4896 if (!m_request.fcache)
4898 kdWarning(7113) <<
"(" << m_pid <<
")createCacheEntry: opening " << filename <<
" failed." << endl;
4902 fputs(CACHE_REVISION, m_request.fcache);
4904 fputs(m_request.url.url().latin1(), m_request.fcache);
4905 fputc(
'\n', m_request.fcache);
4908 m_request.creationDate = time(0);
4909 date.setNum( m_request.creationDate );
4910 date = date.leftJustify(16);
4911 fputs(date.latin1(), m_request.fcache);
4912 fputc(
'\n', m_request.fcache);
4914 date.setNum( expireDate );
4915 date = date.leftJustify(16);
4916 fputs(date.latin1(), m_request.fcache);
4917 fputc(
'\n', m_request.fcache);
4919 if (!m_request.etag.isEmpty())
4920 fputs(m_request.etag.latin1(), m_request.fcache);
4921 fputc(
'\n', m_request.fcache);
4923 if (!m_request.lastModified.isEmpty())
4924 fputs(m_request.lastModified.latin1(), m_request.fcache);
4925 fputc(
'\n', m_request.fcache);
4927 fputs(mimetype.latin1(), m_request.fcache);
4928 fputc(
'\n', m_request.fcache);
4930 if (!m_request.strCharset.isEmpty())
4931 fputs(m_request.strCharset.latin1(), m_request.fcache);
4932 fputc(
'\n', m_request.fcache);
4940 void HTTPProtocol::writeCacheEntry(
const char *buffer,
int nbytes)
4942 if (fwrite( buffer, nbytes, 1, m_request.fcache) != 1)
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) );
4951 long file_pos = ftell( m_request.fcache ) / 1024;
4952 if ( file_pos > m_maxCacheSize )
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) );
4964 void HTTPProtocol::closeCacheEntry()
4966 TQString filename = m_request.cef +
".new";
4967 int result = fclose( m_request.fcache);
4968 m_request.fcache = 0;
4971 if (::rename( TQFile::encodeName(filename), TQFile::encodeName(m_request.cef)) == 0)
4974 kdWarning(7113) <<
"(" << m_pid <<
") closeCacheEntry: error renaming "
4975 <<
"cache entry. (" << filename <<
" -> " << m_request.cef
4979 kdWarning(7113) <<
"(" << m_pid <<
") closeCacheEntry: error closing cache "
4980 <<
"entry. (" << filename<<
")" << endl;
4983 void HTTPProtocol::cleanCache()
4985 const time_t maxAge = DEFAULT_CLEAN_CACHE_INTERVAL;
4986 bool doClean =
false;
4987 TQString cleanFile = m_strCacheDir;
4988 if (cleanFile[cleanFile.length()-1] !=
'/')
4990 cleanFile +=
"cleaned";
4992 struct stat stat_buf;
4994 int result = ::stat(TQFile::encodeName(cleanFile), &stat_buf);
4997 int fd = creat( TQFile::encodeName(cleanFile), 0600);
5006 time_t age = (time_t) difftime( time(0), stat_buf.st_mtime );
5013 utime(TQFile::encodeName(cleanFile), 0);
5014 TDEApplication::startServiceByDesktopPath(
"http_cache_cleaner.desktop");
5023 void HTTPProtocol::configAuth(
char *p,
bool isForProxy )
5025 HTTP_AUTH f = AUTH_None;
5026 const char *strAuth = p;
5028 if ( strncasecmp( p,
"Basic", 5 ) == 0 )
5034 else if ( strncasecmp (p,
"Digest", 6) == 0 )
5037 memcpy((
void *)p,
"Digest", 6);
5040 else if (strncasecmp( p,
"MBS_PWD_COOKIE", 14 ) == 0)
5047 #ifdef HAVE_LIBGSSAPI
5048 else if ( strncasecmp( p,
"Negotiate", 9 ) == 0 )
5052 if ( !isForProxy && !(m_responseCode == 401 && m_prevResponseCode == 401) )
5055 memcpy((
void *)p,
"Negotiate", 9);
5060 else if ( strncasecmp( p,
"NTLM", 4 ) == 0 )
5063 memcpy((
void *)p,
"NTLM", 4);
5065 m_strRealm =
"NTLM";
5069 kdWarning(7113) <<
"(" << m_pid <<
") Unsupported or invalid authorization "
5070 <<
"type requested" << endl;
5072 kdWarning(7113) <<
"(" << m_pid <<
") Proxy URL: " << m_proxyURL << endl;
5074 kdWarning(7113) <<
"(" << m_pid <<
") URL: " << m_request.url << endl;
5075 kdWarning(7113) <<
"(" << m_pid <<
") Request Authorization: " << p << endl;
5087 if ((f == AUTH_None) ||
5088 ((m_iProxyAuthCount > 0) && (f < ProxyAuthentication)))
5094 if ( m_iProxyAuthCount == 0)
5095 ProxyAuthentication = f;
5096 kdDebug(7113) <<
"(" << m_pid <<
") Rejected proxy auth method: " << f << endl;
5099 m_iProxyAuthCount++;
5100 kdDebug(7113) <<
"(" << m_pid <<
") Accepted proxy auth method: " << f << endl;
5104 if ((f == AUTH_None) ||
5105 ((m_iWWWAuthCount > 0) && (f < Authentication)))
5107 kdDebug(7113) <<
"(" << m_pid <<
") Rejected auth method: " << f << endl;
5111 kdDebug(7113) <<
"(" << m_pid <<
") Accepted auth method: " << f << endl;
5118 while( (*p ==
' ') || (*p ==
',') || (*p ==
'\t') ) { p++; }
5119 if ( strncasecmp( p,
"realm=", 6 ) == 0 )
5122 TQTextCodec* oldCodec=TQTextCodec::codecForCStrings();
5123 if (TDEGlobal::locale()->language().contains(
"ru"))
5124 TQTextCodec::setCodecForCStrings(TQTextCodec::codecForName(
"CP1251"));
5128 while( p[i] && p[i] !=
'"' ) i++;
5130 m_strProxyRealm = TQString::fromAscii( p, i );
5132 m_strRealm = TQString::fromAscii( p, i );
5134 TQTextCodec::setCodecForCStrings(oldCodec);
5143 ProxyAuthentication = f;
5144 m_strProxyAuthorization = TQString::fromLatin1( strAuth );
5149 m_strAuthorization = TQString::fromLatin1( strAuth );
5154 bool HTTPProtocol::retryPrompt()
5157 switch ( m_responseCode )
5160 prompt = i18n(
"Authentication Failed.");
5163 prompt = i18n(
"Proxy Authentication Failed.");
5168 prompt += i18n(
" Do you want to retry?");
5169 return (messageBox(QuestionYesNo, prompt, i18n(
"Authentication")) == 3);
5172 void HTTPProtocol::promptInfo( AuthInfo& info )
5174 if ( m_responseCode == 401 )
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;
5183 if ( !m_strRealm.isEmpty() )
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 );
5192 else if ( m_responseCode == 407 )
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() )
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() );
5211 bool HTTPProtocol::getAuthorization()
5214 bool result =
false;
5216 kdDebug (7113) <<
"(" << m_pid <<
") HTTPProtocol::getAuthorization: "
5217 <<
"Current Response: " << m_responseCode <<
", "
5218 <<
"Previous Response: " << m_prevResponseCode <<
", "
5219 <<
"Authentication: " << Authentication <<
", "
5220 <<
"ProxyAuthentication: " << ProxyAuthentication << endl;
5222 if (m_request.bNoAuth)
5224 if (m_request.bErrorPage)
5227 error( ERR_COULD_NOT_LOGIN, i18n(
"Authentication needed for %1 but authentication is disabled.").arg(m_request.hostname));
5231 bool repeatFailure = (m_prevResponseCode == m_responseCode);
5238 if ( Authentication == AUTH_Digest || ProxyAuthentication == AUTH_Digest )
5240 bool isStaleNonce =
false;
5241 TQString auth = ( m_responseCode == 401 ) ? m_strAuthorization : m_strProxyAuthorization;
5242 int pos = auth.find(
"stale", 0,
false);
5246 int len = auth.length();
5247 while( pos < len && (auth[pos] ==
' ' || auth[pos] ==
'=') ) pos++;
5248 if ( pos < len && auth.find(
"true", pos,
false) != -1 )
5250 isStaleNonce =
true;
5251 kdDebug(7113) <<
"(" << m_pid <<
") Stale nonce value. "
5252 <<
"Will retry using same info..." << endl;
5259 if ( m_responseCode == 401 )
5261 info.username = m_request.user;
5262 info.password = m_request.passwd;
5263 info.realmValue = m_strRealm;
5264 info.digestInfo = m_strAuthorization;
5266 else if ( m_responseCode == 407 )
5268 info.username = m_proxyURL.user();
5269 info.password = m_proxyURL.pass();
5270 info.realmValue = m_strProxyRealm;
5271 info.digestInfo = m_strProxyAuthorization;
5276 if ( Authentication == AUTH_NTLM || ProxyAuthentication == AUTH_NTLM )
5278 TQString auth = ( m_responseCode == 401 ) ? m_strAuthorization : m_strProxyAuthorization;
5279 kdDebug(7113) <<
"auth: " << auth << endl;
5280 if ( auth.length() > 4 )
5284 kdDebug(7113) <<
"(" << m_pid <<
") NTLM auth second phase, "
5285 <<
"sending response..." << endl;
5286 if ( m_responseCode == 401 )
5288 info.username = m_request.user;
5289 info.password = m_request.passwd;
5290 info.realmValue = m_strRealm;
5291 info.digestInfo = m_strAuthorization;
5293 else if ( m_responseCode == 407 )
5295 info.username = m_proxyURL.user();
5296 info.password = m_proxyURL.pass();
5297 info.realmValue = m_strProxyRealm;
5298 info.digestInfo = m_strProxyAuthorization;
5305 switch ( m_responseCode )
5308 errorMsg = i18n(
"Authentication Failed.");
5311 errorMsg = i18n(
"Proxy Authentication Failed.");
5325 if (m_bProxyAuthValid)
5328 m_bProxyAuthValid =
false;
5329 KURL proxy ( config()->readEntry(
"UseProxy") );
5330 m_proxyURL.setUser(proxy.user());
5331 m_proxyURL.setPass(proxy.pass());
5334 info.verifyPath =
false;
5335 if ( m_responseCode == 407 )
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;
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;
5354 if ( info.username.isNull() ||
5355 info.password.isNull() )
5356 result = checkCachedAuthentication( info );
5358 if ( Authentication == AUTH_Digest )
5362 if (m_responseCode == 401)
5363 auth = m_strAuthorization;
5365 auth = m_strProxyAuthorization;
5367 int pos = auth.find(
"stale", 0,
false);
5371 int len = auth.length();
5372 while( pos < len && (auth[pos] ==
' ' || auth[pos] ==
'=') ) pos++;
5373 if ( pos < len && auth.find(
"true", pos,
false) != -1 )
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;
5388 if ( !repeatFailure &&
5389 !info.username.isNull() &&
5390 !info.password.isNull() )
5394 if (Authentication == AUTH_Negotiate)
5399 else if ( m_request.disablePassDlg ==
false )
5401 kdDebug( 7113 ) <<
"(" << m_pid <<
") Prompting the user for authorization..." << endl;
5403 result = openPassDlg( info, errorMsg );
5410 switch (m_responseCode)
5413 m_request.user = info.username;
5414 m_request.passwd = info.password;
5415 m_strRealm = info.realmValue;
5416 m_strAuthorization = info.digestInfo;
5419 m_proxyURL.setUser( info.username );
5420 m_proxyURL.setPass( info.password );
5421 m_strProxyRealm = info.realmValue;
5422 m_strProxyAuthorization = info.digestInfo;
5430 if (m_request.bErrorPage)
5433 error( ERR_USER_CANCELED, TQString::null );
5437 void HTTPProtocol::saveAuthorization()
5440 if ( m_prevResponseCode == 407 )
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 );
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 );
5463 #ifdef HAVE_LIBGSSAPI
5464 TQCString HTTPProtocol::gssError(
int major_status,
int minor_status )
5466 OM_uint32 new_status;
5467 OM_uint32 msg_ctx = 0;
5468 gss_buffer_desc major_string;
5469 gss_buffer_desc minor_string;
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;
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;
5482 }
while (!GSS_ERROR(ret) && msg_ctx != 0);
5487 TQString HTTPProtocol::createNegotiateAuth()
5490 TQCString servicename;
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;
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"};
5503 gss_OID_set mech_set;
5506 ctx = GSS_C_NO_CONTEXT;
5507 mech_oid = &krb5_oid_desc;
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;
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;
5520 mech_oid = &spnego_oid_desc;
5524 gss_release_oid_set(&minor_status, &mech_set);
5528 servicename =
"HTTP@";
5529 servicename += m_state.hostname.ascii();
5531 input_token.value = (
void *)servicename.data();
5532 input_token.length = servicename.length() + 1;
5534 major_status = gss_import_name(&minor_status, &input_token,
5535 GSS_C_NT_HOSTBASED_SERVICE, &server);
5537 input_token.value = NULL;
5538 input_token.length = 0;
5540 if (GSS_ERROR(major_status)) {
5541 kdDebug(7113) <<
"(" << m_pid <<
") gss_import_name failed: " << gssError(major_status, minor_status) << endl;
5543 m_strAuthorization = TQString::null;
5544 return TQString::null;
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,
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;
5563 m_strAuthorization = TQString::null;
5564 return TQString::null;
5567 input.duplicate((
const char *)output_token.value, output_token.length);
5568 auth =
"Authorization: Negotiate ";
5569 auth += KCodecs::base64Encode( input );
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;
5578 gss_release_buffer(&minor_status, &output_token);
5585 TQCString HTTPProtocol::gssError(
int,
int )
5591 TQString HTTPProtocol::createNegotiateAuth()
5593 return TQString::null;
5597 TQString HTTPProtocol::createNTLMAuth(
bool isForProxy )
5600 TQString auth, user, domain, passwd;
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();
5615 auth =
"Authorization: NTLM ";
5616 user = m_state.user;
5617 passwd = m_state.passwd;
5618 strauth = m_strAuthorization.latin1();
5619 len = m_strAuthorization.length();
5621 if ( user.contains(
'\\') ) {
5622 domain = user.section(
'\\', 0, 0);
5623 user = user.section(
'\\', 1 );
5626 kdDebug(7113) <<
"(" << m_pid <<
") NTLM length: " << len << endl;
5627 if ( user.isEmpty() || passwd.isEmpty() || len < 4 )
5628 return TQString::null;
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 );
5640 KNTLM::getNegotiate( buf );
5645 m_strProxyAuthorization =
"NTLM";
5647 m_strAuthorization =
"NTLM";
5649 auth += KCodecs::base64Encode( buf );
5655 TQString HTTPProtocol::createBasicAuth(
bool isForProxy )
5658 TQCString user, passwd;
5661 auth =
"Proxy-Authorization: Basic ";
5662 user = m_proxyURL.user().latin1();
5663 passwd = m_proxyURL.pass().latin1();
5667 auth =
"Authorization: Basic ";
5668 user = m_state.user.latin1();
5669 passwd = m_state.passwd.latin1();
5672 if ( user.isEmpty() )
5674 if ( passwd.isEmpty() )
5679 auth += KCodecs::base64Encode( user );
5685 void HTTPProtocol::calculateResponse( DigestAuthInfo& info, TQCString& Response )
5692 TQCString authStr = info.username;
5694 authStr += info.realm;
5696 authStr += info.password;
5697 md.update( authStr );
5699 if ( info.algorithm.lower() ==
"md5-sess" )
5701 authStr = md.hexDigest();
5703 authStr += info.nonce;
5705 authStr += info.cnonce;
5707 md.update( authStr );
5709 HA1 = md.hexDigest();
5711 kdDebug(7113) <<
"(" << m_pid <<
") calculateResponse(): A1 => " << HA1 << endl;
5714 authStr = info.method;
5716 authStr += m_request.url.encodedPathAndQuery(0,
true).latin1();
5717 if ( info.qop ==
"auth-int" )
5720 authStr += info.entityBody;
5723 md.update( authStr );
5724 HA2 = md.hexDigest();
5726 kdDebug(7113) <<
"(" << m_pid <<
") calculateResponse(): A2 => "
5732 authStr += info.nonce;
5734 if ( !info.qop.isEmpty() )
5738 authStr += info.cnonce;
5740 authStr += info.qop;
5745 md.update( authStr );
5746 Response = md.hexDigest();
5748 kdDebug(7113) <<
"(" << m_pid <<
") calculateResponse(): Response => "
5749 << Response << endl;
5752 TQString HTTPProtocol::createDigestAuth (
bool isForProxy )
5760 DigestAuthInfo info;
5765 auth =
"Proxy-Authorization: Digest ";
5766 info.username = m_proxyURL.user().latin1();
5767 info.password = m_proxyURL.pass().latin1();
5768 p = m_strProxyAuthorization.latin1();
5772 auth =
"Authorization: Digest ";
5773 info.username = m_state.user.latin1();
5774 info.password = m_state.passwd.latin1();
5775 p = m_strAuthorization.latin1();
5778 return TQString::null;
5782 if ( info.username.isEmpty() || info.password.isEmpty() || !p )
5783 return TQString::null;
5787 info.algorithm =
"MD5";
5792 info.cnonce = TDEApplication::randomString(16).latin1();
5795 info.nc =
"00000001";
5798 switch ( m_request.method )
5801 info.method =
"GET";
5804 info.method =
"PUT";
5807 info.method =
"POST";
5810 info.method =
"HEAD";
5813 info.method =
"DELETE";
5816 info.method =
"PROPFIND";
5819 info.method =
"PROPPATCH";
5822 info.method =
"MKCOL";
5825 info.method =
"COPY";
5828 info.method =
"MOVE";
5831 info.method =
"LOCK";
5834 info.method =
"UNLOCK";
5837 info.method =
"SEARCH";
5840 info.method =
"SUBSCRIBE";
5842 case DAV_UNSUBSCRIBE:
5843 info.method =
"UNSUBSCRIBE";
5846 info.method =
"POLL";
5849 error( ERR_UNSUPPORTED_ACTION, i18n(
"Unsupported method: authentication will fail. Please submit a bug report."));
5857 while ( (*p ==
' ') || (*p ==
',') || (*p ==
'\t')) { p++; }
5858 if (strncasecmp(p,
"realm=", 6 )==0)
5861 while ( *p ==
'"' ) p++;
5862 while ( p[i] !=
'"' ) i++;
5863 info.realm = TQCString( p, i+1 );
5865 else if (strncasecmp(p,
"algorith=", 9)==0)
5868 while ( *p ==
'"' ) p++;
5869 while ( ( p[i] !=
'"' ) && ( p[i] !=
',' ) && ( p[i] !=
'\0' ) ) i++;
5870 info.algorithm = TQCString(p, i+1);
5872 else if (strncasecmp(p,
"algorithm=", 10)==0)
5875 while ( *p ==
'"' ) p++;
5876 while ( ( p[i] !=
'"' ) && ( p[i] !=
',' ) && ( p[i] !=
'\0' ) ) i++;
5877 info.algorithm = TQCString(p,i+1);
5879 else if (strncasecmp(p,
"domain=", 7)==0)
5882 while ( *p ==
'"' ) p++;
5883 while ( p[i] !=
'"' ) i++;
5886 TQCString uri = TQCString(p,i+1);
5889 pos = uri.find(
' ', idx );
5892 KURL u (m_request.url, uri.mid(idx, pos-idx));
5894 info.digestURI.append( u.url().latin1() );
5898 KURL u (m_request.url, uri.mid(idx, uri.length()-idx));
5900 info.digestURI.append( u.url().latin1() );
5903 }
while ( pos != -1 );
5905 else if (strncasecmp(p,
"nonce=", 6)==0)
5908 while ( *p ==
'"' ) p++;
5909 while ( p[i] !=
'"' ) i++;
5910 info.nonce = TQCString(p,i+1);
5912 else if (strncasecmp(p,
"opaque=", 7)==0)
5915 while ( *p ==
'"' ) p++;
5916 while ( p[i] !=
'"' ) i++;
5917 opaque = TQCString(p,i+1);
5919 else if (strncasecmp(p,
"qop=", 4)==0)
5922 while ( *p ==
'"' ) p++;
5923 while ( p[i] !=
'"' ) i++;
5924 info.qop = TQCString(p,i+1);
5929 if (info.realm.isEmpty() || info.nonce.isEmpty())
5930 return TQString::null;
5935 if (info.digestURI.isEmpty() && (m_responseCode == 401 || m_responseCode == 407))
5936 info.digestURI.append (m_request.url.url().latin1());
5944 TQString requestPath = m_request.url.directory(
false,
false);
5945 if (requestPath.isEmpty())
5948 int count = info.digestURI.count();
5950 for (
int i = 0; i < count; i++ )
5952 KURL u ( info.digestURI.at(i) );
5954 send &= (m_request.url.protocol().lower() == u.protocol().lower());
5955 send &= (m_request.hostname.lower() == u.host().lower());
5957 if (m_request.port > 0 && u.port() > 0)
5958 send &= (m_request.port == u.port());
5960 TQString digestPath = u.directory (
false,
false);
5961 if (digestPath.isEmpty())
5964 send &= (requestPath.startsWith(digestPath));
5970 kdDebug(7113) <<
"(" << m_pid <<
") createDigestAuth(): passed digest "
5971 "authentication credential test: " << send << endl;
5974 return TQString::null;
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;
5985 calculateResponse( info, Response );
5987 auth +=
"username=\"";
5988 auth += info.username;
5990 auth +=
"\", realm=\"";
5994 auth +=
", nonce=\"";
5997 auth +=
"\", uri=\"";
5998 auth += m_request.url.encodedPathAndQuery(0,
true);
6000 auth +=
"\", algorithm=\"";
6001 auth += info.algorithm;
6004 if ( !info.qop.isEmpty() )
6008 auth +=
"\", cnonce=\"";
6009 auth += info.cnonce;
6014 auth +=
", response=\"";
6016 if ( !opaque.isEmpty() )
6018 auth +=
"\", opaque=\"";
6026 TQString HTTPProtocol::proxyAuthenticationHeader()
6033 if ( m_strProxyRealm.isEmpty() )
6036 info.url = m_proxyURL;
6037 info.username = m_proxyURL.user();
6038 info.password = m_proxyURL.pass();
6039 info.verifyPath =
true;
6044 if ( !info.username.isNull() && !info.password.isNull() )
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;
6053 ProxyAuthentication = AUTH_Digest;
6057 if ( checkCachedAuthentication(info) && !info.digestInfo.isEmpty() )
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;
6068 ProxyAuthentication = AUTH_Digest;
6072 ProxyAuthentication = AUTH_None;
6078 if ( ProxyAuthentication != AUTH_None )
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;
6089 switch ( ProxyAuthentication )
6092 header += createBasicAuth(
true );
6095 header += createDigestAuth(
true );
6098 if ( m_bFirstRequest ) header += createNTLMAuth(
true );