Imported Upstream version 17.11.3
[platform/upstream/libzypp.git] / zypp / media / MediaCurl.cc
index b54ffd4..0427191 100644 (file)
@@ -21,7 +21,6 @@
 #include "zypp/base/Gettext.h"
 
 #include "zypp/media/MediaCurl.h"
-#include "zypp/media/proxyinfo/ProxyInfos.h"
 #include "zypp/media/ProxyInfo.h"
 #include "zypp/media/MediaUserAuth.h"
 #include "zypp/media/CredentialManager.h"
@@ -29,6 +28,7 @@
 #include "zypp/thread/Once.h"
 #include "zypp/Target.h"
 #include "zypp/ZYppFactory.h"
+#include "zypp/ZConfig.h"
 
 #include <cstdlib>
 #include <sys/types.h>
 #include <errno.h>
 #include <dirent.h>
 #include <unistd.h>
-#include <boost/format.hpp>
 
 #define  DETECT_DIR_INDEX       0
 #define  CONNECT_TIMEOUT        60
-#define  TRANSFER_TIMEOUT       60 * 3
 #define  TRANSFER_TIMEOUT_MAX   60 * 60
 
+#define EXPLICITLY_NO_PROXY "_none_"
+
+#undef CURLVERSION_AT_LEAST
+#define CURLVERSION_AT_LEAST(M,N,O) LIBCURL_VERSION_NUM >= ((((M)<<8)+(N))<<8)+(O)
 
 using namespace std;
 using namespace zypp::base;
@@ -112,13 +114,11 @@ namespace
     return 0;
   }
 
-  static size_t
-  log_redirects_curl(
-      void *ptr, size_t size, size_t nmemb, void *stream)
+  static size_t log_redirects_curl( char *ptr, size_t size, size_t nmemb, void *userdata)
   {
-    // INT << "got header: " << string((char *)ptr, ((char*)ptr) + size*nmemb) << endl;
+    // INT << "got header: " << string(ptr, ptr + size*nmemb) << endl;
 
-    char * lstart = (char *)ptr, * lend = (char *)ptr;
+    char * lstart = ptr, * lend = ptr;
     size_t pos = 0;
     size_t max = size * nmemb;
     while (pos + 1 < max)
@@ -127,10 +127,21 @@ namespace
       for (lstart = lend; *lend != '\n' && pos < max; ++lend, ++pos);
 
       // look for "Location"
-      string line(lstart, lend);
-      if (line.find("Location") != string::npos)
+      if ( lstart[0] == 'L'
+       && lstart[1] == 'o'
+       && lstart[2] == 'c'
+       && lstart[3] == 'a'
+       && lstart[4] == 't'
+       && lstart[5] == 'i'
+       && lstart[6] == 'o'
+       && lstart[7] == 'n'
+       && lstart[8] == ':' )
       {
+       std::string line { lstart, *(lend-1)=='\r' ? lend-1 : lend };
         DBG << "redirecting to " << line << endl;
+       if ( userdata ) {
+         *reinterpret_cast<std::string *>( userdata ) = line;
+       }
         return max;
       }
 
@@ -149,28 +160,133 @@ namespace
 }
 
 namespace zypp {
+
+  ///////////////////////////////////////////////////////////////////
+  namespace env
+  {
+    namespace
+    {
+      inline int getZYPP_MEDIA_CURL_IPRESOLVE()
+      {
+       int ret = 0;
+       if ( const char * envp = getenv( "ZYPP_MEDIA_CURL_IPRESOLVE" ) )
+       {
+         WAR << "env set: $ZYPP_MEDIA_CURL_IPRESOLVE='" << envp << "'" << endl;
+         if (      strcmp( envp, "4" ) == 0 )  ret = 4;
+         else if ( strcmp( envp, "6" ) == 0 )  ret = 6;
+       }
+       return ret;
+      }
+    }
+
+    inline int ZYPP_MEDIA_CURL_IPRESOLVE()
+    {
+      static int _v = getZYPP_MEDIA_CURL_IPRESOLVE();
+      return _v;
+    }
+  } // namespace env
+  ///////////////////////////////////////////////////////////////////
+
   namespace media {
 
   namespace {
     struct ProgressData
     {
-      ProgressData(const long _timeout, const zypp::Url &_url = zypp::Url(),
-                   callback::SendReport<DownloadProgressReport> *_report=NULL)
-        : timeout(_timeout)
-        , reached(false)
-        , report(_report)
-        , drate_period(-1)
-        , dload_period(0)
-        , secs(0)
-        , drate_avg(-1)
-        , ltime( time(NULL))
-        , dload( 0)
-        , uload( 0)
-        , url(_url)
+      ProgressData( CURL *_curl, time_t _timeout = 0, const Url & _url = Url(),
+                    ByteCount expectedFileSize_r = 0,
+                   callback::SendReport<DownloadProgressReport> *_report = nullptr )
+        : curl( _curl )
+       , url( _url )
+       , timeout( _timeout )
+        , reached( false )
+        , fileSizeExceeded ( false )
+        , report( _report )
+        , _expectedFileSize( expectedFileSize_r )
       {}
-      long                                          timeout;
-      bool                                          reached;
+
+      CURL     *curl;
+      Url      url;
+      time_t   timeout;
+      bool     reached;
+      bool      fileSizeExceeded;
       callback::SendReport<DownloadProgressReport> *report;
+      ByteCount _expectedFileSize;
+
+      time_t _timeStart        = 0;    ///< Start total stats
+      time_t _timeLast = 0;    ///< Start last period(~1sec)
+      time_t _timeRcv  = 0;    ///< Start of no-data timeout
+      time_t _timeNow  = 0;    ///< Now
+
+      double _dnlTotal = 0.0;  ///< Bytes to download or 0 if unknown
+      double _dnlLast  = 0.0;  ///< Bytes downloaded at period start
+      double _dnlNow   = 0.0;  ///< Bytes downloaded now
+
+      int    _dnlPercent= 0;   ///< Percent completed or 0 if _dnlTotal is unknown
+
+      double _drateTotal= 0.0; ///< Download rate so far
+      double _drateLast        = 0.0;  ///< Download rate in last period
+
+      void updateStats( double dltotal = 0.0, double dlnow = 0.0 )
+      {
+       time_t now = _timeNow = time(0);
+
+       // If called without args (0.0), recompute based on the last values seen
+       if ( dltotal && dltotal != _dnlTotal )
+         _dnlTotal = dltotal;
+
+       if ( dlnow && dlnow != _dnlNow )
+       {
+         _timeRcv = now;
+         _dnlNow = dlnow;
+       }
+       else if ( !_dnlNow && !_dnlTotal )
+       {
+         // Start time counting as soon as first data arrives.
+         // Skip the connection / redirection time at begin.
+         return;
+       }
+
+       // init or reset if time jumps back
+       if ( !_timeStart || _timeStart > now )
+         _timeStart = _timeLast = _timeRcv = now;
+
+       // timeout condition
+       if ( timeout )
+         reached = ( (now - _timeRcv) > timeout );
+
+        // check if the downloaded data is already bigger than what we expected
+       fileSizeExceeded = _expectedFileSize > 0 && _expectedFileSize < static_cast<ByteCount::SizeType>(_dnlNow);
+
+       // percentage:
+       if ( _dnlTotal )
+         _dnlPercent = int(_dnlNow * 100 / _dnlTotal);
+
+       // download rates:
+       _drateTotal = _dnlNow / std::max( int(now - _timeStart), 1 );
+
+       if ( _timeLast < now )
+       {
+         _drateLast = (_dnlNow - _dnlLast) / int(now - _timeLast);
+         // start new period
+         _timeLast  = now;
+         _dnlLast   = _dnlNow;
+       }
+       else if ( _timeStart == _timeLast )
+         _drateLast = _drateTotal;
+      }
+
+      int reportProgress() const
+      {
+        if ( fileSizeExceeded )
+          return 1;
+       if ( reached )
+         return 1;     // no-data timeout
+       if ( report && !(*report)->progress( _dnlPercent, url, _drateTotal, _drateLast ) )
+         return 1;     // user requested abort
+       return 0;
+      }
+
+
       // download rate of the last period (cca 1 sec)
       double                                        drate_period;
       // bytes downloaded at the start of the last period
@@ -185,7 +301,6 @@ namespace zypp {
       double                                        dload;
       // bytes uploaded at the moment the progress was last reported
       double                                        uload;
-      zypp::Url                                     url;
     };
 
     ///////////////////////////////////////////////////////////////////
@@ -235,7 +350,7 @@ void fillSettingsFromUrl( const Url &url, TransferSettings &s )
     else
     {
         // if there is no username, set anonymous auth
-        if ( url.getScheme() == "ftp" && s.username().empty() )
+        if ( ( url.getScheme() == "ftp" || url.getScheme() == "tftp" ) && s.username().empty() )
             s.setAnonymousAuth();
     }
 
@@ -273,25 +388,80 @@ void fillSettingsFromUrl( const Url &url, TransferSettings &s )
         }
     }
 
-    Pathname ca_path = Pathname(url.getQueryParam("ssl_capath")).asString();
+    Pathname ca_path( url.getQueryParam("ssl_capath") );
     if( ! ca_path.empty())
     {
-        if( !PathInfo(ca_path).isDir() || !Pathname(ca_path).absolute())
+        if( !PathInfo(ca_path).isDir() || ! ca_path.absolute())
             ZYPP_THROW(MediaBadUrlException(url, "Invalid ssl_capath path"));
         else
             s.setCertificateAuthoritiesPath(ca_path);
     }
 
-    string proxy = url.getQueryParam( "proxy" );
-    if ( ! proxy.empty() )
+    Pathname client_cert( url.getQueryParam("ssl_clientcert") );
+    if( ! client_cert.empty())
+    {
+        if( !PathInfo(client_cert).isFile() || !client_cert.absolute())
+            ZYPP_THROW(MediaBadUrlException(url, "Invalid ssl_clientcert file"));
+        else
+            s.setClientCertificatePath(client_cert);
+    }
+    Pathname client_key( url.getQueryParam("ssl_clientkey") );
+    if( ! client_key.empty())
+    {
+        if( !PathInfo(client_key).isFile() || !client_key.absolute())
+            ZYPP_THROW(MediaBadUrlException(url, "Invalid ssl_clientkey file"));
+        else
+            s.setClientKeyPath(client_key);
+    }
+
+    param = url.getQueryParam( "proxy" );
+    if ( ! param.empty() )
+    {
+        if ( param == EXPLICITLY_NO_PROXY ) {
+           // Workaround TransferSettings shortcoming: With an
+           // empty proxy string, code will continue to look for
+           // valid proxy settings. So set proxy to some non-empty
+           // string, to indicate it has been explicitly disabled.
+           s.setProxy(EXPLICITLY_NO_PROXY);
+            s.setProxyEnabled(false);
+        }
+        else {
+            string proxyport( url.getQueryParam( "proxyport" ) );
+            if ( ! proxyport.empty() ) {
+                param += ":" + proxyport;
+            }
+            s.setProxy(param);
+            s.setProxyEnabled(true);
+        }
+    }
+
+    param = url.getQueryParam( "proxyuser" );
+    if ( ! param.empty() )
+    {
+      s.setProxyUsername(param);
+      s.setProxyPassword(url.getQueryParam( "proxypass" ));
+    }
+
+    // HTTP authentication type
+    param = url.getQueryParam("auth");
+    if (!param.empty() && (url.getScheme() == "http" || url.getScheme() == "https"))
     {
-        string proxyport( url.getQueryParam( "proxyport" ) );
-        if ( ! proxyport.empty() ) {
-            proxy += ":" + proxyport;
+        try
+        {
+           CurlAuthData::auth_type_str2long(param);    // check if we know it
         }
-        s.setProxy(proxy);
-        s.setProxyEnabled(true);
+        catch (MediaException & ex_r)
+       {
+           DBG << "Rethrowing as MediaUnauthorizedException.";
+           ZYPP_THROW(MediaUnauthorizedException(url, ex_r.msg(), "", ""));
+       }
+        s.setAuthType(param);
     }
+
+    // workarounds
+    param = url.getQueryParam("head_requests");
+    if( !param.empty() && param == "no" )
+        s.setHeadRequestsAllowed(false);
 }
 
 /**
@@ -300,46 +470,23 @@ void fillSettingsFromUrl( const Url &url, TransferSettings &s )
  */
 void fillSettingsSystemProxy( const Url&url, TransferSettings &s )
 {
-    ProxyInfo proxy_info (ProxyInfo::ImplPtr(new ProxyInfoSysconfig("proxy")));
-
-    if ( proxy_info.enabled())
+    ProxyInfo proxy_info;
+    if ( proxy_info.useProxyFor( url ) )
     {
-      s.setProxyEnabled(true);
-      std::list<std::string> nope = proxy_info.noProxy();
-      for (ProxyInfo::NoProxyIterator it = proxy_info.noProxyBegin();
-           it != proxy_info.noProxyEnd();
-           it++)
-      {
-        std::string host( str::toLower(url.getHost()));
-        std::string temp( str::toLower(*it));
-
-        // no proxy if it points to a suffix
-        // preceeded by a '.', that maches
-        // the trailing portion of the host.
-        if( temp.size() > 1 && temp.at(0) == '.')
-        {
-          if(host.size() > temp.size() &&
-             host.compare(host.size() - temp.size(), temp.size(), temp) == 0)
-          {
-            DBG << "NO_PROXY: '" << *it  << "' matches host '"
-                                 << host << "'" << endl;
-            s.setProxyEnabled(false);
-            break;
-          }
-        }
-        else
-        // no proxy if we have an exact match
-        if( host == temp)
-        {
-          DBG << "NO_PROXY: '" << *it  << "' matches host '"
-                               << host << "'" << endl;
-          s.setProxyEnabled(false);
-          break;
-        }
+      // We must extract any 'user:pass' from the proxy url
+      // otherwise they won't make it into curl (.curlrc wins).
+      try {
+       Url u( proxy_info.proxy( url ) );
+       s.setProxy( u.asString( url::ViewOption::WITH_SCHEME + url::ViewOption::WITH_HOST + url::ViewOption::WITH_PORT ) );
+       // don't overwrite explicit auth settings
+       if ( s.proxyUsername().empty() )
+       {
+         s.setProxyUsername( u.getUsername( url::E_ENCODED ) );
+         s.setProxyPassword( u.getPassword( url::E_ENCODED ) );
+       }
+       s.setProxyEnabled( true );
       }
-
-      if ( s.proxyEnabled() )
-          s.setProxy(proxy_info.proxy(url.getScheme()));
+      catch (...) {}   // no proxy if URL is malformed
     }
 }
 
@@ -354,13 +501,11 @@ static const char *const anonymousIdHeader()
   // we need to add the release and identifier to the
   // agent string.
   // The target could be not initialized, and then this information
-  // is not available.
-  Target_Ptr target = zypp::getZYpp()->getTarget();
-
+  // is guessed.
   static const std::string _value(
       str::trim( str::form(
           "X-ZYpp-AnonymousId: %s",
-          target ? target->anonymousUniqueId().c_str() : "" ) )
+          Target::anonymousUniqueId( Pathname()/*guess root*/ ).c_str() ) )
   );
   return _value.c_str();
 }
@@ -374,13 +519,11 @@ static const char *const distributionFlavorHeader()
   // we need to add the release and identifier to the
   // agent string.
   // The target could be not initialized, and then this information
-  // is not available.
-  Target_Ptr target = zypp::getZYpp()->getTarget();
-
+  // is guessed.
   static const std::string _value(
       str::trim( str::form(
           "X-ZYpp-DistributionFlavor: %s",
-          target ? target->distributionFlavor().c_str() : "" ) )
+          Target::distributionFlavor( Pathname()/*guess root*/ ).c_str() ) )
   );
   return _value.c_str();
 }
@@ -394,15 +537,13 @@ static const char *const agentString()
   // we need to add the release and identifier to the
   // agent string.
   // The target could be not initialized, and then this information
-  // is not available.
-  Target_Ptr target = zypp::getZYpp()->getTarget();
-
+  // is guessed.
   static const std::string _value(
     str::form(
        "ZYpp %s (curl %s) %s"
        , VERSION
        , curl_version_info(CURLVERSION_NOW)->version
-       , target ? target->targetDistribution().c_str() : ""
+       , Target::targetDistribution( Pathname()/*guess root*/ ).c_str()
     )
   );
   return _value.c_str();
@@ -410,13 +551,17 @@ static const char *const agentString()
 
 // we use this define to unbloat code as this C setting option
 // and catching exception is done frequently.
-#define SET_OPTION(opt,val) { \
+/** \todo deprecate SET_OPTION and use the typed versions below. */
+#define SET_OPTION(opt,val) do { \
     ret = curl_easy_setopt ( _curl, opt, val ); \
     if ( ret != 0) { \
-      disconnectFrom(); \
       ZYPP_THROW(MediaCurlSetOptException(_url, _curlError)); \
     } \
-  }
+  } while ( false )
+
+#define SET_OPTION_OFFT(opt,val) SET_OPTION(opt,(curl_off_t)val)
+#define SET_OPTION_LONG(opt,val) SET_OPTION(opt,(long)val)
+#define SET_OPTION_VOID(opt,val) SET_OPTION(opt,(void*)val)
 
 MediaCurl::MediaCurl( const Url &      url_r,
                       const Pathname & attach_point_hint_r )
@@ -454,6 +599,37 @@ MediaCurl::MediaCurl( const Url &      url_r,
   }
 }
 
+Url MediaCurl::clearQueryString(const Url &url) const
+{
+  Url curlUrl (url);
+  curlUrl.setUsername( "" );
+  curlUrl.setPassword( "" );
+  curlUrl.setPathParams( "" );
+  curlUrl.setFragment( "" );
+  curlUrl.delQueryParam("cookies");
+  curlUrl.delQueryParam("proxy");
+  curlUrl.delQueryParam("proxyport");
+  curlUrl.delQueryParam("proxyuser");
+  curlUrl.delQueryParam("proxypass");
+  curlUrl.delQueryParam("ssl_capath");
+  curlUrl.delQueryParam("ssl_verify");
+  curlUrl.delQueryParam("ssl_clientcert");
+  curlUrl.delQueryParam("timeout");
+  curlUrl.delQueryParam("auth");
+  curlUrl.delQueryParam("username");
+  curlUrl.delQueryParam("password");
+  curlUrl.delQueryParam("mediahandler");
+  curlUrl.delQueryParam("credentials");
+  curlUrl.delQueryParam("head_requests");
+  return curlUrl;
+}
+
+TransferSettings & MediaCurl::settings()
+{
+    return _settings;
+}
+
+
 void MediaCurl::setCookieFile( const Pathname &fileName )
 {
   _cookieFile = fileName;
@@ -461,24 +637,15 @@ void MediaCurl::setCookieFile( const Pathname &fileName )
 
 ///////////////////////////////////////////////////////////////////
 
-void MediaCurl::attachTo (bool next)
+void MediaCurl::checkProtocol(const Url &url) const
 {
-  if ( next )
-    ZYPP_THROW(MediaNotSupportedException(_url));
-
-  if ( !_url.isValid() )
-    ZYPP_THROW(MediaBadUrlException(_url));
-
-  CurlConfig curlconf;
-  CurlConfig::parseConfig(curlconf); // parse ~/.curlrc
-
   curl_version_info_data *curl_info = NULL;
   curl_info = curl_version_info(CURLVERSION_NOW);
   // curl_info does not need any free (is static)
   if (curl_info->protocols)
   {
     const char * const *proto;
-    std::string        scheme( _url.getScheme());
+    std::string        scheme( url.getScheme());
     bool               found = false;
     for(proto=curl_info->protocols; !found && *proto; ++proto)
     {
@@ -493,54 +660,44 @@ void MediaCurl::attachTo (bool next)
       ZYPP_THROW(MediaBadUrlException(_url, msg));
     }
   }
+}
 
-  if( !isUseableAttachPoint(attachPoint()))
-  {
-    std::string mountpoint = createAttachPoint().asString();
-
-    if( mountpoint.empty())
-      ZYPP_THROW( MediaBadAttachPointException(url()));
-
-    setAttachPoint( mountpoint, true);
-  }
-
-  disconnectFrom(); // clean _curl if needed
-  _curl = curl_easy_init();
-  if ( !_curl ) {
-    ZYPP_THROW(MediaCurlInitException(_url));
-  }
-
+void MediaCurl::setupEasy()
+{
   {
     char *ptr = getenv("ZYPP_MEDIA_CURL_DEBUG");
     _curlDebug = (ptr && *ptr) ? str::strtonum<long>( ptr) : 0L;
     if( _curlDebug > 0)
     {
-      curl_easy_setopt( _curl, CURLOPT_VERBOSE, 1);
+      curl_easy_setopt( _curl, CURLOPT_VERBOSE, 1L);
       curl_easy_setopt( _curl, CURLOPT_DEBUGFUNCTION, log_curl);
       curl_easy_setopt( _curl, CURLOPT_DEBUGDATA, &_curlDebug);
     }
   }
 
   curl_easy_setopt(_curl, CURLOPT_HEADERFUNCTION, log_redirects_curl);
-
+  curl_easy_setopt(_curl, CURLOPT_HEADERDATA, &_lastRedirect);
   CURLcode ret = curl_easy_setopt( _curl, CURLOPT_ERRORBUFFER, _curlError );
   if ( ret != 0 ) {
-    disconnectFrom();
     ZYPP_THROW(MediaCurlSetOptException(_url, "Error setting error buffer"));
   }
 
-  SET_OPTION(CURLOPT_FAILONERROR,true);
-  SET_OPTION(CURLOPT_NOSIGNAL, 1);
+  SET_OPTION(CURLOPT_FAILONERROR, 1L);
+  SET_OPTION(CURLOPT_NOSIGNAL, 1L);
 
-  // reset settings in case we are re-attaching
-  _settings.reset();
+  // create non persistant settings
+  // so that we don't add headers twice
+  TransferSettings vol_settings(_settings);
 
-  // add custom headers
-  _settings.addHeader(anonymousIdHeader());
-  _settings.addHeader(distributionFlavorHeader());
-  _settings.addHeader("Pragma:");
+  // add custom headers for download.opensuse.org (bsc#955801)
+  if ( _url.getHost() == "download.opensuse.org" )
+  {
+    vol_settings.addHeader(anonymousIdHeader());
+    vol_settings.addHeader(distributionFlavorHeader());
+  }
+  vol_settings.addHeader("Pragma:");
 
-  _settings.setTimeout(TRANSFER_TIMEOUT);
+  _settings.setTimeout(ZConfig::instance().download_transfer_timeout());
   _settings.setConnectTimeout(CONNECT_TIMEOUT);
 
   _settings.setUserAgentString(agentString());
@@ -555,43 +712,79 @@ void MediaCurl::attachTo (bool next)
       disconnectFrom();
       ZYPP_RETHROW(e);
   }
-
-  // if the proxy was not set by url, then look
+  // if the proxy was not set (or explicitly unset) by url, then look...
   if ( _settings.proxy().empty() )
   {
-      // at the system proxy settings
+      // ...at the system proxy settings
       fillSettingsSystemProxy(_url, _settings);
   }
 
-  DBG << "Proxy: " << (_settings.proxy().empty() ? "-none-" : _settings.proxy()) << endl;
+  /** Force IPv4/v6 */
+  if ( env::ZYPP_MEDIA_CURL_IPRESOLVE() )
+  {
+    switch ( env::ZYPP_MEDIA_CURL_IPRESOLVE() )
+    {
+      case 4: SET_OPTION(CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4); break;
+      case 6: SET_OPTION(CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V6); break;
+    }
+  }
 
  /**
   * Connect timeout
   */
   SET_OPTION(CURLOPT_CONNECTTIMEOUT, _settings.connectTimeout());
-
-  if ( _url.getScheme() == "http" )
+  // If a transfer timeout is set, also set CURLOPT_TIMEOUT to an upper limit
+  // just in case curl does not trigger its progress callback frequently
+  // enough.
+  if ( _settings.timeout() )
   {
-    // follow any Location: header that the server sends as part of
-    // an HTTP header (#113275)
-    SET_OPTION(CURLOPT_FOLLOWLOCATION, true);
-    SET_OPTION(CURLOPT_MAXREDIRS, 3L);
-    SET_OPTION(CURLOPT_USERAGENT, _settings.userAgentString().c_str() );
+    SET_OPTION(CURLOPT_TIMEOUT, 3600L);
   }
 
+  // follow any Location: header that the server sends as part of
+  // an HTTP header (#113275)
+  SET_OPTION(CURLOPT_FOLLOWLOCATION, 1L);
+  // 3 redirects seem to be too few in some cases (bnc #465532)
+  SET_OPTION(CURLOPT_MAXREDIRS, 6L);
+
   if ( _url.getScheme() == "https" )
   {
+#if CURLVERSION_AT_LEAST(7,19,4)
+    // restrict following of redirections from https to https only
+    SET_OPTION( CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTPS );
+#endif
+
     if( _settings.verifyPeerEnabled() ||
         _settings.verifyHostEnabled() )
     {
       SET_OPTION(CURLOPT_CAPATH, _settings.certificateAuthoritiesPath().c_str());
     }
 
+    if( ! _settings.clientCertificatePath().empty() )
+    {
+      SET_OPTION(CURLOPT_SSLCERT, _settings.clientCertificatePath().c_str());
+    }
+    if( ! _settings.clientKeyPath().empty() )
+    {
+      SET_OPTION(CURLOPT_SSLKEY, _settings.clientKeyPath().c_str());
+    }
+
+#ifdef CURLSSLOPT_ALLOW_BEAST
+    // see bnc#779177
+    ret = curl_easy_setopt( _curl, CURLOPT_SSL_OPTIONS, CURLSSLOPT_ALLOW_BEAST );
+    if ( ret != 0 ) {
+      disconnectFrom();
+      ZYPP_THROW(MediaCurlSetOptException(_url, _curlError));
+    }
+#endif
     SET_OPTION(CURLOPT_SSL_VERIFYPEER, _settings.verifyPeerEnabled() ? 1L : 0L);
     SET_OPTION(CURLOPT_SSL_VERIFYHOST, _settings.verifyHostEnabled() ? 2L : 0L);
-    SET_OPTION(CURLOPT_USERAGENT, _settings.userAgentString().c_str() );
+    // bnc#903405 - POODLE: libzypp should only talk TLS
+    SET_OPTION(CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
   }
 
+  SET_OPTION(CURLOPT_USERAGENT, _settings.userAgentString().c_str() );
+
   /*---------------------------------------------------------------*
    CURLOPT_USERPWD: [user name]:[password]
 
@@ -601,102 +794,105 @@ void MediaCurl::attachTo (bool next)
 
   if ( _settings.userPassword().size() )
   {
-    SET_OPTION(CURLOPT_USERPWD, unEscape(_settings.userPassword()).c_str());
-
-    //FIXME, we leave this here for now, as it does not make sense yet
-    // to refactor it to the fill settings from url function
-
-    // HTTP authentication type
-    if(_url.getScheme() == "http" || _url.getScheme() == "https")
+    SET_OPTION(CURLOPT_USERPWD, _settings.userPassword().c_str());
+    string use_auth = _settings.authType();
+    if (use_auth.empty())
+      use_auth = "digest,basic";       // our default
+    long auth = CurlAuthData::auth_type_str2long(use_auth);
+    if( auth != CURLAUTH_NONE)
     {
-      string use_auth = _url.getQueryParam("auth");
-      if( use_auth.empty())
-        use_auth = "digest,basic";
-
-      try
-      {
-        long auth = CurlAuthData::auth_type_str2long(use_auth);
-        if( auth != CURLAUTH_NONE)
-        {
-          DBG << "Enabling HTTP authentication methods: " << use_auth
-              << " (CURLOPT_HTTPAUTH=" << auth << ")" << std::endl;
-
-          SET_OPTION(CURLOPT_HTTPAUTH, auth);
-        }
-      }
-      catch (MediaException & ex_r)
-      {
-        string auth_hint = getAuthHint();
-
-        DBG << "Rethrowing as MediaUnauthorizedException. auth hint: '"
-            << auth_hint << "'" << endl;
-
-        ZYPP_THROW(MediaUnauthorizedException(
-          _url, ex_r.msg(), _curlError, auth_hint
-        ));
-      }
+      DBG << "Enabling HTTP authentication methods: " << use_auth
+         << " (CURLOPT_HTTPAUTH=" << auth << ")" << std::endl;
+      SET_OPTION(CURLOPT_HTTPAUTH, auth);
     }
   }
 
-  if ( _settings.proxyEnabled() )
+  if ( _settings.proxyEnabled() && ! _settings.proxy().empty() )
   {
-    if ( ! _settings.proxy().empty() )
+    DBG << "Proxy: '" << _settings.proxy() << "'" << endl;
+    SET_OPTION(CURLOPT_PROXY, _settings.proxy().c_str());
+    SET_OPTION(CURLOPT_PROXYAUTH, CURLAUTH_BASIC|CURLAUTH_DIGEST|CURLAUTH_NTLM );
+    /*---------------------------------------------------------------*
+     *    CURLOPT_PROXYUSERPWD: [user name]:[password]
+     *
+     * Url::option(proxyuser and proxypassword) -> CURLOPT_PROXYUSERPWD
+     *  If not provided, $HOME/.curlrc is evaluated
+     *---------------------------------------------------------------*/
+
+    string proxyuserpwd = _settings.proxyUserPassword();
+
+    if ( proxyuserpwd.empty() )
     {
-      SET_OPTION(CURLOPT_PROXY, _settings.proxy().c_str());
-      /*---------------------------------------------------------------*
-        CURLOPT_PROXYUSERPWD: [user name]:[password]
-
-        Url::option(proxyuser and proxypassword) -> CURLOPT_PROXYUSERPWD
-        If not provided, $HOME/.curlrc is evaluated
-        *---------------------------------------------------------------*/
-
-      string proxyuserpwd = _settings.proxyUserPassword();
-
-      if ( proxyuserpwd.empty() )
+      CurlConfig curlconf;
+      CurlConfig::parseConfig(curlconf); // parse ~/.curlrc
+      if ( curlconf.proxyuserpwd.empty() )
+       DBG << "Proxy: ~/.curlrc does not contain the proxy-user option" << endl;
+      else
       {
-        if (curlconf.proxyuserpwd.empty())
-          DBG << "~/.curlrc does not contain the proxy-user option" << endl;
-        else
-        {
-          proxyuserpwd = curlconf.proxyuserpwd;
-          DBG << "using proxy-user from ~/.curlrc" << endl;
-        }
+       proxyuserpwd = curlconf.proxyuserpwd;
+       DBG << "Proxy: using proxy-user from ~/.curlrc" << endl;
       }
+    }
+    else
+    {
+      DBG << "Proxy: using provided proxy-user '" << _settings.proxyUsername() << "'" << endl;
+    }
 
-      proxyuserpwd = unEscape( proxyuserpwd );
-      if ( ! proxyuserpwd.empty() )
-        SET_OPTION(CURLOPT_PROXYUSERPWD, proxyuserpwd.c_str());
+    if ( ! proxyuserpwd.empty() )
+    {
+      SET_OPTION(CURLOPT_PROXYUSERPWD, unEscape( proxyuserpwd ).c_str());
     }
   }
+#if CURLVERSION_AT_LEAST(7,19,4)
+  else if ( _settings.proxy() == EXPLICITLY_NO_PROXY )
+  {
+    // Explicitly disabled in URL (see fillSettingsFromUrl()).
+    // This should also prevent libcurl from looking into the environment.
+    DBG << "Proxy: explicitly NOPROXY" << endl;
+    SET_OPTION(CURLOPT_NOPROXY, "*");
+  }
+#endif
+  else
+  {
+    DBG << "Proxy: not explicitly set" << endl;
+    DBG << "Proxy: libcurl may look into the environment" << endl;
+  }
 
   /** Speed limits */
   if ( _settings.minDownloadSpeed() != 0 )
   {
       SET_OPTION(CURLOPT_LOW_SPEED_LIMIT, _settings.minDownloadSpeed());
       // default to 10 seconds at low speed
-      SET_OPTION(CURLOPT_LOW_SPEED_TIME, 10);
+      SET_OPTION(CURLOPT_LOW_SPEED_TIME, 60L);
   }
 
+#if CURLVERSION_AT_LEAST(7,15,5)
   if ( _settings.maxDownloadSpeed() != 0 )
-      SET_OPTION(CURLOPT_MAX_RECV_SPEED_LARGE, _settings.maxDownloadSpeed());
+      SET_OPTION_OFFT(CURLOPT_MAX_RECV_SPEED_LARGE, _settings.maxDownloadSpeed());
+#endif
 
   /*---------------------------------------------------------------*
    *---------------------------------------------------------------*/
 
   _currentCookieFile = _cookieFile.asString();
-  SET_OPTION(CURLOPT_COOKIEFILE, _currentCookieFile.c_str() );
+  if ( str::strToBool( _url.getQueryParam( "cookies" ), true ) )
+    SET_OPTION(CURLOPT_COOKIEFILE, _currentCookieFile.c_str() );
+  else
+    MIL << "No cookies requested" << endl;
   SET_OPTION(CURLOPT_COOKIEJAR, _currentCookieFile.c_str() );
   SET_OPTION(CURLOPT_PROGRESSFUNCTION, &progressCallback );
-  SET_OPTION(CURLOPT_NOPROGRESS, false );
+  SET_OPTION(CURLOPT_NOPROGRESS, 0L);
 
+#if CURLVERSION_AT_LEAST(7,18,0)
   // bnc #306272
-  SET_OPTION(CURLOPT_PROXY_TRANSFER_MODE, 1 );
-
+    SET_OPTION(CURLOPT_PROXY_TRANSFER_MODE, 1L );
+#endif
   // append settings custom headers to curl
-  for ( TransferSettings::Headers::const_iterator it = _settings.headersBegin();
-        it != _settings.headersEnd();
+  for ( TransferSettings::Headers::const_iterator it = vol_settings.headersBegin();
+        it != vol_settings.headersEnd();
         ++it )
   {
+    // MIL << "HEADER " << *it << std::endl;
 
       _customHeaders = curl_slist_append(_customHeaders, it->c_str());
       if ( !_customHeaders )
@@ -704,6 +900,39 @@ void MediaCurl::attachTo (bool next)
   }
 
   SET_OPTION(CURLOPT_HTTPHEADER, _customHeaders);
+}
+
+///////////////////////////////////////////////////////////////////
+
+
+void MediaCurl::attachTo (bool next)
+{
+  if ( next )
+    ZYPP_THROW(MediaNotSupportedException(_url));
+
+  if ( !_url.isValid() )
+    ZYPP_THROW(MediaBadUrlException(_url));
+
+  checkProtocol(_url);
+  if( !isUseableAttachPoint( attachPoint() ) )
+  {
+    setAttachPoint( createAttachPoint(), true );
+  }
+
+  disconnectFrom(); // clean _curl if needed
+  _curl = curl_easy_init();
+  if ( !_curl ) {
+    ZYPP_THROW(MediaCurlInitException(_url));
+  }
+  try
+    {
+      setupEasy();
+    }
+  catch (Exception & ex)
+    {
+      disconnectFrom();
+      ZYPP_RETHROW(ex);
+    }
 
   // FIXME: need a derived class to propelly compare url's
   MediaSourceRef media( new MediaSource(_url.getScheme(), _url.asString()));
@@ -740,50 +969,36 @@ void MediaCurl::releaseFrom( const std::string & ejectDev )
   disconnect();
 }
 
-static Url getFileUrl(const Url & url, const Pathname & filename)
+Url MediaCurl::getFileUrl( const Pathname & filename_r ) const
 {
-  Url newurl(url);
-  string path = url.getPathName();
-  if ( !path.empty() && path != "/" && *path.rbegin() == '/' &&
-       filename.absolute() )
-  {
-    // If url has a path with trailing slash, remove the leading slash from
-    // the absolute file name
-    path += filename.asString().substr( 1, filename.asString().size() - 1 );
-  }
-  else if ( filename.relative() )
-  {
-    // Add trailing slash to path, if not already there
-    if (path.empty()) path = "/";
-    else if (*path.rbegin() != '/' ) path += "/";
-    // Remove "./" from begin of relative file name
-    path += filename.asString().substr( 2, filename.asString().size() - 2 );
-  }
-  else
-  {
-    path += filename.asString();
-  }
-
-  newurl.setPathName(path);
+  // Simply extend the URLs pathname. An 'absolute' URL path
+  // is achieved by encoding the leading '/' in an URL path:
+  //   URL: ftp://user@server          -> ~user
+  //   URL: ftp://user@server/         -> ~user
+  //   URL: ftp://user@server//                -> ~user
+  //   URL: ftp://user@server/%2F      -> /
+  //                         ^- this '/' is just a separator
+  Url newurl( _url );
+  newurl.setPathName( ( Pathname("./"+_url.getPathName()) / filename_r ).asString().substr(1) );
   return newurl;
 }
 
 ///////////////////////////////////////////////////////////////////
 
-void MediaCurl::getFile( const Pathname & filename ) const
+void MediaCurl::getFile(const Pathname & filename , const ByteCount &expectedFileSize_r) const
 {
     // Use absolute file name to prevent access of files outside of the
     // hierarchy below the attach point.
-    getFileCopy(filename, localPath(filename).absolutename());
+    getFileCopy(filename, localPath(filename).absolutename(), expectedFileSize_r);
 }
 
 ///////////////////////////////////////////////////////////////////
 
-void MediaCurl::getFileCopy( const Pathname & filename , const Pathname & target) const
+void MediaCurl::getFileCopy( const Pathname & filename , const Pathname & target, const ByteCount &expectedFileSize_r ) const
 {
   callback::SendReport<DownloadProgressReport> report;
 
-  Url fileurl(getFileUrl(_url, filename));
+  Url fileurl(getFileUrl(filename));
 
   bool retry = false;
 
@@ -791,7 +1006,7 @@ void MediaCurl::getFileCopy( const Pathname & filename , const Pathname & target
   {
     try
     {
-      doGetFileCopy(filename, target, report);
+      doGetFileCopy(filename, target, report, expectedFileSize_r);
       retry = false;
     }
     // retry with proper authentication data
@@ -808,8 +1023,13 @@ void MediaCurl::getFileCopy( const Pathname & filename , const Pathname & target
     // unexpected exception
     catch (MediaException & excpt_r)
     {
-      // FIXME: error number fix
-      report->finish(fileurl, zypp::media::DownloadProgressReport::ERROR, excpt_r.asUserHistory());
+      media::DownloadProgressReport::Error reason = media::DownloadProgressReport::ERROR;
+      if( typeid(excpt_r) == typeid( media::MediaFileNotFoundException )  ||
+         typeid(excpt_r) == typeid( media::MediaNotAFileException ) )
+      {
+       reason = media::DownloadProgressReport::NOT_FOUND;
+      }
+      report->finish(fileurl, reason, excpt_r.asUserHistory());
       ZYPP_RETHROW(excpt_r);
     }
   }
@@ -851,23 +1071,35 @@ bool MediaCurl::getDoesFileExist( const Pathname & filename ) const
 
 ///////////////////////////////////////////////////////////////////
 
-void MediaCurl::evaluateCurlCode( const Pathname &filename,
+void MediaCurl::evaluateCurlCode(const Pathname &filename,
                                   CURLcode code,
-                                  bool timeout_reached ) const
+                                  bool timeout_reached) const
 {
-  Url url(getFileUrl(_url, filename));
-
   if ( code != 0 )
   {
+    Url url;
+    if (filename.empty())
+      url = _url;
+    else
+      url = getFileUrl(filename);
+
     std::string err;
-    try
     {
       switch ( code )
       {
       case CURLE_UNSUPPORTED_PROTOCOL:
+         err = " Unsupported protocol";
+         if ( !_lastRedirect.empty() )
+         {
+           err += " or redirect (";
+           err += _lastRedirect;
+           err += ")";
+         }
+         break;
       case CURLE_URL_MALFORMAT:
       case CURLE_URL_MALFORMAT_USER:
           err = " Bad URL";
+          break;
       case CURLE_LOGIN_DENIED:
           ZYPP_THROW(
               MediaUnauthorizedException(url, "Login failed.", _curlError, ""));
@@ -895,13 +1127,22 @@ void MediaCurl::evaluateCurlCode( const Pathname &filename,
                            ));
           }
 
+          case 502: // bad gateway (bnc #1070851)
           case 503: // service temporarily unavailable (bnc #462545)
             ZYPP_THROW(MediaTemporaryProblemException(url));
           case 504: // gateway timeout
             ZYPP_THROW(MediaTimeoutException(url));
           case 403:
-            ZYPP_THROW(MediaForbiddenException(url));
+          {
+            string msg403;
+           if ( url.getHost().find(".suse.com") != string::npos )
+             msg403 = _("Visit the SUSE Customer Center to check whether your registration is valid and has not expired.");
+           else if (url.asString().find("novell.com") != string::npos)
+              msg403 = _("Visit the Novell Customer Center to check whether your registration is valid and has not expired.");
+            ZYPP_THROW(MediaForbiddenException(url, msg403));
+          }
           case 404:
+          case 410:
               ZYPP_THROW(MediaFileNotFoundException(_url, filename));
           }
 
@@ -917,7 +1158,11 @@ void MediaCurl::evaluateCurlCode( const Pathname &filename,
       }
       break;
       case CURLE_FTP_COULDNT_RETR_FILE:
+#if CURLVERSION_AT_LEAST(7,16,0)
+      case CURLE_REMOTE_FILE_NOT_FOUND:
+#endif
       case CURLE_FTP_ACCESS_DENIED:
+      case CURLE_TFTP_NOTFOUND:
         err = "File not found";
         ZYPP_THROW(MediaFileNotFoundException(_url, filename));
         break;
@@ -934,9 +1179,12 @@ void MediaCurl::evaluateCurlCode( const Pathname &filename,
       case CURLE_WRITE_ERROR:
         err = "Write error";
         break;
-      case CURLE_ABORTED_BY_CALLBACK:
+      case CURLE_PARTIAL_FILE:
       case CURLE_OPERATION_TIMEDOUT:
-        if( timeout_reached)
+       timeout_reached = true; // fall though to TimeoutException
+       // fall though...
+      case CURLE_ABORTED_BY_CALLBACK:
+         if( timeout_reached )
         {
           err  = "Timeout reached";
           ZYPP_THROW(MediaTimeoutException(url));
@@ -948,17 +1196,13 @@ void MediaCurl::evaluateCurlCode( const Pathname &filename,
         break;
       case CURLE_SSL_PEER_CERTIFICATE:
       default:
-        err = "Unrecognized error";
+        err = "Curl error " + str::numstring( code );
         break;
       }
 
       // uhm, no 0 code but unknown curl exception
       ZYPP_THROW(MediaCurlException(url, err, _curlError));
     }
-    catch (const MediaException & excpt_r)
-    {
-      ZYPP_RETHROW(excpt_r);
-    }
   }
   else
   {
@@ -978,21 +1222,14 @@ bool MediaCurl::doGetDoesFileExist( const Pathname & filename ) const
   if(_url.getHost().empty())
     ZYPP_THROW(MediaBadUrlEmptyHostException(_url));
 
-  Url url(getFileUrl(_url, filename));
+  Url url(getFileUrl(filename));
 
   DBG << "URL: " << url.asString() << endl;
     // Use URL without options and without username and passwd
     // (some proxies dislike them in the URL).
     // Curl seems to need the just scheme, hostname and a path;
     // the rest was already passed as curl options (in attachTo).
-  Url curlUrl( url );
-
-  // Use asString + url::ViewOptions instead?
-  curlUrl.setUsername( "" );
-  curlUrl.setPassword( "" );
-  curlUrl.setPathParams( "" );
-  curlUrl.setQueryString( "" );
-  curlUrl.setFragment( "" );
+  Url curlUrl( clearQueryString(url) );
 
   //
     // See also Bug #154197 and ftp url definition in RFC 1738:
@@ -1002,6 +1239,7 @@ bool MediaCurl::doGetDoesFileExist( const Pathname & filename ) const
     // encoded slash as %2f) "ftp://user@host/%2ffoo/bar/file"
     // contains an absolute path.
   //
+  _lastRedirect.clear();
   string urlBuffer( curlUrl.asString());
   CURLcode ret = curl_easy_setopt( _curl, CURLOPT_URL,
                                    urlBuffer.c_str() );
@@ -1014,35 +1252,35 @@ bool MediaCurl::doGetDoesFileExist( const Pathname & filename ) const
   // works for ftp as well, because retrieving only headers
   // ftp will return always OK code ?
   // See http://curl.haxx.se/docs/knownbugs.html #58
-  if (  _url.getScheme() == "http" ||  _url.getScheme() == "https" )
-    ret = curl_easy_setopt( _curl, CURLOPT_NOBODY, 1 );
+  if (  (_url.getScheme() == "http" ||  _url.getScheme() == "https") &&
+        _settings.headRequestsAllowed() )
+    ret = curl_easy_setopt( _curl, CURLOPT_NOBODY, 1L );
   else
     ret = curl_easy_setopt( _curl, CURLOPT_RANGE, "0-1" );
 
   if ( ret != 0 ) {
-    curl_easy_setopt( _curl, CURLOPT_NOBODY, NULL );
+    curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
     curl_easy_setopt( _curl, CURLOPT_RANGE, NULL );
     /* yes, this is why we never got to get NOBODY working before,
        because setting it changes this option too, and we also
        need to reset it
        See: http://curl.haxx.se/mail/archive-2005-07/0073.html
     */
-    curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1 );
+    curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1L );
     ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
   }
 
   FILE *file = ::fopen( "/dev/null", "w" );
   if ( !file ) {
-      ::fclose(file);
       ERR << "fopen failed for /dev/null" << endl;
-      curl_easy_setopt( _curl, CURLOPT_NOBODY, NULL );
+      curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
       curl_easy_setopt( _curl, CURLOPT_RANGE, NULL );
       /* yes, this is why we never got to get NOBODY working before,
        because setting it changes this option too, and we also
        need to reset it
        See: http://curl.haxx.se/mail/archive-2005-07/0073.html
       */
-      curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1 );
+      curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1L );
       if ( ret != 0 ) {
           ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
       }
@@ -1054,13 +1292,13 @@ bool MediaCurl::doGetDoesFileExist( const Pathname & filename ) const
       ::fclose(file);
       std::string err( _curlError);
       curl_easy_setopt( _curl, CURLOPT_RANGE, NULL );
-      curl_easy_setopt( _curl, CURLOPT_NOBODY, NULL );
+      curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
       /* yes, this is why we never got to get NOBODY working before,
        because setting it changes this option too, and we also
        need to reset it
        See: http://curl.haxx.se/mail/archive-2005-07/0073.html
       */
-      curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1 );
+      curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1L );
       if ( ret != 0 ) {
           ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
       }
@@ -1073,7 +1311,7 @@ bool MediaCurl::doGetDoesFileExist( const Pathname & filename ) const
   // reset curl settings
   if (  _url.getScheme() == "http" ||  _url.getScheme() == "https" )
   {
-    curl_easy_setopt( _curl, CURLOPT_NOBODY, NULL );
+    curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
     if ( ret != 0 ) {
       ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
     }
@@ -1083,7 +1321,7 @@ bool MediaCurl::doGetDoesFileExist( const Pathname & filename ) const
        need to reset it
        See: http://curl.haxx.se/mail/archive-2005-07/0073.html
     */
-    curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1);
+    curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1L);
     if ( ret != 0 ) {
       ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
     }
@@ -1122,77 +1360,68 @@ bool MediaCurl::doGetDoesFileExist( const Pathname & filename ) const
 
 ///////////////////////////////////////////////////////////////////
 
-void MediaCurl::doGetFileCopy( const Pathname & filename , const Pathname & target, callback::SendReport<DownloadProgressReport> & report, RequestOptions options ) const
-{
-    DBG << filename.asString() << endl;
 
-    if(!_url.isValid())
-      ZYPP_THROW(MediaBadUrlException(_url));
-
-    if(_url.getHost().empty())
-      ZYPP_THROW(MediaBadUrlEmptyHostException(_url));
+#if DETECT_DIR_INDEX
+bool MediaCurl::detectDirIndex() const
+{
+  if(_url.getScheme() != "http" && _url.getScheme() != "https")
+    return false;
+  //
+  // try to check the effective url and set the not_a_file flag
+  // if the url path ends with a "/", what usually means, that
+  // we've received a directory index (index.html content).
+  //
+  // Note: This may be dangerous and break file retrieving in
+  //       case of some server redirections ... ?
+  //
+  bool      not_a_file = false;
+  char     *ptr = NULL;
+  CURLcode  ret = curl_easy_getinfo( _curl,
+                                    CURLINFO_EFFECTIVE_URL,
+                                    &ptr);
+  if ( ret == CURLE_OK && ptr != NULL)
+  {
+    try
+    {
+      Url         eurl( ptr);
+      std::string path( eurl.getPathName());
+      if( !path.empty() && path != "/" && *path.rbegin() == '/')
+      {
+       DBG << "Effective url ("
+           << eurl
+           << ") seems to provide the index of a directory"
+           << endl;
+       not_a_file = true;
+      }
+    }
+    catch( ... )
+    {}
+  }
+  return not_a_file;
+}
+#endif
 
-    Url url(getFileUrl(_url, filename));
+///////////////////////////////////////////////////////////////////
 
+void MediaCurl::doGetFileCopy(const Pathname & filename , const Pathname & target, callback::SendReport<DownloadProgressReport> & report, const ByteCount &expectedFileSize_r, RequestOptions options ) const
+{
     Pathname dest = target.absolutename();
     if( assert_dir( dest.dirname() ) )
     {
       DBG << "assert_dir " << dest.dirname() << " failed" << endl;
+      Url url(getFileUrl(filename));
       ZYPP_THROW( MediaSystemException(url, "System error on " + dest.dirname().asString()) );
     }
-
-    DBG << "URL: " << url.asString() << endl;
-    // Use URL without options and without username and passwd
-    // (some proxies dislike them in the URL).
-    // Curl seems to need the just scheme, hostname and a path;
-    // the rest was already passed as curl options (in attachTo).
-    Url curlUrl( url );
-
-    // Use asString + url::ViewOptions instead?
-    curlUrl.setUsername( "" );
-    curlUrl.setPassword( "" );
-    curlUrl.setPathParams( "" );
-    curlUrl.setQueryString( "" );
-    curlUrl.setFragment( "" );
-
-    //
-    // See also Bug #154197 and ftp url definition in RFC 1738:
-    // The url "ftp://user@host/foo/bar/file" contains a path,
-    // that is relative to the user's home.
-    // The url "ftp://user@host//foo/bar/file" (or also with
-    // encoded slash as %2f) "ftp://user@host/%2ffoo/bar/file"
-    // contains an absolute path.
-    //
-    string urlBuffer( curlUrl.asString());
-    CURLcode ret = curl_easy_setopt( _curl, CURLOPT_URL,
-                                     urlBuffer.c_str() );
-    if ( ret != 0 ) {
-      ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
-    }
-
-    // set IFMODSINCE time condition (no download if not modified)
-    if( PathInfo(target).isExist() )
-    {
-      curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_IFMODSINCE);
-      curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, PathInfo(target).mtime());
-    }
-    else
-    {
-      curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
-      curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, 0);
-    }
-
     string destNew = target.asString() + ".new.zypp.XXXXXX";
     char *buf = ::strdup( destNew.c_str());
     if( !buf)
     {
       ERR << "out of memory for temp file name" << endl;
-      ZYPP_THROW(MediaSystemException(
-        url, "out of memory for temp file name"
-      ));
+      Url url(getFileUrl(filename));
+      ZYPP_THROW(MediaSystemException(url, "out of memory for temp file name"));
     }
 
-    int tmp_fd = ::mkstemp( buf );
+    int tmp_fd = ::mkostemp( buf, O_CLOEXEC );
     if( tmp_fd == -1)
     {
       free( buf);
@@ -1202,7 +1431,7 @@ void MediaCurl::doGetFileCopy( const Pathname & filename , const Pathname & targ
     destNew = buf;
     free( buf);
 
-    FILE *file = ::fdopen( tmp_fd, "w" );
+    FILE *file = ::fdopen( tmp_fd, "we" );
     if ( !file ) {
       ::close( tmp_fd);
       filesystem::unlink( destNew );
@@ -1213,92 +1442,29 @@ void MediaCurl::doGetFileCopy( const Pathname & filename , const Pathname & targ
     DBG << "dest: " << dest << endl;
     DBG << "temp: " << destNew << endl;
 
-    ret = curl_easy_setopt( _curl, CURLOPT_WRITEDATA, file );
-    if ( ret != 0 ) {
-      ::fclose( file );
-      filesystem::unlink( destNew );
-      ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
+    // set IFMODSINCE time condition (no download if not modified)
+    if( PathInfo(target).isExist() && !(options & OPTION_NO_IFMODSINCE) )
+    {
+      curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_IFMODSINCE);
+      curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, (long)PathInfo(target).mtime());
     }
-
-    // Set callback and perform.
-    ProgressData progressData(_settings.timeout(), url, &report);
-    report->start(url, dest);
-    if ( curl_easy_setopt( _curl, CURLOPT_PROGRESSDATA, &progressData ) != 0 ) {
-      WAR << "Can't set CURLOPT_PROGRESSDATA: " << _curlError << endl;;
+    else
+    {
+      curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
+      curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, 0L);
     }
-
-    ret = curl_easy_perform( _curl );
-
-    if ( curl_easy_setopt( _curl, CURLOPT_PROGRESSDATA, NULL ) != 0 ) {
-      WAR << "Can't unset CURLOPT_PROGRESSDATA: " << _curlError << endl;;
+    try
+    {
+      doGetFileCopyFile(filename, dest, file, report, expectedFileSize_r, options);
     }
-
-    if ( ret != 0 )
+    catch (Exception &e)
     {
-      ERR << "curl error: " << ret << ": " << _curlError
-          << ", temp file size " << PathInfo(destNew).size()
-          << " byte." << endl;
-
       ::fclose( file );
       filesystem::unlink( destNew );
-
-      // the timeout is determined by the progress data object
-      // which holds wheter the timeout was reached or not,
-      // otherwise it would be a user cancel
-      try {
-        evaluateCurlCode( filename, ret, progressData.reached);
-      }
-      catch ( const MediaException &e ) {
-        // some error, we are not sure about file existence, rethrw
-        ZYPP_RETHROW(e);
-      }
-    }
-
-#if DETECT_DIR_INDEX
-    else
-    if(curlUrl.getScheme() == "http" ||
-       curlUrl.getScheme() == "https")
-    {
-      //
-      // try to check the effective url and set the not_a_file flag
-      // if the url path ends with a "/", what usually means, that
-      // we've received a directory index (index.html content).
-      //
-      // Note: This may be dangerous and break file retrieving in
-      //       case of some server redirections ... ?
-      //
-      bool      not_a_file = false;
-      char     *ptr = NULL;
-      CURLcode  ret = curl_easy_getinfo( _curl,
-                                         CURLINFO_EFFECTIVE_URL,
-                                         &ptr);
-      if ( ret == CURLE_OK && ptr != NULL)
-      {
-        try
-        {
-          Url         eurl( ptr);
-          std::string path( eurl.getPathName());
-          if( !path.empty() && path != "/" && *path.rbegin() == '/')
-          {
-            DBG << "Effective url ("
-                << eurl
-                << ") seems to provide the index of a directory"
-                << endl;
-            not_a_file = true;
-          }
-        }
-        catch( ... )
-        {}
-      }
-
-      if( not_a_file)
-      {
-        ::fclose( file );
-        filesystem::unlink( destNew );
-        ZYPP_THROW(MediaNotAFileException(_url, filename));
-      }
+      curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
+      curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, 0L);
+      ZYPP_RETHROW(e);
     }
-#endif // DETECT_DIR_INDEX
 
     long httpReturnCode = 0;
     CURLcode infoRet = curl_easy_getinfo(_curl,
@@ -1309,7 +1475,7 @@ void MediaCurl::doGetFileCopy( const Pathname & filename , const Pathname & targ
     {
       DBG << "HTTP response: " + str::numstring(httpReturnCode);
       if ( httpReturnCode == 304
-           || ( httpReturnCode == 213 && _url.getScheme() == "ftp" ) ) // not modified
+           || ( httpReturnCode == 213 && (_url.getScheme() == "ftp" || _url.getScheme() == "tftp") ) ) // not modified
       {
         DBG << " Not modified.";
         modified = false;
@@ -1328,8 +1494,11 @@ void MediaCurl::doGetFileCopy( const Pathname & filename , const Pathname & targ
       {
         ERR << "Failed to chmod file " << destNew << endl;
       }
-      ::fclose( file );
-
+      if (::fclose( file ))
+      {
+        ERR << "Fclose failed for file '" << destNew << "'" << endl;
+        ZYPP_THROW(MediaWriteException(destNew));
+      }
       // move the temp file into dest
       if ( rename( destNew, dest ) != 0 ) {
         ERR << "Rename failed" << endl;
@@ -1348,6 +1517,113 @@ void MediaCurl::doGetFileCopy( const Pathname & filename , const Pathname & targ
 
 ///////////////////////////////////////////////////////////////////
 
+void MediaCurl::doGetFileCopyFile(const Pathname & filename , const Pathname & dest, FILE *file, callback::SendReport<DownloadProgressReport> & report, const ByteCount &expectedFileSize_r, RequestOptions options ) const
+{
+    DBG << filename.asString() << endl;
+
+    if(!_url.isValid())
+      ZYPP_THROW(MediaBadUrlException(_url));
+
+    if(_url.getHost().empty())
+      ZYPP_THROW(MediaBadUrlEmptyHostException(_url));
+
+    Url url(getFileUrl(filename));
+
+    DBG << "URL: " << url.asString() << endl;
+    // Use URL without options and without username and passwd
+    // (some proxies dislike them in the URL).
+    // Curl seems to need the just scheme, hostname and a path;
+    // the rest was already passed as curl options (in attachTo).
+    Url curlUrl( clearQueryString(url) );
+
+    //
+    // See also Bug #154197 and ftp url definition in RFC 1738:
+    // The url "ftp://user@host/foo/bar/file" contains a path,
+    // that is relative to the user's home.
+    // The url "ftp://user@host//foo/bar/file" (or also with
+    // encoded slash as %2f) "ftp://user@host/%2ffoo/bar/file"
+    // contains an absolute path.
+    //
+    _lastRedirect.clear();
+    string urlBuffer( curlUrl.asString());
+    CURLcode ret = curl_easy_setopt( _curl, CURLOPT_URL,
+                                     urlBuffer.c_str() );
+    if ( ret != 0 ) {
+      ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
+    }
+
+    ret = curl_easy_setopt( _curl, CURLOPT_WRITEDATA, file );
+    if ( ret != 0 ) {
+      ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
+    }
+
+    // Set callback and perform.
+    ProgressData progressData(_curl, _settings.timeout(), url, expectedFileSize_r, &report);
+    if (!(options & OPTION_NO_REPORT_START))
+      report->start(url, dest);
+    if ( curl_easy_setopt( _curl, CURLOPT_PROGRESSDATA, &progressData ) != 0 ) {
+      WAR << "Can't set CURLOPT_PROGRESSDATA: " << _curlError << endl;;
+    }
+
+    ret = curl_easy_perform( _curl );
+#if CURLVERSION_AT_LEAST(7,19,4)
+    // bnc#692260: If the client sends a request with an If-Modified-Since header
+    // with a future date for the server, the server may respond 200 sending a
+    // zero size file.
+    // curl-7.19.4 introduces CURLINFO_CONDITION_UNMET to check this condition.
+    if ( ftell(file) == 0 && ret == 0 )
+    {
+      long httpReturnCode = 33;
+      if ( curl_easy_getinfo( _curl, CURLINFO_RESPONSE_CODE, &httpReturnCode ) == CURLE_OK && httpReturnCode == 200 )
+      {
+       long conditionUnmet = 33;
+       if ( curl_easy_getinfo( _curl, CURLINFO_CONDITION_UNMET, &conditionUnmet ) == CURLE_OK && conditionUnmet )
+       {
+         WAR << "TIMECONDITION unmet - retry without." << endl;
+         curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
+         curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, 0L);
+         ret = curl_easy_perform( _curl );
+       }
+      }
+    }
+#endif
+
+    if ( curl_easy_setopt( _curl, CURLOPT_PROGRESSDATA, NULL ) != 0 ) {
+      WAR << "Can't unset CURLOPT_PROGRESSDATA: " << _curlError << endl;;
+    }
+
+    if ( ret != 0 )
+    {
+      ERR << "curl error: " << ret << ": " << _curlError
+          << ", temp file size " << ftell(file)
+          << " bytes." << endl;
+
+      // the timeout is determined by the progress data object
+      // which holds whether the timeout was reached or not,
+      // otherwise it would be a user cancel
+      try {
+
+        if ( progressData.fileSizeExceeded )
+          ZYPP_THROW(MediaFileSizeExceededException(url, progressData._expectedFileSize));
+
+        evaluateCurlCode( filename, ret, progressData.reached );
+      }
+      catch ( const MediaException &e ) {
+        // some error, we are not sure about file existence, rethrw
+        ZYPP_RETHROW(e);
+      }
+    }
+
+#if DETECT_DIR_INDEX
+    if (!ret && detectDirIndex())
+      {
+       ZYPP_THROW(MediaNotAFileException(_url, filename));
+      }
+#endif // DETECT_DIR_INDEX
+}
+
+///////////////////////////////////////////////////////////////////
+
 void MediaCurl::getDir( const Pathname & dirname, bool recurse_r ) const
 {
   filesystem::DirContent content;
@@ -1360,7 +1636,7 @@ void MediaCurl::getDir( const Pathname & dirname, bool recurse_r ) const
       switch ( it->type ) {
       case filesystem::FT_NOT_AVAIL: // old directory.yast contains no typeinfo at all
       case filesystem::FT_FILE:
-        getFile( filename );
+        getFile( filename, 0 );
         break;
       case filesystem::FT_DIR: // newer directory.yast contain at least directory info
         if ( recurse_r ) {
@@ -1396,96 +1672,43 @@ void MediaCurl::getDirInfo( filesystem::DirContent & retlist,
 }
 
 ///////////////////////////////////////////////////////////////////
-
-int MediaCurl::progressCallback( void *clientp,
-                                 double dltotal, double dlnow,
-                                 double ultotal, double ulnow)
+//
+int MediaCurl::aliveCallback( void *clientp, double /*dltotal*/, double dlnow, double /*ultotal*/, double /*ulnow*/ )
 {
-  ProgressData *pdata = reinterpret_cast<ProgressData *>(clientp);
-  if( pdata)
+  ProgressData *pdata = reinterpret_cast<ProgressData *>( clientp );
+  if( pdata )
   {
-    time_t now   = time(NULL);
-    if( now > 0)
-    {
-       // reset time of last change in case initial time()
-       // failed or the time was adjusted (goes backward)
-       if( pdata->ltime <= 0 || pdata->ltime > now)
-       {
-         pdata->ltime = now;
-       }
-
-       // start time counting as soon as first data arrives
-       // (skip the connection / redirection time at begin)
-       time_t dif = 0;
-       if (dlnow > 0 || ulnow > 0)
-       {
-         dif = (now - pdata->ltime);
-         dif = dif > 0 ? dif : 0;
-
-         pdata->secs += dif;
-       }
-
-       // update the drate_avg and drate_period only after a second has passed
-       // (this callback is called much more often than a second)
-       // otherwise the values would be far from accurate when measuring
-       // the time in seconds
-       //! \todo more accurate download rate computationn, e.g. compute average value from last 5 seconds, or work with milliseconds instead of seconds
-
-        if ( pdata->secs > 1 && (dif > 0 || dlnow == dltotal ))
-          pdata->drate_avg = (dlnow / pdata->secs);
-
-       if ( dif > 0 )
-       {
-         pdata->drate_period = ((dlnow - pdata->dload_period) / dif);
-         pdata->dload_period = dlnow;
-       }
-    }
-
-    // send progress report first, abort transfer if requested
-    if( pdata->report)
-    {
-      if (!(*(pdata->report))->progress(int( dlnow * 100 / dltotal ),
-                                       pdata->url,
-                                       pdata->drate_avg,
-                                       pdata->drate_period))
-      {
-        return 1; // abort transfer
-      }
-    }
-
-    // check if we there is a timeout set
-    if( pdata->timeout > 0)
-    {
-      if( now > 0)
-      {
-        bool progress = false;
+    // Do not propagate dltotal in alive callbacks. MultiCurl uses this to
+    // prevent a percentage raise while downloading a metalink file. Download
+    // activity however is indicated by propagating the download rate (via dlnow).
+    pdata->updateStats( 0.0, dlnow );
+    return pdata->reportProgress();
+  }
+  return 0;
+}
 
-        // update download data if changed, mark progress
-        if( dlnow != pdata->dload)
-        {
-          progress     = true;
-          pdata->dload = dlnow;
-          pdata->ltime = now;
-        }
-        // update upload data if changed, mark progress
-        if( ulnow != pdata->uload)
-        {
-          progress     = true;
-          pdata->uload = ulnow;
-          pdata->ltime = now;
-        }
+int MediaCurl::progressCallback( void *clientp, double dltotal, double dlnow, double ultotal, double ulnow )
+{
+  ProgressData *pdata = reinterpret_cast<ProgressData *>( clientp );
+  if( pdata )
+  {
+    // work around curl bug that gives us old data
+    long httpReturnCode = 0;
+    if ( curl_easy_getinfo( pdata->curl, CURLINFO_RESPONSE_CODE, &httpReturnCode ) != CURLE_OK || httpReturnCode == 0 )
+      return aliveCallback( clientp, dltotal, dlnow, ultotal, ulnow );
 
-        if( !progress && (now >= (pdata->ltime + pdata->timeout)))
-        {
-          pdata->reached = true;
-          return 1; // aborts transfer
-        }
-      }
-    }
+    pdata->updateStats( dltotal, dlnow );
+    return pdata->reportProgress();
   }
   return 0;
 }
 
+CURL *MediaCurl::progressCallback_getcurl( void *clientp )
+{
+  ProgressData *pdata = reinterpret_cast<ProgressData *>(clientp);
+  return pdata ? pdata->curl : 0;
+}
+
 ///////////////////////////////////////////////////////////////////
 
 string MediaCurl::getAuthHint() const
@@ -1503,13 +1726,24 @@ string MediaCurl::getAuthHint() const
   return "";
 }
 
+/**
+ * MediaMultiCurl needs to reset the expected filesize in case a metalink file is downloaded
+ * otherwise this function should not be called
+ */
+void MediaCurl::resetExpectedFileSize(void *clientp, const ByteCount &expectedFileSize)
+{
+  ProgressData *data = reinterpret_cast<ProgressData *>(clientp);
+  if ( data ) {
+    data->_expectedFileSize = expectedFileSize;
+  }
+}
+
 ///////////////////////////////////////////////////////////////////
 
 bool MediaCurl::authenticate(const string & availAuthTypes, bool firstTry) const
 {
   //! \todo need a way to pass different CredManagerOptions here
-  Target_Ptr target = zypp::getZYpp()->getTarget();
-  CredentialManager cm(CredManagerOptions(target ? target->root() : ""));
+  CredentialManager cm(CredManagerOptions(ZConfig::instance().repoManagerRoot()));
   CurlAuthData_Ptr credentials;
 
   // get stored credentials
@@ -1538,9 +1772,7 @@ bool MediaCurl::authenticate(const string & availAuthTypes, bool firstTry) const
     // indicate we have no good credentials from CM
     cmcred.reset();
 
-    string prompt_msg = boost::str(boost::format(
-      //!\todo add comma to the message for the next release
-      _("Authentication required for '%s'")) % _url.asString());
+    string prompt_msg = str::Format(_("Authentication required for '%s'")) % _url.asString();
 
     // set available authentication types from the exception
     // might be needed in prompt
@@ -1587,9 +1819,11 @@ bool MediaCurl::authenticate(const string & availAuthTypes, bool firstTry) const
     if (credentials->authType() == CURLAUTH_NONE)
       credentials->setAuthType(availAuthTypes);
 
-    // set auth type (seems this must be set _after_ setting the userpwd
+    // set auth type (seems this must be set _after_ setting the userpwd)
     if (credentials->authType() != CURLAUTH_NONE)
     {
+      // FIXME: only overwrite if not empty?
+      const_cast<MediaCurl*>(this)->_settings.setAuthType(credentials->authTypeAsString());
       ret = curl_easy_setopt(_curl, CURLOPT_HTTPAUTH, credentials->authType());
       if ( ret != 0 ) ZYPP_THROW(MediaCurlSetOptException(_url, _curlError));
     }