00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024 #include <config.h>
00025
00026 #include <errno.h>
00027 #include <fcntl.h>
00028 #include <utime.h>
00029 #include <stdlib.h>
00030 #include <signal.h>
00031 #include <sys/stat.h>
00032 #include <sys/socket.h>
00033 #include <netinet/in.h>
00034 #include <netinet/tcp.h>
00035 #include <unistd.h>
00036
00037
00038
00039
00040
00041
00042
00043 #include <qdom.h>
00044 #include <qfile.h>
00045 #include <qregexp.h>
00046 #include <qdatetime.h>
00047 #include <qstringlist.h>
00048
00049 #include <kurl.h>
00050 #include <kidna.h>
00051 #include <ksocks.h>
00052 #include <kdebug.h>
00053 #include <klocale.h>
00054 #include <kconfig.h>
00055 #include <kextsock.h>
00056 #include <kservice.h>
00057 #include <krfcdate.h>
00058 #include <kmdcodec.h>
00059 #include <kinstance.h>
00060 #include <kresolver.h>
00061 #include <kmimemagic.h>
00062 #include <dcopclient.h>
00063 #include <kdatastream.h>
00064 #include <kapplication.h>
00065 #include <kstandarddirs.h>
00066 #include <kstringhandler.h>
00067 #include <kremoteencoding.h>
00068
00069 #include "kio/ioslave_defaults.h"
00070 #include "kio/http_slave_defaults.h"
00071
00072 #include "httpfilter.h"
00073 #include "http.h"
00074
00075 #ifdef HAVE_LIBGSSAPI
00076 #ifdef GSSAPI_MIT
00077 #include <gssapi/gssapi.h>
00078 #else
00079 #include <gssapi.h>
00080 #endif
00081
00082
00083 #if defined(GSS_RFC_COMPLIANT_OIDS) && (GSS_RFC_COMPLIANT_OIDS == 0)
00084 #include <gssapi/gssapi_generic.h>
00085 #define GSS_C_NT_HOSTBASED_SERVICE gss_nt_service_name
00086 #endif
00087
00088 #endif
00089
00090 #include <misc/kntlm/kntlm.h>
00091
00092 using namespace KIO;
00093
00094 extern "C" {
00095 KDE_EXPORT int kdemain(int argc, char **argv);
00096 }
00097
00098 int kdemain( int argc, char **argv )
00099 {
00100 KLocale::setMainCatalogue("kdelibs");
00101 KInstance instance( "kio_http" );
00102 ( void ) KGlobal::locale();
00103
00104 if (argc != 4)
00105 {
00106 fprintf(stderr, "Usage: kio_http protocol domain-socket1 domain-socket2\n");
00107 exit(-1);
00108 }
00109
00110 HTTPProtocol slave(argv[1], argv[2], argv[3]);
00111 slave.dispatchLoop();
00112 return 0;
00113 }
00114
00115
00116
00117 static char * trimLead (char *orig_string)
00118 {
00119 while (*orig_string == ' ')
00120 orig_string++;
00121 return orig_string;
00122 }
00123
00124 static bool isCrossDomainRequest( const QString& fqdn, const QString& originURL )
00125 {
00126 if (originURL == "true")
00127 return true;
00128
00129 KURL url ( originURL );
00130
00131
00132 QString a = url.host();
00133
00134
00135 QString b = fqdn;
00136
00137 if (a == b)
00138 return false;
00139
00140 QStringList l1 = QStringList::split('.', a);
00141 QStringList l2 = QStringList::split('.', b);
00142
00143 while(l1.count() > l2.count())
00144 l1.pop_front();
00145
00146 while(l2.count() > l1.count())
00147 l2.pop_front();
00148
00149 while(l2.count() >= 2)
00150 {
00151 if (l1 == l2)
00152 return false;
00153
00154 l1.pop_front();
00155 l2.pop_front();
00156 }
00157
00158 return true;
00159 }
00160
00161
00162
00163
00164 static QString sanitizeCustomHTTPHeader(const QString& _header)
00165 {
00166 QString sanitizedHeaders;
00167 QStringList headers = QStringList::split("\r\n", _header);
00168
00169 for(QStringList::Iterator it = headers.begin(); it != headers.end(); ++it)
00170 {
00171 QString header = (*it).lower();
00172
00173
00174 if (header.find(':') == -1 ||
00175 header.startsWith("host") ||
00176 header.startsWith("via"))
00177 continue;
00178
00179 sanitizedHeaders += (*it);
00180 sanitizedHeaders += "\r\n";
00181 }
00182
00183 return sanitizedHeaders.stripWhiteSpace();
00184 }
00185
00186 static QString htmlEscape(const QString &plain)
00187 {
00188 QString rich;
00189 rich.reserve(uint(plain.length() * 1.1));
00190 for (uint i = 0; i < plain.length(); ++i) {
00191 if (plain.at(i) == '<')
00192 rich += "<";
00193 else if (plain.at(i) == '>')
00194 rich += ">";
00195 else if (plain.at(i) == '&')
00196 rich += "&";
00197 else if (plain.at(i) == '"')
00198 rich += """;
00199 else
00200 rich += plain.at(i);
00201 }
00202 rich.squeeze();
00203 return rich;
00204 }
00205
00206
00207 #define NO_SIZE ((KIO::filesize_t) -1)
00208
00209 #ifdef HAVE_STRTOLL
00210 #define STRTOLL strtoll
00211 #else
00212 #define STRTOLL strtol
00213 #endif
00214
00215
00216
00217
00218 HTTPProtocol::HTTPProtocol( const QCString &protocol, const QCString &pool,
00219 const QCString &app )
00220 :TCPSlaveBase( 0, protocol , pool, app,
00221 (protocol == "https" || protocol == "webdavs") )
00222 {
00223 m_requestQueue.setAutoDelete(true);
00224
00225 m_bBusy = false;
00226 m_bFirstRequest = false;
00227 m_bProxyAuthValid = false;
00228
00229 m_iSize = NO_SIZE;
00230 m_lineBufUnget = 0;
00231
00232 m_protocol = protocol;
00233
00234 m_maxCacheAge = DEFAULT_MAX_CACHE_AGE;
00235 m_maxCacheSize = DEFAULT_MAX_CACHE_SIZE / 2;
00236 m_remoteConnTimeout = DEFAULT_CONNECT_TIMEOUT;
00237 m_remoteRespTimeout = DEFAULT_RESPONSE_TIMEOUT;
00238 m_proxyConnTimeout = DEFAULT_PROXY_CONNECT_TIMEOUT;
00239
00240 m_pid = getpid();
00241
00242 setMultipleAuthCaching( true );
00243 reparseConfiguration();
00244 }
00245
00246 HTTPProtocol::~HTTPProtocol()
00247 {
00248 httpClose(false);
00249 }
00250
00251 void HTTPProtocol::reparseConfiguration()
00252 {
00253 kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::reparseConfiguration" << endl;
00254
00255 m_strProxyRealm = QString::null;
00256 m_strProxyAuthorization = QString::null;
00257 ProxyAuthentication = AUTH_None;
00258 m_bUseProxy = false;
00259
00260 if (m_protocol == "https" || m_protocol == "webdavs")
00261 m_iDefaultPort = DEFAULT_HTTPS_PORT;
00262 else if (m_protocol == "ftp")
00263 m_iDefaultPort = DEFAULT_FTP_PORT;
00264 else
00265 m_iDefaultPort = DEFAULT_HTTP_PORT;
00266 }
00267
00268 void HTTPProtocol::resetConnectionSettings()
00269 {
00270 m_bEOF = false;
00271 m_bError = false;
00272 m_lineCount = 0;
00273 m_iWWWAuthCount = 0;
00274 m_lineCountUnget = 0;
00275 m_iProxyAuthCount = 0;
00276
00277 }
00278
00279 void HTTPProtocol::resetResponseSettings()
00280 {
00281 m_bRedirect = false;
00282 m_redirectLocation = KURL();
00283 m_bChunked = false;
00284 m_iSize = NO_SIZE;
00285
00286 m_responseHeader.clear();
00287 m_qContentEncodings.clear();
00288 m_qTransferEncodings.clear();
00289 m_sContentMD5 = QString::null;
00290 m_strMimeType = QString::null;
00291
00292 setMetaData("request-id", m_request.id);
00293 }
00294
00295 void HTTPProtocol::resetSessionSettings()
00296 {
00297
00298
00299 KURL proxy ( config()->readEntry("UseProxy") );
00300
00301 if ( m_strProxyRealm.isEmpty() || !proxy.isValid() ||
00302 m_proxyURL.host() != proxy.host() ||
00303 (!proxy.user().isNull() && proxy.user() != m_proxyURL.user()) ||
00304 (!proxy.pass().isNull() && proxy.pass() != m_proxyURL.pass()) )
00305 {
00306 m_bProxyAuthValid = false;
00307 m_proxyURL = proxy;
00308 m_bUseProxy = m_proxyURL.isValid();
00309
00310 kdDebug(7113) << "(" << m_pid << ") Using proxy: " << m_bUseProxy <<
00311 " URL: " << m_proxyURL.url() <<
00312 " Realm: " << m_strProxyRealm << endl;
00313 }
00314
00315 m_bPersistentProxyConnection = config()->readBoolEntry("PersistentProxyConnection", false);
00316 kdDebug(7113) << "(" << m_pid << ") Enable Persistent Proxy Connection: "
00317 << m_bPersistentProxyConnection << endl;
00318
00319 m_request.bUseCookiejar = config()->readBoolEntry("Cookies");
00320 m_request.bUseCache = config()->readBoolEntry("UseCache", true);
00321 m_request.bErrorPage = config()->readBoolEntry("errorPage", true);
00322 m_request.bNoAuth = config()->readBoolEntry("no-auth");
00323 m_strCacheDir = config()->readPathEntry("CacheDir");
00324 m_maxCacheAge = config()->readNumEntry("MaxCacheAge", DEFAULT_MAX_CACHE_AGE);
00325 m_request.window = config()->readEntry("window-id");
00326
00327 kdDebug(7113) << "(" << m_pid << ") Window Id = " << m_request.window << endl;
00328 kdDebug(7113) << "(" << m_pid << ") ssl_was_in_use = "
00329 << metaData ("ssl_was_in_use") << endl;
00330
00331 m_request.referrer = QString::null;
00332 if ( config()->readBoolEntry("SendReferrer", true) &&
00333 (m_protocol == "https" || m_protocol == "webdavs" ||
00334 metaData ("ssl_was_in_use") != "TRUE" ) )
00335 {
00336 KURL referrerURL ( metaData("referrer") );
00337 if (referrerURL.isValid())
00338 {
00339
00340 QString protocol = referrerURL.protocol();
00341 if (protocol.startsWith("webdav"))
00342 {
00343 protocol.replace(0, 6, "http");
00344 referrerURL.setProtocol(protocol);
00345 }
00346
00347 if (protocol.startsWith("http"))
00348 {
00349 referrerURL.setRef(QString::null);
00350 referrerURL.setUser(QString::null);
00351 referrerURL.setPass(QString::null);
00352 m_request.referrer = referrerURL.url();
00353 }
00354 }
00355 }
00356
00357 if ( config()->readBoolEntry("SendLanguageSettings", true) )
00358 {
00359 m_request.charsets = config()->readEntry( "Charsets", "iso-8859-1" );
00360
00361 if ( !m_request.charsets.isEmpty() )
00362 m_request.charsets += DEFAULT_PARTIAL_CHARSET_HEADER;
00363
00364 m_request.languages = config()->readEntry( "Languages", DEFAULT_LANGUAGE_HEADER );
00365 }
00366 else
00367 {
00368 m_request.charsets = QString::null;
00369 m_request.languages = QString::null;
00370 }
00371
00372
00373 QString resumeOffset = metaData("resume");
00374 if ( !resumeOffset.isEmpty() )
00375 m_request.offset = resumeOffset.toInt();
00376 else
00377 m_request.offset = 0;
00378
00379 m_request.disablePassDlg = config()->readBoolEntry("DisablePassDlg", false);
00380 m_request.allowCompressedPage = config()->readBoolEntry("AllowCompressedPage", true);
00381 m_request.id = metaData("request-id");
00382
00383
00384 if ( config()->readBoolEntry("SendUserAgent", true) )
00385 m_request.userAgent = metaData("UserAgent");
00386 else
00387 m_request.userAgent = QString::null;
00388
00389
00390
00391
00392 if ( m_request.bUseCache )
00393 cleanCache();
00394
00395
00396 if ( m_bIsSSL && m_bUseProxy && m_proxyURL.protocol() != "https" &&
00397 m_proxyURL.protocol() != "webdavs")
00398 {
00399 m_bNeedTunnel = true;
00400 setRealHost( m_request.hostname );
00401 kdDebug(7113) << "(" << m_pid << ") SSL tunnel: Setting real hostname to: "
00402 << m_request.hostname << endl;
00403 }
00404 else
00405 {
00406 m_bNeedTunnel = false;
00407 setRealHost( QString::null);
00408 }
00409
00410 m_responseCode = 0;
00411 m_prevResponseCode = 0;
00412
00413 m_strRealm = QString::null;
00414 m_strAuthorization = QString::null;
00415 Authentication = AUTH_None;
00416
00417
00418 m_proxyConnTimeout = proxyConnectTimeout();
00419 m_remoteConnTimeout = connectTimeout();
00420 m_remoteRespTimeout = responseTimeout();
00421
00422
00423 setSSLMetaData();
00424
00425
00426 setMetaData("referrer", m_request.referrer);
00427
00428
00429
00430
00431 m_bKeepAlive = true;
00432 m_keepAliveTimeout = 0;
00433 m_bUnauthorized = false;
00434
00435
00436
00437
00438
00439
00440
00441
00442
00443 m_bFirstRequest = false;
00444 }
00445
00446 void HTTPProtocol::setHost( const QString& host, int port,
00447 const QString& user, const QString& pass )
00448 {
00449
00450 if ( m_request.hostname != host )
00451 m_davHostOk = m_davHostUnsupported = false;
00452
00453
00454 if (host.find(':') == -1)
00455 {
00456 m_request.hostname = host;
00457 m_request.encoded_hostname = KIDNA::toAscii(host);
00458 }
00459 else
00460 {
00461 m_request.hostname = host;
00462 int pos = host.find('%');
00463 if (pos == -1)
00464 m_request.encoded_hostname = '[' + host + ']';
00465 else
00466
00467 m_request.encoded_hostname = '[' + host.left(pos) + ']';
00468 }
00469 m_request.port = (port == 0) ? m_iDefaultPort : port;
00470 m_request.user = user;
00471 m_request.passwd = pass;
00472
00473 m_bIsTunneled = false;
00474
00475 kdDebug(7113) << "(" << m_pid << ") Hostname is now: " << m_request.hostname <<
00476 " (" << m_request.encoded_hostname << ")" <<endl;
00477 }
00478
00479 bool HTTPProtocol::checkRequestURL( const KURL& u )
00480 {
00481 kdDebug (7113) << "(" << m_pid << ") HTTPProtocol::checkRequestURL: " << u.url() << endl;
00482
00483 m_request.url = u;
00484
00485 if (m_request.hostname.isEmpty())
00486 {
00487 error( KIO::ERR_UNKNOWN_HOST, i18n("No host specified."));
00488 return false;
00489 }
00490
00491 if (u.path().isEmpty())
00492 {
00493 KURL newUrl(u);
00494 newUrl.setPath("/");
00495 redirection(newUrl);
00496 finished();
00497 return false;
00498 }
00499
00500 if ( m_protocol != u.protocol().latin1() )
00501 {
00502 short unsigned int oldDefaultPort = m_iDefaultPort;
00503 m_protocol = u.protocol().latin1();
00504 reparseConfiguration();
00505 if ( m_iDefaultPort != oldDefaultPort &&
00506 m_request.port == oldDefaultPort )
00507 m_request.port = m_iDefaultPort;
00508 }
00509
00510 resetSessionSettings();
00511 return true;
00512 }
00513
00514 void HTTPProtocol::retrieveContent( bool dataInternal )
00515 {
00516 kdDebug (7113) << "(" << m_pid << ") HTTPProtocol::retrieveContent " << endl;
00517 if ( !retrieveHeader( false ) )
00518 {
00519 if ( m_bError )
00520 return;
00521 }
00522 else
00523 {
00524 if ( !readBody( dataInternal ) && m_bError )
00525 return;
00526 }
00527
00528 httpClose(m_bKeepAlive);
00529
00530
00531
00532 if ( !dataInternal )
00533 {
00534 if ((m_responseCode == 204) &&
00535 ((m_request.method == HTTP_GET) || (m_request.method == HTTP_POST)))
00536 error(ERR_NO_CONTENT, "");
00537 else
00538 finished();
00539 }
00540 }
00541
00542 bool HTTPProtocol::retrieveHeader( bool close_connection )
00543 {
00544 kdDebug (7113) << "(" << m_pid << ") HTTPProtocol::retrieveHeader " << endl;
00545 while ( 1 )
00546 {
00547 if (!httpOpen())
00548 return false;
00549
00550 resetResponseSettings();
00551 if (!readHeader())
00552 {
00553 if ( m_bError )
00554 return false;
00555
00556 if (m_bIsTunneled)
00557 {
00558 kdDebug(7113) << "(" << m_pid << ") Re-establishing SSL tunnel..." << endl;
00559 httpCloseConnection();
00560 }
00561 }
00562 else
00563 {
00564
00565
00566 kdDebug(7113) << "(" << m_pid << ") Previous Response: "
00567 << m_prevResponseCode << endl;
00568 kdDebug(7113) << "(" << m_pid << ") Current Response: "
00569 << m_responseCode << endl;
00570
00571 if (isSSLTunnelEnabled() && m_bIsSSL && !m_bUnauthorized && !m_bError)
00572 {
00573
00574 if ( m_responseCode < 400 )
00575 {
00576 kdDebug(7113) << "(" << m_pid << ") Unset tunneling flag!" << endl;
00577 setEnableSSLTunnel( false );
00578 m_bIsTunneled = true;
00579
00580 m_responseCode = m_prevResponseCode;
00581 continue;
00582 }
00583 else
00584 {
00585 if ( !m_request.bErrorPage )
00586 {
00587 kdDebug(7113) << "(" << m_pid << ") Sending an error message!" << endl;
00588 error( ERR_UNKNOWN_PROXY_HOST, m_proxyURL.host() );
00589 return false;
00590 }
00591
00592 kdDebug(7113) << "(" << m_pid << ") Sending an error page!" << endl;
00593 }
00594 }
00595
00596 if (m_responseCode < 400 && (m_prevResponseCode == 401 ||
00597 m_prevResponseCode == 407))
00598 saveAuthorization();
00599 break;
00600 }
00601 }
00602
00603
00604 if (!m_bufPOST.isEmpty())
00605 {
00606 m_bufPOST.resize(0);
00607 kdDebug(7113) << "(" << m_pid << ") HTTP::retreiveHeader: Cleared POST "
00608 "buffer..." << endl;
00609 }
00610
00611 if ( close_connection )
00612 {
00613 httpClose(m_bKeepAlive);
00614 finished();
00615 }
00616
00617 return true;
00618 }
00619
00620 void HTTPProtocol::stat(const KURL& url)
00621 {
00622 kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::stat " << url.prettyURL()
00623 << endl;
00624
00625 if ( !checkRequestURL( url ) )
00626 return;
00627
00628 if ( m_protocol != "webdav" && m_protocol != "webdavs" )
00629 {
00630 QString statSide = metaData(QString::fromLatin1("statSide"));
00631 if ( statSide != "source" )
00632 {
00633
00634 error( ERR_DOES_NOT_EXIST, url.prettyURL() );
00635 return;
00636 }
00637
00638
00639 UDSEntry entry;
00640 UDSAtom atom;
00641 atom.m_uds = KIO::UDS_NAME;
00642 atom.m_str = url.fileName();
00643 entry.append( atom );
00644
00645 atom.m_uds = KIO::UDS_FILE_TYPE;
00646 atom.m_long = S_IFREG;
00647 entry.append( atom );
00648
00649 atom.m_uds = KIO::UDS_ACCESS;
00650 atom.m_long = S_IRUSR | S_IRGRP | S_IROTH;
00651 entry.append( atom );
00652
00653 statEntry( entry );
00654 finished();
00655 return;
00656 }
00657
00658 davStatList( url );
00659 }
00660
00661 void HTTPProtocol::listDir( const KURL& url )
00662 {
00663 kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::listDir " << url.url()
00664 << endl;
00665
00666 if ( !checkRequestURL( url ) )
00667 return;
00668
00669 if (!url.protocol().startsWith("webdav")) {
00670 error(ERR_UNSUPPORTED_ACTION, url.prettyURL());
00671 return;
00672 }
00673
00674 davStatList( url, false );
00675 }
00676
00677 void HTTPProtocol::davSetRequest( const QCString& requestXML )
00678 {
00679
00680 m_bufPOST = requestXML;
00681
00682 if (m_bufPOST.size())
00683 m_bufPOST.truncate( m_bufPOST.size() - 1 );
00684 }
00685
00686 void HTTPProtocol::davStatList( const KURL& url, bool stat )
00687 {
00688 UDSEntry entry;
00689 UDSAtom atom;
00690
00691
00692 if ( !davHostOk() )
00693 return;
00694
00695
00696 QString query = metaData("davSearchQuery");
00697 if ( !query.isEmpty() )
00698 {
00699 QCString request = "<?xml version=\"1.0\"?>\r\n";
00700 request.append( "<D:searchrequest xmlns:D=\"DAV:\">\r\n" );
00701 request.append( query.utf8() );
00702 request.append( "</D:searchrequest>\r\n" );
00703
00704 davSetRequest( request );
00705 } else {
00706
00707 QCString request;
00708 request = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>"
00709 "<D:propfind xmlns:D=\"DAV:\">";
00710
00711
00712 if ( hasMetaData( "davRequestResponse" ) )
00713 request += metaData( "davRequestResponse" ).utf8();
00714 else {
00715
00716 request += "<D:prop>"
00717 "<D:creationdate/>"
00718 "<D:getcontentlength/>"
00719 "<D:displayname/>"
00720 "<D:source/>"
00721 "<D:getcontentlanguage/>"
00722 "<D:getcontenttype/>"
00723 "<D:executable/>"
00724 "<D:getlastmodified/>"
00725 "<D:getetag/>"
00726 "<D:supportedlock/>"
00727 "<D:lockdiscovery/>"
00728 "<D:resourcetype/>"
00729 "</D:prop>";
00730 }
00731 request += "</D:propfind>";
00732
00733 davSetRequest( request );
00734 }
00735
00736
00737 m_request.method = query.isEmpty() ? DAV_PROPFIND : DAV_SEARCH;
00738 m_request.query = QString::null;
00739 m_request.cache = CC_Reload;
00740 m_request.doProxy = m_bUseProxy;
00741 m_request.davData.depth = stat ? 0 : 1;
00742 if (!stat)
00743 m_request.url.adjustPath(+1);
00744
00745 retrieveContent( true );
00746
00747
00748 if (m_bRedirect) {
00749 finished();
00750 return;
00751 }
00752
00753 QDomDocument multiResponse;
00754 multiResponse.setContent( m_bufWebDavData, true );
00755
00756 bool hasResponse = false;
00757
00758 for ( QDomNode n = multiResponse.documentElement().firstChild();
00759 !n.isNull(); n = n.nextSibling())
00760 {
00761 QDomElement thisResponse = n.toElement();
00762 if (thisResponse.isNull())
00763 continue;
00764
00765 hasResponse = true;
00766
00767 QDomElement href = thisResponse.namedItem( "href" ).toElement();
00768 if ( !href.isNull() )
00769 {
00770 entry.clear();
00771
00772 QString urlStr = href.text();
00773 int encoding = remoteEncoding()->encodingMib();
00774 if ((encoding == 106) && (!KStringHandler::isUtf8(KURL::decode_string(urlStr, 4).latin1())))
00775 encoding = 4;
00776
00777 KURL thisURL ( urlStr, encoding );
00778
00779 atom.m_uds = KIO::UDS_NAME;
00780
00781 if ( thisURL.isValid() ) {
00782
00783 if ( !stat && thisURL.path(+1).length() == url.path(+1).length() )
00784 continue;
00785
00786 atom.m_str = thisURL.fileName();
00787 } else {
00788
00789 atom.m_str = href.text();
00790 }
00791
00792 entry.append( atom );
00793
00794 QDomNodeList propstats = thisResponse.elementsByTagName( "propstat" );
00795
00796 davParsePropstats( propstats, entry );
00797
00798 if ( stat )
00799 {
00800
00801 statEntry( entry );
00802 finished();
00803 return;
00804 }
00805 else
00806 {
00807 listEntry( entry, false );
00808 }
00809 }
00810 else
00811 {
00812 kdDebug(7113) << "Error: no URL contained in response to PROPFIND on "
00813 << url.prettyURL() << endl;
00814 }
00815 }
00816
00817 if ( stat || !hasResponse )
00818 {
00819 error( ERR_DOES_NOT_EXIST, url.prettyURL() );
00820 }
00821 else
00822 {
00823 listEntry( entry, true );
00824 finished();
00825 }
00826 }
00827
00828 void HTTPProtocol::davGeneric( const KURL& url, KIO::HTTP_METHOD method )
00829 {
00830 kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::davGeneric " << url.url()
00831 << endl;
00832
00833 if ( !checkRequestURL( url ) )
00834 return;
00835
00836
00837 if ( !davHostOk() )
00838 return;
00839
00840
00841 m_request.method = method;
00842 m_request.query = QString::null;
00843 m_request.cache = CC_Reload;
00844 m_request.doProxy = m_bUseProxy;
00845
00846 retrieveContent( false );
00847 }
00848
00849 int HTTPProtocol::codeFromResponse( const QString& response )
00850 {
00851 int firstSpace = response.find( ' ' );
00852 int secondSpace = response.find( ' ', firstSpace + 1 );
00853 return response.mid( firstSpace + 1, secondSpace - firstSpace - 1 ).toInt();
00854 }
00855
00856 void HTTPProtocol::davParsePropstats( const QDomNodeList& propstats, UDSEntry& entry )
00857 {
00858 QString mimeType;
00859 UDSAtom atom;
00860 bool foundExecutable = false;
00861 bool isDirectory = false;
00862 uint lockCount = 0;
00863 uint supportedLockCount = 0;
00864
00865 for ( uint i = 0; i < propstats.count(); i++)
00866 {
00867 QDomElement propstat = propstats.item(i).toElement();
00868
00869 QDomElement status = propstat.namedItem( "status" ).toElement();
00870 if ( status.isNull() )
00871 {
00872
00873 kdDebug(7113) << "Error, no status code in this propstat" << endl;
00874 return;
00875 }
00876
00877 int code = codeFromResponse( status.text() );
00878
00879 if ( code != 200 )
00880 {
00881 kdDebug(7113) << "Warning: status code " << code << " (this may mean that some properties are unavailable" << endl;
00882 continue;
00883 }
00884
00885 QDomElement prop = propstat.namedItem( "prop" ).toElement();
00886 if ( prop.isNull() )
00887 {
00888 kdDebug(7113) << "Error: no prop segment in this propstat." << endl;
00889 return;
00890 }
00891
00892 if ( hasMetaData( "davRequestResponse" ) )
00893 {
00894 atom.m_uds = KIO::UDS_XML_PROPERTIES;
00895 QDomDocument doc;
00896 doc.appendChild(prop);
00897 atom.m_str = doc.toString();
00898 entry.append( atom );
00899 }
00900
00901 for ( QDomNode n = prop.firstChild(); !n.isNull(); n = n.nextSibling() )
00902 {
00903 QDomElement property = n.toElement();
00904 if (property.isNull())
00905 continue;
00906
00907 if ( property.namespaceURI() != "DAV:" )
00908 {
00909
00910 continue;
00911 }
00912
00913 if ( property.tagName() == "creationdate" )
00914 {
00915
00916 atom.m_uds = KIO::UDS_CREATION_TIME;
00917 atom.m_long = parseDateTime( property.text(), property.attribute("dt") );
00918 entry.append( atom );
00919 }
00920 else if ( property.tagName() == "getcontentlength" )
00921 {
00922
00923 atom.m_uds = KIO::UDS_SIZE;
00924 atom.m_long = property.text().toULong();
00925 entry.append( atom );
00926 }
00927 else if ( property.tagName() == "displayname" )
00928 {
00929
00930 setMetaData( "davDisplayName", property.text() );
00931 }
00932 else if ( property.tagName() == "source" )
00933 {
00934
00935 QDomElement source = property.namedItem( "link" ).toElement()
00936 .namedItem( "dst" ).toElement();
00937 if ( !source.isNull() )
00938 setMetaData( "davSource", source.text() );
00939 }
00940 else if ( property.tagName() == "getcontentlanguage" )
00941 {
00942
00943 setMetaData( "davContentLanguage", property.text() );
00944 }
00945 else if ( property.tagName() == "getcontenttype" )
00946 {
00947
00948
00949
00950 if ( property.text() == "httpd/unix-directory" )
00951 {
00952 isDirectory = true;
00953 }
00954 else
00955 {
00956 mimeType = property.text();
00957 }
00958 }
00959 else if ( property.tagName() == "executable" )
00960 {
00961
00962 if ( property.text() == "T" )
00963 foundExecutable = true;
00964
00965 }
00966 else if ( property.tagName() == "getlastmodified" )
00967 {
00968
00969 atom.m_uds = KIO::UDS_MODIFICATION_TIME;
00970 atom.m_long = parseDateTime( property.text(), property.attribute("dt") );
00971 entry.append( atom );
00972
00973 }
00974 else if ( property.tagName() == "getetag" )
00975 {
00976
00977 setMetaData( "davEntityTag", property.text() );
00978 }
00979 else if ( property.tagName() == "supportedlock" )
00980 {
00981
00982 for ( QDomNode n2 = property.firstChild(); !n2.isNull(); n2 = n2.nextSibling() )
00983 {
00984 QDomElement lockEntry = n2.toElement();
00985 if ( lockEntry.tagName() == "lockentry" )
00986 {
00987 QDomElement lockScope = lockEntry.namedItem( "lockscope" ).toElement();
00988 QDomElement lockType = lockEntry.namedItem( "locktype" ).toElement();
00989 if ( !lockScope.isNull() && !lockType.isNull() )
00990 {
00991
00992 supportedLockCount++;
00993 QString scope = lockScope.firstChild().toElement().tagName();
00994 QString type = lockType.firstChild().toElement().tagName();
00995
00996 setMetaData( QString("davSupportedLockScope%1").arg(supportedLockCount), scope );
00997 setMetaData( QString("davSupportedLockType%1").arg(supportedLockCount), type );
00998 }
00999 }
01000 }
01001 }
01002 else if ( property.tagName() == "lockdiscovery" )
01003 {
01004
01005 davParseActiveLocks( property.elementsByTagName( "activelock" ), lockCount );
01006 }
01007 else if ( property.tagName() == "resourcetype" )
01008 {
01009
01010 if ( !property.namedItem( "collection" ).toElement().isNull() )
01011 {
01012
01013 isDirectory = true;
01014 }
01015 }
01016 else
01017 {
01018 kdDebug(7113) << "Found unknown webdav property: " << property.tagName() << endl;
01019 }
01020 }
01021 }
01022
01023 setMetaData( "davLockCount", QString("%1").arg(lockCount) );
01024 setMetaData( "davSupportedLockCount", QString("%1").arg(supportedLockCount) );
01025
01026 atom.m_uds = KIO::UDS_FILE_TYPE;
01027 atom.m_long = isDirectory ? S_IFDIR : S_IFREG;
01028 entry.append( atom );
01029
01030 if ( foundExecutable || isDirectory )
01031 {
01032
01033 atom.m_uds = KIO::UDS_ACCESS;
01034 atom.m_long = 0700;
01035 entry.append(atom);
01036 }
01037 else
01038 {
01039 atom.m_uds = KIO::UDS_ACCESS;
01040 atom.m_long = 0600;
01041 entry.append(atom);
01042 }
01043
01044 if ( !isDirectory && !mimeType.isEmpty() )
01045 {
01046 atom.m_uds = KIO::UDS_MIME_TYPE;
01047 atom.m_str = mimeType;
01048 entry.append( atom );
01049 }
01050 }
01051
01052 void HTTPProtocol::davParseActiveLocks( const QDomNodeList& activeLocks,
01053 uint& lockCount )
01054 {
01055 for ( uint i = 0; i < activeLocks.count(); i++ )
01056 {
01057 QDomElement activeLock = activeLocks.item(i).toElement();
01058
01059 lockCount++;
01060
01061 QDomElement lockScope = activeLock.namedItem( "lockscope" ).toElement();
01062 QDomElement lockType = activeLock.namedItem( "locktype" ).toElement();
01063 QDomElement lockDepth = activeLock.namedItem( "depth" ).toElement();
01064
01065 QDomElement lockOwner = activeLock.namedItem( "owner" ).toElement();
01066 QDomElement lockTimeout = activeLock.namedItem( "timeout" ).toElement();
01067 QDomElement lockToken = activeLock.namedItem( "locktoken" ).toElement();
01068
01069 if ( !lockScope.isNull() && !lockType.isNull() && !lockDepth.isNull() )
01070 {
01071
01072 lockCount++;
01073 QString scope = lockScope.firstChild().toElement().tagName();
01074 QString type = lockType.firstChild().toElement().tagName();
01075 QString depth = lockDepth.text();
01076
01077 setMetaData( QString("davLockScope%1").arg( lockCount ), scope );
01078 setMetaData( QString("davLockType%1").arg( lockCount ), type );
01079 setMetaData( QString("davLockDepth%1").arg( lockCount ), depth );
01080
01081 if ( !lockOwner.isNull() )
01082 setMetaData( QString("davLockOwner%1").arg( lockCount ), lockOwner.text() );
01083
01084 if ( !lockTimeout.isNull() )
01085 setMetaData( QString("davLockTimeout%1").arg( lockCount ), lockTimeout.text() );
01086
01087 if ( !lockToken.isNull() )
01088 {
01089 QDomElement tokenVal = lockScope.namedItem( "href" ).toElement();
01090 if ( !tokenVal.isNull() )
01091 setMetaData( QString("davLockToken%1").arg( lockCount ), tokenVal.text() );
01092 }
01093 }
01094 }
01095 }
01096
01097 long HTTPProtocol::parseDateTime( const QString& input, const QString& type )
01098 {
01099 if ( type == "dateTime.tz" )
01100 {
01101 return KRFCDate::parseDateISO8601( input );
01102 }
01103 else if ( type == "dateTime.rfc1123" )
01104 {
01105 return KRFCDate::parseDate( input );
01106 }
01107
01108
01109 time_t time = KRFCDate::parseDate( input );
01110 if ( time != 0 )
01111 return time;
01112
01113 return KRFCDate::parseDateISO8601( input );
01114 }
01115
01116 QString HTTPProtocol::davProcessLocks()
01117 {
01118 if ( hasMetaData( "davLockCount" ) )
01119 {
01120 QString response("If:");
01121 int numLocks;
01122 numLocks = metaData( "davLockCount" ).toInt();
01123 bool bracketsOpen = false;
01124 for ( int i = 0; i < numLocks; i++ )
01125 {
01126 if ( hasMetaData( QString("davLockToken%1").arg(i) ) )
01127 {
01128 if ( hasMetaData( QString("davLockURL%1").arg(i) ) )
01129 {
01130 if ( bracketsOpen )
01131 {
01132 response += ")";
01133 bracketsOpen = false;
01134 }
01135 response += " <" + metaData( QString("davLockURL%1").arg(i) ) + ">";
01136 }
01137
01138 if ( !bracketsOpen )
01139 {
01140 response += " (";
01141 bracketsOpen = true;
01142 }
01143 else
01144 {
01145 response += " ";
01146 }
01147
01148 if ( hasMetaData( QString("davLockNot%1").arg(i) ) )
01149 response += "Not ";
01150
01151 response += "<" + metaData( QString("davLockToken%1").arg(i) ) + ">";
01152 }
01153 }
01154
01155 if ( bracketsOpen )
01156 response += ")";
01157
01158 response += "\r\n";
01159 return response;
01160 }
01161
01162 return QString::null;
01163 }
01164
01165 bool HTTPProtocol::davHostOk()
01166 {
01167
01168 return true;
01169
01170
01171 if ( m_davHostOk )
01172 {
01173 kdDebug(7113) << "(" << m_pid << ") " << k_funcinfo << " true" << endl;
01174 return true;
01175 }
01176 else if ( m_davHostUnsupported )
01177 {
01178 kdDebug(7113) << "(" << m_pid << ") " << k_funcinfo << " false" << endl;
01179 davError( -2 );
01180 return false;
01181 }
01182
01183 m_request.method = HTTP_OPTIONS;
01184
01185
01186 m_request.path = "*";
01187 m_request.query = QString::null;
01188 m_request.cache = CC_Reload;
01189 m_request.doProxy = m_bUseProxy;
01190
01191
01192 m_davCapabilities.clear();
01193
01194 retrieveHeader(false);
01195
01196 if (m_davCapabilities.count())
01197 {
01198 for (uint i = 0; i < m_davCapabilities.count(); i++)
01199 {
01200 bool ok;
01201 uint verNo = m_davCapabilities[i].toUInt(&ok);
01202 if (ok && verNo > 0 && verNo < 3)
01203 {
01204 m_davHostOk = true;
01205 kdDebug(7113) << "Server supports DAV version " << verNo << "." << endl;
01206 }
01207 }
01208
01209 if ( m_davHostOk )
01210 return true;
01211 }
01212
01213 m_davHostUnsupported = true;
01214 davError( -2 );
01215 return false;
01216 }
01217
01218
01219
01220 void HTTPProtocol::davFinished()
01221 {
01222
01223 httpClose(m_bKeepAlive);
01224 finished();
01225 }
01226
01227 void HTTPProtocol::mkdir( const KURL& url, int )
01228 {
01229 kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::mkdir " << url.url()
01230 << endl;
01231
01232 if ( !checkRequestURL( url ) )
01233 return;
01234
01235 m_request.method = DAV_MKCOL;
01236 m_request.path = url.path();
01237 m_request.query = QString::null;
01238 m_request.cache = CC_Reload;
01239 m_request.doProxy = m_bUseProxy;
01240
01241 retrieveHeader( false );
01242
01243 if ( m_responseCode == 201 )
01244 davFinished();
01245 else
01246 davError();
01247 }
01248
01249 void HTTPProtocol::get( const KURL& url )
01250 {
01251 kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::get " << url.url()
01252 << endl;
01253
01254 if ( !checkRequestURL( url ) )
01255 return;
01256
01257 m_request.method = HTTP_GET;
01258 m_request.path = url.path();
01259 m_request.query = url.query();
01260
01261 QString tmp = metaData("cache");
01262 if (!tmp.isEmpty())
01263 m_request.cache = parseCacheControl(tmp);
01264 else
01265 m_request.cache = DEFAULT_CACHE_CONTROL;
01266
01267 m_request.passwd = url.pass();
01268 m_request.user = url.user();
01269 m_request.doProxy = m_bUseProxy;
01270
01271 retrieveContent();
01272 }
01273
01274 void HTTPProtocol::put( const KURL &url, int, bool overwrite, bool)
01275 {
01276 kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::put " << url.prettyURL()
01277 << endl;
01278
01279 if ( !checkRequestURL( url ) )
01280 return;
01281
01282
01283 if (!overwrite && m_protocol.left(6) == "webdav") {
01284
01285 if ( !davHostOk() )
01286 return;
01287
01288 QCString request;
01289 request = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>"
01290 "<D:propfind xmlns:D=\"DAV:\"><D:prop>"
01291 "<D:creationdate/>"
01292 "<D:getcontentlength/>"
01293 "<D:displayname/>"
01294 "<D:resourcetype/>"
01295 "</D:prop></D:propfind>";
01296
01297 davSetRequest( request );
01298
01299
01300 m_request.method = DAV_PROPFIND;
01301 m_request.query = QString::null;
01302 m_request.cache = CC_Reload;
01303 m_request.doProxy = m_bUseProxy;
01304 m_request.davData.depth = 0;
01305
01306 retrieveContent(true);
01307
01308 if (m_responseCode == 207) {
01309 error(ERR_FILE_ALREADY_EXIST, QString::null);
01310 return;
01311 }
01312
01313 m_bError = false;
01314 }
01315
01316 m_request.method = HTTP_PUT;
01317 m_request.path = url.path();
01318 m_request.query = QString::null;
01319 m_request.cache = CC_Reload;
01320 m_request.doProxy = m_bUseProxy;
01321
01322 retrieveHeader( false );
01323
01324 kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::put error = " << m_bError << endl;
01325 if (m_bError)
01326 return;
01327
01328 kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::put responseCode = " << m_responseCode << endl;
01329
01330 httpClose(false);
01331
01332 if ( (m_responseCode >= 200) && (m_responseCode < 300) )
01333 finished();
01334 else
01335 httpError();
01336 }
01337
01338 void HTTPProtocol::copy( const KURL& src, const KURL& dest, int, bool overwrite )
01339 {
01340 kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::copy " << src.prettyURL()
01341 << " -> " << dest.prettyURL() << endl;
01342
01343 if ( !checkRequestURL( dest ) || !checkRequestURL( src ) )
01344 return;
01345
01346
01347 KURL newDest = dest;
01348 if (newDest.protocol() == "webdavs")
01349 newDest.setProtocol("https");
01350 else
01351 newDest.setProtocol("http");
01352
01353 m_request.method = DAV_COPY;
01354 m_request.path = src.path();
01355 m_request.davData.desturl = newDest.url();
01356 m_request.davData.overwrite = overwrite;
01357 m_request.query = QString::null;
01358 m_request.cache = CC_Reload;
01359 m_request.doProxy = m_bUseProxy;
01360
01361 retrieveHeader( false );
01362
01363
01364 if ( m_responseCode == 201 || m_responseCode == 204 )
01365 davFinished();
01366 else
01367 davError();
01368 }
01369
01370 void HTTPProtocol::rename( const KURL& src, const KURL& dest, bool overwrite )
01371 {
01372 kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::rename " << src.prettyURL()
01373 << " -> " << dest.prettyURL() << endl;
01374
01375 if ( !checkRequestURL( dest ) || !checkRequestURL( src ) )
01376 return;
01377
01378
01379 KURL newDest = dest;
01380 if (newDest.protocol() == "webdavs")
01381 newDest.setProtocol("https");
01382 else
01383 newDest.setProtocol("http");
01384
01385 m_request.method = DAV_MOVE;
01386 m_request.path = src.path();
01387 m_request.davData.desturl = newDest.url();
01388 m_request.davData.overwrite = overwrite;
01389 m_request.query = QString::null;
01390 m_request.cache = CC_Reload;
01391 m_request.doProxy = m_bUseProxy;
01392
01393 retrieveHeader( false );
01394
01395 if ( m_responseCode == 301 )
01396 {
01397
01398
01399
01400
01401 if (m_redirectLocation.protocol() == "https")
01402 m_redirectLocation.setProtocol("webdavs");
01403 else
01404 m_redirectLocation.setProtocol("webdav");
01405
01406 if ( !checkRequestURL( m_redirectLocation ) )
01407 return;
01408
01409 m_request.method = DAV_MOVE;
01410 m_request.path = m_redirectLocation.path();
01411 m_request.davData.desturl = newDest.url();
01412 m_request.davData.overwrite = overwrite;
01413 m_request.query = QString::null;
01414 m_request.cache = CC_Reload;
01415 m_request.doProxy = m_bUseProxy;
01416
01417 retrieveHeader( false );
01418 }
01419
01420 if ( m_responseCode == 201 )
01421 davFinished();
01422 else
01423 davError();
01424 }
01425
01426 void HTTPProtocol::del( const KURL& url, bool )
01427 {
01428 kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::del " << url.prettyURL()
01429 << endl;
01430
01431 if ( !checkRequestURL( url ) )
01432 return;
01433
01434 m_request.method = HTTP_DELETE;
01435 m_request.path = url.path();
01436 m_request.query = QString::null;
01437 m_request.cache = CC_Reload;
01438 m_request.doProxy = m_bUseProxy;
01439
01440 retrieveHeader( false );
01441
01442
01443
01444 if ( m_responseCode == 200 || m_responseCode == 204 )
01445 davFinished();
01446 else
01447 davError();
01448 }
01449
01450 void HTTPProtocol::post( const KURL& url )
01451 {
01452 kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::post "
01453 << url.prettyURL() << endl;
01454
01455 if ( !checkRequestURL( url ) )
01456 return;
01457
01458 m_request.method = HTTP_POST;
01459 m_request.path = url.path();
01460 m_request.query = url.query();
01461 m_request.cache = CC_Reload;
01462 m_request.doProxy = m_bUseProxy;
01463
01464 retrieveContent();
01465 }
01466
01467 void HTTPProtocol::davLock( const KURL& url, const QString& scope,
01468 const QString& type, const QString& owner )
01469 {
01470 kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::davLock "
01471 << url.prettyURL() << endl;
01472
01473 if ( !checkRequestURL( url ) )
01474 return;
01475
01476 m_request.method = DAV_LOCK;
01477 m_request.path = url.path();
01478 m_request.query = QString::null;
01479 m_request.cache = CC_Reload;
01480 m_request.doProxy = m_bUseProxy;
01481
01482
01483 QDomDocument lockReq;
01484
01485 QDomElement lockInfo = lockReq.createElementNS( "DAV:", "lockinfo" );
01486 lockReq.appendChild( lockInfo );
01487
01488 QDomElement lockScope = lockReq.createElement( "lockscope" );
01489 lockInfo.appendChild( lockScope );
01490
01491 lockScope.appendChild( lockReq.createElement( scope ) );
01492
01493 QDomElement lockType = lockReq.createElement( "locktype" );
01494 lockInfo.appendChild( lockType );
01495
01496 lockType.appendChild( lockReq.createElement( type ) );
01497
01498 if ( !owner.isNull() ) {
01499 QDomElement ownerElement = lockReq.createElement( "owner" );
01500 lockReq.appendChild( ownerElement );
01501
01502 QDomElement ownerHref = lockReq.createElement( "href" );
01503 ownerElement.appendChild( ownerHref );
01504
01505 ownerHref.appendChild( lockReq.createTextNode( owner ) );
01506 }
01507
01508
01509 m_bufPOST = lockReq.toCString();
01510
01511 retrieveContent( true );
01512
01513 if ( m_responseCode == 200 ) {
01514
01515 QDomDocument multiResponse;
01516 multiResponse.setContent( m_bufWebDavData, true );
01517
01518 QDomElement prop = multiResponse.documentElement().namedItem( "prop" ).toElement();
01519
01520 QDomElement lockdiscovery = prop.namedItem( "lockdiscovery" ).toElement();
01521
01522 uint lockCount = 0;
01523 davParseActiveLocks( lockdiscovery.elementsByTagName( "activelock" ), lockCount );
01524
01525 setMetaData( "davLockCount", QString("%1").arg( lockCount ) );
01526
01527 finished();
01528
01529 } else
01530 davError();
01531 }
01532
01533 void HTTPProtocol::davUnlock( const KURL& url )
01534 {
01535 kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::davUnlock "
01536 << url.prettyURL() << endl;
01537
01538 if ( !checkRequestURL( url ) )
01539 return;
01540
01541 m_request.method = DAV_UNLOCK;
01542 m_request.path = url.path();
01543 m_request.query = QString::null;
01544 m_request.cache = CC_Reload;
01545 m_request.doProxy = m_bUseProxy;
01546
01547 retrieveContent( true );
01548
01549 if ( m_responseCode == 200 )
01550 finished();
01551 else
01552 davError();
01553 }
01554
01555 QString HTTPProtocol::davError( int code , QString url )
01556 {
01557 bool callError = false;
01558 if ( code == -1 ) {
01559 code = m_responseCode;
01560 callError = true;
01561 }
01562 if ( code == -2 ) {
01563 callError = true;
01564 }
01565
01566 if ( !url.isNull() )
01567 url = m_request.url.url();
01568
01569 QString action, errorString;
01570 KIO::Error kError;
01571
01572
01573 QString ow = i18n( "Otherwise, the request would have succeeded." );
01574
01575 switch ( m_request.method ) {
01576 case DAV_PROPFIND:
01577 action = i18n( "retrieve property values" );
01578 break;
01579 case DAV_PROPPATCH:
01580 action = i18n( "set property values" );
01581 break;
01582 case DAV_MKCOL:
01583 action = i18n( "create the requested folder" );
01584 break;
01585 case DAV_COPY:
01586 action = i18n( "copy the specified file or folder" );
01587 break;
01588 case DAV_MOVE:
01589 action = i18n( "move the specified file or folder" );
01590 break;
01591 case DAV_SEARCH:
01592 action = i18n( "search in the specified folder" );
01593 break;
01594 case DAV_LOCK:
01595 action = i18n( "lock the specified file or folder" );
01596 break;
01597 case DAV_UNLOCK:
01598 action = i18n( "unlock the specified file or folder" );
01599 break;
01600 case HTTP_DELETE:
01601 action = i18n( "delete the specified file or folder" );
01602 break;
01603 case HTTP_OPTIONS:
01604 action = i18n( "query the server's capabilities" );
01605 break;
01606 case HTTP_GET:
01607 action = i18n( "retrieve the contents of the specified file or folder" );
01608 break;
01609 case HTTP_PUT:
01610 case HTTP_POST:
01611 case HTTP_HEAD:
01612 default:
01613
01614 Q_ASSERT(0);
01615 }
01616
01617
01618 kError = ERR_INTERNAL;
01619 errorString = i18n("An unexpected error (%1) occurred while attempting to %2.")
01620 .arg( code ).arg( action );
01621
01622 switch ( code )
01623 {
01624 case -2:
01625
01626 kError = ERR_UNSUPPORTED_PROTOCOL;
01627 errorString = i18n("The server does not support the WebDAV protocol.");
01628 break;
01629 case 207:
01630
01631 {
01632
01633
01634
01635
01636
01637 if ( !readBody( true ) && m_bError )
01638 return QString::null;
01639
01640 QStringList errors;
01641 QDomDocument multiResponse;
01642
01643 multiResponse.setContent( m_bufWebDavData, true );
01644
01645 QDomElement multistatus = multiResponse.documentElement().namedItem( "multistatus" ).toElement();
01646
01647 QDomNodeList responses = multistatus.elementsByTagName( "response" );
01648
01649 for (uint i = 0; i < responses.count(); i++)
01650 {
01651 int errCode;
01652 QString errUrl;
01653
01654 QDomElement response = responses.item(i).toElement();
01655 QDomElement code = response.namedItem( "status" ).toElement();
01656
01657 if ( !code.isNull() )
01658 {
01659 errCode = codeFromResponse( code.text() );
01660 QDomElement href = response.namedItem( "href" ).toElement();
01661 if ( !href.isNull() )
01662 errUrl = href.text();
01663 errors << davError( errCode, errUrl );
01664 }
01665 }
01666
01667
01668 errorString = i18n("An error occurred while attempting to %1, %2. A "
01669 "summary of the reasons is below.<ul>").arg( action ).arg( url );
01670
01671 for ( QStringList::Iterator it = errors.begin(); it != errors.end(); ++it )
01672 errorString += "<li>" + *it + "</li>";
01673
01674 errorString += "</ul>";
01675 }
01676 case 403:
01677 case 500:
01678
01679 kError = ERR_ACCESS_DENIED;
01680 errorString = i18n("Access was denied while attempting to %1.").arg( action );
01681 break;
01682 case 405:
01683
01684 if ( m_request.method == DAV_MKCOL )
01685 {
01686 kError = ERR_DIR_ALREADY_EXIST;
01687 errorString = i18n("The specified folder already exists.");
01688 }
01689 break;
01690 case 409:
01691
01692 kError = ERR_ACCESS_DENIED;
01693 errorString = i18n("A resource cannot be created at the destination "
01694 "until one or more intermediate collections (folders) "
01695 "have been created.");
01696 break;
01697 case 412:
01698
01699 if ( m_request.method == DAV_COPY || m_request.method == DAV_MOVE )
01700 {
01701 kError = ERR_ACCESS_DENIED;
01702 errorString = i18n("The server was unable to maintain the liveness of "
01703 "the properties listed in the propertybehavior XML "
01704 "element or you attempted to overwrite a file while "
01705 "requesting that files are not overwritten. %1")
01706 .arg( ow );
01707
01708 }
01709 else if ( m_request.method == DAV_LOCK )
01710 {
01711 kError = ERR_ACCESS_DENIED;
01712 errorString = i18n("The requested lock could not be granted. %1").arg( ow );
01713 }
01714 break;
01715 case 415:
01716
01717 kError = ERR_ACCESS_DENIED;
01718 errorString = i18n("The server does not support the request type of the body.");
01719 break;
01720 case 423:
01721
01722 kError = ERR_ACCESS_DENIED;
01723 errorString = i18n("Unable to %1 because the resource is locked.").arg( action );
01724 break;
01725 case 425:
01726
01727 errorString = i18n("This action was prevented by another error.");
01728 break;
01729 case 502:
01730
01731 if ( m_request.method == DAV_COPY || m_request.method == DAV_MOVE )
01732 {
01733 kError = ERR_WRITE_ACCESS_DENIED;
01734 errorString = i18n("Unable to %1 because the destination server refuses "
01735 "to accept the file or folder.").arg( action );
01736 }
01737 break;
01738 case 507:
01739
01740 kError = ERR_DISK_FULL;
01741 errorString = i18n("The destination resource does not have sufficient space "
01742 "to record the state of the resource after the execution "
01743 "of this method.");
01744 break;
01745 }
01746
01747
01748
01749
01750 if ( callError )
01751 error( ERR_SLAVE_DEFINED, errorString );
01752
01753 return errorString;
01754 }
01755
01756 void HTTPProtocol::httpError()
01757 {
01758 QString action, errorString;
01759 KIO::Error kError;
01760
01761 switch ( m_request.method ) {
01762 case HTTP_PUT:
01763 action = i18n( "upload %1" ).arg(m_request.url.prettyURL());
01764 break;
01765 default:
01766
01767 Q_ASSERT(0);
01768 }
01769
01770
01771 kError = ERR_INTERNAL;
01772 errorString = i18n("An unexpected error (%1) occurred while attempting to %2.")
01773 .arg( m_responseCode ).arg( action );
01774
01775 switch ( m_responseCode )
01776 {
01777 case 403:
01778 case 405:
01779 case 500:
01780
01781
01782 kError = ERR_ACCESS_DENIED;
01783 errorString = i18n("Access was denied while attempting to %1.").arg( action );
01784 break;
01785 case 409:
01786
01787 kError = ERR_ACCESS_DENIED;
01788 errorString = i18n("A resource cannot be created at the destination "
01789 "until one or more intermediate collections (folders) "
01790 "have been created.");
01791 break;
01792 case 423:
01793
01794 kError = ERR_ACCESS_DENIED;
01795 errorString = i18n("Unable to %1 because the resource is locked.").arg( action );
01796 break;
01797 case 502:
01798
01799 kError = ERR_WRITE_ACCESS_DENIED;
01800 errorString = i18n("Unable to %1 because the destination server refuses "
01801 "to accept the file or folder.").arg( action );
01802 break;
01803 case 507:
01804
01805 kError = ERR_DISK_FULL;
01806 errorString = i18n("The destination resource does not have sufficient space "
01807 "to record the state of the resource after the execution "
01808 "of this method.");
01809 break;
01810 }
01811
01812
01813
01814
01815 error( ERR_SLAVE_DEFINED, errorString );
01816 }
01817
01818 bool HTTPProtocol::isOffline(const KURL &url)
01819 {
01820 const int NetWorkStatusUnknown = 1;
01821 const int NetWorkStatusOnline = 8;
01822 QCString replyType;
01823 QByteArray params;
01824 QByteArray reply;
01825
01826 QDataStream stream(params, IO_WriteOnly);
01827 stream << url.url();
01828
01829 if ( dcopClient()->call( "kded", "networkstatus", "status(QString)",
01830 params, replyType, reply ) && (replyType == "int") )
01831 {
01832 int result;
01833 QDataStream stream2( reply, IO_ReadOnly );
01834 stream2 >> result;
01835 kdDebug(7113) << "(" << m_pid << ") networkstatus status = " << result << endl;
01836 return (result != NetWorkStatusUnknown) && (result != NetWorkStatusOnline);
01837 }
01838 kdDebug(7113) << "(" << m_pid << ") networkstatus <unreachable>" << endl;
01839 return false;
01840 }
01841
01842 void HTTPProtocol::multiGet(const QByteArray &data)
01843 {
01844 QDataStream stream(data, IO_ReadOnly);
01845 Q_UINT32 n;
01846 stream >> n;
01847
01848 kdDebug(7113) << "(" << m_pid << ") HTTPProtcool::multiGet n = " << n << endl;
01849
01850 HTTPRequest saveRequest;
01851 if (m_bBusy)
01852 saveRequest = m_request;
01853
01854
01855 for(unsigned i = 0; i < n; i++)
01856 {
01857 KURL url;
01858 stream >> url >> mIncomingMetaData;
01859
01860 if ( !checkRequestURL( url ) )
01861 continue;
01862
01863 kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::multi_get " << url.url() << endl;
01864
01865 m_request.method = HTTP_GET;
01866 m_request.path = url.path();
01867 m_request.query = url.query();
01868 QString tmp = metaData("cache");
01869 if (!tmp.isEmpty())
01870 m_request.cache = parseCacheControl(tmp);
01871 else
01872 m_request.cache = DEFAULT_CACHE_CONTROL;
01873
01874 m_request.passwd = url.pass();
01875 m_request.user = url.user();
01876 m_request.doProxy = m_bUseProxy;
01877
01878 HTTPRequest *newRequest = new HTTPRequest(m_request);
01879 m_requestQueue.append(newRequest);
01880 }
01881
01882 if (m_bBusy)
01883 m_request = saveRequest;
01884
01885 if (!m_bBusy)
01886 {
01887 m_bBusy = true;
01888 while(!m_requestQueue.isEmpty())
01889 {
01890 HTTPRequest *request = m_requestQueue.take(0);
01891 m_request = *request;
01892 delete request;
01893 retrieveContent();
01894 }
01895 m_bBusy = false;
01896 }
01897 }
01898
01899 ssize_t HTTPProtocol::write (const void *_buf, size_t nbytes)
01900 {
01901 int bytes_sent = 0;
01902 const char* buf = static_cast<const char*>(_buf);
01903 while ( nbytes > 0 )
01904 {
01905 int n = TCPSlaveBase::write(buf, nbytes);
01906
01907 if ( n <= 0 )
01908 {
01909
01910 if ( n == 0 )
01911 break;
01912
01913 if (n < 0 && ((errno == EINTR) || (errno == EAGAIN)))
01914 continue;
01915
01916 return -1;
01917 }
01918
01919 nbytes -= n;
01920 buf += n;
01921 bytes_sent += n;
01922 }
01923
01924 return bytes_sent;
01925 }
01926
01927 void HTTPProtocol::setRewindMarker()
01928 {
01929 m_rewindCount = 0;
01930 }
01931
01932 void HTTPProtocol::rewind()
01933 {
01934 m_linePtrUnget = m_rewindBuf,
01935 m_lineCountUnget = m_rewindCount;
01936 m_rewindCount = 0;
01937 }
01938
01939
01940 char *HTTPProtocol::gets (char *s, int size)
01941 {
01942 int len=0;
01943 char *buf=s;
01944 char mybuf[2]={0,0};
01945
01946 while (len < size)
01947 {
01948 read(mybuf, 1);
01949 if (m_bEOF)
01950 break;
01951
01952 if (m_rewindCount < sizeof(m_rewindBuf))
01953 m_rewindBuf[m_rewindCount++] = *mybuf;
01954
01955 if (*mybuf == '\r')
01956 continue;
01957
01958 if ((*mybuf == '\n') || !*mybuf)
01959 break;
01960
01961 *buf++ = *mybuf;
01962 len++;
01963 }
01964
01965 *buf=0;
01966 return s;
01967 }
01968
01969 ssize_t HTTPProtocol::read (void *b, size_t nbytes)
01970 {
01971 ssize_t ret = 0;
01972
01973 if (m_lineCountUnget > 0)
01974 {
01975 ret = ( nbytes < m_lineCountUnget ? nbytes : m_lineCountUnget );
01976 m_lineCountUnget -= ret;
01977 memcpy(b, m_linePtrUnget, ret);
01978 m_linePtrUnget += ret;
01979
01980 return ret;
01981 }
01982
01983 if (m_lineCount > 0)
01984 {
01985 ret = ( nbytes < m_lineCount ? nbytes : m_lineCount );
01986 m_lineCount -= ret;
01987 memcpy(b, m_linePtr, ret);
01988 m_linePtr += ret;
01989 return ret;
01990 }
01991
01992 if (nbytes == 1)
01993 {
01994 ret = read(m_lineBuf, 1024);
01995 m_linePtr = m_lineBuf;
01996 if (ret <= 0)
01997 {
01998 m_lineCount = 0;
01999 return ret;
02000 }
02001 m_lineCount = ret;
02002 return read(b, 1);
02003 }
02004
02005 do
02006 {
02007 ret = TCPSlaveBase::read( b, nbytes);
02008 if (ret == 0)
02009 m_bEOF = true;
02010
02011 } while ((ret == -1) && (errno == EAGAIN || errno == EINTR));
02012
02013 return ret;
02014 }
02015
02016 void HTTPProtocol::httpCheckConnection()
02017 {
02018 kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::httpCheckConnection: " <<
02019 " Socket status: " << m_iSock <<
02020 " Keep Alive: " << m_bKeepAlive <<
02021 " First: " << m_bFirstRequest << endl;
02022
02023 if ( !m_bFirstRequest && (m_iSock != -1) )
02024 {
02025 bool closeDown = false;
02026 if ( !isConnectionValid())
02027 {
02028 kdDebug(7113) << "(" << m_pid << ") Connection lost!" << endl;
02029 closeDown = true;
02030 }
02031 else if ( m_request.method != HTTP_GET )
02032 {
02033 closeDown = true;
02034 }
02035 else if ( !m_state.doProxy && !m_request.doProxy )
02036 {
02037 if (m_state.hostname != m_request.hostname ||
02038 m_state.port != m_request.port ||
02039 m_state.user != m_request.user ||
02040 m_state.passwd != m_request.passwd)
02041 closeDown = true;
02042 }
02043 else
02044 {
02045
02046 if ( !(m_request.doProxy && m_state.doProxy) )
02047 closeDown = true;
02048 }
02049
02050 if (closeDown)
02051 httpCloseConnection();
02052 }
02053
02054
02055 m_state.hostname = m_request.hostname;
02056 m_state.encoded_hostname = m_request.encoded_hostname;
02057 m_state.port = m_request.port;
02058 m_state.user = m_request.user;
02059 m_state.passwd = m_request.passwd;
02060 m_state.doProxy = m_request.doProxy;
02061 }
02062
02063 bool HTTPProtocol::httpOpenConnection()
02064 {
02065 int errCode;
02066 QString errMsg;
02067
02068 kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::httpOpenConnection" << endl;
02069
02070 setBlockConnection( true );
02071
02072 KSocks::self()->disableSocks();
02073
02074 if ( m_state.doProxy )
02075 {
02076 QString proxy_host = m_proxyURL.host();
02077 int proxy_port = m_proxyURL.port();
02078
02079 kdDebug(7113) << "(" << m_pid << ") Connecting to proxy server: "
02080 << proxy_host << ", port: " << proxy_port << endl;
02081
02082 infoMessage( i18n("Connecting to %1...").arg(m_state.hostname) );
02083
02084 setConnectTimeout( m_proxyConnTimeout );
02085
02086 if ( !connectToHost(proxy_host, proxy_port, false) )
02087 {
02088 if (userAborted()) {
02089 error(ERR_NO_CONTENT, "");
02090 return false;
02091 }
02092
02093 switch ( connectResult() )
02094 {
02095 case IO_LookupError:
02096 errMsg = proxy_host;
02097 errCode = ERR_UNKNOWN_PROXY_HOST;
02098 break;
02099 case IO_TimeOutError:
02100 errMsg = i18n("Proxy %1 at port %2").arg(proxy_host).arg(proxy_port);
02101 errCode = ERR_SERVER_TIMEOUT;
02102 break;
02103 default:
02104 errMsg = i18n("Proxy %1 at port %2").arg(proxy_host).arg(proxy_port);
02105 errCode = ERR_COULD_NOT_CONNECT;
02106 }
02107 error( errCode, errMsg );
02108 return false;
02109 }
02110 }
02111 else
02112 {
02113
02114 setConnectTimeout(m_remoteConnTimeout);
02115
02116 if ( !connectToHost(m_state.hostname, m_state.port, false ) )
02117 {
02118 if (userAborted()) {
02119 error(ERR_NO_CONTENT, "");
02120 return false;
02121 }
02122
02123 switch ( connectResult() )
02124 {
02125 case IO_LookupError:
02126 errMsg = m_state.hostname;
02127 errCode = ERR_UNKNOWN_HOST;
02128 break;
02129 case IO_TimeOutError:
02130 errMsg = i18n("Connection was to %1 at port %2").arg(m_state.hostname).arg(m_state.port);
02131 errCode = ERR_SERVER_TIMEOUT;
02132 break;
02133 default:
02134 errCode = ERR_COULD_NOT_CONNECT;
02135 if (m_state.port != m_iDefaultPort)
02136 errMsg = i18n("%1 (port %2)").arg(m_state.hostname).arg(m_state.port);
02137 else
02138 errMsg = m_state.hostname;
02139 }
02140 error( errCode, errMsg );
02141 return false;
02142 }
02143 }
02144
02145
02146 int on = 1;
02147 (void) setsockopt( m_iSock, IPPROTO_TCP, TCP_NODELAY, (char*)&on, sizeof(on) );
02148
02149 m_bFirstRequest = true;
02150
02151 connected();
02152 return true;
02153 }
02154
02155
02178 bool HTTPProtocol::httpOpen()
02179 {
02180 kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::httpOpen" << endl;
02181
02182
02183
02184
02185 if ( (m_protocol == "https" || m_protocol == "webdavs") && !m_bIsSSL )
02186 {
02187 error( ERR_UNSUPPORTED_PROTOCOL, m_protocol );
02188 return false;
02189 }
02190
02191 m_request.fcache = 0;
02192 m_request.bCachedRead = false;
02193 m_request.bCachedWrite = false;
02194 m_request.bMustRevalidate = false;
02195 m_request.expireDate = 0;
02196 m_request.creationDate = 0;
02197
02198 if (m_request.bUseCache)
02199 {
02200 m_request.fcache = checkCacheEntry( );
02201
02202 bool bCacheOnly = (m_request.cache == KIO::CC_CacheOnly);
02203 bool bOffline = isOffline(m_request.doProxy ? m_proxyURL : m_request.url);
02204 if (bOffline && (m_request.cache != KIO::CC_Reload))
02205 m_request.cache = KIO::CC_CacheOnly;
02206
02207 if (m_request.cache == CC_Reload && m_request.fcache)
02208 {
02209 if (m_request.fcache)
02210 fclose(m_request.fcache);
02211 m_request.fcache = 0;
02212 }
02213 if ((m_request.cache == KIO::CC_CacheOnly) || (m_request.cache == KIO::CC_Cache))
02214 m_request.bMustRevalidate = false;
02215
02216 m_request.bCachedWrite = true;
02217
02218 if (m_request.fcache && !m_request.bMustRevalidate)
02219 {
02220
02221 m_request.bCachedRead = true;
02222 return true;
02223 }
02224 else if (!m_request.fcache)
02225 {
02226 m_request.bMustRevalidate = false;
02227 }
02228 else
02229 {
02230
02231 }
02232
02233 if (bCacheOnly)
02234 {
02235 error( ERR_DOES_NOT_EXIST, m_request.url.url() );
02236 return false;
02237 }
02238 if (bOffline)
02239 {
02240 error( ERR_COULD_NOT_CONNECT, m_request.url.url() );
02241 return false;
02242 }
02243 }
02244
02245 QString header;
02246 QString davHeader;
02247
02248 bool moreData = false;
02249 bool davData = false;
02250
02251
02252 resetConnectionSettings ();
02253
02254
02255 httpCheckConnection();
02256
02257 if ( !m_bIsTunneled && m_bNeedTunnel )
02258 {
02259 setEnableSSLTunnel( true );
02260
02261
02262 header = QString("CONNECT %1:%2 HTTP/1.0"
02263 "\r\n").arg( m_request.encoded_hostname).arg(m_request.port);
02264
02265
02266 if (!m_request.userAgent.isEmpty())
02267 header += "User-Agent: " + m_request.userAgent + "\r\n";
02268
02269
02270 header += "Host: " + m_state.encoded_hostname;
02271
02272 if (m_state.port != m_iDefaultPort)
02273 header += QString(":%1").arg(m_state.port);
02274 header += "\r\n";
02275
02276 header += proxyAuthenticationHeader();
02277 }
02278 else
02279 {
02280
02281 switch (m_request.method)
02282 {
02283 case HTTP_GET:
02284 header = "GET ";
02285 break;
02286 case HTTP_PUT:
02287 header = "PUT ";
02288 moreData = true;
02289 m_request.bCachedWrite = false;
02290 break;
02291 case HTTP_POST:
02292 header = "POST ";
02293 moreData = true;
02294 m_request.bCachedWrite = false;
02295 break;
02296 case HTTP_HEAD:
02297 header = "HEAD ";
02298 break;
02299 case HTTP_DELETE:
02300 header = "DELETE ";
02301 m_request.bCachedWrite = false;
02302 break;
02303 case HTTP_OPTIONS:
02304 header = "OPTIONS ";
02305 m_request.bCachedWrite = false;
02306 break;
02307 case DAV_PROPFIND:
02308 header = "PROPFIND ";
02309 davData = true;
02310 davHeader = "Depth: ";
02311 if ( hasMetaData( "davDepth" ) )
02312 {
02313 kdDebug(7113) << "Reading DAV depth from metadata: " << metaData( "davDepth" ) << endl;
02314 davHeader += metaData( "davDepth" );
02315 }
02316 else
02317 {
02318 if ( m_request.davData.depth == 2 )
02319 davHeader += "infinity";
02320 else
02321 davHeader += QString("%1").arg( m_request.davData.depth );
02322 }
02323 davHeader += "\r\n";
02324 m_request.bCachedWrite = false;
02325 break;
02326 case DAV_PROPPATCH:
02327 header = "PROPPATCH ";
02328 davData = true;
02329 m_request.bCachedWrite = false;
02330 break;
02331 case DAV_MKCOL:
02332 header = "MKCOL ";
02333 m_request.bCachedWrite = false;
02334 break;
02335 case DAV_COPY:
02336 case DAV_MOVE:
02337 header = ( m_request.method == DAV_COPY ) ? "COPY " : "MOVE ";
02338 davHeader = "Destination: " + m_request.davData.desturl;
02339
02340
02341 davHeader += "\r\nDepth: infinity\r\nOverwrite: ";
02342 davHeader += m_request.davData.overwrite ? "T" : "F";
02343 davHeader += "\r\n";
02344 m_request.bCachedWrite = false;
02345 break;
02346 case DAV_LOCK:
02347 header = "LOCK ";
02348 davHeader = "Timeout: ";
02349 {
02350 uint timeout = 0;
02351 if ( hasMetaData( "davTimeout" ) )
02352 timeout = metaData( "davTimeout" ).toUInt();
02353 if ( timeout == 0 )
02354 davHeader += "Infinite";
02355 else
02356 davHeader += QString("Seconds-%1").arg(timeout);
02357 }
02358 davHeader += "\r\n";
02359 m_request.bCachedWrite = false;
02360 davData = true;
02361 break;
02362 case DAV_UNLOCK:
02363 header = "UNLOCK ";
02364 davHeader = "Lock-token: " + metaData("davLockToken") + "\r\n";
02365 m_request.bCachedWrite = false;
02366 break;
02367 case DAV_SEARCH:
02368 header = "SEARCH ";
02369 davData = true;
02370 m_request.bCachedWrite = false;
02371 break;
02372 case DAV_SUBSCRIBE:
02373 header = "SUBSCRIBE ";
02374 m_request.bCachedWrite = false;
02375 break;
02376 case DAV_UNSUBSCRIBE:
02377 header = "UNSUBSCRIBE ";
02378 m_request.bCachedWrite = false;
02379 break;
02380 case DAV_POLL:
02381 header = "POLL ";
02382 m_request.bCachedWrite = false;
02383 break;
02384 default:
02385 error (ERR_UNSUPPORTED_ACTION, QString::null);
02386 return false;
02387 }
02388
02389
02390
02391 if (m_state.doProxy && !m_bIsTunneled)
02392 {
02393 KURL u;
02394
02395 if (m_protocol == "webdav")
02396 u.setProtocol( "http" );
02397 else if (m_protocol == "webdavs" )
02398 u.setProtocol( "https" );
02399 else
02400 u.setProtocol( m_protocol );
02401
02402
02403
02404
02405
02406 if (m_protocol != "http" && m_protocol != "https" &&
02407 !m_state.user.isEmpty())
02408 u.setUser (m_state.user);
02409
02410 u.setHost( m_state.hostname );
02411 if (m_state.port != m_iDefaultPort)
02412 u.setPort( m_state.port );
02413 u.setEncodedPathAndQuery( m_request.url.encodedPathAndQuery(0,true) );
02414 header += u.url();
02415 }
02416 else
02417 {
02418 header += m_request.url.encodedPathAndQuery(0, true);
02419 }
02420
02421 header += " HTTP/1.1\r\n";
02422
02423 if (!m_request.userAgent.isEmpty())
02424 {
02425 header += "User-Agent: ";
02426 header += m_request.userAgent;
02427 header += "\r\n";
02428 }
02429
02430 if (!m_request.referrer.isEmpty())
02431 {
02432 header += "Referer: ";
02433 header += m_request.referrer;
02434 header += "\r\n";
02435 }
02436
02437 if ( m_request.offset > 0 )
02438 {
02439 header += QString("Range: bytes=%1-\r\n").arg(KIO::number(m_request.offset));
02440 kdDebug(7103) << "kio_http : Range = " << KIO::number(m_request.offset) << endl;
02441 }
02442
02443 if ( m_request.cache == CC_Reload )
02444 {
02445
02446 header += "Pragma: no-cache\r\n";
02447 header += "Cache-control: no-cache\r\n";
02448 }
02449
02450 if (m_request.bMustRevalidate)
02451 {
02452
02453 if (!m_request.etag.isEmpty())
02454 header += "If-None-Match: "+m_request.etag+"\r\n";
02455 if (!m_request.lastModified.isEmpty())
02456 header += "If-Modified-Since: "+m_request.lastModified+"\r\n";
02457 }
02458
02459 header += "Accept: ";
02460 QString acceptHeader = metaData("accept");
02461 if (!acceptHeader.isEmpty())
02462 header += acceptHeader;
02463 else
02464 header += DEFAULT_ACCEPT_HEADER;
02465 header += "\r\n";
02466
02467 #ifdef DO_GZIP
02468 if (m_request.allowCompressedPage)
02469 header += "Accept-Encoding: x-gzip, x-deflate, gzip, deflate\r\n";
02470 #endif
02471
02472 if (!m_request.charsets.isEmpty())
02473 header += "Accept-Charset: " + m_request.charsets + "\r\n";
02474
02475 if (!m_request.languages.isEmpty())
02476 header += "Accept-Language: " + m_request.languages + "\r\n";
02477
02478
02479
02480 header += "Host: " + m_state.encoded_hostname;
02481
02482 if (m_state.port != m_iDefaultPort)
02483 header += QString(":%1").arg(m_state.port);
02484 header += "\r\n";
02485
02486 QString cookieStr;
02487 QString cookieMode = metaData("cookies").lower();
02488 if (cookieMode == "none")
02489 {
02490 m_request.cookieMode = HTTPRequest::CookiesNone;
02491 }
02492 else if (cookieMode == "manual")
02493 {
02494 m_request.cookieMode = HTTPRequest::CookiesManual;
02495 cookieStr = metaData("setcookies");
02496 }
02497 else
02498 {
02499 m_request.cookieMode = HTTPRequest::CookiesAuto;
02500 if (m_request.bUseCookiejar)
02501 cookieStr = findCookies( m_request.url.url());
02502 }
02503
02504 if (!cookieStr.isEmpty())
02505 header += cookieStr + "\r\n";
02506
02507 QString customHeader = metaData( "customHTTPHeader" );
02508 if (!customHeader.isEmpty())
02509 {
02510 header += sanitizeCustomHTTPHeader(customHeader);
02511 header += "\r\n";
02512 }
02513
02514 if (m_request.method == HTTP_POST)
02515 {
02516 header += metaData("content-type");
02517 header += "\r\n";
02518 }
02519
02520
02521
02522
02523 if ( !m_request.bNoAuth && m_responseCode != 401 && m_responseCode != 407 && Authentication != AUTH_Negotiate )
02524 {
02525 kdDebug(7113) << "(" << m_pid << ") Calling checkCachedAuthentication " << endl;
02526 AuthInfo info;
02527 info.url = m_request.url;
02528 info.verifyPath = true;
02529 if ( !m_request.user.isEmpty() )
02530 info.username = m_request.user;
02531 if ( checkCachedAuthentication( info ) && !info.digestInfo.isEmpty() )
02532 {
02533 Authentication = info.digestInfo.startsWith("Basic") ? AUTH_Basic : info.digestInfo.startsWith("NTLM") ? AUTH_NTLM : info.digestInfo.startsWith("Negotiate") ? AUTH_Negotiate : AUTH_Digest ;
02534 m_state.user = info.username;
02535 m_state.passwd = info.password;
02536 m_strRealm = info.realmValue;
02537 if ( Authentication != AUTH_NTLM && Authentication != AUTH_Negotiate )
02538 m_strAuthorization = info.digestInfo;
02539 }
02540 }
02541 else
02542 {
02543 kdDebug(7113) << "(" << m_pid << ") Not calling checkCachedAuthentication " << endl;
02544 }
02545
02546 switch ( Authentication )
02547 {
02548 case AUTH_Basic:
02549 header += createBasicAuth();
02550 break;
02551 case AUTH_Digest:
02552 header += createDigestAuth();
02553 break;
02554 #ifdef HAVE_LIBGSSAPI
02555 case AUTH_Negotiate:
02556 header += createNegotiateAuth();
02557 break;
02558 #endif
02559 case AUTH_NTLM:
02560 header += createNTLMAuth();
02561 break;
02562 case AUTH_None:
02563 default:
02564 break;
02565 }
02566
02567
02568 if ( Authentication != AUTH_None )
02569 {
02570 kdDebug(7113) << "(" << m_pid << ") Using Authentication: " << endl;
02571 kdDebug(7113) << "(" << m_pid << ") HOST= " << m_state.hostname << endl;
02572 kdDebug(7113) << "(" << m_pid << ") PORT= " << m_state.port << endl;
02573 kdDebug(7113) << "(" << m_pid << ") USER= " << m_state.user << endl;
02574 kdDebug(7113) << "(" << m_pid << ") PASSWORD= [protected]" << endl;
02575 kdDebug(7113) << "(" << m_pid << ") REALM= " << m_strRealm << endl;
02576 kdDebug(7113) << "(" << m_pid << ") EXTRA= " << m_strAuthorization << endl;
02577 }
02578
02579
02580 if ( m_state.doProxy && !m_bIsTunneled )
02581 header += proxyAuthenticationHeader();
02582
02583
02584
02585
02586
02587 if (!m_bUseProxy || m_bPersistentProxyConnection || m_bIsTunneled)
02588 header += "Connection: Keep-Alive\r\n";
02589 else
02590 header += "Connection: close\r\n";
02591
02592 if ( m_protocol == "webdav" || m_protocol == "webdavs" )
02593 {
02594 header += davProcessLocks();
02595
02596
02597 QString davExtraHeader = metaData("davHeader");
02598 if ( !davExtraHeader.isEmpty() )
02599 davHeader += davExtraHeader;
02600
02601
02602 if (davData)
02603 davHeader += "Content-Type: text/xml; charset=utf-8\r\n";
02604
02605
02606 if ( !davHeader.isNull() )
02607 header += davHeader;
02608 }
02609 }
02610
02611 kdDebug(7103) << "(" << m_pid << ") ============ Sending Header:" << endl;
02612
02613 QStringList headerOutput = QStringList::split("\r\n", header);
02614 QStringList::Iterator it = headerOutput.begin();
02615
02616 for (; it != headerOutput.end(); it++)
02617 kdDebug(7103) << "(" << m_pid << ") " << (*it) << endl;
02618
02619 if ( !moreData && !davData)
02620 header += "\r\n";
02621
02622
02623
02624
02625 if ( m_iSock == -1)
02626 {
02627 if (!httpOpenConnection())
02628 return false;
02629 }
02630
02631
02632 bool sendOk = (write(header.latin1(), header.length()) == (ssize_t) header.length());
02633 if (!sendOk)
02634 {
02635 kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::httpOpen: "
02636 "Connection broken! (" << m_state.hostname << ")" << endl;
02637
02638
02639
02640 if (m_bKeepAlive)
02641 {
02642 httpCloseConnection();
02643 return true;
02644 }
02645
02646 if (!sendOk)
02647 {
02648 kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::httpOpen: sendOk==false."
02649 " Connnection broken !" << endl;
02650 error( ERR_CONNECTION_BROKEN, m_state.hostname );
02651 return false;
02652 }
02653 }
02654
02655 bool res = true;
02656
02657 if ( moreData || davData )
02658 res = sendBody();
02659
02660 infoMessage(i18n("%1 contacted. Waiting for reply...").arg(m_request.hostname));
02661
02662 return res;
02663 }
02664
02665 void HTTPProtocol::forwardHttpResponseHeader()
02666 {
02667
02668 if ( config()->readBoolEntry("PropagateHttpHeader", false) )
02669 {
02670 setMetaData("HTTP-Headers", m_responseHeader.join("\n"));
02671 sendMetaData();
02672 }
02673 m_responseHeader.clear();
02674 }
02675
02682 bool HTTPProtocol::readHeader()
02683 {
02684 try_again:
02685 kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::readHeader" << endl;
02686
02687
02688 if (m_request.bCachedRead)
02689 {
02690 m_responseHeader << "HTTP-CACHE";
02691
02692 char buffer[4097];
02693 if (!fgets(buffer, 4096, m_request.fcache) )
02694 {
02695
02696 kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::readHeader: "
02697 << "Could not access cache to obtain mimetype!" << endl;
02698 error( ERR_CONNECTION_BROKEN, m_state.hostname );
02699 return false;
02700 }
02701
02702 m_strMimeType = QString::fromUtf8( buffer).stripWhiteSpace();
02703
02704 kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::readHeader: cached "
02705 << "data mimetype: " << m_strMimeType << endl;
02706
02707 if (!fgets(buffer, 4096, m_request.fcache) )
02708 {
02709
02710 kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::readHeader: "
02711 << "Could not access cached data! " << endl;
02712 error( ERR_CONNECTION_BROKEN, m_state.hostname );
02713 return false;
02714 }
02715
02716 m_request.strCharset = QString::fromUtf8( buffer).stripWhiteSpace().lower();
02717 setMetaData("charset", m_request.strCharset);
02718 if (!m_request.lastModified.isEmpty())
02719 setMetaData("modified", m_request.lastModified);
02720 QString tmp;
02721 tmp.setNum(m_request.expireDate);
02722 setMetaData("expire-date", tmp);
02723 tmp.setNum(m_request.creationDate);
02724 setMetaData("cache-creation-date", tmp);
02725 mimeType(m_strMimeType);
02726 forwardHttpResponseHeader();
02727 return true;
02728 }
02729
02730 QCString locationStr;
02731 QCString cookieStr;
02732
02733 QString dispositionType;
02734 QString dispositionFilename;
02735
02736 QString mediaValue;
02737 QString mediaAttribute;
02738
02739 QStringList upgradeOffers;
02740
02741 bool upgradeRequired = false;
02742
02743
02744
02745 bool canUpgrade = false;
02746
02747
02748 m_request.etag = QString::null;
02749 m_request.lastModified = QString::null;
02750 m_request.strCharset = QString::null;
02751
02752 time_t dateHeader = 0;
02753 time_t expireDate = 0;
02754 int currentAge = 0;
02755 int maxAge = -1;
02756 int maxHeaderSize = 64*1024;
02757
02758
02759 int len = 0;
02760 char buffer[4097];
02761 bool cont = false;
02762 bool cacheValidated = false;
02763 bool mayCache = true;
02764 bool hasCacheDirective = false;
02765 bool bCanResume = false;
02766
02767 if (m_iSock == -1)
02768 {
02769 kdDebug(7113) << "HTTPProtocol::readHeader: No connection." << endl;
02770 return false;
02771 }
02772
02773 if (!waitForResponse(m_remoteRespTimeout))
02774 {
02775
02776 error( ERR_SERVER_TIMEOUT , m_state.hostname );
02777 return false;
02778 }
02779
02780 setRewindMarker();
02781
02782 gets(buffer, sizeof(buffer)-1);
02783
02784 if (m_bEOF || *buffer == '\0')
02785 {
02786 kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::readHeader: "
02787 << "EOF while waiting for header start." << endl;
02788 if (m_bKeepAlive)
02789 {
02790 httpCloseConnection();
02791 return false;
02792 }
02793
02794 if (m_request.method == HTTP_HEAD)
02795 {
02796
02797
02798
02799
02800 kdDebug(7113) << "(" << m_pid << ") HTTPPreadHeader: HEAD -> returned "
02801 << "mimetype: " << DEFAULT_MIME_TYPE << endl;
02802 mimeType(QString::fromLatin1(DEFAULT_MIME_TYPE));
02803 return true;
02804 }
02805
02806 kdDebug(7113) << "HTTPProtocol::readHeader: Connection broken !" << endl;
02807 error( ERR_CONNECTION_BROKEN, m_state.hostname );
02808 return false;
02809 }
02810
02811 kdDebug(7103) << "(" << m_pid << ") ============ Received Response:"<< endl;
02812
02813 bool noHeader = true;
02814 HTTP_REV httpRev = HTTP_None;
02815 int headerSize = 0;
02816
02817 do
02818 {
02819
02820 len = strlen(buffer);
02821
02822 while(len && (buffer[len-1] == '\n' || buffer[len-1] == '\r'))
02823 buffer[--len] = 0;
02824
02825
02826 if (!len)
02827 {
02828 kdDebug(7103) << "(" << m_pid << ") --empty--" << endl;
02829 continue;
02830 }
02831
02832 headerSize += len;
02833
02834
02835
02836
02837
02838 noHeader = false;
02839
02840 kdDebug(7103) << "(" << m_pid << ") \"" << buffer << "\"" << endl;
02841
02842
02843 char* buf = buffer;
02844 while( *buf == ' ' )
02845 buf++;
02846
02847
02848 if (buf[0] == '<')
02849 {
02850
02851
02852 kdDebug(7103) << "kio_http: No valid HTTP header found! Document starts with XML/HTML tag" << endl;
02853
02854
02855 m_strMimeType = "text/html";
02856
02857 rewind();
02858 break;
02859 }
02860
02861
02862
02863 m_responseHeader << QString::fromLatin1(buf);
02864
02865 if ((strncasecmp(buf, "HTTP", 4) == 0) ||
02866 (strncasecmp(buf, "ICY ", 4) == 0))
02867 {
02868 if (strncasecmp(buf, "ICY ", 4) == 0)
02869 {
02870
02871 httpRev = SHOUTCAST;
02872 m_bKeepAlive = false;
02873 }
02874 else if (strncmp((buf + 5), "1.0",3) == 0)
02875 {
02876 httpRev = HTTP_10;
02877
02878
02879
02880
02881
02882 m_bKeepAlive = false;
02883 }
02884 else if (strncmp((buf + 5), "1.1",3) == 0)
02885 {
02886 httpRev = HTTP_11;
02887 }
02888 else
02889 {
02890 httpRev = HTTP_Unknown;
02891 }
02892
02893 if (m_responseCode)
02894 m_prevResponseCode = m_responseCode;
02895
02896 const char* rptr = buf;
02897 while ( *rptr && *rptr > ' ' )
02898 ++rptr;
02899 m_responseCode = atoi(rptr);
02900
02901
02902 if (m_responseCode >= 500 && m_responseCode <= 599)
02903 {
02904 if (m_request.method == HTTP_HEAD)
02905 {
02906 ;
02907 }
02908 else
02909 {
02910 if (m_request.bErrorPage)
02911 errorPage();
02912 else
02913 {
02914 error(ERR_INTERNAL_SERVER, m_request.url.url());
02915 return false;
02916 }
02917 }
02918 m_request.bCachedWrite = false;
02919 mayCache = false;
02920 }
02921
02922 else if (m_responseCode == 401 || m_responseCode == 407)
02923 {
02924
02925
02926 if ( m_prevResponseCode != m_responseCode &&
02927 (m_prevResponseCode == 401 || m_prevResponseCode == 407) )
02928 saveAuthorization();
02929
02930 m_bUnauthorized = true;
02931 m_request.bCachedWrite = false;
02932 mayCache = false;
02933 }
02934
02935 else if (m_responseCode == 416)
02936 {
02937 m_request.offset = 0;
02938 httpCloseConnection();
02939 return false;
02940 }
02941
02942 else if (m_responseCode == 426)
02943 {
02944 upgradeRequired = true;
02945 }
02946
02947 else if (m_responseCode >= 400 && m_responseCode <= 499)
02948 {
02949
02950 if (m_request.bErrorPage)
02951 errorPage();
02952 else
02953 {
02954 error(ERR_DOES_NOT_EXIST, m_request.url.url());
02955 return false;
02956 }
02957 m_request.bCachedWrite = false;
02958 mayCache = false;
02959 }
02960 else if (m_responseCode == 307)
02961 {
02962
02963 m_request.bCachedWrite = false;
02964 mayCache = false;
02965 }
02966 else if (m_responseCode == 304)
02967 {
02968
02969
02970 cacheValidated = true;
02971 }
02972 else if (m_responseCode >= 301 && m_responseCode<= 303)
02973 {
02974
02975 if (m_responseCode == 301)
02976 setMetaData("permanent-redirect", "true");
02977
02978
02979
02980 if (m_request.method != HTTP_HEAD && m_request.method != HTTP_GET)
02981 {
02982 #if 0
02983
02984
02985 if (m_request.method == HTTP_POST)
02986 m_bufPOST.resize(0);
02987 #endif
02988
02989
02990
02991
02992
02993
02994
02995
02996
02997 m_request.method = HTTP_GET;
02998 }
02999 m_request.bCachedWrite = false;
03000 mayCache = false;
03001 }
03002 else if ( m_responseCode == 207 )
03003 {
03004
03005 }
03006 else if ( m_responseCode == 204 )
03007 {
03008
03009
03010
03011
03012
03013
03014
03015 }
03016 else if ( m_responseCode == 206 )
03017 {
03018 if ( m_request.offset )
03019 bCanResume = true;
03020 }
03021 else if (m_responseCode == 102)
03022 {
03023
03024
03025
03026
03027
03028 infoMessage( i18n( "Server processing request, please wait..." ) );
03029 cont = true;
03030 }
03031 else if (m_responseCode == 100)
03032 {
03033
03034 cont = true;
03035 }
03036 }
03037
03038
03039 else if (strncasecmp(buf, "Accept-Ranges:", 14) == 0) {
03040 if (strncasecmp(trimLead(buf + 14), "none", 4) == 0)
03041 bCanResume = false;
03042 }
03043
03044 else if (strncasecmp(buf, "Keep-Alive:", 11) == 0) {
03045 QStringList options = QStringList::split(',',
03046 QString::fromLatin1(trimLead(buf+11)));
03047 for(QStringList::ConstIterator it = options.begin();
03048 it != options.end();
03049 it++)
03050 {
03051 QString option = (*it).stripWhiteSpace().lower();
03052 if (option.startsWith("timeout="))
03053 {
03054 m_keepAliveTimeout = option.mid(8).toInt();
03055 }
03056 }
03057 }
03058
03059
03060 else if (strncasecmp(buf, "Cache-Control:", 14) == 0) {
03061 QStringList cacheControls = QStringList::split(',',
03062 QString::fromLatin1(trimLead(buf+14)));
03063 for(QStringList::ConstIterator it = cacheControls.begin();
03064 it != cacheControls.end();
03065 it++)
03066 {
03067 QString cacheControl = (*it).stripWhiteSpace();
03068 if (strncasecmp(cacheControl.latin1(), "no-cache", 8) == 0)
03069 {
03070 m_request.bCachedWrite = false;
03071 mayCache = false;
03072 }
03073 else if (strncasecmp(cacheControl.latin1(), "no-store", 8) == 0)
03074 {
03075 m_request.bCachedWrite = false;
03076 mayCache = false;
03077 }
03078 else if (strncasecmp(cacheControl.latin1(), "max-age=", 8) == 0)
03079 {
03080 QString age = cacheControl.mid(8).stripWhiteSpace();
03081 if (!age.isNull())
03082 maxAge = STRTOLL(age.latin1(), 0, 10);
03083 }
03084 }
03085 hasCacheDirective = true;
03086 }
03087
03088
03089 else if (strncasecmp(buf, "Content-length:", 15) == 0) {
03090 char* len = trimLead(buf + 15);
03091 if (len)
03092 m_iSize = STRTOLL(len, 0, 10);
03093 }
03094
03095 else if (strncasecmp(buf, "Content-location:", 17) == 0) {
03096 setMetaData ("content-location",
03097 QString::fromLatin1(trimLead(buf+17)).stripWhiteSpace());
03098 }
03099
03100
03101 else if (strncasecmp(buf, "Content-type:", 13) == 0) {
03102 char *start = trimLead(buf + 13);
03103 char *pos = start;
03104
03105
03106 while ( *pos && *pos != ';' ) pos++;
03107
03108
03109 m_strMimeType = QString::fromLatin1(start, pos-start).stripWhiteSpace().lower();
03110 kdDebug(7113) << "(" << m_pid << ") Content-type: " << m_strMimeType << endl;
03111
03112
03113
03114 while (*pos)
03115 {
03116 start = ++pos;
03117 while ( *pos && *pos != '=' ) pos++;
03118
03119 char *end = pos;
03120 while ( *end && *end != ';' ) end++;
03121
03122 if (*pos)
03123 {
03124 mediaAttribute = QString::fromLatin1(start, pos-start).stripWhiteSpace().lower();
03125 mediaValue = QString::fromLatin1(pos+1, end-pos-1).stripWhiteSpace();
03126 pos = end;
03127 if (mediaValue.length() &&
03128 (mediaValue[0] == '"') &&
03129 (mediaValue[mediaValue.length()-1] == '"'))
03130 mediaValue = mediaValue.mid(1, mediaValue.length()-2);
03131
03132 kdDebug (7113) << "(" << m_pid << ") Media-Parameter Attribute: "
03133 << mediaAttribute << endl;
03134 kdDebug (7113) << "(" << m_pid << ") Media-Parameter Value: "
03135 << mediaValue << endl;
03136
03137 if ( mediaAttribute == "charset")
03138 {
03139 mediaValue = mediaValue.lower();
03140 m_request.strCharset = mediaValue;
03141 }
03142 else
03143 {
03144 setMetaData("media-"+mediaAttribute, mediaValue);
03145 }
03146 }
03147 }
03148 }
03149
03150
03151 else if (strncasecmp(buf, "Date:", 5) == 0) {
03152 dateHeader = KRFCDate::parseDate(trimLead(buf+5));
03153 }
03154
03155
03156 else if (strncasecmp(buf, "ETag:", 5) == 0) {
03157 m_request.etag = trimLead(buf+5);
03158 }
03159
03160
03161 else if (strncasecmp(buf, "Expires:", 8) == 0) {
03162 expireDate = KRFCDate::parseDate(trimLead(buf+8));
03163 if (!expireDate)
03164 expireDate = 1;
03165 }
03166
03167
03168 else if (strncasecmp(buf, "Last-Modified:", 14) == 0) {
03169 m_request.lastModified = (QString::fromLatin1(trimLead(buf+14))).stripWhiteSpace();
03170 }
03171
03172
03173 else if (strncasecmp(buf, "Warning:", 8) == 0) {
03174
03175
03176 infoMessage(trimLead(buf + 8));
03177 }
03178
03179
03180 else if (strncasecmp(buf, "Pragma:", 7) == 0) {
03181 QCString pragma = QCString(trimLead(buf+7)).stripWhiteSpace().lower();
03182 if (pragma == "no-cache")
03183 {
03184 m_request.bCachedWrite = false;
03185 mayCache = false;
03186 hasCacheDirective = true;
03187 }
03188 }
03189
03190
03191 else if (strncasecmp(buf,"Refresh:", 8) == 0) {
03192 mayCache = false;
03193 setMetaData( "http-refresh", QString::fromLatin1(trimLead(buf+8)).stripWhiteSpace() );
03194 }
03195
03196
03197 else if (strncasecmp(buf, "Location:", 9) == 0) {
03198
03199 if ( m_responseCode > 299 && m_responseCode < 400 )
03200 locationStr = QCString(trimLead(buf+9)).stripWhiteSpace();
03201 }
03202
03203
03204 else if (strncasecmp(buf, "Set-Cookie", 10) == 0) {
03205 cookieStr += buf;
03206 cookieStr += '\n';
03207 }
03208
03209
03210 else if (strncasecmp(buf, "WWW-Authenticate:", 17) == 0) {
03211 configAuth(trimLead(buf + 17), false);
03212 }
03213
03214
03215 else if (strncasecmp(buf, "Proxy-Authenticate:", 19) == 0) {
03216 configAuth(trimLead(buf + 19), true);
03217 }
03218
03219 else if (strncasecmp(buf, "Upgrade:", 8) == 0) {
03220
03221 QString offered = &(buf[8]);
03222 upgradeOffers = QStringList::split(QRegExp("[ \n,\r\t]"), offered);
03223 }
03224
03225
03226 else if (strncasecmp(buf, "Content-Encoding:", 17) == 0) {
03227
03228
03229
03230
03231
03232
03233
03234
03235
03236
03237
03238
03239
03240 addEncoding(trimLead(buf + 17), m_qContentEncodings);
03241 }
03242
03243 else if(strncasecmp(buf, "Content-Disposition:", 20) == 0) {
03244 char* dispositionBuf = trimLead(buf + 20);
03245 while ( *dispositionBuf )
03246 {
03247 if ( strncasecmp( dispositionBuf, "filename", 8 ) == 0 )
03248 {
03249 dispositionBuf += 8;
03250
03251 while ( *dispositionBuf == ' ' || *dispositionBuf == '=' )
03252 dispositionBuf++;
03253
03254 char* bufStart = dispositionBuf;
03255
03256 while ( *dispositionBuf && *dispositionBuf != ';' )
03257 dispositionBuf++;
03258
03259 if ( dispositionBuf > bufStart )
03260 {
03261
03262 while ( *bufStart == '"' )
03263 bufStart++;
03264
03265
03266 while ( *(dispositionBuf-1) == ' ' || *(dispositionBuf-1) == '"')
03267 dispositionBuf--;
03268
03269 if ( dispositionBuf > bufStart )
03270 dispositionFilename = QString::fromLatin1( bufStart, dispositionBuf-bufStart );
03271
03272 break;
03273 }
03274 }
03275 else
03276 {
03277 char *bufStart = dispositionBuf;
03278
03279 while ( *dispositionBuf && *dispositionBuf != ';' )
03280 dispositionBuf++;
03281
03282 if ( dispositionBuf > bufStart )
03283 dispositionType = QString::fromLatin1( bufStart, dispositionBuf-bufStart ).stripWhiteSpace();
03284
03285 while ( *dispositionBuf == ';' || *dispositionBuf == ' ' )
03286 dispositionBuf++;
03287 }
03288 }
03289
03290
03291
03292 if ( !dispositionFilename.isEmpty() )
03293 {
03294 int pos = dispositionFilename.findRev( '/' );
03295
03296 if( pos > -1 )
03297 dispositionFilename = dispositionFilename.mid(pos+1);
03298
03299 kdDebug(7113) << "(" << m_pid << ") Content-Disposition: filename="
03300 << dispositionFilename<< endl;
03301 }
03302 }
03303 else if(strncasecmp(buf, "Content-Language:", 17) == 0) {
03304 QString language = QString::fromLatin1(trimLead(buf+17)).stripWhiteSpace();
03305 if (!language.isEmpty())
03306 setMetaData("content-language", language);
03307 }
03308 else if (strncasecmp(buf, "Proxy-Connection:", 17) == 0)
03309 {
03310 if (strncasecmp(trimLead(buf + 17), "Close", 5) == 0)
03311 m_bKeepAlive = false;
03312 else if (strncasecmp(trimLead(buf + 17), "Keep-Alive", 10)==0)
03313 m_bKeepAlive = true;
03314 }
03315 else if (strncasecmp(buf, "Link:", 5) == 0) {
03316
03317 QStringList link = QStringList::split(";", QString(buf)
03318 .replace(QRegExp("^Link:[ ]*"),
03319 ""));
03320 if (link.count() == 2) {
03321 QString rel = link[1].stripWhiteSpace();
03322 if (rel.startsWith("rel=\"")) {
03323 rel = rel.mid(5, rel.length() - 6);
03324 if (rel.lower() == "pageservices") {
03325 QString url = link[0].replace(QRegExp("[<>]"),"").stripWhiteSpace();
03326 setMetaData("PageServices", url);
03327 }
03328 }
03329 }
03330 }
03331 else if (strncasecmp(buf, "P3P:", 4) == 0) {
03332 QString p3pstr = buf;
03333 p3pstr = p3pstr.mid(4).simplifyWhiteSpace();
03334 QStringList policyrefs, compact;
03335 QStringList policyfields = QStringList::split(QRegExp(",[ ]*"), p3pstr);
03336 for (QStringList::Iterator it = policyfields.begin();
03337 it != policyfields.end();
03338 ++it) {
03339 QStringList policy = QStringList::split("=", *it);
03340
03341 if (policy.count() == 2) {
03342 if (policy[0].lower() == "policyref") {
03343 policyrefs << policy[1].replace(QRegExp("[\"\']"), "")
03344 .stripWhiteSpace();
03345 } else if (policy[0].lower() == "cp") {
03346
03347
03348
03349 QStringList cps = QStringList::split(" ",
03350 policy[1].replace(QRegExp("[\"\']"), "")
03351 .simplifyWhiteSpace());
03352
03353 for (QStringList::Iterator j = cps.begin(); j != cps.end(); ++j)
03354 compact << *j;
03355 }
03356 }
03357 }
03358
03359 if (!policyrefs.isEmpty())
03360 setMetaData("PrivacyPolicy", policyrefs.join("\n"));
03361
03362 if (!compact.isEmpty())
03363 setMetaData("PrivacyCompactPolicy", compact.join("\n"));
03364 }
03365
03366 else if (strncasecmp(buf, "Connection:", 11) == 0)
03367 {
03368 if (strncasecmp(trimLead(buf + 11), "Close", 5) == 0)
03369 m_bKeepAlive = false;
03370 else if (strncasecmp(trimLead(buf + 11), "Keep-Alive", 10)==0)
03371 m_bKeepAlive = true;
03372 else if (strncasecmp(trimLead(buf + 11), "Upgrade", 7)==0)
03373 {
03374 if (m_responseCode == 101) {
03375
03376 upgradeRequired = true;
03377 } else if (upgradeRequired) {
03378
03379 } else {
03380
03381 canUpgrade = true;
03382 }
03383 }
03384 }
03385
03386 else if ( httpRev == HTTP_11) {
03387
03388 if (strncasecmp(buf, "Transfer-Encoding:", 18) == 0) {
03389
03390
03391
03392 addEncoding(trimLead(buf + 18), m_qTransferEncodings);
03393 }
03394
03395
03396 else if (strncasecmp(buf, "Content-MD5:", 12) == 0) {
03397 m_sContentMD5 = QString::fromLatin1(trimLead(buf + 12));
03398 }
03399
03400
03401
03402 else if (strncasecmp(buf, "DAV:", 4) == 0) {
03403 if (m_davCapabilities.isEmpty()) {
03404 m_davCapabilities << QString::fromLatin1(trimLead(buf + 4));
03405 }
03406 else {
03407 m_davCapabilities << QString::fromLatin1(trimLead(buf + 4));
03408 }
03409 }
03410
03411 }
03412 else if ((httpRev == HTTP_None) && (strlen(buf) != 0))
03413 {
03414
03415
03416 rewind();
03417 if (m_responseCode)
03418 m_prevResponseCode = m_responseCode;
03419
03420 m_responseCode = 200;
03421 httpRev = HTTP_Unknown;
03422 m_bKeepAlive = false;
03423 break;
03424 }
03425 setRewindMarker();
03426
03427
03428 memset(buffer, 0, sizeof(buffer));
03429
03430 } while (!m_bEOF && (len || noHeader) && (headerSize < maxHeaderSize) && (gets(buffer, sizeof(buffer)-1)));
03431
03432
03433
03434 QStringList::Iterator opt = upgradeOffers.begin();
03435 for( ; opt != upgradeOffers.end(); ++opt) {
03436 if (*opt == "TLS/1.0") {
03437 if(upgradeRequired) {
03438 if (!startTLS() && !usingTLS()) {
03439 error(ERR_UPGRADE_REQUIRED, *opt);
03440 return false;
03441 }
03442 }
03443 } else if (*opt == "HTTP/1.1") {
03444 httpRev = HTTP_11;
03445 } else {
03446
03447 if (upgradeRequired) {
03448 error(ERR_UPGRADE_REQUIRED, *opt);
03449 return false;
03450 }
03451 }
03452 }
03453
03454 setMetaData("charset", m_request.strCharset);
03455
03456
03457 if ( (m_responseCode == 401 && Authentication == AUTH_None) ||
03458 (m_responseCode == 407 && ProxyAuthentication == AUTH_None) )
03459 {
03460 m_bUnauthorized = false;
03461 if (m_request.bErrorPage)
03462 errorPage();
03463 else
03464 {
03465 error( ERR_UNSUPPORTED_ACTION, "Unknown Authorization method!" );
03466 return false;
03467 }
03468 }
03469
03470
03471 if (expireDate && (expireDate <= dateHeader))
03472 expireDate = 1;
03473
03474
03475 if (maxAge == 0)
03476 expireDate = 1;
03477 else if (maxAge > 0)
03478 {
03479 if (currentAge)
03480 maxAge -= currentAge;
03481 if (maxAge <=0)
03482 maxAge = 0;
03483 expireDate = time(0) + maxAge;
03484 }
03485
03486 if (!expireDate)
03487 {
03488 time_t lastModifiedDate = 0;
03489 if (!m_request.lastModified.isEmpty())
03490 lastModifiedDate = KRFCDate::parseDate(m_request.lastModified);
03491
03492 if (lastModifiedDate)
03493 {
03494 long diff = static_cast<long>(difftime(dateHeader, lastModifiedDate));
03495 if (diff < 0)
03496 expireDate = time(0) + 1;
03497 else
03498 expireDate = time(0) + (diff / 10);
03499 }
03500 else
03501 {
03502 expireDate = time(0) + DEFAULT_CACHE_EXPIRE;
03503 }
03504 }
03505
03506
03507 if (!cookieStr.isEmpty())
03508 {
03509 if ((m_request.cookieMode == HTTPRequest::CookiesAuto) && m_request.bUseCookiejar)
03510 {
03511
03512 QString domain = config()->readEntry("cross-domain");
03513 if (!domain.isEmpty() && isCrossDomainRequest(m_request.url.host(), domain))
03514 cookieStr = "Cross-Domain\n" + cookieStr;
03515 addCookies( m_request.url.url(), cookieStr );
03516 }
03517 else if (m_request.cookieMode == HTTPRequest::CookiesManual)
03518 {
03519
03520 setMetaData("setcookies", cookieStr);
03521 }
03522 }
03523
03524 if (m_request.bMustRevalidate)
03525 {
03526 m_request.bMustRevalidate = false;
03527 if (cacheValidated)
03528 {
03529
03530
03531 fclose(m_request.fcache);
03532 m_request.fcache = 0;
03533 updateExpireDate( expireDate, true );
03534 m_request.fcache = checkCacheEntry( );
03535
03536 if (m_request.fcache)
03537 {
03538 m_request.bCachedRead = true;
03539 goto try_again;
03540 }
03541 else
03542 {
03543
03544 }
03545 }
03546 else
03547 {
03548
03549 fclose(m_request.fcache);
03550 m_request.fcache = 0;
03551 }
03552 }
03553
03554
03555 if ( cont )
03556 {
03557 goto try_again;
03558 }
03559
03560
03561
03562 if (!m_bChunked && (m_iSize == NO_SIZE))
03563 m_bKeepAlive = false;
03564
03565 if ( m_responseCode == 204 )
03566 {
03567 return true;
03568 }
03569
03570
03571 if ( m_bUnauthorized )
03572 {
03573 if ( (m_responseCode == 401) ||
03574 (m_bUseProxy && (m_responseCode == 407))
03575 )
03576 {
03577 if ( getAuthorization() )
03578 {
03579
03580 if ( Authentication == AUTH_NTLM && m_strAuthorization.length() > 4 )
03581 {
03582 m_bKeepAlive = true;
03583 readBody( true );
03584 }
03585 else if (ProxyAuthentication == AUTH_NTLM && m_strProxyAuthorization.length() > 4)
03586 {
03587 readBody( true );
03588 }
03589 else
03590 httpCloseConnection();
03591 return false;
03592 }
03593
03594 if (m_bError)
03595 return false;
03596
03597
03598 }
03599 m_bUnauthorized = false;
03600 }
03601
03602
03603 if (!locationStr.isEmpty())
03604 {
03605 KURL u(m_request.url, locationStr);
03606 if(!u.isValid())
03607 {
03608 error(ERR_MALFORMED_URL, u.url());
03609 return false;
03610 }
03611 if ((u.protocol() != "http") && (u.protocol() != "https") &&
03612 (u.protocol() != "ftp") && (u.protocol() != "webdav") &&
03613 (u.protocol() != "webdavs"))
03614 {
03615 redirection(u);
03616 error(ERR_ACCESS_DENIED, u.url());
03617 return false;
03618 }
03619
03620
03621
03622
03623
03624 if (m_request.url.hasRef() && !u.hasRef() &&
03625 (m_request.url.host() == u.host()) &&
03626 (m_request.url.protocol() == u.protocol()))
03627 u.setRef(m_request.url.ref());
03628
03629 m_bRedirect = true;
03630 m_redirectLocation = u;
03631
03632 if (!m_request.id.isEmpty())
03633 {
03634 sendMetaData();
03635 }
03636
03637 kdDebug(7113) << "(" << m_pid << ") request.url: " << m_request.url.url()
03638 << endl << "LocationStr: " << locationStr.data() << endl;
03639
03640 kdDebug(7113) << "(" << m_pid << ") Requesting redirection to: " << u.url()
03641 << endl;
03642
03643
03644 if (m_protocol == "webdav" || m_protocol == "webdavs")
03645 u.setProtocol(m_protocol);
03646
03647 redirection(u);
03648 m_request.bCachedWrite = false;
03649 mayCache = false;
03650 }
03651
03652
03653 if ( bCanResume && m_request.offset )
03654 canResume();
03655 else
03656 m_request.offset = 0;
03657
03658
03659 if (m_strMimeType.startsWith("text/") &&
03660 (m_strMimeType != "text/css") &&
03661 (m_strMimeType != "text/x-javascript") &&
03662 !hasCacheDirective)
03663 {
03664
03665
03666
03667 if ( m_bIsSSL || (Authentication != AUTH_None) )
03668 {
03669 m_request.bCachedWrite = false;
03670 mayCache = false;
03671 }
03672 }
03673
03674
03675
03676
03677
03678
03679 if (m_qContentEncodings.last() == "gzip")
03680 {
03681 if (m_strMimeType == "application/x-tar")
03682 {
03683 m_qContentEncodings.remove(m_qContentEncodings.fromLast());
03684 m_strMimeType = QString::fromLatin1("application/x-tgz");
03685 }
03686 else if (m_strMimeType == "application/postscript")
03687 {
03688
03689
03690 m_qContentEncodings.remove(m_qContentEncodings.fromLast());
03691 m_strMimeType = QString::fromLatin1("application/x-gzpostscript");
03692 }
03693 else if ( (m_request.allowCompressedPage &&
03694 m_strMimeType == "text/html")
03695 ||
03696 (m_request.allowCompressedPage &&
03697 m_strMimeType != "application/x-tgz" &&
03698 m_strMimeType != "application/x-targz" &&
03699 m_strMimeType != "application/x-gzip" &&
03700 m_request.url.path().right(3) != ".gz")
03701 )
03702 {
03703
03704 }
03705 else
03706 {
03707 m_qContentEncodings.remove(m_qContentEncodings.fromLast());
03708 m_strMimeType = QString::fromLatin1("application/x-gzip");
03709 }
03710 }
03711
03712
03713
03714
03715
03716
03717
03718 if (m_qContentEncodings.last() == "bzip2")
03719 {
03720 m_qContentEncodings.remove(m_qContentEncodings.fromLast());
03721 m_strMimeType = QString::fromLatin1("application/x-bzip2");
03722 }
03723
03724
03725 if (m_strMimeType == "application/x-targz")
03726 m_strMimeType = QString::fromLatin1("application/x-tgz");
03727 else if (m_strMimeType == "application/zip")
03728 m_strMimeType = QString::fromLatin1("application/x-zip");
03729 else if (m_strMimeType == "image/x-png")
03730 m_strMimeType = QString::fromLatin1("image/png");
03731 else if (m_strMimeType == "image/bmp")
03732 m_strMimeType = QString::fromLatin1("image/x-bmp");
03733 else if (m_strMimeType == "audio/mpeg" || m_strMimeType == "audio/x-mpeg" || m_strMimeType == "audio/mp3")
03734 m_strMimeType = QString::fromLatin1("audio/x-mp3");
03735 else if (m_strMimeType == "audio/microsoft-wave")
03736 m_strMimeType = QString::fromLatin1("audio/x-wav");
03737 else if (m_strMimeType == "audio/midi")
03738 m_strMimeType = QString::fromLatin1("audio/x-midi");
03739 else if (m_strMimeType == "image/x-xpixmap")
03740 m_strMimeType = QString::fromLatin1("image/x-xpm");
03741 else if (m_strMimeType == "application/rtf")
03742 m_strMimeType = QString::fromLatin1("text/rtf");
03743
03744
03745 else if (m_strMimeType == "application/pkix-cert" ||
03746 m_strMimeType == "application/binary-certificate")
03747 {
03748 m_strMimeType = QString::fromLatin1("application/x-x509-ca-cert");
03749 }
03750
03751
03752 else if (m_strMimeType == "application/x-gzip")
03753 {
03754 if ((m_request.url.path().right(7) == ".tar.gz") ||
03755 (m_request.url.path().right(4) == ".tar"))
03756 m_strMimeType = QString::fromLatin1("application/x-tgz");
03757 if ((m_request.url.path().right(6) == ".ps.gz"))
03758 m_strMimeType = QString::fromLatin1("application/x-gzpostscript");
03759 }
03760
03761
03762 else if ((m_strMimeType == "text/plain") || (m_strMimeType == "application/octet-stream"))
03763 {
03764 QString ext = m_request.url.path().right(4).upper();
03765 if (ext == ".BZ2")
03766 m_strMimeType = QString::fromLatin1("application/x-bzip2");
03767 else if (ext == ".PEM")
03768 m_strMimeType = QString::fromLatin1("application/x-x509-ca-cert");
03769 else if (ext == ".SWF")
03770 m_strMimeType = QString::fromLatin1("application/x-shockwave-flash");
03771 else if (ext == ".PLS")
03772 m_strMimeType = QString::fromLatin1("audio/x-scpls");
03773 else if (ext == ".WMV")
03774 m_strMimeType = QString::fromLatin1("video/x-ms-wmv");
03775 }
03776
03777 #if 0
03778
03779
03780
03781 if (!m_qContentEncodings.isEmpty())
03782 {
03783
03784 m_iSize = NO_SIZE;
03785 }
03786 #endif
03787
03788 if( !dispositionType.isEmpty() )
03789 {
03790 kdDebug(7113) << "(" << m_pid << ") Setting Content-Disposition type to: "
03791 << dispositionType << endl;
03792 setMetaData("content-disposition-type", dispositionType);
03793 }
03794 if( !dispositionFilename.isEmpty() )
03795 {
03796 kdDebug(7113) << "(" << m_pid << ") Setting Content-Disposition filename to: "
03797 << dispositionFilename << endl;
03798
03799 setMetaData("content-disposition", dispositionFilename);
03800 setMetaData("content-disposition-filename", dispositionFilename);
03801 }
03802
03803 if (!m_request.lastModified.isEmpty())
03804 setMetaData("modified", m_request.lastModified);
03805
03806 if (!mayCache)
03807 {
03808 setMetaData("no-cache", "true");
03809 setMetaData("expire-date", "1");
03810 }
03811 else
03812 {
03813 QString tmp;
03814 tmp.setNum(expireDate);
03815 setMetaData("expire-date", tmp);
03816 tmp.setNum(time(0));
03817 setMetaData("cache-creation-date", tmp);
03818 }
03819
03820
03821
03822 if (locationStr.isEmpty() && (!m_strMimeType.isEmpty() ||
03823 m_request.method == HTTP_HEAD))
03824 {
03825 kdDebug(7113) << "(" << m_pid << ") Emitting mimetype " << m_strMimeType << endl;
03826 mimeType( m_strMimeType );
03827 }
03828
03829 forwardHttpResponseHeader();
03830
03831 if (m_request.method == HTTP_HEAD)
03832 return true;
03833
03834
03835 if (m_request.bUseCache)
03836 {
03837 ::unlink( QFile::encodeName(m_request.cef));
03838 if ( m_request.bCachedWrite && !m_strMimeType.isEmpty() )
03839 {
03840
03841 createCacheEntry(m_strMimeType, expireDate);
03842 if (!m_request.fcache)
03843 {
03844 m_request.bCachedWrite = false;
03845 kdDebug(7113) << "(" << m_pid << ") Error creating cache entry for " << m_request.url.url()<<"!\n";
03846 }
03847 m_request.expireDate = expireDate;
03848 m_maxCacheSize = config()->readNumEntry("MaxCacheSize", DEFAULT_MAX_CACHE_SIZE) / 2;
03849 }
03850 }
03851
03852 if (m_request.bCachedWrite && !m_strMimeType.isEmpty())
03853 kdDebug(7113) << "(" << m_pid << ") Cache, adding \"" << m_request.url.url() << "\"" << endl;
03854 else if (m_request.bCachedWrite && m_strMimeType.isEmpty())
03855 kdDebug(7113) << "(" << m_pid << ") Cache, pending \"" << m_request.url.url() << "\"" << endl;
03856 else
03857 kdDebug(7113) << "(" << m_pid << ") Cache, not adding \"" << m_request.url.url() << "\"" << endl;
03858 return true;
03859 }
03860
03861
03862 void HTTPProtocol::addEncoding(QString encoding, QStringList &encs)
03863 {
03864 encoding = encoding.stripWhiteSpace().lower();
03865
03866 if (encoding == "identity") {
03867 return;
03868 } else if (encoding == "8bit") {
03869
03870 return;
03871 } else if (encoding == "chunked") {
03872 m_bChunked = true;
03873
03874
03875 m_iSize = NO_SIZE;
03876 } else if ((encoding == "x-gzip") || (encoding == "gzip")) {
03877 encs.append(QString::fromLatin1("gzip"));
03878 } else if ((encoding == "x-bzip2") || (encoding == "bzip2")) {
03879 encs.append(QString::fromLatin1("bzip2"));
03880 } else if ((encoding == "x-deflate") || (encoding == "deflate")) {
03881 encs.append(QString::fromLatin1("deflate"));
03882 } else {
03883 kdDebug(7113) << "(" << m_pid << ") Unknown encoding encountered. "
03884 << "Please write code. Encoding = \"" << encoding
03885 << "\"" << endl;
03886 }
03887 }
03888
03889 bool HTTPProtocol::sendBody()
03890 {
03891 int result=-1;
03892 int length=0;
03893
03894 infoMessage( i18n( "Requesting data to send" ) );
03895
03896
03897
03898
03899 if ( !m_bufPOST.isNull() )
03900 {
03901 kdDebug(7113) << "(" << m_pid << ") POST'ing saved data..." << endl;
03902
03903 result = 0;
03904 length = m_bufPOST.size();
03905 }
03906 else
03907 {
03908 kdDebug(7113) << "(" << m_pid << ") POST'ing live data..." << endl;
03909
03910 QByteArray buffer;
03911 int old_size;
03912
03913 m_bufPOST.resize(0);
03914 do
03915 {
03916 dataReq();
03917 result = readData( buffer );
03918 if ( result > 0 )
03919 {
03920 length += result;
03921 old_size = m_bufPOST.size();
03922 m_bufPOST.resize( old_size+result );
03923 memcpy( m_bufPOST.data()+ old_size, buffer.data(), buffer.size() );
03924 buffer.resize(0);
03925 }
03926 } while ( result > 0 );
03927 }
03928
03929 if ( result < 0 )
03930 {
03931 error( ERR_ABORTED, m_request.hostname );
03932 return false;
03933 }
03934
03935 infoMessage( i18n( "Sending data to %1" ).arg( m_request.hostname ) );
03936
03937 QString size = QString ("Content-Length: %1\r\n\r\n").arg(length);
03938 kdDebug( 7113 ) << "(" << m_pid << ")" << size << endl;
03939
03940
03941 bool sendOk = (write(size.latin1(), size.length()) == (ssize_t) size.length());
03942 if (!sendOk)
03943 {
03944 kdDebug( 7113 ) << "(" << m_pid << ") Connection broken when sending "
03945 << "content length: (" << m_state.hostname << ")" << endl;
03946 error( ERR_CONNECTION_BROKEN, m_state.hostname );
03947 return false;
03948 }
03949
03950
03951
03952 sendOk = (write(m_bufPOST.data(), m_bufPOST.size()) == (ssize_t) m_bufPOST.size());
03953 if (!sendOk)
03954 {
03955 kdDebug(7113) << "(" << m_pid << ") Connection broken when sending message body: ("
03956 << m_state.hostname << ")" << endl;
03957 error( ERR_CONNECTION_BROKEN, m_state.hostname );
03958 return false;
03959 }
03960
03961 return true;
03962 }
03963
03964 void HTTPProtocol::httpClose( bool keepAlive )
03965 {
03966 kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::httpClose" << endl;
03967
03968 if (m_request.fcache)
03969 {
03970 fclose(m_request.fcache);
03971 m_request.fcache = 0;
03972 if (m_request.bCachedWrite)
03973 {
03974 QString filename = m_request.cef + ".new";
03975 ::unlink( QFile::encodeName(filename) );
03976 }
03977 }
03978
03979
03980
03981
03982
03983 if (keepAlive && (!m_bUseProxy ||
03984 m_bPersistentProxyConnection || m_bIsTunneled))
03985 {
03986 if (!m_keepAliveTimeout)
03987 m_keepAliveTimeout = DEFAULT_KEEP_ALIVE_TIMEOUT;
03988 else if (m_keepAliveTimeout > 2*DEFAULT_KEEP_ALIVE_TIMEOUT)
03989 m_keepAliveTimeout = 2*DEFAULT_KEEP_ALIVE_TIMEOUT;
03990
03991 kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::httpClose: keep alive (" << m_keepAliveTimeout << ")" << endl;
03992 QByteArray data;
03993 QDataStream stream( data, IO_WriteOnly );
03994 stream << int(99);
03995 setTimeoutSpecialCommand(m_keepAliveTimeout, data);
03996 return;
03997 }
03998
03999 httpCloseConnection();
04000 }
04001
04002 void HTTPProtocol::closeConnection()
04003 {
04004 kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::closeConnection" << endl;
04005 httpCloseConnection ();
04006 }
04007
04008 void HTTPProtocol::httpCloseConnection ()
04009 {
04010 kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::httpCloseConnection" << endl;
04011 m_bIsTunneled = false;
04012 m_bKeepAlive = false;
04013 closeDescriptor();
04014 setTimeoutSpecialCommand(-1);
04015 }
04016
04017 void HTTPProtocol::slave_status()
04018 {
04019 kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::slave_status" << endl;
04020
04021 if ( m_iSock != -1 && !isConnectionValid() )
04022 httpCloseConnection();
04023
04024 slaveStatus( m_state.hostname, (m_iSock != -1) );
04025 }
04026
04027 void HTTPProtocol::mimetype( const KURL& url )
04028 {
04029 kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::mimetype: "
04030 << url.prettyURL() << endl;
04031
04032 if ( !checkRequestURL( url ) )
04033 return;
04034
04035 m_request.method = HTTP_HEAD;
04036 m_request.path = url.path();
04037 m_request.query = url.query();
04038 m_request.cache = CC_Cache;
04039 m_request.doProxy = m_bUseProxy;
04040
04041 retrieveHeader();
04042
04043 kdDebug(7113) << "(" << m_pid << ") http: mimetype = " << m_strMimeType
04044 << endl;
04045 }
04046
04047 void HTTPProtocol::special( const QByteArray &data )
04048 {
04049 kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::special" << endl;
04050
04051 int tmp;
04052 QDataStream stream(data, IO_ReadOnly);
04053
04054 stream >> tmp;
04055 switch (tmp) {
04056 case 1:
04057 {
04058 KURL url;
04059 stream >> url;
04060 post( url );
04061 break;
04062 }
04063 case 2:
04064 {
04065 KURL url;
04066 bool no_cache;
04067 time_t expireDate;
04068 stream >> url >> no_cache >> expireDate;
04069 cacheUpdate( url, no_cache, expireDate );
04070 break;
04071 }
04072 case 5:
04073 {
04074 KURL url;
04075 QString scope, type, owner;
04076 stream >> url >> scope >> type >> owner;
04077 davLock( url, scope, type, owner );
04078 break;
04079 }
04080 case 6:
04081 {
04082 KURL url;
04083 stream >> url;
04084 davUnlock( url );
04085 break;
04086 }
04087 case 7:
04088 {
04089 KURL url;
04090 int method;
04091 stream >> url >> method;
04092 davGeneric( url, (KIO::HTTP_METHOD) method );
04093 break;
04094 }
04095 case 99:
04096 {
04097 httpCloseConnection();
04098 break;
04099 }
04100 default:
04101
04102
04103 break;
04104 }
04105 }
04106
04110 int HTTPProtocol::readChunked()
04111 {
04112 if ((m_iBytesLeft == 0) || (m_iBytesLeft == NO_SIZE))
04113 {
04114 setRewindMarker();
04115
04116 m_bufReceive.resize(4096);
04117
04118 if (!gets(m_bufReceive.data(), m_bufReceive.size()-1))
04119 {
04120 kdDebug(7113) << "(" << m_pid << ") gets() failure on Chunk header" << endl;
04121 return -1;
04122 }
04123
04124
04125 if (m_bufReceive[0] == '\0')
04126 {
04127 if (!gets(m_bufReceive.data(), m_bufReceive.size()-1))
04128 {
04129 kdDebug(7113) << "(" << m_pid << ") gets() failure on Chunk header" << endl;
04130 return -1;
04131 }
04132 }
04133 if (m_bEOF)
04134 {
04135 kdDebug(7113) << "(" << m_pid << ") EOF on Chunk header" << endl;
04136 return -1;
04137 }
04138
04139 long long trunkSize = STRTOLL(m_bufReceive.data(), 0, 16);
04140 if (trunkSize < 0)
04141 {
04142 kdDebug(7113) << "(" << m_pid << ") Negative chunk size" << endl;
04143 return -1;
04144 }
04145 m_iBytesLeft = trunkSize;
04146
04147
04148
04149 if (m_iBytesLeft == 0)
04150 {
04151
04152
04153 do {
04154
04155 if (!gets(m_bufReceive.data(), m_bufReceive.size()-1))
04156 {
04157 kdDebug(7113) << "(" << m_pid << ") gets() failure on Chunk trailer" << endl;
04158 return -1;
04159 }
04160
04161 }
04162 while (strlen(m_bufReceive.data()) != 0);
04163
04164 return 0;
04165 }
04166 }
04167
04168 int bytesReceived = readLimited();
04169 if (!m_iBytesLeft)
04170 m_iBytesLeft = NO_SIZE;
04171 return bytesReceived;
04172 }
04173
04174 int HTTPProtocol::readLimited()
04175 {
04176 if (!m_iBytesLeft)
04177 return 0;
04178
04179 m_bufReceive.resize(4096);
04180
04181 int bytesReceived;
04182 int bytesToReceive;
04183
04184 if (m_iBytesLeft > m_bufReceive.size())
04185 bytesToReceive = m_bufReceive.size();
04186 else
04187 bytesToReceive = m_iBytesLeft;
04188
04189 bytesReceived = read(m_bufReceive.data(), bytesToReceive);
04190
04191 if (bytesReceived <= 0)
04192 return -1;
04193
04194 m_iBytesLeft -= bytesReceived;
04195 return bytesReceived;
04196 }
04197
04198 int HTTPProtocol::readUnlimited()
04199 {
04200 if (m_bKeepAlive)
04201 {
04202 kdDebug(7113) << "(" << m_pid << ") Unbounded datastream on a Keep "
04203 << "alive connection!" << endl;
04204 m_bKeepAlive = false;
04205 }
04206
04207 m_bufReceive.resize(4096);
04208
04209 int result = read(m_bufReceive.data(), m_bufReceive.size());
04210 if (result > 0)
04211 return result;
04212
04213 m_bEOF = true;
04214 m_iBytesLeft = 0;
04215 return 0;
04216 }
04217
04218 void HTTPProtocol::slotData(const QByteArray &_d)
04219 {
04220 if (!_d.size())
04221 {
04222 m_bEOD = true;
04223 return;
04224 }
04225
04226 if (m_iContentLeft != NO_SIZE)
04227 {
04228 if (m_iContentLeft >= _d.size())
04229 m_iContentLeft -= _d.size();
04230 else
04231 m_iContentLeft = NO_SIZE;
04232 }
04233
04234 QByteArray d = _d;
04235 if ( !m_dataInternal )
04236 {
04237
04238
04239
04240 if ( m_strMimeType.isEmpty() && !m_bRedirect &&
04241 !( m_responseCode >= 300 && m_responseCode <=399) )
04242 {
04243 kdDebug(7113) << "(" << m_pid << ") Determining mime-type from content..." << endl;
04244 int old_size = m_mimeTypeBuffer.size();
04245 m_mimeTypeBuffer.resize( old_size + d.size() );
04246 memcpy( m_mimeTypeBuffer.data() + old_size, d.data(), d.size() );
04247 if ( (m_iBytesLeft != NO_SIZE) && (m_iBytesLeft > 0)
04248 && (m_mimeTypeBuffer.size() < 1024) )
04249 {
04250 m_cpMimeBuffer = true;
04251 return;
04252 }
04253
04254 kdDebug(7113) << "(" << m_pid << ") Mimetype buffer size: " << m_mimeTypeBuffer.size()
04255 << endl;
04256
04257 KMimeMagicResult *result;
04258 result = KMimeMagic::self()->findBufferFileType( m_mimeTypeBuffer,
04259 m_request.url.fileName() );
04260 if( result )
04261 {
04262 m_strMimeType = result->mimeType();
04263 kdDebug(7113) << "(" << m_pid << ") Mimetype from content: "
04264 << m_strMimeType << endl;
04265 }
04266
04267 if ( m_strMimeType.isEmpty() )
04268 {
04269 m_strMimeType = QString::fromLatin1( DEFAULT_MIME_TYPE );
04270 kdDebug(7113) << "(" << m_pid << ") Using default mimetype: "
04271 << m_strMimeType << endl;
04272 }
04273
04274 if ( m_request.bCachedWrite )
04275 {
04276 createCacheEntry( m_strMimeType, m_request.expireDate );
04277 if (!m_request.fcache)
04278 m_request.bCachedWrite = false;
04279 }
04280
04281 if ( m_cpMimeBuffer )
04282 {
04283 d.resize(0);
04284 d.resize(m_mimeTypeBuffer.size());
04285 memcpy( d.data(), m_mimeTypeBuffer.data(),
04286 d.size() );
04287 }
04288 mimeType(m_strMimeType);
04289 m_mimeTypeBuffer.resize(0);
04290 }
04291
04292 data( d );
04293 if (m_request.bCachedWrite && m_request.fcache)
04294 writeCacheEntry(d.data(), d.size());
04295 }
04296 else
04297 {
04298 uint old_size = m_bufWebDavData.size();
04299 m_bufWebDavData.resize (old_size + d.size());
04300 memcpy (m_bufWebDavData.data() + old_size, d.data(), d.size());
04301 }
04302 }
04303
04313 bool HTTPProtocol::readBody( bool dataInternal )
04314 {
04315 if (m_responseCode == 204)
04316 return true;
04317
04318 m_bEOD = false;
04319
04320
04321
04322
04323
04324 m_dataInternal = dataInternal;
04325 if ( dataInternal )
04326 m_bufWebDavData.resize (0);
04327
04328
04329
04330 bool useMD5 = !m_sContentMD5.isEmpty();
04331
04332
04333 KIO::filesize_t sz = m_request.offset;
04334 if ( sz )
04335 m_iSize += sz;
04336
04337
04338
04339
04340
04341 if ( !dataInternal ) {
04342 if ( (m_iSize > 0) && (m_iSize != NO_SIZE)) {
04343 totalSize(m_iSize);
04344 infoMessage( i18n( "Retrieving %1 from %2...").arg(KIO::convertSize(m_iSize))
04345 .arg( m_request.hostname ) );
04346 }
04347 else
04348 {
04349 totalSize ( 0 );
04350 }
04351 }
04352 else
04353 infoMessage( i18n( "Retrieving from %1..." ).arg( m_request.hostname ) );
04354
04355 if (m_request.bCachedRead)
04356 {
04357 kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::readBody: read data from cache!" << endl;
04358 m_request.bCachedWrite = false;
04359
04360 char buffer[ MAX_IPC_SIZE ];
04361
04362 m_iContentLeft = NO_SIZE;
04363
04364
04365 while (!feof(m_request.fcache) && !ferror(m_request.fcache))
04366 {
04367 int nbytes = fread( buffer, 1, MAX_IPC_SIZE, m_request.fcache);
04368
04369 if (nbytes > 0)
04370 {
04371 m_bufReceive.setRawData( buffer, nbytes);
04372 slotData( m_bufReceive );
04373 m_bufReceive.resetRawData( buffer, nbytes );
04374 sz += nbytes;
04375 }
04376 }
04377
04378 m_bufReceive.resize( 0 );
04379
04380 if ( !dataInternal )
04381 {
04382 processedSize( sz );
04383 data( QByteArray() );
04384 }
04385
04386 return true;
04387 }
04388
04389
04390 if (m_iSize != NO_SIZE)
04391 m_iBytesLeft = m_iSize - sz;
04392 else
04393 m_iBytesLeft = NO_SIZE;
04394
04395 m_iContentLeft = m_iBytesLeft;
04396
04397 if (m_bChunked)
04398 m_iBytesLeft = NO_SIZE;
04399
04400 kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::readBody: retrieve data. "<<KIO::number(m_iBytesLeft)<<" left." << endl;
04401
04402
04403 m_cpMimeBuffer = false;
04404 m_mimeTypeBuffer.resize(0);
04405 struct timeval last_tv;
04406 gettimeofday( &last_tv, 0L );
04407
04408 HTTPFilterChain chain;
04409
04410 QObject::connect(&chain, SIGNAL(output(const QByteArray &)),
04411 this, SLOT(slotData(const QByteArray &)));
04412 QObject::connect(&chain, SIGNAL(error(int, const QString &)),
04413 this, SLOT(error(int, const QString &)));
04414
04415
04416 while (!m_qTransferEncodings.isEmpty())
04417 {
04418 QString enc = m_qTransferEncodings.last();
04419 m_qTransferEncodings.remove(m_qTransferEncodings.fromLast());
04420 if ( enc == "gzip" )
04421 chain.addFilter(new HTTPFilterGZip);
04422 else if ( enc == "deflate" )
04423 chain.addFilter(new HTTPFilterDeflate);
04424 }
04425
04426
04427
04428
04429
04430
04431
04432 HTTPFilterMD5 *md5Filter = 0;
04433 if ( useMD5 )
04434 {
04435 md5Filter = new HTTPFilterMD5;
04436 chain.addFilter(md5Filter);
04437 }
04438
04439
04440
04441
04442
04443
04444
04445
04446
04447 while (!m_qContentEncodings.isEmpty())
04448 {
04449 QString enc = m_qContentEncodings.last();
04450 m_qContentEncodings.remove(m_qContentEncodings.fromLast());
04451 if ( enc == "gzip" )
04452 chain.addFilter(new HTTPFilterGZip);
04453 else if ( enc == "deflate" )
04454 chain.addFilter(new HTTPFilterDeflate);
04455 }
04456
04457 while (!m_bEOF)
04458 {
04459 int bytesReceived;
04460
04461 if (m_bChunked)
04462 bytesReceived = readChunked();
04463 else if (m_iSize != NO_SIZE)
04464 bytesReceived = readLimited();
04465 else
04466 bytesReceived = readUnlimited();
04467
04468
04469
04470
04471
04472 if (bytesReceived == -1)
04473 {
04474 if (m_iContentLeft == 0)
04475 {
04476
04477
04478 m_iBytesLeft = 0;
04479 break;
04480 }
04481
04482 kdDebug(7113) << "(" << m_pid << ") readBody: bytesReceived==-1 sz=" << (int)sz
04483 << " Connnection broken !" << endl;
04484 error(ERR_CONNECTION_BROKEN, m_state.hostname);
04485 return false;
04486 }
04487
04488
04489
04490 if (bytesReceived > 0)
04491 {
04492
04493
04494 m_bufReceive.truncate( bytesReceived );
04495
04496 chain.slotInput(m_bufReceive);
04497
04498 if (m_bError)
04499 return false;
04500
04501 sz += bytesReceived;
04502 if (!dataInternal)
04503 processedSize( sz );
04504 }
04505 m_bufReceive.resize(0);
04506
04507 if (m_iBytesLeft && m_bEOD && !m_bChunked)
04508 {
04509
04510
04511 m_iBytesLeft = 0;
04512 }
04513
04514 if (m_iBytesLeft == 0)
04515 {
04516 kdDebug(7113) << "("<<m_pid<<") EOD received! Left = "<< KIO::number(m_iBytesLeft) << endl;
04517 break;
04518 }
04519 }
04520 chain.slotInput(QByteArray());
04521
04522 if ( useMD5 )
04523 {
04524 QString calculatedMD5 = md5Filter->md5();
04525
04526 if ( m_sContentMD5 == calculatedMD5 )
04527 kdDebug(7113) << "(" << m_pid << ") MD5 checksum MATCHED!!" << endl;
04528 else
04529 kdDebug(7113) << "(" << m_pid << ") MD5 checksum MISMATCH! Expected: "
04530 << calculatedMD5 << ", Got: " << m_sContentMD5 << endl;
04531 }
04532
04533
04534 if (m_iBytesLeft == 0)
04535 {
04536 if (m_request.bCachedWrite && m_request.fcache)
04537 closeCacheEntry();
04538 else if (m_request.bCachedWrite) kdDebug(7113) << "(" << m_pid << ") no cache file!\n";
04539 }
04540 else kdDebug(7113) << "(" << m_pid << ") still "<< KIO::number(m_iBytesLeft) <<" bytes left! can't close cache entry!\n";
04541
04542 if (!dataInternal)
04543 data( QByteArray() );
04544 return true;
04545 }
04546
04547
04548 void HTTPProtocol::error( int _err, const QString &_text )
04549 {
04550 httpClose(false);
04551
04552 if (!m_request.id.isEmpty())
04553 {
04554 forwardHttpResponseHeader();
04555 sendMetaData();
04556 }
04557
04558
04559 if (!m_bufPOST.isEmpty())
04560 {
04561 m_bufPOST.resize(0);
04562 kdDebug(7113) << "(" << m_pid << ") HTTP::retreiveHeader: Cleared POST "
04563 "buffer..." << endl;
04564 }
04565
04566 SlaveBase::error( _err, _text );
04567 m_bError = true;
04568 }
04569
04570
04571 void HTTPProtocol::addCookies( const QString &url, const QCString &cookieHeader )
04572 {
04573 long windowId = m_request.window.toLong();
04574 QByteArray params;
04575 QDataStream stream(params, IO_WriteOnly);
04576 stream << url << cookieHeader << windowId;
04577
04578 kdDebug(7113) << "(" << m_pid << ") " << cookieHeader << endl;
04579 kdDebug(7113) << "(" << m_pid << ") " << "Window ID: "
04580 << windowId << ", for host = " << url << endl;
04581
04582 if ( !dcopClient()->send( "kded", "kcookiejar", "addCookies(QString,QCString,long int)", params ) )
04583 {
04584 kdWarning(7113) << "(" << m_pid << ") Can't communicate with kded_kcookiejar!" << endl;
04585 }
04586 }
04587
04588 QString HTTPProtocol::findCookies( const QString &url)
04589 {
04590 QCString replyType;
04591 QByteArray params;
04592 QByteArray reply;
04593 QString result;
04594
04595 long windowId = m_request.window.toLong();
04596 result = QString::null;
04597 QDataStream stream(params, IO_WriteOnly);
04598 stream << url << windowId;
04599
04600 if ( !dcopClient()->call( "kded", "kcookiejar", "findCookies(QString,long int)",
04601 params, replyType, reply ) )
04602 {
04603 kdWarning(7113) << "(" << m_pid << ") Can't communicate with kded_kcookiejar!" << endl;
04604 return result;
04605 }
04606 if ( replyType == "QString" )
04607 {
04608 QDataStream stream2( reply, IO_ReadOnly );
04609 stream2 >> result;
04610 }
04611 else
04612 {
04613 kdError(7113) << "(" << m_pid << ") DCOP function findCookies(...) returns "
04614 << replyType << ", expected QString" << endl;
04615 }
04616 return result;
04617 }
04618
04619
04620
04621
04622 void HTTPProtocol::cacheUpdate( const KURL& url, bool no_cache, time_t expireDate)
04623 {
04624 if ( !checkRequestURL( url ) )
04625 return;
04626
04627 m_request.path = url.path();
04628 m_request.query = url.query();
04629 m_request.cache = CC_Reload;
04630 m_request.doProxy = m_bUseProxy;
04631
04632 if (no_cache)
04633 {
04634 m_request.fcache = checkCacheEntry( );
04635 if (m_request.fcache)
04636 {
04637 fclose(m_request.fcache);
04638 m_request.fcache = 0;
04639 ::unlink( QFile::encodeName(m_request.cef) );
04640 }
04641 }
04642 else
04643 {
04644 updateExpireDate( expireDate );
04645 }
04646 finished();
04647 }
04648
04649
04650
04651
04652
04653 FILE* HTTPProtocol::checkCacheEntry( bool readWrite)
04654 {
04655 const QChar separator = '_';
04656
04657 QString CEF = m_request.path;
04658
04659 int p = CEF.find('/');
04660
04661 while(p != -1)
04662 {
04663 CEF[p] = separator;
04664 p = CEF.find('/', p);
04665 }
04666
04667 QString host = m_request.hostname.lower();
04668 CEF = host + CEF + '_';
04669
04670 QString dir = m_strCacheDir;
04671 if (dir[dir.length()-1] != '/')
04672 dir += "/";
04673
04674 int l = host.length();
04675 for(int i = 0; i < l; i++)
04676 {
04677 if (host[i].isLetter() && (host[i] != 'w'))
04678 {
04679 dir += host[i];
04680 break;
04681 }
04682 }
04683 if (dir[dir.length()-1] == '/')
04684 dir += "0";
04685
04686 unsigned long hash = 0x00000000;
04687 QCString u = m_request.url.url().latin1();
04688 for(int i = u.length(); i--;)
04689 {
04690 hash = (hash * 12211 + u[i]) % 2147483563;
04691 }
04692
04693 QString hashString;
04694 hashString.sprintf("%08lx", hash);
04695
04696 CEF = CEF + hashString;
04697
04698 CEF = dir + "/" + CEF;
04699
04700 m_request.cef = CEF;
04701
04702 const char *mode = (readWrite ? "r+" : "r");
04703
04704 FILE *fs = fopen( QFile::encodeName(CEF), mode);
04705 if (!fs)
04706 return 0;
04707
04708 char buffer[401];
04709 bool ok = true;
04710
04711
04712 if (ok && (!fgets(buffer, 400, fs)))
04713 ok = false;
04714 if (ok && (strcmp(buffer, CACHE_REVISION) != 0))
04715 ok = false;
04716
04717 time_t date;
04718 time_t currentDate = time(0);
04719
04720
04721 if (ok && (!fgets(buffer, 400, fs)))
04722 ok = false;
04723 if (ok)
04724 {
04725 int l = strlen(buffer);
04726 if (l>0)
04727 buffer[l-1] = 0;
04728 if (m_request.url.url() != buffer)
04729 {
04730 ok = false;
04731 }
04732 }
04733
04734
04735 if (ok && (!fgets(buffer, 400, fs)))
04736 ok = false;
04737 if (ok)
04738 {
04739 date = (time_t) strtoul(buffer, 0, 10);
04740 m_request.creationDate = date;
04741 if (m_maxCacheAge && (difftime(currentDate, date) > m_maxCacheAge))
04742 {
04743 m_request.bMustRevalidate = true;
04744 m_request.expireDate = currentDate;
04745 }
04746 }
04747
04748
04749 m_request.cacheExpireDateOffset = ftell(fs);
04750 if (ok && (!fgets(buffer, 400, fs)))
04751 ok = false;
04752 if (ok)
04753 {
04754 if (m_request.cache == CC_Verify)
04755 {
04756 date = (time_t) strtoul(buffer, 0, 10);
04757
04758 if (!date || difftime(currentDate, date) >= 0)
04759 m_request.bMustRevalidate = true;
04760 m_request.expireDate = date;
04761 }
04762 else if (m_request.cache == CC_Refresh)
04763 {
04764 m_request.bMustRevalidate = true;
04765 m_request.expireDate = currentDate;
04766 }
04767 }
04768
04769
04770 if (ok && (!fgets(buffer, 400, fs)))
04771 ok = false;
04772 if (ok)
04773 {
04774 m_request.etag = QString(buffer).stripWhiteSpace();
04775 }
04776
04777
04778 if (ok && (!fgets(buffer, 400, fs)))
04779 ok = false;
04780 if (ok)
04781 {
04782 m_request.lastModified = QString(buffer).stripWhiteSpace();
04783 }
04784
04785 if (ok)
04786 return fs;
04787
04788 fclose(fs);
04789 unlink( QFile::encodeName(CEF));
04790 return 0;
04791 }
04792
04793 void HTTPProtocol::updateExpireDate(time_t expireDate, bool updateCreationDate)
04794 {
04795 bool ok = true;
04796
04797 FILE *fs = checkCacheEntry(true);
04798 if (fs)
04799 {
04800 QString date;
04801 char buffer[401];
04802 time_t creationDate;
04803
04804 fseek(fs, 0, SEEK_SET);
04805 if (ok && !fgets(buffer, 400, fs))
04806 ok = false;
04807 if (ok && !fgets(buffer, 400, fs))
04808 ok = false;
04809 long cacheCreationDateOffset = ftell(fs);
04810 if (ok && !fgets(buffer, 400, fs))
04811 ok = false;
04812 creationDate = strtoul(buffer, 0, 10);
04813 if (!creationDate)
04814 ok = false;
04815
04816 if (updateCreationDate)
04817 {
04818 if (!ok || fseek(fs, cacheCreationDateOffset, SEEK_SET))
04819 return;
04820 QString date;
04821 date.setNum( time(0) );
04822 date = date.leftJustify(16);
04823 fputs(date.latin1(), fs);
04824 fputc('\n', fs);
04825 }
04826
04827 if (expireDate>(30*365*24*60*60))
04828 {
04829
04830
04831 date.setNum( expireDate );
04832 }
04833 else
04834 {
04835
04836
04837
04838
04839
04840 date.setNum( creationDate + expireDate );
04841 }
04842 date = date.leftJustify(16);
04843 if (!ok || fseek(fs, m_request.cacheExpireDateOffset, SEEK_SET))
04844 return;
04845 fputs(date.latin1(), fs);
04846 fseek(fs, 0, SEEK_END);
04847 fclose(fs);
04848 }
04849 }
04850
04851 void HTTPProtocol::createCacheEntry( const QString &mimetype, time_t expireDate)
04852 {
04853 QString dir = m_request.cef;
04854 int p = dir.findRev('/');
04855 if (p == -1) return;
04856 dir.truncate(p);
04857
04858
04859 (void) ::mkdir( QFile::encodeName(dir), 0700 );
04860
04861 QString filename = m_request.cef + ".new";
04862
04863
04864
04865 m_request.fcache = fopen( QFile::encodeName(filename), "w");
04866 if (!m_request.fcache)
04867 {
04868 kdWarning(7113) << "(" << m_pid << ")createCacheEntry: opening " << filename << " failed." << endl;
04869 return;
04870 }
04871
04872 fputs(CACHE_REVISION, m_request.fcache);
04873
04874 fputs(m_request.url.url().latin1(), m_request.fcache);
04875 fputc('\n', m_request.fcache);
04876
04877 QString date;
04878 m_request.creationDate = time(0);
04879 date.setNum( m_request.creationDate );
04880 date = date.leftJustify(16);
04881 fputs(date.latin1(), m_request.fcache);
04882 fputc('\n', m_request.fcache);
04883
04884 date.setNum( expireDate );
04885 date = date.leftJustify(16);
04886 fputs(date.latin1(), m_request.fcache);
04887 fputc('\n', m_request.fcache);
04888
04889 if (!m_request.etag.isEmpty())
04890 fputs(m_request.etag.latin1(), m_request.fcache);
04891 fputc('\n', m_request.fcache);
04892
04893 if (!m_request.lastModified.isEmpty())
04894 fputs(m_request.lastModified.latin1(), m_request.fcache);
04895 fputc('\n', m_request.fcache);
04896
04897 fputs(mimetype.latin1(), m_request.fcache);
04898 fputc('\n', m_request.fcache);
04899
04900 if (!m_request.strCharset.isEmpty())
04901 fputs(m_request.strCharset.latin1(), m_request.fcache);
04902 fputc('\n', m_request.fcache);
04903
04904 return;
04905 }
04906
04907
04908
04909
04910 void HTTPProtocol::writeCacheEntry( const char *buffer, int nbytes)
04911 {
04912 if (fwrite( buffer, nbytes, 1, m_request.fcache) != 1)
04913 {
04914 kdWarning(7113) << "(" << m_pid << ") writeCacheEntry: writing " << nbytes << " bytes failed." << endl;
04915 fclose(m_request.fcache);
04916 m_request.fcache = 0;
04917 QString filename = m_request.cef + ".new";
04918 ::unlink( QFile::encodeName(filename) );
04919 return;
04920 }
04921 long file_pos = ftell( m_request.fcache ) / 1024;
04922 if ( file_pos > m_maxCacheSize )
04923 {
04924 kdDebug(7113) << "writeCacheEntry: File size reaches " << file_pos
04925 << "Kb, exceeds cache limits. (" << m_maxCacheSize << "Kb)" << endl;
04926 fclose(m_request.fcache);
04927 m_request.fcache = 0;
04928 QString filename = m_request.cef + ".new";
04929 ::unlink( QFile::encodeName(filename) );
04930 return;
04931 }
04932 }
04933
04934 void HTTPProtocol::closeCacheEntry()
04935 {
04936 QString filename = m_request.cef + ".new";
04937 int result = fclose( m_request.fcache);
04938 m_request.fcache = 0;
04939 if (result == 0)
04940 {
04941 if (::rename( QFile::encodeName(filename), QFile::encodeName(m_request.cef)) == 0)
04942 return;
04943
04944 kdWarning(7113) << "(" << m_pid << ") closeCacheEntry: error renaming "
04945 << "cache entry. (" << filename << " -> " << m_request.cef
04946 << ")" << endl;
04947 }
04948
04949 kdWarning(7113) << "(" << m_pid << ") closeCacheEntry: error closing cache "
04950 << "entry. (" << filename<< ")" << endl;
04951 }
04952
04953 void HTTPProtocol::cleanCache()
04954 {
04955 const time_t maxAge = DEFAULT_CLEAN_CACHE_INTERVAL;
04956 bool doClean = false;
04957 QString cleanFile = m_strCacheDir;
04958 if (cleanFile[cleanFile.length()-1] != '/')
04959 cleanFile += "/";
04960 cleanFile += "cleaned";
04961
04962 struct stat stat_buf;
04963
04964 int result = ::stat(QFile::encodeName(cleanFile), &stat_buf);
04965 if (result == -1)
04966 {
04967 int fd = creat( QFile::encodeName(cleanFile), 0600);
04968 if (fd != -1)
04969 {
04970 doClean = true;
04971 ::close(fd);
04972 }
04973 }
04974 else
04975 {
04976 time_t age = (time_t) difftime( time(0), stat_buf.st_mtime );
04977 if (age > maxAge)
04978 doClean = true;
04979 }
04980 if (doClean)
04981 {
04982
04983 utime(QFile::encodeName(cleanFile), 0);
04984 KApplication::startServiceByDesktopPath("http_cache_cleaner.desktop");
04985 }
04986 }
04987
04988
04989
04990
04991
04992
04993 void HTTPProtocol::configAuth( char *p, bool isForProxy )
04994 {
04995 HTTP_AUTH f = AUTH_None;
04996 const char *strAuth = p;
04997
04998 if ( strncasecmp( p, "Basic", 5 ) == 0 )
04999 {
05000 f = AUTH_Basic;
05001 p += 5;
05002 strAuth = "Basic";
05003 }
05004 else if ( strncasecmp (p, "Digest", 6) == 0 )
05005 {
05006 f = AUTH_Digest;
05007 memcpy((void *)p, "Digest", 6);
05008 p += 6;
05009 }
05010 else if (strncasecmp( p, "MBS_PWD_COOKIE", 14 ) == 0)
05011 {
05012
05013 f = AUTH_Basic;
05014 p += 14;
05015 strAuth = "Basic";
05016 }
05017 #ifdef HAVE_LIBGSSAPI
05018 else if ( strncasecmp( p, "Negotiate", 9 ) == 0 )
05019 {
05020
05021
05022 if ( !isForProxy && !(m_responseCode == 401 && m_prevResponseCode == 401) )
05023 {
05024 f = AUTH_Negotiate;
05025 memcpy((void *)p, "Negotiate", 9);
05026 p += 9;
05027 };
05028 }
05029 #endif
05030 else if ( strncasecmp( p, "NTLM", 4 ) == 0 )
05031 {
05032 f = AUTH_NTLM;
05033 memcpy((void *)p, "NTLM", 4);
05034 p += 4;
05035 m_strRealm = "NTLM";
05036 }
05037 else
05038 {
05039 kdWarning(7113) << "(" << m_pid << ") Unsupported or invalid authorization "
05040 << "type requested" << endl;
05041 if (isForProxy)
05042 kdWarning(7113) << "(" << m_pid << ") Proxy URL: " << m_proxyURL << endl;
05043 else
05044 kdWarning(7113) << "(" << m_pid << ") URL: " << m_request.url << endl;
05045 kdWarning(7113) << "(" << m_pid << ") Request Authorization: " << p << endl;
05046 }
05047
05048
05049
05050
05051
05052
05053
05054
05055 if (isForProxy)
05056 {
05057 if ((f == AUTH_None) ||
05058 ((m_iProxyAuthCount > 0) && (f < ProxyAuthentication)))
05059 {
05060
05061
05062
05063
05064 if ( m_iProxyAuthCount == 0)
05065 ProxyAuthentication = f;
05066 kdDebug(7113) << "(" << m_pid << ") Rejected proxy auth method: " << f << endl;
05067 return;
05068 }
05069 m_iProxyAuthCount++;
05070 kdDebug(7113) << "(" << m_pid << ") Accepted proxy auth method: " << f << endl;
05071 }
05072 else
05073 {
05074 if ((f == AUTH_None) ||
05075 ((m_iWWWAuthCount > 0) && (f < Authentication)))
05076 {
05077 kdDebug(7113) << "(" << m_pid << ") Rejected auth method: " << f << endl;
05078 return;
05079 }
05080 m_iWWWAuthCount++;
05081 kdDebug(7113) << "(" << m_pid << ") Accepted auth method: " << f << endl;
05082 }
05083
05084
05085 while (*p)
05086 {
05087 int i = 0;
05088 while( (*p == ' ') || (*p == ',') || (*p == '\t') ) { p++; }
05089 if ( strncasecmp( p, "realm=", 6 ) == 0 )
05090 {
05091 p += 6;
05092 if (*p == '"') p++;
05093 while( p[i] && p[i] != '"' ) i++;
05094 if( isForProxy )
05095 m_strProxyRealm = QString::fromLatin1( p, i );
05096 else
05097 m_strRealm = QString::fromLatin1( p, i );
05098 if (!p[i]) break;
05099 }
05100 p+=(i+1);
05101 }
05102
05103 if( isForProxy )
05104 {
05105 ProxyAuthentication = f;
05106 m_strProxyAuthorization = QString::fromLatin1( strAuth );
05107 }
05108 else
05109 {
05110 Authentication = f;
05111 m_strAuthorization = QString::fromLatin1( strAuth );
05112 }
05113 }
05114
05115
05116 bool HTTPProtocol::retryPrompt()
05117 {
05118 QString prompt;
05119 switch ( m_responseCode )
05120 {
05121 case 401:
05122 prompt = i18n("Authentication Failed.");
05123 break;
05124 case 407:
05125 prompt = i18n("Proxy Authentication Failed.");
05126 break;
05127 default:
05128 break;
05129 }
05130 prompt += i18n(" Do you want to retry?");
05131 return (messageBox(QuestionYesNo, prompt, i18n("Authentication")) == 3);
05132 }
05133
05134 void HTTPProtocol::promptInfo( AuthInfo& info )
05135 {
05136 if ( m_responseCode == 401 )
05137 {
05138 info.url = m_request.url;
05139 if ( !m_state.user.isEmpty() )
05140 info.username = m_state.user;
05141 info.readOnly = !m_request.url.user().isEmpty();
05142 info.prompt = i18n( "You need to supply a username and a "
05143 "password to access this site." );
05144 info.keepPassword = true;
05145 if ( !m_strRealm.isEmpty() )
05146 {
05147 info.realmValue = m_strRealm;
05148 info.verifyPath = false;
05149 info.digestInfo = m_strAuthorization;
05150 info.commentLabel = i18n( "Site:" );
05151 info.comment = i18n("<b>%1</b> at <b>%2</b>").arg( htmlEscape(m_strRealm) ).arg( m_request.hostname );
05152 }
05153 }
05154 else if ( m_responseCode == 407 )
05155 {
05156 info.url = m_proxyURL;
05157 info.username = m_proxyURL.user();
05158 info.prompt = i18n( "You need to supply a username and a password for "
05159 "the proxy server listed below before you are allowed "
05160 "to access any sites." );
05161 info.keepPassword = true;
05162 if ( !m_strProxyRealm.isEmpty() )
05163 {
05164 info.realmValue = m_strProxyRealm;
05165 info.verifyPath = false;
05166 info.digestInfo = m_strProxyAuthorization;
05167 info.commentLabel = i18n( "Proxy:" );
05168 info.comment = i18n("<b>%1</b> at <b>%2</b>").arg( htmlEscape(m_strProxyRealm) ).arg( m_proxyURL.host() );
05169 }
05170 }
05171 }
05172
05173 bool HTTPProtocol::getAuthorization()
05174 {
05175 AuthInfo info;
05176 bool result = false;
05177
05178 kdDebug (7113) << "(" << m_pid << ") HTTPProtocol::getAuthorization: "
05179 << "Current Response: " << m_responseCode << ", "
05180 << "Previous Response: " << m_prevResponseCode << ", "
05181 << "Authentication: " << Authentication << ", "
05182 << "ProxyAuthentication: " << ProxyAuthentication << endl;
05183
05184 if (m_request.bNoAuth)
05185 {
05186 if (m_request.bErrorPage)
05187 errorPage();
05188 else
05189 error( ERR_COULD_NOT_LOGIN, i18n("Authentication needed for %1 but authentication is disabled.").arg(m_request.hostname));
05190 return false;
05191 }
05192
05193 bool repeatFailure = (m_prevResponseCode == m_responseCode);
05194
05195 QString errorMsg;
05196
05197 if (repeatFailure)
05198 {
05199 bool prompt = true;
05200 if ( Authentication == AUTH_Digest || ProxyAuthentication == AUTH_Digest )
05201 {
05202 bool isStaleNonce = false;
05203 QString auth = ( m_responseCode == 401 ) ? m_strAuthorization : m_strProxyAuthorization;
05204 int pos = auth.find("stale", 0, false);
05205 if ( pos != -1 )
05206 {
05207 pos += 5;
05208 int len = auth.length();
05209 while( pos < len && (auth[pos] == ' ' || auth[pos] == '=') ) pos++;
05210 if ( pos < len && auth.find("true", pos, false) != -1 )
05211 {
05212 isStaleNonce = true;
05213 kdDebug(7113) << "(" << m_pid << ") Stale nonce value. "
05214 << "Will retry using same info..." << endl;
05215 }
05216 }
05217 if ( isStaleNonce )
05218 {
05219 prompt = false;
05220 result = true;
05221 if ( m_responseCode == 401 )
05222 {
05223 info.username = m_request.user;
05224 info.password = m_request.passwd;
05225 info.realmValue = m_strRealm;
05226 info.digestInfo = m_strAuthorization;
05227 }
05228 else if ( m_responseCode == 407 )
05229 {
05230 info.username = m_proxyURL.user();
05231 info.password = m_proxyURL.pass();
05232 info.realmValue = m_strProxyRealm;
05233 info.digestInfo = m_strProxyAuthorization;
05234 }
05235 }
05236 }
05237
05238 if ( Authentication == AUTH_NTLM || ProxyAuthentication == AUTH_NTLM )
05239 {
05240 QString auth = ( m_responseCode == 401 ) ? m_strAuthorization : m_strProxyAuthorization;
05241 kdDebug(7113) << "auth: " << auth << endl;
05242 if ( auth.length() > 4 )
05243 {
05244 prompt = false;
05245 result = true;
05246 kdDebug(7113) << "(" << m_pid << ") NTLM auth second phase, "
05247 << "sending response..." << endl;
05248 if ( m_responseCode == 401 )
05249 {
05250 info.username = m_request.user;
05251 info.password = m_request.passwd;
05252 info.realmValue = m_strRealm;
05253 info.digestInfo = m_strAuthorization;
05254 }
05255 else if ( m_responseCode == 407 )
05256 {
05257 info.username = m_proxyURL.user();
05258 info.password = m_proxyURL.pass();
05259 info.realmValue = m_strProxyRealm;
05260 info.digestInfo = m_strProxyAuthorization;
05261 }
05262 }
05263 }
05264
05265 if ( prompt )
05266 {
05267 switch ( m_responseCode )
05268 {
05269 case 401:
05270 errorMsg = i18n("Authentication Failed.");
05271 break;
05272 case 407:
05273 errorMsg = i18n("Proxy Authentication Failed.");
05274 break;
05275 default:
05276 break;
05277 }
05278 }
05279 }
05280 else
05281 {
05282
05283
05284
05285
05286
05287 if (m_bProxyAuthValid)
05288 {
05289
05290 m_bProxyAuthValid = false;
05291 KURL proxy ( config()->readEntry("UseProxy") );
05292 m_proxyURL.setUser(proxy.user());
05293 m_proxyURL.setPass(proxy.pass());
05294 }
05295
05296 info.verifyPath = false;
05297 if ( m_responseCode == 407 )
05298 {
05299 info.url = m_proxyURL;
05300 info.username = m_proxyURL.user();
05301 info.password = m_proxyURL.pass();
05302 info.realmValue = m_strProxyRealm;
05303 info.digestInfo = m_strProxyAuthorization;
05304 }
05305 else
05306 {
05307 info.url = m_request.url;
05308 info.username = m_request.user;
05309 info.password = m_request.passwd;
05310 info.realmValue = m_strRealm;
05311 info.digestInfo = m_strAuthorization;
05312 }
05313
05314
05315
05316 if ( info.username.isNull() ||
05317 info.password.isNull() )
05318 result = checkCachedAuthentication( info );
05319
05320 if ( Authentication == AUTH_Digest )
05321 {
05322 QString auth;
05323
05324 if (m_responseCode == 401)
05325 auth = m_strAuthorization;
05326 else
05327 auth = m_strProxyAuthorization;
05328
05329 int pos = auth.find("stale", 0, false);
05330 if ( pos != -1 )
05331 {
05332 pos += 5;
05333 int len = auth.length();
05334 while( pos < len && (auth[pos] == ' ' || auth[pos] == '=') ) pos++;
05335 if ( pos < len && auth.find("true", pos, false) != -1 )
05336 {
05337 info.digestInfo = (m_responseCode == 401) ? m_strAuthorization : m_strProxyAuthorization;
05338 kdDebug(7113) << "(" << m_pid << ") Just a stale nonce value! "
05339 << "Retrying using the new nonce sent..." << endl;
05340 }
05341 }
05342 }
05343 }
05344
05345 if (!result )
05346 {
05347
05348
05349
05350 if ( !repeatFailure &&
05351 !info.username.isNull() &&
05352 !info.password.isNull() )
05353 result = true;
05354 else
05355 {
05356 if (Authentication == AUTH_Negotiate)
05357 {
05358 if (!repeatFailure)
05359 result = true;
05360 }
05361 else if ( m_request.disablePassDlg == false )
05362 {
05363 kdDebug( 7113 ) << "(" << m_pid << ") Prompting the user for authorization..." << endl;
05364 promptInfo( info );
05365 result = openPassDlg( info, errorMsg );
05366 }
05367 }
05368 }
05369
05370 if ( result )
05371 {
05372 switch (m_responseCode)
05373 {
05374 case 401:
05375 m_request.user = info.username;
05376 m_request.passwd = info.password;
05377 m_strRealm = info.realmValue;
05378 m_strAuthorization = info.digestInfo;
05379 break;
05380 case 407:
05381 m_proxyURL.setUser( info.username );
05382 m_proxyURL.setPass( info.password );
05383 m_strProxyRealm = info.realmValue;
05384 m_strProxyAuthorization = info.digestInfo;
05385 break;
05386 default:
05387 break;
05388 }
05389 return true;
05390 }
05391
05392 if (m_request.bErrorPage)
05393 errorPage();
05394 else
05395 error( ERR_USER_CANCELED, QString::null );
05396 return false;
05397 }
05398
05399 void HTTPProtocol::saveAuthorization()
05400 {
05401 AuthInfo info;
05402 if ( m_prevResponseCode == 407 )
05403 {
05404 if (!m_bUseProxy)
05405 return;
05406 m_bProxyAuthValid = true;
05407 info.url = m_proxyURL;
05408 info.username = m_proxyURL.user();
05409 info.password = m_proxyURL.pass();
05410 info.realmValue = m_strProxyRealm;
05411 info.digestInfo = m_strProxyAuthorization;
05412 cacheAuthentication( info );
05413 }
05414 else
05415 {
05416 info.url = m_request.url;
05417 info.username = m_request.user;
05418 info.password = m_request.passwd;
05419 info.realmValue = m_strRealm;
05420 info.digestInfo = m_strAuthorization;
05421 cacheAuthentication( info );
05422 }
05423 }
05424
05425 #ifdef HAVE_LIBGSSAPI
05426 QCString HTTPProtocol::gssError( int major_status, int minor_status )
05427 {
05428 OM_uint32 new_status;
05429 OM_uint32 msg_ctx = 0;
05430 gss_buffer_desc major_string;
05431 gss_buffer_desc minor_string;
05432 OM_uint32 ret;
05433 QCString errorstr;
05434
05435 errorstr = "";
05436
05437 do {
05438 ret = gss_display_status(&new_status, major_status, GSS_C_GSS_CODE, GSS_C_NULL_OID, &msg_ctx, &major_string);
05439 errorstr += (const char *)major_string.value;
05440 errorstr += " ";
05441 ret = gss_display_status(&new_status, minor_status, GSS_C_MECH_CODE, GSS_C_NULL_OID, &msg_ctx, &minor_string);
05442 errorstr += (const char *)minor_string.value;
05443 errorstr += " ";
05444 } while (!GSS_ERROR(ret) && msg_ctx != 0);
05445
05446 return errorstr;
05447 }
05448
05449 QString HTTPProtocol::createNegotiateAuth()
05450 {
05451 QString auth;
05452 QCString servicename;
05453 QByteArray input;
05454 OM_uint32 major_status, minor_status;
05455 OM_uint32 req_flags = 0;
05456 gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER;
05457 gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER;
05458 gss_name_t server;
05459 gss_ctx_id_t ctx;
05460 gss_OID mech_oid;
05461 static gss_OID_desc krb5_oid_desc = {9, (void *) "\x2a\x86\x48\x86\xf7\x12\x01\x02\x02"};
05462 static gss_OID_desc spnego_oid_desc = {6, (void *) "\x2b\x06\x01\x05\x05\x02"};
05463 int found = 0;
05464 unsigned int i;
05465 gss_OID_set mech_set;
05466 gss_OID tmp_oid;
05467
05468 ctx = GSS_C_NO_CONTEXT;
05469 mech_oid = &krb5_oid_desc;
05470
05471
05472 major_status = gss_indicate_mechs(&minor_status, &mech_set);
05473 if (GSS_ERROR(major_status)) {
05474 kdDebug(7113) << "(" << m_pid << ") gss_indicate_mechs failed: " << gssError(major_status, minor_status) << endl;
05475 } else {
05476 for (i=0; i<mech_set->count && !found; i++) {
05477 tmp_oid = &mech_set->elements[i];
05478 if (tmp_oid->length == spnego_oid_desc.length &&
05479 !memcmp(tmp_oid->elements, spnego_oid_desc.elements, tmp_oid->length)) {
05480 kdDebug(7113) << "(" << m_pid << ") createNegotiateAuth: found SPNEGO mech" << endl;
05481 found = 1;
05482 mech_oid = &spnego_oid_desc;
05483 break;
05484 }
05485 }
05486 gss_release_oid_set(&minor_status, &mech_set);
05487 }
05488
05489
05490 servicename = "HTTP@";
05491 servicename += m_state.hostname.ascii();
05492
05493 input_token.value = (void *)servicename.data();
05494 input_token.length = servicename.length() + 1;
05495
05496 major_status = gss_import_name(&minor_status, &input_token,
05497 GSS_C_NT_HOSTBASED_SERVICE, &server);
05498
05499 input_token.value = NULL;
05500 input_token.length = 0;
05501
05502 if (GSS_ERROR(major_status)) {
05503 kdDebug(7113) << "(" << m_pid << ") gss_import_name failed: " << gssError(major_status, minor_status) << endl;
05504
05505 m_strAuthorization = QString::null;
05506 return QString::null;
05507 }
05508
05509 major_status = gss_init_sec_context(&minor_status, GSS_C_NO_CREDENTIAL,
05510 &ctx, server, mech_oid,
05511 req_flags, GSS_C_INDEFINITE,
05512 GSS_C_NO_CHANNEL_BINDINGS,
05513 GSS_C_NO_BUFFER, NULL, &output_token,
05514 NULL, NULL);
05515
05516
05517 if (GSS_ERROR(major_status) || (output_token.length == 0)) {
05518 kdDebug(7113) << "(" << m_pid << ") gss_init_sec_context failed: " << gssError(major_status, minor_status) << endl;
05519 gss_release_name(&minor_status, &server);
05520 if (ctx != GSS_C_NO_CONTEXT) {
05521 gss_delete_sec_context(&minor_status, &ctx, GSS_C_NO_BUFFER);
05522 ctx = GSS_C_NO_CONTEXT;
05523 }
05524
05525 m_strAuthorization = QString::null;
05526 return QString::null;
05527 }
05528
05529 input.duplicate((const char *)output_token.value, output_token.length);
05530 auth = "Authorization: Negotiate ";
05531 auth += KCodecs::base64Encode( input );
05532 auth += "\r\n";
05533
05534
05535 gss_release_name(&minor_status, &server);
05536 if (ctx != GSS_C_NO_CONTEXT) {
05537 gss_delete_sec_context(&minor_status, &ctx, GSS_C_NO_BUFFER);
05538 ctx = GSS_C_NO_CONTEXT;
05539 }
05540 gss_release_buffer(&minor_status, &output_token);
05541
05542 return auth;
05543 }
05544 #else
05545
05546
05547 QCString HTTPProtocol::gssError( int, int )
05548 {
05549 return "";
05550 }
05551
05552
05553 QString HTTPProtocol::createNegotiateAuth()
05554 {
05555 return QString::null;
05556 }
05557 #endif
05558
05559 QString HTTPProtocol::createNTLMAuth( bool isForProxy )
05560 {
05561 uint len;
05562 QString auth, user, domain, passwd;
05563 QCString strauth;
05564 QByteArray buf;
05565
05566 if ( isForProxy )
05567 {
05568 auth = "Proxy-Connection: Keep-Alive\r\n";
05569 auth += "Proxy-Authorization: NTLM ";
05570 user = m_proxyURL.user();
05571 passwd = m_proxyURL.pass();
05572 strauth = m_strProxyAuthorization.latin1();
05573 len = m_strProxyAuthorization.length();
05574 }
05575 else
05576 {
05577 auth = "Authorization: NTLM ";
05578 user = m_state.user;
05579 passwd = m_state.passwd;
05580 strauth = m_strAuthorization.latin1();
05581 len = m_strAuthorization.length();
05582 }
05583 if ( user.contains('\\') ) {
05584 domain = user.section( '\\', 0, 0);
05585 user = user.section( '\\', 1 );
05586 }
05587
05588 kdDebug(7113) << "(" << m_pid << ") NTLM length: " << len << endl;
05589 if ( user.isEmpty() || passwd.isEmpty() || len < 4 )
05590 return QString::null;
05591
05592 if ( len > 4 )
05593 {
05594
05595 QByteArray challenge;
05596 KCodecs::base64Decode( strauth.right( len - 5 ), challenge );
05597 KNTLM::getAuth( buf, challenge, user, passwd, domain,
05598 KNetwork::KResolver::localHostName(), false, false );
05599 }
05600 else
05601 {
05602 KNTLM::getNegotiate( buf );
05603 }
05604
05605
05606 if ( isForProxy )
05607 m_strProxyAuthorization = "NTLM";
05608 else
05609 m_strAuthorization = "NTLM";
05610
05611 auth += KCodecs::base64Encode( buf );
05612 auth += "\r\n";
05613
05614 return auth;
05615 }
05616
05617 QString HTTPProtocol::createBasicAuth( bool isForProxy )
05618 {
05619 QString auth;
05620 QCString user, passwd;
05621 if ( isForProxy )
05622 {
05623 auth = "Proxy-Authorization: Basic ";
05624 user = m_proxyURL.user().latin1();
05625 passwd = m_proxyURL.pass().latin1();
05626 }
05627 else
05628 {
05629 auth = "Authorization: Basic ";
05630 user = m_state.user.latin1();
05631 passwd = m_state.passwd.latin1();
05632 }
05633
05634 if ( user.isEmpty() )
05635 user = "";
05636 if ( passwd.isEmpty() )
05637 passwd = "";
05638
05639 user += ':';
05640 user += passwd;
05641 auth += KCodecs::base64Encode( user );
05642 auth += "\r\n";
05643
05644 return auth;
05645 }
05646
05647 void HTTPProtocol::calculateResponse( DigestAuthInfo& info, QCString& Response )
05648 {
05649 KMD5 md;
05650 QCString HA1;
05651 QCString HA2;
05652
05653
05654 QCString authStr = info.username;
05655 authStr += ':';
05656 authStr += info.realm;
05657 authStr += ':';
05658 authStr += info.password;
05659 md.update( authStr );
05660
05661 if ( info.algorithm.lower() == "md5-sess" )
05662 {
05663 authStr = md.hexDigest();
05664 authStr += ':';
05665 authStr += info.nonce;
05666 authStr += ':';
05667 authStr += info.cnonce;
05668 md.reset();
05669 md.update( authStr );
05670 }
05671 HA1 = md.hexDigest();
05672
05673 kdDebug(7113) << "(" << m_pid << ") calculateResponse(): A1 => " << HA1 << endl;
05674
05675
05676 authStr = info.method;
05677 authStr += ':';
05678 authStr += m_request.url.encodedPathAndQuery(0, true).latin1();
05679 if ( info.qop == "auth-int" )
05680 {
05681 authStr += ':';
05682 authStr += info.entityBody;
05683 }
05684 md.reset();
05685 md.update( authStr );
05686 HA2 = md.hexDigest();
05687
05688 kdDebug(7113) << "(" << m_pid << ") calculateResponse(): A2 => "
05689 << HA2 << endl;
05690
05691
05692 authStr = HA1;
05693 authStr += ':';
05694 authStr += info.nonce;
05695 authStr += ':';
05696 if ( !info.qop.isEmpty() )
05697 {
05698 authStr += info.nc;
05699 authStr += ':';
05700 authStr += info.cnonce;
05701 authStr += ':';
05702 authStr += info.qop;
05703 authStr += ':';
05704 }
05705 authStr += HA2;
05706 md.reset();
05707 md.update( authStr );
05708 Response = md.hexDigest();
05709
05710 kdDebug(7113) << "(" << m_pid << ") calculateResponse(): Response => "
05711 << Response << endl;
05712 }
05713
05714 QString HTTPProtocol::createDigestAuth ( bool isForProxy )
05715 {
05716 const char *p;
05717
05718 QString auth;
05719 QCString opaque;
05720 QCString Response;
05721
05722 DigestAuthInfo info;
05723
05724 opaque = "";
05725 if ( isForProxy )
05726 {
05727 auth = "Proxy-Authorization: Digest ";
05728 info.username = m_proxyURL.user().latin1();
05729 info.password = m_proxyURL.pass().latin1();
05730 p = m_strProxyAuthorization.latin1();
05731 }
05732 else
05733 {
05734 auth = "Authorization: Digest ";
05735 info.username = m_state.user.latin1();
05736 info.password = m_state.passwd.latin1();
05737 p = m_strAuthorization.latin1();
05738 }
05739 if (!p || !*p)
05740 return QString::null;
05741
05742 p += 6;
05743
05744 if ( info.username.isEmpty() || info.password.isEmpty() || !p )
05745 return QString::null;
05746
05747
05748 info.realm = "";
05749 info.algorithm = "MD5";
05750 info.nonce = "";
05751 info.qop = "";
05752
05753
05754 info.cnonce = KApplication::randomString(16).latin1();
05755
05756
05757 info.nc = "00000001";
05758
05759
05760 switch ( m_request.method )
05761 {
05762 case HTTP_GET:
05763 info.method = "GET";
05764 break;
05765 case HTTP_PUT:
05766 info.method = "PUT";
05767 break;
05768 case HTTP_POST:
05769 info.method = "POST";
05770 break;
05771 case HTTP_HEAD:
05772 info.method = "HEAD";
05773 break;
05774 case HTTP_DELETE:
05775 info.method = "DELETE";
05776 break;
05777 case DAV_PROPFIND:
05778 info.method = "PROPFIND";
05779 break;
05780 case DAV_PROPPATCH:
05781 info.method = "PROPPATCH";
05782 break;
05783 case DAV_MKCOL:
05784 info.method = "MKCOL";
05785 break;
05786 case DAV_COPY:
05787 info.method = "COPY";
05788 break;
05789 case DAV_MOVE:
05790 info.method = "MOVE";
05791 break;
05792 case DAV_LOCK:
05793 info.method = "LOCK";
05794 break;
05795 case DAV_UNLOCK:
05796 info.method = "UNLOCK";
05797 break;
05798 case DAV_SEARCH:
05799 info.method = "SEARCH";
05800 break;
05801 case DAV_SUBSCRIBE:
05802 info.method = "SUBSCRIBE";
05803 break;
05804 case DAV_UNSUBSCRIBE:
05805 info.method = "UNSUBSCRIBE";
05806 break;
05807 case DAV_POLL:
05808 info.method = "POLL";
05809 break;
05810 default:
05811 error( ERR_UNSUPPORTED_ACTION, i18n("Unsupported method: authentication will fail. Please submit a bug report."));
05812 break;
05813 }
05814
05815
05816 while (*p)
05817 {
05818 int i = 0;
05819 while ( (*p == ' ') || (*p == ',') || (*p == '\t')) { p++; }
05820 if (strncasecmp(p, "realm=", 6 )==0)
05821 {
05822 p+=6;
05823 while ( *p == '"' ) p++;
05824 while ( p[i] != '"' ) i++;
05825 info.realm = QCString( p, i+1 );
05826 }
05827 else if (strncasecmp(p, "algorith=", 9)==0)
05828 {
05829 p+=9;
05830 while ( *p == '"' ) p++;
05831 while ( ( p[i] != '"' ) && ( p[i] != ',' ) && ( p[i] != '\0' ) ) i++;
05832 info.algorithm = QCString(p, i+1);
05833 }
05834 else if (strncasecmp(p, "algorithm=", 10)==0)
05835 {
05836 p+=10;
05837 while ( *p == '"' ) p++;
05838 while ( ( p[i] != '"' ) && ( p[i] != ',' ) && ( p[i] != '\0' ) ) i++;
05839 info.algorithm = QCString(p,i+1);
05840 }
05841 else if (strncasecmp(p, "domain=", 7)==0)
05842 {
05843 p+=7;
05844 while ( *p == '"' ) p++;
05845 while ( p[i] != '"' ) i++;
05846 int pos;
05847 int idx = 0;
05848 QCString uri = QCString(p,i+1);
05849 do
05850 {
05851 pos = uri.find( ' ', idx );
05852 if ( pos != -1 )
05853 {
05854 KURL u (m_request.url, uri.mid(idx, pos-idx));
05855 if (u.isValid ())
05856 info.digestURI.append( u.url().latin1() );
05857 }
05858 else
05859 {
05860 KURL u (m_request.url, uri.mid(idx, uri.length()-idx));
05861 if (u.isValid ())
05862 info.digestURI.append( u.url().latin1() );
05863 }
05864 idx = pos+1;
05865 } while ( pos != -1 );
05866 }
05867 else if (strncasecmp(p, "nonce=", 6)==0)
05868 {
05869 p+=6;
05870 while ( *p == '"' ) p++;
05871 while ( p[i] != '"' ) i++;
05872 info.nonce = QCString(p,i+1);
05873 }
05874 else if (strncasecmp(p, "opaque=", 7)==0)
05875 {
05876 p+=7;
05877 while ( *p == '"' ) p++;
05878 while ( p[i] != '"' ) i++;
05879 opaque = QCString(p,i+1);
05880 }
05881 else if (strncasecmp(p, "qop=", 4)==0)
05882 {
05883 p+=4;
05884 while ( *p == '"' ) p++;
05885 while ( p[i] != '"' ) i++;
05886 info.qop = QCString(p,i+1);
05887 }
05888 p+=(i+1);
05889 }
05890
05891 if (info.realm.isEmpty() || info.nonce.isEmpty())
05892 return QString::null;
05893
05894
05895
05896
05897 if (info.digestURI.isEmpty() && (m_responseCode == 401 || m_responseCode == 407))
05898 info.digestURI.append (m_request.url.url().latin1());
05899 else
05900 {
05901
05902
05903 bool send = true;
05904
05905
05906 QString requestPath = m_request.url.directory(false, false);
05907 if (requestPath.isEmpty())
05908 requestPath = "/";
05909
05910 int count = info.digestURI.count();
05911
05912 for (int i = 0; i < count; i++ )
05913 {
05914 KURL u ( info.digestURI.at(i) );
05915
05916 send &= (m_request.url.protocol().lower() == u.protocol().lower());
05917 send &= (m_request.hostname.lower() == u.host().lower());
05918
05919 if (m_request.port > 0 && u.port() > 0)
05920 send &= (m_request.port == u.port());
05921
05922 QString digestPath = u.directory (false, false);
05923 if (digestPath.isEmpty())
05924 digestPath = "/";
05925
05926 send &= (requestPath.startsWith(digestPath));
05927
05928 if (send)
05929 break;
05930 }
05931
05932 kdDebug(7113) << "(" << m_pid << ") createDigestAuth(): passed digest "
05933 "authentication credential test: " << send << endl;
05934
05935 if (!send)
05936 return QString::null;
05937 }
05938
05939 kdDebug(7113) << "(" << m_pid << ") RESULT OF PARSING:" << endl;
05940 kdDebug(7113) << "(" << m_pid << ") algorithm: " << info.algorithm << endl;
05941 kdDebug(7113) << "(" << m_pid << ") realm: " << info.realm << endl;
05942 kdDebug(7113) << "(" << m_pid << ") nonce: " << info.nonce << endl;
05943 kdDebug(7113) << "(" << m_pid << ") opaque: " << opaque << endl;
05944 kdDebug(7113) << "(" << m_pid << ") qop: " << info.qop << endl;
05945
05946
05947 calculateResponse( info, Response );
05948
05949 auth += "username=\"";
05950 auth += info.username;
05951
05952 auth += "\", realm=\"";
05953 auth += info.realm;
05954 auth += "\"";
05955
05956 auth += ", nonce=\"";
05957 auth += info.nonce;
05958
05959 auth += "\", uri=\"";
05960 auth += m_request.url.encodedPathAndQuery(0, true);
05961
05962 auth += "\", algorithm=\"";
05963 auth += info.algorithm;
05964 auth +="\"";
05965
05966 if ( !info.qop.isEmpty() )
05967 {
05968 auth += ", qop=\"";
05969 auth += info.qop;
05970 auth += "\", cnonce=\"";
05971 auth += info.cnonce;
05972 auth += "\", nc=";
05973 auth += info.nc;
05974 }
05975
05976 auth += ", response=\"";
05977 auth += Response;
05978 if ( !opaque.isEmpty() )
05979 {
05980 auth += "\", opaque=\"";
05981 auth += opaque;
05982 }
05983 auth += "\"\r\n";
05984
05985 return auth;
05986 }
05987
05988 QString HTTPProtocol::proxyAuthenticationHeader()
05989 {
05990 QString header;
05991
05992
05993
05994
05995 if ( m_strProxyRealm.isEmpty() )
05996 {
05997 AuthInfo info;
05998 info.url = m_proxyURL;
05999 info.username = m_proxyURL.user();
06000 info.password = m_proxyURL.pass();
06001 info.verifyPath = true;
06002
06003
06004
06005
06006 if ( !info.username.isNull() && !info.password.isNull() )
06007 {
06008 if( m_strProxyAuthorization.isEmpty() )
06009 ProxyAuthentication = AUTH_None;
06010 else if( m_strProxyAuthorization.startsWith("Basic") )
06011 ProxyAuthentication = AUTH_Basic;
06012 else if( m_strProxyAuthorization.startsWith("NTLM") )
06013 ProxyAuthentication = AUTH_NTLM;
06014 else
06015 ProxyAuthentication = AUTH_Digest;
06016 }
06017 else
06018 {
06019 if ( checkCachedAuthentication(info) && !info.digestInfo.isEmpty() )
06020 {
06021 m_proxyURL.setUser( info.username );
06022 m_proxyURL.setPass( info.password );
06023 m_strProxyRealm = info.realmValue;
06024 m_strProxyAuthorization = info.digestInfo;
06025 if( m_strProxyAuthorization.startsWith("Basic") )
06026 ProxyAuthentication = AUTH_Basic;
06027 else if( m_strProxyAuthorization.startsWith("NTLM") )
06028 ProxyAuthentication = AUTH_NTLM;
06029 else
06030 ProxyAuthentication = AUTH_Digest;
06031 }
06032 else
06033 {
06034 ProxyAuthentication = AUTH_None;
06035 }
06036 }
06037 }
06038
06039
06040 if ( ProxyAuthentication != AUTH_None )
06041 {
06042 kdDebug(7113) << "(" << m_pid << ") Using Proxy Authentication: " << endl;
06043 kdDebug(7113) << "(" << m_pid << ") HOST= " << m_proxyURL.host() << endl;
06044 kdDebug(7113) << "(" << m_pid << ") PORT= " << m_proxyURL.port() << endl;
06045 kdDebug(7113) << "(" << m_pid << ") USER= " << m_proxyURL.user() << endl;
06046 kdDebug(7113) << "(" << m_pid << ") PASSWORD= [protected]" << endl;
06047 kdDebug(7113) << "(" << m_pid << ") REALM= " << m_strProxyRealm << endl;
06048 kdDebug(7113) << "(" << m_pid << ") EXTRA= " << m_strProxyAuthorization << endl;
06049 }
06050
06051 switch ( ProxyAuthentication )
06052 {
06053 case AUTH_Basic:
06054 header += createBasicAuth( true );
06055 break;
06056 case AUTH_Digest:
06057 header += createDigestAuth( true );
06058 break;
06059 case AUTH_NTLM:
06060 if ( m_bFirstRequest ) header += createNTLMAuth( true );
06061 break;
06062 case AUTH_None:
06063 default:
06064 break;
06065 }
06066
06067 return header;
06068 }
06069
06070 #include "http.moc"