libproxy implementation for ProxyInfo. Right now it is used if libproxy is present.
[platform/upstream/libzypp.git] / zypp / media / MediaCurl.cc
index 280c9a7..0699e59 100644 (file)
@@ -111,6 +111,41 @@ namespace
     }
     return 0;
   }
+
+  static size_t
+  log_redirects_curl(
+      void *ptr, size_t size, size_t nmemb, void *stream)
+  {
+    // INT << "got header: " << string((char *)ptr, ((char*)ptr) + size*nmemb) << endl;
+
+    char * lstart = (char *)ptr, * lend = (char *)ptr;
+    size_t pos = 0;
+    size_t max = size * nmemb;
+    while (pos + 1 < max)
+    {
+      // get line
+      for (lstart = lend; *lend != '\n' && pos < max; ++lend, ++pos);
+
+      // look for "Location"
+      string line(lstart, lend);
+      if (line.find("Location") != string::npos)
+      {
+        DBG << "redirecting to " << line << endl;
+        return max;
+      }
+
+      // continue with the next line
+      if (pos + 1 < max)
+      {
+        ++lend;
+        ++pos;
+      }
+      else
+        break;
+    }
+
+    return max;
+  }
 }
 
 namespace zypp {
@@ -177,66 +212,202 @@ namespace zypp {
 
   }
 
-///////////////////////////////////////////////////////////////////
-//
-//        CLASS NAME : MediaCurl
-//
-///////////////////////////////////////////////////////////////////
+/**
+ * Fills the settings structure using options passed on the url
+ * for example ?timeout=x&proxy=foo
+ */
+void fillSettingsFromUrl( const Url &url, TransferSettings &s )
+{
+    std::string param(url.getQueryParam("timeout"));
+    if( !param.empty())
+    {
+      long num = str::strtonum<long>(param);
+      if( num >= 0 && num <= TRANSFER_TIMEOUT_MAX)
+          s.setTimeout(num);
+    }
+
+    if ( ! url.getUsername().empty() )
+    {
+        s.setUsername(url.getUsername());
+        if ( url.getPassword().size() )
+            s.setPassword(url.getPassword());
+    }
+    else
+    {
+        // if there is no username, set anonymous auth
+        if ( url.getScheme() == "ftp" && s.username().empty() )
+            s.setAnonymousAuth();
+    }
+
+    if ( url.getScheme() == "https" )
+    {
+        s.setVerifyPeerEnabled(false);
+        s.setVerifyHostEnabled(false);
+
+        std::string verify( url.getQueryParam("ssl_verify"));
+        if( verify.empty() ||
+            verify == "yes")
+        {
+            s.setVerifyPeerEnabled(true);
+            s.setVerifyHostEnabled(true);
+        }
+        else if( verify == "no")
+        {
+            s.setVerifyPeerEnabled(false);
+            s.setVerifyHostEnabled(false);
+        }
+        else
+        {
+            std::vector<std::string>                 flags;
+            std::vector<std::string>::const_iterator flag;
+            str::split( verify, std::back_inserter(flags), ",");
+            for(flag = flags.begin(); flag != flags.end(); ++flag)
+            {
+                if( *flag == "host")
+                    s.setVerifyHostEnabled(true);
+                else if( *flag == "peer")
+                    s.setVerifyPeerEnabled(true);
+                else
+                    ZYPP_THROW(MediaBadUrlException(url, "Unknown ssl_verify flag"));
+            }
+        }
+    }
+
+    Pathname ca_path = Pathname(url.getQueryParam("ssl_capath")).asString();
+    if( ! ca_path.empty())
+    {
+        if( !PathInfo(ca_path).isDir() || !Pathname(ca_path).absolute())
+            ZYPP_THROW(MediaBadUrlException(url, "Invalid ssl_capath path"));
+        else
+            s.setCertificateAuthoritiesPath(ca_path);
+    }
+
+    string proxy = url.getQueryParam( "proxy" );
+    if ( ! proxy.empty() )
+    {
+        if ( proxy == "_none_" ) {
+            s.setProxyEnabled(false);
+        }
+        else {
+            string proxyport( url.getQueryParam( "proxyport" ) );
+            if ( ! proxyport.empty() ) {
+                proxy += ":" + proxyport;
+            }
+            s.setProxy(proxy);
+            s.setProxyEnabled(true);
+        }
+    }
+
+    // HTTP authentication type
+    string use_auth = url.getQueryParam("auth");
+    if (!use_auth.empty() && (url.getScheme() == "http" || url.getScheme() == "https"))
+    {
+        try
+        {
+           CurlAuthData::auth_type_str2long(use_auth); // check if we know it
+        }
+        catch (MediaException & ex_r)
+       {
+           DBG << "Rethrowing as MediaUnauthorizedException.";
+           ZYPP_THROW(MediaUnauthorizedException(url, ex_r.msg(), "", ""));
+       }
+        s.setAuthType(use_auth);
+    }
+
+    // workarounds
+    std::string head_requests( url.getQueryParam("head_requests"));
+    if( !head_requests.empty() && head_requests == "no")
+        s.setHeadRequestsAllowed(false);
+}
+
+/**
+ * Reads the system proxy configuration and fills the settings
+ * structure proxy information
+ */
+void fillSettingsSystemProxy( const Url&url, TransferSettings &s )
+{
+#ifdef _WITH_LIBPROXY_SUPPORT_
+    ProxyInfo proxy_info (ProxyInfo::ImplPtr(new ProxyInfoLibproxy()));
+#else
+    ProxyInfo proxy_info (ProxyInfo::ImplPtr(new ProxyInfoSysconfig("proxy")));
+#endif
+    s.setProxyEnabled( proxy_info.useProxyFor( url ) );
+    if ( s.proxyEnabled() )
+      s.setProxy(proxy_info.proxy(url));
+}
 
 Pathname MediaCurl::_cookieFile = "/var/lib/YaST2/cookies";
 
+/**
+ * initialized only once, this gets the anonymous id
+ * from the target, which we pass in the http header
+ */
 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();
 }
 
+/**
+ * initialized only once, this gets the distribution flavor
+ * from the target, which we pass in the http header
+ */
 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();
 }
 
-
+/**
+ * initialized only once, this gets the agent string
+ * which also includes the curl version
+ */
 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();
 }
 
+// we use this define to unbloat code as this C setting option
+// and catching exception is done frequently.
+/** \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) { \
+      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 )
@@ -274,37 +445,50 @@ MediaCurl::MediaCurl( const Url &      url_r,
   }
 }
 
-void MediaCurl::setCookieFile( const Pathname &fileName )
+Url MediaCurl::clearQueryString(const Url &url) const
 {
-  _cookieFile = fileName;
+  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("timeout");
+  curlUrl.delQueryParam("auth");
+  curlUrl.delQueryParam("username");
+  curlUrl.delQueryParam("password");
+  curlUrl.delQueryParam("mediahandler");
+  return curlUrl;
 }
 
-///////////////////////////////////////////////////////////////////
-//
-//
-//        METHOD NAME : MediaCurl::attachTo
-//        METHOD TYPE : PMError
-//
-//        DESCRIPTION : Asserted that not already attached, and attachPoint is a directory.
-//
-void MediaCurl::attachTo (bool next)
+TransferSettings & MediaCurl::settings()
 {
-  if ( next )
-    ZYPP_THROW(MediaNotSupportedException(_url));
+    return _settings;
+}
 
-  if ( !_url.isValid() )
-    ZYPP_THROW(MediaBadUrlException(_url));
 
-  CurlConfig curlconf;
-  CurlConfig::parseConfig(curlconf); // parse ~/.curlrc
+void MediaCurl::setCookieFile( const Pathname &fileName )
+{
+  _cookieFile = fileName;
+}
+
+///////////////////////////////////////////////////////////////////
 
+void MediaCurl::checkProtocol(const Url &url) const
+{
   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)
     {
@@ -319,181 +503,91 @@ 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);
   CURLcode ret = curl_easy_setopt( _curl, CURLOPT_ERRORBUFFER, _curlError );
   if ( ret != 0 ) {
-    disconnectFrom();
     ZYPP_THROW(MediaCurlSetOptException(_url, "Error setting error buffer"));
   }
 
-  ret = curl_easy_setopt( _curl, CURLOPT_FAILONERROR, true );
-  if ( ret != 0 ) {
-    disconnectFrom();
-    ZYPP_THROW(MediaCurlSetOptException(_url, _curlError));
-  }
+  SET_OPTION(CURLOPT_FAILONERROR, 1L);
+  SET_OPTION(CURLOPT_NOSIGNAL, 1L);
 
-  ret = curl_easy_setopt( _curl, CURLOPT_NOSIGNAL, 1 );
-  if ( ret != 0 ) {
-    disconnectFrom();
-    ZYPP_THROW(MediaCurlSetOptException(_url, _curlError));
-  }
+  // create non persistant settings
+  // so that we don't add headers twice
+  TransferSettings vol_settings(_settings);
 
-  /**
-   * Transfer timeout
-   */
-  {
-    _xfer_timeout = TRANSFER_TIMEOUT;
+  // add custom headers
+  vol_settings.addHeader(anonymousIdHeader());
+  vol_settings.addHeader(distributionFlavorHeader());
+  vol_settings.addHeader("Pragma:");
 
-    std::string param(_url.getQueryParam("timeout"));
-    if( !param.empty())
-    {
-      long num = str::strtonum<long>( param);
-      if( num >= 0 && num <= TRANSFER_TIMEOUT_MAX)
-        _xfer_timeout = num;
-    }
-  }
+  _settings.setTimeout(TRANSFER_TIMEOUT);
+  _settings.setConnectTimeout(CONNECT_TIMEOUT);
 
-  /*
-  ** Connect timeout
-  */
-  ret = curl_easy_setopt( _curl, CURLOPT_CONNECTTIMEOUT, CONNECT_TIMEOUT);
-  if ( ret != 0 ) {
-    disconnectFrom();
-    ZYPP_THROW(MediaCurlSetOptException(_url, _curlError));
-  }
+  _settings.setUserAgentString(agentString());
 
-  if ( _url.getScheme() == "http" ) {
-    // follow any Location: header that the server sends as part of
-    // an HTTP header (#113275)
-    ret = curl_easy_setopt ( _curl, CURLOPT_FOLLOWLOCATION, true );
-    if ( ret != 0) {
-      disconnectFrom();
-      ZYPP_THROW(MediaCurlSetOptException(_url, _curlError));
-    }
-    ret = curl_easy_setopt ( _curl, CURLOPT_MAXREDIRS, 3L );
-    if ( ret != 0) {
-      disconnectFrom();
-      ZYPP_THROW(MediaCurlSetOptException(_url, _curlError));
-    }
-
-    ret = curl_easy_setopt ( _curl, CURLOPT_USERAGENT, agentString() );
-
-
-    if ( ret != 0) {
+  // fill some settings from url query parameters
+  try
+  {
+      fillSettingsFromUrl(_url, _settings);
+  }
+  catch ( const MediaException &e )
+  {
       disconnectFrom();
-      ZYPP_THROW(MediaCurlSetOptException(_url, _curlError));
-    }
+      ZYPP_RETHROW(e);
   }
 
-  if ( _url.getScheme() == "https" )
+  // if the proxy was not set by url, then look
+  if ( _settings.proxy().empty() )
   {
-    bool verify_peer = false;
-    bool verify_host = false;
+      // at the system proxy settings
+      fillSettingsSystemProxy(_url, _settings);
+  }
 
-    std::string verify( _url.getQueryParam("ssl_verify"));
-    if( verify.empty() ||
-        verify == "yes")
-    {
-      verify_peer = true;
-      verify_host = true;
-    }
-    else
-    if( verify == "no")
-    {
-      verify_peer = false;
-      verify_host = false;
-    }
-    else
-    {
-      std::vector<std::string>                 flags;
-      std::vector<std::string>::const_iterator flag;
-      str::split( verify, std::back_inserter(flags), ",");
-      for(flag = flags.begin(); flag != flags.end(); ++flag)
-      {
-        if( *flag == "host")
-        {
-          verify_host = true;
-        }
-        else
-        if( *flag == "peer")
-        {
-          verify_peer = true;
-        }
-        else
-        {
-                disconnectFrom();
-          ZYPP_THROW(MediaBadUrlException(_url, "Unknown ssl_verify flag"));
-        }
-      }
-    }
+  DBG << "Proxy: " << (_settings.proxy().empty() ? "-none-" : _settings.proxy()) << endl;
 
-    _ca_path = Pathname(_url.getQueryParam("ssl_capath")).asString();
-    if( _ca_path.empty())
-    {
-        _ca_path = "/etc/ssl/certs/";
-    }
-    else
-    if( !PathInfo(_ca_path).isDir() || !Pathname(_ca_path).absolute())
-    {
-        disconnectFrom();
-        ZYPP_THROW(MediaBadUrlException(_url, "Invalid ssl_capath path"));
-    }
+ /**
+  * Connect timeout
+  */
+  SET_OPTION(CURLOPT_CONNECTTIMEOUT, _settings.connectTimeout());
 
-    if( verify_peer || verify_host)
-    {
-      ret = curl_easy_setopt( _curl, CURLOPT_CAPATH, _ca_path.c_str());
-      if ( ret != 0 ) {
-        disconnectFrom();
-        ZYPP_THROW(MediaCurlSetOptException(_url, _curlError));
-      }
-    }
+  // 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);
 
-    ret = curl_easy_setopt( _curl, CURLOPT_SSL_VERIFYPEER, verify_peer ? 1L : 0L);
-    if ( ret != 0 ) {
-      disconnectFrom();
-      ZYPP_THROW(MediaCurlSetOptException(_url, _curlError));
-    }
-    ret = curl_easy_setopt( _curl, CURLOPT_SSL_VERIFYHOST, verify_host ? 2L : 0L);
-    if ( ret != 0 ) {
-      disconnectFrom();
-      ZYPP_THROW(MediaCurlSetOptException(_url, _curlError));
-    }
+  if ( _url.getScheme() == "https" )
+  {
+    // restrict following of redirections from https to https only
+    SET_OPTION( CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTPS );
 
-    ret = curl_easy_setopt ( _curl, CURLOPT_USERAGENT, agentString() );
-    if ( ret != 0) {
-      disconnectFrom();
-      ZYPP_THROW(MediaCurlSetOptException(_url, _curlError));
+    if( _settings.verifyPeerEnabled() ||
+        _settings.verifyHostEnabled() )
+    {
+      SET_OPTION(CURLOPT_CAPATH, _settings.certificateAuthoritiesPath().c_str());
     }
 
+    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() );
 
   /*---------------------------------------------------------------*
    CURLOPT_USERPWD: [user name]:[password]
@@ -502,235 +596,135 @@ void MediaCurl::attachTo (bool next)
    If not provided, anonymous FTP identification
    *---------------------------------------------------------------*/
 
-  if ( _url.getUsername().empty() ) {
-    if ( _url.getScheme() == "ftp" ) {
-      string id = "yast2@";
-      id += VERSION;
-      DBG << "Anonymous FTP identification: '" << id << "'" << endl;
-      _userpwd = "anonymous:" + id;
-    }
-  } else {
-    _userpwd = _url.getUsername();
-    if ( _url.getPassword().size() ) {
-      _userpwd += ":" + _url.getPassword();
-    }
-  }
-
-  if ( _userpwd.size() ) {
-    _userpwd = unEscape( _userpwd );
-    ret = curl_easy_setopt( _curl, CURLOPT_USERPWD, _userpwd.c_str() );
-    if ( ret != 0 ) {
-      disconnectFrom();
-      ZYPP_THROW(MediaCurlSetOptException(_url, _curlError));
-    }
-
-    // HTTP authentication type
-    if(_url.getScheme() == "http" || _url.getScheme() == "https")
+  if ( _settings.userPassword().size() )
+  {
+    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;
-
-          ret = curl_easy_setopt( _curl, CURLOPT_HTTPAUTH, auth);
-          if ( ret != 0 ) {
-            disconnectFrom();
-            ZYPP_THROW(MediaCurlSetOptException(_url, _curlError));
-          }
-        }
-      }
-      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);
     }
   }
 
-  /*---------------------------------------------------------------*
-   CURLOPT_PROXY: host[:port]
-
-   Url::option(proxy and proxyport) -> CURLOPT_PROXY
-   If not provided, /etc/sysconfig/proxy is evaluated
-   *---------------------------------------------------------------*/
-
-  _proxy = _url.getQueryParam( "proxy" );
+  if ( _settings.proxyEnabled() )
+  {
+    if ( ! _settings.proxy().empty() )
+    {
+      SET_OPTION(CURLOPT_PROXY, _settings.proxy().c_str());
+      /*---------------------------------------------------------------*
+        CURLOPT_PROXYUSERPWD: [user name]:[password]
 
-  if ( ! _proxy.empty() ) {
-    string proxyport( _url.getQueryParam( "proxyport" ) );
-    if ( ! proxyport.empty() ) {
-      _proxy += ":" + proxyport;
-    }
-  } else {
+        Url::option(proxyuser and proxypassword) -> CURLOPT_PROXYUSERPWD
+        If not provided, $HOME/.curlrc is evaluated
+        *---------------------------------------------------------------*/
 
-    ProxyInfo proxy_info (ProxyInfo::ImplPtr(new ProxyInfoSysconfig("proxy")));
+      string proxyuserpwd = _settings.proxyUserPassword();
 
-    if ( proxy_info.enabled())
-    {
-      bool useproxy = true;
-
-      std::list<std::string> nope = proxy_info.noProxy();
-      for (ProxyInfo::NoProxyIterator it = proxy_info.noProxyBegin();
-           it != proxy_info.noProxyEnd();
-           it++)
+      if ( proxyuserpwd.empty() )
       {
-        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;
-            useproxy = false;
-            break;
-          }
-        }
+        CurlConfig curlconf;
+        CurlConfig::parseConfig(curlconf); // parse ~/.curlrc
+        if (curlconf.proxyuserpwd.empty())
+          DBG << "~/.curlrc does not contain the proxy-user option" << endl;
         else
-        // no proxy if we have an exact match
-        if( host == temp)
         {
-          DBG << "NO_PROXY: '" << *it  << "' matches host '"
-                               << host << "'" << endl;
-          useproxy = false;
-          break;
+          proxyuserpwd = curlconf.proxyuserpwd;
+          DBG << "using proxy-user from ~/.curlrc" << endl;
         }
       }
 
-      if ( useproxy ) {
-        _proxy = proxy_info.proxy(_url.getScheme());
-      }
+      proxyuserpwd = unEscape( proxyuserpwd );
+      if ( ! proxyuserpwd.empty() )
+        SET_OPTION(CURLOPT_PROXYUSERPWD, proxyuserpwd.c_str());
     }
   }
+  else
+  {
+      SET_OPTION(CURLOPT_NOPROXY, "*");
+  }
 
-
-  DBG << "Proxy: " << (_proxy.empty() ? "-none-" : _proxy) << endl;
-
-  if ( ! _proxy.empty() ) {
-
-    ret = curl_easy_setopt( _curl, CURLOPT_PROXY, _proxy.c_str() );
-    if ( ret != 0 ) {
-      disconnectFrom();
-      ZYPP_THROW(MediaCurlSetOptException(_url, _curlError));
-    }
-
-    /*---------------------------------------------------------------*
-     CURLOPT_PROXYUSERPWD: [user name]:[password]
-
-     Url::option(proxyuser and proxypassword) -> CURLOPT_PROXYUSERPWD
-     If not provided, $HOME/.curlrc is evaluated
-     *---------------------------------------------------------------*/
-
-    _proxyuserpwd = _url.getQueryParam( "proxyuser" );
-
-    if ( ! _proxyuserpwd.empty() ) {
-      string proxypassword( _url.getQueryParam( "proxypassword" ) );
-      if ( ! proxypassword.empty() ) {
-        _proxyuserpwd += ":" + proxypassword;
-      }
-    } 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 = unEscape( _proxyuserpwd );
-    if ( ! _proxyuserpwd.empty() ) {
-        ret = curl_easy_setopt( _curl, CURLOPT_PROXYUSERPWD, _proxyuserpwd.c_str() );
-        if ( ret != 0 ) {
-            disconnectFrom();
-            ZYPP_THROW(MediaCurlSetOptException(_url, _curlError));
-        }
-    }
+  /** 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, 10L);
   }
 
+  if ( _settings.maxDownloadSpeed() != 0 )
+      SET_OPTION_OFFT(CURLOPT_MAX_RECV_SPEED_LARGE, _settings.maxDownloadSpeed());
+
   /*---------------------------------------------------------------*
    *---------------------------------------------------------------*/
 
   _currentCookieFile = _cookieFile.asString();
+  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, 0L);
 
-  ret = curl_easy_setopt( _curl, CURLOPT_COOKIEFILE,
-                          _currentCookieFile.c_str() );
-  if ( ret != 0 ) {
-    disconnectFrom();
-    ZYPP_THROW(MediaCurlSetOptException(_url, _curlError));
-  }
+  // bnc #306272
+  SET_OPTION(CURLOPT_PROXY_TRANSFER_MODE, 1L );
 
-  ret = curl_easy_setopt( _curl, CURLOPT_COOKIEJAR,
-                          _currentCookieFile.c_str() );
-  if ( ret != 0 ) {
-    disconnectFrom();
-    ZYPP_THROW(MediaCurlSetOptException(_url, _curlError));
-  }
+  // append settings custom headers to curl
+  for ( TransferSettings::Headers::const_iterator it = vol_settings.headersBegin();
+        it != vol_settings.headersEnd();
+        ++it )
+  {
+      MIL << "HEADER " << *it << std::endl;
 
-  ret = curl_easy_setopt( _curl, CURLOPT_PROGRESSFUNCTION,
-                          &progressCallback );
-  if ( ret != 0 ) {
-    disconnectFrom();
-    ZYPP_THROW(MediaCurlSetOptException(_url, _curlError));
+      _customHeaders = curl_slist_append(_customHeaders, it->c_str());
+      if ( !_customHeaders )
+          ZYPP_THROW(MediaCurlInitException(_url));
   }
 
-  ret = curl_easy_setopt( _curl, CURLOPT_NOPROGRESS, false );
-  if ( ret != 0 ) {
-    disconnectFrom();
-    ZYPP_THROW(MediaCurlSetOptException(_url, _curlError));
-  }
+  SET_OPTION(CURLOPT_HTTPHEADER, _customHeaders);
+}
 
-  // bnc #306272
-  ret = curl_easy_setopt( _curl, CURLOPT_PROXY_TRANSFER_MODE, 1 );
-  if ( ret != 0 ) {
-    disconnectFrom();
-    ZYPP_THROW(MediaCurlSetOptException(_url, _curlError));
-  }
+///////////////////////////////////////////////////////////////////
 
-  _customHeaders = curl_slist_append(_customHeaders, "Pragma:");
 
-  if ( !_customHeaders ) {
-      ZYPP_THROW(MediaCurlInitException(_url));
-  }
+void MediaCurl::attachTo (bool next)
+{
+  if ( next )
+    ZYPP_THROW(MediaNotSupportedException(_url));
 
-  // now add the anonymous id header
-  _customHeaders = curl_slist_append(_customHeaders, anonymousIdHeader());
+  if ( !_url.isValid() )
+    ZYPP_THROW(MediaBadUrlException(_url));
 
-  if ( !_customHeaders ) {
-      ZYPP_THROW(MediaCurlInitException(_url));
-  }
+  checkProtocol(_url);
+  if( !isUseableAttachPoint(attachPoint()))
+  {
+    std::string mountpoint = createAttachPoint().asString();
 
-  // now add the product flavor header
-  _customHeaders = curl_slist_append(_customHeaders, distributionFlavorHeader());
+    if( mountpoint.empty())
+      ZYPP_THROW( MediaBadAttachPointException(url()));
 
-  if ( !_customHeaders ) {
-      ZYPP_THROW(MediaCurlInitException(_url));
+    setAttachPoint( mountpoint, true);
   }
 
-  ret = curl_easy_setopt ( _curl, CURLOPT_HTTPHEADER, _customHeaders );
-
-  if ( ret != 0) {
-    disconnectFrom();
-    ZYPP_THROW(MediaCurlSetOptException(_url, _curlError));
+  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()));
@@ -744,11 +738,7 @@ MediaCurl::checkAttachPoint(const Pathname &apoint) const
 }
 
 ///////////////////////////////////////////////////////////////////
-//
-//
-//        METHOD NAME : MediaCurl::disconnectFrom
-//        METHOD TYPE : PMError
-//
+
 void MediaCurl::disconnectFrom()
 {
   if ( _customHeaders )
@@ -764,24 +754,17 @@ void MediaCurl::disconnectFrom()
   }
 }
 
-
 ///////////////////////////////////////////////////////////////////
-//
-//
-//        METHOD NAME : MediaCurl::releaseFrom
-//        METHOD TYPE : void
-//
-//        DESCRIPTION : Asserted that media is attached.
-//
+
 void MediaCurl::releaseFrom( const std::string & ejectDev )
 {
   disconnect();
 }
 
-static Url getFileUrl(const Url & url, const Pathname & filename)
+Url MediaCurl::getFileUrl(const Pathname & filename) const
 {
-  Url newurl(url);
-  string path = url.getPathName();
+  Url newurl(_url);
+  string path = _url.getPathName();
   if ( !path.empty() && path != "/" && *path.rbegin() == '/' &&
        filename.absolute() )
   {
@@ -806,12 +789,8 @@ static Url getFileUrl(const Url & url, const Pathname & filename)
   return newurl;
 }
 
-
 ///////////////////////////////////////////////////////////////////
-//
-//        METHOD NAME : MediaCurl::getFile
-//        METHOD TYPE : void
-//
+
 void MediaCurl::getFile( const Pathname & filename ) const
 {
     // Use absolute file name to prevent access of files outside of the
@@ -820,15 +799,12 @@ void MediaCurl::getFile( const Pathname & filename ) const
 }
 
 ///////////////////////////////////////////////////////////////////
-//
-//        METHOD NAME : MediaCurl::getFileCopy
-//        METHOD TYPE : void
-//
+
 void MediaCurl::getFileCopy( const Pathname & filename , const Pathname & target) const
 {
   callback::SendReport<DownloadProgressReport> report;
 
-  Url fileurl(getFileUrl(_url, filename));
+  Url fileurl(getFileUrl(filename));
 
   bool retry = false;
 
@@ -863,6 +839,7 @@ void MediaCurl::getFileCopy( const Pathname & filename , const Pathname & target
   report->finish(fileurl, zypp::media::DownloadProgressReport::NO_ERROR, "");
 }
 
+///////////////////////////////////////////////////////////////////
 
 bool MediaCurl::getDoesFileExist( const Pathname & filename ) const
 {
@@ -893,6 +870,134 @@ bool MediaCurl::getDoesFileExist( const Pathname & filename ) const
   return false;
 }
 
+///////////////////////////////////////////////////////////////////
+
+void MediaCurl::evaluateCurlCode( const Pathname &filename,
+                                  CURLcode code,
+                                  bool timeout_reached ) const
+{
+  if ( code != 0 )
+  {
+    Url url;
+    if (filename.empty())
+      url = _url;
+    else
+      url = getFileUrl(filename);
+    std::string err;
+    try
+    {
+      switch ( code )
+      {
+      case CURLE_UNSUPPORTED_PROTOCOL:
+      case CURLE_URL_MALFORMAT:
+      case CURLE_URL_MALFORMAT_USER:
+          err = " Bad URL";
+      case CURLE_LOGIN_DENIED:
+          ZYPP_THROW(
+              MediaUnauthorizedException(url, "Login failed.", _curlError, ""));
+          break;
+      case CURLE_HTTP_RETURNED_ERROR:
+      {
+        long httpReturnCode = 0;
+        CURLcode infoRet = curl_easy_getinfo( _curl,
+                                              CURLINFO_RESPONSE_CODE,
+                                              &httpReturnCode );
+        if ( infoRet == CURLE_OK )
+        {
+          string msg = "HTTP response: " + str::numstring( httpReturnCode );
+          switch ( httpReturnCode )
+          {
+          case 401:
+          {
+            string auth_hint = getAuthHint();
+
+            DBG << msg << " Login failed (URL: " << url.asString() << ")" << std::endl;
+            DBG << "MediaUnauthorizedException auth hint: '" << auth_hint << "'" << std::endl;
+
+            ZYPP_THROW(MediaUnauthorizedException(
+                           url, "Login failed.", _curlError, auth_hint
+                           ));
+          }
+
+          case 503: // service temporarily unavailable (bnc #462545)
+            ZYPP_THROW(MediaTemporaryProblemException(url));
+          case 504: // gateway timeout
+            ZYPP_THROW(MediaTimeoutException(url));
+          case 403:
+          {
+            string msg403;
+            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:
+              ZYPP_THROW(MediaFileNotFoundException(_url, filename));
+          }
+
+          DBG << msg << " (URL: " << url.asString() << ")" << std::endl;
+          ZYPP_THROW(MediaCurlException(url, msg, _curlError));
+        }
+        else
+        {
+          string msg = "Unable to retrieve HTTP response:";
+          DBG << msg << " (URL: " << url.asString() << ")" << std::endl;
+          ZYPP_THROW(MediaCurlException(url, msg, _curlError));
+        }
+      }
+      break;
+      case CURLE_FTP_COULDNT_RETR_FILE:
+      case CURLE_FTP_ACCESS_DENIED:
+        err = "File not found";
+        ZYPP_THROW(MediaFileNotFoundException(_url, filename));
+        break;
+      case CURLE_BAD_PASSWORD_ENTERED:
+      case CURLE_FTP_USER_PASSWORD_INCORRECT:
+          err = "Login failed";
+          break;
+      case CURLE_COULDNT_RESOLVE_PROXY:
+      case CURLE_COULDNT_RESOLVE_HOST:
+      case CURLE_COULDNT_CONNECT:
+      case CURLE_FTP_CANT_GET_HOST:
+        err = "Connection failed";
+        break;
+      case CURLE_WRITE_ERROR:
+        err = "Write error";
+        break;
+      case CURLE_PARTIAL_FILE:
+      case CURLE_ABORTED_BY_CALLBACK:
+      case CURLE_OPERATION_TIMEDOUT:
+        if( timeout_reached)
+        {
+          err  = "Timeout reached";
+          ZYPP_THROW(MediaTimeoutException(url));
+        }
+        else
+        {
+          err = "User abort";
+        }
+        break;
+      case CURLE_SSL_PEER_CERTIFICATE:
+      default:
+        err = "Unrecognized error";
+        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
+  {
+    // actually the code is 0, nothing happened
+  }
+}
+
+///////////////////////////////////////////////////////////////////
+
 bool MediaCurl::doGetDoesFileExist( const Pathname & filename ) const
 {
   DBG << filename.asString() << endl;
@@ -903,37 +1008,14 @@ bool MediaCurl::doGetDoesFileExist( const Pathname & filename ) const
   if(_url.getHost().empty())
     ZYPP_THROW(MediaBadUrlEmptyHostException(_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.rbegin() != '/' ) path += "/";
-    // Remove "./" from begin of relative file name
-    path += filename.asString().substr( 2, filename.asString().size() - 2 );
-  } else {
-    path += filename.asString();
-  }
-
-  Url url( _url );
-  url.setPathName( path );
+  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:
@@ -954,36 +1036,37 @@ bool MediaCurl::doGetDoesFileExist( const Pathname & filename ) const
   // little data, that works with broken servers, and
   // works for ftp as well, because retrieving only headers
   // ftp will return always OK code ?
-  if (  _url.getScheme() == "http" ||  _url.getScheme() == "https" )
-    ret = curl_easy_setopt( _curl, CURLOPT_NOBODY, 1 );
+  // See http://curl.haxx.se/docs/knownbugs.html #58
+  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));
       }
@@ -995,242 +1078,133 @@ 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));
       }
       ZYPP_THROW(MediaCurlSetOptException(url, err));
   }
-    // Set callback and perform.
-  //ProgressData progressData(_xfer_timeout, url, &report);
-  //report->start(url, dest);
-  //if ( curl_easy_setopt( _curl, CURLOPT_PROGRESSDATA, &progressData ) != 0 ) {
-  //  WAR << "Can't set CURLOPT_PROGRESSDATA: " << _curlError << endl;;
-  //}
 
   CURLcode ok = curl_easy_perform( _curl );
   MIL << "perform code: " << ok << " [ " << curl_easy_strerror(ok) << " ]" << endl;
 
-  // reset curl settings
-  if (  _url.getScheme() == "http" ||  _url.getScheme() == "https" )
-  {
-    ret = curl_easy_setopt( _curl, CURLOPT_NOBODY, 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
-    */
-    ret = curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1 );
-  }
-  else
-    ret = curl_easy_setopt( _curl, CURLOPT_RANGE, NULL );
-
-  if ( ret != 0 )
-  {
-    ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
-  }
-
-  if ( ok != 0 )
-  {
-    ::fclose( file );
-
-    std::string err;
-    try
-    {
-      bool err_file_not_found = false;
-      switch ( ok )
-      {
-      case CURLE_FTP_COULDNT_RETR_FILE:
-      case CURLE_FTP_ACCESS_DENIED:
-        err_file_not_found = true;
-        break;
-      case CURLE_LOGIN_DENIED:
-        ZYPP_THROW(
-            MediaUnauthorizedException(url, "Login failed.", _curlError, ""));
-        break;
-      case CURLE_HTTP_RETURNED_ERROR:
-        {
-          long httpReturnCode = 0;
-          CURLcode infoRet = curl_easy_getinfo( _curl,
-                                                CURLINFO_RESPONSE_CODE,
-                                                &httpReturnCode );
-          if ( infoRet == CURLE_OK )
-          {
-            string msg = "HTTP response: " + str::numstring( httpReturnCode );
-            bool brk = false; // break also from the parent switch
-            switch ( httpReturnCode )
-            {
-            case 401: // authorization required
-            {
-              std::string auth_hint = getAuthHint();
-
-              DBG << msg << " Login failed (URL: " << url.asString() << ")" << std::endl;
-              DBG << "MediaUnauthorizedException auth hint: '" << auth_hint << "'" << std::endl;
-
-              ZYPP_THROW(MediaUnauthorizedException(
-                url, "Login failed.", _curlError, auth_hint
-              ));
-            }
-
-            case 503: // service temporarily unavailable (bnc #462545)
-              ZYPP_THROW(MediaTemporaryProblemException(url));
-
-            case 504: // gateway timeout
-              ZYPP_THROW(MediaTimeoutException(url));
-
-            case 403: // access denied
-               ZYPP_THROW(MediaForbiddenException(url));
-
-            case 404: // not found
-               err_file_not_found = true;
-               brk = true;
-               break;
-            }
-
-            if (brk)
-              break;
-
-            DBG << msg << " (URL: " << url.asString() << ")" << std::endl;
-            ZYPP_THROW(MediaCurlException(url, msg, _curlError));
-          }
-          else
-          {
-            string msg = "Unable to retrieve HTTP response:";
-            DBG << msg << " (URL: " << url.asString() << ")" << std::endl;
-            ZYPP_THROW(MediaCurlException(url, msg, _curlError));
-          }
-        }
-        break;
-      case CURLE_UNSUPPORTED_PROTOCOL:
-      case CURLE_URL_MALFORMAT:
-      case CURLE_URL_MALFORMAT_USER:
-      case CURLE_BAD_PASSWORD_ENTERED:
-      case CURLE_FTP_USER_PASSWORD_INCORRECT:
-        err = "Login failed";
-        break;
-      case CURLE_COULDNT_RESOLVE_PROXY:
-      case CURLE_COULDNT_RESOLVE_HOST:
-      case CURLE_COULDNT_CONNECT:
-      case CURLE_FTP_CANT_GET_HOST:
-        err = "Connection failed";
-        break;
-      case CURLE_WRITE_ERROR:
-        err = "Write error";
-        break;
-      case CURLE_ABORTED_BY_CALLBACK:
-      case CURLE_OPERATION_TIMEOUTED:
-        err  = "Timeout reached";
-        ZYPP_THROW(MediaTimeoutException(url));
-        break;
-      case CURLE_SSL_CACERT:
-        ZYPP_THROW(MediaBadCAException(url,_curlError));
-      case CURLE_SSL_PEER_CERTIFICATE:
-      default:
-        err = curl_easy_strerror(ok);
-        if (err.empty())
-          err = "Unrecognized error";
-        break;
-      }
-
-      if( err_file_not_found)
-      {
-        // file does not exists
-        return false;
-      }
-      else
-      {
-        // there was an error
-        ZYPP_THROW(MediaCurlException(url, string(), _curlError));
-      }
+  // reset curl settings
+  if (  _url.getScheme() == "http" ||  _url.getScheme() == "https" )
+  {
+    curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
+    if ( ret != 0 ) {
+      ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
     }
-    catch (const MediaException & excpt_r)
-    {
-      ZYPP_RETHROW(excpt_r);
+
+    /* 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, 1L);
+    if ( ret != 0 ) {
+      ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
+    }
+
+  }
+  else
+  {
+    // for FTP we set different options
+    curl_easy_setopt( _curl, CURLOPT_RANGE, NULL);
+    if ( ret != 0 ) {
+      ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
     }
   }
 
+  // if the code is not zero, close the file
+  if ( ok != 0 )
+      ::fclose(file);
+
+  // as we are not having user interaction, the user can't cancel
+  // the file existence checking, a callback or timeout return code
+  // will be always a timeout.
+  try {
+      evaluateCurlCode( filename, ok, true /* timeout */);
+  }
+  catch ( const MediaFileNotFoundException &e ) {
+      // if the file did not exist then we can return false
+      return false;
+  }
+  catch ( const MediaException &e ) {
+      // some error, we are not sure about file existence, rethrw
+      ZYPP_RETHROW(e);
+  }
   // exists
   return ( ok == CURLE_OK );
-  //if ( curl_easy_setopt( _curl, CURLOPT_PROGRESSDATA, NULL ) != 0 ) {
-  //  WAR << "Can't unset CURLOPT_PROGRESSDATA: " << _curlError << endl;;
-  //}
 }
 
+///////////////////////////////////////////////////////////////////
 
-void MediaCurl::doGetFileCopy( const Pathname & filename , const Pathname & target, callback::SendReport<DownloadProgressReport> & report) 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, 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 );
@@ -1254,187 +1228,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(_xfer_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, options);
     }
-
-    if ( ret != 0 ) {
-      ERR << "curl error: " << ret << ": " << _curlError
-          << ", temp file size " << PathInfo(destNew).size()
-          << " byte." << endl;
-
+    catch (Exception &e)
+    {
       ::fclose( file );
       filesystem::unlink( destNew );
-
-      std::string err;
-      try {
-       bool err_file_not_found = false;
-       switch ( ret ) {
-        case CURLE_UNSUPPORTED_PROTOCOL:
-        case CURLE_URL_MALFORMAT:
-        case CURLE_URL_MALFORMAT_USER:
-          err = " Bad URL";
-        case CURLE_LOGIN_DENIED:
-          ZYPP_THROW(
-              MediaUnauthorizedException(url, "Login failed.", _curlError, ""));
-          break;
-        case CURLE_HTTP_RETURNED_ERROR:
-          {
-            long httpReturnCode = 0;
-            CURLcode infoRet = curl_easy_getinfo( _curl,
-                                                  CURLINFO_RESPONSE_CODE,
-                                                  &httpReturnCode );
-            if ( infoRet == CURLE_OK )
-            {
-              string msg = "HTTP response: " + str::numstring( httpReturnCode );
-              switch ( httpReturnCode )
-              {
-              case 401:
-              {
-                string auth_hint = getAuthHint();
-
-                DBG << msg << " Login failed (URL: " << url.asString() << ")" << std::endl;
-                DBG << "MediaUnauthorizedException auth hint: '" << auth_hint << "'" << std::endl;
-
-                ZYPP_THROW(MediaUnauthorizedException(
-                  url, "Login failed.", _curlError, auth_hint
-                ));
-              }
-
-              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));
-
-              case 404:
-                 ZYPP_THROW(MediaFileNotFoundException(_url, filename));
-              }
-
-              DBG << msg << " (URL: " << url.asString() << ")" << std::endl;
-              ZYPP_THROW(MediaCurlException(url, msg, _curlError));
-            }
-            else
-            {
-              string msg = "Unable to retrieve HTTP response:";
-              DBG << msg << " (URL: " << url.asString() << ")" << std::endl;
-              ZYPP_THROW(MediaCurlException(url, msg, _curlError));
-            }
-          }
-          break;
-        case CURLE_FTP_COULDNT_RETR_FILE:
-        case CURLE_FTP_ACCESS_DENIED:
-          err = "File not found";
-          err_file_not_found = true;
-          break;
-        case CURLE_BAD_PASSWORD_ENTERED:
-        case CURLE_FTP_USER_PASSWORD_INCORRECT:
-          err = "Login failed";
-          break;
-        case CURLE_COULDNT_RESOLVE_PROXY:
-        case CURLE_COULDNT_RESOLVE_HOST:
-        case CURLE_COULDNT_CONNECT:
-        case CURLE_FTP_CANT_GET_HOST:
-          err = "Connection failed";
-          break;
-        case CURLE_WRITE_ERROR:
-          err = "Write error";
-          break;
-        case CURLE_ABORTED_BY_CALLBACK:
-        case CURLE_OPERATION_TIMEDOUT:
-          if( progressData.reached)
-          {
-            err  = "Timeout reached";
-            ZYPP_THROW(MediaTimeoutException(url));
-          }
-          else
-          {
-            err = "User abort";
-          }
-          break;
-        case CURLE_SSL_PEER_CERTIFICATE:
-        default:
-          err = "Unrecognized error";
-          break;
-       }
-       if( err_file_not_found)
-       {
-         ZYPP_THROW(MediaFileNotFoundException(_url, filename));
-       }
-       else
-       {
-         ZYPP_THROW(MediaCurlException(url, err, _curlError));
-       }
-      }
-      catch (const MediaException & excpt_r)
-      {
-        ZYPP_RETHROW(excpt_r);
-      }
-    }
-#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,
@@ -1464,8 +1280,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;
@@ -1482,15 +1301,89 @@ void MediaCurl::doGetFileCopy( const Pathname & filename , const Pathname & targ
     DBG << "done: " << PathInfo(dest) << endl;
 }
 
+///////////////////////////////////////////////////////////////////
+
+void MediaCurl::doGetFileCopyFile( const Pathname & filename , const Pathname & dest, FILE *file, 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));
+
+    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.
+    //
+    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(_settings.timeout(), url, &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 ( 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 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
+    if (!ret && detectDirIndex())
+      {
+       ZYPP_THROW(MediaNotAFileException(_url, filename));
+      }
+#endif // DETECT_DIR_INDEX
+}
 
 ///////////////////////////////////////////////////////////////////
-//
-//
-//        METHOD NAME : MediaCurl::getDir
-//        METHOD TYPE : PMError
-//
-//        DESCRIPTION : Asserted that media is attached
-//
+
 void MediaCurl::getDir( const Pathname & dirname, bool recurse_r ) const
 {
   filesystem::DirContent content;
@@ -1523,13 +1416,7 @@ void MediaCurl::getDir( const Pathname & dirname, bool recurse_r ) const
 }
 
 ///////////////////////////////////////////////////////////////////
-//
-//
-//        METHOD NAME : MediaCurl::getDirInfo
-//        METHOD TYPE : PMError
-//
-//        DESCRIPTION : Asserted that media is attached and retlist is empty.
-//
+
 void MediaCurl::getDirInfo( std::list<std::string> & retlist,
                                const Pathname & dirname, bool dots ) const
 {
@@ -1537,13 +1424,7 @@ void MediaCurl::getDirInfo( std::list<std::string> & retlist,
 }
 
 ///////////////////////////////////////////////////////////////////
-//
-//
-//        METHOD NAME : MediaCurl::getDirInfo
-//        METHOD TYPE : PMError
-//
-//        DESCRIPTION : Asserted that media is attached and retlist is empty.
-//
+
 void MediaCurl::getDirInfo( filesystem::DirContent & retlist,
                             const Pathname & dirname, bool dots ) const
 {
@@ -1551,13 +1432,7 @@ void MediaCurl::getDirInfo( filesystem::DirContent & retlist,
 }
 
 ///////////////////////////////////////////////////////////////////
-//
-//
-//        METHOD NAME : MediaCurl::progressCallback
-//        METHOD TYPE : int
-//
-//        DESCRIPTION : Progress callback triggered from MediaCurl::getFile
-//
+
 int MediaCurl::progressCallback( void *clientp,
                                  double dltotal, double dlnow,
                                  double ultotal, double ulnow)
@@ -1605,7 +1480,7 @@ int MediaCurl::progressCallback( void *clientp,
     // send progress report first, abort transfer if requested
     if( pdata->report)
     {
-      if (!(*(pdata->report))->progress(int( dlnow * 100 / dltotal ),
+      if (!(*(pdata->report))->progress(int( dltotal ? dlnow * 100 / dltotal : 0 ),
                                        pdata->url,
                                        pdata->drate_avg,
                                        pdata->drate_period))
@@ -1647,6 +1522,7 @@ int MediaCurl::progressCallback( void *clientp,
   return 0;
 }
 
+///////////////////////////////////////////////////////////////////
 
 string MediaCurl::getAuthHint() const
 {
@@ -1663,6 +1539,7 @@ string MediaCurl::getAuthHint() const
   return "";
 }
 
+///////////////////////////////////////////////////////////////////
 
 bool MediaCurl::authenticate(const string & availAuthTypes, bool firstTry) const
 {
@@ -1734,19 +1611,23 @@ bool MediaCurl::authenticate(const string & availAuthTypes, bool firstTry) const
   // set username and password
   if (credentials)
   {
-    _userpwd = credentials->getUserPwd();
+    // HACK, why is this const?
+    const_cast<MediaCurl*>(this)->_settings.setUsername(credentials->username());
+    const_cast<MediaCurl*>(this)->_settings.setPassword(credentials->password());
 
     // set username and password
-    CURLcode ret = curl_easy_setopt(_curl, CURLOPT_USERPWD, _userpwd.c_str());
+    CURLcode ret = curl_easy_setopt(_curl, CURLOPT_USERPWD, _settings.userPassword().c_str());
     if ( ret != 0 ) ZYPP_THROW(MediaCurlSetOptException(_url, _curlError));
 
     // set available authentication types from the exception
     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));
     }